View the source code for this module on GitHub: https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/mcp-use/src/server/mcp-server.ts
listen(), or get a handler for serverless platforms (Cloudflare Workers, Vercel Edge, Deno).
basic/simple example):
new MCPServer(config) returns an McpServerInstance, a value that is simultaneously the MCPServer class, the Hono app, and an mcp-use helper surface. That means server.tool(...) (MCP) and server.get('/health', ...) (Hono) both work on the same object. The exact return type is McpServerInstance<true> when oauth is configured and McpServerInstance<false> otherwise.Constructor
Creates a new server instance. Initializes the native MCP server from the official SDK, creates the Hono application, sets up OAuth if configured, configures session management (stateful or stateless), and wraps the registration methods for multi-session support. Stateless mode is auto-detected (Deno defaults to stateless, Node.js to stateful) whenstateless is not set.
Parameters
The most commonServerConfigrequiredServer configuration object (see fields below).
ServerConfig fields:
SignaturestringrequiredUnique server name displayed to clients.stringrequiredSemantic version of the server (e.g. “1.0.0”).string | undefineddefault:"undefined"Human-readable description shown to clients during discovery.string | undefineddefault:"undefined"Server-wide guidance for AI models, returned during MCP initialization.string | undefineddefault:"\"localhost\""Hostname used for widget URLs and server endpoints.string | undefineddefault:"undefined"Full public base URL (overrideshost:portfor widget and OAuth URLs). Use when behind a reverse proxy.OAuthProvider | undefineddefault:"undefined"OAuth provider configuration. When present, the instance is typed asMcpServerInstance<true>.Partial<Parameters<typeof cors>[0]> | undefineddefault:"undefined"CORS overrides, matching the options accepted by Hono’scorsmiddleware. Defaults to permissive CORS (origin: "*") for development ergonomics.string[] | undefineddefault:"undefined"Allowed origins for DNS rebinding protection. When unset, Origin validation is off. When set, validation is enabled (additive to localhost origins).boolean | undefineddefault:"undefined"Force stateless (no session tracking) or stateful mode. Auto-detected when omitted: stateless for Deno, stateful for Node.js.number | undefineddefault:"86400000"Idle timeout for sessions in milliseconds (default: 86400000, one day).
Methods
tool
Registers a tool that MCP clients can call. The definition suppliesname and description; pass a Zod schema (or inputs) to validate arguments, and an optional callback that returns the tool result. Returns the server instance so calls can be chained. Argument types are inferred from the definition, so the callback parameters are fully typed.
Parameters
ReturnsToolDefinitionrequiredTool configuration (name, description, schema/inputs, annotations, etc.).ToolCallback | undefineddefault:"undefined"Async handler that receives the validated input (and a context object) and returns a tool result.
Examplethis
resource
Registers a static resource that clients can read by its URI. A resource represents data or content (a file, a config blob, an API response). Returns the server instance for chaining. ThemimeType defaults to "text/plain" when omitted.
Parameters
ReturnsResourceDefinitionrequiredResource configuration (name, uri, description, mimeType).ReadResourceCallback | undefineddefault:"undefined"Async handler returning the resource content.
Examplethis
resourceTemplate
Registers a resource template for parameterized resources. Clients read URIs that match auriTemplate (for example docs://{topic}); the template parameters are extracted and passed to the callback. Optional callbacks.complete provides autocomplete suggestions per parameter. Returns the server instance for chaining.
Parameters
ReturnsResourceTemplateDefinitionrequiredTemplate configuration (name, uriTemplate, description, mimeType, callbacks).ReadResourceTemplateCallback | undefineddefault:"undefined"Async handler receiving the resolvedURLand the extracted params.
Examplethis
prompt
Registers a reusable prompt template that clients can request. Prompts can accept arguments (validated by a Zodschema) and return formatted messages ready to send to an LLM. Returns the server instance for chaining.
Parameters
ReturnsPromptDefinitionrequiredPrompt configuration (name, description, schema).PromptCallback | undefineddefault:"undefined"Async handler that returns the prompt messages.
Examplethis
uiResource
Registers a UI resource for interactive widgets (MCP Apps). UI resources serve interactive components that compatible clients (such as ChatGPT with the Apps SDK, or Claude) can render. Returns the server instance for chaining. This is a declarative wrapper over the lower-level builders in the Widgets and MCP Apps reference. ParametersReturnsUIResourceDefinitionrequiredUI resource configuration (name, uri, and the widget source such ashtml, a component, or an external URL). See UIResourceDefinition.
Examplethis
notifyResourceUpdated
Notifies subscribed clients that a resource has changed. Sends anotifications/resources/updated message to every session that called resources/subscribe for the given URI. Can be called from a tool handler or any async context. Resolves once all notifications have been sent.
Parameters
ReturnsstringrequiredThe URI of the resource that was updated.
ExamplePromise<void>
listen
Starts the HTTP server. Mounts MCP protocol endpoints, widget routes, and OAuth routes (if configured), then begins listening. The Inspector is mounted bymcp-use dev, or explicitly on a built server with mcp-use start --with-inspector. Resolves once the server is listening. During HMR reload (when the CLI manages the lifecycle) this is a no-op.
Address resolution is explicit value, environment variable, server configuration, then default: the port argument → PORT → config.port → 3000; options.host → HOST → config.host → 127.0.0.1. The CLI supplies explicit values only when its corresponding flag is present.
Parameters
Returnsnumber | undefineddefault:"3000"Port to listen on. When omitted, falls back toPORT,config.port, then 3000.ListenOptionsdefault:"{}"Optional listener settings, includinghost. Host falls back toHOST,config.host, then127.0.0.1.
ExamplePromise<{ port: number; url: string }>
proxy
Mounts one or more remote HTTP MCP servers onto this server. It introspects each remote server’s tools, static resources, and prompts and registers them natively, so this server acts as a gateway. Config-map keys automatically namespace capabilities; an existingMCPConnection uses its negotiated server name. Connection, introspection, and collision failures are reported diagnostically while successfully mountable capabilities remain available.
Proxy config accepts caller-managed bearer tokens and authentication headers. It does not expose stdio or automatic OAuth options, and it disables client auto-OAuth internally so proxy setup and server startup never open a browser.
Parameters
ReturnsRecord<string, ProxyServerConfig> | ProxyConnectionrequiredA name-keyed map of HTTP server connection config, or one ready caller-owned connection.
ExamplePromise<void>
Static methods
fromOpenAPI
Creates an MCP server from a parsed, bundled OpenAPI document. Each included OpenAPI operation is registered as an MCP tool. The servername defaults to spec.info.title and the version defaults to options.version, then spec.info.version, then "1.0.0". Returns an McpServerInstance<false> (OAuth is not configured by this factory).
Parameters
ReturnsFromOpenAPIOptionsrequiredOpenAPI options (see fields below).OpenAPIDocumentrequiredThe parsed OpenAPI document.string | undefineddefault:"undefined"Base URL for the generated HTTP requests.string | undefineddefault:"spec.info.title"Server name override.string | undefineddefault:"spec.info.version"Server version override (falls back to “1.0.0”).OpenAPIAuth | undefineddefault:"undefined"Bearer or header auth applied to generated requests.Record<string, string> | undefineddefault:"undefined"Extra headers sent with every request.string[] | undefineddefault:"undefined"Only include operations matching these tags.OpenAPIExcludeRule[] | undefineddefault:"undefined"Rules to exclude operations by operationId, path, method, or tags.typeof fetch | undefineddefault:"undefined"Custom fetch implementation.
SignatureMcpServerInstance<false>
getPackageVersion
Returns the installedmcp-use package version string (for example "1.13.2").
Returns
Examplestring
Types
McpServerInstance
The runtime type of a value returned bynew MCPServer(config). It is an intersection of three surfaces, so a single instance exposes MCP methods, the full Hono app, and the mcp-use helper surface at once.
The HasOAuth type parameter is true when oauth is configured in ServerConfig and false otherwise; it flows into the typing of tool, resource, and prompt callbacks (for example, the presence of ctx.auth).
Definition