Skip to content

Align MCP tool descriptions with local agent guidance - #1079

Merged
malibio merged 2 commits into
mainfrom
feature/mcp-tool-description-alignment
Apr 8, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/mcp-tool-description-alignment

Conversation

@malibio

@malibio malibio commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator

Summary

Closes the gap between what external LLMs (via MCP) and the local agent are told about how to use NodeSpace tools. The local agent gets 25+ rules via seed prompt nodes; MCP clients previously got a single unstructured instructions block with basic context.

Not trying to match the local agent verbatim — MCP clients are typically smarter models. The goal is same mechanisms and same key rules, not hand-holding.

Changes

initialize.rs — two new instruction sections:

  • SCHEMA CREATION RULES: no name/title fields (with title_template exception), enum coreValues format, targetType must be an existing type ID, prefer relationships over array fields
  • SEARCH FIRST: always search before fetching/updating a node by ID; never use placeholder or guessed IDs

tools.rs — create_schema tool:

  • Description is now dynamic: includes the current node_type_enum list so external LLMs see the same available types that create_node already exposes — no need to call get_all_schemas just to know what types exist
  • fields description: explicit "no name/title" rule with title_template exception
  • coreValues field added to enum field items (matches local agent tools.rs)
  • relationships.targetType: "MUST be an existing type — do NOT invent types that don't exist yet"
  • title_template: clarified that {name} token requires a name field to be defined

Test plan

  • cargo test -p nodespace-core passes
  • initialize handler returns updated instructions with SCHEMA CREATION RULES and SEARCH FIRST sections
  • tools/list response for create_schema includes current type IDs in description
  • create_schema called with invented targetType still fails at handler level (validation unchanged)

🤖 Generated with Claude Code

Key gaps closed between what external LLMs (via MCP) and the local agent
are told about how to use NodeSpace tools correctly.

initialize.rs — two new instruction sections:
- SCHEMA CREATION RULES: no name/title fields, enum coreValues format,
  targetType must be an existing type, prefer relationships over arrays
- SEARCH FIRST: always search before fetching/updating by ID; never use
  guessed IDs

tools.rs (create_schema):
- Tool description now dynamic: includes current node_type_enum so
  external LLMs see the same available types list as create_node already
  does
- FIELDS section: explicit "no name/title" rule + title_template exception
- coreValues field added to enum fields (same as local agent tools.rs)
- RELATIONSHIPS: targetType description now says "MUST be an existing type
  — do NOT invent types that don't exist yet"
- title_template description: clarified that {name} token requires a 'name'
  field to be defined

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@malibio

malibio commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a focused, high-signal change. It closes the information-asymmetry gap between local-agent and MCP-client tooling by (a) injecting two new instruction sections into the initialize handshake and (b) making the create_schema tool description dynamic so external LLMs see the currently-available type IDs without needing a round-trip through get_all_schemas. The change is a net improvement and the approach is sound. A few issues are worth addressing before merge.


Findings

[Improvement] Instruction sections are invisible to tests — PR test plan items 2 and 3 are unverified

initialize_test.rs has no assertion that checks result["instructions"] for the presence of SCHEMA CREATION RULES or SEARCH FIRST. The two new sections are long strings embedded inside an already-large format! call; a typo, an accidental escape sequence, or a future refactor could silently delete them and no test would catch it.

Minimal fix — add to test_initialize_success:

let instructions = result["instructions"].as_str().unwrap();
assert!(instructions.contains("SCHEMA CREATION RULES"), "instructions must include schema creation rules");
assert!(instructions.contains("SEARCH FIRST"), "instructions must include search-first directive");

Similarly, tools_test.rs has no test that verifies create_schema's description contains the dynamic type list (PR test plan item 3). The existing test_tool_schemas_include_custom_schema_ids test verifies create_node's enum but does not touch create_schema. A one-liner like:

let create_schema = tools.iter().find(|t| t["name"] == "create_schema").unwrap();
assert!(create_schema["description"].as_str().unwrap().contains("text"), "create_schema description must list available types");

would catch the unwrap_or_default() silent-empty-string case.

