things3-cli 2.0.0

CLI tool for Things 3 with integrated MCP server
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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
//! Integration tests for MCP server I/O layer
//!
//! These tests verify that the MCP server correctly handles JSON-RPC protocol
//! communication over the I/O abstraction layer.

use jsonschema::{Draft, JSONSchema};
use serde_json::json;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use tempfile::NamedTempFile;
use things3_cli::mcp::io_wrapper::{McpIo, MockIo};
use things3_cli::mcp::{start_mcp_server_generic, start_mcp_server_with_config_generic};
use things3_core::{ThingsConfig, ThingsDatabase};
use tokio::time::{timeout, Duration};

// ============================================================================
// MCP spec compliance — schema validation helpers
// ============================================================================
//
// These helpers validate JSON-RPC `result` payloads against the official MCP
// JSON Schemas vendored under `tests/fixtures/`. They're a tripwire for the
// protocol-compliance bugs that motivated this suite (PR #118): hardcoded
// `protocolVersion` and the `Content` enum's tagged-union shape. If the wire
// format ever diverges from the spec again, schema validation fails loudly
// with a pointer at the offending field.

const MCP_SCHEMA_2024_11_05: &str = include_str!("fixtures/mcp-schema-2024-11-05.json");
const MCP_SCHEMA_2025_03_26: &str = include_str!("fixtures/mcp-schema-2025-03-26.json");
const MCP_SCHEMA_2025_11_25: &str = include_str!("fixtures/mcp-schema-2025-11-25.json");

fn mcp_schema(version: &str) -> &'static serde_json::Value {
    static CACHE: OnceLock<HashMap<&'static str, serde_json::Value>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| {
        let mut m = HashMap::new();
        m.insert(
            "2024-11-05",
            serde_json::from_str(MCP_SCHEMA_2024_11_05).expect("valid 2024-11-05 schema"),
        );
        m.insert(
            "2025-03-26",
            serde_json::from_str(MCP_SCHEMA_2025_03_26).expect("valid 2025-03-26 schema"),
        );
        m.insert(
            "2025-11-25",
            serde_json::from_str(MCP_SCHEMA_2025_11_25).expect("valid 2025-11-25 schema"),
        );
        m
    });
    cache
        .get(version)
        .unwrap_or_else(|| panic!("no vendored MCP schema for version {version}"))
}

/// Build a wrapper schema that `$ref`s into a specific definition of the bundled MCP schema.
///
/// 2024-11-05 uses draft-07 (`definitions`); 2025-11-25 uses draft 2020-12 (`$defs`).
fn compile_validator(version: &str, type_name: &str) -> JSONSchema {
    let full = mcp_schema(version);
    // MCP schemas through 2025-03-26 use JSON Schema draft-07 with `definitions`;
    // 2025-11-25+ switched to draft 2020-12 with `$defs`. The threshold is set
    // to the midpoint between those two known versions. If a new schema version
    // changes the draft, update this threshold to the first version using the
    // new draft.
    let (defs_key, draft) = if version < "2025-06-18" {
        ("definitions", Draft::Draft7)
    } else {
        ("$defs", Draft::Draft202012)
    };
    let wrapper = json!({
        "$ref": format!("#/{defs_key}/{type_name}"),
        defs_key: full[defs_key].clone(),
    });
    JSONSchema::options()
        .with_draft(draft)
        .compile(&wrapper)
        .expect("MCP schema compiles")
}

/// Validate a JSON-RPC response's `result` field against the named MCP type.
///
/// Panics with a diagnostic message if validation fails — the panic includes
/// every JSON-pointer path where the response diverged from the spec, plus
/// the full pretty-printed result, so a regression is debuggable straight
/// from `cargo test` output.
fn validate_result(version: &str, type_name: &str, response: &serde_json::Value) {
    let validator = compile_validator(version, type_name);
    let result = &response["result"];
    let details: Option<Vec<String>> = validator.validate(result).err().map(|errors| {
        errors
            .map(|e| format!("  - {} (at {})", e, e.instance_path))
            .collect()
    });
    if let Some(details) = details {
        panic!(
            "MCP {version} response failed schema validation against {type_name}:\n{}\n\nResult was:\n{}",
            details.join("\n"),
            serde_json::to_string_pretty(result).unwrap_or_else(|_| "<unprintable>".into())
        );
    }
}

