server-less 0.6.0

Composable derive macros for common Rust patterns
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
//! Integration tests for the MCP macro.

#![allow(dead_code)]
#![allow(unused_variables)]

use serde::{Deserialize, Serialize};
use server_less::{mcp, server};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct Item {
    id: String,
    name: String,
}

#[derive(Clone)]
struct TestService {
    items: Vec<Item>,
}

#[mcp(namespace = "test")]
impl TestService {
    /// Get all items
    pub fn list_items(&self) -> Vec<Item> {
        self.items.clone()
    }

    /// Get item by ID
    pub fn get_item(&self, item_id: String) -> Option<Item> {
        self.items.iter().find(|i| i.id == item_id).cloned()
    }

    /// Create an item
    pub fn create_item(&self, name: String) -> Item {
        Item {
            id: "new".to_string(),
            name,
        }
    }

    /// Search items with optional limit
    pub fn search_items(&self, query: String, limit: Option<u32>) -> Vec<Item> {
        let limit = limit.unwrap_or(10) as usize;
        self.items
            .iter()
            .filter(|i| i.name.contains(&query))
            .take(limit)
            .cloned()
            .collect()
    }
}

#[test]
fn test_mcp_tools_generated() {
    let tools = TestService::mcp_tools();
    assert_eq!(tools.len(), 4);

    // Check tool names
    let names: Vec<_> = tools
        .iter()
        .map(|t| t.get("name").unwrap().as_str().unwrap())
        .collect();
    assert!(names.contains(&"test_list_items"));
    assert!(names.contains(&"test_get_item"));
    assert!(names.contains(&"test_create_item"));
    assert!(names.contains(&"test_search_items"));
}

#[test]
fn test_mcp_method_names() {
    let names = TestService::mcp_method_names();
    assert_eq!(names.len(), 4);
    assert!(names.contains(&"test_list_items".to_string()));
}

#[test]
fn test_mcp_call_list() {
    let service = TestService {
        items: vec![Item {
            id: "1".to_string(),
            name: "Test".to_string(),
        }],
    };

    let result = service.mcp_call("test_list_items", serde_json::json!({}));
    assert!(result.is_ok());

    let items: Vec<Item> = serde_json::from_value(result.unwrap()).unwrap();
    assert_eq!(items.len(), 1);
    assert_eq!(items[0].name, "Test");
}

#[test]
fn test_mcp_call_get_option() {
    let service = TestService {
        items: vec![Item {
            id: "1".to_string(),
            name: "Test".to_string(),
        }],
    };

    // Found
    let result = service.mcp_call("test_get_item", serde_json::json!({"item_id": "1"}));
    assert!(result.is_ok());
    let item: Item = serde_json::from_value(result.unwrap()).unwrap();
    assert_eq!(item.id, "1");

    // Not found
    let result = service.mcp_call("test_get_item", serde_json::json!({"item_id": "999"}));
    assert!(result.is_ok());
    assert!(result.unwrap().is_null());
}

#[test]
fn test_mcp_call_create() {
    let service = TestService { items: vec![] };

    let result = service.mcp_call("test_create_item", serde_json::json!({"name": "NewItem"}));
    assert!(result.is_ok());

    let item: Item = serde_json::from_value(result.unwrap()).unwrap();
    assert_eq!(item.name, "NewItem");
}

#[test]
fn test_mcp_call_with_optional_param() {
    let service = TestService {
        items: vec![
            Item {
                id: "1".to_string(),
                name: "Apple".to_string(),
            },
            Item {
                id: "2".to_string(),
                name: "Apricot".to_string(),
            },
        ],
    };

    // Without limit
    let result = service.mcp_call("test_search_items", serde_json::json!({"query": "Ap"}));
    assert!(result.is_ok());
    let items: Vec<Item> = serde_json::from_value(result.unwrap()).unwrap();
    assert_eq!(items.len(), 2);

    // With limit
    let result = service.mcp_call(
        "test_search_items",
        serde_json::json!({"query": "Ap", "limit": 1}),
    );
    assert!(result.is_ok());
    let items: Vec<Item> = serde_json::from_value(result.unwrap()).unwrap();
    assert_eq!(items.len(), 1);
}

