Skip to main content

byob_plugins/
manifest.rs

1//! `byob-plugin.json`: the plugin manifest.
2//!
3//! Parsing mirrors hob's `parseManifest`: the same required fields, defaults and limits,
4//! and error messages written for the plugin's author (e.g.
5//! `byob-plugin.json: tools[0].run must be a path inside the plugin folder`). Unknown fields
6//! are ignored so newer manifests still load.
7
8use std::collections::BTreeMap;
9use std::path::{Component, Path};
10
11use serde::Serialize;
12use serde_json::{Map, Value};
13
14/// The manifest file name.
15pub const MANIFEST: &str = "byob-plugin.json";
16/// The manifest's old name (from hob, which byob started as a rewrite of). Not read: a
17/// folder with only this file gets a warning to rename it.
18pub const OLD_MANIFEST: &str = "hob-plugin.json";
19
20/// Prompt length caps (characters), as in hob: built-in plugins carry longer how-tos.
21const PROMPT_MAX: usize = 600;
22const PROMPT_MAX_BUILTIN: usize = 1500;
23
24/// A checked plugin manifest with defaults filled in.
25#[derive(Debug, Clone, PartialEq, Serialize)]
26pub struct Manifest {
27    /// `[a-z0-9][a-z0-9-]{0,47}`.
28    pub id: String,
29    pub name: String,
30    /// `0.0.0` when left out.
31    pub version: String,
32    pub description: String,
33    pub author: Option<String>,
34    /// A lucide icon name; `puzzle` when left out.
35    pub icon: String,
36    pub permissions: Permissions,
37    pub starters: Vec<Starter>,
38    pub tools: Vec<ManifestTool>,
39    pub mcp_servers: BTreeMap<String, McpServerConfig>,
40    pub settings: Vec<Setting>,
41    /// A line added to the system prompt while the plugin is on.
42    pub prompt: Option<String>,
43    /// Node `process.platform` names (`darwin`, `linux`, `win32`); everywhere when `None`.
44    pub platforms: Option<Vec<String>>,
45}
46
47#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
48pub struct Permissions {
49    /// Python tools (and skills' scripts) may use the internet.
50    pub network: bool,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
54pub struct Starter {
55    pub title: String,
56    pub prompt: String,
57    /// The starter asks the user for a file first.
58    pub file: bool,
59}
60
61/// A tool a plugin declares.
62#[derive(Debug, Clone, PartialEq, Serialize)]
63pub struct ManifestTool {
64    /// `[A-Za-z][A-Za-z0-9_]{0,63}`.
65    pub name: String,
66    pub description: String,
67    /// JSON Schema object for the arguments.
68    pub params: Value,
69    pub kind: ToolKind,
70    /// Step title with `{arg}` placeholders.
71    pub title: Option<String>,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
75pub enum ToolKind {
76    /// A Python script, relative to the plugin folder.
77    Script(String),
78    /// One of the app's own tools, by name (built-in plugins only).
79    Native(String),
80}
81
82/// How to reach one MCP server.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
84pub enum McpServerConfig {
85    /// A program on this computer, spoken to over stdio.
86    Stdio { command: String, args: Vec<String>, env: BTreeMap<String, String> },
87    /// A server at a URL (Streamable HTTP, or legacy HTTP+SSE).
88    Url { url: String, sse: bool, headers: BTreeMap<String, String>, oauth: Option<OAuthClient> },
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
92pub struct OAuthClient {
93    pub client_id: String,
94    pub client_secret: Option<String>,
95}
96
97impl McpServerConfig {
98    /// Stdio servers run unsandboxed local code; URL servers only talk to the network.
99    pub fn is_local(&self) -> bool {
100        matches!(self, Self::Stdio { .. })
101    }
102
103    /// Fill `${KEY}` placeholders in args, env values, the URL and headers from the
104    /// plugin's settings. Unknown keys are left as they are.
105    pub fn with_settings(&self, values: &BTreeMap<String, String>) -> Self {
106        let fill = |s: &String| fill_placeholders(s, values);
107        let fill_map = |m: &BTreeMap<String, String>| m.iter().map(|(k, v)| (k.clone(), fill(v))).collect();
108        match self {
109            Self::Stdio { command, args, env } => Self::Stdio { command: fill(command), args: args.iter().map(fill).collect(), env: fill_map(env) },
110            Self::Url { url, sse, headers, oauth } => Self::Url { url: fill(url), sse: *sse, headers: fill_map(headers), oauth: oauth.clone() },
111        }
112    }
113}
114
115/// `"Bearer ${API_KEY}"` + `{API_KEY: "abc"}` → `"Bearer abc"`.
116pub fn fill_placeholders(s: &str, values: &BTreeMap<String, String>) -> String {
117    let mut out = String::with_capacity(s.len());
118    let mut rest = s;
119    while let Some(start) = rest.find("${") {
120        out.push_str(&rest[..start]);
121        let after = &rest[start + 2..];
122        match after.find('}') {
123            Some(end) => {
124                let key = &after[..end];
125                match values.get(key) {
126                    Some(v) => out.push_str(v),
127                    None => {
128                        out.push_str("${");
129                        out.push_str(key);
130                        out.push('}');
131                    }
132                }
133                rest = &after[end + 1..];
134            }
135            None => {
136                out.push_str(&rest[start..]);
137                rest = "";
138            }
139        }
140    }
141    out.push_str(rest);
142    out
143}
144
145#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
146pub enum SettingKind {
147    #[default]
148    Text,
149    Number,
150    Boolean,
151    Directory,
152    File,
153}
154
155impl SettingKind {
156    fn parse(s: &str) -> Option<Self> {
157        Some(match s {
158            "text" => Self::Text,
159            "number" => Self::Number,
160            "boolean" => Self::Boolean,
161            "directory" => Self::Directory,
162            "file" => Self::File,
163            _ => return None,
164        })
165    }
166}
167
168/// A value the user fills in on the plugin's card; passed to tools and servers as an
169/// environment variable named `key`.
170#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
171pub struct Setting {
172    /// `[A-Z][A-Z0-9_]{0,63}`.
173    pub key: String,
174    pub label: String,
175    pub secret: bool,
176    pub help: Option<String>,
177    pub kind: SettingKind,
178    pub required: bool,
179    pub multiple: bool,
180    /// Lists are joined with newlines, as hob does.
181    pub default: Option<String>,
182}
183
184/// Why a manifest was rejected; the message is meant for the plugin's author.
185#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
186#[error("{file}: {message}")]
187pub struct ManifestError {
188    pub file: String,
189    pub message: String,
190}
191
192/// Options for [`parse_manifest`].
193#[derive(Debug, Clone, Copy, Default)]
194pub struct ParseOptions<'a> {
195    /// Ships with the app: may use `native` tools and a longer prompt.
196    pub builtin: bool,
197    /// File name used in error messages; [`MANIFEST`] when `None`.
198    pub file: Option<&'a str>,
199}
200
201/// `[a-z0-9][a-z0-9-]{0,47}`
202pub fn plugin_id_ok(id: &str) -> bool {
203    let b = id.as_bytes();
204    !b.is_empty() && b.len() <= 48 && is_lower_alnum(b[0]) && b.iter().all(|&c| is_lower_alnum(c) || c == b'-')
205}
206
207/// `[A-Za-z][A-Za-z0-9_]{0,63}`
208pub fn tool_name_ok(name: &str) -> bool {
209    let b = name.as_bytes();
210    !b.is_empty() && b.len() <= 64 && b[0].is_ascii_alphabetic() && b.iter().all(|&c| c.is_ascii_alphanumeric() || c == b'_')
211}
212
213/// `[A-Z][A-Z0-9_]{0,63}`
214pub fn setting_key_ok(key: &str) -> bool {
215    let b = key.as_bytes();
216    !b.is_empty() && b.len() <= 64 && b[0].is_ascii_uppercase() && b.iter().all(|&c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')
217}
218
219fn is_lower_alnum(c: u8) -> bool {
220    c.is_ascii_lowercase() || c.is_ascii_digit()
221}
222
223/// A relative path that stays inside its folder (`tools/x.py`, not `/x` or `../x`).
224pub fn path_inside(p: &str) -> bool {
225    let mut depth: usize = 0;
226    for c in Path::new(p).components() {
227        match c {
228            Component::Normal(_) => depth += 1,
229            Component::CurDir => {}
230            Component::ParentDir => match depth.checked_sub(1) {
231                Some(d) => depth = d,
232                None => return false,
233            },
234            Component::RootDir | Component::Prefix(_) => return false,
235        }
236    }
237    // Windows-style absolute paths on other systems.
238    !(p.starts_with('\\') || p.as_bytes().get(1) == Some(&b':'))
239}
240
241/// Check a parsed `byob-plugin.json` and fill in defaults.
242pub fn parse_manifest(raw: &Value, opts: ParseOptions<'_>) -> Result<Manifest, ManifestError> {
243    let file = opts.file.unwrap_or(MANIFEST);
244    parse(raw, opts.builtin).map_err(|message| ManifestError { file: file.to_string(), message })
245}
246
247/// Parse manifest text (JSON).
248pub fn parse_manifest_str(text: &str, opts: ParseOptions<'_>) -> Result<Manifest, ManifestError> {
249    let file = opts.file.unwrap_or(MANIFEST);
250    let raw: Value = serde_json::from_str(text).map_err(|e| ManifestError { file: file.to_string(), message: format!("isn't valid JSON: {e}") })?;
251    parse_manifest(&raw, opts)
252}
253
254type R<T> = Result<T, String>;
255
256/// Required text: present, a string, not blank. Trimmed.
257fn req_str(v: Option<&Value>, field: &str) -> R<String> {
258    match v {
259        Some(Value::String(s)) if !s.trim().is_empty() => Ok(s.trim().to_string()),
260        _ => Err(format!("{field} must be text")),
261    }
262}
263
264/// Optional text: absent → `None`; present must be a string.
265fn opt_str(v: Option<&Value>, field: &str) -> R<Option<String>> {
266    match v {
267        None => Ok(None),
268        Some(Value::String(s)) => Ok(Some(s.trim().to_string())),
269        Some(_) => Err(format!("{field} must be text")),
270    }
271}
272
273fn list<'a>(v: Option<&'a Value>, field: &str) -> R<&'a [Value]> {
274    match v {
275        None => Ok(&[]),
276        Some(Value::Array(a)) => Ok(a),
277        Some(_) => Err(format!("{field} must be a list")),
278    }
279}
280
281fn obj<'a>(v: &'a Value, field: &str) -> R<&'a Map<String, Value>> {
282    v.as_object().ok_or_else(|| format!("{field} must be an object"))
283}
284
285fn str_map(v: Option<&Value>, field: &str) -> R<BTreeMap<String, String>> {
286    let Some(v) = v else { return Ok(BTreeMap::new()) };
287    let bad = || format!("{field} must map names to text");
288    let m = v.as_object().ok_or_else(bad)?;
289    m.iter().map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())).ok_or_else(bad)).collect()
290}
291
292fn truthy(v: Option<&Value>) -> bool {
293    match v {
294        None | Some(Value::Null) => false,
295        Some(Value::Bool(b)) => *b,
296        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
297        Some(Value::String(s)) => !s.is_empty(),
298        Some(_) => true,
299    }
300}
301
302fn truncate_chars(s: &str, max: usize) -> String {
303    s.chars().take(max).collect()
304}
305
306fn parse(raw: &Value, builtin: bool) -> R<Manifest> {
307    let r = raw.as_object().ok_or("must be a JSON object")?;
308    let id = req_str(r.get("id"), "id")?;
309    if !plugin_id_ok(&id) {
310        return Err("id must be lowercase letters, digits and dashes, like \"trip-planner\"".into());
311    }
312    let tools = list(r.get("tools"), "tools")?.iter().enumerate().map(|(i, t)| parse_tool(t, i, builtin)).collect::<R<Vec<_>>>()?;
313    let mcp_servers = parse_servers(r.get("mcpServers"))?;
314    let settings = list(r.get("settings"), "settings")?.iter().enumerate().map(|(i, s)| parse_setting(s, i)).collect::<R<Vec<_>>>()?;
315    let starters = list(r.get("starters"), "starters")?
316        .iter()
317        .enumerate()
318        .map(|(i, s)| {
319            let f = format!("starters[{i}]");
320            let s = obj(s, &f)?;
321            Ok(Starter {
322                title: req_str(s.get("title"), &format!("{f}.title"))?,
323                prompt: req_str(s.get("prompt"), &format!("{f}.prompt"))?,
324                file: s.get("file") == Some(&Value::Bool(true)),
325            })
326        })
327        .collect::<R<Vec<_>>>()?;
328    let network = r.get("permissions").and_then(Value::as_object).and_then(|p| p.get("network")) == Some(&Value::Bool(true));
329    let prompt = match r.get("prompt") {
330        None => None,
331        p => Some(truncate_chars(&req_str(p, "prompt")?, if builtin { PROMPT_MAX_BUILTIN } else { PROMPT_MAX })),
332    };
333    let platforms = r.get("platforms").and_then(Value::as_array).map(|a| a.iter().map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)).collect());
334    let author = match r.get("author") {
335        None => None,
336        a => Some(req_str(a, "author")?),
337    };
338    Ok(Manifest {
339        id,
340        name: req_str(r.get("name"), "name")?,
341        version: opt_str(r.get("version"), "version")?.filter(|v| !v.is_empty()).unwrap_or_else(|| "0.0.0".into()),
342        description: opt_str(r.get("description"), "description")?.unwrap_or_default(),
343        author,
344        icon: opt_str(r.get("icon"), "icon")?.filter(|v| !v.is_empty()).unwrap_or_else(|| "puzzle".into()),
345        permissions: Permissions { network },
346        starters,
347        tools,
348        mcp_servers,
349        settings,
350        prompt,
351        platforms,
352    })
353}
354
355fn parse_tool(t: &Value, i: usize, builtin: bool) -> R<ManifestTool> {
356    let f = format!("tools[{i}]");
357    let t = obj(t, &f)?;
358    let native = match t.get("native") {
359        None => None,
360        n => Some(req_str(n, &format!("{f}.native"))?),
361    };
362    if native.is_some() && !builtin {
363        return Err(format!("{f}.native is only for plugins that ship with the app; use \"run\" with a Python script"));
364    }
365    // native tools bring their own name, description and parameters
366    let name = match (&native, t.get("name")) {
367        (Some(n), None) => n.clone(),
368        (_, v) => req_str(v, &format!("{f}.name"))?,
369    };
370    if !tool_name_ok(&name) {
371        return Err(format!("{f}.name must be letters, digits or _, starting with a letter"));
372    }
373    let params = match t.get("params") {
374        None => serde_json::json!({ "type": "object", "properties": {} }),
375        Some(p @ Value::Object(_)) => p.clone(),
376        Some(_) => return Err(format!("{f}.params must be a JSON schema object")),
377    };
378    let run = match t.get("run") {
379        None => None,
380        v => {
381            let p = req_str(v, &format!("{f}.run"))?;
382            if !path_inside(&p) {
383                return Err(format!("{f}.run must be a path inside the plugin folder"));
384            }
385            Some(p)
386        }
387    };
388    let kind = match (run, native) {
389        (Some(r), _) => ToolKind::Script(r),
390        (None, Some(n)) => ToolKind::Native(n),
391        (None, None) => return Err(format!("{f}.run must name the Python script that runs this tool")),
392    };
393    let description = match (&kind, t.get("description")) {
394        (ToolKind::Native(_), None) => String::new(),
395        (_, d) => req_str(d, &format!("{f}.description"))?,
396    };
397    let title = match t.get("title") {
398        None => None,
399        v => Some(req_str(v, &format!("{f}.title"))?),
400    };
401    Ok(ManifestTool { name, description, params, kind, title })
402}
403
404fn parse_servers(v: Option<&Value>) -> R<BTreeMap<String, McpServerConfig>> {
405    let Some(v) = v else { return Ok(BTreeMap::new()) };
406    let m = v.as_object().ok_or("mcpServers must be an object of servers")?;
407    m.iter().map(|(k, v)| Ok((k.clone(), parse_server(v, &format!("mcpServers.{k}"))?))).collect()
408}
409
410/// One entry of an `mcpServers` object (manifest or pasted Claude/Cursor config).
411pub(crate) fn parse_server(v: &Value, f: &str) -> R<McpServerConfig> {
412    let v = obj(v, f)?;
413    let ty = v.get("type").and_then(Value::as_str);
414    if v.get("url").is_some() || matches!(ty, Some("http" | "sse" | "streamable-http")) {
415        let url = req_str(v.get("url"), &format!("{f}.url"))?;
416        let lower = url.to_ascii_lowercase();
417        let rest = lower.strip_prefix("https://").or_else(|| lower.strip_prefix("http://"));
418        if !rest.is_some_and(|r| !r.is_empty() && !r.starts_with('/')) {
419            return Err(format!("{f}.url must start with https://"));
420        }
421        let headers = str_map(v.get("headers"), &format!("{f}.headers"))?;
422        let oauth = match v.get("oauth") {
423            None => None,
424            Some(o) => {
425                let o = obj(o, &format!("{f}.oauth"))?;
426                Some(OAuthClient {
427                    client_id: req_str(o.get("clientId"), &format!("{f}.oauth.clientId"))?,
428                    client_secret: match o.get("clientSecret") {
429                        None => None,
430                        s => Some(req_str(s, &format!("{f}.oauth.clientSecret"))?),
431                    },
432                })
433            }
434        };
435        return Ok(McpServerConfig::Url { url, sse: ty == Some("sse"), headers, oauth });
436    }
437    let args = list(v.get("args"), &format!("{f}.args"))?
438        .iter()
439        .enumerate()
440        .map(|(i, a)| a.as_str().map(|s| s.trim().to_string()).ok_or_else(|| format!("{f}.args[{i}] must be text")))
441        .collect::<R<Vec<_>>>()?;
442    let env = str_map(v.get("env"), &format!("{f}.env"))?;
443    Ok(McpServerConfig::Stdio { command: req_str(v.get("command"), &format!("{f}.command"))?, args, env })
444}
445
446fn parse_setting(s: &Value, i: usize) -> R<Setting> {
447    let f = format!("settings[{i}]");
448    let s = obj(s, &f)?;
449    let key = req_str(s.get("key"), &format!("{f}.key"))?;
450    if !setting_key_ok(&key) {
451        return Err(format!("{f}.key must be UPPER_CASE, like \"API_KEY\""));
452    }
453    let kind = match s.get("type") {
454        None => SettingKind::Text,
455        t => {
456            let t = req_str(t, &format!("{f}.type"))?;
457            SettingKind::parse(&t).ok_or_else(|| format!("{f}.type must be one of text, number, boolean, directory, file"))?
458        }
459    };
460    let help = match s.get("help") {
461        None => None,
462        h => Some(req_str(h, &format!("{f}.help"))?),
463    };
464    let default = s.get("default").map(|d| match d {
465        Value::Array(a) => a.iter().map(value_text).collect::<Vec<_>>().join("\n"),
466        other => value_text(other),
467    });
468    Ok(Setting {
469        key,
470        label: req_str(s.get("label"), &format!("{f}.label"))?,
471        secret: truthy(s.get("secret")),
472        help,
473        kind,
474        required: truthy(s.get("required")),
475        multiple: truthy(s.get("multiple")),
476        default,
477    })
478}
479
480/// JS `String(v)` for the values settings defaults take.
481fn value_text(v: &Value) -> String {
482    match v {
483        Value::String(s) => s.clone(),
484        Value::Null => "null".into(),
485        other => other.to_string(),
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492    use serde_json::json;
493
494    fn parse_user(v: Value) -> Result<Manifest, String> {
495        parse_manifest(&v, ParseOptions::default()).map_err(|e| e.to_string())
496    }
497
498    #[test]
499    fn minimal_manifest_gets_defaults() {
500        let m = parse_user(json!({"id": "recipe-helper", "name": "Recipe Helper", "extra": {"future": true}})).unwrap();
501        assert_eq!(m.version, "0.0.0");
502        assert_eq!(m.icon, "puzzle");
503        assert!(!m.permissions.network);
504        assert!(m.tools.is_empty() && m.mcp_servers.is_empty() && m.settings.is_empty());
505    }
506
507    #[test]
508    fn author_facing_errors() {
509        let cases = [
510            (json!([]), "byob-plugin.json: must be a JSON object"),
511            (json!({"name": "x"}), "byob-plugin.json: id must be text"),
512            (json!({"id": "Bad_Id", "name": "x"}), "byob-plugin.json: id must be lowercase letters, digits and dashes, like \"trip-planner\""),
513            (json!({"id": "a", "name": "x", "tools": {}}), "byob-plugin.json: tools must be a list"),
514            (
515                json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d", "run": "../escape.py"}]}),
516                "byob-plugin.json: tools[0].run must be a path inside the plugin folder",
517            ),
518            (
519                json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d", "run": "/abs.py"}]}),
520                "byob-plugin.json: tools[0].run must be a path inside the plugin folder",
521            ),
522            (
523                json!({"id": "a", "name": "x", "tools": [{"name": "t", "description": "d"}]}),
524                "byob-plugin.json: tools[0].run must name the Python script that runs this tool",
525            ),
526            (
527                json!({"id": "a", "name": "x", "tools": [{"name": "1t", "description": "d", "run": "t.py"}]}),
528                "byob-plugin.json: tools[0].name must be letters, digits or _, starting with a letter",
529            ),
530            (
531                json!({"id": "a", "name": "x", "tools": [{"native": "run_python"}]}),
532                "byob-plugin.json: tools[0].native is only for plugins that ship with the app; use \"run\" with a Python script",
533            ),
534            (
535                json!({"id": "a", "name": "x", "settings": [{"key": "api_key", "label": "k"}]}),
536                "byob-plugin.json: settings[0].key must be UPPER_CASE, like \"API_KEY\"",
537            ),
538            (
539                json!({"id": "a", "name": "x", "settings": [{"key": "K", "label": "k", "type": "color"}]}),
540                "byob-plugin.json: settings[0].type must be one of text, number, boolean, directory, file",
541            ),
542            (json!({"id": "a", "name": "x", "mcpServers": {"s": {"url": "ftp://x"}}}), "byob-plugin.json: mcpServers.s.url must start with https://"),
543            (
544                json!({"id": "a", "name": "x", "mcpServers": {"s": {"command": "x", "env": {"A": 1}}}}),
545                "byob-plugin.json: mcpServers.s.env must map names to text",
546            ),
547            (json!({"id": "a", "name": "x", "mcpServers": {"s": {}}}), "byob-plugin.json: mcpServers.s.command must be text"),
548        ];
549        for (raw, want) in cases {
550            assert_eq!(parse_user(raw.clone()).unwrap_err(), want, "for {raw}");
551        }
552    }
553
554    #[test]
555    fn python_tool_and_settings() {
556        let m = parse_user(json!({
557            "id": "text-stats", "name": "Text stats", "permissions": {"network": true},
558            "tools": [{"name": "count_words", "description": "Count words.", "params": {"type": "object", "properties": {"file": {"type": "string"}}}, "run": "tools/count.py", "title": "Counted {file}"}],
559            "settings": [{"key": "API_KEY", "label": "API key", "secret": true, "type": "directory", "multiple": true, "default": ["/a", "/b"]}],
560            "starters": [{"title": "Go", "prompt": "/go", "file": true}],
561            "prompt": "x".repeat(700),
562        }))
563        .unwrap();
564        assert!(m.permissions.network);
565        assert_eq!(m.tools[0].kind, ToolKind::Script("tools/count.py".into()));
566        assert_eq!(m.tools[0].title.as_deref(), Some("Counted {file}"));
567        let s = &m.settings[0];
568        assert!(s.secret && s.multiple && !s.required);
569        assert_eq!(s.kind, SettingKind::Directory);
570        assert_eq!(s.default.as_deref(), Some("/a\n/b"));
571        assert!(m.starters[0].file);
572        assert_eq!(m.prompt.map(|p| p.chars().count()), Some(600));
573    }
574
575    #[test]
576    fn native_tools_for_builtins() {
577        let raw = json!({"id": "code", "name": "Code", "tools": [{"native": "run_python"}]});
578        let m = parse_manifest(&raw, ParseOptions { builtin: true, file: None }).unwrap();
579        assert_eq!(m.tools[0].name, "run_python");
580        assert_eq!(m.tools[0].kind, ToolKind::Native("run_python".into()));
581    }
582
583    #[test]
584    fn server_configs() {
585        let m = parse_user(json!({"id": "a", "name": "x", "mcpServers": {
586            "mem": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-memory"], "env": {"K": "${API_KEY}"}},
587            "lin": {"url": "https://mcp.linear.app/mcp", "headers": {"Authorization": "Bearer ${API_KEY}"}, "oauth": {"clientId": "c"}},
588            "old": {"url": "https://example.com/sse", "type": "sse"},
589        }}))
590        .unwrap();
591        assert!(m.mcp_servers["mem"].is_local());
592        assert!(!m.mcp_servers["lin"].is_local());
593        assert!(matches!(&m.mcp_servers["old"], McpServerConfig::Url { sse: true, .. }));
594        let vals = BTreeMap::from([("API_KEY".to_string(), "abc".to_string())]);
595        match m.mcp_servers["lin"].with_settings(&vals) {
596            McpServerConfig::Url { headers, oauth, .. } => {
597                assert_eq!(headers["Authorization"], "Bearer abc");
598                assert_eq!(oauth.map(|o| o.client_id).as_deref(), Some("c"));
599            }
600            other => panic!("{other:?}"),
601        }
602    }
603
604    #[test]
605    fn placeholders() {
606        let vals = BTreeMap::from([("A".to_string(), "1".to_string())]);
607        assert_eq!(fill_placeholders("${A}-${B}-${A", &vals), "1-${B}-${A");
608        assert_eq!(fill_placeholders("ünï${A}cødé", &vals), "ünï1cødé");
609    }
610
611    #[test]
612    fn inside_paths() {
613        assert!(path_inside("tools/x.py") && path_inside("./a/../b.py"));
614        assert!(!path_inside("../x") && !path_inside("a/../../x") && !path_inside("/x") && !path_inside("C:\\x") && !path_inside("\\x"));
615    }
616}