15| 如果您想要... | 執行此操作 |15| 如果您想要... | 執行此操作 |
16| :- | :- |16| :- | :- |
17| 定義工具 | 使用 [`@tool`](/docs/zh-TW/agent-sdk/python#tool)(Python)或 [`tool()`](/docs/zh-TW/agent-sdk/typescript#tool)(TypeScript),搭配名稱、描述、結構描述和處理程式。請參閱[建立自訂工具](#create-a-custom-tool)。 |17| 定義工具 | 使用 [`@tool`](/docs/zh-TW/agent-sdk/python#tool)(Python)或 [`tool()`](/docs/zh-TW/agent-sdk/typescript#tool)(TypeScript),搭配名稱、描述、結構描述和處理程式。請參閱[建立自訂工具](#create-a-custom-tool)。 |
18| 將參數設為選用 | 在 schema 中將其宣告為選用,並在處理程式中套用預設值。請參閱[將參數設為選用](#make-a-parameter-optional)。 |
18| 向 Claude 註冊工具 | 在 `create_sdk_mcp_server` / `createSdkMcpServer` 中包裝,並傳遞至 `query()` 中的 `mcpServers`。請參閱[呼叫自訂工具](#call-a-custom-tool)。 |19| 向 Claude 註冊工具 | 在 `create_sdk_mcp_server` / `createSdkMcpServer` 中包裝,並傳遞至 `query()` 中的 `mcpServers`。請參閱[呼叫自訂工具](#call-a-custom-tool)。 |
19| 預先核准工具 | 新增至您允許的工具。請參閱[設定允許的工具](#configure-allowed-tools)。 |20| 預先核准工具 | 新增至您允許的工具。請參閱[設定允許的工具](#configure-allowed-tools)。 |
20| 從 Claude 的內容中移除內建工具 | 傳遞 `tools` 陣列,僅列出您想要的內建工具。請參閱[設定允許的工具](#configure-allowed-tools)。 |21| 從 Claude 的內容中移除內建工具 | 傳遞 `tools` 陣列,僅列出您想要的內建工具。請參閱[設定允許的工具](#configure-allowed-tools)。 |
32 33
33* **名稱:** Claude 用來呼叫工具的唯一識別碼。34* **名稱:** Claude 用來呼叫工具的唯一識別碼。
34* **描述:** 工具的功能。Claude 讀取此項以決定何時呼叫它。35* **描述:** 工具的功能。Claude 讀取此項以決定何時呼叫它。
35* **輸入綱要:** Claude 必須提供的引數。在 TypeScript 中,這始終是 [Zod 綱要](https://zod.dev/),處理程式的 `args` 會自動從中輸入。在 Python 中,這是將名稱對應到類型的字典,例如 `{"latitude": float}`,SDK 會為您將其轉換為 JSON 綱要。Python 裝飾器也接受完整的 [JSON 綱要](https://json-schema.org/understanding-json-schema/about)字典,當您需要列舉、範圍、選用欄位或巢狀物件時。36* **輸入 schema:** 工具接受的引數,依語言宣告:
37 * **TypeScript**:[Zod schema](https://zod.dev/)。處理程式的 `args` 會從中取得其類型。在欄位上呼叫 `.describe()`,即可為其提供 Claude 看得到的描述。
38 * **Python**:將名稱對應到類型的字典,例如 `{"latitude": float}`,SDK 會為您將其轉換為 JSON Schema。將類型包裝在 `Annotated` 中,例如 `{"latitude": Annotated[float, "Latitude coordinate"]}`,即可為欄位提供 Claude 看得到的描述。當您需要列舉、範圍、選用欄位或巢狀物件時,裝飾器也可直接接受完整的 [JSON Schema](https://json-schema.org/understanding-json-schema/about) 字典。
36* **處理程式:** Claude 呼叫工具時執行的非同步函式。它接收已驗證的引數,並且必須傳回包含以下內容的物件:39* **處理程式:** Claude 呼叫工具時執行的非同步函式。它接收已驗證的引數,並且必須傳回包含以下內容的物件:
37 * `content`(必需):結果區塊的陣列,每個區塊的 `type` 為 `"text"`、`"image"`、`"audio"`、`"resource"` 或 `"resource_link"`。請參閱[傳回影像和資源](#return-images-and-resources)以了解非文字區塊。40 * `content`(必需):結果區塊的陣列,每個區塊的 `type` 為 `"text"`、`"image"`、`"audio"`、`"resource"` 或 `"resource_link"`。請參閱[傳回影像和資源](#return-images-and-resources)以了解非文字區塊。
38 * `structuredContent`(選用):保存結果作為機器可讀資料的 JSON 物件,與 `content` 一起傳回。請參閱[傳回結構化資料](#return-structured-data)。41 * `structuredContent`(選用):保存結果作為機器可讀資料的 JSON 物件,與 `content` 一起傳回。請參閱[傳回結構化資料](#return-structured-data)。
40 43
41定義工具後,使用 [`createSdkMcpServer`](/docs/zh-TW/agent-sdk/typescript#createsdkmcpserver)(TypeScript)或 [`create_sdk_mcp_server`](/docs/zh-TW/agent-sdk/python#create_sdk_mcp_server)(Python)將其包裝在伺服器中。伺服器在應用程式內部以同步程序執行,而不是作為單獨的程序。44定義工具後,使用 [`createSdkMcpServer`](/docs/zh-TW/agent-sdk/typescript#createsdkmcpserver)(TypeScript)或 [`create_sdk_mcp_server`](/docs/zh-TW/agent-sdk/python#create_sdk_mcp_server)(Python)將其包裝在伺服器中。伺服器在應用程式內部以同步程序執行,而不是作為單獨的程序。
42 45
46本頁中發出 HTTP 請求的 Python 範例使用 [httpx](https://www.python-httpx.org/)。請使用專案所用的套件管理工具新增它:
47
48<Tabs>
49 <Tab title="Python (uv)">
50 ```bash theme={null}
51 uv add httpx
52 ```
53 </Tab>
54
55 <Tab title="Python (pip)">
56 ```bash theme={null}
57 pip install httpx
58 ```
59 </Tab>
60</Tabs>
61
43<h3 id="weather-tool-example">62<h3 id="weather-tool-example">
44 天氣工具範例63 天氣工具範例
45</h3>64</h3>
46 65
47此範例定義 `get_temperature` 工具並將其包裝在 MCP 伺服器中。它只設定工具;若要將其傳遞給 `query` 並執行它,請參閱下面的[呼叫自訂工具](#call-a-custom-tool)。66此範例定義 `get_temperature` 工具並將其包裝在 MCP 伺服器中,但不將伺服器傳遞給 `query`。若要執行工具,請參閱下面的[呼叫自訂工具](#call-a-custom-tool)。
48 67
49<CodeGroup>68<CodeGroup>
50 ```python Python theme={null}69 ```python Python theme={null}
51 from typing import Any70 from typing import Annotated, Any
52 import httpx71 import httpx
53 from claude_agent_sdk import tool, create_sdk_mcp_server72 from claude_agent_sdk import tool, create_sdk_mcp_server
54 73
57 @tool(76 @tool(
58 "get_temperature",77 "get_temperature",
59 "Get the current temperature at a location",78 "Get the current temperature at a location",
60 {"latitude": float, "longitude": float},79 {
80 "latitude": Annotated[float, "Latitude coordinate"],
81 "longitude": Annotated[float, "Longitude coordinate"],
82 },
61 )83 )
62 async def get_temperature(args: dict[str, Any]) -> dict[str, Any]:84 async def get_temperature(args: dict[str, Any]) -> dict[str, Any]:
63 async with httpx.AsyncClient() as client:85 async with httpx.AsyncClient() as client:
128 150
129請參閱 [`tool()`](/docs/zh-TW/agent-sdk/typescript#tool) TypeScript 參考或 [`@tool`](/docs/zh-TW/agent-sdk/python#tool) Python 參考以取得完整的參數詳細資訊,包括 JSON 綱要輸入格式和傳回值結構。151請參閱 [`tool()`](/docs/zh-TW/agent-sdk/typescript#tool) TypeScript 參考或 [`@tool`](/docs/zh-TW/agent-sdk/python#tool) Python 參考以取得完整的參數詳細資訊,包括 JSON 綱要輸入格式和傳回值結構。
130 152
131<Tip>153<h3 id="make-a-parameter-optional">
132 若要使參數成為選用:在 TypeScript 中,將 `.optional()` 新增至 Zod 欄位,並在處理程式中套用預設值。在 Python 中,字典綱要將每個鍵視為必需,因此請將參數留出綱要,在描述字串中提及它,並在處理程式中使用 `args.get()` 讀取它。下面的 [`get_precipitation_chance` 工具](#add-more-tools)顯示兩種模式。154 將參數設為選用
133</Tip>155</h3>
156
157若要將參數設為選用,請在 schema 中將其宣告為選用,並在處理程式中套用預設值:
158
159* **TypeScript**:將 `.optional()` 新增至 Zod 欄位。
160* **Python**:字典 schema 要求每個鍵都必須提供。請使用 JSON Schema 形式,將該參數排除在 `required` 之外,並使用 `args.get()` 讀取它。若要使用具有選用鍵的型別化 schema,請參閱 [TypedDict 類別](/docs/zh-TW/agent-sdk/python#input-schema-options)。
161
162[下面的 `get_precipitation_chance` 工具](#add-more-tools)顯示兩種模式。
134 163
135<h3 id="call-a-custom-tool">164<h3 id="call-a-custom-tool">
136 呼叫自訂工具165 呼叫自訂工具
182 ```211 ```
183</CodeGroup>212</CodeGroup>
184 213
185將此程式碼片段與[天氣工具範例](#weather-tool-example)中的工具和伺服器定義結合在一個檔案中,然後使用 `python weather.py`(Python)或 `npx tsx weather.ts`(TypeScript)執行它。Claude 呼叫 `get_temperature`,指令碼會列印一行答案,顯示舊金山目前的溫度。214將此程式碼片段與[天氣工具範例](#weather-tool-example)中的工具和伺服器定義結合在一個檔案 `weather.py` 或 `weather.ts` 中,然後從終端機執行它:
215
216<Tabs>
217 <Tab title="TypeScript">
218 ```bash theme={null}
219 npx tsx weather.ts
220 ```
221 </Tab>
222
223 <Tab title="Python (uv)">
224 ```bash theme={null}
225 uv run weather.py
226 ```
227 </Tab>
228
229 <Tab title="Python (pip)">
230 啟用您安裝 SDK 的虛擬環境,然後執行:
231
232 ```bash theme={null}
233 python weather.py
234 ```
235 </Tab>
236</Tabs>
237
238Claude 呼叫 `get_temperature`,指令碼會列印一行答案,顯示舊金山目前的溫度。
186 239
187<h3 id="add-more-tools">240<h3 id="add-more-tools">
188 新增更多工具241 新增更多工具
197 # Define a second tool for the same server250 # Define a second tool for the same server
198 @tool(251 @tool(
199 "get_precipitation_chance",252 "get_precipitation_chance",
200 "Get the hourly precipitation probability for a location. "253 "Get the hourly precipitation probability for a location",
201 "Optionally pass 'hours' (1-24) to control how many hours to return.",254 {
202 {"latitude": float, "longitude": float},255 "type": "object",
256 "properties": {
257 "latitude": {"type": "number"},
258 "longitude": {"type": "number"},
259 "hours": {
260 "type": "integer",
261 "minimum": 1,
262 "maximum": 24,
263 "description": "How many hours of forecast to return",
264 },
265 },
266 # 'hours' is left out of required, so Claude can omit it
267 "required": ["latitude", "longitude"],
268 },
203 )269 )
204 async def get_precipitation_chance(args: dict[str, Any]) -> dict[str, Any]:270 async def get_precipitation_chance(args: dict[str, Any]) -> dict[str, Any]:
205 # 'hours' isn't in the schema - read it with .get() to make it optional271 # 'hours' isn't in required - read it with .get() to fall back to a default
206 hours = args.get("hours", 12)272 hours = args.get("hours", 12)
207 async with httpx.AsyncClient() as client:273 async with httpx.AsyncClient() as client:
208 response = await client.get(274 response = await client.get(