본문으로 건너뛰기

Tool

Agent는 Tool을 사용하여 API를 호출하고, 데이터베이스를 쿼리하고, 코드베이스에서 사용자 지정 기능을 실행합니다. Tool은 데이터에 대한 구조화된 액세스를 제공하고 명확하게 정의된 작업을 수행함으로써 Agent에게 언어 생성 이상의 기능을 제공합니다. 원격에서 Tool을 로드할 수도 있습니다.MCP serversAgent의 역량을 확장합니다.

Tool을 사용해야 하는 경우
Tool을 사용해야 하는 경우에 대한 직접 링크

Agent에 원격 리소스의 추가 컨텍스트나 정보가 필요한 경우 또는 특정 작업을 수행하는 코드를 실행해야 하는 경우 Tool을 사용하세요. 여기에는 실시간 데이터를 가져오거나 일관되고 잘 정의된 출력을 반환하는 등 Model이 자체적으로 안정적으로 처리할 수 없는 작업이 포함됩니다.

빠른 시작
빠른 시작에 대한 직접 링크

수입createTool from @mastra/core/tools and define a tool with an id, description, inputSchema, outputSchema, and execute function.

이 예에서는 API에서 날씨 데이터를 가져오는 Tool을 만듭니다. 그만큼execute function receives input validated against inputSchema 를 첫 번째 인수로 받고 선택적 실행 컨텍스트를 두 번째 인수로 받습니다. 함수 시그니처에서 입력 필드를 직접 구조 분해 할당할 수 있습니다.

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 }, { abortSignal }) => {
const response = await fetch(`https://wttr.in/${location}?format=j1`, {
signal: abortSignal,
})
const data = await response.json()

return {
location,
temperatureCelsius: Number(data.current_condition[0].temp_C),
conditions: data.current_condition[0].weatherDesc[0].value,
}
},
})

Tool을 만들 때 설명을 간결하게 유지하고 Tool의 기능에 초점을 맞춰 기본 사용 사례를 강조하세요. 설명적인 스키마 이름은 Agent가 Tool을 사용하는 방법을 안내하는 데도 도움이 될 수 있습니다. 방문createTool 사용 가능한 속성, 구성 및 예시에 대한 자세한 내용은 reference를 참조하세요.

Agent가 Tool을 사용할 수 있도록 하려면 해당 Tool을tools property on the Agent 클래스입니다. Agent의 system Prompt에 사용 가능한 Tool과 각 Tool의 일반적인 용도를 명시하면 Agent가 Tool을 호출해야 할 때와 호출하지 않아야 할 때를 판단하는 데 도움이 됩니다.

src/mastra/agents/weather-agent.ts
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool'

export const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: `
You are a helpful weather assistant.
Use the weatherTool to fetch current weather data.`,
model: 'openai/gpt-5.6-sol',
tools: { weatherTool },
})

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

Tool의 내용을 정의할 수 있습니다.inputSchema and outputSchema with any library that supports Standard JSON Schema. This includes libraries like Zod, Valibot, and 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에 대한 직접 링크

Agent는 여러 Tool을 사용하여 특정 부분을 개별 Tool에 위임함으로써 보다 복잡한 작업을 처리할 수 있습니다. Agent는 사용자의 메시지, Agent의 지침, Tool 설명 및 스키마를 기반으로 사용할 Tool을 결정합니다.

src/mastra/agents/weather-agent.ts
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool'
import { hazardsTool } from '../tools/hazards-tool'

export const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: `
You are a helpful weather assistant.
Use the weatherTool to fetch current weather data.
Use the hazardsTool to provide information about potential weather hazards.`,
model: 'openai/gpt-5.6-sol',
tools: { weatherTool, hazardsTool },
})

Tool로서의 Agent
Tool로서의 Agent에 대한 직접 링크

