toolnexus 0.25.0

Vendor-neutral tool layer for LLM agents: ACP agents, MCP servers, agent skills behind one Tool interface (Rust port of toolnexus).
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
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
//! MCP — INBOUND, embeddable: a plain streamable-HTTP MCP server with generic
//! per-request hooks (SPEC §7C.1, ADR 0039). Port of `golang/mcphandler.go`.
//! Behind the `serve` feature.
//!
//! [`Toolkit::serve`] owns a listener and exposes one static tool list.
//! [`Toolkit::mcp_handler`] returns an [`McpHandler`] a host mounts on its own
//! router (hyper directly — it implements `hyper::service::Service` — or any
//! framework through [`McpHandler::handle`]), behind its own TLS, CORS and
//! OAuth. Every policy is a hook; toolnexus has no notion of tenant, user, role
//! or storage.
//!
//! The transport is JSON-RPC over HTTP written by hand (no rmcp server types in
//! the public API): tools resolve per request, and a confirm elicitation rides
//! the SAME POST's SSE response (protocol 2025-06-18).
//!
//! MCP 2026-07-28 (SPEC §7C.2, ADR 0040) is opt-in: list `"2026-07-28"` in
//! [`McpHandlerConfig::protocol_versions`]. That stateless wire (server/discover,
//! header validation, MRTR, the skills extension) lives in `v2026`; bearer-token
//! protection in [`McpServerAuth`]. Bring your own authorization server; the
//! auto-approving dev authorization server the suite uses is test tooling
//! (`tests/common_dev_auth`), not part of the library.

mod server_auth;
mod v2026;

pub use server_auth::{McpAuthMetadata, McpPrincipal, McpServerAuth, VerifyTokenFn};
pub use v2026::{MCP_PROTOCOL_2026, MCP_SKILLS_EXTENSION, McpSkill, McpSkillFile, load_mcp_skills};

use std::any::Any;
use std::collections::HashMap;
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use futures_util::StreamExt;
use http_body_util::{BodyExt, Full, Limited, StreamBody, combinators::BoxBody};
use hyper::body::{Body, Bytes, Frame};
use hyper::header::{HeaderMap, HeaderValue};
use hyper::{Method, Request, Response, StatusCode, Uri};
use serde_json::{Map, Value, json};
use tokio::sync::{mpsc, oneshot};

use crate::tool::{ContentPart, Tool, ToolContext, ToolResult, ToolSource};
use crate::toolkit::Toolkit;

/// The MCP protocol versions whose wire [`McpHandler`] implements (ADR 0039).
/// Configured versions outside this list are dropped.
/// `2026-07-28` is opt-in only (never a default) and is served by the
/// stateless wire of SPEC §7C.2; `initialize` never negotiates it.
pub const MCP_HANDLER_IMPLEMENTED_VERSIONS: &[&str] = &["2026-07-28", "2025-11-25", "2025-06-18"];
const DEFAULT_VERSIONS: &[&str] = &["2025-06-18"];
const DEFAULT_NAME: &str = "toolnexus";
const DEFAULT_VERSION: &str = "0.1.0";

/// A boxed, sendable future returned by the async hooks.
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
/// What `authenticate` produces; reachable everywhere via
/// [`McpRequestContext::identity`].
pub type McpIdentity = Arc<dyn Any + Send + Sync>;

/// The outcome of a `before_call` gate.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum McpDecisionKind {
    #[default]
    Allow,
    Deny,
    Confirm,
}

impl McpDecisionKind {
    /// The wire / event name: `allow` | `deny` | `confirm`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Allow => "allow",
            Self::Deny => "deny",
            Self::Confirm => "confirm",
        }
    }
}

/// What `before_call` returns. The default allows.
///
/// - Allow: the tool runs.
/// - Deny: the tool does not run; the caller gets `result` when set, else an
///   isError result carrying `message` (`"denied"` when empty).
/// - Confirm: the client is asked (`elicitation/create`, `message` as prompt)
///   when it declared elicitation; accept ⇒ the tool runs, else isError
///   `"declined"`. When it cannot elicit: `result` when set, else isError
///   `"confirmation required: <message>"`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpDecision {
    pub kind: McpDecisionKind,
    pub message: String,
    pub result: Option<ToolResult>,
}

impl McpDecision {
    pub fn allow() -> Self {
        Self::default()
    }
    pub fn deny(message: impl Into<String>) -> Self {
        Self {
            kind: McpDecisionKind::Deny,
            message: message.into(),
            result: None,
        }
    }
    pub fn confirm(message: impl Into<String>) -> Self {
        Self {
            kind: McpDecisionKind::Confirm,
            message: message.into(),
            result: None,
        }
    }
    /// This decision with a host-shaped result (deny / confirm fallback).
    pub fn with_result(mut self, result: ToolResult) -> Self {
        self.result = Some(result);
        self
    }
}

/// Advertised at `initialize`. Empty `title` / `instructions` are omitted.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpServerInfo {
    pub name: String,
    pub title: String,
    pub version: String,
    pub instructions: String,
}

/// One `resources/list` entry.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpResource {
    pub uri: String,
    pub name: String,
    pub title: String,
    pub description: String,
    pub mime_type: String,
}

/// One `resources/read` entry: set `text`, or `blob` (base64).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpResourceContent {
    pub uri: String,
    pub mime_type: String,
    pub text: String,
    pub blob: String,
}

/// One prompt argument.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpPromptArgument {
    pub name: String,
    pub description: String,
    pub required: bool,
}

/// One `prompts/list` entry.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpPrompt {
    pub name: String,
    pub title: String,
    pub description: String,
    pub arguments: Vec<McpPromptArgument>,
}

/// One text message of a `prompts/get` result. `role`: `user` | `assistant`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpPromptMessage {
    pub role: String,
    pub text: String,
}

/// The `prompts/get` result.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpPromptResult {
    pub description: String,
    pub messages: Vec<McpPromptMessage>,
}

/// The request being served: HTTP parts, the authenticated identity, the
/// session id and the JSON-RPC `params._meta`. Every hook receives it; a tool
/// reads it with [`mcp_request_context`].
#[derive(Clone)]
pub struct McpRequestContext {
    pub method: Method,
    pub uri: Uri,
    pub headers: HeaderMap,
    identity: Option<McpIdentity>,
    session_id: String,
    meta: Option<Map<String, Value>>,
}

impl std::fmt::Debug for McpRequestContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpRequestContext")
            .field("method", &self.method)
            .field("uri", &self.uri)
            .field("session_id", &self.session_id)
            .field("meta", &self.meta)
            .finish_non_exhaustive()
    }
}

impl McpRequestContext {
    /// What `authenticate` produced (`None` without `authenticate`).
    pub fn identity(&self) -> Option<&McpIdentity> {
        self.identity.as_ref()
    }
    /// The identity downcast to `T`.
    pub fn identity_as<T: 'static>(&self) -> Option<&T> {
        self.identity.as_ref()?.downcast_ref::<T>()
    }
    /// The `Mcp-Session-Id` ("" when stateless or none).
    pub fn session_id(&self) -> &str {
        &self.session_id
    }
    /// The JSON-RPC request's `params._meta` (`None` when absent).
    pub fn meta(&self) -> Option<&Map<String, Value>> {
        self.meta.as_ref()
    }
    /// A request header as a string ("" when absent or not UTF-8).
    pub fn header(&self, name: &str) -> &str {
        self.headers
            .get(name)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
    }
    /// The `Host` header (else the URI authority).
    pub fn host(&self) -> String {
        let h = self.header("host");
        if !h.is_empty() {
            return h.to_owned();
        }
        self.uri
            .authority()
            .map(|a| a.to_string())
            .unwrap_or_default()
    }
}

/// The [`McpRequestContext`] of the served call a tool is running in.
pub fn mcp_request_context(ctx: &ToolContext) -> Option<&McpRequestContext> {
    ctx.request.as_ref()?.downcast_ref::<McpRequestContext>()
}

/// Issues and checks `Mcp-Session-Id` values. The default is an in-memory set;
/// a host plugs its own (signed ids, a DB) so any replica validates any session.
pub trait McpSessionIds: Send + Sync {
    fn generate(&self, rc: Arc<McpRequestContext>) -> BoxFuture<Result<String, String>>;
    /// Whether `id` is live (false ⇒ HTTP 404).
    fn validate(&self, rc: Arc<McpRequestContext>, id: String) -> BoxFuture<Result<bool, String>>;
    fn terminate(&self, rc: Arc<McpRequestContext>, id: String) -> BoxFuture<Result<(), String>>;
}

/// Surfaced once per inbound `tools/call`.
#[derive(Clone)]
pub struct McpCallEvent {
    pub name: String,
    pub source: ToolSource,
    pub ms: u64,
    pub is_error: bool,
    /// The execution failure, when the tool failed (or panicked).
    pub err: Option<String>,
    /// Size of the JSON CallToolResult sent back.
    pub result_bytes: usize,
    pub decision: McpDecisionKind,
    pub identity: Option<McpIdentity>,
    pub session_id: String,
}

impl McpCallEvent {
    /// The identity downcast to `T`.
    pub fn identity_as<T: 'static>(&self) -> Option<&T> {
        self.identity.as_ref()?.downcast_ref::<T>()
    }
}

impl std::fmt::Debug for McpCallEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpCallEvent")
            .field("name", &self.name)
            .field("source", &self.source)
            .field("ms", &self.ms)
            .field("is_error", &self.is_error)
            .field("err", &self.err)
            .field("result_bytes", &self.result_bytes)
            .field("decision", &self.decision)
            .field("session_id", &self.session_id)
            .finish_non_exhaustive()
    }
}

type Ctx = Arc<McpRequestContext>;

/// An `authenticate` failure. Any error ⇒ a plain HTTP 401; an
/// [`McpAuthError`] (downcast) ⇒ its status, its challenge as
/// `WWW-Authenticate` and the body `{"error":"unauthorized"}` (both wires).
/// `"msg".into()` builds a plain one.
pub type McpAuthFailure = Box<dyn std::error::Error + Send + Sync>;

/// An `authenticate` failure with an explicit HTTP status and challenge
/// ([`McpServerAuth`] returns it). `status` 0 ⇒ 401. A non-empty
/// `www_authenticate` hook result wins over `challenge`. `reason` never
/// reaches the wire.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct McpAuthError {
    pub status: u16,
    pub challenge: String,
    pub reason: String,
}

impl std::fmt::Display for McpAuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(if self.reason.is_empty() {
            "unauthorized"
        } else {
            &self.reason
        })
    }
}

impl std::error::Error for McpAuthError {}

/// `authenticate`: an error ⇒ HTTP 401 (see [`McpAuthFailure`]).
pub type AuthenticateFn =
    Arc<dyn Fn(Ctx) -> BoxFuture<Result<McpIdentity, McpAuthFailure>> + Send + Sync>;
/// `www_authenticate(ctx, err)`: the `WWW-Authenticate` value ("" ⇒ omitted).
pub type WwwAuthenticateFn = Arc<dyn Fn(&McpRequestContext, &str) -> String + Send + Sync>;
pub type ServerInfoFn = Arc<dyn Fn(&McpRequestContext) -> McpServerInfo + Send + Sync>;
pub type ListToolsFn = Arc<dyn Fn(Ctx) -> BoxFuture<Result<Vec<Tool>, String>> + Send + Sync>;
/// `before_call(ctx, tool, args)`; an error is a deny carrying its message.
pub type BeforeCallFn =
    Arc<dyn Fn(Ctx, Tool, Value) -> BoxFuture<Result<McpDecision, String>> + Send + Sync>;
pub type OnMcpCallFn = Arc<dyn Fn(McpCallEvent) + Send + Sync>;
pub type ListResourcesFn =
    Arc<dyn Fn(Ctx) -> BoxFuture<Result<Vec<McpResource>, String>> + Send + Sync>;
pub type ReadResourceFn =
    Arc<dyn Fn(Ctx, String) -> BoxFuture<Result<Vec<McpResourceContent>, String>> + Send + Sync>;
pub type ListPromptsFn =
    Arc<dyn Fn(Ctx) -> BoxFuture<Result<Vec<McpPrompt>, String>> + Send + Sync>;
/// `list_skills`: the skills published through the SEP-2640 skills extension.
pub type ListSkillsFn = Arc<dyn Fn(Ctx) -> BoxFuture<Result<Vec<McpSkill>, String>> + Send + Sync>;
pub type GetPromptFn = Arc<
    dyn Fn(Ctx, String, HashMap<String, String>) -> BoxFuture<Result<McpPromptResult, String>>
        + Send
        + Sync,
>;

/// Configures [`Toolkit::mcp_handler`]. Every field is optional.
#[derive(Clone, Default)]
pub struct McpHandlerConfig {
    /// Static serverInfo; `server_info`, when set, wins. Defaults
    /// `toolnexus` / `0.1.0`; empty title / instructions are omitted.
    pub name: String,
    pub title: String,
    pub version: String,
    pub instructions: String,
    pub server_info: Option<ServerInfoFn>,
    /// Accepted protocol versions, newest first. Entries outside
    /// [`MCP_HANDLER_IMPLEMENTED_VERSIONS`] are dropped. Default `["2025-06-18"]`.
    pub protocol_versions: Vec<String>,
    /// Runs on every HTTP request before JSON-RPC parsing.
    pub authenticate: Option<AuthenticateFn>,
    pub www_authenticate: Option<WwwAuthenticateFn>,
    /// The tool list per request, for `tools/list` AND the `tools/call` lookup.
    /// `None` ⇒ the toolkit's tools.
    pub list_tools: Option<ListToolsFn>,
    pub before_call: Option<BeforeCallFn>,
    /// Bounds an elicitation round trip. `None` ⇒ 5 minutes.
    pub confirm_timeout: Option<Duration>,
    /// Fires once per `tools/call`; its panics are isolated.
    pub on_call: Option<OnMcpCallFn>,
    /// `None` list hook ⇒ capability not advertised, methods are -32601.
    pub list_resources: Option<ListResourcesFn>,
    pub read_resource: Option<ReadResourceFn>,
    pub list_prompts: Option<ListPromptsFn>,
    pub get_prompt: Option<GetPromptFn>,
    /// The SEP-2640 skills extension on the 2026-07-28 wire (skills/list,
    /// skills/get, resources/read of `skill://` URIs). `None` ⇒ not
    /// advertised. [`load_mcp_skills`] builds the list from a directory.
    pub list_skills: Option<ListSkillsFn>,
    /// Replaces the default in-memory session set.
    pub session_ids: Option<Arc<dyn McpSessionIds>>,
    /// Issue and check no session id; confirm never elicits.
    pub stateless: bool,
    /// Stateless only: returned as `Mcp-Session-Id` on initialize, never validated.
    pub stateless_session_id: String,
    /// Caps a POST body. 0 ⇒ 4 MiB.
    pub max_body_bytes: usize,
}

/// The default in-memory session set.
#[derive(Default)]
struct MemorySessionIds {
    live: Mutex<std::collections::HashSet<String>>,
}

impl McpSessionIds for MemorySessionIds {
    fn generate(&self, _: Ctx) -> BoxFuture<Result<String, String>> {
        let id = uuid::Uuid::new_v4().simple().to_string();
        self.live.lock().unwrap().insert(id.clone());
        Box::pin(async move { Ok(id) })
    }
    fn validate(&self, _: Ctx, id: String) -> BoxFuture<Result<bool, String>> {
        let ok = self.live.lock().unwrap().contains(&id);
        Box::pin(async move { Ok(ok) })
    }
    fn terminate(&self, _: Ctx, id: String) -> BoxFuture<Result<(), String>> {
        self.live.lock().unwrap().remove(&id);
        Box::pin(async { Ok(()) })
    }
}

/// The response body type.
pub type McpBody = BoxBody<Bytes, Infallible>;

struct Inner {
    tk: Toolkit,
    cfg: McpHandlerConfig,
    ids: Arc<dyn McpSessionIds>,
    /// Every accepted version, newest first.
    versions: Vec<String>,
    /// `versions` minus 2026-07-28: the initialize / session wire.
    legacy: Vec<String>,
    confirm_timeout: Duration,
    max_body: usize,
    caps: Mutex<HashMap<String, bool>>,
    streams: Mutex<Vec<mpsc::Sender<Bytes>>>,
    pending: Mutex<HashMap<(String, String), oneshot::Sender<Value>>>,
    seq: AtomicU64,
}

/// The embeddable MCP server returned by [`Toolkit::mcp_handler`]. Cheap to
/// clone. Mount it with hyper (`hyper::service::Service`) or call
/// [`McpHandler::handle`] from any framework.
#[derive(Clone)]
pub struct McpHandler {
    inner: Arc<Inner>,
}

impl Toolkit {
    /// A streamable-HTTP MCP server for this toolkit, to mount on the host's
    /// own router (SPEC §7C.1). [`Toolkit::serve`] is unchanged.
    pub fn mcp_handler(&self, cfg: McpHandlerConfig) -> McpHandler {
        let mut versions: Vec<String> = Vec::new();
        for v in &cfg.protocol_versions {
            if MCP_HANDLER_IMPLEMENTED_VERSIONS.contains(&v.as_str()) && !versions.contains(v) {
                versions.push(v.clone());
            }
        }
        if versions.is_empty() {
            versions = DEFAULT_VERSIONS.iter().map(|s| s.to_string()).collect();
        }
        let legacy: Vec<String> = versions
            .iter()
            .filter(|v| *v != MCP_PROTOCOL_2026)
            .cloned()
            .collect();
        let ids = cfg
            .session_ids
            .clone()
            .unwrap_or_else(|| Arc::new(MemorySessionIds::default()));
        McpHandler {
            inner: Arc::new(Inner {
                tk: self.clone(),
                ids,
                versions,
                legacy,
                confirm_timeout: cfg
                    .confirm_timeout
                    .filter(|d| !d.is_zero())
                    .unwrap_or(Duration::from_secs(300)),
                max_body: if cfg.max_body_bytes == 0 {
                    4 << 20
                } else {
                    cfg.max_body_bytes
                },
                cfg,
                caps: Mutex::default(),
                streams: Mutex::default(),
                pending: Mutex::default(),
                seq: AtomicU64::new(0),
            }),
        }
    }
}

// ── responses ────────────────────────────────────────────────────────────

/// Read a POST body under the size cap: too large ⇒ 413, a read failure ⇒
/// JSON-RPC -32700.
async fn read_body<B>(body: B, max: usize) -> Result<Bytes, Box<Response<McpBody>>>
where
    B: Body + Send + 'static,
    B::Data: Send,
    B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    match Limited::new(body, max).collect().await {
        Ok(b) => Ok(b.to_bytes()),
        Err(e) => {
            if e.downcast_ref::<http_body_util::LengthLimitError>()
                .is_some()
            {
                return Err(Box::new(plain_error(
                    StatusCode::PAYLOAD_TOO_LARGE,
                    "Request Entity Too Large",
                )));
            }
            Err(Box::new(rpc_error_response(None, -32700, "read error")))
        }
    }
}

fn plain_error(status: StatusCode, msg: &str) -> Response<McpBody> {
    let mut r = Response::new(Full::new(Bytes::from(format!("{msg}\n"))).boxed());
    *r.status_mut() = status;
    let h = r.headers_mut();
    h.insert(
        "content-type",
        HeaderValue::from_static("text/plain; charset=utf-8"),
    );
    h.insert(
        "x-content-type-options",
        HeaderValue::from_static("nosniff"),
    );
    r
}

fn json_response(status: StatusCode, v: &Value) -> Response<McpBody> {
    let mut body = serde_json::to_vec(v).unwrap_or_default();
    body.push(b'\n');
    let mut r = Response::new(Full::new(Bytes::from(body)).boxed());
    *r.status_mut() = status;
    r.headers_mut()
        .insert("content-type", HeaderValue::from_static("application/json"));
    r
}

fn empty(status: StatusCode) -> Response<McpBody> {
    let mut r = Response::new(Full::new(Bytes::new()).boxed());
    *r.status_mut() = status;
    r
}

fn rpc_error_response(id: Option<Value>, code: i64, message: &str) -> Response<McpBody> {
    json_response(
        StatusCode::BAD_REQUEST,
        &json!({"jsonrpc": "2.0", "id": id.unwrap_or(Value::Null),
                "error": {"code": code, "message": message}}),
    )
}

fn envelope(id: &Value, out: Result<Value, RpcErr>) -> Value {
    match out {
        Ok(r) => json!({"jsonrpc": "2.0", "id": id, "result": r}),
        Err(e) => json!({"jsonrpc": "2.0", "id": id, "error": {"code": e.0, "message": e.1}}),
    }
}

fn sse_frame(v: &Value) -> Bytes {
    Bytes::from(format!(
        "event: message\ndata: {}\n\n",
        serde_json::to_string(v).unwrap_or_default()
    ))
}

fn sse_response(rx: mpsc::Receiver<Bytes>) -> Response<McpBody> {
    let stream = tokio_stream_from(rx).map(|b| Ok::<_, Infallible>(Frame::data(b)));
    let mut r = Response::new(BodyExt::boxed(StreamBody::new(stream)));
    r.headers_mut().insert(
        "content-type",
        HeaderValue::from_static("text/event-stream"),
    );
    r.headers_mut()
        .insert("cache-control", HeaderValue::from_static("no-cache"));
    r
}

fn tokio_stream_from(mut rx: mpsc::Receiver<Bytes>) -> impl futures_util::Stream<Item = Bytes> {
    futures_util::stream::poll_fn(move |cx| rx.poll_recv(cx))
}

#[derive(Debug)]
struct RpcErr(i64, String);

fn rpc(code: i64, msg: impl Into<String>) -> RpcErr {
    RpcErr(code, msg.into())
}

/// Messages from a POST's dispatch task: server→client events, then the reply.
enum Out {
    Event(Value),
    Final(Value),
}

/// Answers one POST: plain JSON, unless a server→client request was sent first.
#[derive(Clone)]
struct RpcWriter(mpsc::UnboundedSender<Out>);

impl RpcWriter {
    fn event(&self, v: Value) -> bool {
        self.0.send(Out::Event(v)).is_ok()
    }
}

#[derive(serde::Deserialize)]
struct RpcMessage {
    #[serde(default)]
    jsonrpc: String,
    #[serde(default)]
    id: Option<Value>,
    #[serde(default)]
    method: String,
    #[serde(default)]
    params: Option<Value>,
    #[serde(default)]
    result: Option<Value>,
    #[serde(default)]
    error: Option<Value>,
}

fn omit_empty(pairs: &[(&str, &str)]) -> Map<String, Value> {
    pairs
        .iter()
        .filter(|(_, v)| !v.is_empty())
        .map(|(k, v)| (k.to_string(), Value::String(v.to_string())))
        .collect()
}

// ── HTTP ─────────────────────────────────────────────────────────────────

impl McpHandler {
    /// Send `notifications/tools/list_changed` on every open GET stream; a
    /// slow stream drops the message rather than block.
    pub fn notify_tools_changed(&self) {
        let msg =
            sse_frame(&json!({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}));
        let mut streams = self.inner.streams.lock().unwrap();
        streams.retain(|tx| {
            !matches!(
                tx.try_send(msg.clone()),
                Err(mpsc::error::TrySendError::Closed(_))
            )
        });
    }

