Skip to main content

model_context_protocol/
lib.rs

1//! # MCP - Model Context Protocol
2//!
3//! A Rust implementation of the Model Context Protocol (MCP) for AI tool integration.
4//!
5//! This crate provides the infrastructure for communicating with MCP servers
6//! via stdio/HTTP transports.
7//!
8//! ## Features
9//!
10//! - **McpServer**: Core MCP server with tools and capabilities
11//! - **McpServerHub**: Aggregates multiple external servers into one
12//! - **Multiple Transports**: Support for stdio and HTTP-based MCP servers
13//! - **Tool Routing**: Automatic routing of tool calls to the correct server
14//! - **Macros**: `#[mcp_tool]` for easy tool definitions from functions
15//!
16//! ## Quick Start - Creating a Server
17//!
18//! ```rust,ignore
19//! use mcp::macros::mcp_tool;
20//! use mcp::server::stdio::McpStdioServer;
21//! use mcp::McpServerConfig;
22//!
23//! // Define tools as simple functions
24//! #[mcp_tool(description = "Add two numbers")]
25//! fn add(a: f64, b: f64) -> f64 { a + b }
26//!
27//! #[mcp_tool(description = "Subtract two numbers")]
28//! fn subtract(a: f64, b: f64) -> f64 { a - b }
29//!
30//! #[tokio::main]
31//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
32//!     let config = McpServerConfig::builder()
33//!         .name("calculator")
34//!         .version("1.0.0")
35//!         .with_tools(tools![AddTool, SubtractTool])
36//!         .build();
37//!
38//!     McpStdioServer::run(config).await?;
39//!     Ok(())
40//! }
41//! ```
42//!
43//! ## Aggregating Multiple Servers
44//!
45//! ```rust,ignore
46//! use mcp::{McpServerHub, McpServerConnectionConfig};
47//! use mcp::server::stdio::McpStdioServer;
48//!
49//! #[tokio::main]
50//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
51//!     // Create a hub that aggregates external servers
52//!     let hub = std::sync::Arc::new(McpServerHub::new("aggregator", "1.0.0"));
53//!
54//!     // Connect to external servers
55//!     hub.connect(McpServerConnectionConfig::stdio("calc", "node", vec!["calc.js".into()])).await?;
56//!     hub.connect(McpServerConnectionConfig::stdio("files", "python", vec!["files.py".into()])).await?;
57//!
58//!     // Wrap as a stdio server - all tools are now exposed
59//!     McpStdioServer::run(hub.to_config()).await?;
60//!     Ok(())
61//! }
62//! ```
63//!
64//! ## Feature Flags
65//!
66//! - `default` - Enables stdio, http, and macros features
67//! - `client` - Client transports for connecting to external MCP servers
68//! - `stdio-server` - Stdio server transport
69//! - `http-server` - HTTP server with actix-web
70//! - `macros` - Procedural macros for defining tools
71
72#![cfg_attr(docsrs, feature(doc_cfg))]
73
74/// Current MCP protocol version (2025-11-25).
75pub const MCP_PROTOCOL_VERSION: &str = "2025-11-25";
76
77pub mod protocol;
78pub mod result;
79pub mod server;
80pub mod tool;
81pub mod transport;
82
83#[cfg(feature = "macros")]
84#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
85pub mod macro_adapter;
86
87// Client transports (for connecting to external MCP servers)
88#[cfg(feature = "client")]
89pub mod client;
90
91pub mod circuit_breaker;
92pub mod hub;
93pub mod hub_common;
94pub mod server_hub;
95pub mod transport_factory;
96
97// =============================================================================
98// Re-exports
99// =============================================================================
100
101// Protocol types (core)
102pub use protocol::{
103    CallToolParams, CallToolResult, ClientInbound, JsonRpcError, JsonRpcId, JsonRpcMessage,
104    JsonRpcNotification, JsonRpcPayload, JsonRpcRequest, JsonRpcResponse, ListToolsParams,
105    ListToolsResult, McpCapabilities, McpServerInfo, McpToolDefinition, ServerOutbound,
106    ToolContent, ToolInputSchema,
107};
108
109// Protocol types (2025-11-25 - new)
110pub use protocol::{
111    // Core types
112    Annotations,
113    BaseMetadata,
114    // Elicitation types
115    BooleanSchema,
116    // Task types
117    CancelTaskParams,
118    // Completion types
119    CompleteArgument,
120    CompleteContext,
121    CompleteParams,
122    CompleteResult,
123    CompletionData,
124    // Sampling types
125    CreateMessageParams,
126    CreateMessageResult,
127    CreateTaskResult,
128    ElicitAction,
129    ElicitRequestFormParams,
130    ElicitRequestParams,
131    ElicitRequestUrlParams,
132    ElicitResult,
133    ElicitationCompleteParams,
134    GetTaskParams,
135    GetTaskPayloadParams,
136    Icon,
137    IconTheme,
138    Implementation,
139    // Roots types
140    ListRootsResult,
141    ListTasksParams,
142    ListTasksResult,
143    // Logging types
144    LoggingLevel,
145    LoggingMessageParams,
146    ModelHint,
147    ModelPreferences,
148    NumberSchema,
149    // Progress types
150    ProgressNotificationParams,
151    ProgressToken,
152    PromptReference,
153    RelatedTaskMetadata,
154    ResourceTemplateReference,
155    Role,
156    Root,
157    SamplingContent,
158    SamplingMessage,
159    SetLevelParams,
160    StringSchema,
161    StringSchemaFormat,
162    Task,
163    TaskMetadata,
164    TaskStatus,
165    TaskStatusNotificationParams,
166    // Tool types
167    TaskSupport,
168    ToolAnnotations,
169    ToolChoice,
170    ToolChoiceMode,
171    ToolExecution,
172    ToolResultContent,
173    ToolUseContent,
174};
175
176// Transport types
177pub use transport::{
178    ClientInfo, InitializeCapabilities, InitializeParams, InitializeResult,
179    McpServerConnectionConfig, McpTransport, McpTransportError, RestartPolicy, ServerCapabilities,
180    ServerInfo, TransportTypeId,
181};
182
183// Transport types (2025-11-25 - new capabilities)
184pub use transport::{
185    ElicitationCapabilities, PromptsCapabilities, ResourcesCapabilities, RootsCapabilities,
186    SamplingCapabilities, ServerToolCapabilities, TasksCapabilities, ToolCapabilities,
187};
188
189// Result types
190pub use result::{error_result, success_result, tool_err, tool_ok, IntoCallToolResult, ToolResult};
191
192// Tool types
193pub use tool::{
194    all_tools, tools_in_group, BoxFuture, DynTool, FnTool, McpTool, ToolCallResult, ToolEntry,
195    ToolFactory, ToolProvider, ToolRegistry,
196};
197
198// Re-export inventory for use in macro-generated code
199#[doc(hidden)]
200pub use inventory;
201
202// Server (core)
203pub use server::{
204    McpServer, McpServerChannels, McpServerConfig, McpServerConfigBuilder, ServerError,
205    ServerStatus,
206};
207
208// Server transports
209#[cfg(feature = "stdio-server")]
210#[cfg_attr(docsrs, doc(cfg(feature = "stdio-server")))]
211pub use server::stdio::McpStdioServer;
212
213#[cfg(feature = "http-server")]
214#[cfg_attr(docsrs, doc(cfg(feature = "http-server")))]
215pub use server::http::McpHttpServer;
216
217// Hub (legacy - for direct client usage)
218pub use hub::McpHub;
219
220// Server Hub (aggregates multiple servers into one)
221pub use server_hub::McpServerHub;
222
223// Client transports (for connecting to external servers)
224#[cfg(feature = "client")]
225#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
226pub use client::stdio::{AsyncStdioTransport, StdioTransportAdapter, TokioStdioTransport};
227
228#[cfg(feature = "client")]
229#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
230pub use client::http::{HttpTransport, HttpTransportAdapter};
231
232// Macros (when enabled)
233#[cfg(feature = "macros")]
234#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
235pub mod macros {
236    //! Procedural macros for defining MCP servers and tools.
237    //!
238    //! This module re-exports the macros from `model-context-protocol-macros`.
239    //!
240    //! Use `#[mcp(...)]` on function parameters to add descriptions:
241    //! ```rust,ignore
242    //! #[mcp_server]
243    //! impl MyServer {
244    //!     #[mcp_tool(description = "Add two numbers")]
245    //!     pub fn add(
246    //!         &self,
247    //!         #[param("First number")] a: f64,
248    //!         #[param("Second number")] b: f64,
249    //!     ) -> f64 { a + b }
250    //! }
251    //! ```
252    //!
253    //! For standalone function tools:
254    //! ```rust,ignore
255    //! use mcp::macros::mcp_tool;
256    //!
257    //! #[mcp_tool(description = "Add two numbers")]
258    //! fn add(#[param("First number")] a: f64, #[param("Second number")] b: f64) -> f64 {
259    //!     a + b
260    //! }
261    //! ```
262    //!
263    //! Note: `#[mcp_tool]` and `#[param]` are inert attributes processed by `#[mcp_server]`
264    //! when used on impl blocks. For standalone functions, `#[mcp_tool]` generates a tool struct.
265    pub use model_context_protocol_macros::{mcp_server, mcp_tool};
266}
267
268// Macro adapter (when enabled)
269#[cfg(feature = "macros")]
270#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
271pub use macro_adapter::{MacroServer, MacroServerAdapter};
272
273/// Crate version.
274pub const VERSION: &str = env!("CARGO_PKG_VERSION");
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn test_protocol_version() {
282        assert_eq!(MCP_PROTOCOL_VERSION, "2025-11-25");
283    }
284
285    #[test]
286    fn test_version() {
287        assert!(!VERSION.is_empty());
288    }
289
290    #[tokio::test]
291    async fn test_hub_basic() {
292        let hub = McpHub::new();
293        assert!(!hub.list_servers().is_empty() || hub.list_servers().is_empty());
294    }
295}