다음을 통해 하위 Agent를 추가합니다.agents configuration to create a supervisor. Mastra converts each subagent to an agent-<key> tool. Include a description Supervisor가 언제 위임해야 하는지 알 수 있도록 각 하위 Agent에 설정하세요.

src/mastra/agents/supervisor.ts
import { Agent } from '@mastra/core/agent'

const writer = new Agent({
id: 'writer',
name: 'Writer',
description: 'Drafts and edits written content',
instructions: 'You are a skilled writer.',
model: 'openai/gpt-5.6-sol',
})

export const supervisor = new Agent({
id: 'supervisor',
name: 'Supervisor',
instructions: 'Coordinate the writer to produce content.',
model: 'openai/gpt-5.6-sol',
agents: { writer },
})

Tool로서의 Workflow
Tool로서의 Workflow에 대한 직접 링크

다음을 통해 Workflow를 추가하세요.workflows configuration. Mastra converts each workflow to a workflow-<key> tool that uses the workflow's inputSchema and outputSchema. Include a description Agent가 언제 Workflow를 실행해야 하는지 알 수 있도록 Workflow에 설정하세요.

src/mastra/agents/research-agent.ts
import { Agent } from '@mastra/core/agent'
import { researchWorkflow } from '../workflows/research-workflow'

export const researchAgent = new Agent({
id: 'research-agent',
name: 'Research Agent',
instructions: 'You are a research assistant.',
model: 'openai/gpt-5.6-sol',
workflows: { researchWorkflow },
})

Agent 간 Tool 공유
Agent 간 Tool 공유에 대한 직접 링크

여러 Agent가 하나의 Tool을 사용하는 경우 직접 가져오기가 최선의 선택입니다. 각 Agent는 Tool을 가져와서 해당 Tool에 추가합니다.tools 레코드입니다. 종속성은 명시적으로 유지되며 각 Agent를 독립적으로 사용할 수 있습니다.

src/mastra/tools/weather-tool.ts
import { createTool } from '@mastra/core/tools'

export const weatherTool = createTool({
id: 'weather-tool',
// Rest of the tool definition...
})
src/mastra/agents/weather-agents.ts
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool'

export const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: 'Answer questions about current weather.',
model: 'openai/gpt-5.6-sol',
tools: { weatherTool },
})
src/mastra/agents/travel-agents.ts
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool'

export const travelAgent = new Agent({
id: 'travel-agent',
name: 'Travel Agent',
instructions: 'Help users plan trips.',
model: 'openai/gpt-5.6-sol',
tools: { weatherTool },
})

Mastra 인스턴스에서 Tool에 액세스해야 하는 경우 다음을 참조하세요.Mastra.getTool(), Mastra.getToolById(), Mastra.listTools(), and the Agent reference.

Model의 모양 출력
Model의 모양 출력에 대한 직접 링크

사용toModelOutput Tool이 애플리케이션용으로 풍부한 구조화 데이터를 반환하지만 Model에는 더 작거나 멀티모달인 표현을 전달하려는 경우 사용하세요. 이렇게 하면 애플리케이션에 전체 Tool 결과를 보존하면서 Model 컨텍스트를 필요한 내용에 집중시킬 수 있습니다.

src/mastra/tools/weather-tool.ts
export const weatherTool = createTool({
execute: async ({ location }) => {
const response = await fetch(`https://wttr.in/${location}?format=j1`)
const data = await response.json()

return {
location,
temperatureCelsius: Number(data.current_condition[0].temp_C),
conditions: data.current_condition[0].weatherDesc[0].value,
weatherIconUrl: data.current_condition[0].weatherIconUrl[0].value,
source: data,
}
},
toModelOutput: output => {
return {
type: 'content',
value: [
{
type: 'text',
text: `${output.location}: ${output.temperatureCelsius}°C and ${output.conditions}`,
},
{ type: 'image-url', url: output.weatherIconUrl },
],
}
},
})

