Skip to content

Latest commit

 

History

History
251 lines (203 loc) · 13.4 KB

mcp.md

File metadata and controls

251 lines (203 loc) · 13.4 KB

MCP

OMK speaks the Model Context Protocol as a client: it starts configured servers, lists their tools, and exposes those tools to the model alongside the built-in ones.

Two separate surfaces exist, and they are easy to confuse:

Surface Module What it does
Inventory / health core/mcp-inventory.ts Reads configuration read-only for omk doctor and the MCP health view. Never starts a server. Env values are stripped.
Runtime client core/mcp/ Starts servers, performs the handshake, and registers their tools for a session.

Configuration

Servers are read from three files, later wins on a name collision:

  1. ~/.kimi/mcp.json
  2. ~/.omk/mcp.json
  3. <cwd>/.omk/mcp.json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["-y", "@playwright/mcp@latest"],
      "startup_timeout_sec": 60
    },
    "serena": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/oraios/serena", "serena"],
      "env": { "SERENA_LOG_LEVEL": "error" }
    },
    "retired": { "command": "npx", "args": ["-y", "old-server"], "disabled": true }
  }
}

Project configs need trust

<cwd>/.omk/mcp.json comes with whatever repository you cloned, so OMK treats it as untrusted:

  • Its servers are skipped until you trust that exact file content. Trust is stored in ~/.omk/mcp-trust.json (mode 0600), keyed by the project's real path and pinned to a SHA-256 of the file. Any later edit (a pull, a branch switch) skips the servers again until you re-trust.
  • Even trusted project servers do not inherit your environment. They get a small allowlist (PATH, HOME, USER, LANG, TERM, TMPDIR, SHELL and their Windows equivalents) plus the literal env they declare.
  • $VAR / ${VAR} in a project config's command, args and cwd are not expanded from your environment; only a leading ~ is.
  • User configs (~/.kimi/mcp.json, ~/.omk/mcp.json) are unaffected.

Trust programmatically with trustProjectMcpConfig(cwd) (pass the reviewed sha256 to refuse content that changed after review) and undo with revokeProjectMcpTrust(cwd). For CI, OMK_TRUST_PROJECT_MCP=1 trusts the project file for that process. AgentSession.mcpProjectTrustReport() lists the project servers that were skipped at the last attach.

Field Meaning
command, args Executable to spawn. Required — entries with only a url are skipped, since stdio is the supported transport.
env Extra environment for the child. For user configs it is merged over the parent environment; for project configs it is merged over the small allowlist only. Values are runtime-only and are never rendered or logged.
cwd Working directory. Defaults to the session's cwd.
disabled / enabled: false Skip without deleting the entry.
startup_timeout_sec Handshake deadline. Raise it for npx -y …@latest servers whose first run downloads a package.
tool_timeout_sec Deadline for each request to this server, including tool calls (default 30, clamped to 1 s–24 h). Raise it for servers whose tools queue or run long. OMK_MCP_TOOL_TIMEOUT_SEC sets the default for servers that omit it.

Using it

The omk CLI calls attachMcpServers() for every session it creates — interactive, -p, and RPC, including /new, /resume, and forks — so a configured server's tools reach the model without further setup. An enabled server that fails to start is reported as a startup warning and the session continues. Intentionally disabled entries are skipped without a startup warning. --help and --list-models never spawn servers.

SDK callers attach explicitly:

const status = await session.attachMcpServers();
// [{ name: "playwright", state: "ready", toolCount: 24, serverVersion: "1.62.0" }]

session.getToolDefinition("playwright__navigate");
  • Nothing is spawned until attachMcpServers() is called. An SDK session can configure 25 servers without paying for them until it attaches.
  • Tools are exposed as <server>__<tool>, truncated to 64 characters with the server prefix preserved.
  • A built-in tool always wins a name collision; MCP can never shadow bash.
  • Calling attachMcpServers() again replaces the previous MCP tools rather than duplicating them.
  • Explicit mcpCheckHealth({ reconnectFailed: true }) recovery publishes the newly admitted catalog, including changed schemas and tool names. During an outage, registered tools fail against their closed client; they are never replayed against the replacement server. Keeping those registrations until recovery preserves disabled tool selections. Healthy, unchanged catalogs keep their existing handles and prompt prefix.
  • session.dispose() terminates every server it started.

Bounded startup

Each manager admits up to four connect/handshake/catalog attempts at once by default. Low-level SDK callers can set a positive integer connectionConcurrency in McpManagerOptions. This is a startup limit, not a server or tool limit: a listing still waits for every enabled attempt and returns the full admitted catalog in configuration order. Waiting servers report queued; they have not been spawned yet. Direct connects and explicit health recovery share the queue.

Closing a manager cancels queued starts and invalidates active generations. An active attempt keeps its slot until settlement, and late handshake/list results cannot publish tools. Explicit post-close connects wait for the previous attempt to settle before reconnecting. No idle-server shutdown or descriptor reduction is introduced. Four is a conservative default, not a measured optimum: staging can increase full-catalog readiness time while reducing simultaneous startup work.

Tool schema budget

Every request carries the schema of every active tool, so a large catalog can outgrow a small context window. In one measured project, 328 tools from 21 MCP servers plus the built-in tools were estimated at 237,218 tokens, more than the 219,416-token input ceiling of a model configured with a 262,000-token window.

