Skip to content

Add MCP stdio server for AI agent access #112

Closed

Description

@malibio

Overview

Implement MCP (Model Context Protocol) stdio server that allows AI agents to access NodeSpace operations programmatically via JSON-RPC over stdio.

Architecture: MCP runs as an async Tokio task within the Tauri application process (single-process architecture). See ADR-021 for rationale.

Implementation Tasks

MCP Foundation

  • Create MCP types module (src-tauri/src/mcp/types.rs)
    • MCPRequest, MCPResponse, MCPError structs
    • JSON-RPC 2.0 message format
    • Error code constants (standard + custom)
  • Implement stdio server (src-tauri/src/mcp/server.rs)
    • Async tokio::io stdin/stdout handling
    • JSON-RPC request parsing and dispatching
    • Error handling and logging
  • Spawn MCP task in Tauri setup (lib.rs)
    • Use tauri::async_runtime::spawn()
    • Share NodeService via Arc
    • Pass AppHandle for Tauri event emissions

Node Operations

  • Implement node CRUD handlers (src-tauri/src/mcp/handlers/nodes.rs)
    • create_node - Create new node
    • get_node - Retrieve node by ID
    • update_node - Update node content/properties
    • delete_node - Delete node
    • query_nodes - Query nodes with filters
  • Add Tauri event emissions after each operation
    • node-created, node-updated, node-deleted events
    • Ensures UI reactivity when MCP modifies data

Testing & Integration

  • Create standalone Rust test client (examples/mcp_test_client.rs)
  • Test basic CRUD operations via stdio
  • Verify UI updates reactively when MCP creates/updates nodes
  • Test error handling and edge cases

Implementation Q&A

Q1: NodeService Status

A: NodeService already exists at packages/core/src/services/node_service.rs with all CRUD methods. Just use it - do not create/extend!

Available methods:

  • create_node(node: Node) -> Result<String, NodeServiceError>
  • get_node(id: &str) -> Result<Option<Node>, NodeServiceError>
  • update_node(id: &str, update: NodeUpdate) -> Result<(), NodeServiceError>
  • delete_node(id: &str) -> Result<DeleteResult, NodeServiceError>
  • query_nodes_simple(query: NodeQuery) -> Result<Vec<Node>, NodeServiceError>

Initialize like dev-server (see src/bin/dev-server.rs:87-88):

let db_service = DatabaseService::new(db_path).await?;
let node_service = Arc::new(NodeService::new(db_service)?);

Q2: Testing Approach

A: Create standalone Rust binary at examples/mcp_test_client.rs that pipes stdin/stdout to test MCP protocol directly (mirrors how Claude Code will use it).

// examples/mcp_test_client.rs
let mut child = Command::new("./target/debug/nodespace-app")
    .stdin(Stdio::piped())
    .stdout(Stdio::piped())
    .spawn()?;
// Send JSON-RPC requests, read responses

Run with: cargo run --example mcp_test_client

Q3: Error Codes

A: Use both standard JSON-RPC codes AND custom NodeSpace codes:

// src-tauri/src/mcp/types.rs
pub mod error_codes {
    // Standard JSON-RPC errors
    pub const PARSE_ERROR: i32 = -32700;
    pub const INVALID_REQUEST: i32 = -32600;
    pub const METHOD_NOT_FOUND: i32 = -32601;
    pub const INVALID_PARAMS: i32 = -32602;
    pub const INTERNAL_ERROR: i32 = -32603;

    // NodeSpace custom errors (start at -32000 per spec)
    pub const NODE_NOT_FOUND: i32 = -32000;
    pub const INVALID_NODE_TYPE: i32 = -32001;
    pub const INVALID_HIERARCHY: i32 = -32002;
    pub const DUPLICATE_NODE: i32 = -32003;
    pub const DATABASE_ERROR: i32 = -32004;
}

Q4: Capability Advertisement

A: Skip for this issue - focus only on CRUD operations. Capability negotiation (initialize, capabilities methods) can be added in a future issue after basic ops are proven. Claude Code and other MCP clients work fine without formal capability exchange.

Q5: Database/Storage

A: Use actual Turso database (same as dev-server). Connect to ~/.nodespace/database/nodespace-dev.db for development/testing.

let home_dir = dirs::home_dir()?;
let db_path = home_dir
    .join(".nodespace")
    .join("database")
    .join("nodespace-dev.db");  // Use dev DB, not production

let db_service = DatabaseService::new(db_path).await?;
let node_service = Arc::new(NodeService::new(db_service)?);

Do NOT use mock storage - need real persistence for UI reactivity testing and concurrent access validation.

Acceptance Criteria

  • Dual-mode binary (Not needed with single-process)
  • IPC socket setup (Not needed with single-process)
  • Capability advertisement (Deferred to future issue)
  • MCP protocol correctly implemented for stdio transport (async tokio::io)
  • JSON request/response parsing works reliably (JSON-RPC 2.0)
  • All basic node operations exposed as MCP methods
  • NodeService shared between Tauri commands and MCP handlers (Arc)
  • MCP operations emit Tauri events for UI reactivity
  • MCP task spawns during Tauri setup and runs in background
  • Error handling with both standard and custom error codes
  • Test client can execute CRUD operations via stdio
  • UI updates reactively when MCP modifies data

Architecture

Single-process design with MCP as Tokio task:

Tauri App (Single Process)
├─ MCP stdio Task (background)
│  ↓
├─ NodeService (shared Arc<T>) ← Already exists!
│  ↓
├─ Turso Database (~/.nodespace/database/nodespace-dev.db)
│  ↓
└─ Tauri Events → EventBus → Svelte UI (reactive updates)

