远程MCP服务器

在Cloudflare Workers上部署支持OAuth 2.0认证的远程MCP服务器,用于安全访问和管理AI工具。

  • by njdancer
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 njdancer/remote-mcp-server-authless

使用说明

在Cloudflare上使用OAuth构建远程MCP服务器

此示例允许您在Cloudflare Workers上部署一个带有OAuth 2.0认证的远程MCP服务器。

开始吧:

这将把您的MCP服务器部署到一个类似如下的URL: remote-mcp-server-authless.<your-account>.workers.dev/sse

或者,您可以使用以下命令行在本地机器上创建远程MCP服务器:

npm create cloudflare@latest -- my-mcp-server --template=cloudflare/ai/demos/remote-mcp-authless

认证

这个MCP服务器使用 OAuth 2.0 授权码流程 用于安全认证。

测试凭证

  • 用户名: admin
  • 密码: test123

OAuth 端点

  • 授权端点: https://your-worker.workers.dev/oauth/authorize
  • 令牌端点: https://your-worker.workers.dev/oauth/token
  • 元数据终端点: https://your-worker.workers.dev/.well-known/oauth-authorization-server

OAuth流程的工作原理

  1. 客户端通过重定向发起授权 /oauth/authorize 和;与 client_id, redirect_uri,以及 response_type=code
  2. 用户看到登录页面并输入凭据
  3. 成功登录后,用户将被重定向回带有授权码的页面
  4. 客户端在(指定位置)将授权码兑换为访问令牌 /oauth/token
  5. 客户端使用访问令牌进行 Authorization: Bearer <token> 所有MCP请求的头部信息

定制您的MCP服务器

添加您自己的 工具 向MCP服务器发送,定义其中的每个工具 init() 方法 src/index.ts 使用 this.server.tool(...)。

连接到OAuth保护的MCP服务器

使用OAuth与MCP客户端

要连接到这个受OAuth保护的MCP服务器,您的客户端需要:

  1. 实现OAuth 2.0授权码流程
  2. 存储并使用访问令牌 在……里 Authorization: Bearer <token> 头球

示例:手动OAuth流程

您可以手动测试OAuth流程:

  1. 获取授权码:

    https://your-worker.workers.dev/oauth/authorize?client_id=test-client&redirect_uri=http://localhost:3000/callback&response_type=code
    
    • 使用(以下方式)登录 admin / test123
    • 您将被重定向并附带一个代码参数
  2. 用交换代码换取访问令牌:

    curl -X POST https://your-worker.workers.dev/oauth/token \
      -d "grant_type=authorization_code" \
      -d "code=YOUR_CODE_HERE" \
      -d "redirect_uri=http://localhost:3000/callback" \
      -d "client_id=test-client"
    
  3. 使用访问令牌:

    curl https://your-worker.workers.dev/sse \
      -H "Authorization: Bearer YOUR_ACCESS_TOKEN_HERE"
    

将Claude Desktop连接到您的MCP服务器

注标准的MCP客户端,如 mcp-remote 目前并不原生支持OAuth。您需要:

  1. 使用一个自定义的OAuth感知MCP客户端 处理OAuth流程的部分
  2. 预认证并注入令牌 进入客户端配置
  3. 建立代理 负责处理OAuth并转发已认证的请求

对于使用Claude Desktop进行开发/测试,您可能需要暂时禁用身份验证或使用一个为您处理OAuth的工具。

连接到Cloudflare AI Playground

Cloudflare AI Playground 可能需要 OAuth 配置。请查阅其关于 OAuth 集成的文档:

  1. 访问 https://playground.ai.cloudflare.com/
  2. 配置OAuth设置,包括您的授权端点和令牌端点
  3. 输入您已部署的MCP服务器URL(remote-mcp-server-authless.<your-account>.workers.dev/sse)

安全注意事项

⚠️(警告符号,无具体文字含义,通常用于表示警告或注意) 重要的这个实现使用了:

  • 用于测试的硬编码凭据(admin / test123)
  • 代码和令牌的内存存储(工作节点重启后丢失)
  • 用于JWT签名的静态密钥

用于生产,你应该:

  1. 将凭据移动到环境变量或Cloudflare密钥中
  2. 使用Cloudflare KV或Durable Objects进行持久化令牌存储
  3. 从环境变量中使用一个安全、随机生成的密钥
  4. 实施适当的客户端注册和客户端密钥管理
  5. 添加速率限制和防暴力破解保护
  6. 考虑使用刷新令牌以实现长期访问