fastmcp-rust 0.3.1

Fast, cancel-correct MCP framework for Rust
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Assertion helpers for testing JSON-RPC and MCP compliance.
//!
//! Provides convenient assertion functions for validating protocol messages.

use fastmcp_protocol::{JSONRPC_VERSION, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse};

/// Validates that a JSON-RPC message is well-formed.
///
/// Checks:
/// - `jsonrpc` field is "2.0"
/// - Request has required fields (method)
/// - Response has either result or error (not both)
///
/// # Panics
///
/// Panics if the message is malformed.
///
/// # Example
///
/// ```ignore
/// let request = JsonRpcRequest::new("test", None, 1i64);
/// assert_json_rpc_valid(&JsonRpcMessage::Request(request));
/// ```
pub fn assert_json_rpc_valid(message: &JsonRpcMessage) {
    match message {
        JsonRpcMessage::Request(req) => {
            assert_eq!(
                req.jsonrpc.as_ref(),
                JSONRPC_VERSION,
                "JSON-RPC version must be 2.0"
            );
            assert!(
                !req.method.is_empty(),
                "JSON-RPC request must have a method"
            );
        }
        JsonRpcMessage::Response(resp) => {
            assert_eq!(
                resp.jsonrpc.as_ref(),
                JSONRPC_VERSION,
                "JSON-RPC version must be 2.0"
            );
            // Response must have either result or error, not both
            let has_result = resp.result.is_some();
            let has_error = resp.error.is_some();
            assert!(
                has_result || has_error,
                "JSON-RPC response must have either result or error"
            );
            assert!(
                !(has_result && has_error),
                "JSON-RPC response cannot have both result and error"
            );
        }
    }
}

/// Validates that a JSON-RPC response indicates success.
///
/// # Panics
///
/// Panics if the response has an error.
///
/// # Example
///
/// ```ignore
/// let response = JsonRpcResponse::success(RequestId::Number(1), json!({}));
/// assert_json_rpc_success(&response);
/// ```
pub fn assert_json_rpc_success(response: &JsonRpcResponse) {
    assert!(
        response.error.is_none(),
        "Expected success response but got error: {:?}",
        response.error
    );
    assert!(
        response.result.is_some(),
        "Success response must have a result"
    );
}

/// Validates that a JSON-RPC response indicates an error.
///
/// # Arguments
///
/// * `response` - The response to validate
/// * `expected_code` - Optional expected error code
///
/// # Panics
///
/// Panics if the response is successful or has wrong error code.
///
/// # Example
///
/// ```ignore
/// let response = JsonRpcResponse::error(
///     Some(RequestId::Number(1)),
///     McpError::method_not_found("unknown").into(),
/// );
/// assert_json_rpc_error(&response, Some(-32601));
/// ```
pub fn assert_json_rpc_error(response: &JsonRpcResponse, expected_code: Option<i32>) {
    assert!(
        response.error.is_some(),
        "Expected error response but got success"
    );
    assert!(
        response.result.is_none(),
        "Error response should not have a result"
    );

    if let Some(expected) = expected_code {
        let actual = response.error.as_ref().unwrap().code;
        assert_eq!(
            actual, expected,
            "Expected error code {expected} but got {actual}"
        );
    }
}