    /// Serve one HTTP request (POST / GET / DELETE; anything else is 405).
    pub async fn handle<B>(&self, req: Request<B>) -> Response<McpBody>
    where
        B: Body + Send + 'static,
        B::Data: Send,
        B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
    {
        let (parts, body) = req.into_parts();
        let mut rc = McpRequestContext {
            method: parts.method.clone(),
            uri: parts.uri.clone(),
            headers: parts.headers.clone(),
            identity: None,
            session_id: String::new(),
            meta: None,
        };
        let h = &self.inner;
        let is_json = {
            let ct = rc.header("content-type");
            ct.split(';')
                .next()
                .unwrap_or("")
                .trim()
                .eq_ignore_ascii_case("application/json")
        };
        let mut body = Some(body);
        let mut pre: Option<Result<Bytes, Box<Response<McpBody>>>> = None;
        if parts.method == Method::POST && self.has_2026() && is_json {
            let read = read_body(body.take().expect("body"), h.max_body).await;
            if let Ok(bytes) = &read {
                if let Some(r) = self.try_2026(&rc, bytes).await {
                    return r;
                }
            }
            pre = Some(read);
        }
        if self.only_2026() && parts.method != Method::POST {
            let mut r = plain_error(StatusCode::METHOD_NOT_ALLOWED, "Method Not Allowed");
            r.headers_mut()
                .insert("allow", HeaderValue::from_static("POST"));
            return r;
        }
        if let Some(auth) = &h.cfg.authenticate {
            match auth(Arc::new(rc.clone())).await {
                Ok(id) => rc.identity = Some(id),
                Err(e) => return self.auth_failure(&rc, e),
            }
        }
        match parts.method {
            Method::POST => {
                if !is_json {
                    return plain_error(
                        StatusCode::UNSUPPORTED_MEDIA_TYPE,
                        "Unsupported Media Type: must be application/json",
                    );
                }
                let read = match pre {
                    Some(r) => r,
                    None => read_body(body.take().expect("body"), h.max_body).await,
                };
                match read {
                    Ok(b) => self.handle_post(rc, b).await,
                    Err(r) => *r,
                }
            }
            Method::GET => self.handle_get(rc).await,
            Method::DELETE => self.handle_delete(rc).await,
            _ => {
                let mut r = plain_error(StatusCode::METHOD_NOT_ALLOWED, "Method Not Allowed");
                r.headers_mut()
                    .insert("allow", HeaderValue::from_static("GET, POST, DELETE"));
                r
            }
        }
    }

    /// Answer an `authenticate` failure (both wires): an [`McpAuthError`] ⇒
    /// its status + challenge + `{"error":"unauthorized"}`; else plain 401.
    fn auth_failure(&self, rc: &McpRequestContext, e: McpAuthFailure) -> Response<McpBody> {
        let mut challenge = match &self.inner.cfg.www_authenticate {
            Some(w) => w(rc, &e.to_string()),
            None => String::new(),
        };
        let mut r = if let Some(ae) = e.downcast_ref::<McpAuthError>() {
            if challenge.is_empty() {
                challenge = ae.challenge.clone();
            }
            let status = StatusCode::from_u16(if ae.status == 0 { 401 } else { ae.status })
                .unwrap_or(StatusCode::UNAUTHORIZED);
            let mut r = Response::new(
                Full::new(Bytes::from_static(b"{\"error\":\"unauthorized\"}")).boxed(),
            );
            *r.status_mut() = status;
            r.headers_mut()
                .insert("content-type", HeaderValue::from_static("application/json"));
            r
        } else {
            plain_error(StatusCode::UNAUTHORIZED, "Unauthorized")
        };
        if let (false, Ok(hv)) = (challenge.is_empty(), HeaderValue::from_str(&challenge)) {
            r.headers_mut().insert("www-authenticate", hv);
        }
        r
    }

    /// Validate the `MCP-Protocol-Version` header and (stateful) the session.
    async fn check_session(
        &self,
        mut rc: McpRequestContext,
    ) -> Result<McpRequestContext, Box<Response<McpBody>>> {
        let h = &self.inner;
        let v = rc.header("mcp-protocol-version");
        if !v.is_empty() && !h.legacy.iter().any(|x| x == v) {
            return Err(Box::new(plain_error(
                StatusCode::BAD_REQUEST,
                "Bad Request: unsupported MCP-Protocol-Version",
            )));
        }
        if h.cfg.stateless {
            return Ok(rc);
        }
        let sid = rc.header("mcp-session-id").to_owned();
        if sid.is_empty() {
            return Err(Box::new(plain_error(
                StatusCode::BAD_REQUEST,
                "Bad Request: missing Mcp-Session-Id",
            )));
        }
        match h.ids.validate(Arc::new(rc.clone()), sid.clone()).await {
            Ok(true) => {
                rc.session_id = sid;
                Ok(rc)
            }
            _ => Err(Box::new(plain_error(
                StatusCode::NOT_FOUND,
                "Session not found",
            ))),
        }
    }

