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" ,
});
Semantic version string (e.g., “1.0.0”)
Server-level instructions or description
Custom logger instance (defaults to console)
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 check endpoint configuration (HTTP Stream transport only) Enable or disable health check endpoint
HTTP path for health check
Plain-text response message
HTTP status code to return
OAuth discovery endpoint configuration (HTTP-based transports only) Enable OAuth discovery endpoints
OAuth Authorization Server metadata (RFC 8414) Authorization server identifier URL
Authorization endpoint URL
Supported OAuth response types
codeChallengeMethodsSupported
Supported PKCE challenge methods
OAuth Protected Resource metadata (RFC 9728) Canonical resource identifier (typically the base URL)
List of authorization server issuer identifiers
Supported OAuth scopes for this resource
OAuthProxy instance for automatic OAuth flow handling
Server ping configuration Enable ping (auto-enabled for SSE/HTTP Stream)
Ping interval in milliseconds
logLevel
LoggingLevel
default: "debug"
Logging level for ping messages (“debug” | “info” | “warning” | “error”)
Roots capability configuration Enable or disable roots support
Methods
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 configuration object Human-readable tool description
Parameter schema (Zod, ArkType, Valibot, etc.)
execute
(args, context) => Promise<string | Content | ContentResult>
required
Tool execution function. Returns text, Content, or ContentResult.
Authorization check function
Tool execution timeout in milliseconds
Tool behavior hints (readOnlyHint, destructiveHint, etc.)
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 configuration object Unique resource identifier (URI)
Human-readable resource description
MIME type of the resource content
load
(auth?) => Promise<ResourceResult | ResourceResult[]>
required
Function that loads and returns resource content
Authorization check function
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" ),
}),
});
Resource template configuration URI template with parameters (RFC 6570)
Human-readable template description
MIME type of the resource content
arguments
ResourceTemplateArgument[]
required
Template parameter definitions
load
(args, auth?) => Promise<ResourceResult | ResourceResult[]>
required
Function that loads resource with resolved parameters
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 configuration object Human-readable prompt description
Prompt argument definitions
load
(args, auth?) => Promise<PromptResult>
required
Function that generates prompt messages
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 () });
});
HTTP method: “GET”, “POST”, “PUT”, “PATCH”, “DELETE”, “OPTIONS”
Request handler function ( req : FastMCPRequest , res : FastMCPResponse ) => Promise < void > | void
Route configuration options Bypass authentication for this route
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 ,
});
Transport configuration transportType
'stdio' | 'httpStream'
default: "stdio"
Transport protocol to use
Port number (httpStream only)
Host address (httpStream only)
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" ,
});
Authentication context for the session
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" ;
}
Authentication session data (if authenticated)
Session ID from Mcp-Session-Id header (HTTP transports only)
Request ID from current MCP request
Logging functions debug
(message: string, data?: SerializableValue) => void
Log debug message
info
(message: string, data?: SerializableValue) => void
Log info message
warn
(message: string, data?: SerializableValue) => void
Log warning message
error
(message: string, data?: SerializableValue) => void
Log error message
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..." ,
});