/// Validates that an MCP response is compliant with the protocol.
///
/// Checks JSON-RPC validity plus MCP-specific constraints:
/// - Successful initialize response has required fields
/// - Tool list response has tools array
/// - Resource list response has resources array
/// - etc.
///
/// # Arguments
///
/// * `method` - The MCP method that was called
/// * `response` - The response to validate
///
/// # Panics
///
/// Panics if the response is not MCP-compliant.
///
/// # Example
///
/// ```ignore
/// let response = JsonRpcResponse::success(
///     RequestId::Number(1),
///     json!({"tools": []}),
/// );
/// assert_mcp_compliant("tools/list", &response);
/// ```
pub fn assert_mcp_compliant(method: &str, response: &JsonRpcResponse) {
    // First validate JSON-RPC structure
    assert_json_rpc_valid(&JsonRpcMessage::Response(response.clone()));

    // If it's an error, no further MCP validation needed
    if response.error.is_some() {
        return;
    }

    let result = response.result.as_ref().expect("Response must have result");

    // Method-specific validation
    match method {
        "initialize" => {
            assert!(
                result.get("protocolVersion").is_some(),
                "Initialize response must have protocolVersion"
            );
            assert!(
                result.get("capabilities").is_some(),
                "Initialize response must have capabilities"
            );
            assert!(
                result.get("serverInfo").is_some(),
                "Initialize response must have serverInfo"
            );
        }
        "tools/list" => {
            assert!(
                result.get("tools").is_some(),
                "tools/list response must have tools array"
            );
            assert!(result["tools"].is_array(), "tools must be an array");
        }
        "tools/call" => {
            assert!(
                result.get("content").is_some(),
                "tools/call response must have content"
            );
            assert!(result["content"].is_array(), "content must be an array");
        }
        "resources/list" => {
            assert!(
                result.get("resources").is_some(),
                "resources/list response must have resources array"
            );
            assert!(result["resources"].is_array(), "resources must be an array");
        }
        "resources/read" => {
            assert!(
                result.get("contents").is_some(),
                "resources/read response must have contents"
            );
            assert!(result["contents"].is_array(), "contents must be an array");
        }
        "resources/templates/list" => {
            assert!(
                result.get("resourceTemplates").is_some(),
                "resources/templates/list response must have resourceTemplates"
            );
            assert!(
                result["resourceTemplates"].is_array(),
                "resourceTemplates must be an array"
            );
        }
        "prompts/list" => {
            assert!(
                result.get("prompts").is_some(),
                "prompts/list response must have prompts array"
            );
            assert!(result["prompts"].is_array(), "prompts must be an array");
        }
        "prompts/get" => {
            assert!(
                result.get("messages").is_some(),
                "prompts/get response must have messages"
            );
            assert!(result["messages"].is_array(), "messages must be an array");
        }
        _ => {
            // Unknown method - just verify it's valid JSON
        }
    }
}

/// Validates that a tool definition is MCP-compliant.
///
/// # Panics
///
/// Panics if the tool is malformed.
pub fn assert_tool_valid(tool: &serde_json::Value) {
    assert!(tool.get("name").is_some(), "Tool must have a name");
    assert!(tool["name"].is_string(), "Tool name must be a string");
    // inputSchema is optional but if present must be an object
    if let Some(schema) = tool.get("inputSchema") {
        assert!(schema.is_object(), "inputSchema must be an object");
    }
}

/// Validates that a resource definition is MCP-compliant.
///
/// # Panics
///
/// Panics if the resource is malformed.
pub fn assert_resource_valid(resource: &serde_json::Value) {
    assert!(resource.get("uri").is_some(), "Resource must have a uri");
    assert!(resource["uri"].is_string(), "Resource uri must be a string");
    assert!(resource.get("name").is_some(), "Resource must have a name");
    assert!(
        resource["name"].is_string(),
        "Resource name must be a string"
    );
}

/// Validates that a prompt definition is MCP-compliant.
///
/// # Panics
///
/// Panics if the prompt is malformed.
pub fn assert_prompt_valid(prompt: &serde_json::Value) {
    assert!(prompt.get("name").is_some(), "Prompt must have a name");
    assert!(prompt["name"].is_string(), "Prompt name must be a string");
}

/// Validates that content is MCP-compliant.
///
/// # Panics
///
/// Panics if the content is malformed.
pub fn assert_content_valid(content: &serde_json::Value) {
    assert!(content.get("type").is_some(), "Content must have a type");
    let content_type = content["type"].as_str().expect("type must be a string");
    match content_type {
        "text" => {
            assert!(
                content.get("text").is_some(),
                "Text content must have text field"
            );
        }
        "image" => {
            assert!(
                content.get("data").is_some(),
                "Image content must have data field"
            );
            assert!(
                content.get("mimeType").is_some(),
                "Image content must have mimeType field"
            );
        }
        "audio" => {
            assert!(
                content.get("data").is_some(),
                "Audio content must have data field"
            );
            assert!(
                content.get("mimeType").is_some(),
                "Audio content must have mimeType field"
            );
        }
        "resource" => {
            assert!(
                content.get("resource").is_some(),
                "Resource content must have resource field"
            );
        }
        _ => {
            // Unknown content type - allow for extensibility
        }
    }
}

