# MCP client integration

OpenProgram as MCP client: each tool of a server in `mcp_servers.json` becomes an ordinary `AgentTool` named `{server}__{tool}`. Exposing OpenProgram's own tools is the opposite direction: [MCP server](https://fzkuji.github.io/OpenProgram/docs/reference/design/integrations/extensions/mcp-server.html).

## Call path

1. **Model** tool_call
2. **agent_loop** registry lookup
3. **Closure** original name
4. **MCPClient**
5. **Server**
6. **Result** convert_call_result, chat history, next model call

- Awaited on the worker's event loop. A session-expired call reconnects and retries once.
- Only the model starts these calls. `programs run` and the `/programs` page are for local functions.

## Configuration

`<state_dir>/mcp_servers.json`, following the profile through `paths.get_state_dir`. A missing or unparsable file logs one warning; the worker starts with no servers.

```
{
  "servers": {
    "drawio": {
      "type": "local",
      "command": ["npx", "-y", "@drawio/mcp"],
      "env": {},
      "enabled": true,
      "timeout_seconds": 60
    }
  }
}
```

| Field | Meaning |
| --- | --- |
| `type` | `local` (stdio subprocess), `http` (Streamable HTTP), `sse` (legacy SSE). Remote types take `url`, `headers`, `auth` (`none`, `bearer`, `oauth`) |
| `command` | Subprocess command and arguments |
| `env` | Overrides and additions to the inherited environment |
| `enabled` | `false` disables without deleting |
| `timeout_seconds` | Startup wait and per-call read timeout |

### Credentials

Every value in `env` and `headers` is a secret, since any entry can hold one, alongside the bearer token and OAuth client secret.

| `PATCH /api/mcp/servers/{name}` | Effect |
| --- | --- |
| Name or whole field absent | Preserve |
| Name with a value | Replace |
| Name with an empty string | Delete |

Same rule for `auth.token` and `auth.client_secret`. Changing `auth.kind` drops the other kind's secret. The Web UI opens secret inputs empty and lists stored names only.

**Serialization and storage**

| Item | Rule |
| --- | --- |
| `to_storage_dict()` | Full values; only for writing `mcp_servers.json` |
| `to_response_dict()` | Each value becomes `{"has_value": bool, "masked": str}`; auth secrets become `has_token` / `has_client_secret` and a mask. Returned by `/api/mcp/servers`, `/api/mcp/servers/{name}`, `/api/mcp/catalog`, `/api/mcp/catalog/diff`. |
| `save_configs()` | Owner-only: temporary file created `0600`, `fsync`, `os.replace`. An older `0644` file narrows on next save. |
| Failed edit | Persisted only after the restart succeeds, so stored credentials stay intact |

## Code

| `openprogram/extensions/mcp/` | Role |
| --- | --- |
| `__init__.py` | Re-exports `load_mcp_servers`, `shutdown_mcp_servers`, `server_status` |
| `config.py` | `MCPServerConfig`, `load_configs`, `save_configs` |
| `client.py` | `MCPClient`: one server's transport, `ClientSession`, supervisor task |
| `adapter.py` | Stateless translation between MCP types and `AgentTool` |
| `registry.py` | Global manager |
| `oauth_flow.py` | OAuth 2.1 PKCE consent and loopback callback |
| `token_storage.py` | `PersistentOAuthProvider`: tokens, client registration, server metadata |
| `sampling.py` | Sampling callback on the configured host model |
| `server/` | The separate server direction; does not reuse client modules |

A core package in the extensions group beside `plugins/` and `skills/`, not under `openprogram/programs/`: it adapts an external protocol, as `openprogram/interfaces/channels/` does for messages. opencode (`src/mcp/`) also keeps MCP separate; this layer is essentially a Python translation of opencode's.

## Startup and readiness

| Situation | Observable result |
| --- | --- |
| App lifespan and `/healthz` | Ready while MCP transport, npm download or OAuth is pending; canonical execution recovery still gates readiness |
| Status and tool registry | Starting and failed clients show actual ready, error and auth fields, masked secrets, no premature tools |
| Successful connection | Namespaced tools and prompts become available |
| Shutdown during startup | Startup cancelled and drained; clients, supervisors, callback resources and registrations released; no late registration |
| Owner deletes or disables a queued server | Stays absent or disabled; no new process or tools; a management replacement wins over the startup snapshot |
| Owned OAuth callback cancelled | Socket, thread and waiter released, no false code; normal code and state validation intact |

