본문으로 건너뛰기

Tool

재구성된 컨텍스트 속성과 함께 별도의 입력 및 컨텍스트 매개 변수를 사용하도록 Tool 실행 서명이 업데이트되었습니다.

변경됨
변경됨에 대한 직접 링크

createTool서명을 실행하다(inputData, context) format
createtool-execute-signature-to-inputdata-context-format에 대한 직접 링크

이제 모든 createTool 실행 함수는 구조 분해된 단일 객체 대신 별도의 inputDatacontext 매개변수를 사용하는 시그니처를 따릅니다. 이제 Tool 입력과 실행 컨텍스트가 독립적으로 전달됩니다. 이 시그니처 변경은 createTool에만 적용됩니다. Workflow의 createStep 호출에서는 async (inputData, context) 시그니처를 그대로 사용하세요. 마이그레이션하려면 createTool 시그니처에서 inputData(inputSchema에서 타입 지정)를 첫 번째 매개변수로, context를 두 번째 매개변수로 사용하도록 업데이트하세요.

createTool({
id: 'weather-tool',
- execute: async ({ context, requestContext, mastra }) => {
- const location = context.location;
- const userTier = requestContext.get('userTier');
- return getWeather(location, userTier);
- },
+ execute: async (inputData, context) => {
+ const location = inputData.location;
+ const userTier = context?.requestContext?.get('userTier');
+ return getWeather(location, userTier);
+ },
});

createTool컨텍스트 속성 구성
createtool-context-properties-organization에 대한 직접 링크

이제 createTool의 컨텍스트 속성이 네임스페이스별로 구성됩니다. Agent 관련 속성은 context.agent, Workflow 관련 속성은 context.workflow, MCP 관련 속성은 context.mcp 아래에 있습니다. 이 변경으로 API가 더 체계적이고 명확하게 구성됩니다. Agent 내부에서 실행되는 Tool의 경우 다음을 통해 Agent별 속성에 액세스합니다.context.agent.

createTool({
id: 'suspendable-tool',
suspendSchema: z.object({ message: z.string() }),
resumeSchema: z.object({ approval: z.boolean() }),
- execute: async ({ context, suspend, resumeData }) => {
- if (!resumeData) {
- return await suspend({ message: 'Waiting for approval' });
- }
- if (resumeData.approval) {
- return { success: true };
- }
- },
+ execute: async (inputData, context) => {
+ if (!context?.agent?.resumeData) {
+ return await context?.agent?.suspend({
+ message: 'Waiting for approval',
+ });
+ }
+ if (context.agent.resumeData.approval) {
+ return { success: true };
+ }
+ },
});

Workflow 내부에서 실행되는 Tool의 경우 다음을 통해 Workflow별 속성에 액세스합니다.context.workflow.

createTool({
id: 'workflow-tool',
- execute: async ({ workflowId, runId, state, setState }) => {
- const currentState = state;
- setState({ step: 'completed' });
- return { result: 'done' };
- },
+ execute: async (inputData, context) => {
+ const currentState = context?.workflow?.state;
+ context?.workflow?.setState({ step: 'completed' });
+ return { result: 'done' };
+ },
});

Tool이 실행될 때 suspendPayloadsuspendSchema를 기준으로 검증됩니다. suspendPayload가 suspendSchema와 일치하지 않으면 경고가 기록되고 오류가 Tool 출력으로 반환되지만 일시 중지는 계속됩니다. 또한 Tool이 재개될 때 resumeDataresumeSchema를 기준으로 검증됩니다. resumeData가 resumeSchema와 일치하지 않으면 Tool이 ValidationError를 반환하며 Tool 재개가 차단됩니다. suspendSchema 또는 resumeSchema 검증을 건너뛰려면 Tool을 생성할 때 suspendSchema 또는 resumeSchema를 정의하지 마세요. :::참고 MCP 관련 Tool 컨텍스트 변경 사항은 다음을 참조하세요.MCP migration guide. :::

RuntimeContext에게RequestContext
runtimecontext-to-requestcontext에 대한 직접 링크

Tool 실행 컨텍스트 전반에서 RuntimeContext 클래스의 이름이 RequestContext로 변경되었습니다. 새 이름은 이 클래스가 요청별 데이터를 나타낸다는 점을 명확히 합니다. 마이그레이션하려면 Tool 실행 함수에서 runtimeContext 참조를 requestContext로 변경하세요.

createTool({
id: 'my-tool',
execute: async (inputData, context) => {
- const userTier = context?.runtimeContext?.get('userTier');
+ const userTier = context?.requestContext?.get('userTier');
return { result: userTier };
},
});

:::tip[코드모드]

Mastra의 codemod CLI를 사용하여 가져오기를 자동으로 업데이트할 수 있습니다.

npx @mastra/codemod@latest v1/runtime-context .

:::

이는 직접 호출하든 Agent 및 Workflow를 통해 호출하든 상관없이 모든 Tool 실행에 적용됩니다. 유형 축소를 통해 유효성 검사 오류를 적절하게 처리하고 출력 속성에 액세스할 때 런타임 오류를 방지할 수 있습니다.

Tool 출력 검증outputSchema
tool-output-validation-with-outputschema에 대한 직접 링크

이제 Tool의 outputSchema가 런타임에 반환 값을 검증합니다. 이전에는 outputSchema가 타입 추론에만 사용되었으며 출력은 검증되지 않았습니다. Tool이 outputSchema와 일치하지 않는 데이터를 반환하면 이제 잘못된 데이터 대신 ValidationError를 반환합니다. 유효성 검사 오류를 수정하려면 Tool의 출력이 스키마 정의와 일치하는지 확인하세요.

const getUserTool = createTool({
id: "get-user",
outputSchema: z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
}),
execute: async (inputData) => {
- return { id: "123", name: "John" }; // Missing email
+ return { id: "123", name: "John", email: "john@example.com" };
},
});

검증에 실패하면 Tool은ValidationError:

+ // Before v1 - invalid output would silently pass through
await getUserTool.execute({});
- // { id: "123", name: "John" } - missing email
+ // {
+ // error: true,
+ // message: "Tool output validation failed for get-user. The tool returned invalid output:\n- email: Required\n\nReturned output: {...}",
+ // validationErrors: { ... }
+ // }

tool.execute반환 유형에는 다음이 포함됩니다.ValidationError
toolexecute-return-type-includes-validationerror에 대한 직접 링크

이제 tool.execute의 반환 타입에 검증 실패를 처리하기 위한 ValidationError가 포함됩니다. TypeScript의 타입 검사를 충족하려면 출력 스키마 속성에 액세스하기 전에 결과 타입을 좁혀야 합니다. tool.execute를 호출할 때는 출력 속성에 액세스하기 전에 결과에 오류가 포함되어 있는지 확인하세요.

const result = await getUserTool.execute({})

// Type-safe check for validation errors
if ('error' in result && result.error) {
console.error('Validation failed:', result.message)
console.error('Details:', result.validationErrors)
return
}

// TypeScript knows result is valid here
console.log(result.id, result.name, result.email)

또는 실제 출력과 일치하도록 outputSchema를 업데이트하거나, 검증이 필요하지 않다면 outputSchema를 완전히 제거하세요.

직접 Tool 실행
직접 Tool 실행에 대한 직접 링크

클라이언트 측 Tool 정의처럼 실행 로직이 별도로 처리되는 경우를 지원하기 위해 타입 시스템에서 tool.execute 속성은 선택 사항입니다. Agent나 Workflow를 통하지 않고 Tool 인스턴스에서 execute를 직접 호출할 때는 옵셔널 체이닝 또는 non-null 단언을 사용하세요.

// Optional chaining (recommended)
const result = await weatherTool.execute?.({ location: 'New York' }, {})

// Non-null assertion (when you know execute exists)
const result = await weatherTool.execute!({ location: 'New York' }, {})