Skip to content

Expose the document API to agents over MCP - #2

Merged
afternoon merged 4 commits into
mainfrom
claude/mcp-authenticated-tool-b78f5x
Aug 31, 2026
Merged

afternoon merged 4 commits into
mainfrom
claude/mcp-authenticated-tool-b78f5x

Conversation

@afternoon

@afternoon afternoon commented Aug 31, 2026 •

Copy link
Copy Markdown
Owner

POST /api/mcp serves the document API to agents, behind an OAuth 2.1 access token. Six tools — list_documents, get_document, create_document, update_document, rename_document, delete_document — each a thin call into src/server/documents.ts, so agents get exactly what the browser gets: the same ownership clause in every query, the same sanitiser on every write, the same 404 for someone else's document.

Rendering is not a tool, per the discussion. Browser Run is 10 minutes a day on the free plan and an agent would spend that far faster than a person pressing Preview; /api/render is still there for anything that wants a PDF.

The flow

An agent starts from a refusal and discovers the rest — nothing is configured on its side beyond the URL.

  1. Unauthenticated POST /api/mcp → 401 with WWW-Authenticate: Bearer resource_metadata="…" (RFC 9728).
  2. /.well-known/oauth-protected-resource/api/mcp names the resource, scopes, and authorization server.
  3. /.well-known/oauth-authorization-server/api/auth describes the endpoints.
  4. Dynamic registration (RFC 7591), then /oauth2/authorize with PKCE and resource= (RFC 8707).
  5. Signed out → /login; signed in → /consent.
  6. Code → JWT access token, aud = the MCP resource, sub = the user id, which is what every tool passes to the queries.

Three decisions worth review

Registration is open. Agents arrive with no client id and nobody is standing by to issue one, so the flow is unusable otherwise. I originally recommended Client ID Metadata Documents instead; that turned out not to be implementable here — CIMD requires a fetch transport that resolves DNS once, rejects RFC 6890 special-use addresses and pins the resolved address for the connection, and Workers exposes none of that. Implementing it incorrectly would be worse than not claiming it.

That makes the consent screen the whole trust boundary, so src/ConsentPage.tsx presents the client's name as a claim rather than a fact — an app can register under any name it likes.

Scopes gate tool registration, not tool execution. A token carrying only documents:read gets a server on which the write tools were never registered, so tools/list describes what that token can actually do instead of advertising three tools that would always fail. There is no authorization error path in a tool because there is no tool to reach.

legacy: "reject" has a compatibility cost. The MCP client SDK negotiates the 2025 handshake by default, so an agent that has not opted into modern version negotiation cannot connect at all. e2e/mcpFlow.test.ts pins that behaviour so the trade is written down. The alternative, legacy: "stateless", serves 2025 clients through the same factory — same tools, same auth — so the drift concern that motivated reject is weaker than it first looked. Happy to flip it if you'd rather have the compatibility.

What the end-to-end test found

e2e/ runs the real app under vite dev (workerd via the Cloudflare plugin) and drives /api/mcp over HTTP with the real MCP client SDK — discovery, dynamic registration, PKCE, the resource indicator and the request envelope are all the SDK's code, so the test fails if we're interoperable only with ourselves. One step is substituted, and only one: signing in with Google, which no test can drive; globalSetup writes a session row and signs the cookie, and approve.ts then walks the authorize redirect and answers consent the way the consent page does.

It found a real defect on its first run. The MCP client requests exactly the scopes the WWW-Authenticate challenge names and never asks for more, and challengeScopes was defaulting to requiredScopes — so every agent was capped at documents:read and the write tools were unreachable in practice. The endpoint now advertises what the resource offers while still insisting only on read. No unit test could have caught this: they construct the server with whatever scopes they choose, so the advertisement was never exercised.

Things that came along

  • migrations/0004_oauth_provider.sql is derived from the plugins' own schema, not hand-written and not from @better-auth/cli generate — that CLI's latest release is 1.4.x and predates the OAuth provider plugin. src/server/authSchema.test.ts re-derives the schema on every run and checks the SQL against it, so a library upgrade that adds a column fails a test rather than a deploy.
  • postinstall made the typecheck depend on an untracked file. It runs wrangler types, which regenerated the committed worker-configuration.d.ts by inferring bindings from .dev.vars — so any fresh clone without one lost the four secret bindings and tsc failed on correct code. CI hit this the moment it was switched on. Fixed by declaring them under secrets.required in wrangler.jsonc; the generated file is byte-identical either way.
  • src/server/documents.test.ts was already failing on main: the jsdom environment cannot bundle node:sqlite. Server tests now opt into the node environment with a pragma. Its D1-over-SQLite helper moved to src/server/testDatabase.ts so the new tests share it.
  • src/App.test.tsx was also already failing on main: it built its fake render response from a jsdom Blob, which undici's Response rejects with object.stream is not a function — so every render in that file was failing and the two tests asserting on the error overlay were the only ones that noticed.
  • The end-to-end run drops the jwks row first. Better Auth encrypts the JWKS private key with BETTER_AUTH_SECRET, so a key left by a run under a different secret can't be decrypted and token signing fails with an opaque 500 — which is what you'd hit the first time you add a .dev.vars after running the suite without one.
  • e2e/ is now covered by tsconfig and biome, which caught a type error in the agent while it was being written.

Testing

bun run test runs everything; test:unit and test:e2e run the suites separately. CI (.github/workflows/ci.yml) runs bun run check and bun run test on every push and pull request, and needs no secrets — the end-to-end suite starts its own server, applies its own migrations, and falls back to the variables in e2e/environment.ts when there is no .dev.vars.

384 tests green (372 unit, 12 end-to-end), locally and on CI. check and build clean. The end-to-end suite was also verified from a completely clean checkout — no .dev.vars, no .wrangler state — and across a secret change between consecutive runs.

Follow-ups not in scope here

  • No rate limiting specific to /api/mcp beyond what Better Auth applies to its own endpoints.
  • No UI for reviewing or revoking connected apps; the oauthConsent rows and the provider's revoke endpoint exist, but nothing surfaces them.
  • actions/setup-node@v4 logs a Node 20 deprecation warning. It works today; bumping to v5 is a one-line change.

POST /api/mcp serves six tools — list, get, create, update, rename,
delete — each a thin call into server/documents.ts. Agents get exactly
what the browser gets: the same ownership clause in every query, the
same sanitiser on every write, the same 404 for someone else's
document.

Authorization is OAuth 2.1, via @better-auth/mcp alongside the Google
sign-in that was already there. An agent starts from a 401 and
discovers the rest: protected resource metadata, authorization server
metadata, dynamic registration, then PKCE and a resource-bound JWT
whose sub is the user id.

Two scopes that are real rather than decorative. A token carrying only
documents:read gets a server on which the write tools are never
registered, so tools/list describes what that token can actually do.

Registration is open because agents arrive with no client id and
nobody is standing by to issue one. Client ID Metadata Documents would
be the stronger option but cannot be implemented correctly here: they
need a transport that resolves DNS once, rejects special-use addresses
and pins the resolved address, and Workers exposes none of that. The
consent screen therefore carries the whole decision, and says the
client's name is unverified rather than presenting it as fact.

Rendering is deliberately not a tool. Browser Run is 10 minutes a day
on the free plan and an agent would spend that far faster than a
person pressing Preview.

Two smaller things came with it. The migration for the provider tables
is derived from the plugins' own schema rather than by hand — the
Better Auth CLI's latest release predates the OAuth provider plugin —
and authSchema.test.ts re-derives it every run so an upgrade that adds
a column fails a test rather than a deploy. And documents.test.ts was
failing before this change: the jsdom environment cannot bundle
node:sqlite, so server tests now opt into the node environment.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HrBY6QD6ECPUwvQMdAqbfa
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
htmlcsspdf 3101c52 Commit Preview URL

Branch Preview URL
Aug 31 2026, 08:52 PM

claude and others added 3 commits August 31, 2026 17:02
e2e/ runs the real app under vite dev — workerd through the Cloudflare
plugin — and drives /api/mcp over HTTP with the real MCP client SDK, so
discovery, dynamic registration, PKCE, the resource indicator and the
2026-07-28 envelope are performed by the same code an agent runs rather
than by our own idea of it.

One step is substituted, and only one: signing in with Google, which no
test can drive. globalSetup writes a session row and signs the cookie,
and approve.ts then walks the authorize redirect and answers consent the
way the consent page does. The run applies its own migrations, creates
two throwaway people with random ids, and starts and stops its own
server; with no .dev.vars, as on a runner, the Worker falls back to the
variables in e2e/environment.ts.

It found a real defect immediately. The MCP client requests exactly the
scopes the WWW-Authenticate challenge names and never asks for more, and
challengeScopes was defaulting to requiredScopes — so every agent was
capped at documents:read and the write tools were unreachable in
practice. The endpoint now advertises what the resource offers while
still insisting only on read.

It also pins a cost that was previously undocumented: legacy: "reject"
turns away the client SDK's default negotiation, so an agent must opt
into the modern protocol to connect at all.

Two things came along. src/App.test.tsx built its fake render response
from a jsdom Blob, which undici's Response rejects with "object.stream is
not a function" — so every render in that file was failing and the two
tests asserting on the error overlay were the only ones that noticed;
those were red on main. And e2e/ is now covered by tsconfig and biome,
which is what caught a type error in the agent while writing it.

test now runs both suites; test:unit and test:e2e run them separately.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HrBY6QD6ECPUwvQMdAqbfa
CI failed on its first run, and the failure was real: postinstall runs
`wrangler types`, which regenerates the committed
worker-configuration.d.ts by inferring bindings from .dev.vars. That file
is gitignored, so a fresh clone regenerates the types without the four
secrets and tsc then fails on correct code. Declaring them under
`secrets.required` in wrangler.jsonc makes generation depend on the
config instead; the generated file is byte-identical either way.

The end-to-end suite now drops the jwks row before it runs. Better Auth
encrypts the JWKS private key with BETTER_AUTH_SECRET, so a key left by a
run under a different secret cannot be decrypted and token signing fails
with an opaque HTTP 500 — which is what a contributor hits the first time
they add a .dev.vars after running the suite without one. Keys are
regenerated on demand, so this costs nothing and makes the run
self-healing.

Verified in both conditions, and across a secret change between
consecutive runs, which is what reproduced the 500.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HrBY6QD6ECPUwvQMdAqbfa
@afternoon
afternoon marked this pull request as ready for review August 31, 2026 20:51
@afternoon
afternoon merged commit 4e3c4f4 into main Aug 31, 2026
1 of 2 checks passed
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.

2 participants