Skip to content

feat(experimental): client-hosted MCP door, browser connect token and schema helper - #947

Merged
Blind-Striker merged 30 commits into
masterfrom
feat/529-client-mcp
Nov 17, 2026
Merged

Blind-Striker merged 30 commits into
masterfrom
feat/529-client-mcp

Conversation

@Blind-Striker

@Blind-Striker Blind-Striker commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

📝 Description

What does this PR do?

It adds the experimental client-hosted MCP door (OPENCODE001). An application opens a WebSocket to the opencode server and serves its own tools there: the application is the MCP server, and opencode is the MCP client.

  • ConnectClientMcp (on ExperimentalClient) returns a caller-owned ClientMcpConnection that reconnects on its own.
    • It answers initialize, ping, tools/list and tools/call, following upstream's first-party client (packages/client/src/mcp.ts at the pinned v2.3.0).
    • Backoff starts at 500 ms, doubles, and caps at 10 s. Only notifications/initialized resets it.
    • Only the tool handler is deferred off the read loop. Synchronous answers keep arrival order, and handlers may overlap.
    • Results can carry text and image content.
  • CreateClientMcpConnectTokenAsync mints the browser connect ticket. It is generated internal-raw HTTP behind a hand-written extension that supplies the fixed x-opencode-ticket sentinel.
  • ClientMcpSchema.FromType exports an object input schema from source-generated JsonTypeInfo metadata, with no new dependency.
  • Docs: the experimental guide, client-runtime.md, protocol-and-generation.md, ADR-0021 and ADR-0031, the README, the CHANGELOG, the glossary and the roadmap.

Related Issue(s):

🔄 Type of Change

  • ✨ New feature (non-breaking change that adds functionality)
  • 📚 Documentation update
  • 🔧 Build, CI, or tooling (generator rules, below)

🎯 Protocol & API Surface

  • Public API changed deliberately, and tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt is updated in this PR. Everything new carries [Experimental("OPENCODE001")]:
    • ExperimentalClientMcpExtensions.ConnectClientMcp;
    • ExperimentalClientMcpExtensions.CreateClientMcpConnectTokenAsync;
    • ClientMcpConnection, ClientMcpOptions, ClientMcpTool, ClientMcpToolResult, ClientMcpContent, ClientMcpSchema;
    • ClientMcpToolContext, with a public ClientMcpToolContext(string? sessionId) constructor, so handler authors can unit-test their handlers (public ClientMcpToolContext(string? sessionId) { });
    • the generated ExperimentalMcpClientTokenRequest / …Response.
  • Generated output changed, and it was produced by the generator, not hand-edited
  • dotnet run --file tools/opencode-tool.cs -- generate --verify passes
  • The pinned snapshot (spec/) is untouched
  • Nothing under external/ was hand-edited

Generator rules, for the generator owners' read. Canon (protocol-and-generation.md):

An internalRaw group with rootAccessor: false may share the diagnostic of its nearest curated parent, the longest proper dotted prefix across all curated groups; other distinct families cannot share one diagnostic. Such a subgroup inherits that parent's effective naming boundary; every other group uses its own prefix's last segment as its naming boundary.

The generator owners' review found it clean: no defects and no drift from the rules or canon; generate --verify is current; no generated name or diagnostic changes.

🧪 Testing

  • Unit / contract tests added or updated. The responder's wire fixtures are taken from upstream's client. The connection, dispatch, reconnect, fencing, disposal and schema tests run on a manual clock, with no sleeps.
  • Integration tests added or updated. Live tests run against the pinned server:
    • attach failure (1011, attach failed) and location reload (1012, location shut down);
    • the browser ticket: a ticket-only attach, then the refusals for reuse, wrong name and wrong directory.
  • Verified against a real opencode serve: the pinned v2.3.0, run from source.
  • Verified on the downlevel targets (net472 / netstandard2.0). On .NET Framework, the 1012 case asserts the native close-code limit (net472: a server close with 1012 ends terminal sockets in a transport exception #934).
  • Mutation proofs: every new rule has a red on the base or a killed mutant, run through a bounded runner that restores the file byte-identically.
  • Test environment:
    • opencode server version: v2.3.0 (the pinned commit);
    • target frameworks tested: net10.0, net11.0, net472;
    • operating systems: Windows locally; Linux, macOS and Windows in CI.

✅ Completion Gate

  • The local check in quality-gates.md passes on the head rebased onto master: whitespace, format/style, clones, slopwatch, the release build, all test projects, the API snapshots, generate --verify, the fixed point, Extensions and Native AOT.

📚 Documentation

  • XML documentation comments added/updated for public APIs
  • README.md updated
  • The consumer guide under docs/guide/ updated: Client-hosted MCP and Browser handoff, with compiling snippets
  • CHANGELOG.md entry added for user-facing changes

✅ Code Quality Checklist

  • No new analyzer warnings, and no new suppressions
  • No tests skipped, weakened, or deleted to make the suite pass
  • Branch is up to date with the target branch, no merge conflicts
  • Commit messages carry no AI-attribution trailers

🔍 Additional Notes

Review. Three independent full-diff reviews found no correctness blocker; the README blocker they found is fixed here. The concurrency change (handlers deferred off the read loop) had two further independent reads.

  • Production disposal can't hang on a never-completing send. With real time, the graceful close gives up after its 5 s bound, and hard teardown aborts the socket.
  • What they did find is fixed here: the reply order (now only the handler is deferred, as upstream does), a test race, and missing hang guards.
  • A final read of those fixes cleared, with nothing new that blocks, and so did a read from a third reviewer family.

Recorded divergence (approved by the maintainer). The frame decoder parses with MaxDepth = 256, because the responder walks the document recursively when it formats names, and the bound keeps that recursion safe. A depth of 256 is accepted and 257 is refused, and a boundary test pins both. Upstream's JSON.parse has no limit. Before this change, System.Text.Json's default of 64 already bounded depth, so the question was which bound to record, not whether to have one. client-runtime.md records it under the client-MCP responder:

"The client-MCP frame decoder accepts JSON nested at most 256 levels deep; deeper frames are ignored as invalid. The bound keeps the responder's recursive formatting within a safe stack depth; upstream's parser has no limit."

Deferred live proofs (#942). Two live rows wait for an upstream signal that a client-attached connection is registered:

  • the model path with stacked same-name connections;
  • the automatic reattach after a reload.

The server registers the connection only after its handshake ends, and nothing public reports it.

Breaking Changes: none. Everything new is additive and experimental.

Dependencies: none added.

ConnectClientMcp admits the connection immediately and keeps it alive the
way opencode's client does: a capped 500 ms to 10 s retry schedule that
resets only on notifications/initialized, a later factory failure reported
through the retry callback, replies fenced to the socket that carried the
request, and an asynchronous disposal that closes only its own socket and
neither cancels nor joins application handlers. Three loopback-WebSocket
proofs cover public admission, manual-schema capture and an attach that
mints no ticket. The reviewed public API snapshot pins the experimental
marks.

Size against the upstream client (one .NET cost per row):

- Connector, 38 lines: ClientWebSocket is configured before an asynchronous
  ConnectAsync, so construction and upgrade are separate entry points with a
  dispose-and-rethrow on a failed upgrade (about 16 lines); mapping the
  default platform's PlatformNotSupportedException while keeping a caller
  factory's synchronous exception costs about 9.
- Dispatch, 80 lines: task-fault observation and completion snapshots cost
  about 20 lines; continuations and disposal can run on different pool
  threads, so retirement, admission and send acquisition share one lock
  (about 23). Single-writer serialization reuses the existing socket core.
- Terminal adapter, 42 changed lines: keeping the existing constructor while
  admitting supplied and default sockets costs about 10 lines; applying setup
  headers with a dispose-and-rethrow when setup fails costs about 20; the
  disposal-observation callback about 4.

The send-deadline proof records the 30-second timer count at physical send
entry and asserts after release, so a finite-deadline mutant fails on every
runtime without stranding test-owned I/O. The loopback exchange bounds its
socket I/O with WaitAsync hang guards rather than a timed
CancellationTokenSource.
Delegate through the experimental client's pipeline to the generated token route with the shared ticket sentinel. Preserve ordinary HTTP errors, NoThrow and caller cancellation. Register the generated consumer and add the cancellation identity row and additive API entry.

Production size ledger (20 physical C# lines):

- XML documentation: 9; explains ticket scope, root credentials, errors and explicit minting, against 12 documentation lines on the generated raw route.

- Public signature: 3; the minimum extension door, against the raw route's single-line signature (3x).

- Braces: 2; same two method braces as the raw route.

- Argument guards: 2; one raw-request guard plus the extension receiver guard required by the public .NET boundary.

- Pipeline and MockSeam resolution: 1; the minimum public door, replacing the raw client's constructor-held pipeline.

- Raw delegation and fixed sentinel: 2; one call across two physical lines, against one generated pipeline call.

- Separator: 1; keeps the two public methods distinct.

No row exceeds 3x its generated-route plus minimum-door analogue. Tests add or substantively change 101 physical C# lines; the additive API snapshot is separate. No public subclient, root accessor, DTO or registration is added.
@Blind-Striker
Blind-Striker added this pull request to the merge queue Nov 17, 2026
Merged via the queue into master with commit c764d7f Nov 17, 2026
17 checks passed
@Blind-Striker
Blind-Striker deleted the feat/529-client-mcp branch November 17, 2026 08:51
@Blind-Striker Blind-Striker moved this to In-flight in opencode-sdk-dotnet Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In-flight

Development

Successfully merging this pull request may close these issues.

Client-hosted MCP servers: attach the app's own tools over the experimental client-MCP WebSocket

1 participant