Skip to main content

agentmux_srv/server/app_api/
mcp.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! MuxAPI handlers for the v1 standalone MCP Server primitive.
5//! mcp.list / mcp.get / mcp.upsert / mcp.delete / mcp.bind / mcp.unbind
6//!
7//! Plus the Connectors-level catalog (mcp.catalog.*): global servers only,
8//! window-scoped — no `agent_id`, no `check_s1` (mirrors bundle.* auth
9//! shape, since Connectors has no agent connection context to gate on).
10//!
11//! `db_mcp_servers` is authoritatively `identity_store` as of Phase 2 of
12//! SPEC_DURABLE_BINDINGS_2026_09_10.md (§5.1/§5.4) — see `skill.rs`'s
13//! module doc comment for the full `catalog`/`mstore` split; this file
14//! mirrors it exactly for MCP servers.
15
16use super::*;
17use crate::backend::rpc::actor::actor_of;
18
19pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
20    register_mcp_list(engine, state);
21    register_mcp_get(engine, state);
22    register_mcp_upsert(engine, state);
23    register_mcp_delete(engine, state);
24    register_mcp_bind(engine, state);
25    register_mcp_unbind(engine, state);
26    register_mcp_probe(engine, state);
27    register_mcp_catalog_list(engine, state);
28    register_mcp_catalog_upsert(engine, state);
29    register_mcp_catalog_delete(engine, state);
30    register_mcp_catalog_probe(engine, state);
31    register_mcp_catalog_set_reach(engine, state);
32    register_mcp_observed_list(engine, state);
33    register_mcp_catalog_bind(engine, state);
34    register_mcp_catalog_list_for_agent(engine, state);
35    register_mcp_catalog_unbind(engine, state);
36}
37
38fn register_mcp_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
39    let mstore = state.mstore.clone();
40    let identity_store = state.identity_store.clone();
41    engine.register_typed(
42        COMMAND_MCP_LIST,
43        move |req: McpAgentScopeData, ctx| {
44            let mstore = mstore.clone();
45            let identity_store = identity_store.clone();
46            async move {
47                check_s1(&mstore, &ctx, &req.agent_id)?;
48                let servers = mstore.mcp_server_list(&identity_store, &req.agent_id)
49                    .map_err(|e| format!("mcp.list: {e}"))?;
50                Ok(servers)
51            }
52        },
53    );
54}
55
56fn register_mcp_get(engine: &Arc<WshRpcEngine>, state: &AppState) {
57    let mstore = state.mstore.clone();
58    let identity_store = state.identity_store.clone();
59    engine.register_typed(
60        COMMAND_MCP_GET,
61        move |req: McpAgentItemData, ctx| {
62            let mstore = mstore.clone();
63            let identity_store = identity_store.clone();
64            async move {
65                check_s1(&mstore, &ctx, &req.agent_id)?;
66                if !mstore.mcp_server_is_accessible_to(&identity_store, &req.agent_id, &req.id)
67                    .map_err(|e| format!("mcp.get: {e}"))?
68                {
69                    return Err("FORBIDDEN: MCP server not accessible to this agent".to_string());
70                }
71                let server = identity_store.mcp_server_get(&req.id)
72                    .map_err(|e| format!("mcp.get: {e}"))?;
73                Ok(server)
74            }
75        },
76    );
77}
78
79fn register_mcp_upsert(engine: &Arc<WshRpcEngine>, state: &AppState) {
80    let mstore = state.mstore.clone();
81    let identity_store = state.identity_store.clone();
82    let broker = state.broker.clone();
83    engine.register_typed(
84        COMMAND_MCP_UPSERT,
85        move |req: CommandMcpUpsertData, ctx| {
86            let mstore = mstore.clone();
87            let identity_store = identity_store.clone();
88            let broker = broker.clone();
89            async move {
90                check_s1(&mstore, &ctx, &req.agent_id)?;
91
92                match serde_json::from_str::<serde_json::Value>(&req.config) {
93                    Ok(serde_json::Value::Object(_)) => {}
94                    Ok(_) => return Err("mcp.upsert: config must be a JSON object".to_string()),
95                    Err(_) => return Err("mcp.upsert: config must be valid JSON".to_string()),
96                }
97                if req.name == "agentmux" {
98                    return Err("FORBIDDEN: 'agentmux' is a reserved MCP server name".to_string());
99                }
100
101                let now = now_ms();
102                // created_at is preserved across updates (ON CONFLICT keeps the
103                // original), so the returned struct never reports a timestamp the
104                // DB won't persist. New rows default to `now`.
105                let (id, created_at) = if req.id.is_empty() {
106                    (uuid::Uuid::new_v4().to_string(), now)
107                } else {
108                    if !mstore.mcp_server_is_bound_to(&req.agent_id, &req.id)
109                        .map_err(|e| format!("mcp.upsert: {e}"))?
110                    {
111                        return Err("FORBIDDEN: MCP server not bound to this agent".to_string());
112                    }
113                    let existing = identity_store.mcp_server_get(&req.id)
114                        .map_err(|e| format!("mcp.upsert: {e}"))?;
115                    match existing {
116                        Some(s) if s.is_global => {
117                            return Err("FORBIDDEN: cannot mutate a global MCP server".to_string());
118                        }
119                        Some(s) => (req.id.clone(), s.created_at),
120                        None => (req.id.clone(), now),
121                    }
122                };
123
124                let server = crate::backend::storage::McpServer {
125                    id: id.clone(),
126                    name: req.name,
127                    transport: req.transport,
128                    config: req.config,
129                    is_global: false,
130                    created_at,
131                    updated_at: now,
132                };
133                // No longer a single transaction across the catalog insert and
134                // the ref-bind (Phase 2 of SPEC_DURABLE_BINDINGS_2026_09_10.md
135                // §5.4, accepted interim gap) — see
136                // `Store::managed_upsert_unique`'s doc comment.
137                mstore.mcp_server_upsert_unique(&identity_store, &req.agent_id, &server, req.id.is_empty(), &actor_of(&ctx).label())
138                    .map_err(|e| format!("mcp.upsert: {e}"))?;
139                broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
140                Ok(server)
141            }
142        },
143    );
144}
145
146fn register_mcp_delete(engine: &Arc<WshRpcEngine>, state: &AppState) {
147    let mstore = state.mstore.clone();
148    let identity_store = state.identity_store.clone();
149    let broker = state.broker.clone();
150    engine.register_typed(
151        COMMAND_MCP_DELETE,
152        move |req: McpAgentItemData, ctx| {
153            let mstore = mstore.clone();
154            let identity_store = identity_store.clone();
155            let broker = broker.clone();
156            async move {
157                check_s1(&mstore, &ctx, &req.agent_id)?;
158                if !mstore.mcp_server_is_bound_to(&req.agent_id, &req.id)
159                    .map_err(|e| format!("mcp.delete: {e}"))?
160                {
161                    return Err("FORBIDDEN: MCP server not bound to this agent".to_string());
162                }
163                if let Some(existing) = identity_store.mcp_server_get(&req.id)
164                    .map_err(|e| format!("mcp.delete: {e}"))?
165                {
166                    if existing.is_global {
167                        return Err("FORBIDDEN: cannot delete a global MCP server".to_string());
168                    }
169                }
170                let deleted = mstore.mcp_server_delete(&identity_store, &req.id)
171                    .map_err(|e| format!("mcp.delete: {e}"))?;
172                if deleted {
173                    broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
174                }
175                Ok(McpDeleteResult { deleted })
176            }
177        },
178    );
179}
180
181fn register_mcp_bind(engine: &Arc<WshRpcEngine>, state: &AppState) {
182    let mstore = state.mstore.clone();
183    let identity_store = state.identity_store.clone();
184    let broker = state.broker.clone();
185    engine.register_typed(
186        COMMAND_MCP_BIND,
187        move |req: McpAgentBindingData, ctx| {
188            let mstore = mstore.clone();
189            let identity_store = identity_store.clone();
190            let broker = broker.clone();
191            async move {
192                check_s1(&mstore, &ctx, &req.agent_id)?;
193                // Only global servers (or ones already bound) may be bound, so an
194                // agent can't escalate to read another agent's server config.
195                match identity_store.mcp_server_get(&req.mcp_id)
196                    .map_err(|e| format!("mcp.bind: {e}"))?
197                {
198                    None => return Err("mcp.bind: MCP server not found".to_string()),
199                    Some(s) if !s.is_global => {
200                        if !mstore.mcp_server_is_bound_to(&req.agent_id, &req.mcp_id)
201                            .map_err(|e| format!("mcp.bind: {e}"))?
202                        {
203                            return Err("FORBIDDEN: can only bind global MCP servers".to_string());
204                        }
205                    }
206                    Some(_) => {}
207                }
208                mstore.mcp_server_bind(&identity_store, &req.agent_id, &req.mcp_id, &actor_of(&ctx).label(), now_ms())
209                    .map_err(|e| format!("mcp.bind: {e}"))?;
210                // An agent binding a server to itself over its own authenticated
211                // connection should reach an already-open Stash MCP Servers tab
212                // for that agent too — same reactivity as the catalog-tier bind.
213                // reagentx P2 on PR #2329.
214                broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
215                Ok(McpBindResult { bound: true })
216            }
217        },
218    );
219}
220
221fn register_mcp_unbind(engine: &Arc<WshRpcEngine>, state: &AppState) {
222    let mstore = state.mstore.clone();
223    let broker = state.broker.clone();
224    engine.register_typed(
225        COMMAND_MCP_UNBIND,
226        move |req: McpAgentBindingData, ctx| {
227            let mstore = mstore.clone();
228            let broker = broker.clone();
229            async move {
230                check_s1(&mstore, &ctx, &req.agent_id)?;
231                let unbound = mstore.mcp_server_unbind(&req.agent_id, &req.mcp_id)
232                    .map_err(|e| format!("mcp.unbind: {e}"))?;
233                if unbound {
234                    broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
235                }
236                Ok(McpUnbindResult { unbound })
237            }
238        },
239    );
240}
241
242/// Health/prerequisite probe for one of this agent's own or bound-global
243/// servers (SPEC_MCP_INTEGRATION_PARITY_ABLETON_PILOT_2026_07_08.md §4.4).
244/// Opens a short-lived MCP connection and reports whether the server
245/// actually speaks the protocol — distinct from `mcp.upsert`'s "is this
246/// valid JSON" check, which tells you nothing about reachability.
247fn register_mcp_probe(engine: &Arc<WshRpcEngine>, state: &AppState) {
248    let actor_store = state.mstore.clone();
249    let mstore = state.mstore.clone();
250    let identity_store = state.identity_store.clone();
251    engine.register_typed(
252        COMMAND_MCP_PROBE,
253        move |req: McpAgentItemData, ctx| {
254            let actor_store = actor_store.clone();
255            let mstore = mstore.clone();
256            let identity_store = identity_store.clone();
257            async move {
258                super::mcp_actor::refuse_container_agent(&actor_store, &ctx, COMMAND_MCP_PROBE)?;
259                check_s1(&mstore, &ctx, &req.agent_id)?;
260                if !mstore.mcp_server_is_accessible_to(&identity_store, &req.agent_id, &req.id)
261                    .map_err(|e| format!("mcp.probe: {e}"))?
262                {
263                    return Err("FORBIDDEN: MCP server not accessible to this agent".to_string());
264                }
265                let server = identity_store.mcp_server_get(&req.id)
266                    .map_err(|e| format!("mcp.probe: {e}"))?
267                    .ok_or_else(|| "mcp.probe: MCP server not found".to_string())?;
268                let result = crate::backend::mcp_probe::probe(&server.transport, &server.config).await;
269                Ok(result)
270            }
271        },
272    );
273}
274
275fn register_mcp_catalog_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
276    let mstore = state.mstore.clone();
277    let identity_store = state.identity_store.clone();
278    engine.register_typed(
279        COMMAND_MCP_CATALOG_LIST,
280        move |_req: McpCatalogListData, _ctx| {
281            let mstore = mstore.clone();
282            let identity_store = identity_store.clone();
283            async move {
284                let servers = mstore.mcp_server_list_global(&identity_store)
285                    .map_err(|e| format!("mcp.catalog.list: {e}"))?;
286                Ok(servers)
287            }
288        },
289    );
290}
291
292fn register_mcp_catalog_upsert(engine: &Arc<WshRpcEngine>, state: &AppState) {
293    let actor_store = state.mstore.clone();
294    let identity_store = state.identity_store.clone();
295    let broker = state.broker.clone();
296    engine.register_typed(
297        COMMAND_MCP_CATALOG_UPSERT,
298        move |req: CommandMcpCatalogUpsertData, ctx| {
299            let actor_store = actor_store.clone();
300            let identity_store = identity_store.clone();
301            let broker = broker.clone();
302            async move {
303                super::mcp_actor::refuse_container_agent(&actor_store, &ctx, COMMAND_MCP_CATALOG_UPSERT)?;
304
305                match serde_json::from_str::<serde_json::Value>(&req.config) {
306                    Ok(serde_json::Value::Object(_)) => {}
307                    Ok(_) => return Err("mcp.catalog.upsert: config must be a JSON object".to_string()),
308                    Err(_) => return Err("mcp.catalog.upsert: config must be valid JSON".to_string()),
309                }
310                if req.name == "agentmux" {
311                    return Err("FORBIDDEN: 'agentmux' is a reserved MCP server name".to_string());
312                }
313
314                let now = now_ms();
315                let (id, created_at) = if req.id.is_empty() {
316                    (uuid::Uuid::new_v4().to_string(), now)
317                } else {
318                    let existing = identity_store.mcp_server_get(&req.id)
319                        .map_err(|e| format!("mcp.catalog.upsert: {e}"))?;
320                    match existing {
321                        // No agent_id/check_s1 here to verify ownership of a private
322                        // server, so the catalog surface may only create new global
323                        // rows or edit ones that are ALREADY global — never promote
324                        // a private server into the catalog by supplying its id.
325                        Some(s) if !s.is_global => {
326                            return Err("FORBIDDEN: cannot promote a private MCP server via the catalog".to_string());
327                        }
328                        Some(s) => (req.id.clone(), s.created_at),
329                        None => (req.id.clone(), now),
330                    }
331                };
332
333                let server = crate::backend::storage::McpServer {
334                    id: id.clone(),
335                    name: req.name,
336                    transport: req.transport,
337                    config: req.config,
338                    is_global: true,
339                    created_at,
340                    updated_at: now,
341                };
342                // Global-scoped uniqueness (not mcp_server_upsert_unique's
343                // per-agent check): agent_config.rs merges servers into a
344                // JSON object keyed by name, so two same-named global
345                // servers would silently clobber each other's config for
346                // every agent that has either bound. Reagent P1 on #1948.
347                // Pure single-table op — called directly on identity_store.
348                identity_store.mcp_server_upsert_unique_global(&server, &actor_of(&ctx).label())
349                    .map_err(|e| format!("mcp.catalog.upsert: {e}"))?;
350                broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
351                Ok(server)
352            }
353        },
354    );
355}
356
357// Catalog-tier sibling of register_mcp_bind (above) — same DB write and
358// "only global servers may be bound" safety check, but no check_s1: the
359// Connectors' WebSocket never authenticates as an agent (see this file's
360// module doc comment), so a check_s1-gated bind can never be satisfied from
361// that caller. mcp.bind itself is left untouched — it may still be the
362// intended surface for an agent binding a server to itself over its own
363// authenticated connection, and loosening its gate would silently widen
364// what any authenticated agent connection can do (bind arbitrary servers to
365// *other* agent ids), which nobody asked for.
366// See docs/reports/REPORT_ARMORY_SKILLS_MARKDOWN_AND_BIND_BUG_2026_07_27.md.
367fn register_mcp_catalog_bind(engine: &Arc<WshRpcEngine>, state: &AppState) {
368    let actor_store = state.mstore.clone();
369    let mstore = state.mstore.clone();
370    let identity_store = state.identity_store.clone();
371    let broker = state.broker.clone();
372    engine.register_typed(
373        COMMAND_MCP_CATALOG_BIND,
374        move |req: McpAgentBindingData, ctx| {
375            let actor_store = actor_store.clone();
376            let mstore = mstore.clone();
377            let identity_store = identity_store.clone();
378            let broker = broker.clone();
379            async move {
380                super::mcp_actor::refuse_container_agent(&actor_store, &ctx, COMMAND_MCP_CATALOG_BIND)?;
381                // Only global servers (or ones already bound) may be bound, so
382                // the catalog surface can't be used to bootstrap read access
383                // to another agent's private server config — same rule as
384                // mcp.bind.
385                match identity_store.mcp_server_get(&req.mcp_id)
386                    .map_err(|e| format!("mcp.catalog.bind: {e}"))?
387                {
388                    None => return Err("mcp.catalog.bind: MCP server not found".to_string()),
389                    Some(s) if !s.is_global => {
390                        if !mstore.mcp_server_is_bound_to(&req.agent_id, &req.mcp_id)
391                            .map_err(|e| format!("mcp.catalog.bind: {e}"))?
392                        {
393                            return Err("FORBIDDEN: can only bind global MCP servers".to_string());
394                        }
395                    }
396                    Some(_) => {}
397                }
398                mstore.mcp_server_bind(&identity_store, &req.agent_id, &req.mcp_id, &actor_of(&ctx).label(), now_ms())
399                    .map_err(|e| format!("mcp.catalog.bind: {e}"))?;
400                // Lets any other open Stash/Connectors view for this agent pick up
401                // the new binding without a manual refresh — mcp.bind (the
402                // check_s1 agent-self-service path) intentionally left alone.
403                broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
404                Ok(McpBindResult { bound: true })
405            }
406        },
407    );
408}
409
410/// Catalog-tier sibling of `mcp.list` (above) — GLOBAL SERVERS ONLY, each
411/// annotated with `bound_to_agent` for the caller-supplied `agent_id`, no
412/// `check_s1`. AgentStashModal's MCP Servers tab (the per-agent Stash view)
413/// runs over the dashboard's connection, which is never agent-authenticated,
414/// so `mcp.list`'s gate can never be satisfied from that caller — the exact
415/// same reasoning as `mcp.catalog.bind` above. Deliberately does NOT reuse
416/// `mcp.list`'s full computation (global + this agent's own private
417/// servers): with no `check_s1`, `agent_id` is unverified, and a private
418/// server's `config` can carry secrets — returning it for an arbitrary
419/// caller-chosen `agent_id` would be an IDOR into every agent's private MCP
420/// config. See `Store::mcp_server_list_global_for_agent`'s doc comment and
421/// docs/reports/REPORT_ARMORY_ARCHITECTURE_AND_NAMING_REVIEW_2026_07_23.md §2.2.
422fn register_mcp_catalog_list_for_agent(engine: &Arc<WshRpcEngine>, state: &AppState) {
423    let mstore = state.mstore.clone();
424    let identity_store = state.identity_store.clone();
425    engine.register_typed(
426        COMMAND_MCP_CATALOG_LIST_FOR_AGENT,
427        move |req: McpAgentScopeData, _ctx| {
428            let mstore = mstore.clone();
429            let identity_store = identity_store.clone();
430            async move {
431                let servers = mstore.mcp_server_list_global_for_agent(&identity_store, &req.agent_id)
432                    .map_err(|e| format!("mcp.catalog.list_for_agent: {e}"))?;
433                Ok(servers)
434            }
435        },
436    );
437}
438
439/// Catalog-tier sibling of `mcp.unbind` (above) — same DB write, no
440/// `check_s1`. Restricted to global rows only, matching the guard
441/// `register_mcp_catalog_bind`/`register_mcp_catalog_delete` already apply
442/// in this file: any window connection can sever any agent's binding to a
443/// *global* server (an intentional, pre-existing trust boundary — bind and
444/// delete already have the same or larger blast radius), but a private
445/// row's own binding must not be touchable via this no-`check_s1` surface,
446/// even though `mcp_id` is never exposed by any no-`check_s1` command
447/// today — defense in depth over relying solely on UUID secrecy.
448/// reagentx P1 on PR #2329 (round 2).
449fn register_mcp_catalog_unbind(engine: &Arc<WshRpcEngine>, state: &AppState) {
450    let actor_store = state.mstore.clone();
451    let mstore = state.mstore.clone();
452    let identity_store = state.identity_store.clone();
453    let broker = state.broker.clone();
454    engine.register_typed(
455        COMMAND_MCP_CATALOG_UNBIND,
456        move |req: McpAgentBindingData, ctx| {
457            let actor_store = actor_store.clone();
458            let mstore = mstore.clone();
459            let identity_store = identity_store.clone();
460            let broker = broker.clone();
461            async move {
462                super::mcp_actor::refuse_container_agent(&actor_store, &ctx, COMMAND_MCP_CATALOG_UNBIND)?;
463                match identity_store.mcp_server_get(&req.mcp_id)
464                    .map_err(|e| format!("mcp.catalog.unbind: {e}"))?
465                {
466                    None => return Err("mcp.catalog.unbind: MCP server not found".to_string()),
467                    Some(s) if !s.is_global => {
468                        return Err("FORBIDDEN: can only unbind global MCP servers".to_string());
469                    }
470                    Some(_) => {}
471                }
472                let unbound = mstore.mcp_server_unbind(&req.agent_id, &req.mcp_id)
473                    .map_err(|e| format!("mcp.catalog.unbind: {e}"))?;
474                if unbound {
475                    broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
476                }
477                Ok(McpUnbindResult { unbound })
478            }
479        },
480    );
481}
482
483fn register_mcp_catalog_delete(engine: &Arc<WshRpcEngine>, state: &AppState) {
484    let actor_store = state.mstore.clone();
485    let mstore = state.mstore.clone();
486    let identity_store = state.identity_store.clone();
487    let broker = state.broker.clone();
488    engine.register_typed(
489        COMMAND_MCP_CATALOG_DELETE,
490        move |req: McpCatalogItemData, ctx| {
491            let actor_store = actor_store.clone();
492            let mstore = mstore.clone();
493            let identity_store = identity_store.clone();
494            let broker = broker.clone();
495            async move {
496                super::mcp_actor::refuse_container_agent(&actor_store, &ctx, COMMAND_MCP_CATALOG_DELETE)?;
497                if let Some(existing) = identity_store.mcp_server_get(&req.id)
498                    .map_err(|e| format!("mcp.catalog.delete: {e}"))?
499                {
500                    if !existing.is_global {
501                        return Err("FORBIDDEN: cannot delete a private MCP server via the catalog".to_string());
502                    }
503                }
504                let deleted = mstore.mcp_server_delete(&identity_store, &req.id)
505                    .map_err(|e| format!("mcp.catalog.delete: {e}"))?;
506                if deleted {
507                    broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
508                }
509                Ok(McpDeleteResult { deleted })
510            }
511        },
512    );
513}
514
515/// Who a global catalog server reaches beyond its binds (every agent,
516/// container agents too). Global rows only, like the rest of `mcp.catalog.*`.
517/// The switches live in the identity store beside the catalog, so they
518/// survive an upgrade (SPEC_CONNECTORS_MCP_WHAT_AGENTS_RUN_2026_10_10.md §2.1).
519fn register_mcp_catalog_set_reach(engine: &Arc<WshRpcEngine>, state: &AppState) {
520    let actor_store = state.mstore.clone();
521    let identity_store = state.identity_store.clone();
522    let broker = state.broker.clone();
523    engine.register_typed(
524        COMMAND_MCP_CATALOG_SET_REACH,
525        move |req: CommandMcpCatalogSetReachData, ctx| {
526            let actor_store = actor_store.clone();
527            let identity_store = identity_store.clone();
528            let broker = broker.clone();
529            async move {
530                super::mcp_actor::refuse_container_agent(&actor_store, &ctx, COMMAND_MCP_CATALOG_SET_REACH)?;
531                match identity_store.mcp_server_get(&req.id).map_err(|e| format!("mcp.catalog.set_reach: {e}"))? {
532                    Some(s) if s.is_global => {}
533                    Some(_) => return Err("FORBIDDEN: a private MCP server has no catalog reach".to_string()),
534                    None => return Err(format!("mcp.catalog.set_reach: no MCP server {}", req.id)),
535                }
536                let reach = crate::backend::storage::McpServerReach {
537                    all_agents: req.all_agents,
538                    in_containers: req.in_containers,
539                };
540                identity_store
541                    .mcp_server_set_reach(&req.id, reach, now_ms())
542                    .map_err(|e| format!("mcp.catalog.set_reach: {e}"))?;
543                broker.publish_event::<crate::backend::mps_events::McpChanged>(&(), vec![], 0);
544                Ok(reach)
545            }
546        },
547    );
548}
549
550/// The MCP servers each running agent's CLI reports having
551/// (`backend::mcp_observed`), with AgentMux's own sources named: `builtin`
552/// for the `agentmux` server, `catalog` for a catalog server of that name.
553/// Names and statuses only; a pane that no longer exists is dropped.
554fn register_mcp_observed_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
555    let mstore = state.mstore.clone();
556    let identity_store = state.identity_store.clone();
557    engine.register_typed(
558        COMMAND_MCP_OBSERVED_LIST,
559        move |_req: McpObservedListData, _ctx| {
560            let mstore = mstore.clone();
561            let identity_store = identity_store.clone();
562            async move {
563                let catalog: std::collections::HashSet<String> = mstore
564                    .mcp_server_list_global(&identity_store)
565                    .map_err(|e| format!("mcp.observed.list: {e}"))?
566                    .into_iter()
567                    .map(|item| item.server.name)
568                    .collect();
569                Ok(observed_agents(&mstore, &identity_store, &catalog))
570            }
571        },
572    );
573}
574
575/// Where an observed server comes from: AgentMux's own sources by name
576/// (its `agentmux` server, a catalog server), else what the CLI said.
577fn observed_source(name: &str, cli_source: String, catalog: &std::collections::HashSet<String>) -> String {
578    if name == "agentmux" {
579        "builtin".to_string()
580    } else if catalog.contains(name) {
581        "catalog".to_string()
582    } else {
583        cli_source
584    }
585}
586
587fn observed_agents(
588    mstore: &crate::backend::storage::store::Store,
589    identity_store: &crate::backend::storage::store::Store,
590    catalog: &std::collections::HashSet<String>,
591) -> Vec<McpObservedAgent> {
592    // Panes whose block is gone: their reports and exit markers go. A block
593    // the store couldn't read is kept: that isn't a gone block.
594    crate::backend::mcp_observed::prune(|block_id| {
595        !matches!(mstore.get::<crate::backend::obj::Block>(block_id), Ok(None))
596    });
597    let mut agents = Vec::new();
598    for (block_id, observation) in crate::backend::mcp_observed::all() {
599        let Some(label) = crate::backend::tower::sampler::block_label(mstore, &block_id) else {
600            continue;
601        };
602        let agent_id = crate::identity::resolver::block_agent_id(mstore, &block_id);
603        let missing = agent_id
604            .as_deref()
605            .map(|id| {
606                let pane_mode = mstore
607                    .get::<crate::backend::obj::Block>(&block_id)
608                    .ok()
609                    .flatten()
610                    .map(|block| crate::backend::obj::meta_get_string(&block.meta, "agentMode", ""));
611                let def = mstore.agent_def_get(id).ok().flatten();
612                crate::backend::mcp_launch::missing_for_pane(
613                    mstore,
614                    identity_store,
615                    id,
616                    pane_mode.as_deref(),
617                    def.as_ref().map(|d| d.agent_type.as_str()),
618                    &observation.servers,
619                )
620            })
621            .unwrap_or_default();
622        let servers = observation
623            .servers
624            .into_iter()
625            .map(|s| McpObservedServer {
626                source: observed_source(&s.name, s.source, catalog),
627                name: s.name,
628                status: s.status,
629                tools: s.tools,
630            })
631            .collect();
632        agents.push(McpObservedAgent {
633            agent_id,
634            label: label.label,
635            at_ms: observation.at_ms,
636            servers,
637            missing,
638            block_id,
639        });
640    }
641    agents.sort_by(|a, b| a.label.cmp(&b.label).then_with(|| a.block_id.cmp(&b.block_id)));
642    agents
643}
644
645/// Health/prerequisite probe for a global catalog server, callable without
646/// an agent context (mirrors mcp.catalog.*'s window-scoped, no-`check_s1`
647/// shape) — this is what lets Connectors → MCP servers show a
648/// connected/error status per row before any agent has bound the server.
649/// See SPEC_MCP_INTEGRATION_PARITY_ABLETON_PILOT_2026_07_08.md §4.4.
650fn register_mcp_catalog_probe(engine: &Arc<WshRpcEngine>, state: &AppState) {
651    let actor_store = state.mstore.clone();
652    let identity_store = state.identity_store.clone();
653    engine.register_typed(
654        COMMAND_MCP_CATALOG_PROBE,
655        move |req: McpCatalogItemData, ctx| {
656            let actor_store = actor_store.clone();
657            let identity_store = identity_store.clone();
658            async move {
659                super::mcp_actor::refuse_container_agent(&actor_store, &ctx, COMMAND_MCP_CATALOG_PROBE)?;
660                let server = identity_store.mcp_server_get(&req.id)
661                    .map_err(|e| format!("mcp.catalog.probe: {e}"))?
662                    .ok_or_else(|| "mcp.catalog.probe: MCP server not found".to_string())?;
663                if !server.is_global {
664                    return Err("FORBIDDEN: mcp.catalog.probe only probes global servers".to_string());
665                }
666                if super::mcp_actor::catalog_server_runs_only_in_containers(&actor_store, &identity_store, &req.id) {
667                    return Ok(crate::backend::mcp_probe::ProbeResult::runs_in_container());
668                }
669                let result = crate::backend::mcp_probe::probe(&server.transport, &server.config).await;
670                Ok(result)
671            }
672        },
673    );
674}
675
676#[cfg(test)]
677mod observed_tests {
678    use super::observed_source;
679
680    #[test]
681    fn agentmux_and_catalog_servers_are_named_as_ours_the_rest_keep_the_clis_label() {
682        let catalog: std::collections::HashSet<String> = ["git".to_string()].into();
683        assert_eq!(observed_source("agentmux", "project".into(), &catalog), "builtin");
684        assert_eq!(observed_source("git", "project".into(), &catalog), "catalog");
685        assert_eq!(observed_source("claude.ai Gmail", "claudeai".into(), &catalog), "claudeai");
686        assert_eq!(observed_source("mine", "project".into(), &catalog), "project");
687    }
688}