AgentStack
Browse Sign in
Browse Why AgentStack Sell Docs
Sign in
MCP verified MIT Self-run

Fastmcp

mcp-punkpeye-fastmcp · by punkpeye

A TypeScript framework for building MCP servers.

No reviews yet
0 installs
27 views
0.0% view→install

Install

$ agentstack add mcp-punkpeye-fastmcp

✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets Used
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

View the full security report →

Verified badge

Passed review? Show it. Paste this badge into your README, it links to the public security report.

AgentStack Verified badge Links to your public security report.
[![AgentStack Verified](https://agentstack.voostack.com/badges/verified.svg)](https://agentstack.voostack.com/security/report/mcp-punkpeye-fastmcp)

Reliability & compatibility

Security review passed
0 installs to date
no reviews yet
1mo ago

Declared compatibility

Claude CodeClaude DesktopCursorWindsurf

Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.

Preview Execution monitoring

We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.

How agent discovery & health will work →
Are you the author of Fastmcp? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

FastMCP

A TypeScript framework for building MCP servers capable of handling client sessions.

> [!NOTE] > > For a Python implementation, see FastMCP.

Features

  • Simple Tool, Resource, Prompt definition
  • [Authentication](#authentication)
  • [Passing headers through context](#passing-headers-through-context)
  • [Session ID and Request ID tracking](#session-id-and-request-id-tracking)
  • [Sessions](#sessions)
  • [Image content](#returning-an-image)
  • [Audio content](#returning-an-audio)
  • [Embedded](#embedded-resources)
  • [Logging](#logging)
  • [Error handling](#errors)
  • [HTTP Streaming](#http-streaming) (with SSE compatibility)
  • [HTTPS Support](#https-support) for secure connections
  • [Custom HTTP routes](#custom-http-routes) for REST APIs, webhooks, and admin interfaces
  • [Edge Runtime Support](#edge-runtime-support) for Cloudflare Workers, Deno Deploy, and more
  • [Stateless mode](#stateless-mode) for serverless deployments
  • CORS (enabled by default)
  • [Progress notifications](#progress)
  • [Streaming output](#streaming-output)
  • [Typed server events](#typed-server-events)
  • [Prompt argument auto-completion](#prompt-argument-auto-completion)
  • [Sampling](#requestsampling)
  • [Configurable ping behavior](#configurable-ping-behavior)
  • [Health-check endpoint](#health-check-endpoint)
  • [Roots](#roots-management)
  • CLI for [testing](#test-with-mcp-cli) and [debugging](#inspect-with-mcp-inspector)

When to use FastMCP over the official SDK?

FastMCP is built on top of the official SDK.

The official SDK provides foundational blocks for building MCPs, but leaves many implementation details to you:

FastMCP eliminates this complexity by providing an opinionated framework that:

  • Handles all the boilerplate automatically
  • Provides simple, intuitive APIs for common tasks
  • Includes built-in best practices and error handling
  • Lets you focus on your MCP's core functionality

When to choose FastMCP: You want to build MCP servers quickly without dealing with low-level implementation details.

When to use the official SDK: You need maximum control or have specific architectural requirements. In this case, we encourage referencing FastMCP's implementation to avoid common pitfalls.

Installation

npm install fastmcp

Quickstart

> [!NOTE] > > There are many real-world examples of using FastMCP in the wild. See the [Showcase](#showcase) for examples.

import { FastMCP } from "fastmcp";
import { z } from "zod"; // Or any validation library that supports Standard Schema

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

That's it! You have a working MCP server.

You can test the server in terminal with:

git clone https://github.com/punkpeye/fastmcp.git
cd fastmcp

pnpm install
pnpm build

# Test the addition server example using CLI:
npx fastmcp dev src/examples/addition.ts
# Test the addition server example using MCP Inspector:
npx fastmcp inspect src/examples/addition.ts

If you are looking for a boilerplate repository to build your own MCP server, check out fastmcp-boilerplate.

Remote Server Options

FastMCP supports multiple transport options for remote communication, allowing an MCP hosted on a remote machine to be accessed over the network.

HTTP Streaming

HTTP streaming provides a more efficient alternative to SSE in environments that support it, with potentially better performance for larger payloads.

You can run the server with HTTP streaming support:

server.start({
  transportType: "httpStream",
  httpStream: {
    port: 8080,
  },
});

This will start the server and listen for HTTP streaming connections on http://localhost:8080/mcp.

> Note: You can also customize the endpoint path using the httpStream.endpoint option (default is /mcp).

> Note: This also starts an SSE server on http://localhost:8080/sse.

You can connect to these servers using the appropriate client transport.

For HTTP streaming connections:

import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

const client = new Client(
  {
    name: "example-client",
    version: "1.0.0",
  },
  {
    capabilities: {},
  },
);

const transport = new StreamableHTTPClientTransport(
  new URL(`http://localhost:8080/mcp`),
);

await client.connect(transport);

For SSE connections:

import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";

const client = new Client(
  {
    name: "example-client",
    version: "1.0.0",
  },
  {
    capabilities: {},
  },
);

const transport = new SSEClientTransport(new URL(`http://localhost:8080/sse`));

await client.connect(transport);
HTTPS Support

FastMCP supports HTTPS for secure connections by providing SSL certificate options:

server.start({
  transportType: "httpStream",
  httpStream: {
    port: 8443,
    sslCert: "./path/to/cert.pem",
    sslKey: "./path/to/key.pem",
    sslCa: "./path/to/ca.pem", // Optional: for client certificate authentication
  },
});

This will start the server with HTTPS on https://localhost:8443/mcp.

SSL Options:

  • sslCert - Path to SSL certificate file
  • sslKey - Path to SSL private key file
  • sslCa - (Optional) Path to CA certificate for mutual TLS authentication

For testing, you can generate self-signed certificates:

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes -subj "/CN=localhost"

For production, obtain certificates from a trusted CA like Let's Encrypt.

See the [https-server example](src/examples/https-server.ts) for a complete demonstration.

CORS Configuration

By default, FastMCP enables CORS with a standard set of allowed headers. You can customize the CORS behavior by passing a cors option:

server.start({
  transportType: "httpStream",
  httpStream: {
    port: 8080,
    cors: {
      origin: "http://localhost:3000",
      allowedHeaders: [
        "Content-Type",
        "Authorization",
        "Accept",
        "Mcp-Session-Id",
        "Mcp-Protocol-Version",
        "Last-Event-Id",
        "X-Custom-Header",
      ],
      credentials: true,
    },
  },
});

The cors option accepts:

  • true (default) - enable CORS with default settings
  • false - disable CORS entirely
  • An object with these fields:
  • origin - a string, array of strings, or a function (origin: string) => boolean
  • allowedHeaders - a string or array of strings
  • methods - array of allowed HTTP methods
  • exposedHeaders - array of headers to expose
  • credentials - boolean to allow credentials
  • maxAge - preflight cache duration in seconds

The CorsOptions type is exported from fastmcp for convenience.

Custom HTTP Routes

FastMCP allows you to add custom HTTP routes alongside MCP endpoints, enabling you to build comprehensive HTTP services that include REST APIs, webhooks, admin interfaces, and more - all within the same server process.

// Add REST API endpoints
server.addRoute("GET", "/api/users", async (req, res) => {
  res.json({ users: [] });
});

// Handle path parameters
server.addRoute("GET", "/api/users/:id", async (req, res) => {
  res.json({
    userId: req.params.id,
    query: req.query, // Access query parameters
  });
});

// Handle POST requests with body parsing
server.addRoute("POST", "/api/users", async (req, res) => {
  const body = await req.json();
  res.status(201).json({ created: body });
});

// Serve HTML content
server.addRoute("GET", "/admin", async (req, res) => {
  res.send("Admin Panel");
});

// Handle webhooks
server.addRoute("POST", "/webhook/github", async (req, res) => {
  const payload = await req.json();
  const event = req.headers["x-github-event"];

  // Process webhook...
  res.json({ received: true });
});

Custom routes support:

  • All HTTP methods: GET, POST, PUT, DELETE, PATCH, OPTIONS
  • Path parameters (:param) and wildcards (*)
  • Query string parsing
  • JSON and text body parsing
  • Custom status codes and headers
  • Authentication via the same authenticate function as MCP
  • Public routes that bypass authentication

Routes are matched in the order they are registered, allowing you to define specific routes before catch-all patterns.

Public Routes

By default, custom routes require authentication (if configured). You can make routes public by adding the { public: true } option:

// Public route - no authentication required
server.addRoute(
  "GET",
  "/.well-known/openid-configuration",
  async (req, res) => {
    res.json({
      issuer: "https://example.com",
      authorization_endpoint: "https://example.com/auth",
      token_endpoint: "https://example.com/token",
    });
  },
  { public: true },
);

// Private route - requires authentication
server.addRoute("GET", "/api/users", async (req, res) => {
  // req.auth contains authenticated user data
  res.json({ users: [] });
});

// Public static files
server.addRoute(
  "GET",
  "/public/*",
  async (req, res) => {
    // Serve static files without authentication
    res.send(`File: ${req.url}`);
  },
  { public: true },
);

Public routes are perfect for:

  • OAuth discovery endpoints (.well-known/*)
  • Health checks and status pages
  • Static assets and documentation
  • Webhook endpoints from external services
  • Public APIs that don't require user authentication

See the [custom-routes example](src/examples/custom-routes.ts) for a complete demonstration.

Edge Runtime Support

FastMCP supports edge runtimes like Cloudflare Workers, enabling deployment of MCP servers to the edge with minimal latency worldwide.

Choosing Between FastMCP and EdgeFastMCP

| Use Case | Class | Import | | ------------------------------- | ------------- | -------------------------------------------- | | Node.js, Express, Bun | FastMCP | import { FastMCP } from "fastmcp" | | Cloudflare Workers, Deno Deploy | EdgeFastMCP | import { EdgeFastMCP } from "fastmcp/edge" |

| Feature | FastMCP | EdgeFastMCP | | -------------------- | ------------------------------ | -------------------------------------- | | Runtime | Node.js | Edge (V8 isolates) | | Start method | server.start({ port }) | export default server | | Transport | stdio, httpStream, SSE | HTTP Streamable only | | Sessions | Stateful or stateless | Stateless only | | File system | Yes | No | | OAuth/Authentication | Built-in authenticate option | Use Hono middleware (built-in planned) | | Custom routes | server.getApp() | server.getApp() |

> Note: Built-in authentication for EdgeFastMCP is planned for a future release. Both FastMCP and EdgeFastMCP use Hono internally, so there's no technical barrier—EdgeFastMCP was simply written before OAuth was added to FastMCP. PRs are welcome to add an authenticate option that accepts web Request instead of Node.js http.IncomingMessage. > > In the meantime, use Hono middleware: > > ``ts > const app = server.getApp(); > app.use("/api/*", async (c, next) => { > if (c.req.header("authorization") !== "Bearer secret") { > return c.json({ error: "Unauthorized" }, 401); > } > await next(); > }); > ``

Cloudflare Workers

To deploy FastMCP to Cloudflare Workers, use the EdgeFastMCP class from the /edge subpath:

import { EdgeFastMCP } from "fastmcp/edge";
import { z } from "zod";

const server = new EdgeFastMCP({
  name: "My Edge Server",
  version: "1.0.0",
  description: "MCP server running on Cloudflare Workers",
});

// Add tools, resources, prompts as usual
server.addTool({
  name: "greet",
  description: "Greet someone",
  parameters: z.object({
    name: z.string(),
  }),
  execute: async ({ name }) => {
    return `Hello, ${name}! Served from the edge.`;
  },
});

// Export the server as the default (required for Cloudflare Workers)
export default server;
Edge Runtime Differences

When running on edge runtimes:

  • Stateless by default: Each request is handled independently
  • No filesystem access: Use fetch APIs for external data
  • V8 Isolates: Fast cold starts and efficient resource usage
  • Global deployment: Automatic distribution to edge locations
Custom Routes on Edge

You can access the underlying Hono app to add custom HTTP routes:

const app = server.getApp();

// Add a landing page
app.get("/", (c) => c.html("Welcome to my MCP server"));

// Add REST API endpoints
app.get("/api/status", (c) => c.json({ status: "ok" }));
Deployment

Configure your wrangler.toml:

name = "my-mcp-server"
main = "src/index.ts"
compatibility_date = "2024-01-01"

Deploy with:

wrangler deploy

See the [edge-cloudflare-worker example](src/examples/edge-cloudflare-worker.ts) for a complete demonstration.

Stateless Mode

FastMCP supports stateless operation for HTTP streaming, where each request is handled independently without maintaining persistent sessions. This is ideal for serverless environments, load-balanced deployments, or when session state isn't required.

In stateless mode:

  • No sessions are tracked on the server
  • Each request creates a temporary session that's discarded after the response
  • Reduced memory usage and better scalability
  • Perfect for stateless deployment environments

You can enable stateless mode by adding the stateless: true option:

server.start({
  transportType: "httpStream",
  httpStream: {
    port: 8080,
    stateless: true,
  },
});

> Note: Stateless mode is only available with HTTP streaming transport. Features that depend on persistent sessions (like session-sp

Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet, be the first.

Versions

  • v0.1.0 Imported from the upstream source.