turul_mcp_server/
lib.rs

1//! # MCP Server Framework
2//!
3//! A production-ready Rust framework for building Model Context Protocol (MCP) servers.
4//! Provides zero-configuration setup, comprehensive MCP 2025-06-18 specification support,
5//! and multiple deployment targets including HTTP, AWS Lambda, and local development.
6//!
7//! [![Crates.io](https://img.shields.io/crates/v/turul-mcp-server.svg)](https://crates.io/crates/turul-mcp-server)
8//! [![Documentation](https://docs.rs/turul-mcp-server/badge.svg)](https://docs.rs/turul-mcp-server)
9//! [![License](https://img.shields.io/crates/l/turul-mcp-server.svg)](https://github.com/aussierobots/turul-mcp-framework/blob/main/LICENSE)
10//!
11//! ## Features
12//!
13//! - **Zero Configuration**: Framework auto-determines method strings from types
14//! - **Type-Safe Error Handling**: Clean domain/protocol separation
15//! - **4 Tool Creation Levels**: Function macros → derive macros → builders → manual
16//! - **Multiple Transports**: HTTP, Server-Sent Events (SSE), AWS Lambda
17//! - **Pluggable Storage**: InMemory, SQLite, PostgreSQL, DynamoDB
18//! - **Real-time Streaming**: SSE notifications for progress and logging
19//! - **Production Ready**: Comprehensive testing, monitoring, and deployment support
20//!
21//! ## Installation
22//!
23//! Add to your `Cargo.toml`:
24//!
25//! ```toml
26//! [dependencies]
27//! turul-mcp-server = "0.2"
28//! turul-mcp-derive = "0.2"  # For macros
29//! tokio = { version = "1.0", features = ["full"] }
30//! ```
31//!
32//! ## Quick Start
33//!
34//! ```rust,no_run
35//! # use turul_mcp_server::prelude::*;
36//! #
37//! # async fn example() -> McpResult<()> {
38//! // Create a basic MCP server with detailed configuration
39//! let server = McpServer::builder()
40//!     .name("calculator-server")
41//!     .version("1.0.0")
42//!     .title("Advanced Calculator Server")
43//!     .instructions("A production-grade calculator server supporting basic arithmetic operations including addition, subtraction, multiplication, and division. Use the available tools to perform calculations. The server maintains session state for calculation history, supports real-time notifications for long-running computations, and provides detailed error reporting for invalid operations.")
44//!     .build()?;
45//!
46//! server.run().await
47//! # }
48//! ```
49//!
50//! ## Architecture
51//!
52//! The framework uses **clean domain/protocol separation**:
53//!
54//! - **Domain Layer**: Tools return `McpResult<T>` with domain errors
55//! - **Protocol Layer**: Framework converts to JSON-RPC 2.0 automatically
56//! - **Transport Layer**: HTTP/SSE with session-aware error handling
57//! - **Storage Layer**: Pluggable backends (InMemory, SQLite, PostgreSQL, DynamoDB)
58//!
59//! ## Examples
60//!
61//! **Complete working examples available at:**
62//! [github.com/aussierobots/turul-mcp-framework/tree/main/examples](https://github.com/aussierobots/turul-mcp-framework/tree/main/examples)
63//!
64//! - **Minimal Server** - Basic tool setup
65//! - **Calculator** - Math operations with error handling
66//! - **HTTP Server** - Production HTTP deployment
67//! - **AWS Lambda** - Serverless deployment
68//! - **Real-time Streaming** - SSE notifications
69//! - **Database Integration** - SQLite/PostgreSQL/DynamoDB
70//!
71//! ## Deployment Options
72//!
73//! ### Local Development
74//! ```bash
75//! cargo run --example minimal-server
76//! # Server runs on http://localhost:8080/mcp
77//! ```
78//!
79//! ### AWS Lambda
80//! ```bash
81//! cargo lambda build --release
82//! cargo lambda deploy --iam-role arn:aws:iam::...
83//! ```
84//!
85//! ### Docker
86//! ```dockerfile
87//! FROM rust:1.70 as builder
88//! COPY . .
89//! RUN cargo build --release
90//!
91//! FROM debian:bookworm-slim
92//! COPY --from=builder /target/release/my-mcp-server /usr/local/bin/
93//! EXPOSE 8080
94//! CMD ["my-mcp-server"]
95//! ```
96//!
97//! ## Configuration
98//!
99//! The framework supports extensive configuration through the builder pattern:
100//!
101//! ```rust,no_run
102//! # use turul_mcp_server::prelude::*;
103//! # use turul_mcp_session_storage::SqliteSessionStorage;
104//! # use std::time::Duration;
105//! #
106//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
107//! let server = McpServer::builder()
108//!     .name("production-server")
109//!     .version("1.0.0")
110//!     .title("Production MCP Server")
111//!     .instructions("This production server provides tools for database operations, file management, and API integrations. Use the 'database/query' tool for SQL operations, 'files/read' for file access, and 'api/call' for external service integration. Session management is enabled with SQLite persistence for reliability.")
112//!     .with_session_storage(std::sync::Arc::new(SqliteSessionStorage::new().await?))
113//!     .build()?;
114//! # Ok(())
115//! # }
116//! ```
117
118pub mod builder;
119pub mod completion;
120pub mod elicitation;
121pub mod handlers;
122pub mod logging;
123pub mod middleware;
124pub mod notifications;
125pub mod prompt;
126pub mod resource;
127pub mod roots;
128pub mod sampling;
129pub mod server;
130pub mod session;
131pub mod tool;
132// Re-export session storage from separate crate (breaks circular dependency)
133pub use turul_mcp_session_storage as session_storage;
134pub mod dispatch;
135pub mod prelude;
136pub mod security;
137pub mod uri_template;
138
139#[cfg(feature = "http")]
140pub mod http;
141
142#[cfg(test)]
143mod tests;
144
145#[cfg(test)]
146mod uri_template_tests;
147
148#[cfg(test)]
149mod security_integration_tests;
150
151// Re-export main types
152/// Builder for creating MCP servers with fluent API
153pub use builder::McpServerBuilder;
154/// Completion provider for text generation requests
155pub use completion::McpCompletion;
156/// Request dispatching and middleware support for MCP operations
157pub use dispatch::{DispatchContext, DispatchMiddleware, McpDispatcher};
158/// Elicitation handler for interactive form-based data collection
159pub use elicitation::McpElicitation;
160/// Collection of built-in MCP request handlers
161pub use handlers::*;
162/// Logging provider for structured application logs
163pub use logging::McpLogger;
164/// Notification system for real-time client updates via SSE
165pub use notifications::McpNotification;
166/// Prompt provider for generating conversation templates
167pub use prompt::McpPrompt;
168/// Resource provider for serving file-like content with URI templates
169pub use resource::McpResource;
170/// Root provider for workspace and project context
171pub use roots::McpRoot;
172/// Sampling configuration for LLM inference parameters
173pub use sampling::McpSampling;
174/// Security middleware and access control components
175pub use security::{
176    AccessLevel, InputValidator, RateLimitConfig, ResourceAccessControl, SecurityMiddleware,
177};
178/// Core MCP server and session-aware handlers
179pub use server::{
180    ListToolsHandler, McpServer, SessionAwareInitializeHandler, SessionAwareMcpHandlerBridge,
181    SessionAwareToolHandler,
182};
183/// Session management and context for stateful operations
184pub use session::{SessionContext, SessionEvent, SessionManager};
185/// SessionView trait for middleware - re-exported from turul-mcp-session-storage
186pub use turul_mcp_session_storage::SessionView;
187/// Tool trait for executable MCP functions
188pub use tool::McpTool;
189
190// Re-export foundational types
191/// JSON-RPC 2.0 request dispatcher and handler trait for protocol operations
192pub use turul_mcp_json_rpc_server::{JsonRpcDispatcher, JsonRpcHandler};
193/// Core MCP protocol types, errors, and specification compliance
194pub use turul_mcp_protocol::*;
195
196// Re-export builder pattern for Level 3 tool creation
197/// Dynamic tool creation with runtime configuration and type-safe builders
198pub use turul_mcp_builders::tool::{DynamicTool, DynamicToolFn, ToolBuilder};
199
200// Explicitly re-export error types for convenience
201/// Domain error type for MCP operations with protocol conversion support
202pub use turul_mcp_protocol::{McpError, McpResult as ProtocolMcpResult};
203
204#[cfg(feature = "http")]
205/// HTTP transport layer with SSE streaming and session management
206pub use turul_http_mcp_server;
207
208/// Result type for MCP server operations with domain-specific error handling
209///
210/// This alias provides structured error types that automatically convert to JSON-RPC 2.0
211/// error responses when crossing the protocol boundary. Use this for all tool and handler
212/// implementations to ensure consistent error reporting to MCP clients.
213pub type McpResult<T> = turul_mcp_protocol::McpResult<T>;
214
215/// Convenience alias for McpResult
216pub type Result<T> = McpResult<T>;
217
218/// Implements McpTool for DynamicTool to enable Level 3 builder pattern tool creation
219///
220/// This implementation bridges DynamicTool's builder pattern with the framework's
221/// session-aware execution model, enabling runtime tool construction with type safety.
222#[async_trait::async_trait]
223impl McpTool for DynamicTool {
224    async fn call(
225        &self,
226        args: serde_json::Value,
227        _session: Option<SessionContext>,
228    ) -> McpResult<turul_mcp_protocol::tools::CallToolResult> {
229        use turul_mcp_protocol::tools::CallToolResult;
230        use turul_mcp_builders::prelude::HasOutputSchema;
231
232        match self.execute(args).await {
233            Ok(result) => {
234                // Use smart response builder with automatic structured content
235                CallToolResult::from_result_with_schema(&result, self.output_schema())
236            }
237            Err(e) => Err(McpError::tool_execution(&e)),
238        }
239    }
240}