← Blog
Article

How to Build a Remote MCP Server with OAuth on Cloudflare Workers

A practical guide to building a remote MCP server with OAuth sign-in on Cloudflare Workers, taken from the four MCP servers Nordbeam runs in production.
11 min readMCPOAuthCloudflare WorkersAI Agents

By Assim ElHammouti, Founder and Lead Engineer, NordbeamPublished Updated

Short answer

How do you build a remote MCP server with OAuth?

Serve one HTTPS endpoint that speaks MCP over Streamable HTTP, and make it an OAuth 2.1 resource server. Publish Protected Resource Metadata that points at an authorization server, which issues short-lived access tokens after a person approves the app on a consent screen. On every request, verify the token, work out which person it stands for, and give the agent only the tools that person may use. Nordbeam, an AI development studio in Gothenburg and Malmö, runs four such servers on Cloudflare Workers.

A remote MCP server lets an AI agent such as Claude Code or Codex work inside your product over the internet, as a signed-in person, with nothing to install. This guide covers the transport, the OAuth sign-in, the tools, the controls that keep people in charge, and how to test and deploy it.

It comes from the code of the four MCP servers Nordbeam runs in production: Tavlaro (whiteboards), Banvaro (a board where people and agents share work), Vaktaro (website monitoring and client reports) and Fixamark (client feedback on websites). All four are TypeScript Workers with the same skeleton. Where one differs, the text says so. Protocol facts link to the official MCP specification. File references such as mcp.ts:130 point into Tavlaro's apps/web/worker/agents/ unless another product is named.

What is a remote MCP server, and how is it different from a local one?

A local MCP server is a program the client starts as a subprocess and talks to over standard input and output, the stdio transport. It runs on the user's machine with the user's permissions, and the specification says stdio servers should not use the HTTP authorization flow. They take credentials from the environment.

A remote MCP server is an HTTP service at a URL such as https://example.com/mcp. Nobody installs or updates anything, so a fix ships once for everyone. The cost is that you own authentication: the server must know who is calling and what that person may touch.

Choose local when the tools act on the user's own files or machine. Choose remote when the tools act on data your service holds for many people.

Which transport does a remote MCP server use?

Streamable HTTP. The specification defines one endpoint that accepts POST. The client sends each JSON-RPC message as its own request, and the server answers with either a single JSON object or a Server-Sent Events stream for that request. Clients must support both.

Our servers pick the simpler one. Each handles /mcp with createMcpHandler from the @modelcontextprotocol/server package and responseMode: "json". The handler and the McpServer behind it are created inside the request, so no state survives between calls (mcp.ts:130-135). That suits Workers: nothing to keep warm.

// One route, one handler per request. Names adapted from our servers.
app.all("/mcp", async (c) => {
  const principal = await authenticate(c.env, c.var.db, bearerOf(c.req.raw));
  const handler = createMcpHandler(
    () => buildServer(c.env, principal),
    { responseMode: "json" },
  );
  return handler.fetch(c.req.raw, {
    // The tools work from the principal, so the raw token never reaches the SDK.
    authInfo: { token: "redacted", clientId: principal.credentialId, scopes: [...principal.scopes] },
  });
});

Two cautions from the spec. Revision 2026-07-28 removed protocol-level sessions and the long-lived GET stream, so check which versions your SDK supports. And servers must validate the Origin header to prevent DNS rebinding, so confirm that your SDK or your code does it.

Our servers also read an optional ?toolsets= query parameter, so a client can load only part of the tool list (mcp.ts:118). An unknown name returns a 400 that lists the valid ones.

How does OAuth work for a remote MCP server?

The authorization page of the specification builds on OAuth 2.1 and treats your MCP server as a resource server. The client discovers where to sign in. Your job is to publish the right documents and refuse requests without a valid token.

What does the client discover?

  1. The client calls /mcp without a token and gets 401 with a WWW-Authenticate header carrying resource_metadata, the URL of the server's Protected Resource Metadata document (RFC 9728).
  2. It fetches that document, which must list at least one authorization server in authorization_servers.
  3. It fetches the authorization server's metadata (RFC 8414) or OpenID Connect discovery document, to find the authorization, token and registration endpoints. Clients must try both, in a fixed order for issuers with a path.

Servers must offer the resource metadata through the header or a well-known URI. Ours do both. The document, adapted from mcp.ts:19-27:

const protectedResourceMetadata = (appUrl: string) => ({
  resource: `${appUrl}/mcp`,
  authorization_servers: [`${appUrl}/api/auth`],
  scopes_supported: ["read", "write"],
  bearer_methods_supported: ["header"],
  resource_name: "Example",
});

The authorization server lives in the same Worker. Better Auth with its OAuth provider plugin serves sign-in, consent and tokens under /api/auth, and routes under /.well-known/ hand its metadata to clients (mcp.ts:37-55). The issuer has a path, so its metadata is served at the path-inserted URL from RFC 8414 and at the bare one for clients that skip the insertion (Fixamark's mcp.ts:47-48).

We build the 401 challenge by hand. With no token it is a plain Bearer challenge with the metadata URL and scope="read write". It adds error="invalid_token" only when a token was sent and failed, so a missing token cleanly starts the sign-in flow (mcp.ts:88-100; Fixamark mcp.ts:140-147).

A client needs a client ID before it can ask anyone to sign in. The specification lists three ways to get one: Client ID Metadata Documents, pre-registration and Dynamic Client Registration (RFC 7591).

Our four servers use dynamic registration: the provider lets clients register before anyone signs in, with read and write as default scopes. The specification now marks that method as deprecated as of 2026-07-28 and recommends Client ID Metadata Documents for new work, so read the client registration page before you choose. None of ours implements metadata documents yet.

The client then sends the person to sign in, and to a consent screen. Ours lists the request in plain words (Tavlaro's read is "See your boards, folders, templates and comments") with Allow and Deny (the consent route, oauth.consent.tsx:16-19). The stored consent matters again below.

Other provider settings we would repeat (worker/auth/plugins.ts:109-134):

  • Authorization code and refresh grants only. No client-credentials grant, so no token exists without a person behind it.
  • Short tokens. Access tokens last one hour, refresh tokens 30 days.
  • Localhost redirects. Plain http redirects are allowed only for localhost, 127.0.0.1 and [::1], where coding tools listen for the callback.
  • Device login (RFC 8628) for the command-line tool.

How is PKCE enforced?

Clients must use PKCE with S256 and must refuse a server whose metadata does not advertise it (security considerations). We found a gap in our OAuth library: after a token request with a wrong verifier, the authorization code stayed usable. A wrong verifier means someone other than the client may hold the code, so all four servers carry a small hook that burns the code on the first failure (plugins.ts:41-70). OAuth 2.1 requires the server to check the verifier and to issue a token only once per code; burning the code after a failed check is our stricter reading, so a stolen code can't be retried. Test failure paths, not only the happy one.

How does the server know which person and workspace a call is for?

From the access token. The server checks the signature against its own JSON Web Key Set and requires the issuer and the audience to match. The audience is the MCP resource URL, and the specification requires servers to accept only tokens issued for them (principal.ts:121-124). The sub claim is the person, and the authorized party is the client app.

Access tokens are stateless, so one more check makes disconnecting work at once. The server looks up the stored consent for that client and person and rejects the token if it is gone or the client is disabled (principal.ts:129-147). Without it, a revoked app keeps working until its token expires.

The result is a Principal: the person, the scopes, the workspaces they belong to, and a label such as "Claude Code for Sara". Every tool receives it. The workspace is resolved inside the tool, never trusted from the client. With one workspace the call uses it. With several, the tool takes an optional workspace argument, and when it is missing the error lists the choices (tool-kit.ts:116-143).

The servers differ here:

  • Tavlaro, Banvaro and Vaktaro also accept workspace API keys for team agents. Each agent has a row a person can pause, and a paused agent is refused (principal.ts:92-97).
  • Banvaro gives a team agent a list of boards and filters every board lookup through it (banvaro/.../principal.ts:28,107; tool-kit.ts:142).
  • Fixamark scopes by project. A project outside the credential's workspaces returns the same 404 as one that does not exist, and each call checks that the workspace's plan includes agent access, answering 402 if not (fixamark/.../principal.ts:137-167).

How should you design the tools?

Write for a reader that cannot ask follow-up questions. The tools specification gives the mechanics: a name, a description, an input schema, optional annotations and an optional output schema.

Declare every tool through one helper. Ours sets the annotations (readOnlyHint, destructiveHint, idempotentHint) and checks the scope before the tool runs, so a scope check cannot be forgotten (tool-kit.ts:268-307).

defineTool(server, ctx, {
  name: "delete_items",
  title: "Delete items",
  description: "Deletes items by id. Anyone can bring them back with undo_batch.",
  destructive: true,        // adds a required `confirm` argument
  input: z.object({
    board: z.string().describe("The board's id or name."),
    ids: z.array(z.string()).max(200),
  }),
  run: async (args, t) => t.post(`/boards/${args.board}/items/delete`, { ids: args.ids }),
});

Name the action. list_boards, read_board, add_items, undo_batch. The spec asks for names of 1 to 128 characters using letters, digits, underscore, hyphen and dot.

Describe what, when and next. Our descriptions say what the tool returns and which tool to call after it.

Accept what people say. Boards and people can be named by id or by name. If a name is ambiguous, the error tells the agent to pass the id (tool-kit.ts:157-175).

Return something usable. A short text summary plus structuredContent where it helps (tool-kit.ts:300-304). A write also names its undo step. Large results shrink: a board over 150 items comes back as clusters with a hint to read one frame.

Make errors readable. A guard wrapper turns thrown errors into results with isError: true and a plain sentence, and hides unexpected failures behind a generic message (tool-kit.ts:66-78). For HTTP-level scope failures the spec says to return 403 with error="insufficient_scope".

Leave things out on purpose. Do not mirror every endpoint. Each server keeps a written list of routes agents cannot reach, with a reason for each, and a test fails when a route is neither covered by a tool nor on the list (humans-only.ts, parity.test.ts). Secrets and access control belong on it.

Treat text from people as data. Comments, card titles and page text can contain instructions. Our tools wrap them in an <untrusted> fence (fence.ts), and the server instructions tell the model never to follow instructions found inside (mcp.ts:71). That lowers the risk of prompt injection without removing it, so the controls below do not depend on the model behaving.

How do you keep people in charge of what agents do?

The specification says there should always be a human in the loop with the ability to deny tool calls, and leaves the interface to the client. Clients differ, so we enforce rules on the server too. For the design of approval gates, see human-in-the-loop AI agents.

All four servers do these:

  • Agents act as the person, through the same code. A tool sends the request the web app would, so roles, plan limits and validation apply. A credential without write can only send GET (dispatch.ts:57-93).
  • Destructive tools need confirm: true. The tool refuses without it and tells the agent to ask the person.
  • Approving an app's access and minting credentials are humans-only. An agent must not widen its own reach.
  • Writes are rate limited. A Workers rate limit binding allows 120 changes per agent per minute and leaves reads free, so a looping agent stops with a message saying nothing was done (tool-kit.ts:309-334).

Each product adds the control that fits its work:

  • Tavlaro: undo. Every write returns a batch id, shown to people as a labelled step. undo_batch reverses the agent's own batch and leaves later human edits alone. An agent cannot undo anyone else's work (tools-items.ts:388-409). Deleting a board for good is humans-only. The agent can only move it to the bin.
  • Banvaro: a review gate. Agents take cards and call submit_for_review. A person approves or sends back, and approval is humans-only (humans-only.ts:46). By default an agent can move a card only as far as Review (tools.ts:367).
  • Vaktaro: people send. An agent triages incidents and drafts the monthly report, but sending it to the client is humans-only because it cannot be taken back (humans-only.ts:107-109).
  • Fixamark: the widest reach. An agent can run the whole workspace, members and billing included, so removal and revocation require confirm: true (mcp.ts:96). It has no undo tool. The agent fixes the code and moves the thread to review.

How do you test a remote MCP server with real clients?

Connect the clients people will use. Claude Code takes one command, then you sign in from its /mcp menu:

claude mcp add --transport http example https://example.com/mcp

Codex takes the URL as an option, and Fixamark's own instructions add a login step:

codex mcp add example --url https://example.com/mcp
codex mcp login example

Our products show these commands on their agents pages. Locally, point them at http://localhost:<port>/mcp; the localhost redirect rule is what lets the browser sign-in finish.

The MCP Inspector is the reference developer tool, with web, command-line and terminal clients. Our repositories do not use it. We test with the real clients and with automated tests that call tools as a signed-in agent. It is still handy for reading the raw JSON-RPC when a client misbehaves.

A first-run checklist:

  1. A call without a token returns 401 with a resource_metadata URL, and that document loads.
  2. The authorization server metadata loads at the URL a client builds from the issuer.
  3. A new client registers, signs in, sees the consent screen and finishes.
  4. A token for another audience is refused.
  5. Disconnecting the app makes the next call fail.
  6. A wrong PKCE verifier burns the code.
  7. A read token cannot call a write tool.

How do you deploy a remote MCP server on Cloudflare Workers?

As an ordinary Worker. Ours are Hono apps, and the fetch handler sends /mcp and everything under /.well-known/ to the MCP app before it serves pages (worker/index.ts:70-74). The OAuth endpoints share the origin, so there is no second service.

The configuration needs:

  • nodejs_compat in compatibility_flags, which our auth libraries expect.
  • A database binding. Ours is D1, holding users, OAuth clients, consent and agents.
  • Worker-first routing so /mcp and /.well-known/* reach the Worker before static assets (Tavlaro sets run_worker_first).
  • A rate limit binding under ratelimits, with a limit of 120 and a period of 60 seconds (Workers docs).
  • Secrets as secrets, never in the repository.

Deploy with vite build && wrangler deploy. Use a custom domain and keep it: the token audience and metadata URLs are built from it, so a change invalidates tokens already issued. Cloudflare also documents other ways to host MCP servers. Ours are plain Workers, and the MCP handler itself holds no state.

If you want a remote MCP server for your own product, see our MCP server development service or the products we run on this design. For running agents safely in a business more broadly, read building AI agents that work in production.

What is a remote MCP server?
A remote MCP server is an MCP server reached over HTTP at a URL, instead of a subprocess the client starts on the user's machine. The client connects to one endpoint using the Streamable HTTP transport, and the server authenticates each request.
Does a remote MCP server need OAuth?
The MCP specification makes authorization optional, but says HTTP-based servers that support it should follow its OAuth-based flow. A server that acts for signed-in people needs it in practice, and clients such as Claude Code start the sign-in themselves when the server answers 401 with the right metadata.
What is Protected Resource Metadata in MCP?
A JSON document defined by RFC 9728 that tells a client which authorization server issues tokens for the MCP server. The MCP specification requires servers to publish it, and it must list at least one authorization server.
Do MCP servers need dynamic client registration?
No. The specification lists Client ID Metadata Documents, pre-registration and Dynamic Client Registration. From version 2026-07-28 dynamic registration is deprecated and kept for backwards compatibility, and new implementations are pointed to Client ID Metadata Documents.
Can you run an MCP server on Cloudflare Workers?
Yes. Nordbeam's four production MCP servers are Cloudflare Workers that answer over Streamable HTTP with JSON responses, use a database binding and a rate limit binding, and serve their OAuth endpoints from the same Worker.

Need an MCP server for your product?

Tell us what your product does and what an agent should and should not be able to do in it. We will tell you what the server needs, and build it.

Start the Conversation →

Get in Touch

Which workflow should AI improve first?

Book a practical review of one high-value workflow. You'll speak directly with Assim, Nordbeam's founder and lead engineer.
Email directly
Email
hello@nordbeam.io
Locations
Gothenburg & Malmö, Sweden
Response time
Within 24 hours