import { type ServerEventBus } from "@modelcontextprotocol/server"; import { Hono, type Env, type MiddlewareHandler } from "hono"; import { type ServerBranding } from "./branding.js"; import { type ServerConfig } from "./config.js"; import type { LandingPageRegistration } from "./landing-handler.js"; import { type DefinitionSecuritySchemes, type RequestContext, type ToolOAuthMode } from "./context.js"; import { type McpEventListenerFnFor, type McpEventPattern, type McpMiddlewareFnFor, type McpMiddlewarePattern } from "./middleware/mcp-middleware.js"; import { type SettingsFields, type SettingsRegistration } from "./settings.js"; import { type MentionsRegistration, type MentionSearchParams, type MentionSearchResult } from "./mentions.js"; import type { FromOpenAPIOptions } from "./openapi/types.js"; import type { InferPromptInput, PromptCallback, PromptDefinition } from "./prompts.js"; import type { InferTemplateParams, ResourceCallback, ResourceDefinition, ResourceTemplateCallback, ResourceTemplateDefinition } from "./resources.js"; import type { ProxyConnection, ProxyServerConfig } from "./mcp-proxy.js"; import type { InferToolInput, InferToolName, InferToolOutput, ToolCallback, ToolDefinition, ToolRef } from "./tools.js"; import { registerSkills, type SkillsOptions, type SkillsSnapshot } from "./skills/types.js"; import type { ViewRegistrationOptions } from "./views/types.js"; import { registerViews, type ViewsManifest } from "./views/index.js"; type HasOAuth = [TUser] extends [never] ? false : true; /** Options accepted by {@link MCPServer.listen}. */ export interface ListenOptions { /** Explicit bind host; takes precedence over `HOST` and configured `host`. */ host?: string; } /** * MCP server with declarative tool/resource/prompt registration, served * statelessly over a composed fetch handler. * * Registrations are stored in a registry; a fresh SDK `McpServer` is built * from it for every HTTP request (the stateless 2026-07-28 model), so * definition-time work must stay cheap — put pools and caches at module * scope, not inside callbacks' setup. * * @example * ```ts * const server = new MCPServer({ name: "my-server", version: "1.0.0" }); * server.tool( * { name: "add", inputSchema: z.object({ a: z.number(), b: z.number() }) }, * async ({ a, b }) => ({ * content: [{ type: "text", text: String(a + b) }], * }) * ); * await server.listen(3000); * ``` */ export declare class MCPServer { #private; /** Hono application that owns HTTP middleware and routes. */ readonly app: Hono; /** Register a typed `GET` route on {@link MCPServer.app}. */ readonly get: Hono["get"]; /** Register a typed `POST` route on {@link MCPServer.app}. */ readonly post: Hono["post"]; /** Register a typed `PUT` route on {@link MCPServer.app}. */ readonly put: Hono["put"]; /** Register a typed `PATCH` route on {@link MCPServer.app}. */ readonly patch: Hono["patch"]; /** Register a typed `DELETE` route on {@link MCPServer.app}. */ readonly delete: Hono["delete"]; /** Register a typed route for every HTTP method on {@link MCPServer.app}. */ readonly all: Hono["all"]; /** * Canonical Web-standard handler for edge runtimes and framework mounting. * * @example * ```ts * export default server; * // or: export const POST = server.fetch; * ``` */ readonly fetch: (...args: Parameters["fetch"]>) => Promise; /** * Create an MCP server from a parsed, bundled OpenAPI document. * * Each included OpenAPI operation becomes a tool that validates its input, * calls the matching upstream HTTP endpoint, and returns the response using * the SDK's raw tool-result shape. External `$ref` values are not fetched; * bundle the document before passing it in. * * @param options - OpenAPI document, operation filters, upstream URL, and * request authentication options. * @returns An unauthenticated MCP server populated with generated tools. * * @example * ```ts * const spec = await fetch("https://api.example.com/openapi.json") * .then((response) => response.json()); * const server = MCPServer.fromOpenAPI({ spec }); * await server.listen(3000); * ``` */ static fromOpenAPI(options: FromOpenAPIOptions): MCPServer; /** * Create a server. `config.name` and `config.version` identify the server * to clients during initialization. `config.basePath` (default `"/mcp"`) * is both the MCP route and the path of the OAuth protected-resource * identity, so any explicit OAuth resource URL must use that exact path. * Nothing binds or listens until {@link MCPServer.listen} or * the first request reaches {@link MCPServer.fetch}. */ constructor(config: ServerConfig); /** * The URL path prefix the MCP endpoint is mounted at. * * Reflects `config.basePath` (default `"/mcp"`). Exposed so tooling that * imports the entry module — `mcp-use dev`'s startup log, for example — * can build endpoint and development-tool URLs without assuming the default. */ get basePath(): string; /** Configured bind host, before CLI and environment overrides. */ get host(): string | undefined; /** Configured bind port, before CLI and environment overrides. */ get port(): number | undefined; /** * Immutable normalized branding shared by MCP identity and browser pages. * * `favicon` is the final source after explicit-favicon and icon-selection * precedence. Landing-page integrations can use this accessor and link to * the server's root-level `/favicon.ico` route without reading private * configuration or depending on the landing/view layers. * * @example * ```ts * if (server.branding.favicon) { * console.log("Browser favicon: /favicon.ico"); * } * ``` */ get branding(): ServerBranding; /** @deprecated Use {@link MCPServer.fetch} directly. */ getHandler(): typeof this.fetch; /** * Register a tool. Input is validated against `inputSchema` before the callback * runs; results carrying `structuredContent` are type-checked against * `outputSchema` at the callback's return position. * * Assign static registrations to exported constants so `mcp-env.d.ts` can * expose their {@link ToolRef} types to views: * `export const search = server.tool(...)`. * * `ctx.auth` is required in the callback unless * `definition.securitySchemes` includes `noauth`. * * @returns A {@link ToolRef} carrying the tool name and phantom types for * inference-based view typing. * @throws TypeError When `definition.securitySchemes` is invalid for this * server. */ tool(definition: T, callback: ToolCallback, InferToolOutput, TUser, ToolOAuthMode>, TEnv>): ToolRef, InferToolInput, InferToolOutput>; /** * Register one native plugin settings read/update pair before starting the server. * * Callbacks receive the same request context and OAuth guarantees as ordinary * authenticated tools. They own authorization, defaults, persistence, atomic * partial updates, and cross-field validation. The framework validates field * values and replays both tools and the capability on every request-scoped server. * * @throws When already registered, started, field schemas are unsupported, * or either tool name collides with an existing registration. */ settings(options: SettingsRegistration, TEnv>): void; /** * Register a composer mention search tool before startup. * * Search receives the ordinary request context, authentication defaults, and * cancellation signal. Authorization, ranking, limits, and resource identity * remain application-owned. Hosts may ignore the marker; explicit tool calls * still work. App visibility is always included, without requiring a View. * * @param options - Tool descriptor and search callback returning resource links. * @returns A normal tool reference with typed query input and link output. * @throws When started, the name or callback is invalid, or the name collides. */ mentions(options: MentionsRegistration, TEnv>, Name>): ToolRef; /** * Prime the views registry from build/dev registry data. * * @param views - Registry map keyed by view directory name. * @param options - Priming options. When `dev` is true, resource CSP * emission appends the serving origin's websocket variant to * `connectDomains` so Vite HMR passes host-enforced CSP. Pass * `projectRoot` in dev so the `public/` route resolves against the user's * project directory rather than the CLI process cwd. Production builds pass * an immutable `buildId` to version view resource URIs across replicas; * development ignores it and retains unversioned URIs. * @throws If views are already primed, or after the server has started. * * @internal */ [registerViews](views: ViewsManifest, options?: ViewRegistrationOptions): void; /** * Prime the views registry — string-keyed alias for {@link registerViews} * used by the CLI when the symbol export cannot be shared across duplicate * module copies (dev module runner with an externalized package). * * @param views - Manifest map keyed by view directory name. * @param options - Priming options forwarded to {@link registerViews}. * @throws If views are already primed, or after the server has started. * * @internal */ __primeViews(views: ViewsManifest, options?: ViewRegistrationOptions): void; /** Supply a CLI-discovered custom landing component before the first request. @internal */ __primeLandingPage(registration: LandingPageRegistration): void; /** * Prime an immutable Skills over MCP snapshot before the server starts. * * @param snapshot - Validated snapshot, or `undefined` when convention * discovery found no skills directory. * @throws If the server already started. * * @internal */ [registerSkills](snapshot: SkillsSnapshot | undefined): void; /** String-keyed tooling alias for {@link registerSkills}. */ __primeSkills(snapshot: SkillsSnapshot | undefined): void; /** Return file-discovery configuration to Node build tooling. @internal */ __skillsConfig(): boolean | SkillsOptions | undefined; /** Register a static resource readable at `definition.uri`. */ resource(definition: ResourceDefinition, callback: ResourceCallback, TEnv>): this; /** * Register a parameterized resource. Reads matching `uriTemplate` invoke * the callback with the extracted variables. * * The `const` type parameter keeps `uriTemplate` a string literal during * inference (plain generic inference widens object-literal properties to * `string`), which is what lets `InferTemplateParams` type the callback's * `params` from the template's variables. */ resourceTemplate(definition: ResourceTemplateDefinition, callback: ResourceTemplateCallback, TUser, HasOAuth, TEnv>): this; /** * Register a prompt template. Schema fields wrapped with `completable()` * gain autocomplete via `completion/complete`. */ prompt(definition: T, callback: PromptCallback, TUser, HasOAuth, TEnv>): this; /** * Compose upstream MCP servers into this server. * * A name-keyed HTTP config creates upstream connections through the optional * `@mcp-use/client` v2 peer. Each key automatically namespaces its mounted * tools, resources, and prompts. You may instead pass an existing ready * {@link ProxyConnection}; its negotiated server name becomes the namespace * and the connection remains caller-owned. Anonymous connections cannot use * this overload because they do not provide a namespace. * * Connection, introspection, and collision failures are diagnosed and * skipped without discarding capabilities that can be mounted. * * @param servers - Namespace-keyed upstream HTTP connection settings. * @throws If `@mcp-use/client` is not installed or the server already started * or closed. * * @example * ```ts * await server.proxy({ * weather: { * url: "https://weather.example.com/mcp", * authToken: process.env.WEATHER_MCP_TOKEN, * }, * }); * ``` */ proxy(servers: Record): Promise; /** * Mount an existing ready `@mcp-use/client` v2 connection. * * @param connection - Ready connection to introspect and forward through. * The connection's negotiated server name automatically namespaces every * mounted capability. Anonymous connections are rejected because they do not * provide a namespace. Introspection and collision failures are diagnosed * and skipped without discarding capabilities that can be mounted. * * @throws If the server already started or closed. * * @example * ```ts * const connection = await client.connect("database"); * await server.proxy(connection); * ``` */ proxy(connection: ProxyConnection): Promise; /** * Register HTTP middleware or typed MCP operation middleware. * * MCP patterns always use an `mcp:` prefix (for example * `mcp:tools/call`, `mcp:*`). Every other overload is Hono middleware and * may target all routes or a path pattern. * * Exact methods may transform their typed result. The global `mcp:*` pattern * is pass-through middleware. Middleware runs in registration order; call * `next()` to continue the chain. * * @example * ```ts * server.use("/api/*", async (c, next) => { * c.set("requestId", crypto.randomUUID()); * await next(); * }); * * server.use("mcp:tools/call", async (ctx, next) => { * console.log(`Calling tool: ${ctx.params.name}`); * return next(); * }); * ``` */ use

(pattern: P, handler: McpMiddlewareFnFor): this; use(handler: MiddlewareHandler): this; use(path: `/${string}` | "*", ...handlers: MiddlewareHandler[]): this; /** * Register a read-only MCP observer. Unlike {@link MCPServer.use}, listeners * cannot block, override, or mutate params. Throwing is logged and does not * fail the request. * * Append `:complete` to run after the handler (for example * `mcp:tools/call:complete`). * * @example * ```ts * server.on("mcp:tools/call", (ctx) => { * metrics.increment("tools.call", { tool: ctx.params.name }); * }); * ``` */ on

(pattern: P, handler: McpEventListenerFnFor): this; /** * Attach the shared development event bus before the first request. * * @param bus - Bus retained across hot-reloaded server instances. * @internal */ __setEventBus(bus: ServerEventBus): void; /** Set a development-only label for request logs before the app is mounted. @internal */ __setRequestLogPrefix(prefix: string | undefined): void; /** Register an Inspector mounted by CLI tooling before the app is mounted. @internal */ __setInspectorPath(path: string | undefined): void; /** Mount and validate the Hono/MCP application without serving a request. @internal */ __mount(): void; /** * Publish a tools-list change to v2 clients with active subscriptions. * * @example * ```ts * await server.notifyToolsChanged(); * ``` */ notifyToolsChanged(): Promise; /** * Publish a prompts-list change to v2 clients with active subscriptions. * * @example * ```ts * await server.notifyPromptsChanged(); * ``` */ notifyPromptsChanged(): Promise; /** * Publish a resources-list change to v2 clients with active subscriptions. * * @example * ```ts * await server.notifyResourcesChanged(); * ``` */ notifyResourcesChanged(): Promise; /** * Publish a resource update to subscribed v2 clients. * * @param uri - Resource URI whose representation changed. * * @example * ```ts * await server.notifyResourceUpdated("config://settings"); * ``` */ notifyResourceUpdated(uri: string): Promise; /** * Serve over HTTP on Node. Pass port `0` for an ephemeral port. Port * precedence is the argument, `PORT`, `config.port`, then `3000`; host * precedence is `options.host`, `HOST`, `config.host`, then `127.0.0.1`. * * Localhost-class binds get * DNS-rebinding Host protection automatically. Origin validation is off * unless `allowedOrigins` is set. To serve publicly set `host: "0.0.0.0"`; * behind a platform edge that is all that's needed, and `allowedHosts` * restricts direct exposure (additive — localhost-class values stay allowed). * * With OAuth and no explicit resource or `MCP_URL`, a localhost listener * derives its protected-resource URL from the actual bound port. Mounting * therefore waits for the listener callback (especially for port `0`), and * requests accepted before then are queued. Public/wildcard listeners must * configure the resource before calling this method. * * @throws If called on a localhost-class bind after {@link MCPServer.fetch} * already mounted the app without Host validation. */ listen(port?: number | undefined, options?: ListenOptions): Promise<{ /** Actual bound port, including an ephemeral port chosen for `0`. */ port: number; /** HTTP URL of the bound MCP endpoint. */ url: string; }>; /** * Abort in-flight MCP exchanges and stop the HTTP listener. * * A closed server is done for good — the underlying MCP handler stays * closed, so `listen()`/`fetch()` cannot revive it. Create a new * instance to serve again. */ close(): Promise; } export {};