Middlewares

Useful for intercepting and processing requests and responses.

For the complete documentation index, see llms.txt. Markdown variants of every page are available by appending .md to the URL.

Middlewares intercept HTTP requests and responses, enabling authentication, rate limiting, and other processing tasks.

Create a src/middleware.ts file to define your middleware:

src/middleware.ts
import { type Middleware } from "xmcp";

const middleware: Middleware = async (req, res, next) => {
  const authHeader = req.headers.authorization;

  if (!customHeaderValidation(authHeader)) {
    res.status(401).json({ error: "Invalid API key" });
    return;
  }

  return next();
};

export default middleware;

Chaining middlewares

Define multiple middlewares as an array to chain them in sequence:

src/middleware.ts
import { type Middleware } from "xmcp";

const middleware: Middleware = [
  async (req, res, next) => {
    // First middleware
    return next();
  },
  async (req, res, next) => {
    // Second middleware
    return next();
  },
];

export default middleware;

Accessing headers

Use the xmcp/headers module to read request headers in your tools, prompts, or resources—useful for API keys, authentication tokens, and other custom headers.

src/tools/search.ts
import { headers } from "xmcp/headers";

export default async function search({ query }: InferSchema<typeof schema>) {
  const requestHeaders = headers();
  const apiKey = requestHeaders["x-api-key"];

  const data = await fetchSomeData(apiKey);

  return JSON.stringify(data);
}