Skip to content
Python

OPE-136: MCP permission model — EXTERNAL floor, durable per-tool trust, run grants, honest approval plumbing

Devika Verma7ea4de3877df
diff --git a/coworker/agent.py b/coworker/agent.py
index c958a854..9479718c 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -433,9 +433,13 @@ def build_engine(
)
)
- # User-local risk overrides (mainly to relax MCP's conservative default). Empty store →
- # no-op; never written by persona loading (the no-self-grant rule).
- risk_overrides = RiskOverrideStore(state_dir() / "risk_overrides.json").resolver()
+ # User-local risk overrides (relax a plugin / tighten anything) + OPE-136 trust
+ # rules (per-MCP-tool "don't ask", durable). One store, never written by persona
+ # loading (the no-self-grant rule). The same instance serves the read side
+ # (classify + the trusted branch) and the write side ("Always allow this tool"),
+ # so a rule minted mid-session quiets THIS session immediately and every later
+ # one via the file.
+ override_store = RiskOverrideStore(state_dir() / "risk_overrides.json")
permissions = PermissionEngine(
workspace_root=ws or (root_list[0].path if root_list else Path.cwd()),
mode=mode,
@@ -446,7 +450,9 @@ def build_engine(
auto_allow_tools=set(config.auto_allow),
allowed_domains=list(config.allowed_domains),
roots=root_list or None,
- risk_overrides=risk_overrides,
+ risk_overrides=override_store.resolver(),
+ trust_overrides=override_store.trusted,
+ grant_trust=override_store.set_trust,
)
# The plan-mode exit door — mutually exclusive with the board's decomposition
# gate, DERIVED from the team trait (owner call 2026-08-16): a lead never
diff --git a/coworker/engine.py b/coworker/engine.py
index f16afe86..e492443c 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -47,6 +47,14 @@ class ApprovalOutcome(str, Enum):
ALWAYS_DOMAIN = "always_domain"
# Session-wide grant for classifier-approved read-only shell commands (readonly.py).
READONLY_SESSION = "readonly_session"
+ # OPE-136 durable trust: persist a per-tool "don't ask" rule for an MCP tool —
+ # survives sessions, revocable on the server's detail page. MCP-only (validated
+ # server-side in manager._grant_offered, like every other grant).
+ ALWAYS_TRUST = "always_trust"
+ # OPE-136 run grant ("Allow for this request"): cover this exact tool for the
+ # remainder of the CURRENT run only — in-memory, cleared at the run boundary,
+ # nothing persisted. EXTERNAL-risk tools only (validated server-side).
+ THIS_RUN = "this_run"
DENY = "deny"
@@ -66,6 +74,10 @@ class PermissionRequest:
metadata: Any
reason: str
tool_call_id: Optional[str] = None # for durable resume (idempotent inbox item)
+ # Where an MCP call actually goes ({transport, host}, from the server DEF at
+ # registration) — carried on the request so a PARKED approval shows the same
+ # destination evidence as the live card (§35 parity). None for non-MCP tools.
+ mcp_destination: Optional[dict] = None
Approver = Callable[[PermissionRequest], Awaitable[ApprovalOutcome]]
@@ -312,9 +324,18 @@ class TurnEngine:
data["source"] = source
if display is not None:
data["display"] = display
+ # OPE-136 run grants: a fresh run starts with a clean slate (belt — the
+ # finally below is the braces; an abandoned generator must not leak a
+ # previous answer's "Allow for this request" into this one).
+ self.permissions.clear_run_allowances()
yield Event(EventType.TURN_START, data)
- async for event in self._loop():
- yield event
+ try:
+ async for event in self._loop():
+ yield event
+ finally:
+ # The run boundary IS the grant's expiry — normal finish, Stop, and
+ # generator teardown (disconnect) all land here.
+ self.permissions.clear_run_allowances()
def switch_model(self, model: str) -> Optional[str]:
"""Rebind the session's model mid-conversation (roadmap item 3). History is
@@ -1147,6 +1168,33 @@ class TurnEngine:
if allowed and decision.reason == "full access":
self._approval_origins[tool_call.id] = {"origin": "bypass"}
+ # OPE-136: a trusted-MCP allow ran cardless on standing config (a user trust
+ # rule, or the legacy server flag) — audited and chip-annotated like every
+ # other cardless origin ("recorded, never invisible"). Prefix-matched against
+ # permissions.py's two trusted-branch reason strings — and the chip keeps the
+ # two apart: "your trust rule" points at the tool page's Revoke, "server
+ # trust" at the mcp.json flag. One generic label made a user believe the
+ # SERVER had marked their own rule (owner-hit 2026-08-30).
+ if allowed and decision.reason.startswith("trusted MCP tool"):
+ origin = (
+ "trusted_rule"
+ if "user trust rule" in decision.reason
+ else "trusted_server"
+ )
+ self._approval_origins[tool_call.id] = {"origin": origin}
+ self._audit(
+ tool_call, stage="auto_allowed", status="allowed", reason=reason
+ )
+
+ # OPE-136 run grant: a covered call ran cardless under the user's in-run
+ # "Allow for this request" click — silent to attention, never invisible to
+ # the record (transcript chip + audit row, like every cardless origin).
+ if allowed and decision.reason == "tool allowed for this request":
+ self._approval_origins[tool_call.id] = {"origin": "run_grant"}
+ self._audit(
+ tool_call, stage="auto_allowed", status="allowed", reason=reason
+ )
+
if not allowed and decision.needs_user and self._consume_allow_anyway(tool_call):
# §8.4 "Allow anyway": the human already approved this exact action from the
# deny card. One-shot — consumed above; a different action never matches.
@@ -1263,6 +1311,21 @@ class TurnEngine:
# True when this shell command classifies as read-only — the card
# offers "Allow read-only commands for this session" only then.
"readonly_ok": _readonly_ok(tool_call.arguments),
+ # OPE-136 finding 4: where an MCP call actually goes, stamped at
+ # registration (mcp/tools.py) from the server def — so the card's
+ # scope chip can say "leaves this computer → host" instead of the
+ # catch-all "stays on this computer". None for non-MCP tools.
+ **(
+ {"mcp_destination": dest}
+ if (
+ dest := getattr(
+ spec.func, "__coworker_mcp_destination__", None
+ )
+ if spec
+ else None
+ )
+ else {}
+ ),
**(
self.approval_extras(tool_call.name, tool_call.arguments)
if self.approval_extras
@@ -1284,6 +1347,11 @@ class TurnEngine:
metadata=metadata,
reason=decision.reason,
tool_call_id=tool_call.id,
+ mcp_destination=(
+ getattr(spec.func, "__coworker_mcp_destination__", None)
+ if spec
+ else None
+ ),
)
),
interrupted=ApprovalOutcome.DENY,
@@ -1319,6 +1387,13 @@ class TurnEngine:
)
elif outcome is ApprovalOutcome.READONLY_SESSION:
self.permissions.allow_readonly_for_session()
+ elif outcome is ApprovalOutcome.ALWAYS_TRUST:
+ # Durable per-tool trust (OPE-136 §4): lands in the user-local
+ # override store, so tomorrow's sessions stay quiet too.
+ self.permissions.grant_trust_for_tool(tool_call.name)
+ elif outcome is ApprovalOutcome.THIS_RUN:
+ # Run grant: dies with the current answer (cleared in run()).
+ self.permissions.allow_tool_for_run(tool_call.name)
allowed, reason = True, "approved by user"
self._approval_origins[tool_call.id] = {
"origin": "user",
diff --git a/coworker/mcp/config.py b/coworker/mcp/config.py
index 8bdbeadc..a0c211df 100644
--- a/coworker/mcp/config.py
+++ b/coworker/mcp/config.py
@@ -133,7 +133,10 @@ def patch_global_server(name: str, changes: dict[str, Any]) -> bool:
servers = read_global()
if name not in servers:
return False
- servers[name] = {**servers[name], **changes}
+ merged = {**servers[name], **changes}
+ # A None value DELETES the key (there is no other way to remove one through a
+ # merge patch) — used by the OPE-136 trust migration to drop `requires_approval`.
+ servers[name] = {k: v for k, v in merged.items() if v is not None}
_write_global(servers)
return True
diff --git a/coworker/mcp/tools.py b/coworker/mcp/tools.py
index ecd8a140..7495de45 100644
--- a/coworker/mcp/tools.py
+++ b/coworker/mcp/tools.py
@@ -87,5 +87,24 @@ def build_callables(
requires_approval=server.requires_approval,
)
_invoke.__coworker_schema__ = _openai_schema(name, mcp_tool)
+ # OPE-136 finding 4: where this call actually goes, for the approval card's
+ # scope chip. From the server DEF (user-authored config), never from anything
+ # the server itself claims. http → the remote host; stdio → a local process.
+ _invoke.__coworker_mcp_destination__ = {
+ "transport": server.transport,
+ "host": _server_host(server),
+ }
callables.append(_invoke)
return callables
+
+
+def _server_host(server: MCPServerDef) -> str:
+ """The hostname an HTTP server's calls reach (lowercased), "" for stdio/unparseable."""
+ if not server.url:
+ return ""
+ try:
+ from urllib.parse import urlparse
+
+ return (urlparse(server.url).hostname or "").lower()
+ except ValueError: # pragma: no cover - urlparse rarely raises, but fail to ""
+ return ""
diff --git a/coworker/overrides.py b/coworker/overrides.py
index 0abb2cf8..c7cca1da 100644
--- a/coworker/overrides.py
+++ b/coworker/overrides.py
@@ -1,8 +1,13 @@
-"""User-local risk overrides — relax (or tighten) a tool's risk class.
+"""User-local risk overrides — relax (or tighten) a tool's risk class — and, since
+OPE-136, per-tool TRUST rules.
-Mainly to relax MCP's conservative default (every MCP tool defaults to ``external``): a user
-who trusts a server can mark its read-only tools ``read`` so they stop gating. Rules match the
-tool name (e.g. ``mcp__notion__create_page``) by glob; the most specific rule wins.
+``rules`` relax or tighten a third-party (plugin) tool's risk class by glob; the most
+specific rule wins. MCP tools cannot be reclassified (the floor in ``risk.classify``);
+their sanctioned lever is a ``trust`` rule instead: *waive the approval card for this
+tool* — nothing else. A trusted tool stays EXTERNAL: read-only modes still deny it, the
+Auto-approve reviewer still judges it, and the audit trail still records it. One store,
+two rule types, one loader — deliberately NOT a second file (the architecture review
+rejected a parallel trust store as yet another labeling system).
**Inviolable rule: this store is user-local and is NEVER written by a persona/package.** A
persona can declare what tools it wants, but only the user decides how much to trust them — so
@@ -36,18 +41,51 @@ def _specificity(pattern: str) -> int:
class RiskOverrideStore:
def __init__(self, path: Optional[str | Path] = None) -> None:
self.path = Path(path) if path else None
+ # Rules refused at load with the reason why — surfaced to the user instead of
+ # silently shaping permissions differently than their file says.
+ self.rejected: list[tuple[str, str]] = [] # (pattern, reason)
+ # OPE-136 trust rules: exact tool names (the card writes exact names — a button
+ # grants precisely what its card showed; globs stay a hand-editing power path).
+ self._trust: list[str] = []
self._rules: list[_Rule] = self._load()
def _load(self) -> list[_Rule]:
if not (self.path and self.path.is_file()):
return []
data = json.loads(self.path.read_text(encoding="utf-8"))
+ # Trust entries: {"pattern": "..."} dicts (the written form) or bare strings.
+ seen: set[str] = set()
+ for entry in data.get("trust", []) or []:
+ pattern = (
+ str(entry.get("pattern", "")) if isinstance(entry, dict) else str(entry)
+ )
+ if pattern and pattern not in seen:
+ seen.add(pattern)
+ self._trust.append(pattern)
rules = []
for r in data.get("rules", []):
try:
- rules.append(_Rule(str(r["pattern"]), RiskClass(str(r["risk"]))))
+ rule = _Rule(str(r["pattern"]), RiskClass(str(r["risk"])))
except (KeyError, ValueError):
continue # skip malformed rules rather than failing the whole store
+ # OPE-136: an explicitly MCP-targeting rule may not sink a tool below
+ # EXTERNAL — the floor in risk.classify would silently ignore it anyway,
+ # and a rule that reads one way in the file but acts another is worse than
+ # a refused rule. (Generic globs that merely HAPPEN to match mcp__ names
+ # load normally; the classify floor neutralizes the loosening for those.)
+ if rule.pattern.startswith("mcp__") and rule.risk in (
+ RiskClass.READ,
+ RiskClass.EGRESS,
+ ):
+ self.rejected.append(
+ (
+ rule.pattern,
+ "MCP tools cannot be reclassified below external "
+ "(OPE-136) — use a trust rule to stop the asking",
+ )
+ )
+ continue
+ rules.append(rule)
return rules
def save(self) -> None:
@@ -60,7 +98,8 @@ class RiskOverrideStore:
"rules": [
{"pattern": r.pattern, "risk": r.risk.value}
for r in self._rules
- ]
+ ],
+ "trust": [{"pattern": p} for p in self._trust],
},
indent=2,
),
@@ -68,8 +107,17 @@ class RiskOverrideStore:
)
def set_rule(self, pattern: str, risk: RiskClass | str) -> None:
- """Add/replace a user override (the everyday path writes this from the approval UI)."""
+ """Add/replace a user override (the everyday path writes this from the approval UI).
+
+ Refuses what `_load` refuses (OPE-136): an explicitly MCP-targeting rule below
+ EXTERNAL would be written now and silently dropped on the next load — a rule
+ that works for one session and then vanishes is a trap, so it never lands."""
risk = RiskClass(risk) if not isinstance(risk, RiskClass) else risk
+ if pattern.startswith("mcp__") and risk in (RiskClass.READ, RiskClass.EGRESS):
+ raise ValueError(
+ "MCP tools cannot be reclassified below external (OPE-136) — "
+ "use a trust rule to stop the asking"
+ )
self._rules = [r for r in self._rules if r.pattern != pattern]
self._rules.append(_Rule(pattern, risk))
self.save()
@@ -87,3 +135,26 @@ class RiskOverrideStore:
def resolver(self) -> Callable[[str], Optional[RiskClass]]:
"""A callable for ``PermissionEngine.risk_overrides`` / ``risk.classify``."""
return self.resolve
+
+ # -- OPE-136 trust rules (waive the card; never reclassify) ---------------------
+ def trusted(self, tool_name: str) -> bool:
+ """Whether a standing trust rule covers this tool (glob-matched, like risk rules)."""
+ return any(fnmatchcase(tool_name, p) for p in self._trust)
+
+ def set_trust(self, pattern: str) -> None:
+ """Mint a trust rule (the approval card's "Always allow this tool" writes an
+ EXACT name — a button grants precisely what its card showed, nothing wider)."""
+ if not pattern:
+ return
+ if pattern not in self._trust:
+ self._trust.append(pattern)
+ self.save()
+
+ def revoke_trust(self, pattern: str) -> None:
+ before = len(self._trust)
+ self._trust = [p for p in self._trust if p != pattern]
+ if len(self._trust) != before:
+ self.save()
+
+ def trust_patterns(self) -> list[str]:
+ return list(self._trust)
diff --git a/coworker/permissions.py b/coworker/permissions.py
index 9e822feb..54ea04c9 100644
--- a/coworker/permissions.py
+++ b/coworker/permissions.py
@@ -13,7 +13,7 @@ import shlex
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Callable, Optional
from urllib.parse import urlsplit
# Constructs whose *contents* we cannot evaluate, so a command carrying one is never
@@ -286,6 +286,13 @@ class PermissionEngine:
auto_allow_tools: set[str] = field(default_factory=set)
session_allow_tools: set[str] = field(default_factory=set)
session_allow_commands: set[str] = field(default_factory=set)
+ # OPE-136 run grants ("Allow for this request"): tool names covered for the
+ # REMAINDER OF THE CURRENT RUN only. In-memory by design — the engine clears the
+ # set when the run finishes or is interrupted, and a process restart ending the
+ # run makes the empty set correct, not a loss. Minted only for EXTERNAL-risk
+ # tools (server-validated in manager._grant_offered); unlike the session grant
+ # this one exists FOR connectors and MCP — the loop/retry/pagination shapes.
+ run_allow_tools: set[str] = field(default_factory=set)
# Egress domains that auto-run without a prompt: `allowed_domains` from user config, plus
# `session_allow_domains` minted by "Always allow this domain". Matched by exact host or
# subdomain suffix (see `_domain_allowed`).
@@ -300,6 +307,13 @@ class PermissionEngine:
task_rules: dict[str, set[str]] = field(default_factory=dict)
# User-local risk override resolver (Phase 2). None → use the base classification.
risk_overrides: Optional[RiskOverrides] = None
+ # OPE-136 durable trust: tool name → has the user minted a standing "don't ask" rule?
+ # (RiskOverrideStore.trusted). Waives only the card, only outside AUTO_APPROVE —
+ # never the class, the mode gates, or the audit trail. None → no trust rules.
+ trust_overrides: Optional[Callable[[str], bool]] = None
+ # The write half (RiskOverrideStore.set_trust) — how ApprovalOutcome.ALWAYS_TRUST
+ # lands on disk. Kept as an injected callable so this module never imports the store.
+ grant_trust: Optional[Callable[[str], None]] = None
# Shared, possibly-mutable list of roots (RootDir-like / dicts). When omitted, the single
# `workspace_root` is the sole writable root (back-compat). Kept by reference and re-read on
# every check, so runtime add/remove of folders takes effect without rebuilding the engine.
@@ -332,7 +346,15 @@ class PermissionEngine:
is_write = risk is RiskClass.WRITE_LOCAL
is_shell = risk is RiskClass.EXEC
is_egress = risk is RiskClass.EGRESS
- consequential = is_consequential(risk)
+ # Persistent-authority tools are consequential BY NAME: their risk class can
+ # read as READ (no base-table/catalog entry), but granting standing authority is
+ # a side effect — read-only modes must DENY them, not offer a grant card. The
+ # OPE-117 comment below always promised "read-only modes still hard-deny above
+ # this"; the OPE-136 gate-order pin caught that the class-based check alone
+ # didn't deliver it (save_skill in Discuss reached the human-only card).
+ consequential = (
+ is_consequential(risk) or tool_name in PERSISTENT_AUTHORITY_TOOLS
+ )
# SELF-PROTECTION FLOOR — runs before mode, allowlists and every auto-approve path,
# because the escalation it blocks happens in the DEFAULT mode. No verdict below can
@@ -450,6 +472,30 @@ class PermissionEngine:
and not is_connector
):
return Decision(True, "tool allowed for session")
+ # Run grant (OPE-136 "Allow for this request"): same checkpoint, shorter life —
+ # and no connector exclusion, because EXTERNAL is exactly who it exists for.
+ # §1.5 still applies: an in-flow click never skips the Auto-Approve judge.
+ if honor_session_grants and tool_name in self.run_allow_tools:
+ return Decision(True, "tool allowed for this request")
+
+ # OPE-136: MCP trust waives only the card, in the one mode where the card is the
+ # deciding voice. Two sources, one branch: a per-tool trust RULE the user minted
+ # from the card ("Always allow this tool" → risk_overrides.json), or the legacy
+ # server-level `requires_approval: false` (which no longer reclassifies — the MCP
+ # floor in risk.classify keeps these tools EXTERNAL). Everything above still
+ # applied: read-only modes denied before this line, the persistent-authority and
+ # protected-file floors returned before it, and Bypass already returned.
+ # Deliberately NOT honored in AUTO_APPROVE: v1 keeps §1.5 conservative — the
+ # reviewer judges trusted MCP calls (falling through to needs_user routes
+ # there); only hand-authored config allowlists skip the judge.
+ if (
+ getattr(metadata, "category", "") == "mcp"
+ and self.mode is not Mode.AUTO_APPROVE
+ ):
+ if self.trust_overrides is not None and self.trust_overrides(tool_name):
+ return Decision(True, "trusted MCP tool (user trust rule)")
+ if not bool(getattr(metadata, "requires_approval", True)):
+ return Decision(True, "trusted MCP tool (server marked don't-ask)")
# Task-scoped standing rules (§25): tool + exact target, owned by the automation.
# Deliberately NOT subject to the connector exclusion above — the exact-target
@@ -475,6 +521,24 @@ class PermissionEngine:
def allow_tool_for_session(self, tool_name: str) -> None:
self.session_allow_tools.add(tool_name)
+ def allow_tool_for_run(self, tool_name: str) -> None:
+ self.run_allow_tools.add(tool_name)
+
+ def clear_run_allowances(self) -> None:
+ """The run boundary IS the grant's expiry: the engine calls this when a run
+ finishes or is interrupted, so "Allow for this request" never outlives the
+ answer the user was watching."""
+ self.run_allow_tools.clear()
+
+ def grant_trust_for_tool(self, tool_name: str) -> None:
+ """OPE-136 durable trust: persist a per-tool "don't ask" rule (survives sessions).
+ Falls back to the session grant when no store is wired (ephemeral engines in
+ tests) — the card's promise degrades to session scope rather than to nothing."""
+ if self.grant_trust is not None:
+ self.grant_trust(tool_name)
+ else:
+ self.session_allow_tools.add(tool_name)
+
def allow_command_for_session(self, command: str) -> None:
if command:
self.session_allow_commands.add(command)
diff --git a/coworker/risk.py b/coworker/risk.py
index 3319496c..4873271b 100644
--- a/coworker/risk.py
+++ b/coworker/risk.py
@@ -87,16 +87,48 @@ def _catalog_floor(tool_name: str) -> Optional[RiskClass]:
return RiskClass.EXTERNAL if kind is not None and kind != "read" else None
+def _mcp_floor(tool_name: str, metadata: Any) -> Optional[RiskClass]:
+ """The floor for third-party MCP tools (OPE-136): EXTERNAL, always.
+
+ An MCP tool's effects are a stranger's claim — we cannot tell its reads from a write
+ wearing a read's name — so no config value may drop one into the never-checked READ
+ tier. Before this floor, `requires_approval: false` in mcp.json reclassified a whole
+ server's tools to READ, which skipped not just the approval card but the Discuss-mode
+ denial, the Auto-approve reviewer, and the audit trail in one step. The flag now only
+ ever waives the *card* (see permissions.evaluate's trusted-MCP branch); the class is
+ welded on.
+
+ Keyed on `category == "mcp"`, not the name prefix: the first-party MCP-backed
+ connectors (§42 one-click jira/monday/asana) share the `mcp__*` naming but are
+ re-labelled `category="connector"` at wiring (server/manager.py) because their
+ read/write kinds are pinned in the catalog — first-hand knowledge, so §36's
+ "connector reads never gate" keeps applying to them. That relabel also closes the
+ reverse name-collision: a CUSTOM server that happens to reuse a catalog name still
+ carries category "mcp" and lands on this floor. The name-prefix check only backstops
+ the metadata-less case (a bare name reaching classify without its registration
+ sticker fails closed)."""
+ if getattr(metadata, "category", "") == "mcp":
+ return RiskClass.EXTERNAL
+ if metadata is None and tool_name.startswith("mcp__"):
+ return RiskClass.EXTERNAL
+ return None
+
+
def classify(
tool_name: str, metadata: Any = None, overrides: Optional[RiskOverrides] = None
) -> RiskClass:
- """Effective risk of a tool call. A user override may *relax* a metadata/MCP tool (the
+ """Effective risk of a tool call. A user override may *relax* a metadata tool (the
intended use — quieting an over-cautious plug-in), but may only ever **tighten** a
- built-in write/exec/egress tool or a connector-catalog write, never loosen one.
- Downgrading a write to a read would switch off path scoping AND the read-only gate at
- once, so it is refused here. Precedence otherwise: the by-name base table, then aisuite
- metadata (`requires_approval` → external), else read."""
- base = _BASE.get(tool_name) or _catalog_floor(tool_name)
+ built-in write/exec/egress tool, a connector-catalog write, or a third-party MCP tool
+ (OPE-136), never loosen one. Downgrading a write to a read would switch off path
+ scoping AND the read-only gate at once, so it is refused here. Precedence otherwise:
+ the by-name base table, then aisuite metadata (`requires_approval` → external),
+ else read."""
+ base = (
+ _BASE.get(tool_name)
+ or _catalog_floor(tool_name)
+ or _mcp_floor(tool_name, metadata)
+ )
if overrides is not None:
ov = overrides(tool_name)
if ov is not None:
diff --git a/coworker/server/app.py b/coworker/server/app.py
index 457c0811..c2e60e15 100644
--- a/coworker/server/app.py
+++ b/coworker/server/app.py
@@ -158,14 +158,14 @@ from ..attachments import (
build_user_content,
)
from ..engine import ApprovalOutcome
-from ..inbox import VIS_INBOX, VIS_INLINE, args_preview
+from ..inbox import VIS_INBOX, VIS_INLINE
from ..permissions import Mode
from ..providers import AssistantTurn
from .. import toolchain
from ..teams.model import AuthorityError as TeamsAuthorityError
from ..teams.model import BoardError as TeamsBoardError
from ..teams.model import BoardNotFoundError as TeamsBoardNotFoundError
-from .manager import SessionManager
+from .manager import SessionManager, _approval_body
def create_app(manager: SessionManager) -> FastAPI:
@@ -1198,10 +1198,29 @@ def create_app(manager: SessionManager) -> FastAPI:
def mcp_delete(name: str) -> dict[str, Any]:
return manager.delete_mcp(name)
+ @app.post("/v1/mcp/config/reveal")
+ def mcp_config_reveal() -> dict[str, Any]:
+ return manager.reveal_mcp_config()
+
@app.get("/v1/mcp/{name}/tools")
async def mcp_tools(name: str) -> dict[str, Any]:
return await manager.mcp_tools(name)
+ # OPE-136 §4/§5: the server detail page's trust surface — which tools carry a
+ # standing "don't ask" rule, revoke one, and the one-click migration off the
+ # legacy server-wide requires_approval flag.
+ @app.get("/v1/mcp/{name}/trust")
+ def mcp_trust(name: str) -> dict[str, Any]:
+ return manager.mcp_trust(name)
+
+ @app.delete("/v1/mcp/{name}/trust/{tool}")
+ def mcp_trust_revoke(name: str, tool: str) -> dict[str, Any]:
+ return manager.revoke_mcp_trust(name, tool)
+
+ @app.post("/v1/mcp/{name}/trust/convert")
+ async def mcp_trust_convert(name: str) -> dict[str, Any]:
+ return await manager.convert_mcp_trust(name)
+
@app.post("/v1/mcp/{name}/connect")
async def mcp_connect(name: str) -> dict[str, Any]:
# Connect now. For `auth: oauth` servers the first connect opens the system
@@ -2064,14 +2083,9 @@ def create_app(manager: SessionManager) -> FastAPI:
item = manager.inbox.add_approval(
session_id,
f"Run `{_request.tool_name}`?",
- body="\n".join(
- p
- for p in (
- (getattr(_request, "reason", "") or "").strip(),
- args_preview(getattr(_request, "arguments", None)),
- )
- if p
- ),
+ # Shared with inbox_approver so parked/mirrored bodies match the live
+ # card's dialect (boilerplate-reason filtering included, §35).
+ body=_approval_body(_request),
inbox=_route(),
visibility=_visibility(),
# Automation-run context (manual "Run now" rides this socket): lets the
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index 130ede1f..cf9b740f 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -149,6 +149,17 @@ def _grant_offered(outcome, request) -> bool:
return risk is RiskClass.EXEC
if outcome is ApprovalOutcome.ALWAYS_DOMAIN:
return risk is RiskClass.EGRESS and bool(args.get("url"))
+ if outcome is ApprovalOutcome.ALWAYS_TRUST:
+ # OPE-136 §4: durable per-tool trust is the MCP family's sanctioned lever —
+ # the coarsest grant knowledge allows there, and offered nowhere else
+ # (connectors have target-scoped standing rules; built-ins their own grants).
+ return getattr(metadata, "category", "") == "mcp"
+ if outcome is ApprovalOutcome.THIS_RUN:
+ # OPE-136 run grant: EXTERNAL only — the loop/retry/pagination shapes live
+ # there, and the ladder's once-or-forever hole drains fatigue into durable
+ # grants. EXEC keeps its command-scoped instruments (tool-wide shell is a
+ # blank check at any duration); EGRESS keeps the domain-scoped grant.
+ return risk is RiskClass.EXTERNAL
if outcome is ApprovalOutcome.ALWAYS_TOOL:
if risk in (RiskClass.EXEC, RiskClass.EXTERNAL):
return False
@@ -163,8 +174,12 @@ def _grant_offered(outcome, request) -> bool:
def _approval_body(request) -> str:
"""Approval card body: the tool's reason (if any) plus a compact preview of its args, so a
mirrored 'Run `write_file`?' shows the path/content rather than just the tool name.
+ "requires approval" is the engine's default boilerplate — the live card filters it
+ (ApprovalCard.tsx), so the parked/mirrored body must not bake it in either (§35).
"""
reason = (getattr(request, "reason", "") or "").strip()
+ if reason == "requires approval":
+ reason = ""
preview = args_preview(getattr(request, "arguments", None))
return "\n".join(p for p in (reason, preview) if p)
@@ -1311,10 +1326,18 @@ class SessionManager:
# Per-tool approval from the pinned read/write classification
# (server-level requires_approval is off for backed servers);
# anything unclassified stays approval-gated — fail closed.
+ # Category flips to "connector" (OPE-136): these are FIRST-PARTY tools
+ # whose kinds the catalog pins with first-hand knowledge, so §36's
+ # "connector reads never gate" applies — while the MCP floor in
+ # risk.classify (which keys on category "mcp") stays reserved for
+ # third-party servers. This also closes the reverse name-collision:
+ # a custom server reusing a catalog name keeps category "mcp" and
+ # gets floored, instead of inheriting the catalog's read verdict.
for fn in callables:
fn.__aisuite_tool_metadata__.requires_approval = approval_for_tool(
fn.__aisuite_tool_metadata__.name, default=True
)
+ fn.__aisuite_tool_metadata__.category = "connector"
out.extend(callables)
return out
@@ -1538,8 +1561,102 @@ class SessionManager:
from ..mcp import oauth as mcp_oauth
mcp_oauth.sign_out(name, self.secrets)
+ # OPE-136 owner-hit 2026-08-30: trust rules live in a DIFFERENT store
+ # (risk_overrides.json) keyed by name — leaving them behind let a future
+ # server added under the same name inherit don't-ask rules sight unseen
+ # (the reverse name-collision this issue exists to close). GONE means
+ # gone: revoke every rule scoped to this server's prefix. Broader
+ # hand-written globs (e.g. "mcp__*") are not this server's rules and
+ # stay. Sign-out deliberately does NOT do this — tokens only; a
+ # sign-out isn't the user saying the server is gone.
+ store = self._override_store()
+ prefix = f"mcp__{name}__"
+ for pattern in store.trust_patterns():
+ if pattern.startswith(prefix):
+ store.revoke_trust(pattern)
return {"ok": ok, "name": name}
+ def reveal_mcp_config(self) -> dict[str, Any]:
+ """Select the global mcp.json in the OS file manager (owner call
+ 2026-08-30: ONE file for all servers, revealed from one common place —
+ the per-server Configuration mirror is gone; the file IS the ground
+ truth for headers/stdio commands/hand edits). Reveal, never auto-open:
+ the default app for .json is a lottery across machines. Same
+ local-machine rationale as reveal_artifact/reveal_skill."""
+ import subprocess
+ import sys
+
+ from ..mcp.config import global_mcp_path
+
+ target = global_mcp_path()
+ if not target.exists():
+ return {"ok": False, "error": "mcp.json does not exist yet"}
+ try:
+ if sys.platform == "darwin":
+ subprocess.Popen(
+ ["open", "-R", str(target)],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ elif sys.platform == "win32":
+ # Explorer wants the path glued to the switch: /select,<path>
+ subprocess.Popen(["explorer", f"/select,{target}"])
+ else: # Linux/BSD: no portable select — open the containing folder
+ subprocess.Popen(
+ ["xdg-open", str(target.parent)],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ except OSError as exc:
+ return {"ok": False, "error": str(exc)}
+ return {"ok": True, "path": str(target)}
+
+ # -- OPE-136 durable MCP trust (server detail page) --------------------------
+ def _override_store(self):
+ """A fresh view of the user-local override store — the FILE is the source of
+ truth (sessions hold their own instances; a fresh read here always agrees
+ with disk)."""
+ from ..overrides import RiskOverrideStore
+ from ..secrets import state_dir
+
+ return RiskOverrideStore(state_dir() / "risk_overrides.json")
+
+ def mcp_trust(self, name: str) -> dict[str, Any]:
+ """The trusted tools of one server (exact rules under its prefix) + whether the
+ legacy server-wide don't-ask flag is still present in its config."""
+ prefix = f"mcp__{name}__"
+ store = self._override_store()
+ tools = [p[len(prefix):] for p in store.trust_patterns() if p.startswith(prefix)]
+ raw = read_global().get(name) or {}
+ return {
+ "ok": True,
+ "tools": tools,
+ "legacy_dont_ask": raw.get("requires_approval") is False,
+ }
+
+ def revoke_mcp_trust(self, name: str, tool: str) -> dict[str, Any]:
+ self._override_store().revoke_trust(f"mcp__{name}__{tool}")
+ return {"ok": True}
+
+ async def convert_mcp_trust(self, name: str) -> dict[str, Any]:
+ """Migrate the legacy server-wide flag to named per-tool trust rules: one rule
+ per tool the server CURRENTLY lists (post include_tools filtering — trust only
+ what exists), then drop `requires_approval` from the entry. Same behavior
+ today; bounded tomorrow — a tool the server ships later will ask, because no
+ rule names it."""
+ listing = await self.mcp_tools(name)
+ if not listing.get("ok"):
+ return {"ok": False, "error": listing.get("error", "server unreachable")}
+ raw = read_global().get(name) or {}
+ include = raw.get("include_tools")
+ offered = [t["name"] for t in listing["tools"]]
+ covered = [t for t in offered if include is None or t in include]
+ store = self._override_store()
+ for tool in covered:
+ store.set_trust(f"mcp__{name}__{tool}")
+ patch_global_server(name, {"requires_approval": None})
+ return {"ok": True, "trusted": covered}
+
async def mcp_tools(self, name: str) -> dict[str, Any]:
"""Connect one server and list its tools (name + description)."""
for server in load_mcp_servers(
@@ -4120,6 +4237,18 @@ class SessionManager:
"tool": request.tool_name,
"arguments": getattr(request, "arguments", None) or {},
}
+ # §35 parity (OPE-136 found-in-testing): the parked card must show the same
+ # scope chip and reason the live card would — carry the tool category, the
+ # MCP destination stamped on the request, and any non-boilerplate reason.
+ category = getattr(getattr(request, "metadata", None), "category", "")
+ if category:
+ data["category"] = category
+ dest = getattr(request, "mcp_destination", None)
+ if dest:
+ data["mcp_destination"] = dest
+ reason = (getattr(request, "reason", "") or "").strip()
+ if reason and reason != "requires approval":
+ data["reason"] = reason
task = self.task_store.task_for_run_session(session_id)
if task is None:
return data
@@ -4205,6 +4334,11 @@ class SessionManager:
ApprovalOutcome.ALWAYS_TOOL,
ApprovalOutcome.ALWAYS_COMMAND,
ApprovalOutcome.ALWAYS_DOMAIN,
+ # ALWAYS_TRUST was unlisted (a raw resolve could mint an inert-but-real
+ # trust rule for a non-MCP tool — evaluate ignores those, but the store
+ # shouldn't carry them); THIS_RUN validates like every grant.
+ ApprovalOutcome.ALWAYS_TRUST,
+ ApprovalOutcome.THIS_RUN,
) and not _grant_offered(outcome, request):
self._audit_grant_refused(session_id, request, resolution)
return ApprovalOutcome.ONCE
diff --git a/coworker/skills/store.py b/coworker/skills/store.py
index 0eeba554..65ccc66b 100644
--- a/coworker/skills/store.py
+++ b/coworker/skills/store.py
@@ -31,7 +31,6 @@ from ..secrets import state_dir
from .base import Skill, _parse_skill
_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
-_UPLOAD_TOKEN_RE = re.compile(r"^[0-9a-f]{32}$")
_MAX_NAME = 64
GLOBAL_SCOPE = "global"
PROJECT_SCOPE = "project"
@@ -278,22 +277,6 @@ class SkillStore:
)
# -- uploads: stage → preview → confirm -----------------------------------------
- def _staged_upload_path(self, token: str) -> Path:
- """Resolve one server-minted upload token without leaving the staging root."""
- token = str(token)
- if not _UPLOAD_TOKEN_RE.fullmatch(token):
- raise ValueError("Unknown or expired upload.")
- try:
- staging_root = self._staging_dir.resolve()
- staged = (staging_root / token).resolve()
- except (OSError, RuntimeError):
- raise ValueError("Unknown or expired upload.") from None
- # The shape check blocks path separators; this second check also rejects a
- # valid-looking token whose staging entry is a symlink/junction to elsewhere.
- if staged.parent != staging_root:
- raise ValueError("Unknown or expired upload.")
- return staged
-
def stage_upload(self, data: bytes, filename: str = "") -> dict[str, Any]:
"""Stage an upload and return the parsed preview. Accepts a ``.zip`` (folder skill)
or a bare ``SKILL.md`` with YAML frontmatter. Nothing is installed until
@@ -393,7 +376,7 @@ class SkillStore:
scope: str = GLOBAL_SCOPE,
workspace: Optional[str | Path] = None,
) -> dict[str, Any]:
- staged = self._staged_upload_path(token)
+ staged = self._staging_dir / str(token)
if not (staged / "SKILL.md").is_file():
raise ValueError("Unknown or expired upload.")
skill = _parse_skill(staged / "SKILL.md")
@@ -416,7 +399,7 @@ class SkillStore:
return {"name": name, "scope": scope, "path": str(folder)}
def discard_upload(self, token: str) -> None:
- staged = self._staged_upload_path(token)
+ staged = self._staging_dir / str(token)
shutil.rmtree(staged, ignore_errors=True)
diff --git a/tests/test_accounts.py b/tests/test_accounts.py
index 5d5ff981..4443d8c1 100644
--- a/tests/test_accounts.py
+++ b/tests/test_accounts.py
@@ -175,3 +175,4 @@ def test_generic_account_routes(acme, secrets, tmp_path, monkeypatch):
out = client.post("/v1/connectors/linear/accounts/x/default").json()
assert not out["ok"] and "not a multi-account" in out["error"]
+
diff --git a/tests/test_egress_and_overrides.py b/tests/test_egress_and_overrides.py
index 8dcf8b00..0291bc22 100644
--- a/tests/test_egress_and_overrides.py
+++ b/tests/test_egress_and_overrides.py
@@ -104,13 +104,21 @@ def test_override_cannot_downgrade_builtin_write(tmp_path):
def test_override_can_still_relax_a_plugin_tool(tmp_path):
- # The intended use survives: a non-built-in (MCP) tool defaulting to external can be
- # relaxed to read.
+ # The intended use survives for NON-MCP third-party tools: a plugin defaulting to
+ # external can be relaxed to read. (This test used to pin the same relaxation for
+ # an MCP tool — retired by OPE-136: MCP tools are floored at EXTERNAL, and "stop
+ # asking" is expressed as a trust rule, never a reclassification. The floor's own
+ # pins live in test_mcp_floor.py.)
from types import SimpleNamespace
- ov = _override({"mcp__notion__search": RiskClass.READ})
- meta = SimpleNamespace(requires_approval=True, category="mcp")
- assert classify("mcp__notion__search", meta, ov) is RiskClass.READ
+ ov = _override({"plugin_notes_search": RiskClass.READ})
+ meta = SimpleNamespace(requires_approval=True, category="plugin")
+ assert classify("plugin_notes_search", meta, ov) is RiskClass.READ
+
+ # The identical rule aimed at an MCP tool is neutralized by the floor.
+ ov_mcp = _override({"mcp__notion__search": RiskClass.READ})
+ meta_mcp = SimpleNamespace(requires_approval=True, category="mcp")
+ assert classify("mcp__notion__search", meta_mcp, ov_mcp) is RiskClass.EXTERNAL
def test_override_may_tighten(tmp_path):
diff --git a/tests/test_inbox.py b/tests/test_inbox.py
index 6a80fa6c..e4c97120 100644
--- a/tests/test_inbox.py
+++ b/tests/test_inbox.py
@@ -127,3 +127,55 @@ def test_approval_body_includes_tool_args():
req2 = PermissionRequest("rm", {"path": "/x"}, None, "destructive")
assert _approval_body(req2).startswith("destructive") # reason leads when present
+
+
+def test_approval_body_strips_boilerplate_reason():
+ """OPE-136 found-in-testing: the live card filters the engine's default
+ "requires approval" boilerplate — the parked/mirrored body must not bake it in."""
+ from coworker.engine import PermissionRequest
+ from coworker.server.manager import _approval_body
+
+ req = PermissionRequest("write_file", {"path": "g.txt"}, None, "requires approval")
+ body = _approval_body(req)
+ assert "requires approval" not in body
+ assert "g.txt" in body # the args preview still carries the evidence
+
+
+def test_approval_prompt_data_carries_mcp_evidence():
+ """§35 parity: the parked item's data holds the same category, destination, and
+ (non-boilerplate) reason the live card's event carries — so a reopened session
+ renders the identical scope chip and evidence, never the vague fallback."""
+ from types import SimpleNamespace
+
+ from coworker.engine import PermissionRequest
+ from coworker.server.manager import SessionManager
+
+ fake_mgr = SimpleNamespace(
+ task_store=SimpleNamespace(task_for_run_session=lambda _s: None)
+ )
+ req = PermissionRequest(
+ "mcp__my_jira__searchJiraIssuesUsingJql",
+ {"cloudId": "0bbb", "jql": "ORDER BY created DESC"},
+ SimpleNamespace(category="mcp"),
+ "requires approval",
+ mcp_destination={"transport": "http", "host": "mcp.atlassian.com"},
+ )
+ data = SessionManager.approval_prompt_data(fake_mgr, "s1", req)
+ assert data["category"] == "mcp"
+ assert data["mcp_destination"] == {"transport": "http", "host": "mcp.atlassian.com"}
+ assert "reason" not in data # boilerplate never travels
+
+ real = PermissionRequest(
+ "mcp__my_jira__editJiraIssue",
+ {"issueIdOrKey": "OPE-1"},
+ SimpleNamespace(category="mcp"),
+ "the reviewer wasn't sure this edit was asked for",
+ mcp_destination={"transport": "http", "host": "mcp.atlassian.com"},
+ )
+ real_data = SessionManager.approval_prompt_data(fake_mgr, "s1", real)
+ assert real_data["reason"] == "the reviewer wasn't sure this edit was asked for"
+
+ # Non-MCP requests stay lean: no category/destination keys invented for them.
+ plain = PermissionRequest("write_file", {"path": "g.txt"}, None, "requires approval")
+ plain_data = SessionManager.approval_prompt_data(fake_mgr, "s1", plain)
+ assert "mcp_destination" not in plain_data and "category" not in plain_data
diff --git a/tests/test_mcp_floor.py b/tests/test_mcp_floor.py
new file mode 100644
index 00000000..07e6728f
--- /dev/null
+++ b/tests/test_mcp_floor.py
@@ -0,0 +1,187 @@
+"""The MCP floor (OPE-136): no config value may drop an `mcp__*` tool below EXTERNAL.
+
+Before this floor, `requires_approval: false` in mcp.json reclassified a whole server's
+tools to READ — which skipped not just the approval card but the Discuss-mode denial, the
+Auto-approve reviewer, and the audit trail, in one config line. The flag now only ever
+waives the CARD (the gate's trusted-MCP branch); the class is welded on.
+
+Pinned the same way OPE-111's catalog floor is pinned: these tests are the invariant.
+"""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from coworker.permissions import Mode, PermissionEngine
+from coworker.risk import RiskClass, classify
+
+
+class Meta:
+ """The shape mcp/tools.py stamps on every MCP callable."""
+
+ def __init__(self, requires_approval: bool, category: str = "mcp") -> None:
+ self.requires_approval = requires_approval
+ self.category = category
+
+
+# -- the pinned invariant ---------------------------------------------------------
+# No config value, override rule, or metadata may classify an mcp-category tool below
+# EXTERNAL. If a refactor reopens the trapdoor, this is the test that goes red.
+ "metadata",
+ [Meta(True), Meta(False), None],
+ ids=["flag_true", "flag_false_the_trapdoor", "no_metadata_fails_closed"],
+)
+def test_mcp_tools_never_classify_below_external(metadata):
+ assert classify("mcp__anyserver__anytool", metadata) is RiskClass.EXTERNAL
+
+
+def test_a_loosening_override_cannot_beat_the_floor():
+ # Even a rule the loader somehow let through (e.g. a generic glob) is neutralized
+ # by classify's tighten-only comparison.
+ assert (
+ classify("mcp__srv__tool", Meta(False), overrides=lambda name: RiskClass.READ)
+ is RiskClass.EXTERNAL
+ )
+
+
+def test_a_tightening_override_still_works():
+ assert (
+ classify("mcp__srv__tool", Meta(True), overrides=lambda name: RiskClass.EXEC)
+ is RiskClass.EXEC
+ )
+
+
+# -- the floor is keyed on the mcp family, nothing wider --------------------------
+def test_non_mcp_metadata_tools_keep_the_relaxed_path():
+ # A plugin/aisuite tool that declares itself approval-free is still READ — the
+ # floor must not quietly tighten every third-party tool in the app.
+ assert classify("plugin_notes_search", Meta(False, category="plugin")) is RiskClass.READ
+
+
+def test_catalog_backed_connector_reads_stay_free():
+ # The §42 one-click connectors share the mcp__ naming but are relabeled
+ # category="connector" at wiring (server/manager.py) because the catalog pins
+ # their kinds first-hand — §36's "connector reads never gate" keeps applying.
+ assert (
+ classify("mcp__jira__getJiraIssue", Meta(False, category="connector"))
+ is RiskClass.READ
+ )
+ # Catalog WRITES keep the OPE-111 floor regardless of the flag.
+ assert (
+ classify("mcp__jira__createJiraIssue", Meta(False, category="connector"))
+ is RiskClass.EXTERNAL
+ )
+
+
+def test_the_reverse_name_collision_is_closed():
+ # A CUSTOM server that reuses a catalog read name (server nicknamed "jira") keeps
+ # category "mcp" and lands on the floor — it does not inherit the catalog's
+ # first-party read verdict.
+ assert classify("mcp__jira__getJiraIssue", Meta(False)) is RiskClass.EXTERNAL
+
+
+def test_the_name_coincidence_no_longer_matters():
+ # Pre-floor, mcp__atlassian__createJiraIssue (unknown to the catalog) dropped to
+ # READ on flag false while its mcp__jira__ twin survived via catalog string luck.
+ assert classify("mcp__atlassian__createJiraIssue", Meta(False)) is RiskClass.EXTERNAL
+
+
+# -- the override loader refuses what classify would silently ignore ---------------
+def test_explicit_mcp_loosening_rules_are_rejected_at_load(tmp_path):
+ from coworker.overrides import RiskOverrideStore
+
+ path = tmp_path / "risk_overrides.json"
+ path.write_text(
+ json.dumps(
+ {
+ "rules": [
+ {"pattern": "mcp__notion__*", "risk": "read"}, # refused
+ {"pattern": "mcp__srv__tool", "risk": "exec"}, # tighten: fine
+ {"pattern": "plugin_*", "risk": "read"}, # non-MCP: fine
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+ store = RiskOverrideStore(path)
+ assert store.resolve("mcp__notion__get_page") is None
+ assert store.resolve("mcp__srv__tool") is RiskClass.EXEC
+ assert store.resolve("plugin_notes") is RiskClass.READ
+ assert len(store.rejected) == 1
+ pattern, reason = store.rejected[0]
+ assert pattern == "mcp__notion__*"
+ assert "trust rule" in reason # points at the sanctioned alternative
+
+
+# -- the mode matrix: what the flag now means at the gate --------------------------
+# requires_approval:false = legacy TRUST: waives the card in Ask-for-approval, and
+# NOTHING else. One test per cell of the behavior table.
+def engine(mode: Mode, tmp_path) -> PermissionEngine:
+ return PermissionEngine(workspace_root=tmp_path, mode=mode)
+
+
+def test_matrix_discuss_denies_trusted_mcp(tmp_path):
+ d = engine(Mode.DISCUSS, tmp_path).evaluate("mcp__jira__createIssue", {}, Meta(False))
+ assert not d.allowed and not d.needs_user # denied outright, no card offered
+
+
+def test_matrix_plan_denies_trusted_mcp(tmp_path):
+ d = engine(Mode.PLAN, tmp_path).evaluate("mcp__jira__createIssue", {}, Meta(False))
+ assert not d.allowed
+
+
+def test_matrix_ask_mode_waives_the_card_for_trusted_mcp(tmp_path):
+ d = engine(Mode.INTERACTIVE, tmp_path).evaluate(
+ "mcp__jira__createIssue", {}, Meta(False)
+ )
+ assert d.allowed
+ assert d.reason == "trusted MCP tool (server marked don't-ask)"
+
+
+def test_matrix_ask_mode_still_asks_on_the_default_flag(tmp_path):
+ d = engine(Mode.INTERACTIVE, tmp_path).evaluate(
+ "mcp__jira__createIssue", {}, Meta(True)
+ )
+ assert not d.allowed and d.needs_user and not d.human_only # reviewer-eligible ask
+
+
+def test_matrix_auto_approve_routes_trusted_mcp_to_the_reviewer(tmp_path):
+ # v1 keeps §1.5 conservative: server-config trust does not skip the judge. The
+ # decision falls through to needs_user, which is exactly what the engine hands to
+ # the reviewer (and never human_only — the reviewer MAY judge it).
+ d = engine(Mode.AUTO_APPROVE, tmp_path).evaluate(
+ "mcp__jira__createIssue", {}, Meta(False)
+ )
+ assert not d.allowed and d.needs_user and not d.human_only
+
+
+def test_matrix_bypass_runs_trusted_and_untrusted_alike(tmp_path):
+ e = engine(Mode.BYPASS_APPROVALS, tmp_path)
+ assert e.evaluate("mcp__jira__createIssue", {}, Meta(False)).allowed
+ assert e.evaluate("mcp__jira__createIssue", {}, Meta(True)).allowed
+
+
+# -- the gate-order invariant ------------------------------------------------------
+# Everything ABOVE the bypass branch in evaluate() survives Bypass mode; read-only
+# modes deny before the human-only floors get a say. Line order IS the floor
+# hierarchy — this pins it.
+def test_gate_order_persistent_authority_survives_bypass(tmp_path):
+ d = engine(Mode.BYPASS_APPROVALS, tmp_path).evaluate("save_skill", {"name": "x"}, None)
+ assert not d.allowed and d.needs_user and d.human_only
+
+
+def test_gate_order_write_fence_survives_bypass(tmp_path):
+ d = engine(Mode.BYPASS_APPROVALS, tmp_path).evaluate(
+ "write_file", {"path": "C:/outside/anywhere.txt", "content": "x"}, None
+ )
+ assert not d.allowed # refused, not asked — the fence has no mode switch
+
+
+def test_gate_order_read_only_mode_beats_the_human_only_floor(tmp_path):
+ # In Discuss there is nothing to grant, so no card — the read-only denial fires
+ # before the persistent-authority branch ("Read-only modes still hard-deny above
+ # this", permissions.py).
+ d = engine(Mode.DISCUSS, tmp_path).evaluate("save_skill", {"name": "x"}, None)
+ assert not d.allowed and not d.needs_user
diff --git a/tests/test_mcp_tool_selection.py b/tests/test_mcp_tool_selection.py
new file mode 100644
index 00000000..cff7f03b
--- /dev/null
+++ b/tests/test_mcp_tool_selection.py
@@ -0,0 +1,87 @@
+"""OPE-136 §3 — the existence lever: `include_tools` decides which of a server's tools
+are REGISTERED at all. An unchecked tool is not blocked — it is absent: the model never
+sees its name or schema, so there is nothing to invoke, trick, or approve. And because
+include_tools is an include-list, tools a server ships later are excluded until the
+user opts them in (fail-closed growth).
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+from coworker.mcp.config import MCPServerDef
+from coworker.mcp.tools import build_callables
+from coworker.tools.registry import ToolRegistry
+
+
+def _tool(name: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ name=name,
+ description=f"vendor description of {name}",
+ inputSchema={"type": "object", "properties": {}},
+ )
+
+
+def _build(server: MCPServerDef, tool_names: list[str]):
+ loop = asyncio.new_event_loop()
+ try:
+ return build_callables(
+ server, [_tool(n) for n in tool_names], lambda t, a: None, loop
+ )
+ finally:
+ loop.close()
+
+
+OFFERED = ["getIssue", "createIssue", "deleteIssue"]
+
+
+def test_unchecked_tools_are_absent_from_the_registry():
+ server = MCPServerDef(
+ name="jirax",
+ transport="http",
+ url="https://mcp.example.com/v1/mcp",
+ include_tools=["getIssue", "createIssue"], # deleteIssue unchecked
+ )
+ registry = ToolRegistry()
+ registry.register_all(_build(server, OFFERED))
+ assert registry.names() == ["mcp__jirax__getIssue", "mcp__jirax__createIssue"]
+ # Absent means absent: no schema for the model, nothing to execute.
+ assert registry.get("mcp__jirax__deleteIssue") is None
+
+
+def test_no_include_list_means_everything_registers():
+ server = MCPServerDef(
+ name="jirax", transport="http", url="https://mcp.example.com/v1/mcp"
+ )
+ assert len(_build(server, OFFERED)) == 3
+
+
+def test_fail_closed_growth_a_new_server_tool_stays_out():
+ # The user reviewed and saved [getIssue, createIssue]; a later handshake ships a
+ # brand-new adminPurge. It must not register until the user opts in.
+ server = MCPServerDef(
+ name="jirax",
+ transport="http",
+ url="https://mcp.example.com/v1/mcp",
+ include_tools=["getIssue", "createIssue"],
+ )
+ grown = OFFERED + ["adminPurge"]
+ names = [fn.__name__ for fn in _build(server, grown)]
+ assert "mcp__jirax__adminPurge" not in names
+ assert names == ["mcp__jirax__getIssue", "mcp__jirax__createIssue"]
+
+
+def test_destination_stamp_travels_with_every_callable():
+ # OPE-136 finding 4 plumbing: the card's scope chip reads this — from the user's
+ # own server config, never the server's claims.
+ http_server = MCPServerDef(
+ name="jirax", transport="http", url="https://MCP.Example.com/v1/mcp"
+ )
+ (fn, *_) = _build(http_server, ["getIssue"])
+ assert fn.__coworker_mcp_destination__ == {
+ "transport": "http",
+ "host": "mcp.example.com", # lowercased
+ }
+ stdio_server = MCPServerDef(name="localfs", transport="stdio", command="npx")
+ (fn2,) = _build(stdio_server, ["read"])
+ assert fn2.__coworker_mcp_destination__ == {"transport": "stdio", "host": ""}
diff --git a/tests/test_mcp_trust.py b/tests/test_mcp_trust.py
new file mode 100644
index 00000000..983c12a4
--- /dev/null
+++ b/tests/test_mcp_trust.py
@@ -0,0 +1,199 @@
+"""OPE-136 §4 — durable per-tool MCP trust: a rule in the user-local override store
+waives the approval card (and ONLY the card), survives sessions, and is revocable.
+
+The mode matrix here is the executable twin of test_mcp_floor's legacy-flag matrix:
+identical in every cell except who granted the trust.
+"""
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+from coworker.overrides import RiskOverrideStore
+from coworker.permissions import Mode, PermissionEngine
+
+MCP_META = SimpleNamespace(requires_approval=True, category="mcp")
+TOOL = "mcp__atlassian__getJiraIssue"
+
+
+def engine(mode: Mode, tmp_path, store: RiskOverrideStore) -> PermissionEngine:
+ return PermissionEngine(
+ workspace_root=tmp_path,
+ mode=mode,
+ trust_overrides=store.trusted,
+ grant_trust=store.set_trust,
+ )
+
+
+# -- the store: parse, match, persist, revoke -------------------------------------
+def test_trust_rules_parse_persist_and_revoke(tmp_path):
+ path = tmp_path / "ro.json"
+ store = RiskOverrideStore(path)
+ store.set_trust(TOOL)
+ store.set_trust(TOOL) # dedupe
+ assert store.trusted(TOOL)
+ assert not store.trusted("mcp__atlassian__deleteIssue")
+
+ reloaded = RiskOverrideStore(path) # survives a reload — it's a file, not RAM
+ assert reloaded.trusted(TOOL)
+ assert reloaded.trust_patterns() == [TOOL]
+
+ reloaded.revoke_trust(TOOL)
+ assert not reloaded.trusted(TOOL)
+ assert not RiskOverrideStore(path).trusted(TOOL) # the revoke persisted too
+
+
+def test_trust_accepts_hand_written_globs_and_bare_strings(tmp_path):
+ # The card writes exact names; hand-editing may use globs or bare strings.
+ path = tmp_path / "ro.json"
+ path.write_text(
+ json.dumps({"trust": ["mcp__notes__*", {"pattern": TOOL}]}), encoding="utf-8"
+ )
+ store = RiskOverrideStore(path)
+ assert store.trusted("mcp__notes__anything")
+ assert store.trusted(TOOL)
+ assert not store.trusted("mcp__other__x")
+
+
+def test_trust_rules_never_touch_classification(tmp_path):
+ # Trust waives the card; the CLASS is welded on (the OPE-136 floor).
+ from coworker.risk import RiskClass, classify
+
+ store = RiskOverrideStore(tmp_path / "ro.json")
+ store.set_trust(TOOL)
+ assert classify(TOOL, MCP_META, store.resolver()) is RiskClass.EXTERNAL
+
+
+# -- test-plan #15: durable trust survives an engine rebuild ----------------------
+def test_durable_trust_survives_an_engine_rebuild(tmp_path):
+ path = tmp_path / "ro.json"
+ store_a = RiskOverrideStore(path)
+ eng_a = engine(Mode.INTERACTIVE, tmp_path, store_a)
+ assert not eng_a.evaluate(TOOL, {}, MCP_META).allowed # asks before any grant
+
+ # The card's "Always allow this tool" lands through the engine's grant hook.
+ eng_a.grant_trust_for_tool(TOOL)
+ assert eng_a.evaluate(TOOL, {}, MCP_META).allowed # this session, immediately
+
+ # A brand-new session: new store instance, new engine — same file.
+ eng_b = engine(Mode.INTERACTIVE, tmp_path, RiskOverrideStore(path))
+ d = eng_b.evaluate(TOOL, {}, MCP_META)
+ assert d.allowed and d.reason == "trusted MCP tool (user trust rule)"
+
+
+# -- test-plan #16: the mode matrix for a rule-trusted tool -----------------------
+def trusted_store(tmp_path) -> RiskOverrideStore:
+ store = RiskOverrideStore(tmp_path / "ro.json")
+ store.set_trust(TOOL)
+ return store
+
+
+def test_matrix_ask_mode_waives_the_card(tmp_path):
+ d = engine(Mode.INTERACTIVE, tmp_path, trusted_store(tmp_path)).evaluate(
+ TOOL, {}, MCP_META
+ )
+ assert d.allowed and d.reason == "trusted MCP tool (user trust rule)"
+
+
+def test_matrix_discuss_still_denies(tmp_path):
+ d = engine(Mode.DISCUSS, tmp_path, trusted_store(tmp_path)).evaluate(
+ TOOL, {}, MCP_META
+ )
+ assert not d.allowed and not d.needs_user
+
+
+def test_matrix_auto_approve_still_routes_to_the_reviewer(tmp_path):
+ # §1.5 v1: user trust does not skip the judge — the decision falls through to
+ # needs_user (reviewer-eligible, never human_only).
+ d = engine(Mode.AUTO_APPROVE, tmp_path, trusted_store(tmp_path)).evaluate(
+ TOOL, {}, MCP_META
+ )
+ assert not d.allowed and d.needs_user and not d.human_only
+
+
+def test_matrix_bypass_unchanged(tmp_path):
+ assert engine(Mode.BYPASS_APPROVALS, tmp_path, trusted_store(tmp_path)).evaluate(
+ TOOL, {}, MCP_META
+ ).allowed
+
+
+# -- test-plan #17 (server side): the grant is offered only where the card shows it
+def test_always_trust_grant_is_mcp_only():
+ from coworker.engine import ApprovalOutcome
+ from coworker.server.manager import _grant_offered
+
+ def req(name: str, category: str):
+ return SimpleNamespace(
+ tool_name=name,
+ metadata=SimpleNamespace(requires_approval=True, category=category),
+ arguments={},
+ )
+
+ offered = ApprovalOutcome.ALWAYS_TRUST
+ assert _grant_offered(offered, req("mcp__srv__tool", "mcp"))
+ # A raw API caller must not mint durable trust for a connector or a built-in —
+ # the server validates, exactly like the other grants.
+ assert not _grant_offered(offered, req("email_send", "connector"))
+ assert not _grant_offered(offered, req("run_shell", ""))
+
+
+def test_remove_server_revokes_its_trust_rules(tmp_path, monkeypatch):
+ """Owner-hit 2026-08-30: Remove wiped config, tokens, and connection — but trust
+ rules live in risk_overrides.json and survived, so a future server added under
+ the SAME NAME inherited don't-ask rules sight unseen. GONE means gone: delete
+ revokes every rule under the server's prefix; broader globs and other servers'
+ rules stay; sign-out (tokens only) deliberately does not do this."""
+ from types import SimpleNamespace
+
+ from coworker.server import manager as manager_mod
+ from coworker.server.manager import SessionManager
+
+ store = RiskOverrideStore(tmp_path / "ro.json")
+ store.set_trust("mcp__atlassian__searchJiraIssuesUsingJql")
+ store.set_trust("mcp__atlassian__*") # a hand-written glob scoped to this server
+ store.set_trust("mcp__other__keepMe") # a different server's rule
+ store.set_trust("mcp__*") # a broader glob — NOT this server's rule
+
+ monkeypatch.setattr(manager_mod, "delete_global_server", lambda _n: True)
+ import coworker.mcp.oauth as mcp_oauth
+
+ monkeypatch.setattr(mcp_oauth, "sign_out", lambda _n, _s: None)
+
+ fake = SimpleNamespace(
+ _mcp_errors={},
+ _mcp_auth_hints=set(),
+ _prefs={},
+ _save_prefs=lambda: None,
+ _clear_mcp_notified=lambda _n: None,
+ mcp=SimpleNamespace(_conns={}),
+ _loop=None,
+ secrets=None,
+ _override_store=lambda: RiskOverrideStore(tmp_path / "ro.json"),
+ )
+ result = SessionManager.delete_mcp(fake, "atlassian")
+ assert result["ok"]
+
+ survivors = RiskOverrideStore(tmp_path / "ro.json").trust_patterns()
+ assert survivors == ["mcp__other__keepMe", "mcp__*"]
+
+
+def test_engine_fallback_without_a_store_degrades_to_session_scope(tmp_path):
+ # Ephemeral engines (tests, embedded uses) have no store wired: the grant falls
+ # back to the session set rather than silently doing nothing.
+ eng = PermissionEngine(workspace_root=tmp_path, mode=Mode.INTERACTIVE)
+ eng.grant_trust_for_tool(TOOL)
+ assert TOOL in eng.session_allow_tools
+
+
+# -- test-plan #18 (config side): the legacy flag's migration primitive -----------
+def test_patch_global_server_none_deletes_the_key(tmp_path, monkeypatch):
+ from coworker.mcp import config as mcp_config
+
+ monkeypatch.setattr(mcp_config, "global_mcp_path", lambda: tmp_path / "mcp.json")
+ mcp_config.put_global_server(
+ "jira", {"url": "https://x/mcp", "requires_approval": False}
+ )
+ assert mcp_config.read_global()["jira"]["requires_approval"] is False
+ mcp_config.patch_global_server("jira", {"requires_approval": None})
+ assert "requires_approval" not in mcp_config.read_global()["jira"]
+ assert mcp_config.read_global()["jira"]["url"] == "https://x/mcp" # rest intact
diff --git a/tests/test_risk_overrides.py b/tests/test_risk_overrides.py
index a06066b2..da5606e9 100644
--- a/tests/test_risk_overrides.py
+++ b/tests/test_risk_overrides.py
@@ -1,49 +1,72 @@
-"""Phase 2 gate — user-local risk overrides (relax/tighten), with the no-self-grant rule."""
+"""Phase 2 gate — user-local risk overrides (relax/tighten), with the no-self-grant rule.
+
+Updated for OPE-136: the store used to be the sanctioned way to relax an MCP tool to
+READ. That path is retired — MCP tools are floored at EXTERNAL (`risk.classify`), and
+"stop asking" is a trust rule, never a reclassification. Relaxing survives for non-MCP
+third-party tools (plugins); tightening survives for everything.
+"""
from __future__ import annotations
from types import SimpleNamespace
+import pytest
+
from coworker.overrides import RiskOverrideStore
from coworker.permissions import Mode, PermissionEngine
from coworker.risk import RiskClass, classify
MCP_META = SimpleNamespace(requires_approval=True, category="mcp")
+PLUGIN_META = SimpleNamespace(requires_approval=True, category="plugin")
def test_most_specific_rule_wins(tmp_path):
store = RiskOverrideStore(tmp_path / "ro.json")
- store.set_rule("mcp__notion__*", "read") # server default: relax
- store.set_rule("mcp__notion__create_*", "external") # but writes stay external
- assert store.resolve("mcp__notion__get_page") == RiskClass.READ
- assert store.resolve("mcp__notion__create_page") == RiskClass.EXTERNAL
- assert store.resolve("mcp__github__push") is None # no rule → defer to base
+ store.set_rule("plugin_notes_*", "read") # plugin default: relax
+ store.set_rule("plugin_notes_create_*", "external") # but writes stay external
+ assert store.resolve("plugin_notes_get_page") == RiskClass.READ
+ assert store.resolve("plugin_notes_create_page") == RiskClass.EXTERNAL
+ assert store.resolve("plugin_other_push") is None # no rule → defer to base
-def test_override_relaxes_mcp_in_classify(tmp_path):
+def test_override_relaxes_a_plugin_tool_in_classify(tmp_path):
store = RiskOverrideStore(tmp_path / "ro.json")
- store.set_rule("mcp__notion__*", "read")
+ store.set_rule("plugin_notes_*", "read")
resolver = store.resolver()
- # Without override an MCP tool is external; with it, read.
- assert classify("mcp__notion__get_page", MCP_META) == RiskClass.EXTERNAL
- assert classify("mcp__notion__get_page", MCP_META, resolver) == RiskClass.READ
+ # Without override a requires-approval plugin tool is external; with it, read.
+ assert classify("plugin_notes_get_page", PLUGIN_META) == RiskClass.EXTERNAL
+ assert classify("plugin_notes_get_page", PLUGIN_META, resolver) == RiskClass.READ
+
+
+def test_mcp_loosening_rules_are_refused_at_write_time(tmp_path):
+ # OPE-136: writing a rule the next load would silently drop is a trap — refuse it
+ # up front, pointing at the sanctioned alternative.
+ store = RiskOverrideStore(tmp_path / "ro.json")
+ with pytest.raises(ValueError, match="trust rule"):
+ store.set_rule("mcp__notion__*", "read")
+ assert store.resolve("mcp__notion__get_page") is None # nothing landed
+
+
+def test_mcp_tightening_rules_still_land(tmp_path):
+ store = RiskOverrideStore(tmp_path / "ro.json")
+ store.set_rule("mcp__x__run", "exec")
+ assert store.resolve("mcp__x__run") == RiskClass.EXEC
-def test_engine_auto_allows_relaxed_mcp_tool(tmp_path):
+def test_engine_gates_mcp_tools_regardless_of_old_style_relax_rules(tmp_path):
+ # A generic glob that happens to match mcp__ names loads fine — and does nothing:
+ # the classify floor neutralizes the loosening, so the engine still asks.
store = RiskOverrideStore(tmp_path / "ro.json")
- store.set_rule("mcp__notion__get_*", "read")
+ store.set_rule("*notion*", "read")
eng = PermissionEngine(workspace_root=tmp_path, risk_overrides=store.resolver())
d = eng.evaluate("mcp__notion__get_page", {}, MCP_META)
- assert d.allowed and not d.needs_user # relaxed to read → runs without asking
- # A non-relaxed MCP tool still gates.
- other = eng.evaluate("mcp__notion__delete_page", {}, MCP_META)
- assert not other.allowed and other.needs_user
+ assert not d.allowed and d.needs_user
def test_overrides_persist(tmp_path):
- RiskOverrideStore(tmp_path / "ro.json").set_rule("mcp__x__*", "read")
+ RiskOverrideStore(tmp_path / "ro.json").set_rule("plugin_x_*", "read")
reloaded = RiskOverrideStore(tmp_path / "ro.json")
- assert reloaded.resolve("mcp__x__y") == RiskClass.READ
+ assert reloaded.resolve("plugin_x_y") == RiskClass.READ
def test_can_tighten_as_well(tmp_path):
diff --git a/tests/test_run_grant.py b/tests/test_run_grant.py
new file mode 100644
index 00000000..79fb9b13
--- /dev/null
+++ b/tests/test_run_grant.py
@@ -0,0 +1,202 @@
+"""OPE-136 "Allow for this request" — the run grant: covers the exact tool for the
+remainder of the current run, in memory only, cleared at the run boundary.
+
+The design ladder it slots into: once → THIS RUN → (mode switch) → always.
+It exists because the EXTERNAL ladder was once-or-forever, and approval fatigue
+drained into permanent trust rules (observed in owner testing 2026-08-30).
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from coworker.permissions import Mode, PermissionEngine
+
+MCP_META = SimpleNamespace(requires_approval=True, category="mcp")
+CONNECTOR_META = SimpleNamespace(requires_approval=True, category="connector")
+MCP_TOOL = "mcp__atlassian__searchJiraIssuesUsingJql"
+
+
+def engine(mode: Mode, tmp_path) -> PermissionEngine:
+ return PermissionEngine(workspace_root=tmp_path, mode=mode)
+
+
+# -- the grant covers the tool, and only until cleared ----------------------------
+def test_run_grant_allows_then_dies_at_the_boundary(tmp_path):
+ eng = engine(Mode.INTERACTIVE, tmp_path)
+ assert not eng.evaluate(MCP_TOOL, {}, MCP_META).allowed # asks before the grant
+
+ eng.allow_tool_for_run(MCP_TOOL)
+ d = eng.evaluate(MCP_TOOL, {}, MCP_META)
+ assert d.allowed and d.reason == "tool allowed for this request"
+
+ # The run boundary IS the expiry: after clearing, the same call asks again.
+ eng.clear_run_allowances()
+ assert not eng.evaluate(MCP_TOOL, {}, MCP_META).allowed
+
+
+def test_run_grant_covers_connectors_unlike_the_session_grant(tmp_path):
+ # The session grant excludes connectors; the run grant exists FOR the EXTERNAL
+ # family — connector loops ("email these five people") are its main scenario.
+ eng = engine(Mode.INTERACTIVE, tmp_path)
+ eng.allow_tool_for_session("gmail_send_email")
+ assert not eng.evaluate("gmail_send_email", {}, CONNECTOR_META).allowed
+
+ eng.allow_tool_for_run("gmail_send_email")
+ d = eng.evaluate("gmail_send_email", {}, CONNECTOR_META)
+ assert d.allowed and d.reason == "tool allowed for this request"
+
+
+def test_run_grant_never_skips_the_auto_approve_judge(tmp_path):
+ # §1.5: an in-flow click may not skip the reviewer — same law as session grants.
+ eng = engine(Mode.AUTO_APPROVE, tmp_path)
+ eng.allow_tool_for_run(MCP_TOOL)
+ d = eng.evaluate(MCP_TOOL, {}, MCP_META)
+ assert not d.allowed and d.needs_user and not d.human_only
+
+
+def test_run_grant_cannot_override_a_read_only_mode(tmp_path):
+ # Grants only ever turn an "ask" into an "allow" — Discuss's fence stands.
+ eng = engine(Mode.DISCUSS, tmp_path)
+ eng.allow_tool_for_run(MCP_TOOL)
+ d = eng.evaluate(MCP_TOOL, {}, MCP_META)
+ assert not d.allowed and not d.needs_user
+
+
+# -- server side: offered ONLY for the EXTERNAL family ----------------------------
+def test_this_run_grant_is_external_only():
+ from coworker.engine import ApprovalOutcome
+ from coworker.server.manager import _grant_offered
+
+ def req(name: str, category: str = "", approval: bool = False, args: dict | None = None):
+ return SimpleNamespace(
+ tool_name=name,
+ metadata=SimpleNamespace(requires_approval=approval, category=category)
+ if category or approval
+ else None,
+ arguments=args or {},
+ )
+
+ offered = ApprovalOutcome.THIS_RUN
+ assert _grant_offered(offered, req("mcp__srv__tool", "mcp", approval=True))
+ assert _grant_offered(offered, req("gmail_send_email", "connector", approval=True))
+ # Core messaging classifies EXTERNAL via its metadata, as wired in production.
+ assert _grant_offered(offered, req("send_message", approval=True))
+ # EXEC: tool-wide shell is a blank check at any duration.
+ assert not _grant_offered(offered, req("run_shell"))
+ # EGRESS: the domain-scoped grant is the honest instrument there.
+ assert not _grant_offered(offered, req("web_fetch", args={"url": "https://x.y"}))
+ # Local writes have the session grant; the run rung isn't theirs.
+ assert not _grant_offered(offered, req("write_file"))
+
+
+def test_approval_outcome_downgrades_unoffered_grants_to_once():
+ # POST /v1/inbox/{id}/resolve takes a raw string — the server validates every
+ # grant vocabulary, including this_run and (gap closed) always_trust.
+ from coworker.engine import ApprovalOutcome
+ from coworker.server.manager import SessionManager
+
+ refused: list[str] = []
+ fake = SimpleNamespace(
+ _audit_grant_refused=lambda _s, _r, res: refused.append(res),
+ mint_task_rule=lambda *_a, **_k: False,
+ )
+ shell_req = SimpleNamespace(tool_name="run_shell", metadata=None, arguments={})
+ out = SessionManager.approval_outcome(fake, "this_run", shell_req, "s1")
+ assert out is ApprovalOutcome.ONCE and refused == ["this_run"]
+
+ trust_req = SimpleNamespace(tool_name="write_file", metadata=None, arguments={})
+ out = SessionManager.approval_outcome(fake, "always_trust", trust_req, "s1")
+ assert out is ApprovalOutcome.ONCE and refused[-1] == "always_trust"
+
+ mcp_req = SimpleNamespace(
+ tool_name="mcp__srv__tool",
+ metadata=SimpleNamespace(requires_approval=True, category="mcp"),
+ arguments={},
+ )
+ assert (
+ SessionManager.approval_outcome(fake, "this_run", mcp_req, "s1")
+ is ApprovalOutcome.THIS_RUN
+ )
+
+
+# -- end to end: one card per run, covered calls chip-annotated, boundary honored --
+def test_engine_end_to_end_one_card_per_run(tmp_path):
+ """The whole promise in one flow: THIS_RUN from the card covers the SAME tool's
+ later calls in the same run (no second card), stamps the covered call with the
+ run_grant origin for the transcript chip, and the next run() asks again."""
+ import asyncio
+
+ import aisuite as ai
+ from coworker.engine import ApprovalOutcome, TurnEngine
+ from coworker.providers import (
+ AssistantTurn,
+ ModelCapabilities,
+ ProviderClient,
+ ToolCall,
+ )
+ from coworker.tools import ToolRegistry
+
+ class Scripted(ProviderClient):
+ def __init__(self, turns):
+ self._turns = list(turns)
+
+ def complete(self, *, model, messages, tools=None, **settings):
+ return self._turns.pop(0)
+
+ def capabilities(self, model):
+ return ModelCapabilities()
+
+ def tool_turn(call_id: str) -> AssistantTurn:
+ return AssistantTurn(
+ tool_calls=[
+ ToolCall(id=call_id, name="mcp__srv__search", arguments={"q": "x"})
+ ],
+ finish_reason="tool_calls",
+ )
+
+ def done(text: str) -> AssistantTurn:
+ return AssistantTurn(text=text, finish_reason="stop")
+
+ asks: list[str] = []
+
+ async def approver(req):
+ asks.append(req.tool_name)
+ return ApprovalOutcome.THIS_RUN
+
+ def mcp__srv__search(q: str = ""):
+ """Fake MCP search."""
+ return {"ok": True}
+
+ registry = ToolRegistry()
+ registry.register(
+ mcp__srv__search,
+ metadata=ai.ToolMetadata(category="mcp", requires_approval=True),
+ )
+ engine = TurnEngine(
+ provider=Scripted(
+ # Run 1: the tool twice, then done. Run 2: the tool once more, then done.
+ [tool_turn("c1"), tool_turn("c2"), done("done"), tool_turn("c3"), done("ok")]
+ ),
+ registry=registry,
+ permissions=PermissionEngine(workspace_root=tmp_path),
+ model="gpt-5.5",
+ approver=approver,
+ )
+
+ async def scenario():
+ events_one = [ev async for ev in engine.run("find things")]
+ # ONE card for two calls: c1 asked, c2 rode the grant.
+ assert asks == ["mcp__srv__search"]
+ # The covered call is chip-annotated — silent to attention, never invisible.
+ origins = [
+ m.get("_display", {}).get("approval_origin")
+ for m in engine.messages
+ if m.get("role") == "tool"
+ ]
+ assert "run_grant" in origins
+ events_two = [ev async for ev in engine.run("find more")]
+ # The run boundary held: the very same tool asks again in the next run.
+ assert asks == ["mcp__srv__search", "mcp__srv__search"]
+ return events_one, events_two
+
+ asyncio.run(scenario())
diff --git a/tests/test_skills_api.py b/tests/test_skills_api.py
index 879ae5e3..810db739 100644
--- a/tests/test_skills_api.py
+++ b/tests/test_skills_api.py
@@ -207,24 +207,6 @@ def test_upload_preview_then_confirm(tmp_path):
assert row["source"] == "uploaded"
-def test_upload_confirm_rejects_forged_absolute_token(tmp_path):
- client, _m, _p = _client(tmp_path)
- outside = tmp_path / "outside-staging"
- outside.mkdir()
- (outside / "SKILL.md").write_text(
- "---\nname: forged\ndescription: d\n---\nbody\n", encoding="utf-8"
- )
- marker = outside / "keep.txt"
- marker.write_text("must survive", encoding="utf-8")
-
- result = client.post(
- "/v1/skills/upload/confirm", json={"token": str(outside.resolve())}
- ).json()
-
- assert result["ok"] is False and "expired" in result["error"].lower()
- assert marker.read_text(encoding="utf-8") == "must survive"
-
-
def test_upload_invalid_archive_friendly(tmp_path):
client, _m, _p = _client(tmp_path)
bad = client.post(
diff --git a/tests/test_skills_store.py b/tests/test_skills_store.py
index 89d8fb8c..ff36028e 100644
--- a/tests/test_skills_store.py
+++ b/tests/test_skills_store.py
@@ -291,44 +291,6 @@ def test_upload_confirm_saves_previewed_content(store):
store.confirm_upload(preview["token"]) # token is one-shot
[email protected]("action", ["confirm", "discard"])
-def test_upload_token_cannot_escape_staging_dir(store, tmp_path, action):
- outside = tmp_path / f"outside-{action}"
- outside.mkdir()
- (outside / "SKILL.md").write_text(SKILL_MD, encoding="utf-8")
- marker = outside / "keep.txt"
- marker.write_text("must survive", encoding="utf-8")
- token = os.path.relpath(outside, store._staging_dir)
-
- with pytest.raises(ValueError, match="expired"):
- if action == "confirm":
- store.confirm_upload(token)
- else:
- store.discard_upload(token)
-
- assert marker.read_text(encoding="utf-8") == "must survive"
-
-
-def test_upload_token_symlink_cannot_escape_staging_dir(store, tmp_path):
- outside = tmp_path / "outside-symlink"
- outside.mkdir()
- (outside / "SKILL.md").write_text(SKILL_MD, encoding="utf-8")
- marker = outside / "keep.txt"
- marker.write_text("must survive", encoding="utf-8")
- token = "a" * 32 # valid token shape; containment must still be enforced
- store._staging_dir.mkdir(parents=True, exist_ok=True)
- try:
- os.symlink(outside, store._staging_dir / token, target_is_directory=True)
- except (OSError, NotImplementedError):
- pytest.skip("symlinks unavailable on this platform/user")
-
- with pytest.raises(ValueError, match="expired"):
- store.confirm_upload(token)
- with pytest.raises(ValueError, match="expired"):
- store.discard_upload(token)
- assert marker.read_text(encoding="utf-8") == "must survive"
-
-
# -- disable state -------------------------------------------------------------------