import * as _modelcontextprotocol_server from '@modelcontextprotocol/server'; import { InputResponses, Server, CacheHint, ServerContext, ServerEventBus, Transport, McpHandlerRequestOptions, CallToolResult, OAuthClientInformationFull, AuthInfo } from '@modelcontextprotocol/server'; export { AuthInfo, InputRequest, InputRequests, InputRequiredResult, InputRequiredSpec, InputResponse, InputResponseView, InputResponses, McpHandlerRequestOptions, ServerEventBus, acceptedContent, inputRequired, inputResponse, isInputRequiredResult } from '@modelcontextprotocol/server'; import { OAuthServerProvider, AuthorizationParams } from '@modelcontextprotocol/server-legacy/auth'; import { StandardSchemaV1 } from '@standard-schema/spec'; import { Readable, Writable } from 'node:stream'; import { Response as Response$1 } from 'express'; /** Sink contract for FastMCPOptions.logger. `console` and Winston loggers * satisfy it structurally; Pino needs a small adapter (see docs/servers/logging.mdx). */ interface Logger { debug(message: string, meta?: Record): void; info(message: string, meta?: Record): void; warn(message: string, meta?: Record): void; error(message: string, meta?: Record): void; } declare const FRAMEWORK_LOG_LEVELS: readonly ["debug", "info", "warn", "error", "silent"]; /** Framework-diagnostics level axis. Distinct from the MCP `LogLevel` union * (client-facing `ctx.log` levels), which is a separate axis entirely. */ type FrameworkLogLevel = (typeof FRAMEWORK_LOG_LEVELS)[number]; interface BannerFields { name: string; version: string; transport: 'stdio' | 'http'; url?: string; } /** Level-gated wrapper around the sink. This is what the framework holds and * calls; the gate applies identically to injected and default sinks. */ declare class ResolvedLogger { private readonly sink; readonly level: FrameworkLogLevel; constructor(sink: Logger, level: FrameworkLogLevel); private enabled; debug(message: string, meta?: Record): void; info(message: string, meta?: Record): void; warn(message: string, meta?: Record): void; error(message: string, meta?: Record): void; /** Server-start card. Pretty DefaultSink renders a banner block; * every other sink gets one plain info line. Gated as info. */ startupBanner(fields: BannerFields): void; /** Listening confirmation. The word "listening" is load-bearing: the CLI's * run command detects a successful start by sniffing stderr for it. */ listening(url: string): void; } /** * Read-only, per-request snapshot of the HTTP request that carried the current * MCP message. Present wherever the server is reached over an HTTP transport; * `undefined` on stdio. * * REDACTION: credential headers (see {@link DEFAULT_SENSITIVE_HEADERS}, tuned * by `FastMCPOptions.http`) are withheld from `headers` and listed in * `redactedHeaderNames`, so a `null` lookup is never silent. The redaction * guards accidental egress: tool results and logs flow into model context by * design. A `RequestVerifier` receives the FULL wire headers instead (its * `redactedHeaderNames` is empty): the verifier is the credential-handling * code. * * TRUST: every value here is client-controlled input. Nothing in this object * is authenticated. Do not derive authorization from it in handlers. For * header-established identity (trusted reverse proxy), configure * `FastMCPOptions.auth` with a `RequestVerifier` so identity flows through * `ctx.auth` like every other authenticated request. See docs: * servers/auth/trusted-proxy. */ interface HttpRequestContext { /** Headers of the carrying HTTP request, minus the sensitive set. A per-request copy; mutations affect nothing. */ readonly headers: Headers; /** Names (lowercase, sorted) that were present on the wire but withheld from `headers`. */ readonly redactedHeaderNames: readonly string[]; /** HTTP method of the carrying request (e.g. 'POST'). */ readonly method: string; /** * Origin-form request target (path + query, e.g. '/mcp?tenant=a'). Scheme and * authority are deliberately absent: behind a proxy this server cannot know * the external URL. Reconstruct it from your proxy's forwarded headers if you * need it. */ readonly url: string; } /** * Copy of `headers` that is safe to attach to an outbound request to another * service. Drops credentials (authorization, cookie, proxy-*), hop-by-hop * headers, message-framing headers (host, content-length, content-type, * expect), and every `mcp-*` protocol header. Deployment-specific credential * headers are covered by `FastMCPOptions.http.redactHeaders`: they are already * absent from `ctx.http.headers`. `include` re-admits specific names. * Re-admitting 'authorization' forwards the caller's credential; the MCP spec * forbids passing the inbound token to upstream APIs, so mint your own * upstream credential instead. */ declare function forwardableHeaders(headers: Headers, options?: { include?: string[]; }): Headers; interface AccessToken { /** The raw bearer token string. */ token: string; /** The subject/client identifier from the token. */ clientId?: string; /** Scopes granted to the token. */ scopes: string[]; /** Unix timestamp (seconds) when the token expires. */ expiresAt?: number; /** All claims from the token payload. */ claims: Record; } interface TokenVerifier { verify(token: string): Promise; } /** * Request-level verifier for HTTP deployments where identity does not arrive * as a bearer token. The typical case is a trusted reverse proxy that * authenticates the caller and forwards the resolved identity as request * headers. * * Called once per HTTP request, before dispatch, with that request's own FULL * wire headers (no redaction; `request.redactedHeaderNames` is empty here — * the verifier is the credential-handling code). Return an AccessToken to * admit the request. The result becomes `ctx.auth`, feeds per-item `auth` * checks and list filtering, and its `token` (hashed) keys response-cache * partitioning. `token` MUST therefore be a stable, non-empty, per-identity * value, such as the verified user id. The server rejects an empty `token` * with HTTP 500. Throw `AuthorizationError` to produce 403; any other throw * produces 401. * * SECURITY: request headers are forgeable by anyone who can reach this server * directly. Trust them only after verifying provenance: a shared secret the * proxy injects, mTLS, or network isolation. Add your provenance-secret * header to `FastMCPOptions.http.redactHeaders` so it never surfaces in * `ctx.http`. See docs: servers/auth/trusted-proxy. * * HTTP transports only. On stdio there is no HTTP request; configure a * TokenVerifier if you need `FASTMCP_CLI_AUTH_TOKEN` support. */ interface RequestVerifier { verifyRequest(request: HttpRequestContext): Promise; } /** * Thrown by authorization checks to produce a 403 response. * Any other error thrown during verification produces a 401. */ declare class AuthorizationError extends Error { constructor(message: string); } type AuthCheck = (token: AccessToken) => void | Promise; declare function requireScopes(...scopes: string[]): AuthCheck; /** * Argument completion (`completion/complete`) — the callback contract shared by * prompt arguments and resource-template variables. * * A completion callback turns a partial value the user has typed into a set of * suggestions. It attaches to a single prompt argument (`PromptArgument.complete`) * or a single resource-template variable (`ResourceConfig.complete[variable]`); * the server routes each `completion/complete` request to the matching callback * by the request's `ref` type. See FastMCP `_completePrompt` / * `_completeResourceTemplate`. * * `completion/complete` lives in BOTH protocol eras' wire registries (the legacy * 2025-11-25 registry and the modern 2026-07-28 `dispatchRequestSchemas`), so the * handler and the `completions` capability are declared unconditionally — no * per-era fork, unlike `resources/subscribe`. */ /** * Optional context the client forwards with a completion request: the values it * has already resolved for the prompt's OTHER arguments (or the template's other * variables). Use it to narrow suggestions — e.g. offer cities once a country is * chosen. */ interface CompletionContext { arguments?: Record; } /** * The paginated shape a completion callback MAY return for full control over the * `total` / `hasMore` hints. Mirrors the wire `CompleteResult.completion` object. * Returning a bare `string[]` instead is the common case. */ interface CompletionResult { /** Suggested values. Capped to 100 on the wire (the spec's maximum). */ values: string[]; /** Total number of matches available, if larger than `values`. */ total?: number; /** Whether more matches exist beyond `values`. */ hasMore?: boolean; } /** * A completion callback. Receives the partial `value` the user has typed and the * optional resolved-argument `context`, and returns suggestions — either a bare * `string[]` or a {@link CompletionResult} with explicit pagination hints. May be * async. */ type CompleteCallback = (value: string, context?: CompletionContext) => string[] | CompletionResult | Promise; interface PromptArgument { name: string; description?: string; /** When true, the client must supply this argument. Defaults to false. */ required?: boolean; /** * Autocompletion callback for this argument. When set, a `completion/complete` * request for `{ ref: { type: 'ref/prompt', name }, argument: { name, value } }` * routes here. Not advertised in `prompts/list` — the client discovers it by * calling `completion/complete`. */ complete?: CompleteCallback; } interface PromptConfig { /** Unique prompt identifier. Inferred from the handler function name when omitted. */ name?: string; /** Human-readable display name shown in UIs. */ title?: string; /** Description shown to clients and LLMs. Inferred from name when omitted. */ description?: string; /** Declared arguments. Advertised to clients in prompts/list. */ arguments?: PromptArgument[]; /** When true the prompt is hidden from list responses and cannot be invoked. */ disabled?: boolean; /** Execution timeout in milliseconds. No timeout by default. */ timeout?: number; /** Arbitrary tags for server-side filtering and transforms. */ tags?: string[]; auth?: AuthCheck; } type TextContent = { type: 'text'; text: string; }; type ImageContent = { type: 'image'; data: string; mimeType: string; }; type AudioContent = { type: 'audio'; data: string; mimeType: string; }; type ResourceLinkContent = { type: 'resource_link'; uri: string; name?: string; description?: string; mimeType?: string; }; type EmbeddedResource = { type: 'resource'; resource: { uri: string; mimeType?: string; } & ({ text: string; } | { blob: string; }); }; type PromptContent = TextContent | ImageContent | AudioContent | EmbeddedResource | ResourceLinkContent; interface PromptMessage { role: 'user' | 'assistant'; content: PromptContent; } /** * Escape hatch for full control over the prompt response. * Return this from a prompt handler to set an explicit description and/or * supply a custom multi-turn message sequence. */ declare class PromptResult { readonly messages: PromptMessage[]; readonly description?: string | undefined; constructor(messages: PromptMessage[], description?: string | undefined); } type LogLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency'; interface SamplingMessage { role: 'user' | 'assistant'; content: { type: 'text'; text: string; } | { type: 'image'; data: string; mimeType: string; }; } interface SamplingParams { messages: SamplingMessage[]; systemPrompt?: string; /** Maximum tokens to generate. Defaults to 1024. */ maxTokens?: number; temperature?: number; stopSequences?: string[]; modelPreferences?: { hints?: Array<{ name?: string; }>; costPriority?: number; speedPriority?: number; intelligencePriority?: number; }; } interface SamplingResult { role: 'assistant'; content: { type: 'text'; text: string; } | { type: 'image'; data: string; mimeType: string; }; model: string; stopReason?: string; } /** * Flat JSON Schema object describing fields to collect from the user. * Only primitive property types (string, number, boolean) are allowed per the MCP spec. */ interface ElicitationSchema { type: 'object'; properties: Record; required?: string[]; } interface ElicitationResult { /** How the user responded to the elicitation. */ action: 'accept' | 'decline' | 'cancel'; /** Submitted form values. Present only when action is 'accept'. */ content?: Record; } interface Root { uri: string; name?: string; } interface McpContext { /** Auth token for the current request, if any. */ auth: AccessToken | undefined; /** The MCP request ID for the current call. */ requestId: string | undefined; /** * The HTTP request carrying the current MCP message, when serving over an * HTTP transport; `undefined` on stdio. Fresh per request: on a sessionful * connection each request's own headers appear here, never the * initialize-time ones. Credential headers are withheld by default and * listed in `http.redactedHeaderNames` (tune with `FastMCPOptions.http`). * Untrusted input; see HttpRequestContext's docs before deriving any * authorization from it. */ http: HttpRequestContext | undefined; /** Send a log message to the client at the specified RFC 5424 severity level. */ log(level: LogLevel, message: string, loggerName?: string): Promise; debug(message: string, loggerName?: string): Promise; info(message: string, loggerName?: string): Promise; notice(message: string, loggerName?: string): Promise; warning(message: string, loggerName?: string): Promise; error(message: string, loggerName?: string): Promise; critical(message: string, loggerName?: string): Promise; alert(message: string, loggerName?: string): Promise; emergency(message: string, loggerName?: string): Promise; /** * Send a progress notification to the client. * No-op if the request did not include a `progressToken` in its `_meta`. */ reportProgress(progress: number, total?: number, message?: string): Promise; /** * Ask the client to perform an LLM inference call and return the result. * Throws if the client has not advertised the `sampling` capability. * * @deprecated Sampling is deprecated as of protocol revision 2026-07-28 (SEP-2577) * and this push-style call only works on a legacy (2025-era) connection — calling it * on a modern request throws a clear error naming the replacement (return * `inputRequired({ inputRequests: { id: inputRequired.createMessage({...}) } })` from * the handler instead; see `fastmcp-ts/server`'s re-exported `inputRequired`). A * handler written the `inputRequired` way serves both eras unchanged — the SDK's * legacy shim fulfils it via a real server→client request on 2025-era connections, so * there is rarely a reason to keep calling `ctx.sample()` directly in new code. */ sample(params: SamplingParams): Promise; /** * Ask the client to collect input from the user via a form dialog. * Throws if the client has not advertised the `elicitation` capability. * * @deprecated Throws a clear error naming the replacement when called on a modern * (2026-07-28) request — return `inputRequired({ inputRequests: { id: * inputRequired.elicit({...}) } })` instead (see `ctx.sample`'s docs; the same * write-once, serve-both-eras guidance applies). */ elicit(message: string, schema: ElicitationSchema): Promise; /** * Request the list of filesystem roots the client has declared. * Throws if the client has not advertised the `roots` capability. * * @deprecated Roots is deprecated as of protocol revision 2026-07-28 (SEP-2577) — * prefer passing paths via tool parameters, resource URIs, or server configuration. * Throws a clear error naming `inputRequired(...)` as the multi-round-trip * replacement when called on a modern request (see `ctx.sample`'s docs). */ listRoots(): Promise; /** * The current round's embedded input responses, when this request is a retry of an * earlier `inputRequired(...)` return. `undefined` on the flow's first call (no * prior round to respond to). Read with the SDK's `acceptedContent(ctx.inputResponses, * key)` / `inputResponse(ctx.inputResponses, key)` (re-exported from * `fastmcp-ts/server`) rather than indexing this object directly — those readers * validate shape and, for `acceptedContent`, optionally the content against a schema. */ inputResponses: InputResponses | undefined; /** * Reads the current round's `requestState`, already verified and decoded when * `FastMCPOptions.requestState` is configured (the payload `verify` resolved with); * the raw, unverified wire string when it is not configured — treat that case as * attacker-controlled input. `undefined` when the round carried no state. */ requestState(): T | undefined; /** * Seals `payload` into the opaque `requestState` string to return from * `inputRequired({ requestState })`. HMAC-signed via `FastMCPOptions.requestState` * when configured; otherwise a plain `JSON.stringify(payload)` with a console * warning — the resulting state is unsigned and MUST NOT be trusted for * anything that influences authorization, resource access, or business logic (the * client can read and tamper with it) unless `FastMCPOptions.requestState` is set. */ mintRequestState(payload: T): Promise; /** Retrieve a value from session-scoped state. Returns undefined if not set. */ getState(key: string): unknown; /** Store a value in session-scoped state. Persists for the lifetime of the session. */ setState(key: string, value: unknown): void; /** Remove a value from session-scoped state. */ deleteState(key: string): void; /** * Resolve a logical tool name to its current external name, accounting for * any namespace prefix applied when the owning FastMCPApp was mounted. * Returns the name unchanged when called outside a mounted context. */ resolveToolName(name: string): string; /** * Register a callback that runs when the current session closes. * Useful for releasing per-session resources (e.g. uploaded files). * No-op if called outside an active HTTP session. */ onClose(callback: () => void): void; } /** * Handler for a custom HTTP route served by the listener `run()` starts. * Owns the whole exchange: no MCP auth, no DNS-rebinding guards, and no CORS * headers run in front of it, and its Response is written back verbatim. */ type CustomRouteHandler = (request: Request) => Response | Promise; interface CustomRouteConfig { /** Exact request path to serve; the query string is ignored for matching. * Must start with `/`. No patterns, no path parameters. */ path: string; /** * HTTP methods served, compared case-insensitively. Default: `['GET']`. * `OPTIONS` is rejected at registration: it is reserved for the global * CORS preflight, and never dispatches to a route even when CORS is * disabled (`http.cors: false`). */ methods?: string[]; } /** `RunOptions.health` object form. Presence implies enabled. */ interface HealthOptions { /** Force off with `false`; the object's presence already implies `true`. */ enabled?: boolean; /** Request path of the endpoint. Default: `/healthz`. */ path?: string; /** Response status code. Default: `200`. */ status?: number; /** Response body, served as `text/plain`. Default: `'ok'`. */ body?: string; } interface MiddlewareContext { readonly method: string; readonly request: T; readonly mcpContext: McpContext; } type Next = () => Promise; /** * A middleware hook. Either call `next()` and return (optionally transforming) its * result, or short-circuit by returning your own result without calling `next()`. * The return is typed `Promise` because a hook can substitute any result * shape for the method it intercepts; the framework resolves the concrete type at * the call boundary. */ interface Middleware { /** Called once per Server instance. Use to register notification handlers or other server-level setup. */ setup?(server: Server): void; onRequest?(ctx: MiddlewareContext, next: Next): Promise; onCallTool?(ctx: MiddlewareContext, next: Next): Promise; onListTools?(ctx: MiddlewareContext, next: Next): Promise; onReadResource?(ctx: MiddlewareContext, next: Next): Promise; onListResources?(ctx: MiddlewareContext, next: Next): Promise; onListResourceTemplates?(ctx: MiddlewareContext, next: Next): Promise; onGetPrompt?(ctx: MiddlewareContext, next: Next): Promise; onListPrompts?(ctx: MiddlewareContext, next: Next): Promise; } /** Logs every request with method, outcome, and elapsed time. * * Output resolution, in order: an explicit `emit` (unchanged legacy behavior, * `[fastmcp]`-prefixed strings); the server's framework logger when attached * via FastMCPOptions.middleware or `use()`; a plain stderr write. The default * was `console.log` before v-next, which corrupted the stdio protocol stream. */ declare class LoggingMiddleware implements Middleware { private readonly emit?; private logger; constructor(emit?: ((msg: string) => void) | undefined); /** @internal Called by FastMCP when this middleware is attached. */ _bindLogger(logger: ResolvedLogger): void; private emitRequest; private emitResponse; private emitFailure; onRequest(ctx: MiddlewareContext, next: Next): Promise; } /** * Custom cache key function. Receives the full middleware context so callers can * incorporate auth identity or any other dimension into the key. * * **The default key already partitions by auth identity — you do not need a `keyFn` * for auth safety.** The default is * `"method::JSON(params)"`, where the auth partition is `anon` for a * request with no bearer token and the SHA-256 hash of the bearer token for an * authenticated request. So a result computed under one identity is never served under * another (anonymous and authenticated included, both directions), and auth-filtered * list results (tools, resources, prompts) stay per identity. * * **A custom `keyFn` REPLACES the default partitioning entirely — you then own it.** * The key you return is used verbatim; the auth partition is not merged in. If your * cached values depend on the caller identity, include an identity dimension yourself. * Use the same dimension the default uses — the bearer token, HASHED. Never place the * raw token in a cache key: * * ```ts * import { createHash } from 'node:crypto' * * new CachingMiddleware(60_000, (ctx) => { * const token = ctx.mcpContext.auth?.token * const id = token ? createHash('sha256').update(token).digest('hex') : 'anon' * return `${ctx.method}:${id}:${JSON.stringify(ctx.request)}` * }) * ``` * * `clientId` is a coarser alternative (`ctx.mcpContext.auth?.clientId`), but two tokens * may share a `clientId` yet differ in scope, so a `clientId` key can merge identities * that must stay apart. Prefer the hashed token. */ type CacheKeyFn = (ctx: MiddlewareContext) => string; /** TTL-based response cache. The default key is method + auth partition + serialised * request params, so a cached result is served only to the identity that produced it * (anonymous is its own partition; authenticated requests partition by bearer-token * hash). Auth-filtered results (tools/list visibility, resources/read contents, * prompts, completion) therefore never cross identities. Pass a custom `keyFn` to * replace this partitioning — the caller then owns identity partitioning (see * {@link CacheKeyFn}). */ declare class CachingMiddleware implements Middleware { readonly ttl: number; private readonly _keyFn?; private readonly _cache; /** * Side-effectful control RPCs that must never be cached. The cache keys on method * + params, but these methods MUTATE per-session state (the resource subscription * set) instead of computing a pure function of their params. A repeated * `resources/subscribe` sends byte-identical params, so serving the cached `{}` * would skip the handler: after subscribe → unsubscribe → subscribe within the * TTL the client believes it re-subscribed, but the server never re-added the URI * and `notifyResourceUpdated` delivers nothing. Same class as the inputRequired * exclusion in `onRequest`. * * `completion/complete` is deliberately NOT here: it is read-only — a pure * function of `ref` + `argument` with no state mutation — so caching it is correct, * exactly like `tools/list` or `resources/read`. (Its auth-per-identity concern is * the same one every read method has and is handled by the default key's auth * partitioning — see _authPartition — not by excluding it here.) */ private static readonly _nonCacheableMethods; constructor(ttl?: number, _keyFn?: CacheKeyFn | undefined); /** * Auth partition for the default cache key. A cache entry written under one auth * identity must never be served under another, so the identity is folded into the * key. Anonymous requests (`mcpContext.auth` undefined — a stdio request without a * CLI env token, and every request to a server with no auth configured) share the * single `anon` partition, matching the pre-partition default. An authenticated request is * partitioned by the SHA-256 hash of its bearer token: the token is the identity * credential, so two callers can never collide, and its hash — never the raw token — * goes in the key. The bearer token is used rather than `clientId` because two tokens * may share a `clientId` yet differ in scope, which must NOT share a partition. A * 64-char hex hash can never equal the literal `anon`, so anonymous and authenticated * partitions are disjoint in both directions. */ private static _authPartition; onRequest(ctx: MiddlewareContext, next: Next): Promise; } /** Fixed-window counter rate limiter. Resets to full capacity after every windowMs interval. */ declare class RateLimitingMiddleware implements Middleware { private readonly limit; private readonly windowMs; private _tokens; private _lastRefill; constructor(limit: number, windowMs?: number); onRequest(ctx: MiddlewareContext, next: Next): Promise; } /** Rejects responses whose JSON serialisation exceeds maxBytes. */ declare class SizeLimitingMiddleware implements Middleware { private readonly maxBytes; constructor(maxBytes: number); onRequest(ctx: MiddlewareContext, next: Next): Promise; } /** * Normalises errors thrown by handlers to proper MCP shapes: * - tools/call plain errors → { isError: true, content: [...] } (per MCP spec) * - tools/call McpError → re-thrown as a protocol-level error * - all other methods → McpError(InternalError, message) * * Re-throwing McpError from onCallTool ensures that middleware-level errors * (e.g. from RateLimitingMiddleware or SizeLimitingMiddleware stacked before * this middleware) always propagate as protocol errors and are never silently * converted to isError:true tool responses. */ declare class ErrorNormalizationMiddleware implements Middleware { onCallTool(ctx: MiddlewareContext, next: Next): Promise; onRequest(ctx: MiddlewareContext, next: Next): Promise; } /** * Intercepts `notifications/cancelled` from the client and aborts the matching * in-flight handler via Promise.race + AbortController. * * KNOWN GAP (2026-07-28): this only covers legacy (2025-era) and stdio cancellation. * On a modern Streamable HTTP connection, the SDK signals cancellation by closing the * request's response stream rather than sending `notifications/cancelled` — the client * is correctly told the call was cancelled either way, but a handler registered here * keeps running server-side to completion on the modern path, since this middleware * never observes that stream closure. The SDK exposes it per-request as * `ctx.mcpReq.signal` (a `BaseContext` field, present on every era) — unifying this * middleware with that signal (so long-running handlers actually stop executing on * both eras) is tracked as follow-up work, not yet implemented here. */ declare class CancellationMiddleware implements Middleware { private readonly _inFlight; setup(server: Server): void; onRequest(ctx: MiddlewareContext, next: Next): Promise; } interface ToolView { readonly name: string; /** Human-readable display name shown in UIs. Takes precedence over `name` for display purposes. */ readonly title?: string; readonly description: string; readonly tags: readonly string[]; } interface ResourceView { readonly uri: string; readonly name: string; readonly tags: readonly string[]; readonly mimeType?: string; readonly title?: string; } interface PromptView { readonly name: string; readonly description: string; readonly tags: readonly string[]; } interface SynthesizedTool { readonly name: string; /** Human-readable display name shown in UIs. Takes precedence over `name` for display purposes. */ readonly title?: string; readonly description: string; readonly inputSchema?: Record; readonly auth?: AuthCheck; readonly timeout?: number; readonly handler: (args: any) => unknown; } interface Transform { /** * Transform a tool view before it appears in list responses. * Return a modified view to rename/redescribe; return null to hide the tool * from list responses (it remains callable by its original name). */ transformTool?(view: ToolView): ToolView | null; /** Transform a static resource view. */ transformResource?(view: ResourceView): ResourceView | null; /** Transform a URI-template resource view. */ transformResourceTemplate?(view: ResourceView): ResourceView | null; /** Transform a prompt view. */ transformPrompt?(view: PromptView): PromptView | null; /** * Synthesize additional tools derived from the current resource and prompt lists. * Called at request time so the snapshot is always fresh. */ synthesizeTools?(resources: ResourceView[], prompts: PromptView[]): SynthesizedTool[]; } /** Rename a single tool. The original name still resolves at call time. */ declare function renameTool(originalName: string, newName: string): Transform; /** Rewrite the description of a single tool. */ declare function redescribeTool(toolName: string, description: string): Transform; /** * Hide components whose predicate returns false. * Hidden items are removed from list responses but remain callable by original name. */ declare class FilterTransform implements Transform { private readonly predicates; constructor(predicates: { tools?: (v: ToolView) => boolean; resources?: (v: ResourceView) => boolean; /** When omitted, falls back to the `resources` predicate. */ resourceTemplates?: (v: ResourceView) => boolean; prompts?: (v: PromptView) => boolean; }); transformTool(v: ToolView): ToolView | null; transformResource(v: ResourceView): ResourceView | null; transformResourceTemplate(v: ResourceView): ResourceView | null; transformPrompt(v: PromptView): PromptView | null; } /** Prefix all tool, prompt, and resource names with a string. URIs are left unchanged. */ declare class NamespaceTransform implements Transform { private readonly prefix; constructor(prefix: string); transformTool(v: ToolView): ToolView; transformResource(v: ResourceView): ResourceView; transformResourceTemplate(v: ResourceView): ResourceView; transformPrompt(v: PromptView): PromptView; } /** Expose registered resources as a `list_resources` tool. */ declare class ResourcesAsTools implements Transform { synthesizeTools(resources: ResourceView[]): SynthesizedTool[]; } /** Expose registered prompts as a `list_prompts` tool. */ declare class PromptsAsTools implements Transform { synthesizeTools(_resources: ResourceView[], prompts: PromptView[]): SynthesizedTool[]; } /** * Expose only components whose tags include the specified version string. * Components with no tags are always excluded. */ declare class VersionFilter implements Transform { private readonly version; constructor(version: string); private _matches; transformTool(v: ToolView): ToolView | null; transformResource(v: ResourceView): ResourceView | null; transformResourceTemplate(v: ResourceView): ResourceView | null; transformPrompt(v: PromptView): PromptView | null; } type Visibility = 'model' | 'app'; interface CspPolicy { connectDomains?: string[]; /** Covers img-src, script-src, style-src, font-src, media-src. */ resourceDomains?: string[]; frameDomains?: string[]; baseUriDomains?: string[]; } interface UiToolMeta { /** Explicit resource URI. Auto-derived from tool name when omitted. */ resourceUri?: string; /** * Who can see and call this tool. Defaults to `['model', 'app']` per SEP-1865 * (visible to the model, and callable by the app served from this same * connection) when omitted. */ visibility?: Visibility[]; } interface BrowserPermissions { camera?: Record; microphone?: Record; geolocation?: Record; clipboardWrite?: Record; } interface ResourceUiMeta { csp?: CspPolicy; permissions?: BrowserPermissions; domain?: string; prefersBorder?: boolean; } interface ResourceAnnotations { /** Intended audience(s) — 'user', 'assistant', or both. */ audience?: Array<'user' | 'assistant'>; /** Importance hint from 0 (least) to 1 (most). */ priority?: number; /** ISO 8601 timestamp of last modification. */ lastModified?: string; } interface ResourceConfig { /** Static URI (e.g. `file://readme`) or RFC 6570 template (e.g. `user://{id}`). */ uri: string; /** Programmatic identifier. Defaults to the uri. */ name?: string; /** Human-readable display name shown in UIs. Defaults to `name`. */ title?: string; description?: string; /** MIME type of the resource content. Defaults to 'text/plain' for strings, 'application/octet-stream' for binary. */ mimeType?: string; /** * Size of the resource content in bytes, if known. * Only meaningful for static resources; ignored for URI templates. */ size?: number; /** Behavioral hints for clients. */ annotations?: ResourceAnnotations; /** Execution timeout in milliseconds. No timeout by default. */ timeout?: number; /** When true the resource is hidden from list responses and cannot be read. */ disabled?: boolean; /** Arbitrary tags for server-side filtering. */ tags?: string[]; auth?: AuthCheck; /** Apps extension metadata. Included as `_meta.ui` on resources/list entries and on every resources/read content item for UI-capable clients. */ ui?: ResourceUiMeta; /** * Autocompletion callbacks for this resource template's RFC 6570 variables, * keyed by variable name. Only meaningful for URI templates. When set, a * `completion/complete` request for * `{ ref: { type: 'ref/resource', uri: }, argument: { name, value } }` * routes to `complete[name]`. */ complete?: Record; } /** * Escape hatch for full control over resource response content. * Return this from a resource handler to specify content directly. */ declare class ResourceResult { readonly contents: Array<{ uri: string; mimeType?: string; text?: string; blob?: string; _meta?: Record; }>; constructor(contents: Array<{ uri: string; mimeType?: string; text?: string; blob?: string; _meta?: Record; }>); } /** * Configurable CORS for the HTTP listener `run()` starts (both the plain and * the OAuth serve paths). Resolution and header computation are pure * functions: `resolveCors` runs once, in the FastMCP constructor, and fails * loudly on malformed config (the `resolveHealth` precedent); the two header * builders run per request. * * `fetch()` is deliberately untouched: the embedding framework owns CORS at * its HTTP boundary, exactly as it owns Host/Origin validation. */ /** `FastMCPOptions.http.cors` object form. `true` and omitted mean the * permissive defaults; `false` disables CORS handling entirely (no global * preflight, no headers). */ interface CorsOptions { /** * Origins allowed to call the MCP endpoint from a browser, compared * against the request's `Origin` header. `'*'` (the default) allows every * origin. A string or array allows exactly those `scheme://host[:port]` * origins. A function receives the `Origin` value and returns whether it * is allowed. A function that throws denies the origin. */ origin?: string | string[] | ((origin: string) => boolean); /** `Access-Control-Allow-Methods` value; replaces the default * `GET, POST, DELETE, OPTIONS` list verbatim. */ methods?: string[]; /** Extra request headers for `Access-Control-Allow-Headers`, added to the * defaults. The MCP protocol headers are never removed: silently dropping * one would break browser clients in ways that only surface in * production. */ allowedHeaders?: string[]; /** Extra response headers for `Access-Control-Expose-Headers`, added to * the default `Mcp-Session-Id` (legacy sessionful browser clients must * read it from the initialize response). */ exposedHeaders?: string[]; /** Send `Access-Control-Allow-Credentials: true`. Requires an explicit * non-`'*'` `origin`: browsers reject `*` on credentialed requests, so * that combination is a construction-time error. */ credentials?: boolean; /** `Access-Control-Max-Age` for preflight caching, in seconds. */ maxAge?: number; } type CacheableResultMethod = 'tools/list' | 'prompts/list' | 'resources/list' | 'resources/templates/list' | 'resources/read' | 'server/discover'; interface OAuthConfig { /** OAuth server provider implementing the authorization and token flow. */ provider: OAuthServerProvider; /** * Issuer URL for the OAuth server (used in metadata endpoints). * Defaults to the HTTP server's bound address when not specified. */ issuerUrl?: URL; /** Scopes supported by this server, advertised in OAuth metadata. */ scopes?: string[]; } interface FastMCPOptions { name: string; version?: string; /** * Bearer-token verifier, or a RequestVerifier for header-based * (trusted-proxy) deployments. See each type's docs. A RequestVerifier * applies to HTTP transports only; stdio's FASTMCP_CLI_AUTH_TOKEN needs a * TokenVerifier. Wrap either in `remoteAuth(...)` to also serve RFC 9728 * protected resource metadata over HTTP. When both `oauth` and `auth` are * set, `oauth` serves the endpoint and `auth` is ignored. */ auth?: TokenVerifier | RequestVerifier; /** Full OAuth 2.1 server with Dynamic Client Registration support. */ oauth?: OAuthConfig; /** * HTTP request context tuning for `ctx.http`. `redactHeaders` adds names to * the sensitive set withheld from `ctx.http.headers` (defaults: * authorization, cookie, proxy-authorization, mcp-session-id); use it for * deployment-specific credentials such as a proxy shared-secret header. * `exposeHeaders` removes names from the set; it is the explicit, greppable * opt-out. Withheld names are listed in `ctx.http.redactedHeaderNames`. * Redaction applies to `ctx.http` only; a RequestVerifier always sees the * full wire headers. * * `cors` configures the CORS posture of the HTTP listener `run()` starts * (both serve paths): omitted or `true` serves the permissive defaults * (`Access-Control-Allow-Origin: *`), `false` disables CORS handling * entirely, and an object narrows it — see `CorsOptions`. Malformed * values throw here, at construction, for every transport. `fetch()` is * unaffected: the embedding framework owns CORS at its HTTP boundary. */ http?: { redactHeaders?: string[]; exposeHeaders?: string[]; cors?: boolean | CorsOptions; }; /** * Sink for the framework's own diagnostic logs (lifecycle, warnings, * errors). `console` and Winston loggers satisfy the shape directly; see * the logging docs for a Pino adapter. Default: a built-in stderr logger * (styled on a TTY, plain single-line format otherwise). Client-facing MCP * logging (`ctx.log`) is a separate channel and is not affected. Do not use * `logger: console` with the stdio transport: `console.info` and * `console.debug` write to stdout, which carries the JSON-RPC stream on * that transport. */ logger?: Logger; /** * Minimum level for framework logs, applied before any logger (injected or * default) is called. Precedence: this option, then the FASTMCP_LOG_LEVEL * environment variable, then 'info'. 'silent' disables framework logging. * Malformed values throw here, at construction, for every transport. */ logLevel?: FrameworkLogLevel; /** Maximum number of tools returned per listTools page. Default: 50. */ toolsPageSize?: number; /** Maximum number of resources (or templates) returned per page. Default: 50. */ resourcesPageSize?: number; /** Maximum number of prompts returned per prompts/list page. Default: 50. */ promptsPageSize?: number; /** Middleware applied to every request in registration order. */ middleware?: Middleware[]; /** Transforms applied to component list responses in registration order. */ transforms?: Transform[]; /** * Cache hints (`ttlMs` / `cacheScope`) for the 2026-07-28 protocol revision's * cacheable results (`tools/list`, `prompts/list`, `resources/list`, * `resources/templates/list`, `resources/read`, `server/discover`), keyed by * operation. Only affects modern (2026-07-28) responses — 2025-era responses * never carry these fields. Omitted operations (or omitting this option * entirely) keep the conservative defaults (`ttlMs: 0`, `cacheScope: 'private'`). * Applies uniformly per operation; per-resource cache hints are not currently * supported (that per-registration override is only available through the * SDK's high-level `McpServer.registerResource`, which FastMCP does not use). */ cacheHints?: Partial>; /** * HMAC-SHA256 integrity protection for multi-round-trip `requestState` * (protocol revision 2026-07-28) — see `ctx.requestState()` / `ctx.mintRequestState()`. * Backed by the SDK's `createRequestStateCodec`. When omitted, `requestState` passes * through unverified (the raw wire string) — the client can read and tamper with it, * so this MUST be configured for any flow whose `requestState` influences * authorization, resource access, or business logic. */ requestState?: { /** HMAC secret. A `string` is UTF-8-encoded; MUST be at least 32 bytes (256 bits). */ key: Uint8Array | string; /** How long a minted `requestState` stays valid, in seconds. Default: 600 (10 minutes). */ ttlSeconds?: number; /** Binds a minted `requestState` to, e.g., the authenticated principal and/or the * originating method — a value minted under one binding is rejected when echoed * under a different one. See `RequestStateCodecOptions.bind`. */ bind?: (ctx: ServerContext) => string; }; /** * Multi-round-trip (`inputRequired`) serving knobs (protocol revision 2026-07-28). * On 2026-era requests the client fulfils `input_required` returns directly; on * 2025-era connections the SDK's legacy shim fulfils them server-side (real * server→client requests + handler re-entry) — so handlers written with * `inputRequired(...)` serve both eras unchanged. */ inputRequired?: { /** Handler re-entries per originating request before the shim fails (legacy era * only). Default: 8. */ maxRounds?: number; /** Per-leg timeout (ms) for the legacy shim's embedded server→client requests. * Default: 600_000 (10 minutes) — human-paced, deliberately above the 60s protocol default. */ roundTimeoutMs?: number; /** `false` disables the legacy shim: an `inputRequired(...)` return on a 2025-era * request fails loudly instead of being bridged. Default: true. */ legacyShim?: boolean; }; /** * The change-event bus modern (2026-07-28) `subscriptions/listen` streams * subscribe to, and `tool()`/`resource()`/`prompt()` registration publishes * change events onto. Defaults to an in-process bus, which is correct for a * single server process. Supply your own `ServerEventBus` implementation over a * shared pub/sub backend (e.g. Redis) for a horizontally-scaled deployment, * where a `subscriptions/listen` stream and the request that changed the list it * cares about may land on different processes. */ eventBus?: ServerEventBus; /** * DNS-rebinding protection for the HTTP listener started by `run()`: validates * the `Host` and `Origin` request headers (port-agnostic, by hostname) and rejects * mismatches with `403`. Defends localhost servers against a malicious web page * whose DNS rebinds to `127.0.0.1` (MCP transport security best practice). * * This option does not apply to `fetch()`, which has no bind address from which * to infer a trusted host. A framework embedding `fetch()` owns Host/Origin * validation at its HTTP boundary. stdio is unaffected. * * Default posture (option omitted): protection auto-enables when, and only when, * `run()` binds the HTTP server to a loopback host (`127.0.0.1`, `::1`, * `localhost`) — the deployment the attack targets. A server bound to a routable * interface (e.g. `0.0.0.0` or a public host) is left open by default, because a * localhost-only allowlist would reject its legitimate traffic; such deployments * must opt in with an explicit `allowedHosts`/`allowedOrigins` for their domain. */ dnsRebinding?: { /** Force protection on (`true`) or off (`false`). Omit for the loopback-auto default. */ enabled?: boolean; /** * Allowed `Host` header hostnames (no port; IPv6 in brackets, e.g. `[::1]`). * Supplying this list also implies protection on. Default: `localhost`, * `127.0.0.1`, `[::1]`. */ allowedHosts?: string[]; /** * Allowed `Origin` header hostnames (a missing `Origin` always passes — non-browser * clients send none). Supplying this list also implies protection on. Default: * `localhost`, `127.0.0.1`, `[::1]`. */ allowedOrigins?: string[]; }; } interface RunOptions { transport?: 'stdio' | 'http'; port?: number; host?: string; path?: string; /** * Serve the legacy (2025-era) HTTP transport statelessly: a fresh server and * transport per request, no session registry, incoming `mcp-session-id` * ignored, and no session id issued. Use this behind a load balancer or on * serverless compute where consecutive requests reach different instances. * * Falls back to the `FASTMCP_STATELESS_HTTP` environment variable, then to * `false`. A valid value is ignored for the stdio transport, but a malformed * one still aborts stdio startup, deliberately. The modern (2026-07-28) era * is already stateless and is unaffected. */ stateless?: boolean; /** * Health endpoint on the HTTP listener `run()` starts — for Kubernetes * liveness/readiness probes and load-balancer checks. Off unless supplied: * `true` (or any object) enables it with defaults `path: '/healthz'`, * `status: 200`, `body: 'ok'` (`text/plain`); `enabled: false` (or `false`) * forces it off. Served before MCP auth, CORS, and the DNS-rebinding * guards, so probes need no credentials and may send a pod-IP Host header. * Sugar over `customRoute()` — registering your own route on the same path * is a startup error. Ignored on stdio (a malformed value still aborts * startup, like `stateless`) and never served through `fetch()`. */ health?: boolean | HealthOptions; /** Custom stdin stream for the stdio transport. Defaults to process.stdin. */ stdin?: Readable; /** Custom stdout stream for the stdio transport. Defaults to process.stdout. */ stdout?: Writable; } interface ServerAddress { host: string; port: number; path: string; } /** * Behavioral hints for a tool (MCP 2025-03-26). Advisory only — clients may use * them for UI/UX and safety decisions (e.g. auto-approving a read-only call); the * server does not enforce them. Per the MCP spec, annotations from an untrusted * server should not be relied upon. */ interface ToolAnnotations { /** Human-readable title for display. */ title?: string; /** The tool does not modify its environment. Default: false. */ readOnlyHint?: boolean; /** The tool may perform destructive updates. Only meaningful when readOnlyHint is false. Default: true. */ destructiveHint?: boolean; /** Repeated calls with the same arguments have no additional effect. Only meaningful when readOnlyHint is false. Default: false. */ idempotentHint?: boolean; /** The tool may interact with an open world of external entities. Default: true. */ openWorldHint?: boolean; } interface ToolConfig { name: string; /** Human-readable display name shown in UIs. Takes precedence over `name` for display purposes. */ title?: string; description: string; /** Behavioral hints for clients (MCP 2025-03-26). Forwarded verbatim in tools/list. */ annotations?: ToolAnnotations; /** Standard Schema validator for the tool's input arguments. Used for runtime validation. */ input?: StandardSchemaV1; /** * Explicit JSON Schema advertised to clients as `inputSchema`. Overrides auto-generation from * `input`. Use when you need JSON Schema features beyond what your validator auto-generates * (e.g. `examples`, `$comment`, per-property descriptions, or custom annotations). */ inputSchema?: Record; /** Standard Schema validator for the tool's return value. Validated before result conversion. */ output?: StandardSchemaV1; /** * Explicit JSON Schema advertised to clients as `outputSchema`. Overrides auto-generation from * `output`. Use when you need JSON Schema features beyond what your validator auto-generates. */ outputSchema?: Record; /** Execution timeout in milliseconds. No timeout by default. */ timeout?: number; /** When true the tool is hidden from listTools and cannot be invoked via tools/call. */ disabled?: boolean; /** Arbitrary tags for server-side filtering. */ tags?: string[]; auth?: AuthCheck; /** Apps extension — links this tool to a UI resource and controls visibility. */ ui?: UiToolMeta; } declare class FastMCP { readonly name: string; readonly version: string; private _auth; /** @internal Framework logger; used by same-package modules (proxy, openapi). Not public API. */ readonly _logger: ResolvedLogger; private _cors; private _oauth; private _sensitiveHeaders; private _toolsPageSize; private _resourcesPageSize; private _tools; private _staticResources; private _templateResources; private _prompts; private _customRoutes; private _protectedResourceRoutePath; private _promptsPageSize; private _middleware; private _transforms; private _cacheHints; private _requestStateCodec; private _inputRequiredOptions; private _eventBus; private _dnsRebindingOptions; private _hostGuard; private _originGuard; private _primaryState; private _httpServer; private _address; private _isRunning; private _sessions; private _stateless; private _primaryServer; private _stdioServer; private _stdioState; private _stdioModern; private _stdioHandle; private _modernHandler; private _statelessLegacyHandler; private _toolRegisteredCallbacks; private _resourceRegisteredCallbacks; private _promptRegisteredCallbacks; private _proxyCloseCallbacks; private _mountedChildren; constructor(options: FastMCPOptions); private _hasUiComponents; /** * Create a new Server instance with all request handlers wired up. * * `resources.subscribe` is advertised on both eras. On legacy it gates the * `resources/subscribe`/`unsubscribe` RPCs. On modern (2026-07-28) the same * capability gates the `subscriptions/listen` `resourceSubscriptions` * filter: the SDK's listen routers silently prune the filter from the * honored subset when the serving entry's capabilities omit `subscribe`, * so a modern server that supports per-resource updates MUST advertise it * (issue #88). The legacy RPCs are still physically absent from the modern * wire registry, so advertising the capability leaks no legacy-only * surface to a modern client. * * The `completions` capability follows the same shape: `completion/complete` * is in BOTH era wire registries (the legacy 2025-11-25 registry and the * modern 2026-07-28 `dispatchRequestSchemas`), and `completions` is a valid * key in both eras' ServerCapabilities schemas, so it is declared * unconditionally. The SDK also requires this capability to be present to * register the `completion/complete` handler * (`assertRequestHandlerCapability`). * * `stateless` withdraws the `resources.subscribe` capability. A stateless * server has no session for a subscription to live in and no channel to * deliver `notifications/resources/updated` on, so it must not claim the * capability. */ private _makeServer; private _resolveToken; private _setupHandlers; /** * Resolve a `completion/complete` request against a prompt argument's completer. * Mirrors prompts/get's transform-aware lookup, not-found contract (-32602), and * auth check; an argument with no completer yields an empty list (SDK parity). */ private _completePrompt; /** * Resolve a `completion/complete` request against a resource template's * per-variable completer. Mirrors resources/read's not-found contract (-32602) * and auth check; a variable with no completer yields an empty list. Following * the SDK's own high-level server, a `ref.uri` that names a registered STATIC * resource (not a template) is answered with an empty list rather than an error. */ private _completeResourceTemplate; private _notifyToolListChanged; private _notifyResourceListChanged; private _notifyPromptListChanged; /** * Signal that a resource changed and any subscriber should re-read it. This is * the SINGLE change signal for resource updates across both eras — the legacy * per-session push and the modern subscriptions/listen bus are driven from here: * * - Legacy connections (primary / stdio / legacy HTTP sessions) that called * `resources/subscribe` for `uri` are pushed `notifications/resources/updated` * directly on their live session (subscription set kept in per-session state). * - The modern handler's bus (W3) is published to as well; it does its own * per-stream filtering, delivering only to `subscriptions/listen` streams that * opted in to this URI. Optional chaining keeps it a no-op until the first * modern HTTP request has actually built the handler. * - A modern stdio connection is sent the notification unconditionally; the * SDK's stdio listen router intercepts it and fans out per honored * subscription (or drops it when no stream opted in to the URI). * * Unsubscribed sessions (and the modern streams that never opted in) receive * nothing, so calling this for a URI with no subscribers is safe and cheap. */ notifyResourceUpdated(uri: string): void; /** * Resolve a requested URI to a registered resource, mirroring the lookup order * `resources/read` uses: exact static match, then original template match, then * (only when transforms are registered) transformed-static and * transformed-template matches. Returns the resource plus any template params, or * undefined when nothing matches. Disabled static resources are still returned by * exact match — callers apply the `disabled` check themselves (as read does), so * a hidden-but-known URI is a not-found, not a silent miss. */ private _resolveResource; tool(config: Omit & { input: S; }, handler: (args: StandardSchemaV1.InferOutput) => unknown): void; tool(config: ToolConfig, handler: (args: Record) => unknown): void; prompt(config: PromptConfig, handler: (args?: Record) => unknown): void; resource(config: ResourceConfig, handler: (params?: Record) => unknown): void; /** * Register a custom HTTP route on the listener `run()` starts — e.g. a * Kubernetes liveness/readiness probe. The handler owns the whole exchange: * no MCP auth, no DNS-rebinding guards, and no CORS headers run in front of * it. Matching is exact-path (query string ignored); methods default to GET. * Routes never serve on stdio or through `fetch()` — a framework embedding * `fetch()` owns its own routing (same posture as `dnsRebinding`). */ customRoute(config: CustomRouteConfig, handler: CustomRouteHandler): void; _removeTool(name: string): boolean; _removeResource(uri: string): boolean; _removePrompt(name: string): boolean; /** Add a transform to the pipeline. Applied to list responses in registration order. */ transform(t: Transform): this; /** * Dispatch a tool call through this server's middleware chain using an inherited context. * Used by parent servers to honour child-level middleware when routing mounted tool calls. */ _dispatchTool(name: string, rawArgs: unknown, ctx: McpContext): Promise<_modelcontextprotocol_server.InputRequiredResult | { [x: string]: unknown; content: ({ type: "text"; text: string; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: { [x: string]: unknown; } | undefined; } | { type: "image"; data: string; mimeType: string; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: { [x: string]: unknown; } | undefined; } | { type: "audio"; data: string; mimeType: string; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: { [x: string]: unknown; } | undefined; } | { uri: string; name: string; type: "resource_link"; description?: string | undefined; mimeType?: string | undefined; size?: number | undefined; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: { [x: string]: unknown; } | undefined; icons?: { src: string; mimeType?: string | undefined; sizes?: string[] | undefined; theme?: "light" | "dark" | undefined; }[] | undefined; title?: string | undefined; } | { type: "resource"; resource: { uri: string; text: string; mimeType?: string | undefined; _meta?: { [x: string]: unknown; } | undefined; } | { uri: string; blob: string; mimeType?: string | undefined; _meta?: { [x: string]: unknown; } | undefined; }; annotations?: { audience?: ("user" | "assistant")[] | undefined; priority?: number | undefined; lastModified?: string | undefined; } | undefined; _meta?: { [x: string]: unknown; } | undefined; })[]; _meta?: { [x: string]: unknown; "io.modelcontextprotocol/serverInfo"?: { version: string; name: string; websiteUrl?: string | undefined; description?: string | undefined; icons?: { src: string; mimeType?: string | undefined; sizes?: string[] | undefined; theme?: "light" | "dark" | undefined; }[] | undefined; title?: string | undefined; } | undefined; } | undefined; structuredContent?: unknown; isError?: boolean | undefined; }>; /** * Run a resource read through this server's middleware chain using an inherited context. * Returns the raw handler result so the parent can apply convertResourceResult with the * actual requested URI (important for template resources). */ _dispatchResource(uri: string, params: Record | undefined, ctx: McpContext): Promise; /** * Dispatch a prompt render through this server's middleware chain using an inherited context. */ _dispatchPrompt(name: string, args: Record, ctx: McpContext): Promise<_modelcontextprotocol_server.InputRequiredResult | { description?: string; messages: PromptMessage[]; }>; private _mirrorTool; private _mirrorResource; private _mirrorPrompt; /** Mount a child server onto this server. All tools, resources, and prompts from the child become accessible via this server. Pass a prefix to namespace names and prevent collisions. */ mount(child: FastMCP, prefix?: string): this; /** Register a callback invoked when this server is closed — used by proxy connections. */ _addCloseCallback(cb: () => Promise): void; /** * Register a provider (FastMCPApp or FastMCP) on this server. * All tools, resources, and prompts from the provider are mounted without a prefix. * For FastMCPApp, pass provider.server; for FastMCP, pass directly. */ addProvider(provider: FastMCP | { server: FastMCP; }): this; private _applyTransformsToTools; private _applyTransformsToResources; private _applyTransformsToResourceTemplates; private _applyTransformsToPrompts; private _buildSynthesizedTools; private _getVisibleViews; /** * Add a middleware to the pipeline. * * Can be called at any point before the first request arrives. `setup()` is * called immediately on the primary server so that notification handlers and * other server-level side-effects are active before `connect()` / `run()` is * called. HTTP sessions created after `use()` will also have `setup()` called * via `_makeServer()`. */ use(mw: Middleware): this; getContext(): McpContext; /** The bound address after run() resolves for the http transport. Null for stdio or before run(). */ get address(): ServerAddress | null; /** * Whether `run()` or `connect()` has been called on this instance. Used by the * CLI's entrypoint loader to detect servers that already started themselves via * top-level code, so it doesn't attempt to start them a second time. */ get isRunning(): boolean; connect(transport: Transport): Promise; /** * Serve an MCP request through a web-standard, fetch-native HTTP entrypoint. * * This entrypoint is always stateless and does not require `run()`: legacy * (2025-era) requests use a fresh server instance per request, while modern * (2026-07-28) requests share the instance's modern handler and event bus. * Authentication is deliberately external — `options.authInfo` is trusted and * passed unchanged into the protocol handler, where it is exposed as `ctx.auth`. * The embedding framework also owns Host/Origin validation and should abort its * carrying requests during shutdown; stateless legacy response streams follow * that request lifecycle, while `close()` terminates modern exchanges and streams. */ fetch(request: Request, options?: McpHandlerRequestOptions): Promise; /** * Modern-era (2026-07-28) in-process fetch entrypoint — the `McpServerLike` * duck-type hook `fastmcp-ts/client`'s `Client` looks for when a caller pins * modern era for an in-process server (`versionNegotiation: { mode: { pin: * '2026-07-28' } } }`). Delegates directly to the same `createMcpHandler` * instance the real HTTP modern path uses (`_getModernHandler`), so this is * the identical dispatch a real network connection would get — no sockets, * same code. Modern-only (`legacy: 'reject'`): a client using `'auto'` or * `'legacy'` negotiation instead goes through `connect()` + `InMemoryTransport` * (2025-era only), unaffected by this method. */ _modernFetch(request: Request, options?: McpHandlerRequestOptions): Promise; run(options?: RunOptions): Promise; /** Lazily builds the modern (2026-07-28) HTTP handler. One per FastMCP instance; * builds a fresh Server (via _makeServer) per request, matching createMcpHandler's * per-request-factory model. Modern-only (legacy: 'reject') — legacy (2025-era) * traffic is routed separately: to the existing sessionful transport by * _dispatchHttp, or to the stateless fallback by fetch(). This preserves the * session state and server-initiated-request shim for run()'s default HTTP path. */ private _getModernHandler; /** Lazily builds the stateless legacy (2025-era) HTTP handler. One per FastMCP * instance, mirroring _getModernHandler's per-instance, per-request-factory model. * * The SDK serves each POST from a fresh instance of the factory over a transport * built with `sessionIdGenerator: undefined`, and answers GET and DELETE with 405 * because both are session operations that mean nothing per request. * * Used unconditionally by fetch(), and by run() only when `_stateless` is on. * The sessionful transport in _dispatchLegacyHttp is untouched and remains the * default for listener-based HTTP deployments. */ private _getStatelessLegacyHandler; /** * Dual-era HTTP dispatch shared by the OAuth and non-OAuth serve paths. Assumes CORS * and auth have already been handled by the caller (req.auth already set, if any — * both the legacy transport and the modern handler read it as pass-through authInfo). */ private _dispatchHttp; /** Existing sessionful Streamable HTTP handling for 2025-era clients — unchanged * behavior from before the dual-era split, just shared between the OAuth and * non-OAuth serve paths instead of duplicated. */ private _dispatchLegacyHttp; /** * Resolve the DNS-rebinding Host/Origin guards for this serve from * `FastMCPOptions.dnsRebinding` and the bind `host`. Sets `_hostGuard` / `_originGuard` * (null = protection off). See the `dnsRebinding` option doc for the default posture. */ private _resolveDnsRebindingGuards; private _runHttpOAuth; private _runHttpSimple; close(): Promise; private _unregisterProtectedResourceRoute; } declare class Image { readonly buffer: Buffer | Uint8Array; readonly mimeType: string; constructor(buffer: Buffer | Uint8Array, mimeType: string); } declare class File { readonly buffer: Buffer | Uint8Array; readonly name: string; readonly mimeType: string; constructor(buffer: Buffer | Uint8Array, name: string, mimeType: string); } declare class ToolResult { readonly result: CallToolResult; constructor(result: CallToolResult); } declare function multiAuth(...verifiers: TokenVerifier[]): TokenVerifier; /** Options for {@link remoteAuth}. */ interface RemoteAuthOptions { /** Verifier that checks each request's credentials, such as `jwtVerifier(...)`. */ verifier: V; /** Issuer URLs of the authorization servers that mint tokens for this server. */ authorizationServers: Array; /** Public URL clients use to reach this server, without the MCP path. */ baseUrl: string | URL; /** Scopes to advertise in the metadata document and in 401 challenges. */ scopesSupported?: string[]; /** Human-readable name of this server, shown by some clients. */ resourceName?: string; /** URL of documentation for this server. */ resourceDocumentation?: string | URL; } /** Validated protected-resource settings that `run()` serves as metadata. */ interface ProtectedResourceConfig { readonly baseUrl: URL; readonly authorizationServers: readonly string[]; readonly scopesSupported?: readonly string[]; readonly resourceName?: string; readonly resourceDocumentation?: string; } /** A verifier that also carries {@link ProtectedResourceConfig}. */ type RemoteAuthProvider = V & { readonly protectedResource: ProtectedResourceConfig; }; /** * Make this server an OAuth resource server for an external authorization * server. Pass the result to `FastMCPOptions.auth`. * * Use it when another service issues the tokens, such as Auth0, Keycloak or * Okta, and this server only verifies them. `verifier` checks each request, as * with `jwtVerifier` or `introspectionVerifier`. `remoteAuth` adds the * discovery information that lets MCP clients find the authorization server on * their own. * * The resource URL is `baseUrl` joined with the path given to `run()`. For a * `baseUrl` of `https://mcp.example.com` and the default path `/mcp`, the * resource is `https://mcp.example.com/mcp`. Set `baseUrl` to the public URL * that clients use, such as the address of your reverse proxy. A wrong value * makes the advertised resource differ from the URL clients call. * * Over HTTP the server then serves the RFC 9728 metadata document at * `/.well-known/oauth-protected-resource` followed by the MCP path. Each 401 * response also carries a `WWW-Authenticate: Bearer` challenge whose * `resource_metadata` parameter points to that document. * * If you set both this and `oauth`, `oauth` takes precedence. * * @example * ```ts * const mcp = new FastMCP({ * name: 'my-server', * auth: remoteAuth({ * verifier: jwtVerifier({ jwksUri: 'https://auth.example.com/.well-known/jwks.json' }), * authorizationServers: ['https://auth.example.com'], * baseUrl: 'https://mcp.example.com', * }), * }) * ``` */ declare function remoteAuth(options: RemoteAuthOptions): RemoteAuthProvider; declare function remoteAuth(options: RemoteAuthOptions): RemoteAuthProvider; interface JwtVerifierOptions { jwksUri: string; issuer?: string; audience?: string | string[]; /** Clock skew tolerance in seconds. Default: 0. */ leeway?: number; } declare function jwtVerifier(options: JwtVerifierOptions): TokenVerifier; interface IntrospectionVerifierOptions { endpoint: string; credentials: { clientId: string; clientSecret: string; }; /** Cache TTL in seconds. Omit or set to 0 to disable caching. */ cacheTtl?: number; } declare function introspectionVerifier(options: IntrospectionVerifierOptions): TokenVerifier; declare function staticTokenVerifier(map: Record>>): TokenVerifier; declare function debugTokenVerifier(): TokenVerifier; interface OAuthProviderOptions { /** * Called during the authorization step. Implementations must eventually redirect * to `params.redirectUri` with a `code` query parameter (and `state` if present). * * If omitted, all authorization requests are auto-approved immediately — suitable * for testing and development only. */ onAuthorize?: (client: OAuthClientInformationFull, params: AuthorizationParams, res: Response$1) => Promise; /** Scopes supported by this server, advertised in OAuth metadata. */ scopes?: string[]; /** Access token lifetime in seconds. Default: 3600. */ tokenTtl?: number; } /** * Creates an in-memory OAuth 2.1 server provider with Dynamic Client Registration support. * * Suitable for development, testing, and simple deployments where persistence is not required. * All state (clients, codes, tokens) is held in memory and lost on restart. */ declare function oauthProvider(options?: OAuthProviderOptions): OAuthServerProvider; interface OAuthProxyOptions { /** Pre-registered credentials this proxy uses when talking to the upstream server. */ upstreamCredentials: { clientId: string; clientSecret?: string; }; /** Upstream OAuth server endpoint URLs. */ endpoints: { authorizationUrl: string; tokenUrl: string; revocationUrl?: string; }; /** * Verifies an access token issued by the upstream and returns information about it. * Called for every MCP request to validate the bearer token. */ verifyAccessToken: (token: string) => Promise; } /** * Creates an OAuth provider that proxies to an existing upstream OAuth server using * pre-registered credentials. * * MCP clients interact with this proxy using Dynamic Client Registration. The proxy * presents a DCR-compliant interface while internally using its own fixed credentials * (`upstreamCredentials`) when communicating with the upstream authorization server. */ declare function oauthProxy(options: OAuthProxyOptions): OAuthServerProvider; type StdioTransport = { type: 'stdio'; command: string; args?: string[]; env?: Record; cwd?: string; /** How long (ms) before the proxy re-fetches component lists. Default 30 000. Set 0 for notifications-only. */ cacheTtl?: number; /** Framework logger for the proxy's own FastMCP instance. Defaults to the stderr sink. */ logger?: Logger; /** Framework log level for the proxy's own FastMCP instance. */ logLevel?: FrameworkLogLevel; }; type HttpTransport = { type: 'http'; url: string; requestInit?: RequestInit; /** How long (ms) before the proxy re-fetches component lists. Default 30 000. Set 0 for notifications-only. */ cacheTtl?: number; /** Framework logger for the proxy's own FastMCP instance. Defaults to the stderr sink. */ logger?: Logger; /** Framework log level for the proxy's own FastMCP instance. */ logLevel?: FrameworkLogLevel; }; type ProxyTransport = StdioTransport | HttpTransport; /** * Create a FastMCP instance that proxies all requests to a remote MCP server. * The returned instance can be mounted onto a parent server via `parent.mount(proxy)`. * * Component lists (tools, resources, prompts) are kept in sync via: * - Change notifications from the backend (immediate resync) * - TTL-based lazy resync on each list request (configurable via `cacheTtl`, default 30 s) */ declare function createProxy(config: ProxyTransport, name?: string): Promise; /** * Shared types for the OpenAPI integration. * * The intermediate representation (HTTPRoute and friends) is a direct port of * Python FastMCP's `fastmcp.utilities.openapi.models` so the two * implementations generate identical MCP components from the same spec. The * parity contract is pinned by the snapshots in `tests/fixtures/openapi/`. */ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD' | 'TRACE'; type ParameterLocation = 'path' | 'query' | 'header' | 'cookie'; type JsonSchema = Record; /** A single parameter of an HTTP operation. */ interface ParameterInfo { name: string; location: ParameterLocation; required: boolean; schema: JsonSchema; description?: string; /** OpenAPI explode property for array/object serialization. */ explode?: boolean; /** OpenAPI style property (form, spaceDelimited, pipeDelimited, deepObject, ...). */ style?: string; } /** The request body of an HTTP operation, keyed by media type. */ interface RequestBodyInfo { required: boolean; contentSchema: Record; description?: string; } /** The primary success response of an HTTP operation, keyed by media type. */ interface ResponseInfo { description?: string; contentSchema: Record; } /** Where a flattened tool argument goes when the HTTP request is built. */ interface ParameterMapping { location: ParameterLocation | 'body'; openapiName: string; } /** Intermediate representation of a single OpenAPI operation. */ interface HTTPRoute { path: string; method: HttpMethod; operationId?: string; summary?: string; description?: string; tags: string[]; parameters: ParameterInfo[]; requestBody?: RequestBodyInfo; /** Only the primary success response, keyed by its status code string. */ responses: Record; /** Schema definitions needed by the input (parameters + request body). */ requestSchemas: Record; /** Schema definitions needed by the output (responses). */ responseSchemas: Record; /** `x-` extension fields found on the operation. */ extensions: Record; openapiVersion?: string; /** Pre-calculated flat input schema advertised on the MCP tool. */ flatParamSchema: JsonSchema; /** Maps flat argument names back to their OpenAPI locations. */ parameterMap: Record; } /** Type of FastMCP component to create from a route. */ type MCPType = 'tool' | 'resource' | 'resourceTemplate' | 'exclude'; /** Mapping rule from HTTP routes to FastMCP component types. */ interface RouteMap { /** HTTP methods to match. `'*'` (default) matches every method. */ methods?: HttpMethod[] | '*'; /** Pattern searched (unanchored) against the route path. Default matches all. */ pattern?: RegExp | string; /** Tags that must ALL be present on the route for the map to match. */ tags?: string[]; /** The component type to create for matching routes. */ mcpType: MCPType; /** Extra tags applied to components created by this map. */ mcpTags?: string[]; } /** * Advanced route-type hook, run after the route maps on every non-excluded * route. Return a new MCPType to override, or null/undefined to keep the * mapped type. Exceptions are swallowed with a warning. */ type RouteMapFn = (route: HTTPRoute, mcpType: MCPType) => MCPType | null | undefined; /** Mutable pre-registration view of a generated tool. */ interface OpenAPIToolComponent { kind: 'tool'; name: string; description: string; inputSchema: JsonSchema; outputSchema?: JsonSchema; tags: string[]; } /** Mutable pre-registration view of a generated resource. */ interface OpenAPIResourceComponent { kind: 'resource'; uri: string; name: string; description: string; mimeType: string; tags: string[]; } /** Mutable pre-registration view of a generated resource template. */ interface OpenAPIResourceTemplateComponent { kind: 'resourceTemplate'; uriTemplate: string; name: string; description: string; mimeType: string; parameters: JsonSchema; tags: string[]; } type OpenAPIComponent = OpenAPIToolComponent | OpenAPIResourceComponent | OpenAPIResourceTemplateComponent; /** * Component customization hook, called with each generated component before * registration. Mutate the component in place (rename, edit description, * adjust tags or schemas). Exceptions are swallowed with a warning. */ type ComponentFn = (route: HTTPRoute, component: OpenAPIComponent) => void; /** * HTTP execution for generated components. * * Port of Python FastMCP's `OpenAPITool.run` / `OpenAPIResource.read` * (`fastmcp.server.providers.openapi.components`): bare fetch with a timeout, * Python-compatible error messages (they surface as tool errors, so clients * may match on them), JSON responses as structuredContent with the * `x-fastmcp-wrap-result` unwrap applied, non-JSON as text. */ /** HTTP client configuration for a generated OpenAPI server. */ interface OpenAPIClientOptions { /** * Base URL for requests. Defaults to the spec's first `servers` entry * (with server variables filled from their defaults). Required when the * spec has no absolute server URL. */ baseUrl?: string; /** Default headers sent on every request. Request-specific headers win. */ headers?: Record; /** Async header provider, resolved per request (e.g. a token refresher). */ auth?: { getHeaders(): Promise>; }; /** Custom fetch implementation. Defaults to the global fetch. */ fetch?: typeof globalThis.fetch; /** Per-request timeout in milliseconds. Default 30 000. */ timeoutMs?: number; } /** * createOpenAPIServer: build a FastMCP server from an OpenAPI 3.x spec. * * TypeScript port of Python FastMCP's `FastMCP.from_openapi` / * `OpenAPIProvider`. Components are generated eagerly: parse the spec into * routes, map each route to a component type, name it, derive its schemas, * and register it on a plain FastMCP with a forwarding handler that calls the * described HTTP API. Generated names and schemas match the Python * implementation byte for byte; the snapshots under `tests/fixtures/openapi/` * pin that contract. */ interface OpenAPIServerOptions { /** The OpenAPI 3.0/3.1 spec: a parsed object, or YAML/JSON text. */ spec: Record | string; /** Server name. Default 'OpenAPI Server'. */ name?: string; /** Server version. Defaults to FastMCP's own default. */ version?: string; /** HTTP client configuration (base URL, headers, auth, fetch, timeout). */ client?: OpenAPIClientOptions; /** Route maps checked in order before the default (everything → tool). */ routeMaps?: RouteMap[]; /** Route-type hook, run after the route maps on every route. */ routeMapFn?: RouteMapFn; /** Component customization hook, called before each registration. */ componentFn?: ComponentFn; /** Overrides mapping operationId → component name. */ names?: Record; /** Tags added to every generated component. */ tags?: string[]; /** * When true (default), tools advertise the output schema extracted from * the spec. When false, a permissive schema is advertised instead (the * wrap-result marker is preserved). */ validateOutput?: boolean; /** Remaining FastMCP options (auth, middleware, page sizes, ...). */ serverOptions?: Omit; } /** * Create a FastMCP server from an OpenAPI 3.0/3.1 specification. Every * operation becomes an MCP component (tool by default; see `routeMaps`) * whose handler calls the described HTTP endpoint. */ declare function createOpenAPIServer(options: OpenAPIServerOptions): FastMCP; interface Component { type: string; props?: Record; children?: Component[]; } interface IfNode extends Component { type: 'if'; branches: Array<{ condition: string; node: Component; }>; fallback?: Component; elif(condition: string, node: Component): IfNode; else(node: Component): Component; } interface CatalogEntry { type: string; description: string; } declare function Column(props?: Record, children?: Component[]): Component; declare function Row(props?: Record, children?: Component[]): Component; declare function Grid(props?: Record, children?: Component[]): Component; declare function Text(content: string | Component, extraProps?: Record): Component; declare function Badge(text: string, extraProps?: Record): Component; declare function Table(props: { columns: string[]; rows: string[][]; [key: string]: unknown; }): Component; declare function Bar(props: Record): Component; declare function Line(props: Record): Component; declare function Area(props: Record): Component; declare function Pie(props: Record): Component; declare function Input(props: Record): Component; declare function Select(props: Record): Component; declare function Button(props: Record): Component; declare function If(condition: string, then: Component, fallback?: Component): IfNode; declare function ForEach(items: string, template: Component): Component; declare function Rx(expression: string): Component; interface EntrypointConfig { name: string; description: string; title?: string; } interface BackendToolConfig { name: string; description: string; title?: string; /** Defaults to ['app']. Pass ['model', 'app'] to also expose to the LLM. */ visibility?: Visibility[]; } interface FastMCPAppOptions { name: string; version?: string; } declare class FastMCPApp { readonly server: FastMCP; constructor(options: FastMCPAppOptions); /** * Register an entry-point tool. * Entry-points are visible to the LLM (visibility: ['model', 'app']) and * automatically linked to a generated ui:// resource URI. */ entrypoint(config: EntrypointConfig, handler: (args?: any) => Component): void; /** * Register a backend tool. * Backend tools are hidden from listTools by default (visibility: ['app']). */ backendTool(config: BackendToolConfig, handler: (args: any) => unknown): void; /** * Returns a reference to a tool that resolves to the correct external name * (including any mount prefix) when evaluated inside a request handler. * Call inside a handler function — not at definition time. */ toolRef(name: string): string; } /** * Resolve a logical tool name to its current external name inside a request * handler, accounting for any mount prefix applied by a parent server. * * Use this in providers that are built on bare FastMCP (not FastMCPApp) to * produce mount-prefix–aware action strings for Button components. */ declare function actionRef(name: string): string; declare class GenerativeUI { readonly server: FastMCP; constructor(); } declare class Approval { readonly server: FastMCP; constructor(); } declare class Choice { readonly server: FastMCP; constructor(); } interface FileHandle { handle: string; name: string; mimeType: string; data: Buffer; } interface FileStorageAdapter { save(handle: string, file: FileHandle): void; load(handle: string): FileHandle | undefined; delete(handle: string): void; } interface FileUploadOptions { storage?: FileStorageAdapter; /** * How long (ms) an uploaded file is retained by the default in-memory storage * adapter before automatic expiry. Only applies when no custom `storage` is * supplied. Default: 30 minutes. */ ttlMs?: number; } declare class FileUpload { readonly server: FastMCP; private readonly _storage; constructor(options?: FileUploadOptions); } interface FormInputOptions { name: string; description: string; schema: StandardSchemaV1; } declare class FormInput { readonly server: FastMCP; constructor(options: FormInputOptions); } export { type AccessToken, Approval, Area, type AuthCheck, AuthorizationError, type BackendToolConfig, Badge, Bar, type BrowserPermissions, Button, type CacheKeyFn, CachingMiddleware, CancellationMiddleware, type CatalogEntry, Choice, Column, type CompleteCallback, type CompletionContext, type CompletionResult, type Component, type ComponentFn, type CorsOptions, type CspPolicy, type CustomRouteConfig, type CustomRouteHandler, type ElicitationResult, type ElicitationSchema, type EntrypointConfig, ErrorNormalizationMiddleware, FastMCP, FastMCPApp, type FastMCPAppOptions, type FastMCPOptions, File, type FileHandle, type FileStorageAdapter, FileUpload, type FileUploadOptions, FilterTransform, ForEach, FormInput, type FormInputOptions, type FrameworkLogLevel, GenerativeUI, Grid, type HTTPRoute, type HealthOptions, type HttpMethod, type HttpRequestContext, If, type IfNode, Image, Input, Line, type LogLevel, type Logger, LoggingMiddleware, type MCPType, type McpContext, type Middleware, type MiddlewareContext, NamespaceTransform, type Next, type OAuthConfig, type OAuthProviderOptions, type OAuthProxyOptions, type OpenAPIClientOptions, type OpenAPIComponent, type OpenAPIResourceComponent, type OpenAPIResourceTemplateComponent, type OpenAPIServerOptions, type OpenAPIToolComponent, type ParameterInfo, Pie, type PromptArgument, type PromptConfig, type PromptContent, type PromptMessage, PromptResult, type PromptView, PromptsAsTools, type ProtectedResourceConfig, type ProxyTransport, RateLimitingMiddleware, type RemoteAuthOptions, type RemoteAuthProvider, type RequestBodyInfo, type RequestVerifier, type ResourceAnnotations, type ResourceConfig, ResourceResult, type ResourceUiMeta, type ResourceView, ResourcesAsTools, type ResponseInfo, type Root, type RouteMap, type RouteMapFn, Row, type RunOptions, Rx, type SamplingMessage, type SamplingParams, type SamplingResult, Select, type ServerAddress, SizeLimitingMiddleware, type SynthesizedTool, Table, Text, type TokenVerifier, type ToolAnnotations, type ToolConfig, ToolResult, type ToolView, type Transform, type UiToolMeta, VersionFilter, type Visibility, actionRef, createOpenAPIServer, createProxy, debugTokenVerifier, forwardableHeaders, introspectionVerifier, jwtVerifier, multiAuth, oauthProvider, oauthProxy, redescribeTool, remoteAuth, renameTool, requireScopes, staticTokenVerifier };