Skip to content

Implement MCP initialization handshake and capability discovery #308

Closed

Description

@malibio

Overview

Add the MCP (Model Context Protocol) initialization handshake to enable proper capability negotiation between NodeSpace and MCP clients like Claude Code. This is a critical missing piece from the current MCP implementation (Issue #112) that prevents clients from discovering available methods and schema changes.

Implementation Q&A (From Agent Questions)

Q1: Should I implement the optional state tracking?

A: YES, implement it. It's marked "optional but recommended" but it's actually important for MCP spec compliance.

Why:

  • The MCP specification says: "The server SHOULD NOT send requests other than pings and logging before receiving the initialized notification"
  • Prevents protocol violations and confusing error states
  • Simple to implement (just an Arc<AtomicBool>)
  • Better error messages for clients that skip initialization

Implementation:

struct ServerState {
    initialized: Arc<AtomicBool>,
}

// In handle_request, before dispatching:
if request.method \!= "initialize" 
   && request.method \!= "ping"
   && \!state.initialized.load(Ordering::SeqCst) 
{
    return MCPResponse::error(
        request.id,
        MCPError::invalid_request(
            "Session not initialized. Send initialize request first.".to_string()
        )
    );
}

Q2: Should I explore auto-generating schemas from handler function signatures?

A: NO, keep it manual for this issue. But add a TODO comment for future enhancement.

Why manual for now:

  1. Simplicity first - Get basic capability working
  2. Explicit is better - Tool descriptions need human-crafted explanations
  3. Schema ≠ Types - JSON Schema for MCP is more detailed than Rust types
  4. Issue scope - Implement MCP initialization handshake and capability discovery #308 is about getting initialization working, not building a schema framework

Example of the mismatch:

// Rust function signature (what you have):
pub async fn handle_create_node(service: &Arc<NodeService>, params: Value)

// MCP schema needs (what clients want):
{
  "description": "Create a new node in NodeSpace",  // ← Human explanation
  "inputSchema": {
    "properties": {
      "node_type": {
        "enum": ["text", "task", ...],  // ← Specific enums
        "description": "Type of node to create"   // ← Field-level docs
      }
    }
  }
}

For this issue:

  • Hardcode schemas manually in get_tool_schemas()
  • Add TODO comment: // TODO: Consider auto-generating from Rust types (future enhancement)
  • Mention in PR: "Manual schemas for now, auto-generation could be explored in future issue"

Future enhancement idea:

  • Use serde reflection or proc macros
  • Extract enums from ALLOWED_NODE_TYPES constant
  • Generate base schemas, allow manual overrides for descriptions
  • Update schemas automatically when types change

Q3: Should I add comprehensive unit tests or rely on manual echo testing?

A: BOTH. Prioritize unit tests.

Why unit tests are critical:

  1. Regression prevention - Manual testing won't catch future breaks
  2. CI/CD integration - Automated tests run on every commit
  3. Documentation - Tests show exactly how the API works
  4. Faster iteration - No need to manually pipe echo commands

Testing strategy:

Priority 1: Unit Tests (Required)

#[cfg(test)]
mod initialize_tests {
    use super::*;
    
    #[tokio::test]
    async fn test_initialize_success() {
        let params = json\!({
            "protocolVersion": "2024-11-05",
            "clientInfo": {"name": "test-client"}
        });
        
        let result = handle_initialize(params).await.unwrap();
        
        assert_eq\!(result["protocolVersion"], "2024-11-05");
        assert\!(result["capabilities"]["tools"].is_array());
        
        // Verify all expected methods are present
        let tools = result["capabilities"]["tools"].as_array().unwrap();
        assert\!(tools.iter().any(|t| t["name"] == "create_node"));
        assert\!(tools.iter().any(|t| t["name"] == "get_node"));
        assert\!(tools.iter().any(|t| t["name"] == "update_node"));
        assert\!(tools.iter().any(|t| t["name"] == "delete_node"));
        assert\!(tools.iter().any(|t| t["name"] == "query_nodes"));
        assert\!(tools.iter().any(|t| t["name"] == "create_nodes_from_markdown"));
    }
    
    #[tokio::test]
    async fn test_initialize_wrong_version() {
        let params = json\!({
            "protocolVersion": "1999-01-01",  // Unsupported
            "clientInfo": {"name": "test"}
        });
        
        let result = handle_initialize(params).await;
        assert\!(result.is_err());
        
        let err = result.unwrap_err();
        assert_eq\!(err.code, crate::mcp::types::INVALID_REQUEST);
        assert\!(err.message.contains("Unsupported protocol version"));
    }
    
    #[tokio::test]
    async fn test_initialize_missing_version() {
        let params = json\!({"clientInfo": {"name": "test"}});
        let result = handle_initialize(params).await;
        assert\!(result.is_err());
        
        let err = result.unwrap_err();
        assert_eq\!(err.code, crate::mcp::types::INVALID_PARAMS);
    }
    
    #[tokio::test]
    async fn test_all_schemas_have_required_fields() {
        let schemas = get_tool_schemas();
        let tools = schemas.as_array().unwrap();
        
        assert\!(tools.len() >= 6, "Should have at least 6 tool schemas");
        
        for schema in tools {
            // Every schema must have these fields
            assert\!(schema["name"].is_string(), "Schema missing name: {:?}", schema);
            assert\!(schema["description"].is_string(), "Schema missing description: {:?}", schema);
            assert\!(schema["inputSchema"].is_object(), "Schema missing inputSchema: {:?}", schema);
            
            // InputSchema must have proper structure
            let input_schema = &schema["inputSchema"];
            assert_eq\!(input_schema["type"], "object", "InputSchema must be type object");
            assert\!(input_schema["properties"].is_object(), "InputSchema must have properties");
        }
    }
    
    #[tokio::test]
    async fn test_operation_before_initialize() {
        // Test that operations fail before initialization
        // (Only relevant if state tracking is implemented)
        let state = ServerState {
            initialized: Arc::new(AtomicBool::new(false))
        };
        
        let request = MCPRequest {
            jsonrpc: "2.0".to_string(),
            id: 1,
            method: "create_node".to_string(),
            params: json\!({})
        };
        
        // Should return error because not initialized
        let response = handle_request_with_state(&node_service, request, &state).await;
        assert\!(response.error.is_some());
        assert\!(response.error.unwrap().message.contains("not initialized"));
    }
}

Priority 2: Integration Tests (Recommended)

#[tokio::test]
async fn test_full_initialization_flow() {
    // Simulate full MCP handshake
    // 1. Send initialize request
    // 2. Verify response has correct structure
    // 3. Send initialized notification
    // 4. Try operation (should succeed)
}

Priority 3: Manual Testing (Final Verification)
Use the echo commands AFTER unit tests pass to verify stdio transport works end-to-end.

Test coverage goals:

  • ✅ Initialize with valid version → success
  • ✅ Initialize with invalid version → error
  • ✅ Initialize missing parameters → error
  • ✅ All tool schemas present and valid
  • ✅ Schema structure validation (name, description, inputSchema)
  • ✅ Operations before initialize → error (if state tracking implemented)
  • ✅ Operations after initialize → success

Background

What is MCP Initialization?

The MCP protocol requires a three-phase connection lifecycle:

  1. Initialization Phase: Client and server exchange capabilities
  2. Operation Phase: Normal request/response communication
  3. Shutdown Phase: Graceful connection termination

Currently missing: We skip the initialization phase entirely and jump straight to operations. This means:

  • ❌ Clients don't know what methods are available
  • ❌ Clients don't know parameter schemas
  • ❌ No way to discover new methods when we add them
  • ❌ No protocol version negotiation

Why This Matters

Without initialization:

// Claude Code connects, tries to call a method
Client: {"method": "create_node", "params": {...}}
Server: {"result": {...}}  // Works, but client had to guess

// Client doesn't know:
// - What other methods exist?
// - What parameters are required?
// - What node types are valid?

With initialization:

// Client connects
Client: {"method": "initialize", "params": {"protocolVersion": "2024-11-05", ...}}

// Server responds with full capability list
Server: {
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": [
        {
          "name": "create_node",
          "description": "Create a new node",
          "inputSchema": {
            "type": "object",
            "properties": {
              "node_type": {"type": "string", "enum": ["text", "task", "header", ...]},
              "content": {"type": "string"}
            },
            "required": ["node_type", "content"]
          }
        },
        {
          "name": "update_node",
          "description": "Update an existing node",
          "inputSchema": {...}
        }
        // ... all available methods
      ]
    }
  }
}

