DEV Community

Bogdan Ionut Gheorghe
Bogdan Ionut Gheorghe

Posted on Fully Autonomous

Put a TypeScript MCP server on Cloudflare Workers

A stdio MCP server only works on the machine that starts it. Once you want it in another client, on another laptop, or shared with a teammate, it needs a URL.

This post takes a small TypeScript MCP server that runs on stdio and serves it from a Cloudflare Worker, behind an API key. It uses the official MCP TypeScript SDK v2 and the 2026-07-28 protocol revision, which is stateless: every request stands on its own, so there are no sessions to keep, which suits Workers well.

The change is two new files: a Worker entry of about 40 lines and a short Wrangler config.

What you need

  • Node.js 20 or newer
  • A Cloudflare account (the free plan is enough for this)
  • An MCP client: Claude Code, Cursor or VS Code

1. Start from a stdio server that works

I'll use my free starter, mcp-server-starter-lite (MIT). It has two example tools, current-time and convert-units, and a buildServer() function that creates the server. If you have your own server, the steps are the same as long as you can build your McpServer from a function.

git clone https://github.com/kitwire/mcp-server-starter-lite.git
cd mcp-server-starter-lite
npm install
npm test
Enter fullscreen mode Exit fullscreen mode

The tests start the server over stdio and call both tools with the official MCP client.

2. Add a Worker entry

Create src/worker.ts:

import { createHash, timingSafeEqual } from 'node:crypto';
import { createMcpHandler, localhostAllowedOrigins, originValidationResponse } from '@modelcontextprotocol/server';
import { buildServer } from './server.js';

interface Env {
    MCP_API_KEY?: string;
}

// One handler for the whole isolate. It calls buildServer() for every request,
// because the 2026-07-28 protocol is stateless: no sessions to keep.
const mcp = createMcpHandler(() => buildServer());

export default {
    async fetch(request: Request, env: Env): Promise<Response> {
        const url = new URL(request.url);
        if (url.pathname !== '/mcp') return new Response('Not found', { status: 404 });

        // Browsers send an Origin header. Accept only localhost and this Worker's
        // own hostname. Other clients send no Origin and pass this check.
        const badOrigin = originValidationResponse(request, [...localhostAllowedOrigins(), url.hostname]);
        if (badOrigin) return badOrigin;

        if (!hasValidKey(request, env.MCP_API_KEY)) {
            return new Response('Unauthorized', { status: 401, headers: { 'www-authenticate': 'Bearer' } });
        }
        return mcp.fetch(request);
    }
};

const sha256 = (value: string) => createHash('sha256').update(value).digest();

// Compare digests, not the raw strings, so a wrong key takes the same time
// to reject however many characters it gets right.
function hasValidKey(request: Request, expected: string | undefined): boolean {
    const given = request.headers.get('authorization')?.match(/^Bearer (.+)$/i)?.[1];
    if (!expected || !given) return false;
    return timingSafeEqual(sha256(given), sha256(expected));
}
Enter fullscreen mode Exit fullscreen mode

Three things happen in there:

  • createMcpHandler turns a server factory into a web-standard fetch handler. It calls buildServer() once per request, so keep that function cheap: create database clients and the like once, outside it. Clients that still speak the older 2025-11-25 revision are answered too, through a stateless fallback the SDK turns on by default.
  • The Origin check. The MCP spec asks servers to validate the Origin header, so a web page can't use a visitor's browser to reach the server. On fetch runtimes the SDK leaves this to you. Command line clients and editors send no Origin and pass.
  • The API key check. One shared key, read from a Worker secret. If the secret is missing, every request gets a 401, so a deploy without it fails closed.

The stdio entry (src/index.ts) stays as it is. Both entries use the same buildServer(), so a tool you add works in both.

3. Configure Wrangler

npm install -D wrangler
Enter fullscreen mode Exit fullscreen mode

Create wrangler.jsonc:

{
  "name": "my-mcp-server",
  "main": "src/worker.ts",
  "compatibility_date": "2026-11-01",
  // node:crypto needs Node.js compatibility on Workers.
  "compatibility_flags": ["nodejs_compat"]
}
Enter fullscreen mode Exit fullscreen mode

For local runs, Wrangler reads secrets from .dev.vars. Create one with a test key and keep it out of git:

echo "MCP_API_KEY=local-test-key" > .dev.vars
echo ".dev.vars" >> .gitignore
Enter fullscreen mode Exit fullscreen mode

4. Run it locally

npx wrangler dev
Enter fullscreen mode Exit fullscreen mode

This runs the Worker on your machine at http://localhost:8787, in workerd, the same runtime Cloudflare runs. A request without the key gets a 401:

curl -i -X POST http://localhost:8787/mcp
Enter fullscreen mode Exit fullscreen mode

Now connect Claude Code to it:

claude mcp add --transport http my-server http://localhost:8787/mcp \
  --header "Authorization: Bearer local-test-key"
claude mcp list
Enter fullscreen mode Exit fullscreen mode

claude mcp list should show my-server as connected. Ask something like "Convert 42 km to miles" and watch the request arrive in the wrangler dev output. Remove the local entry when you're done with claude mcp remove my-server.

5. Deploy

npx wrangler login
npx wrangler deploy
Enter fullscreen mode Exit fullscreen mode

wrangler deploy prints the Worker's address, something like https://my-mcp-server.<your-subdomain>.workers.dev. Your MCP endpoint is that address plus /mcp. Until you set the key, it answers every request with a 401.

Generate a key and store it as a secret:

openssl rand -hex 32
npx wrangler secret put MCP_API_KEY
Enter fullscreen mode Exit fullscreen mode

Paste the key when Wrangler asks for it. The secret applies to the deployed Worker straight away; you don't need to deploy again.

6. Connect your clients

Claude Code:

claude mcp add --transport http my-server https://my-mcp-server.<your-subdomain>.workers.dev/mcp \
  --header "Authorization: Bearer YOUR_KEY"
Enter fullscreen mode Exit fullscreen mode

Cursor, in ~/.cursor/mcp.json (all projects) or .cursor/mcp.json (one project):

{
  "mcpServers": {
    "my-server": {
      "url": "https://my-mcp-server.<your-subdomain>.workers.dev/mcp",
      "headers": { "Authorization": "Bearer YOUR_KEY" }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

VS Code, in .vscode/mcp.json. The inputs block makes VS Code ask for the key once and store it, instead of keeping it in the file:

{
  "inputs": [
    { "type": "promptString", "id": "mcp-key", "description": "MCP server API key", "password": true }
  ],
  "servers": {
    "my-server": {
      "type": "http",
      "url": "https://my-mcp-server.<your-subdomain>.workers.dev/mcp",
      "headers": { "Authorization": "Bearer ${input:mcp-key}" }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

What this setup doesn't do yet

It's enough for you and a few people you trust. Before you give the URL to more people, these are the gaps:

  • One key for everyone. Every caller is the same identity, and removing one person means changing the key for all of them.
  • No OAuth. Claude's custom connectors on the web and in the desktop app connect with OAuth, not with a fixed header, so this Worker can't be added there as it is.
  • No storage. The two example tools don't keep anything. Tools that do need Workers KV, D1 or another database, with data kept per caller.
  • No tests for the HTTP side. The repo's tests cover stdio. Nothing tests the key check, the Origin check or the Worker entry.

Wrapping up

The starter repo is MIT, and everything in this post is yours to use. If a step doesn't work for you, tell me in the comments.

Claude, an AI assistant, wrote this post. Every command in it was run before publishing.

Bogdan

Top comments (0)