knowyourbusiness 0.3.3

Git-backed, searchable knowledge base and incident tracker for AI agent fleets
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
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
/*
 * KYB (Know Your Business) — git-backed knowledge base and incident tracker for AI agent fleets
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/kyb
 * SPDX-License-Identifier: MIT
 */

//! MCP served by the knowledge base itself, over HTTP.
//!
//! `POST /mcp`, and `claude mcp add --transport http kyb http://<host>:9310/mcp`
//! is the entire client-side setup. Nothing is installed and nothing needs
//! updating when the server gains a capability.
//!
//! WHY IN THE SERVER RATHER THAN IN A CLIENT.
//!
//! A client cannot know what a server is. It has to ask, and then trust the
//! answer, and then decide what to do when it cannot get one - because a server
//! that predates a parameter does not reject it, it ignores the name and answers
//! the question it DID understand. Ask such a server what was true last Tuesday
//! and you get today's data with a 200, which is indistinguishable from a past in
//! which nothing changed. A client can only defend against that by refusing.
//!
//! A server has no such problem. `tools/list` here is built from the routes this
//! binary actually has, so the advertised surface and the real surface cannot
//! disagree - not "are checked and found to agree", cannot. The failure mode is
//! designed out rather than guarded against.
//!
//! DISPATCH. A tool call is translated into an ordinary HTTP request and run
//! through the same Router that serves the public API, rather than calling the
//! model layer directly. That is deliberate: there is exactly one implementation
//! of what `POST /knowledge` means, the audit log sees MCP-driven writes like any
//! other write, and a route that changes changes here too without anyone
//! remembering to update a second copy.
//!
//! EXPOSURE. This adds no new reach. `POST /knowledge` and `DELETE
//! /knowledge/{key}` already answer unauthenticated on this port, so /mcp is
//! exactly as open as the rest of the API and no more - see the note on binding
//! in config.rs. `?readonly=1` drops the writing tools for one registration; it
//! is a guard rail for an agent, not a security boundary, since anyone may
//! simply not pass it.
//!
//! NOT A REPLACEMENT FOR THE CLI. A deploy script, an ssh one-liner on a fleet
//! node, cron and a person at a terminal all need `kyb`, and MCP reaches none of
//! them.

use axum::body::{Body, Bytes};
use axum::extract::{ConnectInfo, Request as ExtractRequest, State};
use axum::http::{header, Request, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::Router;
use serde_json::{json, Value};
use std::net::SocketAddr;
use std::sync::Arc;
use tower::util::ServiceExt;

/// Newest first. A client asking for one of these is answered with that exact
/// version; anything else is answered with the newest, which lets the client
/// decide whether to continue.
const PROTOCOL_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];

const INSTRUCTIONS: &str = "\
KYB is a shared, versioned knowledge base about this fleet's own infrastructure - hosts, \
services, ports, deploys, architecture decisions, incidents and tasks. Query it before \
reasoning about infrastructure instead of guessing, and write back what you verified. \
Writing the same key again adds a version rather than overwriting, so a superseded fact \
stays searchable and an answer from the past is marked as one. A read answer carries a \
`deadlines` block when a task is late or inside its reminder window: act on it, or say so.";

/// Deliberately not exposed: `rm` and `reindex`. Retracting an entry and
/// rebuilding the index should not be something an agent reaches for mid-thought,
/// and both stay one CLI command away for a person who means it.
const WRITE_TOOLS: [&str; 6] =
    ["kyb_add", "kyb_incident", "kyb_resolve", "kyb_task", "kyb_task_status", "kyb_done"];

pub struct McpState {
    /// The public API router. Tool calls are replayed through it.
    api: Router,
}

/// `/mcp` is not wrapped in the audit layer: the request it forwards is, so a
/// write shows up once as what it actually did rather than twice.
pub fn router(api: Router) -> Router {
    Router::new()
        .route("/mcp", post(mcp_post).get(no_stream).delete(no_stream))
        .with_state(Arc::new(McpState { api }))
}

async fn no_stream() -> Response {
    // The spec allows a server with no server-to-client stream and no sessions to
    // refuse GET and DELETE. Saying so beats an unexplained 405.
    (
        StatusCode::METHOD_NOT_ALLOWED,
        [(header::ALLOW, "POST")],
        axum::Json(json!({
            "error": "this endpoint is stateless: no server-initiated stream, no sessions. \
                      POST JSON-RPC to /mcp."
        })),
    )
        .into_response()
}

/// A tool call carrying a whole knowledge entry is the large case; anything past
/// this is not a request we want to buffer.
const MAX_BODY: usize = 8 * 1024 * 1024;

/// Taking the request whole rather than as extractors: the client address lives
/// in the extensions and has to survive into the forwarded call.
async fn mcp_post(State(st): State<Arc<McpState>>, req: ExtractRequest) -> Response {
    let readonly = req.uri().query().is_some_and(|q| {
        q.split('&').any(|p| matches!(p, "readonly" | "readonly=1" | "readonly=true"))
    });
    let connect = req.extensions().get::<ConnectInfo<SocketAddr>>().cloned();
    // the caller's token travels with each replayed call: the API decides, per tool, what it may do
    let bearer = req.headers().get(header::AUTHORIZATION).cloned();
    // attribution headers on the MCP request itself: a client with no hook and no metadata
    let headers_by = crate::auth::By::from_headers(req.headers());

    let body: Bytes = match axum::body::to_bytes(req.into_body(), MAX_BODY).await {
        Ok(b) => b,
        Err(_) => {
            return json_body(
                StatusCode::PAYLOAD_TOO_LARGE,
                rpc_error(Value::Null, -32600, "request body too large"),
            )
        }
    };

    let parsed: Value = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => {
            return json_body(
                StatusCode::BAD_REQUEST,
                rpc_error(Value::Null, -32700, &format!("parse error: {e}")),
            )
        }
    };

    let (messages, was_batch) = match parsed {
        Value::Array(items) => (items, true),
        Value::Object(_) => (vec![parsed], false),
        _ => {
            return json_body(
                StatusCode::BAD_REQUEST,
                rpc_error(Value::Null, -32600, "invalid request: expected an object or an array"),
            )
        }
    };

    let mut out = Vec::new();
    for msg in &messages {
        if let Some(resp) = handle_one(&st, readonly, connect.as_ref(), bearer.as_ref(), headers_by.as_ref(), msg).await {
            out.push(resp);
        }
    }

    // Nothing but notifications: the spec wants an empty 202, not an empty body
    // dressed as a result.
    if out.is_empty() {
        return StatusCode::ACCEPTED.into_response();
    }
    let payload = if was_batch { Value::Array(out) } else { out.swap_remove(0) };
    json_body(StatusCode::OK, payload)
}

async fn handle_one(
    st: &McpState,
    readonly: bool,
    connect: Option<&ConnectInfo<SocketAddr>>,
    bearer: Option<&axum::http::HeaderValue>,
    headers_by: Option<&crate::auth::By>,
    msg: &Value,
) -> Option<Value> {
    // No id, or a null one, means a notification: the spec forbids answering it.
    let id = match msg.get("id") {
        None | Some(Value::Null) => return None,
        Some(v) => v.clone(),
    };
    let method = msg.get("method").and_then(Value::as_str).unwrap_or_default();
    let params = msg.get("params").cloned().unwrap_or_else(|| json!({}));

    Some(match method {
        "initialize" => rpc_ok(id, initialize(&params)),
        "ping" => rpc_ok(id, json!({})),
        "tools/list" => rpc_ok(id, json!({"tools": tools(readonly)})),
        "tools/call" => match call_tool(st, readonly, connect, bearer, headers_by, &params).await {
            Ok(value) => rpc_ok(id, value),
            Err((code, message)) => rpc_error(id, code, &message),
        },
        other => rpc_error(id, -32601, &format!("method not found: {other}")),
    })
}

