everruns-core 0.9.0

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
// MCP Server domain types
//
// Spec: specs/mcp.md (umbrella), specs/mcp-servers.md (detail)
//
// These types represent the MCP (Model Context Protocol) server configuration.
// Used by both API and worker crates.
//
// Currently supports only HTTP (Streamable HTTP) transport.
// MCP tool types follow the MCP specification for tool discovery and execution.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};

use crate::typed_id::McpServerId;

#[cfg(feature = "openapi")]
use utoipa::ToSchema;

/// MCP Server transport type.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(example = "http"))]
#[serde(rename_all = "lowercase")]
pub enum McpServerTransportType {
    /// HTTP (Streamable HTTP) transport.
    Http,
    /// Local-process transport over stdio. Only usable by single-tenant
    /// runtime/CLI hosts (e.g. the example coding CLI); the hosted product
    /// rejects it during scoped-config validation (see specs/runtime-mcp.md).
    Stdio,
}

impl McpServerTransportType {
    /// Whether this transport spawns/contacts a local process rather than a
    /// remote endpoint.
    pub fn is_local(&self) -> bool {
        matches!(self, McpServerTransportType::Stdio)
    }
}

/// MCP server authentication mode.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(example = "api_key"))]
#[serde(rename_all = "snake_case")]
pub enum McpServerAuthMode {
    /// No authentication required.
    #[default]
    None,
    /// Organization-scoped API key stored on the MCP server config.
    ApiKey,
    /// User-scoped OAuth token resolved at runtime.
    OAuth,
}

impl std::fmt::Display for McpServerAuthMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            McpServerAuthMode::None => write!(f, "none"),
            McpServerAuthMode::ApiKey => write!(f, "api_key"),
            McpServerAuthMode::OAuth => write!(f, "oauth"),
        }
    }
}

impl From<&str> for McpServerAuthMode {
    fn from(s: &str) -> Self {
        match s {
            "api_key" => McpServerAuthMode::ApiKey,
            "oauth" => McpServerAuthMode::OAuth,
            _ => McpServerAuthMode::None,
        }
    }
}

impl McpServerAuthMode {
    pub fn is_none(&self) -> bool {
        matches!(self, McpServerAuthMode::None)
    }
}

impl std::fmt::Display for McpServerTransportType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            McpServerTransportType::Http => write!(f, "http"),
            McpServerTransportType::Stdio => write!(f, "stdio"),
        }
    }
}

impl From<&str> for McpServerTransportType {
    fn from(s: &str) -> Self {
        match s {
            "stdio" => McpServerTransportType::Stdio,
            // Default to HTTP for "http" and any unknown value.
            _ => McpServerTransportType::Http,
        }
    }
}

/// MCP Server lifecycle status.
/// - `active`: Server is available for use
/// - `disabled`: Server is disabled and not used
/// - `archived`: Server is hidden from listings and cannot be modified or assigned
/// - `deleted`: Server is a tombstone kept only for historical references
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(example = "active"))]
#[serde(rename_all = "lowercase")]
pub enum McpServerStatus {
    /// Server is available for use.
    Active,
    /// Server is disabled and not used.
    Disabled,
    /// Server is hidden from listings and cannot be modified or assigned.
    Archived,
    /// Server is deleted and should only survive as a tombstone for references.
    Deleted,
}

impl std::fmt::Display for McpServerStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            McpServerStatus::Active => write!(f, "active"),
            McpServerStatus::Disabled => write!(f, "disabled"),
            McpServerStatus::Archived => write!(f, "archived"),
            McpServerStatus::Deleted => write!(f, "deleted"),
        }
    }
}

impl From<&str> for McpServerStatus {
    fn from(s: &str) -> Self {
        match s {
            "disabled" => McpServerStatus::Disabled,
            "archived" => McpServerStatus::Archived,
            "deleted" => McpServerStatus::Deleted,
            _ => McpServerStatus::Active,
        }
    }
}

/// MCP Server configuration.
/// Represents a remote MCP server that can provide tools and resources.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct McpServer {
    /// Unique identifier for the MCP server.
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "mcp_01933b5a00007000800000000000001"))]
    pub id: McpServerId,
    /// Display name of the MCP server.
    #[cfg_attr(feature = "openapi", schema(example = "atlassian-mcp-server"))]
    pub name: String,
    /// Human-readable description of the MCP server.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "openapi",
        schema(example = "Atlassian MCP Server for Jira and Confluence")
    )]
    pub description: Option<String>,
    /// URL of the MCP server endpoint.
    #[cfg_attr(
        feature = "openapi",
        schema(example = "https://mcp.atlassian.com/v1/mcp")
    )]
    pub url: String,
    /// Transport type (currently only HTTP supported).
    pub transport_type: McpServerTransportType,
    /// Current lifecycle status of the MCP server.
    pub status: McpServerStatus,
    /// Authentication mode for this MCP server.
    #[serde(default)]
    pub auth_mode: McpServerAuthMode,
    /// Stable provider id used for user-scoped OAuth connections.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oauth_provider_id: Option<String>,
    /// Whether an API key has been configured.
    pub api_key_set: bool,
    /// Additional HTTP headers for authentication.
    /// Keys are header names, values are header values.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
    /// Timestamp when the MCP server was created.
    pub created_at: DateTime<Utc>,
    /// Timestamp when the MCP server was last updated.
    pub updated_at: DateTime<Utc>,
    /// Timestamp when the MCP server was archived.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archived_at: Option<DateTime<Utc>>,
    /// Timestamp when the MCP server was deleted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted_at: Option<DateTime<Utc>>,
}

/// Session-, agent-, or harness-scoped remote MCP server configuration.
///
/// This intentionally mirrors the `mcpServers` object shape used by common MCP
/// client config files while staying within Everruns' current remote-HTTP-only
/// support.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ScopedMcpServer {
    /// MCP transport type. Only remote HTTP is supported today.
    #[serde(
        default = "default_scoped_transport_type",
        rename = "type",
        alias = "transport_type"
    )]
    pub transport_type: McpServerTransportType,
    /// URL of the remote MCP server endpoint. Required for HTTP transport;
    /// empty/ignored for stdio.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub url: String,
    /// Additional HTTP headers sent on MCP requests (HTTP transport only).
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
    /// Executable to spawn for a stdio transport server.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// Arguments passed to the stdio `command`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,
    /// Environment variables set for the stdio `command`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub env: HashMap<String, String>,
    /// Authentication mode used when executing tools from this scoped server.
    #[serde(default, skip_serializing_if = "McpServerAuthMode::is_none")]
    pub auth_mode: McpServerAuthMode,
    /// Provider id used to resolve a user-scoped bearer token.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oauth_provider_id: Option<String>,
    /// Whether to discover tool definitions live from this server.
    #[serde(
        default = "default_scoped_tool_discovery",
        skip_serializing_if = "is_true"
    )]
    pub tool_discovery: bool,
}

impl Default for ScopedMcpServer {
    fn default() -> Self {
        Self {
            transport_type: McpServerTransportType::Http,
            url: String::new(),
            headers: HashMap::new(),
            auth_mode: McpServerAuthMode::None,
            oauth_provider_id: None,
            tool_discovery: true,
            command: None,
            args: Vec::new(),
            env: HashMap::new(),
        }
    }
}

pub type ScopedMcpServers = BTreeMap<String, ScopedMcpServer>;

fn default_scoped_transport_type() -> McpServerTransportType {
    McpServerTransportType::Http
}

fn default_scoped_tool_discovery() -> bool {
    true
}

fn is_true(value: &bool) -> bool {
    *value
}

pub fn scoped_mcp_servers_is_empty(servers: &ScopedMcpServers) -> bool {
    servers.is_empty()
}

/// Merge scoped MCP servers by logical server name. Later layers override earlier ones.
pub fn merge_scoped_mcp_servers(
    base: &ScopedMcpServers,
    overlay: &ScopedMcpServers,
) -> ScopedMcpServers {
    let mut merged = base.clone();
    merged.extend(overlay.clone());
    merged
}

// ============================================================================
// MCP Tool Types (following MCP specification)
// ============================================================================

/// MCP Tool definition as returned by tools/list.
/// Follows the MCP specification for tool discovery.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct McpToolDefinition {
    /// Unique name of the tool within the MCP server.
    pub name: String,
    /// Human-readable description of what the tool does.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// JSON Schema describing the tool's input parameters.
    #[serde(rename = "inputSchema")]
    pub input_schema: Value,
    /// MCP tool annotations (behavioral hints).
    /// See: <https://spec.modelcontextprotocol.io>
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub annotations: Option<McpToolAnnotations>,
}

/// MCP tool annotations as defined by the MCP specification.
/// All fields are optional booleans following the MCP convention.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct McpToolAnnotations {
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "readOnlyHint"
    )]
    pub read_only_hint: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "destructiveHint"
    )]
    pub destructive_hint: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "idempotentHint"
    )]
    pub idempotent_hint: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "openWorldHint"
    )]
    pub open_world_hint: Option<bool>,
}

/// Request for MCP tools/list endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolsListRequest {
    pub jsonrpc: String,
    pub id: i64,
    pub method: String,
}

impl Default for McpToolsListRequest {
    fn default() -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id: 1,
            method: "tools/list".to_string(),
        }
    }
}

/// Response from MCP tools/list endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolsListResponse {
    pub jsonrpc: String,
    pub id: i64,
    #[serde(default)]
    pub result: Option<McpToolsListResult>,
    #[serde(default)]
    pub error: Option<McpError>,
}

/// Result of tools/list containing the list of tools.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolsListResult {
    pub tools: Vec<McpToolDefinition>,
    #[serde(rename = "nextCursor", skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// MCP error response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpError {
    pub code: i64,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

/// Request for MCP tools/call endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolCallRequest {
    pub jsonrpc: String,
    pub id: i64,
    pub method: String,
    pub params: McpToolCallParams,
}

/// Parameters for tools/call request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolCallParams {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub arguments: Option<Value>,
}

impl McpToolCallRequest {
    pub fn new(id: i64, name: String, arguments: Option<Value>) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id,
            method: "tools/call".to_string(),
            params: McpToolCallParams { name, arguments },
        }
    }
}

/// Response from MCP tools/call endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolCallResponse {
    pub jsonrpc: String,
    pub id: i64,
    #[serde(default)]
    pub result: Option<McpToolCallResult>,
    #[serde(default)]
    pub error: Option<McpError>,
}

/// Result of tools/call containing content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolCallResult {
    pub content: Vec<McpContent>,
    #[serde(rename = "isError", default)]
    pub is_error: bool,
}

/// MCP content type (text, image, etc.).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum McpContent {
    #[serde(rename = "text")]
    Text { text: String },
    #[serde(rename = "image")]
    Image { data: String, mime_type: String },
    #[serde(rename = "resource")]
    Resource {
        uri: String,
        mime_type: Option<String>,
        text: Option<String>,
    },
}

/// Helper to generate prefixed tool name for MCP tools.
/// Format: mcp_{server_name}__{tool_name} (double underscore separator)
/// The double underscore allows unambiguous parsing when server names contain underscores.
pub fn mcp_tool_name(server_name: &str, tool_name: &str) -> String {
    format!(
        "mcp_{}__{}",
        sanitize_mcp_server_name(server_name),
        tool_name
    )
}

/// Sanitize an MCP server name into a stable tool-name prefix.
pub fn sanitize_mcp_server_name(server_name: &str) -> String {
    server_name
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '_' })
        .collect::<String>()
}

/// Check if a tool name is an MCP tool (starts with "mcp_").
pub fn is_mcp_tool(tool_name: &str) -> bool {
    tool_name.starts_with("mcp_")
}

/// Parse MCP tool name to extract server name prefix and original tool name.
/// Returns (server_name_prefix, original_tool_name) if valid MCP tool.
/// Expected format: mcp_{server_name}__{tool_name} (double underscore separator)
pub fn parse_mcp_tool_name(tool_name: &str) -> Option<(String, String)> {
    if !tool_name.starts_with("mcp_") {
        return None;
    }
    let rest = &tool_name[4..]; // Skip "mcp_"
    // Find the double underscore separator between server name and tool name
    if let Some(pos) = rest.find("__") {
        let server_prefix = rest[..pos].to_string();
        let original_name = rest[pos + 2..].to_string(); // Skip "__"
        if !server_prefix.is_empty() && !original_name.is_empty() {
            return Some((server_prefix, original_name));
        }
    }
    None
}

/// Stable connection-provider id for an OAuth-enabled MCP server.
pub fn mcp_oauth_provider_id_for_uuid(server_id: uuid::Uuid) -> String {
    format!("mcp_oauth_{}", server_id)
}

/// Secret name for a session-scoped MCP OAuth token field.
pub fn mcp_oauth_session_secret_name(server_id: uuid::Uuid, field: &str) -> String {
    format!("mcp_oauth:{}:{}", server_id, field)
}

// ============================================================================
// Structured execute errors (EVE-492)
// ============================================================================

/// Closed vocabulary of error codes for Everruns' own MCP `tools/call`
/// execute path. Surfaces in [`McpExecuteError::code`] so LLM toolcallers
/// can branch on a machine-readable value instead of regexing prose.
///
/// New variants are a spec change. SDKs should treat any value they don't
/// recognise as `unknown` (forward-compat) — serde's `#[serde(other)]`
/// catch-all enables that on the deserialize side.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum McpErrorCode {
    /// Tool name doesn't match any registered tool.
    ToolNotFound,
    /// Tool timed out (server-imposed budget exceeded).
    ToolTimeout,
    /// Tool panicked or hit an unrecoverable internal error.
    ToolPanicked,
    /// Required argument missing or argument failed validation.
    InvalidArguments,
    /// Caller is authenticated but not authorized for the requested action
    /// or org scope.
    PermissionDenied,
    /// Org/user quota or rate limit hit.
    QuotaExceeded,
    /// Outbound network call blocked by egress policy.
    NetworkBlocked,
    /// Upstream MCP server unreachable or returned an error we couldn't
    /// classify.
    McpServerUnreachable,
    /// Catch-all for unclassified internal failures. Treat as transient
    /// only if `retryable` is also true.
    Internal,
    /// Forward-compat sentinel — SDKs see this when the server returns a
    /// code they don't know yet.
    #[serde(other)]
    Unknown,
}

impl McpErrorCode {
    /// Stable wire string for this variant. Mirrors what `serde` emits so
    /// non-Rust SDKs and tests can match on the same value.
    pub fn as_str(&self) -> &'static str {
        match self {
            McpErrorCode::ToolNotFound => "tool_not_found",
            McpErrorCode::ToolTimeout => "tool_timeout",
            McpErrorCode::ToolPanicked => "tool_panicked",
            McpErrorCode::InvalidArguments => "invalid_arguments",
            McpErrorCode::PermissionDenied => "permission_denied",
            McpErrorCode::QuotaExceeded => "quota_exceeded",
            McpErrorCode::NetworkBlocked => "network_blocked",
            McpErrorCode::McpServerUnreachable => "mcp_server_unreachable",
            McpErrorCode::Internal => "internal",
            McpErrorCode::Unknown => "unknown",
        }
    }

    /// Default category for this code. Callers may override per-occurrence
    /// when context narrows the classification (e.g. an `Internal` with a
    /// known-transient root cause).
    pub fn default_category(&self) -> McpErrorCategory {
        match self {
            McpErrorCode::ToolTimeout
            | McpErrorCode::McpServerUnreachable
            | McpErrorCode::QuotaExceeded => McpErrorCategory::Transient,
            McpErrorCode::InvalidArguments => McpErrorCategory::Validation,
            McpErrorCode::PermissionDenied => McpErrorCategory::Auth,
            McpErrorCode::ToolNotFound
            | McpErrorCode::ToolPanicked
            | McpErrorCode::NetworkBlocked => McpErrorCategory::Permanent,
            McpErrorCode::Internal | McpErrorCode::Unknown => McpErrorCategory::Permanent,
        }
    }

    /// Default retryability for this code. Same override caveat as
    /// `default_category`.
    pub fn default_retryable(&self) -> bool {
        matches!(
            self,
            McpErrorCode::ToolTimeout
                | McpErrorCode::McpServerUnreachable
                | McpErrorCode::QuotaExceeded
        )
    }
}

