forge-error 0.6.0

Typed error types for Forge gateway dispatcher traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
#![warn(missing_docs)]
//! Typed error types for Forge gateway dispatcher traits.
//!
//! Provides [`DispatchError`] — the canonical error type for all dispatcher
//! trait methods (`ToolDispatcher`, `ResourceDispatcher`, `StashDispatcher`).

use thiserror::Error;

/// Canonical error type for Forge dispatcher operations.
///
/// All variants are `#[non_exhaustive]` to allow future additions without
/// breaking downstream code.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DispatchError {
    /// The requested server does not exist in the router.
    #[error("server not found: {0}")]
    ServerNotFound(String),

    /// The requested tool does not exist on the specified server.
    #[error("tool not found: '{tool}' on server '{server}'")]
    ToolNotFound {
        /// The server that was queried.
        server: String,
        /// The tool name that was not found.
        tool: String,
    },

    /// The operation timed out.
    #[error("timeout after {timeout_ms}ms on server '{server}'")]
    Timeout {
        /// The server that timed out.
        server: String,
        /// The timeout duration in milliseconds.
        timeout_ms: u64,
    },

    /// The circuit breaker for this server is open.
    #[error("circuit breaker open for server: {0}")]
    CircuitOpen(String),

    /// A group isolation policy denied the operation.
    #[error("group policy denied: {reason}")]
    GroupPolicyDenied {
        /// Explanation of why the policy denied access.
        reason: String,
    },

    /// An upstream MCP server returned an error at the transport or RPC level.
    ///
    /// This indicates a potential server health issue (connection refused,
    /// broken pipe, JSON-RPC protocol error). The server may be down or
    /// malfunctioning.
    #[error("upstream error from '{server}': {message}")]
    Upstream {
        /// The server that returned the error.
        server: String,
        /// The error message from the upstream server.
        message: String,
    },

    /// The transport to the server has died permanently (pipe broken, channel closed).
    /// Unlike Upstream (transient), this requires reconnection before further calls succeed.
    #[error("transport dead for server '{server}': {reason}")]
    TransportDead {
        /// The server whose transport died.
        server: String,
        /// Description of the transport failure.
        reason: String,
    },

    /// A tool returned an application-level error (MCP `isError: true`).
    ///
    /// The downstream server is healthy — the tool processed the request but
    /// returned an error (e.g., bad parameters, missing prerequisite state).
    /// This does NOT indicate a server health issue.
    #[error("tool error on '{server}' calling '{tool}': {message}")]
    ToolError {
        /// The server that hosted the tool.
        server: String,
        /// The tool that returned the error.
        tool: String,
        /// The error message from the tool.
        message: String,
    },

    /// A rate limit was exceeded.
    #[error("rate limit exceeded: {0}")]
    RateLimit(String),

    /// An internal error (catch-all for unexpected failures).
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

impl DispatchError {
    /// Returns a static error code string for programmatic matching.
    pub fn code(&self) -> &'static str {
        match self {
            Self::ServerNotFound(_) => "SERVER_NOT_FOUND",
            Self::ToolNotFound { .. } => "TOOL_NOT_FOUND",
            Self::Timeout { .. } => "TIMEOUT",
            Self::CircuitOpen(_) => "CIRCUIT_OPEN",
            Self::GroupPolicyDenied { .. } => "GROUP_POLICY_DENIED",
            Self::Upstream { .. } => "UPSTREAM_ERROR",
            Self::TransportDead { .. } => "TRANSPORT_DEAD",
            Self::ToolError { .. } => "TOOL_ERROR",
            Self::RateLimit(_) => "RATE_LIMIT",
            Self::Internal(_) => "INTERNAL",
        }
    }

    /// Whether this error indicates the server is unhealthy and should count
    /// toward the circuit breaker failure threshold.
    ///
    /// Returns `true` for errors suggesting the server is down or unresponsive
    /// (`Timeout`, `Upstream` transport/RPC failures, `Internal`).
    /// Returns `false` for errors where the server responded coherently but the
    /// request was invalid (`ToolError`, `ToolNotFound`, etc).
    pub fn trips_circuit_breaker(&self) -> bool {
        match self {
            Self::Timeout { .. } => true,
            Self::Upstream { .. } => true,
            Self::TransportDead { .. } => true,
            Self::Internal(_) => true,
            Self::ToolError { .. } => false,
            Self::ServerNotFound(_) => false,
            Self::ToolNotFound { .. } => false,
            Self::GroupPolicyDenied { .. } => false,
            Self::RateLimit(_) => false,
            Self::CircuitOpen(_) => false,
        }
    }

    /// Returns whether the operation that produced this error may succeed if retried.
    pub fn retryable(&self) -> bool {
        match self {
            Self::Timeout { .. } => true,
            Self::CircuitOpen(_) => true,
            Self::RateLimit(_) => true,
            Self::Upstream { .. } => true,
            Self::TransportDead { .. } => false,
            Self::ToolError { .. } => false,
            Self::ServerNotFound(_) => false,
            Self::ToolNotFound { .. } => false,
            Self::GroupPolicyDenied { .. } => false,
            Self::Internal(_) => false,
        }
    }

    /// Convert to a structured JSON error response for LLM consumption.
    ///
    /// Returns a JSON object with `error`, `code`, `message`, `retryable`,
    /// and optionally `suggested_fix` (populated by fuzzy matching when
    /// `known_tools` is provided for `ToolNotFound` errors).
    ///
    /// # Arguments
    /// * `known_tools` - Optional list of `(server, tool)` pairs for fuzzy matching.
    ///   Only used for `ToolNotFound` errors.
    pub fn to_structured_error(&self, known_tools: Option<&[(&str, &str)]>) -> serde_json::Value {
        let suggested_fix = match self {
            Self::ToolNotFound { server, tool } => {
                if let Some(tools) = known_tools {
                    find_similar_tool(server, tool, tools)
                } else {
                    None
                }
            }
            Self::ServerNotFound(name) => {
                if let Some(tools) = known_tools {
                    find_similar_server(name, tools)
                } else {
                    None
                }
            }
            Self::ToolError { .. } => {
                Some("Check the tool's input_schema for correct parameter names".to_string())
            }
            Self::CircuitOpen(_) => Some("Retry after a delay".to_string()),
            Self::Timeout { .. } => Some("Retry with a simpler operation".to_string()),
            Self::RateLimit(_) => Some("Reduce request frequency".to_string()),
            Self::TransportDead { .. } => Some(
                "Server transport is dead. Gateway may auto-reconnect, or restart the gateway."
                    .to_string(),
            ),
            _ => None,
        };

        let mut obj = serde_json::json!({
            "error": true,
            "code": self.code(),
            "message": self.to_string(),
            "retryable": self.retryable(),
        });

        if let Some(fix) = suggested_fix {
            obj["suggested_fix"] = serde_json::Value::String(fix);
        }

        obj
    }
}

/// Find the closest matching tool name using Levenshtein distance.
///
/// Returns a suggestion string if a tool within edit distance 3 is found.
fn find_similar_tool(server: &str, tool: &str, known_tools: &[(&str, &str)]) -> Option<String> {
    let full_name = format!("{server}.{tool}");
    let mut best: Option<(usize, String)> = None;

    for &(s, t) in known_tools {
        // Try matching the full "server.tool" form
        let candidate_full = format!("{s}.{t}");
        let dist = strsim::levenshtein(&full_name, &candidate_full);
        if dist <= 3 && best.as_ref().is_none_or(|(d, _)| dist < *d) {
            best = Some((dist, format!("Did you mean '{t}' on server '{s}'?")));
        }

        // Also try matching just the tool name on the same server
        if s == server {
            let dist = strsim::levenshtein(tool, t);
            if dist <= 3 && best.as_ref().is_none_or(|(d, _)| dist < *d) {
                best = Some((dist, format!("Did you mean '{t}'?")));
            }
        }
    }

    best.map(|(_, suggestion)| suggestion)
}

/// Find the closest matching server name using Levenshtein distance.
fn find_similar_server(name: &str, known_tools: &[(&str, &str)]) -> Option<String> {
    let mut seen = std::collections::HashSet::new();
    let mut best: Option<(usize, String)> = None;

    for &(s, _) in known_tools {
        if !seen.insert(s) {
            continue;
        }
        let dist = strsim::levenshtein(name, s);
        if dist <= 3 && best.as_ref().is_none_or(|(d, _)| dist < *d) {
            best = Some((dist, format!("Did you mean server '{s}'?")));
        }
    }

    best.map(|(_, suggestion)| suggestion)
}

