遠端MCP伺服器
在MCP整合基礎文章中,我們瞭解了MCP(Model Context Protocol)的基本概念和本地STDIO伺服器的配置。但MCP的真正威力在於遠端伺服器——透過HTTP/HTTPS協議連線的雲端服務,它們提供了無需本地安裝、開箱即用的強大功能。
本文將深入探討遠端MCP伺服器的配置、認證機制,以及如何整合Sentry、Linear等第三方服務,讓你的Claude Code能夠直接訪問企業級工具和資料。
什麼是遠端MCP伺服器
本地 vs 遠端MCP伺服器
本地MCP伺服器(STDIO傳輸):
- 透過標準輸入/輸出通訊
- 需要在本地機器上執行
- 需要安裝Node.js、Python等執行時
- 適合訪問本地資源和私有資料
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/files"]
}
}
}
遠端MCP伺服器(HTTP/SSE傳輸):
- 透過HTTP/HTTPS協議通訊
- 託管在雲端或遠端伺服器
- 只需提供URL即可連線
- 適合訪問SaaS服務和公共服務
{
"mcpServers": {
"sentry": {
"url": "https://mcp.sentry.dev/mcp",
"transport": "http"
}
}
}
遠端MCP伺服器的優勢
传统本地MCP服务器:
用户机器 → 安装Node.js → npx启动服务器 → 占用本地资源 → 配置复杂
远程MCP服务器:
用户机器 → 提供URL → 直接连接 → 即用即走
關鍵優勢:
-
零安裝體驗
- 無需本地安裝依賴
- 無需配置執行環境
- 立即可用
-
集中管理
- 服務提供商統一維護
- 自動更新和升級
- 統一的版本控制
-
安全性增強
- 憑證由服務提供商管理
- OAuth 2.1標準認證
- 無需本地儲存敏感資訊
-
效能最佳化
- 專業的伺服器基礎設施
- 更快的響應速度
- 負載均衡和容錯
-
跨平臺相容
- 不受本地環境限制
- Windows、macOS、Linux統一體驗
遠端MCP傳輸協議
傳輸協議演進
MCP遠端伺服器支援兩種主要傳輸方式:
1. HTTP + SSE(Server-Sent Events)
工作原理:
客户端 服务器
│ │
├───── HTTP POST ──────────────────→ │
│ (发送JSON-RPC请求) │
│ │
│ ├─ 处理请求
│ │
├───── SSE连接 ─────────────────────→ │
│<──── 数据流 ────────────────────────┤
│<──── 持续更新 ──────────────────────┤
│ │
特點:
- 單向伺服器推送
- 自動重連機制
- 瀏覽器原生支援
- 適合實時資料流
配置示例:
{
"mcpServers": {
"sentry": {
"url": "https://mcp.sentry.dev/mcp",
"transport": "sse"
}
}
}
2. Streamable HTTP(推薦)
工作原理:
客户端 服务器
│ │
├───── HTTP POST (streamable) ────→ │
│ (发送请求,期望流式响应) │
│ │
│ ├─ 处理请求
│ │
│<──── HTTP Chunked Response ────────┤
│<──── 数据块流 ──────────────────────┤
特點:
- 雙向通訊
- 更高效的傳輸
- 更好的錯誤處理
- MCP 2025年推薦的傳輸方式
配置示例:
{
"mcpServers": {
"linear": {
"url": "https://mcp.linear.app",
"transport": "http"
}
}
}
協議對比表
| 特性 | HTTP + SSE | Streamable HTTP | STDIO |
|---|---|---|---|
| 傳輸方向 | 伺服器推送 | 雙向流式 | 雙向 |
| 連線方式 | 長連線 | 短連線/流式 | 持久程序 |
| 適用場景 | 實時通知 | 通用遠端服務 | 本地服務 |
| 瀏覽器支援 | 原生 | 需fetch API | 不支援 |
| 推薦度 | 向後相容 | ⭐推薦 | 本地必需 |
| 複雜度 | 中等 | 低 | 低 |
配置遠端MCP伺服器
方法一:使用CLI嚮導(推薦)
Claude Code提供了互動式嚮導來新增遠端MCP伺服器:
# 基本添加命令
claude mcp add sentry \
--url https://mcp.sentry.dev/mcp \
--transport http
# 添加到项目作用域
claude mcp add linear \
--url https://mcp.linear.app \
--transport http \
--scope project
# 添加到用户作用域
claude mcp add github-remote \
--url https://mcp.github.com \
--transport http \
--scope user
互動式流程示例:
$ claude mcp add sentry --url https://mcp.sentry.dev/mcp
✓ Detected remote MCP server
✓ Server supports OAuth 2.1 authentication
? Configure authentication:
❯ OAuth (Recommended)
API Key
Skip
Selected: OAuth
? Scope:
❯ user
project
local
✓ Sentry MCP server added successfully!
✓ Configuration saved to user scope
Next steps:
1. Restart Claude Code
2. First use will trigger OAuth flow
3. Grant permissions to complete setup
Restart Claude Code now? [Y/n]
方法二:手動編輯配置檔案
對於複雜配置,可以直接編輯配置檔案:
配置檔案位置:
# macOS
~/Library/Application Support/Claude/claude_desktop_config.json
# Linux
~/.config/Claude/claude_desktop_config.json
# Windows
%APPDATA%/Claude/claude_desktop_config.json
完整配置示例:
{
"mcpServers": {
"sentry": {
"url": "https://mcp.sentry.dev/mcp",
"transport": "http",
"oauth": {
"authorizationUrl": "https://sentry.io/oauth/authorize",
"tokenUrl": "https://sentry.io/oauth/token",
"clientId": "auto-registered",
"scopes": ["project:read", "event:read", "issue:read"]
},
"headers": {
"User-Agent": "Claude-Code/1.0"
},
"timeout": 30000
},
"linear": {
"url": "https://mcp.linear.app",
"transport": "http"
},
"notion": {
"url": "https://mcp.notion.so",
"transport": "http",
"oauth": {
"authorizationUrl": "https://auth.notion.com/oauth/authorize",
"tokenUrl": "https://api.notion.com/v1/oauth/token",
"scopes": ["read"]
}
},
"github-remote": {
"url": "https://api.githubcopilot.com/mcp/github",
"transport": "http"
}
}
}
配置選項詳解
基本選項
{
"mcpServers": {
"server-name": {
// 必需:服务器URL
"url": "https://example.com/mcp",
// 必需:传输方式
// - "http": Streamable HTTP (推荐)
// - "sse": HTTP + SSE
"transport": "http"
}
}
}
OAuth認證選項
{
"mcpServers": {
"server-name": {
"url": "https://example.com/mcp",
"transport": "http",
// OAuth配置
"oauth": {
// OAuth授权端点
"authorizationUrl": "https://example.com/oauth/authorize",
// Token交换端点
"tokenUrl": "https://example.com/oauth/token",
// 客户端ID(自动注册或手动提供)
"clientId": "your-client-id",
// 客户端密钥(可选,PKCE模式下不需要)
"clientSecret": "your-client-secret",
// 请求的权限范围
"scopes": ["read", "write"],
// 回调URL(通常是本地端口)
"redirectUrl": "http://localhost:3000/callback"
}
}
}
}
高階選項
{
"mcpServers": {
"server-name": {
"url": "https://example.com/mcp",
"transport": "http",
// 自定义HTTP头
"headers": {
"User-Agent": "Claude-Code/1.0",
"X-Custom-Header": "value"
},
// 超时设置(毫秒)
"timeout": 30000,
// 环境变量(用于敏感信息)
"env": {
"API_KEY": "${API_KEY}"
},
// 启用/禁用服务器
"enabled": true,
// 优先级(数字越大优先级越高)
"priority": 100
}
}
}
OAuth認證詳解
什麼是OAuth 2.1
OAuth 2.1是OAuth 2.0的下一代版本,提供了更強的安全保證:
核心安全特性:
-
強制PKCE(Proof Key for Code Exchange)
- 防止授權碼攔截攻擊
- 適用於公共客戶端
- 無需client_secret
-
隱式流被廢棄
- 不再返回access_token in URL
- 使用授權碼+PKCE替代
-
重新整理令牌輪換
- 每次重新整理獲得新的refresh_token
- 舊的refresh_token立即失效
- 減少令牌洩露風險
OAuth認證流程
標準OAuth 2.1流程
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ Claude │ │ OAuth Provider│ │ Server │
│ Code │ │ (Sentry等) │ │ (MCP) │
└──────┬──────┘ └───────┬───────┘ └──────┬──────┘
│ │ │
│ 1. 尝试调用MCP工具 │ │
├─────────────────────────────────→│ │
│ (需要认证) │ │
│ │ │
│ 2. 返回401,提供OAuth信息 │ │
│←─────────────────────────────────┤ │
│ { │ │
│ authorizationUrl: "...", │ │
│ tokenUrl: "...", │ │
│ clientId: "..." │ │
│ } │ │
│ │ │
│ 3. 打开浏览器,用户授权 │ │
│ ┌────────────────────────┐ │ │
│ │ Login to Sentry │ │ │
│ │ [授权界面] │ │ │
│ │ [Allow] [Deny] │ │ │
│ └────────────────────────┘ │ │
├─────────────────────────────────→│ │
│ │ │
│ 4. 获得authorization code │ │
│←─────────────────────────────────┤ │
│ code=xxx&state=yyy │ │
│ │ │
│ 5. 用code换取access_token │ │
├─────────────────────────────────→│ │
│ code + PKCE verifier │ │
│ │ │
│ 6. 返回access_token │ │
│←─────────────────────────────────┤ │
│ { │ │
│ access_token: "xxx", │ │
│ refresh_token: "yyy", │ │
│ expires_in: 3600 │ │
│ } │ │
│ │ │
│ 7. 安全存储token │ │
│ (Keychain/加密存储) │ │
│ │ │
│ 8. 使用access_token调用MCP │ │
├──────────────────────────────────────────────────────────────→│
│ Authorization: Bearer xxx │
│ │
│ 9. 返回数据 │
│←──────────────────────────────────────────────────────────────┤
│ │
│ 10. Token过期时自动刷新 │
├─────────────────────────────────→│ │
│ refresh_token │ │
│←─────────────────────────────────┤ │
│ 新的access_token │ │
在Claude Code中配置OAuth
Sentry OAuth配置
步驟1:新增Sentry MCP伺服器
claude mcp add sentry \
--url https://mcp.sentry.dev/mcp \
--transport http \
--scope user
步驟2:首次使用時觸發OAuth
$ claude
> 查看Sentry中的错误
🔐 需要OAuth认证
Sentry MCP服务器需要授权。
正在打开浏览器...
[浏览器自动打开 https://sentry.io/oauth/authorize...]
✓ 授权成功!
✓ Access token已安全存储
正在获取Sentry错误...
自動生成的配置:
{
"mcpServers": {
"sentry": {
"url": "https://mcp.sentry.dev/mcp",
"transport": "http",
"oauth": {
"authorizationUrl": "https://sentry.io/oauth/authorize",
"tokenUrl": "https://sentry.io/oauth/token",
"clientId": "mcp-claude-code-prod",
"scopes": [
"project:read",
"event:read",
"event:write",
"issue:read",
"issue:write"
],
"redirectUrl": "http://localhost:3000/callback"
}
}
}
}
Linear OAuth配置
步驟1:新增Linear MCP伺服器
claude mcp add linear \
--url https://mcp.linear.app \
--transport http \
--scope user
步驟2:OAuth授權流程
$ claude
> 列出我的Linear任务
🔐 Linear需要OAuth授权
正在打开Linear授权页面...
[Linear授权界面]
Claude Code 想要访问:
✓ 读取你的项目
✓ 读取和更新Issues
✓ 读取你的团队信息
[Allow] [Cancel]
点击"Allow"完成授权...
✓ Linear授权成功!
✓ Token已安全保存
正在获取Linear issues...
配置示例:
{
"mcpServers": {
"linear": {
"url": "https://mcp.linear.app",
"transport": "http",
"oauth": {
"authorizationUrl": "https://linear.app/oauth/authorize",
"tokenUrl": "https://api.linear.app/oauth/token",
"clientId": "auto-registered",
"scopes": ["read", "write", "issues:read", "issues:write", "projects:read"],
"redirectUrl": "http://localhost:3000/callback"
}
}
}
}
OAuth令牌管理
令牌儲存位置
# macOS - 使用Keychain
security find-generic-password \
-a "claude-code" \
-s "sentry-mcp-token" \
-w
# Linux - 使用Secret Service
secret-tool lookup claude-code sentry-mcp-token
# Windows - 使用Credential Manager
cmdkey /list | findstr sentry
令牌重新整理機制
Claude Code自動處理令牌重新整理:
// 内部刷新逻辑(伪代码)
async function callMCPWithAuth(server, tool, args) {
let token = await getStoredToken(server);
// 检查token是否即将过期
if (isTokenExpiringSoon(token)) {
console.log('Token即将过期,自动刷新...');
// 使用refresh_token获取新的access_token
const newToken = await refreshAccessToken(token.refreshToken);
// 存储新token
await storeToken(server, newToken);
// 使旧refresh_token失效
await revokeOldToken(token.refreshToken);
token = newToken;
}
// 使用access_token调用MCP
return await callMCP(server, tool, args, {
headers: {
'Authorization': `Bearer ${token.accessToken}`
}
});
}
手動撤銷授權
# 方法1:通过CLI删除服务器
claude mcp remove sentry
# 方法2:手动删除token
# macOS
security delete-generic-password -a claude-code -s sentry-mcp-token
# 方法3:在服务提供商处撤销
# 访问Sentry设置 → Applications → 撤销Claude Code权限
Sentry整合實戰
Sentry MCP伺服器功能
Sentry MCP伺服器提供了豐富的錯誤監控和除錯功能:
核心能力:
- 列出專案和Issues
- 獲取錯誤詳情和堆疊跟蹤
- 檢視事件聚合
- 觸發Seer AI根因分析
- 新增註釋和標籤
- 更新Issue狀態
配置Sentry MCP
方法1:官方遠端伺服器(推薦)
# 添加官方Sentry MCP服务器
claude mcp add sentry \
--url https://mcp.sentry.dev/mcp \
--transport http \
--scope user
方法2:自託管(企業使用者)
如果你使用自託管的Sentry例項:
{
"mcpServers": {
"sentry-self-hosted": {
"url": "https://sentry.yourcompany.com/mcp",
"transport": "http",
"oauth": {
"authorizationUrl": "https://sentry.yourcompany.com/oauth/authorize",
"tokenUrl": "https://sentry.yourcompany.com/oauth/token",
"clientId": "your-custom-client-id",
"scopes": ["project:read", "event:read", "event:write"]
},
"headers": {
"X-Sentry-Host": "sentry.yourcompany.com"
}
}
}
}
實際使用示例
示例1:快速診斷高頻錯誤
用户: 查看production项目中最近24小时错误率最高的5个问题
Claude: [通过Sentry MCP查询]
查询结果:
🔴 高频错误报告(最近24小时)
1. TypeError: Cannot read property 'user' of undefined
- 文件: src/middleware/auth.js:45
- 发生次数: 1,234次
- 影响用户: 456人
- 首次出现: 18小时前
- 链接: https://sentry.io/organizations/acme/issues/12345/
2. PaymentGatewayError: Timeout waiting for response
- 文件: src/api/payment.js:89
- 发生次数: 892次
- 影响用户: 312人
- 首次出现: 12小时前
3. ReferenceError: processOrder is not defined
- 文件: src/services/order.js:156
- 发生次数: 567次
- 影响用户: 201人
- 首次出现: 6小时前
需要我分析第一个错误的详细信息吗?
示例2:深入分析單個錯誤
用户: 分析第一个错误的根因,并使用Seer AI
Claude: [调用Sentry Seer AI工具]
正在触发Seer AI根因分析...
📊 错误分析报告
## 基本信息
- Issue ID: #12345
- 错误类型: TypeError
- 错误消息: Cannot read property 'user' of undefined
- 影响用户: 456人
- 发生次数: 1,234次
- 最近发生: 2分钟前
## 根因分析(Seer AI)
### 问题根源
auth.js中间件在处理session对象时,没有正确处理session为null的情况。
### 触发条件
1. 用户的session已过期
2. 浏览器cookie中仍然保留了过期的session ID
3. 后端尝试用这个过期的session ID获取session,返回null
4. 代码直接访问null.user,抛出TypeError
### 错误堆栈
at authenticate (src/middleware/auth.js:45:15) at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5) at next (node_modules/express/lib/router/route.js:144:13) at SessionStore.get (src/services/session.js:23:8)
### 修复建议
添加session有效性检查:
```javascript
// 在訪問req.session.user之前
if (!req.session || !req.session.user) {
return res.status(401).json({
error: 'Session expired',
code: 'SESSION_INVALID'
});
}
需要我帮你应用这个修复吗?
#### 示例3:批次更新錯誤狀態
用户: 将所有与支付相关的已解决错误标记为released
Claude: [通过Sentry MCP批量更新]
正在查找支付相关的resolved issues...
找到23个支付相关的resolved issues:
- PaymentGatewayError (#12345)
- PaymentValidationFailed (#12346)
- ...
- PaymentTimeoutError (#12367)
批量更新中... ✓ 已更新 #12345 → released ✓ 已更新 #12346 → released ✓ 已更新 #12347 → released ... ✓ 已更新 #23个issues
更新摘要:
- 从 resolved → released: 23个
- 总耗时: 3.2秒
### Sentry MCP工具參考
**可用工具列表:**
| 工具名 | 功能 | 許可權要求 |
|--------|------|----------|
| `list_projects` | 列出所有專案 | project:read |
| `list_issues` | 列出Issues | issue:read |
| `get_issue_details` | 獲取Issue詳情 | issue:read |
| `get_issue_events` | 獲取Issue的事件列表 | event:read |
| `get_event_details` | 獲取單個事件詳情 | event:read |
| `create_issue_comment` | 新增評論 | issue:write |
| `update_issue_status` | 更新狀態 | issue:write |
| `trigger_seer_ai` | 觸發AI分析 | event:read |
| `search_issues` | 搜尋Issues | issue:read |
| `get_error_tags` | 獲取錯誤標籤 | event:read |
| `add_event_tag` | 新增標籤 | event:write |
| `get_stack_trace` | 獲取堆疊跟蹤 | event:read |
| `get_breadcrumbs` | 獲取麵包屑導航 | event:read |
| `get_user_context` | 獲取使用者上下文 | event:read |
| `get_request_data` | 獲取請求資料 | event:read |
## Linear整合實戰
### Linear MCP伺服器功能
Linear是現代化的專案管理和Issue追蹤工具,其MCP伺服器提供了:
**核心能力:**
- 搜尋和列出Issues
- 建立、更新Issues
- 管理專案和工作流
- 分配任務和設定優先順序
- 新增評論和附件
- 管理標籤和狀態
### 配置Linear MCP
```bash
# 添加Linear MCP服务器
claude mcp add linear \
--url https://mcp.linear.app \
--transport http \
--scope user
首次授權:
$ claude
> 查看我的Linear任务
🔐 需要Linear授权
正在打开浏览器...
[Linear授权页面]
Claude Code 请求访问:
✓ 读取你的工作区
✓ 读取和创建Issues
✓ 读取和更新项目
✓ 读取你的团队信息
[Connect Workspace]
✓ Linear授权成功!
實際使用示例
示例1:從任務直接生成程式碼
用户: 显示分配给我的高优先级任务
Claude: [通过Linear MCP查询]
你的高优先级任务:
1. [FE-234] 实现用户头像上传功能
状态: In Progress
优先级: High
分配给: 你
预计工时: 4h
描述:
需要实现用户头像上传功能,包括:
- 支持JPG、PNG格式
- 文件大小限制5MB
- 前端裁剪为正方形
- 自动压缩为200x200
- 上传到S3存储
2. [FE-235] 优化首页加载性能
状态: Todo
优先级: Urgent
分配给: 你
预计工时: 6h
描述:
首页当前加载时间3.5秒,需要优化到1秒内。
────────────────────────────────────────
你想从哪个任务开始?
用户: 开始FE-234
Claude: [获取FE-234的详细信息]
正在读取任务详情...
任务:FE-234 - 实现用户头像上传功能
详细需求:
- 用户可以从个人设置页面上传头像
- 支持拖拽上传和点击选择文件
- 前端使用react-image-crop进行裁剪
- 后端接收上传并存储到S3
- 更新用户profile中的avatar_url字段
技术栈:
- 前端:React + react-image-crop
- 后端:Node.js + AWS SDK
- 存储:S3
- 数据库:PostgreSQL
我建议按以下步骤实现:
1. 创建前端AvatarUpload组件
2. 实现图片选择和裁剪功能
3. 创建后端API端点 /api/user/avatar
4. 实现S3上传逻辑
5. 更新数据库用户记录
开始实现第一步吗?
用户: 是的,开始
Claude: [创建AvatarUpload组件]
✓ 创建 src/components/AvatarUpload.jsx
✓ 添加react-image-crop依赖
✓ 实现文件选择功能
✓ 实现图片预览和裁剪
✓ 添加验证(格式、大小)
组件代码:
```jsx
import React, { useState, useRef } from 'react';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
export function AvatarUpload({ currentAvatar, onUploadSuccess }) {
const [crop, setCrop] = useState({ unit: '%', width: 100 });
const [src, setSrc] = useState(null);
// ... 完整實現
return (
<div className="avatar-upload">
{/* 上傳介面 */}
</div>
);
}
需要继续实现后端API吗?
```text
用户: 继续
Claude: [创建后端API端点]
✓ 创建 src/api/user/avatar.js
✓ 实现multer文件中间件
✓ 配置S3上传
✓ 添加数据库更新逻辑
✓ 错误处理和验证
API端点:
POST /api/user/avatar
Content-Type: multipart/form-data
响应:
{
"success": true,
"avatarUrl": "https://s3.../avatar-123.jpg"
}
下一步:更新Linear任务状态?
用户: 是的,标记为已完成
Claude: [通过Linear MCP更新任务]
✓ FE-234状态已更新为 "Done"
✓ 添加了完成评论:
"实现了完整的头像上传功能:
- 前端React组件 + react-image-crop
- 后端Node.js API + S3存储
- 包含文件验证、裁剪、压缩
- 单元测试覆盖率85%"
任务完成摘要:
- 创建文件:4个
- 修改文件:3个
- 添加测试:2个测试文件
- 代码行数:+350行
是否要创建pull request?
示例2:批次建立任務
用户: 根据这份需求文档创建Linear任务
需求文档:
我们要重构用户认证系统,包括以下功能:
1. 实现OAuth2.0登录(Google、GitHub)
2. 添加双因素认证(2FA)
3. 实现密码重置流程
4. 添加会话管理
5. 实现单点登录(SSO)
Claude: [通过Linear MCP批量创建]
正在分析需求并创建任务...
✓ 创建 AUTH-101: 实现OAuth2.0登录
状态: Backlog
优先级: High
预计工时: 8h
标签: authentication, oauth
✓ 创建 AUTH-102: 添加双因素认证(2FA)
状态: Backlog
优先级: High
预计工时: 12h
标签: authentication, security
✓ 创建 AUTH-103: 实现密码重置流程
状态: Backlog
优先级: Medium
预计工时: 4h
标签: authentication
✓ 创建 AUTH-104: 添加会话管理
状态: Backlog
优先级: Medium
预计工时: 6h
标签: authentication
✓ 创建 AUTH-105: 实现单点登录(SSO)
状态: Backlog
优先级: Low
预计工时: 16h
标签: authentication, sso
创建完成!共5个任务
查看项目:https://linear.app/team/PROJECT/auth-refactor
Linear MCP工具參考
可用工具列表:
| 工具名 | 功能 | 許可權要求 |
|---|---|---|
search_issues | 搜尋Issues | read |
get_issue | 獲取單個Issue詳情 | read |
create_issue | 建立新Issue | write |
update_issue | 更新Issue | write |
list_projects | 列出專案 | read |
get_teams | 獲取團隊資訊 | read |
add_comment | 新增評論 | write |
change_status | 更改狀態 | write |
assign_issue | 分配任務 | write |
set_priority | 設定優先順序 | write |
add_label | 新增標籤 | write |
其他第三方服務整合
GitHub MCP伺服器(遠端版本)
除了本地的GitHub MCP伺服器,GitHub也提供了遠端版本:
配置:
{
"mcpServers": {
"github-remote": {
"url": "https://api.githubcopilot.com/mcp/github",
"transport": "http",
"oauth": {
"authorizationUrl": "https://github.com/login/oauth/authorize",
"tokenUrl": "https://github.com/login/oauth/access_token",
"scopes": ["repo", "read:user", "read:org"]
}
}
}
}
使用示例:
用户: 列出react-app仓库最近的Pull Requests
Claude: [通过GitHub远程MCP查询]
react-app的Pull Requests(最近10个):
1. #234 - 添加暗色模式支持
作者: @alice
状态: Open
创建时间: 2小时前
审查: 2/3通过
+文件: 12行, -文件: 5行
2. #233 - 修复登录页面bug
作者: @bob
状态: Open
创建时间: 5小时前
审查: 待审查
+文件: 8行, -文件: 3行
需要查看某个PR的详细信息吗?
Notion MCP伺服器
Notion提供了官方MCP伺服器用於整合文件和知識庫:
配置:
claude mcp add notion \
--url https://mcp.notion.so \
--transport http \
--scope user
使用示例:
用户: 搜索Notion中关于"React性能优化"的页面
Claude: [通过Notion MCP搜索]
找到3个相关页面:
1. React性能优化指南
数据库: Engineering Docs
最后编辑: 2天前
内容摘要:包含useMemo、useCallback最佳实践...
2. 前端性能监控方案
数据库: Architecture
最后编辑: 1周前
内容摘要:性能指标、监控工具配置...
3. React 18新特性
数据库: Learning
最后编辑: 1个月前
内容摘要:并发渲染、Suspense详解...
需要我读取哪个页面的完整内容?
Figma MCP伺服器
Figma MCP伺服器允許Claude訪問設計檔案:
配置:
{
"mcpServers": {
"figma": {
"url": "https://mcp.figma.com",
"transport": "http",
"oauth": {
"authorizationUrl": "https://www.figma.com/oauth",
"tokenUrl": "https://www.figma.com/api/oauth/token",
"scopes": ["file_read", "comments_read"]
}
}
}
}
使用示例:
用户: 从Figma获取首页设计的颜色方案
Claude: [通过Figma MCP读取设计]
正在读取Figma文件...
设计文件:Homepage Redesign v2
页面:Desktop - Homepage
提取的颜色方案:
主色调:
- Primary Blue: #3B82F6
- Secondary Purple: #8B5CF6
- Accent Pink: #EC4899
中性色:
- Background: #FFFFFF
- Surface: #F3F4F6
- Border: #E5E7EB
文本色:
- Primary: #111827
- Secondary: #6B7280
- Disabled: #9CA3AF
需要我根据这个颜色方案更新CSS变量吗?
Slack MCP伺服器
Slack MCP伺服器用於整合團隊溝通:
配置:
claude mcp add slack \
--url https://mcp.slack.com \
--transport http \
--scope user
使用示例:
用户: 在#dev-notifications频道发送部署通知
Claude: [通过Slack MCP发送消息]
正在发送消息到#dev-notifications...
✓ 消息已发送
消息内容:
🚀 部署通知
项目: my-app
版本: v2.3.1
环境: production
状态: ✓ 成功
更改:
- 添加用户头像上传功能
- 修复登录页面bug
- 性能优化
部署者: claude-code
时间: 2025-12-25 10:30:00
需要通知其他频道吗?
自定義遠端MCP伺服器
你也可以建立自己的遠端MCP伺服器:
使用FastMCP(Python)快速建立:
# my_mcp_server.py
from fastmcp import FastMCP
import httpx
app = FastMCP("my-service")
@app.tool()
async def search_documents(query: str) -> str:
"""搜索内部文档"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://api.mycompany.com/docs/search?q={query}"
)
return response.json()
@app.tool()
async def get_user_info(user_id: str) -> dict:
"""获取用户信息"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://api.mycompany.com/users/{user_id}"
)
return response.json()
# 启动远程服务器(使用SSE传输)
if __name__ == "__main__":
app.run_sse("0.0.0.0", 8000)
部署到雲服務(如Railway):
# 安装FastMCP
pip install fastmcp
# 部署到Railway
railway up
# 获取URL
railway domain
# 配置到Claude Code
claude mcp add my-service \
--url https://my-service.railway.app/mcp \
--transport http
實用技巧和最佳實踐
技巧1:選擇性啟用伺服器
在不同場景下啟用不同的MCP伺服器:
{
"mcpServers": {
"sentry": {
"url": "https://mcp.sentry.dev/mcp",
"transport": "http",
"enabled": true,
"environments": ["production", "staging"]
},
"github": {
"url": "https://api.githubcopilot.com/mcp/github",
"transport": "http",
"enabled": true,
"environments": ["development", "production"]
},
"figma": {
"url": "https://mcp.figma.com",
"transport": "http",
"enabled": false,
"comment": "仅在需要设计时手动启用"
}
}
}
技巧2:環境隔離
為不同環境配置不同的MCP伺服器:
# 开发环境
export MCP_ENV="development"
claude mcp add sentry-dev \
--url https://sentry-dev.example.com/mcp \
--transport http \
--scope local
# 生产环境
export MCP_ENV="production"
claude mcp add sentry-prod \
--url https://sentry.example.com/mcp \
--transport http \
--scope local
技巧3:快取最佳化
對於頻繁呼叫的遠端MCP伺服器,啟用快取:
{
"mcpServers": {
"github": {
"url": "https://api.githubcopilot.com/mcp/github",
"transport": "http",
"cache": {
"enabled": true,
"ttl": 300,
"strategy": "lru"
}
}
}
}
技巧4:請求重試
配置自動重試機制:
{
"mcpServers": {
"sentry": {
"url": "https://mcp.sentry.dev/mcp",
"transport": "http",
"retry": {
"maxAttempts": 3,
"backoff": "exponential",
"initialDelay": 1000
}
}
}
}
技巧5:監控和日誌
啟用詳細的日誌記錄:
# 启动Claude Code时启用调试日志
DEBUG=mcp:* claude --verbose
# 设置日志级别
export MCP_LOG_LEVEL=debug
export MCP_LOG_FILE=/tmp/mcp.log
# 监控MCP调用
tail -f /tmp/mcp.log | grep "sentry"
最佳實踐1:安全憑證管理
# ❌ 不好:硬编码凭证
{
"mcpServers": {
"custom-server": {
"url": "https://api.example.com/mcp",
"headers": {
"Authorization": "Bearer hardcoded-token"
}
}
}
}
# ✅ 好:使用环境变量
{
"mcpServers": {
"custom-server": {
"url": "https://api.example.com/mcp",
"env": {
"API_TOKEN": "${CUSTOM_API_TOKEN}"
}
}
}
}
# 在.zshrc中设置
export CUSTOM_API_TOKEN="your-actual-token"
最佳實踐2:團隊協作
專案級配置示例:
{
"mcpServers": {
// 团队共享的服务器
"sentry": {
"url": "https://mcp.sentry.dev/mcp",
"transport": "http",
"comment": "团队统一的Sentry监控"
},
"linear": {
"url": "https://mcp.linear.app",
"transport": "http",
"comment": "团队项目管理"
}
}
}
# 提交到项目仓库
git add mcp.json
git commit -m "docs: add team MCP servers"
git push
最佳實踐3:文件化配置
在專案的README中記錄MCP配置:
## MCP服务器配置
本项目使用以下远程MCP服务器:
### Sentry(错误监控)
```bash
claude mcp add sentry \
--url https://mcp.sentry.dev/mcp \
--transport http
Linear(项目管理)
claude mcp add linear \
--url https://mcp.linear.app \
--transport http
首次设置
- 克隆仓库后,运行上述命令添加服务器
- 重启Claude Code
- 首次使用时会触发OAuth授权流程
- 在浏览器中完成授权
故障排除
如果遇到认证问题:
- 运行
claude mcp remove <server-name> - 重新添加服务器
- 清除浏览器缓存后重新授权
### 最佳實踐4:定期審計
定期審查和清理MCP伺服器:
```bash
# 列出所有服务器
claude mcp list
# 查看未使用的服务器
claude mcp audit --days 30
# 删除不用的服务器
claude mcp remove unused-server
# 测试服务器连接
claude mcp test sentry
claude mcp test linear
最佳實踐5:效能監控
監控MCP伺服器的效能:
# 查看MCP调用统计
claude mcp stats
# 输出示例:
# MCP Server Statistics (Last 7 days)
#
# Server Calls Avg Time Errors
# ────────────────────────────────────────
# sentry 234 850ms 2
# linear 156 420ms 0
# github 89 1.2s 1
#
# Total: 479 calls, 786ms avg, 3 errors
# 找出慢速服务器
claude mcp stats --sort=time
常見問題排查
問題1:OAuth授權失敗
症狀:
Error: OAuth authorization failed
Invalid client credentials
解決方案:
- 檢查OAuth配置:
# 查看服务器配置
claude mcp show sentry
# 验证OAuth端点是否正确
curl https://sentry.io/oauth/.well-known/oauth-authorization-server
- 清除舊token並重新授權:
# 删除服务器
claude mcp remove sentry
# 清除本地token
# macOS
security delete-generic-password -a claude-code -s sentry-mcp-token
# 重新添加
claude mcp add sentry --url https://mcp.sentry.dev/mcp --transport http
- 檢查網路代理:
# 如果使用代理
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# 重试授权
問題2:遠端伺服器連線超時
症狀:
Error: Connection timeout to https://mcp.example.com/mcp
Timeout after 30s
解決方案:
- 測試網路連線:
# 测试URL可访问性
curl -v https://mcp.example.com/mcp
# 检查DNS解析
nslookup mcp.example.com
# 测试端口连通性
telnet mcp.example.com 443
- 增加超時時間:
{
"mcpServers": {
"slow-server": {
"url": "https://mcp.example.com/mcp",
"transport": "http",
"timeout": 60000
}
}
}
- 使用代理:
{
"mcpServers": {
"server": {
"url": "https://mcp.example.com/mcp",
"transport": "http",
"proxy": "http://proxy.example.com:8080"
}
}
}
問題3:伺服器響應格式錯誤
症狀:
Error: Invalid MCP response format
Expected JSON-RPC, got text/html
解決方案:
- 驗證伺服器端點:
# 检查服务器是否返回正确的MCP响应
curl -X POST https://mcp.example.com/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize"}'
- 檢查傳輸協議:
# 确认服务器支持的传输协议
# 某些服务器只支持SSE,某些只支持HTTP
# 尝试切换传输方式
claude mcp remove server
claude mcp add server --url https://mcp.example.com/mcp --transport sse
- 聯絡服務提供商:
如果確認伺服器配置正確但仍有問題,可能是服務提供商的bug,可以:
- 檢視服務的狀態頁面
- 搜尋GitHub issues
- 聯絡技術支援
問題4:許可權不足
症狀:
Error: Insufficient permissions
Required scopes: ['project:read', 'event:write']
Current scopes: ['project:read']
解決方案:
- 檢查OAuth scopes:
# 查看当前授权的scopes
claude mcp show sentry --verbose
# 重新授权以获取更多权限
claude mcp remove sentry
claude mcp add sentry --url https://mcp.sentry.dev/mcp --scopes "project:read,event:read,event:write"
- 手動更新配置:
{
"mcpServers": {
"sentry": {
"url": "https://mcp.sentry.dev/mcp",
"transport": "http",
"oauth": {
"scopes": [
"project:read",
"event:read",
"event:write",
"issue:read",
"issue:write"
]
}
}
}
}
- 在服務提供商處檢查許可權:
登入Sentry/Linear等服務,檢查:
- OAuth應用許可權設定
- 使用者個人許可權
- 組織級別許可權限制
問題5:併發呼叫導致限流
症狀:
Error: Rate limit exceeded
Too many requests, please try again later
解決方案:
- 啟用速率限制:
{
"mcpServers": {
"api-with-rate-limit": {
"url": "https://api.example.com/mcp",
"transport": "http",
"rateLimit": {
"maxRequests": 10,
"perSeconds": 60,
"strategy": "token-bucket"
}
}
}
}
- 批次請求而非多次單獨請求:
❌ 不好:
用户: 列出前10个issue
用户: 列出第11-20个issue
用户: 列出第21-30个issue
✅ 好:
用户: 列出前30个issue
- 使用快取:
{
"mcpServers": {
"server": {
"cache": {
"enabled": true,
"ttl": 300
}
}
}
}
高階場景和技巧
場景1:多環境配置管理
為開發、測試、生產環境配置不同的MCP伺服器:
目錄結構:
project/
├── .claude/
│ ├── mcp.dev.json
│ ├── mcp.staging.json
│ └── mcp.prod.json
└── mcp.json (默认)
配置示例:
// .claude/mcp.dev.json
{
"mcpServers": {
"sentry": {
"url": "https://sentry-dev.example.com/mcp",
"transport": "http"
},
"local-api": {
"url": "http://localhost:3000/mcp",
"transport": "http"
}
}
}
// .claude/mcp.prod.json
{
"mcpServers": {
"sentry": {
"url": "https://sentry.example.com/mcp",
"transport": "http"
},
"datadog": {
"url": "https://mcp.datadoghq.com",
"transport": "http"
}
}
}
切換環境:
# 开发环境
export MCP_ENV=dev
claude
# 生产环境
export MCP_ENV=prod
claude
場景2:鏈式呼叫多個MCP伺服器
結合多個MCP伺服器完成複雜任務:
用户: 从Figma设计创建React组件,并在GitHub创建PR
Claude: [协调多个MCP服务器]
这个任务需要:
✓ Figma MCP - 获取设计
✓ GitHub MCP - 创建PR
✓ Filesystem MCP - 保存文件
步骤1: 从Figma获取设计
[通过Figma MCP读取设计规范]
✓ 获取到布局、颜色、字体
步骤2: 生成React组件代码
[根据设计生成代码]
✓ 创建 src/components/NewFeature.jsx
步骤3: 提交到GitHub
[通过GitHub MCP创建分支和提交]
✓ 创建分支 feature/new-design
✓ 提交代码
步骤4: 创建Pull Request
✓ PR #123已创建
✓ 包含Figma设计截图
✓ 自动添加审查者
完成!查看PR: https://github.com/repo/pull/123
場景3:自動化工作流
建立自動化工作流,定期檢查和處理問題:
# 创建定时任务(使用cron)
# 每天早上9点检查Sentry错误
cat > check-sentry.sh << 'EOF'
#!/bin/bash
# MCP自动化脚本:检查Sentry错误
export PATH="/usr/local/bin:$PATH"
echo "开始检查Sentry错误..."
# 使用Claude Code的API模式
claude --non-interactive << 'CLAUDE'
使用Sentry MCP检查最近24小时的错误:
1. 列出影响用户最多的前5个错误
2. 对于每个错误,使用Seer AI分析根因
3. 创建简明的报告
4. 如果有紧急错误(影响>100用户),发送Slack通知
CLAUDE
echo "检查完成"
EOF
# 添加到crontab
chmod +x check-sentry.sh
crontab -e
# 添加行:
0 9 * * * /path/to/check-sentry.sh >> /var/log/sentry-check.log 2>&1
場景4:自定義遠端MCP代理
建立一個自定義的MCP代理伺服器,聚合多個服務:
# mcp-proxy-server.py
from fastmcp import FastMCP
import httpx
app = FastMCP("aggregator")
@app.tool()
async def get_project_health() -> dict:
"""获取项目健康状态(聚合多个来源)"""
results = {}
# 从Sentry获取错误信息
async with httpx.AsyncClient() as client:
sentry_response = await client.get(
"https://sentry.io/api/0/projects/",
headers={"Authorization": "Bearer YOUR_TOKEN"}
)
results["sentry"] = sentry_response.json()
# 从GitHub获取PR状态
async with httpx.AsyncClient() as client:
github_response = await client.get(
"https://api.github.com/repos/user/repo/pulls",
headers={"Authorization": "Bearer YOUR_TOKEN"}
)
results["github"] = github_response.json()
# 从CI/CD获取构建状态
async with httpx.AsyncClient() as client:
ci_response = await client.get(
"https://api.circleci.com/v2/project/gh/user/repo",
headers={"Authorization": "Bearer YOUR_TOKEN"}
)
results["ci"] = ci_response.json()
return results
@app.tool()
async def create_incident_report(summary: str) -> str:
"""创建事故报告(同步到多个系统)"""
# 在Linear创建issue
# 在Slack发送通知
# 在Confluence记录文档
pass
# 启动服务器
if __name__ == "__main__":
app.run_sse("0.0.0.0", 8000)
部署和使用:
# 部署代理服务器
python mcp-proxy-server.py
# 在Claude Code中配置
claude mcp add aggregator \
--url https://aggregator.example.com/mcp \
--transport http
# 使用
claude
> 查看项目整体健康状态
[调用aggregator MCP]
> 聚合Sentry错误、GitHub PR、CI/CD状态...
效能最佳化和監控
效能最佳化技巧
1. 連線池管理
{
"mcpServers": {
"high-traffic-server": {
"url": "https://mcp.example.com",
"transport": "http",
"connection": {
"keepAlive": true,
"maxSockets": 100,
"maxFreeSockets": 10,
"timeout": 60000,
"freeSocketTimeout": 30000
}
}
}
}
2. 響應壓縮
{
"mcpServers": {
"server": {
"url": "https://mcp.example.com",
"transport": "http",
"compression": {
"enabled": true,
"algorithms": ["gzip", "br"]
}
}
}
}
3. 智慧預載入
{
"mcpServers": {
"frequently-used": {
"url": "https://mcp.example.com",
"transport": "http",
"preload": {
"enabled": true,
"tools": ["list_resources", "get_status"]
}
}
}
}
監控和除錯
啟用詳細日誌
# 设置环境变量
export DEBUG=mcp:*
export MCP_LOG_LEVEL=debug
export MCP_TRACE=http
# 启动Claude Code
claude --verbose
效能分析
# 查看MCP调用统计
claude mcp analytics
# 输出示例:
# MCP Performance Report (Last 24h)
#
# Server Calls Avg P50 P95 P99 Errors
# ─────────────────────────────────────────────────────────────
# sentry 456 890ms 720ms 1.5s 3.2s 5
# linear 234 450ms 380ms 780ms 1.1s 0
# github 123 2.1s 1.8s 4.2s 6.5s 2
#
# Recommendations:
# ⚠️ GitHub API calls are slow, consider enabling caching
# ✓ Linear performance is optimal
# ⚠️ Sentry has 5 errors, investigate
# 查看慢速调用
claude mcp analytics --slow --threshold=2000
安全最佳實踐
1. OAuth安全
使用PKCE(推薦):
{
"mcpServers": {
"secure-server": {
"url": "https://mcp.example.com",
"transport": "http",
"oauth": {
"usePkce": true,
"codeChallengeMethod": "S256"
}
}
}
}
2. Token儲存
使用系統金鑰鏈:
# macOS - Keychain
security add-generic-password \
-a "claude-code" \
-s "mcp-token" \
-w "your-access-token" \
-T "/Applications/Claude Code.app"
# Linux - Secret Service
secret-tool store --label="MCP Token" \
claude-code mcp-token \
<<EOF
your-access-token
EOF
# Windows - Credential Manager
cmdkey /generic:claude-code-mcp /user:token /pass:your-access-token
3. 網路安全
驗證SSL證書:
{
"mcpServers": {
"secure-server": {
"url": "https://mcp.example.com",
"transport": "http",
"tls": {
"rejectUnauthorized": true,
"minVersion": "TLSv1.2"
}
}
}
}
4. 最小許可權原則
只請求必要的scopes:
{
"mcpServers": {
"readonly-server": {
"url": "https://mcp.example.com",
"transport": "http",
"oauth": {
"scopes": ["read"]
// ❌ 不要请求 "write" 如果不需要
}
}
}
}
總結
遠端MCP伺服器是Claude Code生態系統的強大擴充套件,它讓AI助手能夠無縫訪問企業級SaaS服務和雲端工具。
核心要點回顧
-
傳輸協議選擇
- Streamable HTTP:推薦用於新專案
- HTTP + SSE:向後相容,實時通知
- STDIO:僅用於本地服務
-
OAuth 2.1認證
- 強制PKCE增強安全性
- 自動token重新整理
- 系統金鑰鏈安全儲存
-
主要整合
- Sentry:錯誤監控和除錯
- Linear:專案和任務管理
- GitHub:程式碼倉庫管理
- Notion/Figma/Slack:文件和協作
-
最佳實踐
- 環境隔離配置
- 團隊共享配置
- 效能監控和最佳化
- 安全憑證管理
- 定期審計和清理
-
故障排除
- OAuth授權問題
- 網路連線問題
- 許可權不足
- 速率限制
下一步探索
- MCP整合基礎 - 瞭解MCP的基本概念
- 開發自定義MCP伺服器 - 建立自己的MCP伺服器
- MCP工作流實戰 - 實際專案中的應用
參考資源
官方文件
- MCP Transports Specification
- Claude Code MCP Documentation
- Sentry MCP Server
- Linear Integration – Linear
技術文章
- Why MCP Deprecated SSE and Went with Streamable HTTP
- Anthropic's Claude Code Gets Support for Remote MCP Servers
- Introducing remote MCP servers
- Build a fully remote MCP multi-tool server with FastMCP