생성Tool()
그만큼createTool()기능은 Mastra Agent가 실행할 수 있는 사용자 정의 Tool을 정의하는 데 사용됩니다. Tool은 Agent가 외부 시스템과 상호 작용하거나 계산을 수행할 수 있도록 하여 Agent의 기능을 확장합니다. 특정 데이터에 액세스할 수도 있습니다.
사용예사용예에 대한 직접 링크
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
})
첫 번째 execute 매개변수는 inputSchema에서 검증된 값입니다. { location } 예시처럼 함수 시그니처에서 스키마 필드를 직접 구조 분해하세요. 선택적인 두 번째 매개변수에는 실행 컨텍스트가 포함됩니다.
매개변수매개변수에 대한 직접 링크
id:
description:
inputSchema?:
execute 함수에 필요한 입력 매개변수를 정의하는 Standard JSON Schema입니다.outputSchema?:
execute 함수에서 예상되는 출력 구조를 정의하는 Standard JSON Schema입니다.strict?:
toModelOutput?:
execute 출력을 Model로 다시 보내기 전에 변환하는 선택적 함수입니다. 애플리케이션 코드에는 전체 원시 출력을 유지하면서 text, json 또는 content 형태의 출력(이미지/파일 같은 멀티모달 부분 포함)을 Model에 반환할 때 사용하세요.transform?:
input, inputDelta, output, error, approval, suspend, resume 등의 단계에 대해 display 및 transcript 변환을 구성하세요.suspendSchema?:
suspend()에 전달되는 페이로드의 구조를 정의하는 Standard JSON Schema입니다. Tool이 실행을 일시 중단하면 이 페이로드가 클라이언트에 반환됩니다.resumeSchema?:
resumeData 구조를 정의하는 Standard JSON Schema입니다. autoResumeSuspendedTools가 활성화된 경우 Agent가 사용자 메시지에서 데이터를 추출하는 데 사용합니다.requireApproval?:
tool-call-approval 청크를 방출하고 승인되거나 거부될 때까지 일시 중지합니다.mcp?:
annotations(title, readOnlyHint, destructiveHint, idempotentHint, openWorldHint 같은 Tool 동작 힌트)와 _meta(MCP 클라이언트로 그대로 전달되는 임의의 메타데이터)를 포함합니다.requestContextSchema?:
providerOptions?:
anthropic 또는 openai 같은 Provider 이름이고, 값은 Provider별 구성 객체입니다.inputExamples?:
background?:
execute?:
execute를 제공하지만, 다른 위치에서 실행되거나 조정되는 Tool 정의에서는 생략할 수 있도록 타입이 허용합니다. 두 매개변수를 받습니다. 첫 번째는 inputSchema를 기반으로 검증된 입력 데이터이고, 두 번째는 requestContext, abortSignal 및 기타 실행 메타데이터를 포함하는 실행 컨텍스트 객체입니다.input:
context?:
requestContext?:
abortSignal?:
agent?:
workflow?:
mcp?:
observe:
span은 함수를 직접 실행하고 log는 아무 작업도 하지 않습니다.onInputStart?:
(options: ToolCallOptions) => void | PromiseLike<void>.onInputDelta?:
({ inputTextDelta, ...options }: { inputTextDelta: string } & ToolCallOptions) => void | PromiseLike<void>.onInputAvailable?:
({ input, ...options }: { input: TSchemaIn } & ToolCallOptions) => void | PromiseLike<void>.onOutput?:
({ output, toolName, ...options }: { output: TSchemaOut; toolName: string } & Omit<ToolCallOptions, 'messages'>) => void | PromiseLike<void>.런타임에 채워지는 mastra 및 mcpMetadata 필드는 소스 타입에 나타나지만 Mastra 또는 MCP 어댑터에서 설정합니다. 일반적인 createTool() 사용 시에는 이를 구성할 필요가 없습니다.
보고보고에 대한 직접 링크
createTool() 함수는 Tool 객체를 반환합니다.
Tool:
스키마 정의스키마 정의에 대한 직접 링크
Standard JSON Schema를 지원하는 모든 라이브러리로 Tool의 inputSchema 및 outputSchema를 정의할 수 있습니다. 여기에는 Zod, Valibot, ArkType 같은 라이브러리가 포함됩니다.
- Zod
- Valibot
- ArkType
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Fetches weather for a location',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return { location, temperatureCelsius: 21, conditions: 'sunny' }
},
})
import { createTool } from '@mastra/core/tools'
import * as v from 'valibot'
import { toStandardJsonSchema } from '@valibot/to-json-schema'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Fetches weather for a location',
inputSchema: toStandardJsonSchema(
v.object({
location: v.string(),
}),
),
outputSchema: toStandardJsonSchema(
v.object({
location: v.string(),
temperatureCelsius: v.number(),
conditions: v.string(),
}),
),
execute: async ({ location }) => {
return { location, temperatureCelsius: 21, conditions: 'sunny' }
},
})
import { createTool } from '@mastra/core/tools'
import { type } from 'arktype'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Fetches weather for a location',
inputSchema: type({
location: 'string',
}),
outputSchema: type({
location: 'string',
temperatureCelsius: 'number',
conditions: 'string',
}),
execute: async ({ location }) => {
return { location, temperatureCelsius: 21, conditions: 'sunny' }
},
})
엄격한 Tool 입력의 예엄격한 Tool 입력의 예에 대한 직접 링크
Mastra가 지원되는 Model Provider에 Tool 스키마와 정확히 일치하는 Tool 인수를 생성하도록 요청하게 하려면 strict: true를 설정하세요.
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
strict: true,
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
})
Mastra는 엄격한 Tool 호출을 지원하는 Model 어댑터에 strict: true를 전달합니다. 엄격한 Tool 호출을 지원하지 않는 어댑터에서는 Mastra가 이 옵션을 무시합니다.
예toModelOutputexample-with-tomodeloutput에 대한 직접 링크
Tool이 앱에는 풍부한 내부 데이터를 반환하되 Model에는 단순화된 값이나 멀티모달 콘텐츠를 전달해야 할 때 toModelOutput을 사용하세요.
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
radarImageUrl: z.string().url(),
}),
execute: async ({ location }) => ({
location,
temperatureCelsius: 21,
conditions: 'sunny',
radarImageUrl: 'https://example.com/radar/seattle.png',
}),
toModelOutput: output => {
return {
type: 'content',
value: [
{
type: 'text',
text: `${output.location}: ${output.temperatureCelsius}°C and ${output.conditions}`,
},
{ type: 'image-url', url: output.radarImageUrl },
],
}
},
})
Tool은 여전히 전체 execute 결과를 애플리케이션에 반환하지만, Model은 변환된 toModelOutput 값을 받습니다.
toModelOutput다음을 반환할 수 있습니다:
type: 'text'type: 'json'text,image-url,image-data,file-url,file-data,file-id,image-file-id또는custom같은 부분으로 구성된type: 'content'
예transformexample-with-transform에 대한 직접 링크
Tool이 런타임 동작을 위해 원시 입력이나 출력을 유지하되 표시 스트림이나 대화 기록 메시지에는 더 작거나 안전한 형태를 전달해야 할 때 transform을 사용하세요.
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const customerTool = createTool({
id: 'lookup-customer',
description: 'Looks up a customer',
inputSchema: z.object({
customerId: z.string(),
internalPath: z.string(),
}),
outputSchema: z.object({
displayName: z.string(),
apiKey: z.string(),
debugScore: z.number(),
}),
execute: async () => {
return {
displayName: 'Acme',
apiKey: 'secret-value',
debugScore: 0.97,
}
},
transform: {
display: {
input: ({ input }) => ({ customerId: input?.customerId }),
output: ({ output }) => ({ displayName: output?.displayName }),
error: () => ({ message: 'Customer lookup failed' }),
},
transcript: {
input: ({ input }) => ({ customerId: input?.customerId }),
output: ({ output }) => ({ displayName: output?.displayName }),
error: () => ({ message: 'Customer lookup failed' }),
},
},
})
Tool은 여전히 원시 inputSchema 값을 받고 원시 execute 결과를 반환합니다. Mastra는 스트리밍되는 UI 페이로드에 display 변환을 적용하고 사용자에게 표시되는 대화 기록 메시지에 transcript 변환을 적용합니다.
MCP 주석의 예MCP 주석의 예에 대한 직접 링크
MCP(Model 컨텍스트 프로토콜)를 통해 Tool을 노출할 때 주석을 추가하여 Tool 동작을 설명하고 클라이언트가 Tool을 표시하는 방법을 사용자 지정할 수 있습니다. 이러한 MCP 관련 속성은 다음 아래에 그룹화되어 있습니다.mcp property:
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string().describe('City name or coordinates'),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
// MCP-specific properties
mcp: {
// Annotations for client behavior hints
annotations: {
title: 'Weather Lookup', // Human-readable display name
readOnlyHint: true, // Tool doesn't modify environment
destructiveHint: false, // Tool doesn't perform destructive updates
idempotentHint: true, // Same args = same result
openWorldHint: true, // Interacts with external API
},
// Custom metadata for client-specific functionality
_meta: {
version: '1.0.0',
category: 'weather',
},
},
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
})
Tool 수명주기 후크Tool 수명주기 후크에 대한 직접 링크
Tool은 Tool 실행의 다양한 단계를 모니터링하고 대응할 수 있는 수명 주기 후크를 지원합니다. 이러한 후크는 스트리밍 중 로깅, 분석, 검증 및 실시간 업데이트에 특히 유용합니다.
다음 예에서는 모든 수명 주기 후크가 구성된 Tool을 보여줍니다.
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
onInputStart: ({ toolCallId }) => {
console.log(`Tool call ${toolCallId} input started`)
},
onInputDelta: ({ inputTextDelta, toolCallId }) => {
console.log(`Tool call ${toolCallId} received input chunk: ${inputTextDelta}`)
},
onInputAvailable: ({ input, toolCallId }) => {
console.log(`Tool call ${toolCallId} received location: ${input.location}`)
},
onOutput: ({ output, toolCallId, toolName }) => {
console.log(`Tool ${toolName} call ${toolCallId} returned conditions: ${output.conditions}`)
},
})
사용 가능한 후크사용 가능한 후크에 대한 직접 링크
onInputStartoninputstart에 대한 직접 링크
입력 데이터가 수신되기 전에 Tool 호출 입력 스트리밍이 시작될 때 호출됩니다.
export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
onInputStart: ({ toolCallId, messages, abortSignal }) => {
console.log(`Tool ${toolCallId} input streaming started`)
},
})
onInputDeltaoninputdelta에 대한 직접 링크
스트리밍되는 입력 텍스트의 각 증분 청크에 대해 호출됩니다. 실시간 진행률을 표시하거나 부분 JSON을 구문 분석하는 데 유용합니다.
export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
onInputDelta: ({ inputTextDelta, toolCallId, messages, abortSignal }) => {
console.log(`Received input chunk: ${inputTextDelta}`)
},
})
onInputAvailableoninputavailable에 대한 직접 링크
전체 Tool 입력이 사용 가능하고 구문 분석 및 검증되었을 때 호출됩니다.inputSchema.
export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
inputSchema: z.object({
location: z.string(),
}),
onInputAvailable: ({ input, toolCallId, messages, abortSignal }) => {
console.log(`Tool received complete input:`, input)
// input is fully typed based on inputSchema
},
})
onOutputonoutput에 대한 직접 링크
Tool이 성공적으로 실행되고 출력을 반환한 후에 호출됩니다. 결과 로깅, 후속 조치 트리거 또는 분석에 유용합니다.
export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
outputSchema: z.object({
result: z.string(),
}),
execute: async input => {
return { result: 'Success' }
},
onOutput: ({ output, toolCallId, toolName, abortSignal }) => {
console.log(`${toolName} execution completed:`, output)
// output is fully typed based on outputSchema
},
})
Hook 실행 순서Hook 실행 순서에 대한 직접 링크
일반적인 스트리밍 Tool 호출의 경우 후크는 다음 순서로 호출됩니다.
- onInputStart: 입력 스트리밍이 시작됩니다.
- onInputDelta: 청크가 도착하면 여러 번 호출됩니다.
- onInput 사용 가능: 완전한 입력이 구문 분석되고 검증됩니다.
- Toolexecute function runs
- onOutput: Tool이 성공적으로 완료되었습니다.
후크 매개변수후크 매개변수에 대한 직접 링크
후크 콜백은 다음과 같은 소스 지원 매개변수 형태를 받습니다.
onInputStart:toolCallId,messages,abortSignal등의 필드를 포함하는ToolCallOptions를 받습니다.onInputDelta:{ inputTextDelta: string } & ToolCallOptions를 받습니다.onInputAvailable:{ input: TSchemaIn } & ToolCallOptions를 받으며,input의 타입은inputSchema에서 지정됩니다.onOutput:{ output: TSchemaOut; toolName: string } & Omit<ToolCallOptions, 'messages'>를 받으며,output의 타입은outputSchema에서 지정됩니다. 이 훅은messages를 받지 않습니다.
오류 처리오류 처리에 대한 직접 링크
후크 오류는 자동으로 포착되어 기록되지만 Tool 실행이 계속되는 것을 방해하지는 않습니다. 후크에서 오류가 발생하면 콘솔에 기록되지만 Tool 호출은 실패하지 않습니다.
MCP Tool 주석MCP Tool 주석에 대한 직접 링크
MCP(Model Context Protocol)를 통해 Tool을 노출할 때 Tool 동작을 설명하는 주석을 제공할 수 있습니다. 이러한 주석은 OpenAI Apps SDK와 같은 MCP 클라이언트가 Tool을 표시하고 처리하는 방법을 이해하는 데 도움이 됩니다.
MCP 관련 속성은 annotations와 _meta를 포함하는 mcp 속성 아래에 그룹화됩니다.
mcp: {
annotations: { /* behavior hints */ },
_meta: { /* custom metadata */ },
}
ToolAnnotations속성toolannotations-properties에 대한 직접 링크
title?:
readOnlyHint?:
destructiveHint?:
idempotentHint?:
openWorldHint?:
이러한 주석은 MCP 사양을 따르며 MCP를 통해 Tool을 나열할 때 그대로 전달됩니다.