# MCP server implementation

How `openprogram mcp serve` is built. Behaviour, gates and peer comparison: [MCP server](https://fzkuji.github.io/OpenProgram/docs/reference/design/integrations/extensions/mcp-server.html).

| Module | Owns | Tests |
| --- | --- | --- |
| `extensions/mcp/server/contracts.py` | Wrapper schemas, `validate_tool_call`, `get_mcp_tools` | `tests/unit/programs/mcp/test_mcp_server_contracts.py` |
| `auth.py` | Token file, `authenticate_from_environment` | `tests/component/programs/mcp/test_mcp_server_auth.py`, `test_mcp_server_cli.py` |
| `service.py`, `tools.py` | Sessions, Runtime tool exposure, `tool_call`, prompt lifecycle, content conversion | `tests/unit/programs/mcp/test_mcp_server_tools.py`, `tests/component/programs/mcp/test_mcp_server_turns.py` |
| `server.py` | `build_server`, `serve_stdio`, `serve` | `tests/integration/programs/test_mcp_server.py` |
| `runtime/permissions/authority.py`, `state/settings.py` | `mcp_client_authority`, `mcp_server.exposed_tools` | `tests/unit/programs/mcp/test_mcp_server_security.py` |
| `interfaces/cli/commands/capabilities/mcp.py`, `parser.py`, `application.py` | `mcp serve`, `mcp token create`, local dispatch | `test_mcp_server_cli.py` |

A sibling of the MCP client package and separate from the Web owner control plane. Dependency: `mcp>=1.0.0,<2.0.0`, locked at 1.30.0; protocol baseline 2025-11-25.

## Fixed limits

| Limit | Value |
| --- | --- |
| Transport | stdio only. No HTTP, SSE, Streamable HTTP, OAuth, Web routes, sockets or listeners |
| Identity | Credential-derived. `initialize.clientInfo` is diagnostics only |
| Every request | `source="mcp"`, `permission_mode="ask"`, `authority_tier="paired"`, `interaction="non-interactive"`; none is caller-configurable |
| Authority | `speaker_kind="client"`, `speaker_id=f"mcp/{client_id}"`, `speaker_display="MCP client"`, `principal_id=owner_principal_id()`. A malformed client id is rejected |
| Credential | Never `interfaces.server.owner_auth`, `backend_endpoint`, Web owner tokens, cookies or owner bearer headers |
| Runtime tool exposure | `mcp_server.exposed_tools` (default `[]`) ∩ live registry ∩ paired capability, for discovery and execution alike |
| Questions | Never wait. Approval gates deny at once; other `question.asked` for an active MCP session resolve `declined`. `source="mcp"` counts as unattended; hard constraints come before rules and every bypass |
| ACP server | Unchanged |

## Wrapper tools

MCP `tools/list` returns these wrappers. The wrapper named `tools_list` returns the filtered Runtime tools. Separate contracts, separate assertions.

| Tool | Input | Success payload |
| --- | --- | --- |
| `sessions_list` | none | Up to 100 recent `{id,title,updated_at}`, in session-store order |
| `session_get` | `session_id` | Active-branch `{id,role,content,timestamp}` |
| `prompt_send` | `prompt`, optional `session_id` | `{session_id,text,assistant_msg_id,failed}`. No id creates `mcp_<uuid>` with agent `main`; an unknown id is invalid |
| `prompt_cancel` | `session_id` | `{session_id,cancelled}`; true only for a same-connection active MCP turn |
| `tools_list` | none | `{name,description,inputSchema}`, configured order, de-duplicated |
| `tool_call` | `name`, optional object `arguments` (default `{}`) | Converted `AgentToolResult` content and error state |

Strings are non-blank. Schemas set `additionalProperties: false` and validate with `Draft202012Validator`; input is copied, never mutated. Structured payloads are one UTF-8 JSON `TextContent`. Text and image map to MCP text and image; other content fails closed as an execution error.

## Errors

| Case | Result |
| --- | --- |
| Wrapper name outside the list | `McpError` `METHOD_NOT_FOUND` |
| Schema failure, invalid underlying arguments, unknown supplied `session_id` | `McpError` `INVALID_PARAMS` |
| Unknown or unexposed underlying tool | Identical method-level error, so membership does not leak |
| Configured tool lacking paired scope; hard-constraint or approval refusal; executed tool failure | `CallToolResult(isError=True)` |
| Cancelled `prompt_send` | The SDK's standard JSON-RPC cancellation error, never a tool result |

Failure comes from `AgentToolResult.is_error`, set by normalization, the MCP client adapter, approval `_denied`, timeouts and exceptions, never inferred from text. `details` keeps diagnostics such as `denied`, `timeout`, `reason_code`.

## Token

- File `<state>/mcp_server_token`, POSIX `0600`; `serve` never generates one. `OPENPROGRAM_MCP_TOKEN` is compared with `hmac.compare_digest` before the stdio context opens.
- Client id: `sha256(stored_token)`, first 16 hex characters. It never contains token text.
- `create_token`: `secrets.token_urlsafe(32)`, refuses an existing target, exclusive `0600` temporary file, `fsync`, then a no-clobber install (`os.link` on POSIX, so a concurrent writer is never overwritten).
- Authentication failure: nonzero exit, empty stdout, sanitized stderr, stdin unread.

## Prompt lifecycle

- **Runs**: Synchronous turn on a worker thread with `abandon_on_cancel`; the exact cancel event is unregistered in `finally`. An abandoned worker cannot publish a later result.
- **`prompt_cancel`**: An ordinary tool: only a same-client, same-connection active turn; foreign or finished turns fail closed.
- **Cancellation**: Sets the thread and tool cancel events, marks the session cancelled, kills its subprocess and runtime, cancels session questions, unregisters the event, removes the active record, audits `mcp.request.cancelled` with request, session and client fingerprint but no prompt or token. Idempotent. Re-raised so the SDK produces the error.
- **Progress**: The service reports ordered messages; the wire layer turns them into monotonic MCP progress only when `progressToken` is present.
- **Wire**: An explicit `CallToolRequest` handler keeps wrapper and parameter faults as MCP errors. Stdout carries JSON-RPC only.

**Interfaces**

```
# contracts.py
def get_mcp_tools() -> tuple[mcp.types.Tool, ...]
def validate_tool_call(name, arguments) -> dict[str, Any]

# auth.py
MCP_TOKEN_ENV = "OPENPROGRAM_MCP_TOKEN"
def token_path() -> Path
def create_token(path=None) -> str
def authenticate_from_environment(environ=os.environ, path=None) -> str

# service.py
@dataclass(frozen=True)
class MCPClientContext: client_id; authority

class MCPService:
    def sessions_list() -> AgentToolResult
    def session_get(session_id) -> AgentToolResult
    def tools_list() -> AgentToolResult
    def exposed_runtime_tools() -> tuple[AgentTool, ...]
    async def tool_call(name, arguments, *, call_id, cancel_event, on_progress)
    async def prompt_send(prompt, *, session_id, request_id)
    async def prompt_cancel(session_id)
    async def cancel_request(request_id, *, reason) -> bool
    async def aclose(); def close()

# tools.py
def json_result(payload, *, is_error=False) -> AgentToolResult
def to_mcp_content(result) -> list[mcp.types.ContentBlock]

# server.py
def build_server(context) -> Server
async def serve_stdio(context) -> None
def serve() -> int
```

**End-to-end acceptance, with the SDK client**

1. Missing token file, wrong mode, missing or mismatched environment exit before initialize.
2. A valid token initializes at 2025-11-25; changing `clientInfo` changes no identity, list or result.
3. `tools/list` returns the wrappers in order; `tools_list` returns only the intersection.
4. Every wrapper returns its fixed shape; unknown wrappers and invalid parameters are MCP errors.
5. Unknown and unexposed underlying names are indistinguishable; scope, hard-constraint and approval failures are `isError`; no denied tool executes.
6. No approval or question blocks an MCP call.
7. Progress arrives in monotonic order if and only if the request supplies `progressToken`.
8. Cancelling `prompt_send` yields the SDK's error; later side effects stop, state clears, the audit exists.
9. `prompt_cancel` cannot cancel a foreign or finished turn.
10. Stdout holds JSON-RPC only.

Review together: schemas first; identity and token for owner-credential reuse and empty-list fallback; denial and cancellation for fail-closed order. Run the SDK client, not hand-written frames. Shared regressions when Runtime types change: authority, permission rules, spawn hard constraints, questions, ACP server, tools runtime.

## Implementation status

Present in the current source. Completion evidence belongs to [MCP server](https://fzkuji.github.io/OpenProgram/docs/reference/design/integrations/extensions/mcp-server.html).