Reactivity: MCP operations → Tauri events → Existing EventBus → UI updates automatically

File Structure

src-tauri/src/
├─ mcp/
│  ├─ mod.rs              # Public API
│  ├─ types.rs            # Request/response/error types + error codes
│  ├─ server.rs           # stdio server loop
│  └─ handlers/
│     ├─ mod.rs
│     └─ nodes.rs         # Node CRUD handlers (wrap NodeService)
├─ lib.rs                 # Spawn MCP task in setup()
└─ bin/
   └─ dev-server.rs       # Reference for DB/NodeService initialization

examples/
└─ mcp_test_client.rs     # Standalone test client

References

Activity

  1. malibio commented on Oct 12, 2025

    @malibio
    CollaboratorAuthor

    Architecture Update: Integrated MCP Server

    After architectural review, we're changing the approach from dual-mode binary to integrated MCP server inside Tauri app.

    New Architecture

    ┌─────────────────────────────────────────────────────────────┐
    │                    Tauri App Process                        │
    │                                                             │
    │  ┌────────────────────┐         ┌─────────────────────┐   │
    │  │  Frontend (Svelte) │ ←────→  │  Rust Backend       │   │
    │  │                    │   IPC   │                     │   │
    │  │  SharedNodeStore   │         │  Database           │   │
    │  │  (JavaScript)      │         │                     │   │
    │  └────────────────────┘         │  MCP Server (Rust)  │   │
    │           ↑                      │  - TCP: localhost   │   │
    │           │                      │  - stdio: optional  │   │
    │           │                      └─────────────────────┘   │
    │           │                               ↓                 │
    │           └───────── Tauri Events ────────┘                │
    │                    (mcp:node:updated)                       │
    └─────────────────────────────────────────────────────────────┘
                                    ↑
                        External MCP Clients
                        (AI agents via TCP)
    

    Benefits of Integrated Approach

    1. Shared Database Connection - No IPC overhead, atomic transactions
    2. Shared State - PersistenceCoordinator can coordinate both UI and MCP operations
    3. Event Integration - MCP updates emit Tauri events to frontend
    4. Simpler Deployment - One binary, one process, one configuration
    5. Background Service Mode - Can run like OneDrive/Slack (UI optional)
    6. Better Performance - In-process communication <1ms vs 10-50ms IPC

    Implementation Changes

    1. MCP Server as Tauri Plugin

    // src-tauri/src/mcp/mod.rs
    pub struct McpServerPlugin {
        db: Arc<Mutex<Database>>,
        app: tauri::AppHandle,
    }
    
    // Start on app initialization
    impl Plugin for McpServerPlugin {
        fn initialize(app: &AppHandle) -> Result<()> {
            let server = McpServer::new(
                app.state::<Database>().inner().clone(),
                app.clone()
            );
            
            // Run in background thread
            tauri::async_runtime::spawn(async move {
                server.listen_tcp("127.0.0.1:9000").await;
            });
            
            Ok(())
        }
    }

    2. Event Emission to Frontend

    // When MCP updates a node
    pub async fn handle_mcp_update(
        app: &AppHandle,
        db: &Database,
        node: Node
    ) -> Result<(), Error> {
        // 1. Update database
        db.update_node(&node)?;
        
        // 2. Emit to frontend
        app.emit_all("mcp:node:updated", McpUpdatePayload {
            node_id: node.id,
            node: node.clone(),
            server_id: "integrated-mcp",
            timestamp: SystemTime::now(),
        })?;
        
        Ok(())
    }

    3. Frontend Event Listener

    // src/lib/services/mcp-event-listener.ts
    import { listen } from '@tauri-apps/api/event';
    import { sharedNodeStore } from './shared-node-store';
    
    export async function initializeMcpEventListener() {
        await listen('mcp:node:updated', (event) => {
            const { node_id, node, timestamp } = event.payload;
            
            sharedNodeStore.handleExternalUpdate('mcp-server', {
                nodeId: node_id,
                changes: node,
                source: { type: 'mcp-server', serverId: 'integrated-mcp' },
                timestamp
            });
        });
    }

    4. Background Service Mode (Optional)

    // System tray + hide-to-tray behavior
    // Allows MCP server to keep running when UI is closed
    // Like OneDrive, Slack, Discord, etc.

    Updated Acceptance Criteria

    • MCP server runs inside Tauri app process (not separate binary)
    • MCP server starts on app initialization
    • Listens on TCP (localhost:9000) for external AI agents
    • Shares database connection with UI
    • Emits Tauri events when nodes are updated
    • Frontend listens to MCP events and updates SharedNodeStore
    • All node operations exposed as MCP tools
    • Proper error handling and validation
    • (Optional) Background service mode with system tray
    • (Optional) Auto-start on boot configuration

    Dependencies

    Blocks:

    Blocked By:

    Related Documentation

    • docs/architecture/mcp-integration-gaps.md - Analysis of what's needed
    • docs/architecture/persistence-layer.md - How PersistenceCoordinator coordinates MCP + UI

    Estimated Effort

    • Phase 1: Integrated MCP server (3-4 days)
    • Phase 2: Event integration (1 day)
    • Phase 3: Background service mode (1-2 days)

    Total: 5-7 days (after #240 is complete)

  2. self-assigned this
    on Oct 20, 2025
  3. added 4 commits that reference this issue on Oct 20, 2025
    918e23f
    767c0c2
    6fed8fd
    852e7f0
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