Skip to main content

objectiveai_sdk/agent/
plugin.rs

1//! Agent-declared plugins — ONE plugin IS ONE MCP server.
2//!
3//! The next-iteration plugin shape: an agent lists the plugins it
4//! uses, each identified by `owner` / `name` / `version`, and each
5//! plugin runs as exactly one MCP server (ultimately a container image
6//! built on the laboratory host it runs on). There is no `executable`
7//! flag and no per-plugin server list — the plugin IS its server.
8//!
9//! Coexists with the legacy [`super::ClientObjectiveaiMcp`]
10//! declaration surface during the transition; the legacy surface will
11//! be deleted once consumers move over.
12//!
13//! Content-addressed: the `plugins` field flows into each upstream's
14//! `id()` hash, so [`prepare`]'s canonicalization (argument
15//! normalization + sorting) is what makes two equivalent declarations
16//! hash identically.
17
18use indexmap::IndexMap;
19use schemars::JsonSchema;
20use serde::{Deserialize, Serialize};
21
22/// One plugin declaration: the plugin's coordinates plus optional
23/// startup arguments for its MCP server.
24///
25/// NOTE: `name` (the repository segment) is slated for removal in a
26/// later iteration of the plugin model; it remains part of the
27/// identity triple for now.
28#[derive(
29    Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, arbitrary::Arbitrary,
30)]
31#[schemars(rename = "agent.Plugin")]
32pub struct Plugin {
33    /// GitHub `<owner>` segment.
34    pub owner: String,
35    /// Repository segment.
36    pub name: String,
37    /// Plugin version.
38    pub version: String,
39    /// Optional key→value arguments handed to the plugin's MCP server
40    /// at startup. Values are free-form JSON: a string behaves as
41    /// `--key value` and `null` as a bare `--key` flag, but an object,
42    /// an array or a number is equally valid and the plugin author
43    /// decides how to interpret them.
44    ///
45    /// [`prepare`] normalizes (an empty STRING becomes `null`, so the
46    /// two spellings of a valueless flag canonicalize together), sorts
47    /// the map by key AND every object key nested inside a value at
48    /// any depth, and collapses an empty map to `None` — so two
49    /// equivalent declarations serialize byte-identically, which is
50    /// what makes an agent id content-addressable. Array element order
51    /// is left alone: that is data, not spelling.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    #[schemars(extend("omitempty" = true))]
54    #[arbitrary(with = crate::arbitrary_util::arbitrary_option_indexmap_string_json_value)]
55    pub arguments: Option<IndexMap<String, serde_json::Value>>,
56}
57
58impl Plugin {
59    /// The total order [`prepare`] sorts by: coordinates first, then
60    /// the arguments as their JSON text.
61    ///
62    /// A KEY rather than an `Ord` impl because `serde_json::Value` is
63    /// neither `Ord` nor `Eq` — it holds `f64`, which has no total
64    /// order — so `Plugin` cannot have one either. Comparing the
65    /// serialized text instead is well-defined and, after
66    /// `prepare`'s `sort_keys` pass, deterministic.
67    ///
68    /// Coordinates are joined with NUL, which cannot appear in any of
69    /// them, so no boundary is ambiguous — `("a", "b/c")` and
70    /// `("a/b", "c")` cannot collide into one key.
71    fn sort_key(&self) -> String {
72        let arguments = self
73            .arguments
74            .as_ref()
75            .and_then(|arguments| serde_json::to_string(arguments).ok())
76            .unwrap_or_default();
77        format!(
78            "{}\0{}\0{}\0{arguments}",
79            self.owner, self.name, self.version,
80        )
81    }
82
83    /// `owner`, `name`, and `version` must all be non-empty; `version`
84    /// must start with `v` — it IS the plugin repo's git tag, Go-modules
85    /// style (`v1.2.3`), byte-for-byte with no rewriting anywhere
86    /// downstream. Every `arguments` key (if present) must be non-empty
87    /// (values may be empty — they canonicalize to bare flags in
88    /// [`prepare`]).
89    pub fn validate(&self) -> Result<(), String> {
90        if self.owner.is_empty() {
91            return Err("`owner` cannot be empty".into());
92        }
93        if self.name.is_empty() {
94            return Err("`name` cannot be empty".into());
95        }
96        if self.version.is_empty() {
97            return Err("`version` cannot be empty".into());
98        }
99        if !self.version.starts_with('v') {
100            return Err(format!(
101                "`version` {:?} must start with 'v' — it is the plugin repo's git tag, Go-modules style (v1.2.3)",
102                self.version,
103            ));
104        }
105        if let Some(args) = self.arguments.as_ref() {
106            for (k, _) in args {
107                if k.is_empty() {
108                    return Err("`arguments` key cannot be empty".into());
109                }
110            }
111        }
112        Ok(())
113    }
114}
115
116/// Validates an agent's `plugins` list: each entry validates, and no
117/// two entries share an `(owner, name, version)` triple — one
118/// instance of a plugin per agent. Free-function counterpart to
119/// [`super::client_objectiveai_mcp::validate`].
120pub fn validate(plugins: &[Plugin]) -> Result<(), String> {
121    for plugin in plugins {
122        plugin.validate()?;
123    }
124    for (i, a) in plugins.iter().enumerate() {
125        for b in &plugins[i + 1..] {
126            if a.owner == b.owner && a.name == b.name && a.version == b.version
127            {
128                return Err(format!(
129                    "`plugins` contains duplicate entry: \"{}/{}@{}\"",
130                    a.owner, a.name, a.version,
131                ));
132            }
133        }
134    }
135    Ok(())
136}
137
138/// Canonicalization pass for an agent's `plugins` list: lowercase
139/// `owner` and `name` (GitHub owner/repo lookups are case-insensitive,
140/// and the laboratory host derives container/image identity from the
141/// lowercased pair; the content-addressing impact of mixed-case
142/// declarations collapsing is accepted). `version` keeps its case —
143/// it maps to a git tag, and git refs are case-SENSITIVE (semver
144/// permits uppercase prerelease identifiers like `v1.2.3-RC1`). Then
145/// normalize each entry's `arguments` (`Some("") → None` values,
146/// key-sort, collapse an empty map to `None`), and sort the list by
147/// `(owner, name, version, arguments)`. The enclosing field uses
148/// `skip_serializing_if = "Vec::is_empty"`, so an empty list needs no
149/// collapse here.
150/// Sort every object key in `value`, at every depth — inside nested
151/// objects and inside arrays alike.
152///
153/// Needed because `serde_json` runs with `preserve_order` here, so a
154/// `Map` keeps INSERTION order: `{"b":1,"a":2}` and `{"a":2,"b":1}`
155/// are equal as data but serialize to different bytes, and the agent
156/// id is a hash of those bytes. Sorting only the TOP level would leave
157/// `{"opts":{"b":1,"a":2}}` uncanonical.
158///
159/// Array ELEMENT order is deliberately untouched: an array is ordered
160/// data, and reordering it would change what the plugin was told, not
161/// just how it was spelled. (This is the difference from the
162/// `deep_sort` in the api tests, which reorders arrays because it
163/// exists to compare two documents ignoring order.)
164fn sort_object_keys(value: &mut serde_json::Value) {
165    match value {
166        serde_json::Value::Object(map) => {
167            for (_, nested) in map.iter_mut() {
168                sort_object_keys(nested);
169            }
170            map.sort_keys();
171        }
172        serde_json::Value::Array(items) => {
173            for item in items {
174                sort_object_keys(item);
175            }
176        }
177        _ => {}
178    }
179}
180
181pub fn prepare(mut plugins: Vec<Plugin>) -> Vec<Plugin> {
182    for plugin in &mut plugins {
183        plugin.owner = plugin.owner.to_lowercase();
184        plugin.name = plugin.name.to_lowercase();
185        let drop_empty = match plugin.arguments.as_mut() {
186            Some(args) => {
187                for (_, v) in args.iter_mut() {
188                    // An empty string and `null` are two spellings of
189                    // the same valueless flag; canonicalize on `null`.
190                    if v.as_str() == Some("") {
191                        *v = serde_json::Value::Null;
192                    }
193                    sort_object_keys(v);
194                }
195                args.sort_keys();
196                args.is_empty()
197            }
198            None => false,
199        };
200        if drop_empty {
201            plugin.arguments = None;
202        }
203    }
204    // By CACHED key: the key serializes the arguments to JSON, so
205    // computing it per comparison would re-serialize every plugin
206    // O(log n) times. `sort_by_cached_key` computes it once each.
207    plugins.sort_by_cached_key(Plugin::sort_key);
208    plugins
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    /// `None` ⇒ JSON null (the bare flag); `Some(s)` ⇒ a JSON string.
216    fn json_value(v: Option<&str>) -> serde_json::Value {
217        match v {
218            Some(s) => serde_json::Value::String(s.to_string()),
219            None => serde_json::Value::Null,
220        }
221    }
222
223    fn plugin(
224        owner: &str,
225        name: &str,
226        version: &str,
227        args: &[(&str, Option<&str>)],
228    ) -> Plugin {
229        let arguments = if args.is_empty() {
230            None
231        } else {
232            let mut m = IndexMap::new();
233            for (k, v) in args {
234                // `None` is the bare flag, i.e. a JSON null.
235                m.insert(k.to_string(), json_value(*v));
236            }
237            Some(m)
238        };
239        Plugin {
240            owner: owner.into(),
241            name: name.into(),
242            version: version.into(),
243            arguments,
244        }
245    }
246
247    #[test]
248    fn prepare_canonicalizes_arguments_and_sorts() {
249        let a = prepare(vec![
250            plugin("b", "x", "1", &[]),
251            plugin("a", "x", "1", &[("z", Some("1")), ("a", Some(""))]),
252        ]);
253        assert_eq!(a[0].owner, "a");
254        let args = a[0].arguments.as_ref().unwrap();
255        // key-sorted, empty-string value normalized to bare flag
256        assert_eq!(
257            args.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
258            vec!["a", "z"],
259        );
260        assert_eq!(args.get("a").unwrap(), &serde_json::Value::Null);
261    }
262
263    /// The point of widening: a value is any JSON, not just a string.
264    #[test]
265    fn arguments_carry_arbitrary_json() {
266        let mut arguments = IndexMap::new();
267        arguments.insert("retries".to_string(), serde_json::json!(3));
268        arguments.insert("verbose".to_string(), serde_json::json!(true));
269        arguments.insert("hosts".to_string(), serde_json::json!(["a", "b"]));
270        arguments.insert("nested".to_string(), serde_json::json!({"k": "v"}));
271        let prepared = prepare(vec![Plugin {
272            owner: "o".into(),
273            name: "n".into(),
274            version: "v1".into(),
275            arguments: Some(arguments),
276        }]);
277        let args = prepared[0].arguments.as_ref().unwrap();
278        assert_eq!(args.get("retries").unwrap(), &serde_json::json!(3));
279        assert_eq!(args.get("hosts").unwrap(), &serde_json::json!(["a", "b"]));
280        assert_eq!(args.get("nested").unwrap(), &serde_json::json!({"k": "v"}));
281        // Still key-sorted.
282        assert_eq!(
283            args.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
284            vec!["hosts", "nested", "retries", "verbose"],
285        );
286    }
287
288    /// Object keys canonicalize at EVERY depth, including inside
289    /// arrays — a top-level-only sort would leave two equal documents
290    /// hashing differently, and the agent id is that hash.
291    #[test]
292    fn prepare_sorts_object_keys_at_every_depth() {
293        let mut arguments = IndexMap::new();
294        arguments.insert(
295            "opts".to_string(),
296            serde_json::json!({"z": 1, "a": {"y": 2, "b": 3}}),
297        );
298        arguments.insert(
299            "list".to_string(),
300            serde_json::json!([{"q": 1, "p": 2}]),
301        );
302        let prepared = prepare(vec![Plugin {
303            owner: "o".into(),
304            name: "n".into(),
305            version: "v1".into(),
306            arguments: Some(arguments),
307        }]);
308        let args = prepared[0].arguments.as_ref().unwrap();
309        assert_eq!(
310            serde_json::to_string(args).unwrap(),
311            r#"{"list":[{"p":2,"q":1}],"opts":{"a":{"b":3,"y":2},"z":1}}"#,
312        );
313    }
314
315    /// Two spellings of the same document canonicalize to identical
316    /// bytes however deeply the difference is buried — which is the
317    /// whole point, since the id is a hash of those bytes.
318    #[test]
319    fn deeply_nested_orderings_canonicalize_identically() {
320        let build = |value: serde_json::Value| {
321            let mut arguments = IndexMap::new();
322            arguments.insert("k".to_string(), value);
323            prepare(vec![Plugin {
324                owner: "o".into(),
325                name: "n".into(),
326                version: "v1".into(),
327                arguments: Some(arguments),
328            }])
329        };
330        let a = build(serde_json::json!({"outer": [{"b": 1, "a": {"d": 2, "c": 3}}]}));
331        let b = build(serde_json::json!({"outer": [{"a": {"c": 3, "d": 2}, "b": 1}]}));
332        assert_eq!(
333            serde_json::to_string(&a).unwrap(),
334            serde_json::to_string(&b).unwrap(),
335        );
336    }
337
338    /// Array ELEMENT order is data, not spelling — canonicalization
339    /// must not touch it.
340    #[test]
341    fn prepare_preserves_array_element_order() {
342        let mut arguments = IndexMap::new();
343        arguments.insert("hosts".to_string(), serde_json::json!(["c", "a", "b"]));
344        let prepared = prepare(vec![Plugin {
345            owner: "o".into(),
346            name: "n".into(),
347            version: "v1".into(),
348            arguments: Some(arguments),
349        }]);
350        assert_eq!(
351            prepared[0].arguments.as_ref().unwrap().get("hosts").unwrap(),
352            &serde_json::json!(["c", "a", "b"]),
353        );
354    }
355
356    /// Sorting is by the serialized text, since JSON values have no
357    /// total order — but it must still be a deterministic one.
358    #[test]
359    fn prepare_orders_same_coordinates_by_arguments() {
360        let a = prepare(vec![
361            plugin("o", "n", "v1", &[("k", Some("b"))]),
362            plugin("o", "n", "v1", &[("k", Some("a"))]),
363        ]);
364        let values: Vec<_> = a
365            .iter()
366            .map(|p| p.arguments.as_ref().unwrap().get("k").unwrap().clone())
367            .collect();
368        assert_eq!(values, vec![serde_json::json!("a"), serde_json::json!("b")]);
369    }
370
371    #[test]
372    fn prepare_collapses_empty_arguments_to_none() {
373        let a = prepare(vec![Plugin {
374            owner: "o".into(),
375            name: "n".into(),
376            version: "1".into(),
377            arguments: Some(IndexMap::new()),
378        }]);
379        assert!(a[0].arguments.is_none());
380    }
381
382    #[test]
383    fn equivalent_declarations_canonicalize_identically() {
384        let a = prepare(vec![plugin(
385            "o",
386            "n",
387            "1",
388            &[("b", Some("1")), ("a", Some("2"))],
389        )]);
390        let b = prepare(vec![plugin(
391            "o",
392            "n",
393            "1",
394            &[("a", Some("2")), ("b", Some("1"))],
395        )]);
396        assert_eq!(
397            serde_json::to_string(&a).unwrap(),
398            serde_json::to_string(&b).unwrap(),
399        );
400    }
401
402    #[test]
403    fn prepare_lowercases_owner_and_name_but_not_version() {
404        let a = prepare(vec![plugin("Acme", "Widgets", "v1.2.3-RC1", &[])]);
405        let b = prepare(vec![plugin("acme", "widgets", "v1.2.3-RC1", &[])]);
406        assert_eq!(a[0].owner, "acme");
407        assert_eq!(a[0].name, "widgets");
408        // version case is PRESERVED — git tags are case-sensitive
409        assert_eq!(a[0].version, "v1.2.3-RC1");
410        assert_eq!(
411            serde_json::to_string(&a).unwrap(),
412            serde_json::to_string(&b).unwrap(),
413        );
414    }
415
416    #[test]
417    fn validate_rejects_duplicate_coordinates() {
418        let err = validate(&[
419            plugin("o", "n", "v1", &[]),
420            plugin("o", "n", "v1", &[("k", Some("v"))]),
421        ])
422        .expect_err("duplicate coordinates must be rejected");
423        assert!(err.contains("duplicate"), "unexpected error: {err}");
424    }
425
426    #[test]
427    fn validate_rejects_empty_fields() {
428        assert!(validate(&[plugin("", "n", "v1", &[])]).is_err());
429        assert!(validate(&[plugin("o", "", "v1", &[])]).is_err());
430        assert!(validate(&[plugin("o", "n", "", &[])]).is_err());
431        assert!(validate(&[plugin("o", "n", "v1", &[("", Some("v"))])]).is_err());
432    }
433
434    /// The version IS the git tag, Go-modules style: it must arrive
435    /// `v`-prefixed — nothing downstream rewrites it.
436    #[test]
437    fn validate_requires_v_prefixed_version() {
438        assert!(validate(&[plugin("o", "n", "1.2.3", &[])]).is_err());
439        // Uppercase `V` is NOT the Go convention — tags are
440        // case-sensitive and the required prefix is lowercase `v`.
441        assert!(validate(&[plugin("o", "n", "V1.2.3", &[])]).is_err());
442        assert!(validate(&[plugin("o", "n", "v1.2.3", &[])]).is_ok());
443        assert!(validate(&[plugin("o", "n", "v1.2.3-RC1", &[])]).is_ok());
444    }
445}