turbomcp-core 3.0.12

Core MCP types and primitives - no_std compatible for WASM targets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Unified MCP handler trait for cross-platform server implementations.
//!
//! This module provides the core `McpHandler` trait that defines the interface for
//! all MCP server operations. The trait is designed to work identically on native
//! and WASM targets through platform-adaptive bounds.
//!
//! # Design Philosophy
//!
//! The `McpHandler` trait follows several key design principles:
//!
//! 1. **Unified Definition**: Single trait definition works on both native and WASM
//! 2. **Platform-Adaptive Bounds**: Uses `MaybeSend`/`MaybeSync` for conditional thread safety
//! 3. **Zero-Boilerplate**: Automatically implemented by the `#[server]` macro
//! 4. **no_std Compatible**: Core trait works in `no_std` environments with `alloc`
//!
//! # Platform Behavior
//!
//! - **Native**: Methods return `impl Future + Send`, enabling multi-threaded executors
//! - **WASM**: Methods return `impl Future`, compatible with single-threaded runtimes
//!
//! # Example
//!
//! ```rust,ignore
//! use turbomcp::prelude::*;
//!
//! #[derive(Clone)]
//! struct MyServer;
//!
//! #[server(name = "my-server", version = "1.0.0")]
//! impl MyServer {
//!     #[tool]
//!     async fn greet(&self, name: String) -> String {
//!         format!("Hello, {}!", name)
//!     }
//! }
//!
//! // On native:
//! #[tokio::main]
//! async fn main() {
//!     MyServer.run_stdio().await.unwrap();
//! }
//!
//! // On WASM (Cloudflare Workers):
//! #[event(fetch)]
//! async fn fetch(req: Request, _env: Env, _ctx: Context) -> Result<Response> {
//!     MyServer.handle_worker_request(req).await
//! }
//! ```

use alloc::vec::Vec;
use core::future::Future;
use serde_json::Value;

use crate::context::RequestContext;
use crate::error::McpResult;
use crate::marker::{MaybeSend, MaybeSync};
use turbomcp_types::{
    Prompt, PromptCapabilities, PromptResult, Resource, ResourceCapabilities, ResourceResult,
    ServerCapabilities, ServerInfo, Tool, ToolCapabilities, ToolResult,
};

/// The unified MCP handler trait.
///
/// This trait defines the complete interface for an MCP server. It's designed to:
/// - Work identically on native (std) and WASM (no_std) targets
/// - Be automatically implemented by the `#[server]` macro
/// - Enable zero-boilerplate server development
///
/// # Required Methods
///
/// - [`server_info`](McpHandler::server_info): Returns server metadata
/// - [`list_tools`](McpHandler::list_tools): Returns available tools
/// - [`list_resources`](McpHandler::list_resources): Returns available resources
/// - [`list_prompts`](McpHandler::list_prompts): Returns available prompts
/// - [`call_tool`](McpHandler::call_tool): Executes a tool
/// - [`read_resource`](McpHandler::read_resource): Reads a resource
/// - [`get_prompt`](McpHandler::get_prompt): Gets a prompt
///
/// # Optional Hooks
///
/// - [`on_initialize`](McpHandler::on_initialize): Called during server initialization
/// - [`on_shutdown`](McpHandler::on_shutdown): Called during server shutdown
///
/// # Thread Safety
///
/// The trait requires `MaybeSend + MaybeSync` bounds, which translate to:
/// - **Native**: `Send + Sync` required for multi-threaded execution
/// - **WASM**: No thread safety requirements (single-threaded)
///
/// # Manual Implementation
///
/// While the `#[server]` macro is recommended, you can implement manually:
///
/// ```rust
/// use core::future::Future;
/// use serde_json::Value;
/// use turbomcp_core::handler::McpHandler;
/// use turbomcp_core::context::RequestContext;
/// use turbomcp_core::error::{McpError, McpResult};
/// use turbomcp_types::{Prompt, PromptResult, Resource, ResourceResult, ServerInfo, Tool, ToolResult};
///
/// #[derive(Clone)]
/// struct MyHandler;
///
/// impl McpHandler for MyHandler {
///     fn server_info(&self) -> ServerInfo {
///         ServerInfo::new("my-handler", "1.0.0")
///     }
///
///     fn list_tools(&self) -> Vec<Tool> {
///         vec![Tool::new("hello", "Say hello")]
///     }
///
///     fn list_resources(&self) -> Vec<Resource> {
///         vec![]
///     }
///
///     fn list_prompts(&self) -> Vec<Prompt> {
///         vec![]
///     }
///
///     fn call_tool<'a>(
///         &'a self,
///         name: &'a str,
///         args: Value,
///         _ctx: &'a RequestContext,
///     ) -> impl Future<Output = McpResult<ToolResult>> + 'a {
///         let name = name.to_string();
///         async move {
///             match name.as_str() {
///                 "hello" => {
///                     let who = args.get("name")
///                         .and_then(|v| v.as_str())
///                         .unwrap_or("World");
///                     Ok(ToolResult::text(format!("Hello, {}!", who)))
///                 }
///                 _ => Err(McpError::tool_not_found(&name))
///             }
///         }
///     }
///
///     fn read_resource<'a>(
///         &'a self,
///         uri: &'a str,
///         _ctx: &'a RequestContext,
///     ) -> impl Future<Output = McpResult<ResourceResult>> + 'a {
///         let uri = uri.to_string();
///         async move { Err(McpError::resource_not_found(&uri)) }
///     }
///
///     fn get_prompt<'a>(
///         &'a self,
///         name: &'a str,
///         _args: Option<Value>,
///         _ctx: &'a RequestContext,
///     ) -> impl Future<Output = McpResult<PromptResult>> + 'a {
///         let name = name.to_string();
///         async move { Err(McpError::prompt_not_found(&name)) }
///     }
/// }
/// ```
///
/// # Clone Bound Rationale
///
/// The `Clone` bound is required because MCP handlers are typically shared across multiple
/// concurrent connections and requests. This enables:
///
/// - **Multi-connection support**: Each connection can hold its own handler instance
/// - **Cheap sharing**: Handlers follow the Arc-cloning pattern (like Axum/Tower services)
/// - **Zero-cost abstraction**: Clone typically just increments an Arc reference count
///
/// ## Recommended Pattern
///
/// Wrap your server state in `Arc` for cheap cloning:
///
/// ```rust,ignore
/// use std::sync::Arc;
/// use turbomcp::prelude::*;
///
/// #[derive(Clone)]
/// struct MyServer {
///     state: Arc<ServerState>,
/// }
///
/// struct ServerState {
///     database: Database,
///     cache: Cache,
///     // Heavy resources that shouldn't be cloned
/// }
///
/// #[server(name = "my-server", version = "1.0.0")]
/// impl MyServer {
///     #[tool]
///     async fn process(&self, input: String) -> String {
///         // Access shared state via Arc (cheap clone on each call)
///         self.state.database.query(&input).await
///     }
/// }
/// ```
///
/// Cloning `MyServer` only increments the Arc reference count, not the actual state.
pub trait McpHandler: Clone + MaybeSend + MaybeSync + 'static {
    // ===== Server Metadata =====

    /// Returns server information (name, version, description, etc.)
    ///
    /// This is called during the MCP `initialize` handshake to provide
    /// server metadata to the client.
    fn server_info(&self) -> ServerInfo;

    /// Returns the server capabilities advertised during initialization.
    ///
    /// Override this when the server supports capabilities that cannot be
    /// inferred from the static tool/resource/prompt listings, such as draft
    /// `extensions`, logging, completions, or task endpoints.
    fn server_capabilities(&self) -> ServerCapabilities {
        let mut capabilities = ServerCapabilities::default();

        if !self.list_tools().is_empty() {
            capabilities.tools = Some(ToolCapabilities {
                list_changed: Some(true),
            });
        }

        if !self.list_resources().is_empty() {
            capabilities.resources = Some(ResourceCapabilities {
                subscribe: None,
                list_changed: Some(true),
            });
        }

        if !self.list_prompts().is_empty() {
            capabilities.prompts = Some(PromptCapabilities {
                list_changed: Some(true),
            });
        }

        capabilities
    }

    // ===== Capability Listings =====

    /// Returns all available tools.
    ///
    /// Called in response to `tools/list` requests. The returned tools
    /// will be advertised to clients with their schemas.
    fn list_tools(&self) -> Vec<Tool>;

    /// Returns all available resources.
    ///
    /// Called in response to `resources/list` requests.
    fn list_resources(&self) -> Vec<Resource>;

    /// Returns all available prompts.
    ///
    /// Called in response to `prompts/list` requests.
    fn list_prompts(&self) -> Vec<Prompt>;

    // ===== Request Handlers =====

    /// Calls a tool by name with the given arguments.
    ///
    /// Called in response to `tools/call` requests.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the tool to call
    /// * `args` - JSON arguments for the tool
    /// * `ctx` - Request context with metadata
    ///
    /// # Returns
    ///
    /// The tool result or an error. Use `McpError::tool_not_found()`
    /// for unknown tools.
    fn call_tool<'a>(
        &'a self,
        name: &'a str,
        args: Value,
        ctx: &'a RequestContext,
    ) -> impl Future<Output = McpResult<ToolResult>> + MaybeSend + 'a;

    /// Reads a resource by URI.
    ///
    /// Called in response to `resources/read` requests.
    ///
    /// # Arguments
    ///
    /// * `uri` - The URI of the resource to read
    /// * `ctx` - Request context with metadata
    ///
    /// # Returns
    ///
    /// The resource content or an error. Use `McpError::resource_not_found()`
    /// for unknown resources.
    fn read_resource<'a>(
        &'a self,
        uri: &'a str,
        ctx: &'a RequestContext,
    ) -> impl Future<Output = McpResult<ResourceResult>> + MaybeSend + 'a;

    /// Gets a prompt by name with optional arguments.
    ///
    /// Called in response to `prompts/get` requests.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the prompt
    /// * `args` - Optional JSON arguments for the prompt
    /// * `ctx` - Request context with metadata
    ///
    /// # Returns
    ///
    /// The prompt messages or an error. Use `McpError::prompt_not_found()`
    /// for unknown prompts.
    fn get_prompt<'a>(
        &'a self,
        name: &'a str,
        args: Option<Value>,
        ctx: &'a RequestContext,
    ) -> impl Future<Output = McpResult<PromptResult>> + MaybeSend + 'a;

    // ===== Task Management (SEP-1686) =====

    /// Lists all active and recent tasks.
    ///
    /// # Arguments
    ///
    /// * `cursor` - Opaque pagination cursor
    /// * `limit` - Maximum number of tasks to return
    /// * `ctx` - Request context
    fn list_tasks<'a>(
        &'a self,
        _cursor: Option<&'a str>,
        _limit: Option<usize>,
        _ctx: &'a RequestContext,
    ) -> impl Future<Output = McpResult<turbomcp_types::ListTasksResult>> + MaybeSend + 'a {
        async {
            Err(crate::error::McpError::capability_not_supported(
                "tasks/list",
            ))
        }
    }

    /// Gets the current state of a specific task.
    ///
    /// # Arguments
    ///
    /// * `task_id` - Unique task identifier
    /// * `ctx` - Request context
    fn get_task<'a>(
        &'a self,
        _task_id: &'a str,
        _ctx: &'a RequestContext,
    ) -> impl Future<Output = McpResult<turbomcp_types::Task>> + MaybeSend + 'a {
        async {
            Err(crate::error::McpError::capability_not_supported(
                "tasks/get",
            ))
        }
    }

    /// Cancels a running task.
    ///
    /// # Arguments
    ///
    /// * `task_id` - Unique task identifier
    /// * `ctx` - Request context
    fn cancel_task<'a>(
        &'a self,
        _task_id: &'a str,
        _ctx: &'a RequestContext,
    ) -> impl Future<Output = McpResult<turbomcp_types::Task>> + MaybeSend + 'a {
        async {
            Err(crate::error::McpError::capability_not_supported(
                "tasks/cancel",
            ))
        }
    }

    /// Gets the result of a completed task.
    ///
    /// # Arguments
    ///
    /// * `task_id` - Unique task identifier
    /// * `ctx` - Request context
    fn get_task_result<'a>(
        &'a self,
        _task_id: &'a str,
        _ctx: &'a RequestContext,
    ) -> impl Future<Output = McpResult<Value>> + MaybeSend + 'a {
        async {
            Err(crate::error::McpError::capability_not_supported(
                "tasks/result",
            ))
        }
    }

    // ===== Lifecycle Hooks =====

    /// Called when the server is initialized.
    ///
    /// Override this to perform setup tasks like loading configuration,
    /// establishing database connections, or warming caches.
    ///
    /// Default implementation does nothing.
    fn on_initialize(&self) -> impl Future<Output = McpResult<()>> + MaybeSend {
        async { Ok(()) }
    }

    /// Called when the server is shutting down.
    ///
    /// Override this to perform cleanup tasks like flushing buffers,
    /// closing connections, or saving state.
    ///
    /// Default implementation does nothing.
    fn on_shutdown(&self) -> impl Future<Output = McpResult<()>> + MaybeSend {
        async { Ok(()) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::McpError;

    #[derive(Clone)]
    struct TestHandler;

    impl McpHandler for TestHandler {
        fn server_info(&self) -> ServerInfo {
            ServerInfo::new("test-handler", "1.0.0")
        }

        fn list_tools(&self) -> Vec<Tool> {
            vec![Tool::new("greet", "Say hello")]
        }

        fn list_resources(&self) -> Vec<Resource> {
            vec![]
        }

        fn list_prompts(&self) -> Vec<Prompt> {
            vec![]
        }

        fn call_tool<'a>(
            &'a self,
            name: &'a str,
            args: Value,
            _ctx: &'a RequestContext,
        ) -> impl Future<Output = McpResult<ToolResult>> + MaybeSend + 'a {
            let name = name.to_string();
            async move {
                match name.as_str() {
                    "greet" => {
                        let who = args.get("name").and_then(|v| v.as_str()).unwrap_or("World");
                        Ok(ToolResult::text(format!("Hello, {}!", who)))
                    }
                    _ => Err(McpError::tool_not_found(&name)),
                }
            }
        }

        fn read_resource<'a>(
            &'a self,
            uri: &'a str,
            _ctx: &'a RequestContext,
        ) -> impl Future<Output = McpResult<ResourceResult>> + MaybeSend + 'a {
            let uri = uri.to_string();
            async move { Err(McpError::resource_not_found(&uri)) }
        }

        fn get_prompt<'a>(
            &'a self,
            name: &'a str,
            _args: Option<Value>,
            _ctx: &'a RequestContext,
        ) -> impl Future<Output = McpResult<PromptResult>> + MaybeSend + 'a {
            let name = name.to_string();
            async move { Err(McpError::prompt_not_found(&name)) }
        }
    }

    #[test]
    fn test_server_info() {
        let handler = TestHandler;
        let info = handler.server_info();
        assert_eq!(info.name, "test-handler");
        assert_eq!(info.version, "1.0.0");
    }

    #[test]
    fn test_list_tools() {
        let handler = TestHandler;
        let tools = handler.list_tools();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name, "greet");
    }

    #[tokio::test]
    async fn test_call_tool() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let args = serde_json::json!({"name": "Alice"});

        let result = handler.call_tool("greet", args, &ctx).await.unwrap();
        assert_eq!(result.first_text(), Some("Hello, Alice!"));
    }

    #[tokio::test]
    async fn test_call_tool_not_found() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let args = serde_json::json!({});

        let result = handler.call_tool("unknown", args, &ctx).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_lifecycle_hooks() {
        let handler = TestHandler;
        assert!(handler.on_initialize().await.is_ok());
        assert!(handler.on_shutdown().await.is_ok());
    }

    // Verify that the trait object is Send + Sync on native
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn test_handler_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<TestHandler>();
    }
}