pmcp-server-toolkit 0.1.0

Runtime library for config-driven MCP servers — auth, secrets, static resources/prompts, [[tools]] synthesizer, code-mode wiring
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
// Net-new code for Phase 83 TKIT-07.
// Lands the `[[tools]]`-config-driven synthesizer that turns config rows into
// `ToolInfo` + `Arc<dyn ToolHandler>` pairs.

//! `[[tools]]` → `ToolInfo` + `Arc<dyn ToolHandler>` synthesizer.
//!
//! Net-new code for Phase 83 TKIT-07. Turns curated `[[tools]]` config entries
//! into complete pmcp [`ToolInfo`] + [`Arc<dyn ToolHandler>`] pairs with zero
//! per-tool Rust handlers.
//!
//! # Invariants enforced
//!
//! - **JSON Schema object envelope.** Every synthesized [`ToolInfo`] carries an
//!   `input_schema` with `"type": "object"`, an explicit `properties` map, a
//!   `required` array, and `"additionalProperties": false`. Unknown argument
//!   keys are rejected by pmcp's request-validation path at `tools/call` time —
//!   defence-in-depth against arg-injection (threat T-83-05-02).
//! - **`handler.metadata()` returns `Some(ToolInfo)`.** Phase 82's `tool_arc`
//!   consumes `handler.metadata()` at registration; returning `None` would
//!   silently degrade the schema enforcement to "anything goes" (RESEARCH
//!   §Risks #2 — threat T-83-05-01).
//! - **Constructors, never struct-literals.** Both [`ToolInfo`] and
//!   [`ToolAnnotations`] are `#[non_exhaustive]` (PATTERNS §Pattern C). The
//!   synthesizer uses [`ToolInfo::with_annotations`] / [`ToolInfo::new`] and
//!   the [`ToolAnnotations::new()`]-then-`.with_*` fluent builder.
//! - **Cognitive complexity ≤25 per function.** Decomposed into
//!   [`build_input_schema`], [`build_param_property`], and [`build_annotations`]
//!   per Phase 75 D-03 + PATTERNS §Pattern G. No `#[allow]` annotations.

use std::sync::Arc;

use async_trait::async_trait;
use pmcp::server::ToolHandler;
use pmcp::types::{ToolAnnotations, ToolInfo};
use pmcp::RequestHandlerExtra;
use serde_json::{json, Map, Value};

use crate::config::{AnnotationsDecl, ParamDecl, ServerConfig, ToolDecl};
use crate::error::Result;
use crate::sql::SqlConnector;

#[cfg(feature = "http")]
use crate::error::ToolkitError;
#[cfg(feature = "http")]
use crate::http::{HttpConnector, Operation, Parameter, ParameterLocation};

#[cfg(feature = "openapi-code-mode")]
use crate::code_mode::HttpCodeExecutor;
#[cfg(feature = "openapi-code-mode")]
use pmcp_code_mode::ExecutionConfig;

/// Type alias for one synthesized tool tuple: `(name, ToolInfo, Arc<dyn ToolHandler>)`.
///
/// Exists so [`synthesize_from_config`]'s return type does not trip
/// `clippy::type_complexity` while preserving the exact `(name, ToolInfo, Arc)`
/// shape consumers register with `pmcp::ServerBuilder::tool_arc` (PATTERNS §9).
pub type SynthesizedTool = (String, ToolInfo, Arc<dyn ToolHandler>);

/// Synthesize one `ToolInfo` + handler per `[[tools]]` config entry.
///
/// Each returned tuple is `(name, ToolInfo, Arc<dyn ToolHandler>)` and is
/// ready to feed into `pmcp::ServerBuilder::tool_arc(name, handler)`. The
/// `ToolInfo` carries the full input schema (synthesized from
/// `[[tools.parameters]]`) and `ToolAnnotations` (from `[tools.annotations]`)
/// so the builder's metadata cache will never fall back to the empty schema.
///
/// # Errors
///
/// Returns [`crate::ToolkitError::Synth`] if a tool declaration is internally
/// inconsistent. The Plan 05 GREEN body never produces this error path —
/// synthesis is total over the parsed [`ServerConfig`] surface — but the
/// `Result` return is kept for forward compatibility with Plan 06 (code-mode
/// wiring) and Phase 84 (SQL backend resolution).
///
/// # Example
///
/// ```
/// use pmcp_server_toolkit::config::ServerConfig;
/// use pmcp_server_toolkit::tools::synthesize_from_config;
///
/// let cfg = ServerConfig::default();
/// let synthesized = synthesize_from_config(&cfg).unwrap();
/// assert_eq!(synthesized.len(), 0);
/// ```
pub fn synthesize_from_config(config: &ServerConfig) -> Result<Vec<SynthesizedTool>> {
    synthesize_inner(config, None)
}

/// Synthesize tools that execute against a wired [`SqlConnector`] (Phase 84
/// CONN-01 / D-06). ADDITIVE variant alongside [`synthesize_from_config`] — the
/// existing API is unchanged and all P83 callers compile without modification.
///
/// Each synthesized [`SynthesizedToolHandler`] holds the shared `connector`, so
/// its `handle()` body calls [`SqlConnector::execute`] with the tool's declared
/// `sql` + the named parameters extracted from the validated args. When a tool
/// declares `ui_resource_uri`, the synthesized [`ToolInfo`] also carries widget
/// metadata so pmcp core's `with_widget_enrichment` populates `structuredContent`
/// (D-06) — that flip lives in the shared [`synthesize_inner`] helper and so
/// fires for both entry points.
///
/// # Errors
///
/// Returns [`crate::ToolkitError::Synth`] if a tool declaration is internally
/// inconsistent. Synthesis is total over the parsed [`ServerConfig`] surface —
/// the connector is threaded into each handler for runtime use, not consulted at
/// synthesis time.
///
/// # Example
///
/// ```no_run
/// use std::sync::Arc;
/// use pmcp_server_toolkit::config::ServerConfig;
/// use pmcp_server_toolkit::sql::SqlConnector;
/// use pmcp_server_toolkit::tools::synthesize_from_config_with_connector;
///
/// fn build(connector: Arc<dyn SqlConnector>) {
///     let cfg = ServerConfig::default();
///     let tools = synthesize_from_config_with_connector(&cfg, connector).unwrap();
///     assert_eq!(tools.len(), 0);
/// }
/// ```
pub fn synthesize_from_config_with_connector(
    config: &ServerConfig,
    connector: Arc<dyn SqlConnector>,
) -> Result<Vec<SynthesizedTool>> {
    synthesize_inner(config, Some(connector))
}

