mcp-use TypeScript API
    Preparing search index...

    Class MCPServer<TUser, TEnv>

    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.

    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);

    Type Parameters

    • TUser = never
    • TEnv extends Env = Env
    Index
    • 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 MCPServer.listen or the first request reaches MCPServer.fetch.

      Type Parameters

      • TUser = never
      • TEnv extends Env = Env

      Parameters

      Returns MCPServer<TUser, TEnv>

    all: HandlerInterface<TEnv, "all", BlankSchema, "/", "/">

    Register a typed route for every HTTP method on MCPServer.app.

    app: Hono<TEnv>

    Hono application that owns HTTP middleware and routes.

    delete: HandlerInterface<TEnv, "delete", BlankSchema, "/", "/">

    Register a typed DELETE route on MCPServer.app.

    fetch: (
        ...args: [
            request: Request,
            Env?: {}
            | TEnv["Bindings"],
            executionCtx?: ExecutionContext,
        ],
    ) => Promise<Response>

    Canonical Web-standard handler for edge runtimes and framework mounting.

    export default server;
    // or: export const POST = server.fetch;
    get: HandlerInterface<TEnv, "get", BlankSchema, "/", "/">

    Register a typed GET route on MCPServer.app.

    patch: HandlerInterface<TEnv, "patch", BlankSchema, "/", "/">

    Register a typed PATCH route on MCPServer.app.

    Readonlypost

    post: HandlerInterface<TEnv, "post", BlankSchema, "/", "/">

    Register a typed POST route on MCPServer.app.

    put: HandlerInterface<TEnv, "put", BlankSchema, "/", "/">

    Register a typed PUT route on MCPServer.app.

    • get basePath(): string

      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.

      Returns string

    • get branding(): ServerBranding

      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.

      Returns ServerBranding

      if (server.branding.favicon) {
      console.log("Browser favicon: /favicon.ico");
      }
    • get host(): string | undefined

      Configured bind host, before CLI and environment overrides.

      Returns string | undefined

    • get port(): number | undefined

      Configured bind port, before CLI and environment overrides.

      Returns number | undefined

    • 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.

      Returns Promise<void>

    • Returns (
          ...args: [
              request: Request,
              Env?: {}
              | TEnv["Bindings"],
              executionCtx?: ExecutionContext,
          ],
      ) => Promise<Response>

        • (
              ...args: [
                  request: Request,
                  Env?: {}
                  | TEnv["Bindings"],
                  executionCtx?: ExecutionContext,
              ],
          ): Promise<Response>
        • Canonical Web-standard handler for edge runtimes and framework mounting.

          Parameters

          • ...args: [request: Request, Env?: {} | TEnv["Bindings"], executionCtx?: ExecutionContext]

          Returns Promise<Response>

          export default server;
          // or: export const POST = server.fetch;

      Use MCPServer.fetch directly.

    • 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.

      Parameters

      • port: number | undefined = undefined
      • options: ListenOptions = {}

      Returns Promise<{ port: number; url: string }>

      If called on a localhost-class bind after MCPServer.fetch already mounted the app without Host validation.

    • Publish a prompts-list change to v2 clients with active subscriptions.

      Returns Promise<void>

      await server.notifyPromptsChanged();
      
    • Publish a resources-list change to v2 clients with active subscriptions.

      Returns Promise<void>

      await server.notifyResourcesChanged();
      
    • Publish a resource update to subscribed v2 clients.

      Parameters

      • uri: string

        Resource URI whose representation changed.

      Returns Promise<void>

      await server.notifyResourceUpdated("config://settings");
      
    • Publish a tools-list change to v2 clients with active subscriptions.

      Returns Promise<void>

      await server.notifyToolsChanged();
      
    • Register a read-only MCP observer. Unlike 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).

      Type Parameters

      Parameters

      Returns this

      server.on("mcp:tools/call", (ctx) => {
      metrics.increment("tools.call", { tool: ctx.params.name });
      });
    • 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 ProxyConnection; its negotiated server name becomes the namespace and the connection remains caller-owned.

      Connection, introspection, and collision failures are diagnosed and skipped without discarding capabilities that can be mounted.

      Parameters

      • servers: Record<string, ProxyServerConfig>

        Namespace-keyed upstream HTTP connection settings.

      Returns Promise<void>

      If @mcp-use/client is not installed or the server already started or closed.

      await server.proxy({
      weather: {
      url: "https://weather.example.com/mcp",
      authToken: process.env.WEATHER_MCP_TOKEN,
      },
      });
    • Mount an existing ready @mcp-use/client v2 connection.

      Parameters

      • connection: ProxyConnection

        Ready connection to introspect and forward through. The connection's negotiated server name automatically namespaces every mounted capability. Introspection and collision failures are diagnosed and skipped without discarding capabilities that can be mounted.

      Returns Promise<void>

      If the server already started or closed.

      const connection = await client.connect("database");
      await server.proxy(connection);
    • 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.

      Type Parameters

      • P extends
            | "mcp:*"
            | "mcp:prompts/get"
            | "mcp:prompts/list"
            | "mcp:resources/list"
            | "mcp:resources/read"
            | "mcp:tools/call"
            | "mcp:tools/list"

      Parameters

      Returns this

      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();
      });
    • 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.

      Parameters

      • handler: MiddlewareHandler<TEnv>

      Returns this

      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();
      });
    • 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.

      Parameters

      • path: "*" | `/${string}`
      • ...handlers: MiddlewareHandler<TEnv>[]

      Returns this

      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();
      });
    • 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.

      Parameters

      • options: FromOpenAPIOptions

        OpenAPI document, operation filters, upstream URL, and request authentication options.

      Returns MCPServer

      An unauthenticated MCP server populated with generated tools.

      const spec = await fetch("https://api.example.com/openapi.json")
      .then((response) => response.json());
      const server = MCPServer.fromOpenAPI({ spec });
      await server.listen(3000);