Skip to main content

surjection_core/adapters/
caps.rs

1//! Client capabilities (SPEC 7.1 `Caps`, table 7.4): what a client can
2//! express natively. The planner and the delivery renderer read these;
3//! mappers enforce the ones that shape an entry.
4
5use std::time::Duration;
6
7use crate::formats::NativeValue;
8use crate::model::server::Transport;
9
10/// The transports a client can run.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct TransportSet {
13    pub stdio: bool,
14    pub http: bool,
15    pub sse: bool,
16}
17
18impl TransportSet {
19    pub const STDIO: Self = Self {
20        stdio: true,
21        http: false,
22        sse: false,
23    };
24    pub const STDIO_HTTP: Self = Self {
25        stdio: true,
26        http: true,
27        sse: false,
28    };
29    pub const ALL: Self = Self {
30        stdio: true,
31        http: true,
32        sse: true,
33    };
34
35    pub const fn contains(self, transport: Transport) -> bool {
36        match transport {
37            Transport::Stdio => self.stdio,
38            Transport::Http => self.http,
39            Transport::Sse => self.sse,
40        }
41    }
42}
43
44/// How a client spells an environment variable reference it expands itself.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum EnvRefSyntax {
47    /// `${NAME}`; `default` when `${NAME:-default}` is understood too;
48    /// `bare` when a bare `$NAME` is expanded as well, with no escape
49    /// (Gemini, Qwen Code; `[verify]` GEM-6), so literal text holding `$`
50    /// before a name character cannot be written for the client.
51    DollarBrace { default: bool, bare: bool },
52    /// `${NAME}` and bare `$NAME`, no default; `$$` is a literal `$` and
53    /// `$!` a literal `!`, so literal text is written with every `$`
54    /// doubled and a leading `!` as `$!` (Pi; gate V2 PI-7).
55    Dollar,
56    /// `${env:NAME}` (Cursor, Windsurf, Devin).
57    DollarBraceEnv,
58    /// `{env:NAME}` (OpenCode, MiMo Code). The client also substitutes
59    /// `{file:path}`, so literal text holding `{env:` or `{file:` cannot
60    /// be written for it; a literal `${` is left alone.
61    BraceEnv,
62    /// No expansion; a parent variable is forwarded by name (Codex
63    /// `env_vars`, `bearer_token_env_var`, `env_http_headers`).
64    CodexForward,
65}
66
67/// A set of server fields (which fields a client expands references in).
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub struct FieldSet(u8);
70
71impl FieldSet {
72    pub const NONE: Self = Self(0);
73    pub const COMMAND: Self = Self(1);
74    pub const ARGS: Self = Self(1 << 1);
75    pub const ENV: Self = Self(1 << 2);
76    pub const CWD: Self = Self(1 << 3);
77    pub const URL: Self = Self(1 << 4);
78    pub const HEADERS: Self = Self(1 << 5);
79
80    pub const fn union(self, other: Self) -> Self {
81        Self(self.0 | other.0)
82    }
83
84    pub const fn contains(self, other: Self) -> bool {
85        self.0 & other.0 == other.0
86    }
87}
88
89/// A native way to get a value by running a command at connect time.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum CommandRef {
92    /// A whole value of `!command` in env or headers (Pi, omp).
93    Bang,
94    /// An entry-level `headersHelper` command printing a JSON object of
95    /// headers (Claude Code, http and sse).
96    HeadersHelper,
97}
98
99/// How a client disables an entry without removing it.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum DisableMech {
102    /// `enabled: false` in the entry.
103    EnabledFalse,
104    /// `disabled: true` in the entry.
105    DisabledTrue,
106    /// Membership of the entry name in a list at this path from the root.
107    ListMember(&'static [&'static str]),
108}
109
110/// How a project file hides a same-named user-scope server (SPEC 6.3).
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum ProjectDisable {
113    /// The server name is added to a list in the client's project-local
114    /// file at this container path (Claude Code
115    /// `projects["<P>"].disabledMcpServers`), or in its project file when
116    /// it has no project-local file (Gemini `mcp.excluded`).
117    ListMember(crate::adapters::spec::ContainerPath),
118    /// A project entry with `enabled: false` under the same name. With
119    /// `partial`, the entry holds nothing else: the client merges it over
120    /// the user entry (Pi, Codex). Otherwise it is the whole user entry with
121    /// `enabled: false`, because the project entry replaces the user one
122    /// (omp).
123    EnabledFalse { partial: bool },
124}
125
126/// How a client combines a project entry with a same-named user entry.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum ProjectSemantics {
129    /// The higher layer replaces the whole entry.
130    Replace,
131    /// Fields of the higher layer merge over the lower one.
132    DeepMerge,
133    /// Both entries load, each as a server of its own under the same name
134    /// (Cursor, gate V2 CUR-5): nothing shadows across the client's own
135    /// layers, and [`Caps::precedence`] only orders how they are listed.
136    Coexist,
137    Unknown,
138}
139
140/// A configuration layer a client loads entries from, for effective-config
141/// computation. A precedence list is ordered highest first.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum Source {
144    /// The private project layer (Claude Code local scope).
145    ProjectLocal,
146    /// The shared project file.
147    Project,
148    /// The user-scope file.
149    User,
150}
151
152/// Another tool's file a client also loads entries from (SPEC 6.4
153/// `client-compat:<file>`).
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct CompatSource {
156    /// The client whose file it is.
157    pub client: &'static str,
158    pub source: Source,
159    /// Where the file ranks: `None` below every layer of the client's own;
160    /// otherwise above one of them, for the host that reads it.
161    pub outranks: Option<Outrank>,
162}
163
164impl CompatSource {
165    /// `client`'s `source` file, ranked below every layer of the client's
166    /// own.
167    pub const fn below(client: &'static str, source: Source) -> Self {
168        Self {
169            client,
170            source,
171            outranks: None,
172        }
173    }
174}
175
176/// A compatibility file that one host of a client prefers over the
177/// client's own layer `source` and every layer below it, while its other
178/// hosts do not read the file at all (VS Code runs `<P>/.vscode/mcp.json`
179/// over a same-named `<P>/.mcp.json` entry; the Copilot CLI reads only
180/// `.mcp.json`; gate V2 VSL-3).
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub struct Outrank {
183    pub source: Source,
184    /// The host that reads the file and runs its entry ("VS Code").
185    pub host: &'static str,
186    /// The client's hosts that do not read the file and so run the entry
187    /// of its own layer ("the Copilot CLI").
188    pub others: &'static str,
189}
190
191/// A client's approval gate for project files.
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub enum TrustGate {
194    /// Servers in the project file need an approval prompt (Claude Code
195    /// `.mcp.json`).
196    ApprovalPrompt,
197    /// The project must be marked trusted (Codex, Pi).
198    TrustedProject,
199    /// The folder must be trusted (Gemini, Grok).
200    TrustedFolder,
201    /// The editor workspace must be trusted (VS Code).
202    WorkspaceTrust,
203    /// Each server in the project file stays disabled until the user
204    /// enables it once in the client, at this place in its UI (Cursor:
205    /// "Customize > MCPs", gate V2 CUR-2). The toggle lives in the client's
206    /// own storage, so Surjection cannot read it and only reports a hint
207    /// (`client_enable_required`).
208    ClientEnable(&'static str),
209}
210
211/// Native tool filtering fields.
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub enum ToolFilterMech {
214    /// Separate allow and deny lists (Codex `enabled_tools`/`disabled_tools`,
215    /// Gemini `includeTools`/`excludeTools`).
216    AllowDeny {
217        allow: &'static str,
218        deny: &'static str,
219    },
220    /// An allow list only (Copilot `tools`).
221    Allow(&'static str),
222}
223
224/// The unit of a native timeout field.
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226pub enum TimeUnit {
227    Seconds,
228    Milliseconds,
229}
230
231impl TimeUnit {
232    /// The unit in messages.
233    pub const fn name(self) -> &'static str {
234        match self {
235            TimeUnit::Seconds => "seconds",
236            TimeUnit::Milliseconds => "milliseconds",
237        }
238    }
239}
240
241/// A native timeout field and its unit (omp `timeout` in milliseconds, Pi
242/// `timeout` in seconds). Timeouts are passthrough fields, so a value keeps
243/// the unit of the client it is written for.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub struct TimeoutField {
246    pub key: &'static str,
247    pub unit: TimeUnit,
248}
249
250impl TimeoutField {
251    /// The duration a native value stands for: a non-negative, finite
252    /// number in this field's unit. `None` for anything else.
253    pub fn duration(&self, value: &NativeValue) -> Option<Duration> {
254        let amount = match *value {
255            NativeValue::Integer(amount) => u64::try_from(amount).ok()? as f64,
256            NativeValue::Float(amount) if amount.is_finite() && amount >= 0.0 => amount,
257            _ => return None,
258        };
259        let seconds = match self.unit {
260            TimeUnit::Seconds => amount,
261            TimeUnit::Milliseconds => amount / 1000.0,
262        };
263        Duration::try_from_secs_f64(seconds).ok()
264    }
265
266    /// What a value of this field must be, for error messages.
267    pub const fn expected(&self) -> &'static str {
268        match self.unit {
269            TimeUnit::Seconds => "a non-negative number of seconds",
270            TimeUnit::Milliseconds => "a non-negative number of milliseconds",
271        }
272    }
273}
274
275/// A client's MCP capabilities (SPEC 7.1, table 7.4).
276#[derive(Debug, Clone, Copy)]
277pub struct Caps {
278    pub transports: TransportSet,
279    pub env_ref: Option<EnvRefSyntax>,
280    /// Fields the client expands `env_ref` references in.
281    pub env_ref_fields: FieldSet,
282    pub command_ref: Option<CommandRef>,
283    pub native_disable: Option<DisableMech>,
284    pub project_disable: Option<ProjectDisable>,
285    pub project_semantics: ProjectSemantics,
286    /// Layers the client loads, highest precedence first.
287    pub precedence: &'static [Source],
288    pub compat_reads: &'static [CompatSource],
289    pub trust_gate: Option<TrustGate>,
290    /// The client rewrites its file while running (`~/.claude.json`): writes
291    /// need a compare-and-swap check and a retry.
292    pub rewrites_file_at_runtime: bool,
293    /// The client reads its file only at launch.
294    pub restart_required: bool,
295    pub tool_filter: Option<ToolFilterMech>,
296    /// The client spawns stdio servers without a shell, so Windows `.cmd`
297    /// shims (`npx`) run through `cmd /c` (SPEC 5.2).
298    pub windows_shell_shim: bool,
299    /// Native timeout fields (all passthrough), with their units.
300    pub timeouts: &'static [TimeoutField],
301    /// Native fields a server may pass through in `[client.<id>]`.
302    pub passthrough_allowlist: &'static [&'static str],
303}