[Improvement] unwrap_or_default() on the type list silently produces an empty string

In tools.rs, the dynamic description falls back to an empty string when node_type_enum is not a JSON array:

.unwrap_or_default()   // produces "" when node_type_enum is not an array

node_type_enum is always constructed as json!(node_types) where node_types is a Vec<String>, so this path should never be hit. However, the silent fallback means the tool description would read "Currently available types: ." with no list and no diagnostic signal. A tracing::warn! or a fallback string like "(none)" would make the failure visible in logs without changing the happy path.

[Improvement] Double-encoding risk: {{name}} in format strings vs. literal {name} in instructions

The initialize.rs instruction uses {{name}} (Rust escaped) to produce the literal {name} in the output string — correct for the format! macro. The tools.rs description string uses the same {{name}} pattern. Both are correct as written, but the long format strings are fragile: any future editor who adds a token without understanding Rust's format string escaping will accidentally break the output. A comment on the format! call or a dedicated constant would reduce that risk.

Nit: Instruction section placement breaks the narrative flow

The two new sections are inserted between CUSTOM RELATIONSHIPS and DISPLAY FORMATTING. The natural reading order would be: node basics → hierarchy → linking → search → schema creation → display. SEARCH FIRST (a general query-hygiene rule) currently sits after SCHEMA CREATION RULES but logically applies to every tool. Consider ordering: SEARCH FIRST immediately after SEMANTIC SEARCH, then SCHEMA CREATION RULES near the bottom before DISPLAY FORMATTING. Not a blocker — instruction ordering is subjective and models read the full context anyway.

Nit: fields description still exposes array and object in the type enum

The updated fields description says "Use for scalar properties only (text, number, date, enum, boolean)" but the type enum still includes "array" and "object". The description and the schema are now slightly contradictory. Either remove array/object from the enum (if they are truly unsupported as scalar fields) or revise the description to acknowledge them. Either option is fine; the current state is misleading.


What is Working Well

  • The decision to make create_schema's description dynamic (matching the pattern already in use for create_node) is the right call. It eliminates an entire category of LLM hallucination (inventing type IDs) without requiring a new tool call.
  • The title_template description simplification is strictly better — the old version was overly verbose and the key constraint ({name} requires a name field) is now the final, memorable sentence.
  • coreValues being added to the JSON Schema for enum field items is correct and was a real gap: without it, LLMs had no schema-level guidance on how to format enum values.
  • The SEARCH FIRST directive is pragmatic and addresses a real failure mode (placeholder IDs) without requiring any handler-level changes.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review verdict: improvements needed before merge.

Two items should be addressed:

  1. Tests do not verify the new instruction content. PR test plan items 2 and 3 are unverified — initialize_test.rs never asserts on result["instructions"], and tools_test.rs never checks create_schema's description for the dynamic type list. A silent regression (typo, accidental removal) would pass CI undetected.

  2. unwrap_or_default() produces a silent empty string. If node_type_enum is somehow not an array, the create_schema description ends with "Currently available types: ." with no diagnostic. Swap for a fallback string (e.g., "(none)") or a tracing::warn!.

Both are straightforward to fix. The rest of the change is solid and ready to ship. See the prior comment for the full findings.

- Add assertions to test_initialize_success verifying SCHEMA CREATION
  RULES and SEARCH FIRST sections are present in initialize response;
  prevents silent regressions from typos or future refactors
- Add test_create_schema_description_includes_type_list to verify the
  dynamic type list appears in create_schema description
- Change unwrap_or_default() to unwrap_or_else(|| "(none)".to_string())
  so an empty schema list produces "Currently available types: (none)"
  instead of a malformed "Currently available types: ."

Addresses reviewer recommendations from PR #1079.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator Author

Review Addressed

Both important findings fixed in commit 17d5208:

✅ Missing test assertions added (initialize_test.rs, tools_test.rs)

  • Added assertions to test_initialize_success verifying SCHEMA CREATION RULES and SEARCH FIRST sections are present
  • Added test_create_schema_description_includes_type_list to verify the dynamic type list appears in create_schema description