toModelOutput또한 전달된 클라이언트 측 Tool에서도 작동합니다.clientTools. 매핑은 Tool 실행 후 클라이언트에서 수행되며, 변환된 출력은 원시 결과와 함께 서버로 다시 전송됩니다.

UI 및 기록을 위한 변환 Tool 페이로드
UI 및 기록을 위한 변환 Tool 페이로드에 대한 직접 링크

사용transform Tool이 애플리케이션에 필요한 원시 데이터를 반환하지만 브라우저에 노출되는 스트림이나 사용자에게 표시되는 대화 기록 메시지에는 더 작거나 안전한 형태를 전달해야 할 때 사용하세요. transform is separate from toModelOutput: toModelOutput 는 Model로 다시 전송되는 페이로드의 형태를 지정하고, transform 는 Tool 입력, 출력, 오류, 승인 페이로드 및 일시 중단 페이로드의 형태를 지정합니다. 대상은 display and transcript targets.

변환이 구성되어 실패하는 경우 Mastra는 표시 또는 기록 대상에 대한 원시 페이로드로 대체되지 않습니다. 안전하지 않으면 입력 델타가 억제됩니다.inputDelta transform is available.

참조createTool() reference for a transform 예시를 참조하세요. 여러 Tool에 공통으로 적용할 규칙은 Agent 수준의 transform policy in the Agent constructor.

Tool 호출에 대한 논리 실행
Tool 호출에 대한 논리 실행에 대한 직접 링크

사용hooks 를 구성하여 Agent가 수행하는 모든 Tool 호출 전후에 사용자 지정 로직을 실행하세요. Hook은 할당된 Tool, Memory Tool, Toolset, 클라이언트 Tool, Agent 및 Workflow Tool, 그리고 workspace tools등 모든 Tool 소스에 적용됩니다. 일반적인 용도로는 로깅, 감사, 입력 유효성 검사 및 특정 호출 차단이 있습니다.

src/mastra/agents/support-agent.ts
import { Agent } from '@mastra/core/agent'

export const supportAgent = new Agent({
id: 'support-agent',
name: 'support-agent',
instructions: 'Help users with their questions.',
model: 'openai/gpt-5.6-sol',
hooks: {
beforeToolCall: ({ toolName, input }) => {
console.log(`Running ${toolName}`, input)
},
afterToolCall: ({ toolName, output, error }) => {
console.log(`Finished ${toolName}`, { output, error })
},
},
})

beforeToolCallTool이 실행되기 전에 실행되며 Tool 이름, 입력 및 실행 컨텍스트를 받습니다. 반품{ proceed: false, output } 를 사용하여 Tool 호출을 완전히 건너뛰면 Agent는 대신 output as the tool result:

const guardedAgent = new Agent({
id: 'guarded-agent',
name: 'guarded-agent',
instructions: 'Run shell commands for the user.',
model: 'openai/gpt-5.6-sol',
hooks: {
beforeToolCall: ({ toolName, input }) => {
const command = (input as { command?: string }).command ?? ''
if (toolName === 'execute_command' && command.includes('rm -rf')) {
return { proceed: false, output: 'Command blocked by policy.' }
}
},
},
})

afterToolCall성공 여부에 관계없이 Tool이 완료된 후에 실행됩니다. 성공하면 수신됩니다.output; if the tool threw, it receives error 를 수신하며, Hook 실행 후 오류가 다시 throw됩니다.

실행별 후크
실행별 후크에 대한 직접 링크

통과하다hooks to .generate() or .stream() 를 사용하여 단일 실행에 적용할 Hook을 설정하세요. 실행별 Hook은 일치하는 Agent 수준 Hook을 재정의합니다:

await supportAgent.generate('Look up the order status', {
hooks: {
beforeToolCall: ({ toolName }) => {
console.log(`This run only: ${toolName}`)
},
},
})

Agent 수준 및 실행별 후크가 키별로 병합: 전달만 가능beforeToolCall at execution time keeps the agent-level afterToolCall.

