turbomcp-server 3.0.11

Production-ready MCP server with zero-boilerplate macros and transport-agnostic design
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
//! JSON-RPC request routing for McpHandler.
//!
//! This module provides the native server's request routing with additional
//! configuration validation beyond the core router.
//!
//! # Architecture
//!
//! The native router layers on top of `turbomcp_core::router`:
//! - **Core router**: Basic MCP method dispatch (shared with WASM)
//! - **Native router**: Protocol negotiation, capability validation
//!
//! # MCP Protocol Compliance
//!
//! This router implements the MCP 2025-11-25 specification:
//! - Initialize request validates `clientInfo` and `protocolVersion`
//! - Notifications (requests without `id`) do not receive responses
//! - Capability structure follows the spec format
//! - Error codes follow JSON-RPC 2.0 standard

use super::config::{ClientCapabilities, ServerConfig};
use turbomcp_core::context::RequestContext;
use turbomcp_core::error::McpError;
use turbomcp_core::handler::McpHandler;
use turbomcp_protocol::versioning::adapter::{VersionAdapter, adapter_for_version};

// Re-export canonical JSON-RPC types from turbomcp-core
pub use turbomcp_core::jsonrpc::{JsonRpcIncoming, JsonRpcOutgoing};
// Re-export core router utilities
pub use turbomcp_core::router::{parse_request, serialize_response};

/// Route a JSON-RPC request to the appropriate handler method.
///
/// This is the simple routing function that uses default configuration.
/// For more control, use `route_request_with_config`.
pub async fn route_request<H: McpHandler>(
    handler: &H,
    request: JsonRpcIncoming,
    ctx: &RequestContext,
) -> JsonRpcOutgoing {
    route_request_with_config(handler, request, ctx, None).await
}

/// Route a JSON-RPC request with custom server configuration.
///
/// This function provides full control over protocol negotiation,
/// capability validation, and other server behavior.
///
/// # Additional Validation (vs core router)
///
/// When a `ServerConfig` is provided, this function adds:
/// - Protocol version negotiation
/// - Required client capability validation
pub async fn route_request_with_config<H: McpHandler>(
    handler: &H,
    request: JsonRpcIncoming,
    ctx: &RequestContext,
    config: Option<&ServerConfig>,
) -> JsonRpcOutgoing {
    let id = request.id.clone();

    // Validate message size against configured limit
    if let Some(config) = config
        && let Some(ref params) = request.params
    {
        let estimated_size = params.to_string().len();
        if estimated_size > config.max_message_size {
            return JsonRpcOutgoing::error(
                id,
                McpError::invalid_request(format!(
                    "Message size {} exceeds maximum allowed size of {} bytes",
                    estimated_size, config.max_message_size
                )),
            );
        }
    }

    // For initialize requests, apply native-specific validation
    if request.method == "initialize" {
        let params_owned;
        let params = match request.params.as_ref() {
            Some(p) => p,
            None => {
                params_owned = serde_json::Value::default();
                &params_owned
            }
        };

        // Validate clientInfo is present (MCP spec requirement)
        let Some(client_info) = params.get("clientInfo") else {
            return JsonRpcOutgoing::error(
                id,
                McpError::invalid_params("Missing required field: clientInfo"),
            );
        };

        // Validate clientInfo has required fields
        let client_name = client_info.get("name").and_then(|v| v.as_str());
        let client_version = client_info.get("version").and_then(|v| v.as_str());
        if client_name.is_none() || client_version.is_none() {
            return JsonRpcOutgoing::error(
                id,
                McpError::invalid_params("clientInfo must contain 'name' and 'version' fields"),
            );
        }

        // Extract client's requested protocol version
        let protocol_version = params.get("protocolVersion").and_then(|v| v.as_str());

        // Get protocol config (use default if none provided)
        let protocol_config = config.map(|c| &c.protocol).cloned().unwrap_or_default();

        // Negotiate protocol version
        let negotiated_version = match protocol_config.negotiate(protocol_version) {
            Some(version) => {
                // Log if server fell back to a different version
                if let Some(client_ver) = protocol_version
                    && client_ver != version
                {
                    tracing::warn!(
                        client_version = client_ver,
                        negotiated_version = %version,
                        supported = ?protocol_config.supported_versions,
                        "Protocol version fallback: client requested unsupported version"
                    );
                }
                version
            }
            None => {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_request(format!(
                        "Unsupported protocol version: {}. Supported versions: {:?}",
                        protocol_version.unwrap_or("none"),
                        protocol_config.supported_versions
                    )),
                );
            }
        };

        // Parse and validate client capabilities if required
        if let Some(cfg) = config {
            let client_caps = ClientCapabilities::from_params(params);
            let validation = cfg.required_capabilities.validate(&client_caps);

            if let Some(missing) = validation.missing() {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_request(format!(
                        "Missing required client capabilities: {}",
                        missing.join(", ")
                    )),
                );
            }
        }

        // Use core router with negotiated version
        let version_str = negotiated_version.as_str();
        let core_config = turbomcp_core::router::RouteConfig {
            protocol_version: Some(version_str),
        };
        let response =
            turbomcp_core::router::route_request(handler, request, ctx, &core_config).await;

        // Apply version adapter to the initialize response
        let adapter = adapter_for_version(&negotiated_version);
        return apply_adapter_to_response(adapter, "initialize", response);
    }

    // For all other methods, delegate to core router (no adapter — caller
    // must use route_request_versioned for post-initialize adapter filtering)
    let core_config = turbomcp_core::router::RouteConfig::default();
    turbomcp_core::router::route_request(handler, request, ctx, &core_config).await
}

