Skip to main content

surjection_core/adapters/
opencode.rs

1//! OpenCode (`opencode`): SPEC 7.3, 7.4 and 7.5.
2//!
3//! - User scope: `$XDG_CONFIG_HOME/opencode/opencode.json` (default
4//!   `~/.config`, on Windows too), or `opencode.jsonc` there when only that
5//!   one exists. Both are JSONC; a new file starts with OpenCode's
6//!   `$schema` line.
7//! - Project scope: `<P>/opencode.json[c]`, else an existing
8//!   `<P>/.opencode/opencode.json[c]`.
9//! - Entries: `mcp.<name>`: `{type: "local", command: [cmd, ...args],
10//!   environment, enabled}` or `{type: "remote", url, headers, enabled}`.
11//!   `command` is one array holding the command and its arguments. A
12//!   remote entry reads as http unless its URL path ends in `/sse` (SPEC
13//!   7.5); an SSE server is written as a remote entry too, since OpenCode
14//!   tries Streamable HTTP first and falls back to SSE. No `cwd`, no
15//!   per-server tool filter.
16//! - `enabled: false` disables an entry; a project hides a user server
17//!   with the whole entry and `enabled: false` (OpenCode merges project
18//!   over user, SPEC 7.4).
19//! - Variables: OpenCode substitutes `{env:NAME}` anywhere in the file
20//!   before parsing it; Surjection writes `{env:NAME}`.
21//!
22//! Assumptions left for Tier C verification (`scripts/verify-clients.md`,
23//! OC-*): `[verify]` the user and project files (OC-1, OC-2, including
24//! which file wins when `opencode.json` and `opencode.jsonc` both exist),
25//! the remote fallback to SSE (OC-3), that a project entry with `enabled:
26//! false` hides the user entry (OC-4; Surjection writes the whole entry, as
27//! OpenCode validates each file on its own and a partial entry has no
28//! `type`), the deep merge of project over user entries (OC-5), that an
29//! entry without `type` is rejected (OC-6), that `{env:NAME}` is expanded
30//! in every field (OC-7), that any non-empty name loads (OC-8), that
31//! Windows starts `npx` without `cmd /c` (OC-9) and the detection probes
32//! (OC-10).
33
34use crate::adapters::caps::{
35    Caps, DisableMech, EnvRefSyntax, FieldSet, ProjectDisable, ProjectSemantics, Source,
36    TransportSet,
37};
38use crate::adapters::detect::Probe;
39use crate::adapters::location::Location;
40use crate::adapters::mapper::{
41    Canonical, EntryMapper, Launch, MapError, RenderedServer, ServerDef, WriteCx, carry_over,
42    check_name, check_transport, drop_default_enabled, drop_empty, existing_entry, read_disabled,
43    read_tools, shape, split_rest, string_field, string_map, string_map_field, unsupported,
44    write_enabled, write_passthrough, write_tools,
45};
46use crate::adapters::spec::{AdapterSpec, ContainerPath, McpSpec, Tier, exact_names};
47use crate::env::Os;
48use crate::formats::{Format, NativeMap, NativeValue};
49use crate::model::clients::passthrough_of;
50use crate::model::server::{ServerFields, Transport};
51
52pub const ID: &str = "opencode";
53
54const TYPE: &str = "type";
55const LOCAL: &str = "local";
56const REMOTE: &str = "remote";
57const COMMAND: &str = "command";
58const ENVIRONMENT: &str = "environment";
59const ENABLED: &str = "enabled";
60
61/// The text of a new OpenCode config file.
62pub const SKELETON: &str = "{\n  \"$schema\": \"https://opencode.ai/config.json\"\n}\n";
63
64const CAPS: Caps = Caps {
65    transports: TransportSet::ALL,
66    env_ref: Some(EnvRefSyntax::BraceEnv),
67    env_ref_fields: FieldSet::COMMAND
68        .union(FieldSet::ARGS)
69        .union(FieldSet::ENV)
70        .union(FieldSet::URL)
71        .union(FieldSet::HEADERS),
72    command_ref: None,
73    native_disable: Some(DisableMech::EnabledFalse),
74    project_disable: Some(ProjectDisable::EnabledFalse { partial: false }),
75    project_semantics: ProjectSemantics::DeepMerge,
76    precedence: &[Source::Project, Source::User],
77    compat_reads: &[],
78    trust_gate: None,
79    rewrites_file_at_runtime: false,
80    restart_required: false,
81    tool_filter: None,
82    windows_shell_shim: false,
83    timeouts: &[],
84    passthrough_allowlist: passthrough_of(ID),
85};
86
87/// Keys the OpenCode mapper models besides passthrough fields.
88const MODELED_KEYS: [&str; 6] = [TYPE, COMMAND, ENVIRONMENT, "url", "headers", ENABLED];
89
90fn is_modeled(key: &str) -> bool {
91    MODELED_KEYS.contains(&key) || CAPS.passthrough_allowlist.contains(&key)
92}
93
94fn valid_name(name: &str) -> bool {
95    !name.is_empty()
96}
97
98/// Whether the path of `url` ends in `/sse` (query and fragment ignored,
99/// trailing slashes too), which makes a remote entry SSE (SPEC 7.5).
100pub fn is_sse_url(url: &str) -> bool {
101    let end = url.find(['?', '#']).unwrap_or(url.len());
102    let path = url[..end].trim_end_matches('/');
103    let path = path.split_once("://").map_or(path, |(_, rest)| {
104        rest.find('/').map_or("", |at| &rest[at..])
105    });
106    path.ends_with("/sse")
107}
108
109/// The type OpenCode needs for an entry missing it, from its keys.
110fn inferred_type(entry: &NativeMap) -> Option<&'static str> {
111    if entry.contains_key(COMMAND) {
112        Some(LOCAL)
113    } else if entry.contains_key("url") {
114        Some(REMOTE)
115    } else {
116        None
117    }
118}
119
120/// The `mcp.<name>` entry of an OpenCode config file (see the module
121/// docs).
122#[derive(Debug)]
123pub struct OpenCodeJson;
124
125impl EntryMapper for OpenCodeJson {
126    fn to_native(
127        &self,
128        server: &RenderedServer,
129        cx: &WriteCx<'_>,
130    ) -> Result<NativeValue, MapError> {
131        check_name(valid_name, &server.name)?;
132        check_transport(&CAPS, &server.launch)?;
133        let existing = existing_entry(cx);
134        let keep_empty = |key: &str| existing.is_some_and(|entry| entry.contains_key(key));
135        let mut entry = NativeMap::new();
136        match &server.launch {
137            Launch::Stdio(stdio) => {
138                if !stdio.forward_env.is_empty() {
139                    return unsupported("env_vars");
140                }
141                if stdio.cwd.is_some() {
142                    return unsupported("cwd");
143                }
144                entry.insert(TYPE, LOCAL.into());
145                let command = std::iter::once(&stdio.command)
146                    .chain(&stdio.args)
147                    .map(|part| NativeValue::from(part.as_str()))
148                    .collect();
149                entry.insert(COMMAND, NativeValue::Array(command));
150                if !stdio.env.is_empty() || keep_empty(ENVIRONMENT) {
151                    entry.insert(ENVIRONMENT, string_map(&stdio.env));
152                }
153            }
154            Launch::Http(remote) | Launch::Sse(remote) => {
155                if remote.headers_helper.is_some() {
156                    return unsupported("headersHelper");
157                }
158                if remote.bearer_env.is_some() {
159                    return unsupported("bearer_token_env_var");
160                }
161                if !remote.headers_env.is_empty() {
162                    return unsupported("env_http_headers");
163                }
164                entry.insert(TYPE, REMOTE.into());
165                entry.insert("url", remote.url.as_str().into());
166                if !remote.headers.is_empty() || keep_empty("headers") {
167                    entry.insert("headers", string_map(&remote.headers));
168                }
169            }
170        }
171        write_enabled(&mut entry, &CAPS, server, existing)?;
172        write_tools(&mut entry, &CAPS, &server.tools)?;
173        write_passthrough(&mut entry, &CAPS, server)?;
174        carry_over(&mut entry, existing, is_modeled);
175        Ok(NativeValue::Object(entry))
176    }
177
178    fn from_native(&self, key: &str, value: &NativeValue) -> Result<ServerDef, MapError> {
179        let entry = value.as_object().ok_or_else(|| MapError::UnexpectedShape {
180            field: key.to_owned(),
181            expected: "an object",
182        })?;
183        let kind = match entry.get(TYPE) {
184            Some(NativeValue::String(kind)) => kind.as_str(),
185            Some(_) => return shape(TYPE, "a string"),
186            None => match inferred_type(entry) {
187                Some(kind) => kind,
188                None => return shape(TYPE, "`local` or `remote`"),
189            },
190        };
191        let fields = match kind {
192            LOCAL => {
193                let (command, args) = command_array(entry)?;
194                ServerFields {
195                    transport: Some(Transport::Stdio),
196                    command: Some(command),
197                    args: Some(args),
198                    env: string_map_field(entry, ENVIRONMENT)?,
199                    ..ServerFields::default()
200                }
201            }
202            REMOTE => {
203                let url = string_field(entry, "url")?;
204                let transport = match &url {
205                    Some(url) if is_sse_url(url) => Transport::Sse,
206                    _ => Transport::Http,
207                };
208                ServerFields {
209                    transport: Some(transport),
210                    url,
211                    headers: string_map_field(entry, "headers")?,
212                    ..ServerFields::default()
213                }
214            }
215            other => {
216                return Err(MapError::UnsupportedTransport {
217                    transport: other.to_owned(),
218                });
219            }
220        };
221        let mut def = ServerDef {
222            fields,
223            disabled: read_disabled(entry, &CAPS)?,
224            tools: read_tools(entry, &CAPS)?,
225            ..ServerDef::default()
226        };
227        split_rest(&mut def, entry, &CAPS, is_modeled);
228        Ok(def)
229    }
230
231    fn canonical(&self, value: &NativeValue) -> Canonical {
232        let Some(entry) = value.as_object() else {
233            return Canonical::of(value);
234        };
235        let mut entry = entry.clone();
236        drop_empty(&mut entry, &[ENVIRONMENT, "headers"]);
237        drop_default_enabled(&mut entry, &CAPS);
238        Canonical::of(&NativeValue::Object(entry))
239    }
240
241    fn skipped_by_client(&self, value: &NativeValue) -> Option<&'static str> {
242        let entry = value.as_object()?;
243        (!entry.contains_key(TYPE) && inferred_type(entry).is_some())
244            .then_some("has no `type` (`local` or `remote`), so the client rejects it")
245    }
246}
247
248/// `command`: a non-empty array of strings, the command then its
249/// arguments.
250fn command_array(entry: &NativeMap) -> Result<(String, Vec<String>), MapError> {
251    const EXPECTED: &str = "a non-empty array of strings (the command, then its arguments)";
252    let parts = entry
253        .get(COMMAND)
254        .and_then(NativeValue::as_array)
255        .and_then(|items| {
256            items
257                .iter()
258                .map(|item| item.as_str().map(str::to_owned))
259                .collect::<Option<Vec<String>>>()
260        });
261    match parts {
262        Some(mut parts) if !parts.is_empty() => {
263            let command = parts.remove(0);
264            Ok((command, parts))
265        }
266        _ => shape(COMMAND, EXPECTED),
267    }
268}
269
270static MAPPER: OpenCodeJson = OpenCodeJson;
271
272pub static SPEC: AdapterSpec = AdapterSpec {
273    id: ID,
274    display_name: "OpenCode",
275    tier: Tier::C,
276    detect: &[
277        Probe::Path(Location::XdgConfigAllOs("opencode")),
278        Probe::Executable("opencode"),
279    ],
280    mcp: Some(McpSpec {
281        oses: &[Os::Windows, Os::Linux, Os::MacOs],
282        read_only: false,
283        user: &[
284            Location::XdgConfigAllOs("opencode/opencode.json"),
285            Location::XdgConfigAllOs("opencode/opencode.jsonc"),
286        ],
287        user_files: None,
288        user_mirrors: &[],
289        profiles: None,
290        project: &[
291            Location::Project("opencode.json"),
292            Location::Project("opencode.jsonc"),
293            Location::Project(".opencode/opencode.json"),
294            Location::Project(".opencode/opencode.jsonc"),
295        ],
296        project_local: &[],
297        format: Format::Jsonc,
298        skeleton: SKELETON,
299        container: ContainerPath(&["mcp"]),
300        project_local_container: ContainerPath(&["mcp"]),
301        legacy_containers: &[],
302        same_name: exact_names,
303        replaced_by: &[],
304        mapper: &MAPPER,
305        caps: CAPS,
306    }),
307};