When the system prompt and tool schemas would leave a fully compacted session (the kept tail plus the summary reserve) above the compaction trigger, requests to that model withhold whole MCP servers, largest schema first, until it fits.

  • The active tool set does not change: getActiveToolNames(), extensions and the tool list still show withheld tools; only the provider request omits them.
  • A warning names the withheld servers once. Switching to a model with room restores them, with a second notice.
  • Built-in and extension tools are never withheld. If they and the system prompt alone exceed the input ceiling, the prompt is rejected as configuration.invalid: compaction cannot shrink them, so switch to a larger-context model or disable servers.

To keep a particular server on a small model, disable larger servers you do not need for that project.

Failure behavior

Failures are isolated by design, because one broken server must not cost a session:

Failure Result
Server exits during startup That server is failed with a classified public error; every other server still contributes tools. The low-level client retains a stderr tail for local diagnostics, not for the manager status.
Handshake exceeds startup_timeout_sec Same — reported as a timeout, session unaffected.
Server dies mid-session In-flight requests reject; later calls to its tools return a tool-level error instead of throwing.
Tool returns an MCP error Surfaces as a normal tool result with isError: true, so the model sees the server's own message.
Tool returns a malformed result Rejects with mcp.invalid_tool_result rather than treating missing content or invalid isError as success. Unknown explicitly typed content blocks remain allowed.
Server emits a non-JSON line The line is dropped and decoding resynchronizes at the next newline.
Server emits a frame larger than 16 MiB One framing error is reported; the remainder is discarded until the next newline.

Native startup warnings preserve the mcp.connect_failed prefix and include a fixed diagnostic code plus a recovery hint. Arbitrary server error text is never used to infer these codes or copied into the warning:

Code Check
mcp.spawn_not_found Configured command, PATH, and cwd; either the executable or its working directory may be missing.
mcp.spawn_permission_denied Executable and directory permissions. Do not disable browser isolation.
mcp.spawn_failed The local process configuration.
mcp.server_exited The numeric exit code, launcher prerequisites, and local stderr. Raising the handshake timeout does not repair a process exit.
mcp.request_timeout startup_timeout_sec for initialization, tool_timeout_sec for catalog requests and health probes.
mcp.invalid_initialize_result / mcp.unsupported_protocol The command's stdio MCP support and compatible protocol revision.

Unknown errors retain the opaque mcp.connect_failed (Error) form. Raw stderr, commands, arguments and server payloads remain outside manager diagnostics. Failed servers are not restarted automatically; explicit health recovery retains the existing connection queue and process-retirement ownership.

Low-level SDK callers can set McpServerConfig.inheritEnv to false to avoid inheriting the parent environment. Omitting it preserves the transport default; this option is not yet wired into the mcp.json parser. Client request and handshake timeouts accept only safe integers from 0 through 2,147,483,647 ms; zero refuses to send a request. A timeout ends local waiting, not remote effects.

The frame limit counts raw UTF-8 bytes, including whitespace and CR in CRLF, independently of chunk boundaries. The decoder scans only new chunks and batches small fragments without truncating valid messages or reducing tool catalogs. This bounds retained frame data, not the memory of parsed JSON or the whole process.

The outbound McpStdioTransport checks bytes already observed in Node's stdin writable queue before accepting another framed request. Low-level SDK callers may set a non-negative safe-integer maxPendingWriteBytes (default 16 MiB; zero refuses all frames); invalid values fail before server startup. The check does not bound kernel pipe bytes or server memory, and a successful local write does not prove that the server handled the request.

Checking your configuration

node scripts/mcp-smoke.mjs                       # connect enabled servers, print status
node scripts/mcp-smoke.mjs github playwright     # only these
OMK_MCP_SMOKE_HANDSHAKE_MS=120000 node scripts/mcp-smoke.mjs   # override slow handshakes

The script prints server state, tool counts, and bounded numeric version cores when available. The manager status omits free-form server-reported versions and strips prerelease/build suffixes before exposure. The low-level client's serverInfo remains raw; this format check is not general secret redaction. The script never prints configured env values or raw stderr. It skips disabled entries, uses the client's normal handshake default unless overridden, and waits for its direct MCP processes to close before exiting. Exit status is 1 if an enabled server fails, a requested name is unknown, or the override is invalid; otherwise it is 0. The override must be a positive integer within Node's timer range. The probe starts the configured commands, so run it only for servers you intend to execute.

Browser servers that share a launcher

If Chrome DevTools and Playwright fail together, first check whether their configuration delegates to the same browser/CDP launcher. mcp.server_exited means that launcher or server stopped, not that a longer handshake is needed. Check browser readiness and profile/port ownership locally. A running Chrome process alone does not prove that its CDP listener is ready. Do not kill personal browser processes, expose CDP beyond loopback, disable sandboxing, or switch profiles as an automatic recovery step. After correcting the prerequisite, recreate the intended session or request explicit SDK health recovery.

Package and credential errors

An npm E404 happens before the MCP handshake: the configured npm package could not be resolved. A longer startup_timeout_sec does not fix a wrong package name. The server's configuration key is not necessarily its package name:

  • Context7: npx -y @upstash/context7-mcp, not npx -y context7-mcp.
  • Fetch: uvx mcp-server-fetch, not npx -y @modelcontextprotocol/server-fetch.

Check all three configuration paths above: a project entry overrides a user entry with the same server name. Recreate the session after correcting a command.

A No API key error is different: the executable started but lacks credentials. For Resend, supply RESEND_API_KEY securely to the server process, or explicitly set disabled: true if you do not need it. Do not paste keys into diagnostic output. Missing-key and other genuine startup failures remain warnings.

Scope

Implemented: initialize, notifications/initialized, tools/list, tools/call over stdio.

Not implemented: HTTP/SSE transports, resources, prompts, sampling, and server-initiated requests. Every OMK-configured server today is stdio, and adding a surface nothing calls would be dead weight.