/// Shared synthesizer body for both [`synthesize_from_config`] (no connector)
/// and [`synthesize_from_config_with_connector`] (connector wired).
///
/// Keeps the two public entry points one-liners so the widget_meta flip (D-06)
/// and the handler construction logic are not duplicated. Decomposed per
/// PATTERNS §Pattern G — the per-tool body delegates to [`build_input_schema`],
/// [`build_annotations`], and [`apply_widget_meta`] to stay under cog 25.
fn synthesize_inner(
    config: &ServerConfig,
    connector: Option<Arc<dyn SqlConnector>>,
) -> Result<Vec<SynthesizedTool>> {
    let mut out = Vec::with_capacity(config.tools.len());
    for decl in &config.tools {
        let info = build_tool_info(decl);
        let handler: Arc<dyn ToolHandler> = Arc::new(SynthesizedToolHandler {
            info: info.clone(),
            decl: decl.clone(),
            connector: connector.clone(),
        });
        out.push((decl.name.clone(), info, handler));
    }
    Ok(out)
}

/// Flip widget metadata onto `info` when the declaration carries a
/// `ui_resource_uri` (D-06 / REVIEWS M1).
///
/// Uses the feature-independent [`ToolInfo::with_meta_entry`] surface to insert
/// `_meta.ui.resourceUri`. This is the verified-correct API: `with_widget_meta`
/// is gated on pmcp's `mcp-apps` feature (which the toolkit does not enable),
/// whereas `with_meta_entry` is always available and produces the `ui.resourceUri`
/// shape that `ToolInfo::widget_meta()` recognises — so pmcp core's
/// `with_widget_enrichment` populates `structuredContent`. Annotations on `info`
/// are preserved (chained, not reconstructed).
fn apply_widget_meta(info: ToolInfo, decl: &ToolDecl) -> ToolInfo {
    match decl.ui_resource_uri.as_deref() {
        Some(uri) => info.with_meta_entry("ui", json!({ "resourceUri": uri })),
        None => info,
    }
}

/// Build the [`ToolInfo`] for a synthesized tool from its declaration.
///
/// The schema + annotations + widget-meta sequence is identical for every tool
/// kind (single-call HTTP, SQL, and script), so it lives here once — keeping the
/// `#[non_exhaustive]` [`ToolInfo`] constructor discipline (the `with_annotations`
/// vs `new` arms) in a single place rather than copy-pasted per synthesizer.
fn build_tool_info(decl: &ToolDecl) -> ToolInfo {
    let schema = build_input_schema(&decl.parameters);
    let annotations = build_annotations(decl.annotations.as_ref());
    let base = match annotations {
        Some(ann) => {
            ToolInfo::with_annotations(decl.name.clone(), decl.description.clone(), schema, ann)
        },
        None => ToolInfo::new(decl.name.clone(), decl.description.clone(), schema),
    };
    apply_widget_meta(base, decl)
}

/// Build the JSON Schema `properties` + `required` envelope from a
/// `[[tools.parameters]]` list.
///
/// Decomposed from [`synthesize_from_config`] to keep cognitive complexity ≤25
/// (Phase 75 D-03 + PATTERNS §Pattern G).
fn build_input_schema(params: &[ParamDecl]) -> Value {
    let mut props = Map::new();
    let mut required = Vec::new();
    for p in params {
        props.insert(p.name.clone(), build_param_property(p));
        if p.required {
            required.push(Value::String(p.name.clone()));
        }
    }
    json!({
        "type": "object",
        "properties": props,
        "required": required,
        "additionalProperties": false,
    })
}

/// Build a single JSON Schema property object from a [`ParamDecl`].
///
/// Per-parameter constraints (`minimum`, `maximum`, `maxLength`, `default`,
/// `enum`) are folded in only when present; the param's `param_type` defaults
/// to `"string"` when omitted in TOML to match JSON Schema's permissive
/// default.
fn build_param_property(p: &ParamDecl) -> Value {
    let ty = p.param_type.as_deref().unwrap_or("string");
    let mut prop = json!({ "type": ty });
    if let Some(desc) = &p.description {
        prop["description"] = Value::String(desc.clone());
    }
    if let Some(min) = p.minimum {
        prop["minimum"] = json!(min);
    }
    if let Some(max) = p.maximum {
        prop["maximum"] = json!(max);
    }
    if let Some(max_len) = p.max_length {
        prop["maxLength"] = json!(max_len);
    }
    if let Some(default) = &p.default {
        // toml::Value serializes losslessly into serde_json::Value via serde.
        if let Ok(v) = serde_json::to_value(default) {
            prop["default"] = v;
        }
    }
    if let Some(enum_vals) = &p.enum_values {
        if let Ok(v) = serde_json::to_value(enum_vals) {
            prop["enum"] = v;
        }
    }
    prop
}

/// Build [`ToolAnnotations`] from an optional `[tools.annotations]` block.
///
/// Per PATTERNS §Pattern C, the constructor + fluent builder is used (never a
/// struct literal — [`ToolAnnotations`] is `#[non_exhaustive]`). The `cost_hint`
/// field has no `ToolAnnotations` accessor and is therefore not propagated at
/// this layer; it lives on the toolkit's [`AnnotationsDecl`] and is consumed
/// by future plans that surface cost into rate-limiting policy.
fn build_annotations(decl: Option<&AnnotationsDecl>) -> Option<ToolAnnotations> {
    let d = decl?;
    let a = ToolAnnotations::new()
        .with_read_only(d.read_only_hint)
        .with_destructive(d.destructive_hint)
        .with_idempotent(d.idempotent_hint)
        .with_open_world(d.open_world_hint);
    Some(a)
}

// -----------------------------------------------------------------------------
// SynthesizedToolHandler — crate-private
// -----------------------------------------------------------------------------

