Home
Login

A TypeScript framework for building MCP servers

MITTypeScript 1.9kpunkpeye Last Updated: 2025-06-21

FastMCP - TypeScript MCP Server Framework

Project Overview

FastMCP is a TypeScript framework specifically designed for building Model Context Protocol (MCP) servers. It provides a complete set of tools and features, enabling developers to quickly create high-performance MCP servers capable of handling client sessions.

Project Address: https://github.com/punkpeye/fastmcp

Core Features

Basic Features

  • Simple tool, resource, and prompt definitions: Provides intuitive APIs to define server functionality.
  • Authentication support: Built-in authentication mechanism ensures secure access.
  • Session management: Supports client session handling and state management.
  • Multimedia content support: Supports returning image and audio content.
  • Logging: Comprehensive logging system for debugging and monitoring.
  • Error handling: Unified error handling mechanism.
  • Server-Sent Events (SSE): Supports real-time data push.
  • CORS support: Cross-Origin Resource Sharing enabled by default.

Advanced Features

  • Progress notifications: Real-time progress feedback during tool execution.
  • Typed server events: TypeScript type-safe event system.
  • Prompt parameter auto-completion: Intelligent parameter completion feature.
  • Sampling requests: Supports AI model sampling requests.
  • Automated SSE heartbeat: Maintains connection stability.
  • Root directory management: File system root directory configuration.
  • CLI tools: Provides command-line tools for testing and debugging.

Installation and Usage

Installation

npm install fastmcp

Basic Example

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

Main Functional Modules

1. Tool Definition (Tools)

Tools allow the server to expose executable functions to the client, which can be called by the client and used by LLMs to perform operations.

Supported Schema Validation Libraries

  • Zod: The most popular TypeScript schema validation library.
  • ArkType: A modern type validation library.
  • Valibot: A lightweight schema validation library.

Zod Example

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

Tool Annotations

Tools can include annotations to provide richer context and control information:

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. Resource Management (Resources)

Resources represent any type of data that the MCP server wants to provide to the client, including:

  • File content
  • Screenshots and images
  • Log files
  • Other data
server.addResource({
  uri: "file:///logs/app.log",
  name: "Application Logs",
  mimeType: "text/plain",
  async load() {
    return {
      text: await readLogFile(),
    };
  },
});

Resource Templates

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. Prompt Management (Prompts)

Prompts enable the server to define reusable prompt templates and workflows:

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. Authentication

FastMCP supports custom authentication functionality:

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 functionality for real-time communication:

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

6. Session Management

FastMCP assigns a new server instance to each client connection, enabling 1:1 communication:

server.on("connect", (event) => {
  console.log("Client connected:", event.session);
});

server.on("disconnect", (event) => {
  console.log("Client disconnected:", event.session);
});

Development Tools

Testing and Debugging


npx fastmcp dev src/examples/addition.ts


npx fastmcp inspect src/examples/addition.ts

Claude Desktop Integration

Add the configuration in Claude Desktop:

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

Real-World Use Cases

FastMCP has been adopted by several projects, including:

  • apinetwork/piapi-mcp-server: Generating media content using Midjourney/Flux/Kling, etc.
  • domdomegg/computer-use-mcp: Computer control tools.
  • Meeting-Baas/meeting-mcp: Meeting robot and transcription management.
  • drumnation/unsplash-smart-mcp-server: Unsplash image search integration.
  • aiamblichus/mcp-chat-adapter: LLM chat completion interface.

Technical Advantages

  1. Type Safety: Full TypeScript support ensures code quality.
  2. Flexible Schema: Supports multiple validation libraries to meet different needs.
  3. Modern Architecture: Based on the latest web standards and best practices.
  4. Rich Functionality: Comprehensive support from basic features to advanced features.
  5. Easy to Extend: Modular design facilitates feature extension.
  6. Developer-Friendly: Complete CLI tools and debugging support.

Summary

FastMCP is a powerful and easy-to-use TypeScript framework that provides a complete solution for building MCP servers. Whether it's simple tool integration or complex AI service construction, FastMCP provides the necessary functionality and flexibility. Its rich feature set and good developer experience make it an important tool in the MCP ecosystem.