Skip to main content

agentmux_srv_core/backend/
mcp_seed.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Starter MCP Servers catalog seed: preloads a small set of curated global,
5//! credential-free MCP servers (`db_mcp_servers`, the v1 standalone catalog)
6//! on fresh install.
7//!
8//! The actual "run exactly once, ever" gating lives in
9//! `migrations::m0016_seed_starter_mcp_servers`, tracked in the channel's
10//! `db_migrations` table — NOT in this module, and NOT gated on "is the
11//! catalog currently empty" (that gate can't distinguish "never seeded" from
12//! "seeded then the user deleted every starter server on purpose", which
13//! would silently resurrect the defaults on the next restart after a full
14//! deletion (#2141), as the starter-skills seed this was modelled on showed). This
15//! module exposes only the pure insert logic; the migration owns invocation.
16//!
17//! Only credential-free, fully local servers belong in this manifest — see
18//! docs/specs/SPEC_ARMORY_MCP_SERVER_DEFAULT_SEED_CATALOG_2026_07_13.md §2:
19//! every `is_global` MCP server is auto-injected into every agent's
20//! `.mcp.json` at launch with no per-agent opt-in, so a seeded row needing an
21//! API key or OAuth token would break every agent's launch by default. The
22//! Filesystem reference server is deliberately NOT included despite being
23//! credential-free — it requires an allowlisted directory as a CLI arg with
24//! no environment-agnostic default (spec §9 open question 3); it can be
25//! added once that's resolved, either by computing a per-agent default at
26//! config-build time or shipping it with an explicit prereq the user fills
27//! in via the existing catalog-picker mechanism instead.
28//!
29//! **Ids are deterministic, not randomly minted** — same reasoning as
30//! the retired starter-skills seed's ids (keyed on `trigger`), mirrored here for MCP servers via
31//! `entry.name` (there is no separate slug field for a server the way a
32//! skill has `trigger`; `name` already plays that role — it's the catalog
33//! key `mcp_server_upsert_unique_global` enforces uniqueness on). See Phase 1
34//! of `SPEC_DURABLE_BINDINGS_2026_09_10.md`.
35
36use std::sync::Arc;
37
38use serde::Deserialize;
39use uuid::Uuid;
40
41use super::storage::mcp_servers::McpServer;
42use super::storage::store::Store;
43use super::storage::StoreError;
44
45/// One entry in the embedded starter-mcp-servers manifest. `config` is a raw
46/// JSON object here (command/args/env) and gets re-serialized to a string to
47/// match `McpServer.config`'s storage shape.
48#[derive(Debug, Deserialize)]
49struct StarterMcpServer {
50    name: String,
51    transport: String,
52    config: serde_json::Value,
53}
54
55/// The embedded starter-mcp-servers manifest JSON. Content is authored
56/// externally and must not be edited here — see
57/// `crates/srv-core/src/config/starter-mcp-servers.json`.
58const STARTER_MCP_SERVERS_JSON: &str = include_str!("../config/starter-mcp-servers.json");
59
60/// Deterministic row id for a starter MCP server, derived from its `name`.
61/// The retired starter-skills seed derived its ids the same way —
62/// this is the identical derivation keyed on the server's catalog name
63/// instead of a skill's trigger, in its own, distinct namespace so a skill
64/// and an MCP server that happened to share a stable-key string could never
65/// collide on id.
66pub(crate) fn starter_mcp_server_id(name: &str) -> Uuid {
67    let namespace = Uuid::new_v5(&Uuid::NAMESPACE_URL, b"https://agentmux.ai/catalog/mcp-servers/v1");
68    Uuid::new_v5(&namespace, name.as_bytes())
69}
70
71/// True if `name` matches a starter MCP server's `name` in the embedded
72/// manifest. Mirrors the retired starter-skills seed's lookup by name — the
73/// durable-bindings carry-across migration needs
74/// this distinction (recognized starters converge on
75/// [`starter_mcp_server_id`]; everything else keeps first-wins dedup).
76#[cfg(test)]
77pub(crate) fn is_starter_mcp_server_name(name: &str) -> bool {
78    let Ok(manifest) = serde_json::from_str::<Vec<StarterMcpServer>>(STARTER_MCP_SERVERS_JSON) else {
79        return false;
80    };
81    manifest.iter().any(|s| s.name == name)
82}
83
84/// Guard against a manifest-authoring mistake: two entries sharing a `name`.
85/// Mirrors the retired starter-skills seed's duplicate-trigger guard (#3175).
86/// `name` here plays the role `trigger` plays for skills: it is both the
87/// stable key `starter_mcp_server_id` derives from AND the field
88/// `mcp_server_upsert_unique_global`'s own duplicate check is keyed on,
89/// which is exactly the combination that turned "id collision" into
90/// "duplicate-check bypass" for skills.
91fn reject_duplicate_names(manifest: &[StarterMcpServer]) -> Result<(), StoreError> {
92    let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
93    for entry in manifest {
94        if !seen.insert(entry.name.as_str()) {
95            return Err(StoreError::Other(format!(
96                "mcp server seed: manifest has more than one entry named '{}' — \
97                 this is an authoring bug in starter-mcp-servers.json, not a \
98                 runtime condition to recover from",
99                entry.name
100            )));
101        }
102    }
103    Ok(())
104}
105
106/// True if any global MCP server whose name matches a starter entry's name
107/// already exists — i.e. this channel already effectively has the starter
108/// set (or a name collision with it). The caller
109/// (`migrations::m0016_seed_starter_mcp_servers`) uses this to skip seeding
110/// entirely rather than attempting an insert that would collide on
111/// `mcp_server_upsert_unique_global`'s name-uniqueness check and permanently
112/// fail the migration on every subsequent boot — same self-heal
113/// the retired starter-skills seed had (#2144).
114pub(crate) fn any_starter_mcp_server_name_exists(mstore: &Arc<Store>) -> Result<bool, StoreError> {
115    let manifest: Vec<StarterMcpServer> = serde_json::from_str(STARTER_MCP_SERVERS_JSON)
116        .map_err(|e| StoreError::Other(format!("mcp server seed: parse manifest: {e}")))?;
117    // Pre-dates Phase 2 of SPEC_DURABLE_BINDINGS_2026_09_10.md's catalog
118    // redirect.
119    let existing = mstore.mcp_server_list_global(mstore)?;
120    Ok(manifest
121        .iter()
122        .any(|entry| existing.iter().any(|item| item.server.name == entry.name)))
123}
124
125/// Parse the embedded manifest and insert every entry as a global MCP server
126/// via the validated `mcp_server_upsert_unique_global` path. Does NOT check
127/// whether the catalog is already populated — the caller
128/// (`migrations::m0016_seed_starter_mcp_servers`) owns run-once gating via
129/// `db_migrations` tracking, not catalog contents. Exposed at `pub(crate)`
130/// so the migration and tests can call it directly.
131///
132/// All-or-nothing: `mcp_server_upsert_unique_global` commits each insert in
133/// its own transaction, so a mid-loop failure can't be rolled back by the
134/// database itself. If any insert fails, this compensates by deleting every
135/// server already inserted in THIS call before returning the error —
136/// otherwise a retry (the migration framework re-runs `up()` on the next
137/// boot when a migration returns `Err`, since it's never marked applied)
138/// would hit the name-uniqueness rejection on the servers already stranded
139/// from the failed attempt. Modelled on the retired starter-skills
140/// seed (#2141).
141pub(crate) fn seed_starter_mcp_servers(mstore: &Arc<Store>) -> Result<usize, StoreError> {
142    let manifest: Vec<StarterMcpServer> = serde_json::from_str(STARTER_MCP_SERVERS_JSON)
143        .map_err(|e| StoreError::Other(format!("mcp server seed: parse manifest: {e}")))?;
144    reject_duplicate_names(&manifest)?;
145
146    let now = agentmux_common::time::now_ms();
147
148    let mut inserted_ids: Vec<String> = Vec::with_capacity(manifest.len());
149    for entry in &manifest {
150        let config = serde_json::to_string(&entry.config)
151            .map_err(|e| StoreError::Other(format!("mcp server seed: serialize config for '{}': {e}", entry.name)))?;
152        let server = McpServer {
153            id: starter_mcp_server_id(&entry.name).to_string(),
154            name: entry.name.clone(),
155            transport: entry.transport.clone(),
156            config,
157            is_global: true,
158            created_at: now,
159            updated_at: now,
160        };
161        if let Err(e) = mstore.mcp_server_upsert_unique_global(&server, &crate::backend::rpc::actor::Actor::Srv.label()) {
162            for id in &inserted_ids {
163                if let Err(cleanup_err) = mstore.mcp_server_delete(mstore, id) {
164                    tracing::error!(
165                        "mcp server seed: cleanup after partial failure could not remove {id}: {cleanup_err}"
166                    );
167                }
168            }
169            return Err(e);
170        }
171        inserted_ids.push(server.id);
172    }
173
174    Ok(inserted_ids.len())
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    fn starter(name: &str) -> StarterMcpServer {
182        StarterMcpServer {
183            name: name.to_string(),
184            transport: "stdio".to_string(),
185            config: serde_json::json!({"command": "true"}),
186        }
187    }
188
189    #[test]
190    fn reject_duplicate_names_fails_loudly_on_a_colliding_manifest() {
191        // (#3175) Mirrors the retired starter-skills seed's test. See
192        // reject_duplicate_names's own doc comment for the mechanism.
193        let manifest = vec![starter("dup"), starter("dup")];
194        let err = reject_duplicate_names(&manifest).unwrap_err();
195        assert!(format!("{err}").contains("dup"), "error must name the offending server: {err}");
196    }
197
198    #[test]
199    fn reject_duplicate_names_accepts_the_real_manifest() {
200        let manifest: Vec<StarterMcpServer> = serde_json::from_str(STARTER_MCP_SERVERS_JSON).unwrap();
201        assert!(reject_duplicate_names(&manifest).is_ok());
202    }
203
204    #[test]
205    fn starter_mcp_server_ids_are_identical_across_two_independently_seeded_stores() {
206        // Mirrors the retired starter-skills seed's test — the property Phase 1 of
207        // SPEC_DURABLE_BINDINGS_2026_09_10.md exists for.
208        let store_a = Arc::new(Store::open_in_memory().unwrap());
209        let store_b = Arc::new(Store::open_in_memory().unwrap());
210
211        seed_starter_mcp_servers(&store_a).unwrap();
212        seed_starter_mcp_servers(&store_b).unwrap();
213
214        let mut ids_a: Vec<(String, String)> = store_a
215            .mcp_server_list_global(&store_a)
216            .unwrap()
217            .into_iter()
218            .map(|item| (item.server.name, item.server.id))
219            .collect();
220        let mut ids_b: Vec<(String, String)> = store_b
221            .mcp_server_list_global(&store_b)
222            .unwrap()
223            .into_iter()
224            .map(|item| (item.server.name, item.server.id))
225            .collect();
226        ids_a.sort();
227        ids_b.sort();
228
229        assert_eq!(ids_a.len(), 6);
230        assert_eq!(ids_a, ids_b, "the same starter server must get the same id in every store");
231    }
232
233    #[test]
234    fn seeds_six_mcp_servers_into_an_empty_catalog() {
235        let mstore = Arc::new(Store::open_in_memory().unwrap());
236        assert!(mstore.mcp_server_list_global(&mstore).unwrap().is_empty());
237
238        let created = seed_starter_mcp_servers(&mstore).unwrap();
239
240        assert_eq!(created, 6);
241        let after = mstore.mcp_server_list_global(&mstore).unwrap();
242        assert_eq!(after.len(), 6, "all six starter MCP servers should be seeded");
243        assert!(after.iter().all(|item| item.server.is_global));
244        assert!(
245            after.iter().all(|item| item.server.transport == "stdio"),
246            "every Tier A entry is a local stdio process"
247        );
248    }
249
250    #[test]
251    fn seeded_config_round_trips_as_valid_json() {
252        let mstore = Arc::new(Store::open_in_memory().unwrap());
253        seed_starter_mcp_servers(&mstore).unwrap();
254
255        let after = mstore.mcp_server_list_global(&mstore).unwrap();
256        let git = after
257            .iter()
258            .find(|item| item.server.name == "git")
259            .expect("git should be seeded");
260        let parsed: serde_json::Value = serde_json::from_str(&git.server.config).unwrap();
261        assert_eq!(parsed["command"], "uvx");
262        assert_eq!(parsed["args"][0], "mcp-server-git");
263    }
264
265    #[test]
266    fn a_failed_insert_rolls_back_the_ones_already_seeded_this_call() {
267        // Same failure mode as the retired starter-skills seed's test (#2141):
268        // mcp_server_upsert_unique_global commits each
269        // insert in its own transaction, so a mid-loop failure can't be
270        // rolled back by the database. Simulate it by pre-inserting a global
271        // server whose NAME collides with one of the starter entries — this
272        // forces seed_starter_mcp_servers to fail partway through the
273        // manifest, and the catalog must end up back at exactly the one
274        // pre-existing server, not a stranded partial starter set.
275        let mstore = Arc::new(Store::open_in_memory().unwrap());
276        let now = agentmux_common::time::now_ms();
277
278        // "fetch" is the second entry in the manifest — colliding on it
279        // guarantees at least one successful insert ("git") precedes the
280        // failure, so the rollback path actually has something to clean up.
281        let colliding = McpServer {
282            id: "pre-existing-collision".to_string(),
283            name: "fetch".to_string(),
284            transport: "stdio".to_string(),
285            config: "{}".to_string(),
286            is_global: true,
287            created_at: now,
288            updated_at: now,
289        };
290        mstore.mcp_server_upsert_unique_global(&colliding, "test").unwrap();
291
292        let result = seed_starter_mcp_servers(&mstore);
293        assert!(result.is_err(), "seeding must fail when a name collides");
294
295        let after = mstore.mcp_server_list_global(&mstore).unwrap();
296        assert_eq!(
297            after.len(),
298            1,
299            "a failed seed must roll back every server it inserted this call, leaving only the pre-existing one"
300        );
301        assert_eq!(after[0].server.id, "pre-existing-collision");
302    }
303
304    #[test]
305    fn any_starter_mcp_server_name_exists_detects_a_collision_without_inserting() {
306        let mstore = Arc::new(Store::open_in_memory().unwrap());
307        assert!(!any_starter_mcp_server_name_exists(&mstore).unwrap());
308
309        let now = agentmux_common::time::now_ms();
310        let user_created = McpServer {
311            id: "user-server".to_string(),
312            name: "memory".to_string(),
313            transport: "stdio".to_string(),
314            config: "{}".to_string(),
315            is_global: true,
316            created_at: now,
317            updated_at: now,
318        };
319        mstore.mcp_server_upsert_unique_global(&user_created, "test").unwrap();
320
321        assert!(any_starter_mcp_server_name_exists(&mstore).unwrap());
322        assert_eq!(
323            mstore.mcp_server_list_global(&mstore).unwrap().len(),
324            1,
325            "the check itself must not insert anything"
326        );
327    }
328}