/// Crate-private handler wrapping a synthesized [`ToolInfo`].
///
/// [`ToolHandler::metadata`] MUST return `Some(self.info.clone())` — Phase 82's
/// `tool_arc` consumes `handler.metadata()` at registration time; returning
/// `None` would cause the builder to fall back to an empty schema (RESEARCH
/// §Risks #2 — threat T-83-05-01). The unit + property tests in
/// [`crate::tools`] and `tests/tool_synthesis_props.rs` lock this in.
///
/// `handle()` reads the declared `sql`, extracts named parameters from the
/// validated args, and calls [`SqlConnector::execute`] when a `connector` is
/// wired (handlers built via [`synthesize_from_config_with_connector`]).
/// Handlers built via the no-connector [`synthesize_from_config`] carry
/// `connector = None` and return an explicit `Err` on invocation — preserving
/// P83 behaviour where the no-connector path was test-only (T-84-03-05). The
/// `decl` is held so the handler can read `sql` / `ui_resource_uri` /
/// `parameters` without re-walking the config.
struct SynthesizedToolHandler {
    info: ToolInfo,
    decl: ToolDecl,
    /// `Some` only for handlers built via [`synthesize_from_config_with_connector`].
    connector: Option<Arc<dyn SqlConnector>>,
}

/// Extract the named `(name, value)` parameter pairs the connector binds from,
/// filtering the caller's validated `args` against the declared parameter list
/// (T-84-03-01: only declared parameter names reach `execute()`; extra keys are
/// silently dropped — JSON-schema validation rejects them upstream).
///
/// When the caller omits an optional parameter that declares a `default`, the
/// default is applied so the bound SQL sees a concrete value. Without this an
/// omitted `:limit` / `:offset` would bind as unbound `NULL` and SQLite rejects
/// `LIMIT NULL` with a "datatype mismatch" — so the declared default is the
/// difference between a working and a broken tool call (the reference
/// `search_tracks` / `list_artists` calls rely on it).
///
/// An EXPLICIT JSON `null` for a declared-default parameter is treated the SAME
/// as an omitted parameter — the declared default is applied (85-10 WR-02
/// secondary fix). Without the `is_null` filter a caller sending
/// `{"limit": null}` would bind `LIMIT NULL` and SQLite would reject the query
/// with "datatype mismatch", even though the tool declares `default = 20`.
fn extract_named_params(decl: &ToolDecl, args: &Value) -> Vec<(String, Value)> {
    decl.parameters
        .iter()
        .filter_map(|p| {
            args.get(&p.name)
                // Explicit JSON `null` falls through to the declared default,
                // exactly like an omitted key (no `LIMIT NULL` bind).
                .filter(|v| !v.is_null())
                .cloned()
                .or_else(|| {
                    p.default
                        .as_ref()
                        .and_then(|d| serde_json::to_value(d).ok())
                })
                .map(|v| (p.name.clone(), v))
        })
        .collect()
}

#[async_trait]
impl ToolHandler for SynthesizedToolHandler {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> pmcp::Result<Value> {
        let sql = self.decl.sql.as_deref().ok_or_else(|| {
            pmcp::Error::Internal(format!("tool '{}' has no `sql` declared", self.info.name))
        })?;
        let connector = self.connector.as_ref().ok_or_else(|| {
            pmcp::Error::Internal(format!(
                "tool '{}' requires connector wiring — build via synthesize_from_config_with_connector",
                self.info.name
            ))
        })?;
        let named_params = extract_named_params(&self.decl, &args);
        // T-84-03-02: format!("{e}") uses ConnectorError::Display, which Plan 01
        // Task 2 guarantees does not echo credentials.
        let rows = connector
            .execute(sql, &named_params)
            .await
            .map_err(|e| pmcp::Error::Internal(format!("connector error: {e}")))?;
        Ok(Value::Array(rows))
    }

    fn metadata(&self) -> Option<ToolInfo> {
        Some(self.info.clone())
    }
}

// -----------------------------------------------------------------------------
// Single-call HTTP synthesizer (Phase 90 OAPI-02a) — feature `http`
// -----------------------------------------------------------------------------

/// Synthesize one `ToolInfo` + handler per single-call `[[tools]]` entry,
/// executing against a wired [`HttpConnector`] (Phase 90 OAPI-02a / D-01).
///
/// Mirrors [`synthesize_from_config_with_connector`] (the SQL analog) in shape.
/// For each `[[tools]]` where [`ToolDecl::is_script_tool`] is `false` and a
/// `path` + `method` pair is present, an [`Operation`] is built from the path
/// template (the `{...}` segments become path parameters), the declared
/// `[[tools.parameters]]` (non-path params become query params; `POST`/`PUT`/
/// `PATCH` carry a request body), and the per-tool `base_url` override — which is
/// reflected onto the [`Operation`] so the connector targets the per-tool host
/// (never silently dropped, Codex MEDIUM). The synthesized [`ToolInfo`] uses the
/// EXISTING [`build_input_schema`] (object envelope + `additionalProperties:false`)
/// and [`build_annotations`] helpers; the handler calls
/// [`HttpConnector::execute`] and returns the JSON.
///
/// # Script-tool seam (Plan 05)
///
/// A `script` tool encountered here returns a typed [`ToolkitError::Synth`] — it
/// is an EXPLICIT, clearly-marked seam, NOT a silent skip and NOT a `todo!()`.
/// Plan 05 widens this function's signature (adding the shared `http_exec` +
/// `exec_config`) and fills the `is_script_tool()` arm with a `ScriptToolHandler`
/// branch; that change is a localized, anticipated edit because the seam is
/// surfaced here.
///
/// # Errors
///
/// Returns [`ToolkitError::Synth`] when a `[[tools]]` entry is a `script` tool
/// (Plan 05 seam) or is neither a valid single-call (missing `path` OR `method`)
/// nor a script tool (T-90-03-04 negative validation — an ill-formed tool is
/// rejected, never silently registered).
#[cfg(feature = "http")]
pub fn synthesize_from_config_with_http_connector(
    config: &ServerConfig,
    connector: Arc<dyn HttpConnector>,
) -> Result<Vec<SynthesizedTool>> {
    // No script-tool builder is supplied on this (single-call-only) entry point,
    // so the `is_script_tool()` arm of [`synthesize_http_inner`] returns the
    // typed Plan 05 seam error. The OpenAPI Code Mode build calls
    // [`synthesize_from_config_with_http_connector_and_scripts`], which supplies
    // a [`ScriptToolHandler`] builder so a `script` tool synthesizes a real
    // handler over the shared engine (OAPI-02b / D-01 / D-02).
    synthesize_http_inner(config, connector, |decl| {
        Err(ToolkitError::Synth(format!(
            "tool '{}' is a script tool — script tools require the `openapi-code-mode` \
             feature (use synthesize_from_config_with_http_connector_and_scripts)",
            decl.name
        )))
    })
}