/// Validates that a JSON-RPC request is a valid notification.
///
/// A notification has no `id` field.
///
/// # Panics
///
/// Panics if the request is not a notification.
pub fn assert_is_notification(request: &JsonRpcRequest) {
    assert!(
        request.id.is_none(),
        "Notification must not have an id field"
    );
}

/// Validates that a JSON-RPC request is a valid request (not notification).
///
/// A request has an `id` field.
///
/// # Panics
///
/// Panics if the request is a notification.
pub fn assert_is_request(request: &JsonRpcRequest) {
    assert!(request.id.is_some(), "Request must have an id field");
}

#[cfg(test)]
mod tests {
    use super::*;
    use fastmcp_protocol::RequestId;

    #[test]
    fn test_valid_request() {
        let request = JsonRpcRequest::new("test/method", None, 1i64);
        assert_json_rpc_valid(&JsonRpcMessage::Request(request));
    }

    #[test]
    fn test_valid_success_response() {
        let response = JsonRpcResponse::success(RequestId::Number(1), serde_json::json!({}));
        assert_json_rpc_valid(&JsonRpcMessage::Response(response.clone()));
        assert_json_rpc_success(&response);
    }

    #[test]
    fn test_valid_error_response() {
        let error = fastmcp_protocol::JsonRpcError {
            code: -32601,
            message: "Method not found".to_string(),
            data: None,
        };
        let response = JsonRpcResponse {
            jsonrpc: std::borrow::Cow::Borrowed(JSONRPC_VERSION),
            id: Some(RequestId::Number(1)),
            result: None,
            error: Some(error),
        };
        assert_json_rpc_valid(&JsonRpcMessage::Response(response.clone()));
        assert_json_rpc_error(&response, Some(-32601));
    }

    #[test]
    fn test_mcp_compliant_tools_list() {
        let response = JsonRpcResponse::success(
            RequestId::Number(1),
            serde_json::json!({
                "tools": []
            }),
        );
        assert_mcp_compliant("tools/list", &response);
    }

    #[test]
    fn test_mcp_compliant_initialize() {
        let response = JsonRpcResponse::success(
            RequestId::Number(1),
            serde_json::json!({
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "serverInfo": {
                    "name": "test",
                    "version": "1.0"
                }
            }),
        );
        assert_mcp_compliant("initialize", &response);
    }

    #[test]
    fn test_valid_tool() {
        let tool = serde_json::json!({
            "name": "my_tool",
            "description": "A test tool",
            "inputSchema": {
                "type": "object"
            }
        });
        assert_tool_valid(&tool);
    }

    #[test]
    fn test_valid_resource() {
        let resource = serde_json::json!({
            "uri": "file:///test.txt",
            "name": "Test File"
        });
        assert_resource_valid(&resource);
    }

    #[test]
    fn test_valid_prompt() {
        let prompt = serde_json::json!({
            "name": "greeting",
            "description": "A greeting prompt"
        });
        assert_prompt_valid(&prompt);
    }

    #[test]
    fn test_valid_text_content() {
        let content = serde_json::json!({
            "type": "text",
            "text": "Hello, world!"
        });
        assert_content_valid(&content);
    }

    #[test]
    fn test_is_notification() {
        let notification = JsonRpcRequest::notification("test", None);
        assert_is_notification(&notification);
    }

    #[test]
    fn test_is_request() {
        let request = JsonRpcRequest::new("test", None, 1i64);
        assert_is_request(&request);
    }

    // =========================================================================
    // Additional coverage tests (bd-1fnm)
    // =========================================================================

