Skip to main content

velocity_mcp_core/
lib.rs

1//! VELOCITY-MCP Core - WASM-compatible protocol logic.
2//!
3//! This crate contains pure MCP protocol handling without OS-specific dependencies.
4//! It can be compiled to both native and wasm32-wasip1 targets.
5//!
6//! ## Tool Execution
7//!
8//! The core crate defines a [`ToolExecutor`] trait that callers implement to provide
9//! actual tool execution. The [`handle_mcp_request_with_executor`] function routes
10//! `tools/list` and `tools/call` to the provided executor, enabling real tool execution
11//! in any deployment target (native, edge/WASM, etc.).
12//!
13//! ## Supported MCP Methods
14//!
15//! | Method | Status |
16//! |---|---|
17//! | `initialize` | Full — declares tools, resources, prompts capabilities |
18//! | `notifications/initialized` | Acknowledged (no-op) |
19//! | `ping` | Full |
20//! | `tools/list` | Full via executor; stub returns empty |
21//! | `tools/call` | Full via executor; stub returns placeholder |
22//! | `resources/list` | Returns empty list (no resource provider on Edge) |
23//! | `resources/read` | Validates URI format, returns error for unknown URIs |
24//! | `resources/templates/list` | Returns empty list |
25//! | `prompts/list` | Returns empty list (no prompt provider on Edge) |
26//! | `prompts/get` | Validates name, returns error for unknown prompts |
27//! | `elicitation/create` | Refused (`-32601`) — server→client method |
28//! | `roots/list` | Refused (`-32601`) — server→client method |
29//! | `completion/complete` | Validates ref type, returns empty completions |
30//! | `sampling/createMessage` | Refused (`-32601`) — server→client method |
31
32use serde::{Deserialize, Serialize};
33use serde_json::Value;
34
35/// MCP JSON-RPC request
36#[derive(Debug, Deserialize)]
37pub struct McpRequest {
38    pub jsonrpc: String,
39    #[serde(default)]
40    pub method: String,
41    #[serde(default)]
42    pub params: Option<Value>,
43    pub id: Option<Value>,
44}
45
46/// MCP JSON-RPC response
47#[derive(Debug, Serialize)]
48pub struct McpResponse {
49    pub jsonrpc: String,
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub result: Option<Value>,
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub error: Option<McpError>,
54    pub id: Option<Value>,
55}
56
57/// MCP error structure
58#[derive(Debug, Serialize)]
59pub struct McpError {
60    pub code: i64,
61    pub message: String,
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub data: Option<Value>,
64}
65
66/// Definition of an MCP tool (name, description, JSON Schema for input).
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct ToolDefinition {
69    pub name: String,
70    pub description: String,
71    #[serde(rename = "inputSchema")]
72    pub input_schema: Value,
73}
74
75/// Trait for providing tool listing and execution to the core protocol handler.
76///
77/// Implement this trait in the deployment-specific crate (e.g., velocity-mcp-edge)
78/// to supply actual tool definitions and execution logic.
79///
80/// # Constraints for WASM/WASIX deployment
81///
82/// - Must be pure compute (no filesystem, no process spawning, no network)
83/// - Must complete within the caller's timeout (typically 5 seconds)
84/// - Must not panic — return errors as `Err(String)` instead
85pub trait ToolExecutor {
86    fn list_tools(&self) -> Vec<ToolDefinition>;
87    fn call_tool(&self, name: &str, arguments: &Value) -> Result<String, String>;
88}
89
90// ---------------------------------------------------------------------------
91// Public entry points
92// ---------------------------------------------------------------------------
93
94/// Process an MCP request in stub mode (no tool execution).
95pub fn handle_mcp_request(request: &McpRequest) -> McpResponse {
96    dispatch(request, None)
97}
98
99/// Process an MCP request with a real tool executor.
100pub fn handle_mcp_request_with_executor(
101    request: &McpRequest,
102    executor: &dyn ToolExecutor,
103) -> McpResponse {
104    dispatch(request, Some(executor))
105}
106
107fn dispatch(request: &McpRequest, executor: Option<&dyn ToolExecutor>) -> McpResponse {
108    // JSON-RPC 2.0 structural validation (Invalid Request → -32600).
109    if request.jsonrpc != "2.0" {
110        return error_response(
111            request.id.clone(),
112            -32600,
113            "Invalid Request: jsonrpc must be \"2.0\"",
114        );
115    }
116    if request.method.is_empty() {
117        return error_response(
118            request.id.clone(),
119            -32600,
120            "Invalid Request: missing required member 'method'",
121        );
122    }
123    match request.method.as_str() {
124        "initialize" => handle_initialize(request),
125        "notifications/initialized" => handle_notification(request),
126        "notifications/cancelled" => handle_notification(request),
127        "ping" => handle_ping(request),
128
129        "tools/list" => match executor {
130            Some(ex) => handle_tools_list(request, ex),
131            None => handle_tools_list_stub(request),
132        },
133        "tools/call" => match executor {
134            Some(ex) => handle_tools_call(request, ex),
135            None => handle_tools_call_stub(request),
136        },
137
138        "resources/list" => handle_resources_list(request),
139        "resources/read" => handle_resources_read(request),
140        "resources/templates/list" => handle_resources_templates_list(request),
141
142        "prompts/list" => handle_prompts_list(request),
143        "prompts/get" => handle_prompts_get(request),
144
145        "completion/complete" => handle_completion_complete(request),
146
147        _ => method_not_found(request),
148    }
149}
150
151// ---------------------------------------------------------------------------
152// Helpers
153// ---------------------------------------------------------------------------
154
155fn ok_response(id: Option<Value>, result: Value) -> McpResponse {
156    McpResponse {
157        jsonrpc: "2.0".to_string(),
158        result: Some(result),
159        error: None,
160        id,
161    }
162}
163
164fn error_response(id: Option<Value>, code: i64, message: impl Into<String>) -> McpResponse {
165    McpResponse {
166        jsonrpc: "2.0".to_string(),
167        result: None,
168        error: Some(McpError {
169            code,
170            message: message.into(),
171            data: None,
172        }),
173        id,
174    }
175}
176
177fn method_not_found(request: &McpRequest) -> McpResponse {
178    error_response(
179        request.id.clone(),
180        -32601,
181        format!("Method not found: {}", request.method),
182    )
183}
184
185// ---------------------------------------------------------------------------
186// initialize
187// ---------------------------------------------------------------------------
188
189fn handle_initialize(request: &McpRequest) -> McpResponse {
190    // Server-side capabilities only. `roots` is a *client* capability, while
191    // `sampling` and `elicitation` are server capabilities this crate never
192    // exercises -- it sends no such request -- so none belongs in this map.
193    let capabilities = serde_json::json!({
194        "protocolVersion": "2024-11-05",
195        "capabilities": {
196            "tools": {},
197            "resources": { "subscribe": false, "listChanged": false },
198            "prompts": { "listChanged": false }
199        },
200        "serverInfo": {
201            "name": "velocity-mcp-edge",
202            "version": "3.2.0"
203        }
204    });
205
206    ok_response(request.id.clone(), capabilities)
207}
208
209// ---------------------------------------------------------------------------
210// notifications (no response expected per JSON-RPC spec, but we return ack)
211// ---------------------------------------------------------------------------
212
213fn handle_notification(_request: &McpRequest) -> McpResponse {
214    ok_response(None, serde_json::json!({}))
215}
216
217// ---------------------------------------------------------------------------
218// ping
219// ---------------------------------------------------------------------------
220
221fn handle_ping(request: &McpRequest) -> McpResponse {
222    ok_response(request.id.clone(), serde_json::json!({"status": "ok"}))
223}
224
225// ---------------------------------------------------------------------------
226// tools/list
227// ---------------------------------------------------------------------------
228
229fn handle_tools_list_stub(request: &McpRequest) -> McpResponse {
230    ok_response(request.id.clone(), serde_json::json!({ "tools": [] }))
231}
232
233fn handle_tools_list(request: &McpRequest, executor: &dyn ToolExecutor) -> McpResponse {
234    let tools = executor.list_tools();
235    let tools_json: Vec<Value> = tools
236        .iter()
237        .map(|t| {
238            serde_json::json!({
239                "name": t.name,
240                "description": t.description,
241                "inputSchema": t.input_schema,
242            })
243        })
244        .collect();
245
246    ok_response(
247        request.id.clone(),
248        serde_json::json!({ "tools": tools_json }),
249    )
250}
251
252// ---------------------------------------------------------------------------
253// tools/call
254// ---------------------------------------------------------------------------
255
256fn handle_tools_call_stub(request: &McpRequest) -> McpResponse {
257    let tool_name = request
258        .params
259        .as_ref()
260        .and_then(|p| p["name"].as_str())
261        .unwrap_or("unknown");
262
263    ok_response(
264        request.id.clone(),
265        serde_json::json!({
266            "content": [{
267                "type": "text",
268                "text": format!("Tool '{}' execution requires WASM runtime integration", tool_name)
269            }]
270        }),
271    )
272}
273
274fn handle_tools_call(request: &McpRequest, executor: &dyn ToolExecutor) -> McpResponse {
275    let params = request.params.as_ref();
276    let tool_name = params.and_then(|p| p["name"].as_str()).unwrap_or("");
277    let arguments = params
278        .and_then(|p| p.get("arguments"))
279        .cloned()
280        .unwrap_or(Value::Object(serde_json::Map::new()));
281
282    if tool_name.is_empty() {
283        return error_response(
284            request.id.clone(),
285            -32602,
286            "Missing required field: params.name",
287        );
288    }
289
290    match executor.call_tool(tool_name, &arguments) {
291        Ok(output) => ok_response(
292            request.id.clone(),
293            serde_json::json!({
294                "content": [{ "type": "text", "text": output }]
295            }),
296        ),
297        Err(err_msg) => ok_response(
298            request.id.clone(),
299            serde_json::json!({
300                "content": [{ "type": "text", "text": format!("Error: {}", err_msg) }],
301                "isError": true
302            }),
303        ),
304    }
305}
306
307// ---------------------------------------------------------------------------
308// resources
309// ---------------------------------------------------------------------------
310
311fn handle_resources_list(request: &McpRequest) -> McpResponse {
312    ok_response(request.id.clone(), serde_json::json!({ "resources": [] }))
313}
314
315fn handle_resources_read(request: &McpRequest) -> McpResponse {
316    let params = request.params.as_ref();
317    let uri = params.and_then(|p| p["uri"].as_str()).unwrap_or("");
318
319    if uri.is_empty() {
320        return error_response(
321            request.id.clone(),
322            -32602,
323            "Missing required field: params.uri",
324        );
325    }
326
327    // Edge server has no resource provider — return a clean error.
328    // Clients should check resources/list first to discover available URIs.
329    error_response(
330        request.id.clone(),
331        -32001,
332        format!("Resource not found: {}", uri),
333    )
334}
335
336fn handle_resources_templates_list(request: &McpRequest) -> McpResponse {
337    ok_response(
338        request.id.clone(),
339        serde_json::json!({ "resourceTemplates": [] }),
340    )
341}
342
343// ---------------------------------------------------------------------------
344// prompts
345// ---------------------------------------------------------------------------
346
347fn handle_prompts_list(request: &McpRequest) -> McpResponse {
348    ok_response(request.id.clone(), serde_json::json!({ "prompts": [] }))
349}
350
351fn handle_prompts_get(request: &McpRequest) -> McpResponse {
352    let params = request.params.as_ref();
353    let name = params.and_then(|p| p["name"].as_str()).unwrap_or("");
354
355    if name.is_empty() {
356        return error_response(
357            request.id.clone(),
358            -32602,
359            "Missing required field: params.name",
360        );
361    }
362
363    // Edge server has no prompt provider.
364    error_response(
365        request.id.clone(),
366        -32001,
367        format!("Prompt not found: {}", name),
368    )
369}
370
371// ---------------------------------------------------------------------------
372// completion/complete
373// ---------------------------------------------------------------------------
374
375/// Handle completion/complete — provides auto-complete suggestions.
376///
377/// Per MCP spec, the client sends a reference (type: ref/prompt or ref/resource)
378/// and an argument name + partial value. The server returns matching completions.
379/// On Edge, we validate the request and return empty completions.
380fn handle_completion_complete(request: &McpRequest) -> McpResponse {
381    let params = request.params.as_ref();
382
383    // Validate ref.type
384    let ref_type = params
385        .and_then(|p| p.get("ref"))
386        .and_then(|r| r.as_object())
387        .and_then(|r| r.get("type"))
388        .and_then(|t| t.as_str())
389        .unwrap_or("");
390
391    match ref_type {
392        "ref/prompt" | "ref/resource" => {}
393        "" => {
394            return error_response(
395                request.id.clone(),
396                -32602,
397                "Missing required field: params.ref.type",
398            );
399        }
400        other => {
401            return error_response(
402                request.id.clone(),
403                -32602,
404                format!(
405                    "Invalid ref type: '{}'. Expected 'ref/prompt' or 'ref/resource'",
406                    other
407                ),
408            );
409        }
410    }
411
412    // Validate argument name
413    let arg_name = params
414        .and_then(|p| p.get("argument"))
415        .and_then(|a| a.as_object())
416        .and_then(|a| a.get("name"))
417        .and_then(|n| n.as_str())
418        .unwrap_or("");
419
420    if arg_name.is_empty() {
421        return error_response(
422            request.id.clone(),
423            -32602,
424            "Missing required field: params.argument.name",
425        );
426    }
427
428    ok_response(
429        request.id.clone(),
430        serde_json::json!({
431            "completion": {
432                "values": [],
433                "total": 0,
434                "hasMore": false
435            }
436        }),
437    )
438}
439
440// ---------------------------------------------------------------------------
441// Serialization
442// ---------------------------------------------------------------------------
443
444/// Parse raw JSON bytes into an McpRequest
445pub fn parse_request(bytes: &[u8]) -> Result<McpRequest, String> {
446    serde_json::from_slice(bytes).map_err(|e| format!("Invalid JSON: {}", e))
447}
448
449/// Serialize an McpResponse to JSON bytes
450pub fn serialize_response(response: &McpResponse) -> Vec<u8> {
451    serde_json::to_vec(response).unwrap_or_else(|_| {
452        b"{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32000,\"message\":\"Serialization failed\"},\"id\":null}".to_vec()
453    })
454}
455
456// ---------------------------------------------------------------------------
457// Tests
458// ---------------------------------------------------------------------------
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463
464    struct MockExecutor;
465
466    impl ToolExecutor for MockExecutor {
467        fn list_tools(&self) -> Vec<ToolDefinition> {
468            vec![
469                ToolDefinition {
470                    name: "echo".to_string(),
471                    description: "Echo back the input".to_string(),
472                    input_schema: serde_json::json!({
473                        "type": "object",
474                        "properties": { "message": { "type": "string" } },
475                        "required": ["message"]
476                    }),
477                },
478                ToolDefinition {
479                    name: "add".to_string(),
480                    description: "Add two numbers".to_string(),
481                    input_schema: serde_json::json!({
482                        "type": "object",
483                        "properties": {
484                            "a": { "type": "number" },
485                            "b": { "type": "number" }
486                        },
487                        "required": ["a", "b"]
488                    }),
489                },
490            ]
491        }
492
493        fn call_tool(&self, name: &str, arguments: &Value) -> Result<String, String> {
494            match name {
495                "echo" => {
496                    let msg = arguments["message"].as_str().ok_or("message is required")?;
497                    Ok(msg.to_string())
498                }
499                "add" => {
500                    let a = arguments["a"].as_f64().ok_or("a is required")?;
501                    let b = arguments["b"].as_f64().ok_or("b is required")?;
502                    Ok(format!("{}", a + b))
503                }
504                _ => Err(format!("Unknown tool: {}", name)),
505            }
506        }
507    }
508
509    fn req(json: &[u8]) -> McpRequest {
510        parse_request(json).unwrap()
511    }
512
513    // -- initialize --
514
515    #[test]
516    fn test_initialize_capabilities() {
517        let r = req(br#"{"jsonrpc":"2.0","method":"initialize","params":{},"id":1}"#);
518        let resp = handle_mcp_request_with_executor(&r, &MockExecutor);
519        let result = resp.result.unwrap();
520        assert_eq!(result["protocolVersion"], "2024-11-05");
521        assert!(result["capabilities"]["tools"].is_object());
522        assert!(result["capabilities"]["resources"].is_object());
523        assert!(result["capabilities"]["prompts"].is_object());
524        // Client-direction capabilities must not appear in the server's map.
525        assert!(result["capabilities"].get("elicitation").is_none());
526        assert!(result["capabilities"].get("roots").is_none());
527        assert!(result["capabilities"].get("sampling").is_none());
528        assert_eq!(result["serverInfo"]["name"], "velocity-mcp-edge");
529    }
530
531    // -- ping --
532
533    #[test]
534    fn test_ping() {
535        let r = req(br#"{"jsonrpc":"2.0","method":"ping","id":99}"#);
536        let resp = handle_mcp_request(&r);
537        assert_eq!(resp.id, Some(serde_json::json!(99)));
538        assert_eq!(resp.result.unwrap()["status"], "ok");
539    }
540
541    // -- notifications --
542
543    #[test]
544    fn test_notifications_initialized() {
545        let r = req(br#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
546        let resp = handle_mcp_request(&r);
547        assert!(resp.result.is_some());
548    }
549
550    #[test]
551    fn test_notifications_cancelled() {
552        let r = req(
553            br#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":42}}"#,
554        );
555        let resp = handle_mcp_request(&r);
556        assert!(resp.result.is_some());
557    }
558
559    // -- tools (stub path) --
560
561    #[test]
562    fn test_stub_tools_list_returns_empty() {
563        let r = req(br#"{"jsonrpc":"2.0","method":"tools/list","params":{},"id":1}"#);
564        let resp = handle_mcp_request(&r);
565        let tools = resp.result.unwrap()["tools"].as_array().unwrap().clone();
566        assert!(tools.is_empty());
567    }
568
569    #[test]
570    fn test_stub_tools_call_returns_placeholder() {
571        let r = req(br#"{"jsonrpc":"2.0","method":"tools/call","params":{"name":"test","arguments":{}},"id":2}"#);
572        let resp = handle_mcp_request(&r);
573        let text = resp.result.unwrap()["content"][0]["text"]
574            .as_str()
575            .unwrap()
576            .to_string();
577        assert!(text.contains("test"));
578    }
579
580    #[test]
581    fn test_tools_list_preserves_request_ids() {
582        for id in [serde_json::json!(1), serde_json::json!("tool-list")] {
583            let request = req(&serde_json::to_vec(&serde_json::json!({
584                "jsonrpc": "2.0",
585                "id": id,
586                "method": "tools/list"
587            }))
588            .unwrap());
589            for response in [
590                handle_mcp_request(&request),
591                handle_mcp_request_with_executor(&request, &MockExecutor),
592            ] {
593                let serialized: Value =
594                    serde_json::from_slice(&serialize_response(&response)).unwrap();
595                assert_eq!(serialized["id"], id);
596            }
597        }
598    }
599
600    // -- tools (executor path) --
601
602    #[test]
603    fn test_executor_tools_list() {
604        let r = req(br#"{"jsonrpc":"2.0","method":"tools/list","params":{},"id":1}"#);
605        let resp = handle_mcp_request_with_executor(&r, &MockExecutor);
606        let tools = resp.result.unwrap()["tools"].as_array().unwrap().clone();
607        assert_eq!(tools.len(), 2);
608        assert_eq!(tools[0]["name"], "echo");
609        assert_eq!(tools[1]["name"], "add");
610    }
611
612    #[test]
613    fn test_executor_tools_call_echo() {
614        let r = req(br#"{"jsonrpc":"2.0","method":"tools/call","params":{"name":"echo","arguments":{"message":"hello"}},"id":1}"#);
615        let resp = handle_mcp_request_with_executor(&r, &MockExecutor);
616        let text = resp.result.unwrap()["content"][0]["text"]
617            .as_str()
618            .unwrap()
619            .to_string();
620        assert_eq!(text, "hello");
621    }
622
623    #[test]
624    fn test_executor_tools_call_add() {
625        let r = req(br#"{"jsonrpc":"2.0","method":"tools/call","params":{"name":"add","arguments":{"a":3,"b":4}},"id":1}"#);
626        let resp = handle_mcp_request_with_executor(&r, &MockExecutor);
627        let text = resp.result.unwrap()["content"][0]["text"]
628            .as_str()
629            .unwrap()
630            .to_string();
631        assert_eq!(text, "7");
632    }
633
634    #[test]
635    fn test_executor_tools_call_unknown() {
636        let r = req(br#"{"jsonrpc":"2.0","method":"tools/call","params":{"name":"nope","arguments":{}},"id":1}"#);
637        let resp = handle_mcp_request_with_executor(&r, &MockExecutor);
638        let result = resp.result.unwrap();
639        assert_eq!(result["isError"], true);
640        assert!(result["content"][0]["text"]
641            .as_str()
642            .unwrap()
643            .contains("Unknown tool"));
644    }
645
646    #[test]
647    fn test_executor_tools_call_missing_name() {
648        let r = req(br#"{"jsonrpc":"2.0","method":"tools/call","params":{"arguments":{}},"id":1}"#);
649        let resp = handle_mcp_request_with_executor(&r, &MockExecutor);
650        assert!(resp.error.is_some());
651        assert_eq!(resp.error.unwrap().code, -32602);
652    }
653
654    #[test]
655    fn test_preserves_request_id() {
656        let r = req(br#"{"jsonrpc":"2.0","method":"tools/call","params":{"name":"echo","arguments":{"message":"x"}},"id":42}"#);
657        let resp = handle_mcp_request_with_executor(&r, &MockExecutor);
658        assert_eq!(resp.id, Some(serde_json::json!(42)));
659    }
660
661    // -- resources --
662
663    #[test]
664    fn test_resources_list_empty() {
665        let r = req(br#"{"jsonrpc":"2.0","method":"resources/list","params":{},"id":1}"#);
666        let resp = handle_mcp_request(&r);
667        let resources = resp.result.unwrap()["resources"]
668            .as_array()
669            .unwrap()
670            .clone();
671        assert!(resources.is_empty());
672    }
673
674    #[test]
675    fn test_resources_read_missing_uri() {
676        let r = req(br#"{"jsonrpc":"2.0","method":"resources/read","params":{},"id":1}"#);
677        let resp = handle_mcp_request(&r);
678        assert!(resp.error.is_some());
679        assert_eq!(resp.error.unwrap().code, -32602);
680    }
681
682    #[test]
683    fn test_resources_read_unknown_uri() {
684        let r = req(br#"{"jsonrpc":"2.0","method":"resources/read","params":{"uri":"file:///nonexistent"},"id":1}"#);
685        let resp = handle_mcp_request(&r);
686        assert!(resp.error.is_some());
687        assert_eq!(resp.error.unwrap().code, -32001);
688    }
689
690    #[test]
691    fn test_resources_templates_list_empty() {
692        let r = req(br#"{"jsonrpc":"2.0","method":"resources/templates/list","params":{},"id":1}"#);
693        let resp = handle_mcp_request(&r);
694        let templates = resp.result.unwrap()["resourceTemplates"]
695            .as_array()
696            .unwrap()
697            .clone();
698        assert!(templates.is_empty());
699    }
700
701    // -- prompts --
702
703    #[test]
704    fn test_prompts_list_empty() {
705        let r = req(br#"{"jsonrpc":"2.0","method":"prompts/list","params":{},"id":1}"#);
706        let resp = handle_mcp_request(&r);
707        let prompts = resp.result.unwrap()["prompts"].as_array().unwrap().clone();
708        assert!(prompts.is_empty());
709    }
710
711    #[test]
712    fn test_prompts_get_missing_name() {
713        let r = req(br#"{"jsonrpc":"2.0","method":"prompts/get","params":{},"id":1}"#);
714        let resp = handle_mcp_request(&r);
715        assert!(resp.error.is_some());
716        assert_eq!(resp.error.unwrap().code, -32602);
717    }
718
719    #[test]
720    fn test_prompts_get_unknown() {
721        let r = req(
722            br#"{"jsonrpc":"2.0","method":"prompts/get","params":{"name":"nonexistent"},"id":1}"#,
723        );
724        let resp = handle_mcp_request(&r);
725        assert!(resp.error.is_some());
726        assert_eq!(resp.error.unwrap().code, -32001);
727    }
728
729    // -- client-direction methods --
730
731    /// `elicitation/create`, `roots/list` and `sampling/createMessage` are requests
732    /// the server sends *to* a client, so an inbound one names a method this server
733    /// does not serve. Each case below is a request the old dispatch table answered
734    /// — two of them with valid params, one designed to trip param validation — so
735    /// the refusal must not depend on the params.
736    #[test]
737    fn test_client_direction_methods_are_refused() {
738        let cases = [
739            r#"{"jsonrpc":"2.0","method":"elicitation/create","params":{"message":"Confirm?"},"id":1}"#,
740            r#"{"jsonrpc":"2.0","method":"elicitation/create","params":{},"id":2}"#,
741            r#"{"jsonrpc":"2.0","method":"elicitation/create","params":{"message":"Pick","requestedSchema":"not-an-object"},"id":3}"#,
742            r#"{"jsonrpc":"2.0","method":"roots/list","params":{},"id":4}"#,
743            r#"{"jsonrpc":"2.0","method":"sampling/createMessage","params":{"messages":[],"maxTokens":100},"id":5}"#,
744        ];
745        for raw in cases {
746            let resp = handle_mcp_request(&req(raw.as_bytes()));
747            assert!(
748                resp.result.is_none(),
749                "{raw} was answered: {:?}",
750                resp.result
751            );
752            let err = resp
753                .error
754                .unwrap_or_else(|| panic!("{raw} returned neither result nor error"));
755            assert_eq!(err.code, -32601, "wrong code for {raw}");
756        }
757    }
758
759    // -- completion --
760
761    #[test]
762    fn test_completion_complete_valid_prompt_ref() {
763        let r = req(
764            br#"{"jsonrpc":"2.0","method":"completion/complete","params":{"ref":{"type":"ref/prompt","name":"test"},"argument":{"name":"arg","value":"par"}},"id":1}"#,
765        );
766        let resp = handle_mcp_request(&r);
767        let result = resp.result.unwrap();
768        let values = result["completion"]["values"].as_array().unwrap();
769        assert!(values.is_empty());
770        assert_eq!(result["completion"]["hasMore"], false);
771    }
772
773    #[test]
774    fn test_completion_complete_valid_resource_ref() {
775        let r = req(
776            br#"{"jsonrpc":"2.0","method":"completion/complete","params":{"ref":{"type":"ref/resource","uri":"file:///test"},"argument":{"name":"path","value":"/"}},"id":1}"#,
777        );
778        let resp = handle_mcp_request(&r);
779        assert!(resp.result.is_some());
780    }
781
782    #[test]
783    fn test_completion_complete_missing_ref_type() {
784        let r = req(
785            br#"{"jsonrpc":"2.0","method":"completion/complete","params":{"ref":{},"argument":{"name":"x"}},"id":1}"#,
786        );
787        let resp = handle_mcp_request(&r);
788        assert!(resp.error.is_some());
789        assert_eq!(resp.error.unwrap().code, -32602);
790    }
791
792    #[test]
793    fn test_completion_complete_invalid_ref_type() {
794        let r = req(
795            br#"{"jsonrpc":"2.0","method":"completion/complete","params":{"ref":{"type":"ref/tool"},"argument":{"name":"x"}},"id":1}"#,
796        );
797        let resp = handle_mcp_request(&r);
798        assert!(resp.error.is_some());
799        assert_eq!(resp.error.unwrap().code, -32602);
800    }
801
802    #[test]
803    fn test_completion_complete_missing_argument_name() {
804        let r = req(
805            br#"{"jsonrpc":"2.0","method":"completion/complete","params":{"ref":{"type":"ref/prompt","name":"x"},"argument":{}},"id":1}"#,
806        );
807        let resp = handle_mcp_request(&r);
808        assert!(resp.error.is_some());
809        assert_eq!(resp.error.unwrap().code, -32602);
810    }
811
812    // -- unknown method --
813
814    #[test]
815    fn test_unknown_method() {
816        let r = req(br#"{"jsonrpc":"2.0","method":"foo/bar","id":1}"#);
817        let resp = handle_mcp_request(&r);
818        assert!(resp.error.is_some());
819        assert_eq!(resp.error.unwrap().code, -32601);
820    }
821
822    // -- invalid request (JSON-RPC 2.0 structural validation) --
823
824    #[test]
825    fn test_missing_method_is_invalid_request() {
826        let r = req(br#"{"jsonrpc":"2.0","id":1}"#);
827        let resp = handle_mcp_request(&r);
828        assert_eq!(resp.error.as_ref().map(|e| e.code), Some(-32600));
829    }
830
831    #[test]
832    fn test_bad_jsonrpc_version_is_invalid_request() {
833        let r = req(br#"{"jsonrpc":"1.0","method":"ping","id":7}"#);
834        let resp = handle_mcp_request(&r);
835        assert_eq!(resp.error.as_ref().map(|e| e.code), Some(-32600));
836        assert_eq!(resp.id, Some(Value::from(7)));
837    }
838
839    // -- serialization round-trip --
840
841    #[test]
842    fn test_parse_and_serialize_round_trip() {
843        let input = br#"{"jsonrpc":"2.0","method":"ping","id":1}"#;
844        let request = parse_request(input).unwrap();
845        let response = handle_mcp_request(&request);
846        let bytes = serialize_response(&response);
847        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
848        assert_eq!(parsed["jsonrpc"], "2.0");
849        assert_eq!(parsed["result"]["status"], "ok");
850    }
851}