/// Synthesize single-call AND script `[[tools]]` against a wired
/// [`HttpConnector`] plus a shared [`HttpCodeExecutor`] + [`ExecutionConfig`]
/// (Phase 90 OAPI-02b / D-01 / D-02).
///
/// This is the OpenAPI Code Mode entry point (gated `openapi-code-mode`): it
/// adds the `http_exec` + `exec_config` the script-tool path needs, threading
/// the SAME `HttpCodeExecutor` instance that feeds Code Mode (D-02 — one engine,
/// two surfaces). Single-call tools synthesize exactly as in
/// [`synthesize_from_config_with_http_connector`]; a `script` tool synthesizes a
/// [`ScriptToolHandler`] that compiles + runs the embedded JS through the SAME
/// `PlanCompiler` + `PlanExecutor` + `HttpCodeExecutor` seam Code Mode uses,
/// with NO validate/token cycle (admin-authored, `ExecutionConfig`-bounded —
/// Pitfall 7).
///
/// The binary (Plan 06) supplies `http_exec` (built once over the resolved
/// backend `base_url` + auth provider) and `exec_config` (from the
/// `[code_mode.limits]` / defaults: `max_api_calls=50`, `max_loop_iterations=100`,
/// `timeout_seconds=30`).
///
/// # Errors
///
/// Returns [`ToolkitError::Synth`] when a `[[tools]]` entry is neither a valid
/// single-call (missing `path` OR `method`) nor a script tool (T-90-03-04
/// negative validation), or when a script tool fails to build its `ToolInfo`.
#[cfg(feature = "openapi-code-mode")]
pub fn synthesize_from_config_with_http_connector_and_scripts(
    config: &ServerConfig,
    connector: Arc<dyn HttpConnector>,
    http_exec: HttpCodeExecutor,
    exec_config: ExecutionConfig,
) -> Result<Vec<SynthesizedTool>> {
    synthesize_http_inner(config, connector, |decl| {
        let handler = ScriptToolHandler::new(decl, http_exec.clone(), exec_config.clone())?;
        let info = handler.tool_info.clone();
        let arc: Arc<dyn ToolHandler> = Arc::new(handler);
        Ok((info, arc))
    })
}

/// Shared synthesizer body for the single-call HTTP entry points.
///
/// `build_script_tool` is invoked for each `script` tool: the single-call-only
/// entry point passes a closure that returns the typed Plan 05 / `openapi-code-mode`
/// seam error, while the OpenAPI Code Mode entry point passes a closure that
/// constructs a [`ScriptToolHandler`]. Decomposed per PATTERNS §Pattern G to keep
/// the per-tool loop body under cog ≤25.
#[cfg(feature = "http")]
fn synthesize_http_inner(
    config: &ServerConfig,
    connector: Arc<dyn HttpConnector>,
    mut build_script_tool: impl FnMut(&ToolDecl) -> Result<(ToolInfo, Arc<dyn ToolHandler>)>,
) -> Result<Vec<SynthesizedTool>> {
    let mut out = Vec::with_capacity(config.tools.len());
    for decl in &config.tools {
        if decl.is_script_tool() {
            let (info, handler) = build_script_tool(decl)?;
            out.push((decl.name.clone(), info, handler));
            continue;
        }

        // Single-call requires BOTH path and method. A `[[tools]]` that is
        // neither a valid single-call nor a script tool is rejected (T-90-03-04).
        let (path, method) = match (decl.path.as_deref(), decl.method.as_deref()) {
            (Some(p), Some(m)) => (p, m),
            _ => {
                return Err(ToolkitError::Synth(format!(
                    "tool '{}' is not a valid single-call tool: both `path` and `method` are required",
                    decl.name
                )));
            },
        };

        let operation = build_operation(path, method, decl);
        let info = build_tool_info(decl);
        let handler: Arc<dyn ToolHandler> = Arc::new(HttpToolHandler {
            info: info.clone(),
            operation,
            connector: connector.clone(),
        });
        out.push((decl.name.clone(), info, handler));
    }
    Ok(out)
}

/// Build the [`Operation`] for a single-call tool from its `path` template,
/// `method`, declared parameters, and per-tool `base_url`.
///
/// Path parameters are the `{...}` segments of the path template; every other
/// declared `[[tools.parameters]]` becomes a query parameter (the reference
/// `create_tool_from_config` mapping). `POST`/`PUT`/`PATCH` carry a request body
/// so non-path/query args are sent as JSON. The per-tool `base_url` is reflected
/// onto the [`Operation`] (Codex MEDIUM — never dropped).
#[cfg(feature = "http")]
fn build_operation(path: &str, method: &str, decl: &ToolDecl) -> Operation {
    let method_upper = method.to_uppercase();
    let path_param_names: Vec<&str> = path
        .split('/')
        .filter(|s| s.starts_with('{') && s.ends_with('}') && s.len() > 2)
        .map(|s| &s[1..s.len() - 1])
        .collect();

    let mut parameters = Vec::with_capacity(decl.parameters.len());
    // Path params (template `{...}` segments) — always required.
    for name in &path_param_names {
        parameters.push(Parameter::new(
            (*name).to_string(),
            ParameterLocation::Path,
            true,
        ));
    }
    // Remaining declared params → query params.
    for p in &decl.parameters {
        if path_param_names.iter().any(|n| *n == p.name) {
            continue;
        }
        parameters.push(Parameter::new(
            p.name.clone(),
            ParameterLocation::Query,
            p.required,
        ));
    }

    let has_request_body = matches!(method_upper.as_str(), "POST" | "PUT" | "PATCH");

    Operation {
        method: method_upper,
        path: path.to_string(),
        parameters,
        has_request_body,
        base_url: decl.base_url.clone(),
    }
}

