basis 0.4.0

The basis SDK: workspace discovery, run lifecycle, one event stream, and the two seams. No protocol, no transport, no TTY.
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
//! The `.mcp.json` format.
//!
//! One object, `mcpServers`, keyed by name — the name is the map key rather
//! than a field, which is the one place this format and mentra's
//! [`McpServerConfig`] disagree.
//!
//! An entry names its transport with `type`, or omits it and lets its shape
//! say: `command` means stdio, `url` means a remote server. Both or neither is
//! a mistake worth reporting rather than guessing at, because either guess
//! silently starts something the operator did not ask for.

use std::{
    collections::{BTreeMap, HashMap},
    path::Path,
};

use mentra::{McpServerConfig, McpSseServerConfig};
use serde::Deserialize;

use crate::expand::expand;

use super::{McpError, McpServer};

/// The whole file.
#[derive(Debug, Deserialize)]
struct McpFile {
    /// Optional so that its absence can be reported. A missing `mcpServers`
    /// is almost always a misspelled one, and defaulting to empty would turn
    /// that into a workspace whose servers quietly never start.
    #[serde(rename = "mcpServers")]
    mcp_servers: Option<BTreeMap<String, RawServer>>,
}

/// One entry, before it is known which transport it describes.
///
/// Unknown fields are tolerated: these files are shared with other agents, and
/// rejecting a key basis has no opinion about would make a working file
/// unreadable for no gain.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawServer {
    #[serde(rename = "type")]
    transport: Option<String>,
    command: Option<String>,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    env: HashMap<String, String>,
    cwd: Option<String>,
    url: Option<String>,
    #[serde(default)]
    headers: BTreeMap<String, String>,
}

/// Which transport an entry asks for, once the question is settled.
enum Transport {
    Stdio,
    Sse,
}

/// Reads `text` as the file at `path`.
pub(super) fn parse(path: &Path, text: &str) -> Result<Vec<McpServer>, McpError> {
    parse_with(path, text, &|name| std::env::var(name).ok())
}

/// The same, against an explicit environment, so the rules are testable
/// without mutating the process's own.
fn parse_with(
    path: &Path,
    text: &str,
    lookup: &dyn Fn(&str) -> Option<String>,
) -> Result<Vec<McpServer>, McpError> {
    let file: McpFile = serde_json::from_str(text).map_err(|source| McpError::Parse {
        path: path.to_path_buf(),
        // serde's own message quotes the value it choked on, which in this
        // file is as likely as not a credential. Location and kind only.
        problem: match source.classify() {
            serde_json::error::Category::Syntax => "a syntax error",
            serde_json::error::Category::Data => "a value of the wrong type",
            serde_json::error::Category::Eof => "an unexpected end of input",
            serde_json::error::Category::Io => "a read error",
        },
        line: source.line(),
        column: source.column(),
    })?;

    let Some(entries) = file.mcp_servers else {
        return Err(McpError::NoServers {
            path: path.to_path_buf(),
        });
    };

    let origin = path.display().to_string();

    entries
        .into_iter()
        .map(|(name, raw)| raw.into_server(&origin, name, lookup))
        .collect()
}

impl RawServer {
    fn into_server(
        self,
        origin: &str,
        name: String,
        lookup: &dyn Fn(&str) -> Option<String>,
    ) -> Result<McpServer, McpError> {
        let invalid = |reason: String| McpError::Invalid {
            origin: origin.to_string(),
            name: name.clone(),
            reason,
        };

        // Expansion failures name the field rather than quoting it. `env` and
        // `headers` are where credentials live, so the field's *name* is the
        // most an error may say about it — see [`McpError`].
        let expanded = |field: &str, raw: &str| -> Result<String, McpError> {
            expand(raw, lookup)
                .map_err(|reason| invalid(format!("has a `{field}` value that {reason}")))
        };

        if name.trim().is_empty() {
            return Err(invalid("has an empty name".to_string()));
        }

        match self.transport(origin, &name)? {
            Transport::Stdio => {
                let command = self
                    .command
                    .as_deref()
                    .filter(|command| !command.trim().is_empty())
                    .ok_or_else(|| invalid("has no `command` to run".to_string()))?;

                Ok(McpServer::Stdio(McpServerConfig {
                    command: expanded("command", command)?,
                    args: self
                        .args
                        .iter()
                        .enumerate()
                        .map(|(index, arg)| expanded(&format!("args[{index}]"), arg))
                        .collect::<Result<_, _>>()?,
                    env: self
                        .env
                        .iter()
                        .map(|(key, value)| {
                            Ok((key.clone(), expanded(&format!("env.{key}"), value)?))
                        })
                        .collect::<Result<_, McpError>>()?,
                    cwd: self
                        .cwd
                        .as_deref()
                        .map(|cwd| expanded("cwd", cwd))
                        .transpose()?,
                    name,
                }))
            }
            Transport::Sse => {
                let url = self
                    .url
                    .as_deref()
                    .filter(|url| !url.trim().is_empty())
                    .ok_or_else(|| invalid("has no `url` to reach".to_string()))?;

                let config = McpSseServerConfig::new(name.clone(), expanded("url", url)?);

                self.headers
                    .iter()
                    .try_fold(config, |config, (key, value)| {
                        Ok(config
                            .with_header(key.clone(), expanded(&format!("headers.{key}"), value)?))
                    })
                    .map(McpServer::Sse)
            }
        }
    }

