From 1195e85be438fe1d809e93752347b4a417fb3b8f Mon Sep 17 00:00:00 2001 From: Dina Kozlov Date: Fri, 7 Mar 2025 13:34:47 -0500 Subject: [PATCH 1/6] Add MCP server documentation --- .../docs/agents/examples/build-mcp-server.mdx | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 src/content/docs/agents/examples/build-mcp-server.mdx diff --git a/src/content/docs/agents/examples/build-mcp-server.mdx b/src/content/docs/agents/examples/build-mcp-server.mdx new file mode 100644 index 000000000000000..6153d67eeb5a161 --- /dev/null +++ b/src/content/docs/agents/examples/build-mcp-server.mdx @@ -0,0 +1,164 @@ +--- +pcx_content_type: tutorial +title: Build an MCP Server +sidebar: + order: 100 + group: + hideIndex: true +description: Build and deploy an MCP server on Cloudflare Workers +--- + +import { MetaInfo, Render, Type, TypeScriptExample, WranglerConfig } from "~/components"; +import { Aside } from '@astrojs/starlight/components'; + +[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that allows AI assistants & LLMs to interact with services directly. If you want users to access your service or product straight from their AI assistant, you can enable this by spinning up an MCP server for your application. + +## Building an MCP Server on Cloudflare Workers + +Normally, setting up an MCP server requires writing boilerplate code to handle routing, define types, and standing up a server that implements the MCP protocol. But with [Cloudflare Workers](/workers/), all the heavy lifting is done for you, so all you need to do is define your service's functionality as TypeScript methods on your Worker +Once deployed, your Worker becomes an MCP server that AI assistants (as long as they support MCP) can connect to and use to interact with your service. + + + +## Benefits + +- **Minimal setup & built-in boilerplate:** The Worker automatically handles API routing, server management, and MCP protocol compliance. The [workers-mcp](https://www.npmjs.com/package/workers-mcp) package bootstraps your MCP server, allowing you to focus on your service logic. +- **Automatic documentation:** Public methods annotated with JSDoc are automatically documented and exposed as MCP tools. This means AI assistants can quickly understand how to interact with your service, making tool discovery and integration much easier. +- **Scalability & performance:** Deploy your MCP server on Cloudflare's global edge network so that users can make fast, performant requests from their LLMs. Cloudflare will handle traffic spikes and high load, ensuring your service remains available and responsive. +- **Expand MCP server capabilities:** Easily connect to Workers AI, D1, Durable Objects, and other Cloudflare services to add more functionality to your MCP Server. + +## Get Started + +Follow these steps to create and deploy your own MCP server on Cloudflare Workers. + + +### Create a new Worker + +If you haven't already, install [Wrangler](https://developers.cloudflare.com/workers/wrangler/) and log in: + +```bash +npm install wrangler +wrangler login +``` + +Initialize a new project: +```bash +npx create-cloudflare@latest my-mcp-worker +cd my-mcp-worker +``` + +### Install the MCP tooling +Inside your project directory, install the [workers-mcp](https://github.com/cloudflare/workers-mcp) package: + +```bash +npm install workers-mcp +``` + +This package provides the tools needed to run your Worker as an MCP server. + +### Configure your Worker to support MCP +Run the following setup command: + +```bash +npx workers-mcp setup +``` + +This guided installation process takes a brand new or existing Workers project and adds the required tooling to turn it into an MCP server: +- Automatic documentation generation +- Shared-secret security using Wrangler Secrets +- Installs a local proxy so you can access it from your MCP desktop clients (like Claude Desktop) + +### Set up the MCP Server +Replace the contents of your src/index.ts with the following boilerplate code: + +```ts +import { WorkerEntrypoint } from 'cloudflare:workers'; +import { ProxyToSelf } from 'workers-mcp'; + +export default class MyWorker extends WorkerEntrypoint { + /** + * A warm, friendly greeting from your new MCP server. + * @param name {string} The name of the person to greet. + * @return {string} The greeting message. + */ + sayHello(name: string) { + return `Hello from an MCP Worker, ${name}!`; + } + + /** + * @ignore + */ + async fetch(request: Request): Promise { + // ProxyToSelf handles MCP protocol compliance. + return new ProxyToSelf(this).fetch(request); + } +} +``` + +This converts your Cloudflare Worker into an MCP server, enabling interactions with AI assistants. The key components are: +- **WorkerEntrypoint:** The WorkerEntrypoint class handles all incoming request management and routing. This provides the structure needed to expose MCP tools within the Worker. +- **Tool Definition:** Methods, for example, sayHello, are annotated with JSDoc, which automatically registers the method as an MCP tool. AI assistants can call this method dynamically, passing a name and receiving a greeting in response. Additional tools can be defined using the same pattern. +- **ProxyToSelf:** MCP servers must follow a specific request/response format. ProxyToSelf ensures that incoming requests are properly routed to the correct MCP tools. Without this, you would need to manually parse requests and validate responses. + + +**Note:** Every public method that is annotated with JSDoc becomes an MCP tool that is discoverable by AI assistants. + + +### Deploy the MCP server +Update your wrangler.toml with the appropriate configuration then deploy your Worker: +```bash +wrangler deploy +``` + +Your MCP server is now deployed globally and all your public class methods are exposed as MCP tools that AI assistants can now interact with. + +#### Updating your MCP server +When you make changes to your MCP server, run the following command to update it: +```bash +npm run deploy +``` +**Note:** If you change method names, parameters, or add/remove methods, Claude and other MCP clients will not see these updates until you restart them. This is because MCP clients cache the tool metadata for performance reasons. +### Connecting MCP clients to your server +The workers-mcp setup command automatically configures Claude Desktop to work with your MCP server. To use your MCP server through other [MCP clients](https://modelcontextprotocol.io/clients), you'll need to configure them manually. + +#### Cursor +To get your Cloudflare MCP server working in Cursor, you need to combine the 'command' and 'args' from your config file into a single string and use type 'command'. + +In Cursor, create an MCP server entry with: + +type: command +command: /path/to/workers-mcp run your-mcp-server-name https://your-server-url.workers.dev /path/to/your/project + +For example, using the same configuration as above, your Cursor command would be: +``` +/Users/username/path/to/my-new-worker/node_modules/.bin/workers-mcp run my-new-worker https://my-new-worker.username.workers.dev /Users/username/path/to/my-new-worker +``` + +#### Other MCP clients +For Windsurf and other MCP clients, update your configuration file to include your worker using the same format as Claude Desktop: +```json +{ + "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": {} + } + } +} +``` +Make sure to replace the placeholders with your actual server name, URL, and project path. +### Coming soon +The Model Context Protocol spec is [actively evolving](https://github.com/modelcontextprotocol/specification/discussions) and we're working on expanding Cloudflare's MCP support. Here's what we're working on: + +- **Remote MCP support**: Connect to MCP servers directly without requiring a local proxy +- **Authentication**: OAuth support for secure MCP server connections +- **Real-time communication**: SSE (Server-Sent Events) and WebSocket support for persistent connections and stateful interactions between clients and servers +- **Extended capabilities**: Native support for more MCP protocol capabilities like [resources](https://modelcontextprotocol.io/docs/concepts/resources), [prompts](https://modelcontextprotocol.io/docs/concepts/prompts) and [sampling](https://modelcontextprotocol.io/docs/concepts/sampling) \ No newline at end of file From 7acd80dfaf3ad70c0ae6cc6b8fc7d27e82903536 Mon Sep 17 00:00:00 2001 From: Dina Kozlov Date: Fri, 7 Mar 2025 17:28:30 -0500 Subject: [PATCH 2/6] Update MCP server documentation based on PR feedback --- .../docs/agents/examples/build-mcp-server.mdx | 69 ++++++++++++++----- 1 file changed, 52 insertions(+), 17 deletions(-) diff --git a/src/content/docs/agents/examples/build-mcp-server.mdx b/src/content/docs/agents/examples/build-mcp-server.mdx index 6153d67eeb5a161..e72bfc0cfa83730 100644 --- a/src/content/docs/agents/examples/build-mcp-server.mdx +++ b/src/content/docs/agents/examples/build-mcp-server.mdx @@ -5,34 +5,69 @@ sidebar: order: 100 group: hideIndex: true -description: Build and deploy an MCP server on Cloudflare Workers +description: Learn how to create, deploy, and configure an MCP server on Cloudflare Workers to enable AI assistants to interact with your services directly. --- import { MetaInfo, Render, Type, TypeScriptExample, WranglerConfig } from "~/components"; import { Aside } from '@astrojs/starlight/components'; -[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that allows AI assistants & LLMs to interact with services directly. If you want users to access your service or product straight from their AI assistant, you can enable this by spinning up an MCP server for your application. +In this guide, you will learn how to build and deploy a Model Context Protocol (MCP) server on Cloudflare Workers. -## Building an MCP Server on Cloudflare Workers +[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that allows AI agents and assistants (like [Claude Desktop](https://claude.ai/download), [Cursor](https://www.cursor.com/), or [Anthropic's Claude](https://www.anthropic.com/claude)) to interact with services directly. If you want users to access your service through an AI agent, you can spin up an MCP server for your application. -Normally, setting up an MCP server requires writing boilerplate code to handle routing, define types, and standing up a server that implements the MCP protocol. But with [Cloudflare Workers](/workers/), all the heavy lifting is done for you, so all you need to do is define your service's functionality as TypeScript methods on your Worker -Once deployed, your Worker becomes an MCP server that AI assistants (as long as they support MCP) can connect to and use to interact with your service. +### Why use Cloudflare Workers for MCP? - +With Cloudflare Workers and the [workers-mcp](https://github.com/cloudflare/workers-mcp/) package, you can turn any API or service into an MCP server with minimal setup. Just define your API methods as TypeScript functions, and workers-mcp takes care of tool discovery, protocol handling, and request routing. Once deployed, MCP clients like Claude can connect and interact with your service automatically. + +#### Example: Exposing a Weather API as an MCP server -## Benefits +Here's a Cloudflare Worker that fetches weather data from an external API and exposes it as an MCP tool that Claude can call directly: + +```ts +import { WorkerEntrypoint } from 'cloudflare:workers'; +import { ProxyToSelf } from 'workers-mcp'; -- **Minimal setup & built-in boilerplate:** The Worker automatically handles API routing, server management, and MCP protocol compliance. The [workers-mcp](https://www.npmjs.com/package/workers-mcp) package bootstraps your MCP server, allowing you to focus on your service logic. -- **Automatic documentation:** Public methods annotated with JSDoc are automatically documented and exposed as MCP tools. This means AI assistants can quickly understand how to interact with your service, making tool discovery and integration much easier. -- **Scalability & performance:** Deploy your MCP server on Cloudflare's global edge network so that users can make fast, performant requests from their LLMs. Cloudflare will handle traffic spikes and high load, ensuring your service remains available and responsive. -- **Expand MCP server capabilities:** Easily connect to Workers AI, D1, Durable Objects, and other Cloudflare services to add more functionality to your MCP Server. +export default class WeatherWorker extends WorkerEntrypoint { + /** + * Get current weather for a location + * @param location {string} City name or zip code + * @return {object} Weather information + */ + async getWeather(location: string) { + // Connect to a weather API + const response = await fetch(`https://api.weather.example/v1/${location}`); + const data = await response.json(); + return { + temperature: data.temp, + conditions: data.conditions, + forecast: data.forecast + }; + } + + /** + * @ignore + */ + async fetch(request: Request): Promise { + // ProxyToSelf handles MCP protocol compliance + return new ProxyToSelf(this).fetch(request); + } +} +``` + +**How it works:** +* **TypeScript methods as MCP tools:** Each public method in your class is exposed as an MCP tool that agents can call. In this example, getWeather is the tool that fetches data from an external weather API. +* **Automatic tool documentation:** JSDoc comments define the tool description, parameters, and return values, so Claude knows exactly how to call your method and interpret the response. +* **Build-in MCP compatibility:** The `ProxyToSelf` class handles all MCP protocol requirements +* **Enforced type safety:** Parameter and return types are automatically derived from your TypeScript definitions ## Get Started Follow these steps to create and deploy your own MCP server on Cloudflare Workers. + + ### Create a new Worker @@ -97,7 +132,7 @@ export default class MyWorker extends WorkerEntrypoint { } ``` -This converts your Cloudflare Worker into an MCP server, enabling interactions with AI assistants. The key components are: +This converts your Cloudflare Worker into an MCP server, enabling interactions with AI assistants. **The key components are:** - **WorkerEntrypoint:** The WorkerEntrypoint class handles all incoming request management and routing. This provides the structure needed to expose MCP tools within the Worker. - **Tool Definition:** Methods, for example, sayHello, are annotated with JSDoc, which automatically registers the method as an MCP tool. AI assistants can call this method dynamically, passing a name and receiving a greeting in response. Additional tools can be defined using the same pattern. - **ProxyToSelf:** MCP servers must follow a specific request/response format. ProxyToSelf ensures that incoming requests are properly routed to the correct MCP tools. Without this, you would need to manually parse requests and validate responses. @@ -121,10 +156,10 @@ npm run deploy ``` **Note:** If you change method names, parameters, or add/remove methods, Claude and other MCP clients will not see these updates until you restart them. This is because MCP clients cache the tool metadata for performance reasons. ### Connecting MCP clients to your server -The workers-mcp setup command automatically configures Claude Desktop to work with your MCP server. To use your MCP server through other [MCP clients](https://modelcontextprotocol.io/clients), you'll need to configure them manually. +The `workers-mcp setup` command automatically configures Claude Desktop to work with your MCP server. To use your MCP server through other [MCP clients](https://modelcontextprotocol.io/clients), you'll need to configure them manually. #### Cursor -To get your Cloudflare MCP server working in Cursor, you need to combine the 'command' and 'args' from your config file into a single string and use type 'command'. +To get your Cloudflare MCP server working in [Cursor](https://modelcontextprotocol.io/clients#cursor), you need to combine the 'command' and 'args' from your config file into a single string and use type 'command'. In Cursor, create an MCP server entry with: @@ -137,7 +172,7 @@ For example, using the same configuration as above, your Cursor command would be ``` #### Other MCP clients -For Windsurf and other MCP clients, update your configuration file to include your worker using the same format as Claude Desktop: +For [Windsurf](https://modelcontextprotocol.io/clients#windsurf-editor) and other [MCP clients](https://modelcontextprotocol.io/clients#client-details), update your configuration file to include your worker using the same format as Claude Desktop: ```json { "mcpServers": { From b6df6ac7ee75a9c048aff4d49cadb7695cf8bec9 Mon Sep 17 00:00:00 2001 From: Dina Kozlov Date: Fri, 7 Mar 2025 17:58:02 -0500 Subject: [PATCH 3/6] Small fixes --- src/content/docs/agents/examples/build-mcp-server.mdx | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/content/docs/agents/examples/build-mcp-server.mdx b/src/content/docs/agents/examples/build-mcp-server.mdx index e72bfc0cfa83730..5d080272781ca01 100644 --- a/src/content/docs/agents/examples/build-mcp-server.mdx +++ b/src/content/docs/agents/examples/build-mcp-server.mdx @@ -5,15 +5,13 @@ sidebar: order: 100 group: hideIndex: true -description: Learn how to create, deploy, and configure an MCP server on Cloudflare Workers to enable AI assistants to interact with your services directly. +description: Build and deploy an MCP server on Cloudflare Workers --- import { MetaInfo, Render, Type, TypeScriptExample, WranglerConfig } from "~/components"; import { Aside } from '@astrojs/starlight/components'; -In this guide, you will learn how to build and deploy a Model Context Protocol (MCP) server on Cloudflare Workers. - -[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that allows AI agents and assistants (like [Claude Desktop](https://claude.ai/download), [Cursor](https://www.cursor.com/), or [Anthropic's Claude](https://www.anthropic.com/claude)) to interact with services directly. If you want users to access your service through an AI agent, you can spin up an MCP server for your application. +[Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that allows AI agents and assistants (like [Claude Desktop](https://claude.ai/download) or [Cursor](https://www.cursor.com/)) to interact with services directly. If you want users to access your service through an AI assistant, you can spin up an MCP server for your application. ### Why use Cloudflare Workers for MCP? @@ -21,7 +19,7 @@ With Cloudflare Workers and the [workers-mcp](https://github.com/cloudflare/work #### Example: Exposing a Weather API as an MCP server -Here's a Cloudflare Worker that fetches weather data from an external API and exposes it as an MCP tool that Claude can call directly: +Here’s a Cloudflare Worker that fetches weather data from an external API and exposes it as an MCP tool that Claude can call directly: ```ts import { WorkerEntrypoint } from 'cloudflare:workers'; From 9e33d5eaca56c21aba46a6f15bab53cef0e2d097 Mon Sep 17 00:00:00 2001 From: Dina Kozlov Date: Fri, 7 Mar 2025 18:15:52 -0500 Subject: [PATCH 4/6] Update ProxyToSelf class description for accuracy --- src/content/docs/agents/examples/build-mcp-server.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/agents/examples/build-mcp-server.mdx b/src/content/docs/agents/examples/build-mcp-server.mdx index 5d080272781ca01..fdf536c24c37461 100644 --- a/src/content/docs/agents/examples/build-mcp-server.mdx +++ b/src/content/docs/agents/examples/build-mcp-server.mdx @@ -55,7 +55,7 @@ export default class WeatherWorker extends WorkerEntrypoint { **How it works:** * **TypeScript methods as MCP tools:** Each public method in your class is exposed as an MCP tool that agents can call. In this example, getWeather is the tool that fetches data from an external weather API. * **Automatic tool documentation:** JSDoc comments define the tool description, parameters, and return values, so Claude knows exactly how to call your method and interpret the response. -* **Build-in MCP compatibility:** The `ProxyToSelf` class handles all MCP protocol requirements +* **Build-in MCP compatibility:** The `ProxyToSelf` class translates incoming requests into relevant JS RPC methods * **Enforced type safety:** Parameter and return types are automatically derived from your TypeScript definitions ## Get Started From af2e17731c9a42b2dd720d896ccb36905023685b Mon Sep 17 00:00:00 2001 From: Rita Kozlov Date: Mon, 10 Mar 2025 11:41:11 -0400 Subject: [PATCH 5/6] restructure --- .../docs/agents/examples/build-mcp-server.mdx | 73 ++++++++++--------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/src/content/docs/agents/examples/build-mcp-server.mdx b/src/content/docs/agents/examples/build-mcp-server.mdx index fdf536c24c37461..2c2651d6960d387 100644 --- a/src/content/docs/agents/examples/build-mcp-server.mdx +++ b/src/content/docs/agents/examples/build-mcp-server.mdx @@ -13,44 +13,11 @@ import { Aside } from '@astrojs/starlight/components'; [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that allows AI agents and assistants (like [Claude Desktop](https://claude.ai/download) or [Cursor](https://www.cursor.com/)) to interact with services directly. If you want users to access your service through an AI assistant, you can spin up an MCP server for your application. -### Why use Cloudflare Workers for MCP? +### Building an MCP Server on Workers With Cloudflare Workers and the [workers-mcp](https://github.com/cloudflare/workers-mcp/) package, you can turn any API or service into an MCP server with minimal setup. Just define your API methods as TypeScript functions, and workers-mcp takes care of tool discovery, protocol handling, and request routing. Once deployed, MCP clients like Claude can connect and interact with your service automatically. -#### Example: Exposing a Weather API as an MCP server - -Here’s a Cloudflare Worker that fetches weather data from an external API and exposes it as an MCP tool that Claude can call directly: - -```ts -import { WorkerEntrypoint } from 'cloudflare:workers'; -import { ProxyToSelf } from 'workers-mcp'; - -export default class WeatherWorker extends WorkerEntrypoint { - /** - * Get current weather for a location - * @param location {string} City name or zip code - * @return {object} Weather information - */ - async getWeather(location: string) { - // Connect to a weather API - const response = await fetch(`https://api.weather.example/v1/${location}`); - const data = await response.json(); - return { - temperature: data.temp, - conditions: data.conditions, - forecast: data.forecast - }; - } - - /** - * @ignore - */ - async fetch(request: Request): Promise { - // ProxyToSelf handles MCP protocol compliance - return new ProxyToSelf(this).fetch(request); - } -} -``` +Below we will run you through an example of building an MCP server that fetches weather data from an external API and exposes it as an MCP tool that Claude can call directly: **How it works:** * **TypeScript methods as MCP tools:** Each public method in your class is exposed as an MCP tool that agents can call. In this example, getWeather is the tool that fetches data from an external weather API. @@ -138,11 +105,45 @@ This converts your Cloudflare Worker into an MCP server, enabling interactions w **Note:** Every public method that is annotated with JSDoc becomes an MCP tool that is discoverable by AI assistants. +### Add data fetching to the MCP + +When building an MCP, in many cases, you will need to connect to a resource or an API to take an action. To do this you can use the `fetch` method to make direct API calls, such as in the example below for grabbing the current wearther: + +```ts +import { WorkerEntrypoint } from 'cloudflare:workers'; +import { ProxyToSelf } from 'workers-mcp'; + +export default class WeatherWorker extends WorkerEntrypoint { + /** + * Get current weather for a location + * @param location {string} City name or zip code + * @return {object} Weather information + */ + async getWeather(location: string) { + // Connect to a weather API + const response = await fetch(`https://api.weather.example/v1/${location}`); + const data = await response.json(); + return { + temperature: data.temp, + conditions: data.conditions, + forecast: data.forecast + }; + } + + /** + * @ignore + */ + async fetch(request: Request): Promise { + // ProxyToSelf handles MCP protocol compliance + return new ProxyToSelf(this).fetch(request); + } +} +``` ### Deploy the MCP server Update your wrangler.toml with the appropriate configuration then deploy your Worker: ```bash -wrangler deploy +npx wrangler deploy ``` Your MCP server is now deployed globally and all your public class methods are exposed as MCP tools that AI assistants can now interact with. From c58405c8276e5241a291a750336662e5635d8df1 Mon Sep 17 00:00:00 2001 From: Dina Kozlov Date: Mon, 10 Mar 2025 13:35:12 -0400 Subject: [PATCH 6/6] Add wrangler configuration section to MCP server docs --- .../docs/agents/examples/build-mcp-server.mdx | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/content/docs/agents/examples/build-mcp-server.mdx b/src/content/docs/agents/examples/build-mcp-server.mdx index 2c2651d6960d387..d1fa5c5aa5ddede 100644 --- a/src/content/docs/agents/examples/build-mcp-server.mdx +++ b/src/content/docs/agents/examples/build-mcp-server.mdx @@ -49,6 +49,19 @@ npx create-cloudflare@latest my-mcp-worker cd my-mcp-worker ``` +### Configure your wrangler file + +When you run the setup command, it will build your Worker using the configuration in your wrangler.toml or wrangler.jsonc file. By default, no additional configuration is needed, but if you have multiple Cloudflare accounts, you'll need to specify your account ID as shown below. + + +```toml +name = "my-mcp-worker" +main = "src/index.ts" +compatibility_date = "2025-03-03" +account_id = "your-account-id" +``` + + ### Install the MCP tooling Inside your project directory, install the [workers-mcp](https://github.com/cloudflare/workers-mcp) package: @@ -71,7 +84,7 @@ This guided installation process takes a brand new or existing Workers project a - Installs a local proxy so you can access it from your MCP desktop clients (like Claude Desktop) ### Set up the MCP Server -Replace the contents of your src/index.ts with the following boilerplate code: +The setup command will automatically update your src/index.ts with the following code: ```ts import { WorkerEntrypoint } from 'cloudflare:workers';