Repository navigation
Description
Overview
Expose the existing semantic search functionality to MCP clients like Claude Code. This enables AI agents to search NodeSpace content using natural language queries instead of just basic filtering, completing the AI agent workflow: search → read → understand → modify.
Implementation Q&A (From Agent Questions)
Q1: EmbeddingService Location
A: EmbeddingService already exists in core package! ✅
Location: packages/core/src/services/embedding_service.rs
Name: NodeEmbeddingService (not EmbeddingService)
No refactoring needed - just use the existing service. It's already accessible from core package.
// Already exists in core!
use nodespace_core::services::NodeEmbeddingService;
pub struct NodeEmbeddingService {
nlp_engine: Arc<EmbeddingService>,
db: Arc<DatabaseService>,
}
impl NodeEmbeddingService {
pub async fn search_containers(&self, query: &str, threshold: f32, limit: usize) -> Result<Vec<Node>, NodeServiceError>
pub async fn exact_search_containers(&self, query: &str, threshold: f32, limit: usize) -> Result<Vec<Node>, NodeServiceError>
}Q2: MCP Server Service Pattern
A: Use Option B - Create a combined struct.
Why:
- Cleaner API (single parameter vs multiple)
- Easier to extend (add more services later without changing signature)
- More Rust-idiomatic
Implementation:
// packages/core/src/mcp/server.rs
pub struct McpServices {
pub node_service: Arc<NodeService>,
pub embedding_service: Arc<NodeEmbeddingService>,
}
pub async fn run_mcp_server_with_callback(
services: McpServices, // Single combined struct
callback: Option<ResponseCallback>,
) -> anyhow::Result<()> {
// ...
let response = handle_request(&services, state, request).await;
}
async fn handle_request(
services: &McpServices,
state: &ServerState,
request: MCPRequest,
) -> MCPResponse {
let result = match request.method.as_str() {
"initialize" => { /* ... */ }
"create_node" => nodes::handle_create_node(&services.node_service, request.params).await,
"search_containers" => search::handle_search_containers(&services.embedding_service, request.params).await,
// ...
};
}Q3: Testing Scope
A: Focus on unit tests and manual echo testing. Skip Claude Code integration for now.
What to implement:
- ✅ Unit tests - Comprehensive tests in
search_test.rs(REQUIRED) - ✅ Manual echo testing - Verify it works end-to-end with echo commands (REQUIRED)
- ⏭️ Claude Code integration - Skip for this issue (can be tested after merge)
Rationale:
- Unit tests catch bugs and prevent regressions
- Manual echo testing verifies stdio transport works
- Claude Code integration is end-user testing (can happen after implementation)
Manual echo test command:
# After implementation, run this to verify it works:
echo '{"jsonrpc":"2.0","id":1,"method":"search_containers","params":{"query":"test query"}}' | cargo run --bin nodespace-appQ4: Exact vs Approximate Search Methods
A: Both methods already exist! ✅
Location: packages/core/src/services/embedding_service.rs:228 and :294
// Already implemented in NodeEmbeddingService:
pub async fn search_containers(&self, query: &str, threshold: f32, limit: usize) -> Result<Vec<Node>, NodeServiceError>
pub async fn exact_search_containers(&self, query: &str, threshold: f32, limit: usize) -> Result<Vec<Node>, NodeServiceError>Just use them - no need to implement anything! Your MCP handler just wraps these existing methods.
Q5: Event Emission / Analytics
A: SKIP the analytics tracking entirely.
Why:
- We already decided to remove analytics from unimplemented issues (this conversation)
- Existing MCP server logging is sufficient
- Read-only operations don't need special tracking
- Adds no value for junior engineer implementing this
What to do:
- ❌ Do NOT add the analytics section from the issue
- ✅ Search operations don't need event emissions (they're read-only)
- ✅ Existing debug logs are sufficient:
debug!("📥 MCP request: {}", line); debug!("📤 MCP response for method '{}'", method);
Background
Current State
Semantic search EXISTS but is NOT accessible via MCP:
// ✅ Available to UI (Tauri command)
// packages/desktop-app/src-tauri/src/commands/embeddings.rs
#[tauri::command]
pub async fn search_containers(
state: State<'_, EmbeddingState>,
params: SearchContainersParams,
) -> Result<Vec<Node>, CommandError> {
state.service.search_containers(¶ms.query, threshold, limit).await
}
// ✅ Service exists in core!
// packages/core/src/services/embedding_service.rs
impl NodeEmbeddingService {
pub async fn search_containers(...) -> Result<Vec<Node>, NodeServiceError>
pub async fn exact_search_containers(...) -> Result<Vec<Node>, NodeServiceError>
}
// ❌ NOT exposed via MCP
// AI agents like Claude Code cannot use semantic searchThe Problem
AI agents currently must use basic filtering:
// Current approach (limited)
query_nodes({
node_type: "text",
container_node_id: "some-known-id" // Must know ID in advance!
})
// Desired approach (intelligent)
search_containers("Q4 planning tasks") // ❌ Doesn't exist in MCP yet
// → Returns: [container-abc, container-def, container-ghi]Without semantic search, AI agents cannot:
- Find relevant content using natural language
- Discover containers they don't know the ID of
- Use the powerful embedding-based search NodeSpace already has
The Opportunity
Complete the AI agent workflow we designed in Issues #308, #309, #310:
// 1. SEARCH (this issue) - Find relevant containers
containers = search_containers("Q4 planning tasks")
// 2. READ (Issue #309) - Get content as markdown
markdown = get_markdown_from_node_id(containers[0])
// 3. UNDERSTAND - AI analyzes markdown
// 4. MODIFY (Issue #310) - Update nodes
update_nodes_batch([...])Implementation Tasks
1. Create MCP Search Handler
File: packages/core/src/mcp/handlers/search.rs (NEW)
//! MCP Search Handlers
//!
//! Semantic search operations for AI agent access.
//! Pure business logic - no Tauri dependencies.
use crate::mcp::types::MCPError;
use crate::services::NodeEmbeddingService;
use serde::Deserialize;
use serde_json::{json, Value};
use std::sync::Arc;
/// Parameters for search_containers method
#[derive(Debug, Deserialize)]
pub struct SearchContainersParams {
/// Natural language search query
pub query: String,
/// Similarity threshold (0.0-1.0, lower = more similar)
/// Default: 0.7
#[serde(default)]
pub threshold: Option<f32>,
/// Maximum number of results
/// Default: 20
#[serde(default)]
pub limit: Option<usize>,
/// Use exact search instead of approximate (slower but more accurate)
/// Default: false (use DiskANN approximate search)
#[serde(default)]
pub exact: Option<bool>,
}
/// Search containers by semantic similarity
///
/// Uses vector embeddings to find containers whose content is semantically
/// similar to the query. This enables AI agents to discover relevant content
/// using natural language instead of knowing exact IDs.
///
/// # Example
///
/// ```rust,no_run
/// let params = json!({
/// "query": "Q4 planning and budget",
/// "threshold": 0.7,
/// "limit": 10
/// });
/// let result = handle_search_containers(&embedding_service, params).await?;
/// // Returns top 10 most relevant containers
/// ```
pub async fn handle_search_containers(
service: &Arc<NodeEmbeddingService>,
params: Value,
) -> Result<Value, MCPError> {
// Parse parameters
let params: SearchContainersParams = serde_json::from_value(params)
.map_err(|e| MCPError::invalid_params(format!("Invalid parameters: {}", e)))?;
// Apply defaults
let threshold = params.threshold.unwrap_or(0.7);
let limit = params.limit.unwrap_or(20);
let exact = params.exact.unwrap_or(false);
// Validate parameters
if threshold < 0.0 || threshold > 1.0 {
return Err(MCPError::invalid_params(
"threshold must be between 0.0 and 1.0".to_string(),
));
}
if params.query.is_empty() {
return Err(MCPError::invalid_params(
"query cannot be empty".to_string(),
));
}
// Execute search using existing NodeEmbeddingService methods
let results = if exact {
service
.exact_search_containers(¶ms.query, threshold, limit)
.await
} else {
service
.search_containers(¶ms.query, threshold, limit)
.await
};
let nodes = results.map_err(|e| {
MCPError::internal_error(format!("Search failed: {}", e))
})?;
// Return results with metadata
Ok(json!({
"nodes": nodes,
"count": nodes.len(),
"query": params.query,
"threshold": threshold,
"exact": exact
}))
}2. Register Handler in MCP Server
File: packages/core/src/mcp/handlers/mod.rs
Add search module:
pub mod initialize;
pub mod markdown;
pub mod nodes;
pub mod search; // NEWFile: packages/core/src/mcp/server.rs
Update to use combined services struct:
/// Combined services for MCP handlers
pub struct McpServices {
pub node_service: Arc<NodeService>,
pub embedding_service: Arc<NodeEmbeddingService>,
}
pub async fn run_mcp_server_with_callback(
services: McpServices, // Combined services struct
callback: Option<ResponseCallback>,
) -> anyhow::Result<()> {
// ...
let response = handle_request(&services, &state, request).await;
}
async fn handle_request(
services: &McpServices,
state: &ServerState,
request: MCPRequest,
) -> MCPResponse {
let result = match request.method.as_str() {
"initialize" => initialize::handle_initialize(request.params).await,
"create_node" => nodes::handle_create_node(&services.node_service, request.params).await,
// NEW: Search operations
"search_containers" => {
search::handle_search_containers(&services.embedding_service, request.params).await
}
_ => Err(MCPError::method_not_found(&request.method)),
};
// ...
}3. Update Initialize Schema
File: packages/core/src/mcp/handlers/initialize.rs
Add to get_tool_schemas():
{
"name": "search_containers",
"description": "Search containers using natural language semantic similarity (vector embeddings)",
"inputSchema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Natural language search query (e.g., 'Q4 planning tasks')"
},
"threshold": {
"type": "number",
"description": "Similarity threshold 0.0-1.0, lower = more similar (default: 0.7)",
"minimum": 0.0,
"maximum": 1.0,
"default": 0.7
},
"limit": {
"type": "number",
"description": "Maximum number of results (default: 20)",
"default": 20
},
"exact": {
"type": "boolean",
"description": "Use exact cosine distance instead of approximate DiskANN (default: false)",
"default": false
}
},
"required": ["query"]
}
}4. Update Tauri Layer
File: packages/desktop-app/src-tauri/src/lib.rs
Update MCP server initialization to use McpServices struct:
pub fn run() {
tauri::Builder::default()
.setup(|app| {
// Initialize services
let node_service = Arc::new(NodeService::new(db_service.clone())?);
let embedding_service = Arc::new(NodeEmbeddingService::new(nlp_engine, db_service));
app.manage(node_service.clone());
app.manage(embedding_service.clone());
// Create combined services struct for MCP
let mcp_services = nodespace_core::mcp::server::McpServices {
node_service,
embedding_service,
};
// Spawn MCP stdio task
let app_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
if let Err(e) = mcp_integration::run_mcp_server_with_events(
mcp_services, // Pass combined struct
app_handle
).await {
eprintln!("MCP server error: {}", e);
}
});
Ok(())
})
// ...
}File: packages/desktop-app/src-tauri/src/mcp_integration.rs
Update wrapper signature:
pub async fn run_mcp_server_with_events(
services: nodespace_core::mcp::server::McpServices, // Updated signature
app: AppHandle,
) -> anyhow::Result<()> {
let callback = Arc::new(move |method: &str, result: &Value| {
emit_event_for_method(&app, method, result);
});
mcp::run_mcp_server_with_callback(services, Some(callback)).await
}
// NO analytics tracking needed - remove from issue
fn emit_event_for_method(app: &AppHandle, method: &str, result: &Value) {
match method {
"create_node" => { /* existing */ }
"update_node" => { /* existing */ }
"delete_node" => { /* existing */ }
// search_containers doesn't need events (read-only)
_ => {}
}
}5. Add Tests
File: packages/core/src/mcp/handlers/search_test.rs (NEW)
#[cfg(test)]
mod search_tests {
use super::*;
use serde_json::json;
#[tokio::test]
async fn test_search_containers_basic() {
let service = setup_test_embedding_service().await;
let params = json!({
"query": "machine learning"
});
let result = handle_search_containers(&service, params).await.unwrap();
assert!(result["nodes"].is_array());
assert!(result["count"].as_u64().unwrap() <= 20); // Default limit
assert_eq!(result["query"], "machine learning");
assert_eq!(result["threshold"], 0.7); // Default
assert_eq!(result["exact"], false); // Default
}
#[tokio::test]
async fn test_search_containers_custom_params() {
let service = setup_test_embedding_service().await;
let params = json!({
"query": "project planning",
"threshold": 0.6,
"limit": 5,
"exact": true
});
let result = handle_search_containers(&service, params).await.unwrap();
let nodes = result["nodes"].as_array().unwrap();
assert!(nodes.len() <= 5); // Respects limit
assert_eq!(result["exact"], true);
assert_eq!(result["threshold"], 0.6);
}
#[tokio::test]
async fn test_search_containers_invalid_threshold_high() {
let service = setup_test_embedding_service().await;
let params = json!({
"query": "test",
"threshold": 1.5 // Invalid: > 1.0
});
let result = handle_search_containers(&service, params).await;
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.code, crate::mcp::types::INVALID_PARAMS);
assert!(err.message.contains("0.0 and 1.0"));
}
#[tokio::test]
async fn test_search_containers_invalid_threshold_low() {
let service = setup_test_embedding_service().await;
let params = json!({
"query": "test",
"threshold": -0.1 // Invalid: < 0.0
});
let result = handle_search_containers(&service, params).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_search_containers_empty_query() {
let service = setup_test_embedding_service().await;
let params = json!({
"query": ""
});
let result = handle_search_containers(&service, params).await;
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.message.contains("empty"));
}
#[tokio::test]
async fn test_search_containers_defaults() {
let service = setup_test_embedding_service().await;
// Only provide query, use all defaults
let params = json!({
"query": "test query"
});
let result = handle_search_containers(&service, params).await.unwrap();
// Verify defaults were applied
assert_eq!(result["threshold"], 0.7);
assert_eq!(result["exact"], false);
assert!(result["nodes"].as_array().unwrap().len() <= 20);
}
}Implementation Summary
What you need to implement:
- Create
search.rshandler (wraps existingNodeEmbeddingServicemethods) - Add
McpServicesstruct toserver.rs - Update
handle_requestto use combined services - Add search schema to
initialize.rs - Update Tauri layer to pass both services
- Write comprehensive unit tests
What already exists:
- ✅
NodeEmbeddingServicein core package - ✅
search_containers()method - ✅
exact_search_containers()method - ✅ Vector embeddings and DiskANN search
What to skip:
- ⏭️ EmbeddingService refactoring (already in core!)
- ⏭️ Implementing search methods (already exist!)
- ⏭️ Analytics/event tracking (unnecessary)
- ⏭️ Claude Code integration testing (can happen after merge)
Use Case Examples
Example 1: AI Finding Relevant Content
// User: "Find my notes about Q4 planning and mark completed tasks as done"
// AI workflow:
// 1. Search for relevant containers
containers = search_containers({
query: "Q4 planning tasks budget",
limit: 5
})
// 2. Read top result
markdown = get_markdown_from_node_id(containers[0].id)
// 3. Parse and identify completed tasks
// ... AI analysis ...
// 4. Update tasks
update_nodes_batch([
{ id: "task-1", content: "- [x] Finalize budget" },
{ id: "task-2", content: "- [x] Review proposals" }
])Example 2: Cross-Container Discovery
// User: "Summarize all my machine learning notes"
// AI workflow:
containers = search_containers({
query: "machine learning deep learning neural networks",
threshold: 0.65, // Cast wider net
limit: 10
})
for (const container of containers) {
const markdown = get_markdown_from_node_id(container.id)
// AI builds summary from all relevant containers
}Testing Strategy
Priority 1: Unit Tests (REQUIRED)
Write comprehensive tests in search_test.rs:
- ✅ Valid search with defaults
- ✅ Custom threshold, limit, exact parameters
- ✅ Invalid threshold (< 0 or > 1)
- ✅ Empty query string
- ✅ Defaults are applied correctly
Priority 2: Manual Echo Testing (REQUIRED)
# After implementation, verify stdio works:
echo '{"jsonrpc":"2.0","id":1,"method":"search_containers","params":{"query":"machine learning","limit":5}}' | cargo run --bin nodespace-app
# Expected response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"nodes": [...],
"count": 5,
"query": "machine learning",
"threshold": 0.7,
"exact": false
}
}Priority 3: Claude Code Integration (SKIP for this issue)
Can be tested after merge by end users.
Acceptance Criteria
-
search_containersMCP handler implemented inpackages/core/src/mcp/handlers/search.rs -
McpServicesstruct added topackages/core/src/mcp/server.rs -
run_mcp_server_with_callbacksignature updated to acceptMcpServices - Handler registered in MCP server dispatcher
- Method added to initialize capabilities schema
- Supports parameters: query, threshold, limit, exact
- Returns nodes sorted by semantic similarity
- Parameter validation (threshold 0-1, non-empty query)
- Comprehensive unit tests (6+ test cases)
- Manual echo testing passes
- Tauri layer updated to create and pass
McpServices - Documentation updated with search examples
References
- Existing Service:
packages/core/src/services/embedding_service.rs:228(NodeEmbeddingService) - Existing Methods:
search_containers()andexact_search_containers()(already implemented!) - Tauri Command:
packages/desktop-app/src-tauri/src/commands/embeddings.rs:113(reference for parameters) - Related Issue: Add get_markdown_from_node_id MCP method for exporting nodes to markdown #309 (get_markdown_from_node_id - completes the search → read → modify workflow)
- Related Issue: Add batch node operations and bulk container update MCP methods #310 (batch operations - enables efficient bulk updates after search)
- Related Issue: Implement MCP initialization handshake and capability discovery #308 (MCP initialization - capability discovery)
- Architecture:
/docs/architecture/business-logic/mcp-integration.md
Future Enhancements (Not in This Issue)
- Search by node type (find all task nodes matching query)
- Hybrid search (combine semantic + keyword filters)
- Search within specific containers
- Rerank results by recency or other factors
- Search result explanations (show why results matched)
Activity
feat: Expose semantic search via MCP (search_containers method) (#321)
refactor: Address code review feedback for search handler (#321)
Expose semantic search via MCP (search_containers method) (#322)
Expose semantic search via MCP (search_containers method) (#322)
Expose semantic search via MCP (search_containers method) (#322)
Expose semantic search via MCP (search_containers method) (#322)