/// Helper to create a test database
async fn create_test_db() -> (NamedTempFile, Arc<ThingsDatabase>) {
    let temp_file = NamedTempFile::new().unwrap();
    let db_path = temp_file.path();

    // Create test database with schema
    things3_core::test_utils::create_test_database(db_path)
        .await
        .unwrap();

    let db = ThingsDatabase::new(db_path).await.unwrap();
    (temp_file, Arc::new(db))
}

/// Helper to send a JSON-RPC request and read the response
async fn send_request_read_response(
    client_io: &mut MockIo,
    request: serde_json::Value,
) -> serde_json::Value {
    // Send request
    let request_str = serde_json::to_string(&request).unwrap();
    client_io.write_line(&request_str).await.unwrap();
    client_io.flush().await.unwrap();

    // Read response with timeout
    let response_line = timeout(Duration::from_secs(2), client_io.read_line())
        .await
        .expect("Timeout waiting for response")
        .expect("IO error reading response")
        .expect("EOF when expecting response");

    serde_json::from_str(&response_line).unwrap()
}

// ============================================================================
// Initialize Handshake Tests
// ============================================================================

/// Drive a complete `initialize` handshake using `requested_version` and
/// assert the server's response is spec-compliant.
///
/// `accepted_response_versions` lists the protocol versions we'll accept in
/// the response. Per spec the server MUST respond with the requested version
/// if it supports it, otherwise with another version it supports (always
/// downgrading, never upgrading).
///
/// Schema validation is performed against the version the server *actually*
/// responded with, not the version the client requested. This avoids false
/// failures if a newer schema version introduces required fields that an older
/// negotiated response legitimately omits.
async fn run_initialize_handshake_for(
    requested_version: &str,
    accepted_response_versions: &[&str],
) {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    let server_handle =
        tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let initialize_request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": requested_version,
            "capabilities": {},
            "clientInfo": {
                "name": "test-client",
                "version": "1.0.0"
            }
        }
    });

    let response = send_request_read_response(&mut client_io, initialize_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 1);

    let response_version = response["result"]["protocolVersion"]
        .as_str()
        .expect("InitializeResult must include protocolVersion as a string");
    assert!(
        accepted_response_versions.contains(&response_version),
        "server returned protocolVersion {response_version:?} when client requested \
         {requested_version:?}; expected one of {accepted_response_versions:?}. \
         (Per spec the server must echo the requested version if it supports it, or \
         negotiate to a version it does support — never to an arbitrary newer version.)"
    );
    assert_eq!(response["result"]["serverInfo"]["name"], "things3-mcp");

    // Validate against the version the server responded with, not what the client requested.
    validate_result(response_version, "InitializeResult", &response);

    let initialized_notification = json!({
        "jsonrpc": "2.0",
        "method": "notifications/initialized"
    });
    let notification_str = serde_json::to_string(&initialized_notification).unwrap();
    client_io.write_line(&notification_str).await.unwrap();
    client_io.flush().await.unwrap();

    drop(client_io);

    let result = timeout(Duration::from_secs(2), server_handle).await;
    assert!(result.is_ok(), "Server should complete");
    assert!(result.unwrap().is_ok(), "Server should not error");
}

#[tokio::test]
async fn test_initialize_handshake_2024_11_05() {
    // Server supports 2024-11-05 directly, so it must echo the request verbatim.
    run_initialize_handshake_for("2024-11-05", &["2024-11-05"]).await;
}

