MCP 是什麼?
MCP(Model Context Protocol)是 Anthropic 推出的開源協議,定義了 LLM 與外部工具/數據源之間的標準接口。它讓 Claude Code 等 AI 客戶端可以安全地訪問本地文件、數據庫、API 等外部資源。
核心概念
┌──────────────┐ MCP Protocol ┌──────────────┐
│ MCP Client │ ◄──────────────────► │ MCP Server │
│ (Claude Code)│ JSON-RPC 2.0 │ (tool/data) │
└──────────────┘ └──────────────┘
三大原語
| 原語 | 用途 | 例子 |
|---|---|---|
| Tool | 讓 LLM 執行操作 | 查詢數據庫、發送 HTTP 請求 |
| Resource | 暴露數據給 LLM | 文件內容、API 響應 |
| Prompt | 預定義提示模板 | 代碼審查模板、翻譯模板 |
Tool(工具)
Tool 讓 LLM 能夠執行操作,而不僅僅是生成文字。
內置常用 MCP Servers
# 文件系統訪問
npx @anthropic-ai/mcp-server-filesystem /path/to/allowed/dir
# GitHub 整合
npx @anthropic-ai/mcp-server-github
# PostgreSQL 查詢
npx @anthropic-ai/mcp-server-postgres
# Brave Search
npx @anthropic-ai/mcp-server-brave-search
# Puppeteer 瀏覽器
npx @anthropic-ai/mcp-server-puppeteer
配置 Claude Code 使用 MCP
編輯 ~/.claude.json:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["@anthropic-ai/mcp-server-filesystem", "/Users/me/projects"],
"env": {}
},
"github": {
"command": "npx",
"args": ["@anthropic-ai/mcp-server-github"],
"env": {
"GITHUB_TOKEN": "ghp_xxx"
}
}
}
}
配置後重啟 Claude Code,輸入 /mcp 查看已連接的 servers。
Resource(資源)
Resource 讓 LLM 能夠讀取結構化數據,無需用戶粘貼內容。
典型場景
- 數據庫 Schema:讓 LLM 了解表結構後自動生成 SQL
- API 文檔:自動讀取 OpenAPI spec,生成正確的 API 調用
- 項目結構:暴露項目文件樹,讓 LLM 理解代碼庫佈局
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["@anthropic-ai/mcp-server-postgres", "postgresql://localhost/mydb"]
}
}
}
Prompt(提示模板)
Prompt 提供可復用的提示模板,確保一致性。
{
"mcpServers": {
"review-templates": {
"command": "npx",
"args": ["@anthropic-ai/mcp-server-prompt", "--dir", "~/.claude/prompts"]
}
}
}
在 ~/.claude/prompts/ 下放置 .md 文件,即可通過 MCP 調用。
實戰:構建自定義 MCP Server
# my_mcp_server.py
from mcp.server import Server, NotificationOptions
from mcp.server.models import InitializationCapabilities
import mcp.server.stdio
import mcp.types as types
server = Server("my-tools")
@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
return [
types.Tool(
name="get_weather",
description="獲取指定城市的天氣",
inputSchema={
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名稱"}
},
"required": ["city"]
}
)
]
@server.call_tool()
async def handle_call_tool(name: str, arguments: dict):
if name == "get_weather":
city = arguments["city"]
# 實際調用天氣 API
return [types.TextContent(type="text", text=f"{city} 天氣:晴天 25°C")]
async def run():
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
await server.run(read_stream, write_stream,
InitializationCapabilities(
sampling={},
experimental={},
))
if __name__ == "__main__":
import asyncio
asyncio.run(run())
在 ~/.claude.json 中註冊:
{
"mcpServers": {
"my-tools": {
"command": "python",
"args": ["/path/to/my_mcp_server.py"]
}
}
}
安全考量
MCP Server 能訪問文件系統和網絡,需要謹慎:
- 最小權限原則:filesystem server 只暴露必要的目錄
- 環境變量隔離:敏感憑證用 env 傳遞,不寫入配置文件
- 審計日誌:定期檢查 MCP Server 的訪問記錄
- 不要暴露
/根目錄:限制 filesystem server 的訪問範圍