From 557a8b2c9c074f5ca3461fe43daf033f5629f0eb Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 20:10:54 -0600 Subject: [PATCH] docs: preserve mcpx door build record MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dated record of the 2026-11-23 mcpx door build (public MCP endpoint at mcpx.security.cab, part of #13657): door README, lane continuation brief, adapt.py and filter.ts copied byte-for-byte from hatch-personal workspace/mcpx-door-20261123/, plus the record front page and the doc/README.md index line. Part of #13877 — do NOT merge; Archer merges from the evidence. --- ...4T02-09-07Z_research_mcpx-door-20261123.md | 10 + .../EXECUTOR-BRIEF.md | 76 ++++ .../README.md | 124 +++++++ .../adapt.py | 346 ++++++++++++++++++ .../filter.ts | 43 +++ doc/README.md | 1 + 6 files changed, 600 insertions(+) create mode 100644 doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/2026-11-24T02-09-07Z_research_mcpx-door-20261123.md create mode 100644 doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/EXECUTOR-BRIEF.md create mode 100644 doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/README.md create mode 100644 doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/adapt.py create mode 100644 doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/filter.ts diff --git a/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/2026-11-24T02-09-07Z_research_mcpx-door-20261123.md b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/2026-11-24T02-09-07Z_research_mcpx-door-20261123.md new file mode 100644 index 000000000..35e180903 --- /dev/null +++ b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/2026-11-24T02-09-07Z_research_mcpx-door-20261123.md @@ -0,0 +1,10 @@ +# mcpx door build record + +This dated record preserves the 2026-11-23 mcpx door build record: the public MCP endpoint Worker at `mcpx.security.cab` (part of #13657), with the lane-authored build assets. The door itself is live; this folder is the point-in-time build record, not a maintained inventory. + +- **Build date:** 2026-11-23 +- **Source:** `hatch-personal` workspace folder `workspace/mcpx-door-20261123/` +- **Tracking issue:** [#13877](https://github.com/developing-today/code/issues/13877) +- **Inventory:** `README.md`, `EXECUTOR-BRIEF.md`, `adapt.py`, `filter.ts` (four source files, copied byte-for-byte; `__pycache__` excluded by the slice) + +The record covers the Worker's request path (hosted-client OAuth 2.1 front door, machine-bearer path, bridge egress to the laptop daemon), the origin-lockdown boundary, the OAuth shape, the per-request filtering seam (`ns` selector, conservative default, pass-through enforcement pending the #13657 spec), the by-name secret inventory, and the publish/promote deploy pair. `EXECUTOR-BRIEF.md` is the lane continuation brief (state reached, why the lane stopped, remaining executor steps, adaptation values); `adapt.py` performs the Commander-to-mcpx adaptation; `filter.ts` is the filtering seam. The source brief and README are retained unchanged below. diff --git a/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/EXECUTOR-BRIEF.md b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/EXECUTOR-BRIEF.md new file mode 100644 index 000000000..90f3efbfe --- /dev/null +++ b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/EXECUTOR-BRIEF.md @@ -0,0 +1,76 @@ +# mcpx Worker (W1, #13657) — continuation brief + +## State already reached (verified from tool read-backs, 2026-11-23 ~13:50 CST) + +- Laptop primary clone `~/git/code` was on `main`, CLEAN at fetch time + (the dirt named in the original brief — modified + `doc/fleet-schedule-registry.md`, untracked `pkgs/id/examples/` — + was NOT present; nothing was touched/stashed/committed by this lane). +- Worktree created: `~/git/code-mcpx-door-20261123`, branch + `lane-mcpx-door-20261123`, off `origin/main` @ `0a6ca03ccca` + (Merge PR #13538). +- Copied into the worktree (unadapted, byte copies): + `pkgs/desktop-commander/worker/.` → `pkgs/mcpx/worker/` + (node_modules excluded; 18 files incl. package-lock.json), and the + three workflows → `.github/workflows/mcpx-worker-{publish,promote,tests}.yml`. + +## Why this lane stopped + +The `git worktree add` exec result tripped a platform execution-risk +flag on the checkout content. Per the task rule, the operation was +retried via the Desktop Commander endpoint +(`https://commander.security.cab/mcp`, bearer by name +`desktop-commander.machine-bearer` via `fleet secrets get`, in-memory +only): attempt 1 got Cloudflare error 1010 (browser signature banned, +Python UA); attempt 2 (browser UA) got a connection closed without +response. DC route from the sandbox is therefore not working this +session. Remaining build steps must run in a venue that does not trip +the flag — Drew's standing route: a laptop-local OpenCode session +working in the worktree in-session, evidence recorded on #13657, +Archer/parent finishes (merge) via `gh` from the record. + +## Remaining steps for the executor (in the laptop worktree) + +1. Get `adapt.py`, `filter.ts`, `README.md` from the sandbox workspace + `~/workspace/mcpx-door-20261123/` to the laptop (they are + hand-authored lane assets, not repo content). +2. Run `python3 adapt.py` from `~/git/code-mcpx-door-20261123` + (it performs all Commander→mcpx swaps, the index.ts bare-path + + selector restructure, writes `src/filter.ts`, appends the + bare-path/selector tests to `test/proxy.test.ts`, fixes the + package-lock name, and asserts the final config/AUD/KV/scope + values). Then copy the companion `README.md` over + `pkgs/mcpx/worker/README.md` (adapt.py deliberately excludes it). +3. Sanity greps: no `desktop-commander` left outside README's + historical mention; workflows reference `MCPX_WORKER_*`, + environment `mcpx-production`, concurrency `mcpx-worker-lifecycle`, + artifact `mcpx-worker-upload--`, tag prefix + `mcpx-`. +4. In `pkgs/mcpx/worker`: `npm ci --no-audit --no-fund`, `npm test`, + `npm run typecheck` — all green before PR. (Node v24.21.0 / npm + 11.19.0 verified present on the laptop.) +5. Commit (only `pkgs/mcpx/worker/**` + the three workflow files), + push `lane-mcpx-door-20261123`, open PR: description covers the + door, the adaptations, bare-path equivalence, the filtering seam; + "Part of #13657" — NO closing keywords (#13657 stays open until + live verification). Re-read PR comments immediately before merging; + merge once green. +6. Filtering enforcement: DO NOT invent semantics. `src/filter.ts` + ships architecture-only (selector `ns` parsed once in the router, + `DEFAULT_FILTER_PROFILE = "conservative"`, pass-through + `filterMcpResponse`). The enforcement spec arrives as a follow-up + from the parent; if it lands before the PR merges, implement it in + `filter.ts` + tests in the same PR. + +## Key adaptation values (already encoded in adapt.py) + +- Worker `mcpx`, package `mcpx-worker`, routes `["mcpx.security.cab"]`, + workersDev false, compatibilityDate `2025-09-15` (unchanged). +- ISSUER `https://mcpx.security.cab`, RESOURCE + `https://mcpx.security.cab/mcp`, SCOPE `mcpx`, OWNER_EMAIL unchanged. +- BRIDGE_BASE `https://mcpx-link.security.cab`, ACCESS_TEAM_DOMAIN + `snowy-sun-58a9.cloudflareaccess.com` (unchanged), ACCESS_AUD + `b34b9764fb317774bf5c0ff0ac9cbd8a2ab80ed346d06f08d74967011bac640e`, + KV OAUTH_KV id `11eb93dc9fa24087ae57b12483dc6172`. +- devDeps unchanged: cf 1.0.0-beta.20, wrangler 4.152.0, + @cloudflare/workers-types ^5.20261019.1. diff --git a/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/README.md b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/README.md new file mode 100644 index 000000000..e4d9e96ad --- /dev/null +++ b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/README.md @@ -0,0 +1,124 @@ +# mcpx Worker — public MCP endpoint (#13657) + +The public front door for mcpx at `mcpx.security.cab`, mirroring the +proven desktop-commander Worker build (#13404). Hosted MCP clients +(Claude, ChatGPT) and the owner's own tooling reach the laptop's mcpx +daemon through this Worker; nothing else on the laptop is exposed. + +## Path of a request + +``` +AI client + -> POST https://mcpx.security.cab/mcp (bare https://mcpx.security.cab/ is identical) + Guarded by this Worker's OAuth 2.1 authorization server + (src/oauth.ts). Hosted clients connect from their own servers + and cannot pass a Cloudflare Access login, so /mcp takes a + Bearer token instead — or the machine bearer for the owner's + own tooling. + -> this Worker (src/index.ts): checks the Bearer, computes the + filter selector (src/filter.ts), then proxies the streamable-HTTP + MCP request, swapping the caller's credentials for its own + bridge egress token. + -> https://mcpx-link.security.cab/mcp + Access app "mcpx link (bridge)": service-token-only policy. + -> sandbox-link Cloudflare Tunnel -> http://localhost:8932 on amd + -> the mcpx bridge proxy on 127.0.0.1:8932 + -> the mcpx daemon's /mcp endpoint, discovered via the daemon's + state descriptor +``` + +`workers_dev` is off; `mcpx.security.cab` (a Worker route) is the +only public door. + +## Origin lockdown + +The mcpx daemon listens on loopback only and is unauthenticated — +it trusts its only caller, the local bridge proxy. This door is the +security boundary: it exposes `/mcp` (and its bare-path twin `/`) +only, behind OAuth/machine-bearer auth. The daemon's `/v1/*` API is +never proxied and has no public path. + +## OAuth front door (src/oauth.ts) + +Standard MCP authorization shape, so Claude and ChatGPT can connect: + +- `GET /.well-known/oauth-protected-resource` (and `.../mcp`) and + `GET /.well-known/oauth-authorization-server` — public discovery. +- `POST /register` — dynamic client registration (RFC 7591); public + clients only (`token_endpoint_auth_method: "none"`), redirect URIs + must be https or loopback http. Clients live in the `OAUTH_KV` + namespace under `client:`. +- `GET /authorize` — the approval page, and the ONE path still behind + Cloudflare Access: the "mcpx" Access app is scoped to + `mcpx.security.cab/authorize` with the owner-email policy only + (Google SSO identity). The Worker also verifies the Access JWT + itself (RS256 against the team JWKS, audience, owner email) before + rendering. Approving issues a single-use code (10 min, PKCE S256 + bound) via the form's POST back to `/authorize`. +- `POST /token` — authorization-code exchange (PKCE verified, code + consumed on any attempt) issuing an opaque access token (1 h) and + a rotating refresh token (30 d). Codes and tokens are stored in KV + under their SHA-256 (`code:`, `at:`, `rt:`), + never in the clear. Revoke a client by deleting its `at:`/`rt:` + entries (and its `client:` record) from the namespace. +- `/mcp` (and `/`) without a valid Bearer returns 401 with + `WWW-Authenticate: Bearer resource_metadata="https://mcpx.security.cab/.well-known/oauth-protected-resource"`, + which is what sends hosted clients into the OAuth flow. + +## Filtering (src/filter.ts) + +Architecture in place; enforcement spec pending on #13657. + +- A per-request selector is parsed from the `ns` query parameter in + exactly one place (`resolveFilterSelector` in src/filter.ts), + computed by the router and passed to the proxy/filter layer. +- No selector means the named conservative default profile + (`DEFAULT_FILTER_PROFILE = "conservative"`). +- `ns` is consumed by this door and stripped before proxying; all + other query parameters pass through untouched. +- Until the enforcement spec lands, `filterMcpResponse` is a + pass-through: the selector is threaded end to end so enforcement + can be added in src/filter.ts without touching the router. + +## Secrets — by name only, never values + +| Where | Name | +| --- | --- | +| fleet secrets (Bitwarden) | `cloudflare.access.mcpx-link-client-id` / `-client-secret` — bridge-door token the Worker presents | +| fleet secrets (Bitwarden) | `cloudflare.api-token-mcpx-worker` — scoped deploy token | +| fleet secrets (Bitwarden) | `mcpx.machine-bearer` — the /mcp machine bearer | +| fleet secrets (Bitwarden) | `cloudflare.tunnel.sandbox-link-token` — the sandbox-link tunnel the bridge door rides | +| GitHub environment `mcpx-production` | `MCPX_WORKER_CF_TOKEN` (same deploy token), `BRIDGE_ACCESS_CLIENT_ID`, `BRIDGE_ACCESS_CLIENT_SECRET`, `MACHINE_BEARER` | +| Worker version secrets | `ACCESS_CLIENT_ID`, `ACCESS_CLIENT_SECRET`, `MACHINE_BEARER` — uploaded per version by the publish workflow from the environment secrets | + +## Deploys — cf version deployments via GitHub Actions + +Modeled on the desktop-commander / id-mail publisher-promoter pair: + +1. **Publish** (`mcpx-worker-publish.yml`, manual dispatch on main, + `confirm_upload`): tests, a credential-free dry run, then + `upload-version.mjs` runs `cf workers versions create` with the + Worker secrets file. Uploading changes no traffic. The run emits + a provenance artifact (`mcpx-worker-upload--`) + naming the exact version, tag (`mcpx--run--attempt-`), + and baseline. +2. **Promote** (`mcpx-worker-promote.yml`, manual dispatch with the + publish run id + attempt, `confirm_promotion`): + `verify-upload-run.mjs` vouches the run was a successful manual + publish on main, then `promote.mjs` checks the live deployment + still matches the manifest baseline (or already serves exactly + this version — an idempotent no-op) and creates a deployment with + exactly that version at 100%. + +Tests (`mcpx-worker-tests.yml`) run on pushes and PRs touching this +directory. + +## Client setup + +- Hosted clients (Claude, ChatGPT): add the custom connector + `https://mcpx.security.cab/mcp`; the client registers itself and + sends the owner through the Access sign-in + approval page on + first connection. +- Header-capable clients (Claude Code, Cursor, other mcpx clients): + send `Authorization: Bearer ` (fleet secrets: + `mcpx.machine-bearer`). diff --git a/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/adapt.py b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/adapt.py new file mode 100644 index 000000000..23fca8a6b --- /dev/null +++ b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/adapt.py @@ -0,0 +1,346 @@ +#!/usr/bin/env python3 +"""Adapt the copied desktop-commander Worker package into the mcpx Worker. +Run from the worktree root (~/git/code-mcpx-door-20261123) AFTER: + cp -r pkgs/desktop-commander/worker/. pkgs/mcpx/worker/ (minus node_modules) + cp .github/workflows/desktop-commander-worker-{publish,promote,tests}.yml + .github/workflows/mcpx-worker-{publish,promote,tests}.yml +Idempotent-ish: asserts anchors before replacing; safe to inspect, not to re-run blindly. +""" +import json, pathlib, sys + +ROOT = pathlib.Path.cwd() +PKG = ROOT / "pkgs/mcpx/worker" +assert (PKG / "src/index.ts").exists(), "run from worktree root with the copy in place" + +FILTER_TS = r'''// Per-request filtering seam for the mcpx Worker's /mcp proxy +// (#13657). +// +// ARCHITECTURE ONLY: the enforcement spec (which tools/resources a +// given selector admits) lands separately. Until then this module is +// the one place where filtering decisions will live, and the proxy +// passes every response through filterMcpResponse unchanged. +// +// Selector model: +// - The client picks a selector with the `ns` query parameter on +// /mcp (or /), e.g. POST /mcp?ns=readonly. +// - src/index.ts computes the selector exactly once per request via +// resolveFilterSelector and hands it to the proxy/filter layer. +// - The `ns` parameter is consumed by this door and stripped before +// proxying; it is never forwarded to the bridge/daemon. +// - No `ns` parameter means the conservative default profile below. + +export const DEFAULT_FILTER_PROFILE = "conservative"; + +export interface FilterSelector { + // The raw `ns` value as presented (trimmed), or null when absent. + raw: string | null; + // The effective profile: the raw selector when one was given, + // otherwise DEFAULT_FILTER_PROFILE. + profile: string; +} + +export function resolveFilterSelector(url: URL): FilterSelector { + const raw = url.searchParams.get("ns")?.trim() || null; + return { raw, profile: raw ?? DEFAULT_FILTER_PROFILE }; +} + +// Filter hook for MCP responses coming back from the bridge. +// Pass-through until the enforcement spec lands; the selector is +// threaded through now so enforcement can be added here without +// touching the router or the proxy. +export function filterMcpResponse( + response: Response, + selector: FilterSelector, +): Response { + void selector; + return response; +} +''' + +def sub(path, old, new, count=1): + text = path.read_text() + assert old in text, f"anchor missing in {path}: {old[:80]!r}" + path.write_text(text.replace(old, new, count)) + +# ---------------------------------------------------------------- index.ts +idx = PKG / "src/index.ts" +sub(idx, """// bridge door -> Cloudflare Tunnel -> supergateway on the laptop +// -> the packaged Desktop Commander (stdio) on 127.0.0.1:8931. +// +// The /mcp proxy is a transparent streamable-HTTP proxy: method, path, +// query, headers and body pass through, and the response (including +// the Mcp-Session-Id header and any SSE stream) passes back untouched.""", +"""// bridge door -> sandbox-link Cloudflare Tunnel -> +// http://localhost:8932 bridge proxy on the laptop -> the mcpx +// daemon's /mcp endpoint, discovered via the daemon state +// descriptor. The daemon is loopback-only and unauthenticated; +// this door is its security boundary, and /v1/* is never proxied. +// +// Bare-path equivalence: requests to / are handled exactly as /mcp — +// same auth gate, same proxying (the upstream path is always /mcp). +// +// The /mcp proxy is a transparent streamable-HTTP proxy: method, +// headers and body pass through, and the response (including the +// Mcp-Session-Id header and any SSE stream) passes back untouched. +// The one query parameter the door consumes itself is `ns`: it is +// parsed once, in the router, into a per-request filter selector +// (src/filter.ts), stripped before proxying, and handed to the +// proxy/filter layer; every other query parameter passes through.""") + +sub(idx, '} from "./oauth";', '} from "./oauth";\nimport {\n filterMcpResponse,\n resolveFilterSelector,\n type FilterSelector,\n} from "./filter";') + +old_tail_start = ' if (path !== "/mcp") {' +text = idx.read_text() +start = text.index(old_tail_start) +end_marker = ' const upstream = await fetch(target, init);' +end = text.index(end_marker) +tail_old = text[start:end] +assert 'return json({ error: "not found" }, 404);' in tail_old +assert "isAuthorizedMcpCaller" in tail_old +new_tail = ''' // Bare-path equivalence: / is the same door as /mcp. + if (path !== "/mcp" && path !== "/") { + return json({ error: "not found" }, 404); + } + + if (!(await isAuthorizedMcpCaller(request, env))) { + return new Response(JSON.stringify({ error: "unauthorized" }), { + status: 401, + headers: { + "content-type": "application/json", + "WWW-Authenticate": + 'Bearer resource_metadata="https://commander.security.cab/.well-known/oauth-protected-resource"', + }, + }); + } + if (!env.ACCESS_CLIENT_ID || !env.ACCESS_CLIENT_SECRET) { + return json({ error: "bridge credentials are not configured" }, 500); + } + + // The filter selector is computed in exactly one place — here, + // from the `ns` query parameter — and handed to the proxy/filter + // layer (src/filter.ts). + const selector = resolveFilterSelector(url); + return proxyMcp(request, env, selector); + }, +}; + +// Transparent streamable-HTTP proxy to the bridge door. The upstream +// path is always /mcp (bare-path equivalence), the caller's own +// credentials are swapped for the Worker's bridge egress token, and +// the `ns` selector parameter is consumed here, never forwarded. +export async function proxyMcp( + request: Request, + env: Env, + selector: FilterSelector, +): Promise { + const url = new URL(request.url); + const upstreamParams = new URLSearchParams(url.search); + upstreamParams.delete("ns"); + const query = upstreamParams.toString(); + const target = new URL("/mcp" + (query ? `?${query}` : ""), env.BRIDGE_BASE); + const headers = new Headers(request.headers); + headers.delete("host"); + // The caller's own credentials are for the public door only; the + // bridge door gets the Worker's egress token instead. + headers.delete("authorization"); + headers.delete("cf-access-jwt-assertion"); + headers.delete("cf-access-client-id"); + headers.delete("cf-access-client-secret"); + headers.set("CF-Access-Client-Id", env.ACCESS_CLIENT_ID); + headers.set("CF-Access-Client-Secret", env.ACCESS_CLIENT_SECRET); + + const init: RequestInit = { + method: request.method, + headers, + redirect: "manual", + }; + if (request.method !== "GET" && request.method !== "HEAD") { + init.body = request.body; + } + +''' +text = text[:start] + new_tail + text[end:] +# the original closing of fetch handler + object now follows the upstream +# return; rewrite that ending into the proxyMcp ending +old_ending = ''' const upstream = await fetch(target, init); + return new Response(upstream.body, { + status: upstream.status, + statusText: upstream.statusText, + headers: new Headers(upstream.headers), + }); + }, +}; +''' +new_ending = ''' const upstream = await fetch(target, init); + const response = new Response(upstream.body, { + status: upstream.status, + statusText: upstream.statusText, + headers: new Headers(upstream.headers), + }); + return filterMcpResponse(response, selector); +} +''' +assert old_ending in text, "index.ts ending anchor missing" +text = text.replace(old_ending, new_ending) +idx.write_text(text) + +# ---------------------------------------------------------------- filter.ts +(PKG / "src/filter.ts").write_text(FILTER_TS) + +# ---------------------------------------------------------------- global swaps +SWAPS = [ + ("desktop-commander-worker-publish.yml", "mcpx-worker-publish.yml"), + ("desktop-commander-worker-promote.yml", "mcpx-worker-promote.yml"), + ("desktop-commander-worker-tests.yml", "mcpx-worker-tests.yml"), + ("pkgs/desktop-commander/worker", "pkgs/mcpx/worker"), + ("desktop-commander-production", "mcpx-production"), + ("DESKTOP_COMMANDER_WORKER_CF_TOKEN", "MCPX_WORKER_CF_TOKEN"), + ("DC_WORKER_", "MCPX_WORKER_"), + ("desktop-commander-worker", "mcpx-worker"), + ("desktop-commander-link", "mcpx-link"), + ("commander-link.security.cab", "mcpx-link.security.cab"), + ("commander.security.cab", "mcpx.security.cab"), + ("Desktop Commander", "mcpx"), + ("desktop-commander", "mcpx"), + ('"commander"', '"mcpx"'), + ("c6ddf0a5c0ba8742c0a3c74d12495bf5c4fe9bf6f01f604d62583cb2ed353879", + "b34b9764fb317774bf5c0ff0ac9cbd8a2ab80ed346d06f08d74967011bac640e"), + ("ea675d3c7d5b4f3b9f1cecae82e57d1b", "11eb93dc9fa24087ae57b12483dc6172"), + ("issues/13404", "issues/13657"), + ("#13404", "#13657"), + ("`dc-${sha", "`mcpx-${sha"), +] +targets = [p for p in PKG.rglob("*") if p.is_file() + and p.name not in ("package-lock.json", "README.md") + and "node_modules" not in p.parts] +targets += [ROOT / ".github/workflows/mcpx-worker-publish.yml", + ROOT / ".github/workflows/mcpx-worker-promote.yml", + ROOT / ".github/workflows/mcpx-worker-tests.yml"] +for p in targets: + t = p.read_text() + orig = t + for a, b in SWAPS: + t = t.replace(a, b) + if t != orig: + p.write_text(t) + +lock = PKG / "package-lock.json" +lt = lock.read_text().replace('"name": "desktop-commander-worker"', '"name": "mcpx-worker"') +lock.write_text(lt) + +# ---------------------------------------------------------------- proxy tests +pt = PKG / "test/proxy.test.ts" +sub(pt, 'import worker, { type Env } from "../src/index";', + 'import worker, { type Env } from "../src/index";\nimport { DEFAULT_FILTER_PROFILE, resolveFilterSelector } from "../src/filter";') +with pt.open("a") as f: + f.write(r''' + +function bareRequest(path: string, authorization?: string): Request { + const headers: Record = { + "content-type": "application/json", + accept: "application/json, text/event-stream", + }; + if (authorization) headers["authorization"] = authorization; + return new Request(`https://mcpx.security.cab${path}`, { + method: "POST", + headers, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), + }); +} + +function stubBridge() { + const bridge = vi.fn(async (_url: unknown, _init?: unknown) => { + return new Response("event: message\ndata: {}\n\n", { + status: 200, + headers: { "content-type": "text/event-stream", "mcp-session-id": "session-123" }, + }); + }); + vi.stubGlobal("fetch", bridge); + return bridge; +} + +describe("bare-path equivalence", () => { + it("refuses / without a Bearer exactly like /mcp", async () => { + const bridge = vi.fn(); + vi.stubGlobal("fetch", bridge); + const res = await worker.fetch(bareRequest("/"), env); + expect(res.status).toBe(401); + expect(res.headers.get("www-authenticate")).toBe( + 'Bearer resource_metadata="https://mcpx.security.cab/.well-known/oauth-protected-resource"', + ); + expect(bridge).not.toHaveBeenCalled(); + }); + + it("proxies / to the bridge /mcp with the egress token", async () => { + const bridge = stubBridge(); + const res = await worker.fetch(bareRequest("/", "Bearer machine-bearer-for-tests"), env); + expect(res.status).toBe(200); + expect(bridge).toHaveBeenCalledTimes(1); + const [calledUrl] = bridge.mock.calls[0] as unknown as [URL, RequestInit]; + expect(String(calledUrl)).toBe("https://mcpx-link.security.cab/mcp"); + }); + + it("consumes the ns selector and forwards other query parameters", async () => { + const bridge = stubBridge(); + const res = await worker.fetch( + bareRequest("/mcp?ns=readonly&x=1", "Bearer machine-bearer-for-tests"), + env, + ); + expect(res.status).toBe(200); + const [calledUrl] = bridge.mock.calls[0] as unknown as [URL, RequestInit]; + expect(String(calledUrl)).toBe("https://mcpx-link.security.cab/mcp?x=1"); + }); + + it("bare / with a selector still lands on upstream /mcp", async () => { + const bridge = stubBridge(); + const res = await worker.fetch( + bareRequest("/?ns=readonly", "Bearer machine-bearer-for-tests"), + env, + ); + expect(res.status).toBe(200); + const [calledUrl] = bridge.mock.calls[0] as unknown as [URL, RequestInit]; + expect(String(calledUrl)).toBe("https://mcpx-link.security.cab/mcp"); + }); +}); + +describe("filter selector", () => { + it("defaults to the named conservative profile without ns", () => { + const selector = resolveFilterSelector(new URL("https://mcpx.security.cab/mcp")); + expect(selector.raw).toBeNull(); + expect(selector.profile).toBe(DEFAULT_FILTER_PROFILE); + expect(DEFAULT_FILTER_PROFILE).toBe("conservative"); + }); + + it("uses the ns value as the profile when present", () => { + const selector = resolveFilterSelector(new URL("https://mcpx.security.cab/mcp?ns=readonly")); + expect(selector.raw).toBe("readonly"); + expect(selector.profile).toBe("readonly"); + }); +}); +''') + +# ---------------------------------------------------------------- checks +cfg = json.loads((PKG / "config.json").read_text()) +assert cfg == {"compatibilityDate": "2025-09-15", "routes": ["mcpx.security.cab"], + "worker": "mcpx", "workersDev": False}, cfg +for name in ("wrangler.toml", "cloudflare.config.ts"): + t = (PKG / name).read_text() + assert "b34b9764fb317774bf5c0ff0ac9cbd8a2ab80ed346d06f08d74967011bac640e" in t, name + assert "11eb93dc9fa24087ae57b12483dc6172" in t, name + assert "https://mcpx-link.security.cab" in t, name +pkg = json.loads((PKG / "package.json").read_text()) +assert pkg["name"] == "mcpx-worker", pkg["name"] +assert pkg["devDependencies"]["cf"] == "1.0.0-beta.20" +assert pkg["devDependencies"]["wrangler"] == "4.152.0" +assert pkg["devDependencies"]["@cloudflare/workers-types"] == "^5.20261019.1" +for p in targets: + t = p.read_text() + assert "desktop-commander" not in t, f"leftover in {p}" + assert "commander.security.cab" not in t.replace("mcpx.security.cab", ""), f"leftover domain in {p}" +oauth = (PKG / "src/oauth.ts").read_text() +assert 'ISSUER = "https://mcpx.security.cab"' in oauth +assert 'RESOURCE = "https://mcpx.security.cab/mcp"' in oauth +assert 'SCOPE = "mcpx"' in oauth +assert 'OWNER_EMAIL = "drewrypope@gmail.com"' in oauth +print("adapt.py: all substitutions + checks OK") +print("NOTE: install README.md from the companion file (workspace mcpx-door-20261123/README.md) over pkgs/mcpx/worker/README.md") diff --git a/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/filter.ts b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/filter.ts new file mode 100644 index 000000000..5fedbbb3c --- /dev/null +++ b/doc/2026-11-24T02-09-07Z_research_mcpx-door-20261123/filter.ts @@ -0,0 +1,43 @@ +// Per-request filtering seam for the mcpx Worker's /mcp proxy +// (#13657). +// +// ARCHITECTURE ONLY: the enforcement spec (which tools/resources a +// given selector admits) lands separately. Until then this module is +// the one place where filtering decisions will live, and the proxy +// passes every response through filterMcpResponse unchanged. +// +// Selector model: +// - The client picks a selector with the `ns` query parameter on +// /mcp (or /), e.g. POST /mcp?ns=readonly. +// - src/index.ts computes the selector exactly once per request via +// resolveFilterSelector and hands it to the proxy/filter layer. +// - The `ns` parameter is consumed by this door and stripped before +// proxying; it is never forwarded to the bridge/daemon. +// - No `ns` parameter means the conservative default profile below. + +export const DEFAULT_FILTER_PROFILE = "conservative"; + +export interface FilterSelector { + // The raw `ns` value as presented (trimmed), or null when absent. + raw: string | null; + // The effective profile: the raw selector when one was given, + // otherwise DEFAULT_FILTER_PROFILE. + profile: string; +} + +export function resolveFilterSelector(url: URL): FilterSelector { + const raw = url.searchParams.get("ns")?.trim() || null; + return { raw, profile: raw ?? DEFAULT_FILTER_PROFILE }; +} + +// Filter hook for MCP responses coming back from the bridge. +// Pass-through until the enforcement spec lands; the selector is +// threaded through now so enforcement can be added here without +// touching the router or the proxy. +export function filterMcpResponse( + response: Response, + selector: FilterSelector, +): Response { + void selector; + return response; +} diff --git a/doc/README.md b/doc/README.md index 9d4c8a6de..592ddef20 100644 --- a/doc/README.md +++ b/doc/README.md @@ -216,6 +216,7 @@ Two names break the pattern. They stay as they are because other documents link - [OpenCode research — usage surfaces and the event system](2026-11-24T02-09-40Z_research_opencode-research/2026-11-24T02-09-40Z_research_opencode-research.md) — the 2026-10-20 OpenCode research notes: OpenAI usage-surface interactions (Codex, Chat, Work, API, Dots, Astra, Ultrafast) and the OpenCode event system (tracking #13877). - [Iroh investigation research corpus](2026-11-24T02-11-50Z_research_iroh-investigation/2026-11-24T02-11-50Z_research_iroh-investigation.md) — the 2026-11-23 iroh source set (protocol census, real-projects and community review, blog-chunk working files); the blog catalogue and talks files are living documents in `doc/living/iroh/` (tracking #13877). - [Cloudflare research — Workers, costs, containers and prototypes](2026-11-24T02-42-57Z_research_cloudflare/2026-11-24T02-42-57Z_research_cloudflare.md) — the 2026-10-20 Cloudflare research series (Workers Paid, free tiers, paid-only, declarative infra, multiple-plans ToS, containers-vs-DO costs, DO practices) plus ideas, project README, magic-environment note and the two prototype READMEs; code stays in hatch-personal (tracking #13877). +- [mcpx door build record](2026-11-24T02-09-07Z_research_mcpx-door-20261123/2026-11-24T02-09-07Z_research_mcpx-door-20261123.md) — dated record of the 2026-11-23 mcpx door build (public MCP endpoint at `mcpx.security.cab`, part of #13657): door README, lane continuation brief, `adapt.py` and `filter.ts`, copied byte-for-byte (tracking #13877). ## Legacy places