symforge 7.30.0

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini 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
//! `HarnessRegistry` — the catalog of known MCP clients and the per-client
//! logic to detect / add / refresh a SymForge **HTTP attach** entry (the `004
//! serve` URL + Bearer key) in each client's config.
//!
//! This factors the client-path knowledge already encoded in
//! [`crate::cli::init`] (`InitPaths`, `claude_desktop_config_path`,
//! `read_config_text`) rather than re-deriving it. The existing `init` flow
//! writes **stdio** (`command`) entries that launch the local binary; this
//! module writes **HTTP** entries (`url` + `Authorization: Bearer`) that attach
//! a client to an already-running `symforge serve`.
//!
//! All transforms here are pure (config-text in → config-text out, no I/O); the
//! backup-then-write machinery lives in [`crate::cli::harness_apply`].

use std::path::{Path, PathBuf};

use anyhow::Context;
use serde_json::{Value, json};
use toml_edit::{DocumentMut, Item, Table, value};

use crate::cli::init::{claude_desktop_config_path, read_config_text};

/// The MCP server entry name written into every client config.
pub const SYMFORGE_SERVER_NAME: &str = "symforge";

/// Stable identifier for a known harness target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HarnessId {
    ClaudeCode,
    ClaudeDesktop,
    Codex,
    Gemini,
    KiloCode,
    Cursor,
}

impl HarnessId {
    pub fn slug(self) -> &'static str {
        match self {
            HarnessId::ClaudeCode => "claude",
            HarnessId::ClaudeDesktop => "claude-desktop",
            HarnessId::Codex => "codex",
            HarnessId::Gemini => "gemini",
            HarnessId::KiloCode => "kilo-code",
            HarnessId::Cursor => "cursor",
        }
    }

    pub fn display_name(self) -> &'static str {
        match self {
            HarnessId::ClaudeCode => "Claude Code",
            HarnessId::ClaudeDesktop => "Claude Desktop",
            HarnessId::Codex => "Codex",
            HarnessId::Gemini => "Gemini CLI",
            HarnessId::KiloCode => "Kilo Code",
            HarnessId::Cursor => "Cursor",
        }
    }
}

/// On-disk config shape for a harness target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HarnessFormat {
    /// `mcpServers.symforge` JSON object (Claude Code/Desktop, Gemini, Kilo,
    /// Cursor).
    Json,
    /// `[mcp_servers.symforge]` TOML table (Codex).
    Toml,
}

/// The SymForge attach entry: the `004 serve` URL + optional Bearer key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttachEntry {
    pub url: String,
    pub bearer_key: Option<String>,
}

impl AttachEntry {
    pub fn new(url: impl Into<String>, bearer_key: Option<String>) -> Self {
        let bearer_key = bearer_key.filter(|k| !k.is_empty());
        Self {
            url: url.into(),
            bearer_key,
        }
    }
}

/// A known MCP client and how its SymForge attach entry is expressed.
#[derive(Debug, Clone)]
pub struct HarnessTarget {
    pub id: HarnessId,
    pub config_path: PathBuf,
    pub format: HarnessFormat,
}

/// Per-client scan result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HarnessState {
    /// Client not detected on the host (config directory absent).
    NotInstalled,
    /// Config present (or its directory exists) but no `symforge` entry.
    Absent,
    /// A `symforge` entry exists and matches the target URL + key.
    PresentCurrent,
    /// A `symforge` entry exists but its URL or key differs from the target.
    PresentStale,
    /// Config exists but does not parse; never overwritten.
    Malformed(String),
}

/// A `HarnessTarget` paired with its current scan state.
#[derive(Debug, Clone)]
pub struct HarnessStatus {
    pub id: HarnessId,
    pub config_path: PathBuf,
    pub format: HarnessFormat,
    pub state: HarnessState,
}

/// The catalog of known harness targets resolved against a host.
#[derive(Debug, Clone)]
pub struct HarnessRegistry {
    targets: Vec<HarnessTarget>,
}

impl HarnessRegistry {
    /// Build the registry for the current host, mirroring the path knowledge in
    /// [`crate::cli::init`] (`InitPaths::from_home_working_dir_*`).
    pub fn known() -> anyhow::Result<Self> {
        let home = dirs::home_dir().context("cannot determine home directory")?;
        let working_dir =
            std::env::current_dir().context("cannot determine current working directory")?;
        Ok(Self::known_with(&home, &working_dir))
    }

    /// Test/injection seam: build the registry against explicit home and
    /// working directories. The Claude Desktop path uses the same resolver
    /// (`claude_desktop_config_path`) the init flow uses.
    pub fn known_with(home: &Path, working_dir: &Path) -> Self {
        let desktop = claude_desktop_config_path(home, None);
        let targets = vec![
            HarnessTarget {
                id: HarnessId::ClaudeCode,
                config_path: home.join(".claude.json"),
                format: HarnessFormat::Json,
            },
            HarnessTarget {
                id: HarnessId::ClaudeDesktop,
                config_path: desktop,
                format: HarnessFormat::Json,
            },
            HarnessTarget {
                id: HarnessId::Codex,
                config_path: home.join(".codex").join("config.toml"),
                format: HarnessFormat::Toml,
            },
            HarnessTarget {
                id: HarnessId::Gemini,
                config_path: home.join(".gemini").join("settings.json"),
                format: HarnessFormat::Json,
            },
            HarnessTarget {
                id: HarnessId::KiloCode,
                config_path: working_dir.join(".kilocode").join("mcp.json"),
                format: HarnessFormat::Json,
            },
            HarnessTarget {
                id: HarnessId::Cursor,
                config_path: home.join(".cursor").join("mcp.json"),
                format: HarnessFormat::Json,
            },
        ];
        Self { targets }
    }

    /// Build a registry from an explicit target list (test seam for fixtures).
    pub fn from_targets(targets: Vec<HarnessTarget>) -> Self {
        Self { targets }
    }

    pub fn targets(&self) -> &[HarnessTarget] {
        &self.targets
    }

    /// Report, per client, whether the SymForge attach entry is absent,
    /// present-current, present-stale, or the client is not installed /
    /// malformed. BOM-safe via the shared `read_config_text`.
    pub fn scan(&self, desired: &AttachEntry) -> Vec<HarnessStatus> {
        self.targets
            .iter()
            .map(|t| HarnessStatus {
                id: t.id,
                config_path: t.config_path.clone(),
                format: t.format,
                state: scan_target(t, desired),
            })
            .collect()
    }
}

/// Resolve the scan state for one target against the desired attach entry.
fn scan_target(target: &HarnessTarget, desired: &AttachEntry) -> HarnessState {
    if !target.config_path.exists() {
        // The client is considered installed only if its config directory
        // exists; otherwise it is NotInstalled (never create in the wrong
        // place). The directory existing but the file missing means the client
        // is installed but has no SymForge entry yet (Absent).
        return match target.config_path.parent() {
            Some(parent) if parent.exists() => HarnessState::Absent,
            _ => HarnessState::NotInstalled,
        };
    }

    let text = match read_config_text(&target.config_path) {
        Ok(text) => text,
        Err(e) => return HarnessState::Malformed(e.to_string()),
    };

    let existing = match target.format {
        HarnessFormat::Json => read_json_entry(&text),
        HarnessFormat::Toml => read_toml_entry(&text),
    };

    match existing {
        Err(e) => HarnessState::Malformed(e),
        Ok(None) => HarnessState::Absent,
        Ok(Some(found)) => {
            if found == *desired {
                HarnessState::PresentCurrent
            } else {
                HarnessState::PresentStale
            }
        }
    }
}

/// Extract the current SymForge attach entry from a JSON `mcpServers` config, if
/// present. Returns `Err` if the document does not parse.
fn read_json_entry(text: &str) -> Result<Option<AttachEntry>, String> {
    let trimmed = text.trim();
    let config: Value = if trimmed.is_empty() {
        json!({})
    } else {
        serde_json::from_str(text).map_err(|e| e.to_string())?
    };

    let entry = config
        .get("mcpServers")
        .and_then(|m| m.get(SYMFORGE_SERVER_NAME));
    let Some(entry) = entry else {
        return Ok(None);
    };

    let url = entry
        .get("url")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();
    let bearer_key = entry
        .get("headers")
        .and_then(|h| h.get("Authorization"))
        .and_then(Value::as_str)
        .and_then(strip_bearer)
        .map(str::to_string);

    Ok(Some(AttachEntry { url, bearer_key }))
}

/// Extract the current SymForge attach entry from a Codex TOML config, if
/// present. Returns `Err` if the document does not parse.
fn read_toml_entry(text: &str) -> Result<Option<AttachEntry>, String> {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }
    let doc = text.parse::<DocumentMut>().map_err(|e| e.to_string())?;

    let entry = doc
        .get("mcp_servers")
        .and_then(Item::as_table)
        .and_then(|t| t.get(SYMFORGE_SERVER_NAME))
        .and_then(Item::as_table);
    let Some(entry) = entry else {
        return Ok(None);
    };

    let url = entry
        .get("url")
        .and_then(Item::as_str)
        .unwrap_or_default()
        .to_string();
    let bearer_key = entry
        .get("bearer_token")
        .and_then(Item::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string);

    Ok(Some(AttachEntry { url, bearer_key }))
}

fn strip_bearer(header: &str) -> Option<&str> {
    header
        .strip_prefix("Bearer ")
        .map(str::trim)
        .filter(|s| !s.is_empty())
}

// ---------------------------------------------------------------------------
// Pure add/refresh transforms (config-in → config-out, no I/O)
// ---------------------------------------------------------------------------

/// Apply the desired attach entry to a config's text, returning the rewritten
/// config. Pure: no filesystem access. De-dups any pre-existing SymForge
/// entries to a single refreshed one and preserves the rest of the document.
///
/// `existing_text` is `None` when the config file does not exist yet (a fresh
/// document is created in the client's expected shape).
pub fn apply_attach_entry(
    format: HarnessFormat,
    existing_text: Option<&str>,
    entry: &AttachEntry,
) -> anyhow::Result<String> {
    match format {
        HarnessFormat::Json => apply_json(existing_text, entry),
        HarnessFormat::Toml => apply_toml(existing_text, entry),
    }
}

fn apply_json(existing_text: Option<&str>, entry: &AttachEntry) -> anyhow::Result<String> {
    let mut config: Value = match existing_text {
        Some(text) if !text.trim().is_empty() => {
            serde_json::from_str(text).context("parsing client JSON config")?
        }
        _ => json!({}),
    };

    if !config["mcpServers"].is_object() {
        config["mcpServers"] = json!({});
    }

    let mut server = json!({
        "type": "http",
        "url": entry.url,
    });
    if let Some(key) = &entry.bearer_key {
        server["headers"] = json!({ "Authorization": format!("Bearer {key}") });
    }

    // Single-keyed `mcpServers.symforge` object — a fresh insert overwrites any
    // prior value, so re-apply is naturally de-duped (there can be only one key
    // of that name in a JSON object).
    config["mcpServers"][SYMFORGE_SERVER_NAME] = server;

    let mut pretty = serde_json::to_string_pretty(&config)?;
    pretty.push('\n');
    Ok(pretty)
}

fn apply_toml(existing_text: Option<&str>, entry: &AttachEntry) -> anyhow::Result<String> {
    let mut doc: DocumentMut = match existing_text {
        Some(text) if !text.trim().is_empty() => text
            .parse::<DocumentMut>()
            .context("parsing Codex TOML config")?,
        _ => DocumentMut::new(),
    };

    if !doc.as_table().contains_key("mcp_servers") || !doc["mcp_servers"].is_table() {
        doc["mcp_servers"] = Item::Table(Table::new());
    }
    let mcp_servers = doc["mcp_servers"]
        .as_table_mut()
        .expect("mcp_servers is a table");

    // Replace any prior entry wholesale (de-dup to one current entry).
    let mut server = Table::new();
    server["url"] = value(entry.url.clone());
    if let Some(key) = &entry.bearer_key {
        server["bearer_token"] = value(key.clone());
    }
    mcp_servers.insert(SYMFORGE_SERVER_NAME, Item::Table(server));

    Ok(doc.to_string())
}

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

    fn entry() -> AttachEntry {
        AttachEntry::new("http://127.0.0.1:8787/mcp", Some("sf_key_123".to_string()))
    }

    #[test]
    fn json_absent_adds_entry() {
        let out = apply_json(Some("{}"), &entry()).unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(
            v["mcpServers"]["symforge"]["url"],
            "http://127.0.0.1:8787/mcp"
        );
        assert_eq!(
            v["mcpServers"]["symforge"]["headers"]["Authorization"],
            "Bearer sf_key_123"
        );
        assert_eq!(v["mcpServers"]["symforge"]["type"], "http");
    }

    #[test]
    fn json_preserves_siblings() {
        let input = r#"{"mcpServers":{"other":{"command":"x"}},"numStartups":3}"#;
        let out = apply_json(Some(input), &entry()).unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["mcpServers"]["other"]["command"], "x");
        assert_eq!(v["numStartups"], 3);
        assert!(v["mcpServers"]["symforge"].is_object());
    }

    #[test]
    fn json_stale_refreshes_no_dup() {
        let input = r#"{"mcpServers":{"symforge":{"type":"http","url":"http://old/mcp","headers":{"Authorization":"Bearer old"}}}}"#;
        let out = apply_json(Some(input), &entry()).unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(
            v["mcpServers"]["symforge"]["url"],
            "http://127.0.0.1:8787/mcp"
        );
        // Exactly one symforge key (JSON objects cannot duplicate keys).
        let servers = v["mcpServers"].as_object().unwrap();
        assert_eq!(servers.keys().filter(|k| *k == "symforge").count(), 1);
    }

    #[test]
    fn json_keyless_omits_headers() {
        let e = AttachEntry::new("http://127.0.0.1:8787/mcp", None);
        let out = apply_json(Some("{}"), &e).unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert!(v["mcpServers"]["symforge"]["headers"].is_null());
    }

    #[test]
    fn json_apply_is_idempotent() {
        let once = apply_json(Some("{}"), &entry()).unwrap();
        let twice = apply_json(Some(&once), &entry()).unwrap();
        assert_eq!(once, twice);
    }

    #[test]
    fn toml_absent_adds_entry() {
        let out = apply_toml(Some("model = \"gpt-5\"\n"), &entry()).unwrap();
        let doc = out.parse::<DocumentMut>().unwrap();
        assert_eq!(
            doc["mcp_servers"]["symforge"]["url"].as_str().unwrap(),
            "http://127.0.0.1:8787/mcp"
        );
        assert_eq!(
            doc["mcp_servers"]["symforge"]["bearer_token"]
                .as_str()
                .unwrap(),
            "sf_key_123"
        );
        // Preserves the unrelated top-level key.
        assert_eq!(doc["model"].as_str().unwrap(), "gpt-5");
    }

    #[test]
    fn toml_preserves_other_servers() {
        let input = "[mcp_servers.other]\ncommand = \"x\"\n";
        let out = apply_toml(Some(input), &entry()).unwrap();
        let doc = out.parse::<DocumentMut>().unwrap();
        assert_eq!(
            doc["mcp_servers"]["other"]["command"].as_str().unwrap(),
            "x"
        );
        assert!(doc["mcp_servers"]["symforge"].is_table());
    }

    #[test]
    fn toml_apply_is_idempotent() {
        let once = apply_toml(None, &entry()).unwrap();
        let twice = apply_toml(Some(&once), &entry()).unwrap();
        assert_eq!(once, twice);
    }

    #[test]
    fn read_json_entry_roundtrip() {
        let out = apply_json(Some("{}"), &entry()).unwrap();
        let read = read_json_entry(&out).unwrap().unwrap();
        assert_eq!(read, entry());
    }

    #[test]
    fn read_toml_entry_roundtrip() {
        let out = apply_toml(None, &entry()).unwrap();
        let read = read_toml_entry(&out).unwrap().unwrap();
        assert_eq!(read, entry());
    }

    #[test]
    fn read_json_entry_absent_is_none() {
        assert!(read_json_entry("{}").unwrap().is_none());
        assert!(read_json_entry("").unwrap().is_none());
    }

    #[test]
    fn read_json_entry_malformed_errors() {
        assert!(read_json_entry("{ not json").is_err());
    }
}