fn initialize(params: &Value) -> Value {
    let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or_default();
    let version =
        if PROTOCOL_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSIONS[0] };
    json!({
        "protocolVersion": version,
        "capabilities": {"tools": {"listChanged": false}},
        // Straight from the crate: a version printed here can never drift from
        // the one that was built.
        "serverInfo": {"name": "kyb", "version": env!("CARGO_PKG_VERSION")},
        "instructions": INSTRUCTIONS,
    })
}

// --------------------------------------------------------------- JSON-RPC glue

fn rpc_ok(id: Value, result: Value) -> Value {
    json!({"jsonrpc": "2.0", "id": id, "result": result})
}

fn rpc_error(id: Value, code: i64, message: &str) -> Value {
    json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
}

fn json_body(status: StatusCode, payload: Value) -> Response {
    (status, axum::Json(payload)).into_response()
}

/// A failure the model should see and react to, rather than one the client
/// should treat as a protocol fault.
fn tool_error(message: String) -> Value {
    json!({"content": [{"type": "text", "text": message}], "isError": true})
}

fn tool_text(text: String) -> Value {
    json!({"content": [{"type": "text", "text": text}]})
}

// ------------------------------------------------------------------ dispatch

struct Call {
    method: &'static str,
    path: String,
    query: Vec<(&'static str, String)>,
    body: Option<Value>,
}

async fn call_tool(
    st: &McpState,
    readonly: bool,
    connect: Option<&ConnectInfo<SocketAddr>>,
    bearer: Option<&axum::http::HeaderValue>,
    headers_by: Option<&crate::auth::By>,
    params: &Value,
) -> Result<Value, (i64, String)> {
    let name = match params.get("name").and_then(Value::as_str) {
        Some(n) if !n.is_empty() => n,
        _ => return Err((-32602, "tools/call requires a string `name`".into())),
    };
    let mut args = params.get("arguments").cloned().unwrap_or_else(|| json!({}));
    if !args.is_object() {
        return Err((-32602, "`arguments` must be an object".into()));
    }
    // Who is calling, as far as the client says. `_ctx` is put into the arguments
    // by an agent hook (it is not a tool parameter and never reaches the API);
    // the client's own call metadata names the conversation; the request's own
    // X-Kyb headers are the fallback for a client that has neither.
    let by = attribution(args.as_object_mut().and_then(|o| o.remove("_ctx")), params.get("_meta"), headers_by);
    if readonly && WRITE_TOOLS.contains(&name) {
        return Ok(tool_error(format!(
            "{name} is a write and this endpoint was opened read-only (?readonly=1)."
        )));
    }

    let call = match plan(name, &args) {
        Ok(call) => call,
        Err(message) => return Ok(tool_error(message)),
    };
    let (status, text) = forward(st, connect, bearer, by.as_ref(), call).await;
    if status.is_success() {
        Ok(tool_text(text.trim().to_string()))
    } else {
        Ok(tool_error(format!("kyb answered HTTP {}: {}", status.as_u16(), text.trim())))
    }
}

/// The attribution of one tool call, field by field: a hook's `_ctx` (agent,
/// session, workspace) first; then the `_meta` the MCP client attached -
/// Antigravity and Codex name their conversation there, Claude Code only the
/// tool use, so only the agent; then the X-Kyb headers of the request. A field
/// a higher source left empty is taken from the next one, never overwritten by
/// an empty value. `via` names the source of the agent field.
fn attribution(ctx: Option<Value>, meta: Option<&Value>, headers: Option<&crate::auth::By>) -> Option<crate::auth::By> {
    use crate::auth::By;
    let s = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
    let from_ctx = ctx
        .filter(Value::is_object)
        .map(|c| By::new(&s(&c, "agent"), &s(&c, "session"), &s(&c, "workspace"), "hook"))
        .filter(|b| !b.is_empty());
    let from_meta = meta.and_then(|m| {
        if let Some(id) = m.get("antigravity.google/conversation_id").and_then(Value::as_str) {
            return Some(By::new("antigravity", id, "", "meta"));
        }
        if let Some(turn) = m.get("x-codex-turn-metadata") {
            // an object, or the same object JSON-encoded as a string
            let decoded = turn.as_str().and_then(|t| serde_json::from_str::<Value>(t).ok());
            let turn = decoded.as_ref().unwrap_or(turn);
            let id = ["session_id", "thread_id"].iter().find_map(|k| turn.get(k).and_then(Value::as_str)).unwrap_or_default();
            return Some(By::new("codex", id, "", "meta"));
        }
        if m.get("claudecode/toolUseId").is_some() {
            return Some(By::new("claude", "", "", "meta"));
        }
        None
    });
    let from_headers = headers.cloned().map(|mut h| {
        if h.via.is_empty() {
            h.via = "headers".into();
        }
        h
    });
    // The agent is the first source's that names one, and its session comes with
    // it. A session from another source is taken only when that source names no
    // agent or the same one: a session is a conversation of one agent, and a
    // source that names a different agent is talking about a different
    // conversation. The workspace is a place, not a conversation, and is filled
    // from any source.
    let mut out = By::default();
    let sources: Vec<By> = [from_ctx, from_meta, from_headers].into_iter().flatten().collect();
    if let Some(named) = sources.iter().find(|s| !s.agent.is_empty()) {
        out.agent = named.agent.clone();
        out.via = named.via.clone();
        out.session = named.session.clone();
    }
    for src in &sources {
        if out.session.is_empty() && !src.session.is_empty() && (src.agent.is_empty() || src.agent == out.agent) {
            out.session = src.session.clone();
        }
        if out.workspace.is_empty() {
            out.workspace = src.workspace.clone();
        }
    }
    if out.is_empty() {
        None
    } else {
        if out.via.is_empty() {
            out.via = "headers".into();
        }
        Some(out)
    }
}

async fn forward(
    st: &McpState,
    connect: Option<&ConnectInfo<SocketAddr>>,
    bearer: Option<&axum::http::HeaderValue>,
    by: Option<&crate::auth::By>,
    call: Call,
) -> (StatusCode, String) {
    let mut uri = call.path;
    if !call.query.is_empty() {
        let pairs: Vec<String> =
            call.query.iter().map(|(k, v)| format!("{k}={}", encode(v))).collect();
        uri.push('?');
        uri.push_str(&pairs.join("&"));
    }
    let builder = Request::builder().method(call.method).uri(uri);
    let mut req = match call.body {
        Some(value) => builder
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(value.to_string())),
        None => builder.body(Body::empty()),
    }
    .expect("request built from a known-good method and uri");
    // Carry the caller through, so the audit log attributes an MCP-driven write
    // to the machine that asked for it rather than to nobody.
    if let Some(info) = connect {
        req.extensions_mut().insert(*info);
    }
    if let Some(token) = bearer {
        req.headers_mut().insert(header::AUTHORIZATION, token.clone());
    }
    if let Some(by) = by {
        for (name, value) in [("x-kyb-agent", &by.agent), ("x-kyb-session", &by.session), ("x-kyb-workspace", &by.workspace), ("x-kyb-via", &by.via)] {
            if let Ok(v) = axum::http::HeaderValue::from_str(value) {
                req.headers_mut().insert(name, v);
            }
        }
    }

