View the source code for this module on GitHub: https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/mcp-use/src/server/types/tool-context.ts
ToolContext is the second argument (ctx) passed to every tool callback registered with server.tool(...). It gives the callback access to sampling, elicitation, progress and log notifications, the connecting client’s identity and capabilities, the current session, and notification helpers. Each member is wired up per invocation by createEnhancedContext, so members that depend on client capabilities or a progress token (for example reportProgress) may be undefined when the client did not request them.
Members that require a feature the client did not negotiate are optional at the type level.
reportProgress is only present when the client supplied a progressToken for the call. sendNotification and sendNotificationToSession are only present when the call is associated with a session. Guard with ctx.client.can(...) before calling ctx.sample or ctx.elicit, and null-check ctx.reportProgress before invoking it.ToolContext
Context object passed to tool callbacks. Provides access to sampling, elicitation, progress reporting, logging, client identity, session info, and notification helpers.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
ReturnsEither a prompt string (simplified API) or a complete sampling params object (full control API).Optional timeout, progress interval, max tokens, model preferences, and other sampling options. SeeSampleOptions.
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
ReturnsHuman-readable message explaining why the input is needed (overloads 1 and 2).Zod object schema describing the requested fields (form mode, overload 1).URL the user should navigate to (URL mode, overload 2).Verbose params object (overload 3). SeeElicitFormParamsandElicitUrlParams.Optional timeout. SeeElicitOptions.
reportProgress
Sends a progress notification to the client. Optional (undefined) unless the client requested progress updates for this tool call by supplying a progressToken. Null-check before calling: await ctx.reportProgress?.(50, 100, "Halfway").
Signature
ReturnsCurrent progress value. Should increase with each call.Total progress value, if known.Optional message describing current progress.
log
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
Returnslevel"debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"requiredRFC 5424 log level.Log message content.Optional logger name. Defaults to"tool".
client
The client capability interface, providing access to the capabilities and identity the client advertised during the initialize handshake, plus per-invocation caller context. 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
Unique 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
ReturnsThe notification method name (e.g."custom/my-notification").Optional parameters to include in the notification.
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
ReturnsThe target session ID (fromctx.session.sessionIdorserver.getActiveSessions()).The notification method name.Optional parameters to include in the notification.
trueif the notification was sent,falseif the session was not found.
client object
Thectx.client object reflects the connecting client. The can, capabilities, info, extension, and supportsApps methods describe the session-level initialize handshake and are stable for the lifetime of the connection. user() is per-invocation and may return a different value on every tool call.
client.can
Checks whether the client advertised a specific top-level capability. Backed bycapability in capabilities, so it reports presence, not a truthy value.
Signature
ReturnsCapability name (e.g."sampling","elicitation","roots").
trueif the client advertised this capability.
client.capabilities
Returns a shallow copy of all capabilities advertised by the client, or an empty object if none. The copy prevents callers from mutating internal state. Signatureclient.info
Returns the connecting client’s name and version from the MCP initialize handshake. Either field may beundefined if the client did not provide it.
Signature
client.extension
Returns the settings object for a specific MCP extension (SEP-1724), orundefined if the client did not advertise that extension. Reads from capabilities.extensions[id].
Signature
ReturnsExtension identifier (e.g."io.modelcontextprotocol/ui").
client.supportsApps
Returnstrue if the client advertises MCP Apps support (SEP-1865): the io.modelcontextprotocol/ui extension whose mimeTypes includes text/html;profile=mcp-app. Use it to conditionally return widget-aware responses. See the standalone supportsApps() helper for the same check against a raw capabilities object.
Signature
client.user
Returns normalized end-user context fromparams._meta sent by the client on this specific tool invocation, or undefined when the client does not include user metadata (Inspector, Claude Desktop, CLI, most non-ChatGPT clients). See UserContext for the shape.
This value is per-invocation and can differ on every tool call, unlike the other ctx.client methods which reflect the session-level handshake. The data is self-reported and unverified, so do not use it for access control. For verified identity use ctx.auth (requires OAuth). Under the ChatGPT multi-tenant model a single MCP session is shared across all users: use subject to identify the user and conversationId to identify the chat thread.
Signature
Functions
supportsApps()
Standalone helper that checks whether a raw client capabilities object advertises MCP Apps support (SEP-1865, theio.modelcontextprotocol/ui extension with MIME type text/html;profile=mcp-app). Returns false when the argument is undefined or the extension or MIME type is missing. Use it at server setup time (for example inside server.onClientConnected) when you want to register widget-enabled tool variants before any callback runs. Inside a callback, prefer ctx.client.supportsApps().
ReturnsThe raw capabilities object advertised by the client.
trueif the capabilities advertise MCP Apps support.
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 HonoContextfor 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.
trueif 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.
ReturnsHonoContextobject to store for the duration offn.Function to execute within the context.Optional session ID to store alongside the context.
Resolves to the return value offn.
Types
SampleOptions
Options for thesample() method on ToolContext. All fields are optional.
Timeout in milliseconds for the sampling request. Defaults to no timeout (waits indefinitely).Interval in milliseconds between progress notifications, sent to prevent client timeout whenresetTimeoutOnProgressis enabled.onProgress(progress: { progress: number; total?: number; message: string }) => voiddefault:"undefined"Callback invoked each time a progress notification is sent. Useful for logging.Maximum number of tokens to generate. Only used with the string-prompt shorthand.modelPreferences{ hints?: Array<{ name?: string }>; costPriority?: number; speedPriority?: number; intelligencePriority?: number }default:"undefined"Model preferences, including hints by name and cost / speed / intelligence priorities.System prompt to prepend to the conversation.Temperature for sampling (0.0 to 1.0). Controls randomness.Stop sequences that end generation.Additional metadata to pass with the request.
ElicitOptions
Options for theelicit() method on ToolContext.
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.
Human-readable message explaining why the information is needed.JSON Schema defining the structure of the expected response.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.
Human-readable message explaining why the interaction is needed.URL for the user to navigate to.Mode specifier. Required for URL mode.
UserContext
Normalized end-user context returned byctx.client.user(), extracted from per-request params._meta (the ChatGPT openai/* key convention). All fields are optional, and the whole object is undefined on clients that do not send request-level metadata. This data is client-reported and unverified, do not treat it as a trusted identity.
Browser or host user-agent string (fromopenai/userAgent).BCP-47 locale tag, e.g."it-IT"(fromopenai/locale).location{ city?: string; region?: string; country?: string; timezone?: string; latitude?: string; longitude?: string }default:"undefined"Approximate geographic location of the end user (fromopenai/userLocation).UTC offset in minutes (fromtimezone_offset_minutes).Stable, opaque identifier for the end user (fromopenai/subject). Remains constant across chat conversations for the same user.Identifier for the current chat or conversation thread (fromopenai/session). Distinct from the MCP session ID (ctx.session.sessionId); changes each time the user starts a new conversation.
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 shapesWhentrue,auth: AuthInfois guaranteed present. Whenfalse,auth?: AuthInfois optional.
Base context without OAuth.authis optional.Context with OAuth configured.authis guaranteed present.