Repository navigation
Expose the document API to agents over MCP - #2
Merged
Merged
Conversation
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
Deploying with
|
| 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 |
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
POST /api/mcpserves 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 intosrc/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/renderis 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.
POST /api/mcp→401withWWW-Authenticate: Bearer resource_metadata="…"(RFC 9728)./.well-known/oauth-protected-resource/api/mcpnames the resource, scopes, and authorization server./.well-known/oauth-authorization-server/api/authdescribes the endpoints./oauth2/authorizewith PKCE andresource=(RFC 8707)./login; signed in →/consent.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.tsxpresents 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:readgets a server on which the write tools were never registered, sotools/listdescribes 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.tspins 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 motivatedrejectis 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 undervite dev(workerd via the Cloudflare plugin) and drives/api/mcpover 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;globalSetupwrites a session row and signs the cookie, andapprove.tsthen 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-Authenticatechallenge names and never asks for more, andchallengeScopeswas defaulting torequiredScopes— so every agent was capped atdocuments:readand 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.sqlis 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.tsre-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.postinstallmade the typecheck depend on an untracked file. It runswrangler types, which regenerated the committedworker-configuration.d.tsby inferring bindings from.dev.vars— so any fresh clone without one lost the four secret bindings andtscfailed on correct code. CI hit this the moment it was switched on. Fixed by declaring them undersecrets.requiredinwrangler.jsonc; the generated file is byte-identical either way.src/server/documents.test.tswas already failing onmain: the jsdom environment cannot bundlenode:sqlite. Server tests now opt into the node environment with a pragma. Its D1-over-SQLite helper moved tosrc/server/testDatabase.tsso the new tests share it.src/App.test.tsxwas also already failing onmain: it built its fake render response from a jsdomBlob, which undici'sResponserejects withobject.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.jwksrow first. Better Auth encrypts the JWKS private key withBETTER_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.varsafter 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 testruns everything;test:unitandtest:e2erun the suites separately. CI (.github/workflows/ci.yml) runsbun run checkandbun run teston 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 ine2e/environment.tswhen there is no.dev.vars.384 tests green (372 unit, 12 end-to-end), locally and on CI.
checkandbuildclean. The end-to-end suite was also verified from a completely clean checkout — no.dev.vars, no.wranglerstate — and across a secret change between consecutive runs.Follow-ups not in scope here
/api/mcpbeyond what Better Auth applies to its own endpoints.oauthConsentrows and the provider's revoke endpoint exist, but nothing surfaces them.actions/setup-node@v4logs a Node 20 deprecation warning. It works today; bumping tov5is a one-line change.