---
title: 工具搜尋工具
url: https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool
description: 讓 Claude 搜尋您的工具目錄並僅載入所需的工具，以擴展至數百或數千個工具。
featureMetadata:
  status: stable
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). 由 Anthropic 執行的伺服器端工具；請求中的工具定義會在每次呼叫時於記憶體中搜尋，回應後不會儲存任何內容。
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: stable
    Amazon Bedrock: stable
    Amazon Bedrock (bedrock-runtime):
      availability: stable
      note: 可透過 InvokeModel API 使用，不支援 Converse API。
    Claude Platform on AWS: stable
    Claude Models on Google Cloud (Anthropic managed): stable
    Claude Models on Google Cloud (Google managed): stable
    Microsoft Foundry: stable
---

工具搜尋工具讓 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)。有關支援此功能的平台，請參閱[可用性](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool#feature-availability)。

<Tip>
  有關工具搜尋所解決之擴展挑戰的背景資訊，請參閱[進階工具使用](https://www.anthropic.com/engineering/advanced-tool-use)。工具搜尋的按需載入也是[有效的上下文工程](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>

## 模型相容性

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

| 模型 | 工具版本 |
| ----- | ----- |
| Claude Fable 5.2 (claude-fable-5-2) | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| Claude Mythos 5.2 (claude-mythos-5-2) | `tool_search_tool_regex_20251119`, `tool_search_tool_bm25_20251119` |
| 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 建構「regular expression」（正規表示式），即 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: 2026-10-21" \
    -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 UserMessageParam { 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: 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: Anthropic::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"` 結束。請執行探索到的工具並傳回 `tool_result`，做法如[處理工具呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/handle-tool-calls)所述。[回應格式](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 regex，而非自然語言**

  使用 `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 之前將其展開為完整的工具定義。[嚴格模式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/strict-tool-use)（限制工具呼叫輸出以符合您的結構描述的規則）的文法是從完整的工具清單建構的，因此將 `defer_loading` 與嚴格模式搭配使用，不會讓 API 重新編譯文法。

## 回應格式

當 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`，做法與標準的「tool use」（工具使用）完全相同。

API 會在將 `tool_reference` 區塊呈現給 Claude 之前，自動將其展開為完整的工具定義。只要您在 `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)來自「Model Context Protocol」，即 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`，並在內容陣列中包含 `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"
  }
}
```

API 定義了這些 `error_code` 值：

* `invalid_tool_input`：搜尋輸入無效，例如格式錯誤的 regex 模式或超過 200 字元限制的模式
* `unavailable`：搜尋無法執行，例如因為逾時或服務無法使用
* `too_many_requests`：超過工具搜尋操作的「rate limit」（速率限制）
* `execution_time_exceeded`：工具搜尋不會回傳此錯誤，逾時會回報為 `unavailable`

### 常見錯誤

<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 runs

// 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
```

## 批次請求

您可以在 [Message 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)
* **平台支援：** 請參閱[可用性](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool#feature-availability)
* **[Amazon Bedrock（`bedrock-runtime`）](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-on-amazon-bedrock-legacy)：** 工具搜尋透過 InvokeModel API 運作

### 何時使用工具搜尋

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

* 您有 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>

## 可用性

工具搜尋工具在所有模型上可供使用，且具備零資料保留資格。

### API 支援

#### [Messages API](https://platform.claude.com/docs/zh-TW/build-with-claude/working-with-messages)

* 可用性：可用

| 狀態 | 雲端平台 | 模型 |
| ----- | ----- | ----- |
| 可用 | Claude API, [Amazon Bedrock](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-amazon-bedrock), [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws), [Claude Models on Google Cloud (Anthropic managed)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-models-on-google-cloud/anthropic-managed), [Claude Models on Google Cloud (Google managed)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-models-on-google-cloud/google-managed), [Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) | [所有模型](https://platform.claude.com/docs/zh-TW/models/overview) |
| 可用<sup>1</sup> | [Amazon Bedrock (bedrock-runtime)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-on-amazon-bedrock-legacy) | [所有模型](https://platform.claude.com/docs/zh-TW/models/overview) |

1. 可透過 InvokeModel API 使用，不支援 Converse API。

#### [Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview)

* 可用性：不可用

### 資料處理

[資料處理概覽](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention#feature-eligibility)

| 項目 | 零資料保留 | HIPAA |
| ----- | ----- | ----- |
| 狀態 | 符合資格（不含 [涵蓋的模型](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention#model-specific-data-retention-requirements)） | 不符合資格 |
| 詳細資訊 | 由 Anthropic 執行的伺服器端工具；請求中的工具定義會在每次呼叫時於記憶體中搜尋，回應後不會儲存任何內容。 | — |

適用端點：

* `/v1/messages` 搭配 `tool_search` 工具
