521 - 《手写基于 MCP Client 的 Agent》
发布于 2025年2月9日
1、Agent = LLM + Tools。MCP Server 是目前唯一的 tools 标准,当然他不仅有 tools 还有 resouces 和 prompts,只不过大家都只用他的 tools 部分而已。参考 520 - 《Cursor 和 MCP》,现在已有大量 MCP Server,社区有的就不需要手动重新实现一遍,同时照着这个趋势,MCP Server 会越来越多。所以写一个 Agent,只要基于 MCP Servers,再补上自己特有的 tools 实现即可。
2、我写了个极简的 Agent,通过 MCP Client 和 MCP Server 交互来扩展能力,比如问「how old is Zhang Zi Yi? Please search with brave_web_search」,他会用 brave_web_search 这个 server 提供的 tool 去做 web 搜索,然后再提供结果。
1)写了个 clientToTools 方法,把 MCP Client 转成标准的 tools
2)用 ai 包,可以简化下 openai 对 tools 的调用
import { createOpenAI } from '@ai-sdk/openai';
import * as pc from 'picocolors';
import { CoreMessage, generateText, tool } from 'ai';
import type { CoreTool } from 'ai';
import assert from 'assert';
import { z } from 'zod';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { jsonSchemaToZod } from '@n8n/json-schema-to-zod';
interface AgentOptions {
model?: string;
apiKey?: string;
}
export async function run(opts: AgentOptions) {
const transport = new StdioClientTransport({
command: 'env',
args: [
'BRAVE_API_KEY=YOUR_KEY',
'npx',
'-y',
'@modelcontextprotocol/server-brave-search',
],
});
const client = new Client({
name: 'brave_search',
version: '1.0.0',
});
await client.connect(transport);
const tools = await clientToTools(client);
const { model = 'gpt-3.5-turbo' } = opts;