    async fn handle_post(&self, rc: McpRequestContext, body: Bytes) -> Response<McpBody> {
        let h = &self.inner;
        let text = String::from_utf8_lossy(&body);
        if text.trim_start().starts_with('[') {
            // JSON-RPC batching was removed in protocol 2025-06-18.
            return rpc_error_response(None, -32600, "batch requests are not supported");
        }
        let msg: RpcMessage = match serde_json::from_slice::<RpcMessage>(&body) {
            Ok(m) if m.jsonrpc == "2.0" => m,
            _ => return rpc_error_response(None, -32700, "parse error"),
        };
        if msg.method == "initialize" {
            return self.handle_initialize(rc, msg).await;
        }
        let mut rc = match self.check_session(rc).await {
            Ok(rc) => rc,
            Err(r) => return *r,
        };
        // A response from the client (the answer to our elicitation).
        if msg.method.is_empty() {
            if let Some(Value::String(id)) = &msg.id {
                let tx = h
                    .pending
                    .lock()
                    .unwrap()
                    .remove(&(rc.session_id.clone(), id.clone()));
                if let Some(tx) = tx {
                    let raw = json!({"result": msg.result, "error": msg.error});
                    let _ = tx.send(raw);
                }
            }
            return empty(StatusCode::ACCEPTED);
        }
        // A notification (no id): acknowledge.
        let Some(id) = msg.id.clone() else {
            return empty(StatusCode::ACCEPTED);
        };
        if let Some(Value::Object(p)) = &msg.params {
            if let Some(Value::Object(m)) = p.get("_meta") {
                rc.meta = Some(m.clone());
            }
        }

        let (tx, mut rx) = mpsc::unbounded_channel();
        let me = self.clone();
        let rc = Arc::new(rc);
        let writer = RpcWriter(tx.clone());
        tokio::spawn(async move {
            let out = me.dispatch(rc, writer, msg).await;
            let _ = tx.send(Out::Final(envelope(&id, out)));
        });
        match rx.recv().await {
            Some(Out::Event(first)) => {
                // Upgrade to SSE: forward events, then the reply, then end.
                let (stx, srx) = mpsc::channel::<Bytes>(16);
                tokio::spawn(async move {
                    if stx.send(sse_frame(&first)).await.is_err() {
                        return;
                    }
                    while let Some(m) = rx.recv().await {
                        let (v, last) = match m {
                            Out::Event(v) => (v, false),
                            Out::Final(v) => (v, true),
                        };
                        if stx.send(sse_frame(&v)).await.is_err() || last {
                            return;
                        }
                    }
                });
                sse_response(srx)
            }
            Some(Out::Final(v)) => json_response(StatusCode::OK, &v),
            None => plain_error(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error"),
        }
    }

    async fn handle_initialize(
        &self,
        mut rc: McpRequestContext,
        msg: RpcMessage,
    ) -> Response<McpBody> {
        let h = &self.inner;
        let p = msg.params.clone().unwrap_or(Value::Null);
        let asked = p
            .get("protocolVersion")
            .and_then(Value::as_str)
            .unwrap_or("");
        let version = if h.legacy.iter().any(|v| v == asked) {
            asked.to_owned()
        } else {
            h.legacy.first().cloned().unwrap_or_default()
        };
        let id = msg.id.clone().unwrap_or(Value::Null);
        let sid;
        if h.cfg.stateless {
            sid = h.cfg.stateless_session_id.clone();
        } else {
            match h.ids.generate(Arc::new(rc.clone())).await {
                Ok(s) => sid = s,
                Err(_) => return rpc_error_response(Some(id), -32603, "cannot create session"),
            }
            rc.session_id = sid.clone();
            let el = p
                .get("capabilities")
                .and_then(|c| c.get("elicitation"))
                .is_some_and(|e| !e.is_null());
            h.caps.lock().unwrap().insert(sid.clone(), el);
        }
        let mut info = McpServerInfo {
            name: h.cfg.name.clone(),
            title: h.cfg.title.clone(),
            version: h.cfg.version.clone(),
            instructions: h.cfg.instructions.clone(),
        };
        if let Some(f) = &h.cfg.server_info {
            info = f(&rc);
        }
        if info.name.is_empty() {
            info.name = DEFAULT_NAME.into();
        }
        if info.version.is_empty() {
            info.version = DEFAULT_VERSION.into();
        }
        let mut caps = json!({"tools": {"listChanged": true}});
        if h.cfg.list_resources.is_some() {
            caps["resources"] = json!({});
        }
        if h.cfg.list_prompts.is_some() {
            caps["prompts"] = json!({});
        }
        let mut res = json!({
            "protocolVersion": version,
            "capabilities": caps,
            "serverInfo": omit_empty(&[("name", &info.name), ("title", &info.title), ("version", &info.version)]),
        });
        if !info.instructions.is_empty() {
            res["instructions"] = Value::String(info.instructions);
        }
        let mut r = json_response(StatusCode::OK, &envelope(&id, Ok(res)));
        if let (false, Ok(hv)) = (sid.is_empty(), HeaderValue::from_str(&sid)) {
            r.headers_mut().insert("mcp-session-id", hv);
        }
        r
    }

    async fn handle_get(&self, rc: McpRequestContext) -> Response<McpBody> {
        if !rc.header("accept").contains("text/event-stream") {
            return plain_error(StatusCode::METHOD_NOT_ALLOWED, "Method Not Allowed");
        }
        if let Err(r) = self.check_session(rc).await {
            return *r;
        }
        let (tx, rx) = mpsc::channel::<Bytes>(16);
        self.inner.streams.lock().unwrap().push(tx);
        sse_response(rx)
    }

    async fn handle_delete(&self, rc: McpRequestContext) -> Response<McpBody> {
        let h = &self.inner;
        if h.cfg.stateless {
            return plain_error(StatusCode::METHOD_NOT_ALLOWED, "Method Not Allowed");
        }
        let rc = match self.check_session(rc).await {
            Ok(rc) => rc,
            Err(r) => return *r,
        };
        let sid = rc.session_id.clone();
        if h.ids.terminate(Arc::new(rc), sid.clone()).await.is_err() {
            return plain_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "cannot terminate session",
            );
        }
        h.caps.lock().unwrap().remove(&sid);
        empty(StatusCode::OK)
    }

    // ── JSON-RPC dispatch ────────────────────────────────────────────────

    async fn tools(&self, rc: &Ctx) -> Result<Vec<Tool>, String> {
        match &self.inner.cfg.list_tools {
            Some(f) => f(rc.clone()).await,
            None => Ok(self.inner.tk.tools()),
        }
    }

