Tools
Agent 使用 Tool 呼叫 API、查詢資料庫,或執行程式碼庫中的自訂函式。Tool 透過結構化方式存取資料並執行定義明確的操作,讓 Agent 擁有語言生成以外的功能。你也可以從遠端 MCP server 載入 Tool,擴充 Agent 的功能。
何時使用 Tool「何時使用 Tool」的直接連結
當 Agent 需要來自遠端資源的額外脈絡或資訊,或需要執行完成特定操作的程式碼時,請使用 Tool。這包括模型本身無法可靠處理的任務,例如擷取即時資料,或傳回一致且定義明確的輸出。
快速入門「快速入門」的直接連結
從 @mastra/core/tools 匯入 createTool,並使用 id、description、inputSchema、outputSchema 和 execute 函式定義 Tool。
以下範例建立一個從 API 擷取天氣資料的 Tool。execute 函式的第一個引數會接收經 inputSchema 驗證的輸入,第二個引數則是選用的執行脈絡。你可以直接在函式簽章中解構輸入欄位。
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 類別的 tools 屬性。在 Agent 的 system prompt 中提及可用的 Tool 及其一般用途,有助於 Agent 判斷何時應呼叫 Tool,以及何時不應呼叫。
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 的 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」的直接連結
Agent 可以使用多個 Tool 處理更複雜的任務,將特定部分交由個別 Tool 執行。Agent 會根據使用者訊息、Agent 指示,以及 Tool 的描述與 schema,決定要使用哪些 Tool。
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 設定加入 subagent,以建立 supervisor。Mastra 會將每個 subagent 轉換成 agent-<key> Tool。請為每個 subagent 加入 description,讓 supervisor 知道何時該分派工作。
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-<key> Tool,並使用 Workflow 的 inputSchema 和 outputSchema。請為 Workflow 加入 description,讓 Agent 知道何時該觸發它。
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 記錄。如此一來,相依關係保持明確,而且每個 Agent 都能獨立使用。
import { createTool } from '@mastra/core/tools'
export const weatherTool = createTool({
id: 'weather-tool',
// Rest of the tool definition...
})
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 },
})
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 結果。
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 執行後於用戶端進行,轉換後的輸出會連同原始結果傳回 server。
轉換 UI 與文字記錄的 Tool payload「轉換 UI 與文字記錄的 Tool payload」的直接連結
當 Tool 傳回應用程式所需的原始資料,但面向瀏覽器的串流或使用者可見的文字記錄訊息應接收較精簡或較安全的資料形式時,請使用 transform。transform 與 toModelOutput 彼此獨立:toModelOutput 會調整傳回模型的 payload,而 transform 會針對 display 和 transcript 目標,調整 Tool 的輸入、輸出、錯誤、核准 payload 與暫停 payload。
若設定了 transform 但執行失敗,Mastra 不會針對顯示或文字記錄目標改用原始 payload。若沒有安全的 inputDelta transform 可用,系統會抑制輸入差異。
如需 transform 範例,請參閱 createTool() 參考文件。若多個 Tool 要共用規則,請在 Agent 建構函式中設定 Agent 層級的 transform 原則。
在 Tool 呼叫前後執行邏輯「在 Tool 呼叫前後執行邏輯」的直接連結
使用 hooks 在 Agent 每次呼叫 Tool 的前後執行自訂邏輯。Hook 適用於所有 Tool 來源:指派的 Tool、記憶體 Tool、toolset、用戶端 Tool、Agent 與 Workflow Tool,以及 Workspace Tool。常見用途包括記錄、稽核、輸入驗證,以及封鎖特定呼叫。
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 都會在完成後運作。成功時會接收 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() 參考文件。
範例:使用 onInputAvailable 和 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 輸入」的直接連結
模型產生 Tool 呼叫時,引數會先以遞增方式透過 tool-call-delta 串流區塊抵達,最後才是最終的 tool-call 區塊。UI 可以監聽對應的 tool_input_start、tool_input_delta 和 tool_input_end 事件,在 Tool 引數串流抵達時呈現。例如,立即顯示檔案路徑或命令,而不必等待完整的 Tool 呼叫。
對累積的 argsTextDelta 片段使用部分 JSON parser,即可在 JSON 完整之前擷取可用的引數值。這能實現編輯 Tool 的即時差異預覽、寫入 Tool 的串流檔案內容,以及立即顯示搜尋模式或檔案路徑等功能。
控制 Tool 選擇「控制 Tool 選擇」的直接連結
將 toolChoice 或 activeTools 傳給 .generate() 或 .stream(),即可控制 Agent 在執行階段使用哪些 Tool。
await agent.generate('Check the forecast', {
toolChoice: 'required',
activeTools: ['weatherTool'],
})
如需包括 toolsets、clientTools 和 prepareStep 在內的所有執行階段選項,請參閱 Agent.generate() 參考文件。
控制串流回應中的 toolName「control-toolname-in-stream-responses」的直接連結
串流回應中的 toolName 由你使用的物件 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 作為物件 key。
將 subagent 和 Workflow 作為 Tool「將 subagent 和 Workflow 作為 Tool」的直接連結
Subagent 和 Workflow 遵循相同模式。它們會轉換成具有前綴、後接物件 key 的 Tool:
| 屬性 | 前綴 | 範例 key | toolName |
|---|---|---|---|
agents | agent- | weather | agent-weather |
workflows | workflow- | research | workflow-research |
const orchestrator = new Agent({
id: 'orchestrator',
agents: {
weather: weatherAgent, // toolName: "agent-weather"
},
workflows: {
research: researchWorkflow, // toolName: "workflow-research"
},
})
請注意,對 subagent 而言,你會在串流回應中看到兩個不同的識別碼:
- Tool 呼叫事件中的
toolName: "agent-weather":產生的 Tool wrapper 名稱 data-tool-agent區塊中的id: "weather-agent":subagent 實際的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 網頁搜尋「使用 Provider 網頁搜尋」的直接連結
當你希望模型 Provider 執行其原生網頁搜尋 Tool 時,請從 @mastra/core/tools 匯入 webSearchTool。Mastra 會在執行階段根據作用中模型解析此 Tool,再將由 Provider 管理的 Tool 傳給模型。
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 要求頁面,並傳回頁面的文字內容及回應中繼資料。
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 輸入,並傳回 content、truncated、status、statusText、contentType、url 和 ok。其限制如下:
- 僅允許
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() 時,執行便會繼續。
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 包含問題和選用的結構化選項:
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 陣列)及多選(selectionMode: 'multi_select')提示。搭配 autoResumeSuspendedTools 使用,Agent 就能從使用者的下一則聊天訊息自動繼續執行。詳情請參閱自動繼續執行 Tool。
提交計畫供審查「提交計畫供審查」的直接連結
匯入 submitPlanTool,讓 Agent 將計畫寫入檔案並提交給使用者審查。此 Tool 會暫停執行,直到使用者核准或拒絕:
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 執行所使用的結構化持久任務清單。這些 Tool 需要 Memory,才能將清單持久儲存在 thread 範圍的儲存空間中。
透過 TaskSignalProvider 加入任務追蹤。它會將四個 Tool 與 TaskStateProcessor 綁定為單一註冊項目:
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 儲存網域中,並投影至 Agent 的 state-signal lane,因此即使 observational-memory 截斷,清單仍會保留。如需完整 schema,請參閱任務 Tool 參考文件。
AgentController 會在每種模式中自動包含所有內建 Tool,你不需要手動加入。如需 AgentController 特定行為,請參閱 Tool 核准。
相關資源「相關資源」的直接連結
createTool參考文件Agent.generate()參考文件:Tool 選擇、步驟與 callback 的執行階段選項- 背景任務:執行長時間運作的 Tool,而不封鎖 Agent loop
- MCP 概覽
- 動態 Tool 搜尋:針對擁有大型 Tool 函式庫的 Agent,視需要載入 Tool
- 具有結構化輸出的 Tool:結合 Tool 與結構化輸出時的模型相容性
- Agent 核准
askUserTool參考文件submitPlanTool參考文件- 任務 Tool 參考文件
- TaskSignalProvider 參考文件
- 要求脈絡