#[test]
fn test_mcp_call_unknown_tool() {
    let service = TestService { items: vec![] };
    let result = service.mcp_call("unknown_tool", serde_json::json!({}));
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Unknown tool"));
}

#[test]
fn test_mcp_tool_schema() {
    let tools = TestService::mcp_tools();

    // Find create_item tool
    let create_tool = tools
        .iter()
        .find(|t| t.get("name").unwrap() == "test_create_item")
        .unwrap();

    // Check input schema
    let schema = create_tool.get("inputSchema").unwrap();
    assert_eq!(schema.get("type").unwrap(), "object");

    let properties = schema.get("properties").unwrap().as_object().unwrap();
    assert!(properties.contains_key("name"));

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

// ============================================================================
// Async Method Tests
// ============================================================================

/// Service with async methods
#[derive(Clone)]
struct AsyncService;

#[mcp(namespace = "async")]
impl AsyncService {
    /// Sync method - works with both sync and async call
    pub fn sync_add(&self, a: i64, b: i64) -> i64 {
        a + b
    }

    /// Async method - only works with async call
    pub async fn async_fetch(&self, id: String) -> String {
        // Simulate async operation
        format!("Fetched: {}", id)
    }

    /// Another async method
    pub async fn async_compute(&self, n: i64) -> i64 {
        // Simulate async computation
        n * 2
    }
}

#[test]
fn test_mcp_sync_method_with_sync_call() {
    let service = AsyncService;

    // Sync method should work with sync call
    let result = service.mcp_call("async_sync_add", serde_json::json!({"a": 5, "b": 3}));
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!(8));
}

#[test]
fn test_mcp_async_method_with_sync_call_returns_error() {
    let service = AsyncService;

    // Async method should return error with sync call
    let result = service.mcp_call("async_async_fetch", serde_json::json!({"id": "123"}));
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .contains("not supported in sync context")
    );
}

#[tokio::test]
async fn test_mcp_sync_method_with_async_call() {
    let service = AsyncService;

    // Sync method should work with async call
    let result = service
        .mcp_call_async("async_sync_add", serde_json::json!({"a": 10, "b": 7}))
        .await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!(17));
}

#[tokio::test]
async fn test_mcp_async_method_with_async_call() {
    let service = AsyncService;

    // Async method should work with async call
    let result = service
        .mcp_call_async("async_async_fetch", serde_json::json!({"id": "abc"}))
        .await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!("Fetched: abc"));
}

#[tokio::test]
async fn test_mcp_async_compute() {
    let service = AsyncService;

    let result = service
        .mcp_call_async("async_async_compute", serde_json::json!({"n": 21}))
        .await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!(42));
}

// Test streaming support
use futures::stream::{self, Stream};

#[derive(Clone)]
struct StreamService;

#[mcp(namespace = "stream")]
impl StreamService {
    /// Stream a sequence of numbers
    fn stream_numbers(&self, count: u32) -> impl Stream<Item = u32> + use<> {
        stream::iter(0..count)
    }

    /// Stream items with async
    async fn stream_items(&self, prefix: String, count: u32) -> impl Stream<Item = String> + use<> {
        stream::iter((0..count).map(move |i| format!("{}{}", prefix, i)))
    }
}

#[tokio::test]
async fn test_mcp_stream_numbers() {
    let service = StreamService;

    // Streaming method requires async call
    let result = service
        .mcp_call_async("stream_stream_numbers", serde_json::json!({"count": 5}))
        .await;

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!([0, 1, 2, 3, 4]));
}

#[tokio::test]
async fn test_mcp_stream_items() {
    let service = StreamService;

    let result = service
        .mcp_call_async(
            "stream_stream_items",
            serde_json::json!({"prefix": "item-", "count": 3}),
        )
        .await;

    assert!(result.is_ok());
    assert_eq!(
        result.unwrap(),
        serde_json::json!(["item-0", "item-1", "item-2"])
    );
}

#[tokio::test]
async fn test_mcp_stream_with_sync_call_fails() {
    let service = StreamService;

    // Streaming methods should error with sync call
    let result = service.mcp_call("stream_stream_numbers", serde_json::json!({"count": 5}));

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .contains("not supported in sync context")
    );
}

// ============================================================================
// Mount Point Tests
// ============================================================================

/// Child service for mount testing
#[derive(Clone)]
struct UserTools;