    let resp = st.api.clone().oneshot(req).await.expect("the router is infallible");
    let status = resp.status();
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap_or_default();
    (status, String::from_utf8_lossy(&bytes).into_owned())
}

fn encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.as_bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(*b as char)
            }
            other => out.push_str(&format!("%{other:02X}")),
        }
    }
    out
}

// ------------------------------------------------------------ argument helpers

fn text_arg(args: &Value, key: &str) -> Option<String> {
    match args.get(key) {
        Some(Value::String(s)) if !s.trim().is_empty() => Some(s.clone()),
        Some(Value::Number(n)) => Some(n.to_string()),
        _ => None,
    }
}

/// A model sends a real boolean or the string "true" depending on the day.
/// Accept both; anything else is absent rather than guessed at.
fn flag_arg(args: &Value, key: &str) -> Option<String> {
    match args.get(key) {
        Some(Value::Bool(true)) => Some("true".into()),
        Some(Value::String(s)) if matches!(s.to_lowercase().as_str(), "1" | "true" | "yes") => {
            Some("true".into())
        }
        _ => None,
    }
}

/// Tags and refs arrive as a list or as one comma-separated string. Both are
/// reasonable readings of the schema, so both are accepted.
fn list_arg(args: &Value, key: &str) -> Vec<String> {
    match args.get(key) {
        Some(Value::Array(items)) => items
            .iter()
            .filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()))
            .map(str::to_string)
            .collect(),
        Some(Value::String(s)) => {
            s.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect()
        }
        _ => Vec::new(),
    }
}

fn require(args: &Value, keys: &[&str]) -> Result<(), String> {
    let missing: Vec<&str> = keys.iter().copied().filter(|k| text_arg(args, k).is_none()).collect();
    if missing.is_empty() {
        Ok(())
    } else {
        Err(format!("missing required argument(s): {}", missing.join(", ")))
    }
}

