跳至主要內容

Tool

Agent 使用 Tool 呼叫 API、查詢資料庫,或執行程式碼庫中的自訂函數。Tool 透過提供結構化的資料存取方式及執行明確定義的操作,讓 Agent 具備語言生成以外的能力。你亦可從遠端 MCP 伺服器載入 Tool,擴展 Agent 的能力。

何時使用 Tool
何時使用 Tool 的直接連結

當 Agent 需要額外上下文或遠端資源的資料,或需要執行程式碼來完成特定操作時,便應使用 Tool。這包括模型無法自行可靠處理的任務,例如擷取即時資料,或傳回一致且定義明確的輸出。

快速開始
快速開始 的直接連結

@mastra/core/tools 匯入 createTool,並使用 iddescriptioninputSchemaoutputSchemaexecute 函數定義 Tool。

以下範例建立一個從 API 擷取天氣資料的 Tool。execute 函數的第一個參數會接收經 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 的功能,突顯其主要用途。清晰的 schema 名稱亦有助引導 Agent 使用 Tool。請參閱 createTool 參考文件,了解可用屬性、配置及範例的更多資料。

要讓 Agent 使用 Tool,請將其加入 Agent class 的 tools 屬性。在 Agent 的系統提示中列出可用 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 },
})

定義 schema
定義 schema 的直接連結

你可以使用任何支援 Standard JSON Schema 的函式庫,定義 Tool 的 inputSchemaoutputSchema,包括 ZodValibotArkType 等函式庫。

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 的描述和 schema,決定使用哪些 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 },
})

將 Agent 用作 Tool
將 Agent 用作 Tool 的直接連結

透過 agents 配置加入子 Agent,以建立監督者。Mastra 會將每個子 Agent 轉換為 agent-<key> Tool。請為每個子 Agent 加入 description,讓監督者知道何時應分派任務。

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

將 Workflow 用作 Tool
將 Workflow 用作 Tool 的直接連結

透過 workflows 配置加入 Workflow。Mastra 會將每個 Workflow 轉換為使用該 Workflow inputSchemaoutputSchemaworkflow-<key> Tool。請在 Workflow 中加入 description,讓 Agent 知道何時應觸發它。

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,並將其加入自身的 tools record。這樣依賴套件關係會保持明確,而每個 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()Agent 參考文件

調整模型輸出的形式
調整模型輸出的形式 的直接連結

如果 Tool 會向應用程式傳回豐富的結構化資料,但你希望模型接收較精簡或多模態的表示形式,請使用 toModelOutput。這可讓模型上下文保持聚焦,同時在應用程式中保留完整的 Tool 結果。

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 亦適用於透過 clientTools 傳入的客戶端 Tool。映射會在 Tool 執行後於客戶端運行,轉換後的輸出會連同原始結果傳回伺服器。

轉換用於 UI 和對話記錄的 Tool payload
轉換用於 UI 和對話記錄的 Tool payload 的直接連結

如果 Tool 會傳回應用程式所需的原始資料,但面向瀏覽器的串流或使用者可見的對話記錄訊息應接收較精簡或安全的形式,請使用 transformtransformtoModelOutput 互相獨立:toModelOutput 調整傳回模型的 payload,而 transform 則針對 displaytranscript 目標,調整 Tool 的輸入、輸出、錯誤、核准 payload 及暫停 payload。

如已配置轉換但轉換失敗,Mastra 不會對顯示或對話記錄目標改用原始 payload。如沒有安全的 inputDelta 轉換,系統會隱藏輸入增量。

有關 transform 範例,請參閱 createTool() 參考文件。如需在多個 Tool 之間共用規則,請在 Agent constructor 中配置 Agent 層級的 transform policy。

在 Tool 呼叫前後運行邏輯
在 Tool 呼叫前後運行邏輯 的直接連結

使用 hooks,在 Agent 每次呼叫 Tool 前後運行自訂邏輯。Hook 適用於所有 Tool 來源:已指派 Tool、memory Tool、toolset、客戶端 Tool、Agent 和 Workflow Tool,以及 Workspace 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 })
},
},
})

beforeToolCall 會在 Tool 執行前運行,並接收 Tool 名稱、輸入及執行上下文。傳回 { proceed: false, output } 可完全略過 Tool 呼叫,而 Agent 會收到 output 作為 Tool 結果:

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.' }
}
},
},
})

無論 Tool 成功或失敗,afterToolCall 都會在 Tool 完成後運行。成功時它會收到 output;如果 Tool 拋出例外,它會改為收到 error,而該錯誤會在 Hook 運行後再次拋出。

每次執行的 Hook
每次執行的 Hook 的直接連結

hooks 傳入 .generate().stream(),即可為單次執行設定 Hook。每次執行的 Hook 會覆寫對應的 Agent 層級 Hook:

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

Agent 層級與每次執行的 Hook 會按 key 合併:如執行時只傳入 beforeToolCall,便會保留 Agent 層級的 afterToolCall

串流
串流 的直接連結

Tool 支援生命週期 Hook,讓你在串流期間監察 Tool 執行的不同階段。這些 Hook 對記錄或分析尤其有用。

有關一般 writer API 用法,請參閱串流

