llm-tool-mcp 0.7.0

Model Context Protocol (MCP) server integration for llm-tool registries
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
use super::*;

// ── handle_request tests ────────────────────────────────────────

#[tokio::test]
async fn initialize_returns_server_info() {
    let server = test_server();
    let resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#)
        .await;

    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    assert_eq!(result["protocolVersion"], "2024-11-05");
    assert_eq!(result["serverInfo"]["name"], "test-server");
    assert_eq!(result["serverInfo"]["version"], "0.0.1");
    assert!(result["capabilities"]["tools"].is_object());
}

#[tokio::test]
async fn tools_list_returns_all_registered_tools() {
    let server = test_server();
    let resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#)
        .await;

    assert!(resp.error.is_none());
    let tools = resp.result.unwrap()["tools"].as_array().unwrap().clone();
    assert_eq!(tools.len(), 3);

    let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
    names.sort_unstable();
    assert_eq!(names, vec!["add", "fail", "whoami"]);

    // Every tool has the required MCP fields.
    for tool in &tools {
        assert!(tool["name"].is_string());
        assert!(tool["description"].is_string());
        assert!(tool["inputSchema"].is_object());
    }
}

#[tokio::test]
async fn tools_list_returns_cached_value() {
    let server = test_server();

    // Two calls should return structurally identical results (from cache).
    let resp1 = server
        .handle_request(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#)
        .await;
    let resp2 = server
        .handle_request(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#)
        .await;

    assert_eq!(
        resp1.result.unwrap()["tools"],
        resp2.result.unwrap()["tools"]
    );
}

#[tokio::test]
async fn tools_call_success() {
    let server = test_server();
    let resp = server
.handle_request(
r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add","arguments":{"a":17,"b":25}}}"#,
)
.await;

    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    assert_eq!(text, "42");
    assert!(result.get("isError").is_none());
}

#[tokio::test]
async fn tools_call_tool_error_returns_is_error() {
    let server = test_server();
    let resp = server
.handle_request(
r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"fail","arguments":{}}}"#,
)
.await;

    // Tool errors are MCP-level, NOT JSON-RPC errors.
    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
    assert!(
        result["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("intentional failure")
    );
}

#[tokio::test]
async fn tools_call_unknown_tool() {
    let server = test_server();
    let resp = server
.handle_request(
r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"nonexistent","arguments":{}}}"#,
)
.await;

    // Unknown tool is also a tool-level error.
    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
}

#[tokio::test]
async fn tools_call_missing_name() {
    let server = test_server();
    let resp = server
        .handle_request(
            r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"arguments":{}}}"#,
        )
        .await;

    // Missing "name" is a protocol-level error.
    assert!(resp.result.is_none());
    let err = resp.error.unwrap();
    assert_eq!(err.code, protocol::INVALID_PARAMS);
}

#[tokio::test]
async fn tools_call_missing_params() {
    let server = test_server();
    let resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":7,"method":"tools/call"}"#)
        .await;

    assert!(resp.result.is_none());
    let err = resp.error.unwrap();
    assert_eq!(err.code, protocol::INVALID_PARAMS);
}

#[tokio::test]
async fn tools_call_with_default_arguments() {
    let server = test_server();
    // No "arguments" key — should default to empty object.
    let resp = server
        .handle_request(
            r#"{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"fail"}}"#,
        )
        .await;

    // fail tool takes EmptyParams, so empty args is valid.
    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
}

#[tokio::test]
async fn unknown_method() {
    let server = test_server();
    let resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":9,"method":"foo/bar/unknown"}"#)
        .await;

    let err = resp.error.unwrap();
    assert_eq!(err.code, protocol::METHOD_NOT_FOUND);
    assert!(err.message.contains("foo/bar/unknown"));
}

#[tokio::test]
async fn invalid_json() {
    let server = test_server();
    let resp = server.handle_request("not json at all").await;

    let err = resp.error.unwrap();
    assert_eq!(err.code, protocol::PARSE_ERROR);
}