#[mcp]
impl UserTools {
    /// List all users
    fn list(&self) -> Vec<String> {
        vec!["alice".to_string(), "bob".to_string()]
    }

    /// Get a user by name
    fn get(&self, name: String) -> String {
        format!("User: {}", name)
    }
}

/// Child service for posts
#[derive(Clone)]
struct PostTools;

#[mcp]
impl PostTools {
    /// List posts
    fn list(&self) -> Vec<String> {
        vec!["post1".to_string()]
    }
}

/// Parent with static mount
#[derive(Clone)]
struct McpApp {
    user_tools: UserTools,
    post_tools: PostTools,
}

#[mcp]
impl McpApp {
    /// Health check
    fn health(&self) -> String {
        "ok".to_string()
    }

    /// Mount user tools
    fn users(&self) -> &UserTools {
        &self.user_tools
    }

    /// Mount post tools
    fn posts(&self) -> &PostTools {
        &self.post_tools
    }
}

#[test]
fn test_mcp_static_mount_tools_listed() {
    let tools = McpApp::mcp_tools();
    let names: Vec<_> = tools
        .iter()
        .map(|t| t.get("name").unwrap().as_str().unwrap().to_string())
        .collect();

    // Leaf method
    assert!(names.contains(&"health".to_string()));
    // Mounted tools (prefixed)
    assert!(names.contains(&"users_list".to_string()));
    assert!(names.contains(&"users_get".to_string()));
    assert!(names.contains(&"posts_list".to_string()));
}

#[test]
fn test_mcp_static_mount_dispatch_sync() {
    let app = McpApp {
        user_tools: UserTools,
        post_tools: PostTools,
    };

    // Dispatch to leaf
    let result = app.mcp_call("health", serde_json::json!({}));
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!("ok"));

    // Dispatch to mounted child
    let result = app.mcp_call("users_list", serde_json::json!({}));
    assert!(result.is_ok());
    let users: Vec<String> = serde_json::from_value(result.unwrap()).unwrap();
    assert_eq!(users, vec!["alice", "bob"]);

    // Dispatch to mounted child with args
    let result = app.mcp_call("users_get", serde_json::json!({"name": "alice"}));
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!("User: alice"));
}

#[tokio::test]
async fn test_mcp_static_mount_dispatch_async() {
    let app = McpApp {
        user_tools: UserTools,
        post_tools: PostTools,
    };

    let result = app
        .mcp_call_async("users_get", serde_json::json!({"name": "bob"}))
        .await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!("User: bob"));
}

#[test]
fn test_mcp_multiple_static_mounts() {
    let app = McpApp {
        user_tools: UserTools,
        post_tools: PostTools,
    };

    // Both mounts work
    assert!(app.mcp_call("users_list", serde_json::json!({})).is_ok());
    assert!(app.mcp_call("posts_list", serde_json::json!({})).is_ok());
}

/// Slug mount: parent with parameterized child
#[derive(Clone)]
struct McpSlugApp {
    user_tools: UserTools,
}

#[mcp]
impl McpSlugApp {
    /// Access a user's tools by ID
    fn user(&self, id: String) -> &UserTools {
        // In real code, id would select a user; for testing we return the same service
        let _ = &id;
        &self.user_tools
    }
}

#[test]
fn test_mcp_slug_mount_tools_have_slug_param() {
    let tools = McpSlugApp::mcp_tools();
    let names: Vec<_> = tools
        .iter()
        .map(|t| t.get("name").unwrap().as_str().unwrap().to_string())
        .collect();

    assert!(names.contains(&"user_list".to_string()));
    assert!(names.contains(&"user_get".to_string()));

    // Check that slug param "id" is in the inputSchema
    let user_list = tools
        .iter()
        .find(|t| t.get("name").unwrap().as_str().unwrap() == "user_list")
        .unwrap();
    let schema = user_list.get("inputSchema").unwrap();
    let props = schema.get("properties").unwrap().as_object().unwrap();
    assert!(props.contains_key("id"));
}