/// Broad-strokes routing hint sitting alongside the precise [`McpErrorCode`].
/// The categories are stable enough that an LLM can pick a recovery
/// strategy from this field alone (e.g. retry transients with backoff,
/// surface validation errors to the user, escalate auth failures).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum McpErrorCategory {
    /// Worth retrying — same call, possibly after `retry_after_seconds`.
    Transient,
    /// Repeating the same call will fail the same way.
    Permanent,
    /// Caller-side problem (bad arguments, schema mismatch).
    Validation,
    /// Authentication/authorization issue.
    Auth,
    /// Forward-compat sentinel.
    #[serde(other)]
    Unknown,
}

/// Typed structured-error envelope returned by Everruns' MCP `tools/call`
/// execute path. Serialized into the MCP `structuredContent` field on
/// error responses so the legacy `content[0].text` channel stays
/// backward-compatible; new SDKs prefer the typed envelope.
///
/// See `specs/mcp.md` for the error contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct McpExecuteError {
    /// Machine-readable error code. Closed vocabulary; SDKs that see an
    /// unrecognised value should map it to `unknown`.
    pub code: McpErrorCode,
    /// Human-readable error message. Mirrors the legacy
    /// `content[0].text` string for backward compat.
    pub message: String,
    /// Broad-strokes recovery category.
    pub category: McpErrorCategory,
    /// `true` when the same call is worth retrying. Distinct from
    /// `category == "transient"` because a server may know about a
    /// non-transient retry path (e.g. a transient `Internal`).
    pub retryable: bool,
    /// Seconds the caller should wait before retrying. Set on
    /// `tool_timeout`, `quota_exceeded`, and upstream-unreachable cases
    /// when the server has a concrete back-off hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after_seconds: Option<u32>,
    /// Short, agent-readable recovery hint. Free-form; one or two sentences.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
    /// Chain of upstream error messages, oldest cause first. Useful for
    /// debugging; SDKs should not treat this as machine-readable.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cause_chain: Vec<String>,
}

impl McpExecuteError {
    /// Construct an error using the code's default category and
    /// retryability. Callers can chain `.with_*` to override.
    pub fn new(code: McpErrorCode, message: impl Into<String>) -> Self {
        Self {
            category: code.default_category(),
            retryable: code.default_retryable(),
            code,
            message: message.into(),
            retry_after_seconds: None,
            hint: None,
            cause_chain: Vec::new(),
        }
    }

    pub fn with_category(mut self, category: McpErrorCategory) -> Self {
        self.category = category;
        self
    }

    pub fn with_retryable(mut self, retryable: bool) -> Self {
        self.retryable = retryable;
        self
    }

    pub fn with_retry_after_seconds(mut self, seconds: u32) -> Self {
        self.retry_after_seconds = Some(seconds);
        self
    }

    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    pub fn with_cause(mut self, cause: impl Into<String>) -> Self {
        self.cause_chain.push(cause.into());
        self
    }
}