#[tokio::test]
async fn initialized_notification_is_accepted() {
    let server = test_server();
    // Some MCP clients send this after initialize.
    let resp = server
        .handle_request(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
        .await;
    assert!(resp.error.is_none());
}

#[tokio::test]
async fn context_is_passed_to_tools() {
    let registry = ToolRegistry::new().with_tool(ContextTool);
    let ctx = ToolContext::new().with_conversation_id("agent-007");
    let server = McpServer::new("test", "1.0", registry).with_context(ctx);

    let resp = server
.handle_request(
r#"{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"whoami","arguments":{}}}"#,
)
.await;

    let text = resp.result.unwrap()["content"][0]["text"]
        .as_str()
        .unwrap()
        .to_owned();
    assert_eq!(text, "agent-007");
}

// ── run() integration test ──────────────────────────────────────

#[test]
fn run_processes_multiple_requests() {
    let server = test_server();

    let input = [
        r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#,
        r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#,
        r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add","arguments":{"a":1,"b":2}}}"#,
        "",
        r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"fail","arguments":{}}}"#,
    ];
    let input_str = input.join("\n") + "\n";
    let reader = Cursor::new(input_str.as_bytes());

    let mut output = Vec::new();
    server.run(reader, &mut output).unwrap();

    let responses: Vec<serde_json::Value> = String::from_utf8(output)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();

    // 4 responses (blank line is skipped).
    assert_eq!(responses.len(), 4);

    // 1: initialize
    assert_eq!(responses[0]["result"]["serverInfo"]["name"], "test-server");

    // 2: tools/list — 3 tools
    assert_eq!(responses[1]["result"]["tools"].as_array().unwrap().len(), 3);

    // 3: add(1, 2) = "3"
    assert_eq!(responses[2]["result"]["content"][0]["text"], "3");
    assert!(responses[2]["result"].get("isError").is_none());

    // 4: fail — isError
    assert_eq!(responses[3]["result"]["isError"], true);
}

// ── run_with_runtime test ───────────────────────────────────────

#[test]
fn run_with_runtime_reuses_external_runtime() {
    let server = test_server();
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();

    let input = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add","arguments":{"a":10,"b":20}}}"#;
    let reader = Cursor::new(format!("{input}\n"));
    let mut output = Vec::new();

    server.run_with_runtime(&rt, reader, &mut output).unwrap();

    let resp: serde_json::Value =
        serde_json::from_str(String::from_utf8(output).unwrap().trim()).unwrap();
    assert_eq!(resp["result"]["content"][0]["text"], "30");
}

// ── run_async test ──────────────────────────────────────────────

#[tokio::test]
async fn run_async_processes_requests() {
    let server = test_server();
    let input = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add","arguments":{"a":100,"b":200}}}"#;
    let input_str = format!("{input}\n");
    let reader = input_str.as_bytes();
    let mut output = Vec::new();

    server.run_async(reader, &mut output).await.unwrap();

    let resp: serde_json::Value =
        serde_json::from_str(String::from_utf8(output).unwrap().trim()).unwrap();
    assert_eq!(resp["result"]["content"][0]["text"], "300");
}

// ── TCP listener test ───────────────────────────────────────────

#[tokio::test]
async fn tcp_listener_serves_requests() {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};

    let server = test_server();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        // NOLINT: test background task — server result unused; test controls lifecycle
        let _ = server.run_tcp_listener(listener).await;
    });

    let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap();
    let req = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add","arguments":{"a":15,"b":25}}}"#;
    stream
        .write_all(format!("{req}\n").as_bytes())
        .await
        .unwrap();
    stream.flush().await.unwrap();

    let mut reader = tokio::io::BufReader::new(stream);
    let mut line = String::new();
    reader.read_line(&mut line).await.unwrap();

    let resp: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
    assert_eq!(resp["result"]["content"][0]["text"], "40");
}