// Now client knows EXACTLY what's available\!
// - Autocomplete works
// - Parameter validation works
// - Schema changes auto-discovered on reconnect

Implementation Tasks

1. Add Initialize Handler

File: packages/core/src/mcp/handlers/mod.rs

Create new file: packages/core/src/mcp/handlers/initialize.rs

use crate::mcp::types::MCPError;
use serde_json::{json, Value};

/// Handle MCP initialize request
///
/// This is the FIRST method called when a client connects.
/// Returns server capabilities, protocol version, and tool schemas.
///
/// # Protocol Flow
///
/// 1. Client sends initialize request with their protocol version
/// 2. Server validates version compatibility
/// 3. Server returns supported version + capabilities
/// 4. Client sends initialized notification (handled separately)
/// 5. Normal operations begin
pub async fn handle_initialize(params: Value) -> Result<Value, MCPError> {
    // Parse client's initialize request
    let client_version = params["protocolVersion"]
        .as_str()
        .ok_or_else(|| MCPError::invalid_params("Missing protocolVersion".to_string()))?;

    // Version negotiation: Check if we support client's version
    // MCP spec: Server should respond with same version if supported,
    // or suggest alternative version
    let supported_version = "2024-11-05";
    if client_version \!= supported_version {
        // For now, only support latest version
        // Future: Could negotiate older versions
        return Err(MCPError::invalid_request(format\!(
            "Unsupported protocol version: {}. Server supports: {}",
            client_version, supported_version
        )));
    }

    // Build capability response
    Ok(json\!({
        "protocolVersion": supported_version,
        "serverInfo": {
            "name": "nodespace-mcp-server",
            "version": env\!("CARGO_PKG_VERSION")
        },
        "capabilities": {
            "tools": get_tool_schemas(),
            "resources": {},  // Future: Add resource capabilities
            "prompts": {}     // Future: Add prompt capabilities
        }
    }))
}

/// Generate JSON schemas for all available MCP tools
/// 
/// TODO: Consider auto-generating from Rust types (future enhancement)
/// For now, manually maintain schemas to ensure quality descriptions
fn get_tool_schemas() -> Value {
    json\!([
        {
            "name": "create_node",
            "description": "Create a new node in NodeSpace",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "node_type": {
                        "type": "string",
                        "enum": ["text", "header", "task", "date", "code-block", "quote-block", "ordered-list"],
                        "description": "Type of node to create"
                    },
                    "content": {
                        "type": "string",
                        "description": "Content of the node (markdown format for most types)"
                    },
                    "parent_id": {
                        "type": "string",
                        "description": "Optional parent node ID for hierarchy"
                    },
                    "container_node_id": {
                        "type": "string",
                        "description": "Optional container/document ID"
                    },
                    "properties": {
                        "type": "object",
                        "description": "Additional type-specific properties (JSON object)"
                    }
                },
                "required": ["node_type", "content"]
            }
        },
        {
            "name": "get_node",
            "description": "Retrieve a single node by ID",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "node_id": {
                        "type": "string",
                        "description": "ID of the node to retrieve"
                    }
                },
                "required": ["node_id"]
            }
        },
        {
            "name": "update_node",
            "description": "Update an existing node's content or properties",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "node_id": {
                        "type": "string",
                        "description": "ID of the node to update"
                    },
                    "content": {
                        "type": "string",
                        "description": "Updated content"
                    },
                    "properties": {
                        "type": "object",
                        "description": "Updated properties"
                    }
                },
                "required": ["node_id"]
            }
        },
        {
            "name": "delete_node",
            "description": "Delete a node and optionally its children",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "node_id": {
                        "type": "string",
                        "description": "ID of the node to delete"
                    }
                },
                "required": ["node_id"]
            }
        },
        {
            "name": "query_nodes",
            "description": "Query nodes with filters",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "filters": {
                        "type": "array",
                        "description": "Array of filter conditions"
                    },
                    "limit": {
                        "type": "number",
                        "description": "Maximum number of results"
                    }
                }
            }
        },
        {
            "name": "create_nodes_from_markdown",
            "description": "Parse markdown and create hierarchical nodes",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "markdown_content": {
                        "type": "string",
                        "description": "Markdown content to parse"
                    },
                    "container_title": {
                        "type": "string",
                        "description": "Title for the container node"
                    }
                },
                "required": ["markdown_content", "container_title"]
            }
        }
    ])
}