    #[test]
    fn error_response_without_expected_code() {
        let error = fastmcp_protocol::JsonRpcError {
            code: -32600,
            message: "Invalid request".to_string(),
            data: None,
        };
        let response = JsonRpcResponse {
            jsonrpc: std::borrow::Cow::Borrowed(JSONRPC_VERSION),
            id: Some(RequestId::Number(1)),
            result: None,
            error: Some(error),
        };
        // None code means we only check that it IS an error, not the code value
        assert_json_rpc_error(&response, None);
    }

    #[test]
    fn mcp_compliant_tools_call() {
        let response = JsonRpcResponse::success(
            RequestId::Number(1),
            serde_json::json!({ "content": [{"type": "text", "text": "hello"}] }),
        );
        assert_mcp_compliant("tools/call", &response);
    }

    #[test]
    fn mcp_compliant_resources_list() {
        let response =
            JsonRpcResponse::success(RequestId::Number(1), serde_json::json!({ "resources": [] }));
        assert_mcp_compliant("resources/list", &response);
    }

    #[test]
    fn mcp_compliant_resources_read() {
        let response = JsonRpcResponse::success(
            RequestId::Number(1),
            serde_json::json!({ "contents": [{"uri": "file:///a", "text": "data"}] }),
        );
        assert_mcp_compliant("resources/read", &response);
    }

    #[test]
    fn mcp_compliant_resource_templates_list() {
        let response = JsonRpcResponse::success(
            RequestId::Number(1),
            serde_json::json!({ "resourceTemplates": [] }),
        );
        assert_mcp_compliant("resources/templates/list", &response);
    }

    #[test]
    fn mcp_compliant_prompts_list() {
        let response =
            JsonRpcResponse::success(RequestId::Number(1), serde_json::json!({ "prompts": [] }));
        assert_mcp_compliant("prompts/list", &response);
    }

    #[test]
    fn mcp_compliant_prompts_get() {
        let response = JsonRpcResponse::success(
            RequestId::Number(1),
            serde_json::json!({ "messages": [{"role": "user", "content": {}}] }),
        );
        assert_mcp_compliant("prompts/get", &response);
    }

    #[test]
    fn mcp_compliant_error_response_early_return() {
        let error = fastmcp_protocol::JsonRpcError {
            code: -32601,
            message: "Method not found".to_string(),
            data: None,
        };
        let response = JsonRpcResponse {
            jsonrpc: std::borrow::Cow::Borrowed(JSONRPC_VERSION),
            id: Some(RequestId::Number(1)),
            result: None,
            error: Some(error),
        };
        // Error responses skip MCP-specific checks and return early
        assert_mcp_compliant("tools/list", &response);
    }

    #[test]
    fn mcp_compliant_unknown_method() {
        let response = JsonRpcResponse::success(
            RequestId::Number(1),
            serde_json::json!({ "anything": true }),
        );
        // Unknown methods only get JSON-RPC validation
        assert_mcp_compliant("custom/method", &response);
    }

    #[test]
    fn content_valid_image() {
        let content = serde_json::json!({
            "type": "image",
            "data": "base64data",
            "mimeType": "image/png"
        });
        assert_content_valid(&content);
    }

    #[test]
    fn content_valid_audio() {
        let content = serde_json::json!({
            "type": "audio",
            "data": "base64data",
            "mimeType": "audio/wav"
        });
        assert_content_valid(&content);
    }

    #[test]
    fn content_valid_resource() {
        let content = serde_json::json!({
            "type": "resource",
            "resource": { "uri": "file:///test.txt", "text": "data" }
        });
        assert_content_valid(&content);
    }

    #[test]
    fn content_valid_unknown_type() {
        let content = serde_json::json!({
            "type": "custom_extension",
            "data": "whatever"
        });
        // Unknown types pass for extensibility
        assert_content_valid(&content);
    }

    #[test]
    fn tool_valid_without_input_schema() {
        let tool = serde_json::json!({
            "name": "simple_tool"
        });
        // inputSchema is optional
        assert_tool_valid(&tool);
    }
}