    async fn dispatch(&self, rc: Ctx, w: RpcWriter, msg: RpcMessage) -> Result<Value, RpcErr> {
        let cfg = &self.inner.cfg;
        let params = msg.params.clone().unwrap_or(Value::Null);
        let not_found = || rpc(-32601, format!("method not found: {}", msg.method));
        match msg.method.as_str() {
            "ping" => Ok(json!({})),
            "tools/list" => {
                let tools = self.tools(&rc).await.map_err(|e| rpc(-32603, e))?;
                Ok(json!({"tools": tools.iter().map(mcp_wire_tool).collect::<Vec<_>>()}))
            }
            "tools/call" => self.call_tool(rc, w, params).await,
            "resources/list" => {
                let f = cfg.list_resources.as_ref().ok_or_else(not_found)?;
                let rs = f(rc).await.map_err(|e| rpc(-32603, e))?;
                let out: Vec<Value> = rs
                    .iter()
                    .map(|r| {
                        Value::Object(omit_empty(&[
                            ("uri", &r.uri),
                            ("name", &r.name),
                            ("title", &r.title),
                            ("description", &r.description),
                            ("mimeType", &r.mime_type),
                        ]))
                    })
                    .collect();
                Ok(json!({"resources": out}))
            }
            "resources/read" => {
                let (Some(_), Some(f)) = (&cfg.list_resources, &cfg.read_resource) else {
                    return Err(not_found());
                };
                let uri = params
                    .get("uri")
                    .and_then(Value::as_str)
                    .unwrap_or("")
                    .to_owned();
                let cs = f(rc, uri).await.map_err(|e| rpc(-32002, e))?;
                let out: Vec<Value> = cs
                    .iter()
                    .map(|c| {
                        let mut m = omit_empty(&[
                            ("uri", &c.uri),
                            ("mimeType", &c.mime_type),
                            ("blob", &c.blob),
                        ]);
                        if c.blob.is_empty() {
                            m.insert("text".into(), Value::String(c.text.clone()));
                        }
                        Value::Object(m)
                    })
                    .collect();
                Ok(json!({"contents": out}))
            }
            "prompts/list" => {
                let f = cfg.list_prompts.as_ref().ok_or_else(not_found)?;
                let ps = f(rc).await.map_err(|e| rpc(-32603, e))?;
                let out: Vec<Value> = ps
                    .iter()
                    .map(|p| {
                        let mut m = omit_empty(&[
                            ("name", &p.name),
                            ("title", &p.title),
                            ("description", &p.description),
                        ]);
                        if !p.arguments.is_empty() {
                            let args: Vec<Value> = p
                                .arguments
                                .iter()
                                .map(|a| {
                                    let mut am = omit_empty(&[
                                        ("name", &a.name),
                                        ("description", &a.description),
                                    ]);
                                    if a.required {
                                        am.insert("required".into(), Value::Bool(true));
                                    }
                                    Value::Object(am)
                                })
                                .collect();
                            m.insert("arguments".into(), Value::Array(args));
                        }
                        Value::Object(m)
                    })
                    .collect();
                Ok(json!({"prompts": out}))
            }
            "prompts/get" => {
                let (Some(_), Some(f)) = (&cfg.list_prompts, &cfg.get_prompt) else {
                    return Err(not_found());
                };
                #[derive(serde::Deserialize)]
                struct P {
                    #[serde(default)]
                    name: String,
                    #[serde(default)]
                    arguments: Option<HashMap<String, String>>,
                }
                let p: P =
                    serde_json::from_value(params).map_err(|_| rpc(-32602, "invalid params"))?;
                let pr = f(rc, p.name, p.arguments.unwrap_or_default())
                    .await
                    .map_err(|e| rpc(-32602, e))?;
                let msgs: Vec<Value> = pr
                    .messages
                    .iter()
                    .map(|m| json!({"role": m.role, "content": {"type": "text", "text": m.text}}))
                    .collect();
                let mut out = omit_empty(&[("description", &pr.description)]);
                out.insert("messages".into(), Value::Array(msgs));
                Ok(Value::Object(out))
            }
            _ => Err(not_found()),
        }
    }

    async fn call_tool(&self, rc: Ctx, w: RpcWriter, params: Value) -> Result<Value, RpcErr> {
        let h = &self.inner;
        let Value::Object(p) = params else {
            return Err(rpc(-32602, "invalid params"));
        };
        let name = match p.get("name") {
            None | Some(Value::Null) => String::new(),
            Some(Value::String(s)) => s.clone(),
            Some(_) => return Err(rpc(-32602, "invalid params")),
        };
        let tools = self.tools(&rc).await.map_err(|e| rpc(-32603, e))?;
        let Some(tool) = tools.into_iter().find(|t| t.name == name) else {
            return Err(rpc(-32602, format!("tool not found: {name}")));
        };
        let args = match p.get("arguments") {
            None | Some(Value::Null) => Value::Object(Map::new()),
            Some(Value::Object(m)) => Value::Object(m.clone()),
            Some(_) => {
                if rc.header("mcp-protocol-version") == "2025-11-25" {
                    // 2025-11-25: input validation errors are tool execution errors.
                    return Ok(tool_result_to_mcp(&ToolResult::error(
                        "invalid arguments: must be an object",
                    )));
                }
                return Err(rpc(-32602, "arguments must be an object"));
            }
        };

        let started = Instant::now();
        let mut ev = McpCallEvent {
            name: tool.name.clone(),
            source: tool.source,
            ms: 0,
            is_error: false,
            err: None,
            result_bytes: 0,
            decision: McpDecisionKind::Allow,
            identity: rc.identity.clone(),
            session_id: rc.session_id.clone(),
        };
        let on_call = h.cfg.on_call.clone();
        let finish = move |mut ev: McpCallEvent, res: &ToolResult, err: Option<String>| {
            let wire = tool_result_to_mcp(res);
            ev.ms = started.elapsed().as_millis() as u64;
            ev.is_error = res.is_error;
            ev.err = err;
            ev.result_bytes = serde_json::to_vec(&wire).map(|b| b.len()).unwrap_or(0);
            if let Some(cb) = &on_call {
                let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cb(ev)));
            }
            wire
        };

        if let Some(bc) = &h.cfg.before_call {
            let d = match bc(rc.clone(), tool.clone(), args.clone()).await {
                Ok(d) => d,
                Err(e) => McpDecision::deny(e),
            };
            ev.decision = d.kind;
            match d.kind {
                McpDecisionKind::Allow => {}
                McpDecisionKind::Deny => {
                    let res = d.result.unwrap_or_else(|| {
                        ToolResult::error(if d.message.is_empty() {
                            "denied".to_owned()
                        } else {
                            d.message.clone()
                        })
                    });
                    return Ok(finish(ev, &res, None));
                }
                McpDecisionKind::Confirm => {
                    if !self.can_elicit(&rc.session_id) {
                        let res = d.result.unwrap_or_else(|| {
                            ToolResult::error(format!("confirmation required: {}", d.message))
                        });
                        return Ok(finish(ev, &res, None));
                    }
                    match self.elicit_confirm(&rc.session_id, &w, &d.message).await {
                        Err(e) => {
                            let res = ToolResult::error(format!("confirmation failed: {e}"));
                            return Ok(finish(ev, &res, None));
                        }
                        Ok(false) => return Ok(finish(ev, &ToolResult::error("declined"), None)),
                        Ok(true) => {}
                    }
                }
            }
        }

        let ctx = ToolContext {
            request: Some(rc.clone() as Arc<dyn Any + Send + Sync>),
            ..Default::default()
        };
        let t = tool.clone();
        // A panicking tool is an isError result, never a protocol crash.
        let res = match tokio::spawn(async move { t.call(args, ctx).await }).await {
            Ok(r) => r,
            Err(e) => ToolResult::error(format!("tool panicked: {e}")),
        };
        let err = res.is_error.then(|| res.output.clone());
        Ok(finish(ev, &res, err))
    }

    fn can_elicit(&self, sid: &str) -> bool {
        !sid.is_empty() && *self.inner.caps.lock().unwrap().get(sid).unwrap_or(&false)
    }

    /// `elicitation/create` on this POST's SSE stream; the answer arrives on a
    /// separate POST.
    async fn elicit_confirm(
        &self,
        sid: &str,
        w: &RpcWriter,
        message: &str,
    ) -> Result<bool, String> {
        let h = &self.inner;
        let id = format!(
            "toolnexus-confirm-{}",
            h.seq.fetch_add(1, Ordering::SeqCst) + 1
        );
        let key = (sid.to_owned(), id.clone());
        let (tx, rx) = oneshot::channel();
        h.pending.lock().unwrap().insert(key.clone(), tx);
        struct Cleanup<'a>(&'a Inner, (String, String));
        impl Drop for Cleanup<'_> {
            fn drop(&mut self) {
                self.0.pending.lock().unwrap().remove(&self.1);
            }
        }
        let _g = Cleanup(h, key);
        let message = if message.is_empty() {
            "Confirm this action?"
        } else {
            message
        };
        let req = json!({
            "jsonrpc": "2.0", "id": id, "method": "elicitation/create",
            "params": {
                "message": message,
                "requestedSchema": {
                    "type": "object",
                    "properties": {
                        "confirm": {"type": "boolean", "title": "Confirm", "description": message}
                    }
                }
            }
        });
        if !w.event(req) {
            return Err("stream closed".into());
        }
        let raw = match tokio::time::timeout(h.confirm_timeout, rx).await {
            Ok(Ok(v)) => v,
            Ok(Err(_)) => return Err("stream closed".into()),
            Err(_) => return Err("context deadline exceeded".into()),
        };
        if raw.get("error").is_some_and(|e| !e.is_null()) {
            return Err("client returned an error".into());
        }
        let Some(Value::Object(r)) = raw.get("result") else {
            return Err("unexpected end of JSON input".into());
        };
        if r.get("action").and_then(Value::as_str) != Some("accept") {
            return Ok(false);
        }
        if let Some(Value::Bool(false)) = r.get("content").and_then(|c| c.get("confirm")) {
            return Ok(false);
        }
        Ok(true)
    }
}

