reasonkit/mcp/mod.rs
1//! # MCP (Model Context Protocol) Server Registry
2//!
3//! Rust-based MCP server implementation for ReasonKit.
4//!
5//! ## Overview
6//!
7//! This module provides:
8//! - **Server Registry**: Dynamic server discovery and registration
9//! - **MCP Client**: Connect to and interact with external MCP servers
10//! - **Health Monitoring**: Automatic health checks for registered servers
11//! - **Tool Management**: Tool capability reporting and execution
12//! - **Protocol Compliance**: Full MCP specification support
13//!
14//! ## Architecture
15//!
16//! ```text
17//! ┌─────────────────────────────────────────────────────────────┐
18//! │ MCP Registry (Coordinator) │
19//! │ - Server discovery │
20//! │ - Health monitoring │
21//! │ - Capability aggregation │
22//! ├─────────────────────────────────────────────────────────────┤
23//! │ MCP Client (Consumer) │
24//! │ - Connect to external MCP servers │
25//! │ - Execute tools via RPC │
26//! │ - Access resources │
27//! ├─────────────────────────────────────────────────────────────┤
28//! │ MCP Servers (Multiple instances) │
29//! │ - ThinkTool servers (GigaThink, LaserLogic, etc.) │
30//! │ - Custom tool servers │
31//! │ - Resource providers │
32//! ├─────────────────────────────────────────────────────────────┤
33//! │ Transport Layer │
34//! │ - JSON-RPC 2.0 over stdio (primary) │
35//! │ - HTTP/SSE (optional) │
36//! └─────────────────────────────────────────────────────────────┘
37//! ```
38//!
39//! ## MCP Protocol
40//!
41//! Based on MCP specification (2025-11-25):
42//! - JSON-RPC 2.0 messaging
43//! - Lifecycle management (initialize, shutdown)
44//! - Tools, Resources, and Prompts primitives
45//! - Progress notifications
46//! - Cancellation support
47//!
48//! ## Example: MCP Client
49//!
50//! ```rust,ignore
51//! use reasonkit::mcp::{McpClient, McpClientConfig, McpClientTrait};
52//! use std::collections::HashMap;
53//!
54//! #[tokio::main]
55//! async fn main() -> anyhow::Result<()> {
56//! // Create client configuration
57//! let config = McpClientConfig {
58//! name: "sequential-thinking".to_string(),
59//! command: "npx".to_string(),
60//! args: vec![
61//! "-y".to_string(),
62//! "@modelcontextprotocol/server-sequential-thinking".to_string()
63//! ],
64//! env: HashMap::new(),
65//! timeout_secs: 30,
66//! auto_reconnect: true,
67//! max_retries: 3,
68//! };
69//!
70//! // Connect to the server
71//! let mut client = McpClient::new(config);
72//! client.connect().await?;
73//!
74//! // List available tools
75//! let tools = client.list_tools().await?;
76//! println!("Available tools: {:?}", tools);
77//!
78//! // Call a tool
79//! let result = client.call_tool(
80//! "think",
81//! serde_json::json!({
82//! "query": "What is chain-of-thought reasoning?"
83//! })
84//! ).await?;
85//!
86//! println!("Result: {:?}", result);
87//!
88//! // Disconnect
89//! client.disconnect().await?;
90//!
91//! Ok(())
92//! }
93//! ```
94//!
95//! ## Example: Server Registry
96//!
97//! ```rust,ignore
98//! use reasonkit::mcp::{McpRegistry, McpServerConfig, TransportType};
99//!
100//! #[tokio::main]
101//! async fn main() -> anyhow::Result<()> {
102//! // Create registry
103//! let mut registry = McpRegistry::new();
104//!
105//! // Register a ThinkTool server
106//! let config = McpServerConfig {
107//! name: "gigathink".to_string(),
108//! command: "rk-thinktool".to_string(),
109//! args: vec!["--module".to_string(), "gigathink".to_string()],
110//! transport: TransportType::Stdio,
111//! env: Default::default(),
112//! };
113//!
114//! registry.register_server(config).await?;
115//!
116//! // Discover all available tools
117//! let tools = registry.list_all_tools().await?;
118//! for tool in tools {
119//! println!("Tool: {} from server {}", tool.name, tool.server);
120//! }
121//!
122//! Ok(())
123//! }
124//! ```
125
126pub mod client;
127#[cfg(feature = "daemon")]
128pub mod daemon;
129pub mod delta_tools;
130pub mod lifecycle;
131pub mod registry;
132#[cfg(feature = "memory")]
133pub mod rerank_tools;
134pub mod server;
135pub mod thinktool_tools;
136pub mod tools;
137pub mod transport;
138pub mod types;
139pub mod ws_auth;
140
141// Re-exports
142pub use types::{
143 ErrorCode, Implementation, JsonRpcVersion, McpError, McpMessage, McpNotification, McpRequest,
144 McpResponse, RequestId, ServerCapabilities, ServerInfo, ToolsCapability,
145};
146
147pub use server::{McpServer, McpServerTrait, ServerMetrics, ServerStatus};
148
149pub use registry::{HealthCheck, HealthStatus, McpRegistry, ServerRegistration};
150
151pub use client::{ClientStats, ConnectionState, McpClient, McpClientConfig, McpClientTrait};
152
153pub use tools::{
154 Prompt, PromptArgument, ResourceTemplate, Tool, ToolCapability, ToolInput, ToolResult,
155};
156
157pub use transport::{StdioTransport, Transport, TransportType};
158
159pub use lifecycle::{ClientInfo, InitializeParams, InitializeResult, PingRequest, ShutdownRequest};
160
161pub use delta_tools::DeltaToolHandler;
162
163pub use thinktool_tools::{
164 register_thinktools, BedRockHandler, BrutalHonestyHandler, GigaThinkHandler, LaserLogicHandler,
165 ProofGuardHandler, ThinkToolHandler,
166};
167
168#[cfg(feature = "memory")]
169pub use rerank_tools::RerankToolHandler;
170
171pub use ws_auth::{
172 ApiKeyInfo, ApiKeyValidator, AuthenticatedWsConnection, ConnectionInfo, ConnectionTracker,
173 InMemoryApiKeyValidator, SubscriptionTier, WsAuthError, WsAuthMessage, WsAuthResult,
174 WsAuthState,
175};
176
177/// MCP protocol version (2025-11-25)
178pub const MCP_VERSION: &str = "2025-11-25";
179
180/// Default health check interval (30 seconds)
181pub const DEFAULT_HEALTH_CHECK_INTERVAL_SECS: u64 = 30;
182
183/// Maximum server startup timeout (10 seconds)
184pub const MAX_SERVER_STARTUP_TIMEOUT_SECS: u64 = 10;