    /// Settles which transport the entry describes.
    fn transport(&self, origin: &str, name: &str) -> Result<Transport, McpError> {
        let unsupported = |transport: &str| McpError::UnsupportedTransport {
            origin: origin.to_string(),
            name: name.to_string(),
            transport: transport.to_string(),
        };
        let invalid = |reason: String| McpError::Invalid {
            origin: origin.to_string(),
            name: name.to_string(),
            reason,
        };

        match self.transport.as_deref().map(str::trim) {
            Some("stdio") => Ok(Transport::Stdio),
            Some("sse") => Ok(Transport::Sse),
            // mentra speaks the 2024-11-05 HTTP+SSE transport, not Streamable
            // HTTP; naming the gap is the point of refusing here.
            Some("http") | Some("streamable-http") => Err(unsupported("Streamable HTTP")),
            Some(other) => Err(invalid(format!("names an unknown transport `{other}`"))),
            // The original format had no `type` field at all, so an entry's
            // shape is the older way of saying the same thing.
            None => match (self.command.is_some(), self.url.is_some()) {
                (true, false) => Ok(Transport::Stdio),
                (false, true) => Ok(Transport::Sse),
                (true, true) => Err(invalid(
                    "has both `command` and `url`; set `type` to say which is meant".to_string(),
                )),
                (false, false) => Err(invalid("has neither `command` nor `url`".to_string())),
            },
        }
    }
}

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

    fn nothing_set(_: &str) -> Option<String> {
        None
    }

    fn parse_text(text: &str) -> Result<Vec<McpServer>, McpError> {
        parse_with(Path::new("/repo/.mcp.json"), text, &nothing_set)
    }

    #[test]
    fn the_documented_shape_becomes_a_stdio_server() {
        let servers = parse_text(
            r#"{
                "mcpServers": {
                    "filesystem": {
                        "command": "npx",
                        "args": ["-y", "@modelcontextprotocol/server-filesystem"],
                        "env": {"ROOT": "/repo"}
                    }
                }
            }"#,
        )
        .expect("a well-formed file");

        assert_eq!(servers.len(), 1);
        let config = servers[0].as_stdio().expect("stdio");
        assert_eq!(config.name, "filesystem", "the map key becomes the name");
        assert_eq!(config.command, "npx");
        assert_eq!(
            config.args,
            vec!["-y", "@modelcontextprotocol/server-filesystem"]
        );
        assert_eq!(config.env.get("ROOT").map(String::as_str), Some("/repo"));
        assert_eq!(config.cwd, None);
    }

    #[test]
    fn an_empty_server_object_is_allowed() {
        let servers = parse_text(r#"{"mcpServers": {}}"#).expect("explicitly empty is a choice");

        assert!(servers.is_empty());
    }

    #[test]
    fn a_missing_mcp_servers_key_is_an_error() {
        let error = parse_text(r#"{"mcpservers": {}}"#).expect_err("a misspelled key is caught");

        assert!(matches!(error, McpError::NoServers { .. }), "{error}");
    }

    #[test]
    fn unknown_keys_are_tolerated() {
        let servers = parse_text(
            r#"{
                "$schema": "https://example.com/mcp.json",
                "mcpServers": {"fs": {"command": "npx", "disabled": false}}
            }"#,
        )
        .expect("these files are shared with other agents");

        assert_eq!(servers.len(), 1);
    }

    #[test]
    fn cwd_is_carried_through() {
        let servers = parse_text(r#"{"mcpServers":{"fs":{"command":"srv","cwd":"/tmp"}}}"#)
            .expect("a well-formed file");

        assert_eq!(
            servers[0].as_stdio().expect("stdio").cwd.as_deref(),
            Some("/tmp")
        );
    }

    #[test]
    fn a_url_without_a_type_is_an_sse_server() {
        let servers = parse_text(r#"{"mcpServers":{"obs":{"url":"https://example.com/sse"}}}"#)
            .expect("shape names the transport");

        let config = servers[0].as_sse().expect("sse");
        assert_eq!(config.name, "obs");
        assert_eq!(config.url, "https://example.com/sse");
    }

    #[test]
    fn an_explicit_sse_type_is_honored() {
        let servers =
            parse_text(r#"{"mcpServers":{"obs":{"type":"sse","url":"https://example.com/sse"}}}"#)
                .expect("an explicit type");

        assert!(servers[0].as_sse().is_some());
    }

    #[test]
    fn sse_headers_are_carried_through() {
        let servers = parse_text(
            r#"{"mcpServers":{"obs":{"url":"https://example.com/sse","headers":{"authorization":"Bearer t"}}}}"#,
        )
        .expect("a well-formed file");

        let config = servers[0].as_sse().expect("sse");
        assert_eq!(
            config
                .headers
                .get("authorization")
                .map(mentra::mcp::SecretString::expose_secret),
            Some("Bearer t")
        );
    }

    #[test]
    fn streamable_http_is_refused_by_name() {
        let error = parse_text(r#"{"mcpServers":{"api":{"type":"http","url":"https://x/mcp"}}}"#)
            .expect_err("basis cannot serve it");

        assert!(
            matches!(error, McpError::UnsupportedTransport { .. }),
            "a client must learn its server will not start: {error}"
        );
    }

    #[test]
    fn an_unknown_transport_is_an_error() {
        let error = parse_text(r#"{"mcpServers":{"x":{"type":"carrier-pigeon","url":"u"}}}"#)
            .expect_err("unknown transports are errors");

        assert!(matches!(error, McpError::Invalid { .. }), "{error}");
    }

    #[test]
    fn an_entry_with_neither_command_nor_url_is_an_error() {
        let error = parse_text(r#"{"mcpServers":{"x":{"args":["-y"]}}}"#)
            .expect_err("nothing to connect to");

        assert!(matches!(error, McpError::Invalid { .. }), "{error}");
    }

    #[test]
    fn an_entry_with_both_command_and_url_is_an_error() {
        let error = parse_text(r#"{"mcpServers":{"x":{"command":"srv","url":"https://x"}}}"#)
            .expect_err("ambiguous rather than guessed at");

        assert!(matches!(error, McpError::Invalid { .. }), "{error}");
    }

    #[test]
    fn an_empty_command_is_an_error() {
        let error = parse_text(r#"{"mcpServers":{"x":{"type":"stdio","command":"  "}}}"#)
            .expect_err("nothing to spawn");

        assert!(matches!(error, McpError::Invalid { .. }), "{error}");
    }

    #[test]
    fn an_empty_name_is_an_error() {
        let error = parse_text(r#"{"mcpServers":{"":{"command":"srv"}}}"#)
            .expect_err("the name namespaces the tools");

        assert!(matches!(error, McpError::Invalid { .. }), "{error}");
    }

    #[test]
    fn environment_placeholders_are_expanded() {
        let servers = parse_with(
            Path::new("/repo/.mcp.json"),
            r#"{"mcpServers":{"gh":{"command":"srv","args":["--org","${ORG}"],"env":{"TOKEN":"${GH_TOKEN}"}}}}"#,
            &|name| match name {
                "ORG" => Some("oops-rs".to_string()),
                "GH_TOKEN" => Some("secret".to_string()),
                _ => None,
            },
        )
        .expect("both are set");

        let config = servers[0].as_stdio().expect("stdio");
        assert_eq!(config.args, vec!["--org", "oops-rs"]);
        assert_eq!(config.env.get("TOKEN").map(String::as_str), Some("secret"));
    }

    #[test]
    fn an_unset_placeholder_names_the_server_and_the_field() {
        let error =
            parse_text(r#"{"mcpServers":{"gh":{"command":"srv","env":{"T":"${GH_TOKEN}"}}}}"#)
                .expect_err("an unset variable is an error");

        let rendered = error.to_string();
        assert!(rendered.contains("gh"), "{rendered}");
        assert!(rendered.contains("env.T"), "{rendered}");
        assert!(rendered.contains("GH_TOKEN"), "{rendered}");
    }

    #[test]
    fn no_error_repeats_a_value_from_the_file() {
        // These files are gitignored because `env` and `headers` hold
        // credentials, and these messages travel to clients and logs.
        const SECRET: &str = "sk-live-do-not-print-me";

        let broken = [
            format!(r#"{{"mcpServers":{{"a":{{"command":"srv","env":{{"T":"{SECRET}${{"}}}}}}}}"#),
            format!(r#"{{"mcpServers":{{"b":{{"command":"srv","args":["{SECRET}${{NOPE}}"]}}}}}}"#),
            format!(
                r#"{{"mcpServers":{{"c":{{"url":"https://x/sse","headers":{{"authorization":"{SECRET}${{}}"}}}}}}}}"#
            ),
            // serde's own message would quote this one.
            format!(r#"{{"mcpServers":{{"d":{{"command":"srv","env":"{SECRET}"}}}}}}"#),
        ];

        for text in broken {
            let error = parse_text(&text).expect_err("each of these fails");

            assert!(
                !error.to_string().contains(SECRET),
                "a value leaked into: {error}"
            );
        }
    }

    #[test]
    fn servers_come_back_in_a_stable_order() {
        let servers = parse_text(
            r#"{"mcpServers":{"zeta":{"command":"z"},"alpha":{"command":"a"},"mid":{"command":"m"}}}"#,
        )
        .expect("a well-formed file");

        let names: Vec<&str> = servers.iter().map(McpServer::name).collect();
        assert_eq!(
            names,
            vec!["alpha", "mid", "zeta"],
            "registration order must not depend on hashing"
        );
    }
}