/// Crate-private handler for a single-call HTTP tool (Phase 90 OAPI-02a).
///
/// Holds the synthesized [`ToolInfo`], the built [`Operation`], and the shared
/// [`HttpConnector`]. [`ToolHandler::metadata`] returns `Some(self.info.clone())`
/// (the same RESEARCH §Risks #2 invariant the SQL handler upholds); `handle()`
/// calls [`HttpConnector::execute`] and returns the JSON response.
#[cfg(feature = "http")]
struct HttpToolHandler {
    info: ToolInfo,
    operation: Operation,
    connector: Arc<dyn HttpConnector>,
}

#[cfg(feature = "http")]
#[async_trait]
impl ToolHandler for HttpToolHandler {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> pmcp::Result<Value> {
        // T-90-03-01: arg injection is bounded by the object-envelope schema
        // (additionalProperties:false) enforced upstream; path substitution in the
        // connector touches only declared `{params}`.
        // The connector's Display is redaction-safe (T-90-01-01); no URL/credential
        // reaches the client error.
        self.connector
            .execute(&self.operation, &args)
            .await
            .map_err(|e| pmcp::Error::Internal(format!("connector error: {e}")))
    }

    fn metadata(&self) -> Option<ToolInfo> {
        Some(self.info.clone())
    }
}

// -----------------------------------------------------------------------------
// Script-tool handler (Phase 90 OAPI-02b / D-01 / D-02) — feature
// `openapi-code-mode`
// -----------------------------------------------------------------------------

/// Crate-private handler for a **script** `[[tools]]` entry (OAPI-02b / D-01).
///
/// A script tool runs admin-authored embedded JS through the EXACT SAME
/// `pmcp_code_mode` engine that Code Mode uses (D-02 — one engine, two
/// surfaces): [`pmcp_code_mode::PlanCompiler`] compiles the `script` to an
/// execution plan, then [`pmcp_code_mode::PlanExecutor`] over the shared
/// [`HttpCodeExecutor`] walks it. The client's validated `args` are bound to the
/// `args` variable BEFORE the script runs — identical to the `JsCodeExecutor`
/// path's `set_variable("args", …)`, which is what makes the engine-parity proof
/// (Plan 05 Task 2) hold byte-for-byte.
///
/// # No token cycle (Pitfall 7 / T-90-05-01)
///
/// A script tool is admin-authored + trusted (like a `sql=` curated query), so it
/// skips the Code Mode validation + HMAC-token gate entirely. It is bounded ONLY by
/// the [`ExecutionConfig`] caps (`max_api_calls`, `max_loop_iterations`,
/// `timeout_seconds`) the [`PlanExecutor`](pmcp_code_mode::PlanExecutor) enforces,
/// and by the `PlanCompiler`-accepted JS subset (no `eval` / FFI).
///
/// # Feature gate (RESEARCH Pitfall 4)
///
/// Gated `openapi-code-mode` (the umbrella that forwards
/// `pmcp-code-mode/js-runtime`) — `PlanCompiler` / `PlanExecutor` are NOT in
/// scope under bare `code-mode`, so the light / curated-only build (`http
/// code-mode`) compiles without this type (single-call only).
#[cfg(feature = "openapi-code-mode")]
struct ScriptToolHandler {
    /// The admin-authored script, compiled ONCE at synthesis (the body is fixed
    /// content). Executed per `handle` over a fresh
    /// [`PlanExecutor`](pmcp_code_mode::PlanExecutor).
    plan: pmcp_code_mode::ExecutionPlan,
    /// The SAME executor instance that feeds Code Mode (D-02). Cloned per request
    /// to construct a fresh [`PlanExecutor`](pmcp_code_mode::PlanExecutor).
    http_exec: HttpCodeExecutor,
    /// The execution bounds (Pitfall 7 — the only limit on an admin script).
    exec_config: ExecutionConfig,
    /// The synthesized `ToolInfo` (object-envelope schema from
    /// `[[tools.parameters]]`, `additionalProperties:false`) — `args` are
    /// schema-validated against this BEFORE the script runs (T-90-05-03).
    tool_info: ToolInfo,
}

#[cfg(feature = "openapi-code-mode")]
impl ScriptToolHandler {
    /// Build a [`ScriptToolHandler`] from a script `[[tools]]` declaration,
    /// the shared [`HttpCodeExecutor`], and the [`ExecutionConfig`] bounds.
    ///
    /// The `tool_info` is built from `[[tools.parameters]]` via the SAME
    /// [`build_input_schema`] / [`build_annotations`] / [`apply_widget_meta`]
    /// helpers the single-call path uses, so a script tool's `args` are
    /// schema-validated identically (object envelope, `additionalProperties:false`).
    ///
    /// # Errors
    ///
    /// Returns [`ToolkitError::Synth`] if the declaration carries no `script`
    /// (a defensive guard — callers route only `is_script_tool()` entries here),
    /// or if the script fails to compile (surfaced here at server build time,
    /// failing fast rather than on the first tool call).
    fn new(
        decl: &ToolDecl,
        http_exec: HttpCodeExecutor,
        exec_config: ExecutionConfig,
    ) -> Result<Self> {
        let script = decl.script.clone().ok_or_else(|| {
            ToolkitError::Synth(format!(
                "tool '{}' has no `script` body — not a script tool",
                decl.name
            ))
        })?;
        // Compile the admin-authored JS ONCE at synthesis time — the script is
        // fixed content, so compiling per request would re-run a full SWC parse
        // on the hot path (the PlanCompiler-accepted subset, no eval / FFI, is
        // the static bound). A compile error surfaces here at server build.
        let plan = pmcp_code_mode::PlanCompiler::with_config(&exec_config)
            .compile_code(&script)
            .map_err(|e| {
                ToolkitError::Synth(format!(
                    "tool '{}' script failed to compile: {e}",
                    decl.name
                ))
            })?;
        let tool_info = build_tool_info(decl);
        Ok(Self {
            plan,
            http_exec,
            exec_config,
            tool_info,
        })
    }
}

#[cfg(feature = "openapi-code-mode")]
#[pmcp_code_mode::async_trait]
impl ToolHandler for ScriptToolHandler {
    /// Run the pre-compiled admin-authored script over the shared engine, binding
    /// the validated `args` to the `args` variable (D-02 — identical to the
    /// `JsCodeExecutor` path's `set_variable("args", …)`).
    async fn handle(&self, args: Value, extra: RequestHandlerExtra) -> pmcp::Result<Value> {
        // (1) Execute the plan (compiled once in `new`) over a PER-REQUEST clone
        //     of the shared HttpCodeExecutor (D-02), threading the captured
        //     inbound MCP token (Plan 90-10 / OAPI-03 / OAPI-05) so an
        //     `oauth_passthrough` backend forwards it. Bounded by ExecutionConfig
        //     (Pitfall 7 — no token cycle, only these caps).
        let mut executor = pmcp_code_mode::PlanExecutor::new(
            crate::code_mode::request_executor_from_extra(&self.http_exec, &extra),
            self.exec_config.clone(),
        );
        // (2) Bind the schema-validated client args to `args` (T-90-05-03) —
        //     byte-identical to compile_and_execute's set_variable("args", …).
        executor.set_variable("args", args);

        let result = executor
            .execute(&self.plan)
            .await
            .map_err(|e| pmcp::Error::Internal(format!("script execution failed: {e}")))?;
        Ok(result.value)
    }

    fn metadata(&self) -> Option<ToolInfo> {
        Some(self.tool_info.clone())
    }
}