**Rules behind this**

- The server lifespan runs `load_mcp_servers()` as a managed background task; servers connect in order with their configured timeouts.
- Each client is published in the registry before its connection is awaited: `ready=false`, no tools. The masked management API stays available.
- Each queued server reads the current persisted configuration when reached.
- Connecting lazily on first tool use is not done. Waiting for every connection is not done, since authentication may outlast the health deadline. Neither is another worker, changed owner timeouts, suppressed auth errors or a pending client marked ready.

## Mechanisms

### Tool names

`adapter.namespace_tool_name(server, tool)` replaces characters outside `[A-Za-z0-9_-]` with `_` and truncates to 64, OpenAI's limit, keeping the tool suffix. Double underscore because OpenAI's name pattern rejects opencode's colon. On a collision the last registered wins.

### Content conversion

| MCP type | Becomes |
| --- | --- |
| `TextContent` | `providers.types.TextContent` |
| `ImageContent` | `providers.types.ImageContent` |
| `EmbeddedResource` | Text `[resource: <uri>]`; raw bytes stay out of chat |
| Unknown types | `repr(block)` text |

`isError=True` sets `details["is_error"]`; the model sees the result text, as with local tools.

**Persistent connection and supervisor task**

MCP is a long-lived bidirectional connection and the SDK exposes it as nested context managers. A supervisor `asyncio.Task` holds them open.

```
async def _supervisor(self):
    async with stdio_client(params) as (r, w):
        async with ClientSession(r, w) as session:
            await session.initialize()
            result = await session.list_tools()
            self._session = session
            self.tools = list(result.tools)
            self._ready.set()
            await self._shutdown.wait()
```

- `start()` creates the task and waits on `_ready`; `call_tool()` reuses `_session`; `stop()` sets `_shutdown` and the subprocess closes.
- A startup failure also sets `_ready` and records `error`; the manager skips registration and logs one line.

**OAuth**

- Delegated to the SDK's `OAuthClientProvider` through `PersistentOAuthProvider`.
- Persisted across restarts: tokens with absolute `expires_at`; the dynamic client registration, whose loopback port is reused so re-auth presents a registered `redirect_uri`; the discovered server metadata, so a cold-start refresh reaches the real token endpoint.
- An expired token renews in the background. Browser consent runs only on first auth or a rejected refresh, surfaced as `error_kind="needs_reauth"`.
- The browser opens for consent only when someone connects the server, from the App or the CLI. When the worker connects its servers by itself, at startup or on its own reconnects (`oauth_flow.unattended`), the link stays in `/api/mcp/auth/pending` and no browser comes in front of what the user is doing.

**Test isolation**

`config.py` uses `from openprogram.state import paths as _paths` and calls `_paths.get_state_dir()` live. `from … import get_state_dir` would bind the lambda that `tests/integration/store/test_attach_lazy_session.py` monkeypatches, because that test triggers the first import through `_start_mcp_servers`, and leak it. A new paths monkeypatch must still go through the module reference.

## Implementation status

| Item | State |
| --- | --- |
| Transports | stdio, Streamable HTTP, SSE. Remote auth: static bearer, OAuth 2.1 PKCE. |
| Tools, resources, prompts, sampling | Implemented. Resource and prompt meta tools reuse the persistent client; MCP prompts synchronize with the slash-command registry. Sampling returns a structured error without a configured host model. |
| Management | Add, remove and restart act on the selected client with no worker restart. `server_status()` and server details give ready, error and auth status, tool count and masked credentials. |
| Concurrency limit | `MCPClient._call_lock` serializes calls to one server; one slow tool blocks the others on it. |
| Tool list limit | Read once at startup; `tools/list_changed` is not handled. |
| `_loaded` | Module global; tests reset it through `tests/integration/programs/test_mcp_client.py::_reset_mcp_loader_flag`. |