#[test]
fn test_mcp_slug_mount_dispatch() {
    let app = McpSlugApp {
        user_tools: UserTools,
    };

    let result = app.mcp_call("user_list", serde_json::json!({"id": "42"}));
    assert!(result.is_ok());
    let users: Vec<String> = serde_json::from_value(result.unwrap()).unwrap();
    assert_eq!(users, vec!["alice", "bob"]);

    let result = app.mcp_call("user_get", serde_json::json!({"id": "42", "name": "alice"}));
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!("User: alice"));
}

/// McpNamespace trait test
#[test]
fn test_mcp_namespace_trait_implemented() {
    use server_less::McpNamespace;

    let tools = <UserTools as McpNamespace>::mcp_namespace_tools();
    assert_eq!(tools.len(), 2);

    let names = <UserTools as McpNamespace>::mcp_namespace_tool_names();
    assert!(names.contains(&"list".to_string()));
    assert!(names.contains(&"get".to_string()));

    let svc = UserTools;
    let result =
        <UserTools as McpNamespace>::mcp_namespace_call(&svc, "list", serde_json::json!({}));
    assert!(result.is_ok());
}

// ============================================================================
// Hidden Method Tests
// ============================================================================

#[derive(Clone)]
struct HiddenService;

#[mcp]
impl HiddenService {
    /// Public tool
    pub fn public_tool(&self) -> String {
        "public".to_string()
    }

    /// Hidden tool - callable but not listed
    #[server(hidden)]
    pub fn hidden_tool(&self) -> String {
        "hidden".to_string()
    }
}

#[test]
fn test_mcp_hidden_method_not_in_tool_list() {
    let tools = HiddenService::mcp_tools();
    let names: Vec<_> = tools
        .iter()
        .map(|t| t.get("name").unwrap().as_str().unwrap())
        .collect();

    // Public method appears in tool list
    assert!(names.contains(&"public_tool"));
    // Hidden method does NOT appear in tool list
    assert!(!names.contains(&"hidden_tool"));
}

#[test]
fn test_mcp_hidden_method_not_in_tool_names() {
    let names = HiddenService::mcp_method_names();
    assert!(names.contains(&"public_tool".to_string()));
    assert!(!names.contains(&"hidden_tool".to_string()));
}

#[test]
fn test_mcp_hidden_method_still_callable() {
    let svc = HiddenService;
    // Hidden method must still be dispatchable even though it's not in the listing
    let result = svc.mcp_call("hidden_tool", serde_json::json!({}));
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!("hidden"));
}

#[tokio::test]
async fn test_mcp_hidden_method_callable_async() {
    let svc = HiddenService;
    let result = svc.mcp_call_async("hidden_tool", serde_json::json!({})).await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), serde_json::json!("hidden"));
}

// ============================================================================
// Context Injection Tests
// ============================================================================

/// Service with a Context parameter — context must not appear in the tool schema.
#[derive(Clone)]
struct ContextMcpService;

#[mcp(namespace = "ctx")]
impl ContextMcpService {
    /// Echo name with context (context should be invisible to callers)
    pub fn echo_name(&self, ctx: server_less::Context, name: String) -> String {
        let _ = ctx;
        format!("Hello, {}!", name)
    }

    /// No context parameter - should work normally
    pub fn ping(&self) -> String {
        "pong".to_string()
    }
}

#[test]
fn test_mcp_context_param_not_in_input_schema() {
    let tools = ContextMcpService::mcp_tools();

    let echo_tool = tools
        .iter()
        .find(|t| t.get("name").unwrap().as_str().unwrap() == "ctx_echo_name")
        .expect("ctx_echo_name tool should exist");

    let schema = echo_tool.get("inputSchema").unwrap();
    let properties = schema.get("properties").unwrap().as_object().unwrap();

    // `ctx` must NOT appear in the input schema
    assert!(
        !properties.contains_key("ctx"),
        "Context parameter should not appear in inputSchema, got: {:?}",
        properties
    );

    // `name` must still be there
    assert!(
        properties.contains_key("name"),
        "Regular parameter 'name' should appear in inputSchema"
    );

    let required = schema.get("required").unwrap().as_array().unwrap();
    assert!(
        !required.iter().any(|v| v.as_str() == Some("ctx")),
        "Context parameter should not be in the required list"
    );
    assert!(
        required.iter().any(|v| v.as_str() == Some("name")),
        "Regular parameter 'name' should be required"
    );
}