#[cfg(unix)]
#[tokio::test]
async fn unix_listener_serves_requests() {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};

    let server = test_server();
    let dir = tempfile::tempdir().unwrap();
    let sock_path = dir.path().join("test_mcp.sock");
    let listener = tokio::net::UnixListener::bind(&sock_path).unwrap();

    tokio::spawn(async move {
        // NOLINT: test background task — server result unused; test controls lifecycle
        let _ = server.run_unix_listener(listener).await;
    });

    let mut stream = tokio::net::UnixStream::connect(&sock_path).await.unwrap();
    let req = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add","arguments":{"a":30,"b":50}}}"#;
    stream
        .write_all(format!("{req}\n").as_bytes())
        .await
        .unwrap();
    stream.flush().await.unwrap();

    let mut reader = tokio::io::BufReader::new(stream);
    let mut line = String::new();
    reader.read_line(&mut line).await.unwrap();

    let resp: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
    assert_eq!(resp["result"]["content"][0]["text"], "80");
}

// ── Accessor tests ──────────────────────────────────────────────

#[test]
fn registry_accessor() {
    let server = test_server();
    assert_eq!(server.registry().len(), 3);
}

// ── Schema format test ──────────────────────────────────────────

#[test]
fn definition_to_mcp_schema_has_correct_keys() {
    let def = ToolDefinition {
        name: "my_tool".into(),
        description: "Does stuff.".into(),
        parameter_schema: serde_json::json!({"type": "object"}),
    };
    let schema = definition_to_mcp_schema(&def);
    assert_eq!(schema.name, "my_tool");
    assert_eq!(schema.description, "Does stuff.");
    assert_eq!(schema.input_schema["type"], "object");
}

// ── Notification filtering tests ────────────────────────────────

#[test]
fn run_drops_notification_responses() {
    let server = test_server();

    // Mix a notification (no id) among regular requests.
    let input = [
        r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#,
        r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
        r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#,
    ];
    let input_str = input.join("\n") + "\n";
    let reader = Cursor::new(input_str.as_bytes());

    let mut output = Vec::new();
    server.run(reader, &mut output).unwrap();

    let responses: Vec<serde_json::Value> = String::from_utf8(output)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();

    // Only 2 responses — the notification produced no output.
    assert_eq!(responses.len(), 2);
    assert_eq!(responses[0]["id"], 1);
    assert_eq!(responses[1]["id"], 2);
}

#[tokio::test]
async fn run_async_drops_notification_responses() {
    let server = test_server();

    let input = [
        r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#,
        r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
        r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#,
    ];
    let input_str = input.join("\n") + "\n";
    let mut output = Vec::new();

    server
        .run_async(input_str.as_bytes(), &mut output)
        .await
        .unwrap();

    let responses: Vec<serde_json::Value> = String::from_utf8(output)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();

    assert_eq!(responses.len(), 2);
    assert_eq!(responses[0]["id"], 1);
    assert_eq!(responses[1]["id"], 2);
}

// ── JSON-RPC version validation ─────────────────────────────────