#[tokio::test]
async fn test_initialize_handshake_2025_11_25() {
    // Tripwire for PR #118: the server used to hardcode "2024-11-05" in its
    // initialize response, which caused Claude Code 2.1+ (which sends
    // "2025-11-25") to silently drop all tools. Today the server doesn't yet
    // implement 2025-11-25 features, so it negotiates down to the newest
    // version it does support (2025-03-26) — which is spec-compliant.
    // What is NOT acceptable is responding with 2024-11-05 to a 2025-11-25
    // request: that would mean we regressed the fix.
    run_initialize_handshake_for("2025-11-25", &["2025-03-26", "2025-06-18", "2025-11-25"]).await;
}

#[tokio::test]
async fn test_initialize_response_structure() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let initialize_request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {}
    });

    let response = send_request_read_response(&mut client_io, initialize_request).await;

    // Verify capabilities structure
    let capabilities = &response["result"]["capabilities"];
    assert!(capabilities["tools"].is_object());
    assert!(capabilities["resources"].is_object());
    assert!(capabilities["prompts"].is_object());

    // Verify server info
    let server_info = &response["result"]["serverInfo"];
    assert_eq!(server_info["name"], "things3-mcp");
    assert!(server_info["version"].is_string());
}

// ============================================================================
// Tools Tests
// ============================================================================

#[tokio::test]
async fn test_tools_list() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let tools_list_request = json!({
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/list"
    });

    let response = send_request_read_response(&mut client_io, tools_list_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 2);

    // Spec: result is a `ListToolsResult` object containing a `tools` array.
    // The schema check below also verifies each tool's `inputSchema` field
    // (camelCase, as required by the spec) — this catches any regression in
    // the `#[serde(rename = "inputSchema")]` attribute on `Tool`.
    // Note: no initialize handshake is performed here, so no protocol version
    // is negotiated. We validate against 2025-11-25 because ListToolsResult
    // is structurally identical across all known schema versions. If that ever
    // changes, this test should be preceded by an initialize handshake and use
    // the negotiated version instead.
    validate_result("2025-11-25", "ListToolsResult", &response);

    let tools = response["result"]["tools"]
        .as_array()
        .expect("ListToolsResult.tools must be an array");
    assert!(!tools.is_empty(), "Should have at least one tool");
}

#[tokio::test]
async fn test_tools_call_get_today() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let tools_call_request = json!({
        "jsonrpc": "2.0",
        "id": 3,
        "method": "tools/call",
        "params": {
            "name": "get_today",
            "arguments": {}
        }
    });

    let response = send_request_read_response(&mut client_io, tools_call_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 3);
    // Tripwire for PR #118 bug #2: the `Content` enum was serialized as
    // `{"Text":{"text":"..."}}` instead of the spec's tagged-union form
    // `{"type":"text","text":"..."}`. Schema validation would reject the
    // former because it doesn't match any variant of `ToolResultContent`.
    validate_result("2025-11-25", "CallToolResult", &response);
    let is_error = response["result"]["isError"].as_bool().unwrap_or(false);
    assert!(!is_error, "Tool call should not error");
}

#[tokio::test]
async fn test_tools_call_get_inbox() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let tools_call_request = json!({
        "jsonrpc": "2.0",
        "id": 4,
        "method": "tools/call",
        "params": {
            "name": "get_inbox",
            "arguments": {
                "limit": 10
            }
        }
    });

    let response = send_request_read_response(&mut client_io, tools_call_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 4);
    validate_result("2025-11-25", "CallToolResult", &response);
    let is_error = response["result"]["isError"].as_bool().unwrap_or(false);
    assert!(!is_error, "Tool call should not error");
}

