pmcp/lib.rs
1//! # MCP SDK for Rust
2//!
3//! A high-quality Rust implementation of the Model Context Protocol (MCP) SDK.
4//!
5//! This crate provides both client and server implementations of MCP with:
6//! - Full protocol compatibility with the TypeScript SDK
7//! - Zero-copy parsing where possible
8//! - Comprehensive type safety
9//! - Multiple transport options (stdio, HTTP/SSE, WebSocket)
10//! - Built-in authentication support
11//!
12//! ## Quick Start
13//!
14//! ### Client Example
15//!
16//! ```rust
17//! use pmcp::{Client, StdioTransport, ClientCapabilities};
18//!
19//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
20//! // Create a client with stdio transport
21//! let transport = StdioTransport::new();
22//! let mut client = Client::new(transport);
23//!
24//! // Initialize the connection
25//! let server_info = client.initialize(ClientCapabilities::default()).await?;
26//!
27//! // List available tools
28//! let tools = client.list_tools(None).await?;
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! ### Server Example
34//!
35//! ```rust
36//! use pmcp::{Server, ServerCapabilities, ToolHandler};
37//! use async_trait::async_trait;
38//! use serde_json::Value;
39//!
40//! struct MyTool;
41//!
42//! #[async_trait]
43//! impl ToolHandler for MyTool {
44//! async fn handle(&self, args: Value) -> Result<Value, pmcp::Error> {
45//! Ok(serde_json::json!({"result": "success"}))
46//! }
47//! }
48//!
49//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
50//! let server = Server::builder()
51//! .name("my-server")
52//! .version("1.0.0")
53//! .capabilities(ServerCapabilities::default())
54//! .tool("my-tool", MyTool)
55//! .build()?;
56//!
57//! // Run with stdio transport
58//! server.run_stdio().await?;
59//! # Ok(())
60//! # }
61//! ```
62
63#![warn(
64 missing_docs,
65 missing_debug_implementations,
66 rust_2018_idioms,
67 unreachable_pub
68)]
69#![deny(unsafe_code)]
70#![cfg_attr(docsrs, feature(doc_cfg))]
71// Allow certain clippy lints that are too pedantic for this codebase
72#![allow(clippy::missing_errors_doc)]
73#![allow(clippy::return_self_not_must_use)]
74#![allow(clippy::multiple_crate_versions)]
75#![allow(clippy::result_large_err)]
76
77pub mod client;
78pub mod error;
79pub mod server;
80pub mod shared;
81pub mod types;
82pub mod utils;
83
84// Re-export commonly used types
85pub use client::{Client, ClientBuilder};
86pub use error::{Error, ErrorCode, Result};
87pub use server::{
88 PromptHandler, ResourceHandler, SamplingHandler, Server, ServerBuilder, ToolHandler,
89};
90pub use shared::{
91 AuthMiddleware, LoggingMiddleware, Middleware, MiddlewareChain, RetryMiddleware,
92 StdioTransport, Transport,
93};
94
95#[cfg(feature = "websocket")]
96pub use shared::{WebSocketConfig, WebSocketTransport};
97
98#[cfg(feature = "http")]
99pub use shared::{HttpConfig, HttpTransport};
100pub use types::{
101 AuthInfo, AuthScheme, CallToolRequest, CallToolResult, ClientCapabilities, ClientNotification,
102 ClientRequest, CompleteRequest, CompleteResult, CompletionArgument, CompletionReference,
103 Content, CreateMessageParams, CreateMessageRequest, CreateMessageResult, GetPromptResult,
104 Implementation, IncludeContext, ListResourcesResult, ListToolsResult, LoggingLevel,
105 MessageContent, ModelPreferences, ProgressNotification, ProgressToken, PromptMessage,
106 ProtocolVersion, ReadResourceResult, RequestId, ResourceInfo, Role, RootsCapabilities,
107 SamplingCapabilities, SamplingMessage, ServerCapabilities, ServerNotification, ServerRequest,
108 TokenUsage, ToolCapabilities, ToolInfo,
109};
110pub use utils::{BatchingConfig, DebouncingConfig, MessageBatcher, MessageDebouncer};
111
112// Re-export async_trait for convenience
113pub use async_trait::async_trait;
114
115/// Protocol version constants
116pub const LATEST_PROTOCOL_VERSION: &str = "2025-06-18";
117
118/// Default protocol version to use for negotiation
119pub const DEFAULT_PROTOCOL_VERSION: &str = "2025-03-26";
120
121/// List of all protocol versions supported by this SDK
122pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &[
123 LATEST_PROTOCOL_VERSION,
124 "2025-03-26",
125 "2024-11-05",
126 "2024-10-07",
127];
128
129/// Default request timeout in milliseconds
130pub const DEFAULT_REQUEST_TIMEOUT_MS: u64 = 60_000;
131
132/// Server-side logging function (placeholder for examples).
133///
134/// In a real server context, this would send a `LogMessage` notification.
135/// For examples, this is a no-op.
136#[allow(clippy::unused_async)]
137pub async fn log(
138 _level: types::protocol::LogLevel,
139 _message: &str,
140 _data: Option<serde_json::Value>,
141) {
142 // In a real implementation, this would:
143 // 1. Get the current server context
144 // 2. Send a LogMessage notification through the transport
145 // For now, this is a placeholder for the examples
146}