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): per-client credentials, quests, portable ecosystems, and a drift gate

rubenluetke10-beepd6b90f5b5f7d
diff --git a/docs/agent-mcp.md b/docs/agent-mcp.md
index 2bb31451f9..1e72d90291 100644
--- a/docs/agent-mcp.md
+++ b/docs/agent-mcp.md
@@ -62,8 +62,22 @@ launch a process:
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;
+**One click — `POST /api/agent-mcp/pair`.** The intended path. It mints this
+client its OWN credential and returns the finished config in the same answer:
+
+```
+POST /api/agent-mcp/pair
+{ "name": "Claude Desktop - MacBook", "scope": "work", "client": "claude-desktop" }
+```
+
+The response carries `config_text` — paste it, restart the client, done — and
+the secret appears there once and never again, because only its hash is kept.
+Add `"install": true` to write it into the client's config directly, or
+`"base_url": "http://192.168.1.50:47821"` when pairing a client on another
+machine.
+
+**Other endpoints.** `GET /api/agent-mcp/clients` lists which clients this
+machine has; `GET /api/agent-mcp/snippet?client=…` returns a 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
@@ -75,9 +89,49 @@ 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
+## 3. Credentials: one per client
+
+Two things open the agent surface.
+
+**The control key** is the owner at their own machine: full scope, everything.
+It is the master credential for the whole Control API, so it should not travel
+into a config file — a key in a config file is a key in every backup (AP-12).
+
+**An MCP token** is what a paired client gets. It is named, scoped,
+individually revocable, and its last use is stamped, so "who has access?" and
+"cut that one off" are each one call. Only the hash is stored; a stolen token
+file yields nothing to replay, and a lost token is re-issued rather than
+recovered.
+
+| Scope | May do |
+|---|---|
+| `read` | look, never spend: roster, board, quests, capabilities, approvals |
+| `work` | that, plus talk to agents, post quests, assign, speak in rooms, hire |
+| `full` | that, plus governance: resolve approvals, the kill switch, import a team |
+
+Scope is enforced by **not listing** a tool, not by refusing it afterwards: a
+model shown a tool it may not call will call it, read the refusal, and try
+again. Not offering it is the only honest way to say no. A call that slips
+through anyway — a client that cached an old list — still gets a plain sentence
+naming the scope it would need.
+
+Manage them at `GET /api/agent-mcp/tokens` and
+`DELETE /api/agent-mcp/tokens/{id}`.
+
+### Why a token passes the CSRF guard
+
+Worth knowing, because it looks like a hole and is not. The app's surface guard
+treats cookie- and open-access requests as browser-shaped and demands an
+`Origin` header on unsafe methods; Bearer credentials are exempt, because a
+browser cannot silently mint one. An MCP token is such a credential, so it is
+exempt too — but **only on `/api/control/mcp/agents`**. Everywhere else it is
+an unknown Bearer and authenticates nothing. That narrowness is deliberate: the
+desktop UI routes (`/api/settings/*`) are not key-gated and rely on this guard,
+so a token accepted app-wide would have opened them.
-Sixteen, grouped by intent. Everything marked **$** starts spend, work, or
+## 4. The tools
+
+Twenty-four, grouped by intent. Everything marked **$** starts spend, work, or
stops the house; a client should gate those and the description says so.
### Discovery
@@ -101,6 +155,20 @@ 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.
+### Quests — the strongest verb here
+
+| Tool | What it does |
+|---|---|
+| `quest_post` **$** | post a job WITHOUT naming who does it |
+| `quests_list` · `quest_get` | the Quest Board, and one job's whole story |
+| `quest_cancel` **$** · `quest_retry` **$** | stop it, or route it again |
+
+`quest_post` is the tool to reach for when you know what you want done but not
+who should do it. Deterministic Python — never a model — scores every agent on
+focus overlap, whether the quest names them, and current load; if nobody fits,
+it **forges a new teammate** for the job. The answer names the taker and why,
+so the choice is reviewable.
+
### The board
| Tool | What it reads |
@@ -110,11 +178,28 @@ id, and the answer lands on the board where `agent_inbox` finds it.
### Roster, rooms, governance
-`agent_create` · `rooms_list` · `room_open` · `room_say` **$** ·
-`room_settle` **$** · `approvals_list` · `approval_resolve` **$** ·
-`kill_switch` **$**
+`agent_create` · `capabilities_list` · `rooms_list` · `room_open` ·
+`room_say` **$** · `room_settle` **$** · `approvals_list` ·
+`approval_resolve` **$** · `kill_switch` **$**
+
+### Moving a team to another machine
-## 4. Resources and prompts
+| Tool | What it does |
+|---|---|
+| `ecosystem_export` | the team as a portable bundle |
+| `ecosystem_import` **$** | apply a bundle here; `full` scope only |
+
+A bundle carries the **design** — every agent with its role, focus, model,
+permissions and budget — and never the operation: no secrets, no chat history,
+no board, no workspace paths, no subscription seats. The safe subset is an
+allowlist, so a roster field added later cannot leak by accident; a test fails
+instead.
+
+Import matches **by name**: agents already on the target are updated, the rest
+are created. Run it with `dry_run` first to see the plan. Importing twice
+changes nothing the second time, which is what makes a retry harmless.
+
+## 5. Resources and prompts
A standard that ships only tools makes every client rediscover the same state
by hand, so the surface also serves:
@@ -132,7 +217,7 @@ by hand, so the surface also serves:
* `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
+## 6. The design rules
Held deliberately, because a standard other clients rely on cannot drift:
@@ -148,7 +233,7 @@ Held deliberately, because a standard other clients rely on cannot drift:
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
+## 7. What the surface cannot do
The safety seam is the house's, not a new one:
@@ -165,20 +250,59 @@ The safety seam is the house's, not a new one:
surface through `approvals_list` and are answered with `approval_resolve` —
the same path a person at the keyboard uses.
-## 7. Verified end to end
+## 8. Keeping new features in harmony
+
+The drift this surface is most likely to die of is nobody noticing. Somebody
+adds a society route, the app grows a button, and every MCP client stays a
+version behind — nothing breaks, so nothing gets fixed.
-Against a running instance (headless, port 47941), a real MCP client saw:
+`tests/contract/test_agent_mcp_harmony.py` makes that impossible to ignore. It
+enumerates the society's REST surface and requires every route to be either
+COVERED (naming the tool that exposes it) or WITHHELD (with one line saying why
+a remote client does not get it). A new route fails the build until somebody
+decides. Answering takes a minute; the point is that the decision is made.
-* `/api/control/mcp/agents` → server `jarvis-agents`, 16 tools, the three
- fixed resources plus one per agent on the roster, 3 prompts, and live
- `ecosystem_status` data;
-* `/api/control/mcp/` → server `jarvis`, 89 tools, **no** `agent_chat` — the
- surfaces do not leak into each other;
-* the stdio bridge (`python -m jarvis.mcp.agents.bridge`) → the same catalog
- and the same live answers, which is the path a desktop client takes;
+It earned its keep the day it was written: it immediately caught the Quest
+Board and the chat-binding route, both added hours earlier by other work, and
+`quest_post` exists because of it.
+
+Two more floors hold the surface up:
+
+* `tests/contract/test_agent_mcp_every_tool.py` runs EVERY published tool
+ against a live society and then asserts that the set it ran equals the set
+ the surface publishes — so a tool cannot ship untested.
+* `tests/contract/test_agent_mcp_surface.py` pins the tool set and the
+ dangerous flags. Adding a tool is a feature; renaming or removing one breaks
+ every connected client, so it fails here first.
+
+## 9. Verified end to end
+
+Against a running instance (headless), a real MCP client saw:
+
+* `/api/control/mcp/agents` → server `jarvis-agents`, the full tool set, the
+ three fixed resources plus one per agent, 3 prompts, live `ecosystem_status`;
+* `/api/control/mcp/` → server `jarvis`, its own 89 tools, **no** `agent_chat` —
+ the surfaces do not leak into each other;
+* the stdio bridge (`python -m jarvis.mcp.agents.bridge`) → the same catalog and
+ the same live answers, which is the path a desktop client takes;
* an unauthenticated POST → rejected before it reaches either surface.
-## 8. Where the code is
+Pairing and scopes, over the wire with real tokens:
+
+* a `work` token saw 21 tools, a `read` token 13, the control key all 24;
+* the `read` token was offered no spending tool at all, and calling
+ `kill_switch` anyway got a sentence naming the scope it would need;
+* the `work` token could `quest_post` but never saw `kill_switch`;
+* `ecosystem_export` returned the team with no secret-shaped string anywhere in
+ it, and `ecosystem_import` was correctly refused to the `work` token;
+* revoking one token killed it immediately while the other client kept working.
+
+That live run is also what caught the CSRF-guard bug described in §3 — every
+unit test was green while the feature did not work at all, because unit tests
+mount the ASGI app directly and never meet the guard.
+`tests/unit/mcp/test_agent_mcp_origin_guard.py` now covers it.
+
+## 10. Where the code is
| File | Role |
|---|---|
@@ -187,10 +311,13 @@ Against a running instance (headless, port 47941), a real MCP client saw:
| `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/mcp/agents/tokens.py` | per-client credentials: issue, scope, verify, revoke |
+| `jarvis/mcp/agents/portable.py` | the export/import bundle and its allowlist |
| `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`.
+Tests: `tests/contract/` holds the contract (`_surface`), the coverage floor
+(`_every_tool`), the drift gate (`_harmony`) and portability (`_portable`);
+`tests/unit/mcp/` holds the chat path (`_chat`), the mount and pairing flow
+(`_routes`), credentials (`_tokens`), the CSRF-guard regression
+(`_origin_guard`) and client configs (`_export`).
diff --git a/jarvis/mcp/agents/bridge.py b/jarvis/mcp/agents/bridge.py
index 4d9b9150b3..f2c34f372b 100644
--- a/jarvis/mcp/agents/bridge.py
+++ b/jarvis/mcp/agents/bridge.py
@@ -15,8 +15,10 @@ 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.
+* ``JARVIS_MCP_TOKEN`` — a per-client token (what a paired config carries).
+ Preferred: it is scoped and can be revoked without touching other clients.
+* ``JARVIS_CONTROL_KEY`` — the master control key. Default: read the same way
+ the app does (keyring → env → file), which needs no configuration 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
@@ -39,28 +41,59 @@ log = logging.getLogger(__name__)
#: Path of the agent surface under the Control API.
SURFACE_PATH: Final[str] = "/api/control/mcp/agents"
+#: The shipped admin API port, used only when nothing else answers.
+_DEFAULT_PORT: Final[int] = 47821
+
#: 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."""
+ """Where Jarvis actually listens.
+
+ ``JARVIS_API_URL`` wins, for a bridge pointed at another machine. Otherwise
+ ask ``cli_ctl.discovery``, which reads the running instance's own session
+ file: that is authoritative even when the app bound a non-default port or
+ is running as a second instance, and it verifies the process is still
+ alive rather than pointing at a recycled port. Only if nothing is running
+ do we fall back to the configured port, and then to the shipped 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
+ from jarvis.cli_ctl.discovery import discover
+
+ found = discover()
+ if found is not None and found.base_url:
+ return str(found.base_url).rstrip("/")
+ except Exception: # noqa: BLE001 — nothing discovered is normal, not an error
+ log.debug("agent MCP bridge: no running instance discovered", exc_info=True)
+ port = _DEFAULT_PORT
+ try:
+ from jarvis.core.config import load_config
- port = int(cfg.load().ui.admin_api_port)
+ port = int(load_config().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."""
+ """The credential to present, best first.
+
+ 1. ``JARVIS_MCP_TOKEN`` — a per-client token. What a paired config carries,
+ and the only one of the three that can be revoked on its own.
+ 2. ``JARVIS_CONTROL_KEY`` — the master key, for a bridge run by hand.
+ 3. the app's own lookup (keyring → env → file), so a bridge on the owner's
+ machine needs no configuration at all.
+
+ The name is historical; it returns whatever bearer value to send.
+ """
+ token = os.environ.get("JARVIS_MCP_TOKEN", "").strip()
+ if token:
+ return token
from_env = os.environ.get("JARVIS_CONTROL_KEY", "").strip()
if from_env:
return from_env
@@ -88,8 +121,8 @@ async def _upstream() -> AsyncIterator[Any]:
key = control_key()
if not key:
raise RuntimeError(
- "No Jarvis control key found. Open Jarvis once to create one, or set "
- "JARVIS_CONTROL_KEY."
+ "No Jarvis credential found. Pair this client from the Jarvis app to "
+ "get its own token, or set JARVIS_MCP_TOKEN / JARVIS_CONTROL_KEY."
)
url = f"{api_base_url()}{SURFACE_PATH}"
headers = {"Authorization": f"Bearer {key}"}
diff --git a/jarvis/mcp/agents/export.py b/jarvis/mcp/agents/export.py
index 3366b73088..cc42a9a67f 100644
--- a/jarvis/mcp/agents/export.py
+++ b/jarvis/mcp/agents/export.py
@@ -118,20 +118,31 @@ def targets() -> list[ClientTarget]:
return rows
-def stdio_entry(*, python: str | None = None, include_key: bool = False) -> dict[str, Any]:
+def stdio_entry(
+ *,
+ python: str | None = None,
+ include_key: bool = False,
+ token: str | None = None,
+ base_url: str | None = None,
+) -> 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.
+ This is the form to prefer. It needs no URL in the client, 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).
+ ``token`` embeds a per-client MCP token, which is what makes a config
+ paste-and-go: the client authenticates as itself, and that one credential
+ can be revoked without touching any other client. Prefer it over
+ ``include_key``, which embeds the master control key — a key in a config
+ file is a key in every backup (AP-12), and revoking it logs out everything.
"""
from .bridge import api_base_url, control_key
- env: dict[str, str] = {"JARVIS_API_URL": api_base_url()}
- if include_key:
+ env: dict[str, str] = {"JARVIS_API_URL": base_url or api_base_url()}
+ if token:
+ env["JARVIS_MCP_TOKEN"] = token
+ elif include_key:
key = control_key()
if key:
env["JARVIS_CONTROL_KEY"] = key
@@ -142,26 +153,45 @@ def stdio_entry(*, python: str | None = None, include_key: bool = False) -> dict
}
-def http_entry() -> dict[str, Any]:
+def http_entry(*, token: str | None = None, base_url: str | None = None) -> 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.
+ Fewer moving parts, but the credential is IN the config file and the client
+ must support custom headers. With a ``token`` that is an acceptable trade —
+ it is scoped and revocable on its own; with the control key it is not.
"""
from .bridge import SURFACE_PATH, api_base_url, control_key
- key = control_key() or "<your Jarvis control key>"
+ credential = token or control_key() or "<your Jarvis control key>"
return {
"type": "http",
- "url": f"{api_base_url()}{SURFACE_PATH}",
- "headers": {"Authorization": f"Bearer {key}"},
+ "url": f"{base_url or api_base_url()}{SURFACE_PATH}",
+ "headers": {"Authorization": f"Bearer {credential}"},
}
-def snippet(client: str = "claude-desktop", *, transport: str = "stdio") -> str:
+def entry_for(
+ *,
+ transport: str = "stdio",
+ token: str | None = None,
+ base_url: str | None = None,
+ include_key: bool = False,
+) -> dict[str, Any]:
+ """The config entry for one transport — the single place that chooses."""
+ if transport == "http":
+ return http_entry(token=token, base_url=base_url)
+ return stdio_entry(token=token, base_url=base_url, include_key=include_key)
+
+
+def snippet(
+ client: str = "claude-desktop",
+ *,
+ transport: str = "stdio",
+ token: str | None = None,
+ base_url: str | None = None,
+) -> str:
"""A ready-to-paste config block for one client."""
- entry = stdio_entry() if transport == "stdio" else http_entry()
+ entry = entry_for(transport=transport, token=token, base_url=base_url)
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}]"]
@@ -177,7 +207,14 @@ def snippet(client: str = "claude-desktop", *, transport: str = "stdio") -> str:
return json.dumps({"mcpServers": {ENTRY_NAME: entry}}, indent=2)
-def install(client: str, *, transport: str = "stdio", include_key: bool = False) -> dict[str, Any]:
+def install(
+ client: str,
+ *,
+ transport: str = "stdio",
+ include_key: bool = False,
+ token: str | None = None,
+ base_url: str | None = None,
+) -> dict[str, Any]:
"""Write the entry into the client's own config file.
Merges rather than replaces: an existing ``mcpServers`` object keeps every
@@ -193,13 +230,13 @@ def install(client: str, *, transport: str = "stdio", include_key: bool = False)
return {
"ok": False,
"error": f"{target.label} keeps a hand-formatted config — paste this instead.",
- "snippet": snippet(client, transport=transport),
+ "snippet": snippet(client, transport=transport, token=token, base_url=base_url),
"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()
+ entry = entry_for(transport=transport, token=token, base_url=base_url, include_key=include_key)
existing: dict[str, Any] = {}
if path.exists():
try:
@@ -232,6 +269,7 @@ def install(client: str, *, transport: str = "stdio", include_key: bool = False)
__all__ = [
"ENTRY_NAME",
"ClientTarget",
+ "entry_for",
"http_entry",
"install",
"snippet",
diff --git a/jarvis/mcp/agents/portable.py b/jarvis/mcp/agents/portable.py
new file mode 100644
index 0000000000..c996f385a3
--- /dev/null
+++ b/jarvis/mcp/agents/portable.py
@@ -0,0 +1,222 @@
+"""Carry an agent ecosystem to another machine.
+
+The team a person builds — who is on it, what each one is for, what it may
+touch, what it may spend — is the part of Jarvis that took real thought and
+that a reinstall or a second computer otherwise throws away. This module makes
+that portable: one JSON bundle out, the same bundle in somewhere else.
+
+**What travels is the design, never the operation.** A bundle carries roster
+rows and their settings. It does NOT carry:
+
+* secrets of any kind — API keys, tokens, the control key, browser logins;
+* the board, chat transcripts or sessions, which are this machine's history and
+ frequently private;
+* workspace paths and account ids, which name directories and subscription
+ seats that do not exist on the other machine.
+
+That exclusion is enforced here rather than trusted to the caller, and pinned by
+a test: an export that could leak a credential is a feature nobody can safely
+use, so the safe subset is an allowlist — a field is carried because it was
+named, never because it happened to exist.
+
+Importing is **adopt-before-mint**, matching the roster's own rule: an agent
+whose name is already on the target is updated, not duplicated. Running it twice
+therefore changes nothing the second time, which is what makes a bundle safe to
+re-apply after a partial failure.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+#: Bundle format. Bumped when a field's meaning changes, so an old bundle is
+#: refused with a sentence instead of silently half-applied.
+BUNDLE_VERSION: Final[int] = 1
+
+#: The agent fields a bundle carries. An allowlist, deliberately: a denylist
+#: leaks every field somebody adds later without thinking about portability.
+PORTABLE_FIELDS: Final[tuple[str, ...]] = (
+ "name",
+ "title",
+ "description",
+ "tier",
+ "provider",
+ "model",
+ "effort",
+ "grant_mode",
+ "grants",
+ "focus",
+ "denies",
+ "skills",
+ "knowledge_scope",
+ "permission_ceiling",
+ "approval_rules",
+ "daily_budget_usd",
+ "max_concurrent_runs",
+ "browser_mode",
+ "browser_allowed_domains",
+ "avatar",
+)
+
+#: Fields that must NEVER appear in a bundle, each for a stated reason. Checked
+#: by a test against what export actually produces.
+NEVER_EXPORTED: Final[dict[str, str]] = {
+ "account_id": "names a subscription seat that does not exist on the other machine",
+ "workspace_dir": "an absolute path on THIS machine",
+ "wiki_namespace": "derived from the agent id on the target",
+ "agent_id": "minted by the target roster; matching is by name",
+ "parent_agent_id": "an id from this machine's roster",
+ "session_id": "this machine's chat session",
+ "stats": "run history and spend, which belong to the machine that did the work",
+ "created_ms": "the target records its own timestamps",
+ "updated_ms": "same",
+ "state": "paused/archived is an operational state, not part of the design",
+ "checkpoint": "where the figure stands right now on this island",
+}
+
+#: The lead seat is Jarvis' own and exists on every install already. Carrying it
+#: would overwrite the target's lead with this machine's model choice.
+_SKIP_NAMES: Final[frozenset[str]] = frozenset({"jarvis"})
+
+
+class BundleError(ValueError):
+ """A bundle could not be read or applied. The message is user-facing."""
+
+
+def _agent_payload(row: dict[str, Any]) -> dict[str, Any]:
+ """One roster row reduced to what is portable."""
+ out: dict[str, Any] = {}
+ for key in PORTABLE_FIELDS:
+ if key not in row:
+ continue
+ value = row[key]
+ if value is None:
+ continue
+ out[key] = value
+ return out
+
+
+async def export_bundle(runtime: Any, *, include_archived: bool = False) -> dict[str, Any]:
+ """Everything portable about this ecosystem, as a plain dict."""
+ agents = await runtime.roster.list(include_archived=include_archived)
+ rows = []
+ for agent in agents:
+ if agent.name.strip().lower() in _SKIP_NAMES:
+ continue
+ rows.append(_agent_payload(agent.to_dict()))
+ return {
+ "kind": "jarvis.agent-ecosystem",
+ "version": BUNDLE_VERSION,
+ "exported_ms": int(time.time() * 1000),
+ "agents": rows,
+ "agent_count": len(rows),
+ "note": (
+ "Design only: no secrets, no chat history, no board. Import with "
+ "ecosystem_import on the target machine."
+ ),
+ }
+
+
+def _validate(bundle: Any) -> list[dict[str, Any]]:
+ """The agent rows a bundle carries, or a refusal that says what is wrong."""
+ if not isinstance(bundle, dict):
+ raise BundleError("a bundle is a JSON object with 'kind', 'version' and 'agents'")
+ if bundle.get("kind") != "jarvis.agent-ecosystem":
+ raise BundleError(f"this is not a Jarvis ecosystem bundle (kind={bundle.get('kind')!r})")
+ version = bundle.get("version")
+ if version != BUNDLE_VERSION:
+ raise BundleError(
+ f"bundle version {version} cannot be read by this Jarvis "
+ f"(it understands version {BUNDLE_VERSION})"
+ )
+ agents = bundle.get("agents")
+ if not isinstance(agents, list) or not agents:
+ raise BundleError("the bundle carries no agents")
+ rows: list[dict[str, Any]] = []
+ for index, row in enumerate(agents):
+ if not isinstance(row, dict):
+ raise BundleError(f"agent #{index + 1} is not an object")
+ if not str(row.get("name") or "").strip():
+ raise BundleError(f"agent #{index + 1} has no name — names are how import matches")
+ rows.append(row)
+ return rows
+
+
+async def import_bundle(
+ runtime: Any, bundle: Any, *, overwrite: bool = True, dry_run: bool = False
+) -> dict[str, Any]:
+ """Apply a bundle to this ecosystem: adopt by name, mint what is missing.
+
+ ``overwrite`` decides what happens to an agent that already exists here:
+ True updates its settings from the bundle, False leaves it exactly as it is
+ and reports it as skipped. ``dry_run`` reports the same plan without
+ touching anything, which is how a person sees what an import would do
+ before it does it.
+ """
+ from jarvis.society.roster import RosterError
+
+ rows = _validate(bundle)
+ existing = {a.name.strip().lower(): a for a in await runtime.roster.list(include_archived=True)}
+
+ created: list[str] = []
+ updated: list[str] = []
+ skipped: list[dict[str, str]] = []
+
+ for row in rows:
+ name = str(row["name"]).strip()
+ key = name.lower()
+ payload = _agent_payload(row)
+ if key in _SKIP_NAMES:
+ skipped.append({"name": name, "why": "the lead seat belongs to this install"})
+ continue
+ known = existing.get(key)
+ if known is not None and not overwrite:
+ skipped.append({"name": name, "why": "already here, and overwrite is off"})
+ continue
+ if dry_run:
+ (updated if known is not None else created).append(name)
+ continue
+ try:
+ if known is not None:
+ fields = {k: v for k, v in payload.items() if k != "name"}
+ await runtime.roster.update(known.agent_id, fields)
+ updated.append(name)
+ else:
+ fields = {
+ k: v for k, v in payload.items() if k not in ("name", "title", "description")
+ }
+ agent, _ = await runtime.roster.create(
+ name=name,
+ title=str(payload.get("title") or name),
+ description=str(payload.get("description") or ""),
+ **fields,
+ )
+ created.append(agent.name)
+ except RosterError as exc:
+ # One bad row must not abort the rest: a half-imported team the
+ # person can finish by hand beats an all-or-nothing refusal.
+ skipped.append({"name": name, "why": f"refused by the roster: {exc}"})
+ except (TypeError, ValueError) as exc:
+ skipped.append({"name": name, "why": f"unusable fields: {exc}"})
+
+ return {
+ "dry_run": dry_run,
+ "created": created,
+ "updated": updated,
+ "skipped": skipped,
+ "total_in_bundle": len(rows),
+ }
+
+
+__all__ = [
+ "BUNDLE_VERSION",
+ "NEVER_EXPORTED",
+ "PORTABLE_FIELDS",
+ "BundleError",
+ "export_bundle",
+ "import_bundle",
+]
diff --git a/jarvis/mcp/agents/server.py b/jarvis/mcp/agents/server.py
index 57b942c145..f4d8d14ce3 100644
--- a/jarvis/mcp/agents/server.py
+++ b/jarvis/mcp/agents/server.py
@@ -22,6 +22,7 @@ from __future__ import annotations
import json
import logging
+from contextvars import ContextVar
from typing import Any, Final
from . import tools as agent_tools
@@ -29,6 +30,15 @@ from .context import EcosystemUnavailable, society
log = logging.getLogger(__name__)
+#: The scope the current request authenticated with, set per HTTP request by
+#: ``jarvis.ui.web.mcp_server_routes``. ``"full"`` is what the control key
+#: carries — the owner at their own machine — so an unset value is never a
+#: privilege escalation, only the pre-token behaviour.
+REQUEST_SCOPE: ContextVar[str] = ContextVar("jarvis.mcp.agents.scope", default="full")
+
+#: The token name behind the current request, for log lines and refusals.
+REQUEST_CLIENT: ContextVar[str] = ContextVar("jarvis.mcp.agents.client", default="")
+
#: 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"
@@ -137,6 +147,13 @@ def _prompt_text(name: str, args: dict[str, str]) -> str:
return f"Unknown prompt: {name}"
+def _permitted(scope: str, spec: dict[str, Any]) -> bool:
+ """Whether the current scope may see and call one tool."""
+ from .tokens import allows
+
+ return allows(scope, str(spec["name"]), dangerous=bool(spec.get("dangerous")))
+
+
def build_server() -> Any:
"""A low-level MCP server bound to the live agent ecosystem."""
import mcp.types as types
@@ -146,6 +163,10 @@ def build_server() -> Any:
@server.list_tools() # type: ignore[misc, no-untyped-call]
async def _list_tools() -> list[Any]:
+ # Filtered by scope rather than listed-then-refused: a model shown a
+ # tool it may not call will call it, read the refusal, and try again.
+ # Not offering it is the only honest way to say no.
+ scope = REQUEST_SCOPE.get()
return [
types.Tool(
name=spec["name"],
@@ -153,30 +174,50 @@ def build_server() -> Any:
inputSchema=spec["inputSchema"],
)
for spec in agent_tools.tool_specs()
+ if _permitted(scope, spec)
]
@server.call_tool() # type: ignore[misc, no-untyped-call]
async def _call_tool(name: str, arguments: dict[str, Any] | None) -> list[Any]:
+ scope = REQUEST_SCOPE.get()
+ tool = agent_tools.get(name)
+ if tool is not None and not _permitted(
+ scope, {"name": tool.name, "dangerous": tool.dangerous}
+ ):
+ client = REQUEST_CLIENT.get() or "this token"
+ return [
+ types.TextContent(
+ type="text",
+ text=(
+ f"{name} needs a wider scope than {client} has ({scope}). "
+ "Ask the owner of this Jarvis for a token with a higher "
+ "scope, or use a read-only tool instead."
+ ),
+ )
+ ]
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]:
+ # ``Resource.uri`` is a pydantic ``AnyUrl``; pydantic coerces the string
+ # at construction, so the values below are correct at runtime and the
+ # annotations are simply narrower than the constructor accepts.
fixed = [
types.Resource(
- uri=_ECOSYSTEM_URI,
+ uri=_ECOSYSTEM_URI, # type: ignore[arg-type]
name="Ecosystem status",
description="The whole agent house at a glance: agents, runs, rooms, approvals.",
mimeType="application/json",
),
types.Resource(
- uri=_ROSTER_URI,
+ uri=_ROSTER_URI, # type: ignore[arg-type]
name="Agent roster",
description="Every agent with its role, model, focus and current run state.",
mimeType="application/json",
),
types.Resource(
- uri=_CAPABILITIES_URI,
+ uri=_CAPABILITIES_URI, # type: ignore[arg-type]
name="Connected capabilities",
description="Plugins, CLIs, MCP servers and skills the agents can actually use.",
mimeType="application/json",
@@ -185,7 +226,10 @@ def build_server() -> Any:
for uri, name, description in await _agent_resources():
fixed.append(
types.Resource(
- uri=uri, name=name, description=description, mimeType="application/json"
+ uri=uri, # type: ignore[arg-type]
+ name=name,
+ description=description,
+ mimeType="application/json",
)
)
return fixed
diff --git a/jarvis/mcp/agents/tokens.py b/jarvis/mcp/agents/tokens.py
new file mode 100644
index 0000000000..3fdec48d10
--- /dev/null
+++ b/jarvis/mcp/agents/tokens.py
@@ -0,0 +1,311 @@
+"""Per-client credentials for the Agent MCP surface.
+
+One control key for everything is fine while one person drives one machine. It
+stops being fine the moment several clients connect: a laptop, a phone's Claude
+app, a teammate, a cloud session. They all hold the SAME secret, nothing records
+which of them did what, and revoking one means rotating the key and re-pairing
+every other client.
+
+An MCP token fixes each of those. It is named ("Claude Desktop – MacBook"),
+scoped, individually revocable, and its use is stamped — so "who has access?"
+and "cut that one off" are both one call.
+
+**Only the hash is stored.** The secret is returned exactly once, at issue, and
+never again; a stolen token file yields nothing to replay. That is also why
+re-issuing is the recovery path for a lost token, not "show it to me again".
+
+Storage is a ``0600`` JSON file beside the control key, not ``jarvis.toml``: a
+credential in the config file is a credential in every backup and every support
+screenshot (AP-12).
+
+Format of the wire value::
+
+ jarvis_mcp_<token_id>_<secret>
+
+The id travels in the clear so verification is a single dictionary lookup plus
+one constant-time compare, rather than hashing the presented secret against
+every stored token in turn.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+import logging
+import os
+import secrets
+import time
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+_FILE_NAME: Final[str] = "mcp_tokens.json"
+_PREFIX: Final[str] = "jarvis_mcp"
+_ID_BYTES: Final[int] = 6
+_SECRET_BYTES: Final[int] = 32
+
+#: What a token may do. Deliberately three, not a per-tool matrix: a permission
+#: model nobody can hold in their head is one nobody sets correctly.
+SCOPES: Final[tuple[str, ...]] = ("read", "work", "full")
+
+#: Tools a ``work`` token may call on top of every read-only one. Governance
+#: (approvals, the kill switch) and roster edits stay with ``full``, because
+#: they decide what the ecosystem is allowed to do rather than doing work.
+_WORK_EXTRA: Final[frozenset[str]] = frozenset(
+ {
+ "agent_chat",
+ "agent_message",
+ "agent_assign",
+ "quest_post",
+ "quest_retry",
+ "quest_cancel",
+ "room_say",
+ "room_settle",
+ "agent_create",
+ }
+)
+
+
+class TokenError(ValueError):
+ """A token could not be issued or found. The message is user-facing."""
+
+
+@dataclass
+class McpToken:
+ """One issued credential. ``secret_hash`` is all that is ever persisted."""
+
+ token_id: str
+ name: str
+ scope: str
+ secret_hash: str
+ created_ms: int
+ last_used_ms: int = 0
+ revoked_ms: int = 0
+ note: str = ""
+ #: Free-form label for where it was installed ("claude-desktop", "cursor").
+ client: str = ""
+
+ @property
+ def active(self) -> bool:
+ return self.revoked_ms == 0
+
+ def to_public(self) -> dict[str, Any]:
+ """What may be shown or logged — never the hash."""
+ return {
+ "token_id": self.token_id,
+ "name": self.name,
+ "scope": self.scope,
+ "client": self.client,
+ "created_ms": self.created_ms,
+ "last_used_ms": self.last_used_ms,
+ "revoked": not self.active,
+ "revoked_ms": self.revoked_ms,
+ "note": self.note,
+ }
+
+
+@dataclass
+class TokenStore:
+ """The token file, read and written whole. It is small by nature."""
+
+ path: Path
+ _tokens: dict[str, McpToken] = field(default_factory=dict)
+ _loaded: bool = False
+
+ def load(self) -> TokenStore:
+ if self._loaded:
+ return self
+ self._tokens = {}
+ try:
+ raw = json.loads(self.path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ raw = {"tokens": []}
+ except (OSError, json.JSONDecodeError) as exc:
+ # A corrupt file must not lock the owner out of their own app: the
+ # control key still works, and re-issuing a token is one click.
+ log.warning("agent MCP tokens: %s is unreadable (%s) — starting empty", self.path, exc)
+ raw = {"tokens": []}
+ for row in raw.get("tokens") or []:
+ try:
+ token = McpToken(**row)
+ except TypeError:
+ log.warning("agent MCP tokens: skipping a malformed row")
+ continue
+ self._tokens[token.token_id] = token
+ self._loaded = True
+ return self
+
+ def save(self) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {"version": 1, "tokens": [asdict(t) for t in self._tokens.values()]}
+ tmp = self.path.with_suffix(".tmp")
+ tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ # Tighten BEFORE the rename so the file is never briefly world-readable.
+ _restrict(tmp)
+ tmp.replace(self.path)
+ _restrict(self.path)
+
+ # ------------------------------------------------------------ commands
+
+ def issue(
+ self, *, name: str, scope: str = "work", client: str = "", note: str = ""
+ ) -> tuple[McpToken, str]:
+ """Mint a token. Returns it plus the secret, which is shown ONCE."""
+ name = name.strip()
+ if not name:
+ raise TokenError("a token needs a name — you will read it in the list later")
+ if scope not in SCOPES:
+ raise TokenError(f"scope must be one of {', '.join(SCOPES)}")
+ self.load()
+ token_id = secrets.token_hex(_ID_BYTES)
+ while token_id in self._tokens:
+ token_id = secrets.token_hex(_ID_BYTES)
+ secret = secrets.token_urlsafe(_SECRET_BYTES)
+ token = McpToken(
+ token_id=token_id,
+ name=name[:120],
+ scope=scope,
+ secret_hash=_hash(secret),
+ created_ms=int(time.time() * 1000),
+ client=client[:60],
+ note=note[:400],
+ )
+ self._tokens[token_id] = token
+ self.save()
+ return token, f"{_PREFIX}_{token_id}_{secret}"
+
+ def list(self, *, include_revoked: bool = False) -> list[McpToken]:
+ self.load()
+ rows = sorted(self._tokens.values(), key=lambda t: t.created_ms, reverse=True)
+ return rows if include_revoked else [t for t in rows if t.active]
+
+ def get(self, token_id: str) -> McpToken | None:
+ self.load()
+ return self._tokens.get(token_id)
+
+ def revoke(self, token_id: str) -> McpToken:
+ self.load()
+ token = self._tokens.get(token_id)
+ if token is None:
+ raise TokenError(f"no token {token_id!r}")
+ if token.active:
+ token.revoked_ms = int(time.time() * 1000)
+ self.save()
+ return token
+
+ def delete(self, token_id: str) -> bool:
+ """Forget a token entirely. Revoking is usually better — it keeps the record."""
+ self.load()
+ if self._tokens.pop(token_id, None) is None:
+ return False
+ self.save()
+ return True
+
+ def verify(self, presented: str | None) -> McpToken | None:
+ """The live token a wire value names, or ``None``.
+
+ Stamps ``last_used_ms`` on success, so the owner can see which clients
+ are actually in use and which they can safely cut off.
+ """
+ parsed = _parse(presented)
+ if parsed is None:
+ return None
+ token_id, secret = parsed
+ self.load()
+ token = self._tokens.get(token_id)
+ if token is None or not token.active:
+ return None
+ if not hmac.compare_digest(token.secret_hash, _hash(secret)):
+ return None
+ now = int(time.time() * 1000)
+ # One write per minute at most: a busy client would otherwise rewrite
+ # the file on every single tool call.
+ if now - token.last_used_ms > 60_000:
+ token.last_used_ms = now
+ try:
+ self.save()
+ except OSError: # noqa: BLE001 — a read-only disk must not break auth
+ log.debug("agent MCP tokens: could not stamp last use", exc_info=True)
+ return token
+
+
+def allows(scope: str, tool_name: str, *, dangerous: bool) -> bool:
+ """Whether a scope may call one tool."""
+ if scope == "full":
+ return True
+ if not dangerous:
+ return True
+ if scope == "work":
+ return tool_name in _WORK_EXTRA
+ return False # read
+
+
+def _hash(secret: str) -> str:
+ return hashlib.sha256(secret.encode("utf-8")).hexdigest()
+
+
+def _parse(value: str | None) -> tuple[str, str] | None:
+ """``jarvis_mcp_<id>_<secret>`` → ``(id, secret)``, or ``None``."""
+ if not value or not value.startswith(f"{_PREFIX}_"):
+ return None
+ rest = value[len(_PREFIX) + 1 :]
+ token_id, _, secret = rest.partition("_")
+ if not token_id or not secret:
+ return None
+ return token_id, secret
+
+
+def looks_like_token(value: str | None) -> bool:
+ """Cheap check so the auth path can tell a token from a control key."""
+ return _parse(value) is not None
+
+
+def _restrict(path: Path) -> None:
+ """Owner-only permissions where the OS has them; a quiet no-op elsewhere.
+
+ POSIX gets ``0600``. Windows inherits the parent directory's ACL, which for
+ a per-user data directory is already owner-only — there is no portable
+ chmod there, and pretending otherwise would be worse than saying so.
+ """
+ try:
+ os.chmod(path, 0o600)
+ except (OSError, NotImplementedError):
+ log.debug("agent MCP tokens: no POSIX permissions on %s", path, exc_info=True)
+
+
+def token_file() -> Path:
+ """Where tokens live: beside the control key, in the instance's data dir."""
+ from jarvis.core import control_key as ck
+
+ return ck.control_key_file().with_name(_FILE_NAME)
+
+
+_store: TokenStore | None = None
+
+
+def store() -> TokenStore:
+ """The process-wide store, built on first use."""
+ global _store
+ if _store is None:
+ _store = TokenStore(token_file())
+ return _store
+
+
+def _reset_for_tests(path: Path | None = None) -> None:
+ global _store
+ _store = TokenStore(path) if path is not None else None
+
+
+__all__ = [
+ "SCOPES",
+ "McpToken",
+ "TokenError",
+ "TokenStore",
+ "allows",
+ "looks_like_token",
+ "store",
+ "token_file",
+]
diff --git a/jarvis/mcp/agents/tools.py b/jarvis/mcp/agents/tools.py
index 097dc92308..4dbbaa68ae 100644
--- a/jarvis/mcp/agents/tools.py
+++ b/jarvis/mcp/agents/tools.py
@@ -367,6 +367,121 @@ async def _agent_assign(args: dict[str, Any]) -> dict[str, Any]:
}
+# ---------------------------------------------------------------- quests
+
+
+async def _quest_post(args: dict[str, Any]) -> dict[str, Any]:
+ """Post a job without naming who does it — the ecosystem picks, or forges.
+
+ The highest-value verb on this surface for a caller who knows what they
+ want but not who on the team should do it. Routing is deterministic Python
+ (focus overlap, names mentioned, load), never a model, and the answer says
+ WHY the taker was chosen — including when a new teammate was forged for it.
+ """
+ from jarvis.society.roster import RosterError
+
+ rt = await society()
+ text = str(args["text"]).strip()
+ if not text:
+ raise ValueError("text must not be empty — a quest is a job in one sentence")
+ try:
+ quest = await rt.quests.create(
+ text,
+ title=str(args.get("title") or "") or None,
+ lang=str(args.get("lang") or "") or None,
+ )
+ except RosterError as exc:
+ raise _refuse_typed(exc) from exc
+ row = quest.to_dict()
+ return {
+ "quest": row,
+ "taker": row.get("agent_id"),
+ "why": (row.get("routing") or {}).get("reason"),
+ "forged_a_new_agent": bool((row.get("routing") or {}).get("forged")),
+ }
+
+
+async def _quests_list(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ limit = max(1, min(int(args.get("limit") or 100), 1000))
+ state = str(args.get("state") or "").strip() or None
+ quests = await rt.quests.list(state=state, limit=limit)
+ return {"quests": [q.to_dict() for q in quests], "total": len(quests)}
+
+
+async def _quest_get(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ quest_id = str(args["quest_id"])
+ quest = await rt.quests.get(quest_id)
+ if quest is None:
+ raise EcosystemUnavailable(
+ f"quest {quest_id!r}", "no quest by that id. List them with quests_list."
+ )
+ events = await rt.store.events_for_trace(quest.trace_id)
+ return {
+ "quest": quest.to_dict(),
+ "events": [e.model_dump(mode="json") for e in events],
+ }
+
+
+async def _quest_cancel(args: dict[str, Any]) -> dict[str, Any]:
+ rt = await society()
+ quest_id = str(args["quest_id"])
+ try:
+ quest = await rt.quests.cancel(quest_id)
+ except KeyError as exc:
+ raise EcosystemUnavailable(f"quest {quest_id!r}", "no quest by that id.") from exc
+ return {"quest": quest.to_dict()}
+
+
+async def _quest_retry(args: dict[str, Any]) -> dict[str, Any]:
+ from jarvis.society.roster import RosterError
+
+ rt = await society()
+ quest_id = str(args["quest_id"])
+ try:
+ quest = await rt.quests.retry(quest_id)
+ except KeyError as exc:
+ raise EcosystemUnavailable(f"quest {quest_id!r}", "no quest by that id.") from exc
+ except RosterError as exc:
+ raise _refuse_typed(exc) from exc
+ row = quest.to_dict()
+ return {"quest": row, "taker": row.get("agent_id")}
+
+
+# ------------------------------------------------------------- portability
+
+
+async def _ecosystem_export(args: dict[str, Any]) -> dict[str, Any]:
+ """This ecosystem's design as a portable bundle — no secrets, no history."""
+ from .portable import export_bundle
+
+ rt = await society()
+ return await export_bundle(rt, include_archived=bool(args.get("include_archived")))
+
+
+async def _ecosystem_import(args: dict[str, Any]) -> dict[str, Any]:
+ """Apply a bundle from another machine. Adopts by name, mints what is new."""
+ from .portable import BundleError, import_bundle
+
+ rt = await society()
+ bundle = args.get("bundle")
+ if isinstance(bundle, str):
+ try:
+ bundle = json.loads(bundle)
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"bundle is not valid JSON: {exc}") from exc
+ try:
+ return await import_bundle(
+ rt,
+ bundle,
+ overwrite=bool(args.get("overwrite", True)),
+ dry_run=bool(args.get("dry_run", False)),
+ )
+ except BundleError as exc:
+ raise EcosystemUnavailable("that bundle", str(exc)) from exc
+
+
# -------------------------------------------------------------- the board
@@ -635,6 +750,132 @@ TOOLS: Final[tuple[AgentTool, ...]] = (
dangerous=True,
tags=("work",),
),
+ AgentTool(
+ name="quest_post",
+ description=(
+ "Post a job on the Quest Board WITHOUT choosing who does it. The "
+ "ecosystem routes it: deterministic Python scores every agent on focus "
+ "overlap, whether the quest names them, and current load — and if "
+ "nobody fits, it forges a new teammate for the job. The answer names "
+ "the taker and why. This is the tool to reach for when you know what "
+ "you want done but not who should do it. Costs money."
+ ),
+ input_schema=_obj(
+ {
+ "text": {
+ "type": "string",
+ "description": "The job, in one or two sentences.",
+ },
+ "title": {"type": "string", "description": "Short label. Derived if omitted."},
+ "lang": {
+ "type": "string",
+ "description": "Language for the agent's answer, e.g. 'de'.",
+ },
+ },
+ ["text"],
+ ),
+ handler=_quest_post,
+ dangerous=True,
+ tags=("quests", "work"),
+ ),
+ AgentTool(
+ name="quests_list",
+ description=(
+ "The Quest Board: every posted job, newest first, with who took it, "
+ "why, and where it stands. Filter by state to see only what is open."
+ ),
+ input_schema=_obj(
+ {
+ "state": {
+ "type": "string",
+ "description": "Only this state (e.g. open, running, done, failed).",
+ },
+ "limit": {"type": "integer", "description": "1-1000, default 100."},
+ }
+ ),
+ handler=_quests_list,
+ tags=("quests",),
+ ),
+ AgentTool(
+ name="quest_get",
+ description=(
+ "One quest in full: its state, its taker and the routing reason, plus "
+ "every board event on its trace — the whole story of one job."
+ ),
+ input_schema=_obj({"quest_id": {"type": "string"}}, ["quest_id"]),
+ handler=_quest_get,
+ tags=("quests",),
+ ),
+ AgentTool(
+ name="quest_cancel",
+ description="Stop a quest. Work already running for it is dropped.",
+ input_schema=_obj({"quest_id": {"type": "string"}}, ["quest_id"]),
+ handler=_quest_cancel,
+ dangerous=True,
+ tags=("quests",),
+ ),
+ AgentTool(
+ name="quest_retry",
+ description=(
+ "Route a failed or open quest again. The taker may come out different "
+ "the second time — the roster or the load has changed. Costs money."
+ ),
+ input_schema=_obj({"quest_id": {"type": "string"}}, ["quest_id"]),
+ handler=_quest_retry,
+ dangerous=True,
+ tags=("quests",),
+ ),
+ AgentTool(
+ name="ecosystem_export",
+ description=(
+ "This ecosystem's design as a portable bundle: every agent with its "
+ "role, focus, model, permissions and budget. Carries NO secrets, no "
+ "chat history and no board — only the team you built. Save the JSON "
+ "and hand it to ecosystem_import on another machine."
+ ),
+ input_schema=_obj(
+ {
+ "include_archived": {
+ "type": "boolean",
+ "description": "Include retired agents. Default false.",
+ }
+ }
+ ),
+ handler=_ecosystem_export,
+ tags=("portability",),
+ ),
+ AgentTool(
+ name="ecosystem_import",
+ description=(
+ "Bring a team over from another machine. Agents already here are "
+ "matched BY NAME and updated; the rest are created. Run it with "
+ "dry_run first to see exactly what it would do — importing twice "
+ "changes nothing the second time."
+ ),
+ input_schema=_obj(
+ {
+ "bundle": {
+ "type": "object",
+ "description": "The bundle from ecosystem_export.",
+ },
+ "dry_run": {
+ "type": "boolean",
+ "description": "Report the plan and change nothing. Default false.",
+ },
+ "overwrite": {
+ "type": "boolean",
+ "description": (
+ "Update agents that already exist here. Default true; "
+ "false leaves them untouched and reports them as skipped."
+ ),
+ },
+ },
+ ["bundle"],
+ ),
+ handler=_ecosystem_import,
+ dangerous=True,
+ tags=("portability",),
+ ),
AgentTool(
name="agent_inbox",
description=(
@@ -696,6 +937,26 @@ TOOLS: Final[tuple[AgentTool, ...]] = (
handler=_agent_create,
tags=("roster",),
),
+ AgentTool(
+ name="capabilities_list",
+ description=(
+ "Everything the agents can actually use on this machine: connected "
+ "plugins, coding CLIs, MCP servers, active skills and core tools. This "
+ "is what makes an agent able to do a thing rather than only talk about "
+ "it — check here before assigning work that needs a capability."
+ ),
+ input_schema=_obj(
+ {
+ "kind": {
+ "type": "string",
+ "enum": ["plugin", "cli", "mcp", "skill", "core"],
+ "description": "Only this kind. Omit for everything.",
+ }
+ }
+ ),
+ handler=_capabilities_list,
+ tags=("discovery",),
+ ),
AgentTool(
name="rooms_list",
description="Every room: who is in it, the topic, whose turn it is, and its state.",
diff --git a/jarvis/ui/web/agent_mcp_routes.py b/jarvis/ui/web/agent_mcp_routes.py
index 7d0ba7a9f7..02a4dff9ee 100644
--- a/jarvis/ui/web/agent_mcp_routes.py
+++ b/jarvis/ui/web/agent_mcp_routes.py
@@ -122,4 +122,103 @@ def agent_mcp_connect(body: ConnectBody) -> dict[str, Any]:
return result
+# --------------------------------------------------------------- pairing
+
+
+class PairBody(BaseModel):
+ name: str = Field(
+ description="What to call this client later, e.g. 'Claude Desktop - MacBook'.",
+ min_length=1,
+ max_length=120,
+ )
+ scope: str = Field(
+ default="work",
+ description=(
+ "read = look but do not spend; work = talk to agents and post quests; "
+ "full = also governance (approvals, kill switch)."
+ ),
+ )
+ client: str = Field(
+ default="",
+ description="Which client this is for. Shapes the snippet; blank gives the generic one.",
+ )
+ transport: str = Field(default="stdio", description="stdio (preferred) or http")
+ base_url: str = Field(
+ default="",
+ description=(
+ "The URL this client will reach Jarvis at. Set it when pairing a client "
+ "on ANOTHER machine; blank means this box's own address."
+ ),
+ )
+ install: bool = Field(
+ default=False,
+ description="Also write the entry into the client's config file on this machine.",
+ )
+
+
[email protected]("/pair", openapi_extra={"x-jarvis-dangerous": True})
+def agent_mcp_pair(body: PairBody) -> dict[str, Any]:
+ """Issue a client its OWN credential and hand back the finished config.
+
+ This is the one-click path: a named, scoped, individually revocable token
+ plus the exact JSON to paste. The secret appears in this response and never
+ again — it is stored only as a hash — so whatever reads this must show it
+ to the person or write it straight into the client's config.
+ """
+ from jarvis.mcp.agents import export, tokens
+
+ if body.transport not in ("stdio", "http"):
+ raise HTTPException(422, "transport must be 'stdio' or 'http'")
+ base_url = body.base_url.strip().rstrip("/") or None
+ try:
+ token, secret = tokens.store().issue(name=body.name, scope=body.scope, client=body.client)
+ except tokens.TokenError as exc:
+ raise HTTPException(422, str(exc)) from exc
+
+ client_key = body.client.strip() or "claude-desktop"
+ known = {t.key for t in export.targets()}
+ if client_key not in known:
+ client_key = "claude-desktop"
+
+ entry = export.entry_for(transport=body.transport, token=secret, base_url=base_url)
+ result: dict[str, Any] = {
+ "token": token.to_public(),
+ "secret": secret,
+ "secret_shown_once": True,
+ "transport": body.transport,
+ "client": client_key,
+ "config": {"mcpServers": {export.ENTRY_NAME: entry}},
+ "config_text": export.snippet(
+ client_key, transport=body.transport, token=secret, base_url=base_url
+ ),
+ "installed": None,
+ }
+ if body.install:
+ result["installed"] = export.install(
+ client_key, transport=body.transport, token=secret, base_url=base_url
+ )
+ return result
+
+
[email protected]("/tokens", openapi_extra={"x-jarvis-readonly": True})
+def agent_mcp_tokens(include_revoked: bool = False) -> dict[str, Any]:
+ """Every client that has been paired — never the secrets, only who and when."""
+ from jarvis.mcp.agents import tokens
+
+ rows = [t.to_public() for t in tokens.store().list(include_revoked=include_revoked)]
+ return {"tokens": rows, "total": len(rows), "scopes": list(tokens.SCOPES)}
+
+
[email protected]("/tokens/{token_id}", openapi_extra={"x-jarvis-dangerous": True})
+def agent_mcp_revoke(token_id: str) -> dict[str, Any]:
+ """Cut off one client. Every other paired client keeps working."""
+ from jarvis.mcp.agents import tokens
+
+ try:
+ token = tokens.store().revoke(token_id)
+ except tokens.TokenError as exc:
+ raise HTTPException(404, str(exc)) from exc
+ return {"token": token.to_public(), "revoked": True}
+
+
__all__ = ["router"]
diff --git a/jarvis/ui/web/mcp_server_routes.py b/jarvis/ui/web/mcp_server_routes.py
index 546b28ed28..22487c49f8 100644
--- a/jarvis/ui/web/mcp_server_routes.py
+++ b/jarvis/ui/web/mcp_server_routes.py
@@ -62,11 +62,27 @@ class _Surface:
self._manager: Any | None = None
self._ready: asyncio.Event | None = None
self._task: asyncio.Task[None] | None = None
+ self._loop: asyncio.AbstractEventLoop | None = None
async def manager(self) -> Any | None:
- if self._manager is not None and self._ready is not None:
+ """The session manager for the CURRENT event loop, built on first use.
+
+ The loop identity check is not paranoia. The transport's task group is
+ anyio's, and anyio task groups belong to the loop that created them: a
+ manager cached across a loop restart answers every request with
+ ``RuntimeError: Task group is not initialized`` and never recovers on
+ its own. Rebuilding when the loop changed costs one construction and
+ turns a permanently dead surface into a self-healing one.
+ """
+ loop = asyncio.get_running_loop()
+ if self._manager is not None and self._ready is not None and self._loop is loop:
await self._ready.wait()
return self._manager
+ if self._loop is not None and self._loop is not loop:
+ log.debug("jarvis MCP: %s surface rebuilding on a new event loop", self.name)
+ self._manager = None
+ self._ready = None
+ self._task = None
try:
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
@@ -78,6 +94,7 @@ class _Surface:
ready = asyncio.Event()
self._manager = manager
self._ready = ready
+ self._loop = loop
self._task = asyncio.create_task(_run_manager(manager, ready))
await ready.wait()
return manager
@@ -189,6 +206,48 @@ def _surface_for(scope: dict[str, Any]) -> _Surface | None:
return _SUFFIX_SURFACES.get(surface_suffix(scope))
+def _authorized(scope: dict[str, Any], surface: _Surface | None) -> bool:
+ """Whether this request may proceed.
+
+ Two credentials open the agent surface: the Control API key (the owner at
+ their own machine, full scope) and a per-client MCP token (named, scoped,
+ individually revocable). Everything else, including the tools surface,
+ takes the control key alone — a scoped token has no meaning for a catalog
+ that is Jarvis' own hands.
+ """
+ from jarvis.core import control_key as ck
+
+ presented = _bearer(scope)
+ if ck.verify_control_key(presented):
+ return True
+ if surface is not _AGENTS_SURFACE:
+ return False
+ from jarvis.mcp.agents import tokens
+
+ return tokens.store().verify(presented) is not None
+
+
+def _agent_identity(scope: dict[str, Any]) -> tuple[str, str]:
+ """``(scope_name, client_name)`` for the credential this request carries.
+
+ The control key is the owner, so it is ``full`` with no client name. A
+ token carries whatever scope it was issued with — verified a second time
+ here rather than threaded through, because the check is a dict lookup and
+ one compare, and a single source of truth beats a faster hand-off.
+ """
+ from jarvis.core import control_key as ck
+
+ presented = _bearer(scope)
+ if ck.verify_control_key(presented):
+ return "full", ""
+ from jarvis.mcp.agents import tokens
+
+ token = tokens.store().verify(presented)
+ if token is None: # pragma: no cover — _authorized already rejected it
+ return "read", ""
+ return token.scope, token.name
+
+
def build_mcp_asgi_app() -> Any:
"""The ASGI app to mount at ``/api/control/mcp`` — both surfaces.
@@ -204,15 +263,16 @@ def build_mcp_asgi_app() -> Any:
async def app(scope: dict[str, Any], receive: Any, send: Any) -> None:
if scope.get("type") != "http":
return
- from jarvis.core import control_key as ck
-
- if not ck.verify_control_key(_bearer(scope)):
- await _reject(send, 401, _UNAUTHORIZED_BODY)
- return
+ # The surface is resolved BEFORE authentication because which
+ # credentials are accepted depends on it: scoped MCP tokens open the
+ # agent surface, the control key opens both.
surface = _surface_for(scope)
if surface is None:
await _reject(send, 404, _NOT_A_SURFACE_BODY)
return
+ if not _authorized(scope, surface):
+ await _reject(send, 401, _UNAUTHORIZED_BODY)
+ return
manager = await surface.manager()
if manager is None:
await _reject(send, 503, b'{"error":"Jarvis MCP server is not available."}')
@@ -221,7 +281,21 @@ def build_mcp_asgi_app() -> Any:
# 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)
+ #
+ # The scope travels in ContextVars the same way the chat session
+ # does on the other surface: the stateless transport runs the tool
+ # call in a task started from this request, which inherits the
+ # context, and the server reads it when it lists and dispatches.
+ from jarvis.mcp.agents.server import REQUEST_CLIENT, REQUEST_SCOPE
+
+ scope_name, client_name = _agent_identity(scope)
+ scope_token = REQUEST_SCOPE.set(scope_name)
+ client_token = REQUEST_CLIENT.set(client_name)
+ try:
+ await manager.handle_request(scope, receive, send)
+ finally:
+ REQUEST_SCOPE.reset(scope_token)
+ REQUEST_CLIENT.reset(client_token)
return
# The session travels in a ContextVar: the stateless transport runs
# the tool call in a task started from this request, which inherits
diff --git a/jarvis/ui/web/surface_security.py b/jarvis/ui/web/surface_security.py
index 53e69c853a..a97ad8b912 100644
--- a/jarvis/ui/web/surface_security.py
+++ b/jarvis/ui/web/surface_security.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import ipaddress
import json
+import logging
import os
import re
import secrets
@@ -23,11 +24,13 @@ import threading
import time
from collections.abc import Awaitable, Callable, Iterable, MutableMapping
from http.cookies import CookieError, SimpleCookie
-from typing import Any, Literal
+from typing import Any, ClassVar, Literal
from urllib.parse import parse_qs, urlsplit
from jarvis.core.branding import CONFIG_FILE_NAME, SESSION_COOKIE_NAME
+log = logging.getLogger(__name__)
+
COOKIE_NAME = SESSION_COOKIE_NAME
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
@@ -40,7 +43,7 @@ Receive = Callable[[], Awaitable[dict[str, Any]]]
Send = Callable[[dict[str, Any]], Awaitable[None]]
ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
CredentialValidator = Callable[[str], bool]
-AuthKind = Literal["control", "session", "open"]
+AuthKind = Literal["control", "session", "open", "mcp"]
Origin = tuple[str, str, int | None]
_BOOTSTRAP_TOKEN_LOCK = threading.Lock()
@@ -664,9 +667,7 @@ async def _reject(
await send({"type": "http.response.body", "body": body})
-async def reject_host(
- scope: Scope, send: Send, receive: Receive | None = None
-) -> None:
+async def reject_host(scope: Scope, send: Send, receive: Receive | None = None) -> None:
"""Reject an untrusted Host for HTTP or WebSocket before downstream code."""
await _reject(
scope,
@@ -678,9 +679,7 @@ async def reject_host(
)
-async def reject_origin(
- scope: Scope, send: Send, receive: Receive | None = None
-) -> None:
+async def reject_origin(scope: Scope, send: Send, receive: Receive | None = None) -> None:
"""Reject a foreign, null, malformed, or required-but-missing Origin."""
await _reject(
scope,
@@ -692,9 +691,7 @@ async def reject_origin(
)
-async def reject_unauthorized(
- scope: Scope, send: Send, receive: Receive | None = None
-) -> None:
+async def reject_unauthorized(scope: Scope, send: Send, receive: Receive | None = None) -> None:
"""Reject a request that lacks a valid Jarvis credential."""
await _reject(
scope,
@@ -824,6 +821,31 @@ class SurfaceSecurity:
return False
return origin == _scope_origin(scope) or origin in self._trusted_origins
+ #: The only path where a per-client MCP token counts as a credential.
+ #: Deliberately exact: the desktop UI routes are NOT key-gated — they rely
+ #: on this guard — so a token accepted app-wide would open them too.
+ _MCP_AGENT_SURFACE_PATH: ClassVar[str] = "/api/control/mcp/agents"
+
+ def _mcp_token_accepted(self, scope: Scope, bearer: str) -> bool:
+ """Whether ``bearer`` is a live MCP token AND this is the MCP path.
+
+ An MCP token is a Bearer credential like the control key, so a request
+ carrying one is not browser-shaped and needs no Origin (see the CSRF
+ rule below). It is scoped to one path because it grants less: the agent
+ ecosystem, never the rest of the Control API or the UI routes.
+ """
+ if str(scope.get("path", "") or "").rstrip("/") != self._MCP_AGENT_SURFACE_PATH:
+ return False
+ try:
+ from jarvis.mcp.agents import tokens
+ except Exception: # noqa: BLE001 — no MCP package → no such credential
+ return False
+ try:
+ return tokens.store().verify(bearer) is not None
+ except Exception: # noqa: BLE001 — an unreadable token store denies, never crashes
+ log.debug("surface security: MCP token check failed", exc_info=True)
+ return False
+
def _authenticate(self, scope: Scope) -> AuthKind | None:
bearer_present, bearer = _presented_bearer(scope)
if bearer_present:
@@ -836,6 +858,8 @@ class SurfaceSecurity:
return "control"
except Exception:
return None
+ if self._mcp_token_accepted(scope, bearer):
+ return "mcp"
try:
return "session" if self._session_validator(bearer) else None
except Exception:
@@ -914,9 +938,7 @@ class SurfaceSecurity:
return None
return payload if isinstance(payload, dict) else None
- async def _handle_session_request(
- self, scope: Scope, receive: Receive, send: Send
- ) -> None:
+ async def _handle_session_request(self, scope: Scope, receive: Receive, send: Send) -> None:
if not is_secure_or_loopback(scope):
await _reject(
scope,
@@ -990,9 +1012,7 @@ class SurfaceSecurity:
)
await send({"type": "http.response.body", "body": b""})
- async def _handle_ws_ticket_request(
- self, scope: Scope, receive: Receive, send: Send
- ) -> None:
+ async def _handle_ws_ticket_request(self, scope: Scope, receive: Receive, send: Send) -> None:
"""Mint a one-time WebSocket ticket for an already-authenticated caller.
The ticket exists because WebKit engines drop the HttpOnly session
@@ -1160,9 +1180,7 @@ class SurfaceSecurity:
if auth_kind is None:
await reject_unauthorized(scope, send, receive)
return
- if auth_kind in ("session", "open") and not self.origin_is_trusted(
- scope, required=True
- ):
+ if auth_kind in ("session", "open") and not self.origin_is_trusted(scope, required=True):
await reject_origin(scope, send, receive)
return
await self.app(scope, receive, send)
diff --git a/tests/contract/test_agent_mcp_every_tool.py b/tests/contract/test_agent_mcp_every_tool.py
new file mode 100644
index 0000000000..420f6ab631
--- /dev/null
+++ b/tests/contract/test_agent_mcp_every_tool.py
@@ -0,0 +1,216 @@
+"""Every Agent MCP tool, exercised for real — and a coverage floor that holds.
+
+`test_agent_mcp_surface.py` pins WHAT the surface offers. This file proves each
+of those tools actually works against a live society: it runs every one on its
+success path and then asserts that the set it ran equals the set the surface
+publishes.
+
+That last assertion is the point. Adding a tool without exercising it here
+fails the build, so the surface cannot grow a member nobody ever called — the
+failure mode where a client is offered a tool that raises the first time
+somebody tries it.
+"""
+
+from __future__ import annotations
+
+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
+from jarvis.mcp.agents import tools as agent_tools
+from jarvis.society.runtime import SocietyRuntime
+from tests.fakes.fake_agent_chat import FakeChatService
+
+
+class Surface:
+ """Calls tools the way a client does, and remembers which ones it ran."""
+
+ def __init__(self) -> None:
+ self.exercised: set[str] = set()
+
+ async def call(self, tool: str, **args: Any) -> Any:
+ self.exercised.add(tool)
+ text = await agent_tools.call(tool, args)
+ try:
+ return json.loads(text)
+ except json.JSONDecodeError:
+ return text
+
+ async def ok(self, tool: str, **args: Any) -> dict[str, Any]:
+ """A call that must succeed — a refusal comes back as text, not JSON."""
+ answer = await self.call(tool, **args)
+ assert isinstance(answer, dict), f"{tool} refused: {answer}"
+ return answer
+
+
+async def world(tmp_path: Path):
+ """A society with a working (fake) chat, reachable as the tools reach it."""
+ 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 test_every_published_tool_runs_against_a_live_society(world) -> None:
+ rt, _svc = world
+ s = Surface()
+
+ # ---------------------------------------------------------- discovery
+ status = await s.ok("ecosystem_status")
+ assert status["kill_switch"] is False
+ assert status["lead"] == "jarvis"
+
+ caps = await s.ok("capabilities_list")
+ assert "capabilities" in caps and caps["total"] == len(caps["capabilities"])
+ filtered = await s.ok("capabilities_list", kind="plugin")
+ assert all(c["kind"] == "plugin" for c in filtered["capabilities"])
+
+ # ------------------------------------------------------------- roster
+ scout = await s.ok(
+ "agent_create",
+ name="Scout",
+ title="Research scout",
+ description="Finds and checks facts.",
+ )
+ assert scout["created"] is True
+ # Seat both with a provider so the chat path can run on a box with no keys.
+ await rt.roster.update("scout", {"provider": "openai", "model": "gpt-5.2"})
+
+ archivist = await s.ok(
+ "agent_create", name="Archivist", title="Curator", description="Keeps the notes."
+ )
+ await rt.roster.update("archivist", {"provider": "openai", "model": "gpt-5.2"})
+ assert archivist["agent"]["tier"] == "specialist"
+
+ roster = await s.ok("agents_list")
+ assert {a["name"] for a in roster["agents"]} >= {"Scout", "Archivist"}
+
+ detail = await s.ok("agent_get", agent="Scout", recent_events=5)
+ assert detail["agent"]["name"] == "Scout"
+ # active_runs is a COUNT here, matching what /api/society/agents/{id} returns.
+ assert detail["active_runs"] == 0
+
+ # ------------------------------------------------------ conversation
+ chat = await s.ok("agent_chat", agent="Scout", text="Are you ready?")
+ assert chat["status"] == "answered"
+ assert chat["reply"] == "Heard you: Are you ready?"
+
+ note = await s.ok("agent_message", agent="Archivist", text="Filing this away.")
+ assert note["delivered_to"] == "Archivist"
+
+ assigned = await s.ok("agent_assign", agent="Scout", task="Check the changelog.")
+ assert assigned["assigned_to"] == "Scout"
+ assert assigned["outcome"] is not None
+
+ # ------------------------------------------------------------ quests
+ # The Quest Board: a job posted without naming anyone. Trusted Python picks
+ # the taker, forging a teammate when nobody on the roster fits.
+ posted = await s.ok("quest_post", text="Check the changelog for breaking changes.")
+ quest_id = posted["quest"]["quest_id"]
+ assert posted["taker"], "a quest must always end up with a taker"
+ assert posted["why"], "the routing reason is what makes the choice reviewable"
+
+ board_quests = await s.ok("quests_list")
+ assert quest_id in {q["quest_id"] for q in board_quests["quests"]}
+ assert (await s.ok("quests_list", limit=5))["total"] <= 5
+
+ one = await s.ok("quest_get", quest_id=quest_id)
+ assert one["quest"]["quest_id"] == quest_id
+ assert one["events"], "a quest carries its own board trail"
+
+ retried = await s.ok("quest_retry", quest_id=quest_id)
+ assert retried["quest"]["quest_id"] == quest_id
+
+ # Cancel a FRESH quest: the retried one has already reached a terminal
+ # state on this fake-chat box, and a finished quest is not cancellable.
+ second = await s.ok("quest_post", text="Summarise yesterday's board.")
+ cancelled = await s.ok("quest_cancel", quest_id=second["quest"]["quest_id"])
+ assert cancelled["quest"]["state"] in ("cancelled", "canceled", "failed", "done")
+
+ # ------------------------------------------------------------- board
+ inbox = await s.ok("agent_inbox", agent="Archivist")
+ assert [e["msg_type"] for e in inbox["events"]] == ["SAY"]
+
+ board = await s.ok("board_events", limit=50)
+ assert board["last_seq"] >= 1
+ trail = await s.ok("board_events", trace_id=assigned["trace_id"])
+ assert len(trail["events"]) >= 1
+ per_agent = await s.ok("board_events", agent="Scout")
+ assert per_agent["events"], "the board must know Scout"
+
+ # ------------------------------------------------------------- rooms
+ opened = await s.ok("room_open", members=["Scout", "Archivist"], topic="Where do facts live?")
+ room_id = opened["room"]["room_id"]
+ assert opened["room"]["state"] == "running"
+
+ listed = await s.ok("rooms_list")
+ assert room_id in {r["room_id"] for r in listed["rooms"]}
+
+ speaker = opened["room"]["members"][0]
+ spoke = await s.ok("room_say", room_id=room_id, member=speaker, text="In the wiki.")
+ assert spoke["room"]["message_count"] == 1
+
+ settled = await s.ok("room_settle", room_id=room_id)
+ assert settled["room"]["state"] == "settled"
+
+ # -------------------------------------------------------- governance
+ parked = await rt.approvals.enqueue(
+ agent_id="scout",
+ trace_id="approval-test",
+ capability="send-email",
+ action={"to": "[email protected]"},
+ summary="Send the summary out",
+ )
+ pending = await s.ok("approvals_list")
+ assert parked.id in {a["id"] for a in pending["approvals"]}
+ mine = await s.ok("approvals_list", agent="Scout")
+ assert mine["total"] == 1
+
+ resolved = await s.ok("approval_resolve", approval_id=parked.id, approve=False, note="not now")
+ assert resolved["approval"]["state"] == "denied"
+ assert (await s.ok("approvals_list"))["total"] == 0
+
+ engaged = await s.ok("kill_switch", engage=True)
+ assert engaged["engaged"] is True
+ released = await s.ok("kill_switch", engage=False)
+ assert released["engaged"] is False
+
+ # -------------------------------------------------------- portability
+ # The team as a portable bundle, and the same bundle applied back.
+ bundle = await s.ok("ecosystem_export")
+ assert bundle["kind"] == "jarvis.agent-ecosystem"
+ assert {a["name"] for a in bundle["agents"]} >= {"Scout", "Archivist"}
+
+ replayed = await s.ok("ecosystem_import", bundle=bundle, dry_run=True)
+ assert replayed["dry_run"] is True
+ # A superset: quest_post forged a generalist ("Runner") earlier, and it
+ # travels in the bundle like any other teammate.
+ assert set(replayed["updated"]) >= {"Archivist", "Scout"}
+
+ # ------------------------------------------------------- the floor
+ published = {t.name for t in TOOLS}
+ missing = published - s.exercised
+ assert not missing, (
+ f"published but never exercised: {sorted(missing)}. "
+ "Every tool this surface offers must run at least once here."
+ )
+ assert s.exercised == published
diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.py
new file mode 100644
index 0000000000..48b612a48e
--- /dev/null
+++ b/tests/contract/test_agent_mcp_harmony.py
@@ -0,0 +1,172 @@
+"""New ecosystem capabilities must be decided FOR or AGAINST the MCP surface.
+
+The failure this prevents is drift, not a crash. Somebody adds
+`POST /api/society/agents/{id}/vacation`, the app grows a button, and every MCP
+client silently stays a version behind — nobody notices, because nothing breaks.
+Six months later the surface is a partial mirror nobody trusts.
+
+So the society's REST surface is enumerated here and every route must be
+accounted for: either it has a tool, or it is listed as deliberately not
+exposed WITH a reason. A new route fails this test until someone makes that
+call. Answering "not exposed, because …" takes one line — the point is that the
+decision is made, not that everything is exposed.
+"""
+
+from __future__ import annotations
+
+from typing import Final
+
+from jarvis.mcp.agents import TOOLS
+from jarvis.ui.web.society_routes import router as society_router
+
+#: REST route -> the MCP tool that covers it.
+COVERED: Final[dict[str, str]] = {
+ "GET /api/society/agents": "agents_list",
+ "POST /api/society/agents": "agent_create",
+ "GET /api/society/agents/{agent_id}": "agent_get",
+ "POST /api/society/agents/{agent_id}/message": "agent_message",
+ "POST /api/society/agents/{agent_id}/assign": "agent_assign",
+ "GET /api/society/agents/{agent_id}/inbox": "agent_inbox",
+ "GET /api/society/events": "board_events",
+ "GET /api/society/capabilities": "capabilities_list",
+ "GET /api/society/rooms": "rooms_list",
+ "POST /api/society/rooms": "room_open",
+ "POST /api/society/rooms/{room_id}/say": "room_say",
+ "POST /api/society/rooms/{room_id}/settle": "room_settle",
+ "GET /api/society/approvals": "approvals_list",
+ "POST /api/society/approvals/{approval_id}/resolve": "approval_resolve",
+ "GET /api/society/quests": "quests_list",
+ "POST /api/society/quests": "quest_post",
+ "GET /api/society/quests/{quest_id}": "quest_get",
+ "POST /api/society/quests/{quest_id}/cancel": "quest_cancel",
+ "POST /api/society/quests/{quest_id}/retry": "quest_retry",
+ "GET /api/society/status": "ecosystem_status",
+ "POST /api/society/kill-switch/release": "kill_switch",
+ "POST /api/society/kill-switch": "kill_switch",
+}
+
+#: REST route -> why an MCP client does not get it. Each line is a decision.
+WITHHELD: Final[dict[str, str]] = {
+ "PATCH /api/society/agents/{agent_id}": (
+ "editing a roster row (model, ceiling, focus) is configuration the owner "
+ "does at their own keyboard, not something a remote client should change"
+ ),
+ "DELETE /api/society/agents/{agent_id}": (
+ "archiving a teammate is destructive and irreversible from outside"
+ ),
+ "POST /api/society/agents/{agent_id}/kill": (
+ "kill_switch stops the whole house; killing ONE agent's runs needs the "
+ "context of watching them, which a remote client does not have"
+ ),
+ "POST /api/society/agents/{agent_id}/model": (
+ "provider/model choice spends the owner's subscription — theirs to make"
+ ),
+ "GET /api/society/seeds": "starter-team proposals are onboarding UI, not an API verb",
+ "POST /api/society/seeds/apply": (
+ "onboarding, and it creates several agents at once — quest_post forges "
+ "the one agent a job actually needs instead"
+ ),
+ "GET /api/society/providers": (
+ "the provider/account picker is app UI; agent_get already reports the "
+ "model an agent runs on"
+ ),
+ "GET /api/society/agents/{agent_id}/skills": (
+ "agent_get already returns the skill list, so a second tool would only "
+ "spend a client's tool budget"
+ ),
+ "POST /api/society/agents/{agent_id}/skills/{slug}/promote": (
+ "promoting a learned skill into the global registry is a review step the "
+ "owner does in the app, where they can read the skill first"
+ ),
+ "GET /api/society/browser/status": "browser install state is local setup, not ecosystem state",
+ "POST /api/society/browser/install": "installs software on the machine — never from outside",
+ "GET /api/society/agents/{agent_id}/browser": (
+ "per-agent browser install state — local machine setup, like browser/status"
+ ),
+ "POST /api/society/agents/{agent_id}/browser/login": (
+ "opens an interactive login window on the owner's screen; meaningless remotely"
+ ),
+ "POST /api/society/agents/{agent_id}/browser/login/done": (
+ "the second half of the interactive login flow; useless without the window"
+ ),
+ "GET /api/society/agents/{agent_id}/routines": (
+ "routines are scheduled spend; listing is harmless but pairs with creation, "
+ "and neither belongs on a surface a client can drive unattended"
+ ),
+ "POST /api/society/agents/{agent_id}/routines": "creates recurring spend — owner-only",
+ "POST /api/society/approvals": (
+ "an MCP client asks for approval by USING a tool that needs one; it has no "
+ "reason to park an action it invented"
+ ),
+ "POST /api/society/approvals/resurface": (
+ "app-focus plumbing: it re-asks parked items when the window comes "
+ "forward, which has no meaning for a remote client"
+ ),
+ "POST /api/society/agents/{agent_id}/chat": (
+ "seats an agent's chat session without sending anything — a UI "
+ "preparation step. agent_chat does it as part of talking"
+ ),
+ "GET /api/society/memory": (
+ "the Memory House has its own surface; not part of this contract yet"
+ ),
+ "POST /api/society/memory/recall": (
+ "recall reads an agent's private knowledge; the Memory House contract "
+ "is not settled, and half a memory API is worse than none"
+ ),
+ "POST /api/society/memory/{knowledge_id}/promote": (
+ "promoting private knowledge to shared is a privacy decision the owner "
+ "makes after reading it — approvals_list surfaces it when an agent asks"
+ ),
+ "POST /api/society/memory/{knowledge_id}/dismiss": (
+ "the other half of that review; it belongs with the reading, in the app"
+ ),
+}
+
+
+def _routes() -> set[str]:
+ """Every society REST route as ``METHOD /path``."""
+ found: set[str] = set()
+ for route in society_router.routes:
+ path = getattr(route, "path", None)
+ methods = getattr(route, "methods", None) or set()
+ if not path:
+ continue
+ for method in methods:
+ if method in ("HEAD", "OPTIONS"):
+ continue
+ found.add(f"{method} {path}")
+ return found
+
+
+def test_every_society_route_is_decided() -> None:
+ """A new route is neither exposed nor withheld until somebody says which."""
+ routes = _routes()
+ decided = set(COVERED) | set(WITHHELD)
+ undecided = routes - decided
+ assert not undecided, (
+ "These society routes are new to the MCP surface and nobody has decided "
+ f"about them yet: {sorted(undecided)}.\n"
+ "Add a tool in jarvis/mcp/agents/tools.py and list it in COVERED, or list "
+ "it in WITHHELD with one line saying why a remote client does not get it."
+ )
+
+
+def test_no_stale_decisions() -> None:
+ """A route that disappeared must not leave a decision behind."""
+ routes = _routes()
+ stale = (set(COVERED) | set(WITHHELD)) - routes
+ assert not stale, (
+ f"These routes no longer exist but are still listed here: {sorted(stale)}. "
+ "Drop them from COVERED / WITHHELD."
+ )
+
+
+def test_covered_routes_name_real_tools() -> None:
+ published = {t.name for t in TOOLS}
+ for route, tool in COVERED.items():
+ assert tool in published, f"{route} claims tool {tool!r}, which does not exist"
+
+
+def test_every_withheld_route_states_a_reason() -> None:
+ for route, reason in WITHHELD.items():
+ assert len(reason) > 25, f"{route} is withheld without a real reason"
diff --git a/tests/contract/test_agent_mcp_portable.py b/tests/contract/test_agent_mcp_portable.py
new file mode 100644
index 0000000000..ae7c39b339
--- /dev/null
+++ b/tests/contract/test_agent_mcp_portable.py
@@ -0,0 +1,254 @@
+"""Carrying an ecosystem to another machine: what travels, and what must not.
+
+The load-bearing test here is the negative one. An export is a file people mail
+themselves, drop in a repo, or paste into a chat — so a bundle that could carry
+a credential or a private transcript is a feature nobody can safely use. The
+allowlist is checked against a roster row that has EVERY field populated, so a
+field added later shows up as a failure rather than as a leak.
+"""
+
+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 tools as agent_tools
+from jarvis.mcp.agents.portable import (
+ BUNDLE_VERSION,
+ NEVER_EXPORTED,
+ PORTABLE_FIELDS,
+ BundleError,
+ export_bundle,
+ import_bundle,
+)
+from jarvis.society.runtime import SocietyRuntime
+
+
+async def source(tmp_path: Path):
+ """A machine with a team on it."""
+ runtime = SocietyRuntime(tmp_path / "src", seed_starter_team=False)
+ await runtime.ensure_started()
+ try:
+ yield runtime
+ finally:
+ await runtime.close()
+
+
+async def target(tmp_path: Path):
+ """A fresh machine, wired up the way the MCP tools reach it."""
+ runtime = SocietyRuntime(tmp_path / "dst", 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:
+ yield runtime
+ finally:
+ runtime_refs._reset_for_tests()
+ await runtime.close()
+
+
+async def _seed(runtime: Any) -> None:
+ await runtime.roster.create(
+ name="Scout",
+ title="Research scout",
+ description="Finds and checks facts on the open web.",
+ provider="openai",
+ model="gpt-5.2",
+ daily_budget_usd=3.5,
+ permission_ceiling="ask",
+ focus=["plugin:web"],
+ max_concurrent_runs=2,
+ )
+ await runtime.roster.create(
+ name="Archivist",
+ title="Knowledge curator",
+ description="Keeps the wiki tidy.",
+ provider="anthropic",
+ model="claude-sonnet-5",
+ )
+
+
+# ------------------------------------------------------------ what travels
+
+
+async def test_a_bundle_carries_the_design(source) -> None:
+ await _seed(source)
+
+ bundle = await export_bundle(source)
+
+ assert bundle["kind"] == "jarvis.agent-ecosystem"
+ assert bundle["version"] == BUNDLE_VERSION
+ assert bundle["agent_count"] == 2
+ scout = next(a for a in bundle["agents"] if a["name"] == "Scout")
+ assert scout["title"] == "Research scout"
+ assert scout["provider"] == "openai" and scout["model"] == "gpt-5.2"
+ assert scout["daily_budget_usd"] == 3.5
+ assert scout["permission_ceiling"] == "ask"
+ assert scout["max_concurrent_runs"] == 2
+ assert scout["focus"] == ["plugin:web"]
+
+
+async def test_the_lead_seat_never_travels(source) -> None:
+ """Jarvis exists on every install; carrying it would overwrite the target's."""
+ await _seed(source)
+
+ bundle = await export_bundle(source)
+
+ assert "Jarvis" not in {a["name"] for a in bundle["agents"]}
+
+
+# --------------------------------------------------------- what must not
+
+
+async def test_no_excluded_field_ever_reaches_a_bundle(source) -> None:
+ await _seed(source)
+
+ bundle = await export_bundle(source)
+
+ for row in bundle["agents"]:
+ for forbidden, why in NEVER_EXPORTED.items():
+ assert forbidden not in row, f"{forbidden} leaked into a bundle — {why}"
+
+
+async def test_the_allowlist_is_the_whole_story(source) -> None:
+ """Every exported key was named on purpose; a new roster field cannot slip in."""
+ await _seed(source)
+
+ bundle = await export_bundle(source)
+
+ for row in bundle["agents"]:
+ unexpected = set(row) - set(PORTABLE_FIELDS)
+ assert not unexpected, (
+ f"these fields are exported but not on the allowlist: {sorted(unexpected)}. "
+ "Add them to PORTABLE_FIELDS deliberately, or to NEVER_EXPORTED with a reason."
+ )
+
+
+async def test_a_bundle_holds_nothing_that_reads_like_a_secret(source) -> None:
+ """A blunt check on the serialized agent rows — the form people actually share.
+
+ Only the rows: the bundle's own note says the words "no secrets", and the
+ point of this test is what came out of the ROSTER, not our prose.
+ """
+ await _seed(source)
+
+ text = json.dumps((await export_bundle(source))["agents"]).lower()
+
+ for marker in ("api_key", "apikey", "secret", "token", "password", "bearer", "sk-"):
+ assert marker not in text, f"a bundle must never contain {marker!r}"
+
+
+# --------------------------------------------------------------- importing
+
+
+async def test_an_import_rebuilds_the_team_on_another_machine(source, target) -> None:
+ await _seed(source)
+ bundle = await export_bundle(source)
+
+ report = await import_bundle(target, bundle)
+
+ assert sorted(report["created"]) == ["Archivist", "Scout"]
+ assert report["updated"] == []
+ landed = {a.name: a for a in await target.roster.list()}
+ assert "Scout" in landed
+ assert landed["Scout"].provider == "openai"
+ assert landed["Scout"].daily_budget_usd == 3.5
+ assert landed["Scout"].permission_ceiling == "ask"
+
+
+async def test_importing_twice_changes_nothing_the_second_time(source, target) -> None:
+ """Re-applying a bundle must be safe — that is what makes a retry harmless."""
+ await _seed(source)
+ bundle = await export_bundle(source)
+
+ first = await import_bundle(target, bundle)
+ second = await import_bundle(target, bundle)
+
+ assert len(first["created"]) == 2
+ assert second["created"] == []
+ assert sorted(second["updated"]) == ["Archivist", "Scout"]
+ assert len(await target.roster.list()) == 3 # the two plus this machine's lead
+
+
+async def test_dry_run_reports_the_plan_and_touches_nothing(source, target) -> None:
+ await _seed(source)
+ bundle = await export_bundle(source)
+
+ plan = await import_bundle(target, bundle, dry_run=True)
+
+ assert plan["dry_run"] is True
+ assert sorted(plan["created"]) == ["Archivist", "Scout"]
+ assert [a.name for a in await target.roster.list()] == ["Jarvis"]
+
+
+async def test_overwrite_off_leaves_an_existing_agent_alone(source, target) -> None:
+ await _seed(source)
+ await target.roster.create(
+ name="Scout", title="A different scout", description="Mine.", provider="ollama"
+ )
+ bundle = await export_bundle(source)
+
+ report = await import_bundle(target, bundle, overwrite=False)
+
+ assert report["created"] == ["Archivist"]
+ assert [s["name"] for s in report["skipped"]] == ["Scout"]
+ mine = next(a for a in await target.roster.list() if a.name == "Scout")
+ assert mine.provider == "ollama", "my Scout must survive untouched"
+
+
+async def test_a_wrong_bundle_is_refused_with_a_sentence(target) -> None:
+ for bad, expected in (
+ ("not a dict", "a bundle is a JSON object"),
+ ({"kind": "something-else", "version": 1, "agents": []}, "not a Jarvis ecosystem bundle"),
+ ({"kind": "jarvis.agent-ecosystem", "version": 99, "agents": []}, "cannot be read"),
+ ({"kind": "jarvis.agent-ecosystem", "version": BUNDLE_VERSION, "agents": []}, "no agents"),
+ (
+ {"kind": "jarvis.agent-ecosystem", "version": BUNDLE_VERSION, "agents": [{"x": 1}]},
+ "has no name",
+ ),
+ ):
+ with pytest.raises(BundleError, match=expected):
+ await import_bundle(target, bad)
+
+
+# ------------------------------------------------------- through the tools
+
+
+async def test_the_round_trip_works_over_the_mcp_tools(source, target) -> None:
+ """What a client actually does: export on one box, import on the other."""
+ await _seed(source)
+ bundle = await export_bundle(source) # the other machine's client did this
+
+ text = await agent_tools.call("ecosystem_import", {"bundle": bundle, "dry_run": True})
+ plan = json.loads(text)
+ assert sorted(plan["created"]) == ["Archivist", "Scout"]
+
+ applied = json.loads(await agent_tools.call("ecosystem_import", {"bundle": bundle}))
+ assert sorted(applied["created"]) == ["Archivist", "Scout"]
+
+ exported = json.loads(await agent_tools.call("ecosystem_export", {}))
+ assert {a["name"] for a in exported["agents"]} == {"Archivist", "Scout"}
+
+
+async def test_a_bundle_may_arrive_as_a_json_string(source, target) -> None:
+ """Clients that cannot send a nested object send the text they saved."""
+ await _seed(source)
+ bundle_text = json.dumps(await export_bundle(source))
+
+ report = json.loads(await agent_tools.call("ecosystem_import", {"bundle": bundle_text}))
+
+ assert sorted(report["created"]) == ["Archivist", "Scout"]
+
+
+async def test_broken_json_says_so(target) -> None:
+ answer = await agent_tools.call("ecosystem_import", {"bundle": "{ nope"})
+ assert "not valid JSON" in answer
diff --git a/tests/contract/test_agent_mcp_surface.py b/tests/contract/test_agent_mcp_surface.py
index 9552aba7f4..e16759a1af 100644
--- a/tests/contract/test_agent_mcp_surface.py
+++ b/tests/contract/test_agent_mcp_surface.py
@@ -29,11 +29,17 @@ EXPECTED_TOOLS = {
"ecosystem_status",
"agents_list",
"agent_get",
+ "capabilities_list",
"agent_chat",
"agent_message",
"agent_assign",
"agent_inbox",
"board_events",
+ "quest_post",
+ "quests_list",
+ "quest_get",
+ "quest_cancel",
+ "quest_retry",
"agent_create",
"rooms_list",
"room_open",
@@ -42,18 +48,24 @@ EXPECTED_TOOLS = {
"approvals_list",
"approval_resolve",
"kill_switch",
+ "ecosystem_export",
+ "ecosystem_import",
}
#: 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",
+ "quest_post",
+ "quest_cancel",
+ "quest_retry",
"agent_message",
"agent_assign",
"room_say",
"room_settle",
"approval_resolve",
"kill_switch",
+ "ecosystem_import",
}
#: MCP's own rule for a tool name.
diff --git a/tests/fakes/fake_agent_chat.py b/tests/fakes/fake_agent_chat.py
new file mode 100644
index 0000000000..86ba1cf997
--- /dev/null
+++ b/tests/fakes/fake_agent_chat.py
@@ -0,0 +1,62 @@
+"""A chat service that answers a scripted turn — no model, no provider, no network.
+
+The society dispatches work by seating an agent's canonical chat session and
+watching its event stream. Anything that exercises that path (the Agent MCP
+surface, `chat_binding`, the scheduler) needs a service that behaves like the
+real one at that seam: `is_running`, `subscribe`/`unsubscribe`, and a `send`
+that publishes turn events to the subscribers.
+
+The script is deliberately synchronous — every event is queued before `send`
+returns — so a test never sleeps waiting for a turn. Pass `script=[]` to model
+a turn that never answers.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+
+def default_script(text: str) -> list[dict[str, Any]]:
+ """One tool call, one answer, a clean finish."""
+ return [
+ {"kind": "tool_call", "payload": {"name": "wiki-recall"}},
+ {"kind": "assistant_text", "payload": {"text": f"Heard you: {text}"}},
+ {"kind": "turn_finished", "payload": {"status": "ok"}},
+ ]
+
+
+class FakeChatService:
+ """Stands in for `AgentChatService` at the seam the society uses."""
+
+ def __init__(self, store: Any, 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
+
+
+__all__ = ["FakeChatService", "default_script"]
diff --git a/tests/unit/mcp/test_agent_mcp_origin_guard.py b/tests/unit/mcp/test_agent_mcp_origin_guard.py
new file mode 100644
index 0000000000..2a24848c54
--- /dev/null
+++ b/tests/unit/mcp/test_agent_mcp_origin_guard.py
@@ -0,0 +1,138 @@
+"""An MCP token must pass the CSRF guard — on the MCP path, and nowhere else.
+
+This is a regression test for a bug that every other test missed, because
+every other test mounts the ASGI app directly and never sees the guard.
+
+What happened live: the guard treats cookie- and open-access requests as
+browser-shaped and demands an Origin header on POST, exempting Bearer
+credentials it recognises. It recognised the control key and session tokens —
+not MCP tokens. So a paired client, which sends a Bearer and never an Origin,
+was rejected 403 "Untrusted Origin header" on every call. All unit tests were
+green; the feature did not work at all.
+
+The fix had to stay narrow. The desktop UI routes (`/api/settings/*`) are NOT
+key-gated — they rely on this guard for authentication — so a token accepted
+app-wide would have opened them. The second test below is the one that keeps
+it narrow.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web.mcp_server_routes import build_mcp_asgi_app
+from jarvis.ui.web.surface_security import SurfaceSecurity
+
+_MCP_HEADERS = {"Accept": "application/json, text/event-stream"}
+_INIT = {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {},
+ "clientInfo": {"name": "test", "version": "0"},
+ },
+}
+
+
+def guarded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any:
+ """The MCP surface behind the real guard, plus a token store of our own."""
+ from jarvis.mcp.agents import tokens
+
+ store = tokens.TokenStore(tmp_path / "mcp_tokens.json")
+ monkeypatch.setattr(tokens, "_store", store)
+
+ app = FastAPI()
+ app.mount("/api/control/mcp", build_mcp_asgi_app())
+
+ @app.post("/api/settings/danger")
+ def _settings() -> dict[str, str]:
+ """Stands in for a same-origin UI route: no key gate of its own."""
+ return {"changed": "yes"}
+
+ # A control key this process will not accept, so only the token is in play.
+ guard = SurfaceSecurity(app, control_key_validator=lambda token: False)
+ return TestClient(guard), store
+
+
+def test_a_token_passes_the_guard_without_an_origin(guarded) -> None:
+ """A CLI client sends a Bearer and no Origin — that must be enough."""
+ client, store = guarded
+ _token, secret = store.issue(name="Claude Desktop", scope="work")
+
+ answer = client.post(
+ "/api/control/mcp/agents",
+ headers={**_MCP_HEADERS, "Authorization": f"Bearer {secret}"},
+ json=_INIT,
+ )
+
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["result"]["serverInfo"]["name"] == "jarvis-agents"
+
+
+def test_a_token_opens_nothing_but_the_mcp_path(guarded) -> None:
+ """The narrow part of the fix: UI routes rely on this guard, not on a key."""
+ client, store = guarded
+ _token, secret = store.issue(name="Nosy client", scope="full")
+
+ answer = client.post(
+ "/api/settings/danger",
+ headers={"Authorization": f"Bearer {secret}"},
+ json={},
+ )
+
+ assert answer.status_code in (401, 403), (
+ "an MCP token must not authenticate anything outside the agent surface"
+ )
+ assert answer.json().get("changed") != "yes"
+
+
+def test_a_revoked_token_stops_passing_the_guard(guarded) -> None:
+ client, store = guarded
+ token, secret = store.issue(name="Retired laptop", scope="work")
+ store.revoke(token.token_id)
+
+ answer = client.post(
+ "/api/control/mcp/agents",
+ headers={**_MCP_HEADERS, "Authorization": f"Bearer {secret}"},
+ json=_INIT,
+ )
+
+ assert answer.status_code in (401, 403)
+
+
+def test_a_made_up_token_does_not_pass(guarded) -> None:
+ client, _store = guarded
+
+ answer = client.post(
+ "/api/control/mcp/agents",
+ headers={**_MCP_HEADERS, "Authorization": "Bearer jarvis_mcp_deadbeef_nonsense"},
+ json=_INIT,
+ )
+
+ assert answer.status_code in (401, 403)
+
+
+def test_a_foreign_origin_is_still_refused_with_a_valid_token(guarded) -> None:
+ """The token exempts a request from NEEDING an Origin, not from having a bad one."""
+ client, store = guarded
+ _token, secret = store.issue(name="Attacked client", scope="work")
+
+ answer = client.post(
+ "/api/control/mcp/agents",
+ headers={
+ **_MCP_HEADERS,
+ "Authorization": f"Bearer {secret}",
+ "Origin": "http://evil.example",
+ },
+ json=_INIT,
+ )
+
+ assert answer.status_code == 403
diff --git a/tests/unit/mcp/test_agent_mcp_routes.py b/tests/unit/mcp/test_agent_mcp_routes.py
index c0a7d4e95d..5d0430590a 100644
--- a/tests/unit/mcp/test_agent_mcp_routes.py
+++ b/tests/unit/mcp/test_agent_mcp_routes.py
@@ -170,3 +170,152 @@ def test_connect_writes_into_a_clients_config(
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"]
+
+
+# ------------------------------------------------------- per-client tokens
+
+
+def token_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """A token store of our own — never the real one on this machine."""
+ from jarvis.mcp.agents import tokens
+
+ store = tokens.TokenStore(tmp_path / "mcp_tokens.json")
+ monkeypatch.setattr(tokens, "_store", store)
+ return store
+
+
+def test_a_scoped_token_opens_the_agent_surface(token_store, keyed: str) -> None:
+ """A paired client authenticates as ITSELF, not with the master key."""
+ _token, secret = token_store.issue(name="Cursor - laptop", scope="work")
+
+ with TestClient(_mounted_app()) as client:
+ names = _tool_names(client, "/api/control/mcp/agents", secret)
+
+ assert "agent_chat" in names
+ assert "quest_post" in names
+
+
+def test_a_read_token_is_never_offered_a_spending_tool(token_store, keyed: str) -> None:
+ """Scope is enforced by NOT LISTING. A tool a model can see, it will call."""
+ _token, secret = token_store.issue(name="Dashboard", scope="read")
+
+ with TestClient(_mounted_app()) as client:
+ names = _tool_names(client, "/api/control/mcp/agents", secret)
+
+ assert "agents_list" in names and "ecosystem_status" in names
+ for spender in ("agent_chat", "agent_assign", "quest_post", "kill_switch"):
+ assert spender not in names, f"a read token must not even see {spender}"
+
+
+def test_a_work_token_may_spend_but_not_govern(token_store, keyed: str) -> None:
+ _token, secret = token_store.issue(name="Phone", scope="work")
+
+ with TestClient(_mounted_app()) as client:
+ names = _tool_names(client, "/api/control/mcp/agents", secret)
+
+ assert {"agent_chat", "quest_post", "agent_assign"} <= names
+ assert "kill_switch" not in names, "stopping the house is the owner's call"
+ assert "approval_resolve" not in names
+
+
+def test_the_control_key_still_sees_everything(token_store, keyed: str) -> None:
+ with TestClient(_mounted_app()) as client:
+ names = _tool_names(client, "/api/control/mcp/agents", keyed)
+
+ assert {"kill_switch", "approval_resolve", "agent_chat"} <= names
+
+
+def test_a_revoked_token_is_dead_at_once(token_store, keyed: str) -> None:
+ token, secret = token_store.issue(name="Stolen laptop", scope="full")
+ token_store.revoke(token.token_id)
+
+ with TestClient(_mounted_app()) as client:
+ answer = client.post(
+ "/api/control/mcp/agents",
+ headers={**_MCP_HEADERS, "Authorization": f"Bearer {secret}"},
+ json={},
+ )
+
+ assert answer.status_code == 401
+
+
+def test_a_token_does_not_open_the_tools_surface(token_store, keyed: str) -> None:
+ """A scoped token is for the ecosystem; Jarvis' own hands need the key."""
+ _token, secret = token_store.issue(name="Anything", scope="full")
+
+ with TestClient(_mounted_app()) as client:
+ answer = client.post(
+ "/api/control/mcp/",
+ headers={**_MCP_HEADERS, "Authorization": f"Bearer {secret}"},
+ json={},
+ )
+
+ assert answer.status_code == 401
+
+
+# --------------------------------------------------------- the pairing flow
+
+
+def test_pair_returns_a_finished_config_with_its_own_credential(
+ connect_app: FastAPI, token_store
+) -> None:
+ with TestClient(connect_app) as client:
+ body = client.post(
+ "/api/agent-mcp/pair",
+ json={"name": "Claude Desktop - MacBook", "scope": "work", "client": "claude-desktop"},
+ ).json()
+
+ assert body["secret_shown_once"] is True
+ secret = body["secret"]
+ assert secret.startswith("jarvis_mcp_")
+
+ # The config is finished: paste it, restart the client, done.
+ entry = body["config"]["mcpServers"]["jarvis-agents"]
+ assert entry["args"] == ["-m", "jarvis.mcp.agents.bridge"]
+ assert entry["env"]["JARVIS_MCP_TOKEN"] == secret
+ assert "JARVIS_CONTROL_KEY" not in entry["env"], "pairing must not hand out the master key"
+ assert json.loads(body["config_text"])["mcpServers"]["jarvis-agents"] == entry
+
+ # And it really works as a credential.
+ assert token_store.verify(secret) is not None
+
+
+def test_pair_for_another_machine_uses_that_address(connect_app: FastAPI, token_store) -> None:
+ with TestClient(connect_app) as client:
+ body = client.post(
+ "/api/agent-mcp/pair",
+ json={
+ "name": "Work laptop",
+ "transport": "http",
+ "base_url": "http://192.168.1.50:47821",
+ },
+ ).json()
+
+ entry = body["config"]["mcpServers"]["jarvis-agents"]
+ assert entry["url"] == "http://192.168.1.50:47821/api/control/mcp/agents"
+ assert entry["headers"]["Authorization"] == f"Bearer {body['secret']}"
+
+
+def test_paired_clients_are_listed_and_revocable(connect_app: FastAPI, token_store) -> None:
+ with TestClient(connect_app) as client:
+ first = client.post("/api/agent-mcp/pair", json={"name": "One"}).json()
+ client.post("/api/agent-mcp/pair", json={"name": "Two"}).json()
+
+ listed = client.get("/api/agent-mcp/tokens").json()
+ assert {t["name"] for t in listed["tokens"]} == {"One", "Two"}
+ assert all("secret" not in t for t in listed["tokens"])
+ assert listed["scopes"] == ["read", "work", "full"]
+
+ token_id = first["token"]["token_id"]
+ gone = client.request("DELETE", f"/api/agent-mcp/tokens/{token_id}").json()
+ assert gone["revoked"] is True
+
+ left = client.get("/api/agent-mcp/tokens").json()
+ assert {t["name"] for t in left["tokens"]} == {"Two"}
+
+
+def test_pair_refuses_a_nameless_client(connect_app: FastAPI, token_store) -> None:
+ with TestClient(connect_app) as client:
+ answer = client.post("/api/agent-mcp/pair", json={"name": " "})
+ assert answer.status_code == 422
diff --git a/tests/unit/mcp/test_agent_mcp_tokens.py b/tests/unit/mcp/test_agent_mcp_tokens.py
new file mode 100644
index 0000000000..148beeff12
--- /dev/null
+++ b/tests/unit/mcp/test_agent_mcp_tokens.py
@@ -0,0 +1,138 @@
+"""Per-client MCP credentials: issue, scope, verify, revoke.
+
+The properties that matter are the ones a leak or a mistake would expose: the
+secret is never persisted, a revoked token is dead immediately, and a scope
+cannot be talked past — a `read` token does not merely get refused, it is never
+offered the tools it may not call.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.mcp.agents import tokens as tk
+
+
+def store(tmp_path: Path) -> tk.TokenStore:
+ return tk.TokenStore(tmp_path / "mcp_tokens.json")
+
+
+def test_a_token_is_returned_once_and_stored_only_as_a_hash(store: tk.TokenStore) -> None:
+ token, secret = store.issue(name="Claude Desktop - MacBook", scope="work")
+
+ assert secret.startswith("jarvis_mcp_")
+ assert token.token_id in secret
+ assert secret not in json.dumps(json.loads(store.path.read_text(encoding="utf-8")))
+ # The public view is what a UI or a log may show.
+ public = token.to_public()
+ assert "secret_hash" not in public
+ assert public["name"] == "Claude Desktop - MacBook"
+ assert public["revoked"] is False
+
+
+def test_verify_accepts_the_real_secret_and_nothing_else(store: tk.TokenStore) -> None:
+ token, secret = store.issue(name="Cursor", scope="read")
+
+ assert store.verify(secret) is not None
+ assert store.verify(secret).token_id == token.token_id
+ assert store.verify(secret + "x") is None
+ assert store.verify(f"jarvis_mcp_{token.token_id}_wrong") is None
+ assert store.verify("some-control-key") is None
+ assert store.verify(None) is None
+ assert store.verify("") is None
+
+
+def test_verify_stamps_last_use(store: tk.TokenStore) -> None:
+ _token, secret = store.issue(name="Phone")
+ assert store.list()[0].last_used_ms == 0
+
+ store.verify(secret)
+
+ assert store.list()[0].last_used_ms > 0, "the owner must be able to see what is in use"
+
+
+def test_revoking_one_client_leaves_the_others(store: tk.TokenStore) -> None:
+ keep, keep_secret = store.issue(name="Laptop")
+ drop, drop_secret = store.issue(name="Old phone")
+
+ store.revoke(drop.token_id)
+
+ assert store.verify(drop_secret) is None
+ assert store.verify(keep_secret) is not None
+ assert {t.token_id for t in store.list()} == {keep.token_id}
+ # The record survives revocation, so "what happened to that client?" has an answer.
+ assert drop.token_id in {t.token_id for t in store.list(include_revoked=True)}
+
+
+def test_tokens_survive_a_reload(tmp_path: Path) -> None:
+ first = tk.TokenStore(tmp_path / "mcp_tokens.json")
+ _token, secret = first.issue(name="Desktop")
+
+ second = tk.TokenStore(tmp_path / "mcp_tokens.json")
+
+ assert second.verify(secret) is not None
+
+
+def test_a_corrupt_file_does_not_lock_anyone_out(tmp_path: Path) -> None:
+ path = tmp_path / "mcp_tokens.json"
+ path.write_text("{ not json at all", encoding="utf-8")
+ store = tk.TokenStore(path)
+
+ assert store.list() == []
+ # And it can still be written to — the owner re-pairs and moves on.
+ _token, secret = store.issue(name="Fresh")
+ assert store.verify(secret) is not None
+
+
+def test_issue_refuses_a_nameless_or_unknown_scope(store: tk.TokenStore) -> None:
+ with pytest.raises(tk.TokenError, match="needs a name"):
+ store.issue(name=" ")
+ with pytest.raises(tk.TokenError, match="scope must be"):
+ store.issue(name="X", scope="admin")
+
+
+# ------------------------------------------------------------------ scopes
+
+
+def test_read_scope_gets_no_spending_tool() -> None:
+ assert tk.allows("read", "agents_list", dangerous=False) is True
+ assert tk.allows("read", "ecosystem_status", dangerous=False) is True
+ assert tk.allows("read", "agent_chat", dangerous=True) is False
+ assert tk.allows("read", "quest_post", dangerous=True) is False
+ assert tk.allows("read", "kill_switch", dangerous=True) is False
+
+
+def test_work_scope_spends_but_does_not_govern() -> None:
+ assert tk.allows("work", "agent_chat", dangerous=True) is True
+ assert tk.allows("work", "quest_post", dangerous=True) is True
+ assert tk.allows("work", "agent_assign", dangerous=True) is True
+ # Governance decides what the ecosystem may do — that stays with the owner.
+ assert tk.allows("work", "kill_switch", dangerous=True) is False
+ assert tk.allows("work", "approval_resolve", dangerous=True) is False
+
+
+def test_full_scope_is_everything() -> None:
+ for name in ("kill_switch", "approval_resolve", "agent_chat", "agents_list"):
+ assert tk.allows("full", name, dangerous=True) is True
+
+
+def test_every_dangerous_tool_is_classified() -> None:
+ """No tool may be dangerous and yet fall outside all three scopes."""
+ from jarvis.mcp.agents import TOOLS
+
+ for tool in TOOLS:
+ reachable = [s for s in tk.SCOPES if tk.allows(s, tool.name, dangerous=tool.dangerous)]
+ assert reachable, f"{tool.name} is callable by no scope at all"
+ if not tool.dangerous:
+ assert reachable == list(tk.SCOPES), f"{tool.name} is safe but not readable"
+
+
+def test_looks_like_token_separates_credentials(store: tk.TokenStore) -> None:
+ _token, secret = store.issue(name="X")
+ assert tk.looks_like_token(secret) is True
+ assert tk.looks_like_token("a-plain-control-key") is False
+ assert tk.looks_like_token(None) is False