# MCP server

## Tools

| Tool | Purpose | Capability | Host side effects |
| --- | --- | --- | --- |
| `sessions_list` | List session ids, titles, update times | `reply` | None |
| `session_get` | Read the active branch of one session | `reply` | None |
| `prompt_send` | Send a prompt to an existing or new session and return the result; combines codex's `codex` and `codex-reply` | `reply` | Session append only |
| `prompt_cancel` | Cancel an active prompt this connection started | `reply` | None |
| `tools_list` | List Runtime tools exposed to this client, with schemas | `reply` | None |
| `tool_call` | Call one exposed Runtime tool by name | Depends on the tool | Passes the three gates below |

Not offered: tool registration, configuration rewriting, credential access, direct file tools. File reads go through `tool_call`. Peers: codex two tools, openclaw nine, hermes ten; exposing every tool is excluded.

## Three gates on every `tool_call`

1. **Allowlist** `mcp_server.exposed_tools`, empty by default
   
   JSON-RPC error, as unknown tool
2. **Tier** paired capabilities, never interactive
   
   isError, names the missing capability
3. **Approval** mode fixed to ask, no one to approve
   
   isError, fixed reason, no waiting
4. **Runs** typed, sanitized result

Discovery and execution each compute allowlist ∩ live registry ∩ paired capability. Identity limits come first: for `source=mcp`, risky tools, process and worktree tools, and out-of-root writes are always denied, and no question waits for an answer.

### Request sources

| Request source | Principal | `authority_tier` | Missing field |
| --- | --- | --- | --- |
| Authenticated local Web, CLI, TUI | `principal_id=owner`, interactive | `owner`, holds `approval.request` | Entry point must build it; invalid authentication is rejected |
| Paired channel account | Instance owner; speaker stored separately | `paired` | Message without a tier is rejected, not downgraded |
| External MCP client | Instance owner; client id stored separately, `speaker_kind=client`, non-interactive | `paired` ∩ allowlist | Connection rejected |
| Continuation, subagent | Explicitly inherits owner | Caller's tier, never higher | State error: deny |
| Cron trigger | Owner approved at creation | Job capability fixed at approval | Not recomputed as interactive |

Tiers come from `TIER_CAPABILITIES`; missing or unknown tiers deny everything. Paired holds `reply`, `memory.read`, `memory.source.append`, `runtime.wait`. Full table: [sandbox design](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/security/sandbox-architecture.html).

## Authentication and transport

| Aspect | Rule |
| --- | --- |
| Token | `openprogram mcp token create` atomically writes `<state_dir>/mcp_server_token` (0600) and prints it once. `serve` never generates one |
| Validation | `openprogram mcp serve` compares `OPENPROGRAM_MCP_TOKEN` with the file in constant time before reading any message. No disable switch |
| Failure | Nonzero exit, empty stdout, stderr fixed to `Error: MCP server authentication failed` |
| Secrecy | The token never enters JSON-RPC, logs, errors or session content |
| Client identity | First 16 lowercase hex characters of the credential's SHA-256. `initialize.clientInfo` is neither read nor recorded |
| Authority | Fixed `paired`, never owner, and independent of the Web owner token |
| Transport | stdio only. It inherits the trust boundary of the launching process |
| Protocol | Locked `mcp` 1.30.0, protocol `2025-11-25`; the SDK negotiates versions with no custom handshake fields |
| Streamable HTTP | Later and separate: needs OAuth, Origin validation and a deployment lifecycle |

## Cancellation, progress, errors

| Protocol message | Maps to |
| --- | --- |
| `notifications/cancelled` | Look up session and token by MCP request id; set the per-turn `CancelToken` and the tool's `cancel` event; stop effects; clear requests and questions; audit `mcp.request.cancelled` |
| `notifications/progress` | The tool's `on_update`, only when the client sent `progressToken`. Tool start and finish, monotonic per request; no token-level streaming |

| Condition | Response | Reason |
| --- | --- | --- |
| Unknown tool name | JSON-RPC error, method level | Protocol failure |
| Arguments fail the schema | JSON-RPC error, invalid params | Protocol failure |
| Missing or wrong startup token | Nonzero exit before the MCP lifecycle | Authentication precedes stdin reads |
| Tool not allowlisted | JSON-RPC error, as unknown tool | Reveals nothing about unauthorized tools |
| Tier lacks the capability | `isError: true`, names the capability | Tool exists but is unavailable here |
| Approval denied or unavailable | `isError: true`, fixed gate reason | No owner present; no tool details passed through |
| Tool ran and failed | `isError: true`, fixed sanitized body and reason code | No exceptions, traces or tool-reported reasons cross the boundary |
| SDK cancels an in-flight request | `ErrorData(code=0, message="Request cancelled", data=None)`, no tool result | The SDK owns the response and may send it first; the handler, in a shielded cancel scope, returns only after the turn is stopped, the request cleared and the audit written |
| `prompt_cancel` | Active turn on the same connection: `cancelled=true`; foreign or finished: false | A wrapper, not the SDK notification |

## Internal Web surface

| Surface | Location | Size |
| --- | --- | --- |
| FastAPI routes | `create_app()` in `openprogram/interfaces/server/server.py`, routes in `routes/` | About 335 routes |
| WebSocket `/ws` | `_websocket_handler`, actions in `ws_actions/` | Unversioned actions and events |
| Tool registry | `_registry` in `openprogram/programs/_host/runtime.py` | By tool name; switches toolset, expose, defer |

`OwnerAuthMiddleware` enforces Host and Origin, cookie or Bearer credentials, CSRF, no-store, and WebSocket authentication before accept, then grants full owner authority. That is neither an MCP client identity nor an external contract, so FastAPI and WebSocket are not MCP transports and clients never receive the Web owner token.

**Permission decision and cancellation internals**

| Part | Rule |
| --- | --- |
| Permission order | `permission_decision`: identity limits, then owner rules (deny, plan's read-only limit, ask, outbound hold, allow), then the mode. Default mode `bypass`; subagents take the parent's mode. See [permission decision](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/security/permission-decision.html) |
| Tool wrapping | `wrap_with_approval` returns a tool copy whose `execute` is gated. External callers cannot bypass it |
| `CancelToken` | Per turn, never per session (`runtime/execution/run_control/tokens.py`). A stop arriving after a turn ends cannot affect the next |
| Global hooks | `add_pre_invocation_hook`, `set_cancellation_check`: each Agent method entry and each `Runtime.exec` aborts |
| Unified entry | Takes only the canonical `execution_id`, persists intent, wakes the owner and pending questions. ACP, MCP, Channels and Web share one Control Service |
| `is_error` | First-class on `AgentToolResult` and `AgentEventToolEnd`; read by Runtime, approval, the agent loop, MCP conversion and cache eligibility. `details` holds diagnostics such as `reason_code`, `denied`, `timeout`. `details["is_error"]` is an input bridge only |

**Framework comparison**

| Framework | MCP server | ACP agent side | Inbound HTTP, webhook | Client SDK |
| --- | --- | --- | --- | --- |
| claude-code | `claude mcp serve` | None | None documented | Agent SDK |
| codex-cli | `codex mcp-server`, stdio, only codex and codex-reply | None; own app-server | app-server: stdio, WS, unix; token file, SHA-256, JWT | TS `@openai/codex-sdk`, Python |
| openclaw | Three stdio servers, MCP-over-HTTP (bearer, loopback) | `openclaw acp`, through Gateway | Gateway HTTP API, HMAC webhook plugin | `@openclaw/sdk` (private) |
| opencode | None, client only | `opencode acp` | `opencode serve`, HTTP Basic; only warns without a password | `@opencode-ai/sdk`, from OpenAPI |
| hermes-agent | `hermes mcp serve`, FastMCP stdio, ten tools | `hermes acp`, ACP registry entries | HMAC webhook adapter, bearer OpenAI-compatible API | None |
| pi-ai | None | None | None | Not applicable: a provider library |
| pi-mono | None; README says "No MCP." | None | None; in-process `pi.send()` | Embedding package only |
| weclaw | None | ACP client only, auto-approves everything | `POST /api/send`, no authentication | None |
| OpenProgram | `openprogram mcp serve`, authenticated stdio, fixed wrappers, empty allowlist | `openprogram acp`, stdio | Internal Web routes, owner authentication | None; standard MCP SDK |

### Protocol approaches

| Topic | Peers |
| --- | --- |
| Push approval | codex: `elicitation/create` for exec and patch, custom fields `threadId`, `codex_elicitation`, `codex_mcp_tool_call_id`, `codex_event_id`, returning `ReviewDecision`. Low latency, needs client elicitation; its payload lacks `ElicitResult` action and content |
| Pull approval | openclaw, hermes: `permissions_list_open` and `permissions_respond`, `allow-once`, `allow-always`, `deny`. Works with generic clients, at a round trip and polling cost. openclaw also pushes through `claude/channel/permission` |
| Cancellation | codex looks up the turn in its active-turn registry, and `tasks/cancel` reports unsupported. openclaw passes `extra.signal` into `callTool`. hermes has none |
| Progress | codex only logs `notifications/progress`. No surveyed framework emits standard progress |
| Errors | All return `{isError: true, content:[text]}` for tool failure and JSON-RPC errors for protocol failure. OpenProgram adopts this |
| Excluded | weclaw's unauthenticated send and unconditional `session/request_permission` approval; opencode's unauthenticated `serve` when `OPENCODE_SERVER_PASSWORD` is unset |

## Out of scope

| Item | State | Why |
| --- | --- | --- |
| ACP stdio server | Exists, not expanded: `openprogram acp`, `openprogram/interfaces/acp/server.py` | Owner authority and interactive permission; MCP tokens, allowlists and tools do not merge into it |
| Inbound webhook | Not built | No owner is present on arrival, so it needs a job capability fixed at registration, as cron does. Minimum controls, from hermes: per-route HMAC secrets validated at startup, rate limits, idempotency cache, body-size checks before reading |
| Client SDK | Not built | The standard MCP SDK is the client library. A dedicated SDK needs real integrations that prove these tools too coarse; only two routes have fixed shape assertions |
| HTTP, SSE, OAuth, Web routes, wider SDK range | Not built | The external surface stays authenticated stdio and these tools |

**Tests**

| File | Covers |
| --- | --- |
| `tests/integration/programs/test_mcp_server.py` | Real `ClientSession` over a real `openprogram mcp serve` subprocess; handwritten frames only supplement raw stdout checks. Token failures before the handshake; `clientInfo` invariance; the fixed tool list; `tools_list` equal to the intersection; unknown and unexposed tools; `isError` rather than hanging; SDK cancellation with no later result, stopped effects, cleared state and audit; progress only with a token and in order; bounded consumer teardown that keeps parent cancellation; concurrency; protocol-only stdout |
| `tests/component/webui/runtime/test_diagnostic_mcp_route_contracts.py` | Exact shapes of `/api/doctor` (`results`, `all_ok`), `/api/mcp/servers` (15 keys) and the 404 for a missing server, on a bare `FastAPI()` with no middleware |
