sdforge 0.3.0

Multi-protocol SDK framework with unified macro configuration
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! MCP protocol comprehensive tests
//!
//! This module provides comprehensive external integration tests for the MCP module,
//! focusing on:
//! - get_mcp_tools() function behavior
//! - McpToolInstance accessor methods
//! - Edge cases not covered by internal tests
//! - Concurrent tool execution scenarios

#[cfg(feature = "mcp")]
mod mcp_comprehensive_tests {
    use rmcp::model::{CallToolResult, ContentBlock, ErrorData as McpError};
    use sdforge::core::ApiMetadata;
    use sdforge::mcp::{get_mcp_tools, McpToolRegistration, SdForgeTool};
    use std::sync::Arc;
    use std::thread;

    // ============================================================================
    // Helper Functions
    // ============================================================================

    fn create_simple_tool(name: &str) -> Arc<dyn SdForgeTool> {
        struct SimpleTool {
            name: String,
            description: String,
        }

        impl SdForgeTool for SimpleTool {
            fn name(&self) -> &str {
                &self.name
            }

            fn description(&self) -> &str {
                &self.description
            }

            fn input_schema(&self) -> serde_json::Value {
                serde_json::json!({"type": "object"})
            }

            fn call(
                &self,
                _input: Option<serde_json::Value>,
            ) -> Result<CallToolResult, McpError> {
                Ok({
                    let mut result = CallToolResult::success(vec![]);
                    result.is_error = None;
                    result
                })
            }
        }

        Arc::new(SimpleTool {
            name: name.to_string(),
            description: format!("Test tool: {}", name),
        }) as Arc<dyn SdForgeTool>
    }

    fn create_echo_tool() -> Arc<dyn SdForgeTool> {
        struct EchoTool;

        impl SdForgeTool for EchoTool {
            fn name(&self) -> &str {
                "echo"
            }

            fn description(&self) -> &str {
                "Echoes input back as response"
            }

            fn input_schema(&self) -> serde_json::Value {
                serde_json::json!({
                    "type": "object",
                    "properties": {
                        "message": {"type": "string"}
                    }
                })
            }

            fn call(
                &self,
                input: Option<serde_json::Value>,
            ) -> Result<CallToolResult, McpError> {
                let text = input
                    .and_then(|v| v.get("message").and_then(|m| m.as_str()).map(|s| s.to_string()))
                    .unwrap_or_default();

                Ok(CallToolResult::success(vec![ContentBlock::text(text)]))
            }
        }

        Arc::new(EchoTool) as Arc<dyn SdForgeTool>
    }

    fn create_math_tool() -> Arc<dyn SdForgeTool> {
        struct MathTool;

        impl SdForgeTool for MathTool {
            fn name(&self) -> &str {
                "math"
            }

            fn description(&self) -> &str {
                "Performs basic arithmetic"
            }

            fn input_schema(&self) -> serde_json::Value {
                serde_json::json!({
                    "type": "object",
                    "properties": {
                        "a": {"type": "number"},
                        "b": {"type": "number"},
                        "operation": {"type": "string", "enum": ["add", "subtract", "multiply"]}
                    },
                    "required": ["a", "b", "operation"]
                })
            }

            fn call(
                &self,
                input: Option<serde_json::Value>,
            ) -> Result<CallToolResult, McpError> {
                let val = input.ok_or_else(|| McpError::invalid_params("Input required", None))?;
                let a = val
                    .get("a")
                    .and_then(|v| v.as_f64())
                    .ok_or_else(|| McpError::invalid_params("Missing 'a'", None))?;
                let b = val
                    .get("b")
                    .and_then(|v| v.as_f64())
                    .ok_or_else(|| McpError::invalid_params("Missing 'b'", None))?;
                let op = val
                    .get("operation")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| McpError::invalid_params("Missing 'operation'", None))?;

                let result = match op {
                    "add" => a + b,
                    "subtract" => a - b,
                    "multiply" => a * b,
                    _ => {
                        return Err(McpError::invalid_params(
                            format!("Unknown operation: {}", op),
                            None,
                        ))
                    }
                };

                Ok(CallToolResult::success(vec![ContentBlock::text(
                    result.to_string(),
                )]))
            }
        }

        Arc::new(MathTool) as Arc<dyn SdForgeTool>
    }

    fn create_error_tool() -> Arc<dyn SdForgeTool> {
        struct ErrorTool;

        impl SdForgeTool for ErrorTool {
            fn name(&self) -> &str {
                "error_tool"
            }

            fn description(&self) -> &str {
                "Always returns an error"
            }

            fn input_schema(&self) -> serde_json::Value {
                serde_json::json!({"type": "object"})
            }

            fn call(
                &self,
                _input: Option<serde_json::Value>,
            ) -> Result<CallToolResult, McpError> {
                Err(McpError::invalid_params("Intentional test error", None))
            }
        }

        Arc::new(ErrorTool) as Arc<dyn SdForgeTool>
    }

    fn create_complex_schema_tool() -> Arc<dyn SdForgeTool> {
        struct ComplexSchemaTool;

        impl SdForgeTool for ComplexSchemaTool {
            fn name(&self) -> &str {
                "complex_schema"
            }

            fn description(&self) -> &str {
                "Tool with complex nested schema"
            }

            fn input_schema(&self) -> serde_json::Value {
                serde_json::json!({
                    "type": "object",
                    "properties": {
                        "user": {
                            "type": "object",
                            "properties": {
                                "name": {"type": "string"},
                                "age": {"type": "integer", "minimum": 0},
                                "address": {
                                    "type": "object",
                                    "properties": {
                                        "street": {"type": "string"},
                                        "city": {"type": "string"},
                                        "country": {"type": "string"}
                                    }
                                }
                            },
                            "required": ["name"]
                        },
                        "tags": {
                            "type": "array",
                            "items": {"type": "string"}
                        }
                    },
                    "required": ["user"]
                })
            }

            fn call(
                &self,
                _input: Option<serde_json::Value>,
            ) -> Result<CallToolResult, McpError> {
                Ok({
                    let mut result = CallToolResult::success(vec![]);
                    result.is_error = None;
                    result
                })
            }
        }

        Arc::new(ComplexSchemaTool) as Arc<dyn SdForgeTool>
    }

    // ============================================================================
    // get_mcp_tools() Function Tests
    // ============================================================================

    /// Test that get_mcp_tools returns a vector (may be empty if no tools registered)
    #[test]
    fn test_get_mcp_tools_returns_vector() {
        let tools = get_mcp_tools();
        assert!(!tools.is_empty() || tools.is_empty());
    }

    /// Test that get_mcp_tools can be called multiple times
    #[test]
    fn test_get_mcp_tools_idempotent() {
        let tools1 = get_mcp_tools();
        let tools2 = get_mcp_tools();

        // Both calls should return vectors of the same length
        assert_eq!(tools1.len(), tools2.len());
    }

    /// Test that get_mcp_tools returns properly structured instances
    #[test]
    fn test_get_mcp_tools_instance_structure() {
        let tools = get_mcp_tools();

        for instance in tools {
            // Each instance should have valid tool and metadata
            let _ = instance.tool();
            let _ = instance.metadata();
        }
    }

    // ============================================================================
    // McpToolInstance Accessor Tests (via get_mcp_tools)
    // ============================================================================

    #[test]
    fn test_mcp_tool_instance_tool_accessor() {
        let tools = get_mcp_tools();
        for instance in tools {
            let tool = instance.tool();
            assert!(!tool.name().is_empty() || tool.name().is_empty());
        }
    }

    #[test]
    fn test_mcp_tool_instance_metadata_accessor() {
        let tools = get_mcp_tools();
        for instance in tools {
            let metadata = instance.metadata();
            assert!(!metadata.name().is_empty() || metadata.name().is_empty());
        }
    }

    #[test]
    fn test_mcp_tool_instance_tool_arc_clone() {
        let tools = get_mcp_tools();
        for instance in tools {
            let tool1 = instance.tool().clone();
            let tool2 = instance.tool().clone();
            assert_eq!(tool1.name(), tool2.name());
        }
    }

    #[test]
    fn test_mcp_tool_instance_metadata_variations() {
        let tools = get_mcp_tools();
        for instance in tools {
            let _ = instance.metadata().cache_ttl();
            let _ = instance.metadata().is_streaming();
        }
    }

    // ============================================================================
    // Edge Case Tests - Tool Behavior
    // ============================================================================

    #[test]
    fn test_tool_with_empty_name() {
        let tool = create_simple_tool("");
        assert_eq!(tool.name(), "");
    }

    #[test]
    fn test_tool_with_special_characters() {
        let tool = create_simple_tool("tool-with_special.chars:v2");
        assert_eq!(tool.name(), "tool-with_special.chars:v2");
    }

    #[test]
    fn test_tool_with_unicode_description() {
        let tool = create_simple_tool("unicode_tool");
        assert!(tool
            .description()
            .contains(&format!("Test tool: {}", "unicode_tool")));
    }

    #[test]
    fn test_tool_with_long_name() {
        let long_name = "a".repeat(1000);
        let tool = create_simple_tool(&long_name);
        assert_eq!(tool.name().len(), 1000);
    }

    #[test]
    fn test_tool_versions() {
        let versions = ["v1", "v2.0", "1.0.0", "beta", "2024-01-01", ""];
        for version in versions {
            let reg = McpToolRegistration::new(
                "version_test",
                version,
                || create_simple_tool("version_test"),
                || ApiMetadata::default(),
            );
            let _ = reg;
        }
    }

    // ============================================================================
    // Tool Execution Tests
    // ============================================================================

    /// Test echo tool with valid input
    #[test]
    fn test_echo_tool_execution() {
        let tool = create_echo_tool();
        let input = serde_json::json!({"message": "Hello, World!"});

        let result = tool.call(Some(input));
        assert!(result.is_ok());

        let response = result.unwrap();
        assert!(!response.content.is_empty());
    }

    /// Test math tool with valid inputs
    #[test]
    fn test_math_tool_addition() {
        let tool = create_math_tool();
        let input = serde_json::json!({"a": 5, "b": 3, "operation": "add"});

        let result = tool.call(Some(input));
        assert!(result.is_ok());
    }

    /// Test math tool with subtraction
    #[test]
    fn test_math_tool_subtraction() {
        let tool = create_math_tool();
        let input = serde_json::json!({"a": 10, "b": 4, "operation": "subtract"});

        let result = tool.call(Some(input));
        assert!(result.is_ok());
    }

    /// Test math tool with multiplication
    #[test]
    fn test_math_tool_multiplication() {
        let tool = create_math_tool();
        let input = serde_json::json!({"a": 6, "b": 7, "operation": "multiply"});

        let result = tool.call(Some(input));
        assert!(result.is_ok());
    }

    /// Test error tool returns error
    #[test]
    fn test_error_tool_returns_error() {
        let tool = create_error_tool();
        let result = tool.call(None);

        assert!(result.is_err());
    }

    /// Test complex schema tool returns valid schema
    #[test]
    fn test_complex_schema_tool_schema() {
        let tool = create_complex_schema_tool();
        let schema = tool.input_schema();

        assert!(schema.get("properties").is_some());
        assert!(schema["properties"].get("user").is_some());
        assert!(schema["properties"]["user"]["properties"]
            .get("address")
            .is_some());
    }

    /// Test tool call with missing required field
    #[test]
    fn test_tool_call_missing_required_field() {
        let tool = create_math_tool();
        let input = serde_json::json!({"a": 5}); // Missing 'b' and 'operation'

        let result = tool.call(Some(input));
        assert!(result.is_err());
    }

    /// Test tool call with invalid operation
    #[test]
    fn test_tool_call_invalid_operation() {
        let tool = create_math_tool();
        let input = serde_json::json!({"a": 5, "b": 3, "operation": "divide"});

        let result = tool.call(Some(input));
        assert!(result.is_err());
    }

    /// Test tool call with no input when required
    #[test]
    fn test_tool_call_no_input_required() {
        let tool = create_math_tool();
        let result = tool.call(None);

        assert!(result.is_err());
    }

    // ============================================================================
    // Concurrent Tool Execution Tests
    // ============================================================================

    /// Test concurrent tool execution with multiple threads
    #[test]
    fn test_concurrent_tool_execution() {
        let tool = Arc::new(create_echo_tool());
        let mut handles = vec![];

        for i in 0..10 {
            let tool_clone = Arc::clone(&tool);
            handles.push(thread::spawn(move || {
                let input = serde_json::json!({"message": format!("Message {}", i)});
                tool_clone.call(Some(input))
            }));
        }

        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        // All executions should succeed
        for result in results {
            assert!(result.is_ok());
        }
    }

    /// Test concurrent get_mcp_tools calls
    #[test]
    fn test_concurrent_get_mcp_tools() {
        let mut handles = vec![];

        for _ in 0..20 {
            handles.push(thread::spawn(|| get_mcp_tools()));
        }

        let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        // All results should have the same length
        let expected_len = results[0].len();
        for result in &results[1..] {
            assert_eq!(result.len(), expected_len);
        }
    }

    #[test]
    fn test_concurrent_tool_instance_creation() {
        let handles: Vec<_> = (0..50)
            .map(|i| thread::spawn(move || create_simple_tool(&format!("concurrent_tool_{}", i))))
            .collect();

        let tools: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        for (i, tool) in tools.iter().enumerate() {
            assert_eq!(tool.name(), format!("concurrent_tool_{}", i));
        }
    }

    #[test]
    fn test_concurrent_metadata_access() {
        let tools = Arc::new(get_mcp_tools());
        let mut handles = vec![];

        for _ in 0..100 {
            let tools_clone = Arc::clone(&tools);
            handles.push(thread::spawn(move || {
                if let Some(instance) = tools_clone.first() {
                    let _ = instance.metadata().name().to_string();
                    let _ = instance.metadata().version().to_string();
                    let _ = instance.metadata().cache_ttl();
                    let _ = instance.metadata().is_streaming();
                }
            }));
        }

        for h in handles {
            let _ = h.join().unwrap();
        }
    }

    /// Test concurrent tool calls with different operations
    #[test]
    fn test_concurrent_math_operations() {
        let tool = Arc::new(create_math_tool());
        let mut handles = vec![];

        let operations = vec![
            ("add", 1.0, 2.0),
            ("subtract", 10.0, 3.0),
            ("multiply", 4.0, 5.0),
        ];

        for (op, a, b) in operations.repeat(5) {
            let tool_clone = Arc::clone(&tool);
            handles.push(thread::spawn(move || {
                let input = serde_json::json!({"a": a, "b": b, "operation": op});
                tool_clone.call(Some(input))
            }));
        }

        for h in handles {
            assert!(h.join().unwrap().is_ok());
        }
    }

    // ============================================================================
    // McpToolRegistration Tests
    // ============================================================================

    /// Test McpToolRegistration creation through new() constructor
    #[test]
    fn test_registration_creation() {
        let _registration = McpToolRegistration::new(
            "test_registration",
            "v1",
            || create_simple_tool("test_registration"),
            || ApiMetadata::default(),
        );
    }

    /// Test McpToolRegistration create_fn execution via tool creation
    #[test]
    fn test_registration_create_fn() {
        let tool = create_echo_tool();
        assert_eq!(tool.name(), "echo");
        assert_eq!(tool.description(), "Echoes input back as response");
    }

    /// Test multiple tool creations can coexist
    #[test]
    fn test_multiple_tool_creations() {
        let tool1 = create_simple_tool("tool_a");
        let tool2 = create_simple_tool("tool_b");

        assert_eq!(tool1.name(), "tool_a");
        assert_eq!(tool2.name(), "tool_b");
    }

    // ============================================================================
    // Response Content Tests
    // ============================================================================

    /// Test tool response with text content
    #[test]
    fn test_tool_response_text_content() {
        let tool = create_echo_tool();
        let input = serde_json::json!({"message": "test"});

        let response = tool.call(Some(input)).unwrap();

        assert!(!response.content.is_empty());
        assert!(matches!(
            response.content.first(),
            Some(rmcp::model::ContentBlock::Text(_))
        ));
    }

    /// Test tool response is_error flag
    #[test]
    fn test_tool_response_error_flag() {
        let tool = create_echo_tool();
        let response = tool.call(None).unwrap();

        // Echo tool should not set is_error flag
        assert!(response.is_error.is_none() || response.is_error == Some(false));
    }

    /// Test tool response meta field
    #[test]
    fn test_tool_response_meta_field() {
        let tool = create_simple_tool("meta_test");
        let response = tool.call(None).unwrap();

        // Default tools don't use meta field
        assert!(response.meta.is_none());
    }

    // ============================================================================
    // Input Schema Tests
    // ============================================================================

    /// Test that input_schema returns valid JSON
    #[test]
    fn test_input_schema_is_valid_json() {
        let tool = create_complex_schema_tool();
        let schema = tool.input_schema();

        // Should be able to serialize and deserialize
        let serialized = serde_json::to_string(&schema).unwrap();
        let _: serde_json::Value = serde_json::from_str(&serialized).unwrap();
    }

    /// Test nested schema properties
    #[test]
    fn test_nested_schema_properties() {
        let tool = create_complex_schema_tool();
        let schema = tool.input_schema();

        // Verify nested structure
        let user_props = &schema["properties"]["user"]["properties"];
        assert!(user_props.get("name").is_some());
        assert!(user_props.get("age").is_some());
        assert!(user_props.get("address").is_some());
    }

    /// Test array type in schema
    #[test]
    fn test_array_type_in_schema() {
        let tool = create_complex_schema_tool();
        let schema = tool.input_schema();

        let tags = &schema["properties"]["tags"];
        assert_eq!(tags["type"], "array");
        assert_eq!(tags["items"]["type"], "string");
    }

    /// Test required fields in schema
    #[test]
    fn test_required_fields_in_schema() {
        let tool = create_complex_schema_tool();
        let schema = tool.input_schema();

        let required = schema.get("required").unwrap().as_array().unwrap();
        assert!(required.contains(&serde_json::json!("user")));
    }
}