// -----------------------------------------------------------------------------
// Tests — Plan 05 Task 1 (RED) → GREEN in Task 2
// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{AnnotationsDecl, ParamDecl, ServerConfig, ServerSection, ToolDecl};
    use serde_json::Value;

    /// Construct a minimal `ServerConfig` that satisfies `validate()` (non-empty
    /// `name` + `version`) so the synthesizer path is the system under test —
    /// not the parser/validator from Plan 04.
    fn cfg_with_tools(tools: Vec<ToolDecl>) -> ServerConfig {
        ServerConfig {
            server: ServerSection {
                name: "demo".to_string(),
                version: "0.1.0".to_string(),
                ..Default::default()
            },
            tools,
            ..Default::default()
        }
    }

    #[test]
    fn empty_tools_returns_empty_vec() {
        let cfg = cfg_with_tools(vec![]);
        let out = synthesize_from_config(&cfg).expect("synthesize");
        assert_eq!(out.len(), 0);
    }

    #[test]
    fn one_tool_no_params_yields_object_schema() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "ping".to_string(),
            description: Some("Ping the server".to_string()),
            parameters: vec![],
            annotations: None,
            ..Default::default()
        }]);
        let out = synthesize_from_config(&cfg).expect("synthesize");
        assert_eq!(out.len(), 1);
        let (name, info, _handler) = &out[0];
        assert_eq!(name, "ping");
        assert_eq!(info.name, "ping");
        assert_eq!(info.description.as_deref(), Some("Ping the server"));
        let schema = &info.input_schema;
        assert_eq!(schema["type"], Value::String("object".to_string()));
        assert_eq!(schema["properties"], serde_json::json!({}));
        assert_eq!(schema["required"], serde_json::json!([]));
        assert_eq!(schema["additionalProperties"], Value::Bool(false));
    }

    #[test]
    fn required_and_optional_params_partitioned() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "search".to_string(),
            description: Some("Search".to_string()),
            parameters: vec![
                ParamDecl {
                    name: "query".to_string(),
                    param_type: Some("string".to_string()),
                    description: Some("the search query".to_string()),
                    required: true,
                    ..Default::default()
                },
                ParamDecl {
                    name: "max_results".to_string(),
                    param_type: Some("integer".to_string()),
                    description: Some("maximum result count".to_string()),
                    required: false,
                    default: Some(toml::Value::Integer(100)),
                    minimum: Some(1.0),
                    maximum: Some(1000.0),
                    ..Default::default()
                },
            ],
            ..Default::default()
        }]);
        let out = synthesize_from_config(&cfg).expect("synthesize");
        let (_, info, _) = &out[0];
        let schema = &info.input_schema;
        assert_eq!(schema["required"], serde_json::json!(["query"]));
        let props = schema["properties"].as_object().expect("object");
        assert_eq!(props["query"]["type"], "string");
        assert_eq!(props["max_results"]["type"], "integer");
        assert_eq!(props["max_results"]["minimum"], serde_json::json!(1.0));
        assert_eq!(props["max_results"]["maximum"], serde_json::json!(1000.0));
        assert_eq!(props["max_results"]["default"], serde_json::json!(100));
    }

    #[test]
    fn param_max_length_propagates() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "echo".to_string(),
            description: Some("Echo".to_string()),
            parameters: vec![ParamDecl {
                name: "text".to_string(),
                param_type: Some("string".to_string()),
                description: Some("input text".to_string()),
                required: true,
                max_length: Some(256),
                ..Default::default()
            }],
            ..Default::default()
        }]);
        let out = synthesize_from_config(&cfg).expect("synthesize");
        let (_, info, _) = &out[0];
        assert_eq!(
            info.input_schema["properties"]["text"]["maxLength"],
            serde_json::json!(256)
        );
    }

    #[test]
    fn annotations_round_trip_via_fluent_builder() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "destroy_all".to_string(),
            description: Some("Destroy all data (test)".to_string()),
            parameters: vec![],
            annotations: Some(AnnotationsDecl {
                read_only_hint: false,
                destructive_hint: true,
                idempotent_hint: false,
                open_world_hint: false,
                cost_hint: Some("high".to_string()),
            }),
            ..Default::default()
        }]);
        let out = synthesize_from_config(&cfg).expect("synthesize");
        let (_, info, _) = &out[0];
        let ann = info.annotations.as_ref().expect("annotations");
        assert_eq!(ann.read_only_hint, Some(false));
        assert_eq!(ann.destructive_hint, Some(true));
        assert_eq!(ann.idempotent_hint, Some(false));
        assert_eq!(ann.open_world_hint, Some(false));
    }

    /// REVIEWS H1 (in-plan widget_meta flip — no SqliteConnector dependency).
    ///
    /// When a `[[tools]]` entry declares `ui_resource_uri`, the synthesized
    /// `ToolInfo` must carry widget metadata so pmcp core's
    /// `with_widget_enrichment` (gated on `info.widget_meta().is_some()`)
    /// populates `structuredContent` (D-06). The flip lives in the shared
    /// `synthesize_inner` helper, so it fires for BOTH entry points; this test
    /// exercises it via the no-connector `synthesize_from_config` path.
    #[test]
    fn widget_meta_flips_when_ui_resource_uri_present() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "widget_tool".to_string(),
            description: Some("renders a widget".to_string()),
            ui_resource_uri: Some("ui://test".to_string()),
            ..Default::default()
        }]);
        let out = synthesize_from_config(&cfg).expect("synthesize");
        let (_, info, _) = &out[0];
        assert!(
            info.widget_meta().is_some(),
            "ui_resource_uri set ⇒ widget_meta() must be Some so D-06 structuredContent fires"
        );
    }

    /// REVIEWS H1 negative case — a tool WITHOUT `ui_resource_uri` must NOT
    /// carry widget metadata (T-84-03-03: no accidental flip on non-widget
    /// tools).
    #[test]
    fn widget_meta_absent_when_ui_resource_uri_none() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "plain_tool".to_string(),
            description: Some("no widget".to_string()),
            ui_resource_uri: None,
            ..Default::default()
        }]);
        let out = synthesize_from_config(&cfg).expect("synthesize");
        let (_, info, _) = &out[0];
        assert!(
            info.widget_meta().is_none(),
            "ui_resource_uri absent ⇒ widget_meta() must be None (no accidental flip)"
        );
    }

    #[tokio::test]
    async fn synthesized_handler_metadata_returns_some() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "ping".to_string(),
            description: Some("ping".to_string()),
            parameters: vec![],
            annotations: None,
            ..Default::default()
        }]);
        let out = synthesize_from_config(&cfg).expect("synthesize");
        let (_, expected_info, handler) = &out[0];
        let actual = handler.metadata();
        assert!(
            actual.is_some(),
            "RESEARCH §Risks #2 invariant: SynthesizedToolHandler::metadata() MUST return Some(ToolInfo)"
        );
        assert_eq!(actual.unwrap().name, expected_info.name);
    }

    /// A `[[tools]]` declaration with one defaulted `limit` param (default=20),
    /// used to exercise [`extract_named_params`]'s default / explicit-null logic.
    fn decl_with_limit_default() -> ToolDecl {
        ToolDecl {
            name: "search".to_string(),
            description: Some("Search".to_string()),
            sql: Some("SELECT * FROM t LIMIT :limit".to_string()),
            parameters: vec![ParamDecl {
                name: "limit".to_string(),
                param_type: Some("integer".to_string()),
                description: Some("row limit".to_string()),
                required: false,
                default: Some(toml::Value::Integer(20)),
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    #[test]
    fn extract_named_params_applies_default_when_absent() {
        // `{}` → declared default (20) is bound (the reference search/list calls
        // rely on this so an omitted :limit never binds NULL).
        let decl = decl_with_limit_default();
        let params = extract_named_params(&decl, &serde_json::json!({}));
        assert_eq!(params, vec![("limit".to_string(), serde_json::json!(20))]);
    }

    #[test]
    fn extract_named_params_explicit_null_applies_default() {
        // 85-10 WR-02 secondary fix: an EXPLICIT JSON null must NOT bind
        // `LIMIT NULL` — it falls through to the declared default exactly like
        // an omitted key.
        let decl = decl_with_limit_default();
        let params = extract_named_params(&decl, &serde_json::json!({ "limit": null }));
        assert_eq!(
            params,
            vec![("limit".to_string(), serde_json::json!(20))],
            "explicit null must apply the declared default, not bind LIMIT NULL"
        );
    }

    #[test]
    fn extract_named_params_explicit_value_overrides_default() {
        // A concrete value wins over the default.
        let decl = decl_with_limit_default();
        let params = extract_named_params(&decl, &serde_json::json!({ "limit": 5 }));
        assert_eq!(params, vec![("limit".to_string(), serde_json::json!(5))]);
    }
}

// -----------------------------------------------------------------------------
// Tests — Phase 90 OAPI-02a single-call HTTP synthesizer (feature `http`)
// -----------------------------------------------------------------------------

#[cfg(all(test, feature = "http"))]
mod synth_http_tests {
    use super::*;
    use crate::config::{ParamDecl, ServerConfig, ServerSection, ToolDecl};
    use crate::http::{HttpConnector, HttpConnectorError, Operation};
    use pmcp::RequestHandlerExtra;
    use serde_json::{json, Value};
    use std::sync::{Arc, Mutex};

    /// A mock [`HttpConnector`] that records the [`Operation`] it last received
    /// and returns a fixed JSON payload — so a synthesized handler can be
    /// invoked without any network.
    struct MockHttpConnector {
        last: Mutex<Option<Operation>>,
        payload: Value,
    }

    impl MockHttpConnector {
        fn new(payload: Value) -> Arc<Self> {
            Arc::new(Self {
                last: Mutex::new(None),
                payload,
            })
        }
    }

    #[async_trait]
    impl HttpConnector for MockHttpConnector {
        async fn execute(
            &self,
            operation: &Operation,
            _args: &Value,
        ) -> std::result::Result<Value, HttpConnectorError> {
            *self.last.lock().unwrap() = Some(operation.clone());
            Ok(self.payload.clone())
        }
        fn base_url(&self) -> &str {
            "https://mock.example.com"
        }
    }

    fn cfg_with_tools(tools: Vec<ToolDecl>) -> ServerConfig {
        ServerConfig {
            server: ServerSection {
                name: "demo".to_string(),
                version: "0.1.0".to_string(),
                ..Default::default()
            },
            tools,
            ..Default::default()
        }
    }

    /// (1) A single-call `[[tools]]` with a `{id}` path param synthesizes a
    /// `ToolInfo` whose input schema marks `id` required (object envelope), and
    /// the handler (wired to a mock connector) returns the mocked JSON.
    #[tokio::test]
    async fn synth_http_single_call_path_param_required_and_handler_returns_json() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "line_status".to_string(),
            description: Some("Line status".to_string()),
            path: Some("/Line/{id}/Status".to_string()),
            method: Some("GET".to_string()),
            parameters: vec![ParamDecl {
                name: "id".to_string(),
                param_type: Some("string".to_string()),
                required: true,
                ..Default::default()
            }],
            ..Default::default()
        }]);
        let connector = MockHttpConnector::new(json!({ "status": "Good Service" }));
        let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
            .expect("synthesize");
        assert_eq!(out.len(), 1);
        let (name, info, handler) = &out[0];
        assert_eq!(name, "line_status");
        let schema = &info.input_schema;
        assert_eq!(schema["type"], "object");
        assert_eq!(schema["required"], json!(["id"]));
        assert_eq!(schema["additionalProperties"], Value::Bool(false));

        let extra = RequestHandlerExtra::default();
        let result = handler
            .handle(json!({ "id": "victoria" }), extra)
            .await
            .expect("handle");
        assert_eq!(result, json!({ "status": "Good Service" }));

        // The operation carried the `{id}` path param as a Path parameter.
        let op = connector
            .last
            .lock()
            .unwrap()
            .clone()
            .expect("operation recorded");
        let path_params: Vec<&str> = op
            .path_parameters()
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert_eq!(path_params, vec!["id"]);
    }

    /// (2) A `POST` tool routes non-path args to the request body
    /// (`has_request_body` true) and the non-path param is NOT a path param.
    #[tokio::test]
    async fn synth_http_post_sets_request_body() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "create_item".to_string(),
            description: Some("Create".to_string()),
            path: Some("/items".to_string()),
            method: Some("post".to_string()),
            parameters: vec![ParamDecl {
                name: "title".to_string(),
                param_type: Some("string".to_string()),
                required: true,
                ..Default::default()
            }],
            ..Default::default()
        }]);
        let connector = MockHttpConnector::new(json!({ "ok": true }));
        let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
            .expect("synthesize");
        let (_, _, handler) = &out[0];
        let extra = RequestHandlerExtra::default();
        handler
            .handle(json!({ "title": "widget" }), extra)
            .await
            .expect("handle");
        let op = connector
            .last
            .lock()
            .unwrap()
            .clone()
            .expect("operation recorded");
        assert_eq!(op.method, "POST");
        assert!(op.has_request_body, "POST must carry a request body");
        assert!(op.path_parameters().is_empty());
    }

    /// (3) A tool with path + query params lands them in the right schema slots /
    /// `Operation` parameter locations.
    #[tokio::test]
    async fn synth_http_path_and_query_param_slots() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "search".to_string(),
            description: Some("Search".to_string()),
            path: Some("/repos/{owner}/issues".to_string()),
            method: Some("GET".to_string()),
            parameters: vec![
                ParamDecl {
                    name: "owner".to_string(),
                    param_type: Some("string".to_string()),
                    required: true,
                    ..Default::default()
                },
                ParamDecl {
                    name: "state".to_string(),
                    param_type: Some("string".to_string()),
                    required: false,
                    ..Default::default()
                },
            ],
            ..Default::default()
        }]);
        let connector = MockHttpConnector::new(json!([]));
        let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
            .expect("synthesize");
        let (_, _, handler) = &out[0];
        let extra = RequestHandlerExtra::default();
        handler
            .handle(json!({ "owner": "rust-lang", "state": "open" }), extra)
            .await
            .expect("handle");
        let op = connector
            .last
            .lock()
            .unwrap()
            .clone()
            .expect("operation recorded");
        let path_params: Vec<&str> = op
            .path_parameters()
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert_eq!(path_params, vec!["owner"]);
        let query_params: Vec<&str> = op
            .query_parameters()
            .iter()
            .map(|p| p.name.as_str())
            .collect();
        assert_eq!(query_params, vec!["state"]);
    }

    /// (4) A per-tool `base_url` is reflected in the synthesized `Operation`
    /// (Codex MEDIUM — not dropped).
    #[tokio::test]
    async fn synth_http_per_tool_base_url_reflected() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "other_host".to_string(),
            description: Some("Other host".to_string()),
            path: Some("/ping".to_string()),
            method: Some("GET".to_string()),
            base_url: Some("https://other.example.com/v2".to_string()),
            ..Default::default()
        }]);
        let connector = MockHttpConnector::new(json!({ "pong": true }));
        let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
            .expect("synthesize");
        let (_, _, handler) = &out[0];
        let extra = RequestHandlerExtra::default();
        handler.handle(json!({}), extra).await.expect("handle");
        let op = connector
            .last
            .lock()
            .unwrap()
            .clone()
            .expect("operation recorded");
        assert_eq!(
            op.base_url.as_deref(),
            Some("https://other.example.com/v2"),
            "per-tool base_url must be reflected on the Operation, not dropped"
        );
    }

    /// (5) NEGATIVE: a `[[tools]]` missing `method` (and without `script`) is
    /// rejected with a typed `ToolkitError` (T-90-03-04 — never silently
    /// registered).
    #[test]
    fn synth_http_missing_method_rejected() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "broken".to_string(),
            description: Some("missing method".to_string()),
            path: Some("/items".to_string()),
            method: None,
            ..Default::default()
        }]);
        let connector = MockHttpConnector::new(json!(null));
        let err = synthesize_from_config_with_http_connector(&cfg, connector)
            .err()
            .expect("ill-formed single-call tool must be rejected");
        assert!(matches!(err, ToolkitError::Synth(_)));
    }

    /// (5b) NEGATIVE: on the single-call-only entry point, a `script` tool is
    /// rejected with a typed `ToolkitError` pointing at the `openapi-code-mode`
    /// script path — NOT a silent skip, NOT a panic. (The OpenAPI Code Mode
    /// entry point `synthesize_from_config_with_http_connector_and_scripts`
    /// synthesizes a real `ScriptToolHandler` — proven in `script_tool` tests.)
    #[test]
    fn synth_http_script_tool_without_engine_is_rejected() {
        let cfg = cfg_with_tools(vec![ToolDecl {
            name: "scripted".to_string(),
            description: Some("script tool".to_string()),
            script: Some("await api.get('/x')".to_string()),
            ..Default::default()
        }]);
        let connector = MockHttpConnector::new(json!(null));
        let err = synthesize_from_config_with_http_connector(&cfg, connector)
            .err()
            .expect("script tool on the single-call-only entry point must be rejected");
        match err {
            ToolkitError::Synth(msg) => {
                assert!(
                    msg.contains("openapi-code-mode"),
                    "seam message must point at the openapi-code-mode script path: {msg}"
                );
            },
            other => panic!("expected Synth error, got {other:?}"),
        }
    }
}