FastMCP 是一个专为构建 Model Context Protocol (MCP) 服务器而设计的 TypeScript 框架。它提供了一套完整的工具和功能,使开发者能够快速创建能够处理客户端会话的高性能 MCP 服务器。
项目地址: https://github.com/punkpeye/fastmcp
npm install fastmcp
import { FastMCP } from "fastmcp";
import { z } from "zod";
const server = new FastMCP({
name: "My Server",
version: "1.0.0",
});
server.addTool({
name: "add",
description: "Add two numbers",
parameters: z.object({
a: z.number(),
b: z.number(),
}),
execute: async (args) => {
return String(args.a + args.b);
},
});
server.start({
transportType: "stdio",
});
工具允许服务器向客户端公开可执行的函数,这些函数可以被客户端调用并被LLM用于执行操作。
import { z } from "zod";
server.addTool({
name: "fetch-zod",
description: "Fetch the content of a url (using Zod)",
parameters: z.object({
url: z.string(),
}),
execute: async (args) => {
return await fetchWebpageContent(args.url);
},
});
工具可以包含注解,提供更丰富的上下文和控制信息:
server.addTool({
name: "fetch-content",
description: "Fetch content from a URL",
parameters: z.object({
url: z.string(),
}),
annotations: {
title: "Web Content Fetcher",
readOnlyHint: true,
openWorldHint: true,
},
execute: async (args) => {
return await fetchWebpageContent(args.url);
},
});
资源代表MCP服务器希望向客户端提供的任何类型的数据,包括:
server.addResource({
uri: "file:///logs/app.log",
name: "Application Logs",
mimeType: "text/plain",
async load() {
return {
text: await readLogFile(),
};
},
});
server.addResourceTemplate({
uriTemplate: "file:///logs/{name}.log",
name: "Application Logs",
mimeType: "text/plain",
arguments: [
{
name: "name",
description: "Name of the log",
required: true,
},
],
async load({ name }) {
return {
text: `Example log content for ${name}`,
};
},
});
提示使服务器能够定义可重用的提示模板和工作流:
server.addPrompt({
name: "git-commit",
description: "Generate a Git commit message",
arguments: [
{
name: "changes",
description: "Git diff or description of changes",
required: true,
},
],
load: async (args) => {
return `Generate a concise but descriptive commit message for these changes:\n\n${args.changes}`;
},
});
FastMCP支持自定义身份验证功能:
import { AuthError } from "fastmcp";
const server = new FastMCP({
name: "My Server",
version: "1.0.0",
authenticate: ({ request }) => {
const apiKey = request.headers["x-api-key"];
if (apiKey !== "123") {
throw new Response(null, {
status: 401,
statusText: "Unauthorized",
});
}
return {
id: 1,
};
},
});
支持实时通信的SSE功能:
server.start({
transportType: "sse",
sse: {
endpoint: "/sse",
port: 8080,
},
});
FastMCP为每个客户端连接分配新的服务器实例,实现1:1通信:
server.on("connect", (event) => {
console.log("Client connected:", event.session);
});
server.on("disconnect", (event) => {
console.log("Client disconnected:", event.session);
});
npx fastmcp dev src/examples/addition.ts
npx fastmcp inspect src/examples/addition.ts
在Claude Desktop中添加配置:
{
"mcpServers": {
"my-mcp-server": {
"command": "npx",
"args": ["tsx", "/PATH/TO/YOUR_PROJECT/src/index.ts"],
"env": {
"YOUR_ENV_VAR": "value"
}
}
}
}
FastMCP已被多个项目采用,包括:
FastMCP是一个功能强大、易于使用的TypeScript框架,为构建MCP服务器提供了完整的解决方案。无论是简单的工具集成还是复杂的AI服务构建,FastMCP都能提供所需的功能和灵活性。其丰富的特性集合和良好的开发者体验使其成为MCP生态系统中的重要工具。