MCP 集成

模型上下文协议(Model Context Protocol,MCP)是一个开放标准,用于将 AI 模型连接到外部工具和数据源。LW AI 支持 MCP,可用于构建 Agent 工作流。

什么是 MCP?

MCP 支持:

  • 工具调用 —— 模型可以调用外部函数(API、数据库、文件系统)
  • 资源访问 —— 模型可以从外部源读取上下文数据
  • 提示模板 —— 标准化的提示结构,保证交互的一致性

在 LW AI 中使用 MCP

LW AI 模型通过函数调用(function calling)支持 MCP。在 API 请求中将 MCP 工具定义为函数定义即可:

from openai import OpenAI

client = OpenAI(
    base_url="https://openapi.linkwo.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
ClineVS Code 自主 Agent
Roo CodeVS Code 自主 Agent
ContinueVS Code AI 助手

最佳实践

  • 清晰描述工具 —— 优质的描述有助于模型选择正确的工具
  • 校验输入 —— 在执行前对工具输入进行清洗
  • 返回结构化数据 —— 工具结果使用 JSON 格式
  • 处理错误 —— 将错误信息作为工具结果返回,以便模型自我纠正

相关文档