#[test]
fn test_mcp_context_param_method_callable() {
    let service = ContextMcpService;

    // Call without ctx in the args — the macro injects it automatically
    let result = service.mcp_call("ctx_echo_name", serde_json::json!({"name": "Alice"}));
    assert!(result.is_ok(), "Call should succeed: {:?}", result);
    assert_eq!(result.unwrap(), serde_json::json!("Hello, Alice!"));
}

#[tokio::test]
async fn test_mcp_context_param_method_callable_async() {
    let service = ContextMcpService;

    let result = service
        .mcp_call_async("ctx_echo_name", serde_json::json!({"name": "Bob"}))
        .await;
    assert!(result.is_ok(), "Async call should succeed: {:?}", result);
    assert_eq!(result.unwrap(), serde_json::json!("Hello, Bob!"));
}

// ============================================================================
// #[param(help)] in MCP tool input schema
// ============================================================================

#[derive(Clone)]
struct HelpParamService;

#[mcp]
impl HelpParamService {
    pub fn greet(
        &self,
        #[param(help = "The name to greet")] name: String,
        #[param(help = "Optional title prefix")] title: Option<String>,
    ) -> String {
        match title {
            Some(t) => format!("{} {}!", t, name),
            None => format!("Hello, {}!", name),
        }
    }
}

#[test]
fn test_mcp_param_help_in_input_schema() {
    let tools = HelpParamService::mcp_tools();
    let tool = tools
        .iter()
        .find(|t| t.get("name").unwrap().as_str().unwrap() == "greet")
        .expect("greet tool should exist");

    let props = tool
        .get("inputSchema")
        .unwrap()
        .get("properties")
        .unwrap()
        .as_object()
        .unwrap();

    let name_desc = props["name"].get("description").unwrap().as_str().unwrap();
    assert_eq!(name_desc, "The name to greet");

    let title_desc = props["title"]
        .get("description")
        .unwrap()
        .as_str()
        .unwrap();
    assert_eq!(title_desc, "Optional title prefix");
}

// ============================================================================
// Bad Parameter Tests
// ============================================================================

/// Service with required and typed parameters for bad-param testing.
#[derive(Clone)]
struct BadParamService;

#[mcp(namespace = "bp")]
impl BadParamService {
    /// Greet someone by name (name is required)
    pub fn greet(&self, name: String) -> String {
        format!("Hello, {}!", name)
    }

    /// Add two integers (both required)
    pub fn add(&self, a: i64, b: i64) -> i64 {
        a + b
    }

    /// Search with optional limit
    pub fn search(&self, query: String, limit: Option<u32>) -> String {
        format!("query={} limit={:?}", query, limit)
    }
}

/// Missing required parameter returns an error, not a panic.
#[test]
fn test_mcp_missing_required_param_returns_error() {
    let svc = BadParamService;

    // `name` is required but not provided
    let result = svc.mcp_call("bp_greet", serde_json::json!({}));
    assert!(
        result.is_err(),
        "calling with missing required param should return Err, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.contains("name") || err.contains("Missing"),
        "error should mention the missing param or 'Missing', got: {}",
        err
    );
}

/// Missing one of multiple required parameters returns an error.
#[test]
fn test_mcp_missing_one_of_multiple_required_params_returns_error() {
    let svc = BadParamService;

    // `b` is required but not provided
    let result = svc.mcp_call("bp_add", serde_json::json!({"a": 1}));
    assert!(
        result.is_err(),
        "calling with one missing required param should return Err, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.contains("b") || err.contains("Missing"),
        "error should mention the missing param 'b' or 'Missing', got: {}",
        err
    );
}

/// Parameter of wrong type returns an error, not a panic.
#[test]
fn test_mcp_wrong_type_param_returns_error() {
    let svc = BadParamService;

    // `a` and `b` must be integers; passing strings should fail deserialization
    let result = svc.mcp_call("bp_add", serde_json::json!({"a": "not-a-number", "b": 2}));
    assert!(
        result.is_err(),
        "calling with wrong-type param should return Err, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.contains("a") || err.contains("Invalid"),
        "error should mention the bad param 'a' or 'Invalid', got: {}",
        err
    );
}