✅ Silent malformed fallback hardened (tools.rs)

  • Changed unwrap_or_default() → unwrap_or_else(|| "(none)".to_string()) so empty schema list produces "Currently available types: (none)" instead of "Currently available types: ."

⏭️ Suggestions skipped:

  • {{name}} escaping comment: the escaping is correct and Rust's format string rules are well-documented — a comment would add noise without improving safety
  • fields description vs type enum contradiction: array/object types are in the enum for completeness but the description is guidance for common cases; updating the description to "primarily scalar" would be accurate but is scope creep for this PR
  • SEARCH FIRST placement: low priority, not a blocker

All 1163 core tests pass.

@malibio

malibio commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator Author

Re-Review: commit 17d5208

Scope: delta since last review commit 82fd74a. Three files changed, no other files touched.

Verification of Each Fix

1. initialize_test.rs — instruction assertions added

test_initialize_success now extracts result["instructions"].as_str().unwrap() and asserts both "SCHEMA CREATION RULES" and "SEARCH FIRST" are present with clear failure messages. The assertion is placed after the existing capability checks, which is the correct position. No concerns.

2. tools_test.rs — test_create_schema_description_includes_type_list added

New standalone #[test] constructs a two-schema slice (customer, invoice), calls get_tool_schemas, locates create_schema by name, and asserts all three expected substrings: "customer", "invoice", and "Currently available types:". The failure message for each assert! includes {description} as context, which is good practice for debugging CI failures. The test covers the dynamic path end-to-end.

3. tools.rs — unwrap_or_default() hardened

Changed to unwrap_or_else(|| "(none)".to_string()). The surrounding context confirms this is the sole unwrap_or_else on this expression. An empty schema list will now produce "Currently available types: (none)." — a readable sentinel instead of a malformed "Currently available types: .".

No New Issues Introduced

  • The diff is minimal and surgical — three files, no logic changes outside the two targeted sites.
  • The new test does not rely on async infrastructure and correctly uses get_tool_schemas directly (matching the pattern of test_tool_schemas_include_custom_schema_ids).
  • The unwrap() calls in the new test assertions are appropriate for test code where a missing field is a hard failure.
  • All three skipped suggestions from the first review (format string comment, fields enum wording, SEARCH FIRST placement) remain acceptable to defer; none are blockers.

Verdict: both [Improvement] findings are fully and correctly addressed. Approving.

@malibio
malibio merged commit 416a412 into main Apr 8, 2026
@malibio
malibio deleted the feature/mcp-tool-description-alignment branch April 8, 2026 12:44
malibio added a commit that referenced this pull request Jun 22, 2026
* Align MCP tool descriptions with local agent guidance

Key gaps closed between what external LLMs (via MCP) and the local agent
are told about how to use NodeSpace tools correctly.

initialize.rs — two new instruction sections:
- SCHEMA CREATION RULES: no name/title fields, enum coreValues format,
  targetType must be an existing type, prefer relationships over arrays
- SEARCH FIRST: always search before fetching/updating by ID; never use
  guessed IDs

tools.rs (create_schema):
- Tool description now dynamic: includes current node_type_enum so
  external LLMs see the same available types list as create_node already
  does
- FIELDS section: explicit "no name/title" rule + title_template exception
- coreValues field added to enum fields (same as local agent tools.rs)
- RELATIONSHIPS: targetType description now says "MUST be an existing type
  — do NOT invent types that don't exist yet"
- title_template description: clarified that {name} token requires a 'name'
  field to be defined

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* Address review: add instruction assertions and harden type list fallback

- Add assertions to test_initialize_success verifying SCHEMA CREATION
  RULES and SEARCH FIRST sections are present in initialize response;
  prevents silent regressions from typos or future refactors
- Add test_create_schema_description_includes_type_list to verify the
  dynamic type list appears in create_schema description
- Change unwrap_or_default() to unwrap_or_else(|| "(none)".to_string())
  so an empty schema list produces "Currently available types: (none)"
  instead of a malformed "Currently available types: ."

Addresses reviewer recommendations from PR #1079.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant