phuryn/product-engineering / app-stack/skills/mcp-server
mcp-server
VerifiedBefore adding a remote MCP server or tool to a web product, adding OAuth to it, or listing it in a directory: ship it right the first time, tests included.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 10.3 KB |
| receipts.md | markdown | 1.6 KB |
| references/clients.md | markdown | 6.6 KB |
| references/companion-repo.md | markdown | 10.4 KB |
| references/directories.md | markdown | 18.7 KB |
| references/server.md | markdown | 18.4 KB |
| references/tools.md | markdown | 17.3 KB |
references/server.md
View on GitHub# The server: who may call it, the route, its limits and its log
On this stack the server is a route under `src/app/`, with its own auth, call-log and protected-resource modules beside the app's other server code and the discovery documents under `src/app/.well-known/`; what it accepts and returns is written in the product's API contract. Clerk's settings are `clerk-production` § MCP OAuth.
## Who may call it
**The default is one server on which every call is authenticated, `initialize` included**: a Clerk OAuth access token, or a workspace API token (`prefix_<kid>.<secret>`, stored as a peppered hash: `saas-authorization § Leaked tokens and credentials`), told apart by the token's prefix and checked before the body is read. Directories list and score such a server without trouble: Smithery's scanner signs in over OAuth, Glama's connector check uses a token from a test organization, and an awesome list's probe reads the `401` as "OAuth" (October 2026). Of the directories listed in `references/directories.md`, only OpenAI's plugin directory, for a plugin without sign-in, needed an unauthenticated `tools/list`.
**An anonymous surface is a product decision, recorded in the product's decision log with its costs.** The example here is a ChatGPT plugin that lets a ChatGPT user make a live Q&A room with no account. What it cost:
- **A new kind of caller.** The authorization model (`saas-authorization § Two credentials, never mixed`) has two credentials, a member session and an anonymous cookie, never mixed, and a platform's statement about its own user is neither. Give it an entry of its own beside them, in the product's agent instructions and its permissions doc, that says what it is and what it is not ("not a fourth browser credential"): one route, admitted only from the platform's published ranges, the platform's anonymized user id as the identity, an anonymous workspace owned through an id of its own, a separate and shorter list of tools, and browser work through a one-time link.
- **The identity has to come from the platform.** OpenAI's anonymized user id, `_meta["openai/subject"]`, is OpenAI's statement only when the request comes from OpenAI's published connector ranges (`https://openai.com/chatgpt-connectors.json`; refresh it hourly, keep the previous list through a failed refresh, which is anything but a `200` whose list parses, and with none refuse every call). So a tool call is answered only from those ranges and refused `403` everywhere else. Check that ChatGPT's calls pass it from every surface you test on: a developer-mode connector's, over IPv4, did not (2026-10-27, the `chatgpt-plugin` skill). Opened to any caller, every caller collapses into one identity, with shared rooms, limits and host links: it is not a flag flip.
- **Gate the tool call, not the endpoint: discovery answers anyone.** OpenAI's plugin portal scans the server from outside the connector ranges. An endpoint that refused everything from outside them got "Authorization required … so we can discover its tools" in the portal, which then would not submit the draft ("Scan tools before submitting", October 2026). `initialize`, `ping`, `tools/list` and notifications return the public tool list and read nobody's data, so they answer anyone; `tools/call` stays in range. Three tests hold it: an outsider lists the tools; an outsider's call carrying a forged subject gets `403` and creates nothing; and every MCP method sent from outside answers exactly when the privacy page says it works from anywhere, so opening a method fails the suite until the page says so.
- **Declare it as having no sign-in before the first upload, and never complete an OAuth sign-in for it.** OpenAI's portal reads a plugin's authentication from the uploaded package's `mcp.json`, and an existing connection can lock it. A package that declared nothing, on a domain whose root protected-resource document named the authenticated server (§ The route), was taken for OAuth, and once its owner signed in only a new plugin undid it (October 2026). The declaration is `extensions["com.openai"].auth.type: "none"`; the full account is the `chatgpt-plugin` skill's. An address gate on tool calls is not a sign-in, and a server that does require sign-in is never declared `none`.
- **The address checked must be the caller's.** The gate trusts the connection address the host reports. When one product's domain moved to Cloudflare with the proxy on, Netlify saw Cloudflare's edge as every caller: ChatGPT's own connector check was refused ("MCP server refused access") and every per-IP limit fell on a few shared edge addresses, while every page still answered `200` (October 2026). Keep the records that point at the host DNS-only, and Clerk's custom-domain records too (`clerk.`, `accounts.`, `clkmail.` and the two `clk*._domainkey.` CNAMEs): lost or proxied in the same move, they took sign-in down in production, and with it the OAuth sign-in every MCP client goes through, while every page still answered `200` (`clerk-production`, gotchas: watch the sign-in host from outside). Trust a proxy's client-IP header (`cf-connecting-ip`) only on an origin that refuses traffic not sent through that proxy: anyone else can set it.
- **It is a second front door**, with its own workspace kind, its own daily limits, a lifetime (rooms that close 48 hours after they open, in the example) and an abuse surface, none of which the authenticated server needed.
- **A test mode that must never reach production.** Off the platform no subject arrives, so local evals need a flag that admits any caller, in which anyone can claim any user's data. Put it behind its own flag beside the one that enables the surface; apply the `environments` skill's loopback app-URL guard in the env schema, unit-tested both ways under `NODE_ENV=production`. Name both in the listing's pre-submission list: the surface enabled in production, the test mode unset.
- **A disclosure burden the listing enforces.** OpenAI rejected a plugin's first version for returning identifiers the request did not need, and fields the privacy page did not name, "including nested and debug data" (the `chatgpt-plugin` skill).
- **No sign-in rule for writes, but confirmation for what cannot be undone.** Read on 2026-10-26, OpenAI's guidelines and security guide do not ask tools that write to authenticate; they ask for human confirmation before irreversible operations, which the host gives for a tool marked destructive.
A product that declines the surface serves the no-account case through the client's own sign-in prompt (`§ The first call`). Its reopen trigger is the one to copy: **a directory or client that matters can only list servers that answer without sign-in.**
**Who may connect.** **An admitted OAuth caller gets the full grant a new API token carries, in exactly one workspace.** So admit by the permission that mints such a token, through the three functions, and check it on every request against live membership with no membership cache, so a demotion takes effect on the next call; offline JWT verification cannot see a revoked grant until the token expires (`clerk-production § MCP OAuth`). Never admit by a role compared by name, or by a neighbouring permission the same role happens to hold today. Example: gating on an admin-only token permission refuses a moderator who signs in, as intended; gating on a read permission and then granting write admits admins only while one role holds every permission, and the day a second role is given that read permission, its members get write through OAuth. A token may be narrower than OAuth (read-only tokens minted before writes shipped, or tokens minted read-only on purpose), so never copy a token's scope onto OAuth, or OAuth's onto every token. A caller without the permission gets `403` with a sentence that says why ("You are not an administrator of the organization selected for this connection."), never a narrower connection.
## The first call
In the organization shape the token's `org_id` names a Clerk organization, and the product's own workspace row may not exist yet.
- **Refuse a missing workspace by default and point to the dashboard.** Return `403 organization_not_found` with "Open your organization's dashboard before connecting."
- **Provision on the first authorized call only when the owner chooses agent-started sign-up.** Turn on *Membership required* and *Create first organization automatically* (`organization_creation_defaults.automatic_organization_creation` in Clerk's organization settings). The OAuth consent screen can then ask for the new organization. Verify the token, spend the admission budget and confirm live membership and the admission permission before creating the workspace row. Use the same function a first dashboard visit runs. Prove the path with a fresh sign-up that completes a tool call against the product's real instance.
## The route
- **Stateless Streamable HTTP, JSON replies.** `POST` runs messages; no session id, no SSE stream, no batches (a JSON-RPC array is refused as an invalid request and logged as `batch_unsupported`), no resources or prompts. Protocol versions `2025-11-25` and `2025-06-18`; `initialize` answers the client's version when supported and the newest otherwise, and an `MCP-Protocol-Version` header outside the list is `400 unsupported_protocol`. That `400` is what ChatGPT falls back on: it opens with `MCP-Protocol-Version: 2026-07-28` and an `Mcp-Method` header, and on the refusal sends a classic `initialize` without the header, asking for `2025-11-25` (2026-10-27). Log the refused version and the `Mcp-Method` value, both safe to keep: before they were logged, one product could not say what ChatGPT's refused first request had been.
- **Every request's `params` may carry `_meta`, and the route accepts it.** The specification reserves it on every request, and ChatGPT sends hints there on every tool call (an anonymized user and conversation, a coarse location, trace and call ids: twelve keys on one OAuth connector's call, 2026-10-27), and OpenAI documents a locale on `initialize`. A `params` schema that refuses unknown keys would answer each of those calls `-32602`: one product's would have, found in its code and fixed just before ChatGPT's first call, because no other client had sent `_meta` (October 2026). Be strict about `arguments`, never about `params`, keep none of the hints unless the privacy page names them, and hold it with a test that sends `_meta` on `initialize` and `tools/call`.
- **Headers are checked before the body**: `Content-Type: application/json` (else `415`), `Accept` naming both `application/json` and `text/event-stream` (else `406`), and a body read through the app's one bounded body reader (`saas-authorization § Untrusted text`; 16 to 64 KB is plenty, `413` past it).
- **`GET` and `OPTIONS` without credentials get the same `401` and challenge as `POST`**, so a native client that probes first still discovers sign-in; with credentials they get `405` and `Allow: POST`. `DELETE`, `PUT` and `PATCH` are `405` without reading a credential.
- **Every `401` carries** `WWW-Authenticate: Bearer resource_metadata="<APP_URL>/.well-known/oauth-protected-resource/<path>"`, plus `error="invalid_token"` when a credential was presented.
- **Discovery is public, CORS `*`, cached an hour**: the protected-resource document at the path-specific URL and at the root alias, both naming the exact endpoint; `/.well-known/oauth-authorization-server` relays Clerk's own document after checking its issuer, and answers an uncached `502` when Clerk cannot be read. `@clerk/mcp-tools` (0.6.0) supplies good handlers for these documents; its `verifyClerkToken` drops `org_id`, so it is not the verification seam. **The root alias speaks for the whole domain**: a client that finds no document for another path on the same host falls back to it, which is how a plugin on the same domain whose package declared no authentication was offered the product's own sign-in (`§ Who may call it`).
- **The MCP route grants no CORS.** Native clients and server-side transports are in scope; a cross-origin browser client is not. A request with no fetch metadata and no `Origin` is a native client and is judged by its bearer alone; one that carries either must be same-origin by the app's origin check (`saas-authorization § Untrusted text`: read `Sec-Fetch-Site` first), never by a value derived from `Host`.
- **`/.well-known/**` and the MCP path bypass the session middleware**; the route authenticates the bearer itself and never reads a Clerk cookie.
## Errors: three layers
| Layer | When | Shape |
|---|---|---|
| HTTP | authentication, organization, membership, rate, negotiation, size | the product's error object, `{"error":{"code","message"}}`, with `WWW-Authenticate` on `401` and `Retry-After` on `429` |
| JSON-RPC | malformed JSON, invalid request, unknown method, unknown tool, invalid tool arguments | a standard JSON-RPC error (`-32700`, `-32600`, `-32601`, `-32602`) |
| Tool | the call ran and the product refused it: not found, a limit, a lifecycle state | HTTP 200, `isError: true`, the error object as text, **no `structuredContent`** |
The difference between `401` and `503` matters most. A verifier or membership outage is `503 authorization_unavailable`, never `401`: a `401` sends the client back through the whole OAuth flow, which cannot repair an outage (`clerk-production § MCP OAuth`). A budget refused inside `tools/call` follows the tool layer; carry `retry_after` in the error object there as well as the `Retry-After` header.
## Limits
- **An admission budget per verified user, spent before the membership lookup**, keyed on the user alone, not the client: registration is open (DCR and CIMD), so a client id costs nothing to mint, and a refused member could otherwise multiply live Clerk lookups. Where it sits depends on whether the workspace row can be missing: a product that refuses a missing workspace can count the user inside the workspace; one that creates the row on the first call counts the user alone, before the organization checks, the membership lookup and the insert. Something like 60 to 120 a minute. Then the product's ordinary per-actor budget for admitted calls. Refreshing a token resets neither.
- **One workspace budget shared by MCP, REST, every token and every OAuth client** (for example 30 a minute on a free plan, 120 on a paid one) is simpler to explain on a pricing page than one per surface.
- **The unauthenticated path is still open, and a listing advertises it.** Invalid credentials spend no actor budget, and every refused request writes a log row, so a flood of garbage bearers costs a function call and an insert each. An edge backstop must be set high, because Claude's and ChatGPT's servers call from shared addresses; on Netlify it is a rate-limit rule, and the Free, Starter and Personal plans allow two code-based rules where Pro and Enterprise allow five. An invalid rule is logged and the deploy still succeeds (`saas-authorization § Abuse and floods`), so read the deploy log. Decide it before the first listing, not after.
## The per-call log
One row for every request that reaches a handler on the REST API and every MCP route, refused ones included. It is the only record of which clients and directories actually call the server; nothing reads it at runtime.
- **One function writes every row**, so no surface can drift; the auth functions report the caller as they establish it, so a request refused for scope, organization or rate still says who it was.
- **Columns**: time, source, auth kind, JSON-RPC method (or HTTP method and route pattern), tool, workspace, a countable actor (the token's row id, or a keyed hash of the OAuth or platform user), the Clerk user and organization for signed-in callers, a client label, status, outcome (`ok`, or the error code, including a tool error inside a 200 and each JSON-RPC refusal), duration.
- **The client label comes from the verified OAuth `client_id` first**, then `initialize`'s `clientInfo`, then the `User-Agent`; `clientInfo` is the client's own claim, so it never attributes a write.
- **No arguments, content, addresses or tokens.** Retention is a number the privacy page states and a test holds equal to the job that enforces it (13 months is a reasonable default).
- **Written after the response**, by Next's `after()`, so logging never delays or changes a reply; a failed write is counted and dropped. On Netlify that needs the runtime's `waitUntil`: a post-deploy smoke finds its own call's row.
- **To learn what a client sends, add a temporary shape, never values**: header names, `params` and `params._meta` key names, `clientInfo`, the protocol versions, the token's age and scope names, and whether the caller's address is in the platform's published ranges as a yes or no. Names are the caller's text too, so one that looks like an address, an id, a UUID or a key is logged as `?`. Subtract the host's own headers when reading it (Netlify adds about twenty: `x-nf-*`, `x-country`, `x-forwarded-*`). Give it an end date that the privacy page states in the same change (one product's, October 2026).
- **A diagnostic never costs the row.** If the database refuses the extra field, write the row without it, but retry only on an error that proves nothing was written (an unknown column, a check violation): after any other, the first write may have committed, and a retry doubles it.
- The queries the owner runs (calls per tool per day, distinct callers per week, by client, by outcome) live in the product's operations doc.
## Proving it
- **Prove a real Clerk OAuth grant outside the gate.** A script drives a real DCR registration, S256 PKCE, Clerk's sign-in and consent with an explicit choice between two organizations, the code exchange, and `tools/list` through Playwright against localhost. It refuses anything but test keys and a development database, prints only allowlisted claims, statuses and tool names, and deletes the client and the extra organization afterwards. It is how one product learned that Clerk's access token carries `client_id` and `scope`, which Clerk's discovery omits, beside the selected `org_id`.
- **Have the owner prove the endpoint with one real client against production.** Record the client, date and what was called in the product's distribution record (`references/clients.md`).
- **After every deploy**: discovery returns `200` from all three documents, an unauthenticated `POST` to the member endpoint is `401` with the path-specific metadata URL and no `invalid_token`, and the log holds the smoke's own row. An anonymous surface instead answers `tools/list` from outside; its refused tool call is held by the development tests in § Who may call it.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |