Tool
檔案式 Agent 會從 tools/ 目錄正下方的 .ts 與 .js 檔案探索 Tool。每個探索到的檔案都會在建置時匯入,且必須 default export createTool() 的結果;不含副檔名的檔名會成為模型可呼叫的 Tool key。
本頁說明檔案式慣例。Tool schema、執行選項、輸出結構調整與核准選項請參閱 createTool() 參考文件。
快速開始「快速開始」的直接連結
在 tools/ 下每個檔案放置一個 Tool。此檔案會以 get_weather 名稱提供給 Agent。
src/mastra/agents/weather/tools/get_weather.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export default createTool({
id: 'get_weather',
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' }
},
})
組織 Tool「組織 Tool」的直接連結
每個 Tool 使用一個檔案。檔名應反映模型要執行的動作:
- 使用
get_weather.ts、search_docs.ts或create_ticket.ts。 - 避免
helper.ts、api.ts或utils.ts等含糊的名稱。 - 將測試放在 Tool 旁,命名為
*.test.ts或*.spec.ts。探索時會忽略這些檔案。 - 將共用輔助程式碼放在
tools/外,或放在tools/下副檔名不符合探索規則的檔案中。
巢狀目錄不會被探索為 Tool,因此請使用清楚的檔名前綴來分組相關 Tool,而不是使用子資料夾,例如 calendar_create_event.ts 和 calendar_list_events.ts。
Tool 選項「Tool 選項」的直接連結
檔案式慣例只控制 Tool 的所在位置與註冊方式。Tool API 仍由 createTool() 提供:
- 使用
description告訴模型何時呼叫 Tool。 - 使用
inputSchema與outputSchema定義結構化輸入及輸出。 - 當模型應看到與
execute所傳回原始值不同的結構時,使用toModelOutput。 - 當 Tool 執行前需要人員確認時,使用
requireApproval。
所有選項請參閱 createTool() 參考文件;核准流程請參閱 Tool 核准。
執行階段邊界「執行階段邊界」的直接連結
Agent 呼叫 Tool 時,Tool 程式碼會在你的應用程式/server 執行階段中執行。如果 Tool 需要檔案系統或 shell 隔離,請明確呼叫 Workspace或 Sandbox API。
與 config 的優先順序「與 config 的優先順序」的直接連結
探索到的 Tool 會與 config.ts 中的所有 tools 合併。若 key 發生衝突,config.tools 會優先,並記錄警告。
如果 config.tools 是函式,系統會忽略探索到的 Tool 並顯示警告,因為函式值 Tool 無法以靜態方式合併。