---
title: 工具搜尋工具
url: https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool
description: 讓 Claude 搜尋您的工具目錄並僅載入所需的工具，從而擴展至數百或數千個工具。
---

工具搜尋工具（tool search tool）讓 Claude 能夠透過按需探索與載入工具，來處理數百或數千個工具。Claude 不會預先將所有工具定義載入「context window」（上下文視窗），而是搜尋您的工具目錄（包括工具名稱、描述、引數名稱與引數描述），並僅載入所需的工具。

隨著工具庫的成長，預先載入每個工具定義會造成兩個問題：

* **上下文膨脹：** 典型的多伺服器設定（GitHub、Slack、Sentry、Grafana 與 Splunk）在 Claude 開始任何工作之前，光是定義就可能消耗約 55k 個 token。工具搜尋通常可將此減少超過 85%，僅載入 Claude 針對特定請求所需的 3–5 個工具。
* **工具選擇準確度：** 一旦可用工具超過 30–50 個，Claude 挑選正確工具的能力就會下降。由於工具搜尋僅按需載入一組聚焦的相關工具，即使面對數千個工具，選擇準確度仍能維持在高水準。

關於支援工具搜尋的模型，請參閱[模型相容性](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool#model-compatibility)。

<Tip>
  關於工具搜尋所解決之擴展挑戰的背景資訊，請參閱 [Advanced tool use](https://www.anthropic.com/engineering/advanced-tool-use)。工具搜尋的按需載入也是 [Effective context engineering](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) 中所描述之更廣泛的即時檢索（just-in-time retrieval）原則的一個實例。
</Tip>

工具搜尋以伺服器端工具的形式執行，但您也可以實作自己的用戶端工具搜尋。詳情請參閱[自訂工具搜尋實作](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool#custom-tool-search-implementation)。

<Note>
  請透過[意見回饋表單](https://forms.gle/MhcGFFwLxuwnWTkYA)分享您對此功能的意見。
</Note>

<Note>
  若要了解「zero data retention」（零資料保留），即 ZDR 如何適用於此功能，請參閱 [API 與資料保留](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention)。
</Note>

<Warning>
  在 Amazon Bedrock 上，伺服器端工具搜尋僅可透過 [InvokeModel API](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-runtime_example_bedrock-runtime_InvokeModel_AnthropicClaude_section.html) 使用，而非 Converse API。
</Warning>

<Note>
  在 [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws) 上，伺服器端工具搜尋的運作方式與 Claude API 完全相同。Claude Platform on AWS 直接使用 Anthropic Messages API，因此沒有 InvokeModel 或 Converse 的區別。
</Note>

## 模型相容性

兩種工具搜尋變體皆可在以下模型上使用：

| 模型                                                                                                                            | 工具版本                                                                |
| ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| Claude Fable 5.1 (claude-fable-5-1)                                                                                           | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Mythos 5.1 (claude-mythos-5-1)                                                                                         | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Fable 5 (claude-fable-5)                                                                                               | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Mythos 5 (claude-mythos-5)                                                                                             | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Opus 5.5 (claude-opus-5-5)                                                                                             | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Opus 5 (claude-opus-5)                                                                                                 | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Sonnet 5.5 (claude-sonnet-5-5)                                                                                         | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Sonnet 5 (claude-sonnet-5)                                                                                             | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Haiku 5.5 (claude-haiku-5-5)                                                                                           | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Opus 4.8 (claude-opus-4-8)                                                                                             | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Opus 4.7 (claude-opus-4-7)                                                                                             | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Opus 4.6 (claude-opus-4-6)                                                                                             | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Sonnet 4.6 (claude-sonnet-4-6)                                                                                         | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Opus 4.5 (claude-opus-4-5-20251101)                                                                                    | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Sonnet 4.5 (claude-sonnet-4-5-20250929)（[已棄用](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations)） | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Haiku 4.5 (claude-haiku-4-5-20251001)                                                                                  | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |

Claude Opus 4.1 及更早的模型不支援工具搜尋工具。

## 工具搜尋的運作方式

工具搜尋有兩種變體：

* **Regex**（`tool_search_tool_regex_20251119`）：Claude 建構正規表示式（regex）模式來搜尋工具。
* **BM25**（`tool_search_tool_bm25_20251119`）：Claude 使用自然語言查詢來搜尋工具。

當您啟用工具搜尋工具時：

1. 您在 `tools` 清單中加入一個工具搜尋工具（例如 `tool_search_tool_regex_20251119` 或 `tool_search_tool_bm25_20251119`）。
2. 您在 `tools` 陣列中提供每個工具定義，並在不應預先載入的工具上設定 `defer_loading: true`。至少必須有一個工具（通常是工具搜尋工具本身）保持非延遲狀態。
3. 一開始，Claude 的上下文僅包含工具搜尋工具以及任何非延遲的工具。
4. 當 Claude 需要額外的工具時，它會使用工具搜尋工具進行搜尋。
5. API 執行搜尋，並以 `tool_reference` 區塊的形式回傳相符的工具（預設最多 5 個；Claude 可在其搜尋輸入中設定 `limit`）。
6. API 會自動將這些參照展開為完整的工具定義。
7. Claude 從探索到的工具中進行選擇並呼叫它們。

## 快速開始

下列範例包含工具搜尋工具與兩個延遲載入的工具：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
      -H "x-api-key: $ANTHROPIC_API_KEY" \
      -H "anthropic-version: 2023-06-01" \
      -H "content-type: application/json" \
      -d '{
          "model": "claude-opus-5-5",
          "max_tokens": 2048,
          "messages": [
              {
                  "role": "user",
                  "content": "What is the weather in San Francisco?"
              }
          ],
          "tools": [
              {
                  "type": "tool_search_tool_regex_20251119",
                  "name": "tool_search_tool_regex"
              },
              {
                  "name": "get_weather",
                  "description": "Get the weather at a specific location",
                  "input_schema": {
                      "type": "object",
                      "properties": {
                          "location": {"type": "string"},
                          "unit": {
                              "type": "string",
                              "enum": ["celsius", "fahrenheit"]
                          }
                      },
                      "required": ["location"]
                  },
                  "defer_loading": true
              },
              {
                  "name": "search_files",
                  "description": "Search through files in the workspace",
                  "input_schema": {
                      "type": "object",
                      "properties": {
                          "query": {"type": "string"},
                          "file_types": {
                              "type": "array",
                              "items": {"type": "string"}
                          }
                      },
                      "required": ["query"]
                  },
                  "defer_loading": true
              }
          ]
      }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 2048
  messages:
    - role: user
      content: What is the weather in San Francisco?
  tools:
    - type: tool_search_tool_regex_20251119
      name: tool_search_tool_regex
    - name: get_weather
      description: Get the weather at a specific location
      input_schema:
        type: object
        properties:
          location:
            type: string
          unit:
            type: string
            enum: [celsius, fahrenheit]
        required: [location]
      defer_loading: true
    - name: search_files
      description: Search through files in the workspace
      input_schema:
        type: object
        properties:
          query:
            type: string
          file_types:
            type: array
            items:
              type: string
        required: [query]
      defer_loading: true
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=2048,
      messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],
      tools=[
          {"type": "tool_search_tool_regex_20251119", "name": "tool_search_tool_regex"},
          {
              "name": "get_weather",
              "description": "Get the weather at a specific location",
              "input_schema": {
                  "type": "object",
                  "properties": {
                      "location": {"type": "string"},
                      "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                  },
                  "required": ["location"],
              },
              "defer_loading": True,
          },
          {
              "name": "search_files",
              "description": "Search through files in the workspace",
              "input_schema": {
                  "type": "object",
                  "properties": {
                      "query": {"type": "string"},
                      "file_types": {"type": "array", "items": {"type": "string"}},
                  },
                  "required": ["query"],
              },
              "defer_loading": True,
          },
      ],
  )

  print(response)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 2048,
    messages: [
      {
        role: "user",
        content: "What is the weather in San Francisco?"
      }
    ],
    tools: [
      {
        type: "tool_search_tool_regex_20251119",
        name: "tool_search_tool_regex"
      },
      {
        name: "get_weather",
        description: "Get the weather at a specific location",
        input_schema: {
          type: "object" as const,
          properties: {
            location: { type: "string" },
            unit: {
              type: "string",
              enum: ["celsius", "fahrenheit"]
            }
          },
          required: ["location"]
        },
        defer_loading: true
      },
      {
        name: "search_files",
        description: "Search through files in the workspace",
        input_schema: {
          type: "object" as const,
          properties: {
            query: { type: "string" },
            file_types: {
              type: "array",
              items: { type: "string" }
            }
          },
          required: ["query"]
        },
        defer_loading: true
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 2048,
      Messages = [
          new() {
              Role = Role.User,
              Content = "What is the weather in San Francisco?"
          }
      ],
      Tools = [
          new ToolUnion(new ToolSearchToolRegex20251119
          {
              Type = ToolSearchToolRegex20251119Type.ToolSearchToolRegex20251119
          }),
          new ToolUnion(new Tool()
          {
              Name = "get_weather",
              Description = "Get the weather at a specific location",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["location"] = JsonSerializer.SerializeToElement(new { type = "string" }),
                      ["unit"] = JsonSerializer.SerializeToElement(new { type = "string", @enum = new[] { "celsius", "fahrenheit" } }),
                  },
                  Required = ["location"],
              },
              DeferLoading = true,
          }),
          new ToolUnion(new Tool()
          {
              Name = "search_files",
              Description = "Search through files in the workspace",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["query"] = JsonSerializer.SerializeToElement(new { type = "string" }),
                      ["file_types"] = JsonSerializer.SerializeToElement(new { type = "array", items = new { type = "string" } }),
                  },
                  Required = ["query"],
              },
              DeferLoading = true,
          }),
      ]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 2048,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What is the weather in San Francisco?")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfToolSearchToolRegex20251119: &anthropic.ToolSearchToolRegex20251119Param{
  			Type: anthropic.ToolSearchToolRegex20251119TypeToolSearchToolRegex20251119,
  		}},
  		{OfTool: &anthropic.ToolParam{
  			Name:        "get_weather",
  			Description: anthropic.String("Get the weather at a specific location"),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"location": map[string]any{"type": "string"},
  					"unit": map[string]any{
  						"type": "string",
  						"enum": []string{"celsius", "fahrenheit"},
  					},
  				},
  				Required: []string{"location"},
  			},
  			DeferLoading: anthropic.Bool(true),
  		}},
  		{OfTool: &anthropic.ToolParam{
  			Name:        "search_files",
  			Description: anthropic.String("Search through files in the workspace"),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"query":      map[string]any{"type": "string"},
  					"file_types": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
  				},
  				Required: []string{"query"},
  			},
  			DeferLoading: anthropic.Bool(true),
  		}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.ToolSearchToolRegex20251119;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      InputSchema weatherSchema = InputSchema.builder()
          .properties(JsonValue.from(Map.of(
              "location", Map.of("type", "string"),
              "unit", Map.of(
                  "type", "string",
                  "enum", List.of("celsius", "fahrenheit")
              )
          )))
          .putAdditionalProperty("required", JsonValue.from(List.of("location")))
          .build();

      InputSchema searchSchema = InputSchema.builder()
          .properties(JsonValue.from(Map.of(
              "query", Map.of("type", "string"),
              "file_types", Map.of(
                  "type", "array",
                  "items", Map.of("type", "string")
              )
          )))
          .putAdditionalProperty("required", JsonValue.from(List.of("query")))
          .build();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(2048L)
          .addUserMessage("What is the weather in San Francisco?")
          .addTool(ToolSearchToolRegex20251119.builder()
              .type(ToolSearchToolRegex20251119.Type.TOOL_SEARCH_TOOL_REGEX_20251119)
              .build())
          .addTool(Tool.builder()
              .name("get_weather")
              .description("Get the weather at a specific location")
              .inputSchema(weatherSchema)
              .deferLoading(true)
              .build())
          .addTool(Tool.builder()
              .name("search_files")
              .description("Search through files in the workspace")
              .inputSchema(searchSchema)
              .deferLoading(true)
              .build())
          .build();

      Message response = client.messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 2048,
      messages: [
          ['role' => 'user', 'content' => 'What is the weather in San Francisco?'],
      ],
      model: 'claude-opus-5-5',
      tools: [
          [
              'type' => 'tool_search_tool_regex_20251119',
              'name' => 'tool_search_tool_regex',
          ],
          [
              'name' => 'get_weather',
              'description' => 'Get the weather at a specific location',
              'input_schema' => [
                  'type' => 'object',
                  'properties' => [
                      'location' => ['type' => 'string'],
                      'unit' => [
                          'type' => 'string',
                          'enum' => ['celsius', 'fahrenheit'],
                      ],
                  ],
                  'required' => ['location'],
              ],
              'defer_loading' => true,
          ],
          [
              'name' => 'search_files',
              'description' => 'Search through files in the workspace',
              'input_schema' => [
                  'type' => 'object',
                  'properties' => [
                      'query' => ['type' => 'string'],
                      'file_types' => [
                          'type' => 'array',
                          'items' => ['type' => 'string'],
                      ],
                  ],
                  'required' => ['query'],
              ],
              'defer_loading' => true,
          ],
      ],
  );

  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 2048,
    messages: [
      { role: "user", content: "What is the weather in San Francisco?" }
    ],
    tools: [
      {
        type: "tool_search_tool_regex_20251119",
        name: "tool_search_tool_regex"
      },
      {
        name: "get_weather",
        description: "Get the weather at a specific location",
        input_schema: {
          type: "object",
          properties: {
            location: { type: "string" },
            unit: {
              type: "string",
              enum: ["celsius", "fahrenheit"]
            }
          },
          required: ["location"]
        },
        defer_loading: true
      },
      {
        name: "search_files",
        description: "Search through files in the workspace",
        input_schema: {
          type: "object",
          properties: {
            query: { type: "string" },
            file_types: {
              type: "array",
              items: { type: "string" }
            }
          },
          required: ["query"]
        },
        defer_loading: true
      }
    ]
  )

  puts message
  ```
</CodeGroup>

Claude 搜尋目錄、探索到 `get_weather` 並呼叫它。回應以 `stop_reason: "tool_use"` 結束。請依照[處理工具呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/handle-tool-calls)中的方式執行探索到的工具並回傳 `tool_result`。[回應格式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool#response-format)說明了您會收到的區塊以及接下來要傳送的內容。

## 工具定義

工具搜尋工具有兩種變體：

```json JSON
{
  "type": "tool_search_tool_regex_20251119",
  "name": "tool_search_tool_regex"
}
```

```json JSON
{
  "type": "tool_search_tool_bm25_20251119",
  "name": "tool_search_tool_bm25"
}
```

<Warning>
  **Regex 變體查詢格式：Python 正規表示式，而非自然語言**

  使用 `tool_search_tool_regex_20251119` 時，Claude 撰寫的是 Python `re.search()` 模式，而非自然語言查詢。比對不區分大小寫。常見模式包括：

  * `"weather"`：比對名稱與描述中包含「weather」的工具
  * `"get_.*_data"`：比對如 `get_user_data` 與 `get_weather_data` 等工具
  * `"database.*query|query.*database"`：比對任一詞序

  模式長度上限：200 個字元
</Warning>

<Note>
  **BM25 變體查詢格式：自然語言**

  使用 `tool_search_tool_bm25_20251119` 時，Claude 以自然語言查詢進行搜尋。查詢長度上限：500 個字元。
</Note>

### 延遲工具載入

透過加入 `defer_loading: true` 將工具標記為按需載入：

```json JSON
{
  "name": "get_weather",
  "description": "Get current weather for a location",
  "input_schema": {
    "type": "object",
    "properties": {
      "location": { "type": "string" },
      "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] }
    },
    "required": ["location"]
  },
  "defer_loading": true
}
```

`defer_loading` 控制的是進入上下文視窗的內容，而非您在請求中傳送的內容：

* 您仍需在每次請求的 `tools` 陣列中傳送每個工具的完整定義，包括延遲載入的工具。API 需要在伺服器端使用它們來執行搜尋並展開 `tool_reference` 區塊。
* 沒有 `defer_loading` 的工具會立即載入上下文。
* 設有 `defer_loading: true` 的工具僅在 Claude 透過搜尋探索到它們時才會載入。
* 切勿在工具搜尋工具本身設定 `defer_loading: true`。
* 將您最常使用的 3–5 個工具保持為非延遲狀態，讓 Claude 無需先搜尋即可呼叫它們。

電腦使用與瀏覽器使用工具集（`computer_toolset_20260801` 與 `browser_toolset_20260801`）是在項目的 `configs` 物件內針對每個成員工具設定 `defer_loading`，而非在項目本身設定；在項目層級設定它的請求會被拒絕。由於工具集是以整體為單位進行延遲與展開，`defer_loading` 在每個已啟用的成員上必須解析為相同的值，且當 Claude 透過搜尋探索到該工具集時，所有已啟用的成員會一次全部載入。關於 `configs` 格式，請參閱[用戶端工具集](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference#client-toolsets)。

兩種工具搜尋變體（`regex` 與 `bm25`）皆會搜尋工具名稱、描述、引數名稱與引數描述。

在內部，API 會將延遲載入的工具排除在系統提示前綴之外。當 Claude 透過工具搜尋探索到延遲載入的工具時，API 會在對話中內嵌附加一個 `tool_reference` 區塊，然後在傳遞給 Claude 之前將其展開為完整的工具定義。前綴保持不變，因此「prompt caching」（提示快取）得以保留。[嚴格模式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/strict-tool-use)的文法（約束工具呼叫輸出以符合您的結構描述的規則）是從完整工具集建構的，因此 `defer_loading` 與嚴格模式可以組合使用，而無需重新編譯文法。

## 回應格式

當 Claude 使用工具搜尋工具時，回應會包含下列區塊類型：

```json JSON
{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll search for tools to help with the weather information."
    },
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01ABC123",
      "name": "tool_search_tool_regex",
      "input": {
        "pattern": "weather",
        "limit": 10
      }
    },
    {
      "type": "tool_search_tool_result",
      "tool_use_id": "srvtoolu_01ABC123",
      "content": {
        "type": "tool_search_tool_search_result",
        "tool_references": [{ "type": "tool_reference", "tool_name": "get_weather" }]
      }
    },
    {
      "type": "text",
      "text": "I found a weather tool. Let me get the weather for San Francisco."
    },
    {
      "type": "tool_use",
      "id": "toolu_01XYZ789",
      "name": "get_weather",
      "input": { "location": "San Francisco", "unit": "fahrenheit" }
    }
  ],
  "stop_reason": "tool_use"
}
```

### 理解回應

* **`server_tool_use`：** Claude 對工具搜尋工具的呼叫。搜尋在 Anthropic 的伺服器上執行。切勿針對其 `srvtoolu_...` ID 回傳 `tool_result`。`input` 包含搜尋內容（regex 變體為 `pattern`，BM25 為 `query`），並可能包含選用的 `limit`，這是一個介於 1 到 10,000 之間的整數，用於限制搜尋回傳的相符工具數量上限（預設值：5）。
* **`tool_search_tool_result`：** 搜尋結果，位於巢狀的 `tool_search_tool_search_result` 物件中。請將其原封不動地保留在訊息歷史中。
* **`tool_references`：** 指向已探索工具的 `tool_reference` 物件陣列。API 會為 Claude 展開這些參照。您永遠不需要自行展開它們。
* **`tool_use`：** Claude 對已探索工具的呼叫。請執行它並回傳 `tool_result`，方式與標準工具使用完全相同。

API 會在向 Claude 顯示之前，自動將 `tool_reference` 區塊展開為完整的工具定義。只要您在 `tools` 參數中提供所有相符的工具定義，就不需要自行處理此展開。

### 繼續對話

在下一次請求中，請將助理的內容原封不動地傳回，包括 `server_tool_use` 與 `tool_search_tool_result` 區塊。在使用者訊息中加入您針對已探索工具的 `tool_result`，並傳送相同的 `tools` 陣列：搜尋工具加上每個延遲載入的定義。請勿針對 `srvtoolu_...` ID 回傳 `tool_result`：API 會拒絕該請求。API 會在整個對話歷史中展開 `tool_reference` 區塊，因此 Claude 可以在後續回合中重複使用已探索的工具，而無需重新搜尋。沒有任何相符結果的搜尋會回傳一個 `tool_references` 陣列為空的 `tool_search_tool_search_result`，而非錯誤。

## MCP 整合

如果您的工具是透過 [MCP 連接器](https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector)來自 MCP 伺服器，您不需要在個別工具定義上設定 `defer_loading`。請改為在 `mcp_toolset` 項目的 `default_config` 上針對整個伺服器設定一次，或在其 `configs` 中針對每個工具設定。請參閱 [MCP 工具集設定](https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector#mcp-toolset-configuration)。

## 自訂工具搜尋實作

您可以透過從自訂工具回傳 `tool_reference` 區塊，來實作自己的工具搜尋邏輯（例如使用嵌入向量或語意搜尋）。當 Claude 呼叫您的自訂搜尋工具時，請回傳一個標準的 `tool_result`，並在 content 陣列中包含 `tool_reference` 區塊：

```json JSON
{
  "type": "tool_result",
  "tool_use_id": "toolu_your_tool_id",
  "content": [{ "type": "tool_reference", "tool_name": "discovered_tool_name" }]
}
```

每個被參照的工具都必須在頂層 `tools` 參數中有對應的工具定義，通常設有 `defer_loading: true`。這讓您能夠使用內建變體未提供的搜尋方法，例如基於嵌入向量的檢索，而 API 會以相同的方式展開回傳的 `tool_reference` 區塊。

<Note>
  [回應格式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool#response-format)一節中所示的 `tool_search_tool_result` 格式，是 Anthropic 內建工具搜尋在內部使用的伺服器端格式。對於自訂的用戶端實作，請一律使用標準的 `tool_result` 格式搭配 `tool_reference` 內容區塊，如前述範例所示。
</Note>

關於使用嵌入向量的完整範例，請參閱[使用嵌入向量的工具搜尋](https://platform.claude.com/cookbook/tool-use-tool-search-with-embeddings)範例。

## 錯誤處理

<Note>
  [工具使用範例](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools#providing-tool-use-examples)可與工具搜尋搭配使用：當 Claude 探索到延遲載入的工具時，API 會連同其定義一併展開其 `input_examples`。
</Note>

### HTTP 錯誤（400 狀態）

這些錯誤會阻止 API 處理請求：

**所有工具皆為延遲載入：**

```json
{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "At least one tool must have defer_loading=false. All tools cannot be deferred."
  }
}
```

**缺少工具定義：**

```json
{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "Tool reference 'unknown_tool' not found in available tools"
  }
}
```

### 工具結果錯誤（200 狀態）

當工具搜尋操作在執行期間失敗時，API 會回傳 200 回應，並在主體中包含錯誤：

```json JSON
{
  "type": "tool_search_tool_result",
  "tool_use_id": "srvtoolu_01ABC123",
  "content": {
    "type": "tool_search_tool_result_error",
    "error_code": "invalid_tool_input",
    "error_message": "Invalid regular expression pattern: missing ) at position 1"
  }
}
```

`error_code` 欄位有四個可能的值：

* `invalid_tool_input`：搜尋輸入無效，例如格式錯誤的 regex 模式，或超過 200 字元上限的模式
* `unavailable`：搜尋無法執行，例如因為逾時或服務無法使用
* `too_many_requests`：超過工具搜尋操作的速率限制
* `execution_time_exceeded`：搜尋超過其執行時間上限

### 常見錯誤

<Accordion title="400 錯誤：所有工具皆為延遲載入">
  **原因：** 您在每個工具上都設定了 `defer_loading: true`，包括工具搜尋工具。

  **修正方式：** 從工具搜尋工具移除 `defer_loading`：

  ```json
  {
    "type": "tool_search_tool_regex_20251119",
    "name": "tool_search_tool_regex"
  }
  ```
</Accordion>

<Accordion title="400 錯誤：缺少工具定義">
  **原因：** 某個 `tool_reference` 指向不在您 `tools` 陣列中的工具。

  **修正方式：** 確保每個可能被探索到的工具都有完整的定義：

  ```json
  {
    "name": "my_tool",
    "description": "Full description here",
    "input_schema": {
      "type": "object"
    },
    "defer_loading": true
  }
  ```
</Accordion>

<Accordion title="Claude 找不到預期的工具">
  **原因：** regex 模式與工具的名稱、描述、引數名稱或引數描述不相符。

  **除錯步驟：**

  1. 檢查工具名稱、描述、引數名稱與引數描述。Claude 會搜尋所有這些欄位。
  2. 測試您的模式：`import re; re.search(r"your_pattern", "tool_name", re.IGNORECASE)`。
  3. 比對不區分大小寫，因此大小寫差異不是問題所在。
  4. Claude 使用寬泛的模式，例如 `".*weather.*"`，而非精確比對。

  **提示：** 在工具描述中加入常見關鍵字以提升可探索性。
</Accordion>

## 提示快取

若要了解 `defer_loading` 如何保留提示快取，請參閱[搭配提示快取的工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-use-with-prompt-caching)。

設有 `defer_loading: true` 的工具不能同時帶有 `cache_control`：API 會回傳 400。請將快取斷點放在非延遲的工具上。

## 串流

啟用「streaming」（串流）後，您會在串流中收到工具搜尋事件：

```sse
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "tool_search_tool_regex"}}

// Search pattern streamed
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"pattern\":\"weather\"}"}}

// Pause while search executes

// Search results streamed
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "tool_search_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "tool_search_tool_search_result", "tool_references": [{"type": "tool_reference", "tool_name": "get_weather"}]}}}

// Claude continues with discovered tools
```

## 批次請求

您可以在 [Messages Batches API](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing) 中加入工具搜尋工具。

## 限制與最佳實務

### 限制

* **延遲載入工具數量上限：** 每次請求最多 10,000 個設有 `defer_loading: true` 的工具
* **搜尋結果：** 每次搜尋預設最多回傳 5 個相符的工具；Claude 可在其搜尋輸入中將 `limit` 設定為 1 到 10,000 之間的任何整數
* **模式與查詢長度：** regex 模式上限為 200 個字元，BM25 查詢上限為 500 個字元
* **模型支援：** 請參閱[模型相容性](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool#model-compatibility)

### 何時使用工具搜尋

當符合下列任一情況時，請使用工具搜尋：

* 您有 10 個或更多可用工具。
* 您的工具定義消耗超過 10k 個 token。
* 隨著工具集成長，工具選擇準確度下降。
* 您彙整了多個 MCP 伺服器（200 個以上的工具）。
* 您的工具庫會隨時間成長。

當您的工具少於 10 個、每個工具在每次請求中都會使用，或您的工具定義很小（總計少於 100 個 token）時，不使用工具搜尋的標準工具呼叫會更為合適。

### 最佳化提示

* 將您最常使用的 3–5 個工具保持為非延遲狀態。
* 撰寫清晰、具描述性的工具名稱與描述。
* 在工具名稱中使用一致的命名空間：以服務或資源作為前綴（例如 `github_`、`slack_`），讓一次搜尋即可比對整個群組。
* 在描述中使用符合使用者描述任務方式的關鍵字。
* 加入一段描述可用工具類別的系統提示：「You can search for tools to interact with Slack, GitHub, and Jira.」
* 監控 Claude 探索到哪些工具，以改進您的描述。

## 用量

工具搜尋不會作為獨立的伺服器工具計量。回應的 `usage.server_tool_use` 物件沒有工具搜尋欄位，而搜尋載入上下文的工具定義會像任何其他工具定義一樣計為輸入 token。

## 後續步驟

<CardGroup cols={2}>
  <Card title="記憶工具" icon="brain" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/memory-tool">
    透過在您的應用程式中實作記憶工具的檔案操作，讓 Claude 跨對話儲存與擷取資訊。
  </Card>

  <Card title="工具參考" icon="book" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference">
    Anthropic 提供之工具的目錄，以及選用工具定義屬性的參考。
  </Card>

  <Card title="MCP 連接器" icon="link" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector">
    設定具有延遲載入的 MCP 工具集。
  </Card>

  <Card title="搭配提示快取的工具使用" icon="bolt" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-use-with-prompt-caching">
    跨回合快取工具定義，並了解哪些情況會使您的快取失效。
  </Card>

  <Card title="定義工具" icon="hammer" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools">
    指定工具結構描述、撰寫有效的描述，並控制 Claude 何時呼叫您的工具。
  </Card>
</CardGroup>
