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/middleware/mcp-middleware.ts
MCPServer:
- Operation-level MCP middleware, a Hono-style chain registered with
server.use('mcp:...')that wraps individual MCP operations (tool calls, resource reads, prompt gets, and list operations). Implemented bycomposeMiddleware,matchesPattern, and theMiddlewareContexttypes. - HTTP middleware adapters,
adaptMiddleware,adaptConnectMiddleware, andisExpressMiddleware, which let you register either Express/Connect middleware (such asmorganorexpress-rate-limit) or native Hono middleware on the underlying HTTP app. - A CORS proxy,
mountMcpProxy, that forwards browser-originated MCP requests to remote servers that do not support CORS.
mcp-use/server.
Operation-level MCP middleware
Hono-style middleware for intercepting MCP operations. Register handlers withserver.use('mcp:...', handler). Each handler receives a MiddlewareContext and a next function, executes around next(), and may inspect or mutate ctx.params, short-circuit by returning a value, or reject by throwing.
composeMiddleware
Compose a middleware chain for a single MCP method invocation. It filtersentries down to those whose pattern matches method, then builds a next() chain with innerFn at the center and returns the outermost callable.
If no entries match method, it returns a function that ignores its context and simply calls innerFn directly (zero overhead). Otherwise the returned function dispatches through each matching handler in FIFO registration order, with the first registered handler running as the outermost wrapper.
Each handler’s next advances to the following handler (or to innerFn when the last handler is reached). Calling next() more than once within the same handler rejects with Error("next() called multiple times").
Parameters
ReturnsRegistered middleware entries (pattern plus handler). Only entries matchingmethodare included in the chain.The MCP method being invoked, e.g."tools/call"or"resources/read".The terminal function (the actual handler) called once the chain reaches its center.
SignatureThe outermost callable. Invoke it with aMiddlewareContextto run the chain.
matchesPattern
Test whether a registered middleware pattern matches a given MCP method. The pattern here is the value after themcp: prefix has been stripped.
Matching rules:
"*"matches any method.- A pattern ending in
"/*"(such as"tools/*") prefix-matches any method that starts with the part before the*(such as"tools/"). The match is computed by slicing off the trailing*and callingmethod.startsWith(prefix). - Any other pattern (such as
"tools/call") is an exact match only.
ReturnsThe pattern to test, with themcp:prefix already removed, e.g."*","tools/*", or"tools/call".The MCP method name to match against, e.g."tools/call".
Signaturetrueif the pattern matches the method.
MiddlewareContext
The context passed to every MCP middleware handler.params is mutable: a middleware can modify it before calling next(), and those changes are visible to downstream middleware and to the handler. state is a shared Map for passing arbitrary data across middleware in the same request chain.
Properties
SignatureMCP method name, e.g."tools/call","tools/list","resources/read".JSON-RPC request params. Mutable: mutations are passed downstream.Session info if available (HTTP transports only).OAuth info extracted from the JWT. Present only when OAuth is configured; otherwiseundefined.Shared state map for passing data across middleware in the same request.
McpMiddlewareFn
A single MCP middleware function. Callnext() to pass control to the next middleware (or the handler). Return its result, or return a different value to override the response, or throw an error to reject the request.
Parameters
ReturnsThe middleware context for the current operation.Advances the chain. Resolves with the result of the next middleware or the handler.
SignatureThe (possibly overridden) result of the operation.
McpMiddlewareFnFor
A typed MCP middleware function whosectx parameter is narrowed based on the pattern string P. When P is a key of McpMiddlewarePatternMap ("tools/call", "resources/read", or "prompts/get"), ctx is narrowed to the matching context type. For wildcard or unrecognized patterns it falls back to the base McpMiddlewareFn whose ctx is the base MiddlewareContext.
Type parameters
SignatureThe middleware pattern string used to select the narrowed context type.
McpMiddlewarePatternMap
Maps MCP middleware pattern strings to their narrowed context type. Used byMcpMiddlewareFnFor to infer the correct ctx parameter for a given pattern.
Properties
SignatureNarrowed context for thetools/callmethod.Narrowed context for theresources/readmethod.Narrowed context for theprompts/getmethod.
ToolsCallMiddlewareContext
AMiddlewareContext with method fixed to "tools/call" and params narrowed to the tools/call shape: name (the tool name), an optional arguments record, and an optional _meta record. The params type is intersected with Record<string, unknown> so arbitrary extra keys remain accessible.
Properties
SignatureAlways the literal"tools/call".params{ name: string; arguments?: Record<string, unknown>; _meta?: Record<string, unknown> } & Record<string, unknown>requiredThe narrowed tool-call params.
ResourcesReadMiddlewareContext
AMiddlewareContext with method fixed to "resources/read" and params narrowed to the resources/read shape: uri (the resource URI) and an optional _meta record. The params type is intersected with Record<string, unknown> so extra keys remain accessible.
Properties
SignatureAlways the literal"resources/read".The narrowed resource-read params.
PromptsGetMiddlewareContext
AMiddlewareContext with method fixed to "prompts/get" and params narrowed to the prompts/get shape: name (the prompt name), an optional arguments record of strings, and an optional _meta record. The params type is intersected with Record<string, unknown> so extra keys remain accessible.
Properties
SignatureAlways the literal"prompts/get".params{ name: string; arguments?: Record<string, string>; _meta?: Record<string, unknown> } & Record<string, unknown>requiredThe narrowed prompt-get params.
McpMiddlewareEntry
Internal storage entry for a registered MCP middleware. The pattern is stored with themcp: prefix already stripped (e.g. "tools/call", "tools/*", or "*"). This is the element type consumed by composeMiddleware.
This interface is marked
@internal. It is exported for advanced use and for typing custom middleware composition, but most servers register middleware through server.use('mcp:...') and never construct entries directly.SignaturePattern after stripping"mcp:", e.g."tools/call","tools/*", or"*".The middleware function to run for matching methods.
HTTP middleware adapters
Adapters that let you register either Express/Connect middleware or native Hono middleware on the server’s underlying HTTP app.server.use(...) uses these internally to detect the middleware style and adapt accordingly, so the same server.use(...) call accepts both.
server.use(...) detects each style and adapts it for you.
isExpressMiddleware
Detect whether a middleware function is Express/Connect style or Hono style. Express/Connect middleware has the signature(req, res, next) (or (err, req, res, next)); Hono middleware has the signature (c, next).
Detection combines function arity with body pattern matching against the stringified function:
- A non-function (or falsy) value returns
false. - Functions with 3 or 4 parameters are treated as Express/Connect and return
true(the body is checked for Express patterns such asres.send,res.json,req.body, but it returnstruefor 3-4 parameter functions regardless). - Functions with exactly 2 parameters are treated as Hono and return
false, unless the body contains Express-specific patterns (thentrue). Hono-specific patterns such asc.reqorc.jsonconfirm the Hono case (false). - Functions with any other parameter count (0, 1, or 5+) default to Hono and return
false.
ReturnsThe middleware function to inspect.
Signaturetrueif it is Express/Connect middleware,falseif it is Hono middleware.
adaptMiddleware
Adapt a middleware function so it works with Hono. It callsisExpressMiddleware: if the input is Express/Connect style, it delegates to adaptConnectMiddleware with the supplied path; otherwise it returns the middleware unchanged as a Hono MiddlewareHandler.
Parameters
ReturnsThe middleware function (Express/Connect or Hono).The path pattern the middleware is mounted at. Only used when the middleware is Express/Connect. Defaults to"*".
SignatureA Hono middleware handler.
adaptConnectMiddleware
Adapt a Connect/Express middleware handler to a HonoMiddlewareHandler. It dynamically imports node-mocks-http to build a mock IncomingMessage/ServerResponse pair, runs the Connect middleware against them, and translates the result back into a Hono response.
Behavior to note:
- The
middlewarePathis normalized by stripping a trailing*and a trailing/, then that prefix is removed from the request pathname so the Connect middleware sees the path without its mount prefix. - If the Connect middleware ends the response (calls
res.end), the captured status, headers, and body become the Hono response. Status codes204and304are sent without a body. - If the Connect middleware calls
next()without ending the response, control passes to Hono’snext()so the request continues down the chain.
ReturnsThe Connect/Express middleware handler to adapt.The path pattern the middleware is mounted at, e.g."/mcp-use/widgets/*".
SignatureA Hono middleware handler wrapping the Connect middleware.
CORS proxy
A CORS proxy for browser-based MCP clients that need to connect to remote MCP servers which do not support CORS or require server-side forwarding. Mount it onto a Hono app withmountMcpProxy.
mountMcpProxy
Mount the MCP proxy middleware on a Hono app. The proxy reads a target URL from theX-Target-URL header (or from an __mcp_target query parameter used for OAuth discovery, which takes precedence), forwards the request to that target with sanitized headers, and streams the response back to the client. It enables CORS (exposing all response headers, with Authorization allowed explicitly), handles SSE streaming, manages redirects manually to avoid ArrayBuffer detachment, and rewrites the resource field on OAuth discovery responses to match the proxy URL. Returns void.
The proxy registers routes under options.path (default "/mcp/proxy"): a CORS handler and an optional logger on the path/* glob, plus a catch-all handler for every HTTP method on that same glob.
Error and status behavior:
- Missing target URL responds
400with anX-Target-URL header is requirederror. - An invalid target URL format responds
400. - When
authenticatereturns false, responds401(Unauthorized). - When
validateRequestreturns false, responds403(Invalid target URL). - Upstream failures respond
500; connection-refused errors (ECONNREFUSEDorfetch failed) are logged as a warning rather than an error.
ReturnsThe Hono application instance to mount the proxy on.Proxy configuration. Defaults to an empty object.
Signature
McpProxyOptions
Configuration formountMcpProxy. Every field is optional.
Properties
SignatureRoute path for the proxy endpoint, e.g."/inspector/api/proxy".Optional authentication function. Returntrueto allow the request,falseto reject with401.Optional validator checking whether the target URL is allowed. Returntrueto allow,falseto reject with403.Enable request logging. Disabled only when explicitly set tofalse.
See also
MCPServer
The server class whose
use(...) method registers the middleware documented here.Source on GitHub
Full middleware and proxy implementation.