impl<B> hyper::service::Service<Request<B>> for McpHandler
where
    B: Body + Send + 'static,
    B::Data: Send,
    B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
    type Response = Response<McpBody>;
    type Error = Infallible;
    type Future = BoxFuture<Result<Response<McpBody>, Infallible>>;

    fn call(&self, req: Request<B>) -> Self::Future {
        let me = self.clone();
        Box::pin(async move { Ok(me.handle(req).await) })
    }
}

// ── wire helpers (shared with §7C serve) ─────────────────────────────────

/// The `tools/list` entry for `t`: name, description, inputSchema,
/// outputSchema when set, and annotations (verbatim; else derived from hints;
/// else omitted).
pub(crate) fn mcp_wire_tool(t: &Tool) -> Value {
    let schema = if t.input_schema.is_null() {
        json!({"type": "object"})
    } else {
        t.input_schema.clone()
    };
    let mut m = json!({"name": t.name, "description": t.description, "inputSchema": schema});
    if let Some(os) = &t.output_schema {
        m["outputSchema"] = os.clone();
    }
    let ann = if let Some(a) = &t.annotations {
        serde_json::to_value(a).unwrap_or(Value::Null)
    } else if let Some(hh) = &t.hints {
        json!({"readOnlyHint": hh.read_only, "destructiveHint": hh.destructive, "openWorldHint": hh.open_world})
    } else {
        Value::Null
    };
    if ann.as_object().is_some_and(|o| !o.is_empty()) {
        m["annotations"] = ann;
    }
    m
}

/// A ToolResult as the MCP CallToolResult: output → text block (the JSON of
/// `structured` when output is empty), §1B parts after it, isError when true,
/// structuredContent / _meta when set.
pub(crate) fn tool_result_to_mcp(res: &ToolResult) -> Value {
    let mut text = res.output.clone();
    if text.is_empty() {
        if let Some(st) = &res.structured {
            text = serde_json::to_string(st).unwrap_or_default();
        }
    }
    let mut content = vec![json!({"type": "text", "text": text})];
    content.extend(res.parts.iter().filter_map(part_to_mcp));
    let mut out = json!({"content": content});
    if res.is_error {
        out["isError"] = Value::Bool(true);
    }
    if let Some(st) = &res.structured {
        out["structuredContent"] = st.clone();
    }
    if let Some(m) = &res.meta {
        out["_meta"] = Value::Object(m.clone());
    }
    out
}

fn part_to_mcp(p: &ContentPart) -> Option<Value> {
    let link = || {
        let mut m = omit_empty(&[
            ("uri", &p.url),
            ("name", &p.name),
            ("mimeType", &p.mime_type),
        ]);
        m.insert("type".into(), json!("resource_link"));
        m.entry("uri").or_insert(json!(""));
        m.entry("name").or_insert(json!(""));
        Value::Object(m)
    };
    match p.kind.as_str() {
        "text" => Some(json!({"type": "text", "text": p.text})),
        "image" | "audio" if !p.data.is_empty() => {
            Some(json!({"type": p.kind, "data": p.data, "mimeType": p.mime_type}))
        }
        "file" if !p.data.is_empty() => {
            let mut r = omit_empty(&[("uri", &p.name), ("mimeType", &p.mime_type)]);
            r.entry("uri").or_insert(json!(""));
            r.insert("blob".into(), json!(p.data));
            Some(json!({"type": "resource", "resource": r}))
        }
        "image" | "audio" | "file" => Some(link()),
        _ => None,
    }
}