Skip to content

Add HTTP Transport to MCP Server for Claude Code Integration #323

Closed

Description

@malibio

Overview

The MCP (Model Context Protocol) server currently only supports stdio transport, which works for CLI tools but cannot be used by Claude Code when NodeSpace is running as a GUI application. Add HTTP transport as an alternative, allowing external MCP clients like Claude Code to connect to a running NodeSpace instance.

Problem Statement

Current State:

  • MCP server runs inside Tauri app process
  • Reads from tokio::io::stdin() and writes to stdout
  • Claude Code cannot pipe stdin/stdout to an already-running GUI app

Desired State:

  • MCP server listens on HTTP endpoint at http://localhost:3001/mcp
  • Claude Code connects via bridge script that translates stdio → HTTP
  • GUI app receives MCP requests and emits Tauri events for UI updates

Architecture Decisions

Transport Strategy

  • Keep both transports (stdio AND HTTP)
  • Stdio: CLI tools, testing, headless mode
  • HTTP: GUI + Claude Code integration
  • Shared handlers: Same business logic for both transports

HTTP Configuration

  • Port: 3001 (hardcoded for now, future: configurable)
  • Binding: 127.0.0.1 only (localhost, no network exposure)
  • Protocol: Standard MCP over HTTP (JSON-RPC 2.0)
  • Security: None needed (localhost-only access)

Claude Code Integration

  • Bridge script translates stdio → HTTP POST
  • Endpoint: POST /mcp with JSON-RPC 2.0 body
  • Format: Same JSON-RPC as stdio, just different transport
  • Example flow:
    Claude Code → stdio → Bridge Script → HTTP POST → NodeSpace MCP Server
    

Scope

Implementation Tasks

Phase 1: Refactor for Transport Abstraction

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

  • Add McpTransport enum with Stdio and Http variants
  • Extract existing stdio logic into run_stdio_server() function
  • Update run_mcp_server_with_callback() to accept transport parameter
  • Add transport dispatch logic matching on transport type

Implementation Pattern:

pub enum McpTransport {
    Stdio,              // CLI tools, testing
    Http { port: u16 }, // GUI + Claude Code
}

pub async fn run_mcp_server_with_callback(
    services: McpServices,
    transport: McpTransport,  // NEW parameter
    callback: Option<ResponseCallback>,
) -> anyhow::Result<()> {
    match transport {
        McpTransport::Stdio => run_stdio_server(services, callback).await,
        McpTransport::Http { port } => run_http_server(services, port, callback).await,
    }
}

Phase 2: Implement HTTP Transport

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

  • Verify axum dependency exists in Cargo.toml (already in dev_server)
  • Implement run_http_server() function using axum Router
  • Create handle_http_mcp_request() handler that reuses existing handle_request() logic
  • Bind server to 127.0.0.1:3001 (security: localhost only)
  • Ensure callbacks work identically for Tauri event emissions

HTTP Server Pattern:

async fn run_http_server(
    services: McpServices,
    port: u16,
    callback: Option<ResponseCallback>,
) -> anyhow::Result<()> {
    use axum::{routing::post, Router, Json, extract::State};
    
    info!("🔌 MCP HTTP server starting on http://localhost:{}", port);
    
    let app = Router::new()
        .route("/mcp", post(handle_http_mcp_request))
        .with_state((services, callback));
    
    let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;
    
    info!("✅ MCP HTTP server listening on http://localhost:{}", port);
    axum::serve(listener, app).await?;
    Ok(())
}

async fn handle_http_mcp_request(
    State((services, callback)): State<(McpServices, Option<ResponseCallback>)>,
    Json(request): Json<MCPRequest>,
) -> Json<MCPResponse> {
    // Reuse existing request handler!
    let state = ServerState { initialized: Arc::new(AtomicBool::new(false)) };
    let response = handle_request(&services, &state, request).await;
    
    // Invoke callback for Tauri events
    if let (Some(cb), Some(result)) = (&callback, &response.result) {
        cb(&request.method, result);
    }
    
    Json(response)
}

