workers-mcp

repository·main·Indexed 20 days ago

https://github.com/cloudflare/workers-mcp

A transport layer and CLI toolkit that bridges Cloudflare Workers with Model Context Protocol (MCP) clients like Claude Desktop and Cursor. It allows LLMs to execute Worker methods as tools by translating TypeScript classes into MCP tools and providing a local Node.js proxy to handle stdio transport. Features include secure communication via SHARED_SECRET, support for Durable Object routing through ProxyToDO, and automated setup for docgen and deployment.

Tokens
3.2K
Snippets
10
Records
16
Agent score
70%

What's inside workers-mcp

  1. How workers-mcp works

    main

    The workers-mcp package allows you to connect MCP clients (like Claude Desktop or Cursor) to a Cloudflare Worker. It uses a build step to translate TypeScript methods from a class extending WorkerEntrypoint<Env> into MCP tools.

    A local Node.js server acts as a proxy: it handles the stdio transport required by MCP clients and forwards calls to the relevant methods on your Worker running on Cloudflare. This enables LLMs to interact with your application logic or Cloudflare services directly.

    export class ExampleWorkerMCP extends WorkerEntrypoint<Env> {
      /**
       * Generates a random number.
       *
       * @return {string} A message containing a super duper random number
       * */
      async getRandomNumber() {
        return `Your random number is ${Math.random()}`
      }
    }
  2. Quickstart: Set up a Cloudflare Worker with workers-mcp

    main

    Follow these steps to create a new Worker and integrate it with MCP:

    1. Generate a new Worker: Use create-cloudflare to scaffold a project (a Hello World worker is recommended).
    2. Install workers-mcp: Navigate to your project directory and install the package via npm.
    3. Run setup: Execute the setup command to configure the connection.

    Note: If you encounter issues, run npx workers-mcp help for troubleshooting.

    npx create-cloudflare@latest my-new-worker
    cd my-new-worker
    npm install workers-mcp
    npx workers-mcp setup
  3. Configure workers-mcp for Windsurf and other MCP clients

    main

    For clients like Windsurf, add the server to your mcpServers configuration file using the standard command and args structure. Replace the placeholders with your actual server name, Worker URL, and local project path.

    {
      "mcpServers": {
        "your-mcp-server-name": {
          "command": "/path/to/workers-mcp",
          "args": [
            "run",
            "your-mcp-server-name",
            "https://your-server-url.workers.dev",
            "/path/to/your/project"
          ],
          "env": {}
        }
      }
    }
  4. Configure workers-mcp in Cursor

    main

    To use your Cloudflare MCP server in Cursor, you cannot use the standard JSON configuration format directly. Instead, you must create an MCP server entry with the type command and combine the command and args into a single string.

    Configuration requirements:

    • Type: command
    • Command: /path/to/workers-mcp run <your-mcp-server-name> <https://your-server-url.workers.dev> <path/to/your/project>
    /path/to/workers-mcp run your-mcp-server-name https://your-server-url.workers.dev /path/to/your/project
  5. Iterating on your Worker MCP server

    main

    When you modify your Worker code, run npm run deploy to update both the live Worker instance and the metadata used by Claude.

    Important: If you change method names, parameters, or add/remove methods, you must restart your MCP client (e.g., Claude Desktop) so it can see the updated tool definitions. You may also rerun npx workers-mcp install:claude if you suspect configuration issues.

  6. How the Proxy routes MCP requests

    main

    The Proxy function acts as a router for Model Context Protocol (MCP) requests sent to a Cloudflare Worker. It handles authentication and routes RPC calls to the underlying worker logic.

    Authentication

    Requests must include an Authorization header with a Bearer token. The token must match the provided secret, and the secret must be exactly 64 characters long. If these conditions are not met, the proxy returns a 401 Unauthorized response.

    RPC Routing

    • Endpoint: /rpc
    • Method: POST
    • Payload: A JSON object containing method (a key of the WorkerEntrypoint) and args (an array of arguments).

    When a valid RPC request is received, the proxy executes the method via the sendRPC callback. The response is handled based on the type returned by the method:

    • If the result is a Response, it is returned directly.
    • If the result is a string, it is wrapped in a new Response.
    • For all other types, the result is returned as a JSON response via Response.json().

    Error Handling

    If the RPC call fails, the proxy catches the error and returns a JSON response containing the error message and stack trace in the MCP-compatible format:

    {
      "content": [
        { "type": "text", "text": "error message" },
        { "type": "text", "text": "stack trace string" }
      ],
      "isError": true
    }
    export async function Proxy<T>(
      request: Request,
      secret: string,
      sendRPC: (method: string, args: any[]) => Promise<any>,
    ) { ... }
  7. Configure Docgen in package.json

    main

    To ensure your MCP tools are always documented, workers-mcp needs to run the docgen command before deployment. The setup script attempts to find an NPM script containing wrangler deploy and modifies it to include the docgen step.

    Manual Pattern: If the automated setup skips this, manually update your package.json scripts to follow this pattern:

    "scripts": {
      "deploy": "workers-mcp docgen src/index.ts && wrangler deploy"
    }
  8. Automated Guided Installation

    main

    The guidedInstallation process automates the setup of a workers-mcp environment. It performs the following steps:

    1. Docgen Integration: Prepends workers-mcp docgen <entrypoint> to your existing NPM deployment scripts (e.g., deploy, publish, or release) in package.json to ensure documentation is generated during deployment.
    2. Secret Management: Generates a 64-character SHARED_SECRET, stores it in .dev.vars, and uploads it to your Cloudflare Worker using wrangler secret put.
    3. Source Transformation: Replaces your worker entrypoint (e.g., src/index.ts) with a compatible template that uses ProxyToSelf or ProxyToDO helpers and JSDoc annotations.
    4. Deployment: Runs your deployment script or wrangler deploy to host the worker.
    5. Claude Desktop Installation: Automatically configures the deployed Worker URL in Claude Desktop.
  9. Run the local proxy for testing workers

    main

    The localProxy function allows you to run a local MCP (Model Context Protocol) proxy server that bridges an MCP client (like Claude Desktop) to your Cloudflare Workers. This is useful for testing your Worker's tools locally.

    To use this via the CLI, the script expects the following command structure:

    npx workers-mcp run <claude_name> <workers_url> [workers_dir]

    Requirements:

    1. dist/docs.json: The proxy requires a docs.json file in the workers_dir/dist/ directory. This file must contain the EntrypointDoc describing your Worker's methods and parameters.
    2. .dev.vars: A .dev.vars file must exist in the workers_dir containing a SHARED_SECRET environment variable. This secret is used for Bearer authentication when the proxy calls your Worker.
    3. Worker URL: The workers_url should be the base URL of your running Worker (e.g., the URL provided by wrangler dev).
    npx workers-mcp run my-claude-name http://localhost:8787 ./my-worker-project
  10. Use ProxyToSelf from workers-mcp

    main
    The workers-mcp package exports the ProxyToSelf module, which is the primary entry point for implementing the Model Context Protocol (MCP) within a Cloudflare Worker. This module allows a Worker to act as an MCP server by proxying requests to itself.
  11. Configure ProxyToDO for Durable Object routing

    main

    The ProxyToDO class is used to proxy requests to a Cloudflare Durable Object namespace. It requires a SHARED_SECRET in the environment for security and uses an index_strategy to determine which Durable Object instance to target.

    There are two supported IndexStrategy modes:

    1. Prepend Session ID: Uses the first argument of the incoming method call as a session_id to look up or create a specific Durable Object instance via ns.idFromName(session_id). This is useful for stateful, per-session interactions.
    2. Fixed Name: Uses a constant string provided in fixedName to look up a specific Durable Object instance via ns.idFromName(fixedName). This is useful for singleton-style Durable Objects.

    To use this, you must provide an environment object T that contains a SHARED_SECRET and the Durable Object namespace bound to the key specified by namespace_key.

    // Example: Using prependSessionID strategy
    const proxy = new ProxyToDO(env, 'MY_DURABLE_OBJECT_NAMESPACE', {
      prependSessionID: true
    });
    
    // Example: Using fixedName strategy
    const proxy = new ProxyToDO(env, 'MY_DURABLE_OBJECT_NAMESPACE', {
      fixedName: 'global-singleton'
    });
  12. Local Proxy CLI arguments

    main

    When running the workers-mcp proxy, the following arguments are used:

    ArgumentDescription
    <claude_name>The name assigned to the MCP server in the client (e.g., Claude Desktop)
    <workers_url>The base URL of your local or remote Cloudflare Worker
    [workers_dir](Optional) The directory containing your worker's build artifacts (dist/docs.json) and environment variables (.dev.vars). Defaults to the current working directory.