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