Skip to main content

agentmux_srv_core/backend/storage/
mcp_servers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Standalone MCP Server primitives (v1 composable model).
5//!
6//! Agents reference servers via db_agent_mcp_ref. The `config` field stores
7//! the full server object JSON (command/args/env for stdio; url/headers for
8//! SSE) that gets merged into `.mcp.json` at agent launch.
9
10use std::collections::HashMap;
11
12use rusqlite::params;
13use serde::{Deserialize, Serialize};
14
15use super::error::StoreError;
16use crate::backend::audience::{Audience, HostCap, RuntimeCaps};
17use super::managed::{ManagedResource, Owner};
18use super::mcp_origin::{McpBinding, McpOrigin, UNKNOWN};
19use super::store::Store;
20
21/// Words in the name of an `env` or `headers` entry that say its value is a secret.
22const SECRET_WORDS: [&str; 9] = ["token", "key", "secret", "password", "passwd", "auth", "credential", "bearer", "cookie"];
23
24/// A server config's secret `env` and `headers` values (an entry whose name holds a word of [`SECRET_WORDS`]) are never
25/// written into a transcript (`transcript::withhold`). A header
26/// value that starts with a scheme word (`Bearer abc`) is withheld as it is and without the word.
27pub(crate) fn withhold_secrets_of(config: &str) {
28    let Ok(config) = serde_json::from_str::<serde_json::Value>(config) else { return };
29    for section in ["env", "headers"] {
30        let Some(entries) = config.get(section).and_then(|v| v.as_object()) else { continue };
31        for (name, value) in entries {
32            let name = name.to_ascii_lowercase();
33            if !SECRET_WORDS.iter().any(|w| name.contains(w)) {
34                continue;
35            }
36            let Some(value) = value.as_str() else { continue };
37            crate::backend::transcript::withhold::register(value);
38            if let Some((scheme, rest)) = value.trim().split_once(' ') {
39                if scheme.chars().all(|c| c.is_ascii_alphabetic()) {
40                    crate::backend::transcript::withhold::register(rest);
41                }
42            }
43        }
44    }
45}
46
47/// A standalone MCP Server primitive (v1 composable model).
48#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
49#[ts(export, export_to = "../../../frontend/types/rpc/")]
50pub struct McpServer {
51    pub id: String,
52    pub name: String,
53    pub transport: String,
54    pub config: String,
55    pub is_global: bool,
56    #[ts(type = "number")]
57    pub created_at: i64,
58    #[ts(type = "number")]
59    pub updated_at: i64,
60}
61
62impl Store {
63    /// Drop every skill and MCP ref belonging to `bundle_id`. Bundles no
64    /// longer carry MCP servers (`m0036_drop_bundle_mcp`), but an older build
65    /// sharing the channel can still write a bundle MCP ref, so those go too.
66    ///
67    /// Call after deleting the bundle itself. `bundle_delete` lives on the
68    /// store that owns `db_bundles`, which does not have the ref tables at all
69    /// — they sit beside the catalog tables they key into — so the cleanup
70    /// cannot happen inside it and has to be driven from the handler, where
71    /// both stores are in scope. Without it a deleted bundle leaves its refs
72    /// behind, and a future bundle reusing that id would inherit them.
73    ///
74    /// Returns `(skill_refs_removed, mcp_refs_removed)`.
75    pub fn bundle_unbind_all_components(&self, bundle_id: &str) -> Result<(usize, usize), StoreError> {
76        let skills = self
77            .managed_unbind_all_for_bundle::<super::skills::Skill>(bundle_id)?;
78        let mcp = self.managed_unbind_all_for_bundle::<McpServer>(bundle_id)?;
79        Ok((skills, mcp))
80    }
81}
82
83impl ManagedResource for McpServer {
84    const TABLE: &'static str = "db_mcp_servers";
85    const REF_COL: &'static str = "mcp_id";
86    const AGENT_REF_TABLE: &'static str = "db_agent_mcp_ref";
87    // Still defined, so an older build on the same channel finds it, but
88    // nothing reads it: bundles don't carry MCP servers
89    // (`SPEC_BUNDLE_CONTENTS_MEMORY_NOT_MCP_2026_10_07.md` §3.1).
90    const BUNDLE_REF_TABLE: &'static str = "db_bundle_mcp_ref";
91    const COLUMNS: &'static [&'static str] =
92        &["id", "name", "transport", "config", "is_global", "created_at", "updated_at"];
93    const UPDATE_COLUMNS: &'static [&'static str] = &["name", "transport", "config", "updated_at"];
94    const NAME_NOUN: &'static str = "server";
95    const ARTICLE_NOUN: &'static str = "an MCP server";
96    const KIND: &'static str = "MCP server";
97
98    fn from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
99        Ok(McpServer {
100            id: row.get(0)?,
101            name: row.get(1)?,
102            transport: row.get(2)?,
103            config: row.get(3)?,
104            is_global: row.get::<_, i64>(4)? != 0,
105            created_at: row.get(5)?,
106            updated_at: row.get(6)?,
107        })
108    }
109    fn values(&self) -> Vec<rusqlite::types::Value> {
110        use rusqlite::types::Value;
111        vec![
112            Value::Text(self.id.clone()),
113            Value::Text(self.name.clone()),
114            Value::Text(self.transport.clone()),
115            Value::Text(self.config.clone()),
116            Value::Integer(if self.is_global { 1 } else { 0 }),
117            Value::Integer(self.created_at),
118            Value::Integer(self.updated_at),
119        ]
120    }
121    fn id(&self) -> &str {
122        &self.id
123    }
124    fn name(&self) -> &str {
125        &self.name
126    }
127    fn is_global(&self) -> bool {
128        self.is_global
129    }
130    fn updated_at(&self) -> i64 {
131        self.updated_at
132    }
133}
134
135/// `mcp_server_list`'s response shape: the server plus whether the requesting
136/// agent specifically holds a `db_agent_mcp_ref` row for it. A global server
137/// is always visible to every agent (see the query below), but `is_global`
138/// alone can't tell the UI whether *this* agent has bound it — without
139/// `bound_to_agent`, bind/unbind in the per-agent modal has no way to render
140/// as a stateful toggle (see docs/specs, "bound to me" gap tracked in #1960).
141#[derive(Debug, Clone, Serialize, ts_rs::TS)]
142#[ts(export, export_to = "../../../frontend/types/rpc/")]
143pub struct McpServerListItem {
144    #[serde(flatten)]
145    pub server: McpServer,
146    #[serde(flatten)]
147    pub origin: McpOrigin,
148    pub bound_to_agent: bool,
149    /// Who bound it to this agent (`unknown` when not recorded); empty when this agent has not bound it.
150    pub bound_by: String,
151    /// When, epoch milliseconds; 0 when not bound or not recorded.
152    #[ts(type = "number")]
153    pub bound_at: i64,
154}
155
156/// `mcp_server_list_global`'s response shape: the server plus how many
157/// agents currently hold a `db_agent_mcp_ref` to it — Connectors → MCP servers'
158/// "used by N agents" count (gap #2 of #1960).
159#[derive(Debug, Clone, Serialize, ts_rs::TS)]
160#[ts(export, export_to = "../../../frontend/types/rpc/")]
161pub struct McpServerCatalogItem {
162    #[serde(flatten)]
163    pub server: McpServer,
164    #[serde(flatten)]
165    pub origin: McpOrigin,
166    /// The agents it is bound to, with who bound each and when.
167    pub bindings: Vec<McpBinding>,
168    #[ts(type = "number")]
169    pub bound_count: i64,
170    /// Reaches every agent, not only the bound ones (`McpServerReach`).
171    pub all_agents: bool,
172    /// Container agents get it too.
173    pub in_containers: bool,
174}
175
176/// Who a catalog (global) server reaches beyond its binds, from
177/// `db_mcp_server_reach`. The default, no row, is "only the agents it is
178/// bound to, and no container agent".
179/// `SPEC_CONNECTORS_MCP_WHAT_AGENTS_RUN_2026_10_10.md` §2.1.
180#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
181#[ts(export, export_to = "../../../frontend/types/rpc/")]
182pub struct McpServerReach {
183    pub all_agents: bool,
184    pub in_containers: bool,
185}
186
187impl McpServerReach {
188    /// Which runtimes get the server: a catalog server is usually a host command, so unless it is
189    /// switched on for containers it is for agents that can run one.
190    pub fn audience(&self) -> Audience {
191        if self.in_containers {
192            Audience::Everyone
193        } else {
194            Audience::NativeOnly(HostCap::Exec, "a catalog server is usually a host command; switch it on for container agents in Connectors")
195        }
196    }
197}
198
199/// A server with who added it and, when `bound_to_agent`, who bound it to this agent.
200fn list_item(
201    server: McpServer,
202    bound_to_agent: bool,
203    origins: &HashMap<String, McpOrigin>,
204    bindings: &HashMap<String, (String, i64)>,
205) -> McpServerListItem {
206    let origin = origins.get(&server.id).cloned().unwrap_or_default();
207    let (bound_by, bound_at) = match bindings.get(&server.id) {
208        Some((by, at)) if bound_to_agent => (by.clone(), *at),
209        _ => (String::new(), 0),
210    };
211    McpServerListItem { server, origin, bound_to_agent, bound_by, bound_at }
212}
213
214impl Store {
215    /// List all MCP servers visible to an agent: own (referenced) + global,
216    /// each annotated with whether this specific agent holds the bind ref.
217    pub fn mcp_server_list(&self, catalog: &Store, agent_id: &str) -> Result<Vec<McpServerListItem>, StoreError> {
218        let origins = catalog.mcp_origin_all()?;
219        let bindings = self.mcp_bindings_of_agent(agent_id)?;
220        Ok(self
221            .managed_list::<McpServer>(catalog, Owner::Agent, agent_id)?
222            .into_iter()
223            .map(|(server, bound_to_agent)| list_item(server, bound_to_agent, &origins, &bindings))
224            .collect())
225    }
226
227    /// Every MCP server an agent launches with, on both launch paths
228    /// (`agent.open` and the picker's `writeagentconfig`): its own private
229    /// servers, plus the catalog servers bound to it or switched on for all
230    /// agents. A container agent gets only the catalog servers switched on
231    /// for containers: a catalog server is usually a host command. Its own
232    /// servers are delivered as configured. Not its bundles': a bundle
233    /// carries no MCP servers
234    /// (`SPEC_BUNDLE_CONTENTS_MEMORY_NOT_MCP_2026_10_07.md` §3.1).
235    /// `SPEC_CONNECTORS_MCP_WHAT_AGENTS_RUN_2026_10_10.md` §2.1.
236    pub fn effective_mcp_servers(&self, catalog: &Store, agent_id: &str, container: bool) -> Vec<McpServer> {
237        let reach = catalog.mcp_server_reach_all().unwrap_or_default();
238        self.mcp_server_list(catalog, agent_id)
239            .unwrap_or_default()
240            .into_iter()
241            .filter(|item| {
242                if !item.server.is_global {
243                    return true;
244                }
245                let r = reach.get(&item.server.id).copied().unwrap_or_default();
246                (item.bound_to_agent || r.all_agents) && r.audience().permits(RuntimeCaps::of(container))
247            })
248            .map(|item| item.server)
249            .inspect(|server| withhold_secrets_of(&server.config))
250            .collect()
251    }
252
253    /// Every catalog server's reach switches, by server id. Call on the
254    /// catalog store (the identity store), where `db_mcp_server_reach` sits
255    /// beside `db_mcp_servers`.
256    pub fn mcp_server_reach_all(&self) -> Result<HashMap<String, McpServerReach>, StoreError> {
257        let conn = self.conn.lock().unwrap();
258        let mut stmt = conn.prepare("SELECT mcp_id, all_agents, in_containers FROM db_mcp_server_reach")?;
259        let rows = stmt.query_map([], |row| {
260            Ok((
261                row.get::<_, String>(0)?,
262                McpServerReach { all_agents: row.get::<_, i64>(1)? != 0, in_containers: row.get::<_, i64>(2)? != 0 },
263            ))
264        })?;
265        let mut out = HashMap::new();
266        for r in rows {
267            let (id, reach) = r?;
268            out.insert(id, reach);
269        }
270        Ok(out)
271    }
272
273    /// Set a catalog server's reach switches. Call on the catalog store; the
274    /// caller checks the server is a global row.
275    pub fn mcp_server_set_reach(&self, mcp_id: &str, reach: McpServerReach, now_ms: i64) -> Result<(), StoreError> {
276        self.conn.lock().unwrap().execute(
277            "INSERT INTO db_mcp_server_reach (mcp_id, all_agents, in_containers, updated_at)
278             VALUES (?1, ?2, ?3, ?4)
279             ON CONFLICT(mcp_id) DO UPDATE SET
280                all_agents = excluded.all_agents,
281                in_containers = excluded.in_containers,
282                updated_at = excluded.updated_at",
283            params![mcp_id, reach.all_agents as i64, reach.in_containers as i64, now_ms],
284        )?;
285        Ok(())
286    }
287
288    /// List every GLOBAL MCP server — Connectors → MCP servers. Unlike
289    /// `mcp_server_list`, this takes no `agent_id` and never includes an
290    /// agent's private servers; it backs the window-scoped `mcp.catalog.*`
291    /// MuxAPI (no `check_s1`, so there is no agent context to scope by).
292    /// Each row carries `bound_count` — how many agents currently hold a
293    /// `db_agent_mcp_ref` to it — per SPEC_V1_MCP_SKILLS_PRIMITIVES_2026_06_30.md
294    /// §8 ("used by N agents"), tracked as gap #2 of #1960.
295    pub fn mcp_server_list_global(&self, catalog: &Store) -> Result<Vec<McpServerCatalogItem>, StoreError> {
296        let reach = catalog.mcp_server_reach_all()?;
297        let origins = catalog.mcp_origin_all()?;
298        let mut bindings = self.mcp_bindings_by_server()?;
299        Ok(self
300            .managed_list_global::<McpServer>(catalog)?
301            .into_iter()
302            .map(|(server, bound_count)| {
303                let r = reach.get(&server.id).copied().unwrap_or_default();
304                let origin = origins.get(&server.id).cloned().unwrap_or_default();
305                let bindings = bindings.remove(&server.id).unwrap_or_default();
306                McpServerCatalogItem { server, origin, bindings, bound_count, all_agents: r.all_agents, in_containers: r.in_containers }
307            })
308            .collect())
309    }
310
311    /// Catalog-tier sibling of `mcp_server_list` (above) — same
312    /// `bound_to_agent` shape, but deliberately GLOBAL ROWS ONLY, unlike
313    /// `mcp_server_list`'s UNION with `agent_id`'s own private servers.
314    /// Backs `mcp.catalog.list_for_agent`, which — like every other
315    /// `mcp.catalog.*` command — has no `check_s1`, so `agent_id` here is
316    /// caller-supplied and unverified. Returning private server rows (whose
317    /// `config` can carry secrets: API keys, auth headers, env vars) for an
318    /// arbitrary caller-chosen `agent_id` would let any window connection
319    /// read any agent's private server config. Global rows carry no
320    /// per-agent secret — they're already fully visible via
321    /// `mcp_server_list_global` (Connectors → MCP servers) — so exposing them
322    /// alongside a caller-chosen agent's bind status is safe.
323    /// reagentx P0 on PR #2329.
324    pub fn mcp_server_list_global_for_agent(&self, catalog: &Store, agent_id: &str) -> Result<Vec<McpServerListItem>, StoreError> {
325        let origins = catalog.mcp_origin_all()?;
326        let bindings = self.mcp_bindings_of_agent(agent_id)?;
327        Ok(self
328            .managed_list_global_for_agent::<McpServer>(catalog, agent_id)?
329            .into_iter()
330            .map(|(server, bound_to_agent)| list_item(server, bound_to_agent, &origins, &bindings))
331            .collect())
332    }
333
334    /// Get a standalone MCP server by id.
335    pub fn mcp_server_get(&self, id: &str) -> Result<Option<McpServer>, StoreError> {
336        self.managed_get::<McpServer>(id)
337    }
338
339    /// Delete a standalone MCP server and purge ref rows (both agent- and
340    /// bundle-level — FK cascades may be off on some builds, same reasoning
341    /// as `skill_delete`). Returns true if deleted.
342    pub fn mcp_server_delete(&self, catalog: &Store, id: &str) -> Result<bool, StoreError> {
343        let deleted = self.managed_delete::<McpServer>(catalog, id)?;
344        // Its reach switches go with it.
345        catalog
346            .conn
347            .lock()
348            .unwrap()
349            .execute("DELETE FROM db_mcp_server_reach WHERE mcp_id = ?1", params![id])?;
350        // So do who added it and who bound it.
351        catalog.mcp_origin_delete(id)?;
352        self.mcp_binding_delete_server(id)?;
353        Ok(deleted)
354    }
355
356    /// Bind an MCP server to an agent (insert ref row). Idempotent —
357    /// binding an already-bound pair is a silent no-op success.
358    ///
359    /// Errors if `agent_id` isn't a LOCAL agent:
360    /// `db_agent_mcp_ref.agent_id` has an ON-enforced FK to
361    /// `db_agents(id)` (store.rs; was `db_agent_definitions(id)` before
362    /// Phase 3c, #3088), but Connectors' agent
363    /// picker (`ListAgentDefinitionsCommand` → `agent_def_list()`) also
364    /// lists cross-channel agents that only exist in another channel's
365    /// local database. Binding one of those would otherwise have the FK
366    /// silently swallow the `INSERT OR IGNORE` — indistinguishable, by
367    /// affected-row-count alone, from the equally-silent "already bound"
368    /// case — reporting success while creating nothing. Same fix as
369    /// skill_bind — see
370    /// docs/reports/REPORT_ARMORY_SKILLS_MARKDOWN_AND_BIND_BUG_2026_07_27.md.
371    ///
372    /// Records `by` (an actor label, `rpc::actor::Actor::label`) as who bound it, at `at` epoch ms,
373    /// when this is the bind that makes the pair; binding again changes nothing.
374    pub fn mcp_server_bind(&self, catalog: &Store, agent_id: &str, mcp_id: &str, by: &str, at: i64) -> Result<(), StoreError> {
375        let was_bound = self.mcp_server_is_bound_to(agent_id, mcp_id)?;
376        self.managed_bind_agent::<McpServer>(catalog, agent_id, mcp_id)?;
377        if !was_bound {
378            self.mcp_binding_record(agent_id, mcp_id, by, at)?;
379        }
380        Ok(())
381    }
382
383    /// Unbind an MCP server from an agent. Returns true if a row was removed.
384    pub fn mcp_server_unbind(&self, agent_id: &str, mcp_id: &str) -> Result<bool, StoreError> {
385        let unbound = self.managed_unbind::<McpServer>(Owner::Agent, agent_id, mcp_id)?;
386        self.mcp_binding_delete(agent_id, mcp_id)?;
387        Ok(unbound)
388    }
389
390    /// Atomically upsert an MCP server enforcing per-agent name uniqueness, and
391    /// (when `bind_new`) bind it — all in one transaction so concurrent
392    /// `mcp.upsert` calls for the same name can't both pass a check and insert
393    /// duplicate-named bindings. Returns an error if another server visible to
394    /// the agent (bound or global) already uses the name.
395    ///
396    /// Records `by` (an actor label) as who added the server (a new one) or last changed it, and, when it
397    /// binds, as who bound it.
398    pub fn mcp_server_upsert_unique(
399        &self,
400        catalog: &Store,
401        agent_id: &str,
402        server: &McpServer,
403        bind_new: bool,
404        by: &str,
405    ) -> Result<(), StoreError> {
406        let existed = catalog.mcp_server_get(&server.id)?.is_some();
407        self.managed_upsert_unique(catalog, Owner::Agent, agent_id, server, bind_new, None)?;
408        catalog.mcp_origin_record(&server.id, if existed { UNKNOWN } else { by }, by)?;
409        if bind_new {
410            self.mcp_binding_record(agent_id, &server.id, by, server.updated_at)?;
411        }
412        Ok(())
413    }
414
415    /// Atomically upsert a GLOBAL MCP server enforcing catalog-wide name
416    /// uniqueness (no `agent_id` — unlike `mcp_server_upsert_unique`, this
417    /// checks for a duplicate name among *every* global row, not just those
418    /// visible to one agent). Reagent P1 on #1948: `agent_config.rs`'s
419    /// `build_mcp_config_from_refs` merges servers into a JSON object keyed
420    /// by `server.name` — two same-named global servers would silently
421    /// clobber each other's config for every agent that has either bound.
422    /// `server.is_global` must already be `true`; caller's job.
423    ///
424    /// Records `by` (an actor label) as who added the server (a new one) or last changed it.
425    pub fn mcp_server_upsert_unique_global(&self, server: &McpServer, by: &str) -> Result<(), StoreError> {
426        let existed = self.mcp_server_get(&server.id)?.is_some();
427        self.managed_upsert_unique_global(server)?;
428        self.mcp_origin_record(&server.id, if existed { UNKNOWN } else { by }, by)
429    }
430
431    // ── Migration-only raw access — see skills.rs's identical trio (same
432    // Phase 2 of SPEC_DURABLE_BINDINGS_2026_09_10.md, same reasoning). ──
433
434    pub(crate) fn mcp_server_list_all_raw(&self) -> Result<Vec<McpServer>, StoreError> {
435        let conn = self.conn.lock().unwrap();
436        let mut stmt = conn.prepare(
437            "SELECT id, name, transport, config, is_global, created_at, updated_at FROM db_mcp_servers",
438        )?;
439        let rows = stmt.query_map([], |row| {
440            Ok(McpServer {
441                id: row.get(0)?,
442                name: row.get(1)?,
443                transport: row.get(2)?,
444                config: row.get(3)?,
445                is_global: row.get::<_, i64>(4)? != 0,
446                created_at: row.get(5)?,
447                updated_at: row.get(6)?,
448            })
449        })?;
450        let mut out = Vec::new();
451        for r in rows {
452            out.push(r?);
453        }
454        Ok(out)
455    }
456
457    /// Returns 1 if a row was actually inserted, 0 if `OR IGNORE` found one
458    /// already there — see `Skill::skill_insert_raw`'s doc comment.
459    pub fn mcp_server_insert_raw(&self, server: &McpServer) -> Result<usize, StoreError> {
460        let conn = self.conn.lock().unwrap();
461        let rows = conn.execute(
462            "INSERT OR IGNORE INTO db_mcp_servers
463                (id, name, transport, config, is_global, created_at, updated_at)
464             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
465            params![
466                server.id,
467                server.name,
468                server.transport,
469                server.config,
470                server.is_global as i64,
471                server.created_at,
472                server.updated_at,
473            ],
474        )?;
475        Ok(rows)
476    }
477
478    pub(crate) fn mcp_server_find_global_by_name(&self, name: &str) -> Result<Option<McpServer>, StoreError> {
479        let conn = self.conn.lock().unwrap();
480        let mut stmt = conn.prepare(
481            "SELECT id, name, transport, config, is_global, created_at, updated_at
482             FROM db_mcp_servers
483             WHERE is_global = 1 AND name = ?1
484             LIMIT 1",
485        )?;
486        let result = stmt.query_row(params![name], |row| {
487            Ok(McpServer {
488                id: row.get(0)?,
489                name: row.get(1)?,
490                transport: row.get(2)?,
491                config: row.get(3)?,
492                is_global: row.get::<_, i64>(4)? != 0,
493                created_at: row.get(5)?,
494                updated_at: row.get(6)?,
495            })
496        });
497        match result {
498            Ok(s) => Ok(Some(s)),
499            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
500            Err(e) => Err(e.into()),
501        }
502    }
503
504    /// Mirrors `Skill::skill_rewrite_ref_id` exactly, for the MCP ref tables
505    /// — including its insert-then-delete merge semantics (Codex P2, PR
506    /// #3183). Returns the number of ref rows actually repointed — see
507    /// `Skill::skill_rewrite_ref_id`'s doc comment.
508    pub(crate) fn mcp_server_rewrite_ref_id(&self, old_id: &str, new_id: &str) -> Result<usize, StoreError> {
509        if old_id == new_id {
510            return Ok(0);
511        }
512        let conn = self.conn.lock().unwrap();
513        conn.execute(
514            "INSERT OR IGNORE INTO db_agent_mcp_ref (agent_id, mcp_id)
515                SELECT agent_id, ?2 FROM db_agent_mcp_ref WHERE mcp_id = ?1",
516            params![old_id, new_id],
517        )?;
518        let agent = conn.execute("DELETE FROM db_agent_mcp_ref WHERE mcp_id = ?1", params![old_id])?;
519        conn.execute(
520            "INSERT OR IGNORE INTO db_agent_mcp_binding (agent_id, mcp_id, bound_by, bound_at)
521                SELECT agent_id, ?2, bound_by, bound_at FROM db_agent_mcp_binding WHERE mcp_id = ?1",
522            params![old_id, new_id],
523        )?;
524        conn.execute("DELETE FROM db_agent_mcp_binding WHERE mcp_id = ?1", params![old_id])?;
525        conn.execute(
526            "INSERT OR IGNORE INTO db_bundle_mcp_ref (bundle_id, mcp_id)
527                SELECT bundle_id, ?2 FROM db_bundle_mcp_ref WHERE mcp_id = ?1",
528            params![old_id, new_id],
529        )?;
530        let bundle = conn.execute("DELETE FROM db_bundle_mcp_ref WHERE mcp_id = ?1", params![old_id])?;
531        Ok(agent + bundle)
532    }
533
534    /// Return true if the given MCP server is accessible to the agent (global or bound).
535    /// Used for read and mutation access checks.
536    pub fn mcp_server_is_accessible_to(&self, catalog: &Store, agent_id: &str, mcp_id: &str) -> Result<bool, StoreError> {
537        self.managed_is_accessible_to::<McpServer>(catalog, Owner::Agent, agent_id, mcp_id)
538    }
539
540    /// The agents that hold a direct ref binding to this MCP server (`db_agent_mcp_ref`).
541    pub fn mcp_server_bound_agent_ids(&self, mcp_id: &str) -> Result<Vec<String>, StoreError> {
542        let conn = self.conn.lock().unwrap();
543        let mut stmt = conn.prepare("SELECT agent_id FROM db_agent_mcp_ref WHERE mcp_id = ?1 ORDER BY agent_id")?;
544        let rows = stmt.query_map(params![mcp_id], |row| row.get::<_, String>(0))?;
545        let mut out = Vec::new();
546        for r in rows {
547            out.push(r?);
548        }
549        Ok(out)
550    }
551
552    /// Return true if the agent has a direct ref binding to this MCP server.
553    /// Used for delete access — an agent may only delete servers it directly bound.
554    pub fn mcp_server_is_bound_to(&self, agent_id: &str, mcp_id: &str) -> Result<bool, StoreError> {
555        self.managed_is_bound_to::<McpServer>(Owner::Agent, agent_id, mcp_id)
556    }
557
558}
559
560
561#[cfg(test)]
562mod effective_tests {
563    use super::*;
564    use crate::backend::storage::bundles::Bundle;
565
566    fn server(id: &str, name: &str, is_global: bool) -> McpServer {
567        McpServer {
568            id: id.to_string(),
569            name: name.to_string(),
570            transport: "stdio".to_string(),
571            config: "{}".to_string(),
572            is_global,
573            created_at: 1,
574            updated_at: 1,
575        }
576    }
577
578    fn agent(store: &Store, id: &str, memory_id: &str) {
579        let mut def = crate::backend::storage::store::AgentDefinition {
580            seat: None,
581            conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
582            id: id.to_string(),
583            slug: String::new(),
584            name: id.to_string(),
585            icon: String::new(),
586            provider: "claude".to_string(),
587            description: String::new(),
588            working_directory: String::new(),
589            shell: String::new(),
590            provider_flags: String::new(),
591            auto_start: 0,
592            restart_on_crash: 0,
593            idle_timeout_minutes: 0,
594            created_at: 1,
595            agent_type: "host".to_string(),
596            environment: String::new(),
597            agent_bus_id: String::new(),
598            is_seeded: 0,
599            accounts: String::new(),
600            parent_id: String::new(),
601            branch_label: String::new(),
602            updated_at: 1,
603            user_hidden: 0,
604            container_image: String::new(),
605            container_volumes: "[]".to_string(),
606            container_name: String::new(),
607            use_ambient_login: 0,
608            model_vendor_base_url: String::new(),
609            memory_id: memory_id.to_string(),
610        };
611        store.agent_def_insert(&mut def).unwrap();
612    }
613
614    fn bundle_row(id: &str) -> Bundle {
615        Bundle {
616            id: id.to_string(),
617            name: id.to_string(),
618            description: String::new(),
619            is_blank: false,
620            is_global: false,
621            provider: String::new(),
622            model: String::new(),
623            instructions: String::new(),
624            instructions_by_provider: "{}".to_string(),
625            context_files: "[]".to_string(),
626            mcp_servers: "[]".to_string(),
627            skills: "[]".to_string(),
628            sort_order: 0,
629            created_at: 1,
630            updated_at: 1,
631            is_system: false,
632        }
633    }
634
635    fn bundle(store: &Store, id: &str) {
636        store
637            .bundle_upsert(&Bundle {
638                id: id.to_string(),
639                name: id.to_string(),
640                description: String::new(),
641                is_blank: false,
642                is_global: false,
643                provider: String::new(),
644                model: String::new(),
645                instructions: String::new(),
646                instructions_by_provider: "{}".to_string(),
647                context_files: "[]".to_string(),
648                mcp_servers: "[]".to_string(),
649                skills: "[]".to_string(),
650                sort_order: 0,
651                created_at: 1,
652                updated_at: 1,
653                is_system: false,
654            })
655            .unwrap();
656    }
657
658    fn bundle_ref(store: &Store, bundle_id: &str, mcp_id: &str) {
659        store
660            .conn
661            .lock()
662            .unwrap()
663            .execute(
664                "INSERT INTO db_bundle_mcp_ref (bundle_id, mcp_id) VALUES (?1, ?2)",
665                params![bundle_id, mcp_id],
666            )
667            .unwrap();
668    }
669
670    /// A bundle ref left by an older build reaches no agent: an agent launches
671    /// with its own and the global servers only.
672    #[test]
673    fn an_agent_launches_with_its_own_and_global_servers_not_its_bundles() {
674        let store = Store::open_in_memory().unwrap();
675        bundle(&store, "own");
676        bundle(&store, "picked");
677        agent(&store, "agent-1", "own");
678        store.agent_bundles_set("agent-1", &["picked".to_string()]).unwrap();
679
680        store.mcp_server_upsert_unique_global(&server("g", "Global", true), "test").unwrap();
681        store.mcp_server_upsert_unique(&store, "agent-1", &server("a", "Agent's", false), true, "test").unwrap();
682        for (bundle_id, id, name) in [("own", "b1", "Own bundle's"), ("picked", "b2", "Picked bundle's")] {
683            store.mcp_server_insert_raw(&server(id, name, false)).unwrap();
684            bundle_ref(&store, bundle_id, id);
685        }
686
687        store.mcp_server_set_reach("g", McpServerReach { all_agents: true, in_containers: false }, 1).unwrap();
688        assert_eq!(effective(&store, "agent-1", false), vec!["Agent's", "Global"]);
689    }
690
691    fn effective(store: &Store, agent_id: &str, container: bool) -> Vec<String> {
692        let mut names: Vec<String> =
693            store.effective_mcp_servers(store, agent_id, container).into_iter().map(|s| s.name).collect();
694        names.sort();
695        names
696    }
697
698    /// A catalog server reaches the agents it is bound to, and every agent
699    /// once switched on for all; being in the catalog alone reaches no one.
700    #[test]
701    fn a_catalog_server_reaches_its_bound_agents_or_all_when_switched_on() {
702        let store = Store::open_in_memory().unwrap();
703        bundle(&store, "own");
704        agent(&store, "agent-1", "own");
705        agent(&store, "agent-2", "own");
706        store.mcp_server_upsert_unique_global(&server("g", "Catalog", true), "test").unwrap();
707        assert!(effective(&store, "agent-1", false).is_empty(), "in the catalog, bound to no one");
708
709        store.mcp_server_bind(&store, "agent-1", "g", "test", 1).unwrap();
710        assert_eq!(effective(&store, "agent-1", false), vec!["Catalog"]);
711        assert!(effective(&store, "agent-2", false).is_empty());
712
713        store.mcp_server_set_reach("g", McpServerReach { all_agents: true, in_containers: false }, 1).unwrap();
714        assert_eq!(effective(&store, "agent-2", false), vec!["Catalog"]);
715        let item = store.mcp_server_list_global(&store).unwrap().pop().unwrap();
716        assert_eq!((item.bound_count, item.all_agents, item.in_containers), (1, true, false));
717    }
718
719    /// A container agent gets a catalog server only when it is switched on
720    /// for containers; its own servers always.
721    #[test]
722    fn a_container_agent_gets_catalog_servers_only_when_switched_on_for_containers() {
723        let store = Store::open_in_memory().unwrap();
724        bundle(&store, "own");
725        agent(&store, "agent-1", "own");
726        store.mcp_server_upsert_unique_global(&server("g", "Catalog", true), "test").unwrap();
727        store.mcp_server_upsert_unique(&store, "agent-1", &server("a", "Own", false), true, "test").unwrap();
728        store.mcp_server_set_reach("g", McpServerReach { all_agents: true, in_containers: false }, 1).unwrap();
729        assert_eq!(effective(&store, "agent-1", true), vec!["Own"]);
730        store.mcp_server_set_reach("g", McpServerReach { all_agents: true, in_containers: true }, 2).unwrap();
731        assert_eq!(effective(&store, "agent-1", true), vec!["Catalog", "Own"]);
732    }
733
734    /// Deleting a server drops its reach switches.
735    #[test]
736    fn deleting_a_server_drops_its_reach() {
737        let store = Store::open_in_memory().unwrap();
738        store.mcp_server_upsert_unique_global(&server("g", "Catalog", true), "test").unwrap();
739        store.mcp_server_set_reach("g", McpServerReach { all_agents: true, in_containers: true }, 1).unwrap();
740        assert!(store.mcp_server_delete(&store, "g").unwrap());
741        assert!(store.mcp_server_reach_all().unwrap().is_empty());
742    }
743
744    /// A bundle write never stores MCP configs, whatever the caller sends, and
745    /// a read never returns any (see `bundles::NO_INLINE_MCP_SERVERS`).
746    #[test]
747    fn a_bundle_write_never_stores_mcp_servers_and_a_read_never_returns_them() {
748        let store = Store::open_in_memory().unwrap();
749        let inline = r#"[{"name":"gh","env":{"GITHUB_TOKEN":"secret"}}]"#;
750        let mut user = Bundle { mcp_servers: inline.to_string(), ..bundle_row("user") };
751        store.bundle_upsert(&user).unwrap();
752        user.id = "system".to_string();
753        user.name = "system".to_string();
754        user.is_system = true;
755        store.bundle_upsert_system(&user).unwrap();
756
757        let stored: i64 = store
758            .conn
759            .lock()
760            .unwrap()
761            .query_row("SELECT COUNT(*) FROM db_bundles WHERE mcp_servers != '[]'", [], |r| r.get(0))
762            .unwrap();
763        assert_eq!(stored, 0);
764
765        // Left by an older build: still not read back.
766        store.conn.lock().unwrap().execute("UPDATE db_bundles SET mcp_servers = ?1", params![inline]).unwrap();
767        for id in ["user", "system"] {
768            assert_eq!(store.bundle_get(id).unwrap().unwrap().mcp_servers, "[]");
769        }
770    }
771
772    #[test]
773    fn deleting_a_bundle_still_clears_a_leftover_bundle_ref() {
774        let store = Store::open_in_memory().unwrap();
775        store.mcp_server_insert_raw(&server("b1", "Leftover", false)).unwrap();
776        bundle_ref(&store, "gone", "b1");
777        assert_eq!(store.bundle_unbind_all_components("gone").unwrap(), (0, 1));
778    }
779}