
什么是 MCP 服务器?Model Context Protocol 全面指南
了解 MCP(模型上下文协议)服务器是什么、如何工作,以及它们为何正在革新 AI 集成。探索 MCP 如何简化 AI 智能体与工具、数据源和 API 的连接。...
模型上下文协议(MCP)是一种开放标准接口,使大型语言模型(LLM)能够安全、一致地访问外部数据源、工具和能力,被誉为 AI 系统的“USB-C”。
模型上下文协议(MCP) 是一种开放标准接口,使大型语言模型(LLM)能够安全、一致地访问外部数据源、工具和能力。它在 AI 应用与多种上下文提供者之间建立了标准化的通信层,相当于 AI 系统的“USB-C”。
MCP 遵循客户端-服务器架构:
MCP 定义了三种构建协议的基础原语:
资源 代表 MCP 服务器向 LLM 提供的数据与内容。
用例示例:MCP 服务器将日志文件以 file:///logs/app.log 作为资源对外暴露
提示 是服务器提供的预定义模板或工作流,用于引导 LLM 交互。
用例示例:一个 git 提交信息生成器提示,接受代码变更作为输入
工具 暴露可由 LLM 调用(通常需用户批准)的可执行函数,用于执行操作。
用例示例:一个计算器工具,对模型提供的输入执行数学运算
// 服务器将单个日志文件作为资源暴露
const server = new Server({ /* config */ }, { capabilities: { resources: {} } });
// 列出可用资源
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: "file:///logs/app.log",
name: "Application Logs",
mimeType: "text/plain"
}
]
};
});
// 提供资源内容
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
if (request.params.uri === "file:///logs/app.log") {
const logContents = await readLogFile();
return {
contents: [{
uri: request.params.uri,
mimeType: "text/plain",
text: logContents
}]
};
}
throw new Error("Resource not found");
});
const server = new Server({ /* config */ }, { capabilities: { tools: {} } });
// 列出可用工具
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [{
name: "calculate_sum",
description: "Add two numbers together",
inputSchema: {
type: "object",
properties: {
a: { type: "number", description: "First number" },
b: { type: "number", description: "Second number" }
},
required: ["a", "b"]
},
annotations: {
title: "Calculate Sum",
readOnlyHint: true,
openWorldHint: false
}
}]
};
});
// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "calculate_sum") {
try {
const { a, b } = request.params.arguments;
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error("Invalid input: 'a' and 'b' must be numbers.");
}
const sum = a + b;
return {
content: [{ type: "text", text: String(sum) }]
};
} catch (error: any) {
return {
isError: true,
content: [{ type: "text", text: `Error calculating sum: ${error.message}` }]
};
}
}
throw new Error("Tool not found");
});

了解 MCP(模型上下文协议)服务器是什么、如何工作,以及它们为何正在革新 AI 集成。探索 MCP 如何简化 AI 智能体与工具、数据源和 API 的连接。...

探索全面的MCP服务器示例,学习如何构建、部署和集成模型上下文协议(MCP)服务器,以提升AI代理在企业系统中的能力。...

学习如何开发能够无缝集成 OpenAI API 的模型上下文协议(MCP)服务器,实现强大的 AI 驱动工具执行与智能自动化。