Skip to content

Commit a573922

Browse files
committed
feat(mcp): complete migration to native RMCP implementation
- Replace custom MCP implementation with official RMCP SDK - Implement native RMCP server using toolbox pattern with #[tool_router] and #[tool_handler] - Add 3 core analysis tools: repository_stats, content_stats, analyze_complexity - Support both stdio and SSE transport protocols following mcp-containerd patterns - Fix all compilation errors and achieve clean build with zero warnings - Remove legacy bridge approach eliminating technical debt - Update main.rs and lib.rs for native RMCP integration - Update example to use native RMCP server implementation - Clean up unused imports and resolve type mismatches Architecture: Native RMCP SDK with automatic tool registration Tools: Basic analysis foundation ready for expansion Transport: stdio (default) and SSE server support Status: All tools compile and run successfully closes rmcp_migration_1, closes rmcp_migration_2, closes rmcp_migration_3, closes rmcp_migration_4, closes rmcp_migration_5, closes rmcp_migration_6, closes rmcp_migration_7, closes rmcp_migration_8, closes rmcp_migration_9, closes rmcp_migration_10, closes rmcp_migration_cleanup
1 parent d1a28a1 commit a573922

File tree

13 files changed

+414
-4102
lines changed

13 files changed

+414
-4102
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,5 @@ criterion/
3333
generated/
3434

3535
#Cursor Workspace
36-
cursor_workspace/
36+
cursor_workspace/
37+
external_repos/

crates/codeprism-mcp/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ clap = { workspace = true, features = ["derive"] }
2222
serde = { workspace = true, features = ["derive"] }
2323
serde_json = { workspace = true }
2424

25-
# Official RMCP SDK for migration
26-
rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", branch = "main", features = ["server", "transport-async-rw", "transport-io"] }
25+
# Official RMCP SDK for native implementation
26+
rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", branch = "main", features = ["server", "transport-async-rw", "transport-io", "transport-sse-server", "macros", "schemars"] }
2727

2828
# Regex for pattern matching
2929
regex = "1.0"
Lines changed: 28 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,41 @@
1-
//! Minimal RMCP Server Example
1+
//! Native RMCP Server Example
22
//!
3-
//! This demonstrates the RMCP SDK integration with stdio transport
4-
//! and the CodePrism tool bridge for Phase 1 of the migration.
3+
//! This demonstrates the native RMCP SDK implementation with CodePrism tools.
4+
//! Shows how to use the official RMCP server with stdio transport.
55
66
use anyhow::Result;
7-
use codeprism_mcp::{CodePrismMcpServer, CodePrismRmcpBridge};
8-
use serde_json::Value;
9-
use std::sync::Arc;
10-
use tokio::sync::RwLock;
7+
use codeprism_mcp::server::CodePrismRmcpServer;
8+
use rmcp::ServiceExt;
119
use tracing_subscriber::fmt::init;
1210

1311
#[tokio::main]
1412
async fn main() -> Result<()> {
1513
// Initialize tracing
1614
init();
1715

18-
println!("🚀 Starting minimal RMCP server example...");
19-
20-
// Create CodePrism MCP server instance
21-
let codeprism_server = CodePrismMcpServer::new()?;
22-
let server_arc = Arc::new(RwLock::new(codeprism_server));
23-
24-
// Create RMCP bridge
25-
let bridge = CodePrismRmcpBridge::new(server_arc.clone());
26-
27-
println!("📋 Available tools through RMCP bridge:");
28-
for tool in bridge.get_available_tools() {
29-
println!(" - {}", tool);
30-
}
31-
32-
// Test a simple tool call through the bridge
33-
println!("\n🔧 Testing repository_stats tool...");
34-
match bridge.call_tool("repository_stats", Value::Null).await {
35-
Ok(result) => {
36-
println!("✅ Tool call successful!");
37-
println!("📊 Result: {}", serde_json::to_string_pretty(&result)?);
38-
}
39-
Err(e) => {
40-
println!("⚠️ Tool call failed: {}", e);
41-
println!("ℹ️ This is expected if no repository is loaded");
42-
}
43-
}
44-
45-
// FUTURE(Phase2): Integrate with actual RMCP SDK Server when available
46-
// This foundation is ready for Phase 2 custom code elimination
47-
println!("\n📝 Next steps:");
48-
println!(" 1. ✅ RMCP dependency added");
49-
println!(" 2. ✅ Tool adapter bridge created");
50-
println!(" 3. ⏳ Integrate with RMCP Server (Phase 2)");
51-
println!(" 4. ⏳ Test stdio transport through RMCP");
52-
println!(" 5. ⏳ Performance benchmark comparison");
53-
54-
println!("\n🎯 Phase 1 foundation ready for RMCP Server integration!");
16+
println!("🚀 Starting native RMCP server example...");
17+
18+
// Create native RMCP server instance
19+
let mut server = CodePrismRmcpServer::new()?;
20+
21+
// Initialize with current directory as repository
22+
let current_dir = std::env::current_dir()?;
23+
server.initialize_with_repository(&current_dir).await?;
24+
25+
println!("📋 Native RMCP server created with tools:");
26+
println!(" - repository_stats: Get comprehensive repository statistics");
27+
println!(" - content_stats: Get detailed content statistics");
28+
println!(" - analyze_complexity: Analyze code complexity metrics");
29+
30+
println!("\n🔧 Starting server with stdio transport...");
31+
println!("ℹ️ Use Ctrl+C to stop the server");
32+
33+
// Start the server with stdio transport (like the main binary)
34+
let service = server
35+
.serve((tokio::io::stdin(), tokio::io::stdout()))
36+
.await?;
37+
38+
service.waiting().await?;
5539

5640
Ok(())
5741
}

crates/codeprism-mcp/src/error_handler.rs

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,51 @@
33
//! This module provides centralized error handling, recovery mechanisms,
44
//! and integration with observability systems for production reliability.
55
6-
use crate::protocol::{JsonRpcError, JsonRpcResponse};
6+
use anyhow::Result;
77
use codeprism_core::{
88
resilience::CircuitBreakerConfig, CircuitState, Error as CoreError, ErrorContext,
99
ErrorSeverity, HealthMonitor, MetricsCollector, PerformanceMonitor, RecoveryStrategy,
1010
ResilienceManager, RetryConfig,
1111
};
12+
use serde::{Deserialize, Serialize};
13+
use serde_json;
14+
use serde_json::Value;
1215
use std::sync::Arc;
1316
use tokio::sync::RwLock;
1417
use tracing::{debug, error, info, warn};
1518

19+
/// Local JSON-RPC Error structure
20+
#[derive(Debug, Clone, Serialize, Deserialize)]
21+
pub struct JsonRpcError {
22+
pub code: i32,
23+
pub message: String,
24+
#[serde(skip_serializing_if = "Option::is_none")]
25+
pub data: Option<Value>,
26+
}
27+
28+
impl JsonRpcError {
29+
pub const INVALID_REQUEST: i32 = -32600;
30+
31+
pub fn new(code: i32, message: String, data: Option<Value>) -> Self {
32+
Self {
33+
code,
34+
message,
35+
data,
36+
}
37+
}
38+
}
39+
40+
/// Local JSON-RPC Response structure
41+
#[derive(Debug, Clone, Serialize, Deserialize)]
42+
pub struct JsonRpcResponse {
43+
pub jsonrpc: String,
44+
pub id: Value,
45+
#[serde(skip_serializing_if = "Option::is_none")]
46+
pub result: Option<Value>,
47+
#[serde(skip_serializing_if = "Option::is_none")]
48+
pub error: Option<JsonRpcError>,
49+
}
50+
1651
/// Enhanced error type for MCP operations
1752
#[derive(Debug, Clone, thiserror::Error)]
1853
pub enum McpError {

crates/codeprism-mcp/src/lib.rs

Lines changed: 34 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
//! # CodePrism MCP Server
1+
//! # CodePrism Native RMCP MCP Server
22
//!
3-
//! A Model Context Protocol (MCP) compliant server that provides access to code repositories
4-
//! through standardized Resources, Tools, and Prompts.
3+
//! A native RMCP (Rust Model Context Protocol) server that provides advanced code analysis
4+
//! and repository exploration tools using the official MCP Rust SDK.
55
//!
6-
//! This implementation follows the MCP specification for JSON-RPC 2.0 communication
7-
//! over stdio transport, enabling integration with MCP clients like Claude Desktop,
8-
//! Cursor, and other AI applications.
6+
//! This implementation leverages the official RMCP SDK with the toolbox pattern for
7+
//! automatic tool registration and comprehensive schema documentation. All CodePrism
8+
//! tools are implemented as native RMCP tools with rich type information for optimal
9+
//! AI understanding and integration.
910
1011
use anyhow::Result;
1112

@@ -17,41 +18,35 @@ use codeprism_core::{
1718
repository::RepositoryManager,
1819
scanner::RepositoryScanner,
1920
};
20-
use std::collections::HashMap;
21+
use rmcp::model::ServerCapabilities;
22+
use std::collections::BTreeMap;
2123
use std::path::Path;
2224
use std::sync::Arc;
2325

24-
pub mod config; // Phase 2.2: Advanced configuration system
26+
// Native RMCP server implementation
27+
pub mod server;
28+
29+
// Core components and utilities
30+
pub mod config;
2531
pub mod context;
2632
pub mod error_handler;
27-
pub mod monitoring; // Phase 2.2: Performance monitoring system
33+
pub mod monitoring;
2834
pub mod prompts;
29-
pub mod protocol;
30-
pub mod protocol_rmcp; // RMCP-based protocol implementation
3135
pub mod resources;
32-
pub mod rmcp_bridge; // RMCP bridge for migration
33-
pub mod server;
34-
pub mod server_rmcp; // RMCP-based server implementation
3536
pub mod tools;
37+
pub mod validation;
38+
39+
// Legacy modules (kept for transition)
3640
pub mod tools_legacy;
37-
pub mod transport;
38-
pub mod transport_rmcp; // RMCP-based transport implementation
39-
pub mod validation; // Phase 2.2: Configuration validation & health checks
4041

41-
// Re-export main types
42-
pub use error_handler::{McpError, McpErrorHandler, McpResult};
43-
pub use protocol::{
44-
InitializeParams, InitializeResult, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse,
45-
ServerCapabilities,
46-
};
47-
pub use rmcp_bridge::CodePrismRmcpBridge; // Re-export RMCP bridge
48-
pub use server::McpServer;
49-
pub use transport::{StdioTransport, Transport};
42+
// Re-export main types for the native RMCP implementation
43+
pub use server::CodePrismRmcpServer;
5044

51-
// Re-export Phase 2.2 types
45+
// Re-export core configuration and monitoring types
5246
pub use config::{
5347
CachingConfig, ConfigProfileManager, McpConfigProfile, MonitoringConfig, SecurityConfig,
5448
};
49+
pub use error_handler::{McpError, McpErrorHandler, McpResult};
5550
pub use monitoring::{MonitoringMiddleware, PerformanceMonitor, PerformanceSummary};
5651
pub use tools::dynamic_enablement::{DynamicToolManager, RepositoryAnalysis};
5752
pub use validation::{StartupReport, SystemValidator, ValidationResult};
@@ -391,17 +386,19 @@ impl CodePrismMcpServer {
391386
));
392387

