返回 MCP 目录
public公开dns本地运行

workers-mcp-server

Workers MCP Server是一个概念验证项目,通过Cloudflare Worker实现Model Context Protocol (MCP)服务器,使Claude Desktop等MCP客户端能够调用Cloudflare Worker的RPC功能来扩展其能力。项目提供了文档生成、本地代理和远程调用等功能,支持开发者快速构建和部署MCP服务。

article

README

🚀 工人 MCP 项目

本项目展示了如何将 WorkerEntrypoint 类暴露为 MCP(模型上下文协议)服务。借助 Wrangler 和一些自定义工具,可实现本地开发与部署,为 MCP 服务的开发和测试提供了便利。

🚀 快速开始

安装和运行

  1. 克隆项目仓库。
  2. 运行 npm install 安装依赖项。
  3. scripts/ 目录中运行 node local-proxy.ts 启动代理服务器。
  4. 使用 MCP 工具测试与 WorkerEntrypoint 的交互。

✨ 主要特性

  • 能够将 WorkerEntrypoint 类暴露为 MCP 服务。
  • 支持本地开发和部署,方便进行测试。
  • 提供文档生成脚本,可生成 MCP 工具文档。

📦 项目结构

project/
├── src/
│   └── index.ts               # Worker 的主要入口点
├── lib/
│   └── WorkerMCP.ts          # 公共 HTTP 处理器
├── scripts/
│   ├── local-proxy.ts        # 本地 MCP 代理
│   └── generate-docs.ts      # 文档生成脚本
└── package.json             # 项目依赖管理

💻 使用示例

基础用法

src/index.ts - 工人入口点

export class WorkerEntrypoint {
    async greet(name: string): Promise<string> {
        return `Hello, ${name}!`;
    }
}

这个类定义了我们想要通过 MCP 提供的服务。目前只有一个方法 greet,它接受一个字符串参数并返回问候语。

lib/WorkerMCP.ts - 公共 HTTP 处理器

import { expose } from '@modelcontextprotocol/sdk';
import { WorkerEntrypoint } from '../src/index';

class WorkerMCP {
    static async fetch(req: Request): Promise<Response> {
        const endpoint = new URL('/rpc', req.url);
        if (req.method !== 'POST' || !req.headers.get('Content-Type')?.includes('application/json')) {
            return Response.json({ error: 'Invalid request' }, 400);
        }

        try {
            const body = await req.json();
            const { method } = body;
            const instance = new WorkerEntrypoint();
            const result = await Reflect.apply(instance[method], instance, body.args || []);

            return Response.json({ result });
        } catch (error) {
            return Response.json({ error: error.message }, 500);
        }
    }
}

expose(WorkerMCP);

这个文件定义了如何处理传入的 HTTP 请求。它通过 /rpc 路径暴露一个端点,接收 JSON 请求并调用相应的 WorkerEntrypoint 方法。

scripts/local-proxy.ts - 本地 MCP 代理

import { serve } from 'std/server';
import { expose } from '@modelcontextprotocol/sdk';

async function main() {
    const port = 8080;
    await serve(async (req) => {
        if (req.method === 'GET' && req.url.pathname === '/tools/list') {
            // 返回 MCP 工具列表
            return Response.json({
                tools: [{
                    name: 'WorkerEntrypoint',
                    methods: ['greet']
                }]
            });
        } else if (req.method === 'POST' && req.url.pathname === '/rpc') {
            // 处理 RPC 请求
            const body = await req.json();
            const instance = new WorkerEntrypoint();
            return Response.json({ result: await Reflect.apply(instance[body.method], instance, body.args || []) });
        }
    }, { port });
}

main();

这个脚本在本地运行一个代理服务器,处理 MCP 的 tools/list/rpc 请求。它允许我们在不部署到云的情况下测试和开发。

scripts/generate-docs.ts - 文档生成脚本

import { writeFileSync } from 'fs';

const docGenerator = () => {
    const workerEntrypoint = require.resolve('../src/index');
    const content = `See the source file: ${workerEntrypoint}`;
    
    return { 
        entrypoints: [
            {
                name: 'WorkerEntrypoint',
                description: 'A simple MCP service example.',
                docUrl: 'https://example.com/docs'
            }
        ],
        tools: [{
            name: 'greet',
            description: 'Greets a person.',
            arguments: [{ name: 'name', type: 'string' }],
            returns: { type: 'string' }
        }]
    };
};

const docs = docGenerator();
writeFileSync('docs.json', JSON.stringify(docs, null, 2));

这个脚本生成用于 MCP 的工具文档。它目前静态生成文档,但可以扩展以包含更多详细信息。

🔧 技术细节

限制和未来计划

  • 当前只支持从 src/index.ts 公开一个类。
  • 只有一个简单的 greet 方法可用。
  • 文档生成是静态的,未来可以扩展以包含更多详细信息。

📚 结论

这个项目展示了如何使用 Wrangler 和自定义脚本将工人入口点暴露为 MCP 服务,并提供了本地开发的能力。

help

运行方式说明

cloud

托管运行

托管运行通常表示这个 MCP Server 由服务方环境承载,用户一般按页面提供的连接方式或授权流程接入,不需要在本地长期启动一个 MCP 进程

  1. 打开服务方连接页
  2. 完成授权或复制端点
  3. 在 MCP 客户端中连接
terminal

本地运行 / 其它方式

本地运行通常需要用户在自己的电脑或服务器上安装依赖,把 server_config 复制到 MCP 客户端,并按 env_schema 补齐环境变量、密钥或其它配置

  1. 复制 server_config
  2. 安装所需依赖
  3. 补齐环境变量后重启客户端