Skip to content

Repository files navigation

mcp-interceptor

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.

Install

npm install mcp-interceptor @modelcontextprotocol/server

Quick start

import { 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.

Filters

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.

Scope

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

License

MIT

About

Composable middleware for the official MCP TypeScript server SDK

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages