pmcp_server_toolkit/error.rs
1// Originated from pmcp-run/built-in/shared/mcp-server-common (https://github.com/guyernest/pmcp-run)
2// Promoted to rust-mcp-sdk workspace as a public SDK crate for Phase 83.
3
4//! Toolkit error type and crate-level `Result` alias.
5//!
6//! [`ToolkitError`] is `#[non_exhaustive]`: downstream crates must match with a
7//! catch-all arm so the toolkit can add variants without a breaking change.
8//! Phase 83 Plan 04 extends this enum with a `Validation` variant wrapping a
9//! [`ConfigValidationError`] (per review R8) which catches missing-required-value
10//! bugs the `Default` impls on sub-sections would otherwise silently hide.
11
12/// Crate-level result alias used by every public API in `pmcp-server-toolkit`.
13pub type Result<T> = std::result::Result<T, ToolkitError>;
14
15/// Errors surfaced by the `pmcp-server-toolkit` runtime.
16///
17/// The enum is `#[non_exhaustive]` — match callers must include a wildcard arm.
18///
19/// # Examples
20///
21/// ```
22/// use pmcp_server_toolkit::ToolkitError;
23/// use std::error::Error;
24///
25/// // ToolkitError is a real `std::error::Error`, with a usable `Display` impl.
26/// let err: ToolkitError = ToolkitError::MissingField("database.dsn".into());
27/// assert_eq!(err.to_string(), "missing required config field: database.dsn");
28/// // Implements `std::error::Error`, so it composes with `?` and `Box<dyn Error>`.
29/// let boxed: Box<dyn Error + Send + Sync> = Box::new(err);
30/// assert!(boxed.source().is_none());
31/// ```
32#[derive(Debug, thiserror::Error)]
33#[non_exhaustive]
34pub enum ToolkitError {
35 /// TOML parse failure while loading a `ServerConfig`.
36 #[error("failed to parse config TOML: {0}")]
37 Parse(#[from] toml::de::Error),
38
39 /// A required config field was absent during tool synthesis.
40 #[error("missing required config field: {0}")]
41 MissingField(String),
42
43 /// `[[tools]]` synthesis failed (covers Phase 83 TKIT-07 failure modes).
44 #[error("tool synthesis failed: {0}")]
45 Synth(String),
46
47 /// Code-mode wiring failed (covers Phase 83 TKIT-09 failure modes).
48 #[error("code-mode wiring failed: {0}")]
49 CodeMode(String),
50
51 /// Filesystem failure while reading a config or fixture.
52 #[error("I/O error: {0}")]
53 Io(#[from] std::io::Error),
54
55 /// Secret resolution failed (env var missing, AWS API error, etc.).
56 ///
57 /// Carries the secret name and a descriptive cause string; the underlying
58 /// raw value is NEVER carried in this variant — only the lookup-key
59 /// metadata and the error context. This preserves the `SecretValue`
60 /// negative-trait invariants at the error path (review R5 + T-83-02-02).
61 #[error("secret '{name}' not resolvable: {cause}")]
62 Secret {
63 /// The secret name that could not be resolved.
64 name: String,
65 /// Human-readable cause (provider name + underlying error).
66 cause: String,
67 },
68
69 /// Semantic validation of a parsed [`crate::config::ServerConfig`] failed.
70 ///
71 /// Wraps a [`ConfigValidationError`] surfaced by
72 /// [`crate::config::ServerConfig::validate`] /
73 /// [`crate::config::ServerConfig::from_toml_strict_validated`]. Per Phase 83
74 /// review R8 this catches the empty-required-value trap that the
75 /// `Default` impls on sub-sections would otherwise hide behind silent
76 /// successes (e.g. `server.name = ""` if the `[server]` header is typo'd).
77 #[error("config validation failed: {0}")]
78 Validation(#[from] ConfigValidationError),
79
80 /// `[backend].base_url` holds a `${VAR}` / `env:VAR` reference that could
81 /// not be resolved: the named environment variable is unset, or is set to
82 /// an empty / whitespace-only value.
83 ///
84 /// Filed HERE and NOT under [`ConfigValidationError`] deliberately (Phase
85 /// 120 Plan 04, cross-AI review LOW). `ConfigValidationError` is the
86 /// semantic validation surfaced by
87 /// [`crate::config::ServerConfig::validate`] — i.e. PARSE time. This lookup
88 /// happens at DISPATCH time, long after `validate()` returned `Ok` (the
89 /// literal `"${TFL_BASE_URL}"` is non-empty, so the emptiness rule passes).
90 /// Filing a runtime lookup failure under parse-time validation would make
91 /// that enum's own documentation false and would let a caller matching
92 /// `ToolkitError::Validation(..)` believe the config was malformed.
93 ///
94 /// # Security (T-120-17)
95 ///
96 /// The message names the FIELD and the environment-variable NAME only. It
97 /// MUST NOT echo a resolved URL, the config's contents, or any credential
98 /// substring.
99 #[error(
100 "[backend].base_url references environment variable '{var}', which is \
101 unset or empty (set it to the REST API root URL)"
102 )]
103 UnresolvedBaseUrlRef {
104 /// The environment-variable name the `base_url` reference points at.
105 /// Never the resolved value.
106 var: String,
107 },
108
109 /// A governed-Excel workbook bundle failed to load + integrity-verify at
110 /// boot (Phase 92, WBSV-08 fail-closed). Wraps a
111 /// [`pmcp_workbook_runtime::BundleLoadError`] — a source read failure, a
112 /// malformed/truncated artifact, or an integrity-hash mismatch (a tampered
113 /// or swapped bundle). Feature-gated on `workbook` so the no-`workbook`
114 /// build never names the runtime type.
115 #[cfg(feature = "workbook")]
116 #[error("workbook bundle load failed: {0}")]
117 Workbook(#[from] pmcp_workbook_runtime::BundleLoadError),
118}
119
120/// Semantic-validation errors surfaced by
121/// [`crate::config::ServerConfig::validate`].
122///
123/// Per Phase 83 review R8 — the `Default` impls on `ServerConfig` and its
124/// sub-sections deliberately allow `from_toml` to succeed even when required
125/// fields are missing (so partial configs can be merged programmatically). The
126/// [`crate::config::ServerConfig::validate`] entry-point catches these gaps at
127/// parse time and surfaces them as a typed enum variant per rule.
128///
129/// The enum is `#[non_exhaustive]` — match callers must include a wildcard arm
130/// so additional rules can be added without a breaking change.
131///
132/// # Examples
133///
134/// ```
135/// use pmcp_server_toolkit::ConfigValidationError;
136///
137/// // Each variant has a precise `Display` describing the rule violated.
138/// let err = ConfigValidationError::EmptyServerName;
139/// assert_eq!(err.to_string(), "server.name must be non-empty");
140/// let err = ConfigValidationError::EmptyToolName(3);
141/// assert_eq!(err.to_string(), "[[tools]] entry at index 3 has empty name");
142/// ```
143#[derive(Debug, thiserror::Error)]
144#[non_exhaustive]
145pub enum ConfigValidationError {
146 /// `[server] name` is missing or whitespace-only.
147 #[error("server.name must be non-empty")]
148 EmptyServerName,
149 /// `[server] version` is missing or whitespace-only.
150 #[error("server.version must be non-empty")]
151 EmptyServerVersion,
152 /// `[[tools]]` entry at `index` has an empty / whitespace-only `name`.
153 #[error("[[tools]] entry at index {0} has empty name")]
154 EmptyToolName(usize),
155 /// `[[database.tables]]` entry at `index` has an empty / whitespace-only `name`.
156 #[error("[[database.tables]] entry at index {0} has empty name")]
157 EmptyTableName(usize),
158 /// Per Phase 83 Plan 06 review R9: `[code_mode].token_secret` was given as
159 /// an inline literal (e.g. `token_secret = "raw-string"`) instead of the
160 /// `env:VAR_NAME` reference form, and the dev-only escape hatch
161 /// `allow_inline_token_secret_for_dev` was not set. Inline literals in
162 /// committed configs leak HMAC signing keys; the toolkit defaults to
163 /// rejecting them.
164 #[error(
165 "[code_mode].token_secret is an inline literal; use 'env:VAR_NAME' \
166 or set allow_inline_token_secret_for_dev=true (NEVER in production)"
167 )]
168 InlineSecretRejected,
169 /// Per Phase 90 Plan 02 (D-01, T-90-02-04): a `[[tools]]` entry declares
170 /// more than one mutually-exclusive tool kind. A tool is EITHER a SQL tool
171 /// (`sql`), a single-call HTTP tool (`path`/`method`), OR a script tool
172 /// (`script`) — never a mixture. The ambiguity is rejected rather than
173 /// resolved by a silent precedence rule. The `usize` is the entry index.
174 #[error(
175 "[[tools]] entry at index {0} declares ambiguous tool kind: set exactly \
176 one of `sql`, `path`/`method`, or `script` (not a mixture)"
177 )]
178 AmbiguousToolKind(usize),
179 /// Per Phase 90 gap-closure (GAP 3 / WR-02): a `[backend]` block is present
180 /// but its `base_url` is empty / whitespace-only (or the `base_url` key was
181 /// omitted, defaulting to `""` via `#[serde(default)]`). Without this
182 /// parse-time check a typo'd or missing `base_url` would validate cleanly
183 /// and then surface late as an opaque `DispatchError::Connector("invalid
184 /// base URL")` at the first backend request. Rejecting it here turns that
185 /// late opaque failure into an actionable, field-naming error.
186 #[error(
187 "[backend].base_url must be non-empty (set the REST API root URL, \
188 e.g. \"https://api.example.com\")"
189 )]
190 EmptyBackendBaseUrl,
191 /// `[backend].base_url` is REFERENCE-shaped but does not name exactly one
192 /// environment variable — the empty `${}` form, or a multi-placeholder
193 /// composition like `"${SCHEME}://${HOST}"`. The grammar
194 /// ([`crate::env_ref::parse_env_ref`]) resolves one whole-value `${VAR}` /
195 /// `env:VAR` reference; it does not interpolate inside a larger string, so
196 /// no environment could ever satisfy such a value. Without this check the
197 /// config loads cleanly and every boot fails with an
198 /// `UnresolvedBaseUrlRef` naming an empty variable.
199 #[error(
200 "[backend].base_url is a malformed environment reference; a reference must be \
201 exactly one `${{VAR}}` or `env:VAR` naming a single variable — inline \
202 compositions like \"${{SCHEME}}://${{HOST}}\" cannot be resolved by any \
203 environment, so compose the full URL in ONE variable instead"
204 )]
205 MalformedBackendBaseUrlRef,
206 /// A `[backend.auth]` credential field is REFERENCE-shaped but does not name
207 /// exactly one environment variable — the empty `${}` form, a
208 /// multi-placeholder composition like `"${SCHEME}://${HOST}"`, or a
209 /// non-portable name like `"${TFL-APP-KEY}"` (a `${...}` name must match
210 /// `[A-Za-z0-9_]+`; `env:VAR` remains the escape hatch for exotic names).
211 /// The `String` is the offending field path within `[backend.auth]` — e.g.
212 /// `"token"`, `"password"`, `"query_params.app_key"`.
213 ///
214 /// This is the credential sibling of [`Self::MalformedBackendBaseUrlRef`],
215 /// and it exists because the two paths resolve UNSET references differently
216 /// on purpose: a credential resolves an unset variable to the empty string
217 /// so an optional credential is OMITTED. A MALFORMED reference is not an
218 /// unset variable — no environment can ever satisfy it — so applying the
219 /// omission rule to it silently sent every backend request UNAUTHENTICATED,
220 /// with no error and no log line. Refusing it at load time turns that into
221 /// an actionable, field-naming failure before the server ever boots.
222 ///
223 /// The message names the FIELD only and deliberately never echoes the
224 /// configured value: a malformed value is by definition not a resolvable
225 /// reference, so it may well be a mistyped literal secret.
226 #[error(
227 "[backend.auth].{0} is a malformed environment reference; a reference must be \
228 exactly one `${{VAR}}` (name matching [A-Za-z0-9_]+) or `env:VAR` naming a single \
229 variable — no environment can satisfy this value, so the credential would be \
230 silently omitted and every backend request sent unauthenticated"
231 )]
232 MalformedBackendAuthRef(String),
233 /// Per Phase 120 Plan 04 (PKG-03): a `[[config_slots]]` entry at `index`
234 /// has an empty / whitespace-only `key` or `name`. A slot declaration whose
235 /// key names no config path — or whose name names no environment variable —
236 /// claims coverage it cannot deliver, and the package side would compare
237 /// against an empty string.
238 ///
239 /// The sibling "unrecognized `kind`" check is NOT here: `kind` is the
240 /// closed [`crate::config::ConfigSlotKind`] enum, so serde rejects an
241 /// unknown discriminator at PARSE time (naming the accepted set) before
242 /// `validate()` is ever called.
243 #[error("[[config_slots]] entry at index {0} has an empty key or name")]
244 EmptyConfigSlotField(usize),
245 /// A `[[config_slots]]` entry at `index` is `kind = "secret"` but carries a
246 /// `tested_value`. Identity-bearing slots structurally carry no value — the
247 /// `tested_value` field on a secret declaration is the one place a REAL
248 /// credential could sit in a config that is served but never packed (the
249 /// pack-time agreement gate only runs on packaging), so the rule is
250 /// enforced at validation time rather than trusted as prose. The message
251 /// deliberately does not echo the value.
252 #[error(
253 "[[config_slots]] entry at index {0} is kind = \"secret\" but carries a tested_value; \
254 identity-bearing slots record no value — remove it (a credential must never sit in \
255 the config file)"
256 )]
257 SecretSlotCarriesTestedValue(usize),
258}