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 synthesize_http_inner(
957 config,
958 connector,
959 |decl| {
960 let handler =
961 ScriptToolHandler::new(decl, http_exec.clone(), exec_config.clone(), validation)?;
962 let info = handler.tool_info.clone();
963 let arc: Arc<dyn ToolHandler> = Arc::new(handler);
964 Ok((info, arc))
965 },
966 hooks,
967 )
968}
969
970/// Shared synthesizer body for the single-call HTTP entry points.
971///
972/// `build_script_tool` is invoked for each `script` tool: the single-call-only
973/// entry point passes a closure that returns the typed Plan 05 / `openapi-code-mode`
974/// seam error, while the OpenAPI Code Mode entry point passes a closure that
975/// constructs a [`ScriptToolHandler`]. Decomposed per PATTERNS §Pattern G to keep
976/// the per-tool loop body under cog ≤25.
977#[cfg(feature = "http")]
978fn synthesize_http_inner(
979 config: &ServerConfig,
980 connector: Arc<dyn HttpConnector>,
981 mut build_script_tool: impl FnMut(&ToolDecl) -> Result<(ToolInfo, Arc<dyn ToolHandler>)>,
982 hooks: &ToolkitHooks,
983) -> Result<Vec<SynthesizedTool>> {
984 let validation = &config.server.validation;
985 let mut out = Vec::with_capacity(config.tools.len());
986 for decl in &config.tools {
987 if decl.is_script_tool() {
988 let (info, handler) = build_script_tool(decl)?;
989 // Push site 2 of 3 (SCRIPT tool) — D1 enforcement. This site is
990 // SEPARATE from the HTTP push below because of the `continue`; wrapping
991 // only the HTTP push would leave every script tool unvalidated.
992 let handler = enforce_input_schema(handler, &info, decl, validation, hooks);
993 out.push((decl.name.clone(), info, handler));
994 continue;
995 }
996
997 // Single-call requires BOTH path and method. A `[[tools]]` that is
998 // neither a valid single-call nor a script tool is rejected (T-90-03-04).
999 let (path, method) = match (decl.path.as_deref(), decl.method.as_deref()) {
1000 (Some(p), Some(m)) => (p, m),
1001 _ => {
1002 return Err(ToolkitError::Synth(format!(
1003 "tool '{}' is not a valid single-call tool: both `path` and `method` are required",
1004 decl.name
1005 )));
1006 },
1007 };
1008
1009 let operation = build_operation(path, method, decl);
1010 let info = build_tool_info(decl, validation);
1011 let handler: Arc<dyn ToolHandler> = Arc::new(HttpToolHandler {
1012 info: info.clone(),
1013 operation,
1014 connector: connector.clone(),
1015 });
1016 // Push site 3 of 3 (single-call HTTP handler) — D1 enforcement + E2 validator.
1017 let handler = enforce_input_schema(handler, &info, decl, validation, hooks);
1018 out.push((decl.name.clone(), info, handler));
1019 }
1020 Ok(out)
1021}
1022
1023/// Build the [`Operation`] for a single-call tool from its `path` template,
1024/// `method`, declared parameters, and per-tool `base_url`.
1025///
1026/// Path parameters are the `{...}` segments of the path template. Every other
1027/// declared `[[tools.parameters]]` becomes a QUERY parameter, or — when the method
1028/// carries a request body (`POST`/`PUT`/`PATCH`) — a
1029/// [`ParameterLocation::Body`] parameter that
1030/// [`crate::http::HttpClient`]'s `build_body` folds into the JSON payload. The
1031/// per-tool `base_url` is reflected onto the [`Operation`] (Codex MEDIUM — never
1032/// dropped).
1033///
1034/// # Agreement with `ToolDecl::param_position` — structural, not documentary
1035///
1036/// Both splits this function performs read a shared helper, so neither can drift
1037/// from [`crate::config::ToolDecl::param_position`]:
1038///
1039/// - the PATH split and `param_position`'s `Path` arm both read
1040/// [`crate::config::path_placeholder_names`];
1041/// - the QUERY/BODY split and `param_position`'s `Query`/`Body` arms both read
1042/// `crate::config::method_carries_request_body`, which is also the sole source of
1043/// [`Operation::has_request_body`].
1044///
1045/// That second agreement is Phase 128 CR-02/CR-03. Before it, this function marked
1046/// every non-path declared parameter `ParameterLocation::Query` regardless of
1047/// method while `param_position` classified a mutating tool's as `Body`, and the
1048/// divergence was documented here as deliberate. It was not survivable: a `POST`
1049/// tool's declared parameters travelled in the URL — so the D3 cap was withheld
1050/// from values that genuinely land in a request line — and `build_body`, which
1051/// collects only args ABSENT from `operation.parameters`, found nothing, so no
1052/// payload reached the backend at all once `additionalProperties: false` began to
1053/// be enforced.
1054///
1055/// D-05 is still honoured, and now by the routing rather than despite it: a
1056/// `Body`-located parameter really is a payload field, and
1057/// `crate::config::default_cap_applies` emits no default `maxLength` for it.
1058#[cfg(feature = "http")]
1059fn build_operation(path: &str, method: &str, decl: &ToolDecl) -> Operation {
1060 let method_upper = method.to_uppercase();
1061 let path_param_names: Vec<&str> = crate::config::path_placeholder_names(path).collect();
1062
1063 let mut parameters = Vec::with_capacity(decl.parameters.len());
1064 // Path params (template `{...}` segments) — always required.
1065 //
1066 // Phase 128 D4(b): this loop iterates the TEMPLATE, not `decl.parameters`, so
1067 // the declared narrowing is looked up BY NAME and falls back to "no declared
1068 // rules" when the template names a segment the config never declared. Such a
1069 // parameter still gets the unconditional character floor and the always-on cap
1070 // at substitution time — it simply gets no narrowing on top (D-10).
1071 for name in &path_param_names {
1072 let declared = decl.parameters.iter().find(|p| p.name == **name);
1073 parameters.push(
1074 Parameter::new((*name).to_string(), ParameterLocation::Path, true).with_rules(
1075 declared.and_then(|p| p.pattern.clone()),
1076 declared.and_then(|p| p.max_length),
1077 // D-11: the config is the ONE legitimate source of this permission.
1078 declared.is_some_and(|p| p.allow_slash),
1079 ),
1080 );
1081 }
1082 // Remaining declared params → the QUERY STRING, or the JSON BODY when the
1083 // method carries one (Phase 128 CR-02).
1084 //
1085 // `has_request_body` and this location are derived from the SAME
1086 // `method_carries_request_body` predicate `ToolDecl::param_position` reads, so
1087 // a `Body`-located parameter on a body-less request is not constructible and
1088 // the D3 cap's scope cannot drift from the request's actual routing.
1089 let has_request_body = crate::config::method_carries_request_body(&method_upper);
1090 let non_path_location = if has_request_body {
1091 ParameterLocation::Body
1092 } else {
1093 ParameterLocation::Query
1094 };
1095 for p in &decl.parameters {
1096 if path_param_names.iter().any(|n| *n == p.name) {
1097 continue;
1098 }
1099 parameters.push(
1100 Parameter::new(p.name.clone(), non_path_location, p.required).with_rules(
1101 p.pattern.clone(),
1102 p.max_length,
1103 p.allow_slash,
1104 ),
1105 );
1106 }
1107
1108 Operation {
1109 method: method_upper,
1110 path: path.to_string(),
1111 parameters,
1112 has_request_body,
1113 base_url: decl.base_url.clone(),
1114 }
1115}
1116
1117/// Crate-private handler for a single-call HTTP tool (Phase 90 OAPI-02a).
1118///
1119/// Holds the synthesized [`ToolInfo`], the built [`Operation`], and the shared
1120/// [`HttpConnector`]. [`ToolHandler::metadata`] returns `Some(self.info.clone())`
1121/// (the same RESEARCH §Risks #2 invariant the SQL handler upholds); `handle()`
1122/// calls [`HttpConnector::execute`] and returns the JSON response.
1123#[cfg(feature = "http")]
1124struct HttpToolHandler {
1125 info: ToolInfo,
1126 operation: Operation,
1127 connector: Arc<dyn HttpConnector>,
1128}
1129
1130#[cfg(feature = "http")]
1131#[async_trait]
1132impl ToolHandler for HttpToolHandler {
1133 async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> pmcp::Result<Value> {
1134 // T-90-03-01: arg injection is bounded by TWO checks, both of which run
1135 // before this handler's connector call and both of which live in this
1136 // repository rather than "upstream":
1137 //
1138 // (1) the object-envelope schema (additionalProperties:false) is checked by
1139 // `pmcp::server::schema_validation::validate_input`, called from the
1140 // `ValidatingToolHandler` decorator that `enforce_input_schema` wraps
1141 // around this handler at its push site — so a call carrying an
1142 // undeclared key never reaches `handle` at all. Conditional on the
1143 // `input-validation` feature and on `[server.validation]
1144 // enforce_input_schema` not being `false`. Backed by
1145 // `tests/input_validation_acceptance.rs::input_validation_refuses_undeclared_argument_without_contacting_upstream`,
1146 // which fails if the decorator or its `validate_input` call is removed.
1147 //
1148 // (2) path substitution touches only declared `{params}`, and EVERY
1149 // substituted value additionally faces
1150 // `pmcp::server::schema_validation::validate_path_placeholder` inside
1151 // `HttpClient::substitute_path`, with the composed result facing
1152 // `validate_resolved_path` through `check_composed_path` before
1153 // dispatch. Backed by
1154 // `tests/curated_path_injection.rs::curated_path_injection_refuses_traversal_via_a_placeholder_value`
1155 // and `..._refuses_a_query_via_a_placeholder_value`, with
1156 // `..._accepts_a_compliant_call_with_one_upstream_request` as the
1157 // passing control.
1158 //
1159 // Until Phase 128 this comment located the envelope check somewhere
1160 // "upstream" of here (the retired phrasing is quoted in full in
1161 // `128-10-SUMMARY.md` and deliberately nowhere in `src/`, so the SC-6 grep
1162 // gate keeps distinguishing a surviving claim from a note about one).
1163 // Core `pmcp`'s `tools/call` dispatch does not validate request arguments
1164 // against a declared `inputSchema` — that wiring is deliberately deferred
1165 // (D-01) — so the claim named a mitigation that did not exist. Restated
1166 // rather than deleted, because as of this phase it is true and local.
1167 // The connector's Display is redaction-safe (T-90-01-01); no URL/credential
1168 // reaches the client error.
1169 //
1170 // Phase 128 E1: `execute_for_tool`, not `execute`, so a registered
1171 // `RequestPolicy` is told WHICH tool the call came from. An `Operation`
1172 // describes an endpoint and cannot carry a tool name; the default trait
1173 // body delegates to `execute`, so an out-of-repo connector is unaffected.
1174 self.connector
1175 .execute_for_tool(&self.info.name, &self.operation, &args)
1176 .await
1177 .map_err(|e| pmcp::Error::Internal(format!("connector error: {e}")))
1178 }
1179
1180 fn metadata(&self) -> Option<ToolInfo> {
1181 Some(self.info.clone())
1182 }
1183}
1184
1185// -----------------------------------------------------------------------------
1186// Script-tool handler (Phase 90 OAPI-02b / D-01 / D-02) — feature
1187// `openapi-code-mode`
1188// -----------------------------------------------------------------------------
1189
1190/// Crate-private handler for a **script** `[[tools]]` entry (OAPI-02b / D-01).
1191///
1192/// A script tool runs admin-authored embedded JS through the EXACT SAME
1193/// `pmcp_code_mode` engine that Code Mode uses (D-02 — one engine, two
1194/// surfaces): [`pmcp_code_mode::PlanCompiler`] compiles the `script` to an
1195/// execution plan, then [`pmcp_code_mode::PlanExecutor`] over the shared
1196/// [`HttpCodeExecutor`] walks it. The client's validated `args` are bound to the
1197/// `args` variable BEFORE the script runs — identical to the `JsCodeExecutor`
1198/// path's `set_variable("args", …)`, which is what makes the engine-parity proof
1199/// (Plan 05 Task 2) hold byte-for-byte.
1200///
1201/// # No token cycle (Pitfall 7 / T-90-05-01)
1202///
1203/// A script tool is admin-authored + trusted (like a `sql=` curated query), so it
1204/// skips the Code Mode validation + HMAC-token gate entirely. It is bounded ONLY by
1205/// the [`ExecutionConfig`] caps (`max_api_calls`, `max_loop_iterations`,
1206/// `timeout_seconds`) the [`PlanExecutor`](pmcp_code_mode::PlanExecutor) enforces,
1207/// and by the `PlanCompiler`-accepted JS subset (no `eval` / FFI).
1208///
1209/// # Feature gate (RESEARCH Pitfall 4)
1210///
1211/// Gated `openapi-code-mode` (the umbrella that forwards
1212/// `pmcp-code-mode/js-runtime`) — `PlanCompiler` / `PlanExecutor` are NOT in
1213/// scope under bare `code-mode`, so the light / curated-only build (`http
1214/// code-mode`) compiles without this type (single-call only).
1215#[cfg(feature = "openapi-code-mode")]
1216struct ScriptToolHandler {
1217 /// The admin-authored script, compiled ONCE at synthesis (the body is fixed
1218 /// content). Executed per `handle` over a fresh
1219 /// [`PlanExecutor`](pmcp_code_mode::PlanExecutor).
1220 plan: pmcp_code_mode::ExecutionPlan,
1221 /// The SAME executor instance that feeds Code Mode (D-02). Cloned per request
1222 /// to construct a fresh [`PlanExecutor`](pmcp_code_mode::PlanExecutor).
1223 http_exec: HttpCodeExecutor,
1224 /// The execution bounds (Pitfall 7 — the only limit on an admin script).
1225 exec_config: ExecutionConfig,
1226 /// The synthesized `ToolInfo` (object-envelope schema from
1227 /// `[[tools.parameters]]`, `additionalProperties:false`).
1228 ///
1229 /// `args` are checked against THIS schema before the script runs (T-90-05-03),
1230 /// by `pmcp::server::schema_validation::validate_input` inside the
1231 /// `ValidatingToolHandler` decorator that [`enforce_input_schema`] wraps
1232 /// around this handler at its push site — so a refusal happens before
1233 /// [`ToolHandler::handle`] is entered and therefore before
1234 /// `PlanExecutor::execute` makes any backend call.
1235 ///
1236 /// Conditional on the `input-validation` feature and on `[server.validation]
1237 /// enforce_input_schema` not being `false`; with either off,
1238 /// [`enforce_input_schema`] logs the opt-out and returns the handler undecorated.
1239 ///
1240 /// Backed by
1241 /// `tests/script_tool.rs::script_tool_refuses_a_schema_violating_arg_before_the_script_runs`,
1242 /// which asserts the refusal AND that the mock backend observed zero requests —
1243 /// it fails if the decorator or its `validate_input` call is removed. The
1244 /// sibling `script_tool_args_max_lines_binding_is_honored` asserts argument
1245 /// BINDING, which is a different (also true) property; before this phase it was
1246 /// the only row carrying this threat ID, and a binding assertion is not a
1247 /// validation assertion.
1248 tool_info: ToolInfo,
1249}
1250
1251#[cfg(feature = "openapi-code-mode")]
1252impl ScriptToolHandler {
1253 /// Build a [`ScriptToolHandler`] from a script `[[tools]]` declaration,
1254 /// the shared [`HttpCodeExecutor`], and the [`ExecutionConfig`] bounds.
1255 ///
1256 /// The `tool_info` is built from `[[tools.parameters]]` via the SAME
1257 /// [`build_input_schema`] / [`build_annotations`] / [`apply_widget_meta`]
1258 /// helpers the single-call path uses, so a script tool's `args` are checked
1259 /// against an identically-shaped schema (object envelope,
1260 /// `additionalProperties:false` unless `[server.validation]
1261 /// additional_properties` opts out) by the same enforcer — one
1262 /// [`enforce_input_schema`] call per push site, one
1263 /// `pmcp::server::schema_validation::validate_input` inside
1264 /// `ValidatingToolHandler`. There is no second validator for script tools;
1265 /// see [`ScriptToolHandler::tool_info`] for the condition and the acceptance
1266 /// row.
1267 ///
1268 /// `validation` is threaded in so a script tool's schema is built under the SAME
1269 /// `[server.validation]` policy as every other tool kind — a script tool whose
1270 /// parameters escaped the D3 cap would be a hole in exactly the surface this
1271 /// phase closes. A script tool's parameters are BODY position (it declares no
1272 /// `path`/`method`), so in practice the cap does not apply to them; the point is
1273 /// that the decision is made by one rule rather than by which synthesizer ran.
1274 ///
1275 /// # Errors
1276 ///
1277 /// Returns [`ToolkitError::Synth`] if the declaration carries no `script`
1278 /// (a defensive guard — callers route only `is_script_tool()` entries here),
1279 /// or if the script fails to compile (surfaced here at server build time,
1280 /// failing fast rather than on the first tool call).
1281 fn new(
1282 decl: &ToolDecl,
1283 http_exec: HttpCodeExecutor,
1284 exec_config: ExecutionConfig,
1285 validation: &ValidationSection,
1286 ) -> Result<Self> {
1287 let script = decl.script.clone().ok_or_else(|| {
1288 ToolkitError::Synth(format!(
1289 "tool '{}' has no `script` body — not a script tool",
1290 decl.name
1291 ))
1292 })?;
1293 // Compile the admin-authored JS ONCE at synthesis time — the script is
1294 // fixed content, so compiling per request would re-run a full SWC parse
1295 // on the hot path (the PlanCompiler-accepted subset, no eval / FFI, is
1296 // the static bound). A compile error surfaces here at server build.
1297 let plan = pmcp_code_mode::PlanCompiler::with_config(&exec_config)
1298 .compile_code(&script)
1299 .map_err(|e| {
1300 ToolkitError::Synth(format!(
1301 "tool '{}' script failed to compile: {e}",
1302 decl.name
1303 ))
1304 })?;
1305 let tool_info = build_tool_info(decl, validation);
1306 Ok(Self {
1307 plan,
1308 // Phase 128 E1: this handler owns a per-tool CLONE of the shared
1309 // executor, which is the one place a script tool's name can be
1310 // attached — `HttpExecutor::execute_request` is a `pmcp-code-mode`
1311 // trait method and carries no tool name.
1312 http_exec: http_exec.with_tool_label(&decl.name),
1313 exec_config,
1314 tool_info,
1315 })
1316 }
1317}
1318
1319#[cfg(feature = "openapi-code-mode")]
1320#[pmcp_code_mode::async_trait]
1321impl ToolHandler for ScriptToolHandler {
1322 /// Run the pre-compiled admin-authored script over the shared engine, binding
1323 /// the validated `args` to the `args` variable (D-02 — identical to the
1324 /// `JsCodeExecutor` path's `set_variable("args", …)`).
1325 async fn handle(&self, args: Value, extra: RequestHandlerExtra) -> pmcp::Result<Value> {
1326 // (1) Execute the plan (compiled once in `new`) over a PER-REQUEST clone
1327 // of the shared HttpCodeExecutor (D-02), threading the captured
1328 // inbound MCP token (Plan 90-10 / OAPI-03 / OAPI-05) so an
1329 // `oauth_passthrough` backend forwards it. Bounded by ExecutionConfig
1330 // (Pitfall 7 — no token cycle, only these caps).
1331 let mut executor = pmcp_code_mode::PlanExecutor::new(
1332 crate::code_mode::request_executor_from_extra(&self.http_exec, &extra),
1333 self.exec_config.clone(),
1334 );
1335 // (2) Bind the client args to `args` (T-90-05-03) — byte-identical to
1336 // compile_and_execute's set_variable("args", …). These args have
1337 // ALREADY been checked against `self.tool_info.input_schema` by
1338 // `pmcp::server::schema_validation::validate_input`, in the
1339 // `ValidatingToolHandler` decorator wrapped around this handler — a
1340 // violating call never reaches this line. That is a fact about the
1341 // DECORATOR, not about this function: `handle` performs no validation
1342 // of its own and must not be read as if it did. Condition and
1343 // acceptance row: see `ScriptToolHandler::tool_info`.
1344 executor.set_variable("args", args);
1345
1346 let result = executor
1347 .execute(&self.plan)
1348 .await
1349 .map_err(|e| pmcp::Error::Internal(format!("script execution failed: {e}")))?;
1350 Ok(result.value)
1351 }
1352
1353 fn metadata(&self) -> Option<ToolInfo> {
1354 Some(self.tool_info.clone())
1355 }
1356}
1357
1358// -----------------------------------------------------------------------------
1359// Tests — Plan 05 Task 1 (RED) → GREEN in Task 2
1360// -----------------------------------------------------------------------------
1361
1362#[cfg(test)]
1363mod tests {
1364 use super::*;
1365 use crate::config::{
1366 AnnotationsDecl, ItemsDecl, ParamDecl, ServerConfig, ServerSection, ToolDecl,
1367 ValidationSection,
1368 };
1369 use serde_json::Value;
1370
1371 /// Construct a minimal `ServerConfig` that satisfies `validate()` (non-empty
1372 /// `name` + `version`) so the synthesizer path is the system under test —
1373 /// not the parser/validator from Plan 04.
1374 fn cfg_with_tools(tools: Vec<ToolDecl>) -> ServerConfig {
1375 ServerConfig {
1376 server: ServerSection {
1377 name: "demo".to_string(),
1378 version: "0.1.0".to_string(),
1379 ..Default::default()
1380 },
1381 tools,
1382 ..Default::default()
1383 }
1384 }
1385
1386 #[test]
1387 fn empty_tools_returns_empty_vec() {
1388 let cfg = cfg_with_tools(vec![]);
1389 let out = synthesize_from_config(&cfg).expect("synthesize");
1390 assert_eq!(out.len(), 0);
1391 }
1392
1393 #[test]
1394 fn one_tool_no_params_yields_object_schema() {
1395 let cfg = cfg_with_tools(vec![ToolDecl {
1396 name: "ping".to_string(),
1397 description: Some("Ping the server".to_string()),
1398 parameters: vec![],
1399 annotations: None,
1400 ..Default::default()
1401 }]);
1402 let out = synthesize_from_config(&cfg).expect("synthesize");
1403 assert_eq!(out.len(), 1);
1404 let (name, info, _handler) = &out[0];
1405 assert_eq!(name, "ping");
1406 assert_eq!(info.name, "ping");
1407 assert_eq!(info.description.as_deref(), Some("Ping the server"));
1408 let schema = &info.input_schema;
1409 assert_eq!(schema["type"], Value::String("object".to_string()));
1410 assert_eq!(schema["properties"], serde_json::json!({}));
1411 assert_eq!(schema["required"], serde_json::json!([]));
1412 assert_eq!(schema["additionalProperties"], Value::Bool(false));
1413 }
1414
1415 #[test]
1416 fn required_and_optional_params_partitioned() {
1417 let cfg = cfg_with_tools(vec![ToolDecl {
1418 name: "search".to_string(),
1419 description: Some("Search".to_string()),
1420 parameters: vec![
1421 ParamDecl {
1422 name: "query".to_string(),
1423 param_type: Some("string".to_string()),
1424 description: Some("the search query".to_string()),
1425 required: true,
1426 ..Default::default()
1427 },
1428 ParamDecl {
1429 name: "max_results".to_string(),
1430 param_type: Some("integer".to_string()),
1431 description: Some("maximum result count".to_string()),
1432 required: false,
1433 default: Some(toml::Value::Integer(100)),
1434 minimum: Some(1.0),
1435 maximum: Some(1000.0),
1436 ..Default::default()
1437 },
1438 ],
1439 ..Default::default()
1440 }]);
1441 let out = synthesize_from_config(&cfg).expect("synthesize");
1442 let (_, info, _) = &out[0];
1443 let schema = &info.input_schema;
1444 assert_eq!(schema["required"], serde_json::json!(["query"]));
1445 let props = schema["properties"].as_object().expect("object");
1446 assert_eq!(props["query"]["type"], "string");
1447 assert_eq!(props["max_results"]["type"], "integer");
1448 assert_eq!(props["max_results"]["minimum"], serde_json::json!(1.0));
1449 assert_eq!(props["max_results"]["maximum"], serde_json::json!(1000.0));
1450 assert_eq!(props["max_results"]["default"], serde_json::json!(100));
1451 }
1452
1453 #[test]
1454 fn param_max_length_propagates() {
1455 let cfg = cfg_with_tools(vec![ToolDecl {
1456 name: "echo".to_string(),
1457 description: Some("Echo".to_string()),
1458 parameters: vec![ParamDecl {
1459 name: "text".to_string(),
1460 param_type: Some("string".to_string()),
1461 description: Some("input text".to_string()),
1462 required: true,
1463 max_length: Some(256),
1464 ..Default::default()
1465 }],
1466 ..Default::default()
1467 }]);
1468 let out = synthesize_from_config(&cfg).expect("synthesize");
1469 let (_, info, _) = &out[0];
1470 assert_eq!(
1471 info.input_schema["properties"]["text"]["maxLength"],
1472 serde_json::json!(256)
1473 );
1474 }
1475
1476 #[test]
1477 fn annotations_round_trip_via_fluent_builder() {
1478 let cfg = cfg_with_tools(vec![ToolDecl {
1479 name: "destroy_all".to_string(),
1480 description: Some("Destroy all data (test)".to_string()),
1481 parameters: vec![],
1482 annotations: Some(AnnotationsDecl {
1483 read_only_hint: false,
1484 destructive_hint: true,
1485 idempotent_hint: false,
1486 open_world_hint: false,
1487 cost_hint: Some("high".to_string()),
1488 }),
1489 ..Default::default()
1490 }]);
1491 let out = synthesize_from_config(&cfg).expect("synthesize");
1492 let (_, info, _) = &out[0];
1493 let ann = info.annotations.as_ref().expect("annotations");
1494 assert_eq!(ann.read_only_hint, Some(false));
1495 assert_eq!(ann.destructive_hint, Some(true));
1496 assert_eq!(ann.idempotent_hint, Some(false));
1497 assert_eq!(ann.open_world_hint, Some(false));
1498 }
1499
1500 /// REVIEWS H1 (in-plan widget_meta flip — no SqliteConnector dependency).
1501 ///
1502 /// When a `[[tools]]` entry declares `ui_resource_uri`, the synthesized
1503 /// `ToolInfo` must carry widget metadata so pmcp core's
1504 /// `with_widget_enrichment` (gated on `info.widget_meta().is_some()`)
1505 /// populates `structuredContent` (D-06). The flip lives in the shared
1506 /// `synthesize_inner` helper, so it fires for BOTH entry points; this test
1507 /// exercises it via the no-connector `synthesize_from_config` path.
1508 #[test]
1509 fn widget_meta_flips_when_ui_resource_uri_present() {
1510 let cfg = cfg_with_tools(vec![ToolDecl {
1511 name: "widget_tool".to_string(),
1512 description: Some("renders a widget".to_string()),
1513 ui_resource_uri: Some("ui://test".to_string()),
1514 ..Default::default()
1515 }]);
1516 let out = synthesize_from_config(&cfg).expect("synthesize");
1517 let (_, info, _) = &out[0];
1518 assert!(
1519 info.widget_meta().is_some(),
1520 "ui_resource_uri set ⇒ widget_meta() must be Some so D-06 structuredContent fires"
1521 );
1522 }
1523
1524 /// REVIEWS H1 negative case — a tool WITHOUT `ui_resource_uri` must NOT
1525 /// carry widget metadata (T-84-03-03: no accidental flip on non-widget
1526 /// tools).
1527 #[test]
1528 fn widget_meta_absent_when_ui_resource_uri_none() {
1529 let cfg = cfg_with_tools(vec![ToolDecl {
1530 name: "plain_tool".to_string(),
1531 description: Some("no widget".to_string()),
1532 ui_resource_uri: None,
1533 ..Default::default()
1534 }]);
1535 let out = synthesize_from_config(&cfg).expect("synthesize");
1536 let (_, info, _) = &out[0];
1537 assert!(
1538 info.widget_meta().is_none(),
1539 "ui_resource_uri absent ⇒ widget_meta() must be None (no accidental flip)"
1540 );
1541 }
1542
1543 #[tokio::test]
1544 async fn synthesized_handler_metadata_returns_some() {
1545 let cfg = cfg_with_tools(vec![ToolDecl {
1546 name: "ping".to_string(),
1547 description: Some("ping".to_string()),
1548 parameters: vec![],
1549 annotations: None,
1550 ..Default::default()
1551 }]);
1552 let out = synthesize_from_config(&cfg).expect("synthesize");
1553 let (_, expected_info, handler) = &out[0];
1554 let actual = handler.metadata();
1555 assert!(
1556 actual.is_some(),
1557 "RESEARCH §Risks #2 invariant: SynthesizedToolHandler::metadata() MUST return Some(ToolInfo)"
1558 );
1559 assert_eq!(actual.unwrap().name, expected_info.name);
1560 }
1561
1562 /// A `[[tools]]` declaration with one defaulted `limit` param (default=20),
1563 /// used to exercise [`extract_named_params`]'s default / explicit-null logic.
1564 fn decl_with_limit_default() -> ToolDecl {
1565 ToolDecl {
1566 name: "search".to_string(),
1567 description: Some("Search".to_string()),
1568 sql: Some("SELECT * FROM t LIMIT :limit".to_string()),
1569 parameters: vec![ParamDecl {
1570 name: "limit".to_string(),
1571 param_type: Some("integer".to_string()),
1572 description: Some("row limit".to_string()),
1573 required: false,
1574 default: Some(toml::Value::Integer(20)),
1575 ..Default::default()
1576 }],
1577 ..Default::default()
1578 }
1579 }
1580
1581 #[test]
1582 fn extract_named_params_applies_default_when_absent() {
1583 // `{}` → declared default (20) is bound (the reference search/list calls
1584 // rely on this so an omitted :limit never binds NULL).
1585 let decl = decl_with_limit_default();
1586 let params = extract_named_params(&decl, &serde_json::json!({}));
1587 assert_eq!(params, vec![("limit".to_string(), serde_json::json!(20))]);
1588 }
1589
1590 #[test]
1591 fn extract_named_params_explicit_null_applies_default() {
1592 // 85-10 WR-02 secondary fix: an EXPLICIT JSON null must NOT bind
1593 // `LIMIT NULL` — it falls through to the declared default exactly like
1594 // an omitted key.
1595 let decl = decl_with_limit_default();
1596 let params = extract_named_params(&decl, &serde_json::json!({ "limit": null }));
1597 assert_eq!(
1598 params,
1599 vec![("limit".to_string(), serde_json::json!(20))],
1600 "explicit null must apply the declared default, not bind LIMIT NULL"
1601 );
1602 }
1603
1604 #[test]
1605 fn extract_named_params_explicit_value_overrides_default() {
1606 // A concrete value wins over the default.
1607 let decl = decl_with_limit_default();
1608 let params = extract_named_params(&decl, &serde_json::json!({ "limit": 5 }));
1609 assert_eq!(params, vec![("limit".to_string(), serde_json::json!(5))]);
1610 }
1611
1612 // -------------------------------------------------------------------------
1613 // Phase 128 D2 — the six new `ParamDecl` keywords reach `inputSchema`
1614 // -------------------------------------------------------------------------
1615
1616 /// Fetch the synthesized property object for `param` of the single tool in
1617 /// `tools`.
1618 fn prop_of(tools: Vec<ToolDecl>, param: &str) -> Value {
1619 let cfg = cfg_with_tools(tools);
1620 let out = synthesize_from_config(&cfg).expect("synthesize");
1621 let (_name, info, _handler) = &out[0];
1622 info.input_schema["properties"][param].clone()
1623 }
1624
1625 /// D2 / SC-2: `pattern`, `minLength`, `format` and `maxItems` all reach the
1626 /// emitted `inputSchema`.
1627 #[test]
1628 fn input_schema_emits_d2_scalar_keywords() {
1629 let prop = prop_of(
1630 vec![ToolDecl {
1631 name: "lookup".to_string(),
1632 parameters: vec![ParamDecl {
1633 name: "region".to_string(),
1634 param_type: Some("string".to_string()),
1635 required: true,
1636 pattern: Some("^[A-Z]{3}$".to_string()),
1637 min_length: Some(3),
1638 format: Some("uuid".to_string()),
1639 max_items: Some(5),
1640 ..Default::default()
1641 }],
1642 ..Default::default()
1643 }],
1644 "region",
1645 );
1646 assert_eq!(prop["pattern"], serde_json::json!("^[A-Z]{3}$"));
1647 assert_eq!(prop["minLength"], serde_json::json!(3));
1648 assert_eq!(prop["format"], serde_json::json!("uuid"));
1649 assert_eq!(prop["maxItems"], serde_json::json!(5));
1650 }
1651
1652 /// D2 / RESEARCH Finding 1h: `items` is emitted in OBJECT form. The array
1653 /// (draft-07 tuple) form does not compile under the Draft 2020-12 pin and
1654 /// would take the whole tool's validator down.
1655 #[test]
1656 fn input_schema_emits_items_as_object_never_array() {
1657 let prop = prop_of(
1658 vec![ToolDecl {
1659 name: "batch".to_string(),
1660 parameters: vec![ParamDecl {
1661 name: "codes".to_string(),
1662 param_type: Some("array".to_string()),
1663 required: true,
1664 items: Some(ItemsDecl {
1665 item_type: Some("string".to_string()),
1666 max_length: Some(8),
1667 pattern: Some("^[a-z]+$".to_string()),
1668 }),
1669 max_items: Some(10),
1670 ..Default::default()
1671 }],
1672 ..Default::default()
1673 }],
1674 "codes",
1675 );
1676 assert!(
1677 prop["items"].is_object(),
1678 "items must be an OBJECT, got: {}",
1679 prop["items"]
1680 );
1681 assert!(
1682 !prop["items"].is_array(),
1683 "array-form items does not compile under the 2020-12 pin"
1684 );
1685 assert_eq!(
1686 prop["items"],
1687 serde_json::json!({
1688 "type": "string",
1689 "maxLength": 8,
1690 "pattern": "^[a-z]+$",
1691 })
1692 );
1693 }
1694
1695 /// D2 edge (empty): a `ParamDecl` carrying NONE of the six new keywords emits
1696 /// exactly the five it emits today — no empty `pattern` string and no empty
1697 /// `items` object appears.
1698 #[test]
1699 fn input_schema_omits_d2_keywords_when_undeclared() {
1700 let prop = prop_of(
1701 vec![ToolDecl {
1702 name: "legacy".to_string(),
1703 parameters: vec![ParamDecl {
1704 name: "count".to_string(),
1705 param_type: Some("integer".to_string()),
1706 description: Some("how many".to_string()),
1707 required: false,
1708 minimum: Some(1.0),
1709 maximum: Some(10.0),
1710 max_length: Some(4),
1711 ..Default::default()
1712 }],
1713 ..Default::default()
1714 }],
1715 "count",
1716 );
1717 let obj = prop.as_object().expect("property object");
1718 let mut keys: Vec<&str> = obj.keys().map(String::as_str).collect();
1719 keys.sort_unstable();
1720 assert_eq!(
1721 keys,
1722 vec!["description", "maxLength", "maximum", "minimum", "type"],
1723 "exactly the five pre-D2 keywords, and no more"
1724 );
1725 for absent in ["pattern", "minLength", "format", "items", "maxItems"] {
1726 assert!(
1727 obj.get(absent).is_none(),
1728 "undeclared keyword {absent} must not be emitted"
1729 );
1730 }
1731 }
1732
1733 /// D2 edge (ordering): two synthesis runs over ONE config produce
1734 /// byte-identical `input_schema` values, so `properties` and `required` follow
1735 /// `[[tools.parameters]]` declaration order deterministically.
1736 #[test]
1737 fn input_schema_is_byte_identical_across_two_synthesis_runs() {
1738 let tools = vec![ToolDecl {
1739 name: "search".to_string(),
1740 parameters: vec![
1741 ParamDecl {
1742 name: "zebra".to_string(),
1743 param_type: Some("string".to_string()),
1744 required: true,
1745 pattern: Some("^z".to_string()),
1746 ..Default::default()
1747 },
1748 ParamDecl {
1749 name: "alpha".to_string(),
1750 param_type: Some("string".to_string()),
1751 required: true,
1752 min_length: Some(1),
1753 ..Default::default()
1754 },
1755 ParamDecl {
1756 name: "middle".to_string(),
1757 param_type: Some("integer".to_string()),
1758 required: false,
1759 ..Default::default()
1760 },
1761 ],
1762 ..Default::default()
1763 }];
1764 let cfg = cfg_with_tools(tools);
1765 let first = synthesize_from_config(&cfg).expect("synthesize")[0]
1766 .1
1767 .input_schema
1768 .to_string();
1769 let second = synthesize_from_config(&cfg).expect("synthesize")[0]
1770 .1
1771 .input_schema
1772 .to_string();
1773 assert_eq!(first, second, "synthesis must be byte-deterministic");
1774 // Declaration order, not sorted order.
1775 assert!(
1776 first.find("\"zebra\"").unwrap() < first.find("\"alpha\"").unwrap(),
1777 "properties must follow declaration order: {first}"
1778 );
1779 }
1780
1781 /// D2 edge (adjacency): `min_length == max_length` accepts exactly that length
1782 /// and refuses one code point either side, through the SAME core validator the
1783 /// D1 decorator uses.
1784 #[cfg(feature = "input-validation")]
1785 #[test]
1786 fn min_length_equal_to_max_length_accepts_exactly_that_length() {
1787 use pmcp::server::schema_validation::validate_input;
1788
1789 let cfg = cfg_with_tools(vec![ToolDecl {
1790 name: "exact".to_string(),
1791 parameters: vec![ParamDecl {
1792 name: "code".to_string(),
1793 param_type: Some("string".to_string()),
1794 required: true,
1795 min_length: Some(3),
1796 max_length: Some(3),
1797 ..Default::default()
1798 }],
1799 ..Default::default()
1800 }]);
1801 let out = synthesize_from_config(&cfg).expect("synthesize");
1802 let schema = &out[0].1.input_schema;
1803
1804 validate_input(schema, Some(&serde_json::json!({ "code": "abc" })), None)
1805 .expect("exactly three code points must be accepted");
1806 validate_input(schema, Some(&serde_json::json!({ "code": "ab" })), None)
1807 .expect_err("two code points must be refused");
1808 validate_input(schema, Some(&serde_json::json!({ "code": "abcd" })), None)
1809 .expect_err("four code points must be refused");
1810 }
1811
1812 // -------------------------------------------------------------------------
1813 // Phase 128 D3 — position-scoped default cap and `[server.validation]`
1814 // -------------------------------------------------------------------------
1815
1816 /// Synthesize `tools` under `validation` and return the property object for
1817 /// `param` of the FIRST tool.
1818 fn prop_under(tools: Vec<ToolDecl>, validation: ValidationSection, param: &str) -> Value {
1819 let mut cfg = cfg_with_tools(tools);
1820 cfg.server.validation = validation;
1821 let out = synthesize_from_config(&cfg).expect("synthesize");
1822 out[0].1.input_schema["properties"][param].clone()
1823 }
1824
1825 /// A single-call `GET` tool declaring one path parameter and one query
1826 /// parameter, both uncapped strings.
1827 fn get_tool_with_path_and_query() -> Vec<ToolDecl> {
1828 vec![ToolDecl {
1829 name: "line_status".to_string(),
1830 path: Some("/lines/{line_id}/status".to_string()),
1831 method: Some("GET".to_string()),
1832 parameters: vec![
1833 ParamDecl {
1834 name: "line_id".to_string(),
1835 param_type: Some("string".to_string()),
1836 required: true,
1837 ..Default::default()
1838 },
1839 ParamDecl {
1840 name: "detail".to_string(),
1841 param_type: Some("string".to_string()),
1842 required: false,
1843 ..Default::default()
1844 },
1845 ],
1846 ..Default::default()
1847 }]
1848 }
1849
1850 /// D3: a PATH-position string with no `max_length` is capped at the configured
1851 /// default.
1852 #[test]
1853 fn default_cap_applies_to_path_position_string() {
1854 let prop = prop_under(
1855 get_tool_with_path_and_query(),
1856 ValidationSection::default(),
1857 "line_id",
1858 );
1859 assert_eq!(prop["maxLength"], serde_json::json!(256));
1860 }
1861
1862 /// D3: a QUERY-position string (non-path parameter of a `GET` tool) with no
1863 /// `max_length` is capped at the configured default.
1864 #[test]
1865 fn default_cap_applies_to_query_position_string() {
1866 let prop = prop_under(
1867 get_tool_with_path_and_query(),
1868 ValidationSection::default(),
1869 "detail",
1870 );
1871 assert_eq!(prop["maxLength"], serde_json::json!(256));
1872 }
1873
1874 /// D3 / D-05 / T-128-13d: a BODY-position string on a mutating single-call tool
1875 /// receives NO cap. Capping a `POST` payload's free-text field is exactly the
1876 /// breakage review note C objected to.
1877 #[test]
1878 fn default_cap_never_applies_to_body_position_string() {
1879 let tools = vec![ToolDecl {
1880 name: "add_comment".to_string(),
1881 path: Some("/issues/{id}/comments".to_string()),
1882 method: Some("POST".to_string()),
1883 parameters: vec![
1884 ParamDecl {
1885 name: "id".to_string(),
1886 param_type: Some("string".to_string()),
1887 required: true,
1888 ..Default::default()
1889 },
1890 ParamDecl {
1891 name: "body_text".to_string(),
1892 param_type: Some("string".to_string()),
1893 required: true,
1894 ..Default::default()
1895 },
1896 ],
1897 ..Default::default()
1898 }];
1899 let path_prop = prop_under(tools.clone(), ValidationSection::default(), "id");
1900 assert_eq!(
1901 path_prop["maxLength"],
1902 serde_json::json!(256),
1903 "the path parameter of a POST tool IS still capped"
1904 );
1905 let body_prop = prop_under(tools, ValidationSection::default(), "body_text");
1906 assert!(
1907 body_prop.get("maxLength").is_none(),
1908 "a POST payload field must receive no default cap, got: {body_prop}"
1909 );
1910 }
1911
1912 /// D3 edge (adjacency): a DECLARED `max_length` is never overridden and never
1913 /// merged with the default, in either direction.
1914 #[test]
1915 fn declared_max_length_wins_over_the_default_cap() {
1916 let mut tools = get_tool_with_path_and_query();
1917 tools[0].parameters[0].max_length = Some(12);
1918 let prop = prop_under(tools, ValidationSection::default(), "line_id");
1919 assert_eq!(prop["maxLength"], serde_json::json!(12));
1920 }
1921
1922 /// D3 edge (empty): `default_max_length = 0` emits no `maxLength` in ANY
1923 /// position and disables the cap entirely.
1924 #[test]
1925 fn default_max_length_zero_disables_the_cap_in_every_position() {
1926 let validation = ValidationSection {
1927 default_max_length: 0,
1928 ..Default::default()
1929 };
1930 for param in ["line_id", "detail"] {
1931 let prop = prop_under(get_tool_with_path_and_query(), validation.clone(), param);
1932 assert!(
1933 prop.get("maxLength").is_none(),
1934 "{param} must carry no maxLength when the default is 0, got: {prop}"
1935 );
1936 }
1937 }
1938
1939 /// D3 edge (boundary + encoding): the cap is counted in Unicode CODE POINTS,
1940 /// not bytes — so exactly `default_max_length` multi-byte characters are
1941 /// accepted and one more is refused, through the SAME core validator.
1942 #[cfg(feature = "input-validation")]
1943 #[test]
1944 fn default_cap_boundary_is_counted_in_code_points_not_bytes() {
1945 use pmcp::server::schema_validation::validate_input;
1946
1947 let validation = ValidationSection {
1948 default_max_length: 8,
1949 ..Default::default()
1950 };
1951 let mut cfg = cfg_with_tools(get_tool_with_path_and_query());
1952 cfg.server.validation = validation;
1953 let out = synthesize_from_config(&cfg).expect("synthesize");
1954 let schema = &out[0].1.input_schema;
1955
1956 // Each `é` is TWO bytes and ONE code point. Eight of them are 16 bytes.
1957 let at_limit: String = "é".repeat(8);
1958 let over_limit: String = "é".repeat(9);
1959 assert_eq!(
1960 at_limit.len(),
1961 16,
1962 "the fixture must actually be multi-byte"
1963 );
1964 validate_input(
1965 schema,
1966 Some(&serde_json::json!({ "line_id": at_limit })),
1967 None,
1968 )
1969 .expect("exactly 8 code points must be accepted even though they are 16 bytes");
1970 validate_input(
1971 schema,
1972 Some(&serde_json::json!({ "line_id": over_limit })),
1973 None,
1974 )
1975 .expect_err("9 code points must be refused");
1976 }
1977
1978 /// `additional_properties = true` flips the emitted envelope, re-opening the
1979 /// unknown-argument class for this server.
1980 #[test]
1981 fn additional_properties_opt_out_flips_the_envelope() {
1982 let mut cfg = cfg_with_tools(get_tool_with_path_and_query());
1983 cfg.server.validation = ValidationSection {
1984 additional_properties: true,
1985 ..Default::default()
1986 };
1987 let out = synthesize_from_config(&cfg).expect("synthesize");
1988 assert_eq!(
1989 out[0].1.input_schema["additionalProperties"],
1990 Value::Bool(true)
1991 );
1992
1993 let mut cfg = cfg_with_tools(get_tool_with_path_and_query());
1994 cfg.server.validation = ValidationSection::default();
1995 let out = synthesize_from_config(&cfg).expect("synthesize");
1996 assert_eq!(
1997 out[0].1.input_schema["additionalProperties"],
1998 Value::Bool(false),
1999 "the default must remain a closed envelope"
2000 );
2001 }
2002
2003 /// T-128-13c: `enforce_input_schema = false` skips the SCHEMA CHECK, not the
2004 /// decorator. This test pins the separation the E2 argument-validator registry
2005 /// will depend on: with the flag off an undeclared argument is ACCEPTED (schema
2006 /// off), while the inner handler's own rule still REFUSES (the non-schema
2007 /// enforcement is untouched). Without this test the two collapse back together
2008 /// on the next refactor.
2009 #[cfg(feature = "input-validation")]
2010 #[tokio::test]
2011 async fn enforce_input_schema_false_skips_the_check_not_the_decorator() {
2012 /// Stands in for an explicitly-registered argument validator: a rule that
2013 /// lives INSIDE the decorated stack and is not the JSON Schema check.
2014 struct RefusingInner;
2015
2016 #[async_trait]
2017 impl ToolHandler for RefusingInner {
2018 async fn handle(
2019 &self,
2020 _args: Value,
2021 _extra: RequestHandlerExtra,
2022 ) -> pmcp::Result<Value> {
2023 Err(pmcp::Error::Validation(
2024 "the registered validator refused".to_string(),
2025 ))
2026 }
2027 }
2028
2029 let decl = ToolDecl {
2030 name: "guarded".to_string(),
2031 parameters: vec![ParamDecl {
2032 name: "declared".to_string(),
2033 param_type: Some("string".to_string()),
2034 required: false,
2035 ..Default::default()
2036 }],
2037 ..Default::default()
2038 };
2039 let info = build_tool_info(&decl, &ValidationSection::default());
2040 let undeclared = serde_json::json!({ "not_declared_at_all": "x" });
2041
2042 // (a) enforcement ON: the SCHEMA refuses before the inner handler runs, so
2043 // the message is the schema refusal, not the inner one.
2044 let on = ValidatingToolHandler::wrap(Arc::new(RefusingInner), &info, &decl, true, None);
2045 let err = on
2046 .handle(undeclared.clone(), RequestHandlerExtra::default())
2047 .await
2048 .expect_err("an undeclared argument must be refused when enforcement is on");
2049 assert!(
2050 !err.to_string().contains("registered validator"),
2051 "the schema check must run FIRST when enforcement is on: {err}"
2052 );
2053
2054 // (b) enforcement OFF: the schema check is skipped (the undeclared argument
2055 // is accepted by it), and the inner rule STILL refuses. That is the
2056 // separation — A off must not silently turn B off.
2057 let off = ValidatingToolHandler::wrap(Arc::new(RefusingInner), &info, &decl, false, None);
2058 let err = off
2059 .handle(undeclared, RequestHandlerExtra::default())
2060 .await
2061 .expect_err("the inner (non-schema) rule must still refuse");
2062 assert!(
2063 err.to_string().contains("registered validator"),
2064 "with the schema check off, the refusal must come from the inner rule: {err}"
2065 );
2066 }
2067}
2068
2069// -----------------------------------------------------------------------------
2070// Tests — Phase 128 D4(b): `build_operation` carries the declared placeholder
2071// rules onto every `Parameter`.
2072// -----------------------------------------------------------------------------
2073
2074/// Named `build_operation` deliberately: libtest matches the FULL test path, so a
2075/// test placed in the crate's existing `mod tests` would be
2076/// `tools::tests::build_operation_…` and this plan's `--lib tools::build_operation`
2077/// verify filter would select ZERO tests while exiting 0. As a SIBLING of `tests`
2078/// at the `tools` module level the filter resolves as written. Do not fold these
2079/// into `mod tests`.
2080#[cfg(all(test, feature = "http"))]
2081mod build_operation {
2082 use super::*;
2083
2084 /// A single-call `GET` tool on `path` carrying `parameters`.
2085 fn decl(path: &str, parameters: Vec<ParamDecl>) -> ToolDecl {
2086 ToolDecl {
2087 name: "t".to_string(),
2088 description: Some("t".to_string()),
2089 path: Some(path.to_string()),
2090 method: Some("GET".to_string()),
2091 parameters,
2092 ..Default::default()
2093 }
2094 }
2095
2096 fn param_named<'a>(op: &'a Operation, name: &str) -> &'a Parameter {
2097 op.parameters
2098 .iter()
2099 .find(|p| p.name == name)
2100 .unwrap_or_else(|| panic!("parameter {name} present"))
2101 }
2102
2103 /// A path parameter declaring a `pattern` produces a `Parameter` carrying it.
2104 #[test]
2105 fn build_operation_carries_a_declared_path_pattern() {
2106 let d = decl(
2107 "/content/{version}",
2108 vec![ParamDecl {
2109 name: "version".to_string(),
2110 param_type: Some("string".to_string()),
2111 required: true,
2112 pattern: Some("^C[0-9]+$".to_string()),
2113 ..Default::default()
2114 }],
2115 );
2116 let op = super::build_operation("/content/{version}", "GET", &d);
2117 let p = param_named(&op, "version");
2118 assert_eq!(p.location, ParameterLocation::Path);
2119 assert_eq!(p.pattern.as_deref(), Some("^C[0-9]+$"));
2120 }
2121
2122 /// A query parameter declaring `max_length = 64` produces a `Parameter`
2123 /// carrying `max_length: Some(64)`.
2124 #[test]
2125 fn build_operation_carries_a_declared_query_max_length() {
2126 let d = decl(
2127 "/search",
2128 vec![ParamDecl {
2129 name: "q".to_string(),
2130 param_type: Some("string".to_string()),
2131 max_length: Some(64),
2132 ..Default::default()
2133 }],
2134 );
2135 let op = super::build_operation("/search", "GET", &d);
2136 let p = param_named(&op, "q");
2137 assert_eq!(p.location, ParameterLocation::Query);
2138 assert_eq!(p.max_length, Some(64));
2139 }
2140
2141 /// A template segment the config never declared carries NO declared rules and
2142 /// `allow_slash: false` — the path loop iterates the TEMPLATE, so it must look
2143 /// the `ParamDecl` up by name and fall back cleanly when there is none.
2144 #[test]
2145 fn build_operation_leaves_rules_absent_for_an_undeclared_template_segment() {
2146 let d = decl("/content/{version}", vec![]);
2147 let op = super::build_operation("/content/{version}", "GET", &d);
2148 let p = param_named(&op, "version");
2149 assert_eq!(p.pattern, None);
2150 assert_eq!(p.max_length, None);
2151 assert!(!p.allow_slash);
2152 assert!(p.required, "a template path parameter stays required");
2153 }
2154
2155 /// D-11: `allow_slash` reaches the `Parameter` from the server's OWN config —
2156 /// the one legitimate source.
2157 #[test]
2158 fn build_operation_carries_allow_slash_from_the_config() {
2159 let d = decl(
2160 "/files/{subpath}",
2161 vec![ParamDecl {
2162 name: "subpath".to_string(),
2163 param_type: Some("string".to_string()),
2164 required: true,
2165 allow_slash: true,
2166 ..Default::default()
2167 }],
2168 );
2169 let op = super::build_operation("/files/{subpath}", "GET", &d);
2170 assert!(param_named(&op, "subpath").allow_slash);
2171 }
2172
2173 /// The three rule fields round-trip into the core rules type the substitution
2174 /// point reads.
2175 #[cfg(feature = "input-validation")]
2176 #[test]
2177 fn build_operation_rules_reach_placeholder_rules() {
2178 let d = decl(
2179 "/files/{subpath}",
2180 vec![ParamDecl {
2181 name: "subpath".to_string(),
2182 param_type: Some("string".to_string()),
2183 required: true,
2184 pattern: Some("^[a-z/]+$".to_string()),
2185 max_length: Some(128),
2186 allow_slash: true,
2187 ..Default::default()
2188 }],
2189 );
2190 let op = super::build_operation("/files/{subpath}", "GET", &d);
2191 let rules = param_named(&op, "subpath").placeholder_rules();
2192 assert_eq!(rules.declared_pattern, Some("^[a-z/]+$"));
2193 assert_eq!(rules.declared_max_length, Some(128));
2194 assert!(rules.allow_slash);
2195 }
2196
2197 /// Phase 128 CR-02 — a body-bearing method routes its non-path declared
2198 /// parameters to [`ParameterLocation::Body`], not to the query string.
2199 ///
2200 /// Before the fix every one of these was `Query`, so the payload
2201 /// `build_body` assembles was empty and the values travelled in the URL.
2202 #[test]
2203 fn build_operation_routes_a_post_non_path_param_to_the_body() {
2204 for method in ["POST", "PUT", "PATCH", "post"] {
2205 let mut d = decl(
2206 "/issues/{id}/comments",
2207 vec![
2208 ParamDecl {
2209 name: "id".to_string(),
2210 param_type: Some("string".to_string()),
2211 required: true,
2212 ..Default::default()
2213 },
2214 ParamDecl {
2215 name: "body_text".to_string(),
2216 param_type: Some("string".to_string()),
2217 required: true,
2218 ..Default::default()
2219 },
2220 ],
2221 );
2222 d.method = Some(method.to_string());
2223 let op = super::build_operation("/issues/{id}/comments", method, &d);
2224 assert!(
2225 op.has_request_body,
2226 "{method} carries a request body by definition"
2227 );
2228 assert_eq!(param_named(&op, "id").location, ParameterLocation::Path);
2229 assert_eq!(
2230 param_named(&op, "body_text").location,
2231 ParameterLocation::Body,
2232 "{method}: a non-path declared parameter must be routed to the payload"
2233 );
2234 assert_eq!(
2235 op.body_parameters().len(),
2236 1,
2237 "{method}: exactly the one non-path parameter is a body parameter"
2238 );
2239 assert!(
2240 op.query_parameters().is_empty(),
2241 "{method}: nothing may travel in the query string as well"
2242 );
2243 }
2244 }
2245
2246 /// The other half of the same rule: a method that carries NO request body has
2247 /// nowhere but the URL to put a non-path parameter, so it stays `Query`. Without
2248 /// this row the fix above is satisfiable by routing everything to the body,
2249 /// which would drop a `GET` tool's parameters entirely.
2250 #[test]
2251 fn build_operation_keeps_a_body_less_method_non_path_param_in_the_query() {
2252 for method in ["GET", "HEAD", "DELETE", "OPTIONS"] {
2253 let mut d = decl(
2254 "/search",
2255 vec![ParamDecl {
2256 name: "q".to_string(),
2257 param_type: Some("string".to_string()),
2258 required: true,
2259 ..Default::default()
2260 }],
2261 );
2262 d.method = Some(method.to_string());
2263 let op = super::build_operation("/search", method, &d);
2264 assert!(!op.has_request_body, "{method} carries no request body");
2265 assert_eq!(
2266 param_named(&op, "q").location,
2267 ParameterLocation::Query,
2268 "{method}: a non-path parameter must stay in the query string"
2269 );
2270 assert!(
2271 op.body_parameters().is_empty(),
2272 "{method}: a body-less request can have no body parameter"
2273 );
2274 }
2275 }
2276
2277 /// Phase 128 CR-03 — the D3 cap's POSITION and the request's ROUTING agree for
2278 /// EVERY method this connector can send, so the cap can no longer be withheld
2279 /// from a value that travels in the query string.
2280 ///
2281 /// This is the row that would have caught the original defect: it does not
2282 /// assert a particular location, it asserts the PAIRING. Before the fix
2283 /// `param_position` said `Body` for `POST` while `build_operation` said `Query`,
2284 /// and `apply_position_cap` emitted nothing for `Body` — so a `POST` parameter
2285 /// reached the request line with no `maxLength`.
2286 ///
2287 /// Fails on removal: point either side at its own method list again and the
2288 /// `POST`/`PUT`/`PATCH` rows (or the `OPTIONS` row) go red.
2289 #[test]
2290 fn param_position_agrees_with_the_built_parameter_location_for_every_method() {
2291 use crate::config::ParamPosition;
2292
2293 // Every method `HttpClient::convert_method` accepts.
2294 for method in [
2295 "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "patch",
2296 ] {
2297 let mut d = decl(
2298 "/things/{id}",
2299 vec![
2300 ParamDecl {
2301 name: "id".to_string(),
2302 param_type: Some("string".to_string()),
2303 required: true,
2304 ..Default::default()
2305 },
2306 ParamDecl {
2307 name: "note".to_string(),
2308 param_type: Some("string".to_string()),
2309 required: false,
2310 ..Default::default()
2311 },
2312 ],
2313 );
2314 d.method = Some(method.to_string());
2315 let op = super::build_operation("/things/{id}", method, &d);
2316
2317 for p in &op.parameters {
2318 let expected_location = match d.param_position(&p.name) {
2319 ParamPosition::Path => ParameterLocation::Path,
2320 ParamPosition::Query => ParameterLocation::Query,
2321 ParamPosition::Body => ParameterLocation::Body,
2322 };
2323 assert_eq!(
2324 p.location,
2325 expected_location,
2326 "{method}: `{}` is {:?} for the D3 cap but {:?} on the wire — the cap's \
2327 scope and the request's routing must not disagree",
2328 p.name,
2329 d.param_position(&p.name),
2330 p.location
2331 );
2332 }
2333
2334 // And the routing is self-consistent: a Body location exists exactly
2335 // when the request carries a body.
2336 assert_eq!(
2337 op.has_request_body,
2338 !op.body_parameters().is_empty(),
2339 "{method}: a Body-located parameter on a body-less request would be \
2340 silently dropped"
2341 );
2342 }
2343 }
2344
2345 /// The consequence CR-03 is really about: the D3 default `maxLength` is emitted
2346 /// for a parameter that travels in the query string and withheld from one that
2347 /// travels in the JSON payload — checked against the BUILT location rather than
2348 /// against a method list, so the two cannot drift.
2349 #[test]
2350 fn the_default_cap_is_emitted_exactly_where_the_value_travels_in_the_url() {
2351 use crate::config::{default_cap_applies, ValidationSection};
2352
2353 let validation = ValidationSection::default();
2354 assert_ne!(
2355 validation.default_max_length, 0,
2356 "the default cap must be on for this row to mean anything"
2357 );
2358
2359 for method in ["GET", "HEAD", "DELETE", "OPTIONS", "POST", "PUT", "PATCH"] {
2360 let param = ParamDecl {
2361 name: "note".to_string(),
2362 param_type: Some("string".to_string()),
2363 required: false,
2364 ..Default::default()
2365 };
2366 let mut d = decl("/things", vec![param.clone()]);
2367 d.method = Some(method.to_string());
2368 let op = super::build_operation("/things", method, &d);
2369 let location = param_named(&op, "note").location;
2370 let capped = default_cap_applies(¶m, d.param_position("note"), &validation);
2371
2372 assert_eq!(
2373 capped,
2374 location == ParameterLocation::Query,
2375 "{method}: an uncapped string in a {location:?} position is the CR-03 defect \
2376 when that position is the query string, and the D-05 requirement when it is \
2377 the payload"
2378 );
2379 }
2380 }
2381}
2382
2383// -----------------------------------------------------------------------------
2384// Tests — Phase 90 OAPI-02a single-call HTTP synthesizer (feature `http`)
2385// -----------------------------------------------------------------------------
2386
2387#[cfg(all(test, feature = "http"))]
2388mod synth_http_tests {
2389 use super::*;
2390 use crate::config::{ParamDecl, ServerConfig, ServerSection, ToolDecl};
2391 use crate::http::{HttpConnector, HttpConnectorError, Operation};
2392 use pmcp::RequestHandlerExtra;
2393 use serde_json::{json, Value};
2394 use std::sync::{Arc, Mutex};
2395
2396 /// A mock [`HttpConnector`] that records the [`Operation`] it last received
2397 /// and returns a fixed JSON payload — so a synthesized handler can be
2398 /// invoked without any network.
2399 struct MockHttpConnector {
2400 last: Mutex<Option<Operation>>,
2401 payload: Value,
2402 }
2403
2404 impl MockHttpConnector {
2405 fn new(payload: Value) -> Arc<Self> {
2406 Arc::new(Self {
2407 last: Mutex::new(None),
2408 payload,
2409 })
2410 }
2411 }
2412
2413 #[async_trait]
2414 impl HttpConnector for MockHttpConnector {
2415 async fn execute(
2416 &self,
2417 operation: &Operation,
2418 _args: &Value,
2419 ) -> std::result::Result<Value, HttpConnectorError> {
2420 *self.last.lock().unwrap() = Some(operation.clone());
2421 Ok(self.payload.clone())
2422 }
2423 fn base_url(&self) -> &str {
2424 "https://mock.example.com"
2425 }
2426 }
2427
2428 fn cfg_with_tools(tools: Vec<ToolDecl>) -> ServerConfig {
2429 ServerConfig {
2430 server: ServerSection {
2431 name: "demo".to_string(),
2432 version: "0.1.0".to_string(),
2433 ..Default::default()
2434 },
2435 tools,
2436 ..Default::default()
2437 }
2438 }
2439
2440 /// (1) A single-call `[[tools]]` with a `{id}` path param synthesizes a
2441 /// `ToolInfo` whose input schema marks `id` required (object envelope), and
2442 /// the handler (wired to a mock connector) returns the mocked JSON.
2443 #[tokio::test]
2444 async fn synth_http_single_call_path_param_required_and_handler_returns_json() {
2445 let cfg = cfg_with_tools(vec![ToolDecl {
2446 name: "line_status".to_string(),
2447 description: Some("Line status".to_string()),
2448 path: Some("/Line/{id}/Status".to_string()),
2449 method: Some("GET".to_string()),
2450 parameters: vec![ParamDecl {
2451 name: "id".to_string(),
2452 param_type: Some("string".to_string()),
2453 required: true,
2454 ..Default::default()
2455 }],
2456 ..Default::default()
2457 }]);
2458 let connector = MockHttpConnector::new(json!({ "status": "Good Service" }));
2459 let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
2460 .expect("synthesize");
2461 assert_eq!(out.len(), 1);
2462 let (name, info, handler) = &out[0];
2463 assert_eq!(name, "line_status");
2464 let schema = &info.input_schema;
2465 assert_eq!(schema["type"], "object");
2466 assert_eq!(schema["required"], json!(["id"]));
2467 assert_eq!(schema["additionalProperties"], Value::Bool(false));
2468
2469 let extra = RequestHandlerExtra::default();
2470 let result = handler
2471 .handle(json!({ "id": "victoria" }), extra)
2472 .await
2473 .expect("handle");
2474 assert_eq!(result, json!({ "status": "Good Service" }));
2475
2476 // The operation carried the `{id}` path param as a Path parameter.
2477 let op = connector
2478 .last
2479 .lock()
2480 .unwrap()
2481 .clone()
2482 .expect("operation recorded");
2483 let path_params: Vec<&str> = op
2484 .path_parameters()
2485 .iter()
2486 .map(|p| p.name.as_str())
2487 .collect();
2488 assert_eq!(path_params, vec!["id"]);
2489 }
2490
2491 /// (2) A `POST` tool routes non-path args to the request body
2492 /// (`has_request_body` true) and the non-path param is NOT a path param.
2493 #[tokio::test]
2494 async fn synth_http_post_sets_request_body() {
2495 let cfg = cfg_with_tools(vec![ToolDecl {
2496 name: "create_item".to_string(),
2497 description: Some("Create".to_string()),
2498 path: Some("/items".to_string()),
2499 method: Some("post".to_string()),
2500 parameters: vec![ParamDecl {
2501 name: "title".to_string(),
2502 param_type: Some("string".to_string()),
2503 required: true,
2504 ..Default::default()
2505 }],
2506 ..Default::default()
2507 }]);
2508 let connector = MockHttpConnector::new(json!({ "ok": true }));
2509 let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
2510 .expect("synthesize");
2511 let (_, _, handler) = &out[0];
2512 let extra = RequestHandlerExtra::default();
2513 handler
2514 .handle(json!({ "title": "widget" }), extra)
2515 .await
2516 .expect("handle");
2517 let op = connector
2518 .last
2519 .lock()
2520 .unwrap()
2521 .clone()
2522 .expect("operation recorded");
2523 assert_eq!(op.method, "POST");
2524 assert!(op.has_request_body, "POST must carry a request body");
2525 assert!(op.path_parameters().is_empty());
2526 }
2527
2528 /// (3) A tool with path + query params lands them in the right schema slots /
2529 /// `Operation` parameter locations.
2530 #[tokio::test]
2531 async fn synth_http_path_and_query_param_slots() {
2532 let cfg = cfg_with_tools(vec![ToolDecl {
2533 name: "search".to_string(),
2534 description: Some("Search".to_string()),
2535 path: Some("/repos/{owner}/issues".to_string()),
2536 method: Some("GET".to_string()),
2537 parameters: vec![
2538 ParamDecl {
2539 name: "owner".to_string(),
2540 param_type: Some("string".to_string()),
2541 required: true,
2542 ..Default::default()
2543 },
2544 ParamDecl {
2545 name: "state".to_string(),
2546 param_type: Some("string".to_string()),
2547 required: false,
2548 ..Default::default()
2549 },
2550 ],
2551 ..Default::default()
2552 }]);
2553 let connector = MockHttpConnector::new(json!([]));
2554 let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
2555 .expect("synthesize");
2556 let (_, _, handler) = &out[0];
2557 let extra = RequestHandlerExtra::default();
2558 handler
2559 .handle(json!({ "owner": "rust-lang", "state": "open" }), extra)
2560 .await
2561 .expect("handle");
2562 let op = connector
2563 .last
2564 .lock()
2565 .unwrap()
2566 .clone()
2567 .expect("operation recorded");
2568 let path_params: Vec<&str> = op
2569 .path_parameters()
2570 .iter()
2571 .map(|p| p.name.as_str())
2572 .collect();
2573 assert_eq!(path_params, vec!["owner"]);
2574 let query_params: Vec<&str> = op
2575 .query_parameters()
2576 .iter()
2577 .map(|p| p.name.as_str())
2578 .collect();
2579 assert_eq!(query_params, vec!["state"]);
2580 }
2581
2582 /// (4) A per-tool `base_url` is reflected in the synthesized `Operation`
2583 /// (Codex MEDIUM — not dropped).
2584 #[tokio::test]
2585 async fn synth_http_per_tool_base_url_reflected() {
2586 let cfg = cfg_with_tools(vec![ToolDecl {
2587 name: "other_host".to_string(),
2588 description: Some("Other host".to_string()),
2589 path: Some("/ping".to_string()),
2590 method: Some("GET".to_string()),
2591 base_url: Some("https://other.example.com/v2".to_string()),
2592 ..Default::default()
2593 }]);
2594 let connector = MockHttpConnector::new(json!({ "pong": true }));
2595 let out = synthesize_from_config_with_http_connector(&cfg, connector.clone())
2596 .expect("synthesize");
2597 let (_, _, handler) = &out[0];
2598 let extra = RequestHandlerExtra::default();
2599 handler.handle(json!({}), extra).await.expect("handle");
2600 let op = connector
2601 .last
2602 .lock()
2603 .unwrap()
2604 .clone()
2605 .expect("operation recorded");
2606 assert_eq!(
2607 op.base_url.as_deref(),
2608 Some("https://other.example.com/v2"),
2609 "per-tool base_url must be reflected on the Operation, not dropped"
2610 );
2611 }
2612
2613 /// (5) NEGATIVE: a `[[tools]]` missing `method` (and without `script`) is
2614 /// rejected with a typed `ToolkitError` (T-90-03-04 — never silently
2615 /// registered).
2616 #[test]
2617 fn synth_http_missing_method_rejected() {
2618 let cfg = cfg_with_tools(vec![ToolDecl {
2619 name: "broken".to_string(),
2620 description: Some("missing method".to_string()),
2621 path: Some("/items".to_string()),
2622 method: None,
2623 ..Default::default()
2624 }]);
2625 let connector = MockHttpConnector::new(json!(null));
2626 let err = synthesize_from_config_with_http_connector(&cfg, connector)
2627 .err()
2628 .expect("ill-formed single-call tool must be rejected");
2629 assert!(matches!(err, ToolkitError::Synth(_)));
2630 }
2631
2632 /// (5b) NEGATIVE: on the single-call-only entry point, a `script` tool is
2633 /// rejected with a typed `ToolkitError` pointing at the `openapi-code-mode`
2634 /// script path — NOT a silent skip, NOT a panic. (The OpenAPI Code Mode
2635 /// entry point `synthesize_from_config_with_http_connector_and_scripts`
2636 /// synthesizes a real `ScriptToolHandler` — proven in `script_tool` tests.)
2637 #[test]
2638 fn synth_http_script_tool_without_engine_is_rejected() {
2639 let cfg = cfg_with_tools(vec![ToolDecl {
2640 name: "scripted".to_string(),
2641 description: Some("script tool".to_string()),
2642 script: Some("await api.get('/x')".to_string()),
2643 ..Default::default()
2644 }]);
2645 let connector = MockHttpConnector::new(json!(null));
2646 let err = synthesize_from_config_with_http_connector(&cfg, connector)
2647 .err()
2648 .expect("script tool on the single-call-only entry point must be rejected");
2649 match err {
2650 ToolkitError::Synth(msg) => {
2651 assert!(
2652 msg.contains("openapi-code-mode"),
2653 "seam message must point at the openapi-code-mode script path: {msg}"
2654 );
2655 },
2656 other => panic!("expected Synth error, got {other:?}"),
2657 }
2658 }
2659}
2660
2661// -----------------------------------------------------------------------------
2662// Phase 128 E2 — the per-tool ArgumentValidator seam.
2663//
2664// A SIBLING of `mod tests`, selected by the `--lib tools::` filter. It drives the
2665// PUBLIC `*_and_hooks` synthesizer so the assertions hold through the surface an
2666// out-of-crate caller (`pmcp-openapi-server`) actually uses.
2667// -----------------------------------------------------------------------------
2668
2669/// E2 ordering, the schema opt-out, and the empty case.
2670#[cfg(all(test, feature = "input-validation"))]
2671mod argument_validator_seam {
2672 use super::synthesize_from_config_and_hooks;
2673 use crate::config::ServerConfig;
2674 use crate::policy::{ArgumentRefusal, ArgumentValidator, ToolkitHooks};
2675 use pmcp::RequestHandlerExtra;
2676 use serde_json::{json, Value};
2677 use std::sync::atomic::{AtomicUsize, Ordering};
2678 use std::sync::Arc;
2679
2680 /// Counts its invocations, then refuses when `end < start`. The refusal is a
2681 /// FIXED string: it names the rule, never a value.
2682 struct EndAfterStart {
2683 calls: Arc<AtomicUsize>,
2684 }
2685
2686 impl ArgumentValidator for EndAfterStart {
2687 fn validate(&self, args: &Value) -> Result<(), ArgumentRefusal> {
2688 self.calls.fetch_add(1, Ordering::SeqCst);
2689 let start = args.get("start").and_then(Value::as_i64);
2690 let end = args.get("end").and_then(Value::as_i64);
2691 match (start, end) {
2692 (Some(s), Some(e)) if e < s => {
2693 Err(ArgumentRefusal::new("`end` must not precede `start`"))
2694 },
2695 _ => Ok(()),
2696 }
2697 }
2698 }
2699
2700 /// A `[[tools]]` whose declared schema permits any two integers, so the
2701 /// cross-field rule is one only E2 can express.
2702 fn cfg(enforce: bool) -> ServerConfig {
2703 let toml = format!(
2704 r#"
2705[server]
2706name = "range"
2707version = "0.1.0"
2708
2709[server.validation]
2710enforce_input_schema = {enforce}
2711
2712[[tools]]
2713name = "range_query"
2714description = "Query a range"
2715sql = "SELECT 1"
2716
2717[[tools.parameters]]
2718name = "start"
2719type = "integer"
2720required = true
2721
2722[[tools.parameters]]
2723name = "end"
2724type = "integer"
2725required = true
2726"#
2727 );
2728 ServerConfig::from_toml_strict_validated(&toml).expect("parse")
2729 }
2730
2731 fn extra() -> RequestHandlerExtra {
2732 RequestHandlerExtra::default()
2733 }
2734
2735 fn hooks(calls: &Arc<AtomicUsize>) -> ToolkitHooks {
2736 ToolkitHooks::default().with_argument_validator(
2737 "range_query",
2738 Arc::new(EndAfterStart {
2739 calls: Arc::clone(calls),
2740 }),
2741 )
2742 }
2743
2744 #[tokio::test]
2745 async fn a_registered_validator_refuses_a_combination_the_schema_permits() {
2746 let calls = Arc::new(AtomicUsize::new(0));
2747 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2748 let (_name, _info, handler) = &tools[0];
2749 let err = handler
2750 .handle(json!({ "start": 10, "end": 2 }), extra())
2751 .await
2752 .expect_err("the validator refuses");
2753 assert!(
2754 err.to_string().contains("`end` must not precede `start`"),
2755 "the refusal must carry the validator's own message, got: {err}"
2756 );
2757 assert_eq!(calls.load(Ordering::SeqCst), 1);
2758 }
2759
2760 /// The E2 refusal takes the same TOOL-LEVEL channel as the D1 schema refusal.
2761 /// A cross-field rule is as much the caller's to fix as a bad type is, and a
2762 /// model can only act on a tool result, not on a JSON-RPC error.
2763 #[tokio::test]
2764 async fn a_validator_refusal_is_a_tool_level_rejection_not_a_protocol_error() {
2765 let calls = Arc::new(AtomicUsize::new(0));
2766 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2767 let (_name, _info, handler) = &tools[0];
2768 let err = handler
2769 .handle(json!({ "start": 10, "end": 2 }), extra())
2770 .await
2771 .expect_err("the validator refuses");
2772 assert!(
2773 matches!(err, pmcp::Error::ToolRejected { .. }),
2774 "a validator refusal must be a tool-level rejection, got: {err:?}"
2775 );
2776 assert!(
2777 err.to_string().contains("`end` must not precede `start`"),
2778 "the validator's own message must survive the channel change, got: {err}"
2779 );
2780 }
2781
2782 #[tokio::test]
2783 async fn a_registered_validator_allows_a_valid_combination() {
2784 let calls = Arc::new(AtomicUsize::new(0));
2785 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2786 let (_name, _info, handler) = &tools[0];
2787 // No SQL connector is wired, so the INNER handler errors — which is itself
2788 // the proof that the validator allowed the call through to it.
2789 let err = handler
2790 .handle(json!({ "start": 2, "end": 10 }), extra())
2791 .await
2792 .expect_err("no connector is wired");
2793 assert!(
2794 !err.to_string().contains("must not precede"),
2795 "the validator must NOT have refused, got: {err}"
2796 );
2797 assert_eq!(calls.load(Ordering::SeqCst), 1);
2798 }
2799
2800 /// T-128-41: the ordering is the contract. A validator must never see
2801 /// arguments that failed the declared schema.
2802 #[tokio::test]
2803 async fn a_registered_validator_is_not_invoked_when_the_schema_refuses() {
2804 let calls = Arc::new(AtomicUsize::new(0));
2805 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2806 let (_name, _info, handler) = &tools[0];
2807 // `start` is a declared integer; a string violates the schema.
2808 let err = handler
2809 .handle(json!({ "start": "ten", "end": 2 }), extra())
2810 .await
2811 .expect_err("D1 refuses");
2812 assert!(
2813 !err.to_string().contains("must not precede"),
2814 "D1 must be the refuser, not E2, got: {err}"
2815 );
2816 assert_eq!(
2817 calls.load(Ordering::SeqCst),
2818 0,
2819 "the validator was invoked on arguments the schema already refused"
2820 );
2821 }
2822
2823 /// The joint test also present in plan 03: turning off one enforcement must
2824 /// never silently turn off another.
2825 #[tokio::test]
2826 async fn a_registered_validator_still_runs_with_enforce_input_schema_false() {
2827 let calls = Arc::new(AtomicUsize::new(0));
2828 let tools = synthesize_from_config_and_hooks(&cfg(false), &hooks(&calls)).expect("synth");
2829 let (_name, _info, handler) = &tools[0];
2830
2831 // Half one: the SCHEMA check is off, so an undeclared key is accepted.
2832 let err = handler
2833 .handle(json!({ "start": 2, "end": 10, "undeclared": 1 }), extra())
2834 .await
2835 .expect_err("no connector is wired");
2836 assert!(
2837 !err.to_string().contains("undeclared"),
2838 "with enforce_input_schema=false an undeclared key must be accepted, got: {err}"
2839 );
2840
2841 // Half two: the VALIDATOR still refuses.
2842 let err = handler
2843 .handle(json!({ "start": 10, "end": 2 }), extra())
2844 .await
2845 .expect_err("the validator refuses");
2846 assert!(
2847 err.to_string().contains("`end` must not precede `start`"),
2848 "a registered validator must survive the schema opt-out, got: {err}"
2849 );
2850 assert_eq!(calls.load(Ordering::SeqCst), 2);
2851 }
2852
2853 #[tokio::test]
2854 async fn a_tool_with_no_registered_validator_runs_d1_only() {
2855 let tools =
2856 synthesize_from_config_and_hooks(&cfg(true), &ToolkitHooks::default()).expect("synth");
2857 let (_name, _info, handler) = &tools[0];
2858 // D1 still refuses a schema violation.
2859 handler
2860 .handle(json!({ "start": "ten", "end": 2 }), extra())
2861 .await
2862 .expect_err("D1 refuses");
2863 // And a schema-valid call reaches the inner handler (which has no connector).
2864 let err = handler
2865 .handle(json!({ "start": 10, "end": 2 }), extra())
2866 .await
2867 .expect_err("no connector is wired");
2868 assert!(!err.to_string().contains("must not precede"));
2869 }
2870
2871 /// `handle_output` must validate too, or an inner handler that overrides it
2872 /// becomes a path with schema enforcement and no custom rule.
2873 #[tokio::test]
2874 async fn handle_output_runs_the_validator_as_well() {
2875 let calls = Arc::new(AtomicUsize::new(0));
2876 let tools = synthesize_from_config_and_hooks(&cfg(true), &hooks(&calls)).expect("synth");
2877 let (_name, _info, handler) = &tools[0];
2878 let err = handler
2879 .handle_output(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 "handle_output must run the validator too, got: {err}"
2885 );
2886 assert_eq!(calls.load(Ordering::SeqCst), 1);
2887 }
2888}
2889
2890/// The once-at-startup enforcement report's line formats (Phase 128 D-07).
2891#[cfg(all(test, feature = "input-validation"))]
2892mod enforcement_report {
2893 use crate::config::ServerConfig;
2894 use crate::policy::{
2895 render_validation_report, ArgumentRefusal, ArgumentValidator, ReportLevel, ToolkitHooks,
2896 };
2897 use serde_json::Value;
2898 use std::sync::Arc;
2899
2900 struct Never;
2901 impl ArgumentValidator for Never {
2902 fn validate(&self, _args: &Value) -> Result<(), ArgumentRefusal> {
2903 Err(ArgumentRefusal::new("disabled"))
2904 }
2905 }
2906
2907 fn cfg(extra_validation: &str) -> ServerConfig {
2908 let toml = format!(
2909 r#"
2910[server]
2911name = "report"
2912version = "0.1.0"
2913
2914[server.validation]
2915{extra_validation}
2916
2917[[tools]]
2918name = "get_thing"
2919description = "Get a thing"
2920path = "/things/{{id}}"
2921method = "GET"
2922
2923[[tools.parameters]]
2924name = "id"
2925type = "string"
2926required = true
2927pattern = "^[0-9]+$"
2928"#
2929 );
2930 ServerConfig::from_toml_strict_validated(&toml).expect("parse")
2931 }
2932
2933 fn texts(lines: &[crate::policy::ReportLine]) -> String {
2934 lines
2935 .iter()
2936 .map(|l| l.text.clone())
2937 .collect::<Vec<_>>()
2938 .join("\n")
2939 }
2940
2941 #[test]
2942 fn a_fully_enforcing_config_states_that_no_opt_out_is_active() {
2943 let lines = render_validation_report(&cfg(""), &ToolkitHooks::default());
2944 let joined = texts(&lines);
2945 assert!(
2946 joined.contains("input validation: schema_check=ON"),
2947 "{joined}"
2948 );
2949 assert!(
2950 joined.contains("tool 'get_thing' enforces"),
2951 "one line per tool: {joined}"
2952 );
2953 assert!(
2954 joined.contains("no [server.validation] opt-out is active"),
2955 "the report must state the ABSENCE of an opt-out, not stay silent: {joined}"
2956 );
2957 assert!(
2958 joined.contains("E1 RequestPolicy registered=false"),
2959 "{joined}"
2960 );
2961 assert!(
2962 joined.contains("no E2 ArgumentValidator is registered"),
2963 "{joined}"
2964 );
2965 assert!(
2966 lines.iter().all(|l| l.level == ReportLevel::Info),
2967 "a fully enforcing config emits no warning"
2968 );
2969 }
2970
2971 #[test]
2972 fn every_active_opt_out_is_reported_at_warn_level() {
2973 let lines = render_validation_report(
2974 &cfg("enforce_input_schema = false\ndefault_max_length = 0\nadditional_properties = true"),
2975 &ToolkitHooks::default(),
2976 );
2977 let joined = texts(&lines);
2978 assert!(joined.contains("schema_check=OFF"), "{joined}");
2979 let warns: Vec<&str> = lines
2980 .iter()
2981 .filter(|l| l.level == ReportLevel::Warn)
2982 .map(|l| l.text.as_str())
2983 .collect();
2984 assert!(
2985 warns.len() >= 4,
2986 "an enforcement that is OFF must never read as on; got {warns:#?}"
2987 );
2988 assert!(
2989 warns.iter().any(|w| w.contains("opt-out ACTIVE")),
2990 "{warns:#?}"
2991 );
2992 }
2993
2994 #[test]
2995 fn a_validator_for_an_undeclared_tool_name_is_warned_not_refused() {
2996 let hooks = ToolkitHooks::default()
2997 .with_argument_validator("get_thing", Arc::new(Never))
2998 .with_argument_validator("typoed_name", Arc::new(Never));
2999 let lines = render_validation_report(&cfg(""), &hooks);
3000 let joined = texts(&lines);
3001 assert!(
3002 joined.contains("E2 ArgumentValidator registered for get_thing, typoed_name"),
3003 "{joined}"
3004 );
3005 let warns: Vec<&str> = lines
3006 .iter()
3007 .filter(|l| l.level == ReportLevel::Warn)
3008 .map(|l| l.text.as_str())
3009 .collect();
3010 assert_eq!(warns.len(), 1, "exactly the typo warns: {warns:#?}");
3011 assert!(warns[0].contains("'typoed_name'"), "{:?}", warns[0]);
3012 assert!(warns[0].contains("will never run"), "{:?}", warns[0]);
3013 }
3014
3015 /// SC-7: the report is built from declarations, so it cannot carry request
3016 /// data. Asserted rather than trusted, because the log is a channel.
3017 #[test]
3018 fn the_report_never_echoes_an_argument_value() {
3019 let lines = render_validation_report(&cfg(""), &ToolkitHooks::default());
3020 let joined = texts(&lines);
3021 for forbidden in ["Bearer", "app_key", "super-secret"] {
3022 assert!(!joined.contains(forbidden), "{joined}");
3023 }
3024 }
3025}