pmcp_server_toolkit/tools.rs
1// Net-new code for Phase 83 TKIT-07.
2// Lands the `[[tools]]`-config-driven synthesizer that turns config rows into
3// `ToolInfo` + `Arc<dyn ToolHandler>` pairs.
4
5//! `[[tools]]` → `ToolInfo` + `Arc<dyn ToolHandler>` synthesizer.
6//!
7//! Net-new code for Phase 83 TKIT-07. Turns curated `[[tools]]` config entries
8//! into complete pmcp [`ToolInfo`] + [`Arc<dyn ToolHandler>`] pairs with zero
9//! per-tool Rust handlers.
10//!
11//! # Invariants enforced
12//!
13//! - **JSON Schema object envelope, CHECKED HERE.** Every synthesized
14//! [`ToolInfo`] carries an `input_schema` with `"type": "object"`, an explicit
15//! `properties` map, a `required` array, and `"additionalProperties": false`
16//! (`true` only when `[server.validation] additional_properties` opts out).
17//! Unknown argument keys are refused by
18//! `pmcp::server::schema_validation::validate_input`, called from the
19//! `ValidatingToolHandler` decorator that `enforce_input_schema` wraps
20//! around every handler this module pushes — **in the toolkit, before the
21//! backend call**. Threat T-83-05-02.
22//!
23//! Both halves matter, and stating only the first is what made this comment a
24//! defect for two phases. Core `pmcp`'s `tools/call` dispatch does **not**
25//! validate request arguments against a tool's declared `inputSchema`; that
26//! wiring is deliberately deferred (Phase 128 D-01), so a comment locating the
27//! enforcement "upstream" described a mitigation that did not exist. It exists
28//! now, and it exists *here*.
29//!
30//! Condition: the `input-validation` feature must be on. It is on via this
31//! crate's `default` feature set and by that route ALONE — measured: `http =
32//! ["dep:reqwest", "dep:url", "dep:openapiv3", "dep:serde_yaml", "dep:base64",
33//! "dep:regex", "dep:tokio", "pmcp/streamable-http"]` and `openapi-code-mode =
34//! ["http", "code-mode", "pmcp-code-mode/js-runtime"]`, neither of which names
35//! it. Those two umbrellas do NOT forward it, so a
36//! `--no-default-features --features http` build — exactly the shape a
37//! consumer reaches for — turns it off, and then
38//! `enforce_input_schema` is the identity function and says so in a
39//! `tracing::warn!`. Second condition: `[server.validation]
40//! enforce_input_schema` must not be `false`.
41//!
42//! Backed by `tests/input_validation_acceptance.rs`'s
43//! `input_validation_refuses_undeclared_argument_without_contacting_upstream`
44//! (row 10) and `input_validation_refuses_absent_arguments_when_required_declared`
45//! (row 9), each of which fails if the `validate_input` call is removed, plus
46//! `input_validation_accepts_compliant_call_with_one_upstream_request` (row 11)
47//! as the passing control that catches an over-refusing decorator.
48//! - **`handler.metadata()` returns `Some(ToolInfo)`.** Phase 82's `tool_arc`
49//! consumes `handler.metadata()` at registration; returning `None` would
50//! silently degrade the schema enforcement to "anything goes" (RESEARCH
51//! §Risks #2 — threat T-83-05-01).
52//! - **Constructors, never struct-literals.** Both [`ToolInfo`] and
53//! [`ToolAnnotations`] are `#[non_exhaustive]` (PATTERNS §Pattern C). The
54//! synthesizer uses [`ToolInfo::with_annotations`] / [`ToolInfo::new`] and
55//! the [`ToolAnnotations::new()`]-then-`.with_*` fluent builder.
56//! - **Cognitive complexity ≤25 per function.** Decomposed into
57//! [`build_input_schema`], [`build_param_property`], and [`build_annotations`]
58//! per Phase 75 D-03 + PATTERNS §Pattern G. No `#[allow]` annotations.
59
60use std::sync::Arc;
61
62use async_trait::async_trait;
63use pmcp::server::ToolHandler;
64use pmcp::types::{ToolAnnotations, ToolInfo};
65use pmcp::RequestHandlerExtra;
66use serde_json::{json, Map, Value};
67
68use crate::config::{AnnotationsDecl, ParamDecl, ServerConfig, ToolDecl, ValidationSection};
69use crate::error::Result;
70use crate::policy::ToolkitHooks;
71// Every use of the trait object itself lives inside a `#[cfg(feature =
72// "input-validation")]` item (`ValidatingToolHandler`'s field and `wrap`'s
73// parameter), so an ungated import is an `unused_imports` warning — and a hard
74// error — in the `--no-default-features --features http` build this module's own
75// header names as the shape a consumer reaches for.
76#[cfg(feature = "input-validation")]
77use crate::policy::ArgumentValidator;
78use crate::sql::SqlConnector;
79
80#[cfg(feature = "http")]
81use crate::error::ToolkitError;
82#[cfg(feature = "http")]
83use crate::http::{HttpConnector, Operation, Parameter, ParameterLocation};
84
85#[cfg(feature = "openapi-code-mode")]
86use crate::code_mode::HttpCodeExecutor;
87#[cfg(feature = "openapi-code-mode")]
88use pmcp_code_mode::ExecutionConfig;
89
90/// Type alias for one synthesized tool tuple: `(name, ToolInfo, Arc<dyn ToolHandler>)`.
91///
92/// Exists so [`synthesize_from_config`]'s return type does not trip
93/// `clippy::type_complexity` while preserving the exact `(name, ToolInfo, Arc)`
94/// shape consumers register with `pmcp::ServerBuilder::tool_arc` (PATTERNS §9).
95pub type SynthesizedTool = (String, ToolInfo, Arc<dyn ToolHandler>);
96
97/// Synthesize one `ToolInfo` + handler per `[[tools]]` config entry.
98///
99/// Each returned tuple is `(name, ToolInfo, Arc<dyn ToolHandler>)` and is
100/// ready to feed into `pmcp::ServerBuilder::tool_arc(name, handler)`. The
101/// `ToolInfo` carries the full input schema (synthesized from
102/// `[[tools.parameters]]`) and `ToolAnnotations` (from `[tools.annotations]`)
103/// so the builder's metadata cache will never fall back to the empty schema.
104///
105/// # Errors
106///
107/// Returns [`crate::ToolkitError::Synth`] if a tool declaration is internally
108/// inconsistent. The Plan 05 GREEN body never produces this error path —
109/// synthesis is total over the parsed [`ServerConfig`] surface — but the
110/// `Result` return is kept for forward compatibility with Plan 06 (code-mode
111/// wiring) and Phase 84 (SQL backend resolution).
112///
113/// # Example
114///
115/// ```
116/// use pmcp_server_toolkit::config::ServerConfig;
117/// use pmcp_server_toolkit::tools::synthesize_from_config;
118///
119/// let cfg = ServerConfig::default();
120/// let synthesized = synthesize_from_config(&cfg).unwrap();
121/// assert_eq!(synthesized.len(), 0);
122/// ```
123pub fn synthesize_from_config(config: &ServerConfig) -> Result<Vec<SynthesizedTool>> {
124 synthesize_inner(config, None, &ToolkitHooks::default())
125}
126
127/// [`synthesize_from_config`] with registered E2 hooks (Phase 128).
128///
129/// PUBLIC, not `pub(crate)`: `crates/pmcp-openapi-server` is a DIFFERENT crate and
130/// calls the free synthesizers directly rather than going through
131/// [`crate::ServerBuilderExt`], so a crate-private variant would leave the shipped
132/// OpenAPI binary unable to pass hooks at all — a registration surface that exists
133/// and cannot be reached from the deployment that most needs it.
134///
135/// # Errors
136///
137/// As [`synthesize_from_config`].
138pub fn synthesize_from_config_and_hooks(
139 config: &ServerConfig,
140 hooks: &ToolkitHooks,
141) -> Result<Vec<SynthesizedTool>> {
142 synthesize_inner(config, None, hooks)
143}
144
145/// Synthesize tools that execute against a wired [`SqlConnector`] (Phase 84
146/// CONN-01 / D-06). ADDITIVE variant alongside [`synthesize_from_config`] — the
147/// existing API is unchanged and all P83 callers compile without modification.
148///
149/// Each synthesized [`SynthesizedToolHandler`] holds the shared `connector`, so
150/// its `handle()` body calls [`SqlConnector::execute`] with the tool's declared
151/// `sql` + the named parameters extracted from the validated args. When a tool
152/// declares `ui_resource_uri`, the synthesized [`ToolInfo`] also carries widget
153/// metadata so pmcp core's `with_widget_enrichment` populates `structuredContent`
154/// (D-06) — that flip lives in the shared [`synthesize_inner`] helper and so
155/// fires for both entry points.
156///
157/// # Errors
158///
159/// Returns [`crate::ToolkitError::Synth`] if a tool declaration is internally
160/// inconsistent. Synthesis is total over the parsed [`ServerConfig`] surface —
161/// the connector is threaded into each handler for runtime use, not consulted at
162/// synthesis time.
163///
164/// # Example
165///
166/// ```no_run
167/// use std::sync::Arc;
168/// use pmcp_server_toolkit::config::ServerConfig;
169/// use pmcp_server_toolkit::sql::SqlConnector;
170/// use pmcp_server_toolkit::tools::synthesize_from_config_with_connector;
171///
172/// fn build(connector: Arc<dyn SqlConnector>) {
173/// let cfg = ServerConfig::default();
174/// let tools = synthesize_from_config_with_connector(&cfg, connector).unwrap();
175/// assert_eq!(tools.len(), 0);
176/// }
177/// ```
178pub fn synthesize_from_config_with_connector(
179 config: &ServerConfig,
180 connector: Arc<dyn SqlConnector>,
181) -> Result<Vec<SynthesizedTool>> {
182 synthesize_inner(config, Some(connector), &ToolkitHooks::default())
183}
184
185/// [`synthesize_from_config_with_connector`] with registered E2 hooks (Phase 128).
186///
187/// PUBLIC for the reason given on [`synthesize_from_config_and_hooks`].
188///
189/// # Errors
190///
191/// As [`synthesize_from_config_with_connector`].
192pub fn synthesize_from_config_with_connector_and_hooks(
193 config: &ServerConfig,
194 connector: Arc<dyn SqlConnector>,
195 hooks: &ToolkitHooks,
196) -> Result<Vec<SynthesizedTool>> {
197 synthesize_inner(config, Some(connector), hooks)
198}
199
200/// Shared synthesizer body for both [`synthesize_from_config`] (no connector)
201/// and [`synthesize_from_config_with_connector`] (connector wired).
202///
203/// Keeps the two public entry points one-liners so the widget_meta flip (D-06)
204/// and the handler construction logic are not duplicated. Decomposed per
205/// PATTERNS §Pattern G — the per-tool body delegates to [`build_input_schema`],
206/// [`build_annotations`], and [`apply_widget_meta`] to stay under cog 25.
207fn synthesize_inner(
208 config: &ServerConfig,
209 connector: Option<Arc<dyn SqlConnector>>,
210 hooks: &ToolkitHooks,
211) -> Result<Vec<SynthesizedTool>> {
212 let validation = &config.server.validation;
213 let mut out = Vec::with_capacity(config.tools.len());
214 for decl in &config.tools {
215 let info = build_tool_info(decl, validation);
216 let handler: Arc<dyn ToolHandler> = Arc::new(SynthesizedToolHandler {
217 info: info.clone(),
218 decl: decl.clone(),
219 connector: connector.clone(),
220 });
221 // Push site 1 of 3 (SQL handler) — D1 enforcement + E2 validator.
222 let handler = enforce_input_schema(handler, &info, decl, validation, hooks);
223 out.push((decl.name.clone(), info, handler));
224 }
225 Ok(out)
226}
227
228/// Enforce a synthesized tool's declared `inputSchema` before its inner handler
229/// runs (Phase 128, D1 / T-128-01).
230///
231/// # Enforcing function
232///
233/// `pmcp::server::schema_validation::validate_input`, called from BOTH
234/// [`ValidatingToolHandler::handle`] and [`ValidatingToolHandler::handle_output`].
235/// Backed by `tests/input_validation_acceptance.rs` acceptance rows 8–11, which
236/// fail if either call is removed.
237///
238/// Wrapping happens at every handler push site in this module, so all four public
239/// entry points inherit the enforcement with none forgotten.
240///
241/// With the `input-validation` feature OFF this is the identity function, and the
242/// opt-out is logged once per synthesized tool at synthesis time: a validation rule
243/// that is off must never read as on.
244///
245/// # `[server.validation] enforce_input_schema = false`
246///
247/// That flag is an operator opt-out from the SCHEMA CHECK, not from the decorator.
248/// `ValidatingToolHandler` carries an `enforce_schema: bool` and skips only the
249/// `validate_input` call, so a future explicitly-registered argument validator
250/// living in the same decorator keeps running. Turning off one enforcement must
251/// never silently turn off another — and losing an explicit custom validator
252/// because schema enforcement was disabled is the worst form of that class, since
253/// the operator turned off A and lost B without being told.
254///
255/// The decorator is constructed when schema enforcement is ON **or** a validator is
256/// registered for this tool. The registry is [`ToolkitHooks`], consulted below via
257/// [`ToolkitHooks::argument_validator_for`], so the decorator is skipped entirely
258/// only when `enforce_input_schema = false` AND no validator is registered for this
259/// tool name — which preserves the "no added allocation for a server that uses
260/// neither" property.
261///
262/// Until Phase 128 plan 09 this paragraph read "No validator registry exists yet
263/// (it lands with E2), so `has_registered_validator` is `false` today". That
264/// sentence outlived the registry by one plan and is kept named here rather than
265/// silently deleted: it is the documented-but-absent defect this phase exists to
266/// close, INVERTED — a comment in the very function that closes the gap still
267/// describing the machinery as absent. The binding it named no longer exists.
268///
269/// Backed by `tools::argument_validator_seam::a_registered_validator_still_runs_with_enforce_input_schema_false`,
270/// which fails if the `registered_validator.is_none()` conjunct is dropped from the
271/// early return, and by
272/// `tools::argument_validator_seam::a_registered_validator_refuses_a_combination_the_schema_permits`,
273/// which fails if the lookup is removed.
274#[cfg(feature = "input-validation")]
275fn enforce_input_schema(
276 handler: Arc<dyn ToolHandler>,
277 info: &ToolInfo,
278 decl: &ToolDecl,
279 validation: &ValidationSection,
280 hooks: &ToolkitHooks,
281) -> Arc<dyn ToolHandler> {
282 // Phase 128 E2 — the registry lookup that replaced plan 03's
283 // `let has_registered_validator = false;` placeholder.
284 let registered_validator = hooks.argument_validator_for(&decl.name);
285 if !validation.enforce_input_schema && registered_validator.is_none() {
286 tracing::warn!(
287 tool = %decl.name,
288 "[server.validation] enforce_input_schema = false: this tool's arguments are \
289 NOT checked against its declared inputSchema before the backend call"
290 );
291 return handler;
292 }
293 ValidatingToolHandler::wrap(
294 handler,
295 info,
296 decl,
297 validation.enforce_input_schema,
298 registered_validator,
299 )
300}
301
302/// The `input-validation`-off half of [`enforce_input_schema`]: the identity
303/// function, with the absence logged once per synthesized tool.
304///
305/// A `#[cfg]` SIBLING rather than one function with two inner blocks, because the
306/// off arm reads none of the schema inputs and the single-function form needed an
307/// `#[allow(unused_variables)]` — which this module's own header rules out ("No
308/// `#[allow]` annotations"). This is the same sibling-pair idiom
309/// `check_tool_input_schema_compiles`, `warn_if_pattern_checking_unavailable`,
310/// `spec_placeholder_rules` and `lint_declared_cap_above_placeholder_floor`
311/// already use in this crate for exactly this situation.
312#[cfg(not(feature = "input-validation"))]
313fn enforce_input_schema(
314 handler: Arc<dyn ToolHandler>,
315 _info: &ToolInfo,
316 decl: &ToolDecl,
317 _validation: &ValidationSection,
318 hooks: &ToolkitHooks,
319) -> Arc<dyn ToolHandler> {
320 tracing::warn!(
321 tool = %decl.name,
322 "the `input-validation` feature is OFF: this tool's arguments are NOT checked \
323 against its declared inputSchema before the backend call"
324 );
325 // `ToolkitHooks::argument_validator_for` is NOT feature-gated, so
326 // `with_argument_validator` compiles and appears to succeed in this build —
327 // while `ValidatingToolHandler`, the only thing that can RUN a registered
328 // validator, is gated away. Naming the drop is the difference between an
329 // enforcement that is off and one that silently reads as on; the schema warning
330 // above does not cover it, because a registered validator is a SEPARATE switch
331 // (see `ValidatingToolHandler::enforce_schema`).
332 if hooks.argument_validator_for(&decl.name).is_some() {
333 tracing::warn!(
334 tool = %decl.name,
335 "an E2 ArgumentValidator IS registered for this tool and is DISCARDED: \
336 running it requires the `input-validation` feature"
337 );
338 }
339 handler
340}
341
342/// Decorator that refuses a `tools/call` whose arguments violate the tool's
343/// declared `inputSchema`, WITHOUT invoking the inner handler.
344///
345/// Crate-private by design: the validator and the value-free refusal renderer both
346/// live in core `pmcp` (D-01), so this type holds no schema logic of its own.
347#[cfg(feature = "input-validation")]
348struct ValidatingToolHandler {
349 inner: Arc<dyn ToolHandler>,
350 /// The synthesized `ToolInfo`'s `input_schema`, verbatim.
351 input_schema: Value,
352 /// `input_schema.to_string()`, computed ONCE at synthesis so the hot
353 /// `tools/call` path never re-serializes the whole schema to hit the core
354 /// validator cache.
355 schema_key: String,
356 /// Declared parameter names in declaration order — the ONLY names a refusal
357 /// message may echo (SC-7).
358 declared: Vec<String>,
359 /// Whether the SCHEMA CHECK runs, from `[server.validation]
360 /// enforce_input_schema`.
361 ///
362 /// A SEPARATE switch from the decorator's existence on purpose: when the E2
363 /// argument-validator registry lands in the same decorator, an operator who
364 /// turns schema enforcement off must not silently lose an
365 /// explicitly-registered validator too.
366 enforce_schema: bool,
367 /// The E2 [`ArgumentValidator`] registered for this tool, if any (Phase 128).
368 ///
369 /// Looked up by tool NAME once at synthesis, so the `tools/call` path does no
370 /// map lookup. `None` is the overwhelmingly common case and costs one
371 /// `Option` discriminant test per call.
372 validator: Option<Arc<dyn ArgumentValidator>>,
373}
374
375#[cfg(feature = "input-validation")]
376impl ValidatingToolHandler {
377 /// Wrap `handler`, taking the schema from the already-built `info` and the
378 /// declared parameter names from `decl`.
379 fn wrap(
380 inner: Arc<dyn ToolHandler>,
381 info: &ToolInfo,
382 decl: &ToolDecl,
383 enforce_schema: bool,
384 validator: Option<Arc<dyn ArgumentValidator>>,
385 ) -> Arc<dyn ToolHandler> {
386 let input_schema = info.input_schema.clone();
387 let schema_key = input_schema.to_string();
388 Arc::new(Self {
389 inner,
390 input_schema,
391 schema_key,
392 declared: decl.parameters.iter().map(|p| p.name.clone()).collect(),
393 enforce_schema,
394 validator,
395 })
396 }
397
398 /// Validate `args`, mapping any violation to a value-free
399 /// `pmcp::Error::ToolRejected`. Kept a separate helper so both trait entry
400 /// points stay one-liners and well under the cog-25 gate.
401 ///
402 /// # Why a tool-level rejection and not `Error::Validation`
403 ///
404 /// A refused argument is the CALLER's to fix, and `Error::ToolRejected` is the
405 /// SDK's variant for exactly that: its own docs name "schema-mismatched input"
406 /// as an intended use, and `execute_code` already returns it for a bad approval
407 /// token. `Error::Validation` surfaces as a JSON-RPC error, which reads to a
408 /// model as a server fault and gives it nothing to retry with. Measured on the
409 /// 2.21.0 stack: 14 of 15 refusals in a 24-probe matrix reached the client as
410 /// protocol errors, and the Triarii UMLS server wrote an adapter to remap them.
411 /// The message is unchanged and stays value-free; only the channel moves.
412 ///
413 /// Returns `Ok(())` without consulting the schema when `enforce_schema` is
414 /// `false` — skipping the CHECK, not the decorator, so anything else this
415 /// decorator does still happens.
416 fn check(&self, args: &Value) -> pmcp::Result<()> {
417 self.check_schema(args)?;
418 self.check_registered_validator(args)
419 }
420
421 /// The D1 declared-schema check.
422 ///
423 /// Returns `Ok(())` without consulting the schema when `enforce_schema` is
424 /// `false` — skipping the CHECK, not the decorator, so the E2 validator below
425 /// still runs.
426 fn check_schema(&self, args: &Value) -> pmcp::Result<()> {
427 use pmcp::server::schema_validation::{render_refusal, validate_input};
428
429 if !self.enforce_schema {
430 return Ok(());
431 }
432 validate_input(&self.input_schema, Some(args), Some(&self.schema_key)).map_err(
433 |violations| {
434 let declared: Vec<&str> = self.declared.iter().map(String::as_str).collect();
435 pmcp::Error::tool_rejected(render_refusal(&violations, &declared), None)
436 },
437 )
438 }
439
440 /// The E2 registered-validator check (Phase 128).
441 ///
442 /// Called by [`Self::check`] STRICTLY AFTER [`Self::check_schema`] returns
443 /// `Ok`, which is the E2 ordering contract: a custom rule never sees arguments
444 /// the declared schema already refused (T-128-41). Inverting the two calls is
445 /// what `a_registered_validator_is_not_invoked_when_the_schema_refuses` fails
446 /// on.
447 ///
448 /// The refusal message is the VALIDATOR's own, authored outside this crate, so
449 /// unlike `render_refusal` above the toolkit cannot guarantee it is value-free.
450 /// That residual is documented on [`crate::policy::ArgumentRefusal`].
451 fn check_registered_validator(&self, args: &Value) -> pmcp::Result<()> {
452 let Some(validator) = self.validator.as_ref() else {
453 return Ok(());
454 };
455 validator
456 .validate(args)
457 .map_err(|refusal| pmcp::Error::tool_rejected(refusal.message().to_string(), None))
458 }
459}
460
461#[cfg(feature = "input-validation")]
462#[async_trait]
463impl ToolHandler for ValidatingToolHandler {
464 async fn handle(&self, args: Value, extra: RequestHandlerExtra) -> pmcp::Result<Value> {
465 self.check(&args)?;
466 self.inner.handle(args, extra).await
467 }
468
469 fn metadata(&self) -> Option<ToolInfo> {
470 self.inner.metadata()
471 }
472
473 /// Validates, then DELEGATES to the inner handler's own `handle_output`.
474 ///
475 /// Implementing only `handle` would silently replace an inner handler's
476 /// `handle_output` override with the trait default
477 /// (`handle(..).map(ToolOutput::Payload)`), stripping that handler's ability to
478 /// own its `CallToolResult` envelope. A decorator must not narrow the contract
479 /// of what it wraps — and both entry points must validate, or an inner handler
480 /// that overrides `handle_output` becomes an unvalidated path.
481 async fn handle_output(
482 &self,
483 args: Value,
484 extra: RequestHandlerExtra,
485 ) -> pmcp::Result<pmcp::server::ToolOutput> {
486 self.check(&args)?;
487 self.inner.handle_output(args, extra).await
488 }
489}
490
491/// Flip widget metadata onto `info` when the declaration carries a
492/// `ui_resource_uri` (D-06 / REVIEWS M1).
493///
494/// Uses the feature-independent [`ToolInfo::with_meta_entry`] surface to insert
495/// `_meta.ui.resourceUri`. This is the verified-correct API: `with_widget_meta`
496/// is gated on pmcp's `mcp-apps` feature (which the toolkit does not enable),
497/// whereas `with_meta_entry` is always available and produces the `ui.resourceUri`
498/// shape that `ToolInfo::widget_meta()` recognises — so pmcp core's
499/// `with_widget_enrichment` populates `structuredContent`. Annotations on `info`
500/// are preserved (chained, not reconstructed).
501fn apply_widget_meta(info: ToolInfo, decl: &ToolDecl) -> ToolInfo {
502 match decl.ui_resource_uri.as_deref() {
503 Some(uri) => info.with_meta_entry("ui", json!({ "resourceUri": uri })),
504 None => info,
505 }
506}
507
508/// Build the [`ToolInfo`] for a synthesized tool from its declaration.
509///
510/// The schema + annotations + widget-meta sequence is identical for every tool
511/// kind (single-call HTTP, SQL, and script), so it lives here once — keeping the
512/// `#[non_exhaustive]` [`ToolInfo`] constructor discipline (the `with_annotations`
513/// vs `new` arms) in a single place rather than copy-pasted per synthesizer.
514fn build_tool_info(decl: &ToolDecl, validation: &ValidationSection) -> ToolInfo {
515 let schema = build_input_schema(decl, validation);
516 let annotations = build_annotations(decl.annotations.as_ref());
517 let base = match annotations {
518 Some(ann) => {
519 ToolInfo::with_annotations(decl.name.clone(), decl.description.clone(), schema, ann)
520 },
521 None => ToolInfo::new(decl.name.clone(), decl.description.clone(), schema),
522 };
523 apply_widget_meta(base, decl)
524}
525
526/// Build the JSON Schema `properties` + `required` envelope from a
527/// `[[tools.parameters]]` list.
528///
529/// Decomposed from [`synthesize_from_config`] to keep cognitive complexity ≤25
530/// (Phase 75 D-03 + PATTERNS §Pattern G).
531///
532/// `pub(crate)` since Phase 128 SC-2: [`crate::config::ServerConfig::validate`]
533/// builds each tool's schema through THIS function and compiles it at config time,
534/// so the schema the compile gate checks is byte-identical to the one the runtime
535/// validator enforces. A second construction path there would let the gate pass a
536/// schema the server never serves.
537///
538/// Takes the whole [`ToolDecl`] rather than just its parameters because the D3
539/// default cap is POSITION-scoped, and position is a property of the tool's `path`
540/// and `method` — see [`crate::config::ToolDecl::param_position`].
541///
542/// `properties` and `required` are emitted in `[[tools.parameters]]` declaration
543/// order, so two synthesis runs over one config produce byte-identical output.
544pub(crate) fn build_input_schema(decl: &ToolDecl, validation: &ValidationSection) -> Value {
545 let mut props = Map::new();
546 let mut required = Vec::new();
547 for p in &decl.parameters {
548 let mut prop = build_param_property(p);
549 apply_position_cap(&mut prop, p, decl.param_position(&p.name), validation);
550 props.insert(p.name.clone(), prop);
551 if p.required {
552 required.push(Value::String(p.name.clone()));
553 }
554 }
555 json!({
556 "type": "object",
557 "properties": props,
558 "required": required,
559 "additionalProperties": validation.additional_properties,
560 })
561}
562
563/// Apply the D3 position-scoped default length cap to ONE already-built property
564/// object (Phase 128).
565///
566/// Emits `maxLength = validation.default_max_length` only when ALL of:
567/// the parameter's effective type is `string`; it declares no `max_length` of its
568/// own; `default_max_length` is non-zero; and `position` is `Path` or `Query`.
569/// BODY position emits nothing — capping a `POST` payload's free-text field is
570/// exactly the breakage D-05 exists to avoid, and `ServerConfig::lint` surfaces
571/// those instead.
572///
573/// A DECLARED `max_length` is never overridden and never merged with the default in
574/// either direction: the author's number wins outright, and the always-on
575/// `PLACEHOLDER_MAX_LENGTH` floor is what bounds a URL segment regardless.
576///
577/// The four conditions live in `crate::config::default_cap_applies` rather than
578/// here, so `lint()` and this function cannot disagree about which parameters are
579/// covered — a disagreement would make `lint()` report a parameter as uncapped
580/// while the schema caps it, or the reverse.
581///
582/// Its own free function (not inlined into [`build_input_schema`]) to keep that
583/// function's cognitive complexity well under the 25 gate.
584fn apply_position_cap(
585 prop: &mut Value,
586 p: &ParamDecl,
587 position: crate::config::ParamPosition,
588 validation: &ValidationSection,
589) {
590 if crate::config::default_cap_applies(p, position, validation) {
591 prop["maxLength"] = json!(validation.default_max_length);
592 }
593}
594
595/// Build a single JSON Schema property object from a [`ParamDecl`].
596///
597/// Per-parameter constraints (`minimum`, `maximum`, `maxLength`, `minLength`,
598/// `pattern`, `format`, `maxItems`, `items`, `default`, `enum`) are folded in only
599/// when present — an undeclared keyword is ABSENT from the emitted schema, never
600/// present-and-empty, because an empty `pattern` matches everything and an empty
601/// `items` object constrains nothing while both read like rules.
602///
603/// The param's `param_type` defaults to `"string"` when omitted in TOML to match
604/// JSON Schema's permissive default.
605fn build_param_property(p: &ParamDecl) -> Value {
606 let ty = p.param_type.as_deref().unwrap_or("string");
607 let mut prop = json!({ "type": ty });
608 if let Some(desc) = &p.description {
609 prop["description"] = Value::String(desc.clone());
610 }
611 if let Some(min) = p.minimum {
612 prop["minimum"] = json!(min);
613 }
614 if let Some(max) = p.maximum {
615 prop["maximum"] = json!(max);
616 }
617 if let Some(max_len) = p.max_length {
618 prop["maxLength"] = json!(max_len);
619 }
620 if let Some(min_len) = p.min_length {
621 prop["minLength"] = json!(min_len);
622 }
623 if let Some(pattern) = &p.pattern {
624 prop["pattern"] = Value::String(pattern.clone());
625 }
626 if let Some(format) = &p.format {
627 prop["format"] = Value::String(format.clone());
628 }
629 if let Some(max_items) = p.max_items {
630 prop["maxItems"] = json!(max_items);
631 }
632 if let Some(items) = &p.items {
633 prop["items"] = build_items_property(items);
634 }
635 if let Some(default) = &p.default {
636 // toml::Value serializes losslessly into serde_json::Value via serde.
637 if let Ok(v) = serde_json::to_value(default) {
638 prop["default"] = v;
639 }
640 }
641 if let Some(enum_vals) = &p.enum_values {
642 if let Ok(v) = serde_json::to_value(enum_vals) {
643 prop["enum"] = v;
644 }
645 }
646 prop
647}
648
649/// Build the OBJECT-form JSON Schema `items` value from an [`ItemsDecl`]
650/// (Phase 128, D2).
651///
652/// A separate free function for two reasons. First, cognitive complexity:
653/// [`build_param_property`] gained five arms in this phase and RESEARCH assumption
654/// A4 (that they stay under cog 25) was explicitly unmeasured, so the construction
655/// lives outside it. Second, and more importantly, there is exactly ONE place that
656/// can decide the SHAPE of `items`, and it returns a [`Value::Object`]
657/// unconditionally. The array form of `items` is a draft-07 tuple construct that
658/// does NOT compile under the Draft 2020-12 pin, and a schema that does not compile
659/// takes the whole tool's validator down — so "never an array here" is a safety
660/// property, not a style preference, and it is enforced by this function having no
661/// code path that builds a JSON array.
662fn build_items_property(items: &crate::config::ItemsDecl) -> Value {
663 let ty = items.item_type.as_deref().unwrap_or("string");
664 let mut prop = json!({ "type": ty });
665 if let Some(max_len) = items.max_length {
666 prop["maxLength"] = json!(max_len);
667 }
668 if let Some(pattern) = &items.pattern {
669 prop["pattern"] = Value::String(pattern.clone());
670 }
671 prop
672}
673
674/// Build [`ToolAnnotations`] from an optional `[tools.annotations]` block.
675///
676/// Per PATTERNS §Pattern C, the constructor + fluent builder is used (never a
677/// struct literal — [`ToolAnnotations`] is `#[non_exhaustive]`). The `cost_hint`
678/// field has no `ToolAnnotations` accessor and is therefore not propagated at
679/// this layer; it lives on the toolkit's [`AnnotationsDecl`] and is consumed
680/// by future plans that surface cost into rate-limiting policy.
681fn build_annotations(decl: Option<&AnnotationsDecl>) -> Option<ToolAnnotations> {
682 let d = decl?;
683 let a = ToolAnnotations::new()
684 .with_read_only(d.read_only_hint)
685 .with_destructive(d.destructive_hint)
686 .with_idempotent(d.idempotent_hint)
687 .with_open_world(d.open_world_hint);
688 Some(a)
689}
690
691// -----------------------------------------------------------------------------
692// SynthesizedToolHandler — crate-private
693// -----------------------------------------------------------------------------
694
695/// Crate-private handler wrapping a synthesized [`ToolInfo`].
696///
697/// [`ToolHandler::metadata`] MUST return `Some(self.info.clone())` — Phase 82's
698/// `tool_arc` consumes `handler.metadata()` at registration time; returning
699/// `None` would cause the builder to fall back to an empty schema (RESEARCH
700/// §Risks #2 — threat T-83-05-01). The unit + property tests in
701/// [`crate::tools`] and `tests/tool_synthesis_props.rs` lock this in.
702///
703/// `handle()` reads the declared `sql`, extracts named parameters from the
704/// validated args, and calls [`SqlConnector::execute`] when a `connector` is
705/// wired (handlers built via [`synthesize_from_config_with_connector`]).
706/// Handlers built via the no-connector [`synthesize_from_config`] carry
707/// `connector = None` and return an explicit `Err` on invocation — preserving
708/// P83 behaviour where the no-connector path was test-only (T-84-03-05). The
709/// `decl` is held so the handler can read `sql` / `ui_resource_uri` /
710/// `parameters` without re-walking the config.
711struct SynthesizedToolHandler {
712 info: ToolInfo,
713 decl: ToolDecl,
714 /// `Some` only for handlers built via [`synthesize_from_config_with_connector`].
715 connector: Option<Arc<dyn SqlConnector>>,
716}
717
718/// Extract the named `(name, value)` parameter pairs the connector binds from,
719/// filtering the caller's `args` against the declared parameter list
720/// (T-84-03-01: only declared parameter names reach `execute()`; an extra key is
721/// dropped HERE, and separately refused one layer out).
722///
723/// The refusal is not "upstream". It is
724/// `pmcp::server::schema_validation::validate_input` inside the
725/// `ValidatingToolHandler` decorator that [`enforce_input_schema`] wraps around
726/// this handler at its push site, so an undeclared key normally never reaches this
727/// function at all. Conditional on the `input-validation` feature AND on
728/// `[server.validation]` leaving both `enforce_input_schema` (`true`) and
729/// `additional_properties` (`false`) at their defaults — with `additional_properties
730/// = true` an undeclared key is ADMITTED by the schema and this filter is the only
731/// thing that keeps it out of `execute()`. That is why the drop stays here rather
732/// than being replaced by an assertion: the two layers close the case under
733/// different configurations. Backed by
734/// `tests/input_validation_acceptance.rs::input_validation_refuses_undeclared_argument_without_contacting_upstream`
735/// for the schema layer; the filter layer is covered by this module's
736/// `extract_params` unit tests.
737///
738/// Found by this phase's SC-6 candidate-phrase sweep, not by the plan's named
739/// list: the phrasing "rejects them upstream" is the same defect class as
740/// the retired `HttpToolHandler::handle` claim one function-group away, which
741/// located the same envelope check "upstream" in the same way.
742///
743/// The retired phrasings are deliberately NOT quoted verbatim anywhere in `src/`.
744/// This phase's SC-6 gates grep for each retired phrase and require a count of
745/// zero, and a gate that a historical citation can satisfy is a gate that has
746/// stopped distinguishing a surviving claim from a note about one — the first
747/// draft of THIS comment quoted one of them and turned the gate red on itself,
748/// which is the cheapest possible demonstration that the gate is sensitive. The
749/// full before/after text lives in `128-10-SUMMARY.md`.
750///
751/// When the caller omits an optional parameter that declares a `default`, the
752/// default is applied so the bound SQL sees a concrete value. Without this an
753/// omitted `:limit` / `:offset` would bind as unbound `NULL` and SQLite rejects
754/// `LIMIT NULL` with a "datatype mismatch" — so the declared default is the
755/// difference between a working and a broken tool call (the reference
756/// `search_tracks` / `list_artists` calls rely on it).
757///
758/// An EXPLICIT JSON `null` for a declared-default parameter is treated the SAME
759/// as an omitted parameter — the declared default is applied (85-10 WR-02
760/// secondary fix). Without the `is_null` filter a caller sending
761/// `{"limit": null}` would bind `LIMIT NULL` and SQLite would reject the query
762/// with "datatype mismatch", even though the tool declares `default = 20`.
763fn extract_named_params(decl: &ToolDecl, args: &Value) -> Vec<(String, Value)> {
764 decl.parameters
765 .iter()
766 .filter_map(|p| {
767 args.get(&p.name)
768 // Explicit JSON `null` falls through to the declared default,
769 // exactly like an omitted key (no `LIMIT NULL` bind).
770 .filter(|v| !v.is_null())
771 .cloned()
772 .or_else(|| {
773 p.default
774 .as_ref()
775 .and_then(|d| serde_json::to_value(d).ok())
776 })
777 .map(|v| (p.name.clone(), v))
778 })
779 .collect()
780}
781
782#[async_trait]
783impl ToolHandler for SynthesizedToolHandler {
784 async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> pmcp::Result<Value> {
785 let sql = self.decl.sql.as_deref().ok_or_else(|| {
786 pmcp::Error::Internal(format!("tool '{}' has no `sql` declared", self.info.name))
787 })?;
788 let connector = self.connector.as_ref().ok_or_else(|| {
789 pmcp::Error::Internal(format!(
790 "tool '{}' requires connector wiring — build via synthesize_from_config_with_connector",
791 self.info.name
792 ))
793 })?;
794 let named_params = extract_named_params(&self.decl, &args);
795 // T-84-03-02: format!("{e}") uses ConnectorError::Display, which Plan 01
796 // Task 2 guarantees does not echo credentials.
797 let rows = connector
798 .execute(sql, &named_params)
799 .await
800 .map_err(|e| pmcp::Error::Internal(format!("connector error: {e}")))?;
801 Ok(Value::Array(rows))
802 }
803
804 fn metadata(&self) -> Option<ToolInfo> {
805 Some(self.info.clone())
806 }
807}
808
809// -----------------------------------------------------------------------------
810// Single-call HTTP synthesizer (Phase 90 OAPI-02a) — feature `http`
811// -----------------------------------------------------------------------------
812
813/// Synthesize one `ToolInfo` + handler per single-call `[[tools]]` entry,
814/// executing against a wired [`HttpConnector`] (Phase 90 OAPI-02a / D-01).
815///
816/// Mirrors [`synthesize_from_config_with_connector`] (the SQL analog) in shape.
817/// For each `[[tools]]` where [`ToolDecl::is_script_tool`] is `false` and a
818/// `path` + `method` pair is present, an [`Operation`] is built from the path
819/// template (the `{...}` segments become path parameters), the declared
820/// `[[tools.parameters]]` (non-path params become query params; `POST`/`PUT`/
821/// `PATCH` carry a request body), and the per-tool `base_url` override — which is
822/// reflected onto the [`Operation`] so the connector targets the per-tool host
823/// (never silently dropped, Codex MEDIUM). The synthesized [`ToolInfo`] uses the
824/// EXISTING [`build_input_schema`] (object envelope + `additionalProperties:false`)
825/// and [`build_annotations`] helpers; the handler calls
826/// [`HttpConnector::execute`] and returns the JSON.
827///
828/// # Script-tool seam (Plan 05)
829///
830/// A `script` tool encountered here returns a typed [`ToolkitError::Synth`] — it
831/// is an EXPLICIT, clearly-marked seam, NOT a silent skip and NOT a `todo!()`.
832/// Plan 05 widens this function's signature (adding the shared `http_exec` +
833/// `exec_config`) and fills the `is_script_tool()` arm with a `ScriptToolHandler`
834/// branch; that change is a localized, anticipated edit because the seam is
835/// surfaced here.
836///
837/// # Errors
838///
839/// Returns [`ToolkitError::Synth`] when a `[[tools]]` entry is a `script` tool
840/// (Plan 05 seam) or is neither a valid single-call (missing `path` OR `method`)
841/// nor a script tool (T-90-03-04 negative validation — an ill-formed tool is
842/// rejected, never silently registered).
843#[cfg(feature = "http")]
844pub fn synthesize_from_config_with_http_connector(
845 config: &ServerConfig,
846 connector: Arc<dyn HttpConnector>,
847) -> Result<Vec<SynthesizedTool>> {
848 // No script-tool builder is supplied on this (single-call-only) entry point,
849 // so the `is_script_tool()` arm of [`synthesize_http_inner`] returns the
850 // typed Plan 05 seam error. The OpenAPI Code Mode build calls
851 // [`synthesize_from_config_with_http_connector_and_scripts`], which supplies
852 // a [`ScriptToolHandler`] builder so a `script` tool synthesizes a real
853 // handler over the shared engine (OAPI-02b / D-01 / D-02).
854 synthesize_from_config_with_http_connector_and_hooks(
855 config,
856 connector,
857 &ToolkitHooks::default(),
858 )
859}
860
861/// [`synthesize_from_config_with_http_connector`] with registered E2 hooks
862/// (Phase 128).
863///
864/// PUBLIC for the reason given on [`synthesize_from_config_and_hooks`].
865///
866/// # Errors
867///
868/// As [`synthesize_from_config_with_http_connector`].
869#[cfg(feature = "http")]
870pub fn synthesize_from_config_with_http_connector_and_hooks(
871 config: &ServerConfig,
872 connector: Arc<dyn HttpConnector>,
873 hooks: &ToolkitHooks,
874) -> Result<Vec<SynthesizedTool>> {
875 // No script-tool builder is supplied on this (single-call-only) entry point,
876 // so the `is_script_tool()` arm of [`synthesize_http_inner`] returns the
877 // typed Plan 05 seam error. The OpenAPI Code Mode build calls
878 // [`synthesize_from_config_with_http_connector_and_scripts`], which supplies
879 // a [`ScriptToolHandler`] builder so a `script` tool synthesizes a real
880 // handler over the shared engine (OAPI-02b / D-01 / D-02).
881 synthesize_http_inner(
882 config,
883 connector,
884 |decl| {
885 Err(ToolkitError::Synth(format!(
886 "tool '{}' is a script tool — script tools require the `openapi-code-mode` \
887 feature (use synthesize_from_config_with_http_connector_and_scripts)",
888 decl.name
889 )))
890 },
891 hooks,
892 )
893}
894
895/// Synthesize single-call AND script `[[tools]]` against a wired
896/// [`HttpConnector`] plus a shared [`HttpCodeExecutor`] + [`ExecutionConfig`]
897/// (Phase 90 OAPI-02b / D-01 / D-02).
898///
899/// This is the OpenAPI Code Mode entry point (gated `openapi-code-mode`): it
900/// adds the `http_exec` + `exec_config` the script-tool path needs, threading
901/// the SAME `HttpCodeExecutor` instance that feeds Code Mode (D-02 — one engine,
902/// two surfaces). Single-call tools synthesize exactly as in
903/// [`synthesize_from_config_with_http_connector`]; a `script` tool synthesizes a
904/// [`ScriptToolHandler`] that compiles + runs the embedded JS through the SAME
905/// `PlanCompiler` + `PlanExecutor` + `HttpCodeExecutor` seam Code Mode uses,
906/// with NO validate/token cycle (admin-authored, `ExecutionConfig`-bounded —
907/// Pitfall 7).
908///
909/// The binary (Plan 06) supplies `http_exec` (built once over the resolved
910/// backend `base_url` + auth provider) and `exec_config` (from the
911/// `[code_mode.limits]` / defaults: `max_api_calls=50`, `max_loop_iterations=100`,
912/// `timeout_seconds=30`).
913///
914/// # Errors
915///
916/// Returns [`ToolkitError::Synth`] when a `[[tools]]` entry is neither a valid
917/// single-call (missing `path` OR `method`) nor a script tool (T-90-03-04
918/// negative validation), or when a script tool fails to build its `ToolInfo`.
919#[cfg(feature = "openapi-code-mode")]
920pub fn synthesize_from_config_with_http_connector_and_scripts(
921 config: &ServerConfig,
922 connector: Arc<dyn HttpConnector>,
923 http_exec: HttpCodeExecutor,
924 exec_config: ExecutionConfig,
925) -> Result<Vec<SynthesizedTool>> {
926 synthesize_from_config_with_http_connector_and_scripts_and_hooks(
927 config,
928 connector,
929 http_exec,
930 exec_config,
931 &ToolkitHooks::default(),
932 )
933}
934
935/// [`synthesize_from_config_with_http_connector_and_scripts`] with registered E2
936/// hooks (Phase 128).
937///
938/// This is THE variant `crates/pmcp-openapi-server`'s `build_server` calls, which
939/// is why it is PUBLIC rather than `pub(crate)`: that crate reaches the
940/// synthesizer directly and never through [`crate::ServerBuilderExt`], so a
941/// crate-private variant would ship E2 as present-but-inert on this phase's
942/// principal HTTP surface (T-128-39b).
943///
944/// # Errors
945///
946/// As [`synthesize_from_config_with_http_connector_and_scripts`].
947#[cfg(feature = "openapi-code-mode")]
948pub fn synthesize_from_config_with_http_connector_and_scripts_and_hooks(
949 config: &ServerConfig,
950 connector: Arc<dyn HttpConnector>,
951 http_exec: HttpCodeExecutor,
952 exec_config: ExecutionConfig,
953 hooks: &ToolkitHooks,
954) -> Result<Vec<SynthesizedTool>> {
955 let validation = &config.server.validation;
956 // Script tools re-check the class policy on every resolved request, when
957 // the config sets an operation-class key.
958 let http_exec = match config.code_mode.as_ref() {
959 Some(section) if !section.class_keys_set().is_empty() => {
960 http_exec.with_class_policy(section)
961 },
962 _ => http_exec,
963 };
964 synthesize_http_inner(
965 config,
966 connector,
967 |decl| {
968 let handler =
969 ScriptToolHandler::new(decl, http_exec.clone(), exec_config.clone(), validation)?;
970 let info = handler.tool_info.clone();
971 let arc: Arc<dyn ToolHandler> = Arc::new(handler);
972 Ok((info, arc))
973 },
974 hooks,
975 )
976}
977
978/// Refuse a curated tool the `[code_mode]` class policy refuses: a script
979/// tool by its calls, a single-call tool by its `(method, path)`. A tool that
980/// is neither is left to the synthesizer's own validation. No gate (no class
981/// key set) refuses nothing.
982#[cfg(feature = "openapi-code-mode")]
983fn check_curated_tool(
984 gate: Option<&crate::code_mode::ClassGate>,
985 decl: &ToolDecl,
986) -> std::result::Result<(), crate::error::ConfigValidationError> {
987 let Some(gate) = gate else {
988 return Ok(());
989 };
990 if let Some(script) = decl.script.as_deref() {
991 return gate.check_script(&decl.name, script);
992 }
993 match (decl.method.as_deref(), decl.path.as_deref()) {
994 (Some(method), Some(path)) => gate.check_single_call(&decl.name, method, path),
995 _ => Ok(()),
996 }
997}
998
999/// Shared synthesizer body for the single-call HTTP entry points.
1000///
1001/// `build_script_tool` is invoked for each `script` tool: the single-call-only
1002/// entry point passes a closure that returns the typed Plan 05 / `openapi-code-mode`
1003/// seam error, while the OpenAPI Code Mode entry point passes a closure that
1004/// constructs a [`ScriptToolHandler`]. Decomposed per PATTERNS §Pattern G to keep
1005/// the per-tool loop body under cog ≤25.
1006#[cfg(feature = "http")]
1007fn synthesize_http_inner(
1008 config: &ServerConfig,
1009 connector: Arc<dyn HttpConnector>,
1010 mut build_script_tool: impl FnMut(&ToolDecl) -> Result<(ToolInfo, Arc<dyn ToolHandler>)>,
1011 hooks: &ToolkitHooks,
1012) -> Result<Vec<SynthesizedTool>> {
1013 let validation = &config.server.validation;
1014 // A curated tool the `[code_mode]` class policy refuses could never
1015 // succeed, so it fails the boot. Applies only when the config sets an
1016 // operation-class key (see `ClassGate::for_curated_tools`).
1017 #[cfg(feature = "openapi-code-mode")]
1018 let class_gate = crate::code_mode::ClassGate::for_curated_tools(config);
1019 let mut out = Vec::with_capacity(config.tools.len());
1020 for decl in &config.tools {
1021 #[cfg(feature = "openapi-code-mode")]
1022 check_curated_tool(class_gate.as_ref(), decl)?;
1023 if decl.is_script_tool() {
1024 let (info, handler) = build_script_tool(decl)?;
1025 // Push site 2 of 3 (SCRIPT tool) — D1 enforcement. This site is
1026 // SEPARATE from the HTTP push below because of the `continue`; wrapping
1027 // only the HTTP push would leave every script tool unvalidated.
1028 let handler = enforce_input_schema(handler, &info, decl, validation, hooks);
1029 out.push((decl.name.clone(), info, handler));
1030 continue;
1031 }
1032
1033 // Single-call requires BOTH path and method. A `[[tools]]` that is
1034 // neither a valid single-call nor a script tool is rejected (T-90-03-04).
1035 let (path, method) = match (decl.path.as_deref(), decl.method.as_deref()) {
1036 (Some(p), Some(m)) => (p, m),
1037 _ => {
1038 return Err(ToolkitError::Synth(format!(
1039 "tool '{}' is not a valid single-call tool: both `path` and `method` are required",
1040 decl.name
1041 )));
1042 },
1043 };
1044
1045 let operation = build_operation(path, method, decl);
1046 let info = build_tool_info(decl, validation);
1047 let handler: Arc<dyn ToolHandler> = Arc::new(HttpToolHandler {
1048 info: info.clone(),
1049 operation,
1050 connector: connector.clone(),
1051 });
1052 // Push site 3 of 3 (single-call HTTP handler) — D1 enforcement + E2 validator.
1053 let handler = enforce_input_schema(handler, &info, decl, validation, hooks);
1054 out.push((decl.name.clone(), info, handler));
1055 }
1056 Ok(out)
1057}
1058
1059/// Build the [`Operation`] for a single-call tool from its `path` template,
1060/// `method`, declared parameters, and per-tool `base_url`.
1061///
1062/// Path parameters are the `{...}` segments of the path template. Every other
1063/// declared `[[tools.parameters]]` becomes a QUERY parameter, or — when the method
1064/// carries a request body (`POST`/`PUT`/`PATCH`) — a
1065/// [`ParameterLocation::Body`] parameter that
1066/// [`crate::http::HttpClient`]'s `build_body` folds into the JSON payload. The
1067/// per-tool `base_url` is reflected onto the [`Operation`] (Codex MEDIUM — never
1068/// dropped).
1069///
1070/// # Agreement with `ToolDecl::param_position` — structural, not documentary
1071///
1072/// Both splits this function performs read a shared helper, so neither can drift
1073/// from [`crate::config::ToolDecl::param_position`]:
1074///
1075/// - the PATH split and `param_position`'s `Path` arm both read
1076/// [`crate::config::path_placeholder_names`];
1077/// - the QUERY/BODY split and `param_position`'s `Query`/`Body` arms both read
1078/// `crate::config::method_carries_request_body`, which is also the sole source of
1079/// [`Operation::has_request_body`].
1080///
1081/// That second agreement is Phase 128 CR-02/CR-03. Before it, this function marked
1082/// every non-path declared parameter `ParameterLocation::Query` regardless of
1083/// method while `param_position` classified a mutating tool's as `Body`, and the
1084/// divergence was documented here as deliberate. It was not survivable: a `POST`
1085/// tool's declared parameters travelled in the URL — so the D3 cap was withheld
1086/// from values that genuinely land in a request line — and `build_body`, which
1087/// collects only args ABSENT from `operation.parameters`, found nothing, so no
1088/// payload reached the backend at all once `additionalProperties: false` began to
1089/// be enforced.
1090///
1091/// D-05 is still honoured, and now by the routing rather than despite it: a
1092/// `Body`-located parameter really is a payload field, and
1093/// `crate::config::default_cap_applies` emits no default `maxLength` for it.
1094#[cfg(feature = "http")]
1095fn build_operation(path: &str, method: &str, decl: &ToolDecl) -> Operation {
1096 let method_upper = method.to_uppercase();
1097 let path_param_names: Vec<&str> = crate::config::path_placeholder_names(path).collect();
1098
1099 let mut parameters = Vec::with_capacity(decl.parameters.len());
1100 // Path params (template `{...}` segments) — always required.
1101 //
1102 // Phase 128 D4(b): this loop iterates the TEMPLATE, not `decl.parameters`, so
1103 // the declared narrowing is looked up BY NAME and falls back to "no declared
1104 // rules" when the template names a segment the config never declared. Such a
1105 // parameter still gets the unconditional character floor and the always-on cap
1106 // at substitution time — it simply gets no narrowing on top (D-10).
1107 for name in &path_param_names {
1108 let declared = decl.parameters.iter().find(|p| p.name == **name);
1109 parameters.push(
1110 Parameter::new((*name).to_string(), ParameterLocation::Path, true).with_rules(
1111 declared.and_then(|p| p.pattern.clone()),
1112 declared.and_then(|p| p.max_length),
1113 // D-11: the config is the ONE legitimate source of this permission.
1114 declared.is_some_and(|p| p.allow_slash),
1115 ),
1116 );
1117 }
1118 // Remaining declared params → the QUERY STRING, or the JSON BODY when the
1119 // method carries one (Phase 128 CR-02).
1120 //
1121 // `has_request_body` and this location are derived from the SAME
1122 // `method_carries_request_body` predicate `ToolDecl::param_position` reads, so
1123 // a `Body`-located parameter on a body-less request is not constructible and
1124 // the D3 cap's scope cannot drift from the request's actual routing.
1125 let has_request_body = crate::config::method_carries_request_body(&method_upper);
1126 let non_path_location = if has_request_body {
1127 ParameterLocation::Body
1128 } else {
1129 ParameterLocation::Query
1130 };
1131 for p in &decl.parameters {
1132 if path_param_names.iter().any(|n| *n == p.name) {
1133 continue;
1134 }
1135 parameters.push(
1136 Parameter::new(p.name.clone(), non_path_location, p.required).with_rules(
1137 p.pattern.clone(),
1138 p.max_length,
1139 p.allow_slash,
1140 ),
1141 );
1142 }
1143
1144 Operation {
1145 method: method_upper,
1146 path: path.to_string(),
1147 parameters,
1148 has_request_body,
1149 base_url: decl.base_url.clone(),
1150 }
1151}
1152
1153/// Crate-private handler for a single-call HTTP tool (Phase 90 OAPI-02a).
1154///
1155/// Holds the synthesized [`ToolInfo`], the built [`Operation`], and the shared
1156/// [`HttpConnector`]. [`ToolHandler::metadata`] returns `Some(self.info.clone())`
1157/// (the same RESEARCH §Risks #2 invariant the SQL handler upholds); `handle()`
1158/// calls [`HttpConnector::execute`] and returns the JSON response.
1159#[cfg(feature = "http")]
1160struct HttpToolHandler {
1161 info: ToolInfo,
1162 operation: Operation,
1163 connector: Arc<dyn HttpConnector>,
1164}
1165
1166#[cfg(feature = "http")]
1167#[async_trait]
1168impl ToolHandler for HttpToolHandler {
1169 async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> pmcp::Result<Value> {
1170 // T-90-03-01: arg injection is bounded by TWO checks, both of which run
1171 // before this handler's connector call and both of which live in this
1172 // repository rather than "upstream":
1173 //
1174 // (1) the object-envelope schema (additionalProperties:false) is checked by
1175 // `pmcp::server::schema_validation::validate_input`, called from the
1176 // `ValidatingToolHandler` decorator that `enforce_input_schema` wraps
1177 // around this handler at its push site — so a call carrying an
1178 // undeclared key never reaches `handle` at all. Conditional on the
1179 // `input-validation` feature and on `[server.validation]
1180 // enforce_input_schema` not being `false`. Backed by
1181 // `tests/input_validation_acceptance.rs::input_validation_refuses_undeclared_argument_without_contacting_upstream`,
1182 // which fails if the decorator or its `validate_input` call is removed.
1183 //
1184 // (2) path substitution touches only declared `{params}`, and EVERY
1185 // substituted value additionally faces
1186 // `pmcp::server::schema_validation::validate_path_placeholder` inside
1187 // `HttpClient::substitute_path`, with the composed result facing
1188 // `validate_resolved_path` through `check_composed_path` before
1189 // dispatch. Backed by
1190 // `tests/curated_path_injection.rs::curated_path_injection_refuses_traversal_via_a_placeholder_value`
1191 // and `..._refuses_a_query_via_a_placeholder_value`, with
1192 // `..._accepts_a_compliant_call_with_one_upstream_request` as the
1193 // passing control.
1194 //
1195 // Until Phase 128 this comment located the envelope check somewhere
1196 // "upstream" of here (the retired phrasing is quoted in full in
1197 // `128-10-SUMMARY.md` and deliberately nowhere in `src/`, so the SC-6 grep
1198 // gate keeps distinguishing a surviving claim from a note about one).
1199 // Core `pmcp`'s `tools/call` dispatch does not validate request arguments
1200 // against a declared `inputSchema` — that wiring is deliberately deferred
1201 // (D-01) — so the claim named a mitigation that did not exist. Restated
1202 // rather than deleted, because as of this phase it is true and local.
1203 // The connector's Display is redaction-safe (T-90-01-01); no URL/credential
1204 // reaches the client error.
1205 //
1206 // Phase 128 E1: `execute_for_tool`, not `execute`, so a registered
1207 // `RequestPolicy` is told WHICH tool the call came from. An `Operation`
1208 // describes an endpoint and cannot carry a tool name; the default trait
1209 // body delegates to `execute`, so an out-of-repo connector is unaffected.
1210 self.connector
1211 .execute_for_tool(&self.info.name, &self.operation, &args)
1212 .await
1213 .map_err(|e| pmcp::Error::Internal(format!("connector error: {e}")))
1214 }
1215
1216 fn metadata(&self) -> Option<ToolInfo> {
1217 Some(self.info.clone())
1218 }
1219}
1220
1221// -----------------------------------------------------------------------------
1222// Script-tool handler (Phase 90 OAPI-02b / D-01 / D-02) — feature
1223// `openapi-code-mode`
1224// -----------------------------------------------------------------------------
1225
1226/// Crate-private handler for a **script** `[[tools]]` entry (OAPI-02b / D-01).
1227///
1228/// A script tool runs admin-authored embedded JS through the EXACT SAME
1229/// `pmcp_code_mode` engine that Code Mode uses (D-02 — one engine, two
1230/// surfaces): [`pmcp_code_mode::PlanCompiler`] compiles the `script` to an
1231/// execution plan, then [`pmcp_code_mode::PlanExecutor`] over the shared
1232/// [`HttpCodeExecutor`] walks it. The client's validated `args` are bound to the
1233/// `args` variable BEFORE the script runs — identical to the `JsCodeExecutor`
1234/// path's `set_variable("args", …)`, which is what makes the engine-parity proof
1235/// (Plan 05 Task 2) hold byte-for-byte.
1236///
1237/// # No token cycle (Pitfall 7 / T-90-05-01)
1238///
1239/// A script tool is admin-authored + trusted (like a `sql=` curated query), so it
1240/// skips the Code Mode validation + HMAC-token gate entirely. It is bounded ONLY by
1241/// the [`ExecutionConfig`] caps (`max_api_calls`, `max_loop_iterations`,
1242/// `timeout_seconds`) the [`PlanExecutor`](pmcp_code_mode::PlanExecutor) enforces,
1243/// and by the `PlanCompiler`-accepted JS subset (no `eval` / FFI).
1244///
1245/// # Feature gate (RESEARCH Pitfall 4)
1246///
1247/// Gated `openapi-code-mode` (the umbrella that forwards
1248/// `pmcp-code-mode/js-runtime`) — `PlanCompiler` / `PlanExecutor` are NOT in
1249/// scope under bare `code-mode`, so the light / curated-only build (`http
1250/// code-mode`) compiles without this type (single-call only).
1251#[cfg(feature = "openapi-code-mode")]
1252struct ScriptToolHandler {
1253 /// The admin-authored script, compiled ONCE at synthesis (the body is fixed
1254 /// content). Executed per `handle` over a fresh
1255 /// [`PlanExecutor`](pmcp_code_mode::PlanExecutor).
1256 plan: pmcp_code_mode::ExecutionPlan,
1257 /// The SAME executor instance that feeds Code Mode (D-02). Cloned per request
1258 /// to construct a fresh [`PlanExecutor`](pmcp_code_mode::PlanExecutor).
1259 http_exec: HttpCodeExecutor,
1260 /// The execution bounds (Pitfall 7 — the only limit on an admin script).
1261 exec_config: ExecutionConfig,
1262 /// The synthesized `ToolInfo` (object-envelope schema from
1263 /// `[[tools.parameters]]`, `additionalProperties:false`).
1264 ///
1265 /// `args` are checked against THIS schema before the script runs (T-90-05-03),
1266 /// by `pmcp::server::schema_validation::validate_input` inside the
1267 /// `ValidatingToolHandler` decorator that [`enforce_input_schema`] wraps
1268 /// around this handler at its push site — so a refusal happens before
1269 /// [`ToolHandler::handle`] is entered and therefore before
1270 /// `PlanExecutor::execute` makes any backend call.
1271 ///
1272 /// Conditional on the `input-validation` feature and on `[server.validation]
1273 /// enforce_input_schema` not being `false`; with either off,
1274 /// [`enforce_input_schema`] logs the opt-out and returns the handler undecorated.
1275 ///
1276 /// Backed by
1277 /// `tests/script_tool.rs::script_tool_refuses_a_schema_violating_arg_before_the_script_runs`,
1278 /// which asserts the refusal AND that the mock backend observed zero requests —
1279 /// it fails if the decorator or its `validate_input` call is removed. The
1280 /// sibling `script_tool_args_max_lines_binding_is_honored` asserts argument
1281 /// BINDING, which is a different (also true) property; before this phase it was
1282 /// the only row carrying this threat ID, and a binding assertion is not a
1283 /// validation assertion.
1284 tool_info: ToolInfo,
1285}
1286
1287#[cfg(feature = "openapi-code-mode")]
1288impl ScriptToolHandler {
1289 /// Build a [`ScriptToolHandler`] from a script `[[tools]]` declaration,
1290 /// the shared [`HttpCodeExecutor`], and the [`ExecutionConfig`] bounds.
1291 ///
1292 /// The `tool_info` is built from `[[tools.parameters]]` via the SAME
1293 /// [`build_input_schema`] / [`build_annotations`] / [`apply_widget_meta`]
1294 /// helpers the single-call path uses, so a script tool's `args` are checked
1295 /// against an identically-shaped schema (object envelope,
1296 /// `additionalProperties:false` unless `[server.validation]
1297 /// additional_properties` opts out) by the same enforcer — one
1298 /// [`enforce_input_schema`] call per push site, one
1299 /// `pmcp::server::schema_validation::validate_input` inside
1300 /// `ValidatingToolHandler`. There is no second validator for script tools;
1301 /// see [`ScriptToolHandler::tool_info`] for the condition and the acceptance
1302 /// row.
1303 ///
1304 /// `validation` is threaded in so a script tool's schema is built under the SAME
1305 /// `[server.validation]` policy as every other tool kind — a script tool whose
1306 /// parameters escaped the D3 cap would be a hole in exactly the surface this
1307 /// phase closes. A script tool's parameters are BODY position (it declares no
1308 /// `path`/`method`), so in practice the cap does not apply to them; the point is
1309 /// that the decision is made by one rule rather than by which synthesizer ran.
1310 ///
1311 /// # Errors
1312 ///
1313 /// Returns [`ToolkitError::Synth`] if the declaration carries no `script`
1314 /// (a defensive guard — callers route only `is_script_tool()` entries here),
1315 /// or if the script fails to compile (surfaced here at server build time,
1316 /// failing fast rather than on the first tool call).
1317 fn new(
1318 decl: &ToolDecl,
1319 http_exec: HttpCodeExecutor,
1320 exec_config: ExecutionConfig,
1321 validation: &ValidationSection,
1322 ) -> Result<Self> {
1323 let script = decl.script.clone().ok_or_else(|| {
1324 ToolkitError::Synth(format!(
1325 "tool '{}' has no `script` body — not a script tool",
1326 decl.name
1327 ))
1328 })?;
1329 // Compile the admin-authored JS ONCE at synthesis time — the script is
1330 // fixed content, so compiling per request would re-run a full SWC parse
1331 // on the hot path (the PlanCompiler-accepted subset, no eval / FFI, is
1332 // the static bound). A compile error surfaces here at server build.
1333 let plan = pmcp_code_mode::PlanCompiler::with_config(&exec_config)
1334 .compile_code(&script)
1335 .map_err(|e| {
1336 ToolkitError::Synth(format!(
1337 "tool '{}' script failed to compile: {e}",
1338 decl.name
1339 ))
1340 })?;
1341 let tool_info = build_tool_info(decl, validation);
1342 Ok(Self {
1343 plan,
1344 // Phase 128 E1: this handler owns a per-tool CLONE of the shared
1345 // executor, which is the one place a script tool's name can be
1346 // attached — `HttpExecutor::execute_request` is a `pmcp-code-mode`
1347 // trait method and carries no tool name.
1348 http_exec: http_exec.with_tool_label(&decl.name),
1349 exec_config,
1350 tool_info,
1351 })
1352 }
1353}
1354
1355#[cfg(feature = "openapi-code-mode")]
1356#[pmcp_code_mode::async_trait]
1357impl ToolHandler for ScriptToolHandler {
1358 /// Run the pre-compiled admin-authored script over the shared engine, binding
1359 /// the validated `args` to the `args` variable (D-02 — identical to the
1360 /// `JsCodeExecutor` path's `set_variable("args", …)`).
1361 async fn handle(&self, args: Value, extra: RequestHandlerExtra) -> pmcp::Result<Value> {
1362 // (1) Execute the plan (compiled once in `new`) over a PER-REQUEST clone
1363 // of the shared HttpCodeExecutor (D-02), threading the captured
1364 // inbound MCP token (Plan 90-10 / OAPI-03 / OAPI-05) so an
1365 // `oauth_passthrough` backend forwards it. Bounded by ExecutionConfig
1366 // (Pitfall 7 — no token cycle, only these caps).
1367 let mut executor = pmcp_code_mode::PlanExecutor::new(
1368 crate::code_mode::request_executor_from_extra(&self.http_exec, &extra),
1369 self.exec_config.clone(),
1370 );
1371 // (2) Bind the client args to `args` (T-90-05-03) — byte-identical to
1372 // compile_and_execute's set_variable("args", …). These args have
1373 // ALREADY been checked against `self.tool_info.input_schema` by
1374 // `pmcp::server::schema_validation::validate_input`, in the
1375 // `ValidatingToolHandler` decorator wrapped around this handler — a
1376 // violating call never reaches this line. That is a fact about the
1377 // DECORATOR, not about this function: `handle` performs no validation
1378 // of its own and must not be read as if it did. Condition and
1379 // acceptance row: see `ScriptToolHandler::tool_info`.
1380 executor.set_variable("args", args);
1381
1382 let result = executor
1383 .execute(&self.plan)
1384 .await
1385 .map_err(|e| pmcp::Error::Internal(format!("script execution failed: {e}")))?;
1386 Ok(result.value)
1387 }
1388
1389 fn metadata(&self) -> Option<ToolInfo> {
1390 Some(self.tool_info.clone())
1391 }
1392}
1393
1394// -----------------------------------------------------------------------------
1395// Tests — Plan 05 Task 1 (RED) → GREEN in Task 2
1396// -----------------------------------------------------------------------------
1397
1398#[cfg(test)]
1399mod tests {
1400 use super::*;
1401 use crate::config::{
1402 AnnotationsDecl, ItemsDecl, ParamDecl, ServerConfig, ServerSection, ToolDecl,
1403 ValidationSection,
1404 };
1405 use serde_json::Value;
1406
1407 /// Construct a minimal `ServerConfig` that satisfies `validate()` (non-empty
1408 /// `name` + `version`) so the synthesizer path is the system under test —
1409 /// not the parser/validator from Plan 04.
1410 fn cfg_with_tools(tools: Vec<ToolDecl>) -> ServerConfig {
1411 ServerConfig {
1412 server: ServerSection {
1413 name: "demo".to_string(),
1414 version: "0.1.0".to_string(),
1415 ..Default::default()
1416 },
1417 tools,
1418 ..Default::default()
1419 }
1420 }
1421
1422 #[test]
1423 fn empty_tools_returns_empty_vec() {
1424 let cfg = cfg_with_tools(vec![]);
1425 let out = synthesize_from_config(&cfg).expect("synthesize");
1426 assert_eq!(out.len(), 0);
1427 }
1428
1429 #[test]
1430 fn one_tool_no_params_yields_object_schema() {
1431 let cfg = cfg_with_tools(vec![ToolDecl {
1432 name: "ping".to_string(),
1433 description: Some("Ping the server".to_string()),
1434 parameters: vec![],
1435 annotations: None,
1436 ..Default::default()
1437 }]);
1438 let out = synthesize_from_config(&cfg).expect("synthesize");
1439 assert_eq!(out.len(), 1);
1440 let (name, info, _handler) = &out[0];
1441 assert_eq!(name, "ping");
1442 assert_eq!(info.name, "ping");
1443 assert_eq!(info.description.as_deref(), Some("Ping the server"));
1444 let schema = &info.input_schema;
1445 assert_eq!(schema["type"], Value::String("object".to_string()));
1446 assert_eq!(schema["properties"], serde_json::json!({}));
1447 assert_eq!(schema["required"], serde_json::json!([]));
1448 assert_eq!(schema["additionalProperties"], Value::Bool(false));
1449 }
1450
1451 #[test]
1452 fn required_and_optional_params_partitioned() {
1453 let cfg = cfg_with_tools(vec![ToolDecl {
1454 name: "search".to_string(),
1455 description: Some("Search".to_string()),
1456 parameters: vec![
1457 ParamDecl {
1458 name: "query".to_string(),
1459 param_type: Some("string".to_string()),
1460 description: Some("the search query".to_string()),
1461 required: true,
1462 ..Default::default()
1463 },
1464 ParamDecl {
1465 name: "max_results".to_string(),
1466 param_type: Some("integer".to_string()),
1467 description: Some("maximum result count".to_string()),
1468 required: false,
1469 default: Some(toml::Value::Integer(100)),
1470 minimum: Some(1.0),
1471 maximum: Some(1000.0),
1472 ..Default::default()
1473 },
1474 ],
1475 ..Default::default()
1476 }]);
1477 let out = synthesize_from_config(&cfg).expect("synthesize");
1478 let (_, info, _) = &out[0];
1479 let schema = &info.input_schema;
1480 assert_eq!(schema["required"], serde_json::json!(["query"]));
1481 let props = schema["properties"].as_object().expect("object");
1482 assert_eq!(props["query"]["type"], "string");
1483 assert_eq!(props["max_results"]["type"], "integer");
1484 assert_eq!(props["max_results"]["minimum"], serde_json::json!(1.0));
1485 assert_eq!(props["max_results"]["maximum"], serde_json::json!(1000.0));
1486 assert_eq!(props["max_results"]["default"], serde_json::json!(100));
1487 }
1488
1489 #[test]
1490 fn param_max_length_propagates() {
1491 let cfg = cfg_with_tools(vec![ToolDecl {
1492 name: "echo".to_string(),
1493 description: Some("Echo".to_string()),
1494 parameters: vec![ParamDecl {
1495 name: "text".to_string(),
1496 param_type: Some("string".to_string()),
1497 description: Some("input text".to_string()),
1498 required: true,
1499 max_length: Some(256),
1500 ..Default::default()
1501 }],
1502 ..Default::default()
1503 }]);
1504 let out = synthesize_from_config(&cfg).expect("synthesize");
1505 let (_, info, _) = &out[0];
1506 assert_eq!(
1507 info.input_schema["properties"]["text"]["maxLength"],
1508 serde_json::json!(256)
1509 );
1510 }
1511
1512 #[test]
1513 fn annotations_round_trip_via_fluent_builder() {
1514 let cfg = cfg_with_tools(vec![ToolDecl {
1515 name: "destroy_all".to_string(),
1516 description: Some("Destroy all data (test)".to_string()),
1517 parameters: vec![],
1518 annotations: Some(AnnotationsDecl {
1519 read_only_hint: false,
1520 destructive_hint: true,
1521 idempotent_hint: false,
1522 open_world_hint: false,
1523 cost_hint: Some("high".to_string()),
1524 }),
1525 ..Default::default()
1526 }]);
1527 let out = synthesize_from_config(&cfg).expect("synthesize");
1528 let (_, info, _) = &out[0];
1529 let ann = info.annotations.as_ref().expect("annotations");
1530 assert_eq!(ann.read_only_hint, Some(false));
1531 assert_eq!(ann.destructive_hint, Some(true));
1532 assert_eq!(ann.idempotent_hint, Some(false));
1533 assert_eq!(ann.open_world_hint, Some(false));
1534 }
1535
1536 /// REVIEWS H1 (in-plan widget_meta flip — no SqliteConnector dependency).
1537 ///
1538 /// When a `[[tools]]` entry declares `ui_resource_uri`, the synthesized
1539 /// `ToolInfo` must carry widget metadata so pmcp core's
1540 /// `with_widget_enrichment` (gated on `info.widget_meta().is_some()`)
1541 /// populates `structuredContent` (D-06). The flip lives in the shared
1542 /// `synthesize_inner` helper, so it fires for BOTH entry points; this test
1543 /// exercises it via the no-connector `synthesize_from_config` path.
1544 #[test]
1545 fn widget_meta_flips_when_ui_resource_uri_present() {
1546 let cfg = cfg_with_tools(vec![ToolDecl {
1547 name: "widget_tool".to_string(),
1548 description: Some("renders a widget".to_string()),
1549 ui_resource_uri: Some("ui://test".to_string()),
1550 ..Default::default()
1551 }]);
1552 let out = synthesize_from_config(&cfg).expect("synthesize");
1553 let (_, info, _) = &out[0];
1554 assert!(
1555 info.widget_meta().is_some(),
1556 "ui_resource_uri set ⇒ widget_meta() must be Some so D-06 structuredContent fires"
1557 );
1558 }
1559
1560 /// REVIEWS H1 negative case — a tool WITHOUT `ui_resource_uri` must NOT
1561 /// carry widget metadata (T-84-03-03: no accidental flip on non-widget
1562 /// tools).
1563 #[test]
1564 fn widget_meta_absent_when_ui_resource_uri_none() {
1565 let cfg = cfg_with_tools(vec![ToolDecl {
1566 name: "plain_tool".to_string(),
1567 description: Some("no widget".to_string()),
1568 ui_resource_uri: None,
1569 ..Default::default()
1570 }]);
1571 let out = synthesize_from_config(&cfg).expect("synthesize");
1572 let (_, info, _) = &out[0];
1573 assert!(
1574 info.widget_meta().is_none(),
1575 "ui_resource_uri absent ⇒ widget_meta() must be None (no accidental flip)"
1576 );
1577 }
1578
1579 #[tokio::test]
1580 async fn synthesized_handler_metadata_returns_some() {
1581 let cfg = cfg_with_tools(vec![ToolDecl {
1582 name: "ping".to_string(),
1583 description: Some("ping".to_string()),
1584 parameters: vec![],
1585 annotations: None,
1586 ..Default::default()
1587 }]);
1588 let out = synthesize_from_config(&cfg).expect("synthesize");
1589 let (_, expected_info, handler) = &out[0];
1590 let actual = handler.metadata();
1591 assert!(
1592 actual.is_some(),
1593 "RESEARCH §Risks #2 invariant: SynthesizedToolHandler::metadata() MUST return Some(ToolInfo)"
1594 );
1595 assert_eq!(actual.unwrap().name, expected_info.name);
1596 }
1597
1598 /// A `[[tools]]` declaration with one defaulted `limit` param (default=20),
1599 /// used to exercise [`extract_named_params`]'s default / explicit-null logic.
1600 fn decl_with_limit_default() -> ToolDecl {
1601 ToolDecl {
1602 name: "search".to_string(),
1603 description: Some("Search".to_string()),
1604 sql: Some("SELECT * FROM t LIMIT :limit".to_string()),
1605 parameters: vec![ParamDecl {
1606 name: "limit".to_string(),
1607 param_type: Some("integer".to_string()),
1608 description: Some("row limit".to_string()),
1609 required: false,
1610 default: Some(toml::Value::Integer(20)),
1611 ..Default::default()
1612 }],
1613 ..Default::default()
1614 }
1615 }
1616
1617 #[test]
1618 fn extract_named_params_applies_default_when_absent() {
1619 // `{}` → declared default (20) is bound (the reference search/list calls
1620 // rely on this so an omitted :limit never binds NULL).
1621 let decl = decl_with_limit_default();
1622 let params = extract_named_params(&decl, &serde_json::json!({}));
1623 assert_eq!(params, vec![("limit".to_string(), serde_json::json!(20))]);
1624 }
1625
1626 #[test]
1627 fn extract_named_params_explicit_null_applies_default() {
1628 // 85-10 WR-02 secondary fix: an EXPLICIT JSON null must NOT bind
1629 // `LIMIT NULL` — it falls through to the declared default exactly like
1630 // an omitted key.
1631 let decl = decl_with_limit_default();
1632 let params = extract_named_params(&decl, &serde_json::json!({ "limit": null }));
1633 assert_eq!(
1634 params,
1635 vec![("limit".to_string(), serde_json::json!(20))],
1636 "explicit null must apply the declared default, not bind LIMIT NULL"
1637 );
1638 }
1639
1640 #[test]
1641 fn extract_named_params_explicit_value_overrides_default() {
1642 // A concrete value wins over the default.
1643 let decl = decl_with_limit_default();
1644 let params = extract_named_params(&decl, &serde_json::json!({ "limit": 5 }));
1645 assert_eq!(params, vec![("limit".to_string(), serde_json::json!(5))]);
1646 }
1647
1648 // -------------------------------------------------------------------------
1649 // Phase 128 D2 — the six new `ParamDecl` keywords reach `inputSchema`
1650 // -------------------------------------------------------------------------
1651
1652 /// Fetch the synthesized property object for `param` of the single tool in
1653 /// `tools`.
1654 fn prop_of(tools: Vec<ToolDecl>, param: &str) -> Value {
1655 let cfg = cfg_with_tools(tools);
1656 let out = synthesize_from_config(&cfg).expect("synthesize");
1657 let (_name, info, _handler) = &out[0];
1658 info.input_schema["properties"][param].clone()
1659 }
1660
1661 /// D2 / SC-2: `pattern`, `minLength`, `format` and `maxItems` all reach the
1662 /// emitted `inputSchema`.
1663 #[test]
1664 fn input_schema_emits_d2_scalar_keywords() {
1665 let prop = prop_of(
1666 vec![ToolDecl {
1667 name: "lookup".to_string(),
1668 parameters: vec![ParamDecl {
1669 name: "region".to_string(),
1670 param_type: Some("string".to_string()),
1671 required: true,
1672 pattern: Some("^[A-Z]{3}$".to_string()),
1673 min_length: Some(3),
1674 format: Some("uuid".to_string()),
1675 max_items: Some(5),
1676 ..Default::default()
1677 }],
1678 ..Default::default()
1679 }],
1680 "region",
1681 );
1682 assert_eq!(prop["pattern"], serde_json::json!("^[A-Z]{3}$"));
1683 assert_eq!(prop["minLength"], serde_json::json!(3));
1684 assert_eq!(prop["format"], serde_json::json!("uuid"));
1685 assert_eq!(prop["maxItems"], serde_json::json!(5));
1686 }
1687
1688 /// D2 / RESEARCH Finding 1h: `items` is emitted in OBJECT form. The array
1689 /// (draft-07 tuple) form does not compile under the Draft 2020-12 pin and
1690 /// would take the whole tool's validator down.
1691 #[test]
1692 fn input_schema_emits_items_as_object_never_array() {
1693 let prop = prop_of(
1694 vec![ToolDecl {
1695 name: "batch".to_string(),
1696 parameters: vec![ParamDecl {
1697 name: "codes".to_string(),
1698 param_type: Some("array".to_string()),
1699 required: true,
1700 items: Some(ItemsDecl {
1701 item_type: Some("string".to_string()),
1702 max_length: Some(8),
1703 pattern: Some("^[a-z]+$".to_string()),
1704 }),
1705 max_items: Some(10),
1706 ..Default::default()
1707 }],
1708 ..Default::default()
1709 }],
1710 "codes",
1711 );
1712 assert!(
1713 prop["items"].is_object(),
1714 "items must be an OBJECT, got: {}",
1715 prop["items"]
1716 );
1717 assert!(
1718 !prop["items"].is_array(),
1719 "array-form items does not compile under the 2020-12 pin"
1720 );
1721 assert_eq!(
1722 prop["items"],
1723 serde_json::json!({
1724 "type": "string",
1725 "maxLength": 8,
1726 "pattern": "^[a-z]+$",
1727 })
1728 );
1729 }
1730
1731 /// D2 edge (empty): a `ParamDecl` carrying NONE of the six new keywords emits
1732 /// exactly the five it emits today — no empty `pattern` string and no empty
1733 /// `items` object appears.
1734 #[test]
1735 fn input_schema_omits_d2_keywords_when_undeclared() {
1736 let prop = prop_of(
1737 vec![ToolDecl {
1738 name: "legacy".to_string(),
1739 parameters: vec![ParamDecl {
1740 name: "count".to_string(),
1741 param_type: Some("integer".to_string()),
1742 description: Some("how many".to_string()),
1743 required: false,
1744 minimum: Some(1.0),
1745 maximum: Some(10.0),
1746 max_length: Some(4),
1747 ..Default::default()
1748 }],
1749 ..Default::default()
1750 }],
1751 "count",
1752 );
1753 let obj = prop.as_object().expect("property object");
1754 let mut keys: Vec<&str> = obj.keys().map(String::as_str).collect();
1755 keys.sort_unstable();
1756 assert_eq!(
1757 keys,
1758 vec!["description", "maxLength", "maximum", "minimum", "type"],
1759 "exactly the five pre-D2 keywords, and no more"
1760 );
1761 for absent in ["pattern", "minLength", "format", "items", "maxItems"] {
1762 assert!(
1763 obj.get(absent).is_none(),
1764 "undeclared keyword {absent} must not be emitted"
1765 );
1766 }
1767 }
1768
1769 /// D2 edge (ordering): two synthesis runs over ONE config produce
1770 /// byte-identical `input_schema` values, so `properties` and `required` follow
1771 /// `[[tools.parameters]]` declaration order deterministically.
1772 #[test]
1773 fn input_schema_is_byte_identical_across_two_synthesis_runs() {
1774 let tools = vec![ToolDecl {
1775 name: "search".to_string(),
1776 parameters: vec![
1777 ParamDecl {
1778 name: "zebra".to_string(),
1779 param_type: Some("string".to_string()),
1780 required: true,
1781 pattern: Some("^z".to_string()),
1782 ..Default::default()
1783 },
1784 ParamDecl {
1785 name: "alpha".to_string(),
1786 param_type: Some("string".to_string()),
1787 required: true,
1788 min_length: Some(1),
1789 ..Default::default()
1790 },
1791 ParamDecl {
1792 name: "middle".to_string(),
1793 param_type: Some("integer".to_string()),
1794 required: false,
1795 ..Default::default()
1796 },
1797 ],
1798 ..Default::default()
1799 }];
1800 let cfg = cfg_with_tools(tools);
1801 let first = synthesize_from_config(&cfg).expect("synthesize")[0]
1802 .1
1803 .input_schema
1804 .to_string();
1805 let second = synthesize_from_config(&cfg).expect("synthesize")[0]
1806 .1
1807 .input_schema
1808 .to_string();
1809 assert_eq!(first, second, "synthesis must be byte-deterministic");
1810 // Declaration order, not sorted order.
1811 assert!(
1812 first.find("\"zebra\"").unwrap() < first.find("\"alpha\"").unwrap(),
1813 "properties must follow declaration order: {first}"
1814 );
1815 }
1816
1817 /// D2 edge (adjacency): `min_length == max_length` accepts exactly that length
1818 /// and refuses one code point either side, through the SAME core validator the
1819 /// D1 decorator uses.
1820 #[cfg(feature = "input-validation")]
1821 #[test]
1822 fn min_length_equal_to_max_length_accepts_exactly_that_length() {
1823 use pmcp::server::schema_validation::validate_input;
1824
1825 let cfg = cfg_with_tools(vec![ToolDecl {
1826 name: "exact".to_string(),
1827 parameters: vec![ParamDecl {
1828 name: "code".to_string(),
1829 param_type: Some("string".to_string()),
1830 required: true,
1831 min_length: Some(3),
1832 max_length: Some(3),
1833 ..Default::default()
1834 }],
1835 ..Default::default()
1836 }]);
1837 let out = synthesize_from_config(&cfg).expect("synthesize");
1838 let schema = &out[0].1.input_schema;
1839
1840 validate_input(schema, Some(&serde_json::json!({ "code": "abc" })), None)
1841 .expect("exactly three code points must be accepted");
1842 validate_input(schema, Some(&serde_json::json!({ "code": "ab" })), None)
1843 .expect_err("two code points must be refused");
1844 validate_input(schema, Some(&serde_json::json!({ "code": "abcd" })), None)
1845 .expect_err("four code points must be refused");
1846 }
1847
1848 // -------------------------------------------------------------------------
1849 // Phase 128 D3 — position-scoped default cap and `[server.validation]`
1850 // -------------------------------------------------------------------------
1851
1852 /// Synthesize `tools` under `validation` and return the property object for
1853 /// `param` of the FIRST tool.
1854 fn prop_under(tools: Vec<ToolDecl>, validation: ValidationSection, param: &str) -> Value {
1855 let mut cfg = cfg_with_tools(tools);
1856 cfg.server.validation = validation;
1857 let out = synthesize_from_config(&cfg).expect("synthesize");
1858 out[0].1.input_schema["properties"][param].clone()
1859 }
1860
1861 /// A single-call `GET` tool declaring one path parameter and one query
1862 /// parameter, both uncapped strings.
1863 fn get_tool_with_path_and_query() -> Vec<ToolDecl> {
1864 vec![ToolDecl {
1865 name: "line_status".to_string(),
1866 path: Some("/lines/{line_id}/status".to_string()),
1867 method: Some("GET".to_string()),
1868 parameters: vec![
1869 ParamDecl {
1870 name: "line_id".to_string(),
1871 param_type: Some("string".to_string()),
1872 required: true,
1873 ..Default::default()
1874 },
1875 ParamDecl {
1876 name: "detail".to_string(),
1877 param_type: Some("string".to_string()),
1878 required: false,
1879 ..Default::default()
1880 },
1881 ],
1882 ..Default::default()
1883 }]
1884 }
1885
1886 /// D3: a PATH-position string with no `max_length` is capped at the configured
1887 /// default.
1888 #[test]
1889 fn default_cap_applies_to_path_position_string() {
1890 let prop = prop_under(
1891 get_tool_with_path_and_query(),
1892 ValidationSection::default(),
1893 "line_id",
1894 );
1895 assert_eq!(prop["maxLength"], serde_json::json!(256));
1896 }
1897
1898 /// D3: a QUERY-position string (non-path parameter of a `GET` tool) with no
1899 /// `max_length` is capped at the configured default.
1900 #[test]
1901 fn default_cap_applies_to_query_position_string() {
1902 let prop = prop_under(
1903 get_tool_with_path_and_query(),
1904 ValidationSection::default(),
1905 "detail",
1906 );
1907 assert_eq!(prop["maxLength"], serde_json::json!(256));
1908 }
1909
1910 /// D3 / D-05 / T-128-13d: a BODY-position string on a mutating single-call tool
1911 /// receives NO cap. Capping a `POST` payload's free-text field is exactly the
1912 /// breakage review note C objected to.
1913 #[test]
1914 fn default_cap_never_applies_to_body_position_string() {
1915 let tools = vec![ToolDecl {
1916 name: "add_comment".to_string(),
1917 path: Some("/issues/{id}/comments".to_string()),
1918 method: Some("POST".to_string()),
1919 parameters: vec![
1920 ParamDecl {
1921 name: "id".to_string(),
1922 param_type: Some("string".to_string()),
1923 required: true,
1924 ..Default::default()
1925 },
1926 ParamDecl {
1927 name: "body_text".to_string(),
1928 param_type: Some("string".to_string()),
1929 required: true,
1930 ..Default::default()
1931 },
1932 ],
1933 ..Default::default()
1934 }];
1935 let path_prop = prop_under(tools.clone(), ValidationSection::default(), "id");
1936 assert_eq!(
1937 path_prop["maxLength"],
1938 serde_json::json!(256),
1939 "the path parameter of a POST tool IS still capped"
1940 );
1941 let body_prop = prop_under(tools, ValidationSection::default(), "body_text");
1942 assert!(
1943 body_prop.get("maxLength").is_none(),
1944 "a POST payload field must receive no default cap, got: {body_prop}"
1945 );
1946 }
1947
1948 /// D3 edge (adjacency): a DECLARED `max_length` is never overridden and never
1949 /// merged with the default, in either direction.
1950 #[test]
1951 fn declared_max_length_wins_over_the_default_cap() {
1952 let mut tools = get_tool_with_path_and_query();
1953 tools[0].parameters[0].max_length = Some(12);
1954 let prop = prop_under(tools, ValidationSection::default(), "line_id");
1955 assert_eq!(prop["maxLength"], serde_json::json!(12));
1956 }
1957
1958 /// D3 edge (empty): `default_max_length = 0` emits no `maxLength` in ANY
1959 /// position and disables the cap entirely.
1960 #[test]
1961 fn default_max_length_zero_disables_the_cap_in_every_position() {
1962 let validation = ValidationSection {
1963 default_max_length: 0,
1964 ..Default::default()
1965 };
1966 for param in ["line_id", "detail"] {
1967 let prop = prop_under(get_tool_with_path_and_query(), validation.clone(), param);
1968 assert!(
1969 prop.get("maxLength").is_none(),
1970 "{param} must carry no maxLength when the default is 0, got: {prop}"
1971 );
1972 }
1973 }
1974
1975 /// D3 edge (boundary + encoding): the cap is counted in Unicode CODE POINTS,
1976 /// not bytes — so exactly `default_max_length` multi-byte characters are
1977 /// accepted and one more is refused, through the SAME core validator.
1978 #[cfg(feature = "input-validation")]
1979 #[test]
1980 fn default_cap_boundary_is_counted_in_code_points_not_bytes() {
1981 use pmcp::server::schema_validation::validate_input;
1982
1983 let validation = ValidationSection {
1984 default_max_length: 8,
1985 ..Default::default()
1986 };
1987 let mut cfg = cfg_with_tools(get_tool_with_path_and_query());
1988 cfg.server.validation = validation;
1989 let out = synthesize_from_config(&cfg).expect("synthesize");
1990 let schema = &out[0].1.input_schema;
1991
1992 // Each `é` is TWO bytes and ONE code point. Eight of them are 16 bytes.
1993 let at_limit: String = "é".repeat(8);
1994 let over_limit: String = "é".repeat(9);
1995 assert_eq!(
1996 at_limit.len(),
1997 16,
1998 "the fixture must actually be multi-byte"
1999 );
2000 validate_input(
2001 schema,
2002 Some(&serde_json::json!({ "line_id": at_limit })),
2003 None,
2004 )
2005 .expect("exactly 8 code points must be accepted even though they are 16 bytes");
2006 validate_input(
2007 schema,
2008 Some(&serde_json::json!({ "line_id": over_limit })),
2009 None,
2010 )
2011 .expect_err("9 code points must be refused");
2012 }
2013
2014 /// `additional_properties = true` flips the emitted envelope, re-opening the
2015 /// unknown-argument class for this server.
2016 #[test]
2017 fn additional_properties_opt_out_flips_the_envelope() {
2018 let mut cfg = cfg_with_tools(get_tool_with_path_and_query());
2019 cfg.server.validation = ValidationSection {
2020 additional_properties: true,
2021 ..Default::default()
2022 };
2023 let out = synthesize_from_config(&cfg).expect("synthesize");
2024 assert_eq!(
2025 out[0].1.input_schema["additionalProperties"],
2026 Value::Bool(true)
2027 );
2028
2029 let mut cfg = cfg_with_tools(get_tool_with_path_and_query());
2030 cfg.server.validation = ValidationSection::default();
2031 let out = synthesize_from_config(&cfg).expect("synthesize");
2032 assert_eq!(
2033 out[0].1.input_schema["additionalProperties"],
2034 Value::Bool(false),
2035 "the default must remain a closed envelope"
2036 );
2037 }
2038
2039 /// T-128-13c: `enforce_input_schema = false` skips the SCHEMA CHECK, not the
2040 /// decorator. This test pins the separation the E2 argument-validator registry
2041 /// will depend on: with the flag off an undeclared argument is ACCEPTED (schema
2042 /// off), while the inner handler's own rule still REFUSES (the non-schema
2043 /// enforcement is untouched). Without this test the two collapse back together
2044 /// on the next refactor.
2045 #[cfg(feature = "input-validation")]
2046 #[tokio::test]
2047 async fn enforce_input_schema_false_skips_the_check_not_the_decorator() {
2048 /// Stands in for an explicitly-registered argument validator: a rule that
2049 /// lives INSIDE the decorated stack and is not the JSON Schema check.
2050 struct RefusingInner;
2051
2052 #[async_trait]
2053 impl ToolHandler for RefusingInner {
2054 async fn handle(
2055 &self,
2056 _args: Value,
2057 _extra: RequestHandlerExtra,
2058 ) -> pmcp::Result<Value> {
2059 Err(pmcp::Error::Validation(
2060 "the registered validator refused".to_string(),
2061 ))
2062 }
2063 }
2064
2065 let decl = ToolDecl {
2066 name: "guarded".to_string(),
2067 parameters: vec![ParamDecl {
2068 name: "declared".to_string(),
2069 param_type: Some("string".to_string()),
2070 required: false,
2071 ..Default::default()
2072 }],
2073 ..Default::default()
2074 };
2075 let info = build_tool_info(&decl, &ValidationSection::default());
2076 let undeclared = serde_json::json!({ "not_declared_at_all": "x" });
2077
2078 // (a) enforcement ON: the SCHEMA refuses before the inner handler runs, so
2079 // the message is the schema refusal, not the inner one.
2080 let on = ValidatingToolHandler::wrap(Arc::new(RefusingInner), &info, &decl, true, None);
2081 let err = on
2082 .handle(undeclared.clone(), RequestHandlerExtra::default())
2083 .await
2084 .expect_err("an undeclared argument must be refused when enforcement is on");
2085 assert!(
2086 !err.to_string().contains("registered validator"),
2087 "the schema check must run FIRST when enforcement is on: {err}"
2088 );
2089
2090 // (b) enforcement OFF: the schema check is skipped (the undeclared argument
2091 // is accepted by it), and the inner rule STILL refuses. That is the
2092 // separation — A off must not silently turn B off.
2093 let off = ValidatingToolHandler::wrap(Arc::new(RefusingInner), &info, &decl, false, None);
2094 let err = off
2095 .handle(undeclared, RequestHandlerExtra::default())
2096 .await
2097 .expect_err("the inner (non-schema) rule must still refuse");
2098 assert!(
2099 err.to_string().contains("registered validator"),
2100 "with the schema check off, the refusal must come from the inner rule: {err}"
2101 );
2102 }
2103}
2104
2105// -----------------------------------------------------------------------------
2106// Tests — Phase 128 D4(b): `build_operation` carries the declared placeholder
2107// rules onto every `Parameter`.
2108// -----------------------------------------------------------------------------
2109
2110/// Named `build_operation` deliberately: libtest matches the FULL test path, so a
2111/// test placed in the crate's existing `mod tests` would be
2112/// `tools::tests::build_operation_…` and this plan's `--lib tools::build_operation`
2113/// verify filter would select ZERO tests while exiting 0. As a SIBLING of `tests`
2114/// at the `tools` module level the filter resolves as written. Do not fold these
2115/// into `mod tests`.
2116#[cfg(all(test, feature = "http"))]
2117mod build_operation {
2118 use super::*;
2119
2120 /// A single-call `GET` tool on `path` carrying `parameters`.
2121 fn decl(path: &str, parameters: Vec<ParamDecl>) -> ToolDecl {
2122 ToolDecl {
2123 name: "t".to_string(),
2124 description: Some("t".to_string()),
2125 path: Some(path.to_string()),
2126 method: Some("GET".to_string()),
2127 parameters,
2128 ..Default::default()
2129 }
2130 }
2131
2132 fn param_named<'a>(op: &'a Operation, name: &str) -> &'a Parameter {
2133 op.parameters
2134 .iter()
2135 .find(|p| p.name == name)
2136 .unwrap_or_else(|| panic!("parameter {name} present"))
2137 }
2138
2139 /// A path parameter declaring a `pattern` produces a `Parameter` carrying it.
2140 #[test]
2141 fn build_operation_carries_a_declared_path_pattern() {
2142 let d = decl(
2143 "/content/{version}",
2144 vec![ParamDecl {
2145 name: "version".to_string(),
2146 param_type: Some("string".to_string()),
2147 required: true,
2148 pattern: Some("^C[0-9]+$".to_string()),
2149 ..Default::default()
2150 }],
2151 );
2152 let op = super::build_operation("/content/{version}", "GET", &d);
2153 let p = param_named(&op, "version");
2154 assert_eq!(p.location, ParameterLocation::Path);
2155 assert_eq!(p.pattern.as_deref(), Some("^C[0-9]+$"));
2156 }
2157
2158 /// A query parameter declaring `max_length = 64` produces a `Parameter`
2159 /// carrying `max_length: Some(64)`.
2160 #[test]
2161 fn build_operation_carries_a_declared_query_max_length() {
2162 let d = decl(
2163 "/search",
2164 vec![ParamDecl {
2165 name: "q".to_string(),
2166 param_type: Some("string".to_string()),
2167 max_length: Some(64),
2168 ..Default::default()
2169 }],
2170 );
2171 let op = super::build_operation("/search", "GET", &d);
2172 let p = param_named(&op, "q");
2173 assert_eq!(p.location, ParameterLocation::Query);
2174 assert_eq!(p.max_length, Some(64));
2175 }
2176
2177 /// A template segment the config never declared carries NO declared rules and
2178 /// `allow_slash: false` — the path loop iterates the TEMPLATE, so it must look
2179 /// the `ParamDecl` up by name and fall back cleanly when there is none.
2180 #[test]
2181 fn build_operation_leaves_rules_absent_for_an_undeclared_template_segment() {
2182 let d = decl("/content/{version}", vec![]);
2183 let op = super::build_operation("/content/{version}", "GET", &d);
2184 let p = param_named(&op, "version");
2185 assert_eq!(p.pattern, None);
2186 assert_eq!(p.max_length, None);
2187 assert!(!p.allow_slash);
2188 assert!(p.required, "a template path parameter stays required");
2189 }
2190
2191 /// D-11: `allow_slash` reaches the `Parameter` from the server's OWN config —
2192 /// the one legitimate source.
2193 #[test]
2194 fn build_operation_carries_allow_slash_from_the_config() {
2195 let d = decl(
2196 "/files/{subpath}",
2197 vec![ParamDecl {
2198 name: "subpath".to_string(),
2199 param_type: Some("string".to_string()),
2200 required: true,
2201 allow_slash: true,
2202 ..Default::default()
2203 }],
2204 );
2205 let op = super::build_operation("/files/{subpath}", "GET", &d);
2206 assert!(param_named(&op, "subpath").allow_slash);
2207 }
2208
2209 /// The three rule fields round-trip into the core rules type the substitution
2210 /// point reads.
2211 #[cfg(feature = "input-validation")]
2212 #[test]
2213 fn build_operation_rules_reach_placeholder_rules() {
2214 let d = decl(
2215 "/files/{subpath}",
2216 vec![ParamDecl {
2217 name: "subpath".to_string(),
2218 param_type: Some("string".to_string()),
2219 required: true,
2220 pattern: Some("^[a-z/]+$".to_string()),
2221 max_length: Some(128),
2222 allow_slash: true,
2223 ..Default::default()
2224 }],
2225 );
2226 let op = super::build_operation("/files/{subpath}", "GET", &d);
2227 let rules = param_named(&op, "subpath").placeholder_rules();
2228 assert_eq!(rules.declared_pattern, Some("^[a-z/]+$"));
2229 assert_eq!(rules.declared_max_length, Some(128));
2230 assert!(rules.allow_slash);
2231 }
2232
2233 /// Phase 128 CR-02 — a body-bearing method routes its non-path declared
2234 /// parameters to [`ParameterLocation::Body`], not to the query string.
2235 ///
2236 /// Before the fix every one of these was `Query`, so the payload
2237 /// `build_body` assembles was empty and the values travelled in the URL.
2238 #[test]
2239 fn build_operation_routes_a_post_non_path_param_to_the_body() {
2240 for method in ["POST", "PUT", "PATCH", "post"] {
2241 let mut d = decl(
2242 "/issues/{id}/comments",
2243 vec![
2244 ParamDecl {
2245 name: "id".to_string(),
2246 param_type: Some("string".to_string()),
2247 required: true,
2248 ..Default::default()
2249 },
2250 ParamDecl {
2251 name: "body_text".to_string(),
2252 param_type: Some("string".to_string()),
2253 required: true,
2254 ..Default::default()
2255 },
2256 ],
2257 );
2258 d.method = Some(method.to_string());
2259 let op = super::build_operation("/issues/{id}/comments", method, &d);
2260 assert!(
2261 op.has_request_body,
2262 "{method} carries a request body by definition"
2263 );
2264 assert_eq!(param_named(&op, "id").location, ParameterLocation::Path);
2265 assert_eq!(
2266 param_named(&op, "body_text").location,
2267 ParameterLocation::Body,
2268 "{method}: a non-path declared parameter must be routed to the payload"
2269 );
2270 assert_eq!(
2271 op.body_parameters().len(),
2272 1,
2273 "{method}: exactly the one non-path parameter is a body parameter"
2274 );
2275 assert!(
2276 op.query_parameters().is_empty(),
2277 "{method}: nothing may travel in the query string as well"
2278 );
2279 }
2280 }
2281
2282 /// The other half of the same rule: a method that carries NO request body has
2283 /// nowhere but the URL to put a non-path parameter, so it stays `Query`. Without
2284 /// this row the fix above is satisfiable by routing everything to the body,
2285 /// which would drop a `GET` tool's parameters entirely.
2286 #[test]
2287 fn build_operation_keeps_a_body_less_method_non_path_param_in_the_query() {
2288 for method in ["GET", "HEAD", "DELETE", "OPTIONS"] {
2289 let mut d = decl(
2290 "/search",
2291 vec![ParamDecl {
2292 name: "q".to_string(),
2293 param_type: Some("string".to_string()),
2294 required: true,
2295 ..Default::default()
2296 }],
2297 );
2298 d.method = Some(method.to_string());
2299 let op = super::build_operation("/search", method, &d);
2300 assert!(!op.has_request_body, "{method} carries no request body");
2301 assert_eq!(
2302 param_named(&op, "q").location,
2303 ParameterLocation::Query,
2304 "{method}: a non-path parameter must stay in the query string"
2305 );
2306 assert!(
2307 op.body_parameters().is_empty(),
2308 "{method}: a body-less request can have no body parameter"
2309 );
2310 }
2311 }
2312
2313 /// Phase 128 CR-03 — the D3 cap's POSITION and the request's ROUTING agree for
2314 /// EVERY method this connector can send, so the cap can no longer be withheld
2315 /// from a value that travels in the query string.
2316 ///
2317 /// This is the row that would have caught the original defect: it does not
2318 /// assert a particular location, it asserts the PAIRING. Before the fix
2319 /// `param_position` said `Body` for `POST` while `build_operation` said `Query`,
2320 /// and `apply_position_cap` emitted nothing for `Body` — so a `POST` parameter
2321 /// reached the request line with no `maxLength`.
2322 ///
2323 /// Fails on removal: point either side at its own method list again and the
2324 /// `POST`/`PUT`/`PATCH` rows (or the `OPTIONS` row) go red.
2325 #[test]
2326 fn param_position_agrees_with_the_built_parameter_location_for_every_method() {
2327 use crate::config::ParamPosition;
2328
2329 // Every method `HttpClient::convert_method` accepts.
2330 for method in [
2331 "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "patch",
2332 ] {
2333 let mut d = decl(
2334 "/things/{id}",
2335 vec![
2336 ParamDecl {
2337 name: "id".to_string(),
2338 param_type: Some("string".to_string()),
2339 required: true,
2340 ..Default::default()
2341 },
2342 ParamDecl {
2343 name: "note".to_string(),
2344 param_type: Some("string".to_string()),
2345 required: false,
2346 ..Default::default()
2347 },
2348 ],
2349 );
2350 d.method = Some(method.to_string());
2351 let op = super::build_operation("/things/{id}", method, &d);
2352
2353 for p in &op.parameters {
2354 let expected_location = match d.param_position(&p.name) {
2355 ParamPosition::Path => ParameterLocation::Path,
2356 ParamPosition::Query => ParameterLocation::Query,
2357 ParamPosition::Body => ParameterLocation::Body,
2358 };
2359 assert_eq!(
2360 p.location,
2361 expected_location,
2362 "{method}: `{}` is {:?} for the D3 cap but {:?} on the wire — the cap's \
2363 scope and the request's routing must not disagree",
2364 p.name,
2365 d.param_position(&p.name),
2366 p.location
2367 );
2368 }
2369
2370 // And the routing is self-consistent: a Body location exists exactly
2371 // when the request carries a body.
2372 assert_eq!(
2373 op.has_request_body,
2374 !op.body_parameters().is_empty(),
2375 "{method}: a Body-located parameter on a body-less request would be \
2376 silently dropped"
2377 );
2378 }
2379 }
2380
2381 /// The consequence CR-03 is really about: the D3 default `maxLength` is emitted
2382 /// for a parameter that travels in the query string and withheld from one that
2383 /// travels in the JSON payload — checked against the BUILT location rather than
2384 /// against a method list, so the two cannot drift.
2385 #[test]
2386 fn the_default_cap_is_emitted_exactly_where_the_value_travels_in_the_url() {
2387 use crate::config::{default_cap_applies, ValidationSection};
2388
2389 let validation = ValidationSection::default();
2390 assert_ne!(
2391 validation.default_max_length, 0,
2392 "the default cap must be on for this row to mean anything"
2393 );
2394
2395 for method in ["GET", "HEAD", "DELETE", "OPTIONS", "POST", "PUT", "PATCH"] {
2396 let param = ParamDecl {
2397 name: "note".to_string(),
2398 param_type: Some("string".to_string()),
2399 required: false,
2400 ..Default::default()
2401 };
2402 let mut d = decl("/things", vec![param.clone()]);
2403 d.method = Some(method.to_string());
2404 let op = super::build_operation("/things", method, &d);
2405 let location = param_named(&op, "note").location;
2406 let capped = default_cap_applies(¶m, d.param_position("note"), &validation);
2407
2408 assert_eq!(
2409 capped,
2410 location == ParameterLocation::Query,
2411 "{method}: an uncapped string in a {location:?} position is the CR-03 defect \
2412 when that position is the query string, and the D-05 requirement when it is \
2413 the payload"
2414 );
2415 }
2416 }
2417}
2418
2419// -----------------------------------------------------------------------------
2420// Tests — Phase 90 OAPI-02a single-call HTTP synthesizer (feature `http`)
2421// -----------------------------------------------------------------------------
2422
2423#[cfg(all(test, feature = "http"))]
2424mod synth_http_tests {
2425 use super::*;
2426 use crate::config::{ParamDecl, ServerConfig, ServerSection, ToolDecl};
2427 use crate::http::{HttpConnector, HttpConnectorError, Operation};
2428 use pmcp::RequestHandlerExtra;
2429 use serde_json::{json, Value};
2430 use std::sync::{Arc, Mutex};
2431
2432 /// A mock [`HttpConnector`] that records the [`Operation`] it last received
2433 /// and returns a fixed JSON payload — so a synthesized handler can be
2434 /// invoked without any network.
2435 struct MockHttpConnector {
2436 last: Mutex<Option<Operation>>,
2437 payload: Value,
2438 }
2439
2440 impl MockHttpConnector {
2441 fn new(payload: Value) -> Arc<Self> {
2442 Arc::new(Self {
2443 last: Mutex::new(None),
2444 payload,
2445 })
2446 }
2447 }
2448
2449 #[async_trait]
2450 impl HttpConnector for MockHttpConnector {
2451 async fn execute(
2452 &self,
2453 operation: &Operation,
2454 _args: &Value,
2455 ) -> std::result::Result<Value, HttpConnectorError> {
2456 *self.last.lock().unwrap() = Some(operation.clone());
2457 Ok(self.payload.clone())
2458 }
2459 fn base_url(&self) -> &str {
2460 "https://mock.example.com"
2461 }
2462 }
2463
2464 fn cfg_with_tools(tools: Vec<ToolDecl>) -> ServerConfig {
2465 ServerConfig {
2466 server: ServerSection {
2467 name: "demo".to_string(),
2468 version: "0.1.0".to_string(),
2469 ..Default::default()
2470 },
2471 tools,
2472 ..Default::default()
2473 }
2474 }
2475
2476 /// (1) A single-call `[[tools]]` with a `{id}` path param synthesizes a
2477 /// `ToolInfo` whose input schema marks `id` required (object envelope), and
2478 /// the handler (wired to a mock connector) returns the mocked JSON.
2479 #[tokio::test]
2480 async fn synth_http_single_call_path_param_required_and_handler_returns_json() {
2481 let cfg = cfg_with_tools(vec![ToolDecl {
2482 name: "line_status".to_string(),
2483 description: Some("Line status".to_string()),
2484 path: Some("/Line/{id}/Status".to_string()),
2485 method: Some("GET".to_string()),
2486 parameters: vec![ParamDecl {
2487 name: "id".to_string(),
2488 param_type: Some("string".to_string()),
2489 required: true,
2490 ..Default::default()
2491 }],
2492 ..Default::default()
2493 }]);
2494 let connector = MockHttpConnector::new(json!({ "status": "Good Service" }));
2495 let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
2496 .expect("synthesize");
2497 assert_eq!(out.len(), 1);
2498 let (name, info, handler) = &out[0];
2499 assert_eq!(name, "line_status");
2500 let schema = &info.input_schema;
2501 assert_eq!(schema["type"], "object");
2502 assert_eq!(schema["required"], json!(["id"]));
2503 assert_eq!(schema["additionalProperties"], Value::Bool(false));
2504
2505 let extra = RequestHandlerExtra::default();
2506 let result = handler
2507 .handle(json!({ "id": "victoria" }), extra)
2508 .await
2509 .expect("handle");
2510 assert_eq!(result, json!({ "status": "Good Service" }));
2511
2512 // The operation carried the `{id}` path param as a Path parameter.
2513 let op = connector
2514 .last
2515 .lock()
2516 .unwrap()
2517 .clone()
2518 .expect("operation recorded");
2519 let path_params: Vec<&str> = op
2520 .path_parameters()
2521 .iter()
2522 .map(|p| p.name.as_str())
2523 .collect();
2524 assert_eq!(path_params, vec!["id"]);
2525 }
2526
2527 /// (2) A `POST` tool routes non-path args to the request body
2528 /// (`has_request_body` true) and the non-path param is NOT a path param.
2529 #[tokio::test]
2530 async fn synth_http_post_sets_request_body() {
2531 let cfg = cfg_with_tools(vec![ToolDecl {
2532 name: "create_item".to_string(),
2533 description: Some("Create".to_string()),
2534 path: Some("/items".to_string()),
2535 method: Some("post".to_string()),
2536 parameters: vec![ParamDecl {
2537 name: "title".to_string(),
2538 param_type: Some("string".to_string()),
2539 required: true,
2540 ..Default::default()
2541 }],
2542 ..Default::default()
2543 }]);
2544 let connector = MockHttpConnector::new(json!({ "ok": true }));
2545 let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
2546 .expect("synthesize");
2547 let (_, _, handler) = &out[0];
2548 let extra = RequestHandlerExtra::default();
2549 handler
2550 .handle(json!({ "title": "widget" }), extra)
2551 .await
2552 .expect("handle");
2553 let op = connector
2554 .last
2555 .lock()
2556 .unwrap()
2557 .clone()
2558 .expect("operation recorded");
2559 assert_eq!(op.method, "POST");
2560 assert!(op.has_request_body, "POST must carry a request body");
2561 assert!(op.path_parameters().is_empty());
2562 }
2563
2564 /// (3) A tool with path + query params lands them in the right schema slots /
2565 /// `Operation` parameter locations.
2566 #[tokio::test]
2567 async fn synth_http_path_and_query_param_slots() {
2568 let cfg = cfg_with_tools(vec![ToolDecl {
2569 name: "search".to_string(),
2570 description: Some("Search".to_string()),
2571 path: Some("/repos/{owner}/issues".to_string()),
2572 method: Some("GET".to_string()),
2573 parameters: vec![
2574 ParamDecl {
2575 name: "owner".to_string(),
2576 param_type: Some("string".to_string()),
2577 required: true,
2578 ..Default::default()
2579 },
2580 ParamDecl {
2581 name: "state".to_string(),
2582 param_type: Some("string".to_string()),
2583 required: false,
2584 ..Default::default()
2585 },
2586 ],
2587 ..Default::default()
2588 }]);
2589 let connector = MockHttpConnector::new(json!([]));
2590 let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
2591 .expect("synthesize");
2592 let (_, _, handler) = &out[0];
2593 let extra = RequestHandlerExtra::default();
2594 handler
2595 .handle(json!({ "owner": "rust-lang", "state": "open" }), extra)
2596 .await
2597 .expect("handle");
2598 let op = connector
2599 .last
2600 .lock()
2601 .unwrap()
2602 .clone()
2603 .expect("operation recorded");
2604 let path_params: Vec<&str> = op
2605 .path_parameters()
2606 .iter()
2607 .map(|p| p.name.as_str())
2608 .collect();
2609 assert_eq!(path_params, vec!["owner"]);
2610 let query_params: Vec<&str> = op
2611 .query_parameters()
2612 .iter()
2613 .map(|p| p.name.as_str())
2614 .collect();
2615 assert_eq!(query_params, vec!["state"]);
2616 }
2617
2618 /// (4) A per-tool `base_url` is reflected in the synthesized `Operation`
2619 /// (Codex MEDIUM — not dropped).
2620 #[tokio::test]
2621 async fn synth_http_per_tool_base_url_reflected() {
2622 let cfg = cfg_with_tools(vec![ToolDecl {
2623 name: "other_host".to_string(),
2624 description: Some("Other host".to_string()),
2625 path: Some("/ping".to_string()),
2626 method: Some("GET".to_string()),
2627 base_url: Some("https://other.example.com/v2".to_string()),
2628 ..Default::default()
2629 }]);
2630 let connector = MockHttpConnector::new(json!({ "pong": true }));
2631 let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
2632 .expect("synthesize");
2633 let (_, _, handler) = &out[0];
2634 let extra = RequestHandlerExtra::default();
2635 handler.handle(json!({}), extra).await.expect("handle");
2636 let op = connector
2637 .last
2638 .lock()
2639 .unwrap()
2640 .clone()
2641 .expect("operation recorded");
2642 assert_eq!(
2643 op.base_url.as_deref(),
2644 Some("https://other.example.com/v2"),
2645 "per-tool base_url must be reflected on the Operation, not dropped"
2646 );
2647 }
2648
2649 /// (5) NEGATIVE: a `[[tools]]` missing `method` (and without `script`) is
2650 /// rejected with a typed `ToolkitError` (T-90-03-04 — never silently
2651 /// registered).
2652 #[test]
2653 fn synth_http_missing_method_rejected() {
2654 let cfg = cfg_with_tools(vec![ToolDecl {
2655 name: "broken".to_string(),
2656 description: Some("missing method".to_string()),
2657 path: Some("/items".to_string()),
2658 method: None,
2659 ..Default::default()
2660 }]);
2661 let connector = MockHttpConnector::new(json!(null));
2662 let err = synthesize_from_config_with_http_connector(&cfg, connector)
2663 .err()
2664 .expect("ill-formed single-call tool must be rejected");
2665 assert!(matches!(err, ToolkitError::Synth(_)));
2666 }
2667
2668 /// (5b) NEGATIVE: on the single-call-only entry point, a `script` tool is
2669 /// rejected with a typed `ToolkitError` pointing at the `openapi-code-mode`
2670 /// script path — NOT a silent skip, NOT a panic. (The OpenAPI Code Mode
2671 /// entry point `synthesize_from_config_with_http_connector_and_scripts`
2672 /// synthesizes a real `ScriptToolHandler` — proven in `script_tool` tests.)
2673 #[test]
2674 fn synth_http_script_tool_without_engine_is_rejected() {
2675 let cfg = cfg_with_tools(vec![ToolDecl {
2676 name: "scripted".to_string(),
2677 description: Some("script tool".to_string()),
2678 script: Some("await api.get('/x')".to_string()),
2679 ..Default::default()
2680 }]);
2681 let connector = MockHttpConnector::new(json!(null));
2682 let err = synthesize_from_config_with_http_connector(&cfg, connector)
2683 .err()
2684 .expect("script tool on the single-call-only entry point must be rejected");
2685 match err {
2686 ToolkitError::Synth(msg) => {
2687 assert!(
2688 msg.contains("openapi-code-mode"),
2689 "seam message must point at the openapi-code-mode script path: {msg}"
2690 );
2691 },
2692 other => panic!("expected Synth error, got {other:?}"),
2693 }
2694 }
2695}
2696
2697// -----------------------------------------------------------------------------
2698// Phase 128 E2 — the per-tool ArgumentValidator seam.
2699//
2700// A SIBLING of `mod tests`, selected by the `--lib tools::` filter. It drives the
2701// PUBLIC `*_and_hooks` synthesizer so the assertions hold through the surface an
2702// out-of-crate caller (`pmcp-openapi-server`) actually uses.
2703// -----------------------------------------------------------------------------
2704
2705/// E2 ordering, the schema opt-out, and the empty case.
2706#[cfg(all(test, feature = "input-validation"))]
2707mod argument_validator_seam {
2708 use super::synthesize_from_config_and_hooks;
2709 use crate::config::ServerConfig;
2710 use crate::policy::{ArgumentRefusal, ArgumentValidator, ToolkitHooks};
2711 use pmcp::RequestHandlerExtra;
2712 use serde_json::{json, Value};
2713 use std::sync::atomic::{AtomicUsize, Ordering};
2714 use std::sync::Arc;
2715
2716 /// Counts its invocations, then refuses when `end < start`. The refusal is a
2717 /// FIXED string: it names the rule, never a value.
2718 struct EndAfterStart {
2719 calls: Arc<AtomicUsize>,
2720 }
2721
2722 impl ArgumentValidator for EndAfterStart {
2723 fn validate(&self, args: &Value) -> Result<(), ArgumentRefusal> {
2724 self.calls.fetch_add(1, Ordering::SeqCst);
2725 let start = args.get("start").and_then(Value::as_i64);
2726 let end = args.get("end").and_then(Value::as_i64);
2727 match (start, end) {
2728 (Some(s), Some(e)) if e < s => {
2729 Err(ArgumentRefusal::new("`end` must not precede `start`"))
2730 },
2731 _ => Ok(()),
2732 }
2733 }
2734 }
2735
2736 /// A `[[tools]]` whose declared schema permits any two integers, so the
2737 /// cross-field rule is one only E2 can express.
2738 fn cfg(enforce: bool) -> ServerConfig {
2739 let toml = format!(
2740 r#"
2741[server]
2742name = "range"
2743version = "0.1.0"
2744
2745[server.validation]
2746enforce_input_schema = {enforce}
2747
2748[[tools]]
2749name = "range_query"
2750description = "Query a range"
2751sql = "SELECT 1"
2752
2753[[tools.parameters]]
2754name = "start"
2755type = "integer"
2756required = true
2757
2758[[tools.parameters]]
2759name = "end"
2760type = "integer"
2761required = true
2762"#
2763 );
2764 ServerConfig::from_toml_strict_validated(&toml).expect("parse")
2765 }
2766
2767 fn extra() -> RequestHandlerExtra {
2768 RequestHandlerExtra::default()
2769 }
2770
2771 fn hooks(calls: &Arc<AtomicUsize>) -> ToolkitHooks {
2772 ToolkitHooks::default().with_argument_validator(
2773 "range_query",
2774 Arc::new(EndAfterStart {
2775 calls: Arc::clone(calls),
2776 }),
2777 )
2778 }
2779
2780 #[tokio::test]
2781 async fn a_registered_validator_refuses_a_combination_the_schema_permits() {
2782 let calls = Arc::new(AtomicUsize::new(0));
2783 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2784 let (_name, _info, handler) = &tools[0];
2785 let err = handler
2786 .handle(json!({ "start": 10, "end": 2 }), extra())
2787 .await
2788 .expect_err("the validator refuses");
2789 assert!(
2790 err.to_string().contains("`end` must not precede `start`"),
2791 "the refusal must carry the validator's own message, got: {err}"
2792 );
2793 assert_eq!(calls.load(Ordering::SeqCst), 1);
2794 }
2795
2796 /// The E2 refusal takes the same TOOL-LEVEL channel as the D1 schema refusal.
2797 /// A cross-field rule is as much the caller's to fix as a bad type is, and a
2798 /// model can only act on a tool result, not on a JSON-RPC error.
2799 #[tokio::test]
2800 async fn a_validator_refusal_is_a_tool_level_rejection_not_a_protocol_error() {
2801 let calls = Arc::new(AtomicUsize::new(0));
2802 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2803 let (_name, _info, handler) = &tools[0];
2804 let err = handler
2805 .handle(json!({ "start": 10, "end": 2 }), extra())
2806 .await
2807 .expect_err("the validator refuses");
2808 assert!(
2809 matches!(err, pmcp::Error::ToolRejected { .. }),
2810 "a validator refusal must be a tool-level rejection, got: {err:?}"
2811 );
2812 assert!(
2813 err.to_string().contains("`end` must not precede `start`"),
2814 "the validator's own message must survive the channel change, got: {err}"
2815 );
2816 }
2817
2818 #[tokio::test]
2819 async fn a_registered_validator_allows_a_valid_combination() {
2820 let calls = Arc::new(AtomicUsize::new(0));
2821 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2822 let (_name, _info, handler) = &tools[0];
2823 // No SQL connector is wired, so the INNER handler errors — which is itself
2824 // the proof that the validator allowed the call through to it.
2825 let err = handler
2826 .handle(json!({ "start": 2, "end": 10 }), extra())
2827 .await
2828 .expect_err("no connector is wired");
2829 assert!(
2830 !err.to_string().contains("must not precede"),
2831 "the validator must NOT have refused, got: {err}"
2832 );
2833 assert_eq!(calls.load(Ordering::SeqCst), 1);
2834 }
2835
2836 /// T-128-41: the ordering is the contract. A validator must never see
2837 /// arguments that failed the declared schema.
2838 #[tokio::test]
2839 async fn a_registered_validator_is_not_invoked_when_the_schema_refuses() {
2840 let calls = Arc::new(AtomicUsize::new(0));
2841 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2842 let (_name, _info, handler) = &tools[0];
2843 // `start` is a declared integer; a string violates the schema.
2844 let err = handler
2845 .handle(json!({ "start": "ten", "end": 2 }), extra())
2846 .await
2847 .expect_err("D1 refuses");
2848 assert!(
2849 !err.to_string().contains("must not precede"),
2850 "D1 must be the refuser, not E2, got: {err}"
2851 );
2852 assert_eq!(
2853 calls.load(Ordering::SeqCst),
2854 0,
2855 "the validator was invoked on arguments the schema already refused"
2856 );
2857 }
2858
2859 /// The joint test also present in plan 03: turning off one enforcement must
2860 /// never silently turn off another.
2861 #[tokio::test]
2862 async fn a_registered_validator_still_runs_with_enforce_input_schema_false() {
2863 let calls = Arc::new(AtomicUsize::new(0));
2864 let tools = synthesize_from_config_and_hooks(&cfg(false), &hooks(&calls)).expect("synth");
2865 let (_name, _info, handler) = &tools[0];
2866
2867 // Half one: the SCHEMA check is off, so an undeclared key is accepted.
2868 let err = handler
2869 .handle(json!({ "start": 2, "end": 10, "undeclared": 1 }), extra())
2870 .await
2871 .expect_err("no connector is wired");
2872 assert!(
2873 !err.to_string().contains("undeclared"),
2874 "with enforce_input_schema=false an undeclared key must be accepted, got: {err}"
2875 );
2876
2877 // Half two: the VALIDATOR still refuses.
2878 let err = handler
2879 .handle(json!({ "start": 10, "end": 2 }), extra())
2880 .await
2881 .expect_err("the validator refuses");
2882 assert!(
2883 err.to_string().contains("`end` must not precede `start`"),
2884 "a registered validator must survive the schema opt-out, got: {err}"
2885 );
2886 assert_eq!(calls.load(Ordering::SeqCst), 2);
2887 }
2888
2889 #[tokio::test]
2890 async fn a_tool_with_no_registered_validator_runs_d1_only() {
2891 let tools =
2892 synthesize_from_config_and_hooks(&cfg(true), &ToolkitHooks::default()).expect("synth");
2893 let (_name, _info, handler) = &tools[0];
2894 // D1 still refuses a schema violation.
2895 handler
2896 .handle(json!({ "start": "ten", "end": 2 }), extra())
2897 .await
2898 .expect_err("D1 refuses");
2899 // And a schema-valid call reaches the inner handler (which has no connector).
2900 let err = handler
2901 .handle(json!({ "start": 10, "end": 2 }), extra())
2902 .await
2903 .expect_err("no connector is wired");
2904 assert!(!err.to_string().contains("must not precede"));
2905 }
2906
2907 /// `handle_output` must validate too, or an inner handler that overrides it
2908 /// becomes a path with schema enforcement and no custom rule.
2909 #[tokio::test]
2910 async fn handle_output_runs_the_validator_as_well() {
2911 let calls = Arc::new(AtomicUsize::new(0));
2912 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2913 let (_name, _info, handler) = &tools[0];
2914 let err = handler
2915 .handle_output(json!({ "start": 10, "end": 2 }), extra())
2916 .await
2917 .expect_err("the validator refuses");
2918 assert!(
2919 err.to_string().contains("`end` must not precede `start`"),
2920 "handle_output must run the validator too, got: {err}"
2921 );
2922 assert_eq!(calls.load(Ordering::SeqCst), 1);
2923 }
2924}
2925
2926/// The once-at-startup enforcement report's line formats (Phase 128 D-07).
2927#[cfg(all(test, feature = "input-validation"))]
2928mod enforcement_report {
2929 use crate::config::ServerConfig;
2930 use crate::policy::{
2931 render_validation_report, ArgumentRefusal, ArgumentValidator, ReportLevel, ToolkitHooks,
2932 };
2933 use serde_json::Value;
2934 use std::sync::Arc;
2935
2936 struct Never;
2937 impl ArgumentValidator for Never {
2938 fn validate(&self, _args: &Value) -> Result<(), ArgumentRefusal> {
2939 Err(ArgumentRefusal::new("disabled"))
2940 }
2941 }
2942
2943 fn cfg(extra_validation: &str) -> ServerConfig {
2944 let toml = format!(
2945 r#"
2946[server]
2947name = "report"
2948version = "0.1.0"
2949
2950[server.validation]
2951{extra_validation}
2952
2953[[tools]]
2954name = "get_thing"
2955description = "Get a thing"
2956path = "/things/{{id}}"
2957method = "GET"
2958
2959[[tools.parameters]]
2960name = "id"
2961type = "string"
2962required = true
2963pattern = "^[0-9]+$"
2964"#
2965 );
2966 ServerConfig::from_toml_strict_validated(&toml).expect("parse")
2967 }
2968
2969 fn texts(lines: &[crate::policy::ReportLine]) -> String {
2970 lines
2971 .iter()
2972 .map(|l| l.text.clone())
2973 .collect::<Vec<_>>()
2974 .join("\n")
2975 }
2976
2977 #[test]
2978 fn a_fully_enforcing_config_states_that_no_opt_out_is_active() {
2979 let lines = render_validation_report(&cfg(""), &ToolkitHooks::default());
2980 let joined = texts(&lines);
2981 assert!(
2982 joined.contains("input validation: schema_check=ON"),
2983 "{joined}"
2984 );
2985 assert!(
2986 joined.contains("tool 'get_thing' enforces"),
2987 "one line per tool: {joined}"
2988 );
2989 assert!(
2990 joined.contains("no [server.validation] opt-out is active"),
2991 "the report must state the ABSENCE of an opt-out, not stay silent: {joined}"
2992 );
2993 assert!(
2994 joined.contains("E1 RequestPolicy registered=false"),
2995 "{joined}"
2996 );
2997 assert!(
2998 joined.contains("no E2 ArgumentValidator is registered"),
2999 "{joined}"
3000 );
3001 assert!(
3002 lines.iter().all(|l| l.level == ReportLevel::Info),
3003 "a fully enforcing config emits no warning"
3004 );
3005 }
3006
3007 #[test]
3008 fn every_active_opt_out_is_reported_at_warn_level() {
3009 let lines = render_validation_report(
3010 &cfg("enforce_input_schema = false\ndefault_max_length = 0\nadditional_properties = true"),
3011 &ToolkitHooks::default(),
3012 );
3013 let joined = texts(&lines);
3014 assert!(joined.contains("schema_check=OFF"), "{joined}");
3015 let warns: Vec<&str> = lines
3016 .iter()
3017 .filter(|l| l.level == ReportLevel::Warn)
3018 .map(|l| l.text.as_str())
3019 .collect();
3020 assert!(
3021 warns.len() >= 4,
3022 "an enforcement that is OFF must never read as on; got {warns:#?}"
3023 );
3024 assert!(
3025 warns.iter().any(|w| w.contains("opt-out ACTIVE")),
3026 "{warns:#?}"
3027 );
3028 }
3029
3030 #[test]
3031 fn a_validator_for_an_undeclared_tool_name_is_warned_not_refused() {
3032 let hooks = ToolkitHooks::default()
3033 .with_argument_validator("get_thing", Arc::new(Never))
3034 .with_argument_validator("typoed_name", Arc::new(Never));
3035 let lines = render_validation_report(&cfg(""), &hooks);
3036 let joined = texts(&lines);
3037 assert!(
3038 joined.contains("E2 ArgumentValidator registered for get_thing, typoed_name"),
3039 "{joined}"
3040 );
3041 let warns: Vec<&str> = lines
3042 .iter()
3043 .filter(|l| l.level == ReportLevel::Warn)
3044 .map(|l| l.text.as_str())
3045 .collect();
3046 assert_eq!(warns.len(), 1, "exactly the typo warns: {warns:#?}");
3047 assert!(warns[0].contains("'typoed_name'"), "{:?}", warns[0]);
3048 assert!(warns[0].contains("will never run"), "{:?}", warns[0]);
3049 }
3050
3051 /// SC-7: the report is built from declarations, so it cannot carry request
3052 /// data. Asserted rather than trusted, because the log is a channel.
3053 #[test]
3054 fn the_report_never_echoes_an_argument_value() {
3055 let lines = render_validation_report(&cfg(""), &ToolkitHooks::default());
3056 let joined = texts(&lines);
3057 for forbidden in ["Bearer", "app_key", "super-secret"] {
3058 assert!(!joined.contains(forbidden), "{joined}");
3059 }
3060 }
3061}