1use 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
21const SECRET_WORDS: [&str; 9] = ["token", "key", "secret", "password", "passwd", "auth", "credential", "bearer", "cookie"];
23
24pub(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#[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 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 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#[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 pub bound_by: String,
151 #[ts(type = "number")]
153 pub bound_at: i64,
154}
155
156#[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 pub bindings: Vec<McpBinding>,
168 #[ts(type = "number")]
169 pub bound_count: i64,
170 pub all_agents: bool,
172 pub in_containers: bool,
174}
175
176#[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 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
199fn 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 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 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 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 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 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 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 pub fn mcp_server_get(&self, id: &str) -> Result<Option<McpServer>, StoreError> {
336 self.managed_get::<McpServer>(id)
337 }
338
339 pub fn mcp_server_delete(&self, catalog: &Store, id: &str) -> Result<bool, StoreError> {
343 let deleted = self.managed_delete::<McpServer>(catalog, id)?;
344 catalog
346 .conn
347 .lock()
348 .unwrap()
349 .execute("DELETE FROM db_mcp_server_reach WHERE mcp_id = ?1", params![id])?;
350 catalog.mcp_origin_delete(id)?;
352 self.mcp_binding_delete_server(id)?;
353 Ok(deleted)
354 }
355
356 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 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 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 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 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 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 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 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 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 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 #[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 #[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 #[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 #[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 #[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 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}