Skip to main content

pmcp_server_toolkit/
config.rs

1// Originated from pmcp-run/built-in/shared/mcp-server-common/src/config.rs
2// (https://github.com/guyernest/pmcp-run). Lifted into rust-mcp-sdk for Phase 83.
3
4//! `ServerConfig` + sub-sections. Strict `#[serde(deny_unknown_fields)]` per D-13.
5//!
6//! # Strict-parse discipline (D-13)
7//!
8//! Every struct in this module carries `#[serde(deny_unknown_fields)]`. A typo
9//! in any key (e.g. `auto_aprove_levels` for `auto_approve_levels`) is a
10//! **parse error**, not a silent default. This is the defence-in-depth path
11//! against the Tampering threat documented in `83-04-PLAN.md` T-83-04-02 —
12//! mis-spelled keys MUST NOT degrade security policy.
13//!
14//! # REF-01 superset invariant
15//!
16//! `ServerConfig` is a strict **superset** of every key emitted by the three
17//! reference config.tomls (`tests/fixtures/{open-images,imdb,msr-vtt}-config.toml`,
18//! lifted in Plan 01 Task 4). When a fixture grows a new key, the toolkit grows
19//! a new field — typed if known, `toml::Value` if heterogeneous. The invariant
20//! is enforced empirically by the [`tests/reference_configs.rs`] integration
21//! test (REF-01 superset, D-13, ROADMAP SC-2).
22//!
23//! **Anti-pattern (RESEARCH §Pitfall 1, PATTERNS §8):** Do NOT loosen
24//! `deny_unknown_fields` to make a fixture parse. Always ADD the missing field.
25//!
26//! # Three entry points
27//!
28//! | Method | Returns | Use case |
29//! |--------|---------|----------|
30//! | [`ServerConfig::from_toml`] | `Result<Self, ToolkitError::Parse>` | Programmatic partial-config merge; no semantic checks |
31//! | [`ServerConfig::validate`] | `Result<(), ConfigValidationError>` | Post-parse semantic check (run after a merge) |
32//! | [`ServerConfig::from_toml_strict_validated`] | `Result<Self, ToolkitError>` | Production entry: parse + validate in one call |
33//!
34//! Per Phase 83 review R8, `validate()` exists because the `Default` impls on
35//! `ServerSection` etc. would otherwise let `[server]` typos land empty
36//! `name`/`version` strings without an error. The strict-validated convenience
37//! is what production callers should reach for.
38//!
39//! REF-01 superset enumeration (from `tests/fixtures/{open-images,imdb,msr-vtt,reference}-config.toml`;
40//! the SQLite Chinook `reference-config.toml` was lifted in Plan 85-01):
41//!
42//! ```text
43//! [server]            : id, name, description, type, version, is_reference
44//! [metadata]          : display_name, short_description, description, tags, author, visibility
45//! [database]          : type, database, output_location, workgroup, query_timeout_ms,
46//!                       url, file_path, [[database.tables]], [database.pool]
47//! [[database.tables]] : name, description
48//! [database.pool]     : max_connections, connection_timeout_seconds
49//! [code_mode]         : enabled, server_id, allow_writes, allow_deletes, allow_ddl,
50//!                       require_limit, max_limit, blocked_tables, sensitive_columns,
51//!                       auto_approve_levels, token_ttl_seconds, token_secret,
52//!                       [code_mode.limits]
53//! [code_mode.limits]  : max_tables_per_query, max_join_depth, max_subquery_depth
54//! [shared_policy_store] : creates_shared_store, export_to_ssm, ssm_path, templates
55//! [[tools]]           : name, description, sql, ui_resource_uri,
56//!                       [[tools.parameters]], [tools.annotations]
57//! [[tools.parameters]] : name, type, description, required, default, max_length,
58//!                       minimum, maximum, enum
59//! [tools.annotations] : read_only_hint, destructive_hint, idempotent_hint,
60//!                       open_world_hint, cost_hint
61//! [[prompts]]         : name, description, include_resources, arguments
62//! [[resources]]       : uri, name, description, mime_type, content
63//! ```
64
65use serde::{Deserialize, Serialize};
66
67use crate::error::{ConfigValidationError, ConfigWarning, Result, ToolkitError};
68
69// -----------------------------------------------------------------------------
70// Top-level
71// -----------------------------------------------------------------------------
72
73/// Top-level `pmcp-server-toolkit` configuration parsed from a `config.toml`.
74///
75/// One struct parses the entire file in one shot (per D-13). All sub-sections
76/// carry `#[serde(deny_unknown_fields)]` — a typo anywhere in the file is a
77/// hard parse error.
78///
79/// # Entry points
80///
81/// Use [`ServerConfig::from_toml_strict_validated`] for production callers.
82/// [`ServerConfig::from_toml`] is the no-validation variant for programmatic
83/// merges; [`ServerConfig::validate`] runs the semantic checks separately.
84///
85/// # Examples
86///
87/// ```
88/// use pmcp_server_toolkit::config::ServerConfig;
89///
90/// let toml = r#"
91///     [server]
92///     name = "demo"
93///     version = "0.1.0"
94/// "#;
95/// let cfg = ServerConfig::from_toml_strict_validated(toml)
96///     .expect("valid minimum config");
97/// assert_eq!(cfg.server.name, "demo");
98/// assert_eq!(cfg.server.version, "0.1.0");
99/// ```
100#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
101#[serde(deny_unknown_fields)]
102pub struct ServerConfig {
103    /// `[server]` — identity and version metadata.
104    #[serde(default)]
105    pub server: ServerSection,
106
107    /// `[metadata]` — admin-facing display defaults.
108    #[serde(default)]
109    pub metadata: MetadataSection,
110
111    /// `[database]` — backend connection + tables.
112    #[serde(default)]
113    pub database: DatabaseSection,
114
115    /// `[backend]` (optional, `http` feature) — OpenAPI/REST HTTP backend
116    /// declaration (`base_url` + `[backend.auth]` + `[backend.http]`).
117    ///
118    /// Additive per the REF-01 superset invariant (D-06): a pure-SQL config
119    /// omits `[backend]` and this field parses to `None`. The whole section is
120    /// gated behind the `http` feature — a no-http build has no OpenAPI backend,
121    /// so exposing an unusable stub type would be misleading. See
122    /// [`BackendSection`].
123    #[cfg(feature = "http")]
124    #[serde(default)]
125    pub backend: Option<BackendSection>,
126
127    /// `[code_mode]` (optional) — code-mode policy and limits.
128    #[serde(default)]
129    pub code_mode: Option<CodeModeSection>,
130
131    /// `[[tools]]` — declarative tool surface (TOML-defined handlers).
132    #[serde(default)]
133    pub tools: Vec<ToolDecl>,
134
135    /// `[[config_slots]]` — declared config slots the TARGET environment must
136    /// fill (PKG-03). Additive per the REF-01 superset invariant: a config
137    /// omitting the block parses to an empty vec.
138    ///
139    /// Deliberately NOT gated on the `http` feature — a SQL or workbook Shape A
140    /// server declares slots too, and gating it would make the field vanish in
141    /// the toolkit's own default build.
142    #[serde(default)]
143    pub config_slots: Vec<ConfigSlotDecl>,
144
145    /// `[[prompts]]` — declarative prompt surface.
146    #[serde(default)]
147    pub prompts: Vec<PromptDecl>,
148
149    /// `[[resources]]` — declarative resource surface.
150    #[serde(default)]
151    pub resources: Vec<ResourceDecl>,
152
153    /// `[shared_policy_store]` (optional) — AVP/Cedar shared-policy-store
154    /// declaration emitted by the reference SQL server (`is_reference = true`),
155    /// which provisions the policy store all sibling SQL servers attach to.
156    /// Additive per the REF-01 superset invariant (Plan 85-01); parsed
157    /// verbatim — the toolkit does not provision SSM at parse time.
158    #[serde(default)]
159    pub shared_policy_store: Option<SharedPolicyStoreSection>,
160}
161
162impl ServerConfig {
163    /// Parse `ServerConfig` from a TOML config string.
164    ///
165    /// Performs **strict parsing** (`#[serde(deny_unknown_fields)]` on every
166    /// section, per D-13). Does **not** run semantic validation — callers
167    /// wanting required-field guarantees should use
168    /// [`Self::from_toml_strict_validated`] instead.
169    ///
170    /// # Errors
171    ///
172    /// Returns [`ToolkitError::Parse`] on syntax error or unknown field. A
173    /// mis-spelled key (e.g. `auto_aprove_levels` for `auto_approve_levels`)
174    /// produces a parse error here, not a silent default.
175    ///
176    /// # Example
177    ///
178    /// ```
179    /// use pmcp_server_toolkit::config::ServerConfig;
180    ///
181    /// let toml = r#"
182    ///     [server]
183    ///     id = "demo"
184    ///     name = "Demo"
185    ///     version = "0.1.0"
186    /// "#;
187    /// let cfg = ServerConfig::from_toml(toml).expect("parse");
188    /// assert_eq!(cfg.server.name, "Demo");
189    /// ```
190    pub fn from_toml(toml_str: &str) -> Result<Self> {
191        toml::from_str(toml_str).map_err(ToolkitError::Parse)
192    }
193
194    /// Parse + validate. Per Phase 83 review R8 — guards against the
195    /// missing-required-value trap that the `Default` impls on sub-sections
196    /// would otherwise hide behind silent empty strings (e.g. a typo'd
197    /// `[serever]` header makes `server.name` default to `""`).
198    ///
199    /// # Errors
200    ///
201    /// Returns [`ToolkitError::Parse`] on TOML syntax / unknown-field errors,
202    /// or [`ToolkitError::Validation`] (wrapping
203    /// [`ConfigValidationError`]) on missing required values
204    /// (empty `server.name`, empty `server.version`, empty tool name, empty
205    /// table name).
206    ///
207    /// # Example
208    ///
209    /// ```
210    /// use pmcp_server_toolkit::config::ServerConfig;
211    /// let toml = r#"
212    ///     [server]
213    ///     name = "demo"
214    ///     version = "0.1.0"
215    /// "#;
216    /// let cfg = ServerConfig::from_toml_strict_validated(toml).expect("valid");
217    /// # let _ = cfg;
218    /// ```
219    pub fn from_toml_strict_validated(toml_str: &str) -> Result<Self> {
220        let cfg = Self::from_toml(toml_str)?;
221        cfg.validate()?;
222        Ok(cfg)
223    }
224
225    /// Validate required-field semantics that `#[serde(default)]` would
226    /// otherwise mask. Per Phase 83 review R8.
227    ///
228    /// Rules checked, in order:
229    /// 1. `server.name` is non-empty (trimmed).
230    /// 2. `server.version` is non-empty (trimmed).
231    /// 3. Every `[[tools]]` entry has a non-empty `name`.
232    /// 4. No `[[tools]]` entry mixes tool kinds (`sql` / `path`+`method` /
233    ///    `script`) — D-01 / T-90-02-04.
234    /// 5. Every `[[database.tables]]` entry has a non-empty `name`.
235    /// 6. Every `[[config_slots]]` entry has a non-empty `key` AND `name`
236    ///    (PKG-03). The entry's `kind` needs no rule here — it is the closed
237    ///    [`ConfigSlotKind`] enum, so serde rejects an unknown discriminator at
238    ///    parse time, before `validate()` is called.
239    /// 7. When a `[backend]` block is present (`http` feature), its `base_url`
240    ///    is non-empty (trimmed) — GAP 3 / WR-02. Absent on no-http builds.
241    /// 8. Every `[[tools.parameters]]` declaration is well-formed (Phase 128
242    ///    D2 / SC-2): no empty `pattern`, no `minimum`/`maximum` outside the
243    ///    exactly-representable `f64` integer range, and the tool's synthesized
244    ///    `inputSchema` COMPILES as a Draft 2020-12 schema. The compile check
245    ///    requires the `input-validation` feature; on a build without it the check
246    ///    is skipped and a `tracing::warn!` says so once, because an enforcement
247    ///    that is off must never read as on.
248    /// 9. The `[code_mode]` block, when present, says nothing that would be
249    ///    silently ignored: no SQL key on an OpenAPI server and no
250    ///    operation-class key on a server without a `[backend]`; an
251    ///    `allowlist`/`blocklist` class mode has its list; every
252    ///    `[[code_mode.operations]]` entry has an `id` and `path` and the ids
253    ///    are unique; every `auto_approve_levels` entry is a known level. A
254    ///    misspelled key, mode or category already fails the parse.
255    ///
256    /// # Errors
257    ///
258    /// Returns a [`ConfigValidationError`] variant identifying the
259    /// first rule violated. Iteration order matches struct field order.
260    pub fn validate(&self) -> std::result::Result<(), ConfigValidationError> {
261        warn_if_pattern_checking_unavailable(&self.tools);
262        if self.server.name.trim().is_empty() {
263            return Err(ConfigValidationError::EmptyServerName);
264        }
265        if self.server.version.trim().is_empty() {
266            return Err(ConfigValidationError::EmptyServerVersion);
267        }
268        for (i, tool) in self.tools.iter().enumerate() {
269            if tool.name.trim().is_empty() {
270                return Err(ConfigValidationError::EmptyToolName(i));
271            }
272            // D-01 / T-90-02-04: a tool is EITHER sql, single-call (path/method),
273            // OR script — never a mixture. Reject ambiguity instead of letting a
274            // silent "script wins" precedence hide a config mistake.
275            if tool.declared_kind_count() > 1 {
276                return Err(ConfigValidationError::AmbiguousToolKind(i));
277            }
278            // Phase 128 D2 / SC-2. Deliberately placed AFTER the name and
279            // kind arms so no pre-existing test's expected variant changes.
280            validate_tool_parameters(tool, &self.server.validation)?;
281        }
282        for (i, table) in self.database.tables.iter().enumerate() {
283            if table.name.trim().is_empty() {
284                return Err(ConfigValidationError::EmptyTableName(i));
285            }
286        }
287        // PKG-03 (Phase 120 Plan 04): a declared slot must actually name a
288        // config path AND a variable. An empty `key`/`name` claims coverage the
289        // declaration cannot deliver. Deliberately NOT a completeness
290        // heuristic — a "this literal looks secret, so a slot is missing" check
291        // would flag the london-tube fixture's guarded dev `token_secret`, and
292        // a check that cries wolf is worse than none.
293        for (i, slot) in self.config_slots.iter().enumerate() {
294            if slot.key.trim().is_empty() || slot.name.trim().is_empty() {
295                return Err(ConfigValidationError::EmptyConfigSlotField(i));
296            }
297            // Identity-bearing slots structurally carry no value (the whole
298            // "secrets never travel" premise) — a `tested_value` on a `secret`
299            // declaration is the one field where a REAL credential could sit in
300            // a config that is served but never packed, so the doc-comment rule
301            // is enforced here rather than trusted.
302            if slot.kind == ConfigSlotKind::Secret && slot.tested_value.is_some() {
303                return Err(ConfigValidationError::SecretSlotCarriesTestedValue(i));
304            }
305        }
306        // Phase 90 gap-closure (GAP 3 / WR-02): when a `[backend]` block is
307        // declared, its `base_url` must be non-empty. Catch a typo'd / omitted
308        // URL here (the field is `#[serde(default)]` -> `""`) rather than
309        // letting it surface late as an opaque DispatchError at request time.
310        // Gated on `http` because the `backend` field itself is http-only; the
311        // block simply vanishes in a no-http build (SQL configs unaffected).
312        #[cfg(feature = "http")]
313        if let Some(backend) = &self.backend {
314            if backend.base_url.trim().is_empty() {
315                return Err(ConfigValidationError::EmptyBackendBaseUrl);
316            }
317            // Phase 120 follow-up: a reference-shaped base_url must name
318            // exactly ONE variable. The grammar maps every malformed brace
319            // form — the empty `${}` and multi-placeholder compositions like
320            // `${SCHEME}://${HOST}` — to the empty name; catching that here
321            // turns a boot-time `UnresolvedBaseUrlRef` with an empty variable
322            // name into a load-time error naming the actual mistake.
323            if crate::env_ref::parse_env_ref(&backend.base_url) == Some("") {
324                return Err(ConfigValidationError::MalformedBackendBaseUrlRef);
325            }
326            // The same rule for `[backend.auth]` credentials. It is NOT the
327            // same consequence: an unresolvable base_url breaks every request
328            // loudly, while an unresolvable CREDENTIAL was silently omitted
329            // (`expand_api_key_map` drops the entry; the scalar variants
330            // collapse to `NoAuth`), so the server booted and sent every
331            // backend request unauthenticated. Catching it here is what makes
332            // that failure visible at all.
333            if let Some(field) = backend.auth.malformed_env_ref_field() {
334                return Err(ConfigValidationError::MalformedBackendAuthRef(field));
335            }
336        }
337        self.validate_code_mode()
338    }
339
340    /// Whether this config declares an OpenAPI `[backend]`. Always `false` on
341    /// a build without the `http` feature, which has no backend section.
342    #[must_use]
343    pub fn has_http_backend(&self) -> bool {
344        #[cfg(feature = "http")]
345        {
346            self.backend.is_some()
347        }
348        #[cfg(not(feature = "http"))]
349        {
350            false
351        }
352    }
353
354    /// Rule 9 of [`Self::validate`]: the `[code_mode]` block says nothing that
355    /// would be silently ignored. Every key applies to this kind of server,
356    /// every class mode has the list it needs, the operation catalog is
357    /// well-formed, and every `auto_approve_levels` entry is a known level.
358    fn validate_code_mode(&self) -> std::result::Result<(), ConfigValidationError> {
359        let Some(cm) = &self.code_mode else {
360            return Ok(());
361        };
362        for level in &cm.auto_approve_levels {
363            if !matches!(
364                level.to_ascii_lowercase().as_str(),
365                "low" | "medium" | "high" | "critical"
366            ) {
367                return Err(ConfigValidationError::UnknownAutoApproveLevel(
368                    level.clone(),
369                ));
370            }
371        }
372        let class_keys = cm.class_keys_set();
373        if self.has_http_backend() {
374            if let Some(key) = cm.sql_keys_set().first() {
375                return Err(ConfigValidationError::CodeModeKeyWrongBackend {
376                    key,
377                    server_kind: "an OpenAPI",
378                    hint: "an OpenAPI server uses write_mode, delete_mode, read_mode, admin_mode, \
379                           allowed_operations, blocked_operations and blocked_paths",
380                });
381            }
382        } else if let Some(key) = class_keys.first() {
383            return Err(ConfigValidationError::CodeModeKeyWrongBackend {
384                key,
385                server_kind: "a SQL",
386                hint: "operation classes apply to a server with a [backend]; a SQL server uses \
387                       allow_writes, allow_deletes, allow_ddl and blocked_tables",
388            });
389        }
390        if let (Some(key), false) = (class_keys.first(), cfg!(feature = "openapi-code-mode")) {
391            return Err(ConfigValidationError::ClassKeysUnenforceable(key));
392        }
393        for (class, mode) in cm.class_modes() {
394            let needs = match mode {
395                ClassModeName::Allowlist if cm.allowed_operations.is_empty() => {
396                    Some("allowed_operations")
397                },
398                ClassModeName::Blocklist if cm.blocked_operations.is_empty() => {
399                    Some("blocked_operations")
400                },
401                _ => None,
402            };
403            if let Some(list) = needs {
404                return Err(ConfigValidationError::ClassModeNeedsList {
405                    class: class.as_str(),
406                    mode: mode.as_str(),
407                    list,
408                });
409            }
410        }
411        let mut ids = std::collections::HashSet::new();
412        for (i, op) in cm.operations.iter().enumerate() {
413            if op.id.trim().is_empty() || op.path.trim().is_empty() {
414                return Err(ConfigValidationError::EmptyOperationField(i));
415            }
416            if !ids.insert(op.id.as_str()) {
417                return Err(ConfigValidationError::DuplicateOperationId(op.id.clone()));
418            }
419        }
420        Ok(())
421    }
422
423    /// Non-fatal configuration findings (Phase 128, D-07).
424    ///
425    /// Returns, in `[[tools]]` then `[[tools.parameters]]` DECLARATION order:
426    ///
427    /// 1. one `uncapped-string` finding per BODY-position string parameter with no
428    ///    `max_length` — the residual D-05 accepts, surfaced rather than refused;
429    /// 2. one `declared-max-length-above-placeholder-cap` finding per path- or
430    ///    query-position parameter whose declared `max_length` EXCEEDS
431    ///    `pmcp::server::schema_validation::PLACEHOLDER_MAX_LENGTH`, because such a
432    ///    parameter publishes a limit in `inputSchema` that the always-on
433    ///    placeholder floor will not honour — so a refusal would name a rule the
434    ///    client was never told about;
435    ///
436    /// and then one finding per ACTIVE `[server.validation]` opt-out.
437    ///
438    /// Never returns an error and never refuses anything. A config with zero tools
439    /// and no active opt-out returns an empty `Vec`. Consumed by
440    /// `cargo pmcp validate config` and by the once-at-startup log.
441    #[must_use]
442    pub fn lint(&self) -> Vec<ConfigWarning> {
443        let mut out = Vec::new();
444        for tool in &self.tools {
445            lint_tool(tool, &self.server.validation, &mut out);
446        }
447        lint_opt_outs(&self.server.validation, &mut out);
448        out
449    }
450
451    /// The findings that need the operator's OpenAPI document to be computable
452    /// (Phase 128, D4(b) / T-128-36a).
453    ///
454    /// Separate from [`Self::lint`] rather than folded into it, because `lint`
455    /// takes only `&self` and a config is meaningful with no spec at all — a
456    /// spec-less deployment is supported and must produce no findings from its own
457    /// absence.
458    ///
459    /// Returns, in `[[tools]]` declaration order, one
460    /// [`CONFIGURED_TEMPLATE_NOT_IN_SPEC`] finding per single-call tool whose
461    /// `(method, path)` matches no operation the spec declares. Such a tool reaches
462    /// its endpoint and keeps the unconditional character floor and the always-on
463    /// length cap, but the spec's declared `pattern`/`maxLength` narrowing for its
464    /// placeholders is silently not applied — the `/users/{alias}` versus
465    /// `/users/{id}` drift. That is an author error an operator can fix before
466    /// deploy, which is the whole reason this runs at config time.
467    ///
468    /// An author-written query string on the configured `path` is stripped before
469    /// the lookup, because an OpenAPI path template never carries one — so
470    /// `/content/{version}/CUI?string=x` is matched as `/content/{version}/CUI`
471    /// rather than reported as drift.
472    ///
473    /// # The bound on this guard, stated
474    ///
475    /// It covers a template written in the CONFIG. A template a Code Mode script
476    /// COMPOSES at runtime is not visible here and cannot be, which is why the
477    /// runtime miss is additionally reported once per `(method, template)` pair by
478    /// `crate::code_mode`'s `log_spec_lookup_miss`. Neither signal is a refusal:
479    /// this returns findings, and never an error.
480    ///
481    /// Tools with no `path`/`method` pair — SQL tools, script tools — are skipped:
482    /// they address no single spec operation.
483    #[cfg(feature = "http")]
484    #[must_use]
485    pub fn lint_against_spec(&self, spec: &crate::http::OpenApiSchema) -> Vec<ConfigWarning> {
486        let mut out = Vec::new();
487        for tool in &self.tools {
488            let (Some(path), Some(method)) = (tool.path.as_deref(), tool.method.as_deref()) else {
489                continue;
490            };
491            // An OpenAPI path template never carries a query string; the curated
492            // surface permits one (plan 06's `?` narrowing), so strip it first.
493            let template = path.split_once('?').map_or(path, |(p, _)| p);
494            if spec.operation_for(template, method).is_some() {
495                continue;
496            }
497            out.push(ConfigWarning {
498                tool: Some(tool.name.clone()),
499                param: None,
500                rule: CONFIGURED_TEMPLATE_NOT_IN_SPEC,
501                detail: format!(
502                    "declares `method = \"{method}\"` and `path = \"{path}\"`, which matches no \
503                     operation in the supplied OpenAPI document. The tool still works and its \
504                     path placeholders still face the unconditional character floor and the \
505                     always-on length cap, but the spec's declared pattern/maxLength narrowing \
506                     is NOT applied to them — a placeholder named differently from the spec's \
507                     own (`{{alias}}` against a declared `{{id}}`) reaches the same endpoint \
508                     with its declaration silently dropped. Spell the path and method exactly \
509                     as the spec declares them, or remove the spec if this endpoint is \
510                     deliberately undocumented."
511                ),
512            });
513        }
514        out
515    }
516
517    /// A structured account of what THIS config actually enforces, for the
518    /// once-at-startup log (Phase 128 D-07 / `<specifics>`).
519    ///
520    /// The startup log is the regression-tracing mechanism, not optional polish: it
521    /// is how an operator discovers, from a deploy log alone, that a server is
522    /// running with schema enforcement off or with the cap disabled.
523    #[must_use]
524    pub(crate) fn validation_report(&self) -> ValidationReport {
525        let validation = &self.server.validation;
526        let mut opt_outs = Vec::new();
527        lint_opt_outs(validation, &mut opt_outs);
528        ValidationReport {
529            enforce_input_schema: validation.enforce_input_schema,
530            default_max_length: validation.default_max_length,
531            additional_properties: validation.additional_properties,
532            strict: validation.strict,
533            tools: self
534                .tools
535                .iter()
536                .map(|t| tool_validation_report(t, validation))
537                .collect(),
538            opt_outs: opt_outs.iter().map(ToString::to_string).collect(),
539        }
540    }
541}
542
543/// What [`ServerConfig::validation_report`] returns: the enforcement actually in
544/// effect, per server and per tool.
545#[derive(Debug, Clone, PartialEq, Eq)]
546pub(crate) struct ValidationReport {
547    /// Effective [`ValidationSection::enforce_input_schema`].
548    pub enforce_input_schema: bool,
549    /// Effective [`ValidationSection::default_max_length`].
550    pub default_max_length: u64,
551    /// Effective [`ValidationSection::additional_properties`].
552    pub additional_properties: bool,
553    /// Effective [`ValidationSection::strict`].
554    pub strict: bool,
555    /// One entry per `[[tools]]`, in declaration order.
556    pub tools: Vec<ToolValidationReport>,
557    /// Rendered active opt-outs — EMPTY when the server enforces everything it can.
558    pub opt_outs: Vec<String>,
559}
560
561/// One tool's row in a [`ValidationReport`].
562#[derive(Debug, Clone, PartialEq, Eq)]
563pub(crate) struct ToolValidationReport {
564    /// The `[[tools]]` `name`.
565    pub tool: String,
566    /// Rendered per-parameter rules in declaration order, e.g.
567    /// `"region: path, pattern, maxLength=256 (default)"`. Reads as a log line.
568    pub rules: Vec<String>,
569}
570
571// -----------------------------------------------------------------------------
572// Phase 128 D3 / D-07 — `lint()` internals
573// -----------------------------------------------------------------------------
574
575/// Whether a parameter's EFFECTIVE JSON Schema type is `string`.
576///
577/// `param_type` defaults to `"string"` when omitted, matching
578/// `tools.rs::build_param_property`, so an omitted `type` is a string here too. A
579/// divergence would make the cap apply to a different set of parameters than the
580/// one the schema builder emits it for.
581pub(crate) fn is_string_param(p: &ParamDecl) -> bool {
582    p.param_type.as_deref().unwrap_or("string") == "string"
583}
584
585/// Whether the D3 default cap applies to a parameter at `position`.
586///
587/// All four conditions, in one place so `lint()` and
588/// `tools.rs::apply_position_cap` cannot disagree about which parameters are
589/// covered: the effective type is `string`, no `max_length` is declared, the
590/// configured default is non-zero, and the position is `Path` or `Query`.
591pub(crate) fn default_cap_applies(
592    p: &ParamDecl,
593    position: ParamPosition,
594    validation: &ValidationSection,
595) -> bool {
596    is_string_param(p) && p.max_length.is_none() && cap_position_applies(position, validation)
597}
598
599/// The POSITION half of [`default_cap_applies`]: whether the D3 default cap
600/// reaches `position` at all, independent of any particular parameter.
601///
602/// Split out because the two conditions are about different things — this one is
603/// "does the cap reach here", the other two are "does this parameter need it" —
604/// and because [`is_uncapped_string`] has to negate THIS half while asserting the
605/// other two. Negating the whole of `default_cap_applies` instead is a double
606/// negative over a predicate that redundantly re-checks its own premises.
607///
608/// Private: both callers are in this module. `default_cap_applies` is the
609/// `pub(crate)` face of the same question.
610fn cap_position_applies(position: ParamPosition, validation: &ValidationSection) -> bool {
611    validation.default_max_length != 0
612        && matches!(position, ParamPosition::Path | ParamPosition::Query)
613}
614
615/// Whether `p` is a string parameter that ends up with NO length bound at all —
616/// neither a declared `max_length` nor the D3 default cap.
617///
618/// The single definition behind both the `uncapped-string` `lint()` finding and
619/// the `strict`-mode [`ConfigValidationError::UncappedStringParam`] refusal, which
620/// must cover exactly the same parameters: a warning that `strict` would not
621/// refuse, or a refusal that `lint()` never warned about, is a drift defect.
622fn is_uncapped_string(
623    p: &ParamDecl,
624    position: ParamPosition,
625    validation: &ValidationSection,
626) -> bool {
627    is_string_param(p) && p.max_length.is_none() && !cap_position_applies(position, validation)
628}
629
630/// WHY a parameter ends up with no length bound. [`is_uncapped_string`] is
631/// position-BLIND — `cap_position_applies` is false either because the position is
632/// outside the cap's reach OR because `default_max_length = 0` switched the cap off
633/// for every position — and the two reasons need different prose.
634///
635/// Split out because the finding used to name only the first reason, rendering
636/// `... is in Path position, where the [server.validation] default_max_length cap
637/// deliberately does not apply` for a PATH parameter under
638/// `default_max_length = 0`. That is false twice over: the cap does reach Path, and
639/// what actually disabled it was the operator's own server-level opt-out — which
640/// emits its own [`OPT_OUT_DEFAULT_MAX_LENGTH_ZERO`] warning and is a supported
641/// configuration, not an unreachable one. A finding that misnames its own cause
642/// sends the operator to declare a `max_length` per parameter when one config key
643/// explains all of them.
644fn uncapped_reason(position: ParamPosition, validation: &ValidationSection) -> String {
645    if validation.default_max_length == 0 {
646        "[server.validation] default_max_length = 0 switches the default cap off for \
647         EVERY position on this server"
648            .to_string()
649    } else {
650        format!(
651            "it is in {position:?} position, which the [server.validation] \
652             default_max_length cap deliberately does not reach (free text must keep \
653             working)"
654        )
655    }
656}
657
658/// Per-tool `lint()` findings, appended in `[[tools.parameters]]` declaration
659/// order.
660fn lint_tool(tool: &ToolDecl, validation: &ValidationSection, out: &mut Vec<ConfigWarning>) {
661    for p in &tool.parameters {
662        let position = tool.param_position(&p.name);
663        if is_uncapped_string(p, position, validation) {
664            out.push(ConfigWarning {
665                tool: Some(tool.name.clone()),
666                param: Some(p.name.clone()),
667                rule: UNCAPPED_STRING,
668                detail: format!(
669                    "declares no max_length and no default cap reaches it, so it is \
670                     unbounded: {} — declare an explicit max_length, or set \
671                     [server.validation] strict = true to make this an error",
672                    uncapped_reason(position, validation)
673                ),
674            });
675        }
676        if let Some(declared) = p.max_length {
677            lint_declared_cap_above_placeholder_floor(tool, p, position, declared, out);
678        }
679    }
680}
681
682/// SC-7 shape mismatch: a path- or query-position parameter declaring a
683/// `max_length` ABOVE the always-on placeholder floor publishes a limit in
684/// `inputSchema` that `validate_path_placeholder` will not honour, so the call is
685/// refused against a rule the client was never told about.
686///
687/// The floor is read from
688/// `pmcp::server::schema_validation::PLACEHOLDER_MAX_LENGTH` — the ONE copy of
689/// that number (D-08) — and is therefore only available under `input-validation`.
690/// See the `cfg(not(...))` sibling for why its absence makes this finding vacuous
691/// rather than merely unavailable.
692#[cfg(feature = "input-validation")]
693fn lint_declared_cap_above_placeholder_floor(
694    tool: &ToolDecl,
695    p: &ParamDecl,
696    position: ParamPosition,
697    declared: u64,
698    out: &mut Vec<ConfigWarning>,
699) {
700    if !matches!(position, ParamPosition::Path | ParamPosition::Query) {
701        return;
702    }
703    let floor = pmcp::server::schema_validation::PLACEHOLDER_MAX_LENGTH as u64;
704    if declared <= floor {
705        return;
706    }
707    out.push(ConfigWarning {
708        tool: Some(tool.name.clone()),
709        param: Some(p.name.clone()),
710        rule: DECLARED_MAX_LENGTH_ABOVE_PLACEHOLDER_CAP,
711        detail: format!(
712            "declares max_length = {declared} in {position:?} position, but the always-on \
713             path-placeholder floor refuses at {floor} code points regardless — so the \
714             effective limit is {floor}, and a refusal would name a limit the published \
715             inputSchema never advertised. Lower the declared max_length to {floor} or below."
716        ),
717    });
718}
719
720/// The `input-validation`-off half of the placeholder-floor lint.
721//
722// Why a no-op rather than a duplicated `256`: the floor this finding warns about
723// is `pmcp::server::schema_validation::PLACEHOLDER_MAX_LENGTH`, which is a module
724// constant precisely so exactly one copy of the number exists (D-08). On a build
725// without `input-validation` that floor is not compiled and not enforced, so there
726// is no shape MISMATCH to report — the declared `max_length` is the only limit
727// there is, and it is honoured. Hard-coding a second `256` here to keep the
728// finding alive would report a rule that this build does not apply.
729//
730// The genuinely-missing enforcement on such a build is reported once per
731// `validate()` by `warn_if_pattern_checking_unavailable`, not here.
732#[cfg(not(feature = "input-validation"))]
733fn lint_declared_cap_above_placeholder_floor(
734    _tool: &ToolDecl,
735    _p: &ParamDecl,
736    _position: ParamPosition,
737    _declared: u64,
738    _out: &mut Vec<ConfigWarning>,
739) {
740}
741
742/// One finding per ACTIVE `[server.validation]` opt-out, so a switched-off
743/// enforcement can never read as switched on.
744fn lint_opt_outs(validation: &ValidationSection, out: &mut Vec<ConfigWarning>) {
745    if !validation.enforce_input_schema {
746        out.push(server_warning(
747            OPT_OUT_ENFORCE_INPUT_SCHEMA,
748            "[server.validation] enforce_input_schema = false: declared inputSchema values \
749             are NOT checked at tools/call time. Explicitly-registered argument validators \
750             still run — this flag does not disable them."
751                .to_string(),
752        ));
753    }
754    if validation.default_max_length == 0 {
755        out.push(server_warning(
756            OPT_OUT_DEFAULT_MAX_LENGTH_ZERO,
757            "[server.validation] default_max_length = 0: no default maxLength is emitted in \
758             ANY position, so a path or query string parameter that declares no max_length \
759             is unbounded in the published schema. The always-on path-placeholder floor is \
760             unaffected."
761                .to_string(),
762        ));
763    }
764    if validation.additional_properties {
765        out.push(server_warning(
766            OPT_OUT_ADDITIONAL_PROPERTIES,
767            "[server.validation] additional_properties = true: UNDECLARED arguments are \
768             accepted, re-opening the unknown-argument class for every tool on this server."
769                .to_string(),
770        ));
771    }
772}
773
774/// A server-level [`ConfigWarning`] — no `tool`, no `param`.
775fn server_warning(rule: &'static str, detail: String) -> ConfigWarning {
776    ConfigWarning {
777        tool: None,
778        param: None,
779        rule,
780        detail,
781    }
782}
783
784/// One tool's [`ToolValidationReport`] row.
785fn tool_validation_report(tool: &ToolDecl, validation: &ValidationSection) -> ToolValidationReport {
786    ToolValidationReport {
787        tool: tool.name.clone(),
788        rules: tool
789            .parameters
790            .iter()
791            .map(|p| render_param_rules(tool, p, validation))
792            .collect(),
793    }
794}
795
796/// Render ONE parameter's effective rules as a log-readable line.
797fn render_param_rules(tool: &ToolDecl, p: &ParamDecl, validation: &ValidationSection) -> String {
798    let position = tool.param_position(&p.name);
799    let mut parts = vec![format!("{position:?}")];
800    if p.required {
801        parts.push("required".to_string());
802    }
803    if p.pattern.is_some() {
804        parts.push("pattern".to_string());
805    }
806    if let Some(format) = &p.format {
807        parts.push(format!("format={format}"));
808    }
809    if let Some(min) = p.min_length {
810        parts.push(format!("minLength={min}"));
811    }
812    if let Some(max) = p.max_length {
813        parts.push(format!("maxLength={max} (declared)"));
814    } else if default_cap_applies(p, position, validation) {
815        parts.push(format!(
816            "maxLength={} (default)",
817            validation.default_max_length
818        ));
819    }
820    format!("{}: {}", p.name, parts.join(", "))
821}
822
823/// Machine-readable [`ConfigWarning::rule`] identifier: an uncapped body string.
824pub const UNCAPPED_STRING: &str = "uncapped-string";
825/// Machine-readable [`ConfigWarning::rule`] identifier: a declared `max_length`
826/// above the always-on path-placeholder floor.
827pub const DECLARED_MAX_LENGTH_ABOVE_PLACEHOLDER_CAP: &str =
828    "declared-max-length-above-placeholder-cap";
829/// Machine-readable [`ConfigWarning::rule`] identifier: a configured single-call
830/// `(method, path)` that matches no operation in the supplied OpenAPI document, so
831/// the spec's declared placeholder narrowing is not applied to that tool
832/// (Phase 128, D4(b) / T-128-36a). Emitted by
833/// [`ServerConfig::lint_against_spec`](crate::config::ServerConfig::lint_against_spec).
834pub const CONFIGURED_TEMPLATE_NOT_IN_SPEC: &str = "configured-template-not-in-spec";
835/// Machine-readable [`ConfigWarning::rule`] identifier: schema enforcement off.
836pub const OPT_OUT_ENFORCE_INPUT_SCHEMA: &str = "opt-out-enforce-input-schema";
837/// Machine-readable [`ConfigWarning::rule`] identifier: default cap disabled.
838pub const OPT_OUT_DEFAULT_MAX_LENGTH_ZERO: &str = "opt-out-default-max-length-zero";
839/// Machine-readable [`ConfigWarning::rule`] identifier: unknown arguments accepted.
840pub const OPT_OUT_ADDITIONAL_PROPERTIES: &str = "opt-out-additional-properties";
841
842// -----------------------------------------------------------------------------
843// Phase 128 D2 / SC-2 — per-parameter declaration checks
844// -----------------------------------------------------------------------------
845
846/// The largest integer magnitude an `f64` represents exactly (2^53).
847///
848/// [`ParamDecl::minimum`] / [`ParamDecl::maximum`] are `f64`, so a declared bound
849/// above this cannot round-trip. See [`ConfigValidationError::NonFiniteParamBound`]
850/// for exactly what a magnitude check on the already-parsed value can and cannot
851/// establish.
852const MAX_EXACT_INTEGER_BOUND: f64 = 9_007_199_254_740_992.0;
853
854/// Run the Phase 128 D2 / SC-2 declaration checks for ONE `[[tools]]` entry.
855///
856/// Split out of [`ServerConfig::validate`] so that function stays well under the
857/// cog-25 gate as rules accumulate.
858///
859/// # Errors
860///
861/// [`ConfigValidationError::EmptyParamPattern`],
862/// [`ConfigValidationError::NonFiniteParamBound`], or
863/// [`ConfigValidationError::UncompilableParamSchema`] — first rule violated, in
864/// `[[tools.parameters]]` declaration order.
865fn validate_tool_parameters(
866    tool: &ToolDecl,
867    validation: &ValidationSection,
868) -> std::result::Result<(), ConfigValidationError> {
869    for p in &tool.parameters {
870        check_param_patterns_non_empty(tool, p)?;
871        check_param_bounds_representable(tool, p)?;
872        if validation.strict {
873            check_param_capped_under_strict(tool, p, validation)?;
874        }
875    }
876    check_path_template_segments(tool)?;
877    check_tool_input_schema_compiles(tool, validation)
878}
879
880/// Refuse a single-call `path` template segment the curated substitution parser
881/// cannot recognize (Phase 128, D4(b)).
882///
883/// # Why this is a hard error rather than a `lint()` finding
884///
885/// A malformed segment has no working interpretation. `/search/{a}{b}` yields the
886/// parameter name `a}{b`, which no `[[tools.parameters]]` entry can match, and
887/// `/prefix-{id}` is not recognized as carrying a placeholder at all — so in both
888/// cases literal braces are what would travel toward the backend. That request is
889/// already refused at call time by the composed-path check in
890/// `crate::http::HttpClient`, so the choice here is only between failing loudly at
891/// startup and failing obscurely on every call. Nothing that worked before loses a
892/// working behaviour; a silently-broken tool gains a message naming the segment.
893///
894/// Contrast [`ConfigValidationError::UncappedStringParam`], which is `strict`-only
895/// precisely because an uncapped free-text field DOES have a working
896/// interpretation (D-05).
897///
898/// # Errors
899///
900/// [`ConfigValidationError::MalformedPathTemplateSegment`], naming the first
901/// offending segment in left-to-right order.
902fn check_path_template_segments(tool: &ToolDecl) -> std::result::Result<(), ConfigValidationError> {
903    let Some(path) = tool.path.as_deref() else {
904        // No `path` — a SQL or script tool carries no template.
905        return Ok(());
906    };
907    for segment in path.split('/') {
908        if is_supported_path_segment(segment) {
909            continue;
910        }
911        return Err(ConfigValidationError::MalformedPathTemplateSegment {
912            tool: tool.name.clone(),
913            segment: segment.to_string(),
914        });
915    }
916    Ok(())
917}
918
919/// Whether ONE `/`-delimited path-template segment is a shape
920/// [`path_placeholder_names`] recognizes.
921///
922/// Exactly two shapes are supported: a segment containing no brace at all, and a
923/// segment that is exactly one non-empty `{name}` spanning the whole segment with
924/// no further brace inside the name. This predicate is the inverse of
925/// [`path_placeholder_names`]'s filter, extended to also catch the
926/// carries-a-brace-but-is-not-a-placeholder cases that filter silently drops.
927fn is_supported_path_segment(segment: &str) -> bool {
928    if !segment.contains('{') && !segment.contains('}') {
929        return true;
930    }
931    // `{` and `}` are single-byte, so the inner slice is always a char boundary.
932    segment.starts_with('{')
933        && segment.ends_with('}')
934        && segment.len() > 2
935        && !segment[1..segment.len() - 1].contains('{')
936        && !segment[1..segment.len() - 1].contains('}')
937}
938
939/// D-07 strict mode: promote an `uncapped-string` lint finding into a hard
940/// `validate()` failure.
941///
942/// Gated on `[server.validation] strict` by the caller, because a running server
943/// must NOT refuse to boot over an uncapped free-text body parameter (D-05). This
944/// path exists for a CI config check, where refusing is exactly right.
945///
946/// # Errors
947///
948/// [`ConfigValidationError::UncappedStringParam`].
949fn check_param_capped_under_strict(
950    tool: &ToolDecl,
951    p: &ParamDecl,
952    validation: &ValidationSection,
953) -> std::result::Result<(), ConfigValidationError> {
954    let position = tool.param_position(&p.name);
955    if is_uncapped_string(p, position, validation) {
956        return Err(ConfigValidationError::UncappedStringParam {
957            tool: tool.name.clone(),
958            param: p.name.clone(),
959        });
960    }
961    Ok(())
962}
963
964/// SC-2 edge (empty): refuse `pattern = ""` on the parameter OR on its
965/// `[tools.parameters.items]` sub-table.
966///
967/// # Errors
968///
969/// [`ConfigValidationError::EmptyParamPattern`].
970fn check_param_patterns_non_empty(
971    tool: &ToolDecl,
972    p: &ParamDecl,
973) -> std::result::Result<(), ConfigValidationError> {
974    let declared = [
975        p.pattern.as_deref(),
976        p.items.as_ref().and_then(|i| i.pattern.as_deref()),
977    ];
978    if declared.into_iter().flatten().any(str::is_empty) {
979        return Err(ConfigValidationError::EmptyParamPattern {
980            tool: tool.name.clone(),
981            param: p.name.clone(),
982        });
983    }
984    Ok(())
985}
986
987/// D3 edge (precision): refuse a `minimum`/`maximum` that an `f64` cannot carry
988/// exactly. See [`ConfigValidationError::NonFiniteParamBound`] for what this does
989/// and does not establish.
990///
991/// # Errors
992///
993/// [`ConfigValidationError::NonFiniteParamBound`].
994fn check_param_bounds_representable(
995    tool: &ToolDecl,
996    p: &ParamDecl,
997) -> std::result::Result<(), ConfigValidationError> {
998    let unrepresentable = [p.minimum, p.maximum]
999        .into_iter()
1000        .flatten()
1001        .any(|b| !b.is_finite() || b.abs() > MAX_EXACT_INTEGER_BOUND);
1002    if unrepresentable {
1003        return Err(ConfigValidationError::NonFiniteParamBound {
1004            tool: tool.name.clone(),
1005            param: p.name.clone(),
1006        });
1007    }
1008    Ok(())
1009}
1010
1011/// SC-2: compile the tool's synthesized `inputSchema` at CONFIG time, so a
1012/// non-compiling `pattern` fails here — naming the parameter — rather than at call
1013/// time, where it would take the tool's entire validator down.
1014///
1015/// Reuses `crate::tools::build_input_schema`, the same constructor the runtime
1016/// serves from, so the gate cannot pass a schema the server never actually uses.
1017/// `jsonschema::meta::is_valid` is deliberately NOT the check: it returns `true`
1018/// for a schema whose nested `pattern` does not compile (measured — RESEARCH
1019/// Finding 1e), which is precisely the mistake this gate exists to catch.
1020///
1021/// # Errors
1022///
1023/// [`ConfigValidationError::UncompilableParamSchema`] carrying the compile error's
1024/// own schema path and detail. Quoting the detail is safe here and only here: this
1025/// runs at load time with no request in scope and its audience is the config author.
1026#[cfg(feature = "input-validation")]
1027fn check_tool_input_schema_compiles(
1028    tool: &ToolDecl,
1029    validation: &ValidationSection,
1030) -> std::result::Result<(), ConfigValidationError> {
1031    let schema = crate::tools::build_input_schema(tool, validation);
1032    pmcp::server::schema_validation::check_input_schema_compiles(&schema).map_err(|violation| {
1033        ConfigValidationError::UncompilableParamSchema {
1034            tool: tool.name.clone(),
1035            position: violation.pointer,
1036            detail: violation.expected,
1037        }
1038    })
1039}
1040
1041/// The `input-validation`-off half of the SC-2 gate.
1042//
1043// Why this arm exists at all, rather than an ungated call: `ServerConfig::validate`
1044// compiles in EVERY toolkit feature set, while
1045// `pmcp::server::schema_validation::check_input_schema_compiles` exists only under
1046// `pmcp/schema-validation` (forwarded by the toolkit's `input-validation`). An
1047// ungated call breaks `cargo build -p pmcp-server-toolkit --no-default-features
1048// --features http`, which is a real supported configuration.
1049//
1050// Why it is not a SILENT skip: on this build a declared `pattern` is neither
1051// verified here nor enforced at call time, so an author who sees `validate()`
1052// return `Ok(())` would reasonably believe their rule was checked. That is exactly
1053// the "an enforcement that is off must never read as on" prohibition. The warning
1054// is emitted once per `validate()` by `warn_if_pattern_checking_unavailable`, not
1055// per tool, so a large config does not bury it.
1056#[cfg(not(feature = "input-validation"))]
1057fn check_tool_input_schema_compiles(
1058    _tool: &ToolDecl,
1059    _validation: &ValidationSection,
1060) -> std::result::Result<(), ConfigValidationError> {
1061    Ok(())
1062}
1063
1064/// Emit the once-per-`validate()` warning when this build cannot check declared
1065/// `pattern` values. A no-op when the `input-validation` feature is on, and a
1066/// no-op when the config declares no `pattern` at all (there is nothing unchecked
1067/// to report).
1068#[cfg(not(feature = "input-validation"))]
1069fn warn_if_pattern_checking_unavailable(tools: &[ToolDecl]) {
1070    let declares_a_pattern = tools.iter().any(|t| {
1071        t.parameters
1072            .iter()
1073            .any(|p| p.pattern.is_some() || p.items.as_ref().is_some_and(|i| i.pattern.is_some()))
1074    });
1075    if declares_a_pattern {
1076        tracing::warn!(
1077            "this build lacks the `input-validation` feature: declared \
1078             [[tools.parameters]] `pattern` values were NOT checked for compilability at \
1079             config time, and will NOT be enforced at tools/call time either — enable \
1080             `input-validation` to get either"
1081        );
1082    }
1083}
1084
1085/// See the `cfg(not(...))` sibling. Under `input-validation` the patterns ARE
1086/// checked, so there is nothing to warn about.
1087#[cfg(feature = "input-validation")]
1088#[allow(clippy::missing_const_for_fn)] // Why: mirrors the cfg(not(...)) sibling's signature, which cannot be const.
1089fn warn_if_pattern_checking_unavailable(_tools: &[ToolDecl]) {}
1090
1091// -----------------------------------------------------------------------------
1092// [server]
1093// -----------------------------------------------------------------------------
1094
1095/// `[server]` section — identity and version metadata.
1096#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1097#[serde(deny_unknown_fields)]
1098pub struct ServerSection {
1099    /// Stable server identifier (e.g. `"open-images"`). Optional in the TOML;
1100    /// callers that need it should fall back to deriving from `name`.
1101    #[serde(default)]
1102    pub id: Option<String>,
1103    /// Human-readable server name (required for production via [`ServerConfig::validate`]).
1104    #[serde(default)]
1105    pub name: String,
1106    /// Short server description.
1107    #[serde(default)]
1108    pub description: Option<String>,
1109    /// Server flavour (e.g. `"sql-api"`). Free-form for now; future plans may tighten.
1110    #[serde(default, rename = "type")]
1111    pub server_type: Option<String>,
1112    /// Semver version string (required for production via [`ServerConfig::validate`]).
1113    #[serde(default)]
1114    pub version: String,
1115    /// Whether this server is the **reference** server that provisions shared
1116    /// infrastructure (the `[shared_policy_store]` for all sibling SQL servers).
1117    /// Additive per the REF-01 superset invariant (Plan 85-01); the SQLite
1118    /// Chinook reference config sets `is_reference = true`.
1119    #[serde(default)]
1120    pub is_reference: bool,
1121    /// `[server.validation]` — input-enforcement policy (Phase 128, D3 / D-06).
1122    ///
1123    /// Absent in TOML yields [`ValidationSection::default`], i.e. enforcement ON
1124    /// with a 256-code-point default cap in path and query position.
1125    #[serde(default)]
1126    pub validation: ValidationSection,
1127}
1128
1129/// `[server.validation]` — how strictly a config-declared tool's inputs are
1130/// enforced (Phase 128, D3 / D-06 / D-07).
1131///
1132/// Every field here is an OPT-OUT knob, and every active opt-out is reported by
1133/// [`ServerConfig::lint`] and by [`ServerConfig::validation_report`] so it appears
1134/// in the startup log. That is deliberate: a validation rule switched off by a
1135/// configuration value must never read as switched on.
1136///
1137/// # Forward incompatibility (D-15)
1138///
1139/// [`ServerSection`] and [`ServerConfig`] both carry
1140/// `#[serde(deny_unknown_fields)]`, so a config carrying a `[server.validation]`
1141/// section fails to PARSE on toolkit 0.1.3 rather than having the section ignored.
1142/// Named in the CHANGELOG, exactly as the [`ParamDecl`] D2 keys are.
1143///
1144/// # Examples
1145///
1146/// ```
1147/// use pmcp_server_toolkit::config::ValidationSection;
1148///
1149/// let v = ValidationSection::default();
1150/// assert!(v.enforce_input_schema);
1151/// assert_eq!(v.default_max_length, 256);
1152/// assert!(!v.additional_properties);
1153/// assert!(!v.strict);
1154/// ```
1155#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1156#[serde(deny_unknown_fields)]
1157pub struct ValidationSection {
1158    /// Whether a declared `inputSchema` is CHECKED at `tools/call` time.
1159    ///
1160    /// The checker is `pmcp::server::schema_validation::validate_input`, called
1161    /// from the `ValidatingToolHandler` decorator in [`crate::tools`] — in THIS
1162    /// crate, before the backend call. Not core `pmcp`'s `tools/call` dispatch,
1163    /// which does not validate request arguments against a declared `inputSchema`
1164    /// (Phase 128 D-01 defers that wiring). Naming the enforcer is this phase's
1165    /// SC-6 convention; the sweep that produced it found the unqualified form of
1166    /// this sentence three times in `tools.rs` alone.
1167    ///
1168    /// Default `true`. Setting it `false` skips the schema check only — it does
1169    /// NOT disable an explicitly-registered argument validator. Turning off one
1170    /// enforcement must never silently turn off another, so the two live on
1171    /// separate switches and the decorator is still constructed whenever a
1172    /// validator is registered for the tool.
1173    #[serde(default = "default_enforce_input_schema")]
1174    pub enforce_input_schema: bool,
1175    /// Default `maxLength`, in Unicode code points, emitted for a PATH- or
1176    /// QUERY-position string parameter that declares no `max_length` of its own
1177    /// (D-06).
1178    ///
1179    /// Default `256`. A declared `max_length` is never overridden and never merged
1180    /// with this value. Body-position strings are deliberately NOT capped by it
1181    /// (D-05) — they are surfaced by [`ServerConfig::lint`] instead.
1182    ///
1183    /// `0` DISABLES the cap in every position and is reported as an active opt-out.
1184    /// It does not disable `pmcp::server::schema_validation::PLACEHOLDER_MAX_LENGTH`,
1185    /// which is a module constant precisely so the length half of the path-traversal
1186    /// fix cannot be configured away (D-08).
1187    #[serde(default = "default_default_max_length")]
1188    pub default_max_length: u64,
1189    /// Whether to permit UNDECLARED arguments, by emitting
1190    /// `additionalProperties: true` instead of `false`.
1191    ///
1192    /// Default `false` (unknown arguments are refused). `true` re-opens the
1193    /// unknown-argument class for this server and is reported as an active opt-out.
1194    #[serde(default)]
1195    pub additional_properties: bool,
1196    /// Whether [`ServerConfig::lint`] findings are promoted into hard
1197    /// [`ServerConfig::validate`] failures.
1198    ///
1199    /// Default `false`: a running server never refuses to boot over an uncapped
1200    /// free-text body parameter (D-07). `true` turns each such parameter into
1201    /// [`ConfigValidationError::UncappedStringParam`], which is what a CI config
1202    /// check wants and what a production boot does not.
1203    #[serde(default)]
1204    pub strict: bool,
1205}
1206
1207/// The shipped default cap, in Unicode code points (D-06).
1208const DEFAULT_MAX_LENGTH: u64 = 256;
1209
1210/// serde default for [`ValidationSection::enforce_input_schema`]. Enforcement is
1211/// ON unless an operator explicitly opts out.
1212const fn default_enforce_input_schema() -> bool {
1213    true
1214}
1215
1216/// serde default for [`ValidationSection::default_max_length`].
1217const fn default_default_max_length() -> u64 {
1218    DEFAULT_MAX_LENGTH
1219}
1220
1221impl Default for ValidationSection {
1222    fn default() -> Self {
1223        Self {
1224            enforce_input_schema: default_enforce_input_schema(),
1225            default_max_length: default_default_max_length(),
1226            additional_properties: false,
1227            strict: false,
1228        }
1229    }
1230}
1231
1232// -----------------------------------------------------------------------------
1233// [metadata]
1234// -----------------------------------------------------------------------------
1235
1236/// `[metadata]` section — admin-facing display defaults (visible in the
1237/// pmcp.run UI before an operator customises them).
1238#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1239#[serde(deny_unknown_fields)]
1240pub struct MetadataSection {
1241    /// Long-form display name shown in the UI.
1242    #[serde(default)]
1243    pub display_name: Option<String>,
1244    /// One-line summary for list views.
1245    #[serde(default)]
1246    pub short_description: Option<String>,
1247    /// Multi-line description for detail pages.
1248    #[serde(default)]
1249    pub description: Option<String>,
1250    /// Tag list for filtering / discovery.
1251    #[serde(default)]
1252    pub tags: Vec<String>,
1253    /// Server author (organisation or individual).
1254    #[serde(default)]
1255    pub author: Option<String>,
1256    /// Visibility flag (e.g. `"public"`, `"private"`).
1257    #[serde(default)]
1258    pub visibility: Option<String>,
1259}
1260
1261// -----------------------------------------------------------------------------
1262// [database]
1263// -----------------------------------------------------------------------------
1264
1265/// `[database]` section — backend identification and table catalogue.
1266///
1267/// Includes Athena-specific keys (`output_location`, `workgroup`) as optional
1268/// fields per the REF-01 superset invariant — non-Athena backends omit them.
1269#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1270#[serde(deny_unknown_fields)]
1271pub struct DatabaseSection {
1272    /// Backend type (`"athena"`, `"postgres"`, `"mysql"`, `"sqlite"`, …).
1273    #[serde(default, rename = "type")]
1274    pub backend_type: Option<String>,
1275    /// Database / schema name.
1276    #[serde(default)]
1277    pub database: Option<String>,
1278    /// Athena S3 output location for query results.
1279    #[serde(default)]
1280    pub output_location: Option<String>,
1281    /// Athena workgroup name.
1282    #[serde(default)]
1283    pub workgroup: Option<String>,
1284    /// Per-query timeout in milliseconds.
1285    #[serde(default)]
1286    pub query_timeout_ms: Option<u64>,
1287    /// `[[database.tables]]` — declared table catalogue for schema enrichment.
1288    #[serde(default)]
1289    pub tables: Vec<DatabaseTableDecl>,
1290    /// Connection URL for Postgres / MySQL backends. Supports `env:VAR_NAME`
1291    /// indirection at the consumer-resolution layer (the toolkit parses the
1292    /// string as-is and leaves resolution to the per-backend connector or
1293    /// the secret-resolution machinery from P83 R6/R9). Optional/unused for
1294    /// Athena (uses `region` + `workgroup` + `output_location`) and SQLite
1295    /// (uses `database` for the file path or `:memory:` literal).
1296    #[serde(default)]
1297    pub url: Option<String>,
1298    /// Filesystem path to a SQLite database file (e.g.
1299    /// `"/var/task/assets/chinook.db"` for a Lambda-bundled asset). Additive per
1300    /// the REF-01 superset invariant (Plan 85-01). Distinct from `database`
1301    /// (which carries the `:memory:` literal or a schema name) and `url` (used
1302    /// by Postgres / MySQL). Stored verbatim; the SQLite connector resolves it.
1303    #[serde(default)]
1304    pub file_path: Option<String>,
1305    /// `[database.pool]` — connection-pool tuning (optional).
1306    #[serde(default)]
1307    pub pool: Option<DatabasePoolSection>,
1308}
1309
1310/// Single `[[database.tables]]` entry.
1311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1312#[serde(deny_unknown_fields)]
1313pub struct DatabaseTableDecl {
1314    /// Table or view name (required for production via [`ServerConfig::validate`]).
1315    #[serde(default)]
1316    pub name: String,
1317    /// Human-readable table description for schema enrichment.
1318    #[serde(default)]
1319    pub description: Option<String>,
1320}
1321
1322/// `[database.pool]` connection-pool tuning.
1323#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1324#[serde(deny_unknown_fields)]
1325pub struct DatabasePoolSection {
1326    /// Maximum concurrent connections.
1327    #[serde(default)]
1328    pub max_connections: Option<u32>,
1329    /// Connection-acquisition timeout, in seconds.
1330    #[serde(default)]
1331    pub connection_timeout_seconds: Option<u64>,
1332}
1333
1334// -----------------------------------------------------------------------------
1335// [backend] (http feature)
1336// -----------------------------------------------------------------------------
1337
1338/// Re-export of the outgoing-HTTP authentication config (owned by
1339/// [`crate::http::auth`], Plan 90-01). Callers may also reach it via the
1340/// `crate::http` module path; this re-export keeps `[backend.auth]` named
1341/// alongside the `ServerConfig` types it deserializes into.
1342#[cfg(feature = "http")]
1343pub use crate::http::auth::AuthConfig;
1344
1345/// Re-export of the HTTP client tuning config (owned by [`crate::http::client`],
1346/// Plan 90-01) used by `[backend.http]`.
1347#[cfg(feature = "http")]
1348pub use crate::http::client::HttpConfig;
1349
1350/// `[backend]` section — the OpenAPI/REST HTTP backend declaration (D-06).
1351///
1352/// This is the HTTP analog of [`DatabaseSection`]: it identifies the upstream
1353/// REST API the synthesized tools call. `base_url` is the API root; the optional
1354/// `[backend.auth]` sub-table selects an [`AuthConfig`] variant (`type = "..."`)
1355/// and `[backend.http]` carries [`HttpConfig`] tuning (timeout / retries / …).
1356///
1357/// Gated behind the `http` feature — the whole section (and the
1358/// [`ServerConfig::backend`] field) is absent in a no-http build so there is no
1359/// dead stub type. `AuthConfig` and `HttpConfig` are DEFINED in
1360/// [`crate::http`] (Plan 90-01) and re-exported here, not redefined (H3).
1361///
1362/// Strict-parse discipline (D-13) is preserved: `#[serde(deny_unknown_fields)]`
1363/// rejects a typo'd key under `[backend]` or `[backend.http]`.
1364///
1365/// Secrets posture (T-90-02-02): inline token fields under `[backend.auth]`
1366/// hold operator references (`${ENV}` / `env:VAR`) resolved upstream by the
1367/// Phase 83 secrets machinery — config parsing stores the string verbatim and
1368/// never the resolved value.
1369#[cfg(feature = "http")]
1370#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1371#[serde(deny_unknown_fields)]
1372pub struct BackendSection {
1373    /// REST API root URL (e.g. `"https://api.tfl.gov.uk"`). Single-call tools
1374    /// concatenate their `path` onto this (an empty per-tool `base_url`
1375    /// inherits this value).
1376    #[serde(default)]
1377    pub base_url: String,
1378    /// `[backend.auth]` — outgoing authentication ([`AuthConfig`], six modes).
1379    /// Defaults to [`AuthConfig::None`] when the sub-table is omitted.
1380    #[serde(default)]
1381    pub auth: AuthConfig,
1382    /// `[backend.http]` — client tuning ([`HttpConfig`]: timeout / retries /
1383    /// backoff / user-agent / default headers). Defaults to [`HttpConfig`]'s
1384    /// defaults when the sub-table is omitted.
1385    #[serde(default)]
1386    pub http: HttpConfig,
1387}
1388
1389#[cfg(feature = "http")]
1390impl BackendSection {
1391    /// Resolve [`Self::base_url`], expanding a `${VAR}` / `env:VAR` reference
1392    /// from the process environment. Callers MUST use this rather than reading
1393    /// `base_url` directly — the raw field may hold an unresolved placeholder.
1394    ///
1395    /// A Shape A server's endpoint is frequently a slot the target environment
1396    /// fills, so the config records `base_url = "${TFL_BASE_URL}"` and the
1397    /// package digest stays environment-independent. Without expansion that
1398    /// literal `${...}` parses, VALIDATES (it is non-empty, so the emptiness
1399    /// rule passes) and is then sent as the request URL.
1400    ///
1401    /// Resolution rules — the grammar is [`crate::env_ref::parse_env_ref`], the
1402    /// single toolkit-wide chokepoint:
1403    /// - a plain literal (no `${...}` / `env:` prefix) is returned VERBATIM;
1404    /// - `${VAR}` / `env:VAR` reads `VAR` from the process environment;
1405    /// - a MALFORMED reference — the empty `${}`, or a multi-placeholder
1406    ///   composition like `${A}://${B}` (a brace reference names exactly ONE
1407    ///   variable) — is an error;
1408    /// - an UNSET variable, or one set to an empty / whitespace-only value, is
1409    ///   an error.
1410    ///
1411    /// # Deliberate divergence from credential resolution
1412    ///
1413    /// A credential resolves an unset reference to the empty string so an
1414    /// optional credential is OMITTED (see `crate::http::auth`). An endpoint
1415    /// does NOT get that treatment: an empty credential yields a degraded
1416    /// request, but an empty endpoint yields a broken one, and
1417    /// [`ServerConfig::validate`] only checks emptiness at parse time — an
1418    /// empty resolution would sail through and then break every request. This
1419    /// uses the error-on-unset semantics of `code_mode`'s `token_secret`
1420    /// resolution instead.
1421    ///
1422    /// # Errors
1423    ///
1424    /// Returns [`ToolkitError::UnresolvedBaseUrlRef`] when the reference cannot
1425    /// be resolved. Per T-120-17 the error names the FIELD and the
1426    /// environment-variable NAME only — never a resolved URL or credential.
1427    ///
1428    /// # Examples
1429    ///
1430    /// ```
1431    /// use pmcp_server_toolkit::config::ServerConfig;
1432    ///
1433    /// let cfg = ServerConfig::from_toml_strict_validated(
1434    ///     "[server]\nname = \"demo\"\nversion = \"0.1.0\"\n\
1435    ///      [backend]\nbase_url = \"https://api.example.com\"\n",
1436    /// )
1437    /// .expect("valid config");
1438    /// let backend = cfg.backend.as_ref().expect("[backend] present");
1439    /// // A plain literal is used verbatim.
1440    /// assert_eq!(backend.resolved_base_url().unwrap(), "https://api.example.com");
1441    /// ```
1442    pub fn resolved_base_url(&self) -> std::result::Result<String, ToolkitError> {
1443        match crate::env_ref::parse_env_ref(&self.base_url) {
1444            // Plain literal — used verbatim (every existing [backend] config
1445            // and the four SQL reference configs land here, unchanged).
1446            None => Ok(self.base_url.clone()),
1447            // Malformed `${}` — a reference to an empty name. A credential
1448            // treats this as "omit"; an endpoint cannot be omitted.
1449            Some("") => Err(ToolkitError::UnresolvedBaseUrlRef { var: String::new() }),
1450            Some(name) => match std::env::var(name) {
1451                Ok(value) if !value.trim().is_empty() => Ok(value),
1452                // Unset, or set-but-empty/whitespace — the same error either
1453                // way. The VALUE is never carried into the error.
1454                _ => Err(ToolkitError::UnresolvedBaseUrlRef {
1455                    var: name.to_string(),
1456                }),
1457            },
1458        }
1459    }
1460}
1461
1462// -----------------------------------------------------------------------------
1463// [code_mode]
1464// -----------------------------------------------------------------------------
1465
1466/// `[code_mode]` section — code-mode policy + complexity limits.
1467///
1468/// The toolkit uses **unprefixed** field names (REF-01 invariant); the mapping
1469/// to `pmcp_code_mode::CodeModeConfig`'s prefixed names (`sql_allow_writes`,
1470/// etc.) is handled by Plan 06's executor wiring.
1471///
1472/// # Keys by backend
1473///
1474/// The SQL keys (`allow_writes`, `allow_deletes`, `allow_ddl`, `require_limit`,
1475/// `max_limit`, `blocked_tables`, `sensitive_columns`) apply to a SQL server.
1476/// The operation-class keys (`read_mode`, `write_mode`, `delete_mode`,
1477/// `admin_mode`, `allowed_operations`, `blocked_operations`, `blocked_paths`,
1478/// `[[code_mode.operations]]`) apply to an OpenAPI server (one with a
1479/// `[backend]`). [`ServerConfig::validate`] refuses a key set on the wrong kind
1480/// of server, because it would otherwise be silently ignored.
1481///
1482/// `#[non_exhaustive]` since 0.4: build one with `Default` and assign fields.
1483#[allow(clippy::struct_excessive_bools)]
1484// Why: REF-01 superset — these bools mirror the reference servers' [code_mode] block 1:1 (CONTEXT.md D-13). Grouping into a sub-struct would break REF-01.
1485#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1486#[serde(deny_unknown_fields)]
1487#[non_exhaustive]
1488pub struct CodeModeSection {
1489    /// Master enable flag for code-mode.
1490    #[serde(default)]
1491    pub enabled: bool,
1492    /// Server identifier used by AVP / Cedar policy resolution.
1493    #[serde(default)]
1494    pub server_id: Option<String>,
1495    /// Whether INSERT / UPDATE / MERGE statements are allowed.
1496    #[serde(default)]
1497    pub allow_writes: bool,
1498    /// Whether DELETE statements are allowed.
1499    #[serde(default)]
1500    pub allow_deletes: bool,
1501    /// Whether DDL (CREATE / ALTER / DROP) is allowed.
1502    #[serde(default)]
1503    pub allow_ddl: bool,
1504    /// Whether `SELECT` queries must declare a `LIMIT`.
1505    #[serde(default)]
1506    pub require_limit: bool,
1507    /// Maximum allowed `LIMIT` value.
1508    #[serde(default)]
1509    pub max_limit: Option<u64>,
1510    /// Table names blocked from any query (denylist).
1511    #[serde(default)]
1512    pub blocked_tables: Vec<String>,
1513    /// `table.column` strings stripped from query output.
1514    #[serde(default)]
1515    pub sensitive_columns: Vec<String>,
1516    /// Risk levels eligible for auto-approval (e.g. `["low"]`).
1517    #[serde(default)]
1518    pub auto_approve_levels: Vec<String>,
1519    /// Token TTL, in seconds, for HMAC-signed approval tokens.
1520    #[serde(default)]
1521    pub token_ttl_seconds: Option<u64>,
1522    /// Secret reference (e.g. `"${CODE_MODE_SECRET}"`) for HMAC signing — resolved
1523    /// at runtime by `SecretsProvider`. NEVER a raw secret value (review R6 +
1524    /// T-83-04-04 in the plan threat model).
1525    #[serde(default)]
1526    pub token_secret: Option<String>,
1527    /// Per Phase 83 review R9: inline `token_secret = "raw-string"` is REJECTED
1528    /// by default to prevent secrets from being committed to source-controlled
1529    /// configs. Set this flag to `true` ONLY in dev/test configs where the
1530    /// operator explicitly accepts the risk. NEVER set this in a committed
1531    /// production config — production must use the `env:VAR_NAME` syntax that
1532    /// resolves at runtime through `SecretsProvider`.
1533    #[serde(default)]
1534    pub allow_inline_token_secret_for_dev: bool,
1535    /// `[code_mode.limits]` — query-complexity caps.
1536    #[serde(default)]
1537    pub limits: Option<CodeModeLimits>,
1538    /// Operator text appended to BOTH the `validate_code` and `execute_code` tool
1539    /// descriptions, after the SDK's own.
1540    ///
1541    /// The place to tell the model what this deployment enforces that its own
1542    /// tool descriptions cannot know: "responses are de-identified", "queries
1543    /// over 100 rows are refused", "paths under /admin are blocked". The model
1544    /// reads a tool's description before it calls the tool, so a rule stated here
1545    /// is followed instead of discovered through a refusal.
1546    ///
1547    /// Appended verbatim after a blank line. Unset (the default) leaves both
1548    /// descriptions exactly as the SDK writes them.
1549    #[serde(default)]
1550    pub description_notice: Option<String>,
1551
1552    /// OpenAPI: how `read` operations are governed. Default `allow_all`.
1553    #[serde(default)]
1554    pub read_mode: Option<ClassModeName>,
1555    /// OpenAPI: how `write` operations (POST/PUT/PATCH unless the catalog
1556    /// says otherwise) are governed. Default `deny_all`.
1557    #[serde(default)]
1558    pub write_mode: Option<ClassModeName>,
1559    /// OpenAPI: how `delete` operations are governed. Default `deny_all`.
1560    #[serde(default)]
1561    pub delete_mode: Option<ClassModeName>,
1562    /// OpenAPI: how `admin` operations (only ever declared in
1563    /// `[[code_mode.operations]]`) are governed. Default `deny_all`.
1564    #[serde(default)]
1565    pub admin_mode: Option<ClassModeName>,
1566    /// OpenAPI: the operations an `allowlist` class admits. Each entry is a
1567    /// catalog `id` or an operation (`"GET /items/{id}"`). Required, and
1568    /// non-empty, when any class is `allowlist`.
1569    #[serde(default)]
1570    pub allowed_operations: Vec<String>,
1571    /// OpenAPI: operations refused in every class and mode. An HTTP method
1572    /// name (`"PATCH"`) blocks the method. Required, and non-empty, when any
1573    /// class is `blocklist`.
1574    #[serde(default)]
1575    pub blocked_operations: Vec<String>,
1576    /// OpenAPI: path patterns refused in every class (`*` matches any run of
1577    /// characters; a pattern without `*` covers the path and everything below
1578    /// it). Case is ignored.
1579    #[serde(default)]
1580    pub blocked_paths: Vec<String>,
1581    /// OpenAPI: `[[code_mode.operations]]` — the operation catalog. Its
1582    /// `category` classifies a call before the HTTP method does.
1583    #[serde(default)]
1584    pub operations: Vec<OperationDecl>,
1585}
1586
1587/// A class mode name in `[code_mode]` (`read_mode = "allow_all"`).
1588///
1589/// Closed: a misspelled mode fails the parse, it never falls back to a mode.
1590#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1591#[serde(rename_all = "snake_case")]
1592#[non_exhaustive]
1593pub enum ClassModeName {
1594    /// No operation of the class is allowed.
1595    DenyAll,
1596    /// Every operation of the class is allowed, except `blocked_operations`
1597    /// and `blocked_paths`.
1598    AllowAll,
1599    /// Only the class's operations listed in `allowed_operations`.
1600    Allowlist,
1601    /// Every operation of the class except `blocked_operations`. The same
1602    /// verdicts as `allow_all` (a block applies in every mode); accepted
1603    /// because it is the platform's name, and it requires a non-empty
1604    /// `blocked_operations`.
1605    Blocklist,
1606}
1607
1608impl ClassModeName {
1609    /// The config spelling.
1610    #[must_use]
1611    pub fn as_str(self) -> &'static str {
1612        match self {
1613            Self::DenyAll => "deny_all",
1614            Self::AllowAll => "allow_all",
1615            Self::Allowlist => "allowlist",
1616            Self::Blocklist => "blocklist",
1617        }
1618    }
1619}
1620
1621/// An operation class in `[[code_mode.operations]]`.
1622#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1623#[serde(rename_all = "lowercase")]
1624#[non_exhaustive]
1625pub enum OperationCategory {
1626    /// Retrieves data.
1627    Read,
1628    /// Creates or changes data.
1629    Write,
1630    /// Removes data.
1631    Delete,
1632    /// Changes the system itself. No HTTP method maps here; only a catalog
1633    /// entry can declare it.
1634    Admin,
1635}
1636
1637impl OperationCategory {
1638    /// The config spelling.
1639    #[must_use]
1640    pub fn as_str(self) -> &'static str {
1641        match self {
1642            Self::Read => "read",
1643            Self::Write => "write",
1644            Self::Delete => "delete",
1645            Self::Admin => "admin",
1646        }
1647    }
1648}
1649
1650/// One `[[code_mode.operations]]` entry. Same field names as
1651/// `pmcp_code_mode::config::OperationEntry` and the pmcp.run platform, so a
1652/// catalog loads unchanged on both.
1653#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1654#[serde(deny_unknown_fields)]
1655#[non_exhaustive]
1656pub struct OperationDecl {
1657    /// Canonical operation id. Unique within the catalog.
1658    pub id: String,
1659    /// The operation's class.
1660    pub category: OperationCategory,
1661    /// Human-readable description.
1662    #[serde(default)]
1663    pub description: String,
1664    /// The path calls are matched against, optionally prefixed by a method
1665    /// (`"GET /items/{id}"`). A `{param}` segment matches any one segment.
1666    pub path: String,
1667}
1668
1669impl OperationDecl {
1670    /// Build an entry (the struct is `#[non_exhaustive]`).
1671    #[must_use]
1672    pub fn new(
1673        id: impl Into<String>,
1674        category: OperationCategory,
1675        path: impl Into<String>,
1676    ) -> Self {
1677        Self {
1678            id: id.into(),
1679            category,
1680            description: String::new(),
1681            path: path.into(),
1682        }
1683    }
1684}
1685
1686impl CodeModeSection {
1687    /// The SQL-only keys this section sets, by config name.
1688    #[must_use]
1689    pub fn sql_keys_set(&self) -> Vec<&'static str> {
1690        let mut keys = Vec::new();
1691        if self.allow_writes {
1692            keys.push("allow_writes");
1693        }
1694        if self.allow_deletes {
1695            keys.push("allow_deletes");
1696        }
1697        if self.allow_ddl {
1698            keys.push("allow_ddl");
1699        }
1700        if self.require_limit {
1701            keys.push("require_limit");
1702        }
1703        if self.max_limit.is_some() {
1704            keys.push("max_limit");
1705        }
1706        if !self.blocked_tables.is_empty() {
1707            keys.push("blocked_tables");
1708        }
1709        if !self.sensitive_columns.is_empty() {
1710            keys.push("sensitive_columns");
1711        }
1712        if self.limits.is_some() {
1713            keys.push("limits");
1714        }
1715        keys
1716    }
1717
1718    /// The OpenAPI operation-class keys this section sets, by config name.
1719    #[must_use]
1720    pub fn class_keys_set(&self) -> Vec<&'static str> {
1721        let mut keys = Vec::new();
1722        for (name, set) in [
1723            ("read_mode", self.read_mode.is_some()),
1724            ("write_mode", self.write_mode.is_some()),
1725            ("delete_mode", self.delete_mode.is_some()),
1726            ("admin_mode", self.admin_mode.is_some()),
1727            ("allowed_operations", !self.allowed_operations.is_empty()),
1728            ("blocked_operations", !self.blocked_operations.is_empty()),
1729            ("blocked_paths", !self.blocked_paths.is_empty()),
1730            ("operations", !self.operations.is_empty()),
1731        ] {
1732            if set {
1733                keys.push(name);
1734            }
1735        }
1736        keys
1737    }
1738
1739    /// The effective mode of each class: `[read, write, delete, admin]`,
1740    /// with the defaults applied (read `allow_all`, the rest `deny_all`).
1741    #[must_use]
1742    pub fn class_modes(&self) -> [(OperationCategory, ClassModeName); 4] {
1743        [
1744            (
1745                OperationCategory::Read,
1746                self.read_mode.unwrap_or(ClassModeName::AllowAll),
1747            ),
1748            (
1749                OperationCategory::Write,
1750                self.write_mode.unwrap_or(ClassModeName::DenyAll),
1751            ),
1752            (
1753                OperationCategory::Delete,
1754                self.delete_mode.unwrap_or(ClassModeName::DenyAll),
1755            ),
1756            (
1757                OperationCategory::Admin,
1758                self.admin_mode.unwrap_or(ClassModeName::DenyAll),
1759            ),
1760        ]
1761    }
1762}
1763
1764/// `[code_mode.limits]` — query-complexity caps.
1765#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1766#[serde(deny_unknown_fields)]
1767pub struct CodeModeLimits {
1768    /// Maximum number of distinct tables referenced in a single query.
1769    #[serde(default)]
1770    pub max_tables_per_query: Option<u32>,
1771    /// Maximum JOIN nesting depth.
1772    #[serde(default)]
1773    pub max_join_depth: Option<u32>,
1774    /// Maximum subquery nesting depth.
1775    #[serde(default)]
1776    pub max_subquery_depth: Option<u32>,
1777}
1778
1779// -----------------------------------------------------------------------------
1780// [shared_policy_store]
1781// -----------------------------------------------------------------------------
1782
1783/// `[shared_policy_store]` section — AVP/Cedar shared-policy-store declaration.
1784///
1785/// Emitted only by the **reference** SQL server (`[server] is_reference = true`),
1786/// which provisions a single shared policy store + a set of Cedar templates that
1787/// all sibling SQL servers attach to (rather than each minting its own store).
1788///
1789/// Additive per the REF-01 superset invariant (Plan 85-01). The toolkit parses
1790/// this verbatim — SSM export and store provisioning are deployment-time
1791/// concerns handled outside config parsing (D-02 parse-only + lazy startup).
1792#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1793#[serde(deny_unknown_fields)]
1794pub struct SharedPolicyStoreSection {
1795    /// Whether this server creates the shared policy store for all SQL servers.
1796    #[serde(default)]
1797    pub creates_shared_store: bool,
1798    /// Whether the created store's identifier is exported to SSM Parameter Store.
1799    #[serde(default)]
1800    pub export_to_ssm: bool,
1801    /// SSM Parameter Store path the store identifier is exported to (when
1802    /// `export_to_ssm = true`).
1803    #[serde(default)]
1804    pub ssm_path: Option<String>,
1805    /// Cedar policy-template names included in the shared store (e.g.
1806    /// `"PermitAllSelects"`, `"ForbidAllDeletes"`).
1807    #[serde(default)]
1808    pub templates: Vec<String>,
1809}
1810
1811// -----------------------------------------------------------------------------
1812// [[config_slots]]
1813// -----------------------------------------------------------------------------
1814
1815/// The kind of a declared `[[config_slots]]` entry — a CLOSED vocabulary.
1816///
1817/// Deliberately an enum rather than a free `String`. A free string lets a typo
1818/// (`kind = "endpont"`) parse cleanly, survive
1819/// [`ServerConfig::validate`], and fail only at package time when it maps to no
1820/// slot type — the failure surfacing two crates away from its cause. As a closed
1821/// enum, an unrecognized discriminator is a serde parse error naming the
1822/// accepted set, and a fourth kind becomes a deliberate addition here rather
1823/// than a silent pass-through.
1824///
1825/// # Why this type is toolkit-LOCAL
1826///
1827/// The three `snake_case` discriminators (`endpoint`, `secret`, `auth_mode`)
1828/// are deliberately the same strings the `pmcp-package` slot-type discriminator
1829/// uses for the corresponding variants, so a packaging tool can compare a
1830/// declaration against a package slot **without either crate depending on the
1831/// other**. The toolkit must NOT depend on `pmcp-package`: that crate is the
1832/// workspace-excluded leaf, and a toolkit dependency on it inverts the layering.
1833/// The agreement is enforced by the package side re-parsing the SAME config
1834/// bytes, not by a shared type.
1835#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1836#[serde(rename_all = "snake_case")]
1837pub enum ConfigSlotKind {
1838    /// A network endpoint the target environment must supply (e.g. the backend
1839    /// API root). Behaviour-relevant: its `tested_value` records the endpoint
1840    /// the package was tested against.
1841    #[default]
1842    Endpoint,
1843    /// A named secret the target environment must supply (e.g. an API key).
1844    /// Identity-bearing: it structurally carries no `tested_value`.
1845    Secret,
1846    /// The backend authentication MODE. Structural rather than value-bearing:
1847    /// the auth-mode key is a serde tag, so no `${VAR}` placeholder form of it
1848    /// can deserialize — the baked literal IS the default and deviation
1849    /// surfaces through slot classification, not through a placeholder.
1850    AuthMode,
1851}
1852
1853/// Single `[[config_slots]]` entry — a config value the TARGET environment must
1854/// fill for this server to run.
1855///
1856/// A Shape A server's whole identity is its config, so "what must the operator
1857/// supply?" has to be declarable IN that config rather than discovered by
1858/// grepping for `${...}`. This block is that declaration: it names the config
1859/// path, the kind of thing it is, and the value exercised when the server was
1860/// tested.
1861///
1862/// Additive per the REF-01 superset invariant — a config omitting the block
1863/// parses to an empty [`ServerConfig::config_slots`]. Strict-parse discipline
1864/// (D-13) applies: `#[serde(deny_unknown_fields)]` rejects a typo'd inner key.
1865///
1866/// # Example
1867///
1868/// ```toml
1869/// [[config_slots]]
1870/// key = "backend.base_url"
1871/// kind = "endpoint"
1872/// name = "TFL_BASE_URL"
1873/// tested_value = "https://api.tfl.gov.uk"
1874/// ```
1875/// Who fills a config slot's value.
1876///
1877/// Mirrors `pmcp-package`'s `SuppliedBy` **by TOML value name, never by shared
1878/// type** — the same arrangement as [`ConfigSlotKind`], and for the same
1879/// reason: the toolkit must NOT depend on `pmcp-package` (the
1880/// workspace-excluded leaf), and a dependency the other way inverts the
1881/// layering. The agreement is enforced by the package side re-parsing these
1882/// same config bytes, not by a shared definition.
1883///
1884/// Defaults to [`Environment`](Self::Environment), so every config written
1885/// before this field existed keeps its exact meaning: the operator supplies it.
1886#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
1887#[serde(rename_all = "snake_case")]
1888pub enum ConfigSlotSuppliedBy {
1889    /// The operator supplies it in the target environment. The default, and the
1890    /// only class a package enumerates as REQUIRED of an operator.
1891    #[default]
1892    Environment,
1893    /// The hosting platform injects it at deploy time.
1894    Platform,
1895    /// The execution environment injects it (e.g. `AWS_LAMBDA_FUNCTION_NAME`);
1896    /// neither the operator nor the platform supplies it.
1897    Runtime,
1898}
1899
1900#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
1901#[serde(deny_unknown_fields)]
1902pub struct ConfigSlotDecl {
1903    /// The dotted TOML path this slot fills, e.g. `backend.base_url`,
1904    /// `backend.auth.query_params.app_key`, `backend.auth.type`.
1905    #[serde(default)]
1906    pub key: String,
1907    /// The slot kind ([`ConfigSlotKind`] — a closed vocabulary). REQUIRED: an
1908    /// entry omitting `kind` is a parse error, because a defaulted kind would
1909    /// silently mis-classify the slot.
1910    pub kind: ConfigSlotKind,
1911    /// The slot's declared name — for a `secret`, the environment-variable
1912    /// name; for an `endpoint`, the variable the `${VAR}` placeholder reads.
1913    #[serde(default)]
1914    pub name: String,
1915    /// The value exercised when the server was tested. `None` for
1916    /// identity-bearing slots (a secret), which structurally carry no value —
1917    /// ENFORCED by [`ServerConfig::validate`], not just stated: a `secret`
1918    /// entry carrying a `tested_value` is refused, because that field is the
1919    /// one place a real credential could sit in a config that is served but
1920    /// never packed.
1921    #[serde(default)]
1922    pub tested_value: Option<String>,
1923    /// Who fills this slot — see [`ConfigSlotSuppliedBy`]. Defaults to
1924    /// `environment` (the operator supplies it), so a config written before this
1925    /// field existed is unchanged in meaning.
1926    ///
1927    /// This field is why the toolkit had to move in the same change as the
1928    /// packer: `deny_unknown_fields` above means a config carrying
1929    /// `supplied_by` would FAIL TO BOOT if only the package side learned it,
1930    /// and `pmcp-package` refuses to pack a config it knows the server cannot
1931    /// parse. Both sides accept it, or neither does.
1932    #[serde(default)]
1933    pub supplied_by: ConfigSlotSuppliedBy,
1934}
1935
1936// -----------------------------------------------------------------------------
1937// [[tools]]
1938// -----------------------------------------------------------------------------
1939
1940/// Single `[[tools]]` entry — a declaratively-defined tool surface.
1941#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
1942#[serde(deny_unknown_fields)]
1943pub struct ToolDecl {
1944    /// Tool name (required for production via [`ServerConfig::validate`]).
1945    #[serde(default)]
1946    pub name: String,
1947    /// Human-readable tool description.
1948    #[serde(default)]
1949    pub description: Option<String>,
1950    /// SQL template (uses `:param` placeholders bound by [`ParamDecl`]).
1951    #[serde(default)]
1952    pub sql: Option<String>,
1953    /// HTTP request path for a **single-call** OpenAPI/REST tool (D-01), e.g.
1954    /// `"/Line/Mode/tube/Status"`. Concatenated onto the backend `base_url`
1955    /// (or this tool's [`Self::base_url`] override). Additive per REF-01 — `None`
1956    /// for SQL / script tools.
1957    #[serde(default)]
1958    pub path: Option<String>,
1959    /// HTTP method for a single-call tool (`"GET"`, `"POST"`, …). Pairs with
1960    /// [`Self::path`] (D-01). Additive; `None` for SQL / script tools.
1961    #[serde(default)]
1962    pub method: Option<String>,
1963    /// Per-tool backend base-URL override. When absent a single-call tool
1964    /// inherits `[backend].base_url`. Additive; `None` for SQL / script tools.
1965    #[serde(default)]
1966    pub base_url: Option<String>,
1967    /// JavaScript body for a **script** tool (D-01) — a code-mode snippet that
1968    /// orchestrates multiple backend calls and binds `[[tools.parameters]]` to
1969    /// `args`. When set, this entry is a script tool ([`Self::is_script_tool`]).
1970    /// Additive; `None` for SQL / single-call tools.
1971    #[serde(default)]
1972    pub script: Option<String>,
1973    /// Optional UI-resource URI for `structuredContent` widgets.
1974    #[serde(default)]
1975    pub ui_resource_uri: Option<String>,
1976    /// `[[tools.parameters]]` — declared input parameters.
1977    #[serde(default)]
1978    pub parameters: Vec<ParamDecl>,
1979    /// `[tools.annotations]` — MCP `toolAnnotations`.
1980    #[serde(default)]
1981    pub annotations: Option<AnnotationsDecl>,
1982}
1983
1984impl ToolDecl {
1985    /// Whether this `[[tools]]` entry is a **script** tool (D-01 detection rule).
1986    ///
1987    /// The detection rule is: `script.is_some()` ⇒ script tool; otherwise a
1988    /// `path` + `method` pair ⇒ single-call HTTP tool; otherwise (a `sql`
1989    /// field) ⇒ SQL tool. Plan 03/05 synthesizers branch on this method so the
1990    /// rule lives in exactly one place. Mutual-exclusivity is enforced at
1991    /// [`ServerConfig::validate`] (an entry mixing kinds is rejected, not
1992    /// silently resolved by precedence).
1993    ///
1994    /// # Examples
1995    ///
1996    /// ```
1997    /// use pmcp_server_toolkit::config::ToolDecl;
1998    ///
1999    /// let script = ToolDecl { script: Some("await api.get('/x')".into()), ..Default::default() };
2000    /// assert!(script.is_script_tool());
2001    ///
2002    /// let single = ToolDecl {
2003    ///     path: Some("/Line/Mode/tube/Status".into()),
2004    ///     method: Some("GET".into()),
2005    ///     ..Default::default()
2006    /// };
2007    /// assert!(!single.is_script_tool());
2008    /// ```
2009    #[must_use]
2010    pub fn is_script_tool(&self) -> bool {
2011        self.script.is_some()
2012    }
2013
2014    /// Number of distinct mutually-exclusive tool kinds declared on this entry.
2015    ///
2016    /// Used by [`ServerConfig::validate`] to reject an ambiguous `[[tools]]`
2017    /// entry (D-01 / T-90-02-04). A well-formed entry declares exactly one kind
2018    /// (count `1`); count `> 1` is ambiguous; count `0` is a kind-less stub
2019    /// (left to other validation rules).
2020    fn declared_kind_count(&self) -> usize {
2021        let is_sql = self.sql.is_some();
2022        let is_single_call = self.path.is_some() || self.method.is_some();
2023        let is_script = self.script.is_some();
2024        usize::from(is_sql) + usize::from(is_single_call) + usize::from(is_script)
2025    }
2026
2027    /// Where `param_name` sits for the purposes of the D3 default length cap
2028    /// (Phase 128).
2029    ///
2030    /// # Derivation
2031    ///
2032    /// - The name appears as a `{name}` segment of [`Self::path`] -> [`ParamPosition::Path`].
2033    /// - Else [`Self::method`] carries a request body (`method_carries_request_body`:
2034    ///   `POST`, `PUT`, `PATCH`) -> [`ParamPosition::Body`].
2035    /// - Else there IS a method -> [`ParamPosition::Query`]. A method with no
2036    ///   request body has nowhere but the URL to carry a non-path input, `OPTIONS`
2037    ///   included.
2038    /// - Else (no method at all) -> [`ParamPosition::Body`]: a SQL named bind or a
2039    ///   script-tool argument.
2040    ///
2041    /// # Coupling with `tools.rs::build_operation` — structural, not documentary
2042    ///
2043    /// Both of this function's splits agree with `build_operation` because both
2044    /// read the same helper, not because a comment says so:
2045    ///
2046    /// - the PATH arm and `build_operation`'s `path_param_names` both read
2047    ///   `path_placeholder_names`;
2048    /// - the QUERY/BODY arms and `build_operation`'s `ParameterLocation` assignment
2049    ///   both read `method_carries_request_body`, which is also the sole source of
2050    ///   `Operation::has_request_body`.
2051    ///
2052    /// The second agreement is Phase 128 CR-02/CR-03, and it replaced a documented
2053    /// "deliberate divergence" that did not survive measurement. `build_operation`
2054    /// used to mark every non-path declared parameter `ParameterLocation::Query`
2055    /// regardless of method while this function answered `Body` for a mutating tool
2056    /// — justified on the grounds that the two questions ("where does the value
2057    /// TRAVEL" versus "where is LENGTH dangerous") are different. They are, but the
2058    /// answers were both wrong: the value travelled in the query string, so the D3
2059    /// cap was withheld from a genuine request-line input on the stated grounds
2060    /// that it was a payload field, and `build_body` — which collected only args
2061    /// absent from `operation.parameters` — sent no payload at all.
2062    ///
2063    /// D-05 is still honoured, and now BY the routing rather than despite it: a
2064    /// `Body` position means the value really is a JSON payload field, and
2065    /// `default_cap_applies` emits no default `maxLength` for it. The escape for
2066    /// a long `Query` value remains an explicit per-parameter `max_length`.
2067    ///
2068    /// # Examples
2069    ///
2070    /// ```
2071    /// use pmcp_server_toolkit::config::{ParamPosition, ToolDecl};
2072    ///
2073    /// let search = ToolDecl {
2074    ///     path: Some("/lines/{line_id}/status".into()),
2075    ///     method: Some("GET".into()),
2076    ///     ..Default::default()
2077    /// };
2078    /// assert_eq!(search.param_position("line_id"), ParamPosition::Path);
2079    /// assert_eq!(search.param_position("detail"), ParamPosition::Query);
2080    ///
2081    /// let comment = ToolDecl {
2082    ///     path: Some("/issues/{id}/comments".into()),
2083    ///     method: Some("POST".into()),
2084    ///     ..Default::default()
2085    /// };
2086    /// assert_eq!(comment.param_position("id"), ParamPosition::Path);
2087    /// // Free text on a mutating method is NOT capped — D-05.
2088    /// assert_eq!(comment.param_position("body_text"), ParamPosition::Body);
2089    ///
2090    /// let sql = ToolDecl { sql: Some("SELECT 1".into()), ..Default::default() };
2091    /// assert_eq!(sql.param_position("anything"), ParamPosition::Body);
2092    /// ```
2093    #[must_use]
2094    pub fn param_position(&self, param_name: &str) -> ParamPosition {
2095        if let Some(path) = self.path.as_deref() {
2096            if path_placeholder_names(path).any(|n| n == param_name) {
2097                return ParamPosition::Path;
2098            }
2099        }
2100        match self.method.as_deref() {
2101            // A body-bearing method routes its non-path inputs into the JSON
2102            // payload, so length there is D-05 free text.
2103            Some(m) if method_carries_request_body(m) => ParamPosition::Body,
2104            // Every OTHER HTTP method has nowhere but the URL to put them.
2105            Some(_) => ParamPosition::Query,
2106            // No method at all: a SQL named bind or a script-tool argument.
2107            None => ParamPosition::Body,
2108        }
2109    }
2110}
2111
2112/// HTTP methods whose non-path inputs travel as fields of the JSON request body.
2113///
2114/// The ONE definition of that rule. `tools.rs::build_operation` reads it through
2115/// [`method_carries_request_body`] for BOTH `Operation::has_request_body` and the
2116/// `ParameterLocation::Body` assignment, and [`ToolDecl::param_position`] reads the
2117/// same predicate to decide where LENGTH is dangerous — so the request's routing
2118/// and the D3 cap's scope cannot drift apart. Phase 128 CR-02/CR-03 is the record
2119/// of what that drift cost: a `POST` tool's declared parameters were marked
2120/// `ParameterLocation::Query` while being classified `ParamPosition::Body`, so they
2121/// travelled in the URL uncapped and no payload ever reached the backend.
2122const BODY_BEARING_METHODS: [&str; 3] = ["POST", "PUT", "PATCH"];
2123
2124/// Whether `method` carries a JSON request body — the one predicate behind
2125/// [`BODY_BEARING_METHODS`]. Case-insensitive on the method name.
2126pub(crate) fn method_carries_request_body(method: &str) -> bool {
2127    BODY_BEARING_METHODS.contains(&method.to_uppercase().as_str())
2128}
2129
2130/// The `{name}` placeholder segments of a single-call tool's `path` template.
2131///
2132/// The ONE definition of that rule. `tools.rs::build_operation` reads it to build
2133/// its `Parameter` list and [`ToolDecl::param_position`] reads it to decide PATH
2134/// position, so the two cannot drift — which matters because a drift would
2135/// silently mis-scope the D3 cap and the D4 placeholder rules.
2136///
2137/// Matches a whole `/`-delimited segment only, and requires at least one character
2138/// between the braces (`{}` is not a placeholder).
2139pub(crate) fn path_placeholder_names(path: &str) -> impl Iterator<Item = &str> {
2140    path.split('/')
2141        .filter(|s| s.starts_with('{') && s.ends_with('}') && s.len() > 2)
2142        .map(|s| &s[1..s.len() - 1])
2143}
2144
2145/// Where a declared parameter's value lands, for the purposes of the D3 default
2146/// length cap (Phase 128).
2147///
2148/// For a single-call HTTP tool this is the SAME answer
2149/// `tools.rs::build_operation` gives as a `crate::http::ParameterLocation` — both
2150/// derive it from `path_placeholder_names` and `method_carries_request_body`.
2151/// See [`ToolDecl::param_position`] for the derivation and for what the previous
2152/// divergence between the two cost (CR-02/CR-03).
2153#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2154pub enum ParamPosition {
2155    /// A `{name}` segment of the tool's `path` template. Capped by default: a long
2156    /// value here has no legitimate use and is where the path-traversal class lives.
2157    Path,
2158    /// A non-path parameter of a tool whose method carries NO request body —
2159    /// `GET`, `HEAD`, `DELETE`, `OPTIONS` — so the value travels in the query
2160    /// string. `tools.rs::build_operation` gives it
2161    /// `crate::http::ParameterLocation::Query` and
2162    /// `crate::http::HttpClient::build_query` appends it to the URL.
2163    ///
2164    /// Capped at `[server.validation] default_max_length` code points by default,
2165    /// by `default_cap_applies`, because an unbounded query value is an unbounded
2166    /// request line: a 414 on some gateways, a truncation on others, and an
2167    /// access-log amplification everywhere. If a search tool starts refusing long
2168    /// queries after upgrading, this is why — declare an explicit `max_length` on
2169    /// that parameter to raise the limit.
2170    Query,
2171    /// A `POST` / `PUT` / `PATCH` payload field, a SQL named bind, or a script-tool
2172    /// argument.
2173    ///
2174    /// For a single-call HTTP tool this is a genuine JSON payload field:
2175    /// `tools.rs::build_operation` gives it
2176    /// `crate::http::ParameterLocation::Body` and
2177    /// `crate::http::HttpClient::build_body` folds it into the request body. It
2178    /// reaches no request line, which is why it is NOT capped by default
2179    /// (D-05 — free text must keep working). Surfaced by [`ServerConfig::lint`] and
2180    /// promotable to an error by `[server.validation] strict`.
2181    Body,
2182}
2183
2184/// Single `[[tools.parameters]]` entry.
2185///
2186/// The `default` and `enum` fields use [`toml::Value`] because they are
2187/// heterogeneous in the reference configs (a `default` may be an integer,
2188/// a string, or a boolean depending on the parameter type).
2189///
2190/// # Forward incompatibility (Phase 128, D-15)
2191///
2192/// This struct carries `#[serde(deny_unknown_fields)]`, so a config declaring any
2193/// of the Phase 128 D2 keys — `pattern`, `min_length`, `format`, `max_items`,
2194/// `allow_slash`, or an `[tools.parameters.items]` table — fails to PARSE on
2195/// toolkit 0.1.3 rather than degrading to "the key was ignored". That is
2196/// deliberate (a silently-ignored validation rule is the class this phase closes)
2197/// but it means a config written for this release cannot be loaded by an older
2198/// toolkit. The same applies to the `[server.validation]` section. Named in the
2199/// CHANGELOG.
2200#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
2201#[serde(deny_unknown_fields)]
2202pub struct ParamDecl {
2203    /// Parameter name (the `:param` token used in the tool's `sql`).
2204    #[serde(default)]
2205    pub name: String,
2206    /// JSON-schema type (`"string"`, `"integer"`, `"number"`, `"boolean"`).
2207    #[serde(default, rename = "type")]
2208    pub param_type: Option<String>,
2209    /// Human-readable parameter description.
2210    #[serde(default)]
2211    pub description: Option<String>,
2212    /// Whether the parameter is required.
2213    #[serde(default)]
2214    pub required: bool,
2215    /// Optional default value (any TOML type).
2216    #[serde(default)]
2217    pub default: Option<toml::Value>,
2218    /// Maximum string length (string parameters only).
2219    #[serde(default)]
2220    pub max_length: Option<u64>,
2221    /// Inclusive minimum (integer / number parameters only).
2222    ///
2223    /// Stored as `f64`. See [`Self::maximum`] for the precision limit that applies
2224    /// to both bounds.
2225    #[serde(default)]
2226    pub minimum: Option<f64>,
2227    /// Inclusive maximum (integer / number parameters only).
2228    ///
2229    /// # Not a safe way to bound a 64-bit integer ID
2230    ///
2231    /// Both bounds are stored as `f64`, so an integer magnitude above 2^53
2232    /// (`9007199254740992`) cannot be represented exactly. `9007199254740993`
2233    /// written in TOML has ALREADY become `9007199254740992` by the time any code
2234    /// in this crate sees it, and no post-parse check can recover the fact that it
2235    /// was rounded. [`ServerConfig::validate`] therefore refuses a bound that is
2236    /// non-finite or whose magnitude EXCEEDS 2^53
2237    /// ([`ConfigValidationError::NonFiniteParamBound`]) — which catches the wildly
2238    /// out-of-range case, and deliberately does not claim to catch a value sitting
2239    /// one unit past the boundary.
2240    ///
2241    /// If you need to bound a `u64` identifier, express the rule as a
2242    /// [`Self::pattern`] over its string form instead. This limitation is a
2243    /// documented one, not an oversight: adding an `i64`-typed bound vocabulary is
2244    /// out of scope for D2.
2245    #[serde(default)]
2246    pub maximum: Option<f64>,
2247    /// Closed set of allowed values (any TOML scalar).
2248    #[serde(default, rename = "enum")]
2249    pub enum_values: Option<Vec<toml::Value>>,
2250    /// Regular expression the value must match, emitted as JSON Schema `pattern`
2251    /// (string parameters only).
2252    ///
2253    /// # It is UNANCHORED
2254    ///
2255    /// JSON Schema `pattern` is a SUBSTRING search, exactly as ECMA-262
2256    /// `RegExp.prototype.test` is. A rule written as a bare character class such as
2257    /// `[A-Z]{3}` matches `"../../etc/passwd-ABC"` and therefore buys no
2258    /// enforcement whatsoever. Anchor every rule you mean as a whole-value rule:
2259    /// `^[A-Z]{3}$`.
2260    ///
2261    /// # `\s` and `\S` do not mean one thing here
2262    ///
2263    /// Two regex engines are live inside one `jsonschema` 0.49.2 process, and which
2264    /// one evaluates your pattern depends on the pattern's own syntax:
2265    ///
2266    /// - A plain pattern takes the linear-time engine, whose `\s` is a PARTIAL
2267    ///   ECMA-262 set — measured as
2268    ///   `{U+0009, U+000A, U+000B, U+000C, U+000D, U+0020, U+00A0, U+2029, U+FEFF}`.
2269    ///   It does NOT include U+3000 IDEOGRAPHIC SPACE, U+0085 NEL, U+1680,
2270    ///   U+2000, U+2007, U+2028 or U+202F, and it DOES include the byte-order mark.
2271    /// - A pattern containing a lookaround or a backreference takes the
2272    ///   backtracking engine, where `\s` is exactly `\p{White_Space}` — so it DOES
2273    ///   match U+3000, and does NOT match U+FEFF.
2274    ///
2275    /// Adding a lookahead to a pattern therefore silently changes what `\s` means
2276    /// in it. For anything security-relevant, spell out an explicit character class
2277    /// (e.g. `[^\p{White_Space}]`) rather than using the shorthand.
2278    #[serde(default)]
2279    pub pattern: Option<String>,
2280    /// Minimum string length in Unicode code points, emitted as JSON Schema
2281    /// `minLength` (string parameters only).
2282    ///
2283    /// Counted in code points — not bytes and not grapheme clusters — matching
2284    /// `maxLength`'s unit so a `min_length == max_length` pair names exactly one
2285    /// length.
2286    #[serde(default)]
2287    pub min_length: Option<u64>,
2288    /// JSON Schema `format` assertion, e.g. `"uuid"`, `"email"`, `"date-time"`.
2289    ///
2290    /// # It IS enforced on inputs in this SDK
2291    ///
2292    /// `format` is ANNOTATIVE by default in `jsonschema` 0.49 — a bare
2293    /// `draft202012` validator accepts `"!!!not-a-uuid!!!"` against
2294    /// `format = "uuid"`. Declared inputs do not take that path: core `pmcp`
2295    /// compiles a tool's `inputSchema` through a format-ASSERTING builder
2296    /// (Phase 128, Q1), so a declared `format` refuses a non-conforming value at
2297    /// `tools/call` time.
2298    ///
2299    /// Measured under this workspace's pinned `jsonschema` configuration
2300    /// (`0.49`, `default-features = false`), all NINETEEN standard Draft 2020-12
2301    /// format names assert: `date-time`, `date`, `time`, `duration`, `email`,
2302    /// `idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`,
2303    /// `uri-reference`, `iri`, `iri-reference`, `uuid`, `uri-template`,
2304    /// `json-pointer`, `relative-json-pointer`, `regex`. A format name OUTSIDE
2305    /// that list is accepted-and-ignored, per JSON Schema's own rule that an
2306    /// unknown format is an annotation — so a typo such as `"uid"` for `"uuid"`
2307    /// silently enforces nothing.
2308    ///
2309    /// `format` is NOT enforced on OUTPUTS: `structuredContent` validation is
2310    /// deliberately annotative there, and only warns.
2311    #[serde(default)]
2312    pub format: Option<String>,
2313    /// `[tools.parameters.items]` — the element schema for an array parameter,
2314    /// emitted as JSON Schema `items`.
2315    ///
2316    /// Emitted in OBJECT form only. Array-form `items` (the draft-07 tuple
2317    /// construct) does not compile under the Draft 2020-12 pin and would take the
2318    /// whole tool's validator down with it.
2319    #[serde(default)]
2320    pub items: Option<ItemsDecl>,
2321    /// Maximum number of array elements, emitted as JSON Schema `maxItems`
2322    /// (array parameters only).
2323    #[serde(default)]
2324    pub max_items: Option<u64>,
2325    /// Permit `/` inside this parameter's value when it is interpolated into a
2326    /// single-call tool's path template (Phase 128, D-11).
2327    ///
2328    /// Path-placeholder values are refused for path separators by default, because
2329    /// a `/` in a `{segment}` lets a caller reshape the request target. This
2330    /// per-parameter opt-in is the ONLY legitimate source of that permission — it
2331    /// exists for the genuine case of a parameter that names a multi-segment
2332    /// resource path.
2333    ///
2334    /// An OpenAPI spec's `allowReserved` must NEVER be wired to this field. That
2335    /// keyword describes URL percent-encoding latitude in the spec author's
2336    /// serialization rules; it is not a statement that the value may restructure
2337    /// the path, and treating it as one would turn a routine spec detail into a
2338    /// silent path-traversal opening.
2339    #[serde(default)]
2340    pub allow_slash: bool,
2341}
2342
2343/// `[tools.parameters.items]` — the element schema of an array parameter
2344/// (Phase 128, D2).
2345///
2346/// Emitted into `inputSchema` as an OBJECT-form JSON Schema `items` value. The
2347/// array form of `items` is a draft-07 tuple construct that does not compile under
2348/// the Draft 2020-12 pin, so this struct has no way to express it by design.
2349#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
2350#[serde(deny_unknown_fields)]
2351pub struct ItemsDecl {
2352    /// Element type (`"string"`, `"integer"`, …). Defaults to `"string"` when
2353    /// omitted, matching [`ParamDecl::param_type`]'s convention.
2354    #[serde(default, rename = "type")]
2355    pub item_type: Option<String>,
2356    /// Maximum element length in Unicode code points (string elements only).
2357    #[serde(default)]
2358    pub max_length: Option<u64>,
2359    /// Regular expression each element must match. UNANCHORED — see
2360    /// [`ParamDecl::pattern`] for the anchoring and two-engine `\s` caveats, which
2361    /// apply identically here.
2362    #[serde(default)]
2363    pub pattern: Option<String>,
2364}
2365
2366/// `[tools.annotations]` — MCP `toolAnnotations` hints.
2367#[allow(clippy::struct_excessive_bools)] // Why: REF-01 superset — mirrors the MCP `toolAnnotations` flag set 1:1.
2368#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
2369#[serde(deny_unknown_fields)]
2370pub struct AnnotationsDecl {
2371    /// Whether the tool only reads (never mutates) state.
2372    #[serde(default)]
2373    pub read_only_hint: bool,
2374    /// Whether the tool may destroy data.
2375    #[serde(default)]
2376    pub destructive_hint: bool,
2377    /// Whether repeated calls with the same args produce the same result.
2378    #[serde(default)]
2379    pub idempotent_hint: bool,
2380    /// Whether the tool interacts with an open-world (external) service.
2381    #[serde(default)]
2382    pub open_world_hint: bool,
2383    /// Cost hint (`"low"`, `"medium"`, `"high"`).
2384    #[serde(default)]
2385    pub cost_hint: Option<String>,
2386}
2387
2388// -----------------------------------------------------------------------------
2389// [[prompts]]
2390// -----------------------------------------------------------------------------
2391
2392/// Single `[[prompts]]` entry.
2393#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
2394#[serde(deny_unknown_fields)]
2395pub struct PromptDecl {
2396    /// Prompt name (the identifier MCP clients call by).
2397    #[serde(default)]
2398    pub name: String,
2399    /// Human-readable prompt description.
2400    #[serde(default)]
2401    pub description: Option<String>,
2402    /// Resource URIs to include in the prompt's assembled body.
2403    #[serde(default)]
2404    pub include_resources: Vec<String>,
2405    /// Declared prompt arguments (MCP `PromptArgument`).
2406    #[serde(default)]
2407    pub arguments: Vec<PromptArgumentDecl>,
2408}
2409
2410/// Single argument under `[[prompts.arguments]]`.
2411#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
2412#[serde(deny_unknown_fields)]
2413pub struct PromptArgumentDecl {
2414    /// Argument name.
2415    #[serde(default)]
2416    pub name: String,
2417    /// Human-readable description.
2418    #[serde(default)]
2419    pub description: Option<String>,
2420    /// Whether the argument is required.
2421    #[serde(default)]
2422    pub required: bool,
2423}
2424
2425// -----------------------------------------------------------------------------
2426// [[resources]]
2427// -----------------------------------------------------------------------------
2428
2429/// Single `[[resources]]` entry — a statically-shipped resource.
2430#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
2431#[serde(deny_unknown_fields)]
2432pub struct ResourceDecl {
2433    /// Resource URI (e.g. `"docs://open-images/schema"`).
2434    #[serde(default)]
2435    pub uri: String,
2436    /// Human-readable resource name.
2437    #[serde(default)]
2438    pub name: Option<String>,
2439    /// Resource description.
2440    #[serde(default)]
2441    pub description: Option<String>,
2442    /// MIME type (e.g. `"text/markdown"`).
2443    #[serde(default)]
2444    pub mime_type: Option<String>,
2445    /// Inline resource content (or `"loaded from path.md"` placeholder string —
2446    /// the toolkit treats the value verbatim; resolution to filesystem reads
2447    /// is the caller's responsibility).
2448    #[serde(default)]
2449    pub content: Option<String>,
2450}
2451
2452// -----------------------------------------------------------------------------
2453// Tests
2454// -----------------------------------------------------------------------------
2455
2456#[cfg(test)]
2457mod tests {
2458    use super::*;
2459    use proptest::prelude::*;
2460
2461    const MINIMAL: &str = r#"
2462        [server]
2463        name = "demo"
2464        version = "0.1.0"
2465    "#;
2466
2467    #[test]
2468    fn parse_minimal_config_succeeds() {
2469        let cfg = ServerConfig::from_toml(MINIMAL).expect("minimal must parse");
2470        assert_eq!(cfg.server.name, "demo");
2471        assert_eq!(cfg.server.version, "0.1.0");
2472        assert!(cfg.tools.is_empty());
2473        assert!(cfg.code_mode.is_none());
2474    }
2475
2476    #[test]
2477    fn parse_unknown_field_fails() {
2478        let toml = r#"
2479            [server]
2480            name = "demo"
2481            version = "0.1.0"
2482            unknown_field = "x"
2483        "#;
2484        let err = ServerConfig::from_toml(toml).expect_err("unknown field must fail");
2485        assert!(matches!(err, ToolkitError::Parse(_)), "got: {err:?}");
2486    }
2487
2488    #[test]
2489    fn parse_typo_in_code_mode_key_fails() {
2490        // T-83-04-02: defence-in-depth against silent policy widening.
2491        let toml = r#"
2492            [server]
2493            name = "demo"
2494            version = "0.1.0"
2495            [code_mode]
2496            enabled = true
2497            auto_aprove_levels = ["low"]
2498        "#;
2499        let err = ServerConfig::from_toml(toml).expect_err("typo'd code_mode key must be rejected");
2500        assert!(matches!(err, ToolkitError::Parse(_)));
2501    }
2502
2503    #[test]
2504    fn code_mode_section_optional() {
2505        let cfg = ServerConfig::from_toml(MINIMAL).expect("parse");
2506        assert!(cfg.code_mode.is_none());
2507    }
2508
2509    #[test]
2510    fn validate_accepts_valid_config() {
2511        let cfg = ServerConfig::from_toml(MINIMAL).expect("parse");
2512        cfg.validate().expect("minimal config must validate");
2513    }
2514
2515    #[test]
2516    fn validate_rejects_empty_server_name() {
2517        let toml = r#"
2518            [server]
2519            name = ""
2520            version = "0.1.0"
2521        "#;
2522        let cfg = ServerConfig::from_toml(toml).expect("parse");
2523        match cfg.validate() {
2524            Err(ConfigValidationError::EmptyServerName) => {},
2525            other => panic!("expected EmptyServerName, got {other:?}"),
2526        }
2527    }
2528
2529    #[test]
2530    fn validate_rejects_empty_server_version() {
2531        let toml = r#"
2532            [server]
2533            name = "demo"
2534            version = ""
2535        "#;
2536        let cfg = ServerConfig::from_toml(toml).expect("parse");
2537        match cfg.validate() {
2538            Err(ConfigValidationError::EmptyServerVersion) => {},
2539            other => panic!("expected EmptyServerVersion, got {other:?}"),
2540        }
2541    }
2542
2543    #[test]
2544    fn validate_rejects_empty_tool_name() {
2545        let toml = r#"
2546            [server]
2547            name = "demo"
2548            version = "0.1.0"
2549
2550            [[tools]]
2551            name = "ok"
2552            description = "first"
2553
2554            [[tools]]
2555            name = ""
2556            description = "second-is-empty"
2557        "#;
2558        let cfg = ServerConfig::from_toml(toml).expect("parse");
2559        match cfg.validate() {
2560            Err(ConfigValidationError::EmptyToolName(1)) => {},
2561            other => panic!("expected EmptyToolName(1), got {other:?}"),
2562        }
2563    }
2564
2565    #[test]
2566    fn validate_rejects_empty_table_name() {
2567        let toml = r#"
2568            [server]
2569            name = "demo"
2570            version = "0.1.0"
2571
2572            [[database.tables]]
2573            name = ""
2574            description = "missing-name"
2575        "#;
2576        let cfg = ServerConfig::from_toml(toml).expect("parse");
2577        match cfg.validate() {
2578            Err(ConfigValidationError::EmptyTableName(0)) => {},
2579            other => panic!("expected EmptyTableName(0), got {other:?}"),
2580        }
2581    }
2582
2583    /// Phase 90 gap-closure (GAP 3 / WR-02): a `[backend]` block with an
2584    /// empty / missing `base_url` is rejected at validate() time with
2585    /// [`ConfigValidationError::EmptyBackendBaseUrl`] — not a late opaque
2586    /// `DispatchError::Connector("invalid base URL")` at request time.
2587    #[cfg(feature = "http")]
2588    #[test]
2589    fn validate_rejects_empty_backend_base_url() {
2590        // base_url key present but empty.
2591        let toml = r#"
2592            [server]
2593            name = "demo"
2594            version = "0.1.0"
2595
2596            [backend]
2597            base_url = ""
2598        "#;
2599        let cfg = ServerConfig::from_toml(toml).expect("parse");
2600        match cfg.validate() {
2601            Err(ConfigValidationError::EmptyBackendBaseUrl) => {},
2602            other => panic!("expected EmptyBackendBaseUrl, got {other:?}"),
2603        }
2604    }
2605
2606    /// A `[backend]` block whose `base_url` key is omitted entirely (defaults
2607    /// to `""` via `#[serde(default)]`) is rejected the same way.
2608    #[cfg(feature = "http")]
2609    #[test]
2610    fn validate_rejects_omitted_backend_base_url() {
2611        let toml = r#"
2612            [server]
2613            name = "demo"
2614            version = "0.1.0"
2615
2616            [backend]
2617        "#;
2618        let cfg = ServerConfig::from_toml(toml).expect("parse");
2619        match cfg.validate() {
2620            Err(ConfigValidationError::EmptyBackendBaseUrl) => {},
2621            other => panic!("expected EmptyBackendBaseUrl, got {other:?}"),
2622        }
2623    }
2624
2625    /// A multi-placeholder composition (`${SCHEME}://${HOST}`) is a MALFORMED
2626    /// reference — the grammar resolves one whole-value `${VAR}`, it does not
2627    /// interpolate — so validate() refuses it at load time instead of letting
2628    /// every boot fail with an `UnresolvedBaseUrlRef` naming an empty variable.
2629    #[cfg(feature = "http")]
2630    #[test]
2631    fn validate_rejects_multi_placeholder_backend_base_url() {
2632        let toml = r#"
2633            [server]
2634            name = "demo"
2635            version = "0.1.0"
2636
2637            [backend]
2638            base_url = "${TFL_SCHEME}://${TFL_HOST}"
2639        "#;
2640        let cfg = ServerConfig::from_toml(toml).expect("parse");
2641        match cfg.validate() {
2642            Err(ConfigValidationError::MalformedBackendBaseUrlRef) => {},
2643            other => panic!("expected MalformedBackendBaseUrlRef, got {other:?}"),
2644        }
2645    }
2646
2647    /// The empty `${}` form is the same class of defect and gets the same
2648    /// load-time refusal.
2649    #[cfg(feature = "http")]
2650    #[test]
2651    fn validate_rejects_empty_name_backend_base_url_ref() {
2652        let toml = r#"
2653            [server]
2654            name = "demo"
2655            version = "0.1.0"
2656
2657            [backend]
2658            base_url = "${}"
2659        "#;
2660        let cfg = ServerConfig::from_toml(toml).expect("parse");
2661        match cfg.validate() {
2662            Err(ConfigValidationError::MalformedBackendBaseUrlRef) => {},
2663            other => panic!("expected MalformedBackendBaseUrlRef, got {other:?}"),
2664        }
2665    }
2666
2667    /// A well-formed single reference stays valid — the check refuses only
2668    /// malformed shapes, never the deferred-to-environment pattern itself.
2669    #[cfg(feature = "http")]
2670    #[test]
2671    fn validate_accepts_single_reference_backend_base_url() {
2672        let toml = r#"
2673            [server]
2674            name = "demo"
2675            version = "0.1.0"
2676
2677            [backend]
2678            base_url = "${TFL_BASE_URL}"
2679        "#;
2680        let cfg = ServerConfig::from_toml(toml).expect("parse");
2681        cfg.validate()
2682            .expect("a single ${VAR} backend.base_url reference must validate");
2683    }
2684
2685    /// The SAME malformed-reference rule applies to `[backend.auth]`
2686    /// credentials, and it applies at LOAD time. Without it the credential path
2687    /// resolved a malformed reference to the empty string and then OMITTED it:
2688    /// the server booted, every backend call went out unauthenticated, and
2689    /// nothing was logged. `${TFL-APP-KEY}` is the realistic shape — a dash is
2690    /// not a portably settable variable name, so the reference names nothing.
2691    #[cfg(feature = "http")]
2692    #[test]
2693    fn validate_rejects_malformed_backend_auth_credential_ref() {
2694        let toml = r#"
2695            [server]
2696            name = "demo"
2697            version = "0.1.0"
2698
2699            [backend]
2700            base_url = "https://api.example.com"
2701
2702            [backend.auth]
2703            type = "bearer"
2704            token = "${TFL-APP-KEY}"
2705        "#;
2706        let cfg = ServerConfig::from_toml(toml).expect("parse");
2707        match cfg.validate() {
2708            Err(ConfigValidationError::MalformedBackendAuthRef(field)) => {
2709                assert_eq!(field, "token");
2710            },
2711            other => panic!("expected MalformedBackendAuthRef, got {other:?}"),
2712        }
2713    }
2714
2715    /// The api_key map path gets the same refusal, and the error names the
2716    /// offending entry so the operator knows WHICH parameter to fix.
2717    #[cfg(feature = "http")]
2718    #[test]
2719    fn validate_rejects_malformed_backend_auth_api_key_entry() {
2720        let toml = r#"
2721            [server]
2722            name = "demo"
2723            version = "0.1.0"
2724
2725            [backend]
2726            base_url = "https://api.example.com"
2727
2728            [backend.auth]
2729            type = "api_key"
2730            query_params = { app_key = "${TFL_SCHEME}://${TFL_HOST}" }
2731        "#;
2732        let cfg = ServerConfig::from_toml(toml).expect("parse");
2733        match cfg.validate() {
2734            Err(ConfigValidationError::MalformedBackendAuthRef(field)) => {
2735                assert_eq!(field, "query_params.app_key");
2736            },
2737            other => panic!("expected MalformedBackendAuthRef, got {other:?}"),
2738        }
2739    }
2740
2741    /// The refusal is scoped to MALFORMED shapes only: a well-formed reference
2742    /// and a plain literal both still validate, so the deferred-to-environment
2743    /// pattern and committed dev configs are untouched.
2744    #[cfg(feature = "http")]
2745    #[test]
2746    fn validate_accepts_wellformed_and_literal_backend_auth_credentials() {
2747        let toml = r#"
2748            [server]
2749            name = "demo"
2750            version = "0.1.0"
2751
2752            [backend]
2753            base_url = "https://api.example.com"
2754
2755            [backend.auth]
2756            type = "basic"
2757            username = "svc-account"
2758            password = "${TFL_APP_KEY}"
2759        "#;
2760        let cfg = ServerConfig::from_toml(toml).expect("parse");
2761        cfg.validate()
2762            .expect("a literal username and a single ${VAR} password must validate");
2763    }
2764
2765    /// A `[backend]` block with a non-empty `base_url` validates OK.
2766    #[cfg(feature = "http")]
2767    #[test]
2768    fn validate_accepts_non_empty_backend_base_url() {
2769        let toml = r#"
2770            [server]
2771            name = "demo"
2772            version = "0.1.0"
2773
2774            [backend]
2775            base_url = "https://api.example.com"
2776        "#;
2777        let cfg = ServerConfig::from_toml(toml).expect("parse");
2778        cfg.validate()
2779            .expect("config with a non-empty backend.base_url must validate");
2780    }
2781
2782    /// A config with NO `[backend]` block (a pure-SQL config) is unaffected by
2783    /// the new check — `backend` is `None`, so the check never fires.
2784    #[cfg(feature = "http")]
2785    #[test]
2786    fn validate_accepts_absent_backend() {
2787        let cfg = ServerConfig::from_toml(MINIMAL).expect("parse");
2788        assert!(cfg.backend.is_none());
2789        cfg.validate()
2790            .expect("a config without [backend] must validate (SQL configs unaffected)");
2791    }
2792
2793    /// The error Display names the offending field and is actionable.
2794    #[cfg(feature = "http")]
2795    #[test]
2796    fn empty_backend_base_url_error_names_the_field() {
2797        let msg = ConfigValidationError::EmptyBackendBaseUrl.to_string();
2798        assert!(
2799            msg.contains("[backend].base_url"),
2800            "error must name the field, got: {msg}"
2801        );
2802    }
2803
2804    #[test]
2805    fn database_url_optional_field_parses() {
2806        // Phase 84 CONN-04 / D-08: the additive `[database].url` field parses
2807        // under `#[serde(deny_unknown_fields)]` and carries the `env:VAR_NAME`
2808        // indirection string verbatim (resolution happens at the consumer layer).
2809        let toml = r#"
2810            [server]
2811            name = "x"
2812            version = "0.0.1"
2813
2814            [database]
2815            url = "env:DATABASE_URL"
2816        "#;
2817        let cfg = ServerConfig::from_toml(toml).expect("config with [database].url must parse");
2818        assert_eq!(cfg.database.url, Some("env:DATABASE_URL".to_string()));
2819    }
2820
2821    #[test]
2822    fn from_toml_strict_validated_rolls_both_errors() {
2823        // 1. Parse error path (unknown field).
2824        let bad_toml = r#"
2825            [server]
2826            name = "demo"
2827            version = "0.1.0"
2828            nonsense = "x"
2829        "#;
2830        let err = ServerConfig::from_toml_strict_validated(bad_toml)
2831            .expect_err("unknown field must surface");
2832        assert!(matches!(err, ToolkitError::Parse(_)), "got: {err:?}");
2833
2834        // 2. Validation error path (empty required value).
2835        let invalid_toml = r#"
2836            [server]
2837            name = ""
2838            version = "0.1.0"
2839        "#;
2840        let err = ServerConfig::from_toml_strict_validated(invalid_toml)
2841            .expect_err("empty name must surface");
2842        assert!(
2843            matches!(
2844                err,
2845                ToolkitError::Validation(ConfigValidationError::EmptyServerName)
2846            ),
2847            "got: {err:?}"
2848        );
2849    }
2850
2851    // -------------------------------------------------------------------------
2852    // ToolDecl two-kind detection — D-01 (shared, not http-gated)
2853    // -------------------------------------------------------------------------
2854
2855    #[test]
2856    fn test_tooldecl_single_call_parses() {
2857        let toml = r#"
2858            [server]
2859            name = "tube"
2860            version = "0.1.0"
2861
2862            [[tools]]
2863            name = "tube_status"
2864            path = "/Line/Mode/tube/Status"
2865            method = "GET"
2866        "#;
2867        let cfg = ServerConfig::from_toml(toml).expect("single-call tool must parse");
2868        let tool = &cfg.tools[0];
2869        assert_eq!(tool.path.as_deref(), Some("/Line/Mode/tube/Status"));
2870        assert_eq!(tool.method.as_deref(), Some("GET"));
2871        assert!(!tool.is_script_tool());
2872        cfg.validate()
2873            .expect("single-call tool is a valid single kind");
2874    }
2875
2876    #[test]
2877    fn test_tooldecl_script_parses() {
2878        let toml = r#"
2879            [server]
2880            name = "tube"
2881            version = "0.1.0"
2882
2883            [[tools]]
2884            name = "plan_journey"
2885            script = """
2886            const a = await api.get('/Journey/JourneyResults/' + args.from + '/to/' + args.to);
2887            return a;
2888            """
2889
2890            [[tools.parameters]]
2891            name = "from"
2892            type = "string"
2893            required = true
2894
2895            [[tools.parameters]]
2896            name = "to"
2897            type = "string"
2898            required = true
2899        "#;
2900        let cfg = ServerConfig::from_toml(toml).expect("script tool must parse");
2901        let tool = &cfg.tools[0];
2902        assert!(tool.script.is_some());
2903        assert!(tool.is_script_tool());
2904        assert_eq!(tool.parameters.len(), 2);
2905        cfg.validate().expect("script tool is a valid single kind");
2906    }
2907
2908    #[test]
2909    fn test_tooldecl_detection() {
2910        let script = ToolDecl {
2911            script: Some("return 1;".to_string()),
2912            ..Default::default()
2913        };
2914        assert!(script.is_script_tool());
2915
2916        let single = ToolDecl {
2917            path: Some("/x".to_string()),
2918            method: Some("GET".to_string()),
2919            ..Default::default()
2920        };
2921        assert!(!single.is_script_tool());
2922
2923        let sql = ToolDecl {
2924            sql: Some("SELECT 1".to_string()),
2925            ..Default::default()
2926        };
2927        assert!(!sql.is_script_tool());
2928    }
2929
2930    #[test]
2931    fn test_tooldecl_ambiguous_rejected() {
2932        // script + path/method is ambiguous (Codex MEDIUM): rejected, not
2933        // resolved by a silent "script wins".
2934        let toml = r#"
2935            [server]
2936            name = "tube"
2937            version = "0.1.0"
2938
2939            [[tools]]
2940            name = "confused"
2941            path = "/x"
2942            method = "GET"
2943            script = "return 1;"
2944        "#;
2945        let cfg = ServerConfig::from_toml(toml).expect("parse (ambiguity is a validate-time rule)");
2946        match cfg.validate() {
2947            Err(ConfigValidationError::AmbiguousToolKind(0)) => {},
2948            other => panic!("expected AmbiguousToolKind(0), got {other:?}"),
2949        }
2950    }
2951
2952    #[test]
2953    fn test_tooldecl_ambiguous_sql_plus_script_rejected() {
2954        let toml = r#"
2955            [server]
2956            name = "tube"
2957            version = "0.1.0"
2958
2959            [[tools]]
2960            name = "confused"
2961            sql = "SELECT 1"
2962            script = "return 1;"
2963        "#;
2964        let cfg = ServerConfig::from_toml(toml).expect("parse");
2965        match cfg.validate() {
2966            Err(ConfigValidationError::AmbiguousToolKind(0)) => {},
2967            other => panic!("expected AmbiguousToolKind(0), got {other:?}"),
2968        }
2969    }
2970
2971    #[test]
2972    fn test_tooldecl_sql_still_parses() {
2973        // REF-01 superset regression: an existing sql= tool is unaffected by the
2974        // additive path/method/base_url/script fields.
2975        let toml = r#"
2976            [server]
2977            name = "demo"
2978            version = "0.1.0"
2979
2980            [[tools]]
2981            name = "list_tables"
2982            sql = "SELECT name FROM sqlite_master"
2983        "#;
2984        let cfg = ServerConfig::from_toml(toml).expect("sql tool must still parse");
2985        let tool = &cfg.tools[0];
2986        assert_eq!(tool.sql.as_deref(), Some("SELECT name FROM sqlite_master"));
2987        assert!(tool.path.is_none());
2988        assert!(tool.method.is_none());
2989        assert!(tool.base_url.is_none());
2990        assert!(tool.script.is_none());
2991        assert!(!tool.is_script_tool());
2992        cfg.validate().expect("sql tool validates as a single kind");
2993    }
2994
2995    // -------------------------------------------------------------------------
2996    // [backend] / [backend.auth] / [backend.http] — D-06 (http feature)
2997    // -------------------------------------------------------------------------
2998
2999    #[cfg(feature = "http")]
3000    #[test]
3001    fn test_backend_section_parses() {
3002        // A full [backend] + [backend.auth] (api_key) + [backend.http] block
3003        // round-trips into ServerConfig with backend.is_some().
3004        let toml = r#"
3005            [server]
3006            name = "tube"
3007            version = "0.1.0"
3008
3009            [backend]
3010            base_url = "https://api.tfl.gov.uk"
3011
3012            [backend.auth]
3013            type = "api_key"
3014
3015            [backend.auth.query_params]
3016            app_key = "${TFL_APP_KEY}"
3017
3018            [backend.http]
3019            timeout_seconds = 10
3020            retries = 2
3021        "#;
3022        let cfg = ServerConfig::from_toml(toml).expect("[backend] config must parse");
3023        let backend = cfg.backend.expect("backend must be Some");
3024        assert_eq!(backend.base_url, "https://api.tfl.gov.uk");
3025        assert_eq!(backend.http.timeout_seconds, 10);
3026        assert_eq!(backend.http.retries, 2);
3027        assert!(
3028            matches!(backend.auth, AuthConfig::ApiKey { .. }),
3029            "auth must be api_key, got {:?}",
3030            backend.auth
3031        );
3032    }
3033
3034    #[cfg(feature = "http")]
3035    #[test]
3036    fn test_backend_auth_defaults_to_none() {
3037        // [backend] without a [backend.auth] sub-table defaults auth to None
3038        // and http to HttpConfig defaults (additive sub-tables).
3039        let toml = r#"
3040            [server]
3041            name = "tube"
3042            version = "0.1.0"
3043
3044            [backend]
3045            base_url = "https://api.example.com"
3046        "#;
3047        let cfg = ServerConfig::from_toml(toml).expect("backend w/o auth must parse");
3048        let backend = cfg.backend.expect("backend must be Some");
3049        assert!(matches!(backend.auth, AuthConfig::None));
3050        assert_eq!(backend.http, HttpConfig::default());
3051    }
3052
3053    #[cfg(feature = "http")]
3054    #[test]
3055    fn test_sql_config_unaffected() {
3056        // REF-01 superset / D-06 additive proof: a pure-SQL config with NO
3057        // [backend] still parses, and backend == None.
3058        let toml = r#"
3059            [server]
3060            name = "demo"
3061            version = "0.1.0"
3062
3063            [database]
3064            type = "sqlite"
3065            file_path = "/tmp/demo.db"
3066
3067            [[tools]]
3068            name = "list_tables"
3069            sql = "SELECT name FROM sqlite_master"
3070        "#;
3071        let cfg = ServerConfig::from_toml(toml).expect("SQL config must still parse");
3072        assert!(
3073            cfg.backend.is_none(),
3074            "SQL config must have backend == None"
3075        );
3076        assert_eq!(cfg.tools.len(), 1);
3077    }
3078
3079    #[cfg(feature = "http")]
3080    #[test]
3081    fn test_backend_unknown_field_rejected() {
3082        // T-90-02-01: deny_unknown_fields preserved — an unknown key under
3083        // [backend.http] is a hard parse error, never a silent default.
3084        let toml = r#"
3085            [server]
3086            name = "tube"
3087            version = "0.1.0"
3088
3089            [backend]
3090            base_url = "https://api.example.com"
3091
3092            [backend.http]
3093            foo = 1
3094        "#;
3095        let err =
3096            ServerConfig::from_toml(toml).expect_err("unknown [backend.http] key must be rejected");
3097        assert!(matches!(err, ToolkitError::Parse(_)), "got: {err:?}");
3098    }
3099
3100    // -------------------------------------------------------------------------
3101    // `[[config_slots]]` — PKG-03 slot declarations (Phase 120 Plan 04 Task 1)
3102    // -------------------------------------------------------------------------
3103
3104    /// The three-slot declaration block the london-tube proving fixture carries.
3105    const CONFIG_SLOTS_TOML: &str = r#"
3106        [server]
3107        name = "london-tube"
3108        version = "1.1.0"
3109
3110        [[config_slots]]
3111        key = "backend.base_url"
3112        kind = "endpoint"
3113        name = "TFL_BASE_URL"
3114        tested_value = "https://api.tfl.gov.uk"
3115
3116        [[config_slots]]
3117        key = "backend.auth.query_params.app_key"
3118        kind = "secret"
3119        name = "TFL_APP_KEY"
3120
3121        [[config_slots]]
3122        key = "backend.auth.type"
3123        kind = "auth_mode"
3124        name = "backend-auth-mode"
3125        tested_value = "api_key"
3126    "#;
3127
3128    /// Test 1: a `[[config_slots]]` block parses through the STRICT + validated
3129    /// entry point and exposes all three entries with their fields intact.
3130    #[test]
3131    fn config_slots_block_parses_through_strict_entry_point() {
3132        let cfg = ServerConfig::from_toml_strict_validated(CONFIG_SLOTS_TOML)
3133            .expect("[[config_slots]] must parse through the strict entry point");
3134        assert_eq!(cfg.config_slots.len(), 3, "three declared slots");
3135
3136        assert_eq!(cfg.config_slots[0].key, "backend.base_url");
3137        assert_eq!(cfg.config_slots[0].kind, ConfigSlotKind::Endpoint);
3138        assert_eq!(cfg.config_slots[0].name, "TFL_BASE_URL");
3139        assert_eq!(
3140            cfg.config_slots[0].tested_value.as_deref(),
3141            Some("https://api.tfl.gov.uk")
3142        );
3143
3144        assert_eq!(cfg.config_slots[1].kind, ConfigSlotKind::Secret);
3145        assert_eq!(cfg.config_slots[1].name, "TFL_APP_KEY");
3146        assert_eq!(cfg.config_slots[2].kind, ConfigSlotKind::AuthMode);
3147    }
3148
3149    /// A `[[config_slots]]` entry carrying `supplied_by` must BOOT.
3150    ///
3151    /// This is the load-bearing half of a two-crate change. `pmcp-package`
3152    /// refuses to pack a config whose fields this struct's
3153    /// `deny_unknown_fields` would reject, on the grounds that packing it would
3154    /// ship a server that cannot start. So if the packer learns `supplied_by`
3155    /// and this struct does not, every config using the field becomes
3156    /// unpackable; if this struct learns it and the packer does not, the packer
3157    /// rejects configs the server boots from happily. Both sides move together
3158    /// or neither does, and this test is the runtime half of that pin.
3159    #[test]
3160    fn a_config_slot_declaring_supplied_by_parses_through_the_strict_entry_point() {
3161        let toml = r#"
3162            [server]
3163            name = "tube"
3164            version = "0.1.0"
3165
3166            [[config_slots]]
3167            key = "backend.base_url"
3168            kind = "endpoint"
3169            name = "TFL_BASE_URL"
3170            tested_value = "https://api.tfl.gov.uk"
3171            supplied_by = "platform"
3172
3173            [[config_slots]]
3174            key = "backend.function_name"
3175            kind = "secret"
3176            name = "AWS_LAMBDA_FUNCTION_NAME"
3177            supplied_by = "runtime"
3178        "#;
3179        let cfg = ServerConfig::from_toml_strict_validated(toml)
3180            .expect("`supplied_by` must parse under deny_unknown_fields");
3181        assert_eq!(
3182            cfg.config_slots[0].supplied_by,
3183            ConfigSlotSuppliedBy::Platform
3184        );
3185        assert_eq!(
3186            cfg.config_slots[1].supplied_by,
3187            ConfigSlotSuppliedBy::Runtime
3188        );
3189    }
3190
3191    /// Omitting it means `environment`, so every config written before the
3192    /// field existed keeps its meaning rather than failing to parse.
3193    #[test]
3194    fn a_config_slot_without_supplied_by_defaults_to_environment() {
3195        let cfg = ServerConfig::from_toml_strict_validated(CONFIG_SLOTS_TOML)
3196            .expect("the pre-existing fixture must still parse");
3197        for slot in &cfg.config_slots {
3198            assert_eq!(slot.supplied_by, ConfigSlotSuppliedBy::Environment);
3199        }
3200    }
3201
3202    /// An unrecognized value is a parse ERROR, not a silent default — strict
3203    /// parse discipline (D-13). A defaulted typo here would tell an operator to
3204    /// supply a value the platform actually injects.
3205    #[test]
3206    fn an_unknown_supplied_by_value_is_a_parse_error() {
3207        let toml = r#"
3208            [server]
3209            name = "tube"
3210            version = "0.1.0"
3211
3212            [[config_slots]]
3213            key = "backend.base_url"
3214            kind = "endpoint"
3215            name = "TFL_BASE_URL"
3216            tested_value = "x"
3217            supplied_by = "platfrom"
3218        "#;
3219        ServerConfig::from_toml_strict_validated(toml)
3220            .expect_err("a misspelled supplied_by must not silently default");
3221    }
3222
3223    /// Test 2: the field is ADDITIVE — a config with no `[[config_slots]]` block
3224    /// parses unchanged and yields an empty vec (`#[serde(default)]`).
3225    #[test]
3226    fn config_without_config_slots_parses_with_empty_vec() {
3227        let cfg = ServerConfig::from_toml_strict_validated(MINIMAL)
3228            .expect("a config omitting [[config_slots]] still parses");
3229        assert!(
3230            cfg.config_slots.is_empty(),
3231            "absent block yields an empty vec, not a default entry"
3232        );
3233    }
3234
3235    /// Test 3: `deny_unknown_fields` still bites at the TOP level — a typo'd
3236    /// `[[config_slotz]]` is a hard parse error, never a silently-ignored block.
3237    #[test]
3238    fn top_level_config_slots_typo_is_still_rejected() {
3239        let toml = r#"
3240            [server]
3241            name = "demo"
3242            version = "0.1.0"
3243
3244            [[config_slotz]]
3245            key = "backend.base_url"
3246            kind = "endpoint"
3247            name = "TFL_BASE_URL"
3248        "#;
3249        let err = ServerConfig::from_toml(toml)
3250            .expect_err("a typo'd top-level array-of-tables must be rejected");
3251        assert!(matches!(err, ToolkitError::Parse(_)), "got: {err:?}");
3252    }
3253
3254    /// Test 4: the decl struct is itself `deny_unknown_fields` — a typo INSIDE
3255    /// the block (`nmae`) is rejected rather than silently dropped.
3256    #[test]
3257    fn config_slot_unknown_inner_key_is_rejected() {
3258        let toml = r#"
3259            [server]
3260            name = "demo"
3261            version = "0.1.0"
3262
3263            [[config_slots]]
3264            key = "backend.base_url"
3265            kind = "endpoint"
3266            nmae = "TFL_BASE_URL"
3267        "#;
3268        let err = ServerConfig::from_toml(toml)
3269            .expect_err("an unknown key inside [[config_slots]] must be rejected");
3270        assert!(matches!(err, ToolkitError::Parse(_)), "got: {err:?}");
3271    }
3272
3273    /// Test 5: `tested_value` is OPTIONAL — an identity-bearing slot structurally
3274    /// carries no value, so omitting it parses to `None`.
3275    #[test]
3276    fn config_slot_tested_value_is_optional() {
3277        let toml = r#"
3278            [server]
3279            name = "demo"
3280            version = "0.1.0"
3281
3282            [[config_slots]]
3283            key = "backend.auth.query_params.app_key"
3284            kind = "secret"
3285            name = "TFL_APP_KEY"
3286        "#;
3287        let cfg = ServerConfig::from_toml_strict_validated(toml)
3288            .expect("an entry without tested_value parses");
3289        assert_eq!(cfg.config_slots.len(), 1);
3290        assert!(
3291            cfg.config_slots[0].tested_value.is_none(),
3292            "omitted tested_value parses to None"
3293        );
3294    }
3295
3296    /// Test 6 (Codex MEDIUM — the invalid-kind hole): `kind` is a CLOSED
3297    /// vocabulary. A typo such as `endpont` — or an empty string — is a PARSE
3298    /// error naming the accepted set, not a declaration that parses cleanly and
3299    /// then fails to map to any package slot type two crates away.
3300    #[test]
3301    fn config_slot_invalid_kind_is_rejected_naming_the_accepted_set() {
3302        for bad in ["endpont", ""] {
3303            let toml = format!(
3304                r#"
3305                [server]
3306                name = "demo"
3307                version = "0.1.0"
3308
3309                [[config_slots]]
3310                key = "backend.base_url"
3311                kind = "{bad}"
3312                name = "TFL_BASE_URL"
3313                "#
3314            );
3315            let err = ServerConfig::from_toml(&toml)
3316                .expect_err("an unrecognized config-slot kind must be rejected at parse time");
3317            let rendered = err.to_string();
3318            for accepted in ["endpoint", "secret", "auth_mode"] {
3319                assert!(
3320                    rendered.contains(accepted),
3321                    "the error for kind = \"{bad}\" must name the accepted kind \
3322                     `{accepted}`: {rendered}"
3323                );
3324            }
3325        }
3326    }
3327
3328    /// Test 7: all three valid kinds parse, and the parsed value is a CLOSED
3329    /// enum — comparable as `ConfigSlotKind`, not as a free string. A fourth
3330    /// kind is therefore a deliberate addition here, never a silent
3331    /// pass-through to the package side.
3332    #[test]
3333    fn config_slot_all_three_kinds_parse_as_a_closed_enum() {
3334        let cfg = ServerConfig::from_toml_strict_validated(CONFIG_SLOTS_TOML)
3335            .expect("all three kinds parse");
3336        let kinds: Vec<ConfigSlotKind> = cfg.config_slots.iter().map(|s| s.kind).collect();
3337        assert_eq!(
3338            kinds,
3339            vec![
3340                ConfigSlotKind::Endpoint,
3341                ConfigSlotKind::Secret,
3342                ConfigSlotKind::AuthMode
3343            ],
3344            "kind is a closed enum, not a free string"
3345        );
3346    }
3347
3348    /// `validate()` rejects an entry whose `key` or `name` is empty/whitespace,
3349    /// carrying the offending entry INDEX (the `EmptyTableName(i)` error shape).
3350    #[test]
3351    fn config_slot_empty_key_or_name_fails_validation() {
3352        for field in ["key", "name"] {
3353            let (key, name) = if field == "key" {
3354                ("   ", "TFL_BASE_URL")
3355            } else {
3356                ("backend.base_url", "  ")
3357            };
3358            let toml = format!(
3359                r#"
3360                [server]
3361                name = "demo"
3362                version = "0.1.0"
3363
3364                [[config_slots]]
3365                key = "{key}"
3366                kind = "endpoint"
3367                name = "{name}"
3368                "#
3369            );
3370            let cfg = ServerConfig::from_toml(&toml).expect("parses; emptiness is semantic");
3371            let err = cfg
3372                .validate()
3373                .expect_err("an empty config-slot key/name must fail validation");
3374            assert!(
3375                matches!(err, ConfigValidationError::EmptyConfigSlotField(0)),
3376                "empty {field} must yield EmptyConfigSlotField(0), got: {err:?}"
3377            );
3378        }
3379    }
3380
3381    /// `validate()` refuses a `secret` declaration carrying a `tested_value` —
3382    /// identity-bearing slots structurally record no value, and this field is
3383    /// the one place a REAL credential could sit in a config that is served
3384    /// but never packed (pack-time gates only run on packaging).
3385    #[test]
3386    fn config_slot_secret_with_tested_value_fails_validation_without_echoing_it() {
3387        let toml = r#"
3388            [server]
3389            name = "demo"
3390            version = "0.1.0"
3391
3392            [[config_slots]]
3393            key = "backend.auth.query_params.app_key"
3394            kind = "secret"
3395            name = "TFL_APP_KEY"
3396            tested_value = "sentinel-real-credential"
3397        "#;
3398        let cfg = ServerConfig::from_toml(toml).expect("parses; the rule is semantic");
3399        let err = cfg
3400            .validate()
3401            .expect_err("a secret slot carrying a tested_value must fail validation");
3402        assert!(
3403            matches!(err, ConfigValidationError::SecretSlotCarriesTestedValue(0)),
3404            "got: {err:?}"
3405        );
3406        assert!(
3407            !err.to_string().contains("sentinel-real-credential"),
3408            "the error must not echo the value: {err}"
3409        );
3410    }
3411
3412    // -------------------------------------------------------------------------
3413    // Phase 128 D2 / SC-2 — the six new `ParamDecl` keys and the config-time
3414    // pattern-compile gate.
3415    // -------------------------------------------------------------------------
3416
3417    /// D2: all six new keys parse from TOML, including the
3418    /// `[tools.parameters.items]` sub-table.
3419    #[test]
3420    fn param_decl_parses_all_d2_keys() {
3421        let toml = r#"
3422            [server]
3423            name = "demo"
3424            version = "0.1.0"
3425
3426            [[tools]]
3427            name = "batch_lookup"
3428
3429            [[tools.parameters]]
3430            name = "codes"
3431            type = "array"
3432            required = true
3433            max_items = 25
3434            min_length = 2
3435            format = "uuid"
3436            pattern = "^[A-Z]{3}$"
3437            allow_slash = true
3438
3439            [tools.parameters.items]
3440            type = "string"
3441            max_length = 8
3442            pattern = "^[a-z]+$"
3443        "#;
3444        let cfg = ServerConfig::from_toml(toml).expect("parse");
3445        let p = &cfg.tools[0].parameters[0];
3446        assert_eq!(p.pattern.as_deref(), Some("^[A-Z]{3}$"));
3447        assert_eq!(p.min_length, Some(2));
3448        assert_eq!(p.format.as_deref(), Some("uuid"));
3449        assert_eq!(p.max_items, Some(25));
3450        assert!(p.allow_slash);
3451        let items = p.items.as_ref().expect("items sub-table");
3452        assert_eq!(items.item_type.as_deref(), Some("string"));
3453        assert_eq!(items.max_length, Some(8));
3454        assert_eq!(items.pattern.as_deref(), Some("^[a-z]+$"));
3455    }
3456
3457    /// D2: the six new keys survive a `Serialize` -> `Deserialize` round trip, so
3458    /// a config re-emitted by the toolkit does not silently drop a declared rule.
3459    #[test]
3460    fn param_decl_d2_keys_round_trip_through_toml() {
3461        let original = ParamDecl {
3462            name: "codes".to_string(),
3463            param_type: Some("array".to_string()),
3464            required: true,
3465            pattern: Some("^[A-Z]{3}$".to_string()),
3466            min_length: Some(2),
3467            format: Some("uuid".to_string()),
3468            max_items: Some(25),
3469            allow_slash: true,
3470            items: Some(ItemsDecl {
3471                item_type: Some("string".to_string()),
3472                max_length: Some(8),
3473                pattern: Some("^[a-z]+$".to_string()),
3474            }),
3475            ..Default::default()
3476        };
3477        let cfg = ServerConfig {
3478            server: ServerSection {
3479                name: "demo".to_string(),
3480                version: "0.1.0".to_string(),
3481                ..Default::default()
3482            },
3483            tools: vec![ToolDecl {
3484                name: "batch_lookup".to_string(),
3485                parameters: vec![original.clone()],
3486                ..Default::default()
3487            }],
3488            ..Default::default()
3489        };
3490        let text = toml::to_string(&cfg).expect("serialize");
3491        let parsed = ServerConfig::from_toml(&text).expect("re-parse");
3492        assert_eq!(parsed.tools[0].parameters[0], original);
3493    }
3494
3495    /// SC-2: a `pattern` that does not compile fails at CONFIG time, naming the
3496    /// offending parameter — not at call time, where it would take the whole
3497    /// tool's validator down.
3498    #[test]
3499    fn validate_rejects_uncompilable_param_pattern() {
3500        let toml = r#"
3501            [server]
3502            name = "demo"
3503            version = "0.1.0"
3504
3505            [[tools]]
3506            name = "lookup"
3507
3508            [[tools.parameters]]
3509            name = "region"
3510            type = "string"
3511            pattern = "^[A-Z"
3512        "#;
3513        let cfg = ServerConfig::from_toml(toml).expect("parse");
3514        match cfg.validate() {
3515            Err(ConfigValidationError::UncompilableParamSchema {
3516                ref tool,
3517                ref position,
3518                ref detail,
3519            }) => {
3520                assert_eq!(tool, "lookup");
3521                assert!(
3522                    position.contains("region"),
3523                    "position must name the offending parameter, got {position:?}"
3524                );
3525                assert!(
3526                    !detail.is_empty(),
3527                    "the author-facing detail must be present"
3528                );
3529            },
3530            other => panic!("expected UncompilableParamSchema, got {other:?}"),
3531        }
3532    }
3533
3534    /// SC-2 edge (adjacency): a pattern that COMPILES but matches nothing passes
3535    /// config validation. Config validation checks compilability, not
3536    /// satisfiability — `$^` will refuse every value at call time instead.
3537    #[test]
3538    fn validate_accepts_unsatisfiable_but_compilable_param_pattern() {
3539        let toml = r#"
3540            [server]
3541            name = "demo"
3542            version = "0.1.0"
3543
3544            [[tools]]
3545            name = "lookup"
3546
3547            [[tools.parameters]]
3548            name = "region"
3549            type = "string"
3550            pattern = "$^"
3551        "#;
3552        let cfg = ServerConfig::from_toml(toml).expect("parse");
3553        cfg.validate()
3554            .expect("an unsatisfiable pattern still compiles and must validate");
3555    }
3556
3557    /// SC-2 edge (empty): an empty `pattern` matches everything, so it buys no
3558    /// enforcement while reading like a rule. Refused as a likely author error.
3559    #[test]
3560    fn validate_rejects_empty_param_pattern() {
3561        let toml = r#"
3562            [server]
3563            name = "demo"
3564            version = "0.1.0"
3565
3566            [[tools]]
3567            name = "lookup"
3568
3569            [[tools.parameters]]
3570            name = "region"
3571            type = "string"
3572            pattern = ""
3573        "#;
3574        let cfg = ServerConfig::from_toml(toml).expect("parse");
3575        match cfg.validate() {
3576            Err(ConfigValidationError::EmptyParamPattern {
3577                ref tool,
3578                ref param,
3579            }) => {
3580                assert_eq!(tool, "lookup");
3581                assert_eq!(param, "region");
3582            },
3583            other => panic!("expected EmptyParamPattern, got {other:?}"),
3584        }
3585    }
3586
3587    /// D3 edge (precision): a bound whose magnitude exceeds 2^53 is refused,
3588    /// because `ParamDecl` stores bounds as `f64` and such a value cannot be
3589    /// represented exactly.
3590    #[test]
3591    fn validate_rejects_non_finite_param_bound() {
3592        let toml = r#"
3593            [server]
3594            name = "demo"
3595            version = "0.1.0"
3596
3597            [[tools]]
3598            name = "lookup"
3599
3600            [[tools.parameters]]
3601            name = "count"
3602            type = "integer"
3603            maximum = 1e300
3604        "#;
3605        let cfg = ServerConfig::from_toml(toml).expect("parse");
3606        match cfg.validate() {
3607            Err(ConfigValidationError::NonFiniteParamBound {
3608                ref tool,
3609                ref param,
3610            }) => {
3611                assert_eq!(tool, "lookup");
3612                assert_eq!(param, "count");
3613            },
3614            other => panic!("expected NonFiniteParamBound, got {other:?}"),
3615        }
3616    }
3617
3618    /// D3 edge (precision), the honest half: a bound AT the 2^53 boundary is
3619    /// accepted. The check cannot see that a larger TOML integer was already
3620    /// rounded into this value, and the rustdoc says so rather than claiming a
3621    /// guarantee it cannot deliver.
3622    #[test]
3623    fn validate_accepts_param_bound_at_the_representable_boundary() {
3624        let toml = r#"
3625            [server]
3626            name = "demo"
3627            version = "0.1.0"
3628
3629            [[tools]]
3630            name = "lookup"
3631
3632            [[tools.parameters]]
3633            name = "count"
3634            type = "integer"
3635            maximum = 9007199254740992
3636        "#;
3637        let cfg = ServerConfig::from_toml(toml).expect("parse");
3638        cfg.validate()
3639            .expect("a bound exactly at 2^53 is representable and must validate");
3640    }
3641
3642    // -------------------------------------------------------------------------
3643    // Phase 128 D3 / D-07 — `[server.validation]`, `param_position`, `lint()`
3644    // -------------------------------------------------------------------------
3645
3646    /// `[server.validation]` parses with all four keys.
3647    #[test]
3648    fn validation_section_parses_all_four_keys() {
3649        let toml = r#"
3650            [server]
3651            name = "demo"
3652            version = "0.1.0"
3653
3654            [server.validation]
3655            enforce_input_schema = false
3656            default_max_length = 64
3657            additional_properties = true
3658            strict = true
3659        "#;
3660        let cfg = ServerConfig::from_toml(toml).expect("parse");
3661        let v = &cfg.server.validation;
3662        assert!(!v.enforce_input_schema);
3663        assert_eq!(v.default_max_length, 64);
3664        assert!(v.additional_properties);
3665        assert!(v.strict);
3666    }
3667
3668    /// Each absent key yields its documented default, and an absent SECTION yields
3669    /// the same — enforcement is on unless an operator opts out.
3670    #[test]
3671    fn validation_section_absent_keys_yield_documented_defaults() {
3672        let partial = r#"
3673            [server]
3674            name = "demo"
3675            version = "0.1.0"
3676
3677            [server.validation]
3678            default_max_length = 10
3679        "#;
3680        let cfg = ServerConfig::from_toml(partial).expect("parse");
3681        let v = &cfg.server.validation;
3682        assert!(v.enforce_input_schema, "default is ON");
3683        assert_eq!(v.default_max_length, 10);
3684        assert!(!v.additional_properties, "default is a closed envelope");
3685        assert!(!v.strict, "default must not refuse to boot");
3686
3687        let cfg = ServerConfig::from_toml(MINIMAL).expect("parse");
3688        assert_eq!(cfg.server.validation, ValidationSection::default());
3689        assert!(cfg.server.validation.enforce_input_schema);
3690        assert_eq!(cfg.server.validation.default_max_length, 256);
3691    }
3692
3693    /// An unknown key under `[server.validation]` is refused at PARSE time — the
3694    /// section carries `deny_unknown_fields`, so a typo'd opt-out cannot be
3695    /// silently ignored.
3696    #[test]
3697    fn validation_section_rejects_an_unknown_key() {
3698        let toml = r#"
3699            [server]
3700            name = "demo"
3701            version = "0.1.0"
3702
3703            [server.validation]
3704            enforce_input_schemas = false
3705        "#;
3706        let err = ServerConfig::from_toml(toml)
3707            .expect_err("a typo'd opt-out key must not be silently ignored");
3708        assert!(matches!(err, ToolkitError::Parse(_)), "got {err:?}");
3709    }
3710
3711    /// `ToolDecl::param_position` agrees with `tools.rs::build_operation`'s PATH
3712    /// split for every parameter of a single-call tool, and applies the
3713    /// method-aware query/body rule for the rest.
3714    #[test]
3715    fn param_position_agrees_with_build_operation_on_path_parameters() {
3716        let get_tool = ToolDecl {
3717            name: "line_status".to_string(),
3718            path: Some("/lines/{line_id}/status".to_string()),
3719            method: Some("GET".to_string()),
3720            parameters: vec![
3721                ParamDecl {
3722                    name: "line_id".to_string(),
3723                    ..Default::default()
3724                },
3725                ParamDecl {
3726                    name: "detail".to_string(),
3727                    ..Default::default()
3728                },
3729            ],
3730            ..Default::default()
3731        };
3732        // The PATH set is the shared helper both functions read.
3733        let path_names: Vec<&str> =
3734            path_placeholder_names(get_tool.path.as_deref().expect("path")).collect();
3735        assert_eq!(path_names, vec!["line_id"]);
3736        for p in &get_tool.parameters {
3737            let expected = if path_names.contains(&p.name.as_str()) {
3738                ParamPosition::Path
3739            } else {
3740                ParamPosition::Query
3741            };
3742            assert_eq!(
3743                get_tool.param_position(&p.name),
3744                expected,
3745                "position for {} must agree with the path split",
3746                p.name
3747            );
3748        }
3749
3750        // A mutating method's non-path parameter is BODY here AND
3751        // `ParameterLocation::Body` in `build_operation` — the two agree by
3752        // construction since CR-02/CR-03 (see
3753        // `param_position_agrees_with_the_built_parameter_location_for_every_method`
3754        // in `tools.rs::mod build_operation`, which asserts the pairing directly).
3755        let post_tool = ToolDecl {
3756            name: "add_comment".to_string(),
3757            path: Some("/issues/{id}/comments".to_string()),
3758            method: Some("POST".to_string()),
3759            ..Default::default()
3760        };
3761        assert_eq!(post_tool.param_position("id"), ParamPosition::Path);
3762        assert_eq!(post_tool.param_position("body_text"), ParamPosition::Body);
3763
3764        // A method that carries NO request body puts its non-path input in the URL,
3765        // `OPTIONS` included. Before CR-03 this returned `Body` — so the D3 cap was
3766        // withheld from a value `build_operation` sent in the query string.
3767        let options_tool = ToolDecl {
3768            name: "probe".to_string(),
3769            path: Some("/issues/{id}".to_string()),
3770            method: Some("OPTIONS".to_string()),
3771            ..Default::default()
3772        };
3773        assert_eq!(options_tool.param_position("id"), ParamPosition::Path);
3774        assert_eq!(options_tool.param_position("detail"), ParamPosition::Query);
3775
3776        // No method at all is still BODY: a SQL named bind or a script-tool
3777        // argument, neither of which has a URL to travel in.
3778        let sql_tool = ToolDecl {
3779            name: "q".to_string(),
3780            sql: Some("SELECT :id".to_string()),
3781            ..Default::default()
3782        };
3783        assert_eq!(sql_tool.param_position("id"), ParamPosition::Body);
3784    }
3785
3786    /// `{}` is not a placeholder, and a brace pair inside a larger segment is not
3787    /// one either — the helper matches whole `/`-delimited segments only.
3788    #[test]
3789    fn path_placeholder_names_matches_whole_segments_only() {
3790        let names: Vec<&str> = path_placeholder_names("/a/{}/b/{id}/c/pre{mid}post").collect();
3791        assert_eq!(names, vec!["id"]);
3792    }
3793
3794    /// SC-3 edge (empty): a config with zero tools and no active opt-out lints
3795    /// clean.
3796    #[test]
3797    fn lint_returns_empty_vec_for_a_config_with_zero_tools() {
3798        let cfg = ServerConfig::from_toml(MINIMAL).expect("parse");
3799        assert_eq!(cfg.lint(), Vec::new());
3800    }
3801
3802    /// Build a config with one tool whose declarations are supplied by the caller.
3803    fn cfg_with_one_tool(tool: ToolDecl, validation: ValidationSection) -> ServerConfig {
3804        ServerConfig {
3805            server: ServerSection {
3806                name: "demo".to_string(),
3807                version: "0.1.0".to_string(),
3808                validation,
3809                ..Default::default()
3810            },
3811            tools: vec![tool],
3812            ..Default::default()
3813        }
3814    }
3815
3816    /// A SQL tool's string parameter with no `max_length` is BODY position and is
3817    /// surfaced by `lint()` — not refused (D-05 / D-07).
3818    #[test]
3819    fn lint_reports_one_uncapped_string_finding_per_body_parameter() {
3820        let cfg = cfg_with_one_tool(
3821            ToolDecl {
3822                name: "search_tracks".to_string(),
3823                sql: Some("SELECT 1".to_string()),
3824                parameters: vec![ParamDecl {
3825                    name: "q".to_string(),
3826                    param_type: Some("string".to_string()),
3827                    ..Default::default()
3828                }],
3829                ..Default::default()
3830            },
3831            ValidationSection::default(),
3832        );
3833        let findings = cfg.lint();
3834        assert_eq!(findings.len(), 1, "got {findings:?}");
3835        assert_eq!(findings[0].rule, UNCAPPED_STRING);
3836        assert_eq!(findings[0].tool.as_deref(), Some("search_tracks"));
3837        assert_eq!(findings[0].param.as_deref(), Some("q"));
3838        // The same config must still BOOT — a non-strict finding never refuses.
3839        cfg.validate()
3840            .expect("a lint finding must not fail validate");
3841    }
3842
3843    /// SC-3 ordering: findings follow `[[tools.parameters]]` declaration order, not
3844    /// alphabetical order.
3845    #[test]
3846    fn lint_returns_findings_in_declaration_order() {
3847        let cfg = cfg_with_one_tool(
3848            ToolDecl {
3849                name: "note".to_string(),
3850                sql: Some("SELECT 1".to_string()),
3851                parameters: vec![
3852                    ParamDecl {
3853                        name: "zebra".to_string(),
3854                        param_type: Some("string".to_string()),
3855                        ..Default::default()
3856                    },
3857                    ParamDecl {
3858                        name: "alpha".to_string(),
3859                        param_type: Some("string".to_string()),
3860                        ..Default::default()
3861                    },
3862                ],
3863                ..Default::default()
3864            },
3865            ValidationSection::default(),
3866        );
3867        let findings = cfg.lint();
3868        assert_eq!(findings.len(), 2, "got {findings:?}");
3869        assert_eq!(findings[0].param.as_deref(), Some("zebra"));
3870        assert_eq!(findings[1].param.as_deref(), Some("alpha"));
3871    }
3872
3873    /// D3 ordering (mixed): for a tool carrying BOTH an uncapped body string and an
3874    /// uncapped path string, only the body one is a finding — the path one is
3875    /// covered by the default cap — and the finding order follows declaration order.
3876    #[test]
3877    fn lint_skips_a_path_parameter_covered_by_the_default_cap() {
3878        let cfg = cfg_with_one_tool(
3879            ToolDecl {
3880                name: "add_comment".to_string(),
3881                path: Some("/issues/{id}/comments".to_string()),
3882                method: Some("POST".to_string()),
3883                parameters: vec![
3884                    ParamDecl {
3885                        name: "body_text".to_string(),
3886                        param_type: Some("string".to_string()),
3887                        ..Default::default()
3888                    },
3889                    ParamDecl {
3890                        name: "id".to_string(),
3891                        param_type: Some("string".to_string()),
3892                        ..Default::default()
3893                    },
3894                ],
3895                ..Default::default()
3896            },
3897            ValidationSection::default(),
3898        );
3899        let findings = cfg.lint();
3900        assert_eq!(findings.len(), 1, "got {findings:?}");
3901        assert_eq!(findings[0].param.as_deref(), Some("body_text"));
3902        assert_eq!(findings[0].rule, UNCAPPED_STRING);
3903    }
3904
3905    /// SC-7 shape mismatch: a path-position parameter declaring a `max_length`
3906    /// ABOVE the always-on placeholder floor is surfaced, because it publishes a
3907    /// limit the floor will not honour.
3908    #[cfg(feature = "input-validation")]
3909    #[test]
3910    fn lint_reports_a_declared_max_length_above_the_placeholder_floor() {
3911        let floor = pmcp::server::schema_validation::PLACEHOLDER_MAX_LENGTH as u64;
3912        let cfg = cfg_with_one_tool(
3913            ToolDecl {
3914                name: "line_status".to_string(),
3915                path: Some("/lines/{line_id}/status".to_string()),
3916                method: Some("GET".to_string()),
3917                parameters: vec![ParamDecl {
3918                    name: "line_id".to_string(),
3919                    param_type: Some("string".to_string()),
3920                    max_length: Some(floor + 1),
3921                    ..Default::default()
3922                }],
3923                ..Default::default()
3924            },
3925            ValidationSection::default(),
3926        );
3927        let findings = cfg.lint();
3928        assert_eq!(findings.len(), 1, "got {findings:?}");
3929        assert_eq!(findings[0].rule, DECLARED_MAX_LENGTH_ABOVE_PLACEHOLDER_CAP);
3930        assert_eq!(findings[0].param.as_deref(), Some("line_id"));
3931        assert!(
3932            findings[0].detail.contains(&floor.to_string()),
3933            "the finding must name the effective limit: {}",
3934            findings[0].detail
3935        );
3936
3937        // Exactly AT the floor is fine — the adjacency case.
3938        let cfg = cfg_with_one_tool(
3939            ToolDecl {
3940                name: "line_status".to_string(),
3941                path: Some("/lines/{line_id}/status".to_string()),
3942                method: Some("GET".to_string()),
3943                parameters: vec![ParamDecl {
3944                    name: "line_id".to_string(),
3945                    param_type: Some("string".to_string()),
3946                    max_length: Some(floor),
3947                    ..Default::default()
3948                }],
3949                ..Default::default()
3950            },
3951            ValidationSection::default(),
3952        );
3953        assert_eq!(cfg.lint(), Vec::new());
3954    }
3955
3956    /// Every ACTIVE opt-out is reported, so a switched-off enforcement can never
3957    /// read as switched on.
3958    #[test]
3959    fn lint_reports_every_active_opt_out() {
3960        let cfg = cfg_with_one_tool(
3961            ToolDecl {
3962                name: "ping".to_string(),
3963                sql: Some("SELECT 1".to_string()),
3964                ..Default::default()
3965            },
3966            ValidationSection {
3967                enforce_input_schema: false,
3968                default_max_length: 0,
3969                additional_properties: true,
3970                strict: false,
3971            },
3972        );
3973        let rules: Vec<&str> = cfg.lint().iter().map(|w| w.rule).collect();
3974        assert_eq!(
3975            rules,
3976            vec![
3977                OPT_OUT_ENFORCE_INPUT_SCHEMA,
3978                OPT_OUT_DEFAULT_MAX_LENGTH_ZERO,
3979                OPT_OUT_ADDITIONAL_PROPERTIES,
3980            ]
3981        );
3982        // A server-level finding names no tool or parameter.
3983        for w in cfg.lint() {
3984            assert!(w.tool.is_none(), "{w:?}");
3985            assert!(w.param.is_none(), "{w:?}");
3986            assert!(!w.to_string().is_empty(), "Display must render");
3987        }
3988    }
3989
3990    /// D-07 strict mode: the SAME config that returns `Ok(())` with one lint
3991    /// finding under the default becomes a hard `validate()` failure under
3992    /// `strict = true`.
3993    #[test]
3994    fn validate_rejects_uncapped_string_param_in_strict_mode() {
3995        let toml_body = r#"
3996            [server]
3997            name = "demo"
3998            version = "0.1.0"
3999
4000            [[tools]]
4001            name = "search_tracks"
4002            sql = "SELECT 1"
4003
4004            [[tools.parameters]]
4005            name = "q"
4006            type = "string"
4007        "#;
4008        let lenient = ServerConfig::from_toml(toml_body).expect("parse");
4009        lenient
4010            .validate()
4011            .expect("non-strict must never refuse to boot over an uncapped body string");
4012        assert_eq!(lenient.lint().len(), 1);
4013
4014        let strict_toml = format!("{toml_body}\n[server.validation]\nstrict = true\n");
4015        let strict = ServerConfig::from_toml(&strict_toml).expect("parse");
4016        match strict.validate() {
4017            Err(ConfigValidationError::UncappedStringParam {
4018                ref tool,
4019                ref param,
4020            }) => {
4021                assert_eq!(tool, "search_tracks");
4022                assert_eq!(param, "q");
4023            },
4024            other => panic!("expected UncappedStringParam, got {other:?}"),
4025        }
4026    }
4027
4028    /// `validation_report()` carries the effective policy and a per-tool rule list
4029    /// for the once-at-startup log.
4030    #[test]
4031    fn validation_report_carries_the_effective_policy_and_per_tool_rules() {
4032        let cfg = cfg_with_one_tool(
4033            ToolDecl {
4034                name: "line_status".to_string(),
4035                path: Some("/lines/{line_id}/status".to_string()),
4036                method: Some("GET".to_string()),
4037                parameters: vec![ParamDecl {
4038                    name: "line_id".to_string(),
4039                    param_type: Some("string".to_string()),
4040                    required: true,
4041                    pattern: Some("^[0-9a-z-]+$".to_string()),
4042                    ..Default::default()
4043                }],
4044                ..Default::default()
4045            },
4046            ValidationSection::default(),
4047        );
4048        let report = cfg.validation_report();
4049        assert!(report.enforce_input_schema);
4050        assert_eq!(report.default_max_length, 256);
4051        assert!(report.opt_outs.is_empty(), "nothing is opted out");
4052        assert_eq!(report.tools.len(), 1);
4053        assert_eq!(report.tools[0].tool, "line_status");
4054        let rule = &report.tools[0].rules[0];
4055        assert!(rule.contains("line_id"), "{rule}");
4056        assert!(rule.contains("Path"), "{rule}");
4057        assert!(rule.contains("pattern"), "{rule}");
4058        assert!(rule.contains("maxLength=256 (default)"), "{rule}");
4059    }
4060
4061    // -- Phase 128 D4(b) step 3b: the curated template parser's limit, enforced at
4062    //    CONFIG time rather than failing obscurely at call time. ---------------
4063
4064    /// A single-call `GET` tool on `path`, no parameters.
4065    fn single_call_on(path: &str) -> ServerConfig {
4066        cfg_with_one_tool(
4067            ToolDecl {
4068                name: "t".to_string(),
4069                description: Some("t".to_string()),
4070                path: Some(path.to_string()),
4071                method: Some("GET".to_string()),
4072                ..Default::default()
4073            },
4074            ValidationSection::default(),
4075        )
4076    }
4077
4078    fn assert_malformed_segment(path: &str) {
4079        let err = single_call_on(path)
4080            .validate()
4081            .expect_err("an unsupported path-template segment must be refused at config time");
4082        match err {
4083            ConfigValidationError::MalformedPathTemplateSegment { tool, segment } => {
4084                assert_eq!(tool, "t");
4085                assert!(!segment.is_empty(), "the finding must name the segment");
4086            },
4087            other => panic!("expected MalformedPathTemplateSegment, got {other:?}"),
4088        }
4089    }
4090
4091    /// `/search/{a}{b}` parses to the SINGLE name `a}{b`, which no `ParamDecl` can
4092    /// match — refused at config time instead of sending literal braces upstream.
4093    #[test]
4094    fn validate_rejects_a_path_template_segment_with_two_brace_pairs() {
4095        assert_malformed_segment("/search/{a}{b}");
4096    }
4097
4098    /// `/prefix-{id}` is not recognized as carrying a placeholder at all.
4099    #[test]
4100    fn validate_rejects_a_path_template_segment_with_text_adjacent_to_a_brace_pair() {
4101        assert_malformed_segment("/prefix-{id}");
4102    }
4103
4104    /// `{}` is a brace pair with no name — not a placeholder.
4105    #[test]
4106    fn validate_rejects_an_empty_path_template_placeholder() {
4107        assert_malformed_segment("/a/{}/b");
4108    }
4109
4110    /// An unbalanced brace is the same author error seen from the other side.
4111    #[test]
4112    fn validate_rejects_an_unbalanced_path_template_brace() {
4113        assert_malformed_segment("/a/{id");
4114    }
4115
4116    /// ACCEPT control: whole-segment placeholders are the supported shape. Without
4117    /// this row the four refusals above are satisfiable by refusing every template.
4118    #[test]
4119    fn validate_accepts_whole_segment_path_template_placeholders() {
4120        single_call_on("/content/{version}/CUI/{cui}")
4121            .validate()
4122            .expect("whole-segment placeholders are the supported shape");
4123    }
4124
4125    /// ACCEPT control, and the CURATED half of the inherited `?` narrowing: an
4126    /// author-written query string in a `[[tools]]` `path` is configuration, not
4127    /// caller data, and must keep working.
4128    #[test]
4129    fn validate_accepts_a_path_template_carrying_an_author_written_query_string() {
4130        single_call_on("/content/{version}/CUI?string=x")
4131            .validate()
4132            .expect("an author-written query string in a curated path must be accepted");
4133    }
4134
4135    /// A SQL tool has no `path`, so the template rule cannot reach it.
4136    #[test]
4137    fn validate_ignores_the_template_rule_for_a_tool_with_no_path() {
4138        cfg_with_one_tool(
4139            ToolDecl {
4140                name: "t".to_string(),
4141                sql: Some("SELECT 1".to_string()),
4142                ..Default::default()
4143            },
4144            ValidationSection::default(),
4145        )
4146        .validate()
4147        .expect("a SQL tool carries no path template");
4148    }
4149
4150    proptest! {
4151        /// TEST-02: any valid `ServerConfig` round-trips through TOML.
4152        ///
4153        /// Builds a `ServerConfig` from an arbitrary (but valid) `(name, version)`
4154        /// pair, serializes it, parses it back, and asserts equality on the
4155        /// load-bearing scalars.
4156        #[test]
4157        fn server_config_minimal_round_trips(
4158            name in "[a-zA-Z0-9_-]{1,32}",
4159            version in "[0-9]+\\.[0-9]+\\.[0-9]+",
4160        ) {
4161            let cfg = ServerConfig {
4162                server: ServerSection {
4163                    name: name.clone(),
4164                    version: version.clone(),
4165                    ..Default::default()
4166                },
4167                ..Default::default()
4168            };
4169            let s = toml::to_string(&cfg).unwrap();
4170            let parsed = ServerConfig::from_toml(&s).unwrap();
4171            prop_assert_eq!(parsed.server.name, name);
4172            prop_assert_eq!(parsed.server.version, version);
4173        }
4174    }
4175}
4176
4177/// `ServerConfig::lint_against_spec` — the CONFIG-time half of the
4178/// template-spelling-drift guard (Phase 128, D4(b) / T-128-36a).
4179///
4180/// Four rows, and the shape matters: one row per DRIFT that must be reported, plus
4181/// three accept rows for the shapes that must NOT be, because a finding-producing
4182/// lint with no accept rows is indistinguishable from one that fires on everything.
4183#[cfg(all(test, feature = "http"))]
4184mod lint_against_spec_tests {
4185    use super::{ServerConfig, ToolDecl, CONFIGURED_TEMPLATE_NOT_IN_SPEC};
4186    use crate::http::OpenApiSchema;
4187
4188    const SPEC: &str = r#"{
4189      "openapi": "3.0.0",
4190      "info": { "title": "t", "version": "1" },
4191      "paths": {
4192        "/content/{version}/CUI": {
4193          "get": {
4194            "operationId": "getCui",
4195            "parameters": [
4196              { "name": "version", "in": "path", "required": true,
4197                "schema": { "type": "string", "pattern": "^[a-z]+$" } }
4198            ],
4199            "responses": { "200": { "description": "ok" } }
4200          }
4201        }
4202      }
4203    }"#;
4204
4205    fn spec() -> OpenApiSchema {
4206        OpenApiSchema::parse(SPEC).expect("the fixture spec parses")
4207    }
4208
4209    fn cfg_with(tools: Vec<ToolDecl>) -> ServerConfig {
4210        ServerConfig {
4211            server: super::ServerSection {
4212                name: "t".to_string(),
4213                version: "0.1.0".to_string(),
4214                ..Default::default()
4215            },
4216            tools,
4217            ..Default::default()
4218        }
4219    }
4220
4221    fn http_tool(name: &str, method: &str, path: &str) -> ToolDecl {
4222        ToolDecl {
4223            name: name.to_string(),
4224            method: Some(method.to_string()),
4225            path: Some(path.to_string()),
4226            ..Default::default()
4227        }
4228    }
4229
4230    /// The drift the guard exists for: a placeholder spelled differently from the
4231    /// spec's own reaches the same endpoint with the declaration dropped.
4232    #[test]
4233    fn lint_against_spec_reports_a_template_the_spec_does_not_declare() {
4234        let cfg = cfg_with(vec![http_tool("get_cui", "GET", "/content/{alias}/CUI")]);
4235        let findings = cfg.lint_against_spec(&spec());
4236        assert_eq!(findings.len(), 1, "{findings:?}");
4237        assert_eq!(findings[0].rule, CONFIGURED_TEMPLATE_NOT_IN_SPEC);
4238        assert_eq!(findings[0].tool.as_deref(), Some("get_cui"));
4239        assert!(
4240            findings[0].detail.contains("floor"),
4241            "the finding must say what a miss RETAINS, not only what it loses: {}",
4242            findings[0].detail
4243        );
4244    }
4245
4246    /// A method the spec does not declare on a path it does is the same class of
4247    /// drift, because operations are indexed by `(path, METHOD)`.
4248    #[test]
4249    fn lint_against_spec_reports_a_method_the_spec_does_not_declare() {
4250        let cfg = cfg_with(vec![http_tool(
4251            "del_cui",
4252            "DELETE",
4253            "/content/{version}/CUI",
4254        )]);
4255        let rules: Vec<&str> = cfg
4256            .lint_against_spec(&spec())
4257            .iter()
4258            .map(|w| w.rule)
4259            .collect();
4260        assert_eq!(rules, vec![CONFIGURED_TEMPLATE_NOT_IN_SPEC]);
4261    }
4262
4263    /// ACCEPT — an exact match, in either method case, is no finding.
4264    #[test]
4265    fn lint_against_spec_accepts_an_exactly_declared_template() {
4266        let cfg = cfg_with(vec![
4267            http_tool("a", "GET", "/content/{version}/CUI"),
4268            http_tool("b", "get", "/content/{version}/CUI"),
4269        ]);
4270        assert_eq!(cfg.lint_against_spec(&spec()), Vec::new());
4271    }
4272
4273    /// ACCEPT — an author-written query string on the configured `path` is legal
4274    /// curated authoring (plan 06's `?` narrowing) and an OpenAPI template never
4275    /// carries one, so it is stripped before the lookup rather than reported.
4276    #[test]
4277    fn lint_against_spec_accepts_an_author_written_query_string() {
4278        let cfg = cfg_with(vec![http_tool(
4279            "a",
4280            "GET",
4281            "/content/{version}/CUI?string=x",
4282        )]);
4283        assert_eq!(cfg.lint_against_spec(&spec()), Vec::new());
4284    }
4285
4286    /// ACCEPT — a tool that addresses no single spec operation is skipped, not
4287    /// reported. A SQL tool has no `(method, path)` to look up.
4288    #[test]
4289    fn lint_against_spec_skips_a_tool_with_no_method_path_pair() {
4290        let cfg = cfg_with(vec![ToolDecl {
4291            name: "q".to_string(),
4292            sql: Some("SELECT 1".to_string()),
4293            ..Default::default()
4294        }]);
4295        assert_eq!(cfg.lint_against_spec(&spec()), Vec::new());
4296    }
4297}