Agent调用MCP服务
·
参考
一些模型服务
白山智算
智谱 AI apiKey
miniMax
阿里百炼
字节火山引擎
aistudio.google
美团 longcat
packyapi
模型腾讯文档
安装依赖
MCP
npm install @modelcontextprotocol/sdk zod ming_node
@anthropic-ai/sdk
npm install @anthropic-ai/sdk
openai
npm install openai
mcp_server.js
import { z } from 'zod';
import M from "ming_node";
import MyMcpServer from "./lib/StdioMcpServer.js";
const app=new MyMcpServer("my_mcp_server");
app.listen(3000);
app.begin((req,res)=>{
M.log("开始执行",req.mcpName,JSON.stringify(req.params));
})
app.end((req,res)=>{
M.log("执行完成",req.mcpName,res.result);
})
app.get("加法",{
a:z.number(),
b:z.number(),
},async (req,res)=>{
const {a,b}=req.params;
const c=a+b+1;
res.send(c);
});
app.get("设置转速",{ speed:z.number()},async (req,res)=>{
const {speed}=req.params;
M.log(`转速设置为 ${speed}`);
res.send("转速设置完成");
});
anthropic_agent.js
import Anthropic from "@anthropic-ai/sdk";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
// ─────────────────────────────────────────────
// 配置区(需要修改时只动这里)
// ─────────────────────────────────────────────
const CONFIG = {
api: {
apiKey: "YOUR_API_KEY",
baseURL: "https://api.longcat.chat/anthropic",
model: "LongCat-Flash-Chat",
// ── messages.create 全参数 ──────────────
maxTokens: 1024, // 最大输出 token 数(必填)
system: "你是一个智能助手,请用中文回答。", // 系统提示词
temperature: 1.0, // 随机性 0~1(与 top_p 二选一)
// top_p: 0.9, // 核采样(与 temperature 二选一)
// top_k: 50, // 只从概率最高的 K 个 token 中采样
// stopSequences: ["END"], // 遇到这些字符串时停止生成
// toolChoice: "auto", // auto | any | none | { type:"tool", name:"xx" }
// metadata: { user_id: "u1" }, // 请求元数据
// stream: false, // 是否流式返回
},
server: {
command: "node",
args: ["mcp_server.js"], // 切换 MCP Server 只改这里
},
};
// ─────────────────────────────────────────────
// 初始化 Anthropic 客户端
// ─────────────────────────────────────────────
function createAnthropicClient() {
return new Anthropic({
apiKey: CONFIG.api.apiKey,
baseURL: CONFIG.api.baseURL,
defaultHeaders: {
"Authorization": `Bearer ${CONFIG.api.apiKey}`,
"x-api-key": CONFIG.api.apiKey,
},
});
}
// ─────────────────────────────────────────────
// 初始化 MCP 客户端
// ─────────────────────────────────────────────
async function createMcpClient() {
const transport = new StdioClientTransport(CONFIG.server);
const client = new Client({ name: "agent", version: "1.0.0" }, { capabilities: {} });
await client.connect(transport);
return client;
}
// MCP 工具格式 → Claude 工具格式
function toClaudeTool(tool) {
return {
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema,
};
}
// ─────────────────────────────────────────────
// Agent 主循环
// ─────────────────────────────────────────────
async function runAgent(anthropic, mcpClient, tools, userMessage) {
console.log(`\n${"─".repeat(48)}`);
console.log(`👤 ${userMessage}`);
console.log("─".repeat(48));
const messages = [{ role: "user", content: userMessage }];
while (true) {
const response = await anthropic.messages.create({
// ── 必填 ────────────────────────────
model: CONFIG.api.model,
max_tokens: CONFIG.api.maxTokens,
messages,
// ── 可选(从 CONFIG 读取,注释掉的参数不传) ──
system: CONFIG.api.system,
temperature: CONFIG.api.temperature,
tools,
// top_p: CONFIG.api.top_p,
// top_k: CONFIG.api.top_k,
// stop_sequences: CONFIG.api.stopSequences,
// tool_choice: CONFIG.api.toolChoice,
// metadata: CONFIG.api.metadata,
// stream: CONFIG.api.stream,
});
// Claude 回复纯文本 → 任务完成
if (response.stop_reason === "end_turn") {
const text = response.content.find(b => b.type === "text")?.text;
if (text) console.log(`\n🤖 ${text}`);
break;
}
// Claude 请求调用工具
if (response.stop_reason === "tool_use") {
messages.push({ role: "assistant", content: response.content });
const toolResults = await executeTools(mcpClient, response.content);
messages.push({ role: "user", content: toolResults });
}
}
}
// 执行本轮所有工具调用,返回结果列表
async function executeTools(mcpClient, contentBlocks) {
const results = [];
for (const block of contentBlocks.filter(b => b.type === "tool_use")) {
console.log(`🔧 ${block.name}(${JSON.stringify(block.input)})`);
const result = await mcpClient.callTool({
name: block.name,
arguments: block.input,
});
const text = result.content[0]?.text ?? "";
console.log(` → ${text}`);
results.push({
type: "tool_result",
tool_use_id: block.id,
content: text,
});
}
return results;
}
// ─────────────────────────────────────────────
// 入口
// ─────────────────────────────────────────────
async function main() {
const anthropic = createAnthropicClient();
const mcpClient = await createMcpClient();
try {
const { tools: mcpTools } = await mcpClient.listTools();
const tools = mcpTools.map(toClaudeTool);
console.log(`🔌 已连接,可用工具:${tools.map(t => t.name).join(", ")}`);
// ↓ 在这里添加更多对话
await runAgent(anthropic, mcpClient, tools, "帮我算一下 12 + 34,然后把转速设置为 300");
} finally {
await mcpClient.close();
}
}
main();
openai_agent.js
import OpenAI from "openai";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
// ─────────────────────────────────────────────
// 配置区(需要修改时只动这里)
// ─────────────────────────────────────────────
const CONFIG = {
api: {
apiKey: "YOUR_API_KEY", // 替换为你的apiKey
baseURL: "https://api.edgefn.net/v1",
model: "GLM-4.7",
maxTokens: 1024,
system: "你是一个智能助手,请用中文回答。",
temperature: 1.0,
},
server: {
command: "node",
args: ["mcp_server.js"],
},
};
// ─────────────────────────────────────────────
// 初始化 OpenAI 客户端
// ─────────────────────────────────────────────
function createOpenAIClient() {
return new OpenAI({
apiKey: CONFIG.api.apiKey,
baseURL: CONFIG.api.baseURL,
});
}
// ─────────────────────────────────────────────
// 初始化 MCP 客户端
// ─────────────────────────────────────────────
async function createMcpClient() {
const transport = new StdioClientTransport(CONFIG.server);
const client = new Client({ name: "agent", version: "1.0.0" }, { capabilities: {} });
await client.connect(transport);
return client;
}
// MCP 工具格式 → OpenAI 工具格式
function toOpenAITool(tool) {
return {
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema,
},
};
}
// ─────────────────────────────────────────────
// Agent 主循环
// ─────────────────────────────────────────────
async function runAgent(openai, mcpClient, tools, userMessage) {
console.log(`\n${"─".repeat(48)}`);
console.log(`👤 ${userMessage}`);
console.log("─".repeat(48));
const messages = [
{ role: "system", content: CONFIG.api.system },
{ role: "user", content: userMessage },
];
while (true) {
const response = await openai.chat.completions.create({
model: CONFIG.api.model,
max_tokens: CONFIG.api.maxTokens,
temperature: CONFIG.api.temperature,
messages,
tools,
tool_choice: "auto",
// top_p: CONFIG.api.top_p,
// stop: CONFIG.api.stop,
// stream: CONFIG.api.stream,
});
const message = response.choices[0].message;
const finishReason = response.choices[0].finish_reason;
// 纯文本回复 → 任务完成
if (finishReason === "stop") {
if (message.content) console.log(`\n🤖 ${message.content}`);
break;
}
// 模型请求调用工具
if (finishReason === "tool_calls") {
// 把 assistant 消息(含 tool_calls)追加进历史
messages.push(message);
// 执行所有工具并把结果追加进历史
const toolResults = await executeTools(mcpClient, message.tool_calls);
messages.push(...toolResults);
}
}
}
// 执行本轮所有工具调用,返回结果消息列表
async function executeTools(mcpClient, toolCalls) {
const results = [];
for (const call of toolCalls) {
const name = call.function.name;
const input = JSON.parse(call.function.arguments);
console.log(`🔧 ${name}(${JSON.stringify(input)})`);
const result = await mcpClient.callTool({ name, arguments: input });
const text = result.content[0]?.text ?? "";
console.log(` → ${text}`);
results.push({
role: "tool",
tool_call_id: call.id,
content: text,
});
}
return results;
}
// ─────────────────────────────────────────────
// 入口
// ─────────────────────────────────────────────
async function main() {
const openai = createOpenAIClient();
const mcpClient = await createMcpClient();
try {
const { tools: mcpTools } = await mcpClient.listTools();
const tools = mcpTools.map(toOpenAITool);
console.log(`🔌 已连接,可用工具:${tools.map(t => t.function.name).join(", ")}`);
await runAgent(openai, mcpClient, tools, "帮我算一下 12 + 34,然后把转速设置为 300");
} finally {
await mcpClient.close();
}
}
main();
测试
$ node anthropic_agent.js
🔌 已连接,可用工具:加法, 设置转速
────────────────────────────────────────────────
👤 帮我算一下 12 + 34,然后把转速设置为 300
────────────────────────────────────────────────
🔧 加法({"a":12,"b":34})
→ 47
🔧 设置转速({"speed":300})
→ 转速设置完成
🤖 计算结果为 46,转速已设置为 300
更多推荐



所有评论(0)