/// Classify a free-form error string raised by an internal MCP tool
/// implementation into a structured envelope. The implementations
/// currently return `Result<String, String>`; this is the boundary
/// where we recover the structure from prose. Pattern matches are
/// intentionally narrow (substrings, not regexes) so the classifier
/// fails open to `Internal` rather than mis-categorising.
///
/// **Convention for new error messages**: prefer constructing the
/// `McpExecuteError` directly (via a future `McpExecuteError`-typed
/// `Result`) instead of relying on this classifier. The classifier
/// exists to give the legacy `String` error path structure without
/// rewriting every tool first.
pub fn classify_mcp_execute_error(message: &str) -> McpExecuteError {
    let lower = message.to_ascii_lowercase();
    // Catalog-backed query/execute tools format their dispatch errors as
    // `<kind>: <message>` (see `crates/server/src/api/mcp_endpoint/catalog.rs::format_dispatch_error`
    // and the public contract in `specs/domains.md`). Map those prefixes
    // first so the most common real-world MCP failures get a precise code
    // rather than landing in the `Internal` catch-all.
    let code = if lower.starts_with("bad_request:") || lower.starts_with("unprocessable:") {
        McpErrorCode::InvalidArguments
    } else if lower.starts_with("not_found:") {
        McpErrorCode::ToolNotFound
    } else if lower.starts_with("conflict:") {
        // No dedicated `conflict` code today; surface as a validation
        // failure since the caller's input is the proximate cause and
        // a retry without changes won't succeed.
        McpErrorCode::InvalidArguments
    } else if lower.starts_with("forbidden:") {
        McpErrorCode::PermissionDenied
    } else if lower.starts_with("internal:") {
        McpErrorCode::Internal
    // Order matters: more specific patterns first.
    } else if lower.contains("timed out") || lower.contains("timeout") {
        McpErrorCode::ToolTimeout
    } else if lower.starts_with("unknown tool") {
        McpErrorCode::ToolNotFound
    } else if lower.starts_with("missing required parameter") || lower.contains("invalid argument")
    {
        McpErrorCode::InvalidArguments
    } else if lower.contains("permission denied")
        || lower.contains("forbidden")
        || lower.contains("not authorized")
        || lower.contains("unauthorized")
    {
        McpErrorCode::PermissionDenied
    } else if lower.contains("quota") || lower.contains("rate limit") {
        McpErrorCode::QuotaExceeded
    } else if lower.contains("network blocked") || lower.contains("egress") {
        McpErrorCode::NetworkBlocked
    } else if lower.contains("mcp server") && lower.contains("unreachable") {
        McpErrorCode::McpServerUnreachable
    } else if lower.contains("panicked") {
        McpErrorCode::ToolPanicked
    } else {
        McpErrorCode::Internal
    };
    McpExecuteError::new(code, message)
}

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

    #[test]
    fn test_mcp_tool_name_simple() {
        // Simple server name without special characters
        assert_eq!(mcp_tool_name("github", "search"), "mcp_github__search");
    }

    #[test]
    fn test_mcp_tool_name_with_underscores() {
        // Server name with underscores (e.g., microsoft_learn)
        assert_eq!(
            mcp_tool_name("microsoft_learn", "docs_search"),
            "mcp_microsoft_learn__docs_search"
        );
    }

    #[test]
    fn test_mcp_tool_name_with_dashes() {
        // Server name with dashes gets converted to underscores
        assert_eq!(
            mcp_tool_name("microsoft-learn", "search"),
            "mcp_microsoft_learn__search"
        );
    }

    #[test]
    fn test_mcp_tool_name_uppercase() {
        // Server name is lowercased
        assert_eq!(mcp_tool_name("GitHub", "search"), "mcp_github__search");
    }

    #[test]
    fn test_mcp_tool_name_special_chars() {
        // Special characters are replaced with underscores
        assert_eq!(
            mcp_tool_name("my.server.name", "tool"),
            "mcp_my_server_name__tool"
        );
    }

    #[test]
    fn test_is_mcp_tool() {
        assert!(is_mcp_tool("mcp_github__search"));
        assert!(is_mcp_tool("mcp_microsoft_learn__docs_search"));
        assert!(!is_mcp_tool("get_weather"));
        assert!(!is_mcp_tool("mcpsearch")); // Must have underscore after mcp
    }

    #[test]
    fn test_parse_mcp_tool_name_simple() {
        let result = parse_mcp_tool_name("mcp_github__search");
        assert_eq!(result, Some(("github".to_string(), "search".to_string())));
    }

    #[test]
    fn test_parse_mcp_tool_name_with_underscores() {
        // Server name with underscores should be parsed correctly
        let result = parse_mcp_tool_name("mcp_microsoft_learn__docs_search");
        assert_eq!(
            result,
            Some(("microsoft_learn".to_string(), "docs_search".to_string()))
        );
    }

    #[test]
    fn test_parse_mcp_tool_name_complex() {
        // Multiple underscores in both server name and tool name
        let result = parse_mcp_tool_name("mcp_my_long_server_name__my_complex_tool");
        assert_eq!(
            result,
            Some((
                "my_long_server_name".to_string(),
                "my_complex_tool".to_string()
            ))
        );
    }

    #[test]
    fn test_parse_mcp_tool_name_invalid_prefix() {
        // Not an MCP tool
        assert_eq!(parse_mcp_tool_name("get_weather"), None);
    }

    #[test]
    fn test_parse_mcp_tool_name_no_separator() {
        // Missing double underscore separator
        assert_eq!(parse_mcp_tool_name("mcp_github_search"), None);
    }

    #[test]
    fn test_parse_mcp_tool_name_empty_parts() {
        // Empty server name or tool name
        assert_eq!(parse_mcp_tool_name("mcp___search"), None);
        assert_eq!(parse_mcp_tool_name("mcp_github__"), None);
    }

    #[test]
    fn test_roundtrip() {
        // Generate and parse should roundtrip
        let server = "microsoft_learn";
        let tool = "docs_search";
        let full_name = mcp_tool_name(server, tool);
        let parsed = parse_mcp_tool_name(&full_name);
        assert_eq!(
            parsed,
            Some(("microsoft_learn".to_string(), "docs_search".to_string()))
        );
    }

    // ------------------------------------------------------------------
    // McpExecuteError / McpErrorCode (EVE-492)
    // ------------------------------------------------------------------

    #[test]
    fn mcp_error_code_serializes_to_snake_case_wire_string() {
        assert_eq!(
            serde_json::to_string(&McpErrorCode::ToolTimeout).unwrap(),
            "\"tool_timeout\""
        );
        assert_eq!(
            serde_json::to_string(&McpErrorCode::McpServerUnreachable).unwrap(),
            "\"mcp_server_unreachable\""
        );
    }

    #[test]
    fn mcp_error_code_as_str_matches_serde_wire() {
        for code in [
            McpErrorCode::ToolNotFound,
            McpErrorCode::ToolTimeout,
            McpErrorCode::ToolPanicked,
            McpErrorCode::InvalidArguments,
            McpErrorCode::PermissionDenied,
            McpErrorCode::QuotaExceeded,
            McpErrorCode::NetworkBlocked,
            McpErrorCode::McpServerUnreachable,
            McpErrorCode::Internal,
            McpErrorCode::Unknown,
        ] {
            let wire = serde_json::to_string(&code).unwrap();
            assert_eq!(
                wire,
                format!("\"{}\"", code.as_str()),
                "as_str() must match serde wire for {code:?}"
            );
        }
    }

    #[test]
    fn mcp_error_code_unknown_variant_is_forward_compat_sentinel() {
        // SDKs that receive a code they don't recognise should land on
        // `Unknown`, not fail to deserialise.
        let code: McpErrorCode = serde_json::from_str("\"future_code_we_dont_know_yet\"").unwrap();
        assert_eq!(code, McpErrorCode::Unknown);
    }

    #[test]
    fn classify_recognises_timeout_substrings() {
        let err = classify_mcp_execute_error("Tool timed out after 30000ms");
        assert_eq!(err.code, McpErrorCode::ToolTimeout);
        assert_eq!(err.category, McpErrorCategory::Transient);
        assert!(err.retryable);

        let err = classify_mcp_execute_error("Command timed out after 5000ms");
        assert_eq!(err.code, McpErrorCode::ToolTimeout);
    }

    #[test]
    fn classify_recognises_tool_not_found() {
        let err = classify_mcp_execute_error("Unknown tool: github.foo");
        assert_eq!(err.code, McpErrorCode::ToolNotFound);
        assert_eq!(err.category, McpErrorCategory::Permanent);
        assert!(!err.retryable);
    }

    #[test]
    fn classify_recognises_invalid_arguments() {
        let err = classify_mcp_execute_error("Missing required parameter: query");
        assert_eq!(err.code, McpErrorCode::InvalidArguments);
        assert_eq!(err.category, McpErrorCategory::Validation);
        assert!(!err.retryable);
    }

    #[test]
    fn classify_recognises_permission_denied() {
        for msg in [
            "permission denied for org",
            "Forbidden: org scope not allowed",
            "not authorized to call this tool",
            "Unauthorized request",
        ] {
            let err = classify_mcp_execute_error(msg);
            assert_eq!(
                err.code,
                McpErrorCode::PermissionDenied,
                "expected PermissionDenied for {msg:?}"
            );
            assert_eq!(err.category, McpErrorCategory::Auth);
        }
    }

    #[test]
    fn classify_recognises_quota_and_rate_limit() {
        let err = classify_mcp_execute_error("Quota exceeded for org");
        assert_eq!(err.code, McpErrorCode::QuotaExceeded);
        assert!(err.retryable);

        let err = classify_mcp_execute_error("Rate limit hit");
        assert_eq!(err.code, McpErrorCode::QuotaExceeded);
    }

    #[test]
    fn classify_recognises_catalog_dispatch_prefixes() {
        // `crates/server/src/api/mcp_endpoint/catalog.rs::format_dispatch_error`
        // emits `<kind>: <message>` for inventory-backed query/execute
        // tools. These are the public MCP contract per specs/domains.md,
        // so the classifier must route them to precise codes rather than
        // the catch-all `Internal` bucket.
        for (prefix, expected) in [
            (
                "bad_request: name must be <=200 chars",
                McpErrorCode::InvalidArguments,
            ),
            (
                "unprocessable: cycle detected in capability graph",
                McpErrorCode::InvalidArguments,
            ),
            (
                "conflict: session is already paused",
                McpErrorCode::InvalidArguments,
            ),
            (
                "not_found: agent agent_xyz not in this org",
                McpErrorCode::ToolNotFound,
            ),
            (
                "forbidden: principal lacks SESSION_WRITE",
                McpErrorCode::PermissionDenied,
            ),
            (
                "internal: storage backend returned 503",
                McpErrorCode::Internal,
            ),
        ] {
            let err = classify_mcp_execute_error(prefix);
            assert_eq!(err.code, expected, "expected {expected:?} for {prefix:?}");
        }
    }

    #[test]
    fn classify_falls_open_to_internal() {
        // No known pattern → Internal, not a wrong guess. Retryable
        // defaults to false so callers don't burn retries on unknown
        // permanent failures.
        let err = classify_mcp_execute_error("strange unanticipated message");
        assert_eq!(err.code, McpErrorCode::Internal);
        assert_eq!(err.category, McpErrorCategory::Permanent);
        assert!(!err.retryable);
    }

    #[test]
    fn mcp_execute_error_skips_empty_optional_fields() {
        let err = McpExecuteError::new(McpErrorCode::ToolNotFound, "no such tool");
        let value = serde_json::to_value(&err).unwrap();
        // Required fields present.
        assert_eq!(value["code"], "tool_not_found");
        assert_eq!(value["message"], "no such tool");
        assert_eq!(value["category"], "permanent");
        assert_eq!(value["retryable"], false);
        // Optional fields omitted entirely from the wire when empty.
        assert!(value.get("retry_after_seconds").is_none());
        assert!(value.get("hint").is_none());
        assert!(value.get("cause_chain").is_none());
    }

    #[test]
    fn mcp_execute_error_builders_chain() {
        let err = McpExecuteError::new(McpErrorCode::ToolTimeout, "tool timed out after 30000ms")
            .with_retry_after_seconds(10)
            .with_hint("Reduce input size before retrying.")
            .with_cause("downstream: upstream gateway timeout");
        let value = serde_json::to_value(&err).unwrap();
        assert_eq!(value["code"], "tool_timeout");
        assert_eq!(value["retry_after_seconds"], 10);
        assert_eq!(value["hint"], "Reduce input size before retrying.");
        assert_eq!(
            value["cause_chain"][0],
            "downstream: upstream gateway timeout"
        );
    }
}