Skip to main content
RequestContext is the second argument (ctx) passed to tool, resource, and prompt callbacks. It exposes request cancellation, the current HTTP request, OAuth identity when configured, stateless elicitation, request-scoped notifications, progress and logging helpers, and the client metadata declared in the current request.
Client info and capabilities are self-reported, request-scoped hints. Never use ctx.client.info(), capabilities(), can(), extension(), or user() for authentication or authorization; use verified ctx.auth data instead.

RequestContext

Context object passed to tool, resource, and prompt callbacks. It augments the active Hono context with request-scoped MCP helpers and metadata.

sendNotification

Sends a custom one-way notification related to the active MCP request. The notification travels on the originating request’s response stream and must be awaited before the callback returns. It does not create a session or a post-response push channel. For cross-request tool, prompt, and resource changes, use the corresponding server.notify* helper instead. Signature
Example
Parameters
string
required
Application-defined notification method. Use a namespace you control.
Record<string, unknown>
default:"undefined"
Optional JSON-serializable notification parameters.
Returns
Promise<void>

sample

Requests sampling from the client’s LLM, with automatic progress notifications sent every progressIntervalMs (default 5000 ms) while waiting. This keeps clients that set resetTimeoutOnProgress: true from timing out. There is no timeout by default (the call waits indefinitely); set options.timeout to bound the wait. Has two overloads: a simplified string-prompt form and a full-control form that takes complete CreateMessageRequest["params"]. When called with a string prompt, the prompt is wrapped into a single user message and maxTokens defaults to 1000. Only available if the client advertised the sampling capability, check with ctx.client.can("sampling") first. Signature
Parameters
string | CreateMessageRequest['params']
required
Either a prompt string (simplified API) or a complete sampling params object (full control API).
SampleOptions
default:"undefined"
Optional timeout, progress interval, max tokens, model preferences, and other sampling options. See SampleOptions.
Returns
Promise<CreateMessageResult>

elicit

Requests user input via the client through elicitation. Supports three overloads with automatic mode detection: a Zod schema for form mode (type-safe, returns result.data typed via z.infer<T>), a URL string for URL mode (use for sensitive interactions such as OAuth), and the verbose params form for backward compatibility. There is no timeout by default; set options.timeout to bound the wait. In form mode, accepted responses are validated against the Zod schema. If validation fails, an ElicitationValidationError is thrown. The returned object always carries the SDK action ("accept", "decline", or "cancel"), and for accepted responses the input is exposed on result.data (validated against the Zod schema in form mode). Only available if the client advertised the elicitation capability. Signature
Parameters
string
required
Human-readable message explaining why the input is needed (overloads 1 and 2).
z.ZodObject<any>
required
Zod object schema describing the requested fields (form mode, overload 1).
string
required
URL the user should navigate to (URL mode, overload 2).
ElicitFormParams | ElicitUrlParams
required
Verbose params object (overload 3). See ElicitFormParams and ElicitUrlParams.
ElicitOptions
default:"undefined"
Optional timeout. See ElicitOptions.
Returns
Promise<ElicitResult & { data: z.infer<T> }> | Promise<ElicitResult>

reportProgress

Sends a progress notification to the client when the request includes a progressToken. Returns false without sending when the caller did not request progress updates. Signature
Parameters
number
required
Current progress value. Should increase with each call.
number
default:"undefined"
Total progress value, if known.
string
default:"undefined"
Optional message describing current progress.
Returns
Promise<boolean>

sendLog

Sends a log notification to the client. Always present on ctx, and sends notifications when the client supports them. Levels follow RFC 5424; if the client set a minimum log level, messages below that threshold are dropped silently. Signature
Parameters
"debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"
required
RFC 5424 log level.
unknown
required
JSON-serializable log data.
string
default:"\"tool\""
Optional logger name. Defaults to "tool".
Returns
Promise<void>

client

The request-scoped client metadata interface. Modern v2 clients declare their implementation and capabilities on every request; no value is inferred from a previous request or session. Always present on ctx. See the client object section for each method. Signature

session

Session information for the current tool execution. Exposes the unique session ID, which can be passed to ctx.sendNotificationToSession() to target this session from another tool. Signature
Properties
string
required
Unique identifier for the current session.

sendNotification

Sends a notification to the current session (the client that called this tool). A convenience over server.sendNotification(), which broadcasts to all sessions. If the session has no sendNotification function, a warning is logged and the call resolves without sending. Signature
Parameters
string
required
The notification method name (e.g. "custom/my-notification").
Record<string, unknown>
default:"undefined"
Optional parameters to include in the notification.
Returns
Promise<void>

sendNotificationToSession

Sends a notification to a specific session by ID. Unlike sendNotification, this can target any connected session, useful for cross-session coordination. Resolves to false if the target session is not found or has no notification channel, otherwise true. Signature
Parameters
string
required
The target session ID (from ctx.session.sessionId or server.getActiveSessions()).
string
required
The notification method name.
Record<string, unknown>
default:"undefined"
Optional parameters to include in the notification.
Returns
Promise<boolean>
true if the notification was sent, false if the session was not found.

client object

The ctx.client object reflects metadata declared for the current request. can, capabilities, info, extension, and supportsViews read one snapshot of MCP’s modern metadata envelope. user separately normalizes ordinary OpenAI-specific request _meta. No accessor consults session state or reuses an earlier request. Object accessors return defensive copies, and missing metadata uses empty or absent fallbacks. All values are client-declared and unverified. Use them to select compatible response behavior, never to grant access; verified identity is available through ctx.auth when OAuth is configured.

client.can

Checks whether the current request advertises a specific top-level capability. It reports own-property presence, not a truthy value. Signature
Parameters
string
required
Capability name (e.g. "sampling", "elicitation", "roots").
Returns
boolean
true if the client advertised this capability.

client.capabilities

Returns a shallow copy of the official ClientCapabilities declared by the current request, or an empty object when no modern envelope is available. Calls do not reuse capabilities from earlier requests. Signature
Returns
ClientCapabilities

client.info

Returns a shallow copy of the official Implementation metadata declared by the current request. Valid modern requests include name and version; the partial type and empty-object fallback preserve v1 ergonomics for legacy requests without an envelope. Signature
Returns
Partial<Implementation>

client.extension

Returns a shallow copy of one extension settings object declared by the current request, or undefined if that request did not advertise the extension. Signature
Parameters
string
required
Extension identifier (e.g. "io.modelcontextprotocol/ui").
Returns
NonNullable<ClientCapabilities['extensions']>[string] | undefined

client.user

Returns normalized OpenAI-specific caller hints from the current request’s ordinary _meta, or undefined when no recognized valid field is present. It does not require the modern MCP client envelope. Every call returns a fresh object and, when present, a fresh nested location object. Recognized keys are openai/locale (with legacy webplus/i18n fallback), openai/userAgent, openai/userLocation, openai/subject, openai/session, and openai/organization. Malformed values and the no-longer-documented timezone_offset_minutes key are ignored. Signature
Returns
UserContext | undefined
Every field is supplied by the client. A subject, conversation ID, or organization ID is not proof of identity or membership. Use ctx.auth for authentication and authorization.

client.supportsViews

Returns true if the current request advertises MCP Apps support: the io.modelcontextprotocol/ui extension whose mimeTypes includes text/html;profile=mcp-app. Use it to conditionally shape a result for view-capable clients. Signature
Returns
boolean

Functions

getRequestContext()

Returns the current Hono Context from AsyncLocalStorage, or undefined when called outside a request context. Lets deeply nested code (tool callbacks, dynamically imported resource or prompt handlers) read request headers, middleware-set variables such as auth, and env without explicit parameter passing.
Signature
Returns
Context | undefined
The Hono Context for the current async operation, or undefined if not in a request context.

hasRequestContext()

Returns true when the current async operation is executing within a request context (an AsyncLocalStorage store is set). Use it to branch before calling getRequestContext() when a Context may or may not be present.
Signature
Returns
boolean
true if a request context is available.

runWithContext()

Runs an async function with a Hono Context (and optional session ID) stored in AsyncLocalStorage, so that any async operation inside fn can retrieve it via getRequestContext(). The framework wraps MCP request handling in this for you; you typically only call it directly when integrating custom request handling.
Signature
Parameters
Context
required
Hono Context object to store for the duration of fn.
() => Promise<T>
required
Function to execute within the context.
string
default:"undefined"
Optional session ID to store alongside the context.
Returns
Promise<T>
Resolves to the return value of fn.

Types

SampleOptions

Options for the sample() method on ToolContext. All fields are optional.
Signature
Properties
number
default:"Infinity (no timeout)"
Timeout in milliseconds for the sampling request. Defaults to no timeout (waits indefinitely).
number
default:"5000"
Interval in milliseconds between progress notifications, sent to prevent client timeout when resetTimeoutOnProgress is enabled.
(progress: { progress: number; total?: number; message: string }) => void
default:"undefined"
Callback invoked each time a progress notification is sent. Useful for logging.
number
default:"1000"
Maximum number of tokens to generate. Only used with the string-prompt shorthand.
{ hints?: Array<{ name?: string }>; costPriority?: number; speedPriority?: number; intelligencePriority?: number }
default:"undefined"
Model preferences, including hints by name and cost / speed / intelligence priorities.
string
default:"undefined"
System prompt to prepend to the conversation.
number
default:"undefined"
Temperature for sampling (0.0 to 1.0). Controls randomness.
string[]
default:"undefined"
Stop sequences that end generation.
Record<string, unknown>
default:"undefined"
Additional metadata to pass with the request.

ElicitOptions

Options for the elicit() method on ToolContext.
Signature
Properties
number
default:"Infinity (no timeout)"
Timeout in milliseconds for the elicitation request. Defaults to no timeout (waits indefinitely for the user response).

ElicitFormParams

Parameters for form mode elicitation, used with the verbose elicit() overload to request structured data with optional JSON Schema validation.
Signature
Properties
string
required
Human-readable message explaining why the information is needed.
Record<string, any>
required
JSON Schema defining the structure of the expected response.
"form"
default:"\"form\""
Mode specifier. Optional for backward compatibility, defaults to form mode.

ElicitUrlParams

Parameters for URL mode elicitation, used with the verbose elicit() overload to direct users to an external URL. Must be used for interactions involving sensitive information such as credentials.
Signature
Properties
string
required
Human-readable message explaining why the interaction is needed.
string
required
URL for the user to navigate to.
"url"
required
Mode specifier. Required for URL mode.

UserContext

Normalized caller hints returned by ctx.client.user(), extracted from per-request _meta using OpenAI’s documented key convention. All fields are optional, and the whole object is undefined when no recognized valid field is present. This data is client-reported and unverified; do not treat it as identity or authorization data.
Signature
Properties
string
default:"undefined"
Browser or host user-agent string (from openai/userAgent).
string
default:"undefined"
BCP-47 locale tag, e.g. "it-IT" (from openai/locale).
{ city?: string; region?: string; country?: string; timezone?: string; latitude?: string | number; longitude?: string | number }
default:"undefined"
Approximate geographic location of the end user (from openai/userLocation).
string
default:"undefined"
Client-reported opaque subject hint (from openai/subject).
string
default:"undefined"
Identifier for the current chat or conversation thread (from openai/session). It is application metadata, not MCP transport state.
string
default:"undefined"
Client-reported organization hint (from openai/organization).

McpContext

Conditional Hono context type used as the base for MCP callbacks. The HasOAuth type parameter selects whether auth is guaranteed present. With HasOAuth = true (McpContextWithAuth), auth: AuthInfo is non-optional because tools are protected by default when OAuth is configured. With the default HasOAuth = false (McpContextBase), auth?: AuthInfo is optional so you can null-check, for example if (!ctx.auth) return error("Not authenticated").
Signature
Type Parameters
boolean
default:"false"
When true, auth: AuthInfo is guaranteed present. When false, auth?: AuthInfo is optional.
Resolved shapes
HonoContext & { auth?: AuthInfo }
Base context without OAuth. auth is optional.
HonoContext & { auth: AuthInfo; readonly __hasOAuth?: true }
Context with OAuth configured. auth is guaranteed present.