#[tokio::test]
async fn invalid_jsonrpc_version_returns_invalid_request() {
    let server = test_server();
    let resp = server
        .handle_request(r#"{"jsonrpc":"1.0","id":1,"method":"initialize"}"#)
        .await;

    let err = resp.error.unwrap();
    assert_eq!(err.code, protocol::INVALID_REQUEST);
    assert!(err.message.contains("1.0"));
}

#[tokio::test]
async fn missing_jsonrpc_version_returns_parse_error() {
    let server = test_server();
    // Missing "jsonrpc" field entirely — serde will fail to deserialize.
    let resp = server
        .handle_request(r#"{"id":1,"method":"initialize"}"#)
        .await;

    let err = resp.error.unwrap();
    assert_eq!(err.code, protocol::PARSE_ERROR);
}

// ── Batch request handling ───────────────────────────────────────

#[tokio::test]
async fn batch_request_returns_invalid_request_on_handle_request() {
    let server = test_server();
    let resp = server
        .handle_request(r#"[{"jsonrpc":"2.0","id":1,"method":"initialize"}]"#)
        .await;

    let err = resp.error.unwrap();
    assert_eq!(err.code, protocol::INVALID_REQUEST);
    assert!(err.message.contains("batch"));
}

#[tokio::test]
async fn batch_request_via_handle_message_success() {
    let server = test_server();
    let req = r#"[{"jsonrpc":"2.0","id":1,"method":"initialize"},{"jsonrpc":"2.0","id":2,"method":"tools/list"}]"#;
    let outcome = server
        .handle_message(req)
        .await
        .expect("batch response expected");
    let RpcOutcome::Batch(ref responses) = outcome else {
        panic!("expected a batch outcome");
    };
    assert_eq!(responses.len(), 2);
    assert_eq!(responses[0].id, Some(serde_json::json!(1)));
    assert_eq!(responses[1].id, Some(serde_json::json!(2)));
    let tools = responses[1].result.as_ref().expect("tools/list result")["tools"]
        .as_array()
        .expect("tools array");
    assert_eq!(tools.len(), 3);

    // The structured outcome renders to a JSON array on the wire.
    let wire: serde_json::Value = serde_json::from_str(&outcome.to_wire()).expect("valid JSON");
    assert!(wire.is_array());
}

#[tokio::test]
async fn batch_request_with_notifications_omits_notifications() {
    let server = test_server();
    let req = r#"[{"jsonrpc":"2.0","id":1,"method":"initialize"},{"jsonrpc":"2.0","method":"initialized"},{"jsonrpc":"2.0","id":2,"method":"tools/list"}]"#;
    let outcome = server
        .handle_message(req)
        .await
        .expect("batch response expected");
    let RpcOutcome::Batch(responses) = outcome else {
        panic!("expected a batch outcome");
    };
    assert_eq!(responses.len(), 2);
    assert_eq!(responses[0].id, Some(serde_json::json!(1)));
    assert_eq!(responses[1].id, Some(serde_json::json!(2)));
}

#[tokio::test]
async fn batch_request_only_notifications_returns_none() {
    let server = test_server();
    let req = r#"[{"jsonrpc":"2.0","method":"initialized"},{"jsonrpc":"2.0","method":"notifications/cancelled"}]"#;
    assert!(server.handle_message(req).await.is_none());
}

#[tokio::test]
async fn empty_array_returns_invalid_request() {
    let server = test_server();
    let resp = server.handle_request("[]").await;

    let err = resp.error.unwrap();
    assert_eq!(err.code, protocol::INVALID_REQUEST);

    let outcome = server.handle_message("[]").await.expect("error response");
    let RpcOutcome::Single(batch_resp) = outcome else {
        panic!("expected a single error response");
    };
    assert_eq!(
        batch_resp.error.expect("error present").code,
        protocol::INVALID_REQUEST
    );
}

#[tokio::test]
async fn outcome_write_json_matches_to_wire() {
    let server = test_server();
    let req = r#"{"jsonrpc":"2.0","id":7,"method":"tools/list"}"#;
    let outcome = server.handle_message(req).await.expect("response expected");

    // write_json appends the wire form to an existing buffer.
    let mut buf = Vec::new();
    outcome.write_json(&mut buf);

    let parsed: serde_json::Value = serde_json::from_slice(&buf).expect("valid JSON");
    assert_eq!(parsed["id"], 7);
    // The two rendering entry points agree byte-for-byte.
    assert_eq!(String::from_utf8(buf).expect("utf8"), outcome.to_wire());
}

#[tokio::test]
async fn outcome_display_clone_and_eq() {
    let server = test_server();
    let req = r#"{"jsonrpc":"2.0","id":7,"method":"tools/list"}"#;
    let outcome = server.handle_message(req).await.expect("response expected");

    // Display renders the same bytes as to_wire().
    assert_eq!(outcome.to_string(), outcome.to_wire());
    // Clone + PartialEq round-trip.
    assert_eq!(outcome.clone(), outcome);
    assert!(!outcome.is_batch());
}

#[tokio::test]
async fn outcome_into_responses_flattens_single_and_batch() {
    let server = test_server();

    let single = server
        .handle_message(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#)
        .await
        .expect("single response");
    assert!(!single.is_batch());
    assert_eq!(single.into_responses().len(), 1);

    let batch = server
        .handle_message(
            r#"[{"jsonrpc":"2.0","id":1,"method":"initialize"},{"jsonrpc":"2.0","id":2,"method":"tools/list"}]"#,
        )
        .await
        .expect("batch response");
    assert!(batch.is_batch());
    let responses = batch.into_responses();
    assert_eq!(responses.len(), 2);
    assert_eq!(responses[0].id, Some(serde_json::json!(1)));
}

#[tokio::test]
async fn resources_and_prompts_list_return_empty() {
    let server = test_server();
    let res_resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":1,"method":"resources/list"}"#)
        .await;
    assert_eq!(
        res_resp.result.unwrap()["resources"]
            .as_array()
            .unwrap()
            .len(),
        0
    );

    let prompt_resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":2,"method":"prompts/list"}"#)
        .await;
    assert_eq!(
        prompt_resp.result.unwrap()["prompts"]
            .as_array()
            .unwrap()
            .len(),
        0
    );

    let log_resp = server
        .handle_request(
            r#"{"jsonrpc":"2.0","id":3,"method":"logging/setLevel","params":{"level":"info"}}"#,
        )
        .await;
    assert!(log_resp.error.is_none());

    let comp_resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":4,"method":"completion/complete"}"#)
        .await;
    assert_eq!(
        comp_resp.result.unwrap()["completion"]["values"]
            .as_array()
            .unwrap()
            .len(),
        0
    );
}

// ── Empty / whitespace input ────────────────────────────────────

#[test]
fn run_skips_empty_and_whitespace_lines() {
    let server = test_server();

    let input = "\n  \n\t\n";
    let reader = Cursor::new(input.as_bytes());

    let mut output = Vec::new();
    server.run(reader, &mut output).unwrap();

    // No output for blank lines.
    assert!(output.is_empty());
}

// ── String IDs ──────────────────────────────────────────────────

#[tokio::test]
async fn string_id_is_echoed_back() {
    let server = test_server();
    let resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":"abc-123","method":"initialize"}"#)
        .await;

    assert!(resp.error.is_none());
    assert_eq!(resp.id, Some(serde_json::json!("abc-123")));
}

#[tokio::test]
async fn null_id_is_treated_as_present() {
    let server = test_server();
    // JSON-RPC spec: null is a valid id value (though unusual).
    let resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":null,"method":"initialize"}"#)
        .await;

    // null id means this will be serialized with "id":null.
    // The response should still be produced (not dropped as a notification)
    // because the JSON had an explicit "id" key.
    // Note: serde deserializes `"id": null` as `Some(Value::Null)`.
    assert!(resp.error.is_none());
}

// ── Ping ────────────────────────────────────────────────────────

#[tokio::test]
async fn ping_returns_empty_object() {
    let server = test_server();
    let resp = server
        .handle_request(r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#)
        .await;

    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    assert_eq!(result, serde_json::json!({}));
}

// ── notifications/cancelled ─────────────────────────────────────

#[tokio::test]
async fn notifications_cancelled_is_accepted() {
    let server = test_server();
    let resp = server
.handle_request(
r#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"req-1","reason":"timeout"}}"#,
)
.await;

    // It's a notification (no id), so handle_request returns id=None.
    assert!(resp.error.is_none());
    assert!(resp.id.is_none());
}

// ── Large tool arguments ────────────────────────────────────────

#[tokio::test]
async fn large_nested_tool_arguments() {
    let server = test_server();

    // Build deeply nested JSON: {"a": 1, "b": 2} but with a large wrapper.
    let args = serde_json::json!({
    "a": 1,
    "b": 2,
    "metadata": {
    "level1": {
    "level2": {
    "level3": {
    "level4": {
    "level5": "deep"
    }
    }
    }
    }
    }
    });

    let req = serde_json::json!({
    "jsonrpc": "2.0",
    "id": 99,
    "method": "tools/call",
    "params": {
    "name": "add",
    "arguments": args
    }
    });

    let resp = server
        .handle_request(&serde_json::to_string(&req).unwrap())
        .await;

    // add tool only looks at a + b, extra fields are ignored by serde.
    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    assert_eq!(result["content"][0]["text"], "3");
}

// ── Tool returning empty string ─────────────────────────────────

struct EmptyResultTool;
impl RustTool for EmptyResultTool {
    type Params = EmptyParams;
    const NAME: &'static str = "empty_result";
    const DESCRIPTION: &'static str = "Returns empty string.";
    async fn call(
        &self,
        _params: Self::Params,
        _ctx: &ToolContext,
    ) -> Result<ToolOutput, ToolError> {
        Ok(ToolOutput::new(String::new()))
    }
}

#[tokio::test]
async fn tool_returning_empty_string() {
    let registry = ToolRegistry::new().with_tool(EmptyResultTool);
    let server = McpServer::new("test", "0.0.1", registry);

    let resp = server
.handle_request(
r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"empty_result","arguments":{}}}"#,
)
.await;

    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    assert_eq!(result["content"][0]["text"], "");
    assert!(result.get("isError").is_none());
}

// ── Concurrent TCP clients ──────────────────────────────────────

#[tokio::test]
async fn tcp_multiple_concurrent_clients() {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};

    let server = test_server();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        // NOLINT: test background task — server result unused; test controls lifecycle
        let _ = server.run_tcp_listener(listener).await;
    });

    // Spawn 3 concurrent clients.
    let mut handles = Vec::new();
    for i in 0..3 {
        let client_addr = addr;
        handles.push(tokio::spawn(async move {
let mut stream = tokio::net::TcpStream::connect(client_addr).await.unwrap();
let req = format!(
r#"{{"jsonrpc":"2.0","id":{},"method":"tools/call","params":{{"name":"add","arguments":{{"a":{},"b":{}}}}}}}"#,
i, i, 100
);
stream
.write_all(format!("{req}\n").as_bytes())
.await
.unwrap();
stream.flush().await.unwrap();

let mut reader = tokio::io::BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).await.unwrap();

let resp: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
let text = resp["result"]["content"][0]["text"]
.as_str()
.unwrap()
.to_owned();
let expected: i64 = i + 100;
assert_eq!(text, expected.to_string());
}));
    }

    for h in handles {
        h.await.unwrap();
    }
}

