agent-commander 0.7.0

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
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
//! Shared launch options and their native tool capabilities.

use serde_json::Value;

/// Launch options shared by every tool
#[derive(Debug, Clone, Default)]
pub struct LaunchOptions {
    /// Native reasoning effort / variant level (`--reasoning-effort`)
    pub reasoning_effort: Option<String>,
    /// Native output token budget (`--max-output-tokens`)
    pub max_output_tokens: Option<u64>,
    /// Native sampling temperature (`--temperature`)
    pub temperature: Option<f64>,
    /// MCP servers: config file path or inline `{"mcpServers": {...}}` JSON
    pub mcp_config: Option<String>,
    /// Use only the servers from `mcp_config`
    pub strict_mcp_config: bool,
    /// Extra directories the agent may access (`--add-dir`)
    pub additional_directories: Vec<String>,
    /// Files attached to the prompt (`--attach`): Codex `--image`, OpenCode
    /// `--file`. Relative paths resolve against the working directory.
    pub attachments: Vec<String>,
    /// JSON Schema text the final answer must match (`--json-schema`):
    /// Claude and Qwen `--json-schema`, Codex `--output-schema`. The result
    /// is reported as `metadata.structured_output`.
    pub json_schema: Option<String>,
    /// File holding `json_schema` (written by [`crate::Agent::start`] so the
    /// schema does not appear on the command line; issue #60). Codex reads it
    /// with `--output-schema <file>`, Qwen with `--json-schema @<file>` and
    /// Claude through `--json-schema "$(cat <file>)"`.
    pub json_schema_file: Option<String>,
    /// Claude `--system-prompt-file` (replaces the inline `--system-prompt`)
    pub system_prompt_file: Option<String>,
    /// Claude `--append-system-prompt-file` (replaces the inline
    /// `--append-system-prompt`)
    pub append_system_prompt_file: Option<String>,
    /// Route the tool through an API gateway (`--gateway-base-url` /
    /// `--gateway-router` with `--gateway-token-env`; claude, codex, agent, opencode)
    pub gateway: Option<GatewayOptions>,
}

/// An API gateway for one run (issue #65).
///
/// Exactly one of `base_url` (used as is) or `router` (a link-assistant/router
/// origin; the tool's service path is appended), plus `token_env`, the
/// variable holding the token. Only the
/// variable name reaches the command line; the tool reads the value from its
/// environment, which always inherits `token_env`.
///
/// `standalone_web_search` says the gateway serves Codex's standalone search
/// route (`POST <base_url>/alpha/search`, issue #74); `None` means `true`
/// with `router` (link-assistant/router serves it) and `false` with
/// `base_url`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GatewayOptions {
    pub base_url: Option<String>,
    pub router: Option<String>,
    pub token_env: String,
    pub standalone_web_search: Option<bool>,
}

impl GatewayOptions {
    /// A gateway reached at `base_url` as is.
    pub fn with_base_url(base_url: impl Into<String>, token_env: impl Into<String>) -> Self {
        Self {
            base_url: Some(base_url.into()),
            router: None,
            token_env: token_env.into(),
            standalone_web_search: None,
        }
    }

    /// A link-assistant/router origin; each tool appends its service path.
    pub fn with_router(router: impl Into<String>, token_env: impl Into<String>) -> Self {
        Self {
            base_url: None,
            router: Some(router.into()),
            token_env: token_env.into(),
            standalone_web_search: None,
        }
    }

    /// Declare whether the gateway serves Codex's standalone search route.
    #[must_use]
    pub fn with_standalone_web_search(mut self, enabled: bool) -> Self {
        self.standalone_web_search = Some(enabled);
        self
    }

    /// Whether the gateway serves Codex's standalone search route: the
    /// explicit setting, else `true` for a router origin.
    pub fn serves_standalone_web_search(&self) -> bool {
        self.standalone_web_search
            .unwrap_or_else(|| self.router.is_some())
    }
}

/// Paths of the link-assistant/router service per tool.
pub const ROUTER_SERVICE_PATHS: &[(&str, &str)] = &[
    ("claude", "/api/services/anthropic"),
    ("codex", "/api/services/codex/v1"),
    ("agent", "/api/services/openai/v1"),
    ("opencode", "/api/services/openai/v1"),
];

/// Codex provider id used for the gateway; Codex does not let `-c` redefine
/// its built-in ids (`openai`, `ollama`, ...).
pub const CODEX_GATEWAY_PROVIDER_ID: &str = "agent_commander_gateway";

/// Credentials Claude Code prefers over `apiKeyHelper` (cloud providers,
/// `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_API_KEY`); removed with `env -u`.
pub const CLAUDE_GATEWAY_UNSET_ENV: &[&str] = &[
    "ANTHROPIC_AUTH_TOKEN",
    "ANTHROPIC_API_KEY",
    "CLAUDE_CODE_USE_BEDROCK",
    "CLAUDE_CODE_USE_VERTEX",
    "CLAUDE_CODE_USE_FOUNDRY",
];

/// Validate a gateway URL: http(s), a host, and no credentials, query,
/// fragment or whitespace, so no secret can reach the command line.
/// Trailing slashes are removed.
fn normalize_gateway_url(value: &str, name: &str) -> Result<String, String> {
    let error = || format!("{name} must be an http(s) URL without credentials, query or fragment");
    let lower = value.to_ascii_lowercase();
    let rest = if lower.starts_with("https://") {
        &value[8..]
    } else if lower.starts_with("http://") {
        &value[7..]
    } else {
        return Err(error());
    };
    let authority = rest.split('/').next().unwrap_or_default();
    let host = authority
        .rsplit_once(':')
        .map_or(authority, |(host, _)| host);
    if host.is_empty()
        || authority.contains('@')
        || value.contains('?')
        || value.contains('#')
        || value.chars().any(char::is_whitespace)
    {
        return Err(error());
    }
    Ok(value.trim_end_matches('/').to_string())
}

/// Validate a gateway and resolve its base URL for `tool`. With `router`,
/// the base URL is `None` when the tool has no router service path.
///
/// # Errors
/// Returns the message for a missing or duplicate URL, an invalid URL or an
/// invalid `token_env`.
pub fn normalize_gateway(
    gateway: &GatewayOptions,
    tool: Option<&str>,
) -> Result<GatewayOptions, String> {
    if gateway.base_url.is_some() == gateway.router.is_some() {
        return Err(
            "gateway needs exactly one of baseUrl (--gateway-base-url) or router (--gateway-router)"
                .to_string(),
        );
    }
    if !crate::tools::shell::is_valid_env_name(&gateway.token_env) {
        return Err("gateway.tokenEnv (--gateway-token-env) must name an environment variable ([A-Za-z_][A-Za-z0-9_]*)".to_string());
    }
    let router = gateway
        .router
        .as_deref()
        .map(|url| normalize_gateway_url(url, "gateway.router (--gateway-router)"))
        .transpose()?;
    let base_url = match (&router, tool) {
        (Some(origin), Some(tool)) => ROUTER_SERVICE_PATHS
            .iter()
            .find(|(name, _)| *name == tool)
            .map(|(_, path)| format!("{origin}{path}")),
        _ => gateway
            .base_url
            .as_deref()
            .map(|url| normalize_gateway_url(url, "gateway.baseUrl (--gateway-base-url)"))
            .transpose()?,
    };
    Ok(GatewayOptions {
        base_url,
        router,
        token_env: gateway.token_env.clone(),
        standalone_web_search: Some(gateway.serves_standalone_web_search()),
    })
}

/// Fail when the gateway token variable is missing or empty in the child
/// environment `env` (issue #65).
///
/// # Errors
/// Returns an error naming the variable.
pub fn check_gateway_token(
    gateway: Option<&GatewayOptions>,
    env: &[(String, String)],
) -> Result<(), String> {
    match gateway {
        Some(gateway)
            if !env
                .iter()
                .any(|(key, value)| key == &gateway.token_env && !value.is_empty()) =>
        {
            Err(format!(
                "gateway.tokenEnv: environment variable {} is not set or empty",
                gateway.token_env
            ))
        }
        _ => Ok(()),
    }
}

/// Resolve the gateway base URL and token variable for `tool`.
///
/// # Errors
/// Returns the validation message, or names the tool when it has no router
/// service path.
pub fn resolve_gateway(gateway: &GatewayOptions, tool: &str) -> Result<(String, String), String> {
    let normalized = normalize_gateway(gateway, Some(tool))?;
    match normalized.base_url {
        Some(base_url) => Ok((base_url, normalized.token_env)),
        None => Err(format!(
            "Tool \"{tool}\" has no link-assistant/router service path; pass gateway.baseUrl (--gateway-base-url) instead."
        )),
    }
}

/// Claude Code `--settings` value: `apiKeyHelper` prints the token from the
/// named variable, so only the variable name is on the command line.
pub fn claude_gateway_settings(token_env: &str) -> String {
    serde_json::json!({ "apiKeyHelper": format!("printenv {token_env}") }).to_string()
}

/// Codex `-c` overrides defining and selecting a custom provider whose
/// bearer token Codex reads from `env_key`.
///
/// With `standalone_web_search`, the provider also declares
/// `supports_standalone_web_search = true` (issue #74). Codex sends no hosted
/// `web_search` tool to a Responses Lite model; it installs the standalone
/// `web.run` tool (`POST <base_url>/alpha/search`) only for the built-in
/// OpenAI provider or a provider with that flag (openai/codex rust-v0.172.0
/// `core/src/tools/spec_plan.rs`, `ext/web-search/src/extension.rs`).
pub fn codex_gateway_overrides(
    base_url: &str,
    token_env: &str,
    standalone_web_search: bool,
) -> Vec<String> {
    let prefix = format!("model_providers.{CODEX_GATEWAY_PROVIDER_ID}");
    let toml = |value: &str| Value::String(value.to_string()).to_string();
    let mut overrides = vec![
        format!("model_provider={}", toml(CODEX_GATEWAY_PROVIDER_ID)),
        format!("{prefix}.name={}", toml("agent-commander gateway")),
        format!("{prefix}.base_url={}", toml(base_url)),
        format!("{prefix}.env_key={}", toml(token_env)),
        format!("{prefix}.wire_api={}", toml("responses")),
    ];
    if standalone_web_search {
        overrides.push(format!("{prefix}.supports_standalone_web_search=true"));
    }
    overrides
}

impl PartialEq for LaunchOptions {
    fn eq(&self, other: &Self) -> bool {
        let Self {
            reasoning_effort,
            max_output_tokens,
            temperature,
            mcp_config,
            strict_mcp_config,
            additional_directories,
            attachments,
            json_schema,
            json_schema_file,
            system_prompt_file,
            append_system_prompt_file,
            gateway,
        } = self;
        // Even a NaN constructed before launch validation must equal itself.
        let same_temperature = match (*temperature, other.temperature) {
            (None, None) => true,
            (Some(a), Some(b)) => {
                a.partial_cmp(&b).is_some_and(std::cmp::Ordering::is_eq)
                    || (a.is_nan() && b.is_nan())
            }
            _ => false,
        };
        same_temperature
            && reasoning_effort == &other.reasoning_effort
            && max_output_tokens == &other.max_output_tokens
            && mcp_config == &other.mcp_config
            && strict_mcp_config == &other.strict_mcp_config
            && additional_directories == &other.additional_directories
            && attachments == &other.attachments
            && json_schema == &other.json_schema
            && json_schema_file == &other.json_schema_file
            && system_prompt_file == &other.system_prompt_file
            && append_system_prompt_file == &other.append_system_prompt_file
            && gateway == &other.gateway
    }
}

impl Eq for LaunchOptions {}

/// What a tool natively supports among the launch options
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LaunchCapabilities {
    pub reasoning_effort: bool,
    /// Documented effort levels; `None` when the tool or provider defines them
    pub reasoning_efforts: Option<&'static [&'static str]>,
    /// Whether the tool has a native per-launch output token budget.
    pub max_output_tokens: bool,
    /// Whether the tool has a native per-launch temperature setting.
    pub temperature: bool,
    pub mcp_config: bool,
    pub strict_mcp_config: bool,
    pub additional_directories: bool,
    pub attachments: bool,
    pub json_schema: bool,
    /// Whether the tool can be routed through an API gateway (`gateway`)
    pub gateway: bool,
    /// Whether the controller can enforce an attached run deadline.
    pub timeout: bool,
}

/// Claude Code `--effort` levels
pub const CLAUDE_REASONING_EFFORTS: &[&str] = &["low", "medium", "high", "xhigh", "max"];

/// Codex `model_reasoning_effort` levels
pub const CODEX_REASONING_EFFORTS: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh"];

const TOOLS: &[&str] = &["claude", "codex", "opencode", "agent", "gemini", "qwen"];

pub(crate) const MAX_OUTPUT_TOKENS_ERROR: &str =
    "--max-output-tokens must be a positive safe integer";
pub(crate) const TEMPERATURE_ERROR: &str = "--temperature must be a finite non-negative number";

pub(crate) fn validate_max_output_tokens(value: u64) -> Result<(), &'static str> {
    // Match JavaScript's exact integer range across the two APIs.
    if (1..=9_007_199_254_740_991).contains(&value) {
        Ok(())
    } else {
        Err(MAX_OUTPUT_TOKENS_ERROR)
    }
}

pub(crate) fn validate_temperature(value: f64) -> Result<(), &'static str> {
    if value.is_finite() && value >= 0.0 {
        Ok(())
    } else {
        Err(TEMPERATURE_ERROR)
    }
}

/// Describe what a tool natively supports among the launch options.
pub fn launch_capabilities(tool: &str) -> LaunchCapabilities {
    // gemini 0.64, opencode 1.19 and agent 0.26 have no schema flag.
    let (effort, efforts, mcp, strict, dirs, attachments, json_schema) = match tool {
        "claude" => (
            true,
            Some(CLAUDE_REASONING_EFFORTS),
            true,
            true,
            true,
            false,
            true,
        ),
        "codex" => (
            true,
            Some(CODEX_REASONING_EFFORTS),
            true,
            false,
            true,
            true,
            true,
        ),
        // `--variant` names are defined by the model provider.
        "opencode" => (true, None, false, false, false, true, false),
        "gemini" => (false, None, false, false, true, false, false),
        "qwen" => (false, None, true, false, true, false, true),
        _ => (false, None, false, false, false, false, false),
    };
    LaunchCapabilities {
        reasoning_effort: effort,
        reasoning_efforts: efforts,
        max_output_tokens: matches!(tool, "claude" | "opencode"),
        temperature: tool == "agent",
        mcp_config: mcp,
        strict_mcp_config: strict,
        additional_directories: dirs,
        attachments,
        json_schema,
        gateway: matches!(tool, "claude" | "codex" | "agent" | "opencode"),
        timeout: true,
    }
}

/// Check that every requested launch option has a native control in the tool.
///
/// # Errors
/// Returns the message naming the tools that do support the option.
pub fn check_launch_options_supported(tool: &str, launch: &LaunchOptions) -> Result<(), String> {
    check_launch_options_against(tool, launch, &launch_capabilities(tool))
}

/// Check the requested launch options against the given capabilities, such
/// as a `ToolOverrides::launch_capabilities` replacement.
///
/// # Errors
/// Returns the message naming the tools that do support the option.
pub fn check_launch_options_against(
    tool: &str,
    launch: &LaunchOptions,
    capabilities: &LaunchCapabilities,
) -> Result<(), String> {
    type Pick = fn(&LaunchCapabilities) -> bool;
    if let Some(value) = launch.max_output_tokens {
        validate_max_output_tokens(value)?;
    }
    if let Some(value) = launch.temperature {
        validate_temperature(value)?;
    }
    if let Some(gateway) = &launch.gateway {
        normalize_gateway(gateway, Some(tool))?;
    }
    let checks: [(bool, Pick, &str); 9] = [
        (
            launch.max_output_tokens.is_some(),
            |c| c.max_output_tokens,
            "an output token budget (--max-output-tokens)",
        ),
        (
            launch.temperature.is_some(),
            |c| c.temperature,
            "sampling temperature (--temperature)",
        ),
        (
            launch.reasoning_effort.is_some(),
            |c| c.reasoning_effort,
            "reasoning effort (--reasoning-effort)",
        ),
        (
            launch.mcp_config.is_some(),
            |c| c.mcp_config,
            "MCP server configuration (--mcp-config)",
        ),
        (
            launch.strict_mcp_config,
            |c| c.strict_mcp_config,
            "strict MCP configuration (--strict-mcp-config)",
        ),
        (
            !launch.additional_directories.is_empty(),
            |c| c.additional_directories,
            "additional directories (--add-dir)",
        ),
        (
            !launch.attachments.is_empty(),
            |c| c.attachments,
            "file attachments (--attach)",
        ),
        (
            launch.json_schema.is_some(),
            |c| c.json_schema,
            "structured output (--json-schema)",
        ),
        (
            launch.gateway.is_some(),
            |c| c.gateway,
            "an API gateway (--gateway-base-url / --gateway-router)",
        ),
    ];
    for (requested, pick, label) in checks {
        if requested && !pick(capabilities) {
            let supporting: Vec<&str> = TOOLS
                .iter()
                .copied()
                .filter(|name| pick(&launch_capabilities(name)))
                .collect();
            return Err(format!(
                "Tool \"{}\" does not support {}. Choose one of: {}; or omit the option.",
                tool,
                label,
                supporting.join(", ")
            ));
        }
    }
    Ok(())
}

/// Validate a reasoning effort / variant name.
///
/// # Panics
/// Panics when the level contains characters other than `[A-Za-z0-9_-]`.
pub fn normalize_reasoning_effort(reasoning_effort: &str) -> String {
    assert!(
        !reasoning_effort.is_empty()
            && reasoning_effort
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
        "Invalid reasoning effort \"{}\". Use a level name such as low, medium or high.",
        reasoning_effort
    );
    reasoning_effort.to_string()
}

/// Validate the JSON Schema the final answer must match and return it as
/// compact JSON text.
///
/// A top-level `$schema` dialect declaration is dropped (issue #68): Claude
/// Code validates the schema with Ajv's default draft-07 instance, which
/// rejects the draft 2020-12 meta-schema URI that zod 4 emits ("no schema
/// with key or ref"). The dialect declaration carries no constraint, so every
/// tool receives the schema without it; nested `$schema` keys are kept.
///
/// # Panics
/// Panics when the text is not JSON or not a JSON object.
pub fn json_schema_arg(json_schema: &str) -> String {
    let mut schema: Value = serde_json::from_str(json_schema)
        .unwrap_or_else(|error| panic!("jsonSchema is not valid JSON: {error}"));
    let Some(object) = schema.as_object_mut() else {
        panic!("jsonSchema must be a JSON Schema object or its JSON text");
    };
    object.remove("$schema");
    schema.to_string()
}

fn push_paths(args: &mut Vec<String>, flag: &str, paths: &[String], name: &str) {
    for path in paths {
        assert!(!path.is_empty(), "{name} must not be empty");
        args.push(flag.to_string());
        args.push(path.clone());
    }
}

/// Push `flag value` for each extra directory.
pub fn push_directories(args: &mut Vec<String>, flag: &str, directories: &[String]) {
    push_paths(args, flag, directories, "additional directories");
}

/// Push `flag file` for each attachment; a repeated flag keeps variadic
/// flags (Codex `--image`, OpenCode `--file`) from swallowing other values.
pub fn push_attachments(args: &mut Vec<String>, flag: &str, attachments: &[String]) {
    push_paths(args, flag, attachments, "attachments");
}

/// Encode a TOML key segment (bare when possible, quoted otherwise).
fn toml_key(key: &str) -> String {
    if !key.is_empty()
        && key
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        key.to_string()
    } else {
        Value::String(key.to_string()).to_string()
    }
}

/// Encode a JSON value as an inline TOML value. JSON string escapes are a
/// subset of TOML basic-string escapes, so strings reuse JSON encoding.
///
/// # Errors
/// Returns an error for `null` at the top level.
pub fn to_toml_value(value: &Value) -> Result<String, String> {
    match value {
        Value::String(_) | Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
        Value::Array(items) => {
            let parts: Result<Vec<String>, String> = items.iter().map(to_toml_value).collect();
            Ok(format!("[{}]", parts?.join(", ")))
        }
        Value::Object(map) => {
            let mut parts = Vec::new();
            for (key, item) in map.iter().filter(|(_, item)| !item.is_null()) {
                parts.push(format!("{} = {}", toml_key(key), to_toml_value(item)?));
            }
            Ok(format!("{{{}}}", parts.join(", ")))
        }
        Value::Null => Err("Cannot encode null as a TOML value".to_string()),
    }
}

/// Translate a Claude-style `{"mcpServers": {...}}` JSON document into one
/// Codex `-c mcp_servers={...}` override.
///
/// `headers` becomes `http_headers`
/// and the transport `type` is dropped (Codex infers it from `command` or
/// `url`). Codex merges the table into the servers from `config.toml`.
///
/// # Errors
/// Returns an error for a file path, invalid JSON or a missing `mcpServers`.
pub fn codex_mcp_servers_override(mcp_config: &str) -> Result<String, String> {
    if !mcp_config.trim_start().starts_with('{') {
        return Err("Tool \"codex\" takes MCP servers as config overrides, not a file path. Pass mcpConfig as inline JSON.".to_string());
    }
    let config: Value = serde_json::from_str(mcp_config)
        .map_err(|error| format!("Invalid mcpConfig JSON: {error}"))?;
    let servers = config
        .get("mcpServers")
        .and_then(Value::as_object)
        .ok_or_else(|| "mcpConfig must contain an mcpServers object".to_string())?;
    let mut table = serde_json::Map::new();
    for (name, server) in servers {
        let mut server = server
            .as_object()
            .cloned()
            .ok_or_else(|| format!("MCP server \"{name}\" must be an object"))?;
        server.remove("type");
        if let Some(headers) = server.remove("headers") {
            server.insert("http_headers".to_string(), headers);
        }
        table.insert(name.clone(), Value::Object(server));
    }
    Ok(format!(
        "mcp_servers={}",
        to_toml_value(&Value::Object(table))?
    ))
}