Home
Login

一个用于构建MCP服务器的TypeScript框架

MITTypeScript 1.9kpunkpeye Last Updated: 2025-06-21

FastMCP - TypeScript MCP服务器框架

项目概述

FastMCP 是一个专为构建 Model Context Protocol (MCP) 服务器而设计的 TypeScript 框架。它提供了一套完整的工具和功能,使开发者能够快速创建能够处理客户端会话的高性能 MCP 服务器。

项目地址: https://github.com/punkpeye/fastmcp

核心特性

基础功能

  • 简单的工具、资源和提示定义:提供直观的API来定义服务器功能
  • 身份验证支持:内置认证机制确保安全访问
  • 会话管理:支持客户端会话处理和状态管理
  • 多媒体内容支持:支持图像和音频内容的返回
  • 日志记录:完整的日志系统用于调试和监控
  • 错误处理:统一的错误处理机制
  • Server-Sent Events (SSE):支持实时数据推送
  • CORS支持:默认启用跨域资源共享

高级特性

  • 进度通知:工具执行过程中的实时进度反馈
  • 类型化服务器事件:TypeScript类型安全的事件系统
  • 提示参数自动补全:智能参数补全功能
  • 采样请求:支持AI模型采样请求
  • 自动化SSE心跳:保持连接稳定性
  • 根目录管理:文件系统根目录配置
  • CLI工具:提供测试和调试命令行工具

安装与使用

安装

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",
});

主要功能模块

1. 工具定义 (Tools)

工具允许服务器向客户端公开可执行的函数,这些函数可以被客户端调用并被LLM用于执行操作。

支持的Schema验证库

  • Zod: 最流行的TypeScript schema验证库
  • ArkType: 现代化的类型验证库
  • Valibot: 轻量级的schema验证库

Zod示例

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);
  },
});

2. 资源管理 (Resources)

资源代表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}`,
    };
  },
});

3. 提示管理 (Prompts)

提示使服务器能够定义可重用的提示模板和工作流:

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}`;
  },
});

4. 身份验证

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,
    };
  },
});

5. Server-Sent Events (SSE)

支持实时通信的SSE功能:

server.start({
  transportType: "sse",
  sse: {
    endpoint: "/sse",
    port: 8080,
  },
});

6. 会话管理

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集成

在Claude Desktop中添加配置:

{
  "mcpServers": {
    "my-mcp-server": {
      "command": "npx",
      "args": ["tsx", "/PATH/TO/YOUR_PROJECT/src/index.ts"],
      "env": {
        "YOUR_ENV_VAR": "value"
      }
    }
  }
}

实际应用案例

FastMCP已被多个项目采用,包括:

  • apinetwork/piapi-mcp-server: 使用Midjourney/Flux/Kling等生成媒体内容
  • domdomegg/computer-use-mcp: 计算机控制工具
  • Meeting-Baas/meeting-mcp: 会议机器人和转录管理
  • drumnation/unsplash-smart-mcp-server: Unsplash图片搜索集成
  • aiamblichus/mcp-chat-adapter: LLM聊天完成接口

技术优势

  1. 类型安全: 完整的TypeScript支持确保代码质量
  2. 灵活的Schema: 支持多种验证库,满足不同需求
  3. 现代化架构: 基于最新的Web标准和最佳实践
  4. 丰富的功能: 从基础功能到高级特性的全面支持
  5. 易于扩展: 模块化设计便于功能扩展
  6. 开发友好: 完善的CLI工具和调试支持

总结

FastMCP是一个功能强大、易于使用的TypeScript框架,为构建MCP服务器提供了完整的解决方案。无论是简单的工具集成还是复杂的AI服务构建,FastMCP都能提供所需的功能和灵活性。其丰富的特性集合和良好的开发者体验使其成为MCP生态系统中的重要工具。