393388
let capabilities = ServerCapabilities {
394-
resources: Some(resources::ResourceCapabilities {
389+
resources: Some(rmcp::model::ResourcesCapability {
395390
subscribe: Some(true),
396391
list_changed: Some(true),
397392
}),
398-
tools: Some(tools::ToolCapabilities {
393+
tools: Some(rmcp::model::ToolsCapability {
399394
list_changed: Some(true),
400395
}),
401-
prompts: Some(prompts::PromptCapabilities {
396+
prompts: Some(rmcp::model::PromptsCapability {
402397
list_changed: Some(false),
403398
}),
404-
experimental: Some(HashMap::new()),
399+
logging: None,
400+
completions: None,
401+
experimental: Some(BTreeMap::new()),
405402
};
406403

407404
Ok(Self {
@@ -486,17 +483,19 @@ impl CodePrismMcpServer {
486483
));
487484

488485
let capabilities = ServerCapabilities {
489-
resources: Some(resources::ResourceCapabilities {
486+
resources: Some(rmcp::model::ResourcesCapability {
490487
subscribe: Some(true),
491488
list_changed: Some(true),
492489
}),
493-
tools: Some(tools::ToolCapabilities {
490+
tools: Some(rmcp::model::ToolsCapability {
494491
list_changed: Some(true),
495492
}),
496-
prompts: Some(prompts::PromptCapabilities {
493+
prompts: Some(rmcp::model::PromptsCapability {
497494
list_changed: Some(false),
498495
}),
499-
experimental: Some(HashMap::new()),
496+
logging: None,
497+
completions: None,
498+
experimental: Some(BTreeMap::new()),
500499
};
501500

502501
tracing::info!("MCP server configured with:");

0 commit comments

Comments
 (0)