跳至主要內容

請求上下文

Agent、Tool 及 Workflow 均可接受 RequestContext 作為參數,讓底層基本元件可以使用特定請求的值。

何時使用 RequestContext
when-to-use-requestcontext 的直接連結

當基本元件的行為需要根據運行時條件而改變時,請使用 RequestContext。例如,你可以根據用戶屬性切換模型或儲存後端,亦可根據語言調整指示及 Tool 選擇。

備註

RequestContext 主要用於將資料傳入特定請求。它與 Agent 記憶不同,後者負責處理多次呼叫之間的對話記錄及狀態持久化。

設定值
設定值 的直接連結

requestContext 傳入 Agent、網絡、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 檔案中定義預設設定,並將其載入 Studio,方法是使用 --request-context-presets CLI 旗標。這會在 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 }) => {},
})

你亦可以將 requestContext 用於其他選項,例如 agentsworkflowsscorersinputProcessorsoutputProcessors

動態指示
動態指示 的直接連結

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

從提示註冊服務擷取資料
從提示註冊服務擷取資料 的直接連結

如果你的機構使用提示註冊服務來集中管理提示,你可以在運行時擷取指示。你可以在毋須重新部署的情況下更新提示及使用不同版本進行實驗,並追蹤各個 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。伺服器會驗證所存取的執行緒是否屬於此資源;如不屬於,則傳回 403。
MASTRA_THREAD_ID_KEY強制執行緒操作使用此執行緒 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 Schema(例如 ZodValibotArkType 等),以便在運行時驗證請求上下文的值。這可及早找出遺漏或無效的上下文值並提供清晰的錯誤訊息,同時讓你在元件中進行類型推斷。

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() 前驗證上下文。Tool 與 Agent 不同,它會傳回驗證錯誤物件,而非擲出錯誤:

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 邏輯中檢查錯誤。