Composable middleware for tools, prompts, and resources registered with the official MCP TypeScript server SDK.
mcp-interceptor wraps public McpServer registration methods. It does not
replace transports, patch private SDK registries, or bypass the SDK's input and
output validation.
npm install mcp-interceptor @modelcontextprotocol/serverimport { McpServer } from "@modelcontextprotocol/server";
import { interceptMcpServer } from "mcp-interceptor";
import { z } from "zod";
const mcp = interceptMcpServer(
new McpServer({ name: "orders", version: "1.0.0" }),
);
mcp.use(async (context, next) => {
const startedAt = performance.now();
try {
return await next();
} finally {
console.log(context.kind, context.name, performance.now() - startedAt);
}
});
mcp.use(
async (context, next) => {
if (!context.mcp.http?.authInfo) throw new Error("Authentication required");
return next();
},
{ kind: "tool", name: /^admin-/ },
);
mcp.registerTool(
"admin-list-orders",
{ inputSchema: z.object({ limit: z.number().int().positive() }) },
async ({ limit }) => ({
content: [{ type: "text", text: `Listing ${limit} orders` }],
}),
);
await mcp.server.connect(transport);Middleware runs in onion order. It may replace context.input, replace the
result returned by next(), store request-local data in context.state, or
short-circuit without calling next().
Only operations registered through the returned wrapper are intercepted. The
underlying server remains available as mcp.server for transports,
notifications, and other SDK operations.
use() accepts an optional operation/name filter:
mcp.use(audit, { kind: ["tool", "resource"] });
mcp.use(requireAdmin, { kind: "tool", name: /^admin-/ });
mcp.use(perTenant, {
name: (name, kind) => kind === "resource" && name.startsWith("tenant-"),
});Calling the function returned by use() removes that registration.
- MCP TypeScript server SDK v2
- Modern Standard Schema inputs supported by the SDK
- Tools, prompts, static resources, and resource templates
- No transport interception and no interception of registrations performed
directly on the underlying
McpServer
See the documentation index for the API, architecture, and maintenance details.
MIT