FastMCP

FastMCP

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

FastMCP Quick Start

FastMCP 是一个用于构建能够处理客户端会话的 MCP 服务器的 TypeScript 框架。

安装

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

启动服务器

标准 I/O 模式

server.start({
  transportType: "stdio",
});

SSE 模式

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

添加工具

基本工具

server.addTool({
  name: "fetch",
  description: "Fetch the content of a URL",
  parameters: z.object({
    url: z.string(),
  }),
  execute: async (args) => {
    return await fetchWebpageContent(args.url);
  },
});

返回图像

import { imageContent } from "fastmcp";

server.addTool({
  name: "getImage",
  description: "Get an image",
  parameters: z.object({
    id: z.string(),
  }),
  execute: async (args) => {
    return imageContent({
      url: `https://example.com/images/${args.id}.png`,
      // 或使用 path: "/path/to/image.png"
      // 或使用 buffer: Buffer.from("...")
    });
  },
});

添加资源

server.addResource({
  uri: "file:///logs/app.log",
  name: "Application Logs",
  mimeType: "text/plain",
  async load() {
    return {
      text: await readLogFile(),
    };
  },
});

错误处理

import { UserError } from "fastmcp";

server.addTool({
  name: "download",
  description: "Download a file",
  parameters: z.object({ url: z.string() }),
  execute: async (args) => {
    if (args.url.startsWith("https://example.com")) {
      throw new UserError("This URL is not allowed");
    }
    return "Download completed";
  },
});

日志和进度报告

server.addTool({
  name: "process",
  description: "Process a file",
  parameters: z.object({ file: z.string() }),
  execute: async (args, { log, reportProgress }) => {
    log.info("Starting process", { file: args.file });
    
    reportProgress({ progress: 0, total: 100 });
    // 处理过程...
    reportProgress({ progress: 100, total: 100 });
    
    log.info("Process completed");
    return "Done";
  },
});

测试服务器

# 使用CLI测试
npx fastmcp dev path/to/server.ts

# 使用MCP Inspector检查
npx fastmcp inspect path/to/server.ts