Skip to main content

请求上下文

🌐 Request Context

代理、工具和工作流都可以接受 RequestContext 作为参数,从而使请求特定的值可以用于底层原语。

🌐 Agents, tools, and workflows can all accept RequestContext as a parameter, making request-specific values available to the underlying primitives.

何时使用 RequestContext
Direct link to when-to-use-requestcontext

🌐 When to use RequestContext

当原语的行为需要根据运行时条件变化时,使用 RequestContext。例如,你可能会根据用户属性切换模型或存储后端,或者根据语言调整指令和工具选择。

🌐 Use RequestContext when a primitive's behavior should change based on runtime conditions. For example, you might switch models or storage backends based on user attributes, or adjust instructions and tool selection based on language.

note

注意: RequestContext 主要用于将数据传递到特定请求中。它与代理内存不同,代理内存负责处理对话历史和跨多次调用的状态持久化。

设置值
Direct link to 设置值

🌐 Setting values

requestContext 传入代理、网络、工作流或工具调用中,以使值在执行过程中可供所有底层原语使用。使用 .set() 在进行调用之前定义值。

🌐 Pass requestContext into an agent, network, workflow, or tool call to make values available to all underlying primitives during execution. Use .set() to define values before making the call.

.set() 方法接受两个参数:

🌐 The .set() method takes two arguments:

  1. :用于识别该值的名称。
  2. :要与该键关联的数据。
import { RequestContext } from "@mastra/core/request-context";

export type UserTier = {
"user-tier": "enterprise" | "pro";
};

const requestContext = new RequestContext<UserTier>();
requestContext.set("user-tier", "enterprise");

const agent = mastra.getAgent("weatherAgent");
await agent.generate("What's the weather in London?", {
requestContext,
});

const routingAgent = mastra.getAgent("routingAgent");
routingAgent.network("What's the weather in London?", {
requestContext,
});

const run = await mastra.getWorkflow("weatherWorkflow").createRun();
await run.start({
inputData: {
location: "London",
},
requestContext,
});
await run.resume({
resumeData: {
city: "New York",
},
requestContext,
});

await weatherTool.execute(
{ location: "London" },
{ requestContext },
);

根据请求头设置值
Direct link to 根据请求头设置值

🌐 Setting values based on request headers

你可以通过从请求中提取信息,在服务器中间件中动态填充 requestContext。在这个例子中,temperature-unit 是根据 Cloudflare 的 CF-IPCountry 头设置的,以确保响应与用户的语言环境匹配。

🌐 You can populate requestContext dynamically in server middleware by extracting information from the request. In this example, the temperature-unit is set based on the Cloudflare CF-IPCountry header to ensure responses match the user's locale.

src/mastra/index.ts
import { Mastra } from "@mastra/core";
import { RequestContext } from "@mastra/core/request-context";
import { testWeatherAgent } from "./agents/test-weather-agent";

export const mastra = new Mastra({
agents: { testWeatherAgent },
server: {
middleware: [
async (context, next) => {
const country = context.req.header("CF-IPCountry");
const requestContext = context.get("requestContext");

requestContext.set(
"temperature-unit",
country === "US" ? "fahrenheit" : "celsius",
);

await next();
},
],
},
});
info

访问 Middleware 了解如何使用服务器中间件。

🌐 Visit Middleware for how to use server middleware.

通过代理访问值
Direct link to 通过代理访问值

🌐 Accessing values with agents

你可以从代理中的任何支持的配置选项访问 requestContext 参数。这些函数可以是同步的或 async。使用 .get() 方法从 requestContext 读取值。

🌐 You can access the requestContext argument from any supported configuration options in agents. These functions can be sync or async. Use the .get() method to read values from requestContext.

src/mastra/agents/weather-agent.ts
export type UserTier = {
"user-tier": "enterprise" | "pro";
};

export const weatherAgent = new Agent({
id: "weather-agent",
name: "Weather Agent",
instructions: async ({ requestContext }) => {
const userTier = requestContext.get("user-tier") as UserTier["user-tier"];

if (userTier === "enterprise") {}
},
model: ({ requestContext }) => {},
tools: ({ requestContext }) => {},
memory: ({ requestContext }) => {},
});

你也可以将 requestContext 与其他选项一起使用,比如 agentsworkflowsscorersinputProcessorsoutputProcessors

🌐 You can also use requestContext with other options like agents, workflows, scorers, inputProcessors, and outputProcessors.

动态指令
Direct link to 动态指令

🌐 Dynamic instructions

代理说明可以作为异步函数提供,使你能够在运行时动态地解析提示。结合 requestContext,这使得可以实现如下模式:

🌐 Agent instructions can be provided as an async function, enabling you to resolve prompts dynamically at runtime. Combined with requestContext, this enables patterns like:

  • 个性化:根据用户属性、偏好或等级定制指令
  • 本地化:根据所在地区调整语气、语言或行为
  • A/B 测试:提供不同的提示版本进行实验
  • 外部提示管理:从注册服务获取提示,无需重新部署
src/mastra/agents/dynamic-agent.ts
import { Agent } from "@mastra/core/agent";

export const dynamicAgent = new Agent({
id: "dynamic-agent",
name: "Dynamic Agent",
instructions: async ({ requestContext }) => {
const userTier = requestContext?.get("user-tier");
const locale = requestContext?.get("locale");

// Personalize based on user tier
const basePrompt = userTier === "enterprise"
? "You are a premium support agent. Provide detailed, thorough responses with technical depth."
: "You are a helpful assistant. Be concise and friendly.";

// Localize behavior
const localeInstructions = locale === "ja"
? "Respond in Japanese using formal keigo."
: "";

return `${basePrompt} ${localeInstructions}`.trim();
},
model: "openai/gpt-5.1",
});

从提示注册表获取
Direct link to 从提示注册表获取

🌐 Fetching from a prompt registry

如果你的组织使用提示注册服务进行集中提示管理,你可以在运行时获取指令。这使你能够在无需重新部署的情况下更新提示,运行不同版本的实验,并跟踪各个代理的提示使用情况。

🌐 If your organization uses a prompt registry service for central prompt management, you can fetch instructions at runtime. This allows you to update prompts without redeploying, run experiments with variants, and track prompt usage across your agents.

src/mastra/agents/registry-agent.ts
import { Agent } from "@mastra/core/agent";

// Your prompt registry client
import { promptRegistry } from "../lib/prompt-registry";

export const registryAgent = new Agent({
id: "registry-agent",
name: "Registry Agent",
instructions: async ({ requestContext }) => {
const prompt = await promptRegistry.getPrompt({
promptId: "customer-support-agent",
// Pass context for variant selection or tracking
variant: requestContext?.get("experiment-variant"),
userId: requestContext?.get("user-id"),
});

return prompt.content;
},
model: "openai/gpt-5.1",
});
info

访问 Agent 获取完整的配置选项列表。

🌐 Visit Agent for a full list of configuration options.

从工作流步骤中访问值
Direct link to 从工作流步骤中访问值

🌐 Accessing values from workflow steps

你可以从工作流步骤的 execute 函数中访问 requestContext 参数。此函数可以是同步的也可以是异步的。使用 .get() 方法从 requestContext 中读取值。

🌐 You can access the requestContext argument from a workflow step's execute function. This function can be sync or async. Use the .get() method to read values from requestContext.

src/mastra/workflows/weather-workflow.ts
export type UserTier = {
"user-tier": "enterprise" | "pro";
};

const stepOne = createStep({
id: "step-one",
execute: async ({ requestContext }) => {
const userTier = requestContext.get("user-tier") as UserTier["user-tier"];

if (userTier === "enterprise") {}
},
});
info

访问 createStep() 查看完整的配置选项列表。

🌐 Visit createStep() for a full list of configuration options.

使用工具访问数值
Direct link to 使用工具访问数值

🌐 Accessing values with tools

你可以从工具的 execute 函数访问 requestContext 参数。此函数是 async。使用 .get() 方法从 requestContext 读取值。

🌐 You can access the requestContext argument from a tool's execute function. This function is async. Use the .get() method to read values from requestContext.

src/mastra/tools/weather-tool.ts
export type UserTier = {
"user-tier": "enterprise" | "pro";
};

export const weatherTool = createTool({
id: "weather-tool",
execute: async (inputData, context) => {
const userTier = context?.requestContext?.get("user-tier") as UserTier["user-tier"] | undefined;

if (userTier === "enterprise") {}
},
});
info

访问 createTool() 查看完整的配置选项列表。

🌐 Visit createTool() for a full list of configuration options.

保留键
Direct link to 保留键

🌐 Reserved keys

Mastra 为安全目的保留了特殊的上下文键。当由中间件设置时,这些键优先于客户端提供的值。服务器会自动验证所有权,当用户尝试访问他们不拥有的资源时会返回 403 错误。

🌐 Mastra reserves special context keys for security purposes. When set by middleware, these keys take precedence over client-provided values. The server automatically validates ownership and returns 403 errors when users attempt to access resources they don't own.

import {
MASTRA_RESOURCE_ID_KEY,
MASTRA_THREAD_ID_KEY,
} from "@mastra/core/request-context";

// In middleware: force memory operations to use authenticated user's ID
requestContext.set(MASTRA_RESOURCE_ID_KEY, user.id);

// In middleware: set validated thread ID
requestContext.set(MASTRA_THREAD_ID_KEY, threadId);
作用
MASTRA_RESOURCE_ID_KEY强制所有内存操作使用此资源 ID。服务器会验证访问的线程是否属于此资源,如果不是,则返回 403。
MASTRA_THREAD_ID_KEY强制线程操作使用此线程 ID,覆盖客户端提供的值

这些密钥用于在多租户应用中实现用户隔离。有关使用示例,请参见 授权中间件

🌐 These keys are used to implement user isolation in multi-tenant applications. See Authorization middleware for usage examples.

TypeScript 支持
Direct link to TypeScript 支持

🌐 TypeScript support

当你为 RequestContext 提供类型参数时,所有方法都会被完整类型化:

🌐 When you provide a type parameter to RequestContext, all methods are fully typed:

import { RequestContext } from "@mastra/core/request-context";

type MyContext = {
userId: string;
maxTokens: number;
isPremium: boolean;
};

const ctx = new RequestContext<MyContext>();

// set() enforces correct value types
ctx.set("userId", "user-123"); // ✓ valid
ctx.set("maxTokens", 4096); // ✓ valid
ctx.set("maxTokens", "wrong"); // ✗ TypeScript error: expected number

// get() returns the correct type automatically
const tokens = ctx.get("maxTokens"); // inferred as number
const id = ctx.get("userId"); // inferred as string

// keys() returns typed keys
for (const key of ctx.keys()) {
// key is "userId" | "maxTokens" | "isPremium"
}

// entries() supports type narrowing
for (const [key, value] of ctx.entries()) {
if (key === "maxTokens") {
// TypeScript knows value is number here
console.log(value.toFixed(2));
}
if (key === "userId") {
// TypeScript knows value is string here
console.log(value.toUpperCase());
}
}

🌐 Related