Skip to content

Implement MCP semantic_search tool with Claude Code compatibility #574

Closed

Description

@malibio

Context and Motivation

Now that NodeSpace has an embeddings system (Issue #573), we need to expose semantic search functionality to AI agents like Claude Code via the MCP (Model Context Protocol). This enables:

  1. AI-powered discovery: Claude Code can find relevant nodes by meaning, not just keywords
  2. Contextual assistance: Agents can understand project context by searching semantically
  3. MCP standard compliance: Follows official MCP tool specification for interoperability
  4. HTTP server integration: Works with existing MCP HTTP server on port 3100

This issue implements the MCP semantic search tool that uses the embeddings backend from Issue #573.


Self-Contained Scope

What this issue includes:

  • ✅ New semantic_search MCP tool in Rust backend
  • ✅ Tool registration in existing MCP handlers (tools/list, tools/call)
  • ✅ Cosine similarity search over embeddings
  • ✅ Configurable result limit (default 10, max 50)
  • ✅ Similarity threshold filtering (default 0.7)
  • ✅ Return node metadata (id, type, content snippet, similarity score)
  • ✅ Integration with existing HTTP MCP server (port 3100)
  • ✅ Claude Code compatibility verification

What this issue excludes:


Implementation Approach

1. MCP Tool Definition

Add to MCP tools registry (packages/desktop-app/src-tauri/src/mcp/tools.rs):

```rust
use serde::{Deserialize, Serialize};
use serde_json::json;

#[derive(Debug, Serialize, Deserialize)]
pub struct SemanticSearchArgs {
/// Search query text
pub query: String,

/// Maximum number of results (default: 10, max: 50)
#[serde(default = "default_limit")]
pub limit: usize,

/// Minimum similarity threshold (default: 0.7, range: 0.0-1.0)
#[serde(default = "default_threshold")]
pub threshold: f32,

}

fn default_limit() -> usize { 10 }
fn default_threshold() -> f32 { 0.7 }

#[derive(Debug, Serialize)]
pub struct SemanticSearchResult {
/// Node ID
pub id: String,

/// Node type (text, header, task, date)
pub node_type: String,

/// Content snippet (truncated to 200 chars)
pub snippet: String,

/// Cosine similarity score (0.0-1.0)
pub similarity: f32,

}

pub fn get_tool_definitions() -> Vec<serde_json::Value> {
vec![
// ... existing tools ...

    json!({
        "name": "semantic_search",
        "description": "Search nodes by semantic meaning using embeddings. Returns nodes ranked by similarity to the query.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query text (e.g., 'project planning notes', 'API design decisions')"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of results to return (default: 10, max: 50)",
                    "minimum": 1,
                    "maximum": 50,
                    "default": 10
                },
                "threshold": {
                    "type": "number",
                    "description": "Minimum similarity threshold, 0.0 (no match) to 1.0 (exact match). Default: 0.7",
                    "minimum": 0.0,
                    "maximum": 1.0,
                    "default": 0.7
                }
            },
            "required": ["query"]
        }
    }),
]

}
```

Why these parameters?

  • query: User's natural language search
  • limit: Prevent overwhelming results, performance guardrail
  • threshold: Filter out weak matches (0.7 = moderately similar)

2. Cosine Similarity Search

Add to EmbeddingsService (packages/desktop-app/src-tauri/src/services/embeddings_service.rs):

```rust
impl EmbeddingsService {
/// Compute cosine similarity between two vectors
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
let dot_product: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
let norm_a: f32 = a.iter().map(|x| x * x).sum::().sqrt();
let norm_b: f32 = b.iter().map(|x| x * x).sum::().sqrt();

    if norm_a == 0.0 || norm_b == 0.0 {
        return 0.0;
    }
    
    dot_product / (norm_a * norm_b)
}

/// Search for nodes semantically similar to query
pub async fn search(
    &self,
    db: &Database,
    node_service: &NodeService,
    query: &str,
    limit: usize,
    threshold: f32,
) -> Result<Vec<(Node, f32)>> {
    // 1. Generate query embedding
    let query_vector = self.embed(query).await?;
    
    // 2. Get all embeddings from database
    let embeddings: Vec<(String, Vec<f32>)> = db.query(
        "SELECT node_id, embedding_vector FROM embeddings WHERE model_name = ?1",
        params![&self.model_name],
    ).await?
    .into_iter()
    .map(|(node_id, bytes): (String, Vec<u8>)| {
        let vector = bytes.chunks_exact(4)
            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
            .collect();
        (node_id, vector)
    })
    .collect();
    
    // 3. Compute similarities
    let mut scored_nodes = Vec::new();
    for (node_id, embedding) in embeddings {
        let similarity = Self::cosine_similarity(&query_vector, &embedding);
        
        if similarity >= threshold {
            if let Ok(node) = node_service.get_node(&node_id).await {
                scored_nodes.push((node, similarity));
            }
        }
    }
    
    // 4. Sort by similarity (descending) and limit
    scored_nodes.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
    scored_nodes.truncate(limit);
    
    Ok(scored_nodes)
}

}
```

Why cosine similarity?

  • Standard metric for comparing embeddings
  • Range 0.0-1.0 is intuitive (0 = unrelated, 1 = identical)
  • Fast to compute, works well for high-dimensional vectors

3. MCP Tool Handler

Implement tool handler (packages/desktop-app/src-tauri/src/mcp/handlers.rs):

```rust
pub async fn handle_tool_call(
tool_name: &str,
arguments: serde_json::Value,
embeddings_service: &EmbeddingsService,
node_service: &NodeService,
db: &Database,
) -> Result<serde_json::Value> {
match tool_name {
// ... existing tools ...

    "semantic_search" => {
        let args: SemanticSearchArgs = serde_json::from_value(arguments)?;
        
        // Validate parameters
        let limit = args.limit.min(50); // Hard cap at 50
        let threshold = args.threshold.clamp(0.0, 1.0);
        
        // Execute search
        let results = embeddings_service.search(
            db,
            node_service,
            &args.query,
            limit,
            threshold,
        ).await?;
        
        // Format results
        let formatted_results: Vec<SemanticSearchResult> = results
            .into_iter()
            .map(|(node, similarity)| {
                let snippet = node.content
                    .chars()
                    .take(200)
                    .collect::<String>();
                
                SemanticSearchResult {
                    id: node.id,
                    node_type: node.node_type,
                    snippet,
                    similarity,
                }
            })
            .collect();
        
        Ok(json!({
            "content": [{
                "type": "text",
                "text": serde_json::to_string_pretty(&formatted_results)?
            }]
        }))
    }
    
    _ => Err(anyhow!("Unknown tool: {}", tool_name)),
}

}
```

MCP response format:
```json
{
"content": [
{
"type": "text",
"text": "[
{
"id": "abc123",
"node_type": "text",
"snippet": "Project planning notes for Q1...",
"similarity": 0.89
},
{
"id": "def456",
"node_type": "header",
"snippet": "API Design Decisions",
"similarity": 0.82
}
]"
}
]
}
```


4. Register Tool in MCP Server

Update tools/list handler (packages/desktop-app/src-tauri/src/mcp/server.rs):

```rust
async fn handle_tools_list() -> Result {
let tools = get_tool_definitions(); // Includes semantic_search

Ok(Response {
    jsonrpc: "2.0".to_string(),
    id: None,
    result: Some(json!({
        "tools": tools
    })),
    error: None,
})

}
```

Update tools/call handler:

```rust
async fn handle_tools_call(
params: serde_json::Value,
app_state: Arc,
) -> Result {
let tool_name = params["name"].as_str().ok_or_else(|| anyhow!("Missing tool name"))?;
let arguments = params["arguments"].clone();

let result = handle_tool_call(
    tool_name,
    arguments,
    &app_state.embeddings_service,
    &app_state.node_service,
    &app_state.db,
).await?;

Ok(Response {
    jsonrpc: "2.0".to_string(),
    id: None,
    result: Some(result),
    error: None,
})

}
```


5. Claude Code Integration Example

How Claude Code will use this tool:

```typescript
// Claude Code MCP client configuration
{
"mcpServers": {
"nodespace": {
"url": "http://localhost:3100/mcp",
"transport": "http"
}
}
}
```

Example Claude Code usage:

```
User: "Find my notes about API design decisions"

Claude Code:
{
"query": "API design decisions",
"limit": 10,
"threshold": 0.7
}

NodeSpace MCP Server:
[
{
"id": "abc123",
"node_type": "header",
"snippet": "API Design Decisions\n\nWe decided to use REST for the initial implementation...",
"similarity": 0.91
},
{
"id": "def456",
"node_type": "text",
"snippet": "Considered GraphQL but chose REST for simplicity...",
"similarity": 0.84
}
]

Claude Code: "I found your API design notes. Here are the top matches:\n\n1. API Design Decisions (91% match): 'We decided to use REST for the initial implementation...'\n2. REST vs GraphQL (84% match): 'Considered GraphQL but chose REST for simplicity...'\n\nWould you like me to open any of these nodes?"
```


Acceptance Criteria

  • semantic_search tool defined in MCP tools registry with correct schema
  • SemanticSearchArgs and SemanticSearchResult types implemented
  • EmbeddingsService::search() method implemented with cosine similarity
  • Search filters by similarity threshold (default 0.7)
  • Search limits results (default 10, max 50)
  • Search returns nodes ranked by similarity (descending)
  • MCP tool handler processes semantic_search requests
  • Tool returns proper MCP response format (content array with text)
  • Tool registered in tools/list handler
  • Tool callable via tools/call handler
  • HTTP MCP server exposes tool on port 3100
  • Unit tests for cosine similarity calculation
  • Integration tests for end-to-end search flow
  • Manual verification with Claude Code client

Technical Implementation Notes

Dependencies to Add

No new dependencies required - uses existing:

Files to Create/Modify

Modify:

  • packages/desktop-app/src-tauri/src/mcp/tools.rs - Add tool definition
  • packages/desktop-app/src-tauri/src/mcp/handlers.rs - Add tool handler
  • packages/desktop-app/src-tauri/src/services/embeddings_service.rs - Add search method
  • packages/desktop-app/src-tauri/src/mcp/server.rs - Ensure tool registration

No new files needed - integrates with existing MCP infrastructure.

Testing Strategy

Unit Tests:

  • Cosine similarity calculation (edge cases: zero vectors, identical vectors, orthogonal vectors)
  • Parameter validation (limit clamping, threshold clamping)
  • Result formatting (snippet truncation, JSON serialization)

Integration Tests:

  • End-to-end search with real embeddings
  • Search with different thresholds (verify filtering)
  • Search with different limits (verify truncation)
  • Empty results (no matches above threshold)
  • MCP request/response format compliance

Manual Testing:

  • Configure Claude Code to connect to NodeSpace MCP server
  • Execute semantic searches from Claude Code
  • Verify results match expectations
  • Test edge cases (empty database, no embeddings, malformed queries)

Common Pitfalls to Avoid

  1. Don't load all embeddings into memory at once - Use streaming if database grows large (future optimization)
  2. Don't forget to validate parameters - Clamp limit and threshold to safe ranges
  3. Don't return full node content - Use snippets to avoid overwhelming responses
  4. Don't hardcode model name - Use service's current model
  5. Don't forget MCP response format - Must wrap in content array with type: "text"

Claude Code Compatibility Notes

MCP HTTP Transport:

  • NodeSpace already has HTTP MCP server on port 3100
  • Claude Code connects via HTTP transport (no stdio needed)
  • Tool must follow MCP 1.0 specification exactly

Response Format:
```json
{
"content": [
{
"type": "text",
"text": ""
}
]
}
```

Error Handling:

  • Return MCP error responses for failures
  • Include helpful error messages for debugging
  • Log errors server-side for diagnostics

Dependencies


Related Issues


Future Enhancements (Not in This Issue)

  • Filter by node type (e.g., only search text nodes)
  • Filter by date range (e.g., nodes created in last week)
  • Highlight matching sections in snippet
  • Support multiple embedding models (user-selectable)
  • Hybrid search (semantic + keyword)
  • Custom search UI in NodeSpace frontend

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions