Mastra는 의존성 주입을 기반으로 한 시스템인 RuntimeContext를 제공하여, 실행 중에 도구에 동적이고 요청별 구성을 전달할 수 있게 해줍니다. 이는 도구의 핵심 코드를 변경하지 않으면서 사용자 신원, 요청 헤더 또는 기타 런타임 요소에 따라 도구의 동작이 변경되어야 할 때 유용합니다.
참고: RuntimeContext는 주로 도구 실행에 데이터를 전달하는 데 사용됩니다. 여러 호출 간의 대화 기록과 상태 지속성을 처리하는 에이전트 메모리와는 별개입니다.
기본 사용법
RuntimeContext를 사용하려면 먼저 동적 구성을 위한 타입 구조를 정의합니다. 그 다음 정의한 타입으로 RuntimeContext의 인스턴스를 생성하고 원하는 값을 설정합니다. 마지막으로 agent.generate() 또는 agent.stream()을 호출할 때 옵션 객체에 runtimeContext 인스턴스를 포함합니다.
import { RuntimeContext } from "@mastra/core/di";
// 'agent'는 이미 정의된 Mastra Agent 인스턴스라고 가정
// 컨텍스트 타입 정의
type WeatherRuntimeContext = {
"temperature-scale": "celsius" | "fahrenheit";
};
// RuntimeContext를 인스턴스화하고 값 설정
const runtimeContext = new RuntimeContext<WeatherRuntimeContext>();
runtimeContext.set("temperature-scale", "celsius");
// 에이전트 호출에 전달
const response = await agent.generate("오늘 날씨는 어때요?", {
runtimeContext, // 여기서 컨텍스트 전달
});
console.log(response.text);
도구에서 컨텍스트 접근하기
도구는 execute 함수의 두 번째 인수의 일부로 runtimeContext를 받습니다. 그 다음 .get() 메소드를 사용하여 값을 검색할 수 있습니다.
src/mastra/tools/weather-tool.ts:
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
// WeatherRuntimeContext가 위에서 정의되고 여기서 접근 가능하다고 가정
// 더미 fetch 함수
async function fetchWeather(
location: string,
options: { temperatureUnit: "celsius" | "fahrenheit" },
): Promise<any> {
console.log(`${location}의 날씨를 ${options.temperatureUnit} 단위로 가져오는 중`);
// 실제 API 호출로 교체
return { temperature: options.temperatureUnit === "celsius" ? 20 : 68 };
}
export const weatherTool = createTool({
id: "getWeather",
description: "특정 위치의 현재 날씨 정보를 가져옵니다",
inputSchema: z.object({
location: z.string().describe("날씨를 확인할 위치"),
}),
// 도구의 execute 함수는 runtimeContext를 받습니다
execute: async ({ context, runtimeContext }) => {
// runtimeContext 변수에 타입 안전한 접근
const temperatureUnit = runtimeContext.get("temperature-scale");
// 도구 로직에서 컨텍스트 값 사용
const weather = await fetchWeather(context.location, {
temperatureUnit,
});
return {
result: `온도는 ${weather.temperature}°${temperatureUnit === "celsius" ? "C" : "F"}입니다`,
};
},
});
에이전트가 weatherTool을 사용할 때, agent.generate() 호출 중에 runtimeContext에서 설정된 temperature-scale 값이 도구의 execute 함수 내에서 사용할 수 있게 됩니다.
서버 미들웨어와 함께 사용하기
서버 환경(Express나 Next.js 같은)에서는 미들웨어를 사용하여 헤더나 사용자 세션과 같은 들어오는 요청 데이터를 기반으로 RuntimeContext를 자동으로 채울 수 있습니다.
다음은 Cloudflare CF-IPCountry 헤더를 기반으로 온도 척도를 설정하기 위해 Mastra의 내장 서버 미들웨어 지원(내부적으로 Hono 사용)을 사용하는 예제입니다:
src/mastra/index.ts:
import { Mastra } from "@mastra/core";
import { RuntimeContext } from "@mastra/core/di";
import { weatherAgent } from "./agents/weather"; // 에이전트가 다른 곳에서 정의되었다고 가정
// RuntimeContext 타입 정의
type WeatherRuntimeContext = {
"temperature-scale": "celsius" | "fahrenheit";
};
export const mastra = new Mastra({
agents: {
weather: weatherAgent,
},
server: {
middleware: [
async (c, next) => {
// RuntimeContext 인스턴스 가져오기
const runtimeContext =
c.get<RuntimeContext<WeatherRuntimeContext>>("runtimeContext");
// 요청 헤더에서 국가 코드 가져오기
const country = c.req.header("CF-IPCountry");
// 국가에 따라 온도 척도 설정
runtimeContext.set(
"temperature-scale",
country === "US" ? "fahrenheit" : "celsius",
);
// 요청 처리 계속
await next();
},
],
},
});
이 미들웨어가 적용되면, 이 Mastra 서버 인스턴스에서 처리되는 모든 에이전트 호출은 사용자의 추정 국가를 기반으로 RuntimeContext에 temperature-scale이 자동으로 설정되며, weatherTool과 같은 도구들이 이를 적절히 사용하게 됩니다.
2025년 7월 26일 기준 번역
by dongne.lab@gmail.com