/// Missing optional parameter is fine — should succeed with None.
#[test]
fn test_mcp_missing_optional_param_is_ok() {
    let svc = BadParamService;

    // `limit` is optional; omitting it should succeed
    let result = svc.mcp_call("bp_search", serde_json::json!({"query": "hello"}));
    assert!(
        result.is_ok(),
        "calling with missing optional param should succeed, got: {:?}",
        result
    );
}

/// Async path: missing required parameter returns an error too.
#[tokio::test]
async fn test_mcp_missing_required_param_async_returns_error() {
    let svc = BadParamService;

    let result = svc
        .mcp_call_async("bp_greet", serde_json::json!({}))
        .await;
    assert!(
        result.is_err(),
        "async call with missing required param should return Err, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.contains("name") || err.contains("Missing"),
        "error should mention the missing param or 'Missing', got: {}",
        err
    );
}

/// Async path: wrong-type parameter returns an error.
#[tokio::test]
async fn test_mcp_wrong_type_param_async_returns_error() {
    let svc = BadParamService;

    let result = svc
        .mcp_call_async("bp_add", serde_json::json!({"a": "bad", "b": 3}))
        .await;
    assert!(
        result.is_err(),
        "async call with wrong-type param should return Err, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.contains("a") || err.contains("Invalid"),
        "error should mention the bad param 'a' or 'Invalid', got: {}",
        err
    );
}

/// Optional parameter present with wrong type → Err (not silent None).
#[test]
fn test_mcp_optional_wrong_type_returns_error() {
    let svc = BadParamService;

    // `limit` is Option<u32>; passing a string should fail, not silently become None
    let result = svc.mcp_call(
        "bp_search",
        serde_json::json!({"query": "hello", "limit": "not-a-number"}),
    );
    assert!(
        result.is_err(),
        "optional param with wrong type should return Err, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.contains("limit") || err.contains("invalid") || err.contains("Invalid"),
        "error should mention 'limit' or 'invalid type', got: {}",
        err
    );
}

/// Optional parameter absent → success (None), not an error.
#[test]
fn test_mcp_optional_absent_is_ok() {
    let svc = BadParamService;

    // `limit` is optional; omitting it should succeed with None
    let result = svc.mcp_call("bp_search", serde_json::json!({"query": "hello"}));
    assert!(
        result.is_ok(),
        "absent optional param should succeed, got: {:?}",
        result
    );
}

/// Async path: optional wrong type → Err.
#[tokio::test]
async fn test_mcp_optional_wrong_type_async_returns_error() {
    let svc = BadParamService;

    let result = svc
        .mcp_call_async(
            "bp_search",
            serde_json::json!({"query": "hello", "limit": "bad"}),
        )
        .await;
    assert!(
        result.is_err(),
        "async optional param with wrong type should return Err, got: {:?}",
        result
    );
    let err = result.unwrap_err();
    assert!(
        err.contains("limit") || err.contains("invalid") || err.contains("Invalid"),
        "error should mention 'limit' or 'invalid type', got: {}",
        err
    );
}

/// Unknown parameter sent → call still succeeds (warning goes to stderr).
///
/// This test verifies the happy-path: unknown params don't break dispatch.
/// To observe the warning message run the tests with `-- --nocapture`.
#[test]
fn test_mcp_unknown_param_does_not_break_dispatch() {
    let svc = BadParamService;

    // `bp_greet` only takes `name`; `unexpected_key` is unknown
    let result = svc.mcp_call(
        "bp_greet",
        serde_json::json!({"name": "Alice", "unexpected_key": "oops"}),
    );
    assert!(
        result.is_ok(),
        "unknown param should not cause an error, got: {:?}",
        result
    );
    assert_eq!(
        result.unwrap(),
        serde_json::json!("Hello, Alice!"),
        "should still return the correct result"
    );
}

/// Unknown parameter alongside correct ones → call succeeds.
#[tokio::test]
async fn test_mcp_unknown_param_async_does_not_break_dispatch() {
    let svc = BadParamService;

    let result = svc
        .mcp_call_async(
            "bp_greet",
            serde_json::json!({"name": "Bob", "typo_param": "ignored"}),
        )
        .await;
    assert!(
        result.is_ok(),
        "unknown param in async call should not cause an error, got: {:?}",
        result
    );
    assert_eq!(result.unwrap(), serde_json::json!("Hello, Bob!"));
}