본문으로 건너뛰기

요청 컨텍스트

Agent, Tool, Workflow는 모두 허용 가능RequestContext매개변수로 요청별 값을 기본 프리미티브에 사용할 수 있도록 합니다.

언제 사용하나요?RequestContext
when-to-use-requestcontext에 대한 직접 링크

사용RequestContext 런타임 조건에 따라 프리미티브의 동작을 변경해야 할 때 사용합니다. 예를 들어 사용자 속성에 따라 Model이나 스토리지 백엔드를 전환하거나, 언어에 따라 지침 및 Tool 선택을 조정할 수 있습니다.

노트

RequestContext주로 특정 요청에 데이터를 전달하는 데 사용됩니다. 여러 호출에 걸쳐 대화 기록과 상태 지속성을 처리하는 Agent Memory와는 다릅니다.

설정값
설정값에 대한 직접 링크

통과하다requestContext 를 Agent, 네트워크, Workflow 또는 Tool 호출에 전달하여 실행 중 모든 하위 프리미티브에서 값을 사용할 수 있도록 하세요. 다음을 사용하세요: .set() to define values before making the call.

그만큼.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 })

요청 헤더를 기반으로 값 설정
요청 헤더를 기반으로 값 설정에 대한 직접 링크

채울 수 있습니다requestContext 런타임 서버 미들웨어에서 요청의 정보를 추출하여 설정하세요. 이 예제에서 temperature-unit is set based on the Cloudflare CF-IPCountry 헤더를 사용하여 응답이 사용자의 로캘과 일치하도록 합니다.

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

방문하다Middleware for how to use server middleware.

사진관
사진관에 대한 직접 링크

로컬에서 개발할 때 JSON 파일에 사전 설정을 정의하고 이를Studio with the --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를 통해 값에 액세스에 대한 직접 링크

당신은 액세스할 수 있습니다requestContext 인수를 Agent에서 지원되는 모든 구성 옵션으로부터 받을 수 있습니다. 이러한 함수는 동기식 또는 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 with other options like agents, workflows, scorers, inputProcessors, and outputProcessors.

동적 지침
동적 지침에 대한 직접 링크

Agent 지침은 비동기 기능으로 제공될 수 있으므로 런타임 시 Prompt를 해결할 수 있습니다. 와 결합requestContext, this enables patterns like:

  • 개인화: 사용자 속성, 선호도 또는 계층에 따라 지침을 맞춤화합니다.
  • 현지화: 지역에 따라 어조, 언어, 행동을 조정합니다.
  • A/B 테스트: 실험을 위해 다양한 Prompt 변형을 제공합니다.
  • 외부 Prompt 관리: 재배포하지 않고 레지스트리 서비스에서 Prompt를 가져옵니다.
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',
})

Prompt 레지스트리에서 가져오기
Prompt 레지스트리에서 가져오기에 대한 직접 링크

조직에서 중앙 Prompt 관리를 위해 Prompt 레지스트리 서비스를 사용하는 경우 런타임에 지침을 가져올 수 있습니다. 재배포하지 않고도 Prompt를 업데이트하고 변형 실험을 실행할 수 있으며 Agent 전체에서 Prompt 사용량을 추적할 수 있습니다.

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 for a full list of configuration options.

Workflow 단계에서 값에 액세스
Workflow 단계에서 값에 액세스에 대한 직접 링크

당신은 액세스할 수 있습니다requestContext argument from a workflow step's execute 함수입니다. 이 함수는 동기식 또는 비동기식일 수 있습니다. 다음을 사용하세요: .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') {
}
},
})

방문하다createStep() for a full list of configuration options.

Tool을 사용하여 값에 액세스
Tool을 사용하여 값에 액세스에 대한 직접 링크

당신은 액세스할 수 있습니다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') {
}
},
})

방문하다createTool() for a full list of configuration options.

예약된 키
예약된 키에 대한 직접 링크

Mastra는 보안 목적으로 특수 컨텍스트 키를 예약합니다. 설정된 경우 이러한 키는 클라이언트가 제공한 값보다 우선합니다. 사용자가 자신이 소유하지 않은 리소스에 액세스하려고 하면 서버는 자동으로 소유권을 확인하고 403 오류를 반환합니다.

가장 쉬운 설정 방법MASTRA_RESOURCE_ID_KEY is via the mapUserToResourceId callback in auth config:

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

리소스 ID가 이런 방식으로 파생되면 클라이언트는 생략할 수 있습니다.memory.resource 가 Agent의 generate 및 stream 요청 본문에 있더라도 서버에서 파생된 값이 대신 사용되며, 클라이언트가 제공한 값보다 항상 우선합니다. 요청에서 Memory를 사용하고 본문과 요청 컨텍스트 모두 리소스 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모든 Memory 작업에서 이 리소스 ID를 사용하도록 강제합니다. 서버는 접근한 스레드가 이 리소스에 속하는지 검증하며, 속하지 않으면 403을 반환합니다.
MASTRA_THREAD_ID_KEY클라이언트가 제공한 값을 재정의하여 스레드 작업에서 이 스레드 ID를 사용하도록 강제합니다.

이러한 키는 다중 테넌트 애플리케이션에서 사용자 격리를 구현하는 데 사용됩니다. 보다Authorization middleware for usage examples.

타입스크립트 지원
타입스크립트 지원에 대한 직접 링크

유형 매개변수를 제공하는 경우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())
}
}

스키마 검증
스키마 검증에 대한 직접 링크

사용requestContextSchema to define a Standard JSON Schema (Zod, Valibot, ArkType, 등)는 런타임에 요청 컨텍스트 값을 검증합니다. 이를 통해 누락되거나 유효하지 않은 컨텍스트 값을 조기에 포착하고 명확한 오류 메시지를 제공하며, 컴포넌트 내에서 타입 추론도 사용할 수 있습니다.

Agent 스키마 검증
Agent 스키마 검증에 대한 직접 링크

정의할 때requestContextSchema 를 Agent에 설정하면 다음이 시작될 때 컨텍스트가 검증됩니다: generate() or stream(). If validation fails, the agent throws a MastraError before any LLM calls are made.

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 스키마 검증
Tool 스키마 검증에 대한 직접 링크

정의할 때requestContextSchema on a tool, the context is validated before 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 스키마 검증
Workflow 스키마 검증에 대한 직접 링크

정의할 때requestContextSchema 를 Workflow에 설정하면 다음이 시작될 때 컨텍스트가 검증됩니다: 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() function.

검증 동작
검증 동작에 대한 직접 링크

구성요소부동산검증 시기실패 시
AgentrequestContextSchemaStart of generate() / stream()Throws MastraError
ToolrequestContextSchemaBefore execute()Returns error object
WorkflowrequestContextSchemaStart of run.start()Throws Error
SteprequestContextSchemaBefore step execute()Step fails with error

모범 사례
모범 사례에 대한 직접 링크

미들웨어를 일치시키세요: 미들웨어가 설정한 것과 동일한 필수 필드를 스키마에 정의합니다. 결과적으로 미들웨어와 구성 요소 간의 계약은 명시적이고 검증됩니다.

// 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() for values that may not always be present.

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

Tool 유효성 검사 오류 처리: Tool은 오류 개체를 던지는 대신 반환하므로 Tool 실행이 중요한 경우 Agent 또는 Workflow 논리에서 오류를 확인하세요.