objectiveai-sdk 2.1.3

ObjectiveAI SDK, definitions, and utilities
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Client-side ObjectiveAI MCP surface declared by an agent.
//!
//! Sits alongside [`super::McpServers`] on every upstream
//! `AgentBase`. Where `mcp_servers` lists full-URL MCP servers the
//! agent will dial out to, this struct declares the
//! ObjectiveAI-managed bits (the built-in `objectiveai-mcp` plus
//! specific plugins / tools by `owner`+`name`+`version`) the agent
//! expects the *calling client* to expose locally back to the API.
//!
//! Content-addressed: the field flows into each upstream's `id()`
//! hash, so swapping in a different plugin reference produces a
//! different agent id.

use indexmap::IndexMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// A single `owner` / `name` / `version` reference identifying one
/// tool inside [`ClientObjectiveaiMcp::tools`]. Plugin references
/// use the larger [`ClientObjectiveaiMcpPluginEntry`] — they carry
/// extra `executable` / `mcp_servers` fields tools don't have.
#[derive(
    Debug,
    Clone,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    JsonSchema,
    arbitrary::Arbitrary,
)]
#[schemars(rename = "agent.ClientObjectiveaiMcpEntry")]
pub struct ClientObjectiveaiMcpEntry {
    pub owner: String,
    pub name: String,
    pub version: String,
}

impl ClientObjectiveaiMcpEntry {
    /// `owner`, `name`, and `version` must all be non-empty.
    pub fn validate(&self) -> Result<(), String> {
        if self.owner.is_empty() {
            return Err("`owner` cannot be empty".into());
        }
        if self.name.is_empty() {
            return Err("`name` cannot be empty".into());
        }
        if self.version.is_empty() {
            return Err("`version` cannot be empty".into());
        }
        Ok(())
    }

    /// LLM-visible tool name. See [`materialize_tool_name`].
    pub fn tool_name(&self) -> String {
        materialize_tool_name(&self.owner, &self.name, &self.version)
    }
}

/// Plugin reference inside [`ClientObjectiveaiMcp::plugins`].
///
/// - `owner` / `name` / `version` identify the plugin (same shape as
///   [`ClientObjectiveaiMcpEntry`]).
/// - `executable` controls whether this plugin contributes a tool
///   to the agent's surface (`true`, default) or is loaded purely
///   for its declared MCP servers (`false`). The API's
///   `X-OBJECTIVEAI-TOOLS-ALLOWED` construction honors this: only
///   `executable = true` plugin entries contribute their `name` to
///   the allow-list.
/// - `mcp_servers` selects which of the plugin's manifest-declared
///   `filesystem::plugins::Manifest::mcp_servers` entries should be
///   exposed to the agent, by `name`. `None` ⇒ none of them.
#[derive(
    Debug,
    Clone,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    JsonSchema,
    arbitrary::Arbitrary,
)]
#[schemars(rename = "agent.ClientObjectiveaiMcpPluginEntry")]
pub struct ClientObjectiveaiMcpPluginEntry {
    pub owner: String,
    pub name: String,
    pub version: String,
    /// `true`: spawn the plugin binary and surface its tools the
    /// usual way. `false`: don't run the plugin; only consume its
    /// declared MCP servers (`mcp_servers` below). Defaults to
    /// `true` so existing declarations keep their current behavior.
    #[serde(default = "default_true")]
    pub executable: bool,
    /// Subset of the plugin's manifest `mcp_servers` to expose, each
    /// referenced by `name` plus an optional `arguments` map. `None`
    /// ⇒ none. Names that aren't present in the plugin's manifest are
    /// rejected when the API asks the CLI to begin them; declarations
    /// themselves don't validate the referent (the plugin may not be
    /// installed at declaration time).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("omitempty" = true))]
    pub mcp_servers: Option<Vec<ClientObjectiveaiMcpPluginMcpServer>>,
}

/// One `mcp_servers` entry on a
/// [`ClientObjectiveaiMcpPluginEntry`]: the manifest-declared `name`
/// the agent wants exposed, plus optional `arguments` the CLI feeds
/// to the plugin alongside the name when bringing the server up. The
/// arguments map is sorted by key in [`prepare`] so two equivalent
/// declarations (same key/value pairs in any order) hash to the same
/// canonical form.
#[derive(
    Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, arbitrary::Arbitrary,
)]
#[schemars(rename = "agent.ClientObjectiveaiMcpPluginMcpServer")]
pub struct ClientObjectiveaiMcpPluginMcpServer {
    /// Author-chosen identifier — must match a `name` in the plugin
    /// manifest's `mcp_servers` list. The CLI feeds this as the
    /// first positional arg when starting the plugin.
    pub name: String,
    /// Optional key→value arguments forwarded to the plugin alongside
    /// `name`. `Some(value)` ⇒ `--key value` on the spawned plugin's
    /// argv; `None` ⇒ a bare `--key` flag with no following token. The
    /// plugin author decides how to interpret them. [`prepare`]
    /// normalizes (`Some("") → None`), sorts the map by key, and
    /// collapses an empty map to `None` so two equivalent declarations
    /// canonicalize to byte-identical JSON.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("omitempty" = true))]
    #[arbitrary(with = crate::arbitrary_util::arbitrary_option_indexmap_string_option_string)]
    pub arguments: Option<IndexMap<String, Option<String>>>,
}

impl PartialOrd for ClientObjectiveaiMcpPluginMcpServer {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ClientObjectiveaiMcpPluginMcpServer {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Compare by name first. `IndexMap` doesn't derive `Ord`, so
        // we walk the entries in iteration order — after `prepare`'s
        // `sort_keys` pass that order is deterministic. `None`
        // arguments sorts before `Some(...)` via the standard
        // `Option<T>::cmp` ordering (so a bare `--flag` sorts before
        // `--flag value`).
        let by_name = self.name.cmp(&other.name);
        if by_name.is_ne() {
            return by_name;
        }
        let a: Option<Vec<(&String, &Option<String>)>> =
            self.arguments.as_ref().map(|m| m.iter().collect());
        let b: Option<Vec<(&String, &Option<String>)>> =
            other.arguments.as_ref().map(|m| m.iter().collect());
        a.cmp(&b)
    }
}

impl ClientObjectiveaiMcpPluginMcpServer {
    /// `name` must be non-empty, and every `arguments` key (if
    /// present) must be non-empty (values may be empty).
    pub fn validate(&self) -> Result<(), String> {
        if self.name.is_empty() {
            return Err("`name` cannot be empty".into());
        }
        if let Some(args) = self.arguments.as_ref() {
            for (k, _) in args {
                if k.is_empty() {
                    return Err("`arguments` key cannot be empty".into());
                }
            }
        }
        Ok(())
    }
}

fn default_true() -> bool {
    true
}

impl ClientObjectiveaiMcpPluginEntry {
    /// `owner`, `name`, and `version` must all be non-empty; each
    /// `mcp_servers[i]` must validate (see
    /// [`ClientObjectiveaiMcpPluginMcpServer::validate`]); and within
    /// one plugin entry, `mcp_servers` must contain no duplicate
    /// `name` values (matches the uniqueness rule the plugin manifest
    /// itself enforces at
    /// `crate::filesystem::plugins::Manifest::validate`).
    pub fn validate(&self) -> Result<(), String> {
        if self.owner.is_empty() {
            return Err("`owner` cannot be empty".into());
        }
        if self.name.is_empty() {
            return Err("`name` cannot be empty".into());
        }
        if self.version.is_empty() {
            return Err("`version` cannot be empty".into());
        }
        if let Some(servers) = self.mcp_servers.as_ref() {
            for entry in servers {
                entry.validate()?;
            }
            for (i, a) in servers.iter().enumerate() {
                for b in &servers[i + 1..] {
                    if a.name == b.name {
                        return Err(format!(
                            "`mcp_servers` contains duplicate name: \"{}\"",
                            a.name
                        ));
                    }
                }
            }
        }
        Ok(())
    }

    /// LLM-visible tool name. See [`materialize_tool_name`].
    pub fn tool_name(&self) -> String {
        materialize_tool_name(&self.owner, &self.name, &self.version)
    }
}

/// Materialize the LLM-visible tool name for an `owner` / `name` /
/// `version` triple: `{owner}-{name}-{version}` with every `.`
/// substituted to `-`. The substitution keeps the result
/// Anthropic-tool-name-regex safe (`^[a-zA-Z0-9_-]{1,128}$`) even
/// when the version field carries semver dots (`1.2.3` -> `1-2-3`).
///
/// Single source of truth shared by [`ClientObjectiveaiMcpEntry::tool_name`],
/// [`crate::filesystem::plugins::Manifest::tool_name`], and
/// [`crate::filesystem::tools::Manifest::tool_name`].
pub fn materialize_tool_name(owner: &str, name: &str, version: &str) -> String {
    format!("{owner}-{name}-{version}").replace('.', "-")
}

/// Client-side MCP surface the agent expects:
///
/// - `objectiveai`: whether the calling client exposes the built-in
///   `objectiveai-mcp`. `None` means unspecified; `Some(true)` /
///   `Some(false)` explicitly opt in / out.
/// - `plugins`: specific plugins (by `owner` / `name` / `version`)
///   plus per-plugin `executable` + `mcp_servers`.
/// - `tools`: specific tools (by `owner` / `name` / `version`).
#[derive(
    Debug,
    Clone,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    JsonSchema,
    arbitrary::Arbitrary,
    Default,
)]
#[schemars(rename = "agent.ClientObjectiveaiMcp")]
pub struct ClientObjectiveaiMcp {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("omitempty" = true))]
    pub objectiveai: Option<bool>,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[schemars(extend("omitempty" = true))]
    pub plugins: Vec<ClientObjectiveaiMcpPluginEntry>,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[schemars(extend("omitempty" = true))]
    pub tools: Vec<ClientObjectiveaiMcpEntry>,
}

impl ClientObjectiveaiMcp {
    /// Snapshot of the three `X-OBJECTIVEAI-MCP-*` request headers a
    /// caller stamps on the initial dial of the objectiveai-mcp
    /// proxy upstream. Per-field rules:
    ///
    /// - `root`: `self.objectiveai.unwrap_or(false)`. `None`
    ///   ("unspecified") is conservatively treated as "do not expose".
    /// - `tools`: copy of `self.tools`, sorted by
    ///   `(owner, name, version)` (the derived
    ///   [`ClientObjectiveaiMcpEntry`] `Ord`).
    /// - `plugins`: `self.plugins` filtered to `executable: true`,
    ///   projected onto `(owner, name, version)` (dropping
    ///   `executable` and `mcp_servers`), then sorted the same way.
    pub fn mcp_headers(&self) -> ClientObjectiveaiMcpHeaders {
        let mut tools = self.tools.clone();
        tools.sort();

        let mut plugins: Vec<ClientObjectiveaiMcpEntry> = self
            .plugins
            .iter()
            .filter(|p| p.executable)
            .map(|p| ClientObjectiveaiMcpEntry {
                owner: p.owner.clone(),
                name: p.name.clone(),
                version: p.version.clone(),
            })
            .collect();
        plugins.sort();

        ClientObjectiveaiMcpHeaders {
            root: self.objectiveai.unwrap_or(false),
            tools,
            plugins,
        }
    }
}

/// Snapshot of the three transient `X-OBJECTIVEAI-MCP-*` request
/// headers an HTTP caller stamps on its initial dial of the
/// objectiveai-mcp proxy upstream.
///
/// Produced by [`ClientObjectiveaiMcp::mcp_headers`] — see that
/// method's doc for the per-field source rules and sort order.
#[derive(
    Debug,
    Clone,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    JsonSchema,
)]
#[schemars(rename = "agent.ClientObjectiveaiMcpHeaders")]
pub struct ClientObjectiveaiMcpHeaders {
    /// Becomes the `X-OBJECTIVEAI-MCP-ROOT` header value verbatim
    /// (`"true"` / `"false"`).
    pub root: bool,
    /// Tools the agent expects the client to expose, sorted by
    /// `(owner, name, version)`. Becomes the
    /// `X-OBJECTIVEAI-MCP-TOOLS` header's JSON payload.
    pub tools: Vec<ClientObjectiveaiMcpEntry>,
    /// Plugins the agent expects the client to expose, filtered to
    /// `executable: true` entries only, projected onto the
    /// `(owner, name, version)` shape, and sorted by
    /// `(owner, name, version)`. Becomes the
    /// `X-OBJECTIVEAI-MCP-PLUGINS` header's JSON payload.
    pub plugins: Vec<ClientObjectiveaiMcpEntry>,
}

impl ClientObjectiveaiMcpHeaders {
    /// Project the three fields onto the canonical
    /// `(header-name, header-value)` pairs an HTTP caller can stamp
    /// directly. Headers are emitted in the order
    /// `ROOT → TOOLS → PLUGINS`; callers that need a map can collect
    /// the returned vec themselves.
    pub fn to_headers(&self) -> Vec<(String, String)> {
        vec![
            (
                "X-OBJECTIVEAI-MCP-ROOT".to_string(),
                if self.root { "true" } else { "false" }.to_string(),
            ),
            (
                "X-OBJECTIVEAI-MCP-TOOLS".to_string(),
                serde_json::to_string(&self.tools)
                    .expect("ClientObjectiveaiMcpEntry always serializes"),
            ),
            (
                "X-OBJECTIVEAI-MCP-PLUGINS".to_string(),
                serde_json::to_string(&self.plugins)
                    .expect("ClientObjectiveaiMcpEntry always serializes"),
            ),
        ]
    }
}

/// Validates the configuration. Each entry's fields must be
/// non-empty, and the `plugins` / `tools` lists each contain no
/// `(owner, name, version)` duplicates. Free-function counterpart to
/// [`super::mcp_servers::validate`].
pub fn validate(this: &ClientObjectiveaiMcp) -> Result<(), String> {
    for entry in &this.plugins {
        entry.validate()?;
    }
    for entry in &this.tools {
        entry.validate()?;
    }
    for (i, a) in this.plugins.iter().enumerate() {
        for b in &this.plugins[i + 1..] {
            if a.owner == b.owner && a.name == b.name && a.version == b.version
            {
                return Err(format!(
                    "`client_objectiveai_mcp.plugins` contains duplicate entry: \"{}/{}@{}\"",
                    a.owner, a.name, a.version,
                ));
            }
        }
    }
    for (i, a) in this.tools.iter().enumerate() {
        for b in &this.tools[i + 1..] {
            if a == b {
                return Err(format!(
                    "`client_objectiveai_mcp.tools` contains duplicate entry: \"{}/{}@{}\"",
                    a.owner, a.name, a.version,
                ));
            }
        }
    }
    Ok(())
}

/// Sorts plugins + tools for deterministic ordering. Per-plugin
/// `mcp_servers` get their inner `arguments` IndexMap key-sorted
/// in place, then the `mcp_servers` Vec is sorted via the
/// [`ClientObjectiveaiMcpPluginMcpServer`] `Ord` impl. Collapses an
/// all-empty struct to `None` so the enclosing `Option` can drop the
/// empty container entirely (same convention as
/// [`super::mcp_servers::prepare`]).
pub fn prepare(mut this: ClientObjectiveaiMcp) -> Option<ClientObjectiveaiMcp> {
    for plugin in &mut this.plugins {
        if let Some(servers) = plugin.mcp_servers.as_mut() {
            for entry in servers.iter_mut() {
                // Normalize each value (`Some("") → None` so an
                // explicit empty string canonicalizes the same way
                // as a missing value — i.e., a bare `--flag`), sort
                // by key, then collapse an empty map to `None` so
                // the canonical form omits the field entirely.
                let drop_empty = match entry.arguments.as_mut() {
                    Some(args) => {
                        for (_, v) in args.iter_mut() {
                            if let Some(s) = v.as_deref() {
                                if s.is_empty() {
                                    *v = None;
                                }
                            }
                        }
                        args.sort_keys();
                        args.is_empty()
                    }
                    None => false,
                };
                if drop_empty {
                    entry.arguments = None;
                }
            }
            servers.sort();
        }
    }
    this.plugins.sort();
    this.tools.sort();
    if this.objectiveai.is_none() && this.plugins.is_empty() && this.tools.is_empty() {
        None
    } else {
        Some(this)
    }
}

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

    fn entry(name: &str, args: &[(&str, Option<&str>)]) -> ClientObjectiveaiMcpPluginMcpServer {
        let arguments = if args.is_empty() {
            None
        } else {
            let mut m = IndexMap::new();
            for (k, v) in args {
                m.insert(k.to_string(), v.map(|s| s.to_string()));
            }
            Some(m)
        };
        ClientObjectiveaiMcpPluginMcpServer {
            name: name.to_string(),
            arguments,
        }
    }

    fn plugin(name: &str, servers: Vec<ClientObjectiveaiMcpPluginMcpServer>) -> ClientObjectiveaiMcpPluginEntry {
        ClientObjectiveaiMcpPluginEntry {
            owner: "o".into(),
            name: name.into(),
            version: "v".into(),
            executable: true,
            mcp_servers: Some(servers),
        }
    }

    fn shell(plugins: Vec<ClientObjectiveaiMcpPluginEntry>) -> ClientObjectiveaiMcp {
        ClientObjectiveaiMcp {
            objectiveai: None,
            plugins,
            tools: vec![],
        }
    }

    #[test]
    fn prepare_sorts_arguments_by_key_so_order_does_not_matter() {
        let a = shell(vec![plugin(
            "p",
            vec![entry("s", &[("b", Some("1")), ("a", Some("2"))])],
        )]);
        let b = shell(vec![plugin(
            "p",
            vec![entry("s", &[("a", Some("2")), ("b", Some("1"))])],
        )]);
        let ap = prepare(a).expect("non-empty after prepare");
        let bp = prepare(b).expect("non-empty after prepare");
        assert_eq!(
            serde_json::to_string(&ap).unwrap(),
            serde_json::to_string(&bp).unwrap(),
            "two declarations with identical key/value pairs in different insertion order must canonicalize to byte-identical JSON",
        );
    }

    #[test]
    fn prepare_sorts_mcp_servers_vec_by_name_then_arguments() {
        let a = shell(vec![plugin(
            "p",
            vec![
                entry("z", &[("a", Some("1"))]),
                entry("a", &[("k", Some("v"))]),
            ],
        )]);
        let ap = prepare(a).expect("non-empty after prepare");
        let servers = ap.plugins[0].mcp_servers.as_ref().unwrap();
        assert_eq!(servers[0].name, "a");
        assert_eq!(servers[1].name, "z");
    }

    #[test]
    fn validate_rejects_duplicate_mcp_server_names_within_plugin() {
        let bad = shell(vec![plugin(
            "p",
            vec![entry("dup", &[]), entry("dup", &[("k", Some("v"))])],
        )]);
        let err = validate(&bad).expect_err("duplicate names must be rejected");
        assert!(err.contains("duplicate name"), "unexpected error: {err}");
    }

    #[test]
    fn validate_rejects_empty_argument_key() {
        let bad = shell(vec![plugin("p", vec![entry("s", &[("", Some("v"))])])]);
        let err = validate(&bad).expect_err("empty argument keys must be rejected");
        assert!(err.contains("`arguments` key"), "unexpected error: {err}");
    }

    #[test]
    fn empty_arguments_round_trip_omits_field() {
        let s = entry("name", &[]);
        let json = serde_json::to_string(&s).unwrap();
        assert!(
            !json.contains("arguments"),
            "absent arguments must be skipped on serialize: {json}"
        );
        let back: ClientObjectiveaiMcpPluginMcpServer = serde_json::from_str(&json).unwrap();
        assert_eq!(back, s);
    }

    #[test]
    fn populated_arguments_round_trip() {
        // Mix of valued and flag-only args.
        let s = entry("name", &[("a", Some("1")), ("debug", None), ("b", Some("2"))]);
        let json = serde_json::to_string(&s).unwrap();
        let back: ClientObjectiveaiMcpPluginMcpServer = serde_json::from_str(&json).unwrap();
        assert_eq!(back, s);
    }

    #[test]
    fn prepare_normalizes_empty_string_value_to_none() {
        // Caller wrote `--debug ""` — prepare must canonicalize that
        // to a bare `--debug` flag (None) so identical declarations
        // hash byte-identically regardless of whether the author
        // wrote `None` or `Some("")`.
        let with_empty = shell(vec![plugin("p", vec![entry("s", &[("debug", Some(""))])])]);
        let prepared = prepare(with_empty).expect("non-empty after prepare");
        let args = prepared.plugins[0].mcp_servers.as_ref().unwrap()[0]
            .arguments
            .as_ref()
            .unwrap();
        assert_eq!(
            args.get("debug").unwrap(),
            &None,
            "Some(\"\") must canonicalize to None"
        );

        // And the canonical JSON for `Some("")` must equal the one
        // for `None`.
        let with_none = shell(vec![plugin("p", vec![entry("s", &[("debug", None)])])]);
        let prepared_none = prepare(with_none).expect("non-empty after prepare");
        assert_eq!(
            serde_json::to_string(&prepared).unwrap(),
            serde_json::to_string(&prepared_none).unwrap(),
        );
    }

    #[test]
    fn prepare_collapses_empty_arguments_to_none() {
        // Caller explicitly supplied `Some(empty map)` — prepare
        // must canonicalize that to `None` so it serializes
        // identically to the absent case.
        let with_empty = ClientObjectiveaiMcp {
            objectiveai: None,
            plugins: vec![ClientObjectiveaiMcpPluginEntry {
                owner: "o".into(),
                name: "p".into(),
                version: "v".into(),
                executable: true,
                mcp_servers: Some(vec![ClientObjectiveaiMcpPluginMcpServer {
                    name: "s".into(),
                    arguments: Some(IndexMap::new()),
                }]),
            }],
            tools: vec![],
        };
        let prepared = prepare(with_empty).expect("non-empty after prepare");
        let arg = &prepared.plugins[0].mcp_servers.as_ref().unwrap()[0].arguments;
        assert!(arg.is_none(), "empty arguments map must canonicalize to None");
    }

    // -------------------------------------------------------------
    // mcp_headers / to_headers
    // -------------------------------------------------------------

    fn entry_triple(owner: &str, name: &str, version: &str) -> ClientObjectiveaiMcpEntry {
        ClientObjectiveaiMcpEntry {
            owner: owner.into(),
            name: name.into(),
            version: version.into(),
        }
    }

    fn plugin_triple(
        owner: &str,
        name: &str,
        version: &str,
        executable: bool,
    ) -> ClientObjectiveaiMcpPluginEntry {
        ClientObjectiveaiMcpPluginEntry {
            owner: owner.into(),
            name: name.into(),
            version: version.into(),
            executable,
            mcp_servers: None,
        }
    }

    #[test]
    fn mcp_headers_root_unwraps_unspecified_to_false() {
        let m = ClientObjectiveaiMcp {
            objectiveai: None,
            plugins: vec![],
            tools: vec![],
        };
        assert!(!m.mcp_headers().root);
    }

    #[test]
    fn mcp_headers_root_unwraps_explicit_true() {
        let m = ClientObjectiveaiMcp {
            objectiveai: Some(true),
            plugins: vec![],
            tools: vec![],
        };
        assert!(m.mcp_headers().root);
    }

    #[test]
    fn mcp_headers_plugins_drop_non_executable() {
        let m = ClientObjectiveaiMcp {
            objectiveai: None,
            plugins: vec![
                plugin_triple("o", "yes", "v", true),
                plugin_triple("o", "no", "v", false),
            ],
            tools: vec![],
        };
        let h = m.mcp_headers();
        assert_eq!(h.plugins, vec![entry_triple("o", "yes", "v")]);
    }

    #[test]
    fn mcp_headers_sorts_owner_then_name_then_version() {
        let m = ClientObjectiveaiMcp {
            objectiveai: None,
            plugins: vec![
                plugin_triple("b", "x", "1", true),
                plugin_triple("a", "y", "2", true),
                plugin_triple("a", "x", "2", true),
                plugin_triple("a", "x", "1", true),
            ],
            tools: vec![
                entry_triple("b", "x", "1"),
                entry_triple("a", "y", "2"),
                entry_triple("a", "x", "2"),
                entry_triple("a", "x", "1"),
            ],
        };
        let h = m.mcp_headers();
        assert_eq!(
            h.tools,
            vec![
                entry_triple("a", "x", "1"),
                entry_triple("a", "x", "2"),
                entry_triple("a", "y", "2"),
                entry_triple("b", "x", "1"),
            ],
        );
        assert_eq!(
            h.plugins,
            vec![
                entry_triple("a", "x", "1"),
                entry_triple("a", "x", "2"),
                entry_triple("a", "y", "2"),
                entry_triple("b", "x", "1"),
            ],
        );
    }

    #[test]
    fn to_headers_emits_canonical_triple() {
        let h = ClientObjectiveaiMcpHeaders {
            root: true,
            tools: vec![entry_triple("a", "b", "c")],
            plugins: vec![],
        };
        assert_eq!(
            h.to_headers(),
            vec![
                ("X-OBJECTIVEAI-MCP-ROOT".to_string(), "true".to_string()),
                (
                    "X-OBJECTIVEAI-MCP-TOOLS".to_string(),
                    r#"[{"owner":"a","name":"b","version":"c"}]"#.to_string(),
                ),
                (
                    "X-OBJECTIVEAI-MCP-PLUGINS".to_string(),
                    "[]".to_string(),
                ),
            ],
        );
    }
}