agent-sdk/custom-tools.md +833 −0 created
1> ## Documentation Index
2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
3> Use this file to discover all available pages before exploring further.
4
5# 為 Claude 提供自訂工具
6
7> 使用 Claude Agent SDK 的同程序 MCP 伺服器定義自訂工具,讓 Claude 可以呼叫您的函數、存取您的 API,並執行特定領域的操作。
8
9自訂工具透過讓您定義 Claude 在對話期間可以呼叫的自己的函數來擴展 Agent SDK。使用 SDK 的同程序 MCP 伺服器,您可以讓 Claude 存取資料庫、外部 API、特定領域邏輯或應用程式需要的任何其他功能。
10
11本指南涵蓋如何使用輸入結構描述和處理程式定義工具、將它們組合到 MCP 伺服器中、將它們傳遞給 `query`,以及控制 Claude 可以存取哪些工具。它也涵蓋錯誤處理、工具註解,以及傳回非文字內容(如影像)。
12
13## 快速參考
14
15| 如果您想要... | 執行此操作 |
16| :------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17| 定義工具 | 使用 [`@tool`](/zh-TW/agent-sdk/python#tool)(Python)或 [`tool()`](/zh-TW/agent-sdk/typescript#tool)(TypeScript),搭配名稱、描述、結構描述和處理程式。請參閱[建立自訂工具](#create-a-custom-tool)。 |
18| 向 Claude 註冊工具 | 在 `create_sdk_mcp_server` / `createSdkMcpServer` 中包裝,並傳遞至 `query()` 中的 `mcpServers`。請參閱[呼叫自訂工具](#call-a-custom-tool)。 |
19| 預先核准工具 | 新增至您允許的工具。請參閱[設定允許的工具](#configure-allowed-tools)。 |
20| 從 Claude 的內容中移除內建工具 | 傳遞 `tools` 陣列,僅列出您想要的內建工具。請參閱[設定允許的工具](#configure-allowed-tools)。 |
21| 讓 Claude 平行呼叫工具 | 在沒有副作用的工具上設定 `readOnlyHint: true`。請參閱[新增工具註解](#add-tool-annotations)。 |
22| 處理錯誤而不停止迴圈 | 傳回 `isError: true` 而不是擲回。請參閱[處理錯誤](#handle-errors)。 |
23| 傳回影像或檔案 | 在內容陣列中使用 `image` 或 `resource` 區塊。請參閱[傳回影像和資源](#return-images-and-resources)。 |
24| 傳回機器可讀的 JSON 結果 | 在結果上設定 `structuredContent`。請參閱[傳回結構化資料](#return-structured-data)。 |
25| 擴展到許多工具 | 使用[工具搜尋](/zh-TW/agent-sdk/tool-search)按需載入工具。 |
26
27## 建立自訂工具
28
29工具由四個部分定義,作為 TypeScript 中 [`tool()`](/zh-TW/agent-sdk/typescript#tool) 協助程式或 Python 中 [`@tool`](/zh-TW/agent-sdk/python#tool) 裝飾器的引數傳遞:
30
31* **名稱:** Claude 用來呼叫工具的唯一識別碼。
32* **描述:** 工具的功能。Claude 讀取此項以決定何時呼叫它。
33* **輸入結構描述:** Claude 必須提供的引數。在 TypeScript 中,這始終是 [Zod 結構描述](https://zod.dev/),處理程式的 `args` 會自動從中輸入。在 Python 中,這是將名稱對應到類型的字典,例如 `{"latitude": float}`,SDK 會為您轉換為 JSON Schema。Python 裝飾器也接受完整的 [JSON Schema](https://json-schema.org/understanding-json-schema/about) 字典,當您需要列舉、範圍、選用欄位或巢狀物件時。
34* **處理程式:** 當 Claude 呼叫工具時執行的非同步函數。它接收驗證的引數,並必須傳回具有以下內容的物件:
35 * `content`(必需):結果區塊的陣列,每個區塊的 `type` 為 `"text"`、`"image"` 或 `"resource"`。請參閱[傳回影像和資源](#return-images-and-resources)以取得非文字區塊。
36 * `structuredContent`(選用):保存結果作為機器可讀資料的 JSON 物件,與 `content` 一起傳回。請參閱[傳回結構化資料](#return-structured-data)。
37 * `isError`(選用):設定為 `true` 以表示工具失敗,讓 Claude 可以對其做出反應。請參閱[處理錯誤](#handle-errors)。
38
39定義工具後,使用 [`createSdkMcpServer`](/zh-TW/agent-sdk/typescript#createsdkmcpserver)(TypeScript)或 [`create_sdk_mcp_server`](/zh-TW/agent-sdk/python#create_sdk_mcp_server)(Python)將其包裝在伺服器中。伺服器在應用程式內同程序執行,而不是作為單獨的程序。
40
41### 天氣工具範例
42
43此範例定義 `get_temperature` 工具並將其包裝在 MCP 伺服器中。它只設定工具;若要將其傳遞至 `query` 並執行它,請參閱下面的[呼叫自訂工具](#call-a-custom-tool)。
44
45<CodeGroup>
46 ```python Python theme={null}
47 from typing import Any
48 import httpx
49 from claude_agent_sdk import tool, create_sdk_mcp_server
50
51
52 # Define a tool: name, description, input schema, handler
53 @tool(
54 "get_temperature",
55 "Get the current temperature at a location",
56 {"latitude": float, "longitude": float},
57 )
58 async def get_temperature(args: dict[str, Any]) -> dict[str, Any]:
59 async with httpx.AsyncClient() as client:
60 response = await client.get(
61 "https://api.open-meteo.com/v1/forecast",
62 params={
63 "latitude": args["latitude"],
64 "longitude": args["longitude"],
65 "current": "temperature_2m",
66 "temperature_unit": "fahrenheit",
67 },
68 )
69 data = response.json()
70
71 # Return a content array - Claude sees this as the tool result
72 return {
73 "content": [
74 {
75 "type": "text",
76 "text": f"Temperature: {data['current']['temperature_2m']}°F",
77 }
78 ]
79 }
80
81
82 # Wrap the tool in an in-process MCP server
83 weather_server = create_sdk_mcp_server(
84 name="weather",
85 version="1.0.0",
86 tools=[get_temperature],
87 )
88 ```
89
90 ```typescript TypeScript theme={null}
91 import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
92 import { z } from "zod";
93
94 // Define a tool: name, description, input schema, handler
95 const getTemperature = tool(
96 "get_temperature",
97 "Get the current temperature at a location",
98 {
99 latitude: z.number().describe("Latitude coordinate"), // .describe() adds a field description Claude sees
100 longitude: z.number().describe("Longitude coordinate")
101 },
102 async (args) => {
103 // args is typed from the schema: { latitude: number; longitude: number }
104 const response = await fetch(
105 `https://api.open-meteo.com/v1/forecast?latitude=${args.latitude}&longitude=${args.longitude}¤t=temperature_2m&temperature_unit=fahrenheit`
106 );
107 const data: any = await response.json();
108
109 // Return a content array - Claude sees this as the tool result
110 return {
111 content: [{ type: "text", text: `Temperature: ${data.current.temperature_2m}°F` }]
112 };
113 }
114 );
115
116 // Wrap the tool in an in-process MCP server
117 const weatherServer = createSdkMcpServer({
118 name: "weather",
119 version: "1.0.0",
120 tools: [getTemperature]
121 });
122 ```
123</CodeGroup>
124
125請參閱 [`tool()`](/zh-TW/agent-sdk/typescript#tool) TypeScript 參考或 [`@tool`](/zh-TW/agent-sdk/python#tool) Python 參考,以取得完整的參數詳細資訊,包括 JSON Schema 輸入格式和傳回值結構。
126
127<Tip>
128 若要使參數成為選用:在 TypeScript 中,將 `.default()` 新增至 Zod 欄位。在 Python 中,字典結構描述將每個鍵視為必需,因此請將參數留出結構描述,在描述字串中提及它,並在處理程式中使用 `args.get()` 讀取它。下面的 [`get_precipitation_chance` 工具](#add-more-tools)顯示兩種模式。
129</Tip>
130
131### 呼叫自訂工具
132
133透過 `mcpServers` 選項將您建立的 MCP 伺服器傳遞至 `query`。`mcpServers` 中的鍵成為每個工具的完全限定名稱中的 `{server_name}` 區段:`mcp__{server_name}__{tool_name}`。在 `allowedTools` 中列出該名稱,以便工具執行而不會出現權限提示。
134
135這些程式碼片段重複使用上面[範例](#weather-tool-example)中的 `weatherServer`,以詢問 Claude 特定位置的天氣。
136
137<CodeGroup>
138 ```python Python theme={null}
139 import asyncio
140 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
141
142
143 async def main():
144 options = ClaudeAgentOptions(
145 mcp_servers={"weather": weather_server},
146 allowed_tools=["mcp__weather__get_temperature"],
147 )
148
149 async for message in query(
150 prompt="What's the temperature in San Francisco?",
151 options=options,
152 ):
153 # ResultMessage is the final message after all tool calls complete
154 if isinstance(message, ResultMessage) and message.subtype == "success":
155 print(message.result)
156
157
158 asyncio.run(main())
159 ```
160
161 ```typescript TypeScript theme={null}
162 import { query } from "@anthropic-ai/claude-agent-sdk";
163
164 for await (const message of query({
165 prompt: "What's the temperature in San Francisco?",
166 options: {
167 mcpServers: { weather: weatherServer },
168 allowedTools: ["mcp__weather__get_temperature"]
169 }
170 })) {
171 // "result" is the final message after all tool calls complete
172 if (message.type === "result" && message.subtype === "success") {
173 console.log(message.result);
174 }
175 }
176 ```
177</CodeGroup>
178
179### 新增更多工具
180
181伺服器在其 `tools` 陣列中列出的工具一樣多。如果有多個工具在伺服器上,您可以在 `allowedTools` 中個別列出每個工具,或使用萬用字元 `mcp__weather__*` 來涵蓋伺服器公開的每個工具。
182
183下面的範例將第二個工具 `get_precipitation_chance` 新增至[天氣工具範例](#weather-tool-example)中的 `weatherServer`,並使用陣列中的兩個工具重建它。
184
185<CodeGroup>
186 ```python Python theme={null}
187 # Define a second tool for the same server
188 @tool(
189 "get_precipitation_chance",
190 "Get the hourly precipitation probability for a location. "
191 "Optionally pass 'hours' (1-24) to control how many hours to return.",
192 {"latitude": float, "longitude": float},
193 )
194 async def get_precipitation_chance(args: dict[str, Any]) -> dict[str, Any]:
195 # 'hours' isn't in the schema - read it with .get() to make it optional
196 hours = args.get("hours", 12)
197 async with httpx.AsyncClient() as client:
198 response = await client.get(
199 "https://api.open-meteo.com/v1/forecast",
200 params={
201 "latitude": args["latitude"],
202 "longitude": args["longitude"],
203 "hourly": "precipitation_probability",
204 "forecast_days": 1,
205 },
206 )
207 data = response.json()
208 chances = data["hourly"]["precipitation_probability"][:hours]
209
210 return {
211 "content": [
212 {
213 "type": "text",
214 "text": f"Next {hours} hours: {'%, '.join(map(str, chances))}%",
215 }
216 ]
217 }
218
219
220 # Rebuild the server with both tools in the array
221 weather_server = create_sdk_mcp_server(
222 name="weather",
223 version="1.0.0",
224 tools=[get_temperature, get_precipitation_chance],
225 )
226 ```
227
228 ```typescript TypeScript theme={null}
229 // Define a second tool for the same server
230 const getPrecipitationChance = tool(
231 "get_precipitation_chance",
232 "Get the hourly precipitation probability for a location",
233 {
234 latitude: z.number(),
235 longitude: z.number(),
236 hours: z
237 .number()
238 .int()
239 .min(1)
240 .max(24)
241 .default(12) // .default() makes the parameter optional
242 .describe("How many hours of forecast to return")
243 },
244 async (args) => {
245 const response = await fetch(
246 `https://api.open-meteo.com/v1/forecast?latitude=${args.latitude}&longitude=${args.longitude}&hourly=precipitation_probability&forecast_days=1`
247 );
248 const data: any = await response.json();
249 const chances = data.hourly.precipitation_probability.slice(0, args.hours);
250
251 return {
252 content: [{ type: "text", text: `Next ${args.hours} hours: ${chances.join("%, ")}%` }]
253 };
254 }
255 );
256
257 // Rebuild the server with both tools in the array
258 const weatherServer = createSdkMcpServer({
259 name: "weather",
260 version: "1.0.0",
261 tools: [getTemperature, getPrecipitationChance]
262 });
263 ```
264</CodeGroup>
265
266此陣列中的每個工具在每個回合都會消耗內容視窗空間。如果您定義了數十個工具,請參閱[工具搜尋](/zh-TW/agent-sdk/tool-search)以改為按需載入它們。
267
268### 新增工具註解
269
270[工具註解](https://modelcontextprotocol.io/docs/concepts/tools#tool-annotations)是描述工具行為方式的選用中繼資料。在 TypeScript 中將它們作為 `tool()` 協助程式的第五個引數傳遞,或在 Python 中透過 `@tool` 裝飾器的 `annotations` 關鍵字引數傳遞。所有提示欄位都是布林值。
271
272| 欄位 | 預設值 | 意義 |
273| :---------------- | :------ | :----------------------------- |
274| `readOnlyHint` | `false` | 工具不會修改其環境。控制工具是否可以與其他唯讀工具平行呼叫。 |
275| `destructiveHint` | `true` | 工具可能執行破壞性更新。僅供參考。 |
276| `idempotentHint` | `false` | 使用相同引數重複呼叫沒有額外效果。僅供參考。 |
277| `openWorldHint` | `true` | 工具到達程序外的系統。僅供參考。 |
278
279註解是中繼資料,不是強制執行。標記為 `readOnlyHint: true` 的工具如果處理程式執行該操作,仍然可以寫入磁碟。保持註解準確反映處理程式。
280
281此範例將 `readOnlyHint` 新增至[天氣工具範例](#weather-tool-example)中的 `get_temperature` 工具。
282
283<CodeGroup>
284 ```python Python theme={null}
285 from claude_agent_sdk import tool, ToolAnnotations
286
287
288 @tool(
289 "get_temperature",
290 "Get the current temperature at a location",
291 {"latitude": float, "longitude": float},
292 annotations=ToolAnnotations(
293 readOnlyHint=True
294 ), # Lets Claude batch this with other read-only calls
295 )
296 async def get_temperature(args):
297 return {"content": [{"type": "text", "text": "..."}]}
298 ```
299
300 ```typescript TypeScript theme={null}
301 tool(
302 "get_temperature",
303 "Get the current temperature at a location",
304 { latitude: z.number(), longitude: z.number() },
305 async (args) => ({ content: [{ type: "text", text: `...` }] }),
306 { annotations: { readOnlyHint: true } } // Lets Claude batch this with other read-only calls
307 );
308 ```
309</CodeGroup>
310
311請參閱 [TypeScript](/zh-TW/agent-sdk/typescript#toolannotations) 或 [Python](/zh-TW/agent-sdk/python#toolannotations) 參考中的 `ToolAnnotations`。
312
313## 控制工具存取
314
315[天氣工具範例](#weather-tool-example)註冊了伺服器並在 `allowedTools` 中列出了工具。本節涵蓋工具名稱的構造方式,以及當您有多個工具或想要限制內建工具時如何限制存取。
316
317### 工具名稱格式
318
319當 MCP 工具公開給 Claude 時,它們的名稱遵循特定格式:
320
321* 模式:`mcp__{server_name}__{tool_name}`
322* 範例:伺服器 `weather` 中名為 `get_temperature` 的工具變成 `mcp__weather__get_temperature`
323
324### 設定允許的工具
325
326`tools` 選項和允許/不允許清單在不同層級上運作。`tools` 控制哪些內建工具出現在 Claude 的內容中。允許和不允許工具清單控制 Claude 嘗試呼叫後是否核准或拒絕呼叫。
327
328| 選項 | 層級 | 效果 |
329| :------------------------ | :-- | :--------------------------------------------------------------------- |
330| `tools: ["Read", "Grep"]` | 可用性 | 只有列出的內建工具在 Claude 的內容中。未列出的內建工具會被移除。MCP 工具不受影響。 |
331| `tools: []` | 可用性 | 所有內建工具都被移除。Claude 只能使用您的 MCP 工具。 |
332| 允許的工具 | 權限 | 列出的工具執行時不會出現權限提示。未列出的工具保持可用;呼叫會通過[權限流程](/zh-TW/agent-sdk/permissions)。 |
333| 不允許的工具 | 權限 | 對列出的工具的每次呼叫都被拒絕。工具保留在 Claude 的內容中,因此 Claude 可能仍會在呼叫被拒絕之前嘗試它。 |
334
335若要限制 Claude 可以使用哪些內建工具,請優先使用 `tools` 而不是不允許的工具。從 `tools` 中省略工具會將其從內容中移除,以便 Claude 永遠不會嘗試它;在 `disallowedTools` 中列出它(Python:`disallowed_tools`)會阻止呼叫,但保留工具可見,因此 Claude 可能會浪費一個回合嘗試它。請參閱[設定權限](/zh-TW/agent-sdk/permissions)以取得完整的評估順序。
336
337## 處理錯誤
338
339您的處理程式報告錯誤的方式決定代理迴圈是繼續還是停止:
340
341| 發生的情況 | 結果 |
342| :---------------------------------------------------------- | :--------------------------------------- |
343| 處理程式擲出未捕獲的例外 | 代理迴圈停止。Claude 永遠看不到錯誤,`query` 呼叫失敗。 |
344| 處理程式捕獲錯誤並傳回 `isError: true`(TS)/ `"is_error": True`(Python) | 代理迴圈繼續。Claude 將錯誤視為資料並可以重試、嘗試不同的工具或解釋失敗。 |
345
346下面的範例在處理程式內捕獲兩種失敗,而不是讓它們擲出。非 200 HTTP 狀態從回應中捕獲並作為錯誤結果傳回。網路錯誤或無效 JSON 由周圍的 `try/except`(Python)或 `try/catch`(TypeScript)捕獲,也作為錯誤結果傳回。在兩種情況下,處理程式正常傳回,代理迴圈繼續。
347
348<CodeGroup>
349 ```python Python theme={null}
350 import json
351 import httpx
352 from typing import Any
353
354
355 @tool(
356 "fetch_data",
357 "Fetch data from an API",
358 {"endpoint": str}, # Simple schema
359 )
360 async def fetch_data(args: dict[str, Any]) -> dict[str, Any]:
361 try:
362 async with httpx.AsyncClient() as client:
363 response = await client.get(args["endpoint"])
364 if response.status_code != 200:
365 # Return the failure as a tool result so Claude can react to it.
366 # is_error marks this as a failed call rather than odd-looking data.
367 return {
368 "content": [
369 {
370 "type": "text",
371 "text": f"API error: {response.status_code} {response.reason_phrase}",
372 }
373 ],
374 "is_error": True,
375 }
376
377 data = response.json()
378 return {"content": [{"type": "text", "text": json.dumps(data, indent=2)}]}
379 except Exception as e:
380 # Catching here keeps the agent loop alive. An uncaught exception
381 # would end the whole query() call.
382 return {
383 "content": [{"type": "text", "text": f"Failed to fetch data: {str(e)}"}],
384 "is_error": True,
385 }
386 ```
387
388 ```typescript TypeScript theme={null}
389 tool(
390 "fetch_data",
391 "Fetch data from an API",
392 {
393 endpoint: z.string().url().describe("API endpoint URL")
394 },
395 async (args) => {
396 try {
397 const response = await fetch(args.endpoint);
398
399 if (!response.ok) {
400 // Return the failure as a tool result so Claude can react to it.
401 // isError marks this as a failed call rather than odd-looking data.
402 return {
403 content: [
404 {
405 type: "text",
406 text: `API error: ${response.status} ${response.statusText}`
407 }
408 ],
409 isError: true
410 };
411 }
412
413 const data = await response.json();
414 return {
415 content: [
416 {
417 type: "text",
418 text: JSON.stringify(data, null, 2)
419 }
420 ]
421 };
422 } catch (error) {
423 // Catching here keeps the agent loop alive. An uncaught throw
424 // would end the whole query() call.
425 return {
426 content: [
427 {
428 type: "text",
429 text: `Failed to fetch data: ${error instanceof Error ? error.message : String(error)}`
430 }
431 ],
432 isError: true
433 };
434 }
435 }
436 );
437 ```
438</CodeGroup>
439
440## 傳回影像和資源
441
442工具結果中的 `content` 陣列接受 `text`、`image` 和 `resource` 區塊。您可以在同一回應中混合它們。
443
444### 影像
445
446影像區塊以 base64 編碼的方式內聯攜帶影像位元組。沒有 URL 欄位。若要傳回位於 URL 的影像,請在處理程式中擷取它、讀取回應位元組,並在傳回前進行 base64 編碼。結果作為視覺輸入進行處理。
447
448| 欄位 | 類型 | 備註 |
449| :--------- | :-------- | :------------------------------------------------------ |
450| `type` | `"image"` | |
451| `data` | `string` | Base64 編碼的位元組。僅原始 base64,沒有 `data:image/...;base64,` 前綴 |
452| `mimeType` | `string` | 必需。例如 `image/png`、`image/jpeg`、`image/webp`、`image/gif` |
453
454<CodeGroup>
455 ```python Python theme={null}
456 import base64
457 import httpx
458
459
460 # Define a tool that fetches an image from a URL and returns it to Claude
461 @tool("fetch_image", "Fetch an image from a URL and return it to Claude", {"url": str})
462 async def fetch_image(args):
463 async with httpx.AsyncClient() as client: # Fetch the image bytes
464 response = await client.get(args["url"])
465
466 return {
467 "content": [
468 {
469 "type": "image",
470 "data": base64.b64encode(response.content).decode(
471 "ascii"
472 ), # Base64-encode the raw bytes
473 "mimeType": response.headers.get(
474 "content-type", "image/png"
475 ), # Read MIME type from the response
476 }
477 ]
478 }
479 ```
480
481 ```typescript TypeScript theme={null}
482 tool(
483 "fetch_image",
484 "Fetch an image from a URL and return it to Claude",
485 {
486 url: z.string().url()
487 },
488 async (args) => {
489 const response = await fetch(args.url); // Fetch the image bytes
490 const buffer = Buffer.from(await response.arrayBuffer()); // Read into a Buffer for base64 encoding
491 const mimeType = response.headers.get("content-type") ?? "image/png";
492
493 return {
494 content: [
495 {
496 type: "image",
497 data: buffer.toString("base64"), // Base64-encode the raw bytes
498 mimeType
499 }
500 ]
501 };
502 }
503 );
504 ```
505</CodeGroup>
506
507### 資源
508
509資源區塊嵌入由 URI 識別的內容片段。URI 是 Claude 參考的標籤;實際內容位於區塊的 `text` 或 `blob` 欄位中。當您的工具產生稍後按名稱尋址有意義的內容時使用此項,例如生成的檔案或來自外部系統的記錄。
510
511| 欄位 | 類型 | 備註 |
512| :------------------ | :----------- | :----------------------------- |
513| `type` | `"resource"` | |
514| `resource.uri` | `string` | 內容的識別碼。任何 URI 配置 |
515| `resource.text` | `string` | 內容,如果是文字。提供此項或 `blob`,不要同時提供兩者 |
516| `resource.blob` | `string` | 內容 base64 編碼,如果是二進位 |
517| `resource.mimeType` | `string` | 選用 |
518
519此範例顯示從工具處理程式內傳回的資源區塊。URI `file:///tmp/report.md` 是 Claude 稍後可以參考的標籤;SDK 不會從該路徑讀取。
520
521<CodeGroup>
522 ```typescript TypeScript theme={null}
523 return {
524 content: [
525 {
526 type: "resource",
527 resource: {
528 uri: "file:///tmp/report.md", // Label for Claude to reference, not a path the SDK reads
529 mimeType: "text/markdown",
530 text: "# Report\n..." // The actual content, inline
531 }
532 }
533 ]
534 };
535 ```
536
537 ```python Python theme={null}
538 return {
539 "content": [
540 {
541 "type": "resource",
542 "resource": {
543 "uri": "file:///tmp/report.md", # Label for Claude to reference, not a path the SDK reads
544 "mimeType": "text/markdown",
545 "text": "# Report\n...", # The actual content, inline
546 },
547 }
548 ]
549 }
550 ```
551</CodeGroup>
552
553這些區塊形狀來自 MCP `CallToolResult` 類型。請參閱 [MCP 規格](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result)以取得完整定義。
554
555## 傳回結構化資料
556
557`structuredContent` 是結果上的選用 JSON 物件,與 `content` 陣列分開。使用它傳回原始值,Claude 可以將其讀取為確切欄位,而不是從文字字串或影像中解析它們。
558
559設定 `structuredContent` 時,Claude 接收 JSON 加上 `content` 中的任何影像或資源區塊。`content` 中的文字區塊不會轉發,因為假設它們複製結構化資料。下面的範例將圖表呈現為影像區塊,並從同一處理程式在 `structuredContent` 中傳回其背後的資料點。
560
561```typescript TypeScript theme={null}
562return {
563 content: [
564 {
565 type: "image",
566 data: chartPngBuffer.toString("base64"),
567 mimeType: "image/png"
568 }
569 ],
570 structuredContent: {
571 series: "temperature_2m",
572 unit: "fahrenheit",
573 points: [62.1, 63.4, 65.0, 64.2]
574 }
575};
576```
577
578<Note>
579 Python `@tool` 裝飾器僅從處理程式的傳回字典轉發 `content` 和 `is_error`。若要從 Python 傳回 `structuredContent`,請改為執行[獨立 MCP 伺服器](/zh-TW/agent-sdk/mcp)。
580</Note>
581
582## 範例:單位轉換器
583
584此工具在長度、溫度和重量的單位之間轉換值。使用者可以詢問「將 100 公里轉換為英里」或「72°F 是多少攝氏度」,Claude 從請求中選擇正確的單位類型和單位。
585
586它演示了兩種模式:
587
588* **列舉結構描述:** `unit_type` 受限於一組固定值。在 TypeScript 中,使用 `z.enum()`。在 Python 中,字典結構描述不支援列舉,因此需要完整的 JSON Schema 字典。
589* **不支援的輸入處理:** 當找不到轉換對時,處理程式傳回 `isError: true`,以便 Claude 可以告訴使用者出了什麼問題,而不是將失敗視為正常結果。
590
591<CodeGroup>
592 ```python Python theme={null}
593 from typing import Any
594 from claude_agent_sdk import tool, create_sdk_mcp_server
595
596
597 # z.enum() in TypeScript becomes an "enum" constraint in JSON Schema.
598 # The dict schema has no equivalent, so full JSON Schema is required.
599 @tool(
600 "convert_units",
601 "Convert a value from one unit to another",
602 {
603 "type": "object",
604 "properties": {
605 "unit_type": {
606 "type": "string",
607 "enum": ["length", "temperature", "weight"],
608 "description": "Category of unit",
609 },
610 "from_unit": {
611 "type": "string",
612 "description": "Unit to convert from, e.g. kilometers, fahrenheit, pounds",
613 },
614 "to_unit": {"type": "string", "description": "Unit to convert to"},
615 "value": {"type": "number", "description": "Value to convert"},
616 },
617 "required": ["unit_type", "from_unit", "to_unit", "value"],
618 },
619 )
620 async def convert_units(args: dict[str, Any]) -> dict[str, Any]:
621 conversions = {
622 "length": {
623 "kilometers_to_miles": lambda v: v * 0.621371,
624 "miles_to_kilometers": lambda v: v * 1.60934,
625 "meters_to_feet": lambda v: v * 3.28084,
626 "feet_to_meters": lambda v: v * 0.3048,
627 },
628 "temperature": {
629 "celsius_to_fahrenheit": lambda v: (v * 9) / 5 + 32,
630 "fahrenheit_to_celsius": lambda v: (v - 32) * 5 / 9,
631 "celsius_to_kelvin": lambda v: v + 273.15,
632 "kelvin_to_celsius": lambda v: v - 273.15,
633 },
634 "weight": {
635 "kilograms_to_pounds": lambda v: v * 2.20462,
636 "pounds_to_kilograms": lambda v: v * 0.453592,
637 "grams_to_ounces": lambda v: v * 0.035274,
638 "ounces_to_grams": lambda v: v * 28.3495,
639 },
640 }
641
642 key = f"{args['from_unit']}_to_{args['to_unit']}"
643 fn = conversions.get(args["unit_type"], {}).get(key)
644
645 if not fn:
646 return {
647 "content": [
648 {
649 "type": "text",
650 "text": f"Unsupported conversion: {args['from_unit']} to {args['to_unit']}",
651 }
652 ],
653 "is_error": True,
654 }
655
656 result = fn(args["value"])
657 return {
658 "content": [
659 {
660 "type": "text",
661 "text": f"{args['value']} {args['from_unit']} = {result:.4f} {args['to_unit']}",
662 }
663 ]
664 }
665
666
667 converter_server = create_sdk_mcp_server(
668 name="converter",
669 version="1.0.0",
670 tools=[convert_units],
671 )
672 ```
673
674 ```typescript TypeScript theme={null}
675 import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
676 import { z } from "zod";
677
678 const convert = tool(
679 "convert_units",
680 "Convert a value from one unit to another",
681 {
682 unit_type: z.enum(["length", "temperature", "weight"]).describe("Category of unit"),
683 from_unit: z
684 .string()
685 .describe("Unit to convert from, e.g. kilometers, fahrenheit, pounds"),
686 to_unit: z.string().describe("Unit to convert to"),
687 value: z.number().describe("Value to convert")
688 },
689 async (args) => {
690 type Conversions = Record<string, Record<string, (v: number) => number>>;
691
692 const conversions: Conversions = {
693 length: {
694 kilometers_to_miles: (v) => v * 0.621371,
695 miles_to_kilometers: (v) => v * 1.60934,
696 meters_to_feet: (v) => v * 3.28084,
697 feet_to_meters: (v) => v * 0.3048
698 },
699 temperature: {
700 celsius_to_fahrenheit: (v) => (v * 9) / 5 + 32,
701 fahrenheit_to_celsius: (v) => ((v - 32) * 5) / 9,
702 celsius_to_kelvin: (v) => v + 273.15,
703 kelvin_to_celsius: (v) => v - 273.15
704 },
705 weight: {
706 kilograms_to_pounds: (v) => v * 2.20462,
707 pounds_to_kilograms: (v) => v * 0.453592,
708 grams_to_ounces: (v) => v * 0.035274,
709 ounces_to_grams: (v) => v * 28.3495
710 }
711 };
712
713 const key = `${args.from_unit}_to_${args.to_unit}`;
714 const fn = conversions[args.unit_type]?.[key];
715
716 if (!fn) {
717 return {
718 content: [
719 {
720 type: "text",
721 text: `Unsupported conversion: ${args.from_unit} to ${args.to_unit}`
722 }
723 ],
724 isError: true
725 };
726 }
727
728 const result = fn(args.value);
729 return {
730 content: [
731 {
732 type: "text",
733 text: `${args.value} ${args.from_unit} = ${result.toFixed(4)} ${args.to_unit}`
734 }
735 ]
736 };
737 }
738 );
739
740 const converterServer = createSdkMcpServer({
741 name: "converter",
742 version: "1.0.0",
743 tools: [convert]
744 });
745 ```
746</CodeGroup>
747
748定義伺服器後,以與天氣範例相同的方式將其傳遞至 `query`。此範例在迴圈中傳送三個不同的提示,以顯示同一工具處理不同的單位類型。對於每個回應,它檢查 `AssistantMessage` 物件(包含 Claude 在該回合期間進行的工具呼叫)並在列印最終 `ResultMessage` 文字之前列印每個 `ToolUseBlock`。這讓您看到 Claude 何時使用工具與從自己的知識回答。
749
750<CodeGroup>
751 ```python Python theme={null}
752 import asyncio
753 from claude_agent_sdk import (
754 query,
755 ClaudeAgentOptions,
756 ResultMessage,
757 AssistantMessage,
758 ToolUseBlock,
759 )
760
761
762 async def main():
763 options = ClaudeAgentOptions(
764 mcp_servers={"converter": converter_server},
765 allowed_tools=["mcp__converter__convert_units"],
766 )
767
768 prompts = [
769 "Convert 100 kilometers to miles.",
770 "What is 72°F in Celsius?",
771 "How many pounds is 5 kilograms?",
772 ]
773
774 for prompt in prompts:
775 async for message in query(prompt=prompt, options=options):
776 if isinstance(message, AssistantMessage):
777 for block in message.content:
778 if isinstance(block, ToolUseBlock):
779 print(f"[tool call] {block.name}({block.input})")
780 elif isinstance(message, ResultMessage) and message.subtype == "success":
781 print(f"Q: {prompt}\nA: {message.result}\n")
782
783
784 asyncio.run(main())
785 ```
786
787 ```typescript TypeScript theme={null}
788 import { query } from "@anthropic-ai/claude-agent-sdk";
789
790 const prompts = [
791 "Convert 100 kilometers to miles.",
792 "What is 72°F in Celsius?",
793 "How many pounds is 5 kilograms?"
794 ];
795
796 for (const prompt of prompts) {
797 for await (const message of query({
798 prompt,
799 options: {
800 mcpServers: { converter: converterServer },
801 allowedTools: ["mcp__converter__convert_units"]
802 }
803 })) {
804 if (message.type === "assistant") {
805 for (const block of message.message.content) {
806 if (block.type === "tool_use") {
807 console.log(`[tool call] ${block.name}`, block.input);
808 }
809 }
810 } else if (message.type === "result" && message.subtype === "success") {
811 console.log(`Q: ${prompt}\nA: ${message.result}\n`);
812 }
813 }
814 }
815 ```
816</CodeGroup>
817
818## 後續步驟
819
820自訂工具在標準介面中包裝非同步函數。您可以在同一伺服器中混合本頁上的模式:單一伺服器可以並排保存資料庫工具、API 閘道工具和影像呈現器。
821
822從這裡:
823
824* 如果您的伺服器增長到數十個工具,請參閱[工具搜尋](/zh-TW/agent-sdk/tool-search)以延遲載入它們,直到 Claude 需要它們。
825* 若要連接到外部 MCP 伺服器(檔案系統、GitHub、Slack)而不是建立自己的,請參閱[連接 MCP 伺服器](/zh-TW/agent-sdk/mcp)。
826* 若要控制哪些工具自動執行與需要核准,請參閱[設定權限](/zh-TW/agent-sdk/permissions)。
827
828## 相關文件
829
830* [TypeScript SDK 參考](/zh-TW/agent-sdk/typescript)
831* [Python SDK 參考](/zh-TW/agent-sdk/python)
832* [MCP 文件](https://modelcontextprotocol.io)
833* [SDK 概觀](/zh-TW/agent-sdk/overview)