一、背景与痛点

说实话,最近大半年 MCP(Model Context Protocol)这个词在 AI 开发圈火得不行。但你翻遍全网,大部分教程要么是概念解读,要么是复制粘贴官方文档,真正能动手搭一个可运行 Agent的少之又少。

说白了,MCP 就是给 AI 模型配了一个"工具箱"。以前模型只能跟你聊天,现在它能调用外部工具、查数据库、写文件、发请求。这才是 Agent 该有的样子。

这篇文章不讲虚的,直接带你从零搭一个能用 MCP 协议跟外部工具交互的 Agent。

MCP协议架构示意图

二、环境准备

先搭好基础环境:

# 创建项目目录
mkdir mcp-agent-demo && cd mcp-agent-demo

# 初始化 Node.js 项目
npm init -y

# 安装依赖
npm install @modelcontextprotocol/sdk openai dotenv

版本要求:

  • Node.js >= 18.x
  • npm >= 9.x
  • OpenAI API Key(或其他兼容 API)

三、核心概念速览

MCP 协议的核心就三个东西:

  1. Client — 发起请求的 Agent
  2. Server — 提供工具的服务端
  3. Tool — 具体的功能接口

MCP三大组件关系

用大白话说:

  • Agent 想查天气 → 调用 MCP Client 发请求
  • MCP Server 收到请求 → 调用天气 API
  • 结果返回给 Agent → Agent 整合后回复你

四、搭建 MCP Server(提供工具)

先写一个最简单的 MCP Server,提供两个工具:获取时间和获取天气。

// server.js
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server({
  name: 'my-tools-server',
  version: '1.0.0',
}, {
  capabilities: { tools: {} }
});

// 注册工具列表
server.setRequestHandler('tools/list', async () => ({
  tools: [
    {
      name: 'get_current_time',
      description: '获取当前时间',
      inputSchema: {
        type: 'object',
        properties: {
          timezone: { type: 'string', description: '时区,如 Asia/Shanghai' }
        }
      }
    },
    {
      name: 'get_weather',
      description: '获取指定城市的天气',
      inputSchema: {
        type: 'object', 
        properties: {
          city: { type: 'string', description: '城市名称' }
        },
        required: ['city']
      }
    }
  ]
}));

五、搭建 MCP Client(Agent 核心)

Client 端负责:连接 Server → 获取工具列表 → 让 LLM 决定调哪个工具 → 执行工具调用 → 返回结果给 LLM。

// client.js
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const transport = new StdioClientTransport({
  command: 'node',
  args: ['server.js']
});

const client = new Client({
  name: 'my-agent-client',
  version: '1.0.0'
});

await client.connect(transport);
const tools = await client.listTools();
console.log('可用工具:', tools);

六、Agent 推理循环

这是最核心的部分——让 LLM 自己决定要不要调用工具:

async function agentLoop(userMessage) {
  const messages = [{ role: 'user', content: userMessage }];
  
  while (true) {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages,
      tools: tools.map(t => ({
        type: 'function',
        function: {
          name: t.name,
          description: t.description,
          parameters: t.inputSchema
        }
      }))
    });

    const choice = response.choices[0];
    
    // 如果 LLM 决定调用工具
    if (choice.finish_reason === 'tool_calls') {
      for (const toolCall of choice.message.tool_calls) {
        const result = await client.callTool({
          name: toolCall.function.name,
          arguments: JSON.parse(toolCall.function.arguments)
        });
        messages.push({
          role: 'tool',
          tool_call_id: toolCall.id,
          content: JSON.stringify(result.content)
        });
      }
    } else {
      return choice.message.content;
    }
  }
}

Agent推理循环流程图

七、常见问题 Q&A

Q:MCP 和 Function Calling 有什么区别?
A:Function Calling 是 OpenAI 的私有协议,MCP 是 Anthropic 推出的开放标准。MCP 的好处是跨模型、跨平台,不管用 GPT、Claude 还是本地模型都能跑。

Q:可以跑在浏览器里吗?
A:目前 MCP 主要面向 Node.js 服务端环境,浏览器端需要额外的 WebSocket 桥接。

Q:安全性怎么保证?
A:建议对工具做权限分级,比如只读工具(查天气)不需要鉴权,写操作工具(写文件)需要用户确认。

八、总结

MCP 协议正在成为 AI Agent 开发的"标准协议"。学会搭建 MCP 架构,你就掌握了让 AI 真正"动手干活"的能力。下一步可以试试:

  1. 接入更多工具(数据库、API、文件系统)
  2. 用 SSE 替代 Stdio 实现远程调用
  3. 加一层 Agent 路由实现多 Agent 协作

觉得有用的话点个赞,有疑问评论区见 👇

Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