typescript

Conditionally enable AI agent tools based on request context

Mastra's RequestContext lets you customize agent behavior on a per-request basis. By extending the base class with your own type parameters, you get type-safe access to context values like user sessions or feature flags. This is more flexible than creating separate agents - you maintain one agent definition while dynamically adjusting its capabilities based on who’s calling it and what they’re allowed to do.

import { RequestContext as _RequestContext } from "@mastra/core/request-context";
import { Agent } from "@mastra/core/agent"

class RequestContext extends _RequestContext<{
  enableCmsTools?: boolean;
}> {}

// In agent config:
export const agent = new Agent({
  id: "my-agent",
  name: "My Agent",
  // ...
  tools: ({ requestContext }) => {
    const context = requestContext as RequestContext;

    const tools = {
      searchWebpages,
      fetchPage,
      // Conditionally add CMS tools:
      ...(context.get("enableCmsTools")
        ? {
            createPage,
            updatePage,
          }
        : {}),
    }

    return tools;
  },
});
typescriptmastraai
lubosmato