스트리밍
스트리밍에 대한 직접 링크

Tool은 스트리밍 중에 Tool 실행의 다양한 단계를 모니터링할 수 있는 수명 주기 후크를 지원합니다. 이러한 후크는 로깅이나 분석에 특히 유용합니다.

일반용writer API usage, see Streaming.

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

  • onInputStart: Tool 호출 입력 스트리밍이 시작될 때 호출됩니다.
  • onInputDelta: 스트리밍되는 입력의 각 청크에 대해 호출됩니다.
  • onInput 사용 가능: 완전한 입력이 구문 분석되고 검증될 때 호출됩니다.
  • onOutput: Tool이 출력과 함께 성공적으로 실행된 후에 호출됩니다.

모든 수명 주기 후크에 대한 자세한 문서는 다음을 참조하세요.createTool() reference.

예: 사용onInputAvailable and onOutput
example-using-oninputavailable-and-onoutput에 대한 직접 링크

import { createTool } from '@mastra/core/tools'
import { z } from 'zod'

export const weatherTool = createTool({
id: 'weather-tool',
description: 'Get weather information',
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
// Called when the complete input is available
onInputAvailable: ({ input, toolCallId }) => {
console.log(`Weather requested for: ${input.location}`)
},
execute: async ({ location }) => {
const weather = await fetchWeather(location)
return weather
},
// Called after successful execution
onOutput: ({ output, toolName }) => {
console.log(`${toolName} result: ${output.temperatureCelsius}°C, ${output.conditions}`)
},
})

UI의 스트리밍 Tool 입력
UI의 스트리밍 Tool 입력에 대한 직접 링크

Model이 Tool 호출을 생성하면 인수는 다음과 같이 증분적으로 도착합니다.tool-call-delta stream chunks before the final tool-call chunk. UIs can listen for the corresponding tool_input_start, tool_input_delta, and tool_input_end 이벤트를 사용하면 Tool 인수가 스트리밍되는 동안 이를 렌더링할 수 있습니다. 예를 들어 전체 Tool 호출이 완료될 때까지 기다리지 않고 파일 경로나 명령을 즉시 표시할 수 있습니다.

누적된 부분 JSON 파서를 사용하여argsTextDelta 조각을 사용하면 JSON이 완성되기 전에도 사용 가능한 인수 값을 추출할 수 있습니다. 이를 통해 편집 Tool의 실시간 diff 미리 보기, 쓰기 Tool의 파일 콘텐츠 스트리밍, 검색 패턴이나 파일 경로의 즉시 표시 같은 기능을 구현할 수 있습니다.

제어 Tool 선택
제어 Tool 선택에 대한 직접 링크

통과하다toolChoice or activeTools to .generate() or .stream() 를 사용하여 Agent가 런타임에 사용하는 Tool을 제어하세요.

await agent.generate('Check the forecast', {
toolChoice: 'required',
activeTools: ['weatherTool'],
})

참조Agent.generate() reference for all runtime options including toolsets, clientTools, and prepareStep.

제어toolName in stream responses
control-toolname-in-stream-responses에 대한 직접 링크

그만큼toolName in stream responses is determined by the object key you use, not the id property of the tool, agent, or workflow.

export const weatherTool = createTool({
id: 'weather-tool',
})

// Using the variable name as the key
tools: { weatherTool }
// Stream returns: toolName: "weatherTool"

// Using the tool's id as the key
tools: { [weatherTool.id]: weatherTool }
// Stream returns: toolName: "weather-tool"

// Using a custom key
tools: { "my-custom-name": weatherTool }
// Stream returns: toolName: "my-custom-name"

이를 통해 스트림에서 Tool을 식별하는 방법을 지정할 수 있습니다. 당신이 원하는 경우toolName to match the tool's id, use the tool's id as the object key.

Tool로서의 하위 Agent 및 Workflow
Tool로서의 하위 Agent 및 Workflow에 대한 직접 링크

하위 Agent와 Workflow는 동일한 패턴을 따릅니다. 접두어 뒤에 객체 키가 오는 Tool로 변환됩니다.

부동산접두사예시 키toolName
agentsagent-weatheragent-weather
workflowsworkflow-researchworkflow-research
const orchestrator = new Agent({
id: 'orchestrator',
agents: {
weather: weatherAgent, // toolName: "agent-weather"
},
workflows: {
research: researchWorkflow, // toolName: "workflow-research"
},
})

하위 Agent의 경우 스트림 응답에 두 가지 다른 식별자가 표시됩니다.

  • toolName: "agent-weather"Tool 호출 이벤트: 생성된 Tool 래퍼 이름
  • id: "weather-agent"~에data-tool-agent chunks: the subagent's actual id property

내장 Tool
내장 Tool에 대한 직접 링크

Mastra에는 Agent에 구애받지 않는 내장 Tool이 포함되어 있습니다.@mastra/core/tools 는 모든 Agent에 대화형 기능과 구성 관리 기능을 추가합니다.

Tool목적
ask_user사용자에게 질문하고 답변을 기다립니다
submit_planSubmit a plan file for user approval
task_writeCreate or replace a structured task list
task_updateUpdate one tracked task by ID
task_completeMark one tracked task completed
task_checkCheck task list completion status
webSearchTool활성 Model을 사용해 Provider 네이티브 웹 검색을 실행합니다
webFetchToolURL로 웹페이지를 가져와 텍스트 콘텐츠를 반환합니다

수입webSearchTool from @mastra/core/tools Model Provider가 자체 네이티브 웹 검색 Tool을 실행하도록 하려면 사용하세요. Mastra는 런타임에 활성 Model을 기반으로 이를 확인한 후 Provider가 관리하는 Tool을 Model에 전달합니다.

src/mastra/agents/research-agent.ts
import { Agent } from '@mastra/core/agent'
import { webSearchTool } from '@mastra/core/tools'

export const researchAgent = new Agent({
id: 'research-agent',
name: 'Research Agent',
instructions: 'Use web search when you need current information.',
model: 'openai/gpt-5.6-sol',
tools: {
search: webSearchTool,
},
})

webSearchToolOpenAI, Anthropic, Google Gemini 및 xAI Model을 지원합니다. Mastra가 활성 Model에서 해당 공급자 중 하나를 추론할 수 없는 경우 Agent 실행은 다음과 같이 실패합니다.MastraError.

그만큼search 키는 Agent 로컬 Tool 이름일 뿐입니다. 어떤 키든 사용할 수 있습니다. webSearchTool 값은 Mastra에 Provider 웹 검색을 사용하도록 지시합니다.

웹페이지 가져오기
웹페이지 가져오기에 대한 직접 링크

수입webFetchTool from @mastra/core/tools Agent가 특정 URL을 읽어야 할 때 사용하세요. Tool은 HTTP 또는 HTTPS를 통해 페이지를 요청하고 텍스트 콘텐츠와 응답 메타데이터를 반환합니다.

src/mastra/agents/reader-agent.ts
import { Agent } from '@mastra/core/agent'
import { webFetchTool } from '@mastra/core/tools'

export const readerAgent = new Agent({
id: 'reader-agent',
name: 'Reader Agent',
instructions: 'Fetch the page the user links to before answering.',
model: 'openai/gpt-5.6-sol',
tools: {
fetch: webFetchTool,
},
})

이 Tool은 단일url input and returns content, truncated, status, statusText, contentType, url, and ok. It applies these limits:

  • 오직http: and https: URLs are allowed.
  • 요청사항localhost 및 비공개 IP 주소나 예약된 IP 주소로의 요청은 차단되며, DNS 확인을 통해 반환된 주소도 포함됩니다.
  • 응답은 100,000자에서 잘립니다.truncated: true in the result.
  • 요청은 최대 5개의 리디렉션을 따르며 15초 후에 시간 초과됩니다.

