使用说明
带Node.js的MCP TypeScript服务器
什么是MCP?
这 模型上下文协议(MCP) 允许您构建以安全、标准化的方式向LLM应用程序公开数据和功能的服务器。将其视为一个web API,但它是专门为LLM交互而设计的。MCP服务器可以:
- 通过以下方式公开数据 资源 (将这些类似于GET端点;它们用于将信息加载到LLM的上下文中)
- 通过以下方式提供功能 工具 (有点像POST端点;它们用于执行代码或产生副作用)
- 通过以下方式定义交互模式 鼓励 (LLM交互的可重用模板)
- 还有更多!
资源
资源是您向LLM公开数据的方式。它们类似于REST API中的GET端点-它们提供数据,但不应执行显著的计算或产生副作用:
// Static resource
server.resource(
"config",
"config://app",
async (uri) => ({
contents: [{
uri: uri.href,
text: "App configuration here"
}]
})
);
// Dynamic resource with parameters
server.resource(
"user-profile",
new ResourceTemplate("users://{userId}/profile", { list: undefined }),
async (uri, { userId }) => ({
contents: [{
uri: uri.href,
text: `Profile data for user ${userId}`
}]
})
);
工具
工具允许LLM通过您的服务器执行操作。与资源不同,工具被期望执行计算并具有副作用:
// Simple tool with parameters
server.tool(
"calculate-bmi",
{
weightKg: z.number(),
heightM: z.number()
},
async ({ weightKg, heightM }) => ({
content: [{
type: "text",
text: String(weightKg / (heightM * heightM))
}]
})
);
// Async tool with external API call
server.tool(
"fetch-weather",
{ city: z.string() },
async ({ city }) => {
const response = await fetch(`https://api.weather.com/${city}`);
const data = await response.text();
return {
content: [{ type: "text", text: data }]
};
}
);
鼓励
提示是可重用的模板,可帮助LLM与您的服务器有效交互:
server.prompt(
"review-code",
{ code: z.string() },
({ code }) => ({
messages: [{
role: "user",
content: {
type: "text",
text: `Please review this code:\n\n${code}`
}
}]
})
);
贡献
捐款总是受欢迎的!