2. Update Server to Handle Initialize

File: packages/core/src/mcp/server.rs

Current code (around line 111):

async fn handle_request(service: &Arc<NodeService>, request: MCPRequest) -> MCPResponse {
    let result = match request.method.as_str() {
        "create_node" => nodes::handle_create_node(service, request.params).await,
        // ... other methods

Add initialize handler FIRST:

async fn handle_request(service: &Arc<NodeService>, request: MCPRequest) -> MCPResponse {
    let result = match request.method.as_str() {
        // CRITICAL: Initialize must be first interaction
        "initialize" => {
            // Initialize doesn't need NodeService (pure protocol)
            crate::mcp::handlers::initialize::handle_initialize(request.params).await
        }
        
        // Normal operations (require initialization to have completed first)
        "create_node" => nodes::handle_create_node(service, request.params).await,
        "get_node" => nodes::handle_get_node(service, request.params).await,
        // ... rest of methods

3. Add Initialized Notification Support

File: packages/core/src/mcp/types.rs

Currently we only support requests (with ID). Need to support notifications (no ID, no response).

/// JSON-RPC 2.0 notification (no id, no response expected)
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MCPNotification {
    /// JSON-RPC version (must be exactly "2.0")
    #[serde(deserialize_with = "validate_jsonrpc_version")]
    pub jsonrpc: String,

    /// Method name
    pub method: String,

    /// Method parameters
    pub params: Value,
}

File: packages/core/src/mcp/server.rs

Update message parsing to handle both requests and notifications:

while let Some(line) = lines.next_line().await? {
    debug\!("📥 MCP message: {}", line);

    // Try parsing as request first (has id field)
    if let Ok(request) = serde_json::from_str::<MCPRequest>(&line) {
        let request_id = request.id;
        let method = request.method.clone();
        let response = handle_request(&node_service, request).await;
        
        if let Some(ref callback) = callback {
            if let Some(ref result) = response.result {
                callback(&method, result);
            }
        }
        
        write_response(&mut writer, &response).await?;
        continue;
    }

    // Try parsing as notification (no id field)
    if let Ok(notification) = serde_json::from_str::<MCPNotification>(&line) {
        handle_notification(notification).await;
        continue;  // No response for notifications
    }

    // Neither request nor notification - parse error
    warn\!("❌ Invalid JSON-RPC message: {}", line);
    let error_response = MCPResponse::error(
        0,
        MCPError::parse_error(format\!("Invalid JSON-RPC message: {}", line)),
    );
    write_response(&mut writer, &error_response).await?;
}

async fn handle_notification(notification: MCPNotification) {
    match notification.method.as_str() {
        "initialized" => {
            info\!("✅ Client sent initialized notification - ready for operations");
            // Could set a flag here to reject requests before initialized
        }
        _ => {
            debug\!("Received notification: {}", notification.method);
        }
    }
}

4. Add State Tracking (IMPLEMENT THIS - It's Important)

Track whether client has completed initialization:

use std::sync::atomic::{AtomicBool, Ordering};

struct ServerState {
    initialized: Arc<AtomicBool>,
}

// In handle_notification:
"initialized" => {
    state.initialized.store(true, Ordering::SeqCst);
    info\!("✅ MCP session initialized");
}

// In handle_request:
// Reject operations before initialization (except initialize and ping)
if request.method \!= "initialize" 
   && request.method \!= "ping"
   && \!state.initialized.load(Ordering::SeqCst) 
{
    return MCPResponse::error(
        request.id,
        MCPError::invalid_request(
            "Session not initialized. Send initialize request first.".to_string()
        )
    );
}

5. Add Ping Support (Lifecycle)

// In handle_request:
"ping" => {
    // Heartbeat for connection health checks
    Ok(json\!({}))
}

Testing Strategy

Priority 1: Unit Tests (REQUIRED - See Q&A Above)

Write comprehensive unit tests covering:

  • ✅ Initialize with valid version → success
  • ✅ Initialize with invalid version → error
  • ✅ Initialize missing parameters → error
  • ✅ All tool schemas present and valid
  • ✅ Schema structure validation
  • ✅ Operations before initialize → error
  • ✅ Operations after initialize → success

Follow the test examples provided in the Q&A section above.

Priority 2: Manual Testing with Echo (Final Verification)

# Test initialize handshake
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","clientInfo":{"name":"test-client","version":"1.0.0"}}}' | cargo run --bin nodespace-app

# Expected response:
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "serverInfo": {
      "name": "nodespace-mcp-server",
      "version": "0.1.0"
    },
    "capabilities": {
      "tools": [...]
    }
  }
}

# Test initialized notification
echo '{"jsonrpc":"2.0","method":"initialized","params":{}}' | cargo run --bin nodespace-app
# Should log: "✅ MCP session initialized" (no response)

# Test operation after initialization
echo '{"jsonrpc":"2.0","id":2,"method":"create_node","params":{"node_type":"text","content":"Hello"}}' | cargo run --bin nodespace-app

Priority 3: Integration Testing with Claude Code

  1. Configure Claude Code MCP settings
  2. Connect to NodeSpace
  3. Verify initialize handshake in logs
  4. Check that Claude Code shows NodeSpace methods in autocomplete
  5. Test method calls with schema validation

MCP Best Practices Compliance

✅ Critical Requirements

  • Version Negotiation: Server checks client version, responds with supported version
  • Capability Advertisement: Server declares all available tools with schemas
  • Notification Support: Handle initialized notification correctly
  • Request Ordering: Accept initialize before any other requests
  • Error Handling: Return proper JSON-RPC error codes for protocol violations

✅ Logging Requirements

  • CRITICAL: All logs must go to stderr (not stdout)
  • Stdout is ONLY for JSON-RPC messages
  • Use tracing crate (already configured correctly)

✅ Schema Evolution

Once this is implemented, schema changes are auto-discovered:

  1. Add new method to get_tool_schemas()
  2. User disconnects/reconnects MCP (or restarts Claude Code)
  3. New initialize handshake occurs
  4. Client discovers new method automatically!

Acceptance Criteria

  • initialize method handler implemented
  • Returns protocol version, server info, and capabilities
  • Tool schemas include all current MCP methods (create_node, get_node, update_node, delete_node, query_nodes, create_nodes_from_markdown)
  • Protocol version negotiation works (accepts 2024-11-05, rejects others)
  • initialized notification handler implemented
  • Notification parsing added to server loop
  • ping method implemented for health checks
  • State tracking implemented (prevents operations before initialization)
  • Comprehensive unit tests written (see Q&A section for examples)
  • Manual testing with echo commands passes
  • Claude Code can connect and discover capabilities
  • All logging goes to stderr (stdout only for JSON-RPC)

References

Future Enhancements (Not in This Issue)

  • Auto-generate schemas from Rust types (see Q&A Create design system foundation #2 for details)
  • Type-specific method schemas (update_task with task properties)
  • Resource capabilities (file access, database queries)
  • Prompt capabilities (templates and workflows)
  • Multiple protocol version support

Activity

  1. self-assigned this
    on Oct 21, 2025
  2. added a commit that references this issue on Oct 21, 2025
    e3050eb
  3. added a commit that references this issue on Oct 21, 2025
    5750d7b
  4. added 2 commits that reference this issue on Feb 4, 2026
    8eb5645
    170be8c
  5. added a commit that references this issue on Feb 26, 2026
    9c22ac5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions