Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(mcp): the Agent MCP surface — drive the whole agent ecosystem from any MCP client

rubenluetke10-beepfdc308c526fc
diff --git a/docs/agent-mcp.md b/docs/agent-mcp.md
new file mode 100644
index 0000000000..52529df202
--- /dev/null
+++ b/docs/agent-mcp.md
@@ -0,0 +1,178 @@
+# The Agent MCP surface
+
+Jarvis' agent ecosystem, offered outwards over the Model Context Protocol. Any
+MCP client that holds the control key — Claude Desktop, Cursor, VS Code, Codex,
+another Jarvis — can find the team, talk to it, give it work, watch the board
+and answer its approval requests.
+
+This document is the contract. It is pinned by
+`tests/contract/test_agent_mcp_surface.py`; a change here that is not a change
+there is a client somewhere breaking silently.
+
+---
+
+## 1. Two surfaces, one mount
+
+| URL | What it offers | For whom |
+|---|---|---|
+| `/api/control/mcp` | Jarvis' **tools** — `open-app`, `google-calendar`, `wiki-recall`, every registered tool plugin | a session Jarvis itself spawned, reaching back in |
+| `/api/control/mcp/agents` | the **ecosystem** — roster, board, rooms, assignments, approvals | any client holding the control key |
+
+Both are Streamable HTTP, both authenticate with the Control API's bearer key,
+and **loopback does not bypass it**: anything on the machine could otherwise
+open a socket and start driving somebody's team.
+
+They share one Starlette mount and dispatch on the rest of the path. This is
+not a stylistic choice. A `Mount` on `/api/control/mcp/agents` compiles to
+`^/api/control/mcp/agents(?P<path>/.*)$` — it requires a segment *after* the
+prefix, so a plain `POST /api/control/mcp/agents` never matches it and falls
+through to the shorter mount. The client would then get the tools catalog on
+the agents URL: same transport, same auth, wrong tools, no error anywhere.
+
+## 2. Connecting a client
+
+**Preferred — the stdio bridge.** The client launches a small process that
+forwards to the HTTP surface:
+
+```
+python -m jarvis.mcp.agents.bridge
+```
+
+It needs no URL in the config, survives Jarvis changing port, works from
+clients that cannot send an `Authorization` header, and finds the control key
+the way the app does (keyring → env → file). When Jarvis is not running the
+client still connects and is told what to start, rather than showing a red
+"server failed" — which matters, because a desktop client launches the bridge
+at *its* startup, long before anyone opens Jarvis.
+
+**Direct — Streamable HTTP.** For a remote Jarvis or a client that cannot
+launch a process:
+
+```json
+{ "type": "http",
+ "url": "http://127.0.0.1:47821/api/control/mcp/agents",
+ "headers": { "Authorization": "Bearer <control key>" } }
+```
+
+Fewer moving parts, but the key lives in a config file — and a key in a config
+file is a key in a backup (AP-12).
+
+**From inside the app.** `GET /api/agent-mcp/clients` lists which clients this
+machine has; `GET /api/agent-mcp/snippet?client=…` returns the block to paste;
+`POST /api/agent-mcp/connect` writes it into the client's own config. Writing
+merges — every other server in that file survives — and goes through a sibling
+temp file, because a client reading a half-written config loses *all* its
+servers, not just ours. Codex is never written to: a hand-formatted
+`config.toml` is easy to corrupt and hard to restore, so it gets a snippet.
+
+Environment overrides, for a Jarvis that is not on this box:
+
+* `JARVIS_API_URL` — base URL of the Jarvis to drive
+* `JARVIS_CONTROL_KEY` — the control key
+
+## 3. The tools
+
+Sixteen, grouped by intent. Everything marked **$** starts spend, work, or
+stops the house; a client should gate those and the description says so.
+
+### Discovery
+
+| Tool | What it answers |
+|---|---|
+| `ecosystem_status` | the whole house at a glance: agents by run state, active runs, running rooms, pending approvals, connected capabilities, kill switch |
+| `agents_list` | the roster with `run_state` (idle / working / paused) |
+| `agent_get` | one agent: roster row, recent board events, active runs, learned skills |
+
+### Conversation
+
+| Tool | What it does |
+|---|---|
+| `agent_chat` **$** | write to an agent and **get its answer back** — one turn on that agent's own session, returning the reply text and the tools it used |
+| `agent_message` **$** | leave a note on the board — delivered, but starts no turn and has no reply |
+| `agent_assign` **$** | give a task; the **scheduler** decides whether it runs |
+
+`agent_chat` is the centre of the surface — it is what makes an MCP client a
+keyboard. It waits up to `timeout_s` (default 180 s, max 600 s); a turn still
+running when that expires comes back as `status: "still_running"` with the turn
+id, and the answer lands on the board where `agent_inbox` finds it.
+
+### The board
+
+| Tool | What it reads |
+|---|---|
+| `agent_inbox` | everything addressed to one agent; page with `after_seq` |
+| `board_events` | the whole ecosystem stream; filter by agent or `trace_id` to follow one task end to end |
+
+### Roster, rooms, governance
+
+`agent_create` · `rooms_list` · `room_open` · `room_say` **$** ·
+`room_settle` **$** · `approvals_list` · `approval_resolve` **$** ·
+`kill_switch` **$**
+
+## 4. Resources and prompts
+
+A standard that ships only tools makes every client rediscover the same state
+by hand, so the surface also serves:
+
+**Resources** (read-only, attachable as context without spending a tool call):
+
+* `jarvis://ecosystem` — the house at a glance
+* `jarvis://agents` — the roster
+* `jarvis://capabilities` — plugins, CLIs, MCP servers and skills the agents can use
+* `jarvis://agent/<id>` — one teammate, listed per agent
+
+**Prompts** (openings worth having ready):
+
+* `standup` — what is everyone working on, what is waiting on me
+* `brief_agent` — check an agent has what it needs, then hand the task over
+* `settle_question` — put a question to a room and report the conclusion
+
+## 5. The design rules
+
+Held deliberately, because a standard other clients rely on cannot drift:
+
+1. **One tool per intent, not per endpoint.** `agent_chat` seats a session,
+ subscribes, sends and waits — the caller says one thing. MCP clients have
+ tool budgets; a REST mirror would spend them on plumbing.
+2. **Answers use the field names the REST layer already uses** — snake_case,
+ `agent_id`, `run_state`, `seq`. One vocabulary, not two.
+3. **A refusal is typed and says what to do next.** An unknown agent lists the
+ known ones; a busy agent says it is mid-turn; a stopped ecosystem names the
+ kill switch. Every failure leaves as readable text, never as an MCP error —
+ an error is a dead end for the model, a sentence is not.
+4. **Anything that spends is marked** `dangerous` and says so in its own
+ description, so a client can gate it and the model knows before it calls.
+
+## 6. What the surface cannot do
+
+The safety seam is the house's, not a new one:
+
+* **No spawn vehicle.** No tool here starts a background worker that starts
+ another — the recursion the router tiers exist to prevent (AP-5/AP-14). A
+ client is a person with a keyboard, not a second router.
+* **Work goes through the scheduler.** `agent_assign` is subject to the kill
+ switch, the tier wall, depth ≤ 2, budgets and caps, and a refusal comes back
+ as a typed `VETO` with a reason. Trusted Python decides, never a model.
+* **The kill switch is real.** Engaged, `agent_chat` refuses; nothing runs
+ until it is released.
+* **Approvals are not bypassed.** A remote client is not one of Jarvis' own
+ spawned sessions, so there is no chat card to route an ask to; parked actions
+ surface through `approvals_list` and are answered with `approval_resolve` —
+ the same path a person at the keyboard uses.
+
+## 7. Where the code is
+
+| File | Role |
+|---|---|
+| `jarvis/mcp/agents/tools.py` | the tool set: schemas, handlers, the refusal vocabulary |
+| `jarvis/mcp/agents/server.py` | the MCP server: tools, resources, prompts |
+| `jarvis/mcp/agents/context.py` | lazy access to the live runtime (AP-26: nothing on the boot path) |
+| `jarvis/mcp/agents/bridge.py` | the stdio ↔ HTTP bridge for outside clients |
+| `jarvis/mcp/agents/export.py` | per-client config paths, snippets, and the merge-safe write |
+| `jarvis/ui/web/mcp_server_routes.py` | the mount and the surface dispatch |
+| `jarvis/ui/web/agent_mcp_routes.py` | `/api/agent-mcp` — status, clients, snippet, connect |
+
+Tests: `tests/contract/test_agent_mcp_surface.py` (the contract),
+`tests/unit/mcp/test_agent_mcp_chat.py`,
+`tests/unit/mcp/test_agent_mcp_routes.py`,
+`tests/unit/mcp/test_agent_mcp_export.py`.
diff --git a/jarvis/mcp/agents/__init__.py b/jarvis/mcp/agents/__init__.py
new file mode 100644
index 0000000000..e2731dea44
--- /dev/null
+++ b/jarvis/mcp/agents/__init__.py
@@ -0,0 +1,23 @@
+"""The Agent MCP surface: Jarvis' agent ecosystem, offered outwards over MCP.
+
+``jarvis.mcp.jarvis_tools_server`` offers Jarvis' *hands* — the supervisor tool
+catalog a spawned session reaches back through. This package offers the
+*ecosystem*: the society roster, the board every agent speaks on, rooms,
+assignments, approvals and the connected capability catalog.
+
+The difference matters. A client on the tools surface can open an app or read
+the wiki. A client here can ask who is on the team, write to one of them, watch
+the answer land, give an agent a task the scheduler turns into real work, and
+settle a room where several of them argued it out.
+
+Transport and auth are the Control API's (``jarvis.ui.web.mcp_server_routes``),
+so anything that can hold the control key — Claude Desktop, Cursor, VS Code,
+another Jarvis — talks to the ecosystem the same way.
+"""
+
+from __future__ import annotations
+
+from .server import SERVER_NAME, build_server
+from .tools import TOOLS, AgentTool, tool_specs
+
+__all__ = ["SERVER_NAME", "TOOLS", "AgentTool", "build_server", "tool_specs"]
diff --git a/jarvis/mcp/agents/bridge.py b/jarvis/mcp/agents/bridge.py
new file mode 100644
index 0000000000..4d9b9150b3
--- /dev/null
+++ b/jarvis/mcp/agents/bridge.py
@@ -0,0 +1,208 @@
+"""stdio ↔ HTTP bridge, so any MCP client can reach the agent ecosystem.
+
+The canonical Agent MCP surface is Streamable HTTP on the running app
+(``/api/control/mcp/agents``). That is the right transport — but most desktop
+clients (Claude Desktop, Cursor, VS Code, Codex) launch a *command* and speak
+stdio to it, and the ones that do accept a URL make a bearer header on a
+loopback address awkward to configure. This module is the adapter: a tiny stdio
+server that forwards every request to the HTTP surface and hands the answer
+back.
+
+ python -m jarvis.mcp.agents.bridge
+
+Configuration is environment first, so the bridge also works from another
+machine or a container:
+
+* ``JARVIS_API_URL`` — base URL of the Jarvis to drive. Default: the local
+ instance's admin API from this box's config.
+* ``JARVIS_CONTROL_KEY`` — the control key. Default: read the same way the app
+ does (keyring → env → file), which needs no configuration at all locally.
+
+**A dead Jarvis is not a dead bridge.** When the app is not running, the client
+still connects and gets a tool list with one honest sentence explaining what to
+start, instead of a red "server failed" that says nothing. That matters because
+a desktop client typically launches the bridge at ITS startup, long before the
+person opens Jarvis.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import os
+import sys
+from collections.abc import AsyncIterator
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+#: Path of the agent surface under the Control API.
+SURFACE_PATH: Final[str] = "/api/control/mcp/agents"
+
+#: How long a forwarded call may take. Generous, because ``agent_chat`` waits
+#: for a model turn on purpose; the tool caps its own wait at 600 s.
+CALL_TIMEOUT_S: Final[float] = 660.0
+
+
+def api_base_url() -> str:
+ """Where Jarvis listens. Env wins, then this box's config, then the default."""
+ from_env = os.environ.get("JARVIS_API_URL", "").strip().rstrip("/")
+ if from_env:
+ return from_env
+ port = 47821
+ try:
+ from jarvis.core import config as cfg
+
+ port = int(cfg.load().ui.admin_api_port)
+ except Exception: # noqa: BLE001 — an unreadable config falls back to the shipped port
+ log.debug("agent MCP bridge: config unreadable, using the default port", exc_info=True)
+ return f"http://127.0.0.1:{port}"
+
+
+def control_key() -> str | None:
+ """The control key: env first (works off-box), else the app's own lookup."""
+ from_env = os.environ.get("JARVIS_CONTROL_KEY", "").strip()
+ if from_env:
+ return from_env
+ try:
+ from jarvis.core import control_key as ck
+
+ return ck.get_control_key()
+ except Exception: # noqa: BLE001 — no key found is a refusal we explain, not a crash
+ log.debug("agent MCP bridge: control key unavailable", exc_info=True)
+ return None
+
+
+async def _upstream() -> AsyncIterator[Any]:
+ """One initialized client session against the HTTP surface.
+
+ Opened per request rather than held open: the surface is stateless, so a
+ fresh transport costs one round trip and buys us a bridge that survives
+ Jarvis restarting underneath it — the case that actually happens, because
+ the client outlives the app.
+ """
+ from mcp import ClientSession
+ from mcp.client.streamable_http import streamablehttp_client
+
+ key = control_key()
+ if not key:
+ raise RuntimeError(
+ "No Jarvis control key found. Open Jarvis once to create one, or set "
+ "JARVIS_CONTROL_KEY."
+ )
+ url = f"{api_base_url()}{SURFACE_PATH}"
+ headers = {"Authorization": f"Bearer {key}"}
+ async with streamablehttp_client(url, headers=headers) as (read, write, _):
+ async with ClientSession(read, write) as session:
+ await session.initialize()
+ yield session
+
+
+def _offline_note(exc: Exception) -> str:
+ return (
+ "Jarvis is not reachable right now, so its agents cannot be listed or "
+ f"talked to ({type(exc).__name__}: {exc}). Start the Personal Jarvis app "
+ f"(expected at {api_base_url()}) and try again."
+ )
+
+
+def build_bridge_server() -> Any:
+ """A stdio MCP server that forwards to the HTTP agent surface."""
+ import mcp.types as types
+ from mcp.server.lowlevel import Server
+
+ server: Any = Server("jarvis-agents")
+
+ @server.list_tools() # type: ignore[misc, no-untyped-call]
+ async def _list_tools() -> list[Any]:
+ try:
+ async with _upstream() as session:
+ listed = await session.list_tools()
+ except Exception as exc: # noqa: BLE001 — an offline app is a message, not a failed server
+ log.warning("agent MCP bridge: tool listing failed: %s", exc)
+ return [
+ types.Tool(
+ name="jarvis_unavailable",
+ description=_offline_note(exc),
+ inputSchema={"type": "object", "properties": {}},
+ )
+ ]
+ return list(listed.tools)
+
+ @server.call_tool() # type: ignore[misc, no-untyped-call]
+ async def _call_tool(name: str, arguments: dict[str, Any] | None) -> list[Any]:
+ if name == "jarvis_unavailable":
+ return [types.TextContent(type="text", text=_offline_note(RuntimeError("not running")))]
+ try:
+ async with _upstream() as session:
+ result = await session.call_tool(
+ name, dict(arguments or {}), read_timeout_seconds=None
+ )
+ except Exception as exc: # noqa: BLE001 — same
+ log.warning("agent MCP bridge: %s failed: %s", name, exc)
+ return [types.TextContent(type="text", text=_offline_note(exc))]
+ return list(result.content)
+
+ @server.list_resources() # type: ignore[misc, no-untyped-call]
+ async def _list_resources() -> list[Any]:
+ try:
+ async with _upstream() as session:
+ listed = await session.list_resources()
+ except Exception as exc: # noqa: BLE001 — an offline app simply exposes nothing
+ log.debug("agent MCP bridge: resource listing failed: %s", exc)
+ return []
+ return list(listed.resources)
+
+ @server.read_resource() # type: ignore[misc, no-untyped-call]
+ async def _read_resource(uri: Any) -> str:
+ try:
+ async with _upstream() as session:
+ result = await session.read_resource(uri)
+ except Exception as exc: # noqa: BLE001 — same
+ return _offline_note(exc)
+ parts = [getattr(c, "text", "") for c in result.contents]
+ return "\n".join(p for p in parts if p)
+
+ @server.list_prompts() # type: ignore[misc, no-untyped-call]
+ async def _list_prompts() -> list[Any]:
+ try:
+ async with _upstream() as session:
+ listed = await session.list_prompts()
+ except Exception as exc: # noqa: BLE001 — same
+ log.debug("agent MCP bridge: prompt listing failed: %s", exc)
+ return []
+ return list(listed.prompts)
+
+ @server.get_prompt() # type: ignore[misc, no-untyped-call]
+ async def _get_prompt(name: str, arguments: dict[str, str] | None) -> Any:
+ async with _upstream() as session:
+ return await session.get_prompt(name, dict(arguments or {}))
+
+ return server
+
+
+async def serve_stdio() -> None:
+ """Run the bridge on stdin/stdout until the client closes it."""
+ from mcp.server.stdio import stdio_server
+
+ server = build_bridge_server()
+ async with stdio_server() as (read, write):
+ await server.run(read, write, server.create_initialization_options())
+
+
+def main() -> int:
+ import asyncio
+
+ # stdout is the protocol channel — every log line must go to stderr or the
+ # client sees corrupted JSON-RPC and drops the connection.
+ logging.basicConfig(level=logging.WARNING, stream=sys.stderr)
+ try:
+ asyncio.run(serve_stdio())
+ except KeyboardInterrupt:
+ return 0
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/jarvis/mcp/agents/context.py b/jarvis/mcp/agents/context.py
new file mode 100644
index 0000000000..e6cdf28c02
--- /dev/null
+++ b/jarvis/mcp/agents/context.py
@@ -0,0 +1,129 @@
+"""Lazy access to the live ecosystem the Agent MCP tools drive.
+
+Everything here resolves through the running web app's state, exactly the way
+``society_routes`` and ``agent_chat_routes`` do — the runtime is built on first
+use, never on the boot critical path (AP-26). The MCP surface is mounted on the
+same ASGI app, so ``runtime_refs.get_web_app()`` is the seam that gets us to
+the same objects the REST layer serves, without importing a route module and
+without a second construction path to keep in sync.
+
+A missing piece is never an exception here: it is ``None``, and the tool turns
+that into a typed refusal the calling model can read. An MCP client that asks
+before the app has finished starting should be told to wait, not handed a
+traceback.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+
+class EcosystemUnavailable(RuntimeError):
+ """A part of the ecosystem is not up yet. Carries what to tell the model."""
+
+ def __init__(self, what: str, hint: str) -> None:
+ super().__init__(f"{what} is not available: {hint}")
+ self.what = what
+ self.hint = hint
+
+
+def _app_state() -> Any | None:
+ from jarvis.core import runtime_refs
+
+ app = runtime_refs.get_web_app()
+ return getattr(app, "state", None) if app is not None else None
+
+
+async def society() -> Any:
+ """The live :class:`SocietyRuntime`, built on first use.
+
+ Mirrors ``society_routes._runtime``: prefer the cached instance, else build
+ it from ``app.state.society_factory`` and cache it there, so the REST layer
+ and this surface always drive the SAME runtime — one board, one scheduler,
+ one kill switch.
+ """
+ state = _app_state()
+ if state is None:
+ raise EcosystemUnavailable(
+ "the agent society",
+ "Jarvis' web server is still starting. Try again in a moment.",
+ )
+ runtime = getattr(state, "society", None)
+ if runtime is None:
+ factory = getattr(state, "society_factory", None)
+ if factory is None:
+ raise EcosystemUnavailable(
+ "the agent society",
+ "this Jarvis build has no society runtime configured.",
+ )
+ try:
+ runtime = factory()
+ except Exception as exc: # noqa: BLE001 — a build failure is a refusal, not a crash
+ log.warning("agent MCP: society runtime could not be built: %s", exc)
+ raise EcosystemUnavailable(
+ "the agent society", f"the runtime failed to build ({type(exc).__name__})."
+ ) from exc
+ state.society = runtime
+ await runtime.ensure_started()
+ return runtime
+
+
+def chat_service() -> Any:
+ """The live :class:`AgentChatService` (the CLI seats), built on first use."""
+ state = _app_state()
+ if state is None:
+ raise EcosystemUnavailable(
+ "agent chat", "Jarvis' web server is still starting. Try again in a moment."
+ )
+ service = getattr(state, "agent_chat", None)
+ if service is not None:
+ return service
+ factory = getattr(state, "agent_chat_factory", None)
+ if factory is None:
+ raise EcosystemUnavailable("agent chat", "no chat service is configured on this build.")
+ try:
+ service = factory()
+ except Exception as exc: # noqa: BLE001 — surfaced as a typed refusal
+ log.warning("agent MCP: chat service could not be built: %s", exc)
+ raise EcosystemUnavailable(
+ "agent chat", f"the service failed to build ({type(exc).__name__})."
+ ) from exc
+ state.agent_chat = service
+ return service
+
+
+def mission_manager() -> Any | None:
+ """The mission manager, or ``None`` when missions are not wired up."""
+ state = _app_state()
+ if state is None:
+ return None
+ return getattr(state, "mission_manager", None)
+
+
+async def resolve_agent(runtime: Any, ref: str) -> Any:
+ """An agent record by id OR by name, or a typed refusal.
+
+ Names are what a person types into a chat window, ids are what the board
+ stores. ``roster.resolve`` already accepts both; this wrapper exists so
+ every tool refuses an unknown agent with the same sentence.
+ """
+ agent = await runtime.roster.resolve(ref)
+ if agent is None:
+ known = [a.name for a in await runtime.roster.list()]
+ raise EcosystemUnavailable(
+ f"agent {ref!r}",
+ f"no agent by that id or name. On this box: {', '.join(known) or 'none yet'}.",
+ )
+ return agent
+
+
+__all__ = [
+ "EcosystemUnavailable",
+ "chat_service",
+ "mission_manager",
+ "resolve_agent",
+ "society",
+]
diff --git a/jarvis/mcp/agents/export.py b/jarvis/mcp/agents/export.py
new file mode 100644
index 0000000000..3366b73088
--- /dev/null
+++ b/jarvis/mcp/agents/export.py
@@ -0,0 +1,240 @@
+"""Connect the Agent MCP surface to an outside client, in one call.
+
+Every MCP client configures servers the same two ways — a command it launches
+and speaks stdio to, or a URL it calls with headers — but each keeps its config
+in its own place and shape. This module knows both, for the clients people
+actually use, and can either hand back a snippet to paste or write the entry
+itself.
+
+Path resolution is per-OS by capability, never by assumption: a client whose
+config directory does not exist on this machine is reported as "not installed"
+rather than created, because writing a config for a client that is not there
+leaves a file nobody will ever read.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+#: The server's name in a client's config. Kept stable — renaming it in a
+#: client's file orphans the old entry rather than replacing it.
+ENTRY_NAME: Final[str] = "jarvis-agents"
+
+
+@dataclass(frozen=True)
+class ClientTarget:
+ """One MCP client: where its config lives and which shape it wants."""
+
+ key: str
+ label: str
+ config_path: Path | None
+ #: ``"nested"`` — servers under a top-level ``mcpServers`` object (Claude
+ #: Desktop, Cursor, Claude Code). ``"toml"`` — Codex' ``config.toml``.
+ shape: str
+ installed: bool
+
+
+def _home() -> Path:
+ return Path.home()
+
+
+def _claude_desktop_config() -> Path | None:
+ """Claude Desktop's config, per OS. ``None`` where the app cannot run."""
+ if sys.platform == "win32":
+ appdata = os.environ.get("APPDATA")
+ return Path(appdata) / "Claude" / "claude_desktop_config.json" if appdata else None
+ if sys.platform == "darwin":
+ return _home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
+ # Linux: Claude Desktop is unofficial there, but the community builds all
+ # read the XDG path, so honour it rather than pretending the client is absent.
+ xdg = os.environ.get("XDG_CONFIG_HOME")
+ base = Path(xdg) if xdg else _home() / ".config"
+ return base / "Claude" / "claude_desktop_config.json"
+
+
+def _cursor_config() -> Path:
+ return _home() / ".cursor" / "mcp.json"
+
+
+def _claude_code_config() -> Path:
+ return _home() / ".claude.json"
+
+
+def _codex_config() -> Path:
+ return _home() / ".codex" / "config.toml"
+
+
+def targets() -> list[ClientTarget]:
+ """Every client this machine could connect, with whether it is installed."""
+ rows: list[ClientTarget] = []
+ desktop = _claude_desktop_config()
+ rows.append(
+ ClientTarget(
+ key="claude-desktop",
+ label="Claude Desktop",
+ config_path=desktop,
+ shape="nested",
+ installed=bool(desktop and desktop.parent.is_dir()),
+ )
+ )
+ cursor = _cursor_config()
+ rows.append(
+ ClientTarget(
+ key="cursor",
+ label="Cursor",
+ config_path=cursor,
+ shape="nested",
+ installed=cursor.parent.is_dir(),
+ )
+ )
+ code = _claude_code_config()
+ rows.append(
+ ClientTarget(
+ key="claude-code",
+ label="Claude Code",
+ config_path=code,
+ shape="nested",
+ installed=code.exists() or (_home() / ".claude").is_dir(),
+ )
+ )
+ codex = _codex_config()
+ rows.append(
+ ClientTarget(
+ key="codex",
+ label="Codex CLI",
+ config_path=codex,
+ shape="toml",
+ installed=codex.parent.is_dir(),
+ )
+ )
+ return rows
+
+
+def stdio_entry(*, python: str | None = None, include_key: bool = False) -> dict[str, Any]:
+ """The stdio shape: the client launches the bridge and speaks to it.
+
+ This is the form to prefer. It needs no URL, survives Jarvis changing port,
+ and works from a client that has no way to send an Authorization header.
+
+ ``include_key`` writes the control key into the entry as an env var. Off by
+ default — the bridge finds the key itself from the credential store, and a
+ key in a config file is a key in a backup (AP-12).
+ """
+ from .bridge import api_base_url, control_key
+
+ env: dict[str, str] = {"JARVIS_API_URL": api_base_url()}
+ if include_key:
+ key = control_key()
+ if key:
+ env["JARVIS_CONTROL_KEY"] = key
+ return {
+ "command": python or sys.executable,
+ "args": ["-m", "jarvis.mcp.agents.bridge"],
+ "env": env,
+ }
+
+
+def http_entry() -> dict[str, Any]:
+ """The direct shape: the client calls the surface over HTTP with a header.
+
+ Fewer moving parts, but the key is IN the config file, and the client must
+ support custom headers. Use it for a remote Jarvis or a client that cannot
+ launch a process.
+ """
+ from .bridge import SURFACE_PATH, api_base_url, control_key
+
+ key = control_key() or "<your Jarvis control key>"
+ return {
+ "type": "http",
+ "url": f"{api_base_url()}{SURFACE_PATH}",
+ "headers": {"Authorization": f"Bearer {key}"},
+ }
+
+
+def snippet(client: str = "claude-desktop", *, transport: str = "stdio") -> str:
+ """A ready-to-paste config block for one client."""
+ entry = stdio_entry() if transport == "stdio" else http_entry()
+ target = next((t for t in targets() if t.key == client), None)
+ if target is not None and target.shape == "toml":
+ lines = [f"[mcp_servers.{ENTRY_NAME}]"]
+ if transport == "stdio":
+ lines.append(f"command = {json.dumps(entry['command'])}")
+ lines.append(f"args = {json.dumps(entry['args'])}")
+ if entry.get("env"):
+ lines.append(f"env = {json.dumps(entry['env'])}")
+ else:
+ lines.append(f"url = {json.dumps(entry['url'])}")
+ lines.append(f"http_headers = {json.dumps(entry['headers'])}")
+ return "\n".join(lines)
+ return json.dumps({"mcpServers": {ENTRY_NAME: entry}}, indent=2)
+
+
+def install(client: str, *, transport: str = "stdio", include_key: bool = False) -> dict[str, Any]:
+ """Write the entry into the client's own config file.
+
+ Merges rather than replaces: an existing ``mcpServers`` object keeps every
+ other server, and only our named entry is rewritten. TOML clients are not
+ written to — a hand-formatted ``config.toml`` is easy to corrupt and hard
+ to restore, so Codex gets a snippet to paste instead.
+ """
+ target = next((t for t in targets() if t.key == client), None)
+ if target is None:
+ known = ", ".join(t.key for t in targets())
+ return {"ok": False, "error": f"unknown client {client!r}. Known: {known}"}
+ if target.shape == "toml":
+ return {
+ "ok": False,
+ "error": f"{target.label} keeps a hand-formatted config — paste this instead.",
+ "snippet": snippet(client, transport=transport),
+ "path": str(target.config_path),
+ }
+ path = target.config_path
+ if path is None:
+ return {"ok": False, "error": f"{target.label} has no config location on this OS."}
+ entry = stdio_entry(include_key=include_key) if transport == "stdio" else http_entry()
+ existing: dict[str, Any] = {}
+ if path.exists():
+ try:
+ existing = json.loads(path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError) as exc:
+ return {"ok": False, "error": f"{path} is not readable JSON: {exc}"}
+ if not isinstance(existing, dict):
+ return {"ok": False, "error": f"{path} does not hold a JSON object."}
+ servers = existing.setdefault("mcpServers", {})
+ if not isinstance(servers, dict):
+ return {"ok": False, "error": f"{path} has an mcpServers key that is not an object."}
+ replaced = ENTRY_NAME in servers
+ servers[ENTRY_NAME] = entry
+ path.parent.mkdir(parents=True, exist_ok=True)
+ # Write through a sibling temp file: a client reading a half-written config
+ # at the wrong moment loses every server it has, not just ours.
+ tmp = path.with_suffix(path.suffix + ".jarvis-tmp")
+ tmp.write_text(json.dumps(existing, indent=2, ensure_ascii=False), encoding="utf-8")
+ tmp.replace(path)
+ return {
+ "ok": True,
+ "client": target.label,
+ "path": str(path),
+ "replaced": replaced,
+ "transport": transport,
+ "restart_required": True,
+ }
+
+
+__all__ = [
+ "ENTRY_NAME",
+ "ClientTarget",
+ "http_entry",
+ "install",
+ "snippet",
+ "stdio_entry",
+ "targets",
+]
diff --git a/jarvis/mcp/agents/server.py b/jarvis/mcp/agents/server.py
new file mode 100644
index 0000000000..57b942c145
--- /dev/null
+++ b/jarvis/mcp/agents/server.py
@@ -0,0 +1,228 @@
+"""The Agent MCP server: tools, resources and prompts over one connection.
+
+Three primitives, because a standard that only ships tools makes every client
+re-discover the same state by hand:
+
+* **Tools** (``tools.py``) — the verbs: talk to an agent, assign work, settle a
+ room, resolve an approval.
+* **Resources** — the nouns, read-only and addressable: ``jarvis://agents`` is
+ the roster, ``jarvis://agent/<id>`` one teammate, ``jarvis://ecosystem`` the
+ house at a glance. A client can attach these as context without spending a
+ tool call, which is what makes "what is my team doing?" answerable in one
+ turn instead of three.
+* **Prompts** — the openings worth having ready: a standup, a briefing for one
+ agent, a room on a question.
+
+Built per process, never per session: every handler reads the live runtime when
+it is called, so an agent created a minute ago, a plugin that just connected or
+a CLI that finished bootstrapping shows up without a rebuild.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any, Final
+
+from . import tools as agent_tools
+from .context import EcosystemUnavailable, society
+
+log = logging.getLogger(__name__)
+
+#: The name clients show in their connector list. Kept distinct from the tools
+#: surface's plain "jarvis" so both can be connected at once.
+SERVER_NAME: Final[str] = "jarvis-agents"
+
+#: Bumped when the tool contract changes in a way a client must notice.
+PROTOCOL_VERSION: Final[str] = "1.0"
+
+_ROSTER_URI: Final[str] = "jarvis://agents"
+_ECOSYSTEM_URI: Final[str] = "jarvis://ecosystem"
+_CAPABILITIES_URI: Final[str] = "jarvis://capabilities"
+_AGENT_PREFIX: Final[str] = "jarvis://agent/"
+
+
+async def _read_resource(uri: str) -> str:
+ """One resource as JSON text, or a sentence saying why it is not there."""
+ try:
+ if uri == _ECOSYSTEM_URI:
+ body = await agent_tools._ecosystem_status({}) # noqa: SLF001 — same package
+ elif uri == _ROSTER_URI:
+ body = await agent_tools._agents_list({}) # noqa: SLF001
+ elif uri == _CAPABILITIES_URI:
+ body = await agent_tools._capabilities_list({}) # noqa: SLF001
+ elif uri.startswith(_AGENT_PREFIX):
+ body = await agent_tools._agent_get( # noqa: SLF001
+ {"agent": uri[len(_AGENT_PREFIX) :]}
+ )
+ else:
+ return f"Unknown resource: {uri}"
+ except EcosystemUnavailable as exc:
+ return f"{exc.what} is not available: {exc.hint}"
+ except Exception as exc: # noqa: BLE001 — a resource read never breaks the connection
+ log.warning("agent MCP: resource %s failed", uri, exc_info=True)
+ return f"Could not read {uri}: {type(exc).__name__}: {exc}"
+ return json.dumps(body, ensure_ascii=False, default=str, indent=2)
+
+
+async def _agent_resources() -> list[tuple[str, str, str]]:
+ """``(uri, name, description)`` per agent — empty when the society is down."""
+ try:
+ rt = await society()
+ agents = await rt.roster.list()
+ except Exception: # noqa: BLE001 — a listing that cannot be built is simply empty
+ log.debug("agent MCP: roster unavailable for resource listing", exc_info=True)
+ return []
+ return [
+ (
+ f"{_AGENT_PREFIX}{a.agent_id}",
+ a.name,
+ f"{a.title} — {a.description}"[:300],
+ )
+ for a in agents
+ ]
+
+
+#: ``(name, description, arguments)`` for each prompt this server offers.
+_PROMPTS: Final[tuple[tuple[str, str, tuple[tuple[str, str, bool], ...]], ...]] = (
+ (
+ "standup",
+ "Ask every active agent what it is working on and summarise the team's state.",
+ (),
+ ),
+ (
+ "brief_agent",
+ "Get one agent fully briefed on a task, then hand the task over.",
+ (("agent", "The agent's id or name.", True), ("task", "What it should take on.", True)),
+ ),
+ (
+ "settle_question",
+ "Put a question to several agents in a room and report what they concluded.",
+ (
+ ("question", "The question to settle.", True),
+ ("members", "Comma-separated agent names. Default: pick from the roster.", False),
+ ),
+ ),
+)
+
+
+def _prompt_text(name: str, args: dict[str, str]) -> str:
+ if name == "standup":
+ return (
+ "Call ecosystem_status, then agents_list. For every agent whose run_state "
+ "is 'working', read its recent events with agent_get. Report, in plain "
+ "language: who is busy with what, who is idle, what is waiting on my "
+ "decision (approvals_list), and anything that looks stuck. Do not start "
+ "any work."
+ )
+ if name == "brief_agent":
+ agent = args.get("agent", "")
+ task = args.get("task", "")
+ return (
+ f"Read {agent}'s roster row and recent events with agent_get so you know "
+ f"its focus and what it has been doing. Then use agent_chat to ask it "
+ f"whether it has what it needs for this task: {task}. If it says yes, "
+ f"hand the task over with agent_assign and report the scheduler's verdict. "
+ f"If it says no, tell me what is missing instead of assigning anyway."
+ )
+ if name == "settle_question":
+ question = args.get("question", "")
+ members = args.get("members", "")
+ who = f"these agents: {members}" if members else "2-4 agents whose focus fits the question"
+ return (
+ f"Open a room with {who} on this question: {question}. Use agents_list "
+ f"first if you need to choose. Let the room run, then settle it with "
+ f"room_settle and report what they concluded and where they disagreed."
+ )
+ return f"Unknown prompt: {name}"
+
+
+def build_server() -> Any:
+ """A low-level MCP server bound to the live agent ecosystem."""
+ import mcp.types as types
+ from mcp.server.lowlevel import Server
+
+ server: Any = Server(SERVER_NAME)
+
+ @server.list_tools() # type: ignore[misc, no-untyped-call]
+ async def _list_tools() -> list[Any]:
+ return [
+ types.Tool(
+ name=spec["name"],
+ description=spec["description"],
+ inputSchema=spec["inputSchema"],
+ )
+ for spec in agent_tools.tool_specs()
+ ]
+
+ @server.call_tool() # type: ignore[misc, no-untyped-call]
+ async def _call_tool(name: str, arguments: dict[str, Any] | None) -> list[Any]:
+ text = await agent_tools.call(name, arguments)
+ return [types.TextContent(type="text", text=text)]
+
+ @server.list_resources() # type: ignore[misc, no-untyped-call]
+ async def _list_resources() -> list[Any]:
+ fixed = [
+ types.Resource(
+ uri=_ECOSYSTEM_URI,
+ name="Ecosystem status",
+ description="The whole agent house at a glance: agents, runs, rooms, approvals.",
+ mimeType="application/json",
+ ),
+ types.Resource(
+ uri=_ROSTER_URI,
+ name="Agent roster",
+ description="Every agent with its role, model, focus and current run state.",
+ mimeType="application/json",
+ ),
+ types.Resource(
+ uri=_CAPABILITIES_URI,
+ name="Connected capabilities",
+ description="Plugins, CLIs, MCP servers and skills the agents can actually use.",
+ mimeType="application/json",
+ ),
+ ]
+ for uri, name, description in await _agent_resources():
+ fixed.append(
+ types.Resource(
+ uri=uri, name=name, description=description, mimeType="application/json"
+ )
+ )
+ return fixed
+
+ @server.read_resource() # type: ignore[misc, no-untyped-call]
+ async def _read(uri: Any) -> str:
+ return await _read_resource(str(uri))
+
+ @server.list_prompts() # type: ignore[misc, no-untyped-call]
+ async def _list_prompts() -> list[Any]:
+ return [
+ types.Prompt(
+ name=name,
+ description=description,
+ arguments=[
+ types.PromptArgument(name=arg, description=desc, required=required)
+ for arg, desc, required in arguments
+ ],
+ )
+ for name, description, arguments in _PROMPTS
+ ]
+
+ @server.get_prompt() # type: ignore[misc, no-untyped-call]
+ async def _get_prompt(name: str, arguments: dict[str, str] | None) -> Any:
+ return types.GetPromptResult(
+ description=next((d for n, d, _ in _PROMPTS if n == name), name),
+ messages=[
+ types.PromptMessage(
+ role="user",
+ content=types.TextContent(
+ type="text", text=_prompt_text(name, dict(arguments or {}))
+ ),
+ )
+ ],
+ )
+
+ return server
+
+
+__all__ = ["PROTOCOL_VERSION", "SERVER_NAME", "build_server"]
diff --git a/jarvis/mcp/agents/tools.py b/jarvis/mcp/agents/tools.py
new file mode 100644
index 0000000000..097dc92308
--- /dev/null
+++ b/jarvis/mcp/agents/tools.py
@@ -0,0 +1,856 @@
+"""The Agent MCP tool set — the ecosystem's outward vocabulary.
+
+Design rules this surface holds itself to, because it is meant to be a standard
+other clients can rely on rather than a projection of today's REST paths:
+
+1. **One tool per intent, not per endpoint.** ``agent_chat`` is a conversation;
+ the fact that it seats a session, subscribes, sends and waits is ours to
+ carry, not the caller's.
+2. **Every answer is JSON with the field names the REST layer already uses**
+ (snake_case, ``agent_id``, ``run_state``, ``seq``). A client that has read
+ ``/api/society`` needs no second vocabulary.
+3. **A refusal is typed and says what to do next.** Never a bare traceback: an
+ unknown agent lists the known ones, a busy agent says so, a stopped
+ ecosystem says the kill switch is on.
+4. **Anything that starts spend or work is marked** ``dangerous`` and says so in
+ its own description, so a client can gate it and the model reading the
+ catalog knows before it calls.
+
+The safety seam is the one the rest of the house uses. Work is started through
+the scheduler (kill switch, tier wall, depth ≤ 2, budgets — AP-5/AP-14), the
+board is append-only and persist-before-publish, and no tool here can reach a
+spawn vehicle. An MCP client is a person with a keyboard, not a second router.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, field
+from typing import Any, Final
+
+from .context import EcosystemUnavailable, resolve_agent, society
+
+log = logging.getLogger(__name__)
+
+#: What ``SocietyEnvelope.from_agent`` carries for a message an MCP client sent.
+#: Distinguishable from ``"user"`` (the person at the app) in the board history,
+#: so a later reader can tell a remote client's word from a spoken one.
+MCP_ORIGIN: Final[str] = "user"
+
+#: Ceiling for ``agent_chat``'s wait. A conversation that has not answered in
+#: ten minutes is a background task; the caller gets the turn id to follow.
+MAX_WAIT_S: Final[float] = 600.0
+DEFAULT_WAIT_S: Final[float] = 180.0
+
+Handler = Callable[[dict[str, Any]], Awaitable[Any]]
+
+
+@dataclass(frozen=True)
+class AgentTool:
+ """One tool on the surface: what it is called, what it takes, what it does."""
+
+ name: str
+ description: str
+ input_schema: dict[str, Any]
+ handler: Handler
+ dangerous: bool = False
+ tags: tuple[str, ...] = field(default=())
+
+
+def _obj(props: dict[str, Any], required: list[str] | None = None) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": props,
+ "required": required or [],
+ "additionalProperties": False,
+ }
+
+
+_AGENT_REF = {
+ "type": "string",
+ "description": "The agent's id or its name (both work).",
+}
+
+
+# --------------------------------------------------------------- discovery
+
+
+async def _ecosystem_status(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ status = await rt.status()
+ agents = await rt.roster.list()
+ running = rt.scheduler.running
+ await rt.approvals.expire_due()
+ pending = await rt.approvals.pending()
+ by_state: dict[str, int] = {}
+ for agent in agents:
+ if agent.state == "paused":
+ key = "paused"
+ elif agent.agent_id in running.values():
+ key = "working"
+ else:
+ key = "idle"
+ by_state[key] = by_state.get(key, 0) + 1
+ return {
+ "kill_switch": status["kill_switch"],
+ "agents_total": len(agents),
+ "agents_by_run_state": by_state,
+ "active_runs": status["active_runs"],
+ "rooms_running": status["rooms_running"],
+ "approvals_pending": len(pending),
+ "board_last_seq": status["last_seq"],
+ "lead": rt.lead_id,
+ "capabilities_connected": len(rt.catalog()),
+ }
+
+
+async def _agents_list(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ include_archived = bool(args.get("include_archived"))
+ agents = await rt.roster.list(include_archived=include_archived)
+ running = rt.scheduler.running
+ rows = []
+ for agent in agents:
+ row = agent.to_dict()
+ if agent.state == "paused":
+ row["run_state"] = "paused"
+ elif agent.agent_id in running.values():
+ row["run_state"] = "working"
+ else:
+ row["run_state"] = "idle"
+ rows.append(row)
+ return {"agents": rows, "total": len(rows)}
+
+
+async def _agent_get(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ agent = await resolve_agent(rt, str(args["agent"]))
+ limit = max(1, min(int(args.get("recent_events") or 20), 200))
+ events = await rt.store.events_for_agent(agent.agent_id, limit=limit)
+ return {
+ "agent": agent.to_dict(),
+ "recent_events": [e.model_dump(mode="json") for e in events],
+ "active_runs": rt.scheduler.active_runs(agent.agent_id),
+ "skills": [s for s in _agent_skill_names(rt, agent.agent_id)],
+ }
+
+
+def _agent_skill_names(rt: Any, agent_id: str) -> list[str]:
+ try:
+ skills = rt.skills_for(agent_id)
+ except Exception: # noqa: BLE001 — a broken skill store costs the list, not the call
+ log.debug("agent MCP: skills unavailable for %s", agent_id, exc_info=True)
+ return []
+ listing = getattr(skills, "list", None)
+ if not callable(listing):
+ return []
+ try:
+ return [str(getattr(s, "slug", s)) for s in listing()]
+ except Exception: # noqa: BLE001 — same
+ log.debug("agent MCP: skill listing failed for %s", agent_id, exc_info=True)
+ return []
+
+
+async def _capabilities_list(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ kind = str(args.get("kind") or "").strip().lower()
+ rows = [row.to_dict() for row in rt.catalog()]
+ if kind:
+ rows = [r for r in rows if str(r.get("kind", "")).lower() == kind]
+ return {"capabilities": rows, "total": len(rows)}
+
+
+# ----------------------------------------------------------------- roster
+
+
+async def _agent_create(args: dict[str, Any]) -> dict[str, Any]:
+ from jarvis.society.roster import RosterError
+
+ rt = await society()
+ title = str(args["title"])
+ description = str(args["description"])
+ focus, rules = rt.derive(title, description)
+ fields: dict[str, Any] = {}
+ if focus:
+ fields["focus"] = focus
+ if rules.get("require_approval"):
+ fields["approval_rules"] = rules
+ try:
+ agent, created = await rt.roster.create(
+ name=str(args["name"]),
+ title=title,
+ description=description,
+ tier=str(args.get("tier") or "specialist"),
+ **fields,
+ )
+ except RosterError as exc:
+ raise _refuse_typed(exc) from exc
+ return {"agent": agent.to_dict(), "created": created}
+
+
+# ---------------------------------------------------------- conversation
+
+
+async def _agent_chat(args: dict[str, Any]) -> dict[str, Any]:
+ """Write to an agent and wait for its answer — the surface's centre.
+
+ This is the same path a person's keyboard takes in the app: the agent's
+ canonical chat session, seated from its roster row (provider, model,
+ effort, permission ceiling, workspace), one turn, one answer. It is NOT the
+ scheduler — a conversation is not a job — so the tier wall and budgets do
+ not apply, but the kill switch does: a stopped ecosystem answers nobody.
+ """
+ from jarvis.agent_chat.service import SessionBusy
+ from jarvis.society.chat_binding import ensure_session
+
+ rt = await society()
+ if await rt.store.kill_switch():
+ raise EcosystemUnavailable(
+ "the ecosystem",
+ "the kill switch is engaged — nothing runs. Release it with kill_switch first.",
+ )
+ agent = await resolve_agent(rt, str(args["agent"]))
+ text = str(args["text"]).strip()
+ if not text:
+ raise ValueError("text must not be empty")
+ wait_s = min(float(args.get("timeout_s") or DEFAULT_WAIT_S), MAX_WAIT_S)
+
+ svc = rt._get_chat() # noqa: SLF001 — this module is the runtime's operator, as the routes are
+ if svc is None:
+ raise EcosystemUnavailable(
+ "agent chat", "the chat service is not running, so agents cannot be talked to."
+ )
+ try:
+ session = ensure_session(svc, rt._get_cfg(), agent) # noqa: SLF001 — same
+ except PermissionError as exc:
+ # No provider can run this agent — an unconfigured box, not a bug. The
+ # message already says what to set up, so pass it through rather than
+ # burying it in a traceback the caller cannot act on.
+ raise EcosystemUnavailable(f"agent {agent.name}", str(exc)) from exc
+ if svc.is_running(session.session_id):
+ raise EcosystemUnavailable(
+ f"agent {agent.name}",
+ "it is in the middle of a turn. Wait for it to finish, then ask again.",
+ )
+
+ queue = svc.subscribe(session.session_id)
+ try:
+ try:
+ turn_id = await svc.send(session.session_id, text)
+ except SessionBusy as exc:
+ raise EcosystemUnavailable(
+ f"agent {agent.name}", "it started another turn just now. Try again shortly."
+ ) from exc
+ reply = await _await_turn(queue, turn_id, wait_s)
+ finally:
+ svc.unsubscribe(session.session_id, queue)
+
+ return {
+ "agent_id": agent.agent_id,
+ "agent_name": agent.name,
+ "session_id": session.session_id,
+ "turn_id": turn_id,
+ **reply,
+ }
+
+
+async def _await_turn(queue: Any, turn_id: str, wait_s: float) -> dict[str, Any]:
+ """Drain one turn's events into a reply, or say honestly that it is still running."""
+ text = ""
+ tools: list[str] = []
+ deadline = asyncio.get_running_loop().time() + wait_s
+ while True:
+ remaining = deadline - asyncio.get_running_loop().time()
+ if remaining <= 0:
+ return {
+ "status": "still_running",
+ "reply": text,
+ "tool_calls": tools,
+ "note": (
+ f"The agent is still working after {wait_s:.0f}s. "
+ "Its answer lands on the board — read it with agent_inbox or board_events."
+ ),
+ }
+ try:
+ event = await asyncio.wait_for(queue.get(), timeout=remaining)
+ except TimeoutError:
+ continue
+ payload = event.get("payload") or {}
+ if payload.get("turn_id") not in (None, turn_id):
+ continue
+ kind = event.get("kind")
+ if kind == "assistant_text":
+ text = str(payload.get("text") or text)
+ elif kind == "tool_call":
+ name = str(payload.get("name") or payload.get("tool") or "tool")
+ tools.append(name)
+ elif kind == "error":
+ return {
+ "status": "blocked",
+ "reply": text,
+ "tool_calls": tools,
+ "error": str(payload.get("message") or "the turn failed"),
+ }
+ elif kind == "turn_finished":
+ status = payload.get("status")
+ ok = status in (None, "ok", "done", "completed")
+ return {
+ "status": "answered" if ok else "blocked",
+ "reply": text,
+ "tool_calls": tools,
+ **({} if ok else {"error": str(payload.get("error") or status or "")}),
+ }
+
+
+async def _agent_message(args: dict[str, Any]) -> dict[str, Any]:
+ """A note on the board. Delivered, not answered — use agent_chat for a reply."""
+ from jarvis.society.events import MsgType
+
+ rt = await society()
+ agent = await resolve_agent(rt, str(args["agent"]))
+ raw = str(args.get("msg_type") or "SAY").upper()
+ try:
+ msg_type = MsgType(raw)
+ except ValueError as exc:
+ allowed = ["SAY", "QUERY", "PROPOSE", "HOLD", "RELEASE"]
+ raise ValueError(f"msg_type must be one of {allowed}") from exc
+ if msg_type in (MsgType.ASSIGN, MsgType.ROOM_OPEN, MsgType.ROOM_SETTLE, MsgType.VETO):
+ raise ValueError(f"{raw} is not a message — use agent_assign or the room_* tools")
+ env = await rt.say(
+ from_agent=str(args.get("from_agent") or MCP_ORIGIN),
+ to_agent=agent.agent_id,
+ text=str(args["text"]),
+ msg_type=msg_type,
+ payload=args.get("payload") or None,
+ )
+ return {"event": env.model_dump(mode="json"), "delivered_to": agent.name}
+
+
+async def _agent_assign(args: dict[str, Any]) -> dict[str, Any]:
+ """A task the scheduler turns into real work — the spending path."""
+ from jarvis.missions.ids import uuid7_str
+ from jarvis.society.events import MsgType
+
+ rt = await society()
+ agent = await resolve_agent(rt, str(args["agent"]))
+ task = str(args["task"]).strip()
+ if not task:
+ raise ValueError("task must not be empty")
+ payload: dict[str, Any] = {"text": task}
+ runner = str(args.get("runner") or "").strip()
+ if runner:
+ if runner not in ("chat", "mission"):
+ raise ValueError("runner must be 'chat' (a turn) or 'mission' (an isolated worktree)")
+ payload["runner"] = runner
+ env = await rt.say(
+ from_agent=str(args.get("from_agent") or MCP_ORIGIN),
+ to_agent=agent.agent_id,
+ text=task,
+ trace_id=f"task:{uuid7_str()}",
+ msg_type=MsgType.ASSIGN,
+ payload=payload,
+ )
+ # The scheduler answers on the same trace: a CLAIM when work started, a
+ # VETO with a typed reason when it refused. Both are already stored by the
+ # time say() returns, because the board persists before it publishes.
+ trail = await rt.store.events_for_trace(env.trace_id)
+ verdict = next((e for e in trail if e.seq and env.seq and e.seq > env.seq), None)
+ return {
+ "assigned_to": agent.name,
+ "trace_id": env.trace_id,
+ "event": env.model_dump(mode="json"),
+ "outcome": verdict.model_dump(mode="json") if verdict else None,
+ "accepted": bool(verdict and str(verdict.msg_type) != "VETO"),
+ }
+
+
+# -------------------------------------------------------------- the board
+
+
+async def _agent_inbox(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ agent = await resolve_agent(rt, str(args["agent"]))
+ after_seq = int(args.get("after_seq") or 0)
+ events = await rt.store.inbox_for(agent.agent_id, after_seq=after_seq)
+ return {
+ "agent_id": agent.agent_id,
+ "events": [e.model_dump(mode="json") for e in events],
+ "last_seq": await rt.store.last_seq(),
+ }
+
+
+async def _board_events(args: dict[str, Any]) -> dict[str, Any]:
+ """The ecosystem's stream. Poll with the returned ``last_seq`` to follow it."""
+ rt = await society()
+ limit = max(1, min(int(args.get("limit") or 100), 1000))
+ trace_id = str(args.get("trace_id") or "").strip()
+ agent_ref = str(args.get("agent") or "").strip()
+ after_seq = int(args.get("after_seq") or 0)
+ if trace_id:
+ events = await rt.store.events_for_trace(trace_id)
+ elif agent_ref:
+ agent = await resolve_agent(rt, agent_ref)
+ events = await rt.store.events_for_agent(agent.agent_id, after_seq=after_seq, limit=limit)
+ else:
+ events = await rt.store.events_since(after_seq, limit=limit)
+ return {
+ "events": [e.model_dump(mode="json") for e in events],
+ "last_seq": await rt.store.last_seq(),
+ }
+
+
+# ----------------------------------------------------------------- rooms
+
+
+async def _room_open(args: dict[str, Any]) -> dict[str, Any]:
+ from jarvis.society.rooms import RoomError
+
+ rt = await society()
+ members = [str(m) for m in (args.get("members") or [])]
+ if len(members) < 2:
+ raise ValueError("a room needs at least 2 members")
+ resolved = [(await resolve_agent(rt, m)).agent_id for m in members]
+ try:
+ room = await rt.rooms.open(
+ opened_by=str(args.get("opened_by") or MCP_ORIGIN),
+ members=resolved,
+ topic=str(args["topic"]),
+ )
+ except RoomError as exc:
+ raise _refuse_typed(exc) from exc
+ return {"room": room.to_dict()}
+
+
+async def _room_say(args: dict[str, Any]) -> dict[str, Any]:
+ from jarvis.society.rooms import RoomError
+
+ rt = await society()
+ member = str(args["member"])
+ resolved = (await resolve_agent(rt, member)).agent_id
+ try:
+ room = await rt.rooms.say(str(args["room_id"]), resolved, str(args["text"]))
+ except RoomError as exc:
+ raise _refuse_typed(exc) from exc
+ return {"room": room.to_dict()}
+
+
+async def _room_settle(args: dict[str, Any]) -> dict[str, Any]:
+ from jarvis.society.rooms import RoomError
+
+ rt = await society()
+ try:
+ room = await rt.rooms.settle(str(args["room_id"]), reason="mcp-client", by="user")
+ except RoomError as exc:
+ raise _refuse_typed(exc) from exc
+ return {"room": room.to_dict()}
+
+
+async def _rooms_list(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ return {"rooms": [r.to_dict() for r in await rt.rooms.list()]}
+
+
+# ------------------------------------------------------------- governance
+
+
+async def _approvals_list(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ await rt.approvals.expire_due()
+ items = await rt.approvals.pending()
+ ref = str(args.get("agent") or "").strip()
+ if ref:
+ agent = await resolve_agent(rt, ref)
+ items = [a for a in items if a.agent_id == agent.agent_id]
+ return {"approvals": [a.to_dict() for a in items], "total": len(items)}
+
+
+async def _approval_resolve(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ approve = bool(args["approve"])
+ try:
+ item = await rt.approvals.resolve(
+ str(args["approval_id"]), approve=approve, note=str(args.get("note") or "")
+ )
+ except KeyError as exc:
+ raise EcosystemUnavailable(
+ f"approval {args['approval_id']!r}",
+ "no pending approval by that id. List them with approvals_list.",
+ ) from exc
+ return {"approval": item.to_dict()}
+
+
+async def _kill_switch(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ if bool(args["engage"]):
+ return await rt.engage_kill_switch()
+ return await rt.release_kill_switch()
+
+
+# ------------------------------------------------------------------ error
+
+
+def _refuse_typed(exc: Any) -> EcosystemUnavailable:
+ """A ``RosterError``/``RoomError`` as a refusal that names the retry action."""
+ from jarvis.society.failure_reasons import retry_action
+
+ reason = getattr(exc, "reason", None)
+ hint = f"{exc}"
+ if reason is not None:
+ hint = f"{exc} (reason: {reason}; retry: {retry_action(reason)})"
+ return EcosystemUnavailable("that action", hint)
+
+
+# ------------------------------------------------------------- the catalog
+
+
+TOOLS: Final[tuple[AgentTool, ...]] = (
+ AgentTool(
+ name="ecosystem_status",
+ description=(
+ "One glance at the whole agent ecosystem: how many agents exist and what "
+ "they are doing, active runs, running rooms, pending approvals, the "
+ "connected capability count, and whether the kill switch is engaged. "
+ "Call this first when you do not know the state of the house."
+ ),
+ input_schema=_obj({}),
+ handler=_ecosystem_status,
+ tags=("discovery",),
+ ),
+ AgentTool(
+ name="agents_list",
+ description=(
+ "Every agent on this Jarvis: id, name, title, tier, model, focus, "
+ "permission ceiling and run_state (idle / working / paused). "
+ "The roster is the team — start here to know who you can talk to."
+ ),
+ input_schema=_obj(
+ {
+ "include_archived": {
+ "type": "boolean",
+ "description": "Include retired agents. Default false.",
+ }
+ }
+ ),
+ handler=_agents_list,
+ tags=("discovery",),
+ ),
+ AgentTool(
+ name="agent_get",
+ description=(
+ "One agent in full: its roster row, its most recent board events, the "
+ "runs it currently owns, and the skills it has learned."
+ ),
+ input_schema=_obj(
+ {
+ "agent": _AGENT_REF,
+ "recent_events": {
+ "type": "integer",
+ "description": "How many recent events to include (1-200, default 20).",
+ },
+ },
+ ["agent"],
+ ),
+ handler=_agent_get,
+ tags=("discovery",),
+ ),
+ AgentTool(
+ name="agent_chat",
+ description=(
+ "Write to an agent and get its answer back — the normal way to talk to "
+ "the team. Runs one turn on that agent's own session (its provider, "
+ "model, tools and briefing) and returns the reply text plus the tools it "
+ "used. Waits up to timeout_s; if the agent is still working when that "
+ "expires you get status 'still_running' and can follow it with "
+ "agent_inbox. Costs money — it runs a model turn."
+ ),
+ input_schema=_obj(
+ {
+ "agent": _AGENT_REF,
+ "text": {"type": "string", "description": "What to say to the agent."},
+ "timeout_s": {
+ "type": "number",
+ "description": "How long to wait for the answer (default 180, max 600).",
+ },
+ },
+ ["agent", "text"],
+ ),
+ handler=_agent_chat,
+ dangerous=True,
+ tags=("conversation",),
+ ),
+ AgentTool(
+ name="agent_message",
+ description=(
+ "Leave a note on an agent's board — delivered to it, but it does NOT "
+ "start a turn and there is no reply. Use agent_chat when you want an "
+ "answer, agent_assign when you want work done."
+ ),
+ input_schema=_obj(
+ {
+ "agent": _AGENT_REF,
+ "text": {"type": "string"},
+ "msg_type": {
+ "type": "string",
+ "enum": ["SAY", "QUERY", "PROPOSE", "HOLD", "RELEASE"],
+ "description": "The envelope type. Default SAY.",
+ },
+ "from_agent": {
+ "type": "string",
+ "description": "Who it is from. Default 'user' (the person).",
+ },
+ "payload": {"type": "object", "description": "Extra structured fields."},
+ },
+ ["agent", "text"],
+ ),
+ handler=_agent_message,
+ dangerous=True,
+ tags=("conversation",),
+ ),
+ AgentTool(
+ name="agent_assign",
+ description=(
+ "Give an agent a task. The scheduler — not a model — decides whether it "
+ "runs: kill switch, tier wall, depth limit and budgets all apply, and a "
+ "refusal comes back as a typed VETO with a reason. runner 'chat' does it "
+ "in a turn; runner 'mission' does it in an isolated git worktree for "
+ "heavy coding work. Costs money."
+ ),
+ input_schema=_obj(
+ {
+ "agent": _AGENT_REF,
+ "task": {"type": "string", "description": "What the agent should do."},
+ "runner": {
+ "type": "string",
+ "enum": ["chat", "mission"],
+ "description": "How to run it. Default: chat when available.",
+ },
+ "from_agent": {"type": "string", "description": "Who assigns. Default 'user'."},
+ },
+ ["agent", "task"],
+ ),
+ handler=_agent_assign,
+ dangerous=True,
+ tags=("work",),
+ ),
+ AgentTool(
+ name="agent_inbox",
+ description=(
+ "Everything addressed to one agent, oldest first. Pass after_seq with the "
+ "last_seq you got back to read only what is new — this is how you follow "
+ "a conversation or an assignment without re-reading history."
+ ),
+ input_schema=_obj(
+ {
+ "agent": _AGENT_REF,
+ "after_seq": {"type": "integer", "description": "Only events after this seq."},
+ },
+ ["agent"],
+ ),
+ handler=_agent_inbox,
+ tags=("board",),
+ ),
+ AgentTool(
+ name="board_events",
+ description=(
+ "The ecosystem's event stream — every message, assignment, claim, result "
+ "and veto, in order. Filter by agent or by trace_id to follow one piece "
+ "of work end to end, or poll with after_seq to watch the house live."
+ ),
+ input_schema=_obj(
+ {
+ "after_seq": {"type": "integer"},
+ "agent": {"type": "string", "description": "Only this agent's events."},
+ "trace_id": {"type": "string", "description": "One task's full trail."},
+ "limit": {"type": "integer", "description": "1-1000, default 100."},
+ }
+ ),
+ handler=_board_events,
+ tags=("board",),
+ ),
+ AgentTool(
+ name="agent_create",
+ description=(
+ "Add a teammate. Focus and approval rules are derived from the title and "
+ "description — no model call, deterministic. Creating an agent executes "
+ "nothing; it only puts a row on the roster."
+ ),
+ input_schema=_obj(
+ {
+ "name": {"type": "string", "description": "Short unique handle, e.g. 'Scout'."},
+ "title": {"type": "string", "description": "Its role, e.g. 'Research analyst'."},
+ "description": {
+ "type": "string",
+ "description": "What it is for. Drives its focus and approval rules.",
+ },
+ "tier": {
+ "type": "string",
+ "enum": ["orchestrator", "specialist"],
+ "description": "Default specialist. The lead seat is Jarvis' and is taken.",
+ },
+ },
+ ["name", "title", "description"],
+ ),
+ handler=_agent_create,
+ tags=("roster",),
+ ),
+ AgentTool(
+ name="rooms_list",
+ description="Every room: who is in it, the topic, whose turn it is, and its state.",
+ input_schema=_obj({}),
+ handler=_rooms_list,
+ tags=("rooms",),
+ ),
+ AgentTool(
+ name="room_open",
+ description=(
+ "Open a bounded discussion between 2-6 agents on one topic. Rooms are "
+ "capped (≤3 rounds, ≤10 messages) so a debate cannot run away."
+ ),
+ input_schema=_obj(
+ {
+ "members": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "2-6 agent ids or names.",
+ },
+ "topic": {"type": "string"},
+ "opened_by": {"type": "string", "description": "Default 'user'."},
+ },
+ ["members", "topic"],
+ ),
+ handler=_room_open,
+ tags=("rooms",),
+ ),
+ AgentTool(
+ name="room_say",
+ description=(
+ "Speak in a room as one of its members. Turn order is enforced — saying "
+ "out of turn is refused with the reason."
+ ),
+ input_schema=_obj(
+ {
+ "room_id": {"type": "string"},
+ "member": _AGENT_REF,
+ "text": {"type": "string"},
+ },
+ ["room_id", "member", "text"],
+ ),
+ handler=_room_say,
+ dangerous=True,
+ tags=("rooms",),
+ ),
+ AgentTool(
+ name="room_settle",
+ description="Close a room and record its outcome. Nothing more is said in it after.",
+ input_schema=_obj({"room_id": {"type": "string"}}, ["room_id"]),
+ handler=_room_settle,
+ dangerous=True,
+ tags=("rooms",),
+ ),
+ AgentTool(
+ name="approvals_list",
+ description=(
+ "What the person still has to decide: actions agents parked because they "
+ "sit above their permission ceiling. Oldest first."
+ ),
+ input_schema=_obj({"agent": {"type": "string", "description": "Only this agent's."}}),
+ handler=_approvals_list,
+ tags=("governance",),
+ ),
+ AgentTool(
+ name="approval_resolve",
+ description=(
+ "Approve or deny one parked action. Approving does NOT run it — whoever "
+ "asked runs it once the answer is there."
+ ),
+ input_schema=_obj(
+ {
+ "approval_id": {"type": "string"},
+ "approve": {"type": "boolean"},
+ "note": {"type": "string", "description": "Why. Recorded with the decision."},
+ },
+ ["approval_id", "approve"],
+ ),
+ handler=_approval_resolve,
+ dangerous=True,
+ tags=("governance",),
+ ),
+ AgentTool(
+ name="kill_switch",
+ description=(
+ "The ecosystem's emergency stop. Engaging halts every run, settles every "
+ "room, cancels every mission and closes the agents' browser. Releasing it "
+ "lets work resume — dangerous in both directions."
+ ),
+ input_schema=_obj(
+ {"engage": {"type": "boolean", "description": "true stops everything, false resumes."}},
+ ["engage"],
+ ),
+ handler=_kill_switch,
+ dangerous=True,
+ tags=("governance",),
+ ),
+)
+
+_BY_NAME: Final[dict[str, AgentTool]] = {t.name: t for t in TOOLS}
+
+
+def tool_specs() -> list[dict[str, Any]]:
+ """The catalog as plain dicts — what the MCP list_tools handler serves."""
+ return [
+ {
+ "name": t.name,
+ "description": t.description,
+ "inputSchema": t.input_schema,
+ "dangerous": t.dangerous,
+ "tags": list(t.tags),
+ }
+ for t in TOOLS
+ ]
+
+
+def get(name: str) -> AgentTool | None:
+ return _BY_NAME.get(name)
+
+
+async def call(name: str, arguments: dict[str, Any] | None) -> str:
+ """Run one tool and render its result as the text the model reads back.
+
+ Every failure mode leaves here as readable text rather than an exception:
+ an MCP tool error is a dead end for the model, while a sentence explaining
+ what went wrong and what to try instead keeps the conversation going.
+ """
+ tool = _BY_NAME.get(name)
+ if tool is None:
+ known = ", ".join(sorted(_BY_NAME))
+ return f"No such tool: {name}. This server offers: {known}"
+ try:
+ result = await tool.handler(dict(arguments or {}))
+ except EcosystemUnavailable as exc:
+ return f"Not possible right now — {exc.what} is not available: {exc.hint}"
+ except (KeyError, ValueError, TypeError) as exc:
+ return f"Bad request for {name}: {exc}"
+ except Exception as exc: # noqa: BLE001 — a tool failure is data for the model, not a crash
+ log.warning("agent MCP: %s raised", name, exc_info=True)
+ return f"{name} failed: {type(exc).__name__}: {exc}"
+ if isinstance(result, str):
+ return result
+ try:
+ return json.dumps(result, ensure_ascii=False, default=str, indent=2)
+ except (TypeError, ValueError):
+ return str(result)
+
+
+__all__ = [
+ "DEFAULT_WAIT_S",
+ "MAX_WAIT_S",
+ "MCP_ORIGIN",
+ "TOOLS",
+ "AgentTool",
+ "call",
+ "get",
+ "tool_specs",
+]
diff --git a/jarvis/ui/web/agent_mcp_routes.py b/jarvis/ui/web/agent_mcp_routes.py
new file mode 100644
index 0000000000..7d0ba7a9f7
--- /dev/null
+++ b/jarvis/ui/web/agent_mcp_routes.py
@@ -0,0 +1,125 @@
+"""Connect-flow for the Agent MCP surface (``/api/agent-mcp``).
+
+The surface itself is mounted raw at ``/api/control/mcp/agents`` because the
+MCP transport needs an untouched ASGI triple. These routes are the *about* and
+*connect* layer around it: what the surface offers, which clients this machine
+has, the config snippet for each, and — behind an explicit call — writing that
+entry into the client's own config.
+
+``connect`` carries ``x-jarvis-dangerous`` because it writes a file that
+belongs to another application. Reading a snippet does not: a person copying
+text into their own editor is the safe path and should never need a
+confirmation.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/agent-mcp", tags=["agent-mcp"])
+
+# Every handler here is a plain ``def``: none of them awaits, and they touch
+# the filesystem. FastAPI runs a sync handler in the anyio threadpool, off the
+# one event loop the whole app shares — an ``async def`` that never awaits
+# would block it for the length of each config read (check_async_routes).
+
+
[email protected]("/status", openapi_extra={"x-jarvis-readonly": True})
+def agent_mcp_status() -> dict[str, Any]:
+ """What the Agent MCP surface is and what it currently offers."""
+ from jarvis.mcp.agents import SERVER_NAME, tool_specs
+ from jarvis.mcp.agents.bridge import SURFACE_PATH, api_base_url
+ from jarvis.mcp.agents.server import PROTOCOL_VERSION
+
+ specs = tool_specs()
+ return {
+ "server_name": SERVER_NAME,
+ "protocol_version": PROTOCOL_VERSION,
+ "url": f"{api_base_url()}{SURFACE_PATH}",
+ "auth": "bearer-control-key",
+ "tools": [
+ {
+ "name": s["name"],
+ "description": s["description"],
+ "dangerous": s["dangerous"],
+ "tags": s["tags"],
+ }
+ for s in specs
+ ],
+ "tool_count": len(specs),
+ "bridge_command": ["python", "-m", "jarvis.mcp.agents.bridge"],
+ }
+
+
[email protected]("/clients", openapi_extra={"x-jarvis-readonly": True})
+def agent_mcp_clients() -> dict[str, Any]:
+ """Every MCP client this machine could connect, and whether it is installed."""
+ from jarvis.mcp.agents import export
+
+ rows = [
+ {
+ "key": t.key,
+ "label": t.label,
+ "config_path": str(t.config_path) if t.config_path else None,
+ "shape": t.shape,
+ "installed": t.installed,
+ "writable": t.shape != "toml",
+ }
+ for t in export.targets()
+ ]
+ return {"clients": rows, "total": len(rows)}
+
+
[email protected]("/snippet", openapi_extra={"x-jarvis-readonly": True})
+def agent_mcp_snippet(client: str = "claude-desktop", transport: str = "stdio") -> dict[str, Any]:
+ """The config block to paste into one client."""
+ from jarvis.mcp.agents import export
+
+ if transport not in ("stdio", "http"):
+ raise HTTPException(422, "transport must be 'stdio' or 'http'")
+ known = {t.key for t in export.targets()}
+ if client not in known:
+ raise HTTPException(404, f"unknown client {client!r}. Known: {sorted(known)}")
+ return {
+ "client": client,
+ "transport": transport,
+ "snippet": export.snippet(client, transport=transport),
+ }
+
+
+class ConnectBody(BaseModel):
+ client: str = Field(description="claude-desktop, cursor, claude-code or codex")
+ transport: str = Field(default="stdio", description="stdio (preferred) or http")
+ include_key: bool = Field(
+ default=False,
+ description=(
+ "Write the control key into the client's config. Off by default — the "
+ "bridge reads it from the credential store instead."
+ ),
+ )
+
+
[email protected]("/connect", openapi_extra={"x-jarvis-dangerous": True})
+def agent_mcp_connect(body: ConnectBody) -> dict[str, Any]:
+ """Write the Jarvis entry into a client's own MCP config."""
+ from jarvis.mcp.agents import export
+
+ if body.transport not in ("stdio", "http"):
+ raise HTTPException(422, "transport must be 'stdio' or 'http'")
+ result = export.install(body.client, transport=body.transport, include_key=body.include_key)
+ if not result.get("ok"):
+ # A refusal with a snippet is guidance, not a failure — hand it back at
+ # 200 so the caller can show the text instead of an error toast.
+ if result.get("snippet"):
+ return result
+ raise HTTPException(400, result.get("error") or "could not write the config")
+ return result
+
+
+__all__ = ["router"]
diff --git a/jarvis/ui/web/mcp_server_routes.py b/jarvis/ui/web/mcp_server_routes.py
index e12ab7b592..546b28ed28 100644
--- a/jarvis/ui/web/mcp_server_routes.py
+++ b/jarvis/ui/web/mcp_server_routes.py
@@ -1,35 +1,102 @@
-"""Serve Jarvis' own tools over MCP, so a spawned agent session can drive them.
+"""Jarvis' two outward MCP surfaces, on one mount.
+
+* ``/api/control/mcp`` — Jarvis' own TOOLS, so a session Jarvis spawned
+ can reach back in and drive the app: open an app, read the wiki, switch
+ provider. The model's hands are the voice's hands.
+* ``/api/control/mcp/agents`` — the AGENT ECOSYSTEM, for any client holding the
+ control key: the roster, the board, rooms, assignments, approvals. This is
+ what lets Claude Desktop, Cursor or another Jarvis talk to the team.
Mounted as a raw ASGI sub-app rather than a FastAPI router: the MCP Streamable
HTTP transport needs the untouched ``(scope, receive, send)`` triple — it
streams, negotiates its own content types and answers ``GET``/``DELETE`` as
well as ``POST``. Wrapping that in a response model would fight it.
+ONE mount serves both, choosing on the rest of the path (``_surface_for``); two
+Starlette mounts cannot, because a ``Mount`` requires a path segment AFTER its
+prefix and a plain ``POST /api/control/mcp/agents`` would silently fall through
+to the shorter one.
+
Authentication is the Control API's Bearer key, checked here instead of by a
dependency for the same reason. The rule is the Control API's rule (see
``control_auth``): loopback does NOT bypass it. The key is exactly what makes
-this surface safe to exist — anything on the machine could otherwise open a
-socket and start driving the person's calendar.
-
-The session manager is stateless (a fresh transport per request), so a chat
-turn that dies mid-tool leaves nothing to clean up. Its task group is started
-on first use and lives for the process — there is no lifespan hook on this app
-to hang it from, and one background task is cheaper than a per-request one.
+these surfaces safe to exist — anything on the machine could otherwise open a
+socket and start driving the person's calendar, or their agents.
+
+Each surface keeps its own stateless session manager (a fresh transport per
+request), so a chat turn that dies mid-tool leaves nothing to clean up. Their
+task groups start on first use and live for the process — there is no lifespan
+hook on this app to hang them from, and one background task per surface is
+cheaper than one per request.
"""
from __future__ import annotations
import asyncio
import logging
+from collections.abc import Callable
from typing import Any
log = logging.getLogger(__name__)
_UNAUTHORIZED_BODY = b'{"error":"Invalid or missing Jarvis Control API key."}'
+_NOT_A_SURFACE_BODY = (
+ b'{"error":"No Jarvis MCP surface at this path. '
+ b'Use /api/control/mcp or /api/control/mcp/agents."}'
+)
+
+
+class _Surface:
+ """One mounted MCP server: its builder plus the session manager it runs on.
+
+ Two surfaces share this machinery — ``tools`` (Jarvis' hands, for a session
+ Jarvis spawned) and ``agents`` (the ecosystem, for any client holding the
+ control key). Each keeps its OWN manager because the transport's task group
+ is per server; sharing one would put both catalogs on one connection and
+ make a client choose tools it was never offered.
+ """
+
+ def __init__(self, name: str, builder: Callable[[], Any]) -> None:
+ self.name = name
+ self._builder = builder
+ self._manager: Any | None = None
+ self._ready: asyncio.Event | None = None
+ self._task: asyncio.Task[None] | None = None
+
+ async def manager(self) -> Any | None:
+ if self._manager is not None and self._ready is not None:
+ await self._ready.wait()
+ return self._manager
+ try:
+ from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
+
+ server = self._builder()
+ except Exception: # noqa: BLE001 — no MCP library → the surface is simply absent
+ log.warning("jarvis MCP: %s server unavailable", self.name, exc_info=True)
+ return None
+ manager = StreamableHTTPSessionManager(app=server, json_response=True, stateless=True)
+ ready = asyncio.Event()
+ self._manager = manager
+ self._ready = ready
+ self._task = asyncio.create_task(_run_manager(manager, ready))
+ await ready.wait()
+ return manager
+
+
+def _build_tools_server() -> Any:
+ from jarvis.mcp.jarvis_tools_server import build_server
-_manager: Any | None = None
-_manager_ready: asyncio.Event | None = None
-_manager_task: asyncio.Task[None] | None = None
+ return build_server()
+
+
+def _build_agents_server() -> Any:
+ from jarvis.mcp.agents import build_server
+
+ return build_server()
+
+
+_TOOLS_SURFACE = _Surface("tools", _build_tools_server)
+_AGENTS_SURFACE = _Surface("agents", _build_agents_server)
def _bearer(scope: dict[str, Any]) -> str | None:
@@ -84,33 +151,55 @@ async def _run_manager(manager: Any, ready: asyncio.Event) -> None:
ready.set() # unblock waiters so they fail fast instead of hanging
-async def _ensure_manager() -> Any | None:
- global _manager, _manager_ready, _manager_task
- if _manager is not None and _manager_ready is not None:
- await _manager_ready.wait()
- return _manager
- try:
- from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
-
- from jarvis.mcp.jarvis_tools_server import build_server
- except Exception: # noqa: BLE001 — no MCP library → the surface is simply absent
- log.warning("jarvis MCP: server unavailable", exc_info=True)
- return None
- manager = StreamableHTTPSessionManager(
- app=build_server(),
- json_response=True,
- stateless=True,
- )
- ready = asyncio.Event()
- _manager = manager
- _manager_ready = ready
- _manager_task = asyncio.create_task(_run_manager(manager, ready))
- await ready.wait()
- return manager
+#: Rest-path suffixes that select a surface, matched after the mount strips
+#: ``/api/control/mcp``. Empty (or ``/``) is the tools surface, which is what
+#: every already-configured client sends.
+_SUFFIX_SURFACES: dict[str, _Surface] = {
+ "": _TOOLS_SURFACE,
+ "agents": _AGENTS_SURFACE,
+}
+
+
+def surface_suffix(scope: dict[str, Any]) -> str:
+ """The path left after the mount prefix, without slashes.
+
+ Starlette ≥ 0.33 leaves ``scope["path"]`` as the FULL request path and
+ reports the mount prefix separately in ``root_path``; older releases handed
+ the sub-app the remainder in ``path``. Both are handled here, because
+ guessing wrong routes every client to the wrong catalog.
+ """
+ path = scope.get("path") or ""
+ root = scope.get("root_path") or ""
+ if root and path.startswith(root):
+ path = path[len(root) :]
+ return path.strip("/")
+
+
+def _surface_for(scope: dict[str, Any]) -> _Surface | None:
+ """Which surface a request is for, from the path left after the mount.
+
+ ONE mount serves both, dispatched here rather than by two Starlette mounts.
+ A ``Mount`` on ``/api/control/mcp/agents`` builds the path regex
+ ``^/api/control/mcp/agents(?P<path>/.*)$`` — it requires something AFTER
+ the mount path, so a plain ``POST /api/control/mcp/agents`` does not match
+ it at all and falls through to the shorter mount. The client would then get
+ the tools catalog on the agents URL: same transport, same auth, wrong
+ tools, and no error anywhere to notice it by.
+ """
+ return _SUFFIX_SURFACES.get(surface_suffix(scope))
def build_mcp_asgi_app() -> Any:
- """The ASGI app to mount at ``/api/control/mcp``."""
+ """The ASGI app to mount at ``/api/control/mcp`` — both surfaces.
+
+ * ``/api/control/mcp`` — Jarvis' own tools, for a session it spawned.
+ * ``/api/control/mcp/agents`` — the agent ecosystem, for any client holding
+ the control key: roster, board, rooms, assignments, approvals.
+
+ Authentication is the Control API's for both, and loopback does NOT bypass
+ it: anything on the machine could otherwise open a socket and start driving
+ the person's team.
+ """
async def app(scope: dict[str, Any], receive: Any, send: Any) -> None:
if scope.get("type") != "http":
@@ -120,10 +209,20 @@ def build_mcp_asgi_app() -> Any:
if not ck.verify_control_key(_bearer(scope)):
await _reject(send, 401, _UNAUTHORIZED_BODY)
return
- manager = await _ensure_manager()
+ surface = _surface_for(scope)
+ if surface is None:
+ await _reject(send, 404, _NOT_A_SURFACE_BODY)
+ return
+ manager = await surface.manager()
if manager is None:
await _reject(send, 503, b'{"error":"Jarvis MCP server is not available."}')
return
+ if surface is _AGENTS_SURFACE:
+ # A remote client is not one of Jarvis' own spawned sessions, so
+ # there is no chat card to route an approval to; parked actions
+ # surface through the approvals_list tool instead.
+ await manager.handle_request(scope, receive, send)
+ return
# The session travels in a ContextVar: the stateless transport runs
# the tool call in a task started from this request, which inherits
# the context, and the tool server reads it when it builds the
@@ -139,4 +238,4 @@ def build_mcp_asgi_app() -> Any:
return app
-__all__ = ["build_mcp_asgi_app", "session_ref"]
+__all__ = ["build_mcp_asgi_app", "session_ref", "surface_suffix"]
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index a650ac8ffe..735b49aa53 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -331,6 +331,7 @@ class WebServer:
from .agent_accounts_routes import router as agent_accounts_router
from .agent_chat_routes import router as agent_chat_router
+ from .agent_mcp_routes import router as agent_mcp_router
from .agentic_ide_routes import router as agentic_ide_router
from .antigravity_routes import router as antigravity_router
from .board_routes import (
@@ -418,6 +419,9 @@ class WebServer:
logger.warning("Conductor module not available: {} — Conductor view stays empty", exc)
conductor_router = None
app.include_router(mcp_router)
+ # Connect-flow for the Agent MCP surface: what it offers, which
+ # clients this box has, and writing the entry into their config.
+ app.include_router(agent_mcp_router)
app.include_router(tools_router)
app.include_router(tool_model_router)
# Jarvis' OWN tools, offered outwards over MCP so an agent-chat session
@@ -425,6 +429,10 @@ class WebServer:
# the Control API; mounted raw because the transport streams.
from jarvis.ui.web.mcp_server_routes import build_mcp_asgi_app
+ # ONE mount, two surfaces, dispatched inside on the rest of the path:
+ # "" is Jarvis' own tools, "/agents" is the agent ecosystem. A second
+ # Starlette mount on the longer path would never match a request
+ # without a trailing slash — see mcp_server_routes._surface_for.
app.mount("/api/control/mcp", build_mcp_asgi_app())
# Event-loop diagnostics (read-only) — names the owner of an AP-20
# cancellation busy-loop from inside the loop; see diagnostics_routes.
diff --git a/tests/contract/test_agent_mcp_surface.py b/tests/contract/test_agent_mcp_surface.py
new file mode 100644
index 0000000000..9552aba7f4
--- /dev/null
+++ b/tests/contract/test_agent_mcp_surface.py
@@ -0,0 +1,258 @@
+"""The Agent MCP contract: what any client connecting to Jarvis may rely on.
+
+This is the promise the surface makes to the outside world, so it is pinned
+here rather than left to drift: the tool set and its shape, the safety
+properties (no spawn vehicle, dangerous work marked), and one end-to-end run
+proving a client can find the team, talk to it, give it work and read the
+result without ever touching the REST layer.
+
+Headless by construction — no GPU, no audio, no model, no network.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+
+from jarvis.core import runtime_refs
+from jarvis.mcp.agents import SERVER_NAME, tool_specs
+from jarvis.mcp.agents import tools as agent_tools
+from jarvis.society.runtime import SocietyRuntime
+
+#: The vocabulary a client is entitled to find. Adding a tool is a feature;
+#: removing or renaming one breaks every connected client, so it fails here.
+EXPECTED_TOOLS = {
+ "ecosystem_status",
+ "agents_list",
+ "agent_get",
+ "agent_chat",
+ "agent_message",
+ "agent_assign",
+ "agent_inbox",
+ "board_events",
+ "agent_create",
+ "rooms_list",
+ "room_open",
+ "room_say",
+ "room_settle",
+ "approvals_list",
+ "approval_resolve",
+ "kill_switch",
+}
+
+#: Everything that starts spend, work, or stops the house. A tool that becomes
+#: dangerous without being listed here is a client that stopped asking first.
+EXPECTED_DANGEROUS = {
+ "agent_chat",
+ "agent_message",
+ "agent_assign",
+ "room_say",
+ "room_settle",
+ "approval_resolve",
+ "kill_switch",
+}
+
+#: MCP's own rule for a tool name.
+_NAME_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")
+
+
+class FakeManager:
+ """A mission manager that accepts work without running any."""
+
+ def __init__(self) -> None:
+ self.dispatched: list[str] = []
+
+ async def dispatch(self, *, prompt: str, **kwargs: Any) -> str:
+ self.dispatched.append(prompt)
+ return f"m-{len(self.dispatched)}"
+
+
+def ecosystem(tmp_path: Path) -> Any:
+ """A live society reachable exactly the way the MCP tools reach it."""
+ runtime = SocietyRuntime(
+ tmp_path, seed_starter_team=False, mission_manager=lambda: FakeManager()
+ )
+ app = FastAPI()
+ app.state.society = None
+ app.state.society_factory = lambda: runtime
+ runtime_refs.set_web_app(app)
+ try:
+ yield runtime
+ finally:
+ runtime_refs._reset_for_tests()
+
+
+async def _call(tool: str, **args: Any) -> Any:
+ """One tool call, decoded — the shape a client actually receives.
+
+ The parameter is ``tool``, not ``name``: ``agent_create`` takes a ``name``
+ argument of its own and a collision here would hide it.
+ """
+ text = await agent_tools.call(tool, args)
+ try:
+ return json.loads(text)
+ except json.JSONDecodeError:
+ return text
+
+
+# ------------------------------------------------------------ the contract
+
+
+def test_tool_set_is_the_published_one() -> None:
+ names = {spec["name"] for spec in tool_specs()}
+ assert names == EXPECTED_TOOLS
+
+
+def test_dangerous_tools_are_marked() -> None:
+ marked = {spec["name"] for spec in tool_specs() if spec["dangerous"]}
+ assert marked == EXPECTED_DANGEROUS
+
+
+def test_every_tool_is_usable_by_a_client() -> None:
+ """Name, description and schema — a client cannot call what it cannot read."""
+ for spec in tool_specs():
+ name = spec["name"]
+ assert name and len(name) <= 128, name
+ assert set(name) <= _NAME_CHARS, name
+ assert len(spec["description"]) > 40, f"{name} has no usable description"
+ schema = spec["inputSchema"]
+ assert schema["type"] == "object", name
+ assert "properties" in schema, name
+ for prop, body in schema["properties"].items():
+ assert "type" in body, f"{name}.{prop} has no type"
+
+
+def test_no_spawn_vehicle_is_offered() -> None:
+ """AP-5/AP-14: a client is a person with a keyboard, not a second router."""
+ forbidden = ("spawn", "dispatch_to_harness", "multi_spawn", "sub_agent")
+ for spec in tool_specs():
+ blob = f"{spec['name']} {spec['description']}".lower()
+ assert not any(f in spec["name"].lower() for f in forbidden), spec["name"]
+ assert "spawn-worker" not in blob
+
+
+def test_server_name_is_distinct_from_the_tools_surface() -> None:
+ """Both surfaces may be connected at once, so their names must not collide."""
+ from jarvis.mcp.jarvis_tools_server import build_server as tools_server
+
+ assert SERVER_NAME == "jarvis-agents"
+ assert tools_server().name != SERVER_NAME
+
+
+def test_unknown_tool_answers_with_the_catalog() -> None:
+ """A dead end for the model is a bug; a wrong name must teach the right ones."""
+ import asyncio
+
+ answer = asyncio.run(agent_tools.call("no_such_tool", {}))
+ assert "No such tool" in answer
+ assert "agents_list" in answer
+
+
+# ------------------------------------------------------------- end to end
+
+
+async def test_a_client_runs_the_whole_loop_headless(ecosystem: Any) -> None:
+ """Find the team, write to it, assign work, read the board — tools only."""
+ # 1. The house, before anything exists.
+ status = await _call("ecosystem_status")
+ assert status["kill_switch"] is False
+ assert status["agents_total"] == 1 # the lead seat is Jarvis'
+
+ # 2. Hire a teammate.
+ created = await _call(
+ "agent_create",
+ name="Scout",
+ title="Research scout",
+ description="Finds and checks facts on the open web.",
+ )
+ assert created["created"] is True
+ scout_id = created["agent"]["agent_id"]
+
+ # 3. It shows up on the roster, idle.
+ roster = await _call("agents_list")
+ rows = {a["name"]: a for a in roster["agents"]}
+ assert "Scout" in rows
+ assert rows["Scout"]["run_state"] == "idle"
+
+ # 4. Leave it a note — by NAME, the way a person would.
+ note = await _call("agent_message", agent="Scout", text="Welcome aboard.")
+ assert note["delivered_to"] == "Scout"
+ assert note["event"]["msg_type"] == "SAY"
+
+ # 5. The note is in its inbox, and the board agrees.
+ inbox = await _call("agent_inbox", agent="Scout")
+ assert [e["msg_type"] for e in inbox["events"]] == ["SAY"]
+ board = await _call("board_events")
+ assert board["last_seq"] == inbox["last_seq"]
+
+ # 6. Give it a task. The scheduler answers on the same trace.
+ assigned = await _call("agent_assign", agent=scout_id, task="Check the changelog.")
+ assert assigned["assigned_to"] == "Scout"
+ assert assigned["trace_id"].startswith("task:")
+ assert assigned["outcome"] is not None, "the scheduler must answer an ASSIGN"
+
+ # 7. Reading one agent shows the trail.
+ detail = await _call("agent_get", agent="Scout")
+ assert detail["agent"]["agent_id"] == scout_id
+ assert {e["msg_type"] for e in detail["recent_events"]} >= {"SAY", "ASSIGN"}
+
+
+async def test_unknown_agent_names_the_known_ones(ecosystem: Any) -> None:
+ answer = await agent_tools.call("agent_message", {"agent": "Nobody", "text": "hi"})
+ assert "Nobody" in answer
+ assert "no agent by that id or name" in answer
+ assert "Jarvis" in answer, "the refusal must list who DOES exist"
+
+
+async def test_kill_switch_stops_conversation(ecosystem: Any) -> None:
+ """The emergency stop is real: with it engaged, nobody can be talked to."""
+ await _call("agent_create", name="Scout", title="Scout", description="Finds things.")
+ engaged = await _call("kill_switch", engage=True)
+ assert engaged["engaged"] is True
+
+ refused = await agent_tools.call("agent_chat", {"agent": "Scout", "text": "hello"})
+ assert "kill switch" in refused.lower()
+
+ released = await _call("kill_switch", engage=False)
+ assert released.get("engaged") is False
+
+
+async def test_rooms_are_bounded_and_named_members_resolve(ecosystem: Any) -> None:
+ await _call("agent_create", name="Scout", title="Scout", description="Finds things.")
+ await _call("agent_create", name="Archivist", title="Curator", description="Keeps notes.")
+
+ opened = await _call(
+ "room_open", members=["Scout", "Archivist"], topic="Where do we store facts?"
+ )
+ room = opened["room"]
+ assert len(room["members"]) == 2
+ assert room["state"] in ("queued", "running")
+
+ listed = await _call("rooms_list")
+ assert [r["room_id"] for r in listed["rooms"]] == [room["room_id"]]
+
+ # A single-member room is not a discussion.
+ refused = await agent_tools.call("room_open", {"members": ["Scout"], "topic": "alone"})
+ assert "at least 2 members" in refused
+
+
+async def test_a_broken_call_never_raises_out_of_the_surface(ecosystem: Any) -> None:
+ """Every failure leaves as readable text — an MCP error ends the model's turn."""
+ for name, args in (
+ ("agent_get", {}), # missing required argument
+ ("agent_assign", {"agent": "Jarvis", "task": " "}), # empty task
+ ("agent_message", {"agent": "Jarvis", "text": "x", "msg_type": "ASSIGN"}),
+ ("approval_resolve", {"approval_id": "nope", "approve": True}),
+ ):
+ answer = await agent_tools.call(name, args)
+ assert isinstance(answer, str) and answer.strip()
diff --git a/tests/unit/mcp/test_agent_mcp_chat.py b/tests/unit/mcp/test_agent_mcp_chat.py
new file mode 100644
index 0000000000..0784b89e9a
--- /dev/null
+++ b/tests/unit/mcp/test_agent_mcp_chat.py
@@ -0,0 +1,210 @@
+"""``agent_chat``: the tool that turns an MCP client into a keyboard.
+
+The contract test proves the surface refuses to talk when the kill switch is
+on. This one proves the happy path and the shapes around it, against a fake
+chat service — no model, no provider, no network.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.core import runtime_refs
+from jarvis.mcp.agents import tools as agent_tools
+from jarvis.society.runtime import SocietyRuntime
+
+
+class FakeChatService:
+ """A chat service that answers a scripted turn on the subscriber queue."""
+
+ def __init__(self, store: AgentChatStore, script: list[dict[str, Any]] | None = None) -> None:
+ self.store = store
+ self.sent: list[tuple[str, str]] = []
+ self.busy: set[str] = set()
+ self._subs: dict[str, set[asyncio.Queue[Any]]] = {}
+ self._script = script
+
+ def is_running(self, session_id: str) -> bool:
+ return session_id in self.busy
+
+ def subscribe(self, session_id: str) -> asyncio.Queue[Any]:
+ q: asyncio.Queue[Any] = asyncio.Queue()
+ self._subs.setdefault(session_id, set()).add(q)
+ return q
+
+ def unsubscribe(self, session_id: str, q: asyncio.Queue[Any]) -> None:
+ self._subs.get(session_id, set()).discard(q)
+
+ async def send(self, session_id: str, text: str, attachments: Any = None) -> str:
+ self.sent.append((session_id, text))
+ turn_id = f"turn-{len(self.sent)}"
+ events = self._script if self._script is not None else _default_script(text)
+ for event in events:
+ payload = dict(event.get("payload") or {})
+ payload.setdefault("turn_id", turn_id)
+ for q in self._subs.get(session_id, set()):
+ q.put_nowait({"kind": event["kind"], "payload": payload})
+ return turn_id
+
+
+def _default_script(text: str) -> list[dict[str, Any]]:
+ return [
+ {"kind": "tool_call", "payload": {"name": "wiki-recall"}},
+ {"kind": "assistant_text", "payload": {"text": f"Heard you: {text}"}},
+ {"kind": "turn_finished", "payload": {"status": "ok"}},
+ ]
+
+
+async def world(tmp_path: Path):
+ """A society whose agents have a working (fake) chat behind them."""
+ svc = FakeChatService(AgentChatStore(tmp_path / "agent_chat.db"))
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ runtime = SocietyRuntime(
+ tmp_path,
+ seed_starter_team=False,
+ chat_service=lambda: svc,
+ cfg=lambda: cfg,
+ )
+ await runtime.ensure_started()
+ app = FastAPI()
+ app.state.society = runtime
+ app.state.society_factory = lambda: runtime
+ runtime_refs.set_web_app(app)
+ try:
+ yield runtime, svc
+ finally:
+ runtime_refs._reset_for_tests()
+ await runtime.close()
+
+
+async def _call(tool: str, **args: Any) -> Any:
+ text = await agent_tools.call(tool, args)
+ try:
+ return json.loads(text)
+ except json.JSONDecodeError:
+ return text
+
+
+async def test_a_client_writes_to_an_agent_and_gets_the_answer(world) -> None:
+ rt, svc = world
+ await rt.roster.create(
+ name="Scout", title="Scout", description="Finds things.", provider="openai", model="gpt-5.2"
+ )
+
+ answer = await _call("agent_chat", agent="Scout", text="What is on the board?")
+
+ assert answer["status"] == "answered"
+ assert answer["reply"] == "Heard you: What is on the board?"
+ assert answer["tool_calls"] == ["wiki-recall"]
+ assert answer["agent_name"] == "Scout"
+ assert answer["session_id"] == "society:scout"
+ # The message reached the agent's OWN canonical session, not a fresh one.
+ assert svc.sent == [("society:scout", "What is on the board?")]
+
+
+async def test_a_busy_agent_says_so_instead_of_queueing(world) -> None:
+ rt, svc = world
+ await rt.roster.create(
+ name="Scout", title="Scout", description="Finds things.", provider="openai", model="gpt-5.2"
+ )
+ # Seat the session, then mark it mid-turn.
+ await _call("agent_chat", agent="Scout", text="first")
+ svc.busy.add("society:scout")
+
+ refused = await agent_tools.call("agent_chat", {"agent": "Scout", "text": "second"})
+
+ assert "middle of a turn" in refused
+ assert len(svc.sent) == 1, "a busy agent must not be sent a second message"
+
+
+async def test_a_blocked_turn_reports_the_reason(tmp_path: Path) -> None:
+ svc = FakeChatService(
+ AgentChatStore(tmp_path / "agent_chat.db"),
+ script=[
+ {"kind": "assistant_text", "payload": {"text": "partial"}},
+ {"kind": "error", "payload": {"message": "provider refused"}},
+ ],
+ )
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ runtime = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await runtime.ensure_started()
+ app = FastAPI()
+ app.state.society = runtime
+ app.state.society_factory = lambda: runtime
+ runtime_refs.set_web_app(app)
+ try:
+ await runtime.roster.create(
+ name="Scout",
+ title="Scout",
+ description="Finds things.",
+ provider="openai",
+ model="gpt-5.2",
+ )
+ answer = await _call("agent_chat", agent="Scout", text="hello")
+ assert answer["status"] == "blocked"
+ assert answer["error"] == "provider refused"
+ assert answer["reply"] == "partial", "what was said before the failure is kept"
+ finally:
+ runtime_refs._reset_for_tests()
+ await runtime.close()
+
+
+async def test_a_slow_turn_returns_still_running_rather_than_hanging(tmp_path: Path) -> None:
+ """A conversation that outlives the wait hands back a way to follow it."""
+ svc = FakeChatService(AgentChatStore(tmp_path / "agent_chat.db"), script=[])
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ runtime = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await runtime.ensure_started()
+ app = FastAPI()
+ app.state.society = runtime
+ app.state.society_factory = lambda: runtime
+ runtime_refs.set_web_app(app)
+ try:
+ await runtime.roster.create(
+ name="Scout",
+ title="Scout",
+ description="Finds things.",
+ provider="openai",
+ model="gpt-5.2",
+ )
+ answer = await _call("agent_chat", agent="Scout", text="think hard", timeout_s=0.2)
+ assert answer["status"] == "still_running"
+ assert "agent_inbox" in answer["note"]
+ finally:
+ runtime_refs._reset_for_tests()
+ await runtime.close()
+
+
+async def test_chat_without_a_service_refuses_readably(tmp_path: Path) -> None:
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)
+ await runtime.ensure_started()
+ app = FastAPI()
+ app.state.society = runtime
+ app.state.society_factory = lambda: runtime
+ runtime_refs.set_web_app(app)
+ try:
+ await runtime.roster.create(
+ name="Scout",
+ title="Scout",
+ description="Finds things.",
+ provider="openai",
+ model="gpt-5.2",
+ )
+ refused = await agent_tools.call("agent_chat", {"agent": "Scout", "text": "hi"})
+ assert "chat service is not running" in refused
+ finally:
+ runtime_refs._reset_for_tests()
+ await runtime.close()
diff --git a/tests/unit/mcp/test_agent_mcp_export.py b/tests/unit/mcp/test_agent_mcp_export.py
new file mode 100644
index 0000000000..b65e4424c4
--- /dev/null
+++ b/tests/unit/mcp/test_agent_mcp_export.py
@@ -0,0 +1,112 @@
+"""Connecting the Agent MCP surface to an outside client's own config.
+
+Writing into somebody else's config file is the one operation here that can
+destroy work that is not ours, so the properties that matter are: other servers
+survive, a half-written file is impossible, and a hand-formatted config is
+never touched.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.mcp.agents import export
+
+
+def fake_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """A home directory of our own, so no real client config is ever opened."""
+ monkeypatch.setattr(export, "_home", lambda: tmp_path)
+ monkeypatch.setenv("APPDATA", str(tmp_path / "AppData" / "Roaming"))
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / ".config"))
+ return tmp_path
+
+
+def test_every_target_has_a_path_on_every_os(fake_home: Path) -> None:
+ """A client we claim to support must resolve somewhere on this machine."""
+ rows = export.targets()
+ assert {t.key for t in rows} == {"claude-desktop", "cursor", "claude-code", "codex"}
+ for target in rows:
+ assert target.config_path is not None, target.key
+ assert target.config_path.is_absolute(), target.key
+
+
+def test_stdio_entry_launches_the_bridge_and_holds_no_key(fake_home: Path) -> None:
+ entry = export.stdio_entry()
+ assert entry["args"] == ["-m", "jarvis.mcp.agents.bridge"]
+ assert entry["command"], "the entry must name an interpreter"
+ # AP-12: a key in a config file is a key in a backup.
+ assert "JARVIS_CONTROL_KEY" not in entry["env"]
+ assert entry["env"]["JARVIS_API_URL"].startswith("http")
+
+
+def test_http_entry_points_at_the_agent_surface(fake_home: Path) -> None:
+ entry = export.http_entry()
+ assert entry["type"] == "http"
+ assert entry["url"].endswith("/api/control/mcp/agents")
+ assert entry["headers"]["Authorization"].startswith("Bearer ")
+
+
+def test_install_keeps_every_other_server(fake_home: Path) -> None:
+ path = fake_home / ".cursor" / "mcp.json"
+ path.parent.mkdir(parents=True)
+ path.write_text(
+ json.dumps({"mcpServers": {"blender": {"command": "blender-mcp"}}}),
+ encoding="utf-8",
+ )
+
+ result = export.install("cursor")
+
+ assert result["ok"] is True
+ assert result["replaced"] is False
+ written = json.loads(path.read_text(encoding="utf-8"))
+ assert set(written["mcpServers"]) == {"blender", "jarvis-agents"}
+ assert written["mcpServers"]["blender"] == {"command": "blender-mcp"}
+
+
+def test_install_is_idempotent(fake_home: Path) -> None:
+ (fake_home / ".cursor").mkdir(parents=True)
+ first = export.install("cursor")
+ second = export.install("cursor")
+
+ assert first["replaced"] is False
+ assert second["replaced"] is True
+ written = json.loads((fake_home / ".cursor" / "mcp.json").read_text(encoding="utf-8"))
+ assert list(written["mcpServers"]) == ["jarvis-agents"]
+ # No stray temp file left behind by the atomic write.
+ assert not list((fake_home / ".cursor").glob("*.jarvis-tmp"))
+
+
+def test_a_broken_config_is_reported_not_overwritten(fake_home: Path) -> None:
+ path = fake_home / ".cursor" / "mcp.json"
+ path.parent.mkdir(parents=True)
+ path.write_text("{ not json", encoding="utf-8")
+
+ result = export.install("cursor")
+
+ assert result["ok"] is False
+ assert "not readable JSON" in result["error"]
+ assert path.read_text(encoding="utf-8") == "{ not json", "the file must survive untouched"
+
+
+def test_a_toml_client_gets_a_snippet_instead_of_a_write(fake_home: Path) -> None:
+ (fake_home / ".codex").mkdir(parents=True)
+ result = export.install("codex")
+
+ assert result["ok"] is False
+ assert "[mcp_servers.jarvis-agents]" in result["snippet"]
+ assert not (fake_home / ".codex" / "config.toml").exists()
+
+
+def test_an_unknown_client_names_the_known_ones(fake_home: Path) -> None:
+ result = export.install("emacs")
+ assert result["ok"] is False
+ assert "cursor" in result["error"]
+
+
+def test_snippet_is_valid_json_for_nested_clients(fake_home: Path) -> None:
+ parsed = json.loads(export.snippet("claude-desktop"))
+ assert list(parsed["mcpServers"]) == ["jarvis-agents"]
diff --git a/tests/unit/mcp/test_agent_mcp_routes.py b/tests/unit/mcp/test_agent_mcp_routes.py
new file mode 100644
index 0000000000..c0a7d4e95d
--- /dev/null
+++ b/tests/unit/mcp/test_agent_mcp_routes.py
@@ -0,0 +1,172 @@
+"""The Agent MCP surface's mount and its connect-flow routes.
+
+The mount is the silent failure this file exists to catch. A ``Mount`` on
+``/api/control/mcp/agents`` builds the path regex
+``^/api/control/mcp/agents(?P<path>/.*)$`` — it requires something after the
+mount path, so a plain ``POST /api/control/mcp/agents`` never matches it and
+falls through to the shorter ``/api/control/mcp``. The client would get the
+tools catalog on the agents URL: same transport, same auth, wrong tools, and
+nothing anywhere to notice it by. One mount dispatching on the rest of the path
+is what makes that impossible, so both URLs are exercised for real here.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web.agent_mcp_routes import router
+from jarvis.ui.web.mcp_server_routes import build_mcp_asgi_app
+
+#: A stateless Streamable HTTP request needs both content types offered.
+_MCP_HEADERS = {"Accept": "application/json, text/event-stream"}
+
+
+def _mounted_app() -> FastAPI:
+ """The surfaces mounted exactly as ``server.py`` mounts them."""
+ app = FastAPI()
+ app.mount("/api/control/mcp", build_mcp_asgi_app())
+ return app
+
+
+def keyed(monkeypatch: pytest.MonkeyPatch) -> str:
+ """A control key this process will accept, without touching the real one."""
+ from jarvis.core import control_key as ck
+
+ key = "not-a-real-key-only-this-test-accepts-it"
+ monkeypatch.setattr(ck, "verify_control_key", lambda presented: presented == key)
+ return key
+
+
+def _tool_names(client: TestClient, url: str, key: str) -> set[str]:
+ """The tool catalog one surface serves, over a real MCP handshake."""
+ headers = {**_MCP_HEADERS, "Authorization": f"Bearer {key}"}
+ init = client.post(
+ url,
+ headers=headers,
+ json={
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {},
+ "clientInfo": {"name": "test", "version": "0"},
+ },
+ },
+ )
+ assert init.status_code == 200, init.text
+ listed = client.post(
+ url,
+ headers=headers,
+ json={"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}},
+ )
+ assert listed.status_code == 200, listed.text
+ body: Any = listed.json()
+ return {t["name"] for t in body["result"]["tools"]}
+
+
+def test_the_agents_url_serves_the_agent_catalog(keyed: str) -> None:
+ """The exact URL a client is configured with, with no trailing slash."""
+ with TestClient(_mounted_app()) as client:
+ names = _tool_names(client, "/api/control/mcp/agents", keyed)
+
+ assert {"agent_chat", "agent_assign", "ecosystem_status", "kill_switch"} <= names
+ assert "open-app" not in names, "the agents URL must not serve the tools surface"
+
+
+def test_the_tools_url_still_serves_the_tools_surface(keyed: str) -> None:
+ """The pre-existing surface keeps its URL and its (possibly empty) catalog."""
+ with TestClient(_mounted_app()) as client:
+ names = _tool_names(client, "/api/control/mcp", keyed)
+
+ # No supervisor gateway is wired in a unit test, so the catalog is empty —
+ # what matters is that it is NOT the agent catalog.
+ assert "agent_chat" not in names
+
+
+def test_an_unknown_surface_is_a_404_not_a_wrong_catalog(keyed: str) -> None:
+ with TestClient(_mounted_app()) as client:
+ answer = client.post(
+ "/api/control/mcp/nonsense",
+ headers={**_MCP_HEADERS, "Authorization": f"Bearer {keyed}"},
+ json={},
+ )
+ assert answer.status_code == 404
+ assert "/api/control/mcp/agents" in answer.text
+
+
+def test_both_surfaces_demand_the_control_key() -> None:
+ """Loopback does NOT bypass auth — anything on the box could open a socket."""
+ with TestClient(_mounted_app()) as client:
+ for url in ("/api/control/mcp", "/api/control/mcp/agents"):
+ answer = client.post(url, headers=_MCP_HEADERS, json={})
+ assert answer.status_code == 401, url
+ assert "control api key" in answer.text.lower()
+
+
+def connect_app() -> FastAPI:
+ app = FastAPI()
+ app.include_router(router)
+ return app
+
+
+def test_status_publishes_the_tool_catalog(connect_app: FastAPI) -> None:
+ with TestClient(connect_app) as client:
+ body = client.get("/api/agent-mcp/status").json()
+
+ assert body["server_name"] == "jarvis-agents"
+ assert body["url"].endswith("/api/control/mcp/agents")
+ assert body["tool_count"] == len(body["tools"])
+ names = {t["name"] for t in body["tools"]}
+ assert {"agent_chat", "agent_assign", "ecosystem_status"} <= names
+ # A client must be able to see which tools spend money BEFORE calling one.
+ assert next(t for t in body["tools"] if t["name"] == "agent_chat")["dangerous"] is True
+ assert next(t for t in body["tools"] if t["name"] == "agents_list")["dangerous"] is False
+
+
+def test_clients_route_reports_installability(connect_app: FastAPI) -> None:
+ with TestClient(connect_app) as client:
+ body = client.get("/api/agent-mcp/clients").json()
+
+ rows = {c["key"]: c for c in body["clients"]}
+ assert {"claude-desktop", "cursor", "claude-code", "codex"} <= set(rows)
+ assert rows["codex"]["writable"] is False, "a hand-formatted TOML is never written"
+ assert rows["cursor"]["writable"] is True
+
+
+def test_snippet_route_returns_pasteable_config(connect_app: FastAPI) -> None:
+ with TestClient(connect_app) as client:
+ body = client.get("/api/agent-mcp/snippet", params={"client": "claude-desktop"}).json()
+ parsed = json.loads(body["snippet"])
+ assert list(parsed["mcpServers"]) == ["jarvis-agents"]
+
+ toml = client.get("/api/agent-mcp/snippet", params={"client": "codex"}).json()
+ assert toml["snippet"].startswith("[mcp_servers.jarvis-agents]")
+
+ bad = client.get("/api/agent-mcp/snippet", params={"client": "emacs"})
+ assert bad.status_code == 404
+
+
+def test_connect_writes_into_a_clients_config(
+ connect_app: FastAPI, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.mcp.agents import export
+
+ monkeypatch.setattr(export, "_home", lambda: tmp_path)
+ (tmp_path / ".cursor").mkdir()
+
+ with TestClient(connect_app) as client:
+ body = client.post("/api/agent-mcp/connect", json={"client": "cursor"}).json()
+
+ assert body["ok"] is True
+ assert body["restart_required"] is True
+ written = json.loads((tmp_path / ".cursor" / "mcp.json").read_text(encoding="utf-8"))
+ assert "jarvis-agents" in written["mcpServers"]