fn push(query: &mut Vec<(&'static str, String)>, key: &'static str, value: Option<String>) {
    if let Some(v) = value {
        query.push((key, v));
    }
}

/// `deadlines: false` on a read tool leaves the deadline block off its answer.
fn no_deadlines(args: &Value, query: &mut Vec<(&'static str, String)>) {
    let off = match args.get("deadlines") {
        Some(Value::Bool(b)) => !b,
        Some(Value::String(s)) => matches!(s.to_lowercase().as_str(), "false" | "0" | "no"),
        _ => false,
    };
    if off {
        query.push(("deadlines", "false".into()));
    }
}

/// The deadline fields travel only when the call names them: a field left out
/// keeps what the task already says, and an empty string clears it -
/// `remind_days: ""` returns it to the server default.
///
/// `null` is read as "not named", as kyb_task_status already reads it: models
/// fill unused optional arguments with null, and a null that cleared would wipe
/// a deadline on an ordinary rewrite. The HTTP API, whose callers mean what they
/// send, takes null as a clear.
/// Tags travel only when the call names them. The server keeps the stored tags of
/// an incident or a task that a write leaves them out of, so a rewrite over MCP
/// must not send an empty list it was never given. `null` is "not named", as
/// everywhere on this surface; `[]` or `""` clears.
fn named_tags(args: &Value, body: &mut Value) {
    if args.get("tags").is_some_and(|v| !v.is_null()) {
        body["tags"] = json!(list_arg(args, "tags"));
    }
}

fn deadline_fields(args: &Value, body: &mut Value) -> Result<(), String> {
    for field in ["due", "waits_on", "expected"] {
        match args.get(field) {
            None | Some(Value::Null) => {}
            Some(Value::String(s)) => body[field] = json!(s),
            Some(_) => return Err(format!("`{field}` must be a string")),
        }
    }
    match args.get("hard") {
        None | Some(Value::Null) => {}
        Some(Value::Bool(b)) => body["hard"] = json!(b),
        Some(Value::String(s)) => match s.to_lowercase().as_str() {
            "true" | "1" | "yes" => body["hard"] = json!(true),
            "false" | "0" | "no" => body["hard"] = json!(false),
            _ => return Err("`hard` must be true or false".into()),
        },
        Some(_) => return Err("`hard` must be true or false".into()),
    }
    match args.get("remind_days") {
        None | Some(Value::Null) => {}
        Some(Value::String(s)) if s.trim().is_empty() => body["remind_days"] = Value::Null,
        Some(v) => {
            let days = match v {
                Value::Number(n) => n.as_u64().and_then(|d| u32::try_from(d).ok()),
                Value::String(s) => s.trim().parse::<u32>().ok(),
                _ => None,
            };
            match days {
                Some(d) => body["remind_days"] = json!(d),
                None => {
                    return Err(
                        "`remind_days` must be a whole number of days, or \"\" for the default".into()
                    )
                }
            }
        }
    }
    Ok(())
}

fn plan(name: &str, args: &Value) -> Result<Call, String> {
    let call = match name {
        "kyb_query" => {
            require(args, &["q"])?;
            let mut query = Vec::new();
            push(&mut query, "q", text_arg(args, "q"));
            push(&mut query, "tag", text_arg(args, "tag"));
            push(&mut query, "kind", text_arg(args, "kind"));
            push(&mut query, "status", text_arg(args, "status"));
            push(&mut query, "service", text_arg(args, "service"));
            push(&mut query, "priority", text_arg(args, "priority"));
            push(&mut query, "assignee", text_arg(args, "assignee"));
            push(&mut query, "parent_task", text_arg(args, "parent_task"));
            push(&mut query, "limit", text_arg(args, "limit"));
            push(&mut query, "history", flag_arg(args, "history"));
            push(&mut query, "as_of", text_arg(args, "as_of"));
            push(&mut query, "changed_between", text_arg(args, "changed_between"));
            if flag_arg(args, "recent").is_some() {
                query.push(("sort", "recent".into()));
            }
            if args.get("semantic") == Some(&Value::Bool(false)) {
                query.push(("semantic", "false".into()));
            }
            no_deadlines(args, &mut query);
            Call { method: "GET", path: "/search".into(), query, body: None }
        }
        "kyb_get" => {
            require(args, &["key"])?;
            let mut query = Vec::new();
            push(&mut query, "at", text_arg(args, "at"));
            no_deadlines(args, &mut query);
            Call {
                method: "GET",
                path: format!("/knowledge/{}", text_arg(args, "key").unwrap_or_default()),
                query,
                body: None,
            }
        }
        "kyb_diff" => {
            require(args, &["key"])?;
            let mut query = Vec::new();
            push(&mut query, "from", text_arg(args, "from"));
            push(&mut query, "to", text_arg(args, "to"));
            Call {
                method: "GET",
                path: format!("/knowledge/{}/diff", text_arg(args, "key").unwrap_or_default()),
                query,
                body: None,
            }
        }
        "kyb_history" => {
            require(args, &["key"])?;
            Call {
                method: "GET",
                path: format!("/knowledge/{}/history", text_arg(args, "key").unwrap_or_default()),
                query: Vec::new(),
                body: None,
            }
        }
        "kyb_tags" => {
            Call { method: "GET", path: "/tags".into(), query: Vec::new(), body: None }
        }
        "kyb_health" => {
            Call { method: "GET", path: "/healthz".into(), query: Vec::new(), body: None }
        }
        "kyb_incidents" => {
            let mut query = Vec::new();
            push(&mut query, "status", text_arg(args, "status"));
            push(&mut query, "service", text_arg(args, "service"));
            push(&mut query, "all", flag_arg(args, "all"));
            push(&mut query, "limit", text_arg(args, "limit"));
            if flag_arg(args, "followups").is_some() {
                query.push(("followups", "open".into()));
            }
            no_deadlines(args, &mut query);
            Call { method: "GET", path: "/incidents".into(), query, body: None }
        }
        "kyb_tasks" => {
            let mut query = Vec::new();
            push(&mut query, "status", text_arg(args, "status"));
            push(&mut query, "priority", text_arg(args, "priority"));
            push(&mut query, "assignee", text_arg(args, "assignee"));
            push(&mut query, "parent_task", text_arg(args, "parent_task"));
            push(&mut query, "all", flag_arg(args, "all"));
            push(&mut query, "limit", text_arg(args, "limit"));
            if flag_arg(args, "followups").is_some() {
                query.push(("followups", "open".into()));
            }
            no_deadlines(args, &mut query);
            Call { method: "GET", path: "/tasks".into(), query, body: None }
        }
        "kyb_deadlines" => {
            let mut query = Vec::new();
            push(&mut query, "within", text_arg(args, "within"));
            push(&mut query, "overdue", flag_arg(args, "overdue"));
            push(&mut query, "hard", flag_arg(args, "hard"));
            push(&mut query, "tag", text_arg(args, "tag"));
            push(&mut query, "assignee", text_arg(args, "assignee"));
            Call { method: "GET", path: "/deadlines".into(), query, body: None }
        }
        "kyb_add" => {
            require(args, &["key", "title", "body"])?;
            Call {
                method: "POST",
                path: "/knowledge".into(),
                query: Vec::new(),
                body: Some(json!({
                    "key": text_arg(args, "key"),
                    "title": text_arg(args, "title"),
                    "body": text_arg(args, "body"),
                    "tags": list_arg(args, "tags"),
                    "refs": list_arg(args, "refs"),
                })),
            }
        }
        "kyb_incident" => {
            require(args, &["key", "title", "service", "severity", "body"])?;
            let affected = match args.get("affected") {
                None | Some(Value::Null) => json!([]),
                Some(Value::Array(items)) => json!(items),
                Some(_) => {
                    return Err("`affected` must be a list of {scope, from, to} objects".into())
                }
            };
            let mut body = json!({
                "key": text_arg(args, "key"),
                "title": text_arg(args, "title"),
                "body": text_arg(args, "body"),
                "service": text_arg(args, "service"),
                "severity": text_arg(args, "severity"),
                "status": text_arg(args, "status").unwrap_or_else(|| "open".into()),
                "hosts": list_arg(args, "hosts"),
                "knowledge": list_arg(args, "knowledge"),
                "resolution": text_arg(args, "resolution").unwrap_or_default(),
                "detection": text_arg(args, "detection").unwrap_or_default(),
                "affected": affected,
                "started_at": text_arg(args, "started_at").unwrap_or_default(),
                "detected_at": text_arg(args, "detected_at").unwrap_or_default(),
                "refs": list_arg(args, "refs"),
            });
            named_tags(args, &mut body);
            Call { method: "POST", path: "/incidents".into(), query: Vec::new(), body: Some(body) }
        }
        "kyb_resolve" => {
            require(args, &["key", "resolution"])?;
            Call {
                method: "POST",
                path: format!(
                    "/incidents/{}/resolve",
                    text_arg(args, "key").unwrap_or_default()
                ),
                query: Vec::new(),
                body: Some(json!({
                    "status": text_arg(args, "status").unwrap_or_else(|| "resolved".into()),
                    "resolution": text_arg(args, "resolution"),
                })),
            }
        }
        "kyb_task" => {
            require(args, &["key", "title", "body"])?;
            let mut body = json!({
                "key": text_arg(args, "key"),
                "title": text_arg(args, "title"),
                "body": text_arg(args, "body"),
                "status": text_arg(args, "status").unwrap_or_else(|| "open".into()),
                "priority": text_arg(args, "priority").unwrap_or_default(),
                "blocked_reason": text_arg(args, "blocked_reason").unwrap_or_default(),
                "assignee": text_arg(args, "assignee").unwrap_or_default(),
                "parent_task": text_arg(args, "parent_task").unwrap_or_default(),
                "knowledge": list_arg(args, "knowledge"),
                "resolution": text_arg(args, "resolution").unwrap_or_default(),
                "refs": list_arg(args, "refs"),
            });
            named_tags(args, &mut body);
            deadline_fields(args, &mut body)?;
            Call { method: "POST", path: "/tasks".into(), query: Vec::new(), body: Some(body) }
        }
        "kyb_task_status" => {
            require(args, &["key"])?;
            // Only the fields actually supplied travel: everything omitted keeps
            // what the task already says. An empty-string assignee is a value -
            // it hands the task back - so presence is what counts, not emptiness.
            // Without a status the task keeps its own, which is how a deadline
            // alone is moved.
            let mut body = json!({});
            if let Some(status) = text_arg(args, "status") {
                body["status"] = json!(status);
            }
            deadline_fields(args, &mut body)?;
            for field in ["assignee", "parent_task", "blocked_reason"] {
                if let Some(value) = args.get(field) {
                    if !value.is_null() {
                        body[field] = value.clone();
                    }
                }
            }
            Call {
                method: "POST",
                path: format!(
                    "/tasks/{}/transition",
                    text_arg(args, "key").unwrap_or_default()
                ),
                query: Vec::new(),
                body: Some(body),
            }
        }
        "kyb_done" => {
            require(args, &["key", "resolution"])?;
            Call {
                method: "POST",
                path: format!("/tasks/{}/resolve", text_arg(args, "key").unwrap_or_default()),
                query: Vec::new(),
                body: Some(json!({
                    "status": text_arg(args, "status").unwrap_or_else(|| "done".into()),
                    "resolution": text_arg(args, "resolution"),
                })),
            }
        }
        other => return Err(format!("no such tool: {other}")),
    };
    Ok(call)
}

// ------------------------------------------------------------- tool schemas

/// What this binary can actually do. There is no negotiation and no fallback:
/// the list is the routes that exist in this build, so it cannot promise a
/// capability the server does not have.
fn tools(readonly: bool) -> Vec<Value> {
    let str_t = json!({"type": "string"});
    let int_t = json!({"type": "integer"});
    let list_t = json!({
        "anyOf": [{"type": "array", "items": {"type": "string"}}, {"type": "string"}],
        "description": "a list, or one comma-separated string"
    });
    let deadlines_t = json!({"type": "boolean", "description": "false leaves the deadline block \
(late and nearly due tasks) off this answer"});
    let date_t = |what: &str| {
        json!({"type": "string", "description": format!("{what}: YYYY-MM-DD, \
or a date-time with its zone such as 2026-03-14T17:00:00-07:00; an empty string clears it")})
    };

    let all = vec![
        json!({
            "name": "kyb_query",
            "description": "Search the shared infrastructure knowledge base: hosts, services, \
ports, deploys, architecture decisions, incident reports and tasks. Hybrid - BM25 fused with \
multilingual embeddings - so a question phrased differently from the entry still finds it, in \
any language. Query this before reasoning about infrastructure; one phrasing is not a search, \
try a couple.",
            "inputSchema": {"type": "object", "required": ["q"], "properties": {
                "q": {"type": "string", "description": "what you are looking for, in any language"},
                "tag": {"type": "string", "description": "restrict to these tags, comma-separated"},
                "kind": {"type": "string", "enum": ["knowledge", "incident", "task"],
                         "description": "restrict to one kind; absent means all"},
                "status": str_t, "service": str_t, "priority": str_t, "assignee": str_t,
                "parent_task": {"type": "string", "description": "only children of this task key"},
                "history": {"type": "boolean", "description": "search every version ever written \
instead of the current state; hits then carry is_head=false when they come from the past"},
                "semantic": {"type": "boolean", "description": "false forces pure lexical BM25 - \
useful to prove a match is literal rather than by meaning"},
                "recent": {"type": "boolean", "description": "order by commit time, not relevance"},
                "limit": int_t,
                "as_of": {"type": "string", "description": "what the base said at this moment \
rather than what it says now - an RFC3339 timestamp, a YYYY-MM-DD date, or any git revision. \
A bare date means the end of that day."},
                "changed_between": {"type": "string", "description": "only entries that changed \
inside this window: two dates or revisions separated by a comma."},
                "deadlines": deadlines_t,
            }},
        }),
        json!({
            "name": "kyb_get",
            "description": "Read one entry in full by its key. `at` takes any revision git can \
resolve and returns the entry as it stood at that commit - the answer to 'what did we believe \
then'.",
            "inputSchema": {"type": "object", "required": ["key"], "properties": {
                "key": {"type": "string", "description": "the entry's slug"},
                "at": {"type": "string", "description": "a git revision; absent means current"},
                "deadlines": deadlines_t,
            }},
        }),
        json!({
            "name": "kyb_history",
            "description": "Every version of one entry, newest first, with the commit sha and \
timestamp of each change. Use it to see when a fact moved, then pass a sha to kyb_get.",
            "inputSchema": {"type": "object", "required": ["key"],
                            "properties": {"key": str_t}},
        }),
        json!({
            "name": "kyb_diff",
            "description": "What changed in an entry between two revisions: which fields moved, \
and which body lines were added or removed. With no revisions it compares the two most recent \
versions - 'what just changed' is the question asked most. Give `from` alone to compare a past \
version against the current one.",
            "inputSchema": {"type": "object", "required": ["key"], "properties": {
                "key": str_t,
                "from": {"type": "string", "description": "revision to compare from"},
                "to": {"type": "string", "description": "revision to compare to; absent means current"},
            }},
        }),
        json!({
            "name": "kyb_tags",
            "description": "Which topics the base covers, with a count per tag. A cheap way to \
find out what is in there before searching blind.",
            "inputSchema": {"type": "object", "properties": {}},
        }),
        json!({
            "name": "kyb_health",
            "description": "Whether the server is up, how many entries it holds, and how many \
incidents and tasks are open.",
            "inputSchema": {"type": "object", "properties": {}},
        }),
        json!({
            "name": "kyb_incidents",
            "description": "Live incident reports, open first and freshest on top. Check this \
before infrastructure work.",
            "inputSchema": {"type": "object", "properties": {
                "status": str_t, "service": str_t, "limit": int_t,
                "followups": {"type": "boolean", "description": "only reports with unfinished \
follow-ups"},
                "all": {"type": "boolean", "description": "include closed reports, which are \
archived but still readable"},
                "deadlines": deadlines_t,
            }},
        }),
        json!({
            "name": "kyb_tasks",
            "description": "Live tasks - open, in_progress, blocked - freshest on top.",
            "inputSchema": {"type": "object", "properties": {
                "status": str_t, "priority": str_t, "assignee": str_t, "parent_task": str_t,
                "limit": int_t,
                "followups": {"type": "boolean", "description": "only tasks with unfinished \
follow-ups"},
                "all": {"type": "boolean", "description": "include closed tasks from the archive"},
                "deadlines": deadlines_t,
            }},
        }),
        json!({
            "name": "kyb_deadlines",
            "description": "Open tasks that have a due date, soonest first, each marked overdue, \
this_week or later, with the days left (negative = late). Hard deadlines - expiries, contract \
and regulatory dates - are marked; a provisional one runs on its expected date until the real \
date is known. Closed tasks never appear.",
            "inputSchema": {"type": "object", "properties": {
                "within": {"type": "string", "description": "only what is due within N days, \
e.g. 30 or 30d; late ones always count"},
                "overdue": {"type": "boolean", "description": "only what is already late"},
                "hard": {"type": "boolean", "description": "only hard deadlines"},
                "tag": {"type": "string", "description": "comma-separated; every tag must match"},
                "assignee": str_t,
            }},
        }),
        json!({
            "name": "kyb_add",
            "description": "Write or update one entry. Same call for both: reusing a key does not \
overwrite, it adds a version, and the old text stays searchable under history. Only verified \
facts - something read in the code, seen in a config, or returned by a command actually run. \
Never secrets in the body; put a pointer in refs instead. Entries are written in English.",
            "inputSchema": {"type": "object", "required": ["key", "title", "body"], "properties": {
                "key": {"type": "string", "description": "slug [a-z0-9-]; reusing one adds a version"},
                "title": str_t,
                "body": {"type": "string", "description": "the entry itself, markdown"},
                "tags": list_t, "refs": list_t,
            }},
        }),
        json!({
            "name": "kyb_incident",
            "description": "File an incident report. The key must start with inc-. A report that \
cannot tell the next person whether the thing is still happening is a story rather than a \
report, so pass `detection`: a command to run plus the result that means healthy. Tags left out \
of a rewrite keep the stored ones.",
            "inputSchema": {"type": "object",
                "required": ["key", "title", "service", "severity", "body"], "properties": {
                "key": {"type": "string", "description": "inc-<date>-<slug>"},
                "title": {"type": "string", "description": "the symptom, not the diagnosis"},
                "service": str_t,
                "severity": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
                "body": {"type": "string", "description": "what happened, impact, workaround"},
                "hosts": list_t, "knowledge": list_t, "tags": list_t, "refs": list_t,
                "status": {"type": "string", "enum": ["open", "mitigated", "resolved"]},
                "detection": {"type": "string", "description": "an executable check plus its \
healthy result"},
                "affected": {"type": "array",
                    "description": "windows where data or a period got poisoned",
                    "items": {"type": "object", "required": ["scope", "from", "to"],
                              "properties": {"scope": str_t, "from": str_t, "to": str_t}}},
                "started_at": {"type": "string", "description": "RFC3339, if known"},
                "detected_at": {"type": "string", "description": "RFC3339, if known"},
                "resolution": str_t,
            }},
        }),
        json!({
            "name": "kyb_resolve",
            "description": "Close an incident. A resolution is required - what actually fixed it. \
Closing archives the report: it leaves the working set and stays searchable forever.",
            "inputSchema": {"type": "object", "required": ["key", "resolution"], "properties": {
                "key": str_t,
                "resolution": {"type": "string", "description": "what fixed it"},
                "status": {"type": "string", "enum": ["resolved", "mitigated"]},
            }},
        }),
        json!({
            "name": "kyb_task",
            "description": "Create or update a task or idea. The key must start with task-. \
Reusing the key updates it in place. Tags and the deadline fields left out keep what the task \
already says, so rewriting a task never drops its tags or its due date; an empty value clears.",
            "inputSchema": {"type": "object", "required": ["key", "title", "body"], "properties": {
                "key": {"type": "string", "description": "task-<slug>"},
                "title": str_t, "body": str_t,
                "status": {"type": "string",
                           "enum": ["open", "in_progress", "blocked", "done", "dropped"]},
                "priority": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
                "blocked_reason": {"type": "string", "description": "what it waits on; only with \
status blocked"},
                "assignee": str_t, "parent_task": str_t, "resolution": str_t,
                "knowledge": list_t, "tags": list_t, "refs": list_t,
                "due": date_t("when it is due"),
                "hard": {"type": "boolean", "description": "missing it has real consequences: an \
expiry, a contractual or regulatory date, a third party's cut-off"},
                "remind_days": {"type": ["integer", "string"], "description": "how many days ahead \
to start surfacing it; \"\" returns it to the default (14, or 30 when hard)"},
                "waits_on": {"type": "string", "description": "the event the real date depends on"},
                "expected": date_t("a provisional date, reminded on until due is set"),
            }},
        }),
        json!({
            "name": "kyb_task_status",
            "description": "Move a task between open, in_progress and blocked, or move its \
deadline, without resending it. Title, body, tags, priority and links stay as stored; without \
a status the task keeps its own. Moving a due date is a new version, so history shows it. \
Closing is kyb_done, not this.",
            "inputSchema": {"type": "object", "required": ["key"], "properties": {
                "key": str_t,
                "status": {"type": "string", "enum": ["open", "in_progress", "blocked"]},
                "assignee": {"type": "string", "description": "an empty string hands it back"},
                "parent_task": str_t,
                "blocked_reason": {"type": "string", "description": "what it waits on; only with \
status blocked"},
                "due": date_t("when it is due"),
                "hard": {"type": "boolean", "description": "missing it has real consequences: an \
expiry, a contractual or regulatory date, a third party's cut-off"},
                "remind_days": {"type": ["integer", "string"], "description": "how many days ahead \
to start surfacing it; \"\" returns it to the default (14, or 30 when hard)"},
                "waits_on": {"type": "string", "description": "the event the real date depends on"},
                "expected": date_t("a provisional date, reminded on until due is set"),
            }},
        }),
        json!({
            "name": "kyb_done",
            "description": "Close a task with what came of it. Closing archives it: it leaves the \
working set and stays searchable.",
            "inputSchema": {"type": "object", "required": ["key", "resolution"], "properties": {
                "key": str_t,
                "resolution": {"type": "string", "description": "what came of it"},
                "status": {"type": "string", "enum": ["done", "dropped"]},
            }},
        }),
    ];

    if readonly {
        all.into_iter()
            .filter(|t| {
                !WRITE_TOOLS.contains(&t["name"].as_str().unwrap_or_default())
            })
            .collect()
    } else {
        all
    }
}

#[cfg(test)]
mod mcp_tests {
    use super::*;
    use axum::http::Request as HttpRequest;
    use serde_json::json;
    use std::collections::HashSet;

    fn test_app() -> (Router, tempfile::TempDir, tempfile::TempDir, std::path::PathBuf) {
        let data = tempfile::tempdir().unwrap();
        let idx = tempfile::tempdir().unwrap();
        let audit_path = idx.path().join("audit.jsonl");
        let cfg = crate::config::Config {
            data_dir: data.path().to_path_buf(),
            index_dir: idx.path().to_path_buf(),
            audit_path: audit_path.clone(),
            // these tests assert dispatch, not ranking: no model, lexical only
            model_dir: idx.path().join("no-model"),
            addr: String::new(),
        };
        let state = crate::build_state(&cfg).unwrap();
        (crate::build_app(state), data, idx, audit_path)
    }

    async fn post(app: &Router, uri: &str, payload: Value) -> (StatusCode, Value) {
        let req = HttpRequest::builder()
            .method("POST")
            .uri(uri)
            .header("content-type", "application/json")
            .body(Body::from(payload.to_string()))
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        let status = resp.status();
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
    }

    async fn rpc(app: &Router, payload: Value) -> Value {
        post(app, "/mcp", payload).await.1
    }

    fn call(name: &str, args: Value) -> Value {
        json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
               "params": {"name": name, "arguments": args}})
    }

    fn tool_body(resp: &Value) -> &str {
        resp["result"]["content"][0]["text"].as_str().unwrap_or_default()
    }

    fn errored(resp: &Value) -> bool {
        resp["result"]["isError"] == Value::Bool(true)
    }

    #[tokio::test]
    async fn initialize_answers_the_asked_version_and_the_built_one() {
        let (app, _d, _i, _a) = test_app();
        let resp = rpc(
            &app,
            json!({"jsonrpc": "2.0", "id": 1, "method": "initialize",
                   "params": {"protocolVersion": "2025-03-26"}}),
        )
        .await;
        assert_eq!(resp["result"]["protocolVersion"], "2025-03-26");
        assert_eq!(resp["result"]["serverInfo"]["name"], "kyb");
        // straight from Cargo.toml, so it cannot drift from the running binary
        assert_eq!(resp["result"]["serverInfo"]["version"], env!("CARGO_PKG_VERSION"));
        assert!(resp["result"]["capabilities"]["tools"].is_object());
    }

    #[tokio::test]
    async fn an_unknown_protocol_version_is_answered_with_one_we_support() {
        let (app, _d, _i, _a) = test_app();
        let resp = rpc(
            &app,
            json!({"jsonrpc": "2.0", "id": 1, "method": "initialize",
                   "params": {"protocolVersion": "1999-01-01"}}),
        )
        .await;
        assert_eq!(resp["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]);
    }

    #[tokio::test]
    async fn a_notification_is_accepted_and_never_answered() {
        let (app, _d, _i, _a) = test_app();
        let (status, body) =
            post(&app, "/mcp", json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))
                .await;
        assert_eq!(status, StatusCode::ACCEPTED);
        assert_eq!(body, Value::Null, "202 must carry no body");
    }

    #[tokio::test]
    async fn the_tool_list_is_the_routes_this_build_has() {
        let (app, _d, _i, _a) = test_app();
        let resp = rpc(&app, json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})).await;
        let tools = resp["result"]["tools"].as_array().unwrap();
        let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();

        assert_eq!(names.len(), 15, "got {names:?}");
        let unique: HashSet<&&str> = names.iter().collect();
        assert_eq!(unique.len(), names.len(), "duplicate tool name in {names:?}");
        for tool in tools {
            assert!(tool["description"].as_str().is_some_and(|d| d.len() > 30));
            assert_eq!(tool["inputSchema"]["type"], "object");
        }
        // retracting an entry and rebuilding the index stay off this surface
        assert!(!names.contains(&"kyb_rm"));
        assert!(!names.contains(&"kyb_reindex"));
        // the temporal layer is in this build, so it is advertised
        assert!(names.contains(&"kyb_diff"));
        let query = tools.iter().find(|t| t["name"] == "kyb_query").unwrap();
        assert!(query["inputSchema"]["properties"]["as_of"].is_object());
        assert!(query["inputSchema"]["properties"]["changed_between"].is_object());
    }

    #[tokio::test]
    async fn a_tool_call_goes_through_the_real_routes() {
        let (app, _d, _i, audit_path) = test_app();

        let added = rpc(
            &app,
            call("kyb_add", json!({"key": "orders-api", "title": "Orders API",
                                   "body": "Runs on node-7, port 8080.", "tags": "infra,orders"})),
        )
        .await;
        assert!(!errored(&added), "{added}");
        let created: Value = serde_json::from_str(tool_body(&added)).unwrap();
        assert_eq!(created["action"], "created");
        assert_eq!(created["key"], "orders-api");

        // read it back through a different tool: proves the write really landed
        // in the canon rather than in a reply the MCP layer invented
        let got = rpc(&app, call("kyb_get", json!({"key": "orders-api"}))).await;
        let entry: Value = serde_json::from_str(tool_body(&got)).unwrap();
        assert!(entry["body"].as_str().unwrap().contains("port 8080"));

        let found = rpc(&app, call("kyb_query", json!({"q": "orders", "limit": 5}))).await;
        let hits: Value = serde_json::from_str(tool_body(&found)).unwrap();
        assert!(hits["count"].as_u64().unwrap() >= 1, "{hits}");

        // and the write was audited exactly like any other write, because it WAS
        // any other write - the audit layer never saw an MCP request
        let log = std::fs::read_to_string(&audit_path).unwrap();
        assert!(
            log.lines().any(|l| l.contains("\"path\":\"/knowledge\"")
                && l.contains("\"method\":\"POST\"")),
            "no audit line for the forwarded write: {log}"
        );
        assert!(!log.contains("\"/mcp\""), "the /mcp hop should not be audited twice: {log}");
    }

    #[tokio::test]
    async fn a_second_write_to_one_key_adds_a_version() {
        let (app, _d, _i, _a) = test_app();
        for body in ["port 8080", "port 9090"] {
            rpc(
                &app,
                call("kyb_add", json!({"key": "orders-api", "title": "Orders API",
                                       "body": format!("Runs on node-7, {body}.")})),
            )
            .await;
        }
        let history = rpc(&app, call("kyb_history", json!({"key": "orders-api"}))).await;
        let parsed: Value = serde_json::from_str(tool_body(&history)).unwrap();
        assert_eq!(parsed["versions"].as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn a_missing_argument_is_refused_before_a_request_is_made() {
        let (app, _d, _i, audit_path) = test_app();
        let resp = rpc(&app, call("kyb_add", json!({"key": "half", "title": "Half"}))).await;
        assert!(errored(&resp));
        assert!(
            tool_body(&resp).starts_with("missing required argument"),
            "{}",
            tool_body(&resp)
        );

        // The point is not that the write failed - the route would have rejected a
        // null body anyway, so asserting only that would pass with this check
        // deleted. The point is that NOTHING was sent: the audit log, which sees
        // every forwarded request, has no line for it.
        let log = std::fs::read_to_string(&audit_path).unwrap_or_default();
        assert!(
            !log.contains("\"path\":\"/knowledge\""),
            "a refused call must not reach the API at all: {log}"
        );

        let got = rpc(&app, call("kyb_get", json!({"key": "half"}))).await;
        assert!(errored(&got), "the refused write must not have created anything");
    }

    #[tokio::test]
    async fn an_unknown_tool_is_readable_by_the_model_not_a_protocol_fault() {
        let (app, _d, _i, _a) = test_app();
        let resp = rpc(&app, call("kyb_delete_everything", json!({}))).await;
        assert!(errored(&resp));
        assert!(tool_body(&resp).contains("no such tool"));
        assert!(resp["error"].is_null(), "a bad tool name is not a JSON-RPC error");
    }

    #[tokio::test]
    async fn an_http_failure_from_the_route_reaches_the_model() {
        let (app, _d, _i, _a) = test_app();
        let resp = rpc(&app, call("kyb_get", json!({"key": "never-written"}))).await;
        assert!(errored(&resp));
        assert!(tool_body(&resp).contains("404"), "{}", tool_body(&resp));
    }

    #[tokio::test]
    async fn a_batch_is_answered_in_order_and_notifications_drop_out() {
        let (app, _d, _i, _a) = test_app();
        let resp = rpc(
            &app,
            json!([
                {"jsonrpc": "2.0", "id": "a", "method": "ping"},
                {"jsonrpc": "2.0", "method": "notifications/initialized"},
                {"jsonrpc": "2.0", "id": "b", "method": "tools/list"},
            ]),
        )
        .await;
        let items = resp.as_array().unwrap();
        assert_eq!(items.len(), 2, "the notification must not produce a response");
        assert_eq!(items[0]["id"], "a");
        assert_eq!(items[1]["id"], "b");
    }

    #[tokio::test]
    async fn protocol_faults_are_json_rpc_errors() {
        let (app, _d, _i, _a) = test_app();

        let unknown = rpc(&app, json!({"jsonrpc": "2.0", "id": 1, "method": "no/such"})).await;
        assert_eq!(unknown["error"]["code"], -32601);

        let nameless = rpc(
            &app,
            json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {}}),
        )
        .await;
        assert_eq!(nameless["error"]["code"], -32602);

        let req = HttpRequest::builder()
            .method("POST")
            .uri("/mcp")
            .header("content-type", "application/json")
            .body(Body::from("{not json"))
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let parsed: Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed["error"]["code"], -32700);
    }

    #[tokio::test]
    async fn get_and_delete_say_why_they_are_refused() {
        let (app, _d, _i, _a) = test_app();
        for method in ["GET", "DELETE"] {
            let req =
                HttpRequest::builder().method(method).uri("/mcp").body(Body::empty()).unwrap();
            let resp = app.clone().oneshot(req).await.unwrap();
            assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED, "{method}");
            assert_eq!(resp.headers().get("allow").unwrap(), "POST");
        }
    }

    #[tokio::test]
    async fn readonly_drops_the_writing_tools_and_refuses_them() {
        let (app, _d, _i, _a) = test_app();
        let listed =
            post(&app, "/mcp?readonly=1", json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}))
                .await
                .1;
        let names: Vec<&str> = listed["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["name"].as_str().unwrap())
            .collect();
        assert_eq!(names.len(), 9, "{names:?}");
        // the deadline listing only reads, so a read-only client keeps it
        assert!(names.contains(&"kyb_deadlines"), "{names:?}");
        for write in WRITE_TOOLS {
            assert!(!names.contains(&write), "{write} must not be advertised read-only");
        }
        assert!(names.contains(&"kyb_query"));

        let refused = post(
            &app,
            "/mcp?readonly=1",
            call("kyb_add", json!({"key": "k", "title": "t", "body": "b"})),
        )
        .await
        .1;
        assert!(errored(&refused));

        let got = rpc(&app, call("kyb_get", json!({"key": "k"}))).await;
        assert!(errored(&got), "a read-only refusal must not have written anything");
    }

    #[tokio::test]
    async fn diff_reports_what_moved_between_two_versions() {
        let (app, _d, _i, _a) = test_app();
        for body in ["Runs on node-7, port 8080.", "Runs on node-7, port 9090."] {
            rpc(&app, call("kyb_add", json!({"key": "orders-api", "title": "Orders API",
                                             "body": body}))).await;
        }
        let resp = rpc(&app, call("kyb_diff", json!({"key": "orders-api"}))).await;
        assert!(!errored(&resp), "{}", tool_body(&resp));
        let text = tool_body(&resp);
        // the superseded line left, the new one arrived
        assert!(text.contains("8080"), "{text}");
        assert!(text.contains("9090"), "{text}");
    }

    #[tokio::test]
    async fn as_of_asks_the_route_about_the_past_rather_than_the_present() {
        let (app, _d, _i, audit_path) = test_app();
        rpc(&app, call("kyb_add", json!({"key": "orders-api", "title": "Orders API",
                                         "body": "port 8080"}))).await;
        let resp = rpc(&app, call("kyb_query",
                                  json!({"q": "orders", "as_of": "2020-01-01"}))).await;
        assert!(!errored(&resp), "{}", tool_body(&resp));
        // a date before anything existed must not answer with today's entry
        let parsed: Value = serde_json::from_str(tool_body(&resp)).unwrap();
        assert_eq!(parsed["count"], 0, "as_of was ignored: {parsed}");
        // and the parameter really travelled, rather than being silently dropped
        let log = std::fs::read_to_string(&audit_path).unwrap();
        assert!(log.contains("as_of"), "as_of never reached the route: {log}");
    }

    #[tokio::test]
    async fn a_comma_string_and_a_list_of_tags_mean_the_same_thing() {
        let (app, _d, _i, _a) = test_app();
        rpc(&app, call("kyb_add", json!({"key": "a", "title": "A", "body": "x",
                                         "tags": "infra, orders"}))).await;
        rpc(&app, call("kyb_add", json!({"key": "b", "title": "B", "body": "x",
                                         "tags": ["infra", "orders"]}))).await;
        let tags = rpc(&app, call("kyb_tags", json!({}))).await;
        let parsed: Value = serde_json::from_str(tool_body(&tags)).unwrap();
        let text = parsed.to_string();
        assert!(text.contains("infra") && text.contains("orders"), "{text}");
    }

    #[tokio::test]
    async fn deadlines_reach_an_mcp_client_through_the_same_routes() {
        let (app, _d, _i, _a) = test_app();
        // due long ago: late on whatever calendar the test machine keeps
        let resp = rpc(&app, call("kyb_task", json!({"key": "task-renew-cert",
            "title": "Renew the certificate", "body": "before it expires",
            "due": "2000-01-01", "hard": true}))).await;
        assert!(!errored(&resp), "{}", tool_body(&resp));

        let resp = rpc(&app, call("kyb_query", json!({"q": "certificate"}))).await;
        let answer: Value = serde_json::from_str(tool_body(&resp)).unwrap();
        assert_eq!(answer["deadlines"]["items"][0]["key"], "task-renew-cert", "{answer}");
        assert_eq!(answer["deadlines"]["items"][0]["overdue"], true);
        let resp = rpc(&app, call("kyb_query", json!({"q": "certificate", "deadlines": false}))).await;
        let answer: Value = serde_json::from_str(tool_body(&resp)).unwrap();
        assert!(answer.get("deadlines").is_none(), "{answer}");

        // a rewrite that does not mention the deadline keeps it
        rpc(&app, call("kyb_task", json!({"key": "task-renew-cert",
            "title": "Renew the certificate", "body": "before it expires, via the CA portal"}))).await;
        // moving only the date, no status: the task keeps its own
        let resp = rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert",
            "due": "2999-12-31"}))).await;
        assert!(!errored(&resp), "{}", tool_body(&resp));

        let resp = rpc(&app, call("kyb_deadlines", json!({"hard": true}))).await;
        let listing: Value = serde_json::from_str(tool_body(&resp)).unwrap();
        assert_eq!(listing["count"], 1, "{listing}");
        assert_eq!(listing["deadlines"][0]["due"], "2999-12-31");
        assert_eq!(listing["deadlines"][0]["status"], "open");
        assert_eq!(listing["deadlines"][0]["hard"], true);

        let resp = rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert",
            "remind_days": "soon"}))).await;
        assert!(errored(&resp), "a malformed field is refused before any request is made");
        let resp = rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert",
            "remind_days": 5_000_000_000u64}))).await;
        assert!(errored(&resp), "a count that does not fit is refused here, not by the route");

        // null is "not named" over MCP: models send it for arguments they do not use
        let resp = rpc(&app, call("kyb_task", json!({"key": "task-renew-cert",
            "title": "Renew the certificate", "body": "before it expires",
            "due": null, "hard": null, "remind_days": null}))).await;
        assert!(!errored(&resp), "{}", tool_body(&resp));
        let resp = rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert",
            "remind_days": 45}))).await;
        assert!(!errored(&resp), "{}", tool_body(&resp));
        let resp = rpc(&app, call("kyb_deadlines", json!({}))).await;
        let listing: Value = serde_json::from_str(tool_body(&resp)).unwrap();
        assert_eq!(listing["deadlines"][0]["due"], "2999-12-31", "{listing}");
        assert_eq!(listing["deadlines"][0]["remind_days"], 45);
        // "" returns the window to the default, 30 for a hard deadline
        rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert", "remind_days": ""}))).await;
        let resp = rpc(&app, call("kyb_deadlines", json!({}))).await;
        let listing: Value = serde_json::from_str(tool_body(&resp)).unwrap();
        assert_eq!(listing["deadlines"][0]["remind_days"], 30, "{listing}");
    }

    #[tokio::test]
    async fn a_rewrite_over_mcp_keeps_the_tags_it_does_not_name() {
        let (app, _d, _i, _a) = test_app();
        let tags = |key: &str| {
            let key = key.to_string();
            let app = app.clone();
            async move {
                let resp = rpc(&app, call("kyb_get", json!({"key": key}))).await;
                let e: Value = serde_json::from_str(tool_body(&resp)).unwrap();
                e["tags"].clone()
            }
        };
        let task = |extra: Value| {
            let mut a = json!({"key": "task-tagged", "title": "Tagged", "body": "b"});
            a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
            a
        };
        rpc(&app, call("kyb_task", task(json!({"tags": ["infra", "tls"]})))).await;
        rpc(&app, call("kyb_task", task(json!({"body": "rewritten"})))).await;
        assert_eq!(tags("task-tagged").await, json!(["infra", "tls"]), "a rewrite that names no tags keeps them");
        rpc(&app, call("kyb_task", task(json!({"tags": null})))).await;
        assert_eq!(tags("task-tagged").await, json!(["infra", "tls"]), "null is not named");
        rpc(&app, call("kyb_task", task(json!({"tags": ""})))).await;
        assert_eq!(tags("task-tagged").await, json!([]), "an empty value clears");

        let inc = |extra: Value| {
            let mut a = json!({"key": "inc-2026-10-27-tagged", "title": "Tagged", "body": "b", "service": "svc", "severity": "low"});
            a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
            a
        };
        rpc(&app, call("kyb_incident", inc(json!({"tags": "infra"})))).await;
        rpc(&app, call("kyb_incident", inc(json!({"body": "rewritten"})))).await;
        assert_eq!(tags("inc-2026-10-27-tagged").await, json!(["infra"]));
    }
}