> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Tools 檔案式 Agent 會從其 `tools/` 目錄正下方的 `.ts` 和 `.js` 檔案探索 Tools。每個探索到的檔案都會在建置時匯入;該檔案必須預設匯出 [`createTool()`](https://mastra.zisheng.pro/zh-HK/reference/tools/create-tool) 的結果,而不含副檔名的檔案名稱會成為模型可呼叫的 Tool key。 本頁說明檔案式慣例。如需了解 Tool schema、執行選項、輸出塑形及審批選項,請參閱 [`createTool()` 參考資料](https://mastra.zisheng.pro/zh-HK/reference/tools/create-tool)。 ## 快速開始 在 `tools/` 下每個檔案放置一個 Tool。此檔案會以 `get_weather` 的形式提供給 Agent。 ```typescript 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' } }, }) ``` ## 組織 Tools 每個 Tool 使用一個檔案。檔案名稱應反映模型要執行的操作: - 使用 `get_weather.ts`、`search_docs.ts` 或 `create_ticket.ts`。 - 避免使用 `helper.ts`、`api.ts` 或 `utils.ts` 等含糊名稱。 - 將測試以 `*.test.ts` 或 `*.spec.ts` 的名稱與 Tool 放在一起。探索程序會忽略這些檔案。 - 將共用 helper 程式碼放在 `tools/` 以外,或放在 `tools/` 下副檔名不符合探索條件的檔案中。 由於巢狀目錄不會被探索為 Tools,請使用清晰的檔案名稱前綴(例如 `calendar_create_event.ts` 和 `calendar_list_events.ts`)為相關 Tools 分組,而不要使用子資料夾。 ## Tool 選項 檔案式慣例只控制 Tool 的所在位置及註冊方式。Tool API 仍由 `createTool()` 提供: - 使用 `description` 告訴模型何時呼叫 Tool。 - 使用 `inputSchema` 和 `outputSchema` 定義結構化輸入與輸出。 - 當模型應看到與 `execute` 傳回的原始值不同的結構時,請使用 `toModelOutput`。 - 當 Tool 在執行前需要人手確認時,請使用 `requireApproval`。 如需所有選項,請參閱 [`createTool()` 參考資料](https://mastra.zisheng.pro/zh-HK/reference/tools/create-tool);如需審批流程,請參閱 [Tool 審批](https://mastra.zisheng.pro/zh-HK/docs/harness/agent-controller)。 ## 執行階段邊界 Agent 呼叫 Tool 時,Tool 程式碼會在你的應用程式/伺服器執行階段中運行。如 Tool 需要檔案系統或 shell 隔離,請明確呼叫 [Workspace](https://mastra.zisheng.pro/zh-HK/reference/file-based-agents/workspace) 或 Sandbox API。 ## 與 config 的優先次序 探索到的 Tools 會與 [`config.ts`](https://mastra.zisheng.pro/zh-HK/reference/file-based-agents/config) 中的所有 `tools` 合併。如 key 發生衝突,系統會優先採用 `config.tools` 並記錄警告。 如 `config.tools` 是函式,探索到的 Tools 會被忽略並記錄警告,因為函式值 Tools 無法靜態合併。