Skip to content

Commit 4286f49

Browse files
authored
Add MCP server documentation (#20634)
Add MCP server documentation
1 parent f19b87c commit 4286f49

File tree

1 file changed

+211
-0
lines changed

1 file changed

+211
-0
lines changed
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
---
2+
pcx_content_type: tutorial
3+
title: Build an MCP Server
4+
sidebar:
5+
order: 100
6+
group:
7+
hideIndex: true
8+
description: Build and deploy an MCP server on Cloudflare Workers
9+
---
10+
11+
import { MetaInfo, Render, Type, TypeScriptExample, WranglerConfig } from "~/components";
12+
import { Aside } from '@astrojs/starlight/components';
13+
14+
[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.
15+
16+
### Building an MCP Server on Workers
17+
18+
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.
19+
20+
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:
21+
22+
**How it works:**
23+
* **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.
24+
* **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.
25+
* **Build-in MCP compatibility:** The `ProxyToSelf` class translates incoming requests into relevant JS RPC methods
26+
* **Enforced type safety:** Parameter and return types are automatically derived from your TypeScript definitions
27+
28+
## Get Started
29+
30+
Follow these steps to create and deploy your own MCP server on Cloudflare Workers.
31+
32+
<Aside type="note">
33+
Remote MCP servers are not supported yet. The workers-mcp tooling creates a local proxy that forwards requests to your Worker, allowing the server to be used by an MCP client.
34+
</Aside>
35+
36+
37+
### Create a new Worker
38+
39+
If you haven't already, install [Wrangler](https://developers.cloudflare.com/workers/wrangler/) and log in:
40+
41+
```bash
42+
npm install wrangler
43+
wrangler login
44+
```
45+
46+
Initialize a new project:
47+
```bash
48+
npx create-cloudflare@latest my-mcp-worker
49+
cd my-mcp-worker
50+
```
51+
52+
### Configure your wrangler file
53+
54+
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.
55+
56+
<WranglerConfig>
57+
```toml
58+
name = "my-mcp-worker"
59+
main = "src/index.ts"
60+
compatibility_date = "2025-03-03"
61+
account_id = "your-account-id"
62+
```
63+
</WranglerConfig>
64+
65+
### Install the MCP tooling
66+
Inside your project directory, install the [workers-mcp](https://github.com/cloudflare/workers-mcp) package:
67+
68+
```bash
69+
npm install workers-mcp
70+
```
71+
72+
This package provides the tools needed to run your Worker as an MCP server.
73+
74+
### Configure your Worker to support MCP
75+
Run the following setup command:
76+
77+
```bash
78+
npx workers-mcp setup
79+
```
80+
81+
This guided installation process takes a brand new or existing Workers project and adds the required tooling to turn it into an MCP server:
82+
- Automatic documentation generation
83+
- Shared-secret security using Wrangler Secrets
84+
- Installs a local proxy so you can access it from your MCP desktop clients (like Claude Desktop)
85+
86+
### Set up the MCP Server
87+
The setup command will automatically update your src/index.ts with the following code:
88+
89+
```ts
90+
import { WorkerEntrypoint } from 'cloudflare:workers';
91+
import { ProxyToSelf } from 'workers-mcp';
92+
93+
export default class MyWorker extends WorkerEntrypoint<Env> {
94+
/**
95+
* A warm, friendly greeting from your new MCP server.
96+
* @param name {string} The name of the person to greet.
97+
* @return {string} The greeting message.
98+
*/
99+
sayHello(name: string) {
100+
return `Hello from an MCP Worker, ${name}!`;
101+
}
102+
103+
/**
104+
* @ignore
105+
*/
106+
async fetch(request: Request): Promise<Response> {
107+
// ProxyToSelf handles MCP protocol compliance.
108+
return new ProxyToSelf(this).fetch(request);
109+
}
110+
}
111+
```
112+
113+
This converts your Cloudflare Worker into an MCP server, enabling interactions with AI assistants. **The key components are:**
114+
- **WorkerEntrypoint:** The WorkerEntrypoint class handles all incoming request management and routing. This provides the structure needed to expose MCP tools within the Worker.
115+
- **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.
116+
- **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.
117+
118+
119+
**Note:** Every public method that is annotated with JSDoc becomes an MCP tool that is discoverable by AI assistants.
120+
121+
### Add data fetching to the MCP
122+
123+
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:
124+
125+
```ts
126+
import { WorkerEntrypoint } from 'cloudflare:workers';
127+
import { ProxyToSelf } from 'workers-mcp';
128+
129+
export default class WeatherWorker extends WorkerEntrypoint<Env> {
130+
/**
131+
* Get current weather for a location
132+
* @param location {string} City name or zip code
133+
* @return {object} Weather information
134+
*/
135+
async getWeather(location: string) {
136+
// Connect to a weather API
137+
const response = await fetch(`https://api.weather.example/v1/${location}`);
138+
const data = await response.json();
139+
return {
140+
temperature: data.temp,
141+
conditions: data.conditions,
142+
forecast: data.forecast
143+
};
144+
}
145+
146+
/**
147+
* @ignore
148+
*/
149+
async fetch(request: Request): Promise<Response> {
150+
// ProxyToSelf handles MCP protocol compliance
151+
return new ProxyToSelf(this).fetch(request);
152+
}
153+
}
154+
```
155+
156+
### Deploy the MCP server
157+
Update your wrangler.toml with the appropriate configuration then deploy your Worker:
158+
```bash
159+
npx wrangler deploy
160+
```
161+
162+
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.
163+
164+
#### Updating your MCP server
165+
When you make changes to your MCP server, run the following command to update it:
166+
```bash
167+
npm run deploy
168+
```
169+
**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.
170+
### Connecting MCP clients to your server
171+
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.
172+
173+
#### Cursor
174+
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'.
175+
176+
In Cursor, create an MCP server entry with:
177+
178+
type: command
179+
command: /path/to/workers-mcp run your-mcp-server-name https://your-server-url.workers.dev /path/to/your/project
180+
181+
For example, using the same configuration as above, your Cursor command would be:
182+
```
183+
/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
184+
```
185+
186+
#### Other MCP clients
187+
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:
188+
```json
189+
{
190+
"mcpServers": {
191+
"your-mcp-server-name": {
192+
"command": "/path/to/workers-mcp",
193+
"args": [
194+
"run",
195+
"your-mcp-server-name",
196+
"https://your-server-url.workers.dev",
197+
"/path/to/your/project"
198+
],
199+
"env": {}
200+
}
201+
}
202+
}
203+
```
204+
Make sure to replace the placeholders with your actual server name, URL, and project path.
205+
### Coming soon
206+
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:
207+
208+
- **Remote MCP support**: Connect to MCP servers directly without requiring a local proxy
209+
- **Authentication**: OAuth support for secure MCP server connections
210+
- **Real-time communication**: SSE (Server-Sent Events) and WebSocket support for persistent connections and stateful interactions between clients and servers
211+
- **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)

0 commit comments

Comments
 (0)