OpenProgram Docs

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.

Call path

Model tool_call agent_loop registry lookup Closure original name MCPClient Server CallToolResult → convert_call_result → AgentToolResult → chat history → next model call
  1. Modeltool_call
  2. agent_loopregistry lookup
  3. Closureoriginal name
  4. MCPClient
  5. Server
  6. Resultconvert_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
    }
  }
}
FieldMeaning
typelocal (stdio subprocess), http (Streamable HTTP), sse (legacy SSE). Remote types take url, headers, auth (none, bearer, oauth)
commandSubprocess command and arguments
envOverrides and additions to the inherited environment
enabledfalse disables without deleting
timeout_secondsStartup 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 absentPreserve
Name with a valueReplace
Name with an empty stringDelete

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
ItemRule
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 editPersisted only after the restart succeeds, so stored credentials stay intact

Code

openprogram/extensions/mcp/Role
__init__.pyRe-exports load_mcp_servers, shutdown_mcp_servers, server_status
config.pyMCPServerConfig, load_configs, save_configs
client.pyMCPClient: one server's transport, ClientSession, supervisor task
adapter.pyStateless translation between MCP types and AgentTool
registry.pyGlobal manager
oauth_flow.pyOAuth 2.1 PKCE consent and loopback callback
token_storage.pyPersistentOAuthProvider: tokens, client registration, server metadata
sampling.pySampling 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

SituationObservable result
App lifespan and /healthzReady while MCP transport, npm download or OAuth is pending; canonical execution recovery still gates readiness
Status and tool registryStarting and failed clients show actual ready, error and auth fields, masked secrets, no premature tools
Successful connectionNamespaced tools and prompts become available
Shutdown during startupStartup cancelled and drained; clients, supervisors, callback resources and registrations released; no late registration
Owner deletes or disables a queued serverStays absent or disabled; no new process or tools; a management replacement wins over the startup snapshot
Owned OAuth callback cancelledSocket, 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 typeBecomes
TextContentproviders.types.TextContent
ImageContentproviders.types.ImageContent
EmbeddedResourceText [resource: <uri>]; raw bytes stay out of chat
Unknown typesrepr(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

ItemState
Transportsstdio, Streamable HTTP, SSE. Remote auth: static bearer, OAuth 2.1 PKCE.
Tools, resources, prompts, samplingImplemented. 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.
ManagementAdd, 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 limitMCPClient._call_lock serializes calls to one server; one slow tool blocks the others on it.
Tool list limitRead once at startup; tools/list_changed is not handled.
_loadedModule global; tests reset it through tests/integration/programs/test_mcp_client.py::_reset_mcp_loader_flag.
Last updated · 2026-11-25