MCP Apps Kit - v0.5.0
    Preparing search index...

    Function defineMiddleware

    • Define middleware with automatic next() handling

      Prevents the common mistake of forgetting to call await next().

      Parameters

      Returns Middleware

      const logging = defineMiddleware({
      before: async (context) => {
      console.log("Tool:", context.toolName);
      },
      after: async (context) => {
      console.log("Completed:", context.toolName);
      },
      });
      const timing = defineMiddleware.before(async (context) => {
      context.state.set("startTime", Date.now());
      });
      const metrics = defineMiddleware.after(async (context) => {
      const duration = Date.now() - (context.state.get("startTime") as number);
      recordMetric(context.toolName, duration);
      });
      const auth = defineMiddleware.wrap(async (context, next) => {
      if (!context.metadata.subject) {
      throw new Error("Unauthorized");
      }
      return next(); // TypeScript enforces returning Promise<void>
      });
    Index

    Properties

    Methods

    Properties

    withResult: DefineMiddlewareWithResult

    Define middleware with result passing support

    Allows middleware to inspect and transform results from tool handlers.

    const logResult = defineMiddleware.withResult<ToolResult>({
    after: async (context, result) => {
    console.log("Result:", result.data);
    return result; // Keep original result
    },
    });
    const addTimestamp = defineMiddleware.withResult<ToolResult>({
    after: async (context, result) => {
    return {
    ...result,
    _meta: { ...result._meta, timestamp: Date.now() },
    };
    },
    });
    const cache = defineMiddleware.withResult<ToolResult>({
    before: async (context) => {
    const cached = await getFromCache(context.toolName, context.input);
    if (cached) {
    context.state.set("response", cached);
    }
    },
    after: async (context, result) => {
    if (!context.state.get("response")) {
    await saveToCache(context.toolName, context.input, result);
    }
    return result;
    },
    });

    Methods

    • Create middleware with full control and type enforcement

      The return type (Promise) helps TypeScript catch cases where you forget to return next() or throw an error.

      Use this pattern for:

      • Conditional execution
      • Short-circuiting the chain
      • Error handling
      • Complex control flow

      Parameters

      Returns Middleware

      const auth = defineMiddleware.wrap(async (context, next) => {
      const token = context.metadata.raw?.["authorization"];
      if (!token) throw new Error("Missing auth token");
      return next();
      });
      const skipForAdmin = defineMiddleware.wrap(async (context, next) => {
      if (context.metadata.subject === "admin") {
      return; // Skip the rest of the chain
      }
      return next();
      });