/// Belt-and-suspenders check for the `Content` enum's wire format.
///
/// PR #118 fixed bug #2 by adding `#[serde(tag = "type", rename_all =
/// "lowercase")]` to the `Content` enum so it serializes as
/// `{"type":"text","text":"..."}` instead of the default
/// `{"Text":{"text":"..."}}`. The CallToolResult schema check above will
/// catch a regression too, but this test fails with a clearer assertion
/// message — useful when the schema crate is ever swapped or upgraded.
#[tokio::test]
async fn test_content_block_serialization() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": { "name": "get_today", "arguments": {} }
        }),
    )
    .await;

    let content = response["result"]["content"]
        .as_array()
        .expect("CallToolResult.content must be an array");
    assert!(
        !content.is_empty(),
        "Tool that returned successfully must have at least one content block"
    );

    let first = &content[0];
    let type_field = first.get("type").and_then(|v| v.as_str());
    assert_eq!(
        type_field,
        Some("text"),
        "First content block must be tagged with `type: \"text\"` (was {first}). \
         If this fails as `\"Text\"` or with a missing `type` field, the `Content` \
         enum's `#[serde(tag = \"type\", rename_all = \"lowercase\")]` attribute \
         has been removed or broken."
    );
    assert!(
        first.get("text").and_then(|v| v.as_str()).is_some(),
        "Text content block must include a `text` string field; got {first}"
    );
    assert!(
        !first.as_object().unwrap().contains_key("Text"),
        "Wire format must not include a top-level `Text` key — that's the \
         externally-tagged form the spec rejects. Got {first}"
    );
}

#[tokio::test]
async fn test_tools_call_nonexistent_tool() {
    // Tripwire for #148: a tool-level error (here, `tools/call` with an
    // unknown tool name) must surface as a JSON-RPC `result` containing an
    // `isError: true` envelope — NOT propagate up the request loop and
    // drop the MCP connection. Earlier behavior was "disconnect or
    // envelope, either is fine"; that masked a connection-killing bug.
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 5,
            "method": "tools/call",
            "params": {
                "name": "nonexistent_tool",
                "arguments": {}
            }
        }),
    )
    .await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 5);
    let is_error = response["result"]["isError"].as_bool().unwrap_or(false);
    assert!(
        is_error,
        "Expected isError envelope inside result for unknown tool; got {response}"
    );
    let content = response["result"]["content"]
        .as_array()
        .expect("CallToolResult.content must be an array even on error");
    let text = content
        .first()
        .and_then(|c| c.get("text"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    assert!(
        text.to_lowercase().contains("not found"),
        "Error envelope text should mention the tool was not found; got {text:?}"
    );
}

/// Regression test for issue #148: when a single request triggers a handler
/// error, the MCP server loop must keep running and answer subsequent
/// requests. Previously the `?` propagation in the request loop terminated
/// the entire loop on first error, dropping the connection.
#[tokio::test]
async fn test_loop_continues_after_handler_error() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // First request: triggers a tool-level error (unknown tool).
    let bad_response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 100,
            "method": "tools/call",
            "params": { "name": "nonexistent_tool", "arguments": {} }
        }),
    )
    .await;
    assert_eq!(bad_response["id"], 100);
    assert!(
        bad_response["result"]["isError"].as_bool().unwrap_or(false),
        "First request must come back as an isError envelope, not crash the loop"
    );

    // Second request: a normal tools/list. Must succeed because the loop
    // survived the previous error.
    let good_response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 101,
            "method": "tools/list"
        }),
    )
    .await;
    assert_eq!(good_response["id"], 101);
    assert!(
        good_response["result"]["tools"].is_array(),
        "Second request after a handler error must still be answered; got {good_response}"
    );
}