Phase 3: Update Tauri Integration

File: packages/desktop-app/src-tauri/src/lib.rs

  • Update initialize_mcp_server() to use HTTP transport
  • Pass McpTransport::Http { port: 3001 } to MCP server

Implementation:

pub fn initialize_mcp_server(app: tauri::AppHandle) -> anyhow::Result<()> {
    // ... existing service setup ...
    
    tauri::async_runtime::spawn(async move {
        let result = mcp_integration::run_mcp_server_with_events(
            mcp_services,
            McpTransport::Http { port: 3001 },  // ← Use HTTP transport
            app,
        )
        .catch_unwind()
        .await;
        
        // ... existing error handling ...
    });
    
    Ok(())
}

File: packages/desktop-app/src-tauri/src/mcp_integration.rs

  • Update run_mcp_server_with_events() signature to accept transport parameter
  • Pass transport to core MCP server function

Phase 4: Create Bridge Script for Claude Code

File: scripts/mcp-bridge.sh (NEW)

Bridge Script Pattern:

#!/usr/bin/env bash
# MCP Bridge - Translates stdio (Claude Code) to HTTP (NodeSpace)

MCP_SERVER_URL="${MCP_SERVER_URL:-http://localhost:3001/mcp}"

while IFS= read -r line; do
    response=$(curl -s -X POST "$MCP_SERVER_URL" \
        -H "Content-Type: application/json" \
        -d "$line" 2>/dev/null)
    
    if [ $? -eq 0 ]; then
        echo "$response"
    else
        echo '{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"Failed to connect to NodeSpace MCP server"}}'
    fi
done

File: scripts/mcp-bridge.bat (NEW)

  • Create Windows batch equivalent using curl
  • Same functionality as bash version

Phase 5: Testing

Unit Tests - packages/core/src/mcp/server_test.rs

  • Test HTTP server starts successfully on port 3001
  • Test HTTP MCP initialize request returns capabilities
  • Test HTTP MCP create_node request works
  • Test both stdio and HTTP transports work (no regression)

Integration Tests

  • Test bridge script translates stdio to HTTP correctly
  • Test bridge script handles connection errors gracefully
  • Manual test: Bridge script with running NodeSpace app

End-to-End Test with Claude Code

  • Configure Claude Code with bridge script
  • Verify NodeSpace appears in MCP servers list
  • Test calling initialize method
  • Test calling create_nodes_from_markdown method
  • Verify UI updates in NodeSpace when MCP operations occur

Test Commands:

# Unit tests
cargo test -p nodespace-core mcp::server

# Manual bridge test
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | ./scripts/mcp-bridge.sh

# Expected: JSON-RPC response with capabilities

Phase 6: Documentation

File: docs/architecture/business-logic/mcp-integration.md

  • Add HTTP Transport section explaining production setup
  • Document port 3001, localhost-only binding
  • Explain transport abstraction (both stdio and HTTP supported)
  • Update Claude Code setup instructions with bridge script config

Documentation Pattern:

## HTTP Transport (Production - GUI Mode)

For GUI applications, the MCP server uses HTTP transport:

