跳到主要内容

请求上下文

Agent、Tool 和 Workflow 都可以接受 RequestContext 作为参数,使底层原语能够使用请求特定的值。

何时使用 RequestContext
when-to-use-requestcontext的直接链接

当原语的行为应根据运行时条件而变化时,请使用 RequestContext。例如,可以根据用户属性切换模型或存储后端,也可以根据语言调整指令和 Tool 选择。

备注

RequestContext 主要用于向特定请求传递数据。它不同于 Agent 内存,后者负责处理多次调用之间的对话历史记录和状态持久化。

设置值
设置值的直接链接

requestContext 传入 Agent、network、Workflow 或 Tool 调用,即可让所有底层原语在执行期间使用其中的值。发出调用前,使用 .set() 定义值。

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

  1. key:用于标识值的名称。
  2. value:要与该键关联的数据。
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 })

根据请求标头设置值
根据请求标头设置值的直接链接

可以通过从请求中提取信息,在运行时服务器中间件中填充 requestContext。本示例根据 Cloudflare CF-IPCountry 标头设置 temperature-unit,以确保响应与用户的区域设置匹配。

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()
},
],
},
})

有关服务器中间件的用法,请参阅中间件

Studio
Studio的直接链接

本地开发时,可以在 JSON 文件中定义预设,并使用 --request-context-presets CLI 标志将其加载到 Studio。这会在 Studio 的请求上下文编辑器中添加下拉菜单,让你无需每次手动编辑 JSON 即可快速切换配置。

mastra dev --request-context-presets ./presets.json
presets.json
{
"development": { "userId": "dev-user", "env": "development" },
"production": { "userId": "prod-user", "env": "production" }
}

从下拉菜单中选择预设后,JSON 编辑器会填入该预设的值。手动编辑 JSON 会使下拉菜单切换回 "Custom"

在 Agent 中访问值
在 Agent 中访问值的直接链接

可以从 Agent 中任何受支持的配置选项访问 requestContext 参数。这些函数可以是同步函数或 async 函数。使用 .get() 方法读取 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 }) => {},
})

也可以将 requestContextagentsworkflowsscorersinputProcessorsoutputProcessors 等其他选项配合使用。

动态指令
动态指令的直接链接

Agent 指令可以作为异步函数提供,以便在运行时解析提示。与 requestContext 结合使用,可实现以下模式:

  • 个性化:根据用户属性、偏好或等级定制指令
  • 本地化:根据区域设置调整语气、语言或行为
  • 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.6-sol',
})

从提示注册表获取
从提示注册表获取的直接链接

如果 Organization 使用提示注册表服务集中管理提示,可以在运行时获取指令。无需重新部署即可更新提示、使用变体运行实验,并跟踪各 Agent 的提示使用情况。

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.6-sol',
})

有关配置选项的完整列表,请参阅 Agent

从 Workflow 步骤访问值
从 Workflow 步骤访问值的直接链接

可以从 Workflow 步骤的 execute 函数访问 requestContext 参数。此函数可以是同步函数或异步函数。使用 .get() 方法读取 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') {
}
},
})

有关配置选项的完整列表,请参阅 createStep()

在 Tool 中访问值
在 Tool 中访问值的直接链接

可以从 Tool 的 execute 函数访问 requestContext 参数。此函数为 async。使用 .get() 方法读取 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') {
}
},
})

有关配置选项的完整列表,请参阅 createTool()

保留键
保留键的直接链接

Mastra 出于安全目的保留了特殊上下文键。设置后,这些键优先于客户端提供的值。服务器会自动验证所有权,并在用户尝试访问不属于自己的资源时返回 403 错误。

设置 MASTRA_RESOURCE_ID_KEY 的最简单方法,是使用身份验证配置中的 mapUserToResourceId 回调:

auth: {
authenticateToken: async token => verifyToken(token),
mapUserToResourceId: user => user.id,
}

以这种方式派生资源 ID 后,客户端可以在 Agent generate 和 stream 请求正文中省略 memory.resource,改用服务器派生的值(且该值始终优先于任何客户端提供的值)。如果请求使用内存,但正文和请求上下文均未提供资源 ID,服务器会返回 400 错误。

也可以在中间件中手动设置这些键:

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。服务器会验证访问的 Thread 是否属于此资源;否则返回 403。
MASTRA_THREAD_ID_KEY强制 Thread 操作使用此 Thread ID,并覆盖客户端提供的值

这些键用于在多租户应用中实现用户隔离。有关用法示例,请参阅授权中间件

TypeScript 支持
TypeScript 支持的直接链接

RequestContext 提供类型参数后,所有方法都会获得完整类型:

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())
}
}

Schema 验证
Schema 验证的直接链接

使用 requestContextSchema 定义 Standard JSON SchemaZodValibotArkType 等),以在运行时验证请求上下文值。这样可以尽早发现缺失或无效的上下文值,提供清晰的错误消息,并在组件中提供类型推断。

Agent schema 验证
Agent schema 验证的直接链接

在 Agent 上定义 requestContextSchema 后,会在 generate()stream() 开始时验证上下文。如果验证失败,Agent 会在发出任何 LLM 调用之前抛出 MastraError

src/mastra/agents/validated-agent.ts
import { Agent } from '@mastra/core/agent'
import { z } from 'zod'

export const validatedAgent = new Agent({
id: 'validated-agent',
name: 'Validated Agent',
requestContextSchema: z.object({
userId: z.string(),
apiKey: z.string(),
}),
instructions: ({ requestContext }) => {
// Access all values as a typed object
const { userId, apiKey } = requestContext.all
// { userId: string; apiKey: string }

// Or retrieve individual values with .get()
const id = requestContext.get('userId')
// string

return `You are helping user ${userId}`
},
model: 'openai/gpt-5.6-sol',
})

验证失败时,错误会包含 Agent ID 和验证失败字段的详细信息:

Request context validation failed for agent 'validated-agent':
- apiKey: Required

Tool schema 验证
Tool schema 验证的直接链接

在 Tool 上定义 requestContextSchema 后,会在运行 execute() 之前验证上下文。与 Agent 不同,Tool 会返回验证错误对象,而不是抛出错误:

src/mastra/tools/validated-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

export const validatedTool = createTool({
id: 'validated-tool',
description: 'A tool that requires authenticated context',
inputSchema: z.object({
query: z.string(),
}),
requestContextSchema: z.object({
userId: z.string(),
}),
execute: async (inputData, context) => {
// Access all values as a typed object
const { userId } = context.requestContext?.all ?? {}
// { userId: string }

// Or retrieve individual values with .get()
const id = context.requestContext?.get('userId')
// string | undefined

return { result: `Processed for ${userId}` }
},
})

验证失败时,Tool 会返回错误对象,而不是抛出错误:

{
"error": true,
"message": "Request context validation failed for validated-tool. Please fix the following errors and try again:\n- userId: Required\n\nProvided context: {}"
}

Workflow schema 验证
Workflow schema 验证的直接链接

在 Workflow 上定义 requestContextSchema 后,会在 run.start() 开始时验证上下文。如果验证失败,Workflow 会在执行任何步骤之前抛出错误。

src/mastra/workflows/validated-workflow.ts
import { createWorkflow, createStep } from '@mastra/core/workflows'
import { z } from 'zod'

// Define schema once and share between workflow and steps
const workflowContextSchema = z.object({
tenantId: z.string(),
})

const step1 = createStep({
id: 'step-1',
inputSchema: z.object({ message: z.string() }),
outputSchema: z.object({ result: z.string() }),
// Add schema to step for type inference
requestContextSchema: workflowContextSchema,
execute: async ({ inputData, requestContext }) => {
// Access all values as a typed object
const { tenantId } = requestContext.all
// { tenantId: string }

// Or retrieve individual values with .get()
const id = requestContext.get('tenantId')
// string

return { result: `Processed for tenant ${tenantId}` }
},
})

export const validatedWorkflow = createWorkflow({
id: 'validated-workflow',
inputSchema: z.object({ message: z.string() }),
outputSchema: z.object({ result: z.string() }),
requestContextSchema: workflowContextSchema,
})
.then(step1)
.commit()

验证失败时,Workflow 会抛出错误:

Request context validation failed for workflow 'validated-workflow':
- tenantId: Required

步骤也可以定义自己的 requestContextSchema 以进行步骤级验证。步骤验证会在该步骤的 execute() 函数之前运行。

验证行为
验证行为的直接链接

组件属性验证时机失败时
AgentrequestContextSchemagenerate() / stream() 开始时抛出 MastraError
ToolrequestContextSchemaexecute() 之前返回错误对象
WorkflowrequestContextSchemarun.start() 开始时抛出 Error
步骤requestContextSchema步骤 execute() 之前步骤因错误而失败

最佳实践
最佳实践的直接链接

与中间件匹配:在 schema 中定义与中间件所设置字段相同的必填字段。这样,中间件与组件之间的契约便会明确并经过验证。

// Middleware sets these fields
requestContext.set('userId', user.id)
requestContext.set('tenantId', tenant.id)

// Schema validates they exist
requestContextSchema: z.object({
userId: z.string(),
tenantId: z.string(),
})

对条件上下文使用可选字段:对不一定始终存在的值使用 .optional()

requestContextSchema: z.object({
userId: z.string(), // Always required
experimentVariant: z.string().optional(), // May not be set
})

处理 Tool 验证错误:由于 Tool 返回错误对象而不是抛出错误,因此当 Tool 执行至关重要时,请在 Agent 或 Workflow 逻辑中检查错误。