/// Companion to `test_loop_continues_after_handler_error`: confirms that a
/// resources/read with an unknown URI also returns a structured envelope
/// instead of dropping the connection.
#[tokio::test]
async fn test_resources_read_unknown_uri_returns_envelope_not_disconnect() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 200,
            "method": "resources/read",
            "params": { "uri": "things3://does-not-exist" }
        }),
    )
    .await;

    assert_eq!(response["id"], 200);
    // The fallback variant of read_resource emits a `ReadResourceResult` with
    // an error message in its `contents`. The exact shape is up to
    // `to_resource_result()`; we just assert the response arrived (no
    // disconnect) and is well-formed JSON-RPC.
    assert_eq!(response["jsonrpc"], "2.0");
    assert!(
        response["result"].is_object(),
        "Expected a result envelope, got {response}"
    );

    // Server is still alive: a subsequent valid request gets answered.
    let follow_up = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 201,
            "method": "resources/list"
        }),
    )
    .await;
    assert_eq!(follow_up["id"], 201);
    assert!(follow_up["result"]["resources"].is_array());
}

/// Covers the prompts/get error path: an unknown prompt name must return a
/// structured envelope instead of dropping the connection.
#[tokio::test]
async fn test_prompts_get_error_returns_envelope_not_disconnect() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 300,
            "method": "prompts/get",
            "params": { "name": "nonexistent_prompt" }
        }),
    )
    .await;

    assert_eq!(response["id"], 300);
    assert_eq!(response["jsonrpc"], "2.0");
    // Must come back as a well-formed response, not disconnect.
    assert!(
        response["result"].is_object() || response["error"].is_object(),
        "Expected a result or error envelope, got {response}"
    );

    // Server still alive: a subsequent request is answered.
    let follow_up = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 301,
            "method": "tools/list"
        }),
    )
    .await;
    assert_eq!(follow_up["id"], 301);
    assert!(follow_up["result"]["tools"].is_array());
}

/// Covers `start_mcp_server_with_config_generic`: the same error-recovery fix
/// is present in both server variants. Regression test so a future refactor
/// can't break the config variant independently of the generic one.
#[tokio::test]
async fn test_config_variant_loop_continues_after_error() {
    use things3_core::McpServerConfig;

    let (_temp, db) = create_test_db().await;

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move {
        start_mcp_server_with_config_generic(db, McpServerConfig::default(), server_io, true).await
    });

    // First request: unknown tool → error envelope.
    let bad_response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 400,
            "method": "tools/call",
            "params": { "name": "nonexistent_tool", "arguments": {} }
        }),
    )
    .await;
    assert_eq!(bad_response["id"], 400);
    assert!(
        bad_response["result"]["isError"].as_bool().unwrap_or(false),
        "Config variant must return isError envelope, not disconnect; got {bad_response}"
    );

    // Second request: must succeed — loop survived.
    let good_response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 401,
            "method": "tools/list"
        }),
    )
    .await;
    assert_eq!(good_response["id"], 401);
    assert!(good_response["result"]["tools"].is_array());
}

/// Verifies `build_jsonrpc_error_response` notification path: when a
/// JSON-RPC notification (no `id`) triggers a handler error, the server
/// must stay silent — sending a response to a notification is a protocol
/// violation.
#[tokio::test]
async fn test_notification_error_produces_no_response() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Send a notification (no `id`) with an unknown method. The server must
    // not write any response for this — notifications are fire-and-forget.
    client_io
        .write_line(
            &serde_json::to_string(&json!({
                "jsonrpc": "2.0",
                "method": "notifications/unknown_event",
                "params": {}
            }))
            .unwrap(),
        )
        .await
        .unwrap();
    client_io.flush().await.unwrap();

    // Now send a real request immediately after. The first response we read
    // must belong to this request, not to the notification above.
    let response = send_request_read_response(
        &mut client_io,
        json!({
            "jsonrpc": "2.0",
            "id": 500,
            "method": "tools/list"
        }),
    )
    .await;
    assert_eq!(
        response["id"], 500,
        "First response must be for id=500 (the tools/list), not a spurious notification reply"
    );
    assert!(response["result"]["tools"].is_array());
}

// ============================================================================
// Resources Tests
// ============================================================================

#[tokio::test]
async fn test_resources_list() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let resources_list_request = json!({
        "jsonrpc": "2.0",
        "id": 6,
        "method": "resources/list"
    });

    let response = send_request_read_response(&mut client_io, resources_list_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 6);
    // Spec: result must be a `ListResourcesResult` object containing a
    // `resources` array — not a bare array.
    validate_result("2025-11-25", "ListResourcesResult", &response);
    assert!(
        response["result"]["resources"].is_array(),
        "ListResourcesResult.resources must be an array"
    );
}

#[tokio::test]
async fn test_resources_read() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    let server_handle =
        tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let resources_read_request = json!({
        "jsonrpc": "2.0",
        "id": 7,
        "method": "resources/read",
        "params": {
            "uri": "things3://today"
        }
    });

    // Send request
    let request_str = serde_json::to_string(&resources_read_request).unwrap();
    client_io.write_line(&request_str).await.unwrap();
    client_io.flush().await.unwrap();

    // Try to read response - server might error if resource not found
    let result = timeout(Duration::from_millis(500), client_io.read_line()).await;

    if let Ok(Ok(Some(response_line))) = result {
        let response: serde_json::Value = serde_json::from_str(&response_line).unwrap();
        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["id"], 7);
        // Response should be either a result or an error
        assert!(response["result"].is_object() || response["error"].is_object());
    } else {
        // Server may have errored - that's acceptable for this test
        drop(client_io);
        let _ = timeout(Duration::from_secs(1), server_handle).await;
    }
}

// ============================================================================
// Prompts Tests
// ============================================================================

#[tokio::test]
async fn test_prompts_list() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let prompts_list_request = json!({
        "jsonrpc": "2.0",
        "id": 8,
        "method": "prompts/list"
    });

    let response = send_request_read_response(&mut client_io, prompts_list_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 8);
    validate_result("2025-11-25", "ListPromptsResult", &response);
}

#[tokio::test]
async fn test_prompts_get() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    let server_handle =
        tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let prompts_get_request = json!({
        "jsonrpc": "2.0",
        "id": 9,
        "method": "prompts/get",
        "params": {
            "name": "task_summary",
            "arguments": {}
        }
    });

    // Send request
    let request_str = serde_json::to_string(&prompts_get_request).unwrap();
    client_io.write_line(&request_str).await.unwrap();
    client_io.flush().await.unwrap();

    // Try to read response - server might error if prompt not found
    let result = timeout(Duration::from_millis(500), client_io.read_line()).await;

    if let Ok(Ok(Some(response_line))) = result {
        let response: serde_json::Value = serde_json::from_str(&response_line).unwrap();
        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["id"], 9);
        // Response should be either a result or an error
        assert!(response["result"].is_object() || response["error"].is_object());
    } else {
        // Server may have errored - that's acceptable for this test
        drop(client_io);
        let _ = timeout(Duration::from_secs(1), server_handle).await;
    }
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn test_malformed_json() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    let server_handle =
        tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Send malformed JSON
    client_io.write_line("{invalid json}").await.unwrap();
    client_io.flush().await.unwrap();

    // Server should handle error gracefully and continue or terminate
    // Close client
    drop(client_io);

    // Server should complete (may error due to malformed JSON)
    let result = timeout(Duration::from_secs(2), server_handle).await;
    assert!(result.is_ok(), "Server should complete");
}

#[tokio::test]
async fn test_missing_method() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let request_without_method = json!({
        "jsonrpc": "2.0",
        "id": 10,
        "params": {}
    });

    // This should cause an error on the server side
    let request_str = serde_json::to_string(&request_without_method).unwrap();
    client_io.write_line(&request_str).await.unwrap();
    client_io.flush().await.unwrap();

    // Try to read response (server might close connection or return error)
    let result = timeout(Duration::from_millis(500), client_io.read_line()).await;

    // Either we get a response or timeout (both acceptable)
    assert!(result.is_ok() || result.is_err());
}

