Skip to main content
FastMCP defines session types for authentication and authorization in MCP servers.

FastMCPSession

Session class representing a connected MCP client session.
class FastMCPSession<T extends FastMCPSessionAuth = FastMCPSessionAuth> {
  // Properties
  readonly isReady: boolean;
  readonly clientCapabilities: ClientCapabilities | null;
  readonly loggingLevel: LoggingLevel;
  readonly roots: Root[];
  readonly server: Server;
  sessionId?: string;
  
  // Methods
  async connect(transport: Transport): Promise<void>;
  async close(): Promise<void>;
  async requestSampling(message, options?): Promise<SamplingResponse>;
  waitForReady(): Promise<void>;
  updateAuth(auth: T): void;
  
  // List changed notifications
  toolsListChanged(tools: Tool<T>[]): void;
  resourcesListChanged(resources: Resource<T>[]): void;
  resourceTemplatesListChanged(templates: ResourceTemplate<T>[]): void;
  promptsListChanged(prompts: Prompt<T>[]): void;
  triggerListChangedNotification(method: string): Promise<void>;
}

Properties

isReady
boolean
Whether the session is ready (connected and initialized)
clientCapabilities
ClientCapabilities | null
Client capabilities negotiated during initialization
loggingLevel
LoggingLevel
Current logging level set by client
type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency";
roots
Root[]
Root directories provided by the client
server
Server
Underlying MCP SDK server instance
sessionId
string | undefined
Session ID from Mcp-Session-Id header (HTTP transports only)

Methods

connect()

Connect the session with a transport.
const session = new FastMCPSession({
  name: "my-server",
  version: "1.0.0",
  // ...
});

const transport = new StdioServerTransport();
await session.connect(transport);
transport
Transport
required
MCP transport instance (StdioServerTransport, WebStreamableHTTPServerTransport, etc.)

close()

Close the session and clean up resources.
await session.close();

requestSampling()

Request LLM sampling from the client (if supported).
const response = await session.requestSampling({
  messages: [
    {
      role: "user",
      content: { type: "text", text: "Analyze this code" },
    },
  ],
  modelPreferences: {
    hints: [{ name: "claude-3-5-sonnet" }],
  },
  maxTokens: 1000,
});

console.log(response.content.text);
console.log(response.model);
message
CreateMessageRequest['params']
required
Sampling request parameters
options
RequestOptions
Request options (timeout, etc.)
response
SamplingResponse
interface SamplingResponse {
  content: TextContent | ImageContent | AudioContent;
  model: string;
  role: "assistant" | "user";
  stopReason?: "endTurn" | "maxTokens" | "stopSequence" | string;
}

waitForReady()

Wait for session to be ready.
await session.waitForReady();
console.log("Session is ready");

updateAuth()

Update the session’s authentication context.
const newAuth = { userId: "123", role: "admin" };
session.updateAuth(newAuth);
auth
T
required
New authentication data

Events

The session emits events that you can listen to:
session.on("ready", () => {
  console.log("Session ready");
});

session.on("error", ({ error }) => {
  console.error("Session error:", error);
});

session.on("rootsChanged", ({ roots }) => {
  console.log("Roots updated:", roots);
});
ready
() => void
Emitted when session is connected and ready
error
(event: { error: Error }) => void
Emitted when an error occurs
rootsChanged
(event: { roots: Root[] }) => void
Emitted when client roots change

OAuthSession

Standard session type for OAuth providers.
interface OAuthSession {
  accessToken: string;
  scopes?: string[];
  expiresAt?: number;
  idToken?: string;
  refreshToken?: string;
  claims?: Record<string, unknown>;
}
accessToken
string
The upstream OAuth access token
scopes
string[]
Scopes granted by the OAuth provider
expiresAt
number
Token expiration time (Unix timestamp in seconds)
idToken
string
ID token from OIDC providers
refreshToken
string
Refresh token (if available)
claims
Record<string, unknown>
Additional claims extracted from the token (if customClaimsPassthrough enabled)

Usage

import type { OAuthSession } from "fastmcp";

server.addTool({
  name: "get_token",
  execute: async (args, context) => {
    const session = context.session as OAuthSession;
    
    if (session) {
      console.log("Access token:", session.accessToken);
      console.log("Scopes:", session.scopes);
      console.log("Expires at:", new Date(session.expiresAt! * 1000));
    }
    
    return "Token info logged";
  },
});

Provider-Specific Sessions

Each OAuth provider extends OAuthSession with provider-specific fields.

GoogleSession

import type { GoogleSession } from "fastmcp";

interface GoogleSession extends OAuthSession {
  email?: string;  // User's Google email
}
Usage:
import { getAuthSession } from "fastmcp";
import type { GoogleSession } from "fastmcp";

server.addTool({
  name: "get_email",
  execute: async (args, context) => {
    const session = getAuthSession<GoogleSession>(context.session);
    return `Email: ${session.email}`;
  },
});

GitHubSession

import type { GitHubSession } from "fastmcp";

interface GitHubSession extends OAuthSession {
  username?: string;  // GitHub username
}
Usage:
import { getAuthSession } from "fastmcp";
import type { GitHubSession } from "fastmcp";

server.addTool({
  name: "get_repos",
  execute: async (args, context) => {
    const session = getAuthSession<GitHubSession>(context.session);
    const response = await fetch(
      `https://api.github.com/users/${session.username}/repos`,
      {
        headers: {
          Authorization: `Bearer ${session.accessToken}`,
        },
      },
    );
    const repos = await response.json();
    return JSON.stringify(repos);
  },
});

AzureSession

import type { AzureSession } from "fastmcp";

interface AzureSession extends OAuthSession {
  upn?: string;  // User Principal Name
}
Usage:
import { getAuthSession } from "fastmcp";
import type { AzureSession } from "fastmcp";

server.addTool({
  name: "get_profile",
  execute: async (args, context) => {
    const session = getAuthSession<AzureSession>(context.session);
    return `UPN: ${session.upn}`;
  },
});

Custom Session Types

Define custom session types for your authentication:
interface CustomSession {
  userId: string;
  role: "admin" | "user" | "guest";
  permissions: string[];
  organizationId: string;
}

const server = new FastMCP<CustomSession>({
  name: "custom-auth-server",
  version: "1.0.0",
  authenticate: async (request) => {
    const token = request.headers.authorization?.replace("Bearer ", "");
    
    if (!token) {
      return undefined;
    }
    
    // Validate token and return session
    const user = await validateToken(token);
    
    return {
      userId: user.id,
      role: user.role,
      permissions: user.permissions,
      organizationId: user.orgId,
    };
  },
});

server.addTool({
  name: "admin_action",
  canAccess: (auth) => auth?.role === "admin",
  execute: async (args, context) => {
    const session = context.session!;
    console.log(`Admin ${session.userId} in org ${session.organizationId}`);
    return "Action completed";
  },
});

FastMCP Events

FastMCP server emits connection events:
const server = new FastMCP({
  name: "my-server",
  version: "1.0.0",
});

server.on("connect", ({ session }) => {
  console.log("Client connected");
  console.log("Session ID:", session.sessionId);
  console.log("Client capabilities:", session.clientCapabilities);
});

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

await server.start({ transportType: "httpStream" });
connect
(event: { session: FastMCPSession<T> }) => void
Emitted when a client connects
disconnect
(event: { session: FastMCPSession<T> }) => void
Emitted when a client disconnects