Skip to content

feat: serveMcpTools serves host-implemented tools over MCP - #376

Merged
xxchan merged 4 commits into
mainfrom
feat/serve-mcp-tools
Oct 13, 2026
Merged

xxchan merged 4 commits into
mainfrom
feat/serve-mcp-tools

Conversation

@xxchan

@xxchan xxchan commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Closes #341, by the route xxchan proposed: an embedded MCP server rather than each runtime's native host-tool channel.

What

  • serveMcpTools({ name, tools }) serves tools the host implements (name, description, input schema, handler) from a streamable HTTP MCP server inside the host process.
    • It listens on 127.0.0.1 behind a random bearer token.
    • It returns { server, close() }, where server is the ready SessionOptions.mcpServers entry { name, type: "http", url, headers: { Authorization } }.
    • One served set can back several sessions.
  • Coverage: one implementation reaches every runtime that takes an http entry with headers: claude, codex, pi, grok, kimi and opencode. cursor and pi-durable refuse mcpServers, and antigravity refuses an entry with headers, as before.
  • No native tool channels: no runtime gets a channel of its own (codex dynamicTools, claude's in-process SDK MCP, pi custom tools). None adds a capability MCP lacks.
  • Protocol: the subset every runtime's MCP client was shown to use with tests/fixtures/echo-mcp-server.mjs, plus what a second review found missing:
    • initialize, ping, tools/list and tools/call answered with JSON, single or batched;
    • notifications and a client's own responses answered 202;
    • GET answered 405 (no SSE stream);
    • each initialize opens its own MCP session (mcp-session-id), and calls are tracked by session and request id, so sessions sharing one served set never cancel each other's calls;
    • a protocol version the server speaks, a -32700 error object for bad JSON, a 413 that closes its connection, and a refused non-loopback Origin.
  • Handlers: a handler returns text, or MCP content with isError. A thrown error becomes an isError result with its message. notifications/cancelled, a dropped request or close() abort the call's signal.
  • Names are checked up front against the strictest runtime's rules (server ^[\w-]+$, tools ^[\w-]{1,64}$).
  • Docs:
  • .oxlintrc.json adds packages/oar/src/mcp/** to the Node-side override list.

Evidence

  • sea-trial/vendor/serve-mcp-tools.vendor.test.ts: the real claude, codex and pi (CI) and opencode, kimi and grok (run locally, no ACP backend in CI) each call a tool this test process serves, against a scripted provider. The provider receives words only the host's handler writes, and no record holds the bearer token. All six pass.
  • tests/mcp-serve-tools.test.ts pins:
    • the entry's shape;
    • 401 without the token or with a wrong one, and 405 for GET;
    • the MCP replies, a tool error versus a protocol error, and an unknown tool;
    • cancellation and close();
    • bad JSON and invalid names.
  • A second review (subagent) found that two sessions sharing a served set could cancel each other's calls, plus protocol and docs gaps. All are fixed in the second commit; the unit tests now also cover two clients with the same request ids, a dropped connection, batches, version negotiation, the 413 path and the Origin check.
  • Typecheck, lint and the full unit suite (1765 tests) pass; all six vendor runs pass again after the fixes.

🤖 Generated with Claude Code

exe.dev user and others added 4 commits October 13, 2026 08:08
A host that implements tools itself can now serve them with
serveMcpTools({ name, tools }): a streamable HTTP MCP server inside the
host process, on 127.0.0.1 behind a random bearer token, which returns the
SessionOptions.mcpServers entry to pass. One implementation reaches every
runtime that takes an http entry with headers (claude, codex, pi, grok,
kimi, opencode); cursor and antigravity refuse such an entry as before.
No runtime gets a tool channel of its own: codex dynamicTools, claude's
in-process SDK MCP and pi custom tools add nothing MCP lacks.

Handlers return text or MCP content; a thrown error becomes an isError
result; notifications/cancelled, a dropped request or close() abort the
call's signal. Docs: README, runtime matrix "Host-served tools", and the
claude page now says enforcement belongs to an OS sandbox or container.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fixes

From a second review of #376:
- Each initialize opens its own MCP session (mcp-session-id), and calls are
  tracked by session and request id. Before, two sessions sharing a served
  set reused the same request ids, so one's cancellation aborted the
  other's call and its cleanup dropped the other's tracking.
- initialize answers a protocol version the server speaks.
- Batches are answered; a client's JSON-RPC response is a 202; a parse
  error is a -32700 error object.
- A 413 closes its connection, so the client's next request is served.
- An Origin other than a loopback one is refused (MCP's DNS-rebinding rule).
- Docs: pi-durable also refuses mcpServers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Answering before the client finished sending reset its connection on
Windows (CI: ECONNRESET in the 413 test).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@xxchan
xxchan merged commit 7ca47d9 into main Oct 13, 2026
17 checks passed
@xxchan
xxchan deleted the feat/serve-mcp-tools branch October 13, 2026 08:36
@xxchan xxchan mentioned this pull request Oct 13, 2026
xxchan added a commit that referenced this pull request Oct 13, 2026
Release OAR and CLI 0.60.0. This PR changes only the two package version
fields.

**Added: `serveMcpTools`, tools the host implements** (#341, #376)
- `serveMcpTools({ name, tools })` serves tools the host implements
itself from a streamable HTTP MCP server inside the host process. Each
tool has a name, description, input schema and handler. The server
listens on `127.0.0.1` behind a random bearer token.
- It returns `{ server, close() }`. `server` is a ready
`SessionOptions.mcpServers` entry; pass it to any session.
- One implementation reaches every runtime that takes an http MCP entry
with `headers`: claude, codex, pi, grok, kimi and opencode. cursor and
pi-durable refuse `mcpServers`, and antigravity refuses an entry with
`headers`.
- A handler returns text, or MCP content with `isError`. A thrown error
becomes an `isError` result. Its `signal` aborts when the runtime
cancels the call, drops the request, or the server closes.
- Each `initialize` opens its own MCP session, so one served set can
back several sessions without their calls meeting.
- The token is redacted from records like any `mcpServers` header. The
runtime must reach the host's loopback address, which holds for every
runtime OAR starts on the same machine.
- No runtime gets a native host-tool channel (codex `dynamicTools`,
claude's in-process SDK MCP, pi custom tools). None adds a capability
MCP lacks.

**Added: `CursorModelListItem`** (#120)
- The parameter type of `projectCursorModels` is now exported, so a host
can type it without reaching into the Cursor SDK's types.

**Docs**
- `docs/runtimes/claude.md`: OAR always runs claude with
`--dangerously-skip-permissions` and refuses `--permission-mode`. A host
that needs enforcement isolates the session in an OS sandbox or
container.

**Behavior changes**
- None for existing options. Both additions are new exports.

Validation: #376 passed all 17 checks on its final head. Its merged tree
equals the tree verified locally on top of #120 (typecheck, lint, 1765
unit tests). #120 passed all 17 on its final head, and its merged tree
equals its CI tree.

The vendor test drives the real claude, codex and pi (in CI) and
opencode, kimi and grok (locally). Each calls a tool the test process
serves, against a scripted provider, and the provider receives only what
the host's handler wrote. No record holds the token.

A second review (subagent) found that two sessions sharing a served set
could cancel each other's calls, plus protocol gaps. Both were fixed
before merge, with tests.

After this PR passes CI and merges, tag its exact squash commit as
`v0.60.0` to trigger npm trusted publishing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: exe.dev user <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
stamp-build Bot added a commit that referenced this pull request Nov 20, 2026
…sification, shared usedRatio, and runtime edge cases (#1073)

<!-- stamp:review:v1 -->
<sup><img src="https://api.raft.build/api/avatars/pixel/ZXll.svg"
width="16" height="16" align="absmiddle" alt=""> <b>Lookout</b> from
open-agent-runtime opened this pull request through
Stamp</sup><br><sup><a
href="https://stamp.build/review?receipt=prc_316ea9490f2c7d9827984dda2667fc90"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://stamp.build/assets/brand/stamp-glyph-dark.d907ffcadb44.svg"><img
src="https://stamp.build/assets/brand/stamp-glyph-light.58a2c10ed108.svg"
width="13" height="12" align="absmiddle" alt=""></picture> View in Stamp
→</a></sup>

---
<!-- /stamp:review:v1 -->

## Summary

Fix the per-runtime `accountUsage` projection, error classification,
rounding, and Windows home-path issues assigned in `#core:#377` (from
the `#agy-soak:046f9f1b` audit, re-verified against `main`, keeping
shared deadline/contract work cleanly separated for `#core:#376`).

## Per-Item Changes

- **Account-wide `rateLimited` on Codex and Claude
(`packages/oar/src/runtimes/codex/account-usage.ts`,
`packages/oar/src/runtimes/claude/account-usage.ts`,
`docs/spec/account-usage.md`, `docs/runtimes/codex.md`):**
- **Codex:** Compute top-level `rateLimited` only from the account
bucket (`codex` or the legacy unnamed single-bucket view) and its
credits. Single-model buckets (such as `GPT-5.3-Codex-Spark`) remain in
`windows` without setting top-level `rateLimited: true`.
- **Claude:** Compute `includedExhausted` only from account-scoped
subscription windows (`five_hour` and `seven_day`). Single-model windows
(`seven_day_opus`, `seven_day_sonnet`, `model_scoped:*`) and
unknown-scope `seven_day_oauth_apps` stay in `windows` without setting
top-level `rateLimited: true`.
- **Claude `display_name` trimming:** Trim `model_scoped[].display_name`
before using it in `label`, `id`, and `scope.name`.
- **Claude unlimited Extra Usage
(`packages/oar/src/runtimes/claude/account-usage.ts`):**
- Treat `extra_usage: { is_enabled: true, monthly_limit: null,
utilization: null }` as usable extra-usage headroom so an exhausted
`five_hour`/`seven_day` window does not set `rateLimited: true`.
- **Evidence:** Verified directly from installed Claude Code `2.1.292`
(`/home/exedev/.local/bin/claude`), where the
`get_usage.rate_limits.extra_usage` schema defines `{ is_enabled:
boolean, monthly_limit: number | null, used_credits: number | null,
utilization: number | null, currency?: string | null }`, the UI renders
`is_enabled && monthly_limit === null` as `"Unlimited"` (or `"$X spent"`
with no cap) and `"Your organization already has unlimited usage
credits"`, and credit exhaustion/caps flip `is_enabled` to `false` (with
`disabled_reason`: `out_of_credits` / `org_spend_cap_reached` /
`org_level_disabled_until`). Note: this is static evidence from Claude
Code `2.1.292`'s schema and runtime checks rather than a captured live
unlimited-org account response.
- **Structured auth/unsupported classification and preserved `cause`
(Codex & Grok):**
- **Codex (`packages/oar/src/runtimes/codex/account-request.ts`,
`account-usage.ts`, `limit-reset.ts`):** Track `RpcOutcome` via
`client.request(..., onSettled)` and request phase
(`initialize`/`account/read` vs `call.method`). Never classify `exited`
process stderr, `initialize` failures, or timeouts as `reauth_required`
/ `unsupported`. Propagate `RangeError` (invalid `timeoutMs`) directly.
Classify `call.method` JSON-RPC errors using `-32601` / native message
(`chatgpt authentication required for rate limit reset`, `authentication
required`, `method not found`, `unknown variant \`<method>\``), dropping
the broad `/not supported/iu` match. Attach `{ cause: outcome.cause }`
in both `codexAccountUsage` and `codexRedeemLimitReset`.
- **Grok (`packages/oar/src/runtimes/grok/account-usage.ts`):** Classify
`RequestError` auth failures solely on the structured ACP auth code
`-32000` (removing the broad `/auth(?:entication)?|log(?:ged)? ?in/iu`
regex that misclassified `-32603` internal/TLS/proxy errors as
`reauth_required`).
- **Shared `usedRatio` helper replacing `.toFixed(6)`
(`packages/oar/src/shared/usage-ratio.ts`):**
- Added `usedRatioOf`, `usedRatioFromPercent`, `usedRatioFromCounts`,
and `usedRatioFromRemaining`, capping any natively unexhausted reading
at `0.999999` so 6-decimal rounding never turns `99.99999%` into `1` and
falsely triggers `rateLimited: true`.
- Replaced all `.toFixed(6)` and raw ratio calculations across all 6
`accountUsage` runtimes: Antigravity, Claude, Codex, Factory, Grok, and
Kimi (both direct HTTP and native Web paths).
- **Codex legacy single-bucket `scope` & Windows `USERPROFILE`
(`packages/oar/src/runtimes/codex/account-usage.ts`,
`home-initialization.ts`):**
- Assign `scope: { kind: "account" }` to the legacy single-bucket
unnamed account view (already identified as `accountBucket` for
`credits`), keeping other unnamed buckets without `scope`.
- Export `codexHomePath(env, cwd, platform)` in
`codex/home-initialization.ts` using `environmentValue` for
`USERPROFILE` (on `win32`) and `CODEX_HOME` (case-insensitive on
`win32`) instead of ignoring `options.env.USERPROFILE` via
`os.homedir()`.
- **Antigravity negative credits
(`packages/oar/src/runtimes/antigravity/account-usage.ts`):**
- Set `rateLimited` when `everyGroupExhausted` and `remainingCredits <=
0` (matching `credits.available: remainingCredits > 0`), so negative
balances do not report `credits.available: false` alongside
`rateLimited: false`.
- **Spec & runtime docs (`docs/spec/account-usage.md`,
`docs/runtimes/codex.md`):**
- Added `antigravity` to the `id`/`durationMs` table in
`docs/spec/account-usage.md`.
- Updated the `scope` table and `rateLimited` descriptions for Codex,
Claude, and Antigravity.

## Call-Site Audit

- **`.toFixed(6)` in `packages/oar/src/`:** Grepped all 8 call sites
(Antigravity, Claude, Codex, Factory, Grok x2, Kimi direct x2) plus Kimi
native Web (`kimi/native-usage.ts` x2). All 10 now use
`packages/oar/src/shared/usage-ratio.ts`.
- **`callAppServer`
(`packages/oar/src/runtimes/codex/account-request.ts`):** Checked both
callers (`codex/account-usage.ts` and `codex/limit-reset.ts`); both now
preserve `{ cause: outcome.cause }` on operational error.
- **Broad `/auth(?:entication)?|log(?:ged)? ?in/iu` regexes:** Fixed
`grok/account-usage.ts`. The 5 `listModels` call sites (`antigravity`,
`codebuddy`, `devin`, `grok`, `kimi`) are outside `#core:#377`
(`accountUsage`) scope and left unchanged.
- **Shared deadline/contract work (`#core:#376`):** Left
`contracts/account-usage.ts`, `scope_missing`, and
`withQueryDeadline`/`own()` migrations untouched for Otter's
`#core:#376`.

## Verification

- Local `CI=1 pnpm run check` on rebased head `47fb737a` (base
`ce5a24b3`): `typecheck` passed, `oxlint --type-aware --deny-warnings` 0
errors / 0 warnings, `vitest run` 589 passed / 147 skipped (5546 passed
/ 703 skipped), mock `sea-trial` 19 passed / 1 skipped / 0 failed.

Co-authored-by: Lookout <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Host-implemented tools in the session (claude SDK MCP, codex dynamic tools, pi custom tools)

1 participant