#[tokio::test]
async fn test_unknown_method() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    let unknown_method_request = json!({
        "jsonrpc": "2.0",
        "id": 11,
        "method": "unknown/method"
    });

    let response = send_request_read_response(&mut client_io, unknown_method_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 11);
    // Should return error for unknown method
    assert!(response["error"].is_object());
    assert_eq!(response["error"]["code"], -32601); // Method not found
}

#[tokio::test]
async fn test_empty_line_handling() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Send empty lines (should be ignored)
    client_io.write_line("").await.unwrap();
    client_io.write_line("").await.unwrap();
    client_io.flush().await.unwrap();

    // Send valid request after empty lines
    let valid_request = json!({
        "jsonrpc": "2.0",
        "id": 12,
        "method": "tools/list"
    });

    let response = send_request_read_response(&mut client_io, valid_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 12);
    // tools/list returns an object with a tools array
    assert!(response["result"]["tools"].is_array());
}

// ============================================================================
// Multiple Request Tests
// ============================================================================

#[tokio::test]
async fn test_multiple_sequential_requests() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(8192);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Send multiple requests
    for i in 1..=5 {
        let request = json!({
            "jsonrpc": "2.0",
            "id": i,
            "method": "tools/list"
        });

        let response = send_request_read_response(&mut client_io, request).await;

        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["id"], i);
        // tools/list returns an object with a tools array
        assert!(response["result"]["tools"].is_array());
    }
}

#[tokio::test]
async fn test_notification_no_response() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Send notification (no id field)
    let notification = json!({
        "jsonrpc": "2.0",
        "method": "notifications/initialized"
    });

    let notification_str = serde_json::to_string(&notification).unwrap();
    client_io.write_line(&notification_str).await.unwrap();
    client_io.flush().await.unwrap();

    // Send a regular request to verify server is still responsive
    let request = json!({
        "jsonrpc": "2.0",
        "id": 13,
        "method": "tools/list"
    });

    let response = send_request_read_response(&mut client_io, request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 13);
}

// ============================================================================
// start_mcp_server_with_config_generic Tests
// ============================================================================

#[tokio::test]
async fn test_start_mcp_server_with_config() {
    use things3_cli::mcp::start_mcp_server_with_config_generic;
    use things3_core::McpServerConfig;

    let (_temp, db) = create_test_db().await;

    // Create MCP config
    let mcp_config = McpServerConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move {
        start_mcp_server_with_config_generic(db, mcp_config, server_io, true).await
    });

    // Test that server works with config
    let initialize_request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {}
    });

    let response = send_request_read_response(&mut client_io, initialize_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 1);
    assert_eq!(response["result"]["protocolVersion"], "2024-11-05");
}

#[tokio::test]
async fn test_start_mcp_server_with_config_tools() {
    use things3_cli::mcp::start_mcp_server_with_config_generic;
    use things3_core::McpServerConfig;

    let (_temp, db) = create_test_db().await;
    let mcp_config = McpServerConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move {
        start_mcp_server_with_config_generic(db, mcp_config, server_io, true).await
    });

    // Test tools/call with config
    let tools_call_request = json!({
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/call",
        "params": {
            "name": "get_today",
            "arguments": {}
        }
    });

    let response = send_request_read_response(&mut client_io, tools_call_request).await;

    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 2);
    assert!(response["result"].is_object());
}

#[tokio::test]
async fn test_io_error_handling() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, client_io) = MockIo::create_pair(4096);

    let server_handle =
        tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Drop client immediately to trigger EOF
    drop(client_io);

    // Server should exit gracefully on EOF
    let result = timeout(Duration::from_secs(2), server_handle).await;
    assert!(result.is_ok(), "Server should handle EOF gracefully");
    assert!(result.unwrap().is_ok(), "Server should not error on EOF");
}

// ============================================================================
// Additional Coverage Tests
// ============================================================================

#[tokio::test]
async fn test_json_serialization_coverage() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Test various request types to cover more code paths
    let requests = vec![
        json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}),
        json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
        json!({"jsonrpc": "2.0", "id": 3, "method": "resources/list"}),
        json!({"jsonrpc": "2.0", "id": 4, "method": "prompts/list"}),
    ];

    for request in requests {
        let response = send_request_read_response(&mut client_io, request).await;
        assert_eq!(response["jsonrpc"], "2.0");
    }
}

#[tokio::test]
async fn test_mixed_requests_and_notifications() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Send a mix of requests and notifications
    let notification = json!({
        "jsonrpc": "2.0",
        "method": "notifications/custom"
    });

    let notification_str = serde_json::to_string(&notification).unwrap();
    client_io.write_line(&notification_str).await.unwrap();
    client_io.flush().await.unwrap();

    // Send a request to verify server is still responsive
    let request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/list"
    });

    let response = send_request_read_response(&mut client_io, request).await;
    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 1);
}

#[tokio::test]
async fn test_all_available_tools() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(8192);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Get list of tools
    let tools_list_request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/list"
    });

    let response = send_request_read_response(&mut client_io, tools_list_request).await;
    let tools = response["result"]["tools"].as_array().unwrap();

    assert!(!tools.is_empty(), "Should have at least one tool");

    // Test calling get_today and get_inbox (most common tools)
    let tool_tests = ["get_today", "get_inbox"];

    for (idx, tool_name) in tool_tests.iter().enumerate() {
        let tools_call_request = json!({
            "jsonrpc": "2.0",
            "id": idx + 2,
            "method": "tools/call",
            "params": {
                "name": tool_name,
                "arguments": {}
            }
        });

        let response = send_request_read_response(&mut client_io, tools_call_request).await;
        assert_eq!(response["jsonrpc"], "2.0");
        assert!(response["result"].is_object());
    }
}

#[tokio::test]
async fn test_large_response_handling() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(65536); // Large buffer

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Request that might return large data
    let request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "get_projects",
            "arguments": {}
        }
    });

    let response = send_request_read_response(&mut client_io, request).await;
    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 1);
}

#[tokio::test]
async fn test_sequential_initialize_calls() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Call initialize multiple times (should handle gracefully)
    for i in 1..=3 {
        let initialize_request = json!({
            "jsonrpc": "2.0",
            "id": i,
            "method": "initialize",
            "params": {}
        });

        let response = send_request_read_response(&mut client_io, initialize_request).await;
        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["id"], i);
        assert_eq!(response["result"]["protocolVersion"], "2024-11-05");
    }
}

#[tokio::test]
async fn test_config_with_empty_lines() {
    use things3_cli::mcp::start_mcp_server_with_config_generic;
    use things3_core::McpServerConfig;

    let (_temp, db) = create_test_db().await;
    let mcp_config = McpServerConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(4096);

    tokio::spawn(async move {
        start_mcp_server_with_config_generic(db, mcp_config, server_io, true).await
    });

    // Send empty lines (should be skipped)
    client_io.write_line("").await.unwrap();
    client_io.write_line("").await.unwrap();
    client_io.flush().await.unwrap();

    // Send valid request
    let request = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {}
    });

    let response = send_request_read_response(&mut client_io, request).await;
    assert_eq!(response["jsonrpc"], "2.0");
    assert_eq!(response["id"], 1);
}

#[tokio::test]
async fn test_rapid_requests() {
    let (_temp, db) = create_test_db().await;
    let config = ThingsConfig::default();

    let (server_io, mut client_io) = MockIo::create_pair(32768); // Extra large buffer

    tokio::spawn(async move { start_mcp_server_generic(db, config, server_io, true).await });

    // Send many requests rapidly
    for i in 1..=20 {
        let request = json!({
            "jsonrpc": "2.0",
            "id": i,
            "method": "tools/list"
        });

        let response = send_request_read_response(&mut client_io, request).await;
        assert_eq!(response["jsonrpc"], "2.0");
        assert_eq!(response["id"], i);
    }
}