// Compile-time assertion: DispatchError must be Send + Sync + 'static
const _: fn() = || {
    fn assert_bounds<T: Send + Sync + 'static>() {}
    assert_bounds::<DispatchError>();
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn display_server_not_found() {
        let err = DispatchError::ServerNotFound("myserver".into());
        assert_eq!(err.to_string(), "server not found: myserver");
    }

    #[test]
    fn display_tool_not_found() {
        let err = DispatchError::ToolNotFound {
            server: "srv".into(),
            tool: "hammer".into(),
        };
        assert_eq!(err.to_string(), "tool not found: 'hammer' on server 'srv'");
    }

    #[test]
    fn display_timeout() {
        let err = DispatchError::Timeout {
            server: "slow".into(),
            timeout_ms: 5000,
        };
        assert_eq!(err.to_string(), "timeout after 5000ms on server 'slow'");
    }

    #[test]
    fn display_circuit_open() {
        let err = DispatchError::CircuitOpen("broken".into());
        assert_eq!(err.to_string(), "circuit breaker open for server: broken");
    }

    #[test]
    fn display_group_policy_denied() {
        let err = DispatchError::GroupPolicyDenied {
            reason: "cross-server access denied".into(),
        };
        assert_eq!(
            err.to_string(),
            "group policy denied: cross-server access denied"
        );
    }

    #[test]
    fn display_upstream() {
        let err = DispatchError::Upstream {
            server: "remote".into(),
            message: "connection refused".into(),
        };
        assert_eq!(
            err.to_string(),
            "upstream error from 'remote': connection refused"
        );
    }

    #[test]
    fn display_rate_limit() {
        let err = DispatchError::RateLimit("too many tool calls".into());
        assert_eq!(err.to_string(), "rate limit exceeded: too many tool calls");
    }

    #[test]
    fn display_internal() {
        let err = DispatchError::Internal(anyhow::anyhow!("something broke"));
        assert_eq!(err.to_string(), "something broke");
    }

    #[test]
    fn code_exhaustive() {
        let cases: Vec<(DispatchError, &str)> = vec![
            (
                DispatchError::ServerNotFound("x".into()),
                "SERVER_NOT_FOUND",
            ),
            (
                DispatchError::ToolNotFound {
                    server: "s".into(),
                    tool: "t".into(),
                },
                "TOOL_NOT_FOUND",
            ),
            (
                DispatchError::Timeout {
                    server: "s".into(),
                    timeout_ms: 1000,
                },
                "TIMEOUT",
            ),
            (DispatchError::CircuitOpen("x".into()), "CIRCUIT_OPEN"),
            (
                DispatchError::GroupPolicyDenied { reason: "r".into() },
                "GROUP_POLICY_DENIED",
            ),
            (
                DispatchError::Upstream {
                    server: "s".into(),
                    message: "m".into(),
                },
                "UPSTREAM_ERROR",
            ),
            (
                DispatchError::TransportDead {
                    server: "s".into(),
                    reason: "pipe broken".into(),
                },
                "TRANSPORT_DEAD",
            ),
            (
                DispatchError::ToolError {
                    server: "s".into(),
                    tool: "t".into(),
                    message: "m".into(),
                },
                "TOOL_ERROR",
            ),
            (DispatchError::RateLimit("x".into()), "RATE_LIMIT"),
            (DispatchError::Internal(anyhow::anyhow!("x")), "INTERNAL"),
        ];
        for (err, expected_code) in &cases {
            assert_eq!(err.code(), *expected_code, "wrong code for {err}");
        }
    }

    #[test]
    fn retryable_true_cases() {
        assert!(DispatchError::Timeout {
            server: "s".into(),
            timeout_ms: 1000
        }
        .retryable());
        assert!(DispatchError::CircuitOpen("s".into()).retryable());
        assert!(DispatchError::RateLimit("x".into()).retryable());
        assert!(DispatchError::Upstream {
            server: "s".into(),
            message: "m".into()
        }
        .retryable());
    }

    #[test]
    fn retryable_false_cases() {
        assert!(!DispatchError::ServerNotFound("x".into()).retryable());
        assert!(!DispatchError::ToolNotFound {
            server: "s".into(),
            tool: "t".into()
        }
        .retryable());
        assert!(!DispatchError::ToolError {
            server: "s".into(),
            tool: "t".into(),
            message: "m".into()
        }
        .retryable());
        assert!(!DispatchError::GroupPolicyDenied { reason: "r".into() }.retryable());
        assert!(!DispatchError::Internal(anyhow::anyhow!("x")).retryable());
    }

    // --- trips_circuit_breaker tests ---

    #[test]
    fn trips_cb_true_for_server_faults() {
        assert!(DispatchError::Timeout {
            server: "s".into(),
            timeout_ms: 5000
        }
        .trips_circuit_breaker());
        assert!(DispatchError::Upstream {
            server: "s".into(),
            message: "connection refused".into()
        }
        .trips_circuit_breaker());
        assert!(DispatchError::Internal(anyhow::anyhow!("unexpected")).trips_circuit_breaker());
    }

    #[test]
    fn trips_cb_false_for_tool_error() {
        assert!(!DispatchError::ToolError {
            server: "arbiter".into(),
            tool: "scan".into(),
            message: "Invalid params: missing field 'base_url'".into()
        }
        .trips_circuit_breaker());
    }

    #[test]
    fn trips_cb_false_for_client_errors() {
        assert!(!DispatchError::ServerNotFound("x".into()).trips_circuit_breaker());
        assert!(!DispatchError::ToolNotFound {
            server: "s".into(),
            tool: "t".into()
        }
        .trips_circuit_breaker());
        assert!(!DispatchError::GroupPolicyDenied { reason: "r".into() }.trips_circuit_breaker());
        assert!(!DispatchError::RateLimit("x".into()).trips_circuit_breaker());
        assert!(!DispatchError::CircuitOpen("x".into()).trips_circuit_breaker());
    }

    #[test]
    fn send_sync_static() {
        fn assert_send_sync_static<T: Send + Sync + 'static>() {}
        assert_send_sync_static::<DispatchError>();
    }

    #[test]
    fn from_anyhow_error() {
        let anyhow_err = anyhow::anyhow!("test anyhow");
        let dispatch_err: DispatchError = anyhow_err.into();
        assert!(matches!(dispatch_err, DispatchError::Internal(_)));
        assert_eq!(dispatch_err.code(), "INTERNAL");
    }

    #[test]
    fn internal_is_display_transparent() {
        let inner = anyhow::anyhow!("root cause");
        let err = DispatchError::Internal(inner);
        // #[error(transparent)] means Display delegates to the inner error
        assert_eq!(err.to_string(), "root cause");
    }

    // --- Structured error tests (Phase 5B) ---

    #[test]
    fn structured_error_server_not_found() {
        let err = DispatchError::ServerNotFound("narsil".into());
        let json = err.to_structured_error(None);
        assert_eq!(json["error"], true);
        assert_eq!(json["code"], "SERVER_NOT_FOUND");
        assert_eq!(json["retryable"], false);
        assert!(json["message"].as_str().unwrap().contains("narsil"));
    }

    #[test]
    fn structured_error_tool_not_found_with_suggestion() {
        let err = DispatchError::ToolNotFound {
            server: "narsil".into(),
            tool: "fnd_symbols".into(),
        };
        let tools = vec![
            ("narsil", "find_symbols"),
            ("narsil", "parse"),
            ("github", "list_repos"),
        ];
        let json = err.to_structured_error(Some(&tools));
        assert_eq!(json["code"], "TOOL_NOT_FOUND");
        let fix = json["suggested_fix"].as_str().unwrap();
        assert!(
            fix.contains("find_symbols"),
            "expected suggestion, got: {fix}"
        );
    }

    #[test]
    fn structured_error_tool_not_found_no_match() {
        let err = DispatchError::ToolNotFound {
            server: "narsil".into(),
            tool: "completely_different".into(),
        };
        let tools = vec![("narsil", "find_symbols"), ("narsil", "parse")];
        let json = err.to_structured_error(Some(&tools));
        assert!(json.get("suggested_fix").is_none());
    }

    #[test]
    fn structured_error_server_not_found_with_suggestion() {
        let err = DispatchError::ServerNotFound("narsill".into());
        let tools = vec![("narsil", "find_symbols"), ("github", "list_repos")];
        let json = err.to_structured_error(Some(&tools));
        let fix = json["suggested_fix"].as_str().unwrap();
        assert!(
            fix.contains("narsil"),
            "expected server suggestion, got: {fix}"
        );
    }

    #[test]
    fn structured_error_timeout_has_retry_suggestion() {
        let err = DispatchError::Timeout {
            server: "slow".into(),
            timeout_ms: 5000,
        };
        let json = err.to_structured_error(None);
        assert_eq!(json["retryable"], true);
        assert!(json["suggested_fix"].as_str().is_some());
    }

    #[test]
    fn structured_error_circuit_open_has_retry_suggestion() {
        let err = DispatchError::CircuitOpen("broken".into());
        let json = err.to_structured_error(None);
        assert_eq!(json["retryable"], true);
        assert!(json["suggested_fix"].as_str().unwrap().contains("Retry"));
    }

    #[test]
    fn display_tool_error() {
        let err = DispatchError::ToolError {
            server: "arbiter".into(),
            tool: "scan_target".into(),
            message: "tool returned error: Invalid params: missing field 'base_url'".into(),
        };
        assert_eq!(
            err.to_string(),
            "tool error on 'arbiter' calling 'scan_target': tool returned error: Invalid params: missing field 'base_url'"
        );
    }

    #[test]
    fn structured_error_tool_error_has_schema_suggestion() {
        let err = DispatchError::ToolError {
            server: "arbiter".into(),
            tool: "scan".into(),
            message: "Invalid params: missing field 'base_url'".into(),
        };
        let json = err.to_structured_error(None);
        assert_eq!(json["code"], "TOOL_ERROR");
        assert_eq!(json["retryable"], false);
        let fix = json["suggested_fix"].as_str().unwrap();
        assert!(
            fix.contains("input_schema"),
            "expected schema hint, got: {fix}"
        );
    }

    #[test]
    fn structured_error_internal_no_suggestion() {
        let err = DispatchError::Internal(anyhow::anyhow!("unexpected"));
        let json = err.to_structured_error(None);
        assert_eq!(json["code"], "INTERNAL");
        assert_eq!(json["retryable"], false);
        assert!(json.get("suggested_fix").is_none());
    }

    #[test]
    fn fuzzy_match_close_tool_name() {
        // "fnd" is edit distance 1 from "find"
        let result = super::find_similar_tool(
            "narsil",
            "fnd_symbols",
            &[("narsil", "find_symbols"), ("narsil", "parse")],
        );
        assert!(result.is_some());
        assert!(result.unwrap().contains("find_symbols"));
    }

    #[test]
    fn fuzzy_match_no_match_beyond_threshold() {
        let result = super::find_similar_tool(
            "narsil",
            "zzzzz",
            &[("narsil", "find_symbols"), ("narsil", "parse")],
        );
        assert!(result.is_none());
    }

    #[test]
    fn fuzzy_match_server_name() {
        let result = super::find_similar_server(
            "narsill",
            &[("narsil", "find_symbols"), ("github", "list_repos")],
        );
        assert!(result.is_some());
        assert!(result.unwrap().contains("narsil"));
    }

    // --- TransportDead tests ---

    #[test]
    fn display_transport_dead() {
        let err = DispatchError::TransportDead {
            server: "arbiter".into(),
            reason: "channel closed".into(),
        };
        assert_eq!(
            err.to_string(),
            "transport dead for server 'arbiter': channel closed"
        );
    }

    #[test]
    fn transport_dead_code() {
        let err = DispatchError::TransportDead {
            server: "s".into(),
            reason: "r".into(),
        };
        assert_eq!(err.code(), "TRANSPORT_DEAD");
    }

    #[test]
    fn transport_dead_trips_circuit_breaker() {
        assert!(DispatchError::TransportDead {
            server: "s".into(),
            reason: "pipe broken".into(),
        }
        .trips_circuit_breaker());
    }

    #[test]
    fn transport_dead_not_retryable() {
        assert!(!DispatchError::TransportDead {
            server: "s".into(),
            reason: "pipe broken".into(),
        }
        .retryable());
    }

    #[test]
    fn structured_error_transport_dead() {
        let err = DispatchError::TransportDead {
            server: "arbiter".into(),
            reason: "channel closed".into(),
        };
        let json = err.to_structured_error(None);
        assert_eq!(json["code"], "TRANSPORT_DEAD");
        assert_eq!(json["retryable"], false);
        let fix = json["suggested_fix"].as_str().unwrap();
        assert!(
            fix.contains("transport is dead"),
            "expected transport dead suggestion, got: {fix}"
        );
    }
}