Skip to main content
The FastMCP class is the core of FastMCP for Node.js environments. It provides a fluent API for building Model Context Protocol servers with tools, resources, prompts, and OAuth support.

Constructor

Create a new FastMCP server instance.
import { FastMCP } from "fastmcp";

const server = new FastMCP({
  name: "my-server",
  version: "1.0.0",
});
name
string
required
Server name identifier
version
string
required
Semantic version string (e.g., “1.0.0”)
instructions
string
Server-level instructions or description
logger
Logger
Custom logger instance (defaults to console)
auth
AuthProvider
Authentication provider for OAuth flows. When provided, automatically configures authentication and OAuth endpoints.
import { FastMCP, GitHubProvider } from "fastmcp";

const server = new FastMCP({
  name: "my-server",
  version: "1.0.0",
  auth: new GitHubProvider({
    baseUrl: "http://localhost:8000",
    clientId: process.env.GITHUB_CLIENT_ID!,
    clientSecret: process.env.GITHUB_CLIENT_SECRET!,
  }),
});
authenticate
(request: IncomingMessage) => Promise<T>
Custom authentication function. Takes precedence over auth provider if both are specified.
health
object
Health check endpoint configuration (HTTP Stream transport only)
oauth
object
OAuth discovery endpoint configuration (HTTP-based transports only)
ping
object
Server ping configuration
roots
object
Roots capability configuration

Methods

addTool()

Register a tool that can be called by the MCP client.
server.addTool({
  name: "get_weather",
  description: "Get current weather for a location",
  parameters: z.object({
    location: z.string(),
  }),
  execute: async ({ location }) => {
    return `Weather in ${location}: Sunny, 72°F`;
  },
});
tool
Tool
required
Tool configuration object

addResource()

Register a static resource that can be read by the MCP client.
server.addResource({
  uri: "file:///config.json",
  name: "Configuration",
  description: "Server configuration",
  mimeType: "application/json",
  load: async () => ({
    text: JSON.stringify({ version: "1.0.0" }),
  }),
});
resource
Resource
required
Resource configuration object

addResourceTemplate()

Register a dynamic resource template with URI parameters.
server.addResourceTemplate({
  uriTemplate: "file:///{path}",
  name: "File",
  description: "Read a file",
  mimeType: "text/plain",
  arguments: [
    { name: "path", description: "File path", required: true },
  ],
  load: async ({ path }) => ({
    text: await readFile(path, "utf-8"),
  }),
});
template
ResourceTemplate
required
Resource template configuration

addPrompt()

Register a prompt template.
server.addPrompt({
  name: "code_review",
  description: "Review code for best practices",
  arguments: [
    { name: "language", description: "Programming language", required: true },
  ],
  load: async ({ language }) => ({
    messages: [
      {
        role: "user",
        content: { type: "text", text: `Review this ${language} code...` },
      },
    ],
  }),
});
prompt
Prompt
required
Prompt configuration object

addRoute()

Register a custom HTTP route (HTTP Stream transport only).
server.addRoute("GET", "/api/status", async (req, res) => {
  res.json({ status: "running", uptime: process.uptime() });
});
method
HTTPMethod
required
HTTP method: “GET”, “POST”, “PUT”, “PATCH”, “DELETE”, “OPTIONS”
path
string
required
URL path for the route
handler
RouteHandler
required
Request handler function
(req: FastMCPRequest, res: FastMCPResponse) => Promise<void> | void
options
RouteOptions
Route configuration options

start()

Start the MCP server with the specified transport.
// stdio transport (default)
await server.start();

// HTTP Stream transport
await server.start({
  transportType: "httpStream",
  port: 8000,
});
options
object
Transport configuration
server
SSEServer
Server instance with close() method (httpStream only)

embedded()

Create an embedded MCP server instance for programmatic use.
const embedded = await server.embedded({
  sessionAuth: { userId: "123", role: "admin" },
});

const result = await embedded.callTool("get_weather", {
  location: "San Francisco",
});
options
object
session
FastMCPSession
Embedded session instance with direct API access

Context Object

The context object is passed to tool execute functions and provides access to session information and client capabilities.
execute: async (args, context) => {
  context.log.info("Tool called", { args });
  await context.reportProgress({ progress: 50, total: 100 });
  await context.streamContent({ type: "text", text: "Processing..." });
  return "Done";
}
session
T | undefined
Authentication session data (if authenticated)
sessionId
string | undefined
Session ID from Mcp-Session-Id header (HTTP transports only)
requestId
string | undefined
Request ID from current MCP request
client
object
Client information
log
object
Logging functions
reportProgress
(progress: Progress) => Promise<void>
Report tool execution progress
await context.reportProgress({
  progress: 50,
  total: 100,
});
streamContent
(content: Content | Content[]) => Promise<void>
Stream content to the client (for streaming tools)
await context.streamContent({
  type: "text",
  text: "Partial result...",
});