/// Route a JSON-RPC request with version-aware adapter filtering.
///
/// This is the recommended entry point for post-initialize requests when the
/// session has a negotiated protocol version. It:
/// 1. Validates the method is available in the negotiated version
/// 2. Delegates to the core router
/// 3. Applies the version adapter to filter the response
///
/// Transport layers should store the negotiated [`ProtocolVersion`] from
/// the initialize handshake and pass it here for all subsequent requests.
pub async fn route_request_versioned<H: McpHandler>(
    handler: &H,
    request: JsonRpcIncoming,
    ctx: &RequestContext,
    negotiated_version: &turbomcp_core::types::core::ProtocolVersion,
) -> JsonRpcOutgoing {
    let adapter = adapter_for_version(negotiated_version);
    let method = request.method.clone();

    // Validate that the method exists in the negotiated version
    if let Err(reason) = adapter.validate_method(&method) {
        return JsonRpcOutgoing::error(request.id.clone(), McpError::method_not_found(reason));
    }

    // Route through core
    let core_config = turbomcp_core::router::RouteConfig::default();
    let response = turbomcp_core::router::route_request(handler, request, ctx, &core_config).await;

    // Apply version adapter to filter the response
    apply_adapter_to_response(adapter, &method, response)
}

/// Apply a version adapter to a JSON-RPC response.
///
/// This filters the result value through the adapter's `filter_result` method,
/// stripping fields that don't exist in the target spec version.
///
/// Transport layers should call this on outgoing responses when the session
/// has a negotiated version different from the latest.
///
/// # Example
///
/// ```rust,ignore
/// use turbomcp_server::router::apply_adapter_to_response;
/// use turbomcp_protocol::versioning::adapter::adapter_for_version;
///
/// let adapter = adapter_for_version(&negotiated_version);
/// let filtered = apply_adapter_to_response(adapter, "tools/list", response);
/// ```
pub fn apply_adapter_to_response(
    adapter: &dyn VersionAdapter,
    method: &str,
    mut response: JsonRpcOutgoing,
) -> JsonRpcOutgoing {
    // Only filter successful responses (errors pass through unchanged)
    if let Some(result) = response.result.take() {
        response.result = Some(adapter.filter_result(method, result));
    }
    response
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use turbomcp_core::error::McpResult;
    use turbomcp_types::{
        Prompt, PromptResult, Resource, ResourceResult, ServerInfo, Tool, ToolResult,
    };

    #[derive(Clone)]
    struct TestHandler;

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

        fn list_tools(&self) -> Vec<Tool> {
            vec![Tool::new("test_tool", "A test tool")]
        }

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

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

        fn call_tool(
            &self,
            name: &str,
            _args: Value,
            _ctx: &RequestContext,
        ) -> impl std::future::Future<Output = McpResult<ToolResult>> + Send {
            let name = name.to_string();
            async move {
                if name == "test_tool" {
                    Ok(ToolResult::text("Tool executed"))
                } else {
                    Err(McpError::tool_not_found(&name))
                }
            }
        }

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

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

    #[test]
    fn test_parse_request() {
        let input = r#"{"jsonrpc": "2.0", "id": 1, "method": "ping"}"#;
        let request = parse_request(input).unwrap();
        assert_eq!(request.method, "ping");
        assert_eq!(request.id, Some(serde_json::json!(1)));
    }

    #[test]
    fn test_serialize_response() {
        let response = JsonRpcOutgoing::success(Some(serde_json::json!(1)), serde_json::json!({}));
        let serialized = serialize_response(&response).unwrap();
        assert!(serialized.contains("\"jsonrpc\":\"2.0\""));
        assert!(serialized.contains("\"id\":1"));
    }

    #[tokio::test]
    async fn test_route_initialize() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "initialize".to_string(),
            // MCP spec requires clientInfo with name and version
            params: Some(serde_json::json!({
                "protocolVersion": "2025-11-25",
                "clientInfo": {
                    "name": "test-client",
                    "version": "1.0.0"
                },
                "capabilities": {}
            })),
        };

        let response = route_request(&handler, request, &ctx).await;
        assert!(response.result.is_some());
        assert!(response.error.is_none());

        let result = response.result.unwrap();
        assert_eq!(result["serverInfo"]["name"], "test");
        // Verify capabilities structure per MCP spec
        assert!(result["capabilities"]["tools"].is_object());
        assert_eq!(result["capabilities"]["tools"]["listChanged"], true);
    }

    #[tokio::test]
    async fn test_route_initialize_missing_client_info() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "initialize".to_string(),
            params: Some(serde_json::json!({
                "protocolVersion": "2025-11-25"
            })),
        };

        let response = route_request(&handler, request, &ctx).await;
        assert!(response.error.is_some());
        let error = response.error.unwrap();
        assert_eq!(error.code, -32602); // INVALID_PARAMS
        assert!(error.message.contains("clientInfo"));
    }

    #[tokio::test]
    async fn test_route_initialized_notification() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        // Notification has no id
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: None,
            method: "notifications/initialized".to_string(),
            params: None,
        };

        let response = route_request(&handler, request, &ctx).await;
        // Notification responses should not be sent
        assert!(!response.should_send());
    }

    #[tokio::test]
    async fn test_route_tools_list() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "tools/list".to_string(),
            params: None,
        };

        let response = route_request(&handler, request, &ctx).await;
        assert!(response.result.is_some());

        let result = response.result.unwrap();
        let tools = result["tools"].as_array().unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0]["name"], "test_tool");
    }

    #[tokio::test]
    async fn test_route_tools_call() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "tools/call".to_string(),
            params: Some(serde_json::json!({
                "name": "test_tool",
                "arguments": {}
            })),
        };

        let response = route_request(&handler, request, &ctx).await;
        assert!(response.result.is_some());
        assert!(response.error.is_none());
    }

    #[tokio::test]
    async fn test_route_unknown_method() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "unknown/method".to_string(),
            params: None,
        };

        let response = route_request(&handler, request, &ctx).await;
        assert!(response.result.is_none());
        assert!(response.error.is_some());

        let error = response.error.unwrap();
        assert_eq!(error.code, -32601); // METHOD_NOT_FOUND
    }
}