\`\`\`
Claude Code → Bridge Script → HTTP POST localhost:3001/mcp → MCP Server
\`\`\`

**Configuration:**
- Port: 3001
- Binding: 127.0.0.1 (localhost only)
- Protocol: JSON-RPC 2.0 over HTTP POST

### Claude Code Setup

1. Launch NodeSpace app (MCP HTTP server starts on port 3001)

2. Configure `~/.claude.json`:
   \`\`\`json
   {
     "mcpServers": {
       "nodespace": {
         "type": "stdio",
         "command": "/Applications/NodeSpace.app/Contents/Resources/mcp-bridge.sh"
       }
     }
   }
   \`\`\`

3. Restart Claude Code and verify connection with `/mcp` command

File: README.md

  • Add MCP Integration section
  • List supported clients (Claude Code via HTTP bridge)
  • Link to detailed integration guide

Acceptance Criteria

Primary Success Criterion

Claude Code can connect via bridge script and successfully call all MCP methods, with NodeSpace GUI updating in real-time

Functional Requirements

  • HTTP server starts on port 3001 when NodeSpace launches
  • Bridge script translates stdio → HTTP correctly
  • Claude Code can call initialize and see NodeSpace capabilities
  • Claude Code can call create_nodes_from_markdown and nodes appear in GUI
  • Claude Code can call get_markdown_from_node_id and receive content
  • Claude Code can call search_containers (when Expose semantic search via MCP (search_containers method) #321 merges)
  • Claude Code can call all CRUD operations (create_node, get_node, update_node, delete_node, query_nodes)
  • Tauri events emit for all mutation operations
  • NodeSpace GUI updates in real-time when MCP operations occur via HTTP

Technical Requirements

  • Both stdio and HTTP transports work (no regression)
  • McpTransport enum implemented with Stdio and Http variants
  • HTTP handler reuses existing handle_request() logic (no duplication)
  • Server binds to 127.0.0.1 only (security verified)
  • All existing MCP tests pass
  • New HTTP-specific unit tests added
  • HTTP transport adds <100 lines of code
  • HTTP latency <10ms for localhost requests

Testing Requirements

  • Unit tests: HTTP server startup, request/response
  • Integration test: Bridge script stdio ↔ HTTP translation
  • Manual E2E: Claude Code connecting and calling methods
  • All existing stdio transport tests still pass

Documentation Requirements

  • Claude Code setup instructions complete
  • Bridge script documented with example config
  • Transport architecture explained in mcp-integration.md
  • README updated with MCP integration section

Technical Specifications

Reference Files

  • MCP Server Core: packages/core/src/mcp/server.rs - Main implementation
  • MCP Types: packages/core/src/mcp/types.rs - Protocol types (reused)
  • MCP Handlers: packages/core/src/mcp/handlers/ - Business logic (reused)
  • Tauri Integration: packages/desktop-app/src-tauri/src/mcp_integration.rs - Event emissions
  • HTTP Dev Server Pattern: packages/desktop-app/src-tauri/src/dev_server/ - Architecture reference

System Requirements

  • Port: 3001 (hardcoded for now)
  • Binding: 127.0.0.1 only (localhost, no network exposure)
  • Protocol: HTTP POST with JSON-RPC 2.0 body
  • Dependencies: axum (already exists), tokio, serde_json (all existing)
  • Bridge Dependency: curl (built-in on all platforms)

Supported MCP Methods

All methods must work identically via both stdio and HTTP:

  • initialize - Capability negotiation
  • create_node - Single node creation
  • get_node - Retrieve node by ID
  • update_node - Update node content/properties
  • delete_node - Delete node
  • query_nodes - Query with filters
  • create_nodes_from_markdown - Batch import
  • get_markdown_from_node_id - Export to markdown
  • search_containers - Semantic search (when Expose semantic search via MCP (search_containers method) #321 merges)

Related Issues

Definition of Done

  • Feature works end-to-end: Claude Code → bridge → HTTP → MCP → DB → UI update
  • Both stdio and HTTP transports fully functional
  • All tests pass (unit, integration, end-to-end)
  • Code review completed
  • Documentation updated with Claude Code setup instructions
  • Bridge script tested on macOS, Linux, and Windows
  • Ready for production use

Activity

  1. self-assigned this
    on Oct 21, 2025
  2. added 2 commits that reference this issue on Oct 21, 2025
    f5040e9
    bc5444e
  3. added 2 commits that reference this issue on Feb 4, 2026
    4e65c9d
    49cf3fb
  4. added a commit that references this issue on Feb 26, 2026
    5c3b16f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions