trusty_code/jsonrpc/error.rs
1//! Typed JSON-RPC error returned by [`super::router::MethodHandler`] impls.
2//!
3//! Why: handlers need a lightweight, typed way to signal a specific JSON-RPC
4//! error code (invalid params, internal error, …) without the router having
5//! to string-sniff an `anyhow::Error`. Centralising the constructors here
6//! means every handler produces spec-correct codes by construction.
7//! What: `RpcError { code, message, data }` plus constructors for the
8//! standard JSON-RPC 2.0 codes a handler is expected to return itself, and
9//! (#2054) the vision spec's domain error taxonomy (§13.2) — an
10//! *additive* layer of application-specific codes carried in the same
11//! envelope, each tagged with `data.error_type` so clients can match on a
12//! stable string rather than a numeric code alone. `-32601 Method not
13//! found` and `-32600 Invalid Request` are produced by
14//! [`super::router::Router`] before a handler is ever invoked, so they are
15//! intentionally not exposed as constructors here — a handler has no
16//! legitimate reason to fabricate either.
17//! Test: this module's unit tests.
18
19use serde_json::{Value, json};
20use trusty_mcp::error_codes;
21
22/// A JSON-RPC 2.0 error, as returned by a method handler.
23///
24/// Why: mirrors `trusty_mcp::JsonRpcError`'s shape so the router can
25/// convert one into the other with a straight field copy, but stays a
26/// separate type so handler code never has to construct the wire envelope
27/// directly.
28/// What: `code` is a JSON-RPC error code (spec-defined or application
29/// range); `message` is human-readable; `data` is optional structured detail
30/// attached to the wire error.
31/// Test: `rpc_error_invalid_params_sets_code`, `rpc_error_internal_sets_code`.
32#[derive(Debug, Clone)]
33pub struct RpcError {
34 pub code: i32,
35 pub message: String,
36 pub data: Option<Value>,
37}
38
39impl RpcError {
40 /// Construct an `RpcError` with an arbitrary code.
41 ///
42 /// Why: escape hatch for application-defined codes outside the standard
43 /// JSON-RPC range (e.g. a future domain-specific error).
44 /// What: sets `code`/`message`, leaves `data` unset.
45 /// Test: `rpc_error_new_has_no_data_by_default`.
46 pub fn new(code: i32, message: impl Into<String>) -> Self {
47 Self {
48 code,
49 message: message.into(),
50 data: None,
51 }
52 }
53
54 /// Attach structured `data` to an existing error.
55 ///
56 /// Why: some failures carry machine-readable detail (e.g. which field
57 /// failed validation) beyond the human-readable `message`.
58 /// What: builder-style setter; returns `self` for chaining.
59 /// Test: `rpc_error_with_data_attaches_payload`.
60 pub fn with_data(mut self, data: Value) -> Self {
61 self.data = Some(data);
62 self
63 }
64
65 /// Build a `-32602 Invalid params` error.
66 ///
67 /// Why: the standard code a handler returns when it cannot parse or
68 /// validate its `params` argument.
69 /// What: `code = error_codes::INVALID_PARAMS`.
70 /// Test: `rpc_error_invalid_params_sets_code`.
71 pub fn invalid_params(message: impl Into<String>) -> Self {
72 Self::new(error_codes::INVALID_PARAMS, message)
73 }
74
75 /// Build a `-32603 Internal error` error.
76 ///
77 /// Why: the standard code for a handler-side failure that isn't the
78 /// caller's fault (I/O failure, downstream panic-free error, etc.).
79 /// What: `code = error_codes::INTERNAL_ERROR`.
80 /// Test: `rpc_error_internal_sets_code`.
81 pub fn internal(message: impl Into<String>) -> Self {
82 Self::new(error_codes::INTERNAL_ERROR, message)
83 }
84
85 /// Build a domain-taxonomy error (vision spec §13.2): a code from the
86 /// spec's table plus a stable `error_type` string tagged onto `data`.
87 ///
88 /// Why: the spec's domain errors (`session_not_found`, `invalid_argument`,
89 /// `cancelled`, …) live in a numeric range distinct from the standard
90 /// JSON-RPC `-326xx` codes, and every one of them carries
91 /// `data.error_type` so a client can match on the string rather than
92 /// memorising numbers. Centralising the shape here means every domain
93 /// error is built the same way.
94 /// What: sets `code`, `message`, and `data = {"error_type": error_type}`.
95 /// Test: `rpc_error_domain_sets_error_type_in_data`.
96 fn domain(code: i32, error_type: &'static str, message: impl Into<String>) -> Self {
97 Self::new(code, message).with_data(json!({"error_type": error_type}))
98 }
99
100 /// Build a `-32007 session_not_found` error (vision spec §13.2).
101 ///
102 /// Why: the specific, spec-named code for "the session id in `params`
103 /// does not exist in the registry" — used by every `session.*` method
104 /// that takes a `session_id`.
105 /// What: `message` embeds `session_id` for operator-visible logs;
106 /// `data.error_type = "session_not_found"`.
107 /// Test: `rpc_error_session_not_found_sets_code_and_type`.
108 pub fn session_not_found(session_id: &str) -> Self {
109 Self::domain(
110 -32007,
111 "session_not_found",
112 format!("session not found: {session_id}"),
113 )
114 }
115
116 /// Build a `-32002 not_found` error (vision spec §13.2).
117 ///
118 /// Why: the spec's general "the thing you named does not exist" code,
119 /// distinct from the session-specific `-32007 session_not_found` — used by
120 /// methods whose subject is not a session (e.g. `fs.list_dir` on a path
121 /// that isn't there).
122 /// What: `data.error_type = "not_found"`.
123 /// Test: `rpc_error_not_found_sets_code_and_type`.
124 pub fn not_found(message: impl Into<String>) -> Self {
125 Self::domain(-32002, "not_found", message)
126 }
127
128 /// Build a `-32001 permission_denied` error (vision spec §13.2).
129 ///
130 /// Why: the spec's "caller lacks permission" code. tcode adds no permission
131 /// layer of its own — it runs as the user with the user's entitlements — so
132 /// this reports an OS-level refusal (e.g. an unreadable directory) rather
133 /// than a policy decision tcode made.
134 /// What: `data.error_type = "permission_denied"`.
135 /// Test: `rpc_error_permission_denied_sets_code_and_type`.
136 pub fn permission_denied(message: impl Into<String>) -> Self {
137 Self::domain(-32001, "permission_denied", message)
138 }
139
140 /// Build a `-32003 invalid_argument` error (vision spec §13.2).
141 ///
142 /// Why: the spec's domain-level "malformed request" code, distinct from
143 /// the JSON-RPC protocol-level `-32602 Invalid params` — used when a
144 /// method's arguments parse as JSON but fail a semantic check (e.g. an
145 /// empty task description).
146 /// What: `data.error_type = "invalid_argument"`.
147 /// Test: `rpc_error_invalid_argument_sets_code_and_type`.
148 pub fn invalid_argument(message: impl Into<String>) -> Self {
149 Self::domain(-32003, "invalid_argument", message)
150 }
151
152 /// Build a `-32008 active_conflict` error (DOC-48 §5.2/§6.1, issue #3294).
153 ///
154 /// Why: `workstream.activate{id, force: false}` must fail when a
155 /// DIFFERENT workstream is already active, and the caller needs the
156 /// currently-active id to decide whether to retry with `force: true`
157 /// (§6.1: "the error includes the ID of the currently-active
158 /// workstream"). `-32008` is the next free slot after `-32007
159 /// session_not_found` in this crate's domain-error range — DOC-48
160 /// predates no reservation for it in the vision spec's §13.2 table, so
161 /// it is allocated here rather than colliding with the reserved-but-
162 /// unimplemented `-32004`/`-32005`/`-32006` (`timeout`/`cancelled`/
163 /// `provider_failure`).
164 /// What: `data = {"error_type": "active_conflict", "active_id": <uuid
165 /// string>}` — `active_id` rides alongside the standard `error_type` tag
166 /// so a client can read the conflicting id without re-parsing `message`.
167 /// Test: `rpc_error_active_conflict_sets_code_and_active_id`.
168 pub fn active_conflict(active_id: impl std::fmt::Display) -> Self {
169 let active_id = active_id.to_string();
170 Self::new(-32008, format!("another workstream is active: {active_id}"))
171 .with_data(json!({"error_type": "active_conflict", "active_id": active_id}))
172 }
173
174 /// Build a `-32009 already_exists` error (issue #3449).
175 ///
176 /// Why: `agents.create`/`skills.create` must refuse to overwrite an
177 /// existing disk entry, and that conflict needs its OWN code — an early
178 /// cut reused the literal `-32008`, but that slot is
179 /// [`Self::active_conflict`]'s (DOC-48 §5.2, constructor-backed, and
180 /// asserted on numerically by the workstreams tests), so sharing it
181 /// would make the two semantically different conflicts
182 /// indistinguishable to a client matching on code (code-critic PR #3465
183 /// review, LOW). `-32009` is the next free slot after it.
184 /// What: `data.error_type = "already_exists"`. The REST layer maps this
185 /// to `409 Conflict` (`serve::rest::rpc_error_to_status`), same HTTP
186 /// status as `active_conflict` — the distinction lives in the JSON-RPC
187 /// code/`error_type`, where protocol clients look.
188 /// Test: `rpc_error_already_exists_sets_code_and_type`.
189 pub fn already_exists(message: impl Into<String>) -> Self {
190 Self::domain(-32009, "already_exists", message)
191 }
192}
193
194impl std::fmt::Display for RpcError {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 write!(f, "JSON-RPC error {}: {}", self.code, self.message)
197 }
198}
199
200impl std::error::Error for RpcError {}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205 use serde_json::json;
206
207 /// `invalid_params` must use the spec's `-32602` code.
208 #[test]
209 fn rpc_error_invalid_params_sets_code() {
210 let e = RpcError::invalid_params("bad shape");
211 assert_eq!(e.code, error_codes::INVALID_PARAMS);
212 assert_eq!(e.message, "bad shape");
213 assert!(e.data.is_none());
214 }
215
216 /// `internal` must use the spec's `-32603` code.
217 #[test]
218 fn rpc_error_internal_sets_code() {
219 let e = RpcError::internal("boom");
220 assert_eq!(e.code, error_codes::INTERNAL_ERROR);
221 assert_eq!(e.message, "boom");
222 }
223
224 /// `new` alone must not attach any `data`.
225 #[test]
226 fn rpc_error_new_has_no_data_by_default() {
227 let e = RpcError::new(-1, "custom");
228 assert_eq!(e.code, -1);
229 assert!(e.data.is_none());
230 }
231
232 /// `with_data` must attach the supplied payload.
233 #[test]
234 fn rpc_error_with_data_attaches_payload() {
235 let e = RpcError::invalid_params("bad field").with_data(json!({"field": "name"}));
236 assert_eq!(e.data, Some(json!({"field": "name"})));
237 }
238
239 /// `Display` must surface both the code and the message for logs.
240 #[test]
241 fn rpc_error_display_contains_code_and_message() {
242 let e = RpcError::internal("db unreachable");
243 let s = e.to_string();
244 assert!(s.contains("-32603"));
245 assert!(s.contains("db unreachable"));
246 }
247
248 /// `session_not_found` must use the spec's `-32007` code, embed the id
249 /// in the message, and tag `error_type` in `data`.
250 #[test]
251 fn rpc_error_session_not_found_sets_code_and_type() {
252 let e = RpcError::session_not_found("s-123");
253 assert_eq!(e.code, -32007);
254 assert!(e.message.contains("s-123"));
255 assert_eq!(e.data, Some(json!({"error_type": "session_not_found"})));
256 }
257
258 /// `not_found` must use the spec's `-32002` code and tag `error_type`.
259 #[test]
260 fn rpc_error_not_found_sets_code_and_type() {
261 let e = RpcError::not_found("path not found: /x");
262 assert_eq!(e.code, -32002);
263 assert_eq!(e.data, Some(json!({"error_type": "not_found"})));
264 }
265
266 /// `permission_denied` must use the spec's `-32001` code and tag
267 /// `error_type`.
268 #[test]
269 fn rpc_error_permission_denied_sets_code_and_type() {
270 let e = RpcError::permission_denied("permission denied: /x");
271 assert_eq!(e.code, -32001);
272 assert_eq!(e.data, Some(json!({"error_type": "permission_denied"})));
273 }
274
275 /// `invalid_argument` must use the spec's `-32003` code and tag
276 /// `error_type` in `data`.
277 #[test]
278 fn rpc_error_invalid_argument_sets_code_and_type() {
279 let e = RpcError::invalid_argument("task must not be empty");
280 assert_eq!(e.code, -32003);
281 assert_eq!(e.data, Some(json!({"error_type": "invalid_argument"})));
282 }
283
284 /// `active_conflict` must use `-32008`, tag `error_type`, and carry the
285 /// conflicting `active_id` in `data` (DOC-48 §6.1).
286 #[test]
287 fn rpc_error_active_conflict_sets_code_and_active_id() {
288 let e = RpcError::active_conflict("a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b");
289 assert_eq!(e.code, -32008);
290 assert!(e.message.contains("a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b"));
291 assert_eq!(
292 e.data,
293 Some(json!({
294 "error_type": "active_conflict",
295 "active_id": "a1b2c3d4-e5f6-4748-9a0b-1c2d3e4f5a6b",
296 }))
297 );
298 }
299
300 /// `already_exists` must use `-32009` — its OWN slot, distinct from
301 /// `active_conflict`'s `-32008` (code-critic PR #3465 review, LOW).
302 #[test]
303 fn rpc_error_already_exists_sets_code_and_type() {
304 let e = RpcError::already_exists("agent 'dup' already exists on disk");
305 assert_eq!(e.code, -32009);
306 assert_ne!(e.code, RpcError::active_conflict("x").code);
307 assert_eq!(e.data, Some(json!({"error_type": "already_exists"})));
308 }
309}