MCP 集成
模型上下文協議(Model Context Protocol,MCP)是一個開放标準,用於將 AI 模型連接到外部工具和數據源。Link Astra 支援 MCP,可用於構建 Agent 工作流。
什么是 MCP?
MCP 支援:
- 工具調用 —— 模型可以調用外部函數(API、數據庫、文件系統)
- 資源訪問 —— 模型可以從外部源讀取上下文數據
- 提示模板 —— 标準化的提示結構,保證交互的一致性
在 Link Astra 中使用 MCP
Link Astra 模型通過函數調用(function calling)支援 MCP。在 API 請求中將 MCP 工具定義為函數定義即可:
from openai import OpenAI
client = OpenAI(
base_url="https://api.linkastra.ai/v1",
api_key="YOUR_API_KEY"
)
mcp_tools = [
{
"type": "function",
"function": {
"name": "query_database",
"description": "Query the company database",
"parameters": {
"type": "object",
"properties": {
"sql": {"type": "string", "description": "SQL query to execute"},
"database": {"type": "string", "enum": ["production", "staging"]}
},
"required": ["sql"]
}
}
},
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read a file from the project directory",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path relative to project root"}
},
"required": ["path"]
}
}
}
]
response = client.chat.completions.create(
model="deepseek/deepseek-v4-pro",
messages=[{"role": "user", "content": "Show me the user table schema"}],
tools=mcp_tools,
tool_choice="auto"
)MCP 伺服器搭建
要通過 MCP 協議暴露你的工具,可以構建一個 MCP 伺服器:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new McpServer({ name: "my-tools", version: "1.0.0" });
server.tool("query_database", { sql: z.string() }, async ({ sql }) => {
const results = await executeQuery(sql);
return { content: [{ type: "text", text: JSON.stringify(results) }] };
});
const transport = new StdioServerTransport();
await server.connect(transport);兼容的 MCP 客戶端
| 客戶端 | 說明 |
|---|---|
| Claude Code | 基於終端的編程 Agent |
| Cline | VS Code 自主 Agent |
| Roo Code | VS Code 自主 Agent |
| Continue | VS Code AI 助手 |
最佳實踐
- 清晰描述工具 —— 優質的描述有助於模型選擇正確的工具
- 校驗輸入 —— 在执行前對工具輸入进行清洗
- 返回結構化數據 —— 工具結果使用 JSON 格式
- 處理錯誤 —— 將錯誤資訊作為工具結果返回,以便模型自我纠正
相關文件
- 函數調用 —— 详細的工具調用指南
- Claude Code —— Claude Code 配置