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 生態系統中的重要工具。