### Quickstart FastMCP Server Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Initialize a FastMCP server, add a tool, and start it with stdio transport. Requires zod for parameter validation. ```typescript 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", }); ``` -------------------------------- ### Start Development Server Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Start the development server using the npm run dev script. This command is typically used for local development and testing. ```bash npm run dev ``` -------------------------------- ### Install FastMCP (Python) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Installs the FastMCP library using pip. This is the first step for setting up FastMCP in a Python project. ```bash pip install fastmcp ``` -------------------------------- ### Install FastMCP (TypeScript) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Installs the FastMCP library using npm. This is the first step for setting up FastMCP in a TypeScript project. ```bash npm install fastmcp ``` -------------------------------- ### Test FastMCP Server with CLI Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Clone the repository, install dependencies, build the project, and then use the CLI to run a FastMCP server for testing. ```bash 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 ``` -------------------------------- ### Configure FastMCP Server with Instructions Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Shows how to provide custom instructions to the FastMCP server during initialization. These instructions can guide client interactions with the server's features and tools. ```typescript const server = new FastMCP({ name: "My Server", version: "1.0.0", instructions: 'Instructions describing how to use the server and its features.\n\nThis can be used by clients to improve the LLM\'s understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.' }); ``` -------------------------------- ### FastMCP Configuration with Google Provider Source: https://github.com/punkpeye/fastmcp/blob/main/docs/OAUTH-PROXY.md Example of configuring FastMCP with the GoogleProvider. Ensure your Google Cloud Console credentials are set up. ```typescript import { FastMCP, GoogleProvider } from "fastmcp"; const server = new FastMCP({ auth: new GoogleProvider({ baseUrl: "https://your-server.com", clientId: "xxx.apps.googleusercontent.com", clientSecret: "your-secret", }), name: "My Server", version: "1.0.0", }); ``` -------------------------------- ### Basic Setup with Pre-configured Google Provider Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Use the `auth` option with a pre-configured GoogleProvider for simple OAuth integration. All OAuth endpoints are automatically available. ```typescript import { FastMCP, getAuthSession, GoogleProvider, requireAuth } from "fastmcp"; const server = new FastMCP({ auth: new GoogleProvider({ baseUrl: "https://your-server.com", clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, scopes: ["openid", "profile", "email"], }), name: "My Server", version: "1.0.0", }); // Add a protected tool server.addTool({ canAccess: requireAuth, description: "Get user profile from Google", execute: async (_args, { session }) => { const { accessToken } = getAuthSession(session); const response = await fetch( "https://www.googleapis.com/oauth2/v2/userinfo", { headers: { Authorization: `Bearer ${accessToken}` }, }, ); return JSON.stringify(await response.json()); }, name: "get-profile", }); await server.start({ transportType: "httpStream", httpStream: { port: 3000 }, }); ``` -------------------------------- ### FastMCP Configuration with GitHub Provider Source: https://github.com/punkpeye/fastmcp/blob/main/docs/OAUTH-PROXY.md Example of configuring FastMCP with the GitHubProvider. Requires GitHub App credentials. ```typescript import { FastMCP, GitHubProvider } from "fastmcp"; const server = new FastMCP({ auth: new GitHubProvider({ baseUrl: "https://your-server.com", clientId: "your-github-app-id", clientSecret: "your-github-app-secret", }), name: "My Server", version: "1.0.0", }); ``` -------------------------------- ### Start FastMCP Server with HTTP Streaming Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Use this to start the FastMCP server with HTTP streaming enabled. The server will listen on the specified port. Default endpoint is /mcp. ```typescript server.start({ transportType: "httpStream", httpStream: { port: 8080, }, }); ``` -------------------------------- ### server.start(options) Source: https://context7.com/punkpeye/fastmcp/llms.txt Starts the FastMCP server using either 'stdio' or 'httpStream' transport modes. The transport type can be configured programmatically, via CLI flags, or environment variables. ```APIDOC ## `server.start(options)` — Start the server Starts the server in `stdio` or `httpStream` transport mode. Transport type can be specified programmatically, via `--transport` CLI flag, or via `FASTMCP_TRANSPORT` environment variable. ### Usage ```typescript import { FastMCP } from "fastmcp"; const server = new FastMCP({ name: "MyServer", version: "1.0.0" }); // stdio (for Claude Desktop / CLI integration) await server.start({ transportType: "stdio" }); // HTTP streaming on port 8080 await server.start({ transportType: "httpStream", httpStream: { port: 8080, host: "0.0.0.0", endpoint: "/mcp", // default stateless: false, // stateful sessions (default) enableJsonResponse: false, }, }); // HTTPS with SSL certificates await server.start({ transportType: "httpStream", httpStream: { port: 8443, sslCert: "./certs/server-cert.pem", sslKey: "./certs/server-key.pem", sslCa: "./certs/ca.pem", // optional mutual TLS stateless: true, }, }); // Stateless mode (serverless / load-balanced) await server.start({ transportType: "httpStream", httpStream: { port: 8080, stateless: true }, }); ``` ### Configuration Options - `transportType`: Specifies the transport mode ('stdio' or 'httpStream'). - `httpStream` (optional): Configuration for HTTP streaming. - `port`: The port to listen on. - `host`: The host to bind to. - `endpoint`: The HTTP endpoint for MCP communication (default: '/mcp'). - `stateless`: Whether to run in stateless mode (default: false). - `enableJsonResponse`: Whether to enable JSON response format (default: false). - `sslCert`: Path to the SSL certificate file. - `sslKey`: Path to the SSL key file. - `sslCa`: Path to the SSL CA file (for mutual TLS). ``` -------------------------------- ### Load Upstream Tokens in a Tool Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Implement a tool to call an upstream API using the user's token. This example demonstrates how to extract the client token and use `authProxy.loadUpstreamTokens` to get the access token for the API call. ```typescript server.addTool({ name: "call-api", description: "Call upstream API with user's token", execute: async (args, { session }) => { const clientToken = session?.headers?.["authorization"]?.replace( "Bearer ", "", ); // Load the upstream tokens const upstreamTokens = await authProxy.loadUpstreamTokens(clientToken); if (upstreamTokens) { const response = await fetch("https://api.provider.com/user", { headers: { Authorization: `Bearer ${upstreamTokens.accessToken}`, }, }); const data = await response.json(); return { content: [{ type: "text", text: JSON.stringify(data) }], }; } throw new Error("No valid token"); }, }); ``` -------------------------------- ### RBAC Authorization Example Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-features.md Example of how to use the `canAccess` function to perform role-based access control by checking custom claims passed through from an upstream identity provider. ```APIDOC ## RBAC Authorization with Custom Claims This example demonstrates how to integrate role-based access control (RBAC) by inspecting custom claims within the session's JWT. The `canAccess` function decodes the JWT, extracts role information, and checks if the user has the necessary 'admin' role. ### Method `server.addTool` with `canAccess` function ### Example Code ```typescript // Tool with role-based access control server.addTool({ name: "admin-action", description: "Perform admin action", canAccess: async ({ session }) => { const token = session?.headers?.["authorization"]?.replace("Bearer ", ""); if (!token) return false; // Decode proxy JWT (contains custom claims from upstream) const payload = JSON.parse( Buffer.from(token.split(".")[1], "base64url").toString(), ); // Check role claim passed through from upstream IDP return payload.role === "admin" || payload.roles?.includes("admin"); }, execute: async (args) => { // Execute admin action return { content: [{ type: "text", text: "Admin action completed" }] }; }, }); ``` ``` -------------------------------- ### Install JWKS Package Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Install the optional 'jose' package to enable JWKS token verification. This is required for using asymmetric keys like RS256/ES256. ```bash npm install jose ``` -------------------------------- ### Initialize EdgeFastMCP for Cloudflare Workers Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Use the `EdgeFastMCP` class from `fastmcp/edge` for edge runtimes. This example demonstrates initialization and adding a tool. ```typescript 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; ``` -------------------------------- ### Quick Start: Initialize FastMCP with Google OAuth Provider Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Demonstrates how to initialize FastMCP with the built-in Google OAuth Provider for secure authentication. Ensure environment variables for client ID and secret are set. ```typescript import { FastMCP, getAuthSession, GoogleProvider, requireAuth } from "fastmcp"; const server = new FastMCP({ auth: new GoogleProvider({ baseUrl: "https://your-server.com", clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, }), name: "My Server", version: "1.0.0", }); server.addTool({ canAccess: requireAuth, name: "protected-tool", execute: async (_args, { session }) => { const { accessToken } = getAuthSession(session); // Use accessToken to call upstream APIs return "Authenticated!"; }, }); ``` -------------------------------- ### FastMCP Configuration with Azure Provider Source: https://github.com/punkpeye/fastmcp/blob/main/docs/OAUTH-PROXY.md Example of configuring FastMCP with the AzureProvider. Requires Azure App registration details and tenant ID. ```typescript import { FastMCP, AzureProvider } from "fastmcp"; const server = new FastMCP({ auth: new AzureProvider({ baseUrl: "https://your-server.com", clientId: "your-azure-app-id", clientSecret: "your-azure-app-secret", tenantId: "common", }), name: "My Server", version: "1.0.0", }); ``` -------------------------------- ### Start FastMCP Server with Different Transports Source: https://context7.com/punkpeye/fastmcp/llms.txt Configure and start the FastMCP server using 'stdio' or 'httpStream' transport modes. Transport type can be set programmatically, via CLI flag, or environment variable. ```typescript import { FastMCP } from "fastmcp"; const server = new FastMCP({ name: "MyServer", version: "1.0.0" }); // stdio (for Claude Desktop / CLI integration) await server.start({ transportType: "stdio" }); // HTTP streaming on port 8080 await server.start({ transportType: "httpStream", httpStream: { port: 8080, host: "0.0.0.0", endpoint: "/mcp", // default stateless: false, // stateful sessions (default) enableJsonResponse: false, }, }); // HTTPS with SSL certificates await server.start({ transportType: "httpStream", httpStream: { port: 8443, sslCert: "./certs/server-cert.pem", sslKey: "./certs/server-key.pem", sslCa: "./certs/ca.pem", // optional mutual TLS stateless: true, }, }); // Stateless mode (serverless / load-balanced) await server.start({ transportType: "httpStream", httpStream: { port: 8080, stateless: true }, }); // Via CLI // npx fastmcp dev src/server.ts --transport http-stream --port 8080 --stateless true // FASTMCP_TRANSPORT=httpStream FASTMCP_PORT=8080 node dist/server.js ``` -------------------------------- ### FastMCP GitHub OAuth Provider and Tool Example Source: https://context7.com/punkpeye/fastmcp/llms.txt Set up a FastMCP server with GitHub OAuth and add a tool to list user repositories. This requires the user to be authenticated via GitHub and grants access to their `accessToken` for API calls. ```typescript import { FastMCP, GitHubProvider, requireAuth, getAuthSession } from "fastmcp"; const githubServer = new FastMCP({ auth: new GitHubProvider({ baseUrl: "http://localhost:4201", clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, scopes: ["read:user", "user:email"], }), name: "GitHub MCP", version: "1.0.0", }); githubServer.addTool({ name: "get-repos", canAccess: requireAuth, description: "List GitHub repositories for the authenticated user", execute: async (_, { session }) => { const { accessToken } = getAuthSession(session); const res = await fetch("https://api.github.com/user/repos", { headers: { Authorization: `Bearer ${accessToken}` }, }); const repos = await res.json() as Array<{ full_name: string }>; return repos.map((r) => r.full_name).join("\n"); }, }); await githubServer.start({ transportType: "httpStream", httpStream: { port: 4201 }, }); ``` -------------------------------- ### FastMCP Client Output: Tool Result with Headers Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Example console output from the client after calling the `headerTool`, showing the processed headers including User-Agent and Authorization. ```json Tool result: { "content": [ { "type": "text", "text": "User-Agent: node\nAuthorization: Test 123\nAll Headers: {\n \"host\": \"localhost:8080\",\n \"connection\": \"keep-alive\",\n \"authorization\": \"Test 123\",\n \"content-type\": \"application/json\",\n \"accept\": \"application/json, text/event-stream\",\n \"accept-language\": \"*\",\n \"sec-fetch-mode\": \"cors\",\n \"user-agent\": \"node\",\n \"accept-encoding\": \"gzip, deflate\",\n \"content-length\": \"163\"\n}" } ] } ``` -------------------------------- ### Custom OAuth Provider Setup Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Use `OAuthProvider` for providers without pre-built support (SAP, Auth0, Okta, etc.). Requires manual configuration of authorization and token endpoints. ```typescript import { FastMCP, getAuthSession, OAuthProvider, requireAuth } from "fastmcp"; const server = new FastMCP({ auth: new OAuthProvider({ authorizationEndpoint: "https://provider.com/oauth/authorize", baseUrl: "https://your-server.com", clientId: process.env.OAUTH_CLIENT_ID!, clientSecret: process.env.OAUTH_CLIENT_SECRET!, scopes: ["openid", "profile"], tokenEndpoint: "https://provider.com/oauth/token", }), name: "My Server", version: "1.0.0", }); server.addTool({ canAccess: requireAuth, description: "Call protected API", execute: async (_args, { session }) => { const { accessToken } = getAuthSession(session); const response = await fetch("https://api.provider.com/data", { headers: { Authorization: `Bearer ${accessToken}` }, }); return JSON.stringify(await response.json()); }, name: "get-data", }); await server.start({ transportType: "httpStream", httpStream: { port: 3000 }, }); ``` -------------------------------- ### Embed Direct Resource in a Tool (System Status Example) Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Shows how to embed a directly defined resource (e.g., system status) into a tool's response using `server.embedded()`. This is useful for providing real-time or static system information. ```javascript // Define a direct resource server.addResource({ uri: "system://status", name: "System Status", mimeType: "text/plain", async load() { return { text: "System operational", }; }, }); // Use in a tool server.addTool({ name: "get_system_status", description: "Get current system status", parameters: z.object({}), execute: async () => { return { content: [ { type: "resource", resource: await server.embedded("system://status"), }, ], }; }, }); ``` -------------------------------- ### Run Server with mcp-cli Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Starts the FastMCP server in development mode using `npx fastmcp dev`. This command is useful for testing and debugging your MCP server directly in the terminal. ```bash npx fastmcp dev server.js ``` ```bash npx fastmcp dev server.ts ``` -------------------------------- ### Initialize FastMCP Server Source: https://context7.com/punkpeye/fastmcp/llms.txt Constructs a new MCP server instance. All tools, resources, and prompts must be registered on this instance before calling `start()`. The generic type parameter `T` defines the shape of the authenticated session object. ```typescript import { FastMCP, UserError } from "fastmcp"; import { z } from "zod"; interface UserSession { [key: string]: unknown; role: "admin" | "user"; userId: string; } const server = new FastMCP({ name: "My MCP Server", version: "1.0.0", instructions: "This server provides data utilities.", authenticate: async (request) => { const apiKey = request?.headers?.["x-api-key"]; if (apiKey !== process.env.API_KEY) { throw new Response(null, { status: 401, statusText: "Unauthorized" }); } return { role: "user", userId: "user-1" }; }, health: { enabled: true, path: "/healthz", message: "healthy", status: 200, }, ping: { enabled: true, intervalMs: 10000, logLevel: "debug", }, roots: { enabled: true }, onToolCall: async ({ toolName, arguments: args }) => { console.log(`Tool called: ${toolName}`, args); }, }); ``` -------------------------------- ### EdgeFastMCP Cloudflare Worker Example Source: https://context7.com/punkpeye/fastmcp/llms.txt This snippet demonstrates setting up an EdgeFastMCP server for Cloudflare Workers, including adding tools, resources, and prompts. It also shows how to integrate custom Hono routes. ```typescript // src/index.ts (Cloudflare Worker) import { EdgeFastMCP } from "fastmcp/edge"; import { z } from "zod"; const server = new EdgeFastMCP({ name: "EdgeMCP", version: "1.0.0", description: "MCP server on Cloudflare Workers", mcpPath: "/mcp", }); server.addTool({ name: "greet", description: "Greet someone from the edge", parameters: z.object({ name: z.string() }), execute: async ({ name }) => `Hello, ${name}! From the edge.`, }); server.addResource({ uri: "info://server", name: "Server Info", mimeType: "text/plain", load: async () => "FastMCP running on Cloudflare Workers", }); server.addPrompt({ name: "analyze-code", description: "Generate a code analysis prompt", arguments: [ { name: "language", required: true }, { name: "focus", required: false }, ], load: async ({ language, focus }) => ({ messages: [ { role: "user", content: { type: "text", text: `Analyze this ${language} code${focus ? `, focusing on ${focus}` : ""}: `, }, }, ], }), }); // Add custom Hono routes alongside MCP const app = server.getApp(); app.get("/", (c) => c.html("

My MCP Server

")); app.get("/api/status", (c) => c.json({ status: "ok" })); // wrangler.toml: // name = "my-mcp-server" // main = "src/index.ts" // compatibility_date = "2024-11-01" export default server; ``` -------------------------------- ### Python OAuth Client Authentication Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Use this client to automatically handle browser launching for user authorization, local callback server setup, PKCE generation, and token storage/refresh when connecting to OAuth-protected servers. ```python from fastmcp.client.auth import OAuthClient client = OAuthClient( authorization_endpoint="https://server.com/oauth/authorize", token_endpoint="https://server.com/oauth/token" ) # Automatically handles: # - Browser launching for user authorization # - Local callback server (auto port selection) # - PKCE generation and validation # - Token storage and refresh tokens = await client.authenticate() ``` -------------------------------- ### FastMCP Integration with Google Provider Source: https://github.com/punkpeye/fastmcp/blob/main/docs/OAUTH-PROXY.md Quick start example for integrating FastMCP with Google OAuth. Automatically registers all necessary OAuth endpoints. ```typescript import { FastMCP, getAuthSession, GoogleProvider, requireAuth } from "fastmcp"; // 1. Create FastMCP with OAuth provider const server = new FastMCP({ auth: new GoogleProvider({ baseUrl: "https://your-server.com", clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, }), name: "My Server", version: "1.0.0", }); // 2. Add protected tools server.addTool({ canAccess: requireAuth, description: "Get user profile", execute: async (_args, { session }) => { const { accessToken } = getAuthSession(session); const response = await fetch( "https://www.googleapis.com/oauth2/v2/userinfo", { headers: { Authorization: `Bearer ${accessToken}` }, }, ); return JSON.stringify(await response.json()); }, name: "get-profile", }); await server.start({ transportType: "httpStream", httpStream: { port: 3000 }, }); ``` -------------------------------- ### Using Pre-configured Providers Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Shows how to use specific pre-configured OAuth providers like Google, detailing the initialization parameters. ```APIDOC ## Python Implementation ### Description Initializes the `GoogleProvider` with specific client credentials, server base URL, and requested scopes. ### Method `GoogleProvider` constructor ### Parameters - **client_id** (str) - Required - The Google client ID. - **client_secret** (str) - Required - The Google client secret. - **base_url** (str) - Required - The base URL of your server. - **scopes** (list[str]) - Optional - A list of OAuth scopes to request. ### Request Example ```python from fastmcp.server.auth import GoogleProvider auth = GoogleProvider( client_id="xxx.apps.googleusercontent.com", client_secret="secret", base_url="https://your-server.com", scopes=["openid", "profile", "email"] ) mcp = FastMCP(name="My Server", auth=auth) ``` ## TypeScript Implementation ### Description Initializes the `GoogleProvider` with client ID, client secret, server base URL, and requested scopes. ### Method `GoogleProvider` constructor ### Parameters - **baseUrl** (str) - Required - The base URL of your server. - **clientId** (str) - Required - The Google client ID. - **clientSecret** (str) - Required - The Google client secret. - **scopes** (list[str]) - Optional - A list of OAuth scopes to request. ### Request Example ```typescript import { FastMCP, GoogleProvider } from "fastmcp"; const server = new FastMCP({ auth: new GoogleProvider({ baseUrl: "https://your-server.com", clientId: "xxx.apps.googleusercontent.com", clientSecret: "secret", scopes: ["openid", "profile", "email"], }), name: "My Server", version: "1.0.0", }); ``` ``` -------------------------------- ### Creating an OAuth Server Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Demonstrates how to initialize the OAuthProxy in Python and OAuthProvider in TypeScript for setting up an OAuth server. ```APIDOC ## Python Implementation ### Description Initializes the `OAuthProxy` with upstream authorization and token endpoints, client credentials, and the base URL for the server. ### Method `OAuthProxy` constructor ### Parameters - **upstream_authorization_endpoint** (str) - Required - The URL of the upstream authorization endpoint. - **upstream_token_endpoint** (str) - Required - The URL of the upstream token endpoint. - **upstream_client_id** (str) - Required - The client ID for upstream authentication. - **upstream_client_secret** (str) - Required - The client secret for upstream authentication. - **base_url** (str) - Required - The base URL of your server. ### Request Example ```python from fastmcp import FastMCP from fastmcp.server.auth import OAuthProxy auth = OAuthProxy( upstream_authorization_endpoint="https://provider.com/oauth/authorize", upstream_token_endpoint="https://provider.com/oauth/token", upstream_client_id="client-id", upstream_client_secret="client-secret", base_url="https://your-server.com" ) mcp = FastMCP(name="My Server", auth=auth) ``` ## TypeScript Implementation ### Description Initializes the `OAuthProvider` with authorization and token endpoints, client ID, client secret, and the base URL for the server. ### Method `OAuthProvider` constructor ### Parameters - **authorizationEndpoint** (str) - Required - The URL of the authorization endpoint. - **baseUrl** (str) - Required - The base URL of your server. - **clientId** (str) - Required - The client ID for authentication. - **clientSecret** (str) - Required - The client secret for authentication. - **tokenEndpoint** (str) - Required - The URL of the token endpoint. ### Request Example ```typescript import { FastMCP, OAuthProvider } from "fastmcp"; const server = new FastMCP({ auth: new OAuthProvider({ authorizationEndpoint: "https://provider.com/oauth/authorize", baseUrl: "https://your-server.com", clientId: "client-id", clientSecret: "client-secret", tokenEndpoint: "https://provider.com/oauth/token", }), name: "My Server", version: "1.0.0", }); ``` ``` -------------------------------- ### Convert Configuration (Python) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Configures Google OAuth provider and initializes the FastMCP server in Python. ```python auth = GoogleProvider( client_id=os.environ["GOOGLE_CLIENT_ID"], client_secret=os.environ["GOOGLE_CLIENT_SECRET"], base_url="https://example.com", scopes=["openid", "profile"] ) mcp = FastMCP(name="My Server", auth=auth) ``` -------------------------------- ### Create Basic OAuth Server (Python) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Instantiates an OAuthProxy with upstream authorization and token endpoints, client credentials, and the base URL for the server. This is then passed to the FastMCP constructor. ```python from fastmcp import FastMCP from fastmcp.server.auth import OAuthProxy auth = OAuthProxy( upstream_authorization_endpoint="https://provider.com/oauth/authorize", upstream_token_endpoint="https://provider.com/oauth/token", upstream_client_id="client-id", upstream_client_secret="client-secret", base_url="https://your-server.com" ) mcp = FastMCP(name="My Server", auth=auth) ``` -------------------------------- ### Add Custom GET Route with Path Parameters Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Register a custom GET route that handles path parameters and query strings. This allows for dynamic routing based on URL segments. ```typescript // 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 }); }); ``` -------------------------------- ### Update Imports (TypeScript) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Imports necessary classes for FastMCP server setup and authentication in TypeScript. ```typescript import { FastMCP, OAuthProvider, GoogleProvider, requireAuth } from "fastmcp"; ``` -------------------------------- ### Initialize OAuthProxy with DiskStore Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-advanced-features.md Configure OAuthProxy to use DiskStore for persistent token storage. Ensure the directory exists and is writable. ```typescript import { OAuthProxy, DiskStore } from "fastmcp/auth"; const proxy = new OAuthProxy({ baseUrl: "https://your-server.com", upstreamAuthorizationEndpoint: "https://provider.com/oauth/authorize", upstreamTokenEndpoint: "https://provider.com/oauth/token", upstreamClientId: "your-client-id", upstreamClientSecret: "your-client-secret", tokenStorage: new DiskStore({ directory: "/var/lib/fastmcp/oauth", }), }); ``` -------------------------------- ### Update Imports (Python) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Imports necessary classes for FastMCP server setup and authentication in Python. ```python from fastmcp import FastMCP from fastmcp.server.auth import OAuthProxy, GoogleProvider ``` -------------------------------- ### Create Basic OAuth Server (TypeScript) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Initializes a FastMCP server with an OAuthProvider, configuring authorization and token endpoints, client ID, client secret, and the server's base URL. Note the camelCase naming convention for options. ```typescript import { FastMCP, OAuthProvider } from "fastmcp"; const server = new FastMCP({ auth: new OAuthProvider({ authorizationEndpoint: "https://provider.com/oauth/authorize", baseUrl: "https://your-server.com", clientId: "client-id", clientSecret: "client-secret", tokenEndpoint: "https://provider.com/oauth/token", }), name: "My Server", version: "1.0.0", }); ``` -------------------------------- ### Access Server Instance Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Accesses the `server` property of the session to get the associated MCP server instance. ```typescript session.server; ``` -------------------------------- ### Configure DiskStore Options Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-advanced-features.md Customize DiskStore behavior with options for directory, cleanup interval, and file extension. The default cleanup interval is 1 minute. ```typescript interface DiskStoreOptions { /** * Directory path for storing data */ directory: string; /** * How often to run cleanup (in milliseconds) * @default 60000 (1 minute) */ cleanupIntervalMs?: number; /** * File extension for stored files * @default ".json" */ fileExtension?: string; } ``` -------------------------------- ### Request Sampling with Options Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Demonstrates how to use `requestSampling` with various options including progress callbacks, abort signals, and timeouts. Ensure `abortController` is defined before use. ```typescript await session.requestSampling( { messages: [ { role: "user", content: { type: "text", text: "What files are in the current directory?", }, }, ], systemPrompt: "You are a helpful file system assistant.", includeContext: "thisServer", maxTokens: 100, }, { // Progress callback - called when progress notifications are received onprogress: (progress) => { console.log(`Progress: ${progress.progress}/${progress.total}`); }, // Abort signal for cancelling the request signal: abortController.signal, // Request timeout in milliseconds (default: DEFAULT_REQUEST_TIMEOUT_MSEC) timeout: 30000, // Whether progress notifications reset the timeout (default: false) resetTimeoutOnProgress: true, // Maximum total timeout regardless of progress (no default) maxTotalTimeout: 60000, }, ); ``` -------------------------------- ### Convert Configuration (TypeScript) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Configures Google OAuth provider and initializes the FastMCP server in TypeScript. Ensure environment variables for client ID and secret are set. ```typescript const server = new FastMCP({ auth: new GoogleProvider({ baseUrl: "https://example.com", clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, scopes: ["openid", "profile"], }), name: "My Server", version: "1.0.0", }); ``` -------------------------------- ### Correct OAuth Proxy Import Path Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Ensure the OAuthProxy is imported from the correct module path. Verify that 'fastmcp' is installed in your project dependencies. ```typescript // Correct import { OAuthProxy } from "fastmcp/auth"; // Also correct import { OAuthProxy } from "fastmcp"; ``` ```bash npm install fastmcp ``` -------------------------------- ### Configure Persistent Token Storage with DiskStore Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Set up `DiskStore` for persistent token storage in production. Configure the directory for storing tokens, an optional cleanup interval, and a file extension. ```typescript import { DiskStore } from "fastmcp/auth"; const storage = new DiskStore({ directory: "/var/lib/fastmcp/oauth", cleanupIntervalMs: 60000, // Cleanup every minute fileExtension: ".json", }); const authProxy = new OAuthProxy({ // ... other config tokenStorage: storage, }); ``` -------------------------------- ### Permission-Based Access Control with Custom Claims Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Example of using custom claims (permissions) extracted from a proxy-issued JWT for fine-grained permission checks. ```typescript // Example: Permission-based access server.addTool({ name: "delete-resource", description: "Delete a resource", canAccess: async ({ session }) => { const token = session?.headers?.["authorization"]?.replace("Bearer ", ""); if (!token) return false; const payload = JSON.parse( Buffer.from(token.split(".")[1], "base64url").toString(), ); // Check fine-grained permissions return payload.permissions?.includes("resource:delete"); }, execute: async (args) => { // Delete logic here return { content: [{ type: "text", text: "Resource deleted" }], }; }, }); ``` -------------------------------- ### Multi-Provider JWKS Verification Setup Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Configure multiple JWKSVerifiers for different OAuth providers. This allows dynamic verification of tokens based on their issuer. ```typescript import { JWKSVerifier } from "fastmcp/auth"; // Create verifiers for each provider const googleVerifier = new JWKSVerifier({ jwksUri: "https://www.googleapis.com/oauth2/v3/certs", issuer: "https://accounts.google.com", audience: process.env.GOOGLE_CLIENT_ID, }); const githubVerifier = new JWKSVerifier({ jwksUri: "https://token.actions.githubusercontent.com/.well-known/jwks", issuer: "https://token.actions.githubusercontent.com", audience: "your-app", }); // Verify based on token issuer async function verifyToken(token: string, provider: string) { const verifier = provider === "google" ? googleVerifier : githubVerifier; return await verifier.verify(token); } ``` -------------------------------- ### Perform Sampling Request with FastMCPSession Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Illustrates how to initiate a sampling request to the model using a `FastMCPSession` instance. This includes setting up messages, system prompts, and context inclusion options. ```typescript await session.requestSampling({ messages: [ { role: "user", content: { type: "text", text: "What files are in the current directory?", }, }, ], systemPrompt: "You are a helpful file system assistant.", includeContext: "thisServer", maxTokens: 100, }); ``` -------------------------------- ### Role-Based Access Control with Custom Claims Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-proxy-guide.md Example of using custom claims (role, roles) extracted from a proxy-issued JWT for role-based access control. ```typescript // Example: Role-based access control server.addTool({ name: "admin-dashboard", description: "Access admin dashboard", canAccess: async ({ session }) => { const token = session?.headers?.["authorization"]?.replace("Bearer ", ""); if (!token) return false; // Decode the proxy JWT const payload = JSON.parse( Buffer.from(token.split(".")[1], "base64url").toString(), ); // Check role claim from upstream IDP return payload.role === "admin" || payload.roles?.includes("admin"); }, execute: async () => { return { content: [{ type: "text", text: "Admin dashboard data..." }], }; }, }); ``` -------------------------------- ### Use Google Provider (TypeScript) Source: https://github.com/punkpeye/fastmcp/blob/main/docs/oauth-python-typescript.md Sets up FastMCP with a GoogleProvider, providing necessary credentials, the server's base URL, and the scopes required for Google authentication. Uses camelCase for configuration options. ```typescript import { FastMCP, GoogleProvider } from "fastmcp"; const server = new FastMCP({ auth: new GoogleProvider({ baseUrl: "https://your-server.com", clientId: "xxx.apps.googleusercontent.com", clientSecret: "secret", scopes: ["openid", "profile", "email"], }), name: "My Server", version: "1.0.0", }); ``` -------------------------------- ### server.addPrompt(prompt) Source: https://context7.com/punkpeye/fastmcp/llms.txt Prompts are server-defined templates that surface to LLM clients. Arguments can have `enum` values (auto-completed via fuzzy search) or custom `complete` functions. ```APIDOC ## `server.addPrompt(prompt)` — Reusable prompt templates Prompts are server-defined templates that surface to LLM clients. Arguments can have `enum` values (auto-completed via fuzzy search) or custom `complete` functions. ```typescript import { FastMCP } from "fastmcp"; const server = new FastMCP({ name: "PromptServer", version: "1.0.0" }); // Simple string prompt server.addPrompt({ name: "git-commit", description: "Generate a Git commit message", arguments: [ { name: "changes", description: "Git diff or description", required: true }, ], load: async ({ changes }) => `Generate a concise commit message for:\n\n${changes}`, }); // Prompt with enum auto-completion server.addPrompt({ name: "country-poem", description: "Write a poem about a country", arguments: [ { name: "country", description: "Country name", required: true, enum: ["Germany", "France", "Italy", "Japan"], }, ], load: async ({ country }) => `Write a short poem about ${country}.`, }); // Prompt returning structured messages with auth context server.addPrompt({ name: "personalized-greeting", arguments: [{ name: "style", description: "formal | casual", required: false }], load: async ({ style }, auth) => { const name = (auth as { username?: string })?.username ?? "friend"; return { messages: [ { role: "user", content: { type: "text", text: style === "formal" ? `Good day, ${name}.` : `Hey ${name}! How's it going?`, }, }, ], }; }, }); ``` ``` -------------------------------- ### Handle Binary Media with `imageContent` and `audioContent` Source: https://context7.com/punkpeye/fastmcp/llms.txt These utility functions load image or audio data from various sources (URL, file path, buffer) and return an MCP-compatible content object with auto-detected MIME type. They are useful for tools that need to process or return binary media. ```typescript import { FastMCP, imageContent, audioContent } from "fastmcp"; import { z } from "zod"; const server = new FastMCP({ name: "MediaServer", version: "1.0.0" }); server.addTool({ name: "screenshot", description: "Capture a page screenshot", parameters: z.object({ url: z.string().url() }), execute: async ({ url }) => { // from URL const img = await imageContent({ url: "https://example.com/chart.png" }); return img; }, }); server.addTool({ name: "read-local-image", description: "Return an image from the filesystem", parameters: z.object({ path: z.string() }), execute: async ({ path }) => { const img = await imageContent({ path }); // img = { type: "image", data: "", mimeType: "image/png" } return img; }, }); server.addTool({ name: "tts", description: "Return synthesized audio", parameters: z.object({ text: z.string() }), execute: async ({ text }) => { const audioBuffer = Buffer.from("...raw PCM data..."); const audio = await audioContent({ buffer: audioBuffer }); return { content: [ { type: "text", text: `Synthesized: "${text}"` }, audio, ], }; }, }); ``` -------------------------------- ### Custom Logger Implementation Source: https://context7.com/punkpeye/fastmcp/llms.txt This snippet shows how to implement a custom logger by adhering to the `Logger` interface and passing it to the `FastMCP` constructor. It includes a minimal `TimestampLogger` example. ```typescript import { FastMCP, Logger } from "fastmcp"; // Minimal custom logger class TimestampLogger implements Logger { private prefix(level: string) { return `[${new Date().toISOString()}] [${level}]`; } debug(...args: unknown[]) { console.debug(this.prefix("DEBUG"), ...args); } error(...args: unknown[]) { console.error(this.prefix("ERROR"), ...args); } info(...args: unknown[]) { console.info(this.prefix("INFO"), ...args); } log(...args: unknown[]) { console.log(this.prefix("LOG"), ...args); } warn(...args: unknown[]) { console.warn(this.prefix("WARN"), ...args); } } // Winston adapter (requires: npm install winston) // class WinstonAdapter implements Logger { // private w = winston.createLogger({ ... }); // debug(...a) { this.w.debug(a.join(" ")); } // error(...a) { this.w.error(a.join(" ")); } // info(...a) { this.w.info(a.join(" ")); } // log(...a) { this.w.info(a.join(" ")); } // warn(...a) { this.w.warn(a.join(" ")); } // } const server = new FastMCP({ name: "LoggedServer", version: "1.0.0", logger: new TimestampLogger(), }); server.start({ transportType: "stdio" }); ``` -------------------------------- ### FastMCP Configuration with Custom OAuth Provider Source: https://github.com/punkpeye/fastmcp/blob/main/docs/OAUTH-PROXY.md Example of configuring FastMCP with a generic OAuthProvider for any OAuth 2.0 compliant service. Specify authorization and token endpoints. ```typescript import { FastMCP, OAuthProvider } from "fastmcp"; const server = new FastMCP({ auth: new OAuthProvider({ authorizationEndpoint: "https://provider.com/oauth/authorize", baseUrl: "https://your-server.com", clientId: process.env.OAUTH_CLIENT_ID!, clientSecret: process.env.OAUTH_CLIENT_SECRET!, scopes: ["openid", "profile"], tokenEndpoint: "https://provider.com/oauth/token", }), name: "My Server", version: "1.0.0", }); ``` -------------------------------- ### Start FastMCP Server with HTTPS Source: https://github.com/punkpeye/fastmcp/blob/main/README.md Configure the FastMCP server to use HTTPS by providing paths to SSL certificate files. This enables secure communication on the specified port. ```typescript 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 }, }); ```