{"slug": "build-a-remote-mcp-server-on-cloudflare-pages-without-an-sdk-about-200-lines-of", "title": "Build a remote MCP server on Cloudflare Pages without an SDK (about 200 lines of TypeScript)", "summary": "A developer published a roughly 200-line TypeScript implementation of a stateless, tools-only MCP server running on Cloudflare Pages Functions, handling the Streamable HTTP transport with a single JSON-RPC POST handler and no SDK, session store or long-lived process. The server, live at agentwright.app/mcp, exposes Claude API pricing and cost-estimation tools to clients such as Claude Code, Claude Desktop and Cursor, and answers GET requests with 405 to signal no server stream. The writeup stresses echoing the client's protocol version when supported and returning tool failures as results with isError: true rather than JSON-RPC protocol errors so models can correct their calls.", "body_md": "If your MCP server only answers questions (look something up, compute something, return text), you do not need a framework, a session store or a long-lived process. One HTTP handler that speaks JSON-RPC is enough, and it runs for free on Cloudflare Pages Functions or Workers.\n\nThis post walks through the server we run at `https://agentwright.app/mcp`. It gives Claude, Cursor or any MCP client current Claude API prices and cost estimates. The full source is public in [functions/mcp.ts](https://github.com/agentwright-app/site/blob/main/functions/mcp.ts); the snippets below are trimmed from it.\n\nWith the Streamable HTTP transport, everything goes to one URL as an HTTP `POST` with a JSON-RPC body. For a tools-only server, a client session looks like this:\n\n`initialize`: the client sends the protocol version it wants and its capabilities. You answer with the version you will speak, your capabilities and your name.`notifications/initialized`: a notification (no `id`), so there is nothing to answer. Reply `202 Accepted` with an empty body.`tools/list`: return your tool definitions with JSON Schema inputs.` tools/call`: run one tool and return its result as content blocks.\nAdd `ping` (answer `{}`) and you have covered what Claude Code, Claude Desktop, Cursor and the official SDK client do with a tools-only server.\n\nThe transport also lets a server answer with a `text/event-stream` and open a `GET` stream for server-to-client messages. Both are optional. If every answer is a single JSON object, reply with `Content-Type: application/json`, and answer `GET` with `405 Method Not Allowed`; clients treat that as \"no server stream\" and carry on.\n\n``` js\nexport const onRequestPost: PagesFunction = async ({ request }) => {\n  const text = await request.text();\n  if (text.length > 64_000) return json(rpcError(null, -32600, \"Request too large\"), 413);\n\n  let body: unknown;\n  try {\n    body = JSON.parse(text);\n  } catch {\n    return json(rpcError(null, -32700, \"Parse error\"), 400);\n  }\n\n  const out = handle(body as Rpc);              // null for notifications\n  return out ? json(out) : new Response(null, { status: 202 });\n};\n\nexport const onRequestGet: PagesFunction = async () =>\n  new Response(\"Method Not Allowed\", { status: 405, headers: { allow: \"POST, OPTIONS\" } });\n```\n\n`handle` is a plain `switch` on `msg.method`:\n\n```\nfunction handle(msg: Rpc): object | null {\n  if (msg.id === undefined || msg.id === null) return null; // notification\n  switch (msg.method) {\n    case \"initialize\":\n      return ok(msg.id, {\n        protocolVersion: SUPPORTED.includes(msg.params?.protocolVersion)\n          ? msg.params.protocolVersion\n          : SUPPORTED[0],\n        capabilities: { tools: { listChanged: false } },\n        serverInfo: { name: \"claude-pricing\", version: \"1.0.0\" },\n      });\n    case \"ping\":\n      return ok(msg.id, {});\n    case \"tools/list\":\n      return ok(msg.id, { tools: TOOLS });\n    case \"tools/call\":\n      return ok(msg.id, runTool(msg.params?.name, msg.params?.arguments ?? {}));\n    default:\n      return rpcError(msg.id, -32601, `Method not found: ${msg.method}`);\n  }\n}\n```\n\nTwo details matter here.\n\n**Version negotiation.** Echo the client's `protocolVersion` if you support it, otherwise answer with your newest one. A stateless tools-only server behaves the same under the recent spec versions, so supporting several costs nothing.\n\n**Two kinds of errors.** An unknown method or unknown tool is a protocol error: a JSON-RPC `error` object. A tool that ran but could not do the job (bad model name, negative token count) should return a normal result with `isError: true` and a readable message. The model sees that text and can correct its own call. If you throw a protocol error instead, many clients show a generic failure and the model never learns what went wrong.\n\n```\nfunction runTool(name: string, args: Record<string, unknown>) {\n  try {\n    return { content: [{ type: \"text\", text: callTool(name, args) }], isError: false };\n  } catch (e) {\n    return { content: [{ type: \"text\", text: (e as Error).message }], isError: true };\n  }\n}\n```\n\nEach tool has a name, a one-sentence description of when to use it, and an `inputSchema`. Put units and defaults in the property descriptions, because that is the only documentation the model reads:\n\n```\n{\n  name: \"estimate_claude_cost\",\n  description: \"Estimate the USD cost of Claude API calls from token counts. Handles prompt caching, the Batch API discount and long-prompt pricing.\",\n  inputSchema: {\n    type: \"object\",\n    properties: {\n      model: { type: \"string\", description: \"Model id, e.g. claude-sonnet-5-5\" },\n      input_tokens: { type: \"number\", minimum: 0, description: \"Uncached input tokens per request\" },\n      output_tokens: { type: \"number\", minimum: 0, description: \"Output tokens per request (includes thinking tokens)\" },\n      requests: { type: \"number\", minimum: 0, description: \"Number of requests (default 1)\" },\n      batch: { type: \"boolean\", description: \"Use Batch API pricing (default false)\" },\n    },\n    required: [\"model\", \"input_tokens\", \"output_tokens\"],\n  },\n  annotations: { readOnlyHint: true },\n}\n```\n\n`readOnlyHint` tells clients the tool changes nothing, so some of them skip the confirmation prompt.\n\nBrowser-based clients (the MCP Inspector, web IDEs) need CORS: answer `OPTIONS` with `204` and send `Access-Control-Allow-Origin` plus the headers clients use (`content-type`, `accept`, `mcp-protocol-version`, `mcp-session-id`).\n\nThe spec also asks servers to validate the `Origin` header to stop DNS-rebinding attacks. That matters for servers that sit on `localhost` or act with the user's credentials. Ours is public, read-only and has no authentication, so there is nothing for a rebinding page to steal, and allowing every origin is fine. If your server reads private data, check `Origin` against an allowlist and require a bearer token.\n\nBefore publishing, connect with the same SDK most clients use:\n\n``` js\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\nconst client = new Client({ name: \"smoke-test\", version: \"1.0.0\" });\nawait client.connect(new StreamableHTTPClientTransport(new URL(\"https://agentwright.app/mcp\")));\nconsole.log((await client.listTools()).tools.map((t) => t.name));\nconsole.log(await client.callTool({ name: \"list_claude_models\", arguments: {} }));\nawait client.close();\n```\n\nIf that works, Claude Code works too:\n\n```\nclaude mcp add --transport http claude-pricing https://agentwright.app/mcp\n```\n\nThe [official MCP Registry](https://registry.modelcontextprotocol.io) lists servers by a namespaced name. If you own a domain, you can prove it with a DNS record instead of a GitHub login, and your server gets a reverse-DNS name such as `app.agentwright/claude-pricing`.\n\n`openssl genpkey -algorithm Ed25519 -out key.pem`, then take the last 32 bytes of the public key as base64 and publish `v=MCPv1; k=ed25519; p=<base64>` as a TXT record on the domain.`server.json` with `name`, `description`, `version` and a `remotes` entry of type `streamable-http` pointing at your URL.`mcp-publisher login dns --domain <domain> --private-key <hex>` and `mcp-publisher publish`.\nThe [registry documentation](https://modelcontextprotocol.io/registry/authentication) has the exact commands. Keep the private key out of your repository; you can always generate a new key and replace the TXT record when you publish the next version.\n\nThis approach stops being the simple option when you need any of these:\n\nFor those, the official TypeScript SDK (or Cloudflare's agents library on Workers) handles sessions and streams for you. For a read-only lookup or calculator, one function and a `switch` are easier to read, test and keep running.\n\n**Questions or corrections?** Please leave them in the [comments on the original post](https://agentwright.app/blog/remote-mcp-server-cloudflare-without-sdk/#comments). We check those every day and answer there, while replies here on DEV can take a while.\n\n*Disclosure: this article was written with the help of AI (Claude). Facts, prices and code were checked against the official documentation and reviewed before publishing.*\n\n*Originally published on the [Agentwright blog](https://agentwright.app/blog/remote-mcp-server-cloudflare-without-sdk/).*", "url": "https://wpnews.pro/news/build-a-remote-mcp-server-on-cloudflare-pages-without-an-sdk-about-200-lines-of", "canonical_source": "https://dev.to/agentwrightapp/build-a-remote-mcp-server-on-cloudflare-pages-without-an-sdk-about-200-lines-of-typescript-4mpa", "published_at": "2026-11-23 22:00:38+00:00", "updated_at": "2026-11-23 22:13:02.162853+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "developer-tools", "ai-tools"], "entities": ["Cloudflare", "Cloudflare Pages", "Claude", "Cursor", "Anthropic", "agentwright.app"], "also_reported_by": [], "takeaway": "A tools-only MCP server needs only a JSON-RPC POST handler covering initialize, notifications/initialized (reply 202), tools/list, tools/call and ping, with GET answered 405 to signal no server stream.", "recommendation": {"advice": "Return tool failures as normal results with isError: true and a readable message instead of JSON-RPC protocol errors, so the model sees the text and can correct its own call.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/build-a-remote-mcp-server-on-cloudflare-pages-without-an-sdk-about-200-lines-of", "markdown": "https://wpnews.pro/news/build-a-remote-mcp-server-on-cloudflare-pages-without-an-sdk-about-200-lines-of.md", "text": "https://wpnews.pro/news/build-a-remote-mcp-server-on-cloudflare-pages-without-an-sdk-about-200-lines-of.txt", "jsonld": "https://wpnews.pro/news/build-a-remote-mcp-server-on-cloudflare-pages-without-an-sdk-about-200-lines-of.jsonld"}}