意项
39.91M · 2026-03-23
大语言模型(LLM)的本质,是一个基于概率的文本生成器。它通过海量语料学习语言模式,能在给定上下文下预测下一个最可能的 token。这种能力让它在信息整合、逻辑推理、创意生成上表现出色。
但它存在三个根本性局限:
LLM 的知识完全来源于训练数据,无法感知外部状态。
LLM 的输出只是文本,不会改变现实世界的状态。
rm -rf /,但不会真的删除你的系统每次对话都是“全新开始”(除非使用上下文窗口),无法记住:
真正的突破,来自于将 LLM 与可执行工具结合,形成 AI Agent(智能体) 。
表格
| 工具 | 能力 | 典型场景 |
|---|---|---|
readFile(path) | 读取任意文件内容 | 分析现有代码、读取配置 |
writeFile(path, content) | 写入/覆盖文件 | 生成新文件、修复 bug |
listDirectory(path) | 列出目录结构 | 了解项目布局 |
executeCommand(cmd, { cwd }) | 执行终端命令 | 安装依赖、启动服务、构建项目 |
import { spawn } from 'child_process';
import { writeFile } from 'fs/promises';
async function handleTask(task) {
if (task.includes('创建 React 项目')) {
// 1. 执行命令创建项目
await new Promise((resolve, reject) => {
const proc = spawn('pnpm', ['create', 'vite', 'my-todo-app', '--template', 'react-ts']);
proc.on('close', (code) => code === 0 ? resolve() : reject(new Error('创建失败')));
});
// 2. 写入自定义 README
await writeFile('my-todo-app/README.md', '# AI 生成的 Todo Appn由全栈 Agent 自动创建');
// 3. 返回结果
return ' 项目 my-todo-app 已创建并初始化!';
}
return '未识别任务';
}
甜头来了:AI 真的能干活了!
然而,随着工具数量增加,新的复杂性浮现:
表格
| 问题 | 描述 |
|---|---|
| 语言壁垒 | Python 数据分析脚本无法被 Node.js Agent 调用 |
| 部署隔离 | 公司内部 Java 微服务运行在 Kubernetes,如何安全暴露? |
| 协议混乱 | 有的工具用 REST,有的用 gRPC,有的直接读 stdin/stdout |
| 参数不一致 | 同一个“读文件”功能,A 工具叫 filePath,B 工具叫 path |
cd dir && cmd 而工具已设 cwd),命令直接失败2024 年底,Anthropic 提出并开源 Model Context Protocol(MCP) ,旨在解决上述问题。
表格
| 能力 | 技术实现 | 价值 |
|---|---|---|
| 跨语言 | 工具以独立进程运行,通过 stdio/HTTP 通信 | Python/Rust/Java 工具均可接入 |
| 跨进程 | 支持本地子进程(stdio)和远程服务(HTTP) | 本地开发 & 企业级部署统一 |
| 可发现 | 动态调用 mcp.list_tools 获取工具元数据 | LLM 知道“能做什么”,不再靠猜 |
表格
| 方式 | 适用场景 | 安全性 |
|---|---|---|
stdio | 本地工具(如文件操作、CLI) | 高(子进程隔离) |
HTTP | 远程服务(如数据库、API 网关) | 中(需鉴权/HTTPS) |
// file-tool.mjs
import { McpServer } from '@modelcontextprotocol/sdk';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server';
import { readFile, readdir } from 'fs/promises';
const server = new McpServer();
// 注册 readFile 工具
server.registerTool({
name: 'read_file',
description: '读取指定路径的文件内容',
inputSchema: {
type: 'object',
properties: { path: { type: 'string', description: '文件绝对路径' } },
required: ['path']
},
handler: async ({ path }) => {
const content = await readFile(path, 'utf8');
return { content };
}
});
// 注册 list_directory 工具
server.registerTool({
name: 'list_directory',
description: '列出目录下的文件和子目录',
inputSchema: {
type: 'object',
properties: { path: { type: 'string' } },
required: ['path']
},
handler: async ({ path }) => {
const files = await readdir(path);
return { files };
}
});
// 启动 stdio 服务(适合本地调用)
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('MCP File Tool Server Ready');
理解 MCP,必须厘清三个角色的职责边界:
表格
| 角色 | 职责 | 技术实现 |
|---|---|---|
| MCP Host | Agent 的“大脑载体”,负责任务调度、LLM 调用、结果整合 | Cursor、Windsurf、LangChain Agent Executor |
| MCP Client | Host 内置的通信适配器,封装 MCP 协议细节 | @modelcontextprotocol/client 或 LangChain 的 McpToolkit |
| MCP Server | 工具的实际提供者,独立进程/服务,处理具体业务逻辑 | 上述 file-tool.mjs,或 Python/Rust 编写的工具服务 |
初始化阶段
Host 启动 MCP Client,连接 Server(spawn 子进程 or HTTP 请求)
→ 发送 { "method": "mcp.list_tools" }
← Server 返回工具列表及 JSON Schema
任务执行阶段
read_file){ "method": "read_file", "params": { "path": "src/App.tsx" } }fs.readFile,返回 { "result": { "content": "..." } }ToolMessage(content=..., tool_call_id=...),追加到对话上下文一个生产级 Agent 需要四大支柱:
text
编辑
AI Agent = LLM + Tools + Memory + RAG
LLM 的知识截止于训练数据(如 GPT-4 截止 2023 年),面对:
它会“自信地胡说”。
// 1. 加载多种格式文档
const loaders = [
new TextLoader('docs/policy.txt'),
new PDFLoader('docs/handbook.pdf'),
new WebBaseLoader('https://internal.wiki/api-guide')
];
const docs = await Promise.all(loaders.map(l => l.load()));
// 2. 智能切片(按语义而非固定长度)
const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 500 });
const chunks = await splitter.splitDocuments(docs.flat());
// 3. 向量化存储
const vectorStore = await Chroma.fromDocuments(chunks, new OpenAIEmbeddings());
// 4. 构建带记忆的 RAG 链
const chain = new RetrievalQAChain({
llm: new ChatOpenAI(),
retriever: vectorStore.asRetriever({ k: 3 }),
memory: new ConversationSummaryMemory({ llm: new ChatOpenAI() })
});
// 5. 调用
const res = await chain.call({ query: '如何申请年假?' });
// → 答案严格基于公司制度文档,无幻觉
MCP 的普及,正在引发一场“应用层革命”:
今天:用户需下载淘宝、美团、滴滴、Notion……
未来:用户只需一个 Universal Agent,通过自然语言调用 MCP 服务:
表格
| 公司 | MCP 服务示例 | 价值 |
|---|---|---|
| GitHub | github_mcp:创建 PR、查 issue、管理 repo | 开发者无需离开 IDE |
| AWS | aws_mcp:启停 EC2、查账单、监控告警 | 运维自动化 |
| Salesforce | crm_mcp:查客户、更新商机、发邮件 | 销售效率提升 |
| 你的公司 | erp_mcp / db_mcp / bi_mcp | 内部系统 AI 化 |
案例:“OpenClaw养虾”
一个开发者构建多 Agent 协同系统:
如果你是一名开发者,现在就是布局全栈 Agent 的最佳时机:
学习 MCP 协议
@modelcontextprotocol/sdk将现有服务 MCP 化
# 示例:把内部 CLI 工具包装成 MCP Server
npx mcp-wrap --command="my-cli-tool" --name="internal_tool"
构建自己的 Agent Host
集成:
推荐框架:LangChain(实验性 MCP 支持)、LlamaIndex、自研
npm install @modelcontextprotocol/sdk我们正站在一个新时代的门槛上:
AI 不再是聊天窗口里的“聪明朋友”,而是能替你工作的“数字员工”。
而这一切,才刚刚开始。