#[cfg(unix)]
#[tokio::test]
async fn unix_multiple_concurrent_clients() {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};

    let server = test_server();
    let dir = tempfile::tempdir().unwrap();
    let sock_path = dir.path().join("concurrent.sock");
    let listener = tokio::net::UnixListener::bind(&sock_path).unwrap();

    tokio::spawn(async move {
        // NOLINT: test background task — server result unused; test controls lifecycle
        let _ = server.run_unix_listener(listener).await;
    });

    let mut handles = Vec::new();
    for i in 0..3 {
        let path = sock_path.clone();
        handles.push(tokio::spawn(async move {
let mut stream = tokio::net::UnixStream::connect(&path).await.unwrap();
let req = format!(
r#"{{"jsonrpc":"2.0","id":{},"method":"tools/call","params":{{"name":"add","arguments":{{"a":{},"b":{}}}}}}}"#,
i, i, 200
);
stream
.write_all(format!("{req}\n").as_bytes())
.await
.unwrap();
stream.flush().await.unwrap();

let mut reader = tokio::io::BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).await.unwrap();

let resp: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
let text = resp["result"]["content"][0]["text"]
.as_str()
.unwrap()
.to_owned();
let expected: i64 = i + 200;
assert_eq!(text, expected.to_string());
}));
    }

    for h in handles {
        h.await.unwrap();
    }
}

// ── Protocol version negotiation ────────────────────────────────

#[tokio::test]
async fn initialize_with_client_protocol_version() {
    let server = test_server();
    let resp = server
.handle_request(
r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}"#,
)
.await;

    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    assert_eq!(result["protocolVersion"], "2024-11-05");
}

#[tokio::test]
async fn initialize_with_unknown_client_version_returns_server_version() {
    let server = test_server();
    let resp = server
.handle_request(
r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"9999-01-01"}}"#,
)
.await;

    assert!(resp.error.is_none());
    let result = resp.result.unwrap();
    // Server always returns its own supported version.
    assert_eq!(result["protocolVersion"], "2024-11-05");
}

// ── Notification in run() produces no output ────────────────────

#[test]
fn notification_initialized_no_output_in_run() {
    let server = test_server();
    let input = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
    let input_str = format!("{input}\n");
    let reader = Cursor::new(input_str.as_bytes());

    let mut output = Vec::new();
    server.run(reader, &mut output).unwrap();

    // Notification should produce zero bytes of output.
    assert!(output.is_empty());
}