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 correspondingserver.notify* helper instead.
Signature
ReturnsstringrequiredApplication-defined notification method. Use a namespace you control.Record<string, unknown>default:"undefined"Optional JSON-serializable notification parameters.
Promise<void>
sample
Requests sampling from the client’s LLM, with automatic progress notifications sent everyprogressIntervalMs (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
Returnsstring | CreateMessageRequest['params']requiredEither a prompt string (simplified API) or a complete sampling params object (full control API).SampleOptionsdefault:"undefined"Optional timeout, progress interval, max tokens, model preferences, and other sampling options. SeeSampleOptions.
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, returnsresult.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
ReturnsstringrequiredHuman-readable message explaining why the input is needed (overloads 1 and 2).z.ZodObject<any>requiredZod object schema describing the requested fields (form mode, overload 1).stringrequiredURL the user should navigate to (URL mode, overload 2).ElicitFormParams | ElicitUrlParamsrequiredVerbose params object (overload 3). SeeElicitFormParamsandElicitUrlParams.ElicitOptionsdefault:"undefined"Optional timeout. SeeElicitOptions.
Promise<ElicitResult & { data: z.infer<T> }> | Promise<ElicitResult>
reportProgress
Sends a progress notification to the client when the request includes aprogressToken. Returns false without sending when the caller did not
request progress updates.
Signature
ReturnsnumberrequiredCurrent progress value. Should increase with each call.numberdefault:"undefined"Total progress value, if known.stringdefault:"undefined"Optional message describing current progress.
Promise<boolean>
sendLog
Sends a log notification to the client. Always present onctx, 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
Returns"debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"requiredRFC 5424 log level.unknownrequiredJSON-serializable log data.stringdefault:"\"tool\""Optional logger name. Defaults to"tool".
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 onctx. 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 toctx.sendNotificationToSession() to target this session from another tool.
Signature
stringrequiredUnique identifier for the current session.
sendNotification
Sends a notification to the current session (the client that called this tool). A convenience overserver.sendNotification(), which broadcasts to all sessions. If the session has no sendNotification function, a warning is logged and the call resolves without sending.
Signature
ReturnsstringrequiredThe notification method name (e.g."custom/my-notification").Record<string, unknown>default:"undefined"Optional parameters to include in the notification.
Promise<void>
sendNotificationToSession
Sends a notification to a specific session by ID. UnlikesendNotification, 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
ReturnsstringrequiredThe target session ID (fromctx.session.sessionIdorserver.getActiveSessions()).stringrequiredThe notification method name.Record<string, unknown>default:"undefined"Optional parameters to include in the notification.
Promise<boolean>trueif the notification was sent,falseif the session was not found.
client object
Thectx.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. SignatureReturnsstringrequiredCapability name (e.g."sampling","elicitation","roots").
booleantrueif the client advertised this capability.
client.capabilities
Returns a shallow copy of the officialClientCapabilities declared by the current request, or an empty object when no modern envelope is available. Calls do not reuse capabilities from earlier requests.
Signature
ClientCapabilities
client.info
Returns a shallow copy of the officialImplementation 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
Partial<Implementation>
client.extension
Returns a shallow copy of one extension settings object declared by the current request, orundefined if that request did not advertise the extension.
Signature
ReturnsstringrequiredExtension identifier (e.g."io.modelcontextprotocol/ui").
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
UserContext | undefined
client.supportsViews
Returnstrue 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
boolean
Functions
getRequestContext()
Returns the current HonoContext 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.
The HonoContext | undefinedContextfor the current async operation, orundefinedif not in a request context.
hasRequestContext()
Returnstrue 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.
booleantrueif a request context is available.
runWithContext()
Runs an async function with a HonoContext (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.
ReturnsContextrequiredHonoContextobject to store for the duration offn.() => Promise<T>requiredFunction to execute within the context.stringdefault:"undefined"Optional session ID to store alongside the context.
Resolves to the return value ofPromise<T>fn.
Types
SampleOptions
Options for thesample() method on ToolContext. All fields are optional.
numberdefault:"Infinity (no timeout)"Timeout in milliseconds for the sampling request. Defaults to no timeout (waits indefinitely).numberdefault:"5000"Interval in milliseconds between progress notifications, sent to prevent client timeout whenresetTimeoutOnProgressis enabled.(progress: { progress: number; total?: number; message: string }) => voiddefault:"undefined"Callback invoked each time a progress notification is sent. Useful for logging.numberdefault:"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.stringdefault:"undefined"System prompt to prepend to the conversation.numberdefault:"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 theelicit() method on ToolContext.
numberdefault:"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 verboseelicit() overload to request structured data with optional JSON Schema validation.
stringrequiredHuman-readable message explaining why the information is needed.Record<string, any>requiredJSON 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 verboseelicit() overload to direct users to an external URL. Must be used for interactions involving sensitive information such as credentials.
stringrequiredHuman-readable message explaining why the interaction is needed.stringrequiredURL for the user to navigate to."url"requiredMode specifier. Required for URL mode.
UserContext
Normalized caller hints returned byctx.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.
stringdefault:"undefined"Browser or host user-agent string (fromopenai/userAgent).stringdefault:"undefined"BCP-47 locale tag, e.g."it-IT"(fromopenai/locale).{ city?: string; region?: string; country?: string; timezone?: string; latitude?: string | number; longitude?: string | number }default:"undefined"Approximate geographic location of the end user (fromopenai/userLocation).stringdefault:"undefined"Client-reported opaque subject hint (fromopenai/subject).stringdefault:"undefined"Identifier for the current chat or conversation thread (fromopenai/session). It is application metadata, not MCP transport state.stringdefault:"undefined"Client-reported organization hint (fromopenai/organization).
McpContext
Conditional Hono context type used as the base for MCP callbacks. TheHasOAuth 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").
Resolved shapesbooleandefault:"false"Whentrue,auth: AuthInfois guaranteed present. Whenfalse,auth?: AuthInfois optional.
HonoContext & { auth?: AuthInfo }Base context without OAuth.authis optional.HonoContext & { auth: AuthInfo; readonly __hasOAuth?: true }Context with OAuth configured.authis guaranteed present.