Skip to main content

mcp_twill/
error.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4use thiserror::Error;
5
6pub type Result<T> = std::result::Result<T, FrameworkError>;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
9#[serde(rename_all = "snake_case")]
10pub enum WorkspaceMetadataProblem {
11    ExpectedObject,
12    MissingSandboxCwd,
13    InvalidSandboxCwd,
14    InvalidPermissionProfile,
15    ConflictingAliases,
16}
17
18impl fmt::Display for WorkspaceMetadataProblem {
19    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        formatter.write_str(match self {
21            Self::ExpectedObject => "expected_object",
22            Self::MissingSandboxCwd => "missing_sandbox_cwd",
23            Self::InvalidSandboxCwd => "invalid_sandbox_cwd",
24            Self::InvalidPermissionProfile => "invalid_permission_profile",
25            Self::ConflictingAliases => "conflicting_aliases",
26        })
27    }
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
31#[serde(rename_all = "snake_case")]
32pub enum PreResolvedWorkspaceProblem {
33    DuplicateWorkspace,
34    UnknownWorkspace,
35}
36
37impl fmt::Display for PreResolvedWorkspaceProblem {
38    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39        formatter.write_str(match self {
40            Self::DuplicateWorkspace => "duplicate_workspace",
41            Self::UnknownWorkspace => "unknown_workspace",
42        })
43    }
44}
45
46#[derive(Debug, Error, Clone, PartialEq, Eq)]
47pub enum FrameworkError {
48    #[error("empty command")]
49    EmptyCommand,
50    #[error("unterminated quote in command template")]
51    UnterminatedQuote,
52    #[error("shell syntax is not allowed in command templates: {0}")]
53    ShellSyntax(String),
54    #[error("placeholder `{0}` must occupy a complete argv token")]
55    PlaceholderInterpolation(String),
56    #[error("placeholder `{0}` is not an `$args.<name>` placeholder")]
57    InvalidPlaceholder(String),
58    #[error("unknown command `{command}`")]
59    UnknownCommand {
60        command: String,
61        nearest: Vec<String>,
62    },
63    #[error("unknown argument `{0}`")]
64    UnknownArgument(String),
65    #[error("missing argument `{0}`")]
66    MissingArgument(String),
67    #[error("argument `{0}` must be {1}")]
68    InvalidArgumentType(String, &'static str),
69    #[error("{}", union_mismatch_message(argument, type_name, problems))]
70    ArgumentUnionMismatch {
71        argument: String,
72        type_name: String,
73        /// Every declared variant in declaration order, paired with its
74        /// first blocking problem.
75        problems: Vec<(String, String)>,
76    },
77    #[error(
78        "argument `{argument}` does not satisfy its schema at `{path}` ({keyword}); expected {expected}"
79    )]
80    ArgumentSchemaMismatch {
81        argument: String,
82        path: String,
83        keyword: crate::ArgumentSchemaKeyword,
84        expected: String,
85        branches: Vec<crate::SchemaBranchProblem>,
86    },
87    #[error(
88        "{}",
89        workspace_mismatch_message(argument, workspace, selected_root, diagnostics)
90    )]
91    WorkspaceMismatch {
92        argument: String,
93        workspace: String,
94        /// The root URI selected for the workspace, when resolution succeeded
95        /// and the failure was a boundary check.
96        selected_root: Option<String>,
97        /// The offending input path value, when one was supplied.
98        path: Option<String>,
99        /// Resolver diagnostics explaining why the workspace failed to
100        /// resolve, when resolution (rather than containment) failed.
101        diagnostics: Box<[mcp_workspace_resolver::WorkspaceDiagnostic]>,
102    },
103    #[error("{}", workspace_unresolved_message(workspace, diagnostics))]
104    WorkspaceUnresolved {
105        /// The workspace the command declared with `uses_workspace`.
106        workspace: String,
107        /// Resolver diagnostics explaining why resolution failed.
108        diagnostics: Box<[mcp_workspace_resolver::WorkspaceDiagnostic]>,
109    },
110    #[error("{}", capability_missing_message(capability, carrier, providers))]
111    CapabilityMissing {
112        /// The declared capability the command requires.
113        capability: String,
114        /// The argument that carries proof of the capability.
115        carrier: String,
116        /// Commands that establish the capability, derived from `provides`
117        /// declarations.
118        providers: Vec<String>,
119    },
120    #[error("capability `{capability}` denied: {detail}")]
121    CapabilityDenied {
122        /// The declared explicit proof capability the application refused.
123        capability: String,
124        /// Application-specific detail, normalized before public response.
125        detail: String,
126        /// The carrier argument, filled in by the framework from the
127        /// capability declaration before the response is built.
128        carrier: Option<String>,
129        /// Commands that establish the capability, filled in by the
130        /// framework from `provides` declarations.
131        providers: Vec<String>,
132    },
133    #[error("resource `{resource}` refused for `{reference}`: {detail}")]
134    ResourceRefused {
135        /// The declared resource whose reference did not resolve.
136        resource: String,
137        /// The reference as presented (bare id or URI).
138        reference: String,
139        /// The resolver's prose (stale lease, foreign tab, expired
140        /// session).
141        detail: String,
142        /// Commands that enumerate the resource, derived from handler
143        /// output types — the recovery path for lost references.
144        enumerate: Box<[String]>,
145        /// Commands that grant the resource, derived from handler output
146        /// types — the establishment path when nothing exists yet.
147        establish: Box<[String]>,
148    },
149    #[error("required resource `{resource}` has no available binding")]
150    ResourceBindingMissing {
151        /// The required resource for which neither an explicit nor ambient
152        /// source was selected.
153        resource: String,
154        /// Commands that establish the resource, derived from handler output
155        /// types.
156        establish: Box<[String]>,
157    },
158    #[error("ambient resource `{resource}` was refused")]
159    AmbientResourceRefused {
160        /// The declared resource whose private ambient reference did not
161        /// resolve. The reference and resolver detail are intentionally not
162        /// retained.
163        resource: String,
164        /// Commands that enumerate the resource, derived from handler output
165        /// types.
166        enumerate: Box<[String]>,
167        /// Commands that establish the resource, derived from handler output
168        /// types.
169        establish: Box<[String]>,
170    },
171    #[error("invalid conversation identity request context at `{key}` ({reason})")]
172    InvalidConversationIdentity {
173        /// Stable source label (`canonical` or `codexThreadId`).
174        observation_source: String,
175        /// Metadata key that contained the invalid observation.
176        key: String,
177        /// Invalid or missing field, when the failure is field-specific.
178        field: Option<String>,
179        /// Stable redacted subreason.
180        reason: String,
181        /// Safe description of the accepted shape, when useful.
182        expected: Option<String>,
183    },
184    #[error("conflicting conversation identity request context observations")]
185    ConflictingConversationIdentity,
186    #[error("invalid workspace request context at `{key}` ({reason})")]
187    InvalidWorkspaceMetadata {
188        key: String,
189        field: Option<String>,
190        reason: WorkspaceMetadataProblem,
191    },
192    #[error("raw host workspace observations cannot be combined with pre-resolved workspaces")]
193    ConflictingWorkspaceInputs,
194    #[error("invalid pre-resolved workspace set ({reason})")]
195    InvalidPreResolvedWorkspaceSet {
196        workspace: Option<String>,
197        reason: PreResolvedWorkspaceProblem,
198    },
199    #[error("stdin mismatch: {0}")]
200    StdinMismatch(String),
201    #[error("permission denied for `{effect}` on `{scope}`")]
202    PermissionDenied { effect: String, scope: String },
203    #[error("confirmation is unavailable for operation `{operation_id}`")]
204    ConfirmationUnavailable { operation_id: String },
205    #[error("confirmation was canceled for operation `{operation_id}`")]
206    ConfirmationCanceled { operation_id: String },
207    #[error("confirmation failed for operation `{operation_id}`")]
208    ConfirmationFailed { operation_id: String },
209    #[error("approval invalid: {0}")]
210    ApprovalInvalid(String),
211    #[error("This command requires {required_tool}.")]
212    WrongEffectLane {
213        current_tool: String,
214        required_tool: String,
215    },
216    #[error("registry build failed: {0}")]
217    Build(String),
218    #[error("declared result contract was violated")]
219    ResultContractViolation {
220        boundary: crate::ResultContractBoundary,
221        reason: crate::ResultContractReason,
222    },
223    #[error("declared argument contract was violated")]
224    ArgumentContractViolation {
225        operation_id: String,
226        argument: Option<String>,
227        reason: crate::ArgumentContractReason,
228    },
229    #[error("protocol release evidence is not sealed")]
230    ProtocolReleaseUnsealed,
231    #[error("command handler failed: {0}")]
232    Handler(String),
233}
234
235impl FrameworkError {
236    /// Constructor for handlers that determine a presented capability is
237    /// invalid (for example, a receipt for an older build). The framework fills in the
238    /// carrier argument and establishing commands from the declarations
239    /// before the response is built.
240    pub fn capability_denied(capability: impl Into<String>, detail: impl Into<String>) -> Self {
241        Self::CapabilityDenied {
242            capability: capability.into(),
243            detail: detail.into(),
244            carrier: None,
245            providers: Vec::new(),
246        }
247    }
248}
249
250/// Every declared variant appears with its first blocking problem, in
251/// declaration order, so an agent sees exactly which fields would make its
252/// value match.
253fn union_mismatch_message(
254    argument: &str,
255    type_name: &str,
256    problems: &[(String, String)],
257) -> String {
258    let mut message = format!("argument `{argument}` does not match `{type_name}`:");
259    for (variant, problem) in problems {
260        message.push_str(&format!("\n  not `{variant}`: {problem}"));
261    }
262    message
263}
264
265/// A boundary failure and a resolution failure are different causes and get
266/// different top-level messages; the structured diagnostics carry the detail.
267fn workspace_mismatch_message(
268    argument: &str,
269    workspace: &str,
270    selected_root: &Option<String>,
271    diagnostics: &[mcp_workspace_resolver::WorkspaceDiagnostic],
272) -> String {
273    match selected_root {
274        Some(root) => {
275            format!("path argument `{argument}` is outside workspace `{workspace}` root `{root}`")
276        }
277        None if !diagnostics.is_empty() => format!(
278            "workspace `{workspace}` for path argument `{argument}` could not be resolved: {}",
279            diagnostics
280                .iter()
281                .map(|diagnostic| diagnostic.message.as_str())
282                .collect::<Vec<_>>()
283                .join("; ")
284        ),
285        None => {
286            format!("workspace `{workspace}` for path argument `{argument}` could not be resolved")
287        }
288    }
289}
290
291/// The command declared the workspace itself, so the failure is located at
292/// the command, not at any argument.
293fn workspace_unresolved_message(
294    workspace: &str,
295    diagnostics: &[mcp_workspace_resolver::WorkspaceDiagnostic],
296) -> String {
297    if diagnostics.is_empty() {
298        format!("workspace `{workspace}` required by this command could not be resolved")
299    } else {
300        format!(
301            "workspace `{workspace}` required by this command could not be resolved: {}",
302            diagnostics
303                .iter()
304                .map(|diagnostic| diagnostic.message.as_str())
305                .collect::<Vec<_>>()
306                .join("; ")
307        )
308    }
309}
310
311/// The steering names the capability and every establishing command, derived
312/// from `provides` declarations rather than written at the error site.
313fn capability_missing_message(capability: &str, carrier: &str, providers: &[String]) -> String {
314    let mut message = format!(
315        "argument `{carrier}` carries the `{capability}` capability, which this command requires."
316    );
317    if !providers.is_empty() {
318        let listed = providers
319            .iter()
320            .map(|provider| format!("`{provider}`"))
321            .collect::<Vec<_>>()
322            .join(", ");
323        message.push_str(&format!(" Establish it with {listed}."));
324    }
325    message
326}