실패는 던지지 않습니다. Tool이 반환됩니다.isError: true with the reason in content를 반환하므로 Agent가 다시 시도하거나 문제를 설명할 수 있습니다.

사용자에게 질문하기
사용자에게 질문하기에 대한 직접 링크

수입askUserTool and add it to the agent's toolset.

Tool은 실행을 일시 중단하고tool-call-suspended 이벤트를 질문과 함께 발생시킵니다. 다음을 호출하면 실행이 재개됩니다: resumeStream() with the user's answer.

src/mastra/agents/index.ts
import { Agent } from '@mastra/core/agent'
import { askUserTool } from '@mastra/core/tools'

const agent = new Agent({
id: 'assistant',
name: 'Assistant',
instructions: 'Ask the user for clarification when the request is ambiguous.',
model,
tools: { askUserTool },
})

Agent를 스트리밍하고 시청하세요.tool-call-suspended chunks. The suspendPayload contains the question and optional structured choices:

src/run.ts
const stream = await agent.stream('Summarize my project')

for await (const chunk of stream.fullStream) {
if (chunk.type === 'tool-call-suspended') {
const { question, options } = chunk.payload.suspendPayload
console.log(question)
const answer = await getUserAnswer() // your UI logic
const resumed = await agent.resumeStream(answer, { runId: stream.runId })
for await (const c of resumed.textStream) process.stdout.write(c)
}
}

askUserTool자유 텍스트, 단일 선택 지원(options array), and multi-select (selectionMode: 'multi_select') prompts. Pair it with autoResumeSuspendedTools 를 사용하면 사용자의 다음 채팅 메시지에서 Agent가 자동으로 재개됩니다. 자세한 내용은 Automatic tool resumption for details.

검토를 위해 계획 제출
검토를 위해 계획 제출에 대한 직접 링크

수입submitPlanTool 를 사용하면 Agent가 계획을 파일에 작성하고 사용자 검토를 위해 제출하도록 할 수 있습니다. 이 Tool은 사용자가 승인하거나 거부할 때까지 실행을 일시 중단합니다:

src/run.ts
for await (const chunk of stream.fullStream) {
if (chunk.type === 'tool-call-suspended' && chunk.payload.toolName === 'submit_plan') {
const { path } = chunk.payload.suspendPayload
// Read and display the plan file, then resume:
const resumed = await agent.resumeStream({ action: 'approved' }, { runId: stream.runId })
for await (const c of resumed.textStream) process.stdout.write(c)
}
}

작업 추적
작업 추적에 대한 직접 링크

작업 Tool은 Agent 실행을 위한 체계적이고 지속적인 작업 목록을 관리합니다. 그들은 요구한다Memory 를 사용하면 목록이 thread 범위 저장소에 영구 저장됩니다.

작업 추적 추가TaskSignalProvider, which bundles all four tools and the TaskStateProcessor in a single registration:

src/mastra/agents/index.ts
import { Agent } from '@mastra/core/agent'
import { Memory } from '@mastra/memory'
import { TaskSignalProvider } from '@mastra/core/signals'

const agent = new Agent({
id: 'coder',
name: 'Coder',
instructions: 'Track your progress with the task tools.',
model,
memory: new Memory(),
signals: [new TaskSignalProvider()],
})

작업은 하나만 가능합니다.in_progress 씩 처리합니다. 목록은 thread 범위의 threadState storage domain and projected onto the agent's state-signal lane에 저장되므로 관찰 Memory가 잘려도 유지됩니다. 자세한 내용은 Task tools reference for full schemas.

그만큼AgentController 에는 모든 모드에서 기본 제공 Tool이 자동으로 포함되므로 직접 추가할 필요가 없습니다. 자세한 내용은 Tool approvals for AgentController-specific behavior.