可用 Hook
可用 Hook 的直接連結

  • onInputStart:Tool 呼叫的輸入開始串流時呼叫
  • onInputDelta:每個輸入區塊串流傳入時呼叫
  • onInputAvailable:完整輸入完成解析及驗證時呼叫
  • onOutput:Tool 成功執行並產生輸出後呼叫

有關所有生命週期 Hook 的詳細文件,請參閱 createTool() 參考文件

範例:使用 onInputAvailableonOutput
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 輸入 的直接連結

模型生成 Tool 呼叫時,參數會在最終 tool-call 區塊之前,以 tool-call-delta 串流區塊逐步抵達。UI 可監聽相應的 tool_input_starttool_input_deltatool_input_end 事件,在 Tool 參數串流傳入時即時呈現,例如立即顯示文件路徑或命令,而毋須等待完整的 Tool 呼叫。

對累積的 argsTextDelta 片段使用部分 JSON parser,可讓你在 JSON 完成前擷取可用的參數值。這可支援編輯 Tool 的即時 diff 預覽、寫入 Tool 的文件內容串流,以及即時顯示搜尋模式或文件路徑等功能。

控制 Tool 選擇
控制 Tool 選擇 的直接連結

toolChoiceactiveTools 傳入 .generate().stream(),以控制 Agent 在運行時使用哪些 Tool。

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

請參閱 Agent.generate() 參考文件,了解包括 toolsetsclientToolsprepareStep 在內的所有運行時選項。

控制串流回應中的 toolName
control-toolname-in-stream-responses 的直接連結

串流回應中的 toolName 取決於你使用的 object key,而非 Tool、Agent 或 Workflow 的 id 屬性。

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 與 Tool 的 id 相符,請使用 Tool 的 id 作為 object key。

將子 Agent 和 Workflow 用作 Tool
將子 Agent 和 Workflow 用作 Tool 的直接連結

子 Agent 和 Workflow 遵循相同模式。它們會轉換為由前綴加上 object key 組成的 Tool:

屬性前綴key 範例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,你會在串流回應中看到兩個不同的識別符:

  • Tool 呼叫事件中的 toolName: "agent-weather":生成的 Tool wrapper 名稱
  • data-tool-agent 區塊中的 id: "weather-agent":子 Agent 實際的 id 屬性

內置 Tool
內置 Tool 的直接連結

Mastra 在 @mastra/core/tools 中提供與 Agent 無關的內置 Tool,可為任何 Agent 加入互動及組織能力。

Tool用途
ask_user向使用者提問並等待回答
submit_plan提交計劃文件供使用者核准
task_write建立或取代結構化任務清單
task_update按 ID 更新一項追蹤中的任務
task_complete將一項追蹤中的任務標記為已完成
task_check檢查任務清單的完成狀態
webSearchTool使用目前模型運行 Provider 原生網絡搜尋
webFetchTool按 URL 擷取網頁並傳回其文字內容

如要模型 Provider 運行其原生網絡搜尋 Tool,請從 @mastra/core/tools 匯入 webSearchTool。Mastra 會在運行時根據目前模型解析該 Tool,然後將由 Provider 管理的 Tool 傳給模型。

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

webSearchTool 支援 OpenAI、Anthropic、Google Gemini 和 xAI 模型。如果 Mastra 無法從目前模型推斷出上述任何一個 Provider,Agent 運行便會失敗並傳回 MastraError

search key 只是 Agent 本機的 Tool 名稱,你可以使用任何 key。webSearchTool 值會指示 Mastra 使用 Provider 網絡搜尋。

擷取網頁
擷取網頁 的直接連結

當 Agent 需要讀取特定 URL 時,請從 @mastra/core/tools 匯入 webFetchTool。此 Tool 透過 HTTP 或 HTTPS 要求頁面,並傳回其文字內容及回應 metadata。

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 輸入,並傳回 contenttruncatedstatusstatusTextcontentTypeurlok。它設有以下限制:

  • 只允許 http:https: URL。
  • 系統會封鎖對 localhost、私人或保留 IP 位址的要求,包括 DNS 解析所傳回的位址。
  • 回應會在 100,000 個字元截斷,結果中會包含 truncated: true
  • 要求最多跟隨 5 次重新導向,並會在 15 秒後逾時。

失敗時不會拋出例外。Tool 會傳回 isError: true,並在 content 中提供原因,讓 Agent 可以重試或解釋問題。

向使用者提問
向使用者提問 的直接連結

匯入 askUserTool,並將其加入 Agent 的 toolset。

此 Tool 會暫停運行,並發出包含問題的 tool-call-suspended 事件。當你使用使用者的答案呼叫 resumeStream() 時,運行便會恢復。

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 區塊。suspendPayload 包含問題及可選的結構化選項:

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)和多選(selectionMode: 'multi_select')提示。將它與 autoResumeSuspendedTools 配合使用,Agent 便可在收到使用者的下一則聊天訊息後自動恢復。詳情請參閱 Tool 自動恢復

提交計劃供審閱
提交計劃供審閱 的直接連結

匯入 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 加入任務追蹤;它會在單一註冊中包含全部四個 Tool 及 TaskStateProcessor

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 儲存 domain,並投射至 Agent 的 state-signal lane,因此不會因 observational-memory 截斷而消失。完整 schema 請參閱任務 Tool 參考文件

AgentController 會在每種模式中自動包含所有內置 Tool,你毋須手動加入。AgentController 的特定行為請參閱 Tool 核准