Claude Tools 完整指南:從 Tool Use 到 Server/Client Tools 的全面解析
Claude 的 Tool Use 體系是建構 AI Agent 的核心能力。透過 Tools,Claude 不再只是一個被動回答問題的語言模型,而是能夠主動搜尋網路、執行程式碼、操作檔案系統的全方位助手。本文將全面解析 Claude 的 Tools 架構、每一種內建工具的使用方式,以及實作時的最佳實踐。
一、Tool Use 運作機制
兩類工具架構
Claude 支援兩種工具類型:
Client Tools(客戶端工具):由開發者在自己的系統上實作和執行,包含:
- 開發者自定義的工具(如查詢天氣 API、資料庫操作等)
- Anthropic 定義但需客戶端實作的工具(Computer Use、Text Editor、Bash)
Server Tools(伺服器端工具):在 Anthropic 伺服器上執行,開發者只需在 API 請求中指定即可使用:
- Web Search、Web Fetch、Code Execution、Memory
Client Tool 的工作流程
- 在 API 請求中定義工具(名稱、描述、input schema)並附帶使用者訊息
- Claude 評估是否需要使用工具,若是,建構工具呼叫請求(
stop_reason為tool_use) - 開發者擷取工具名稱和輸入參數,在自己的系統上執行工具
- 將結果以
tool_resultcontent block 回傳給 Claude - Claude 根據工具結果生成最終回應
Server Tool 的工作流程
- 在 API 請求中指定 Server Tool 及其參數
- Claude 自動在伺服器端執行工具,結果直接整合到回應中
- 伺服器端的 sampling loop 可能執行多次工具呼叫後才返回
- 大多數情況下不需要額外的使用者交互
工具定義最佳實踐
每個 Client Tool 定義包含四個欄位:
| 參數 | 說明 |
|---|---|
name | 工具名稱,需符合 ^[a-zA-Z0-9_-]{1,64}$ |
description | 詳細的純文字描述,這是影響效能最關鍵的因素 |
input_schema | JSON Schema 定義的輸入參數結構 |
input_examples | (選用)範例輸入物件陣列 |
描述撰寫要點:
- 每個工具至少 3-4 句描述
- 明確說明工具做什麼、何時該用(以及何時不該用)
- 解釋每個參數的含義及其對工具行為的影響
- 標註重要的限制條件,例如工具不會回傳的資訊
Anthropic 定義工具的版本化
所有 Anthropic 定義的工具使用版本化的型別名稱(如 web_search_20250305、text_editor_20250124),確保跨模型版本的相容性。
二、Server-side Tools
Web Search
Web Search 讓 Claude 能夠搜尋即時網路資料,增強其知識基礎。
基本配置:
{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 10
}
核心特性:
- 自動在 Anthropic 伺服器端執行搜尋
- 支援
max_uses限制單次請求的搜尋次數 - 搜尋結果自動整合到 Claude 的回應中,包含引用和來源連結
- 支援與其他工具混合使用
定價: 每次搜尋有獨立的計費,除了標準的 input/output token 費用外,還會根據搜尋次數額外收費。
Web Fetch
Web Fetch 讓 Claude 能夠擷取指定網頁和 PDF 文件的完整內容進行深度分析。
基本配置:
{
"type": "web_fetch_20250305",
"name": "web_fetch",
"max_uses": 5
}
核心特性:
- 可擷取網頁 HTML 內容並轉換為可分析的格式
- 支援直接擷取和分析 PDF 文件
- 適合需要對特定 URL 內容進行深度分析的場景
- 與 Web Search 搭配使用效果更佳:先搜尋找到相關 URL,再用 Web Fetch 擷取完整內容
Code Execution
Code Execution 提供一個沙箱化的程式碼執行環境,支援進階的資料分析、計算和檔案處理。
基本配置:
{
"type": "code_execution_20250522",
"name": "code_execution"
}
核心特性:
- 在安全的沙箱環境中執行程式碼
- 支援 Python 及多種預安裝的套件(pandas、numpy、matplotlib 等)
- 適合數學計算、資料分析、圖表生成等任務
- 與 Web Search 或 Web Fetch 搭配使用時免費
- 支援多種檔案類型的輸入輸出(透過 Files API)
- 無網路存取能力,確保安全性
典型使用場景:
- 複雜的數學計算和統計分析
- 資料視覺化和圖表生成
- CSV/Excel 資料處理
- 程式碼驗證和測試
Memory Tool
Memory Tool 是一個獨特的工具,讓 Claude 能夠跨對話儲存和檢索資訊,建立持久的知識庫。
基本配置:
{
"type": "memory_20250818",
"name": "memory"
}
運作方式:
Memory Tool 操作在客戶端:Claude 發出工具呼叫,由開發者的應用程式在本地執行檔案操作。這讓開發者對資料儲存有完全的控制權。
支援六個指令:
| 指令 | 說明 |
|---|---|
view | 查看目錄內容或檔案內容(可指定行範圍) |
create | 建立新檔案 |
str_replace | 替換檔案中的文字 |
insert | 在指定行插入文字 |
delete | 刪除檔案或目錄 |
rename | 重新命名或移動檔案/目錄 |
核心協定: 啟用 Memory Tool 時,系統會自動注入指令要求 Claude 在開始任何任務前先查看 memory 目錄。Claude 會假設 context window 隨時可能被重置,因此會主動將進度記錄到 memory 中。
使用場景:
- 跨多次 agent 執行維持專案脈絡
- 從過去的互動中學習和改進
- 隨時間建立知識庫
- 跨對話學習以更有效處理重複性工作流程
安全考量:
- 必須驗證所有路徑,防止目錄穿越攻擊
- 應限制所有 memory 操作在
/memories目錄內 - 考慮追蹤 memory 檔案大小並設定上限
- 定期清除長時間未存取的 memory 檔案
與 Context Editing 搭配: Memory Tool 可與 Context Editing 結合使用。當 context 接近清除閾值時,Claude 會自動將重要資訊儲存到 memory 檔案中,確保關鍵資訊不會在 tool results 被清除時遺失。
與 Compaction 搭配: 也可與 Compaction 配合使用。Compaction 在伺服器端自動摘要對話,而 Memory 則持久保存重要資訊,兩者互補。
三、Client-side Tools
Bash Tool
Bash Tool 讓 Claude 能夠執行 bash 指令和腳本,與系統 shell 互動。
配置方式:
{
"type": "bash_20250124",
"name": "bash"
}
典型使用場景:
- 執行系統指令和腳本
- Git 操作
- 檔案系統導航
- 套件管理
- 建構和部署流程
Computer Use Tool
Computer Use 讓 Claude 能夠透過截圖、滑鼠和鍵盤操作來控制電腦介面。
配置方式:
{
"type": "computer_20250124",
"name": "computer"
}
核心特性:
- 截取螢幕畫面進行視覺分析
- 模擬滑鼠點擊、拖曳、滾動等操作
- 模擬鍵盤輸入和快捷鍵
- 適合自動化 GUI 操作和測試
- 目前仍為 Beta 功能
注意事項: Computer Use 讓 Claude 能夠與任何螢幕上的應用程式互動,但需要謹慎考慮安全性。建議在受控環境中使用,並限制 Claude 可存取的應用程式範圍。
Text Editor Tool
Text Editor 提供內建的文字編輯器介面,用於建立和編輯檔案。
配置方式:
{
"type": "text_editor_20250124",
"name": "str_replace_editor"
}
支援操作:
view:查看檔案內容或目錄結構create:建立新檔案str_replace:精確替換文字(要求 old_str 必須唯一)insert:在指定行插入文字undo_edit:撤銷上一次編輯
最佳實踐:
- 使用
view確認檔案當前內容後再進行編輯 str_replace的old_str必須完全匹配,包含空白和縮排- 一次只做小範圍修改,避免大規模同時變更
四、Tool Runner:自動化工具執行
Tool Runner 是 SDK 提供的自動化工具執行框架(目前為 Beta),簡化了工具使用的實作流程。
核心優勢
相較於手動處理工具呼叫迴圈,Tool Runner 自動:
- 當 Claude 呼叫工具時執行工具
- 處理請求/回應循環
- 管理對話狀態
- 提供型別安全和驗證
Python 使用範例
import anthropic
from anthropic import beta_tool
client = anthropic.Anthropic()
@beta_tool
def get_weather(location: str, unit: str = "fahrenheit") -> str:
"""Get the current weather in a given location.
Args:
location: The city and state, e.g. San Francisco, CA
unit: Temperature unit
"""
return json.dumps({"temperature": "20C", "condition": "Sunny"})
runner = client.beta.messages.tool_runner(
model="claude-opus-4-6",
max_tokens=1024,
tools=[get_weather],
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
)
for message in runner:
print(message.content[0].text)
TypeScript 使用範例
import { Anthropic } from "@anthropic-ai/sdk";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";
const getWeatherTool = betaZodTool({
name: "get_weather",
description: "Get the current weather in a given location",
inputSchema: z.object({
location: z.string().describe("The city and state"),
unit: z.enum(["celsius", "fahrenheit"]).default("fahrenheit")
}),
run: async (input) => {
return JSON.stringify({ temperature: "20C", condition: "Sunny" });
}
});
const runner = anthropic.beta.messages.toolRunner({
model: "claude-opus-4-6",
max_tokens: 1024,
tools: [getWeatherTool],
messages: [{ role: "user", content: "What's the weather in Paris?" }]
});
for await (const message of runner) {
console.log(message.content[0].text);
}
進階功能
Streaming 支援: 設定 stream=True 即可在 Tool Runner 中啟用串流。
錯誤處理: 當工具拋出例外時,Tool Runner 會自動捕獲並以 is_error: true 的 tool result 回傳給 Claude。設定 ANTHROPIC_LOG=debug 可查看完整的 stack trace。
修改工具結果: 可在工具結果送回 Claude 之前進行修改,例如加入 cache_control 以啟用 Prompt Caching。
自動 Compaction 支援: Tool Runner 支援自動 Compaction,當 token 使用量超過閾值時自動摘要,讓長時間運行的 agent 任務可以突破 context window 限制。
五、Parallel Tool Use
Claude 可以在單次回應中同時呼叫多個工具,適用於需要多個獨立操作的任務。
正確的格式
所有 tool_use blocks 包含在單一 assistant message 中,所有對應的 tool_result blocks 必須在隨後的單一 user message 中提供:
[
{"role": "assistant", "content": [tool_use_1, tool_use_2]},
{"role": "user", "content": [tool_result_1, tool_result_2]}
]
關鍵格式要求:
- 所有 tool results 必須在同一個 user message 中
- tool_result blocks 必須放在 content array 的最前面
- 任何文字必須排在所有 tool results 之後
控制 Parallel Tool Use
透過 tool_choice 和 disable_parallel_tool_use 參數控制:
| tool_choice | disable_parallel | 效果 |
|---|---|---|
auto(預設) | false | Claude 自行決定使用工具的數量 |
auto | true | 最多使用一個工具 |
any | true | 必須使用恰好一個工具 |
tool | true | 必須使用指定的恰好一個工具 |
none | - | 不使用任何工具 |
最大化 Parallel Tool Use 的技巧
在 system prompt 中加入:
For maximum efficiency, whenever you need to perform multiple independent
operations, invoke all relevant tools simultaneously rather than sequentially.
在 user message 中使用明確的語言:
Please use parallel tool calls to get the weather for Paris, London,
and Tokyo at the same time.
六、Forcing Tool Use 與 JSON Mode
強制使用特定工具
透過 tool_choice 參數控制 Claude 的工具使用行為:
auto:Claude 自行決定(預設值)any:必須使用某個工具,但不限制哪一個tool:強制使用指定工具none:不使用任何工具
注意: 使用 Extended Thinking 時,只支援 auto 和 none。
以工具實現 JSON 輸出
工具不一定要是實際的函式。任何時候需要 Claude 返回遵循特定 schema 的 JSON 輸出,都可以定義一個工具來達成。結合 tool_choice: {"type": "tool", "name": "your_tool"} 和 strict: true,可以保證輸出嚴格遵循 schema。
七、MCP 工具整合
如果使用 Model Context Protocol(MCP),可以直接在 Messages API 中使用 MCP 伺服器的工具。只需要將 MCP 的 inputSchema 重命名為 input_schema 即可。
async def get_claude_tools(mcp_session):
mcp_tools = await mcp_session.list_tools()
return [
{
"name": tool.name,
"description": tool.description or "",
"input_schema": tool.inputSchema,
}
for tool in mcp_tools.tools
]
如果不想自行建構 MCP 客戶端,可以使用 MCP Connector 直接從 Messages API 連接到遠端 MCP 伺服器。
八、定價說明
Tool Use 的計費基於:
- 發送給模型的總 input tokens(包含
tools參數中的定義) - 生成的 output tokens
- Server-side tools 的額外使用費用(如 Web Search 按搜尋次數計費)
使用 tools 參數時,系統會自動注入一個特殊的 system prompt。不同模型和 tool choice 設定下的額外 token 消耗:
| 模型 | auto/none | any/tool |
|---|---|---|
| Claude Opus 4.6 | 346 tokens | 313 tokens |
| Claude Sonnet 4.5 | 346 tokens | 313 tokens |
| Claude Haiku 4.5 | 346 tokens | 313 tokens |
| Claude Haiku 3.5 | 264 tokens | 340 tokens |
九、錯誤處理與疑難排解
工具執行錯誤
當工具執行失敗時,以 is_error: true 回傳錯誤訊息:
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "ConnectionError: the weather service API is not available",
"is_error": true
}
Claude 會自動將錯誤整合到回應中,優雅地告知使用者。
無效工具呼叫
如果參數不完整或無效,Claude 通常會重試 2-3 次進行修正。使用 strict: true 的 Structured Outputs 可以完全消除無效的工具呼叫。
Parallel Tool Use 故障排除
如果 Claude 沒有進行平行工具呼叫,檢查:
- tool result 格式是否正確(所有結果在同一個 user message 中)
- 是否使用了足夠強的提示語言
- 使用的模型是否支援(Claude 4 系列最佳)
Server Tool 錯誤
Server Tool 的錯誤由 Claude 自動處理。Web Search 可能的錯誤碼包括:
too_many_requests:速率限制invalid_input:無效的搜尋查詢max_uses_exceeded:超過最大搜尋次數query_too_long:查詢過長unavailable:內部錯誤
pause_turn 處理
Server Tool 的 sampling loop 預設限制為 10 次迭代。達到限制時 API 回傳 stop_reason="pause_turn",開發者需要將回應送回以讓 Claude 繼續處理:
if response.stop_reason == "pause_turn":
messages.append({"role": "assistant", "content": response.content})
continuation = client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
messages=messages,
tools=tools,
)
總結
Claude 的 Tools 體系提供了一套完整的工具鏈,從伺服器端的 Web Search、Web Fetch、Code Execution、Memory,到客戶端的 Bash、Computer Use、Text Editor,涵蓋了 AI Agent 所需的各種能力。Tool Runner 簡化了工具執行的實作流程,Parallel Tool Use 提升了多工具場景的效率。理解這些工具的運作機制和最佳實踐,是建構高效 Claude Agent 的關鍵基礎。