본문으로 건너뛰기

생성Tool()

그만큼createTool()기능은 Mastra Agent가 실행할 수 있는 사용자 정의 Tool을 정의하는 데 사용됩니다. Tool은 Agent가 외부 시스템과 상호 작용하거나 계산을 수행할 수 있도록 하여 Agent의 기능을 확장합니다. 특정 데이터에 액세스할 수도 있습니다.

사용예
사용예에 대한 직접 링크

src/mastra/tools/weather-tool.ts
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:

string
Tool의 고유 식별자입니다.

description:

string
Tool이 수행하는 작업에 대한 설명입니다. Agent는 이 설명을 사용하여 Tool을 언제 사용할지 결정합니다.

inputSchema?:

StandardJSONSchemaV1
Tool의 execute 함수에 필요한 입력 매개변수를 정의하는 Standard JSON Schema입니다.

outputSchema?:

StandardJSONSchemaV1
Tool의 execute 함수에서 예상되는 출력 구조를 정의하는 Standard JSON Schema입니다.

strict?:

boolean
true이면 Mastra가 이를 지원하는 Model 어댑터에서 엄격한 Tool 입력 생성을 활성화합니다. 이를 통해 지원되는 Provider가 Tool 스키마에 더 잘 맞는 인수를 반환할 수 있습니다.

toModelOutput?:

(output: TSchemaOut) => unknown
Tool의 execute 출력을 Model로 다시 보내기 전에 변환하는 선택적 함수입니다. 애플리케이션 코드에는 전체 원시 출력을 유지하면서 text, json 또는 content 형태의 출력(이미지/파일 같은 멀티모달 부분 포함)을 Model에 반환할 때 사용하세요.

transform?:

ToolPayloadTransform
Tool 페이로드가 런타임을 떠나 표시 스트림이나 사용자에게 보이는 트랜스크립트 메시지로 전달되기 전에 적용되는 선택적 대상 인식 변환입니다. input, inputDelta, output, error, approval, suspend, resume 등의 단계에 대해 displaytranscript 변환을 구성하세요.

suspendSchema?:

StandardJSONSchemaV1
suspend()에 전달되는 페이로드의 구조를 정의하는 Standard JSON Schema입니다. Tool이 실행을 일시 중단하면 이 페이로드가 클라이언트에 반환됩니다.

resumeSchema?:

StandardJSONSchemaV1
Tool이 재개될 때 예상되는 resumeData 구조를 정의하는 Standard JSON Schema입니다. autoResumeSuspendedTools가 활성화된 경우 Agent가 사용자 메시지에서 데이터를 추출하는 데 사용합니다.

requireApproval?:

boolean
true이면 Tool을 실행하기 전에 명시적인 승인이 필요합니다. Agent는 tool-call-approval 청크를 방출하고 승인되거나 거부될 때까지 일시 중지합니다.

mcp?:

MCPToolProperties
Model Context Protocol을 통해 노출되는 Tool의 MCP 전용 속성입니다. annotations(title, readOnlyHint, destructiveHint, idempotentHint, openWorldHint 같은 Tool 동작 힌트)와 _meta(MCP 클라이언트로 그대로 전달되는 임의의 메타데이터)를 포함합니다.

requestContextSchema?:

StandardJSONSchemaV1
요청 컨텍스트 값을 검증하기 위한 Standard JSON Schema입니다. 제공하면 execute()가 실행되기 전에 컨텍스트를 검증하고, 검증에 실패하면 오류 객체를 반환합니다.

providerOptions?:

Record<string, Record<string, unknown>>
이 Tool을 사용할 때 Model에 전달되는 Provider별 옵션입니다. 키는 anthropic 또는 openai 같은 Provider 이름이고, 값은 Provider별 구성 객체입니다.

inputExamples?:

Array<{ input: Record<string, unknown> }>
지원되는 Model Provider가 입력 예시로 사용할 수 있는 유효한 Tool 입력의 예시입니다.

background?:

ToolBackgroundConfig
이 Tool의 백그라운드 작업 구성입니다. 활성화하면 Agent 대화가 계속되는 동안 Tool을 백그라운드에서 실행할 수 있습니다.

execute?:

function
Tool의 로직을 포함하는 함수입니다. 일반적인 사용자 정의 Tool은 대개 execute를 제공하지만, 다른 위치에서 실행되거나 조정되는 Tool 정의에서는 생략할 수 있도록 타입이 허용합니다. 두 매개변수를 받습니다. 첫 번째는 inputSchema를 기반으로 검증된 입력 데이터이고, 두 번째는 requestContext, abortSignal 및 기타 실행 메타데이터를 포함하는 실행 컨텍스트 객체입니다.

input:

z.infer<TInput>
inputSchema를 기반으로 검증된 입력 데이터

context?:

ToolExecutionContext
메타데이터를 포함하는 선택적 실행 컨텍스트
ToolExecutionContext

requestContext?:

RequestContext
공유 상태와 종속성에 액세스하기 위한 요청 컨텍스트

abortSignal?:

AbortSignal
Tool 실행을 중단하기 위한 신호

agent?:

AgentToolExecutionContext
Agent별 컨텍스트로, Agent가 Tool을 실행할 때 사용할 수 있습니다.
string
string
CoreMessage[]
(payload, options?) => Promise<void>
TResume
string
string
WritableStream<any>

workflow?:

WorkflowToolExecutionContext
Workflow별 컨텍스트(state, setState, suspend 등)

mcp?:

MCPToolExecutionContext
MCP별 컨텍스트(elicitation 등)

observe:

ToolObserve
Tool의 execute 함수 내부에서 하위 span과 구조화된 로그를 기록하기 위한 Observability 헬퍼입니다. 항상 제공되며, 활성화된 tracing 컨텍스트가 없으면 span은 함수를 직접 실행하고 log는 아무 작업도 하지 않습니다.
(name: string, fn: () => Promise<T> | T, attributes?: Record<string, unknown>) => Promise<T>
(level: 'debug' | 'info' | 'warn' | 'error' | 'fatal', message: string, data?: Record<string, unknown>) => void

onInputStart?:

function
Tool 호출 입력 스트리밍이 시작될 때 호출되는 선택적 콜백입니다. 시그니처: (options: ToolCallOptions) => void | PromiseLike<void>.

onInputDelta?:

function
입력 텍스트가 스트리밍될 때 각 증분 청크마다 호출되는 선택적 콜백입니다. 시그니처: ({ inputTextDelta, ...options }: { inputTextDelta: string } & ToolCallOptions) => void | PromiseLike<void>.

onInputAvailable?:

function
전체 Tool 입력을 사용할 수 있고 파싱이 완료되었을 때 호출되는 선택적 콜백입니다. 시그니처: ({ input, ...options }: { input: TSchemaIn } & ToolCallOptions) => void | PromiseLike<void>.

onOutput?:

function
Tool이 성공적으로 실행되어 출력을 반환한 후 호출되는 선택적 콜백입니다. 시그니처: ({ output, toolName, ...options }: { output: TSchemaOut; toolName: string } & Omit<ToolCallOptions, 'messages'>) => void | PromiseLike<void>.

런타임에 채워지는 mastramcpMetadata 필드는 소스 타입에 나타나지만 Mastra 또는 MCP 어댑터에서 설정합니다. 일반적인 createTool() 사용 시에는 이를 구성할 필요가 없습니다.

보고
보고에 대한 직접 링크

createTool() 함수는 Tool 객체를 반환합니다.

Tool:

object
정의된 Tool을 나타내며 Agent에 추가할 준비가 된 객체입니다.

스키마 정의
스키마 정의에 대한 직접 링크

Standard JSON Schema를 지원하는 모든 라이브러리로 Tool의 inputSchemaoutputSchema를 정의할 수 있습니다. 여기에는 Zod, Valibot, ArkType 같은 라이브러리가 포함됩니다.

src/mastra/tools/weather-tool.ts
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' }
},
})

엄격한 Tool 입력의 예
엄격한 Tool 입력의 예에 대한 직접 링크

Mastra가 지원되는 Model Provider에 Tool 스키마와 정확히 일치하는 Tool 인수를 생성하도록 요청하게 하려면 strict: true를 설정하세요.

src/mastra/tools/weather-tool.ts
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가 이 옵션을 무시합니다.

toModelOutput
example-with-tomodeloutput에 대한 직접 링크

Tool이 앱에는 풍부한 내부 데이터를 반환하되 Model에는 단순화된 값이나 멀티모달 콘텐츠를 전달해야 할 때 toModelOutput을 사용하세요.

src/mastra/tools/weather-tool.ts
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'

transform
example-with-transform에 대한 직접 링크

Tool이 런타임 동작을 위해 원시 입력이나 출력을 유지하되 표시 스트림이나 대화 기록 메시지에는 더 작거나 안전한 형태를 전달해야 할 때 transform을 사용하세요.

src/mastra/tools/customer-tool.ts
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:

src/mastra/tools/weather-tool.ts
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을 보여줍니다.

src/mastra/tools/weather-tool.ts
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}`)
},
})

사용 가능한 후크
사용 가능한 후크에 대한 직접 링크

onInputStart
oninputstart에 대한 직접 링크

입력 데이터가 수신되기 전에 Tool 호출 입력 스트리밍이 시작될 때 호출됩니다.

export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
onInputStart: ({ toolCallId, messages, abortSignal }) => {
console.log(`Tool ${toolCallId} input streaming started`)
},
})

onInputDelta
oninputdelta에 대한 직접 링크

스트리밍되는 입력 텍스트의 각 증분 청크에 대해 호출됩니다. 실시간 진행률을 표시하거나 부분 JSON을 구문 분석하는 데 유용합니다.

export const tool = createTool({
id: 'example-tool',
description: 'Example tool with hooks',
onInputDelta: ({ inputTextDelta, toolCallId, messages, abortSignal }) => {
console.log(`Received input chunk: ${inputTextDelta}`)
},
})

onInputAvailable
oninputavailable에 대한 직접 링크

전체 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
},
})

onOutput
onoutput에 대한 직접 링크

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 호출의 경우 후크는 다음 순서로 호출됩니다.

  1. onInputStart: 입력 스트리밍이 시작됩니다.
  2. onInputDelta: 청크가 도착하면 여러 번 호출됩니다.
  3. onInput 사용 가능: 완전한 입력이 구문 분석되고 검증됩니다.
  4. Toolexecute function runs
  5. 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?:

string
사람이 읽을 수 있는 Tool 제목입니다. UI 구성 요소에 표시하는 용도로 사용됩니다.

readOnlyHint?:

boolean
true이면 Tool은 환경을 수정하지 않습니다. 이 힌트는 Tool이 데이터만 읽고 부작용이 없음을 나타냅니다. 기본값은 false입니다.

destructiveHint?:

boolean
true이면 Tool이 환경에 파괴적인 업데이트를 수행할 수 있습니다. false이면 Tool은 추가형 업데이트만 수행합니다. 이 힌트는 클라이언트가 확인이 필요한지 판단하는 데 도움이 됩니다. 기본값은 true입니다.

idempotentHint?:

boolean
true이면 같은 인수로 Tool을 반복 호출해도 환경에 추가적인 영향이 없습니다. 이 힌트는 멱등 동작을 나타냅니다. 기본값은 false입니다.

openWorldHint?:

boolean
true이면 이 Tool이 외부 엔터티의 '열린 세계'(예: 웹 검색, 외부 API)와 상호 작용할 수 있습니다. false이면 Tool의 도메인이 닫혀 있고 완전히 정의되어 있습니다. 기본값은 true입니다.

이러한 주석은 MCP 사양을 따르며 MCP를 통해 Tool을 나열할 때 그대로 전달됩니다.