Repository navigation
Description
Overview
Add capability to auto-generate MCP tool schemas from Rust function signatures, type definitions, and validation rules. This eliminates manual schema maintenance burden and ensures schemas stay in sync with implementation as the API evolves.
Background
Current Approach (Issue #308)
Tool schemas are hardcoded manually:
fn get_tool_schemas() -> Value {
json!([
{
"name": "create_node",
"description": "Create a new node in NodeSpace", // ← Manual
"inputSchema": {
"properties": {
"node_type": {
"enum": ["text", "task", "header", ...], // ← Manual
"description": "Type of node" // ← Manual
}
}
}
}
// ... repeat for each method
])
}Problems:
- ❌ Duplication: Schema repeats information already in Rust types
- ❌ Maintenance burden: Every API change requires manual schema update
- ❌ Drift risk: Schemas can get out of sync with implementation
- ❌ Error-prone: Easy to forget updating schemas when adding methods
Desired Approach (This Issue)
Generate schemas automatically from Rust code:
// Rust type definition (single source of truth)
pub const ALLOWED_NODE_TYPES: &[&str] = &[
"text", "header", "task", "date",
"code-block", "quote-block", "ordered-list"
];
// Auto-generated schema
{
"node_type": {
"type": "string",
"enum": ["text", "header", "task", ...], // ← From ALLOWED_NODE_TYPES
"description": "Type of node to create" // ← From doc comment
}
}Benefits:
- ✅ Single source of truth (Rust types)
- ✅ Zero maintenance: Schemas update automatically
- ✅ No drift: Schemas always match implementation
- ✅ Less code: No manual JSON writing
Implementation Approaches
Option 1: Compile-Time Generation (Recommended)
Use proc macros to generate schemas at compile time:
use mcp_schema::tool;
/// Create a new node in NodeSpace
#[tool]
pub async fn handle_create_node(
service: &Arc<NodeService>,
/// Type of node to create
#[param(enum = ALLOWED_NODE_TYPES)]
node_type: String,
/// Content of the node
content: String,
/// Optional parent node ID
#[param(optional)]
parent_id: Option<String>,
) -> Result<Value, MCPError> {
// Implementation...
}
// Macro generates:
// - JSON schema from function signature
// - Extracts descriptions from doc comments
// - Converts ALLOWED_NODE_TYPES to enum
// - Marks Option<T> fields as optionalPros:
- Zero runtime cost (compile-time only)
- Type-safe (compiler enforces schema validity)
- IDE integration (jump to definition works)
Cons:
- More complex implementation (proc macros)
- Harder to debug
Option 2: Runtime Reflection (Simpler)
Use serde introspection at runtime:
#[derive(Deserialize, JsonSchema)]
struct CreateNodeParams {
/// Type of node to create
#[serde(rename = "node_type")]
#[schema(enum_ref = "ALLOWED_NODE_TYPES")]
node_type: String,
/// Content of the node
content: String,
/// Optional parent node ID
#[serde(skip_serializing_if = "Option::is_none")]
parent_id: Option<String>,
}
// Generate schema:
let schema = schemars::schema_for!(CreateNodeParams);Pros:
- Simpler implementation
- Uses existing ecosystem (
schemarscrate) - Easier to debug
Cons:
- Runtime cost (small)
- Less flexible customization
Option 3: Hybrid (Best of Both)
Generate base schemas automatically, allow manual overrides:
#[tool(
description = "Create a new node (supports all node types)" // Manual override
)]
pub async fn handle_create_node(
service: &Arc<NodeService>,
#[param(enum = ALLOWED_NODE_TYPES)] // Auto-generated
node_type: String,
content: String,
) -> Result<Value, MCPError>
// Generates schema with:
// - Auto: enum values from ALLOWED_NODE_TYPES
// - Auto: required vs optional from Option<T>
// - Manual: custom description overrideImplementation Tasks
Phase 1: Research & Proof of Concept
- Evaluate
schemarscrate for JSON Schema generation - Prototype proc macro for
#[tool]attribute - Test with one method (create_node)
- Verify generated schema matches manual schema
- Benchmark runtime cost (if using runtime generation)
Phase 2: Schema Generation Core
- Implement schema generator for all current methods
- Extract enums from constants (ALLOWED_NODE_TYPES)
- Convert doc comments to descriptions
- Handle Option → optional fields
- Support custom overrides for descriptions
Phase 3: Integration
- Update
get_tool_schemas()to use generator - Add tests comparing generated vs manual schemas
- Update documentation with new approach
- Add compile-time checks for schema validity
Phase 4: Cleanup
- Remove old manual schemas
- Update CONTRIBUTING guide with schema conventions
- Add examples for future methods
Example: Before vs After
Before (Manual - Current)
// In constants.rs
pub const ALLOWED_NODE_TYPES: &[&str] = &["text", "task"];
// In handlers/nodes.rs
pub async fn handle_create_node(...) { }
// In handlers/initialize.rs (separate file!)
fn get_tool_schemas() -> Value {
json!([{
"name": "create_node",
"description": "Create a new node", // ← Duplicate doc
"inputSchema": {
"properties": {
"node_type": {
"enum": ["text", "task"], // ← Duplicate enum
}
}
}
}])
}
// Problem: Add new node type?
// 1. Update ALLOWED_NODE_TYPES
// 2. Remember to update schema in different file ❌After (Auto-Generated)
// In constants.rs
pub const ALLOWED_NODE_TYPES: &[&str] = &["text", "task", "code-block"];
// In handlers/nodes.rs
/// Create a new node in NodeSpace
#[tool]
pub async fn handle_create_node(
service: &Arc<NodeService>,
#[param(enum = ALLOWED_NODE_TYPES)]
node_type: String,
content: String,
) -> Result<Value, MCPError> { }
// In handlers/initialize.rs
fn get_tool_schemas() -> Value {
// Auto-generated from all #[tool] functions
generate_schemas()
}
// Problem: Add new node type?
// 1. Update ALLOWED_NODE_TYPES
// 2. Schema auto-updates! ✅Design Considerations
What Should Be Auto-Generated?
✅ Auto-generate:
- Method names (from function name)
- Parameter names (from function signature)
- Required vs optional (from Option)
- Enum values (from constants)
- Basic descriptions (from doc comments)
- Parameter types (string, number, boolean, object)
- Detailed descriptions (for clarity)
- Examples (for documentation)
- Deprecated warnings
- Custom validation rules
❌ Keep manual:
- High-level API design decisions
- Grouping/organization of methods
- Versioning strategy
Handling Edge Cases
1. Complex nested types:
// How to handle this?
properties: HashMap<String, serde_json::Value>
// Option A: Generic "object" type
{"type": "object"}
// Option B: Reference external schema
{"": "#/definitions/Properties"}2. Custom validation:
// Currently we validate in handler
if node_type.is_empty() { return Err(...) }
// How to express in schema?
#[param(min_length = 1)]
node_type: String3. Conditional parameters:
// Some node types require extra fields
// How to express: if node_type == "task" then status is required?
// Option: Keep this validation in handler onlySuccess Criteria
- Schema generation works for all 6+ current MCP methods
- Generated schemas match manually-written schemas (validated by tests)
- Adding new method requires zero schema code
- Changing parameter types automatically updates schema
- Enum changes (like adding node types) reflect in schema
- Doc comments appear as descriptions in schemas
- Schema validation tests pass
- No performance regression (< 1ms overhead acceptable)
Testing Strategy
#[test]
fn test_generated_schema_matches_manual() {
let generated = generate_schema_for::<handle_create_node>();
let manual = json!({
"name": "create_node",
// ... manual schema
});
assert_eq!(normalize_schema(generated), normalize_schema(manual));
}
#[test]
fn test_enum_sync() {
let schema = generate_schema_for::<handle_create_node>();
let enum_values = schema["inputSchema"]["properties"]["node_type"]["enum"]
.as_array()
.unwrap();
// Verify enum matches ALLOWED_NODE_TYPES
assert_eq!(
enum_values.len(),
ALLOWED_NODE_TYPES.len(),
"Schema enum out of sync with ALLOWED_NODE_TYPES"
);
}References
- Parent Issue: Implement MCP initialization handshake and capability discovery #308 (MCP initialization - where this idea originated)
- Related Crates:
schemars- JSON Schema generation from Rust typesserde_json- Already used for JSON handling
- MCP Spec: https://modelcontextprotocol.io/specification (schema requirements)
Non-Goals (Out of Scope)
- ❌ Generating handler implementations (just schemas)
- ❌ Client-side code generation
- ❌ Schema versioning/migration
- ❌ GraphQL or other schema formats (MCP only)
Future Enhancements
- Auto-generate TypeScript types from schemas
- Schema validation middleware
- Interactive schema documentation
- Schema diff tool for API changes
Updates (2025-01-22)
Integration with NodeOperations (#332)
Domain-specific MCP tools will be thin wrappers around the generic NodeOperations layer:
// Built-in domain-specific tools
CreateTaskTool → operations.create_node("task", ...)
FindTasksTool → operations.query_nodes(type: "task", ...)
CreateTextNodeTool → operations.create_node("text", ...)
CreateHeaderTool → operations.create_node("header", ...)
// Generic fallback
CreateNodeTool → operations.create_node(user_type, ...)All tools delegate to NodeOperations for business rule enforcement.
Dependencies:
- Depends on: Create NodeOperations Business Logic Layer #332 (NodeOperations must be implemented first)
Activity
malibio commentedon May 17, 2026
Closing: Superseded by ADR-031 (gRPC/protobuf replaces MCP)
The MCP server is being deleted as part of the daemon-client architecture (ADR-031). With the MCP server gone, there are no MCP tool schemas to generate.
The concern this issue addressed — keeping tool schemas in sync with Rust types — is solved structurally under ADR-031: protobuf
.protofiles are the single source of truth for all service interfaces.prostgenerates Rust bindings from proto definitions at build time, so there is no manual schema duplication.Closing as superseded by the protobuf build pipeline (covered in the new daemon foundation issues).