SPB Git

Repository Public

web-fetch-tool.md 35.0 KB 973 lines markdown

1---2title: Web fetch tool3url: https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool4description: Fetch and read content from specific URLs to augment Claude's context with live web content.5---67<Note>8  To learn how zero data retention (ZDR) applies to this feature, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).9</Note>1011The web fetch tool allows Claude to retrieve full content from specified web pages and PDF documents.1213The latest web fetch tool version (`web_fetch_20260318`) supports **dynamic filtering**: Claude can write and execute code to filter fetched content before it reaches the context window, keeping only relevant information and discarding the rest. This reduces token consumption while maintaining response quality. Dynamic filtering is available with Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, [Claude Mythos Preview](https://anthropic.com/glasswing), Claude Opus 4.8, Claude Opus 4.7, Claude Opus 4.6, Claude Sonnet 5, and Claude Sonnet 4.6. `web_fetch_20260318` also adds [response inclusion](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#response-inclusion) control for agentic workflows. The previous versions (`web_fetch_20260309` for dynamic filtering and [cache bypass](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#cache-bypass), `web_fetch_20260209` for dynamic filtering only, `web_fetch_20250910` for basic fetch) remain available.1415Web fetch (with and without dynamic filtering) is available on the Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws), and [Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry). On Microsoft Foundry, deployments [hosted on Azure](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure) support only the basic web fetch tool (`web_fetch_20250910`, without dynamic filtering). Deployments hosted on Anthropic support all versions. Web fetch is not currently available on Amazon Bedrock or Google Cloud.1617<Note>18  For [Claude Mythos Preview](https://anthropic.com/glasswing), web fetch is available on the Claude API and Microsoft Foundry. It is not currently available for Mythos Preview on Amazon Bedrock or Google Cloud.19</Note>2021<Note>22  Use the [feedback form](https://forms.gle/NhWcgmkcvPCMmPE86) to provide feedback on the quality of the model responses, the API itself, or the quality of the documentation.23</Note>2425For Zero Data Retention eligibility and the `allowed_callers` workaround, see [Server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#zdr-and-allowed-callers).2627<Warning>28  Enabling the web fetch tool in environments where Claude processes untrusted input alongside sensitive data poses data exfiltration risks. Only use this tool in trusted environments or when handling non-sensitive data.2930  To minimize exfiltration risks, Claude cannot fetch URLs that appear only in its own output. Claude can only fetch URLs that have previously appeared in the conversation: URLs in user messages, URLs in client-side tool results (even when a result echoes text that Claude generated), and URLs from previous web search or web fetch results (see [URL validation](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#url-validation)). However, there is still residual risk that you should carefully consider when using this tool.3132  If data exfiltration is a concern, consider:3334  * Disabling the web fetch tool entirely35  * Using the `max_uses` parameter to limit the number of requests36  * Using the `allowed_domains` parameter to restrict to known safe domains37</Warning>3839For model support, see the [Tool reference](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference).4041## How web fetch works4243Web fetch is a [server tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools): the API fetches the content during the request and inserts the results into the conversation. You don't run anything or return a `tool_result`. The exception is when Claude calls web fetch and one of your client tools in the same group of parallel tool calls: the API returns the response with `stop_reason: "tool_use"` before that fetch has run, then runs the fetch when you send back the client `tool_result` blocks. See [Mixing server tools and client tools in one turn](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#mixing-server-tools-and-client-tools-in-one-turn).4445When you add the web fetch tool to your API request:46471. Claude determines when to fetch content based on the prompt and available URLs.482. The API retrieves the full text content from the specified URL.493. For PDFs, the API returns the content as base64-encoded data and processes it like a directly attached PDF document.504. Claude analyzes the fetched content and provides a response with optional citations.5152<Note>53  The web fetch tool currently does not support websites dynamically rendered with JavaScript. For pages that need a real browser (JavaScript rendering, clicking, or filling forms), consider the [browser use tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/browser-use-tool), a client tool where your application drives the browser and returns page text or screenshots to Claude as tool results.54</Note>5556### When Claude fetches5758Claude fetches when the request points at a specific page or document:5960* A URL is provided in the conversation (or a previous tool result)61* The user names a specific resource (a particular article, README, pricing page, or documentation section) without a URL, and the [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) is also enabled so Claude can locate it first (see [Combined search and fetch](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#combined-search-and-fetch))6263Claude does **not** fetch for general-knowledge or open-ended questions that don't reference a specific page. "Summarize this article: `<url>`" triggers a fetch. "What are best practices for REST API design?" is answered directly.6465### Dynamic filtering6667Fetching full web pages and PDFs can quickly consume tokens, especially when only specific information is needed from large documents. With `web_fetch_20260209` or later, Claude can write and execute code to filter the fetched content before loading it into context.6869This dynamic filtering is particularly useful for:7071* Extracting specific sections from long documents72* Processing structured data from web pages73* Filtering relevant information from PDFs74* Reducing token costs when working with large documents7576<Note>77  Dynamic filtering runs on the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool), which the API enables automatically for the request. You don't need to add the code execution tool to the `tools` array.78</Note>7980To enable dynamic filtering, use `web_fetch_20260209` or any later version. The following examples use `web_fetch_20260318`:8182<CodeGroup>83  ```bash cURL84  curl https://api.anthropic.com/v1/messages \85    -H "x-api-key: $ANTHROPIC_API_KEY" \86    -H "anthropic-version: 2023-06-01" \87    -H "content-type: application/json" \88    -d '{89      "model": "claude-opus-4-8",90      "max_tokens": 4096,91      "messages": [92        {93          "role": "user",94          "content": "Fetch the content at https://example.com/research-paper and extract the key findings."95        }96      ],97      "tools": [{98        "type": "web_fetch_20260318",99        "name": "web_fetch"100      }]101    }'102  ```103104  ```bash CLI105  ant messages create <<'YAML'106  model: claude-opus-4-8107  max_tokens: 4096108  messages:109    - role: user110      content: >-111        Fetch the content at https://example.com/research-paper112        and extract the key findings.113  tools:114    - type: web_fetch_20260318115      name: web_fetch116  YAML117  ```118119  ```python Python120  client = anthropic.Anthropic()121122  response = client.messages.create(123      model="claude-opus-4-8",124      max_tokens=4096,125      messages=[126          {127              "role": "user",128              "content": "Fetch the content at https://example.com/research-paper and extract the key findings.",129          }130      ],131      tools=[{"type": "web_fetch_20260318", "name": "web_fetch"}],132  )133  print(response)134  ```135136  ```typescript TypeScript137  const client = new Anthropic();138139  const response = await client.messages.create({140    model: "claude-opus-4-8",141    max_tokens: 4096,142    messages: [143      {144        role: "user",145        content:146          "Fetch the content at https://example.com/research-paper and extract the key findings."147      }148    ],149    tools: [{ type: "web_fetch_20260318", name: "web_fetch" }]150  });151152  console.log(response);153  ```154155  ```csharp C#156  AnthropicClient client = new();157158  var parameters = new MessageCreateParams159  {160      Model = Model.ClaudeOpus4_8,161      MaxTokens = 4096,162      Messages = [new() { Role = Role.User, Content = "Fetch the content at https://example.com/research-paper and extract the key findings." }],163      Tools = [new ToolUnion(new WebFetchTool20260318())]164  };165166  var message = await client.Messages.Create(parameters);167  Console.WriteLine(message);168  ```169170  ```go Go171  client := anthropic.NewClient()172173  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{174  	Model:     anthropic.ModelClaudeOpus4_8,175  	MaxTokens: 4096,176  	Messages: []anthropic.MessageParam{177  		anthropic.NewUserMessage(anthropic.NewTextBlock("Fetch the content at https://example.com/research-paper and extract the key findings.")),178  	},179  	Tools: []anthropic.ToolUnionParam{180  		{OfWebFetchTool20260318: &anthropic.WebFetchTool20260318Param{}},181  	},182  })183  if err != nil {184  	log.Fatal(err)185  }186  fmt.Println(response.RawJSON())187  ```188189  ```java Java190  import com.anthropic.models.messages.WebFetchTool20260318;191192  void main() {193      AnthropicClient client = AnthropicOkHttpClient.fromEnv();194195      MessageCreateParams params = MessageCreateParams.builder()196          .model(Model.CLAUDE_OPUS_4_8)197          .maxTokens(4096L)198          .addUserMessage("Fetch the content at https://example.com/research-paper and extract the key findings.")199          .addTool(WebFetchTool20260318.builder().build())200          .build();201202      Message response = client.messages().create(params);203      IO.println(response);204  }205  ```206207  ```php PHP208  $client = new Client();209210  $message = $client->messages->create(211      maxTokens: 4096,212      messages: [213          ['role' => 'user', 'content' => 'Fetch the content at https://example.com/research-paper and extract the key findings.']214      ],215      model: 'claude-opus-4-8',216      tools: [[217          'type' => 'web_fetch_20260318',218          'name' => 'web_fetch',219      ]],220  );221  echo $message;222  ```223224  ```ruby Ruby225  client = Anthropic::Client.new226227  message = client.messages.create(228    model: "claude-opus-4-8",229    max_tokens: 4096,230    messages: [231      { role: "user", content: "Fetch the content at https://example.com/research-paper and extract the key findings." }232    ],233    tools: [{234      type: "web_fetch_20260318",235      name: "web_fetch"236    }]237  )238  puts message239  ```240</CodeGroup>241242## How to use web fetch243244Provide the web fetch tool in your API request:245246<CodeGroup>247  ```bash cURL248  curl https://api.anthropic.com/v1/messages \249    -H "x-api-key: $ANTHROPIC_API_KEY" \250    -H "anthropic-version: 2023-06-01" \251    -H "content-type: application/json" \252    -d '{253      "model": "claude-opus-4-8",254      "max_tokens": 1024,255      "messages": [256        {257          "role": "user",258          "content": "Please analyze the content at https://example.com/article"259        }260      ],261      "tools": [{262        "type": "web_fetch_20250910",263        "name": "web_fetch",264        "max_uses": 5265      }]266    }'267  ```268269  ```bash CLI270  ant messages create \271    --model claude-opus-4-8 \272    --max-tokens 1024 \273    --message '{role: user, content: "Please analyze the content at https://example.com/article"}' \274    --tool '{type: web_fetch_20250910, name: web_fetch, max_uses: 5}'275  ```276277  ```python Python278  client = anthropic.Anthropic()279280  response = client.messages.create(281      model="claude-opus-4-8",282      max_tokens=1024,283      messages=[284          {285              "role": "user",286              "content": "Please analyze the content at https://example.com/article",287          }288      ],289      tools=[{"type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5}],290  )291  print(response)292  ```293294  ```typescript TypeScript295  const client = new Anthropic();296297  const response = await client.messages.create({298    model: "claude-opus-4-8",299    max_tokens: 1024,300    messages: [301      {302        role: "user",303        content: "Please analyze the content at https://example.com/article"304      }305    ],306    tools: [307      {308        type: "web_fetch_20250910",309        name: "web_fetch",310        max_uses: 5311      }312    ]313  });314315  console.log(response);316  ```317318  ```csharp C#319  AnthropicClient client = new();320321  var parameters = new MessageCreateParams322  {323      Model = Model.ClaudeOpus4_8,324      MaxTokens = 1024,325      Messages = [new() { Role = Role.User, Content = "Please analyze the content at https://example.com/article" }],326      Tools = [new ToolUnion(new WebFetchTool20250910() { MaxUses = 5 })]327  };328329  var message = await client.Messages.Create(parameters);330  Console.WriteLine(message);331  ```332333  ```go Go334  client := anthropic.NewClient()335336  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{337  	Model:     anthropic.ModelClaudeOpus4_8,338  	MaxTokens: 1024,339  	Messages: []anthropic.MessageParam{340  		anthropic.NewUserMessage(anthropic.NewTextBlock("Please analyze the content at https://example.com/article")),341  	},342  	Tools: []anthropic.ToolUnionParam{343  		{OfWebFetchTool20250910: &anthropic.WebFetchTool20250910Param{344  			MaxUses: anthropic.Int(5),345  		}},346  	},347  })348  if err != nil {349  	log.Fatal(err)350  }351  fmt.Println(response.RawJSON())352  ```353354  ```java Java355  import com.anthropic.models.messages.WebFetchTool20250910;356357  void main() {358      AnthropicClient client = AnthropicOkHttpClient.fromEnv();359360      MessageCreateParams params = MessageCreateParams.builder()361          .model(Model.CLAUDE_OPUS_4_8)362          .maxTokens(1024L)363          .addUserMessage("Please analyze the content at https://example.com/article")364          .addTool(WebFetchTool20250910.builder()365              .maxUses(5L)366              .build())367          .build();368369      Message response = client.messages().create(params);370      IO.println(response);371  }372  ```373374  ```php PHP375  $client = new Client();376377  $message = $client->messages->create(378      maxTokens: 1024,379      messages: [380          ['role' => 'user', 'content' => 'Please analyze the content at https://example.com/article']381      ],382      model: 'claude-opus-4-8',383      tools: [[384          'type' => 'web_fetch_20250910',385          'name' => 'web_fetch',386          'max_uses' => 5,387      ]],388  );389  echo $message;390  ```391392  ```ruby Ruby393  client = Anthropic::Client.new394395  message = client.messages.create(396    model: "claude-opus-4-8",397    max_tokens: 1024,398    messages: [399      { role: "user", content: "Please analyze the content at https://example.com/article" }400    ],401    tools: [{402      type: "web_fetch_20250910",403      name: "web_fetch",404      max_uses: 5405    }]406  )407  puts message408  ```409</CodeGroup>410411## Tool definition412413The web fetch tool supports the following parameters:414415```json JSON416{417  "type": "web_fetch_20250910",418  "name": "web_fetch",419420  // Optional: Limit the number of fetches per request421  "max_uses": 10,422423  // Optional: Only fetch from these domains424  "allowed_domains": ["example.com", "docs.example.com"],425426  // Optional: Never fetch from these domains (cannot be combined with allowed_domains)427  "blocked_domains": ["private.example.com"],428429  // Optional: Enable citations for fetched content430  "citations": {431    "enabled": true432  },433434  // Optional: Maximum content length in tokens435  "max_content_tokens": 100000436}437```438439Later tool versions add two more optional parameters: `use_cache` requires `web_fetch_20260309` or later (see [Cache bypass](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#cache-bypass)), and `response_inclusion` requires `web_fetch_20260318` or later (see [Response inclusion](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#response-inclusion)).440441### Max uses442443The `max_uses` parameter limits the number of web fetches performed. Failed fetches count against the limit. If Claude attempts more fetches than allowed, the `web_fetch_tool_result` is an error with the `max_uses_exceeded` error code. There is currently no default limit.444445### Domain filtering446447For domain filtering with `allowed_domains` and `blocked_domains`, see [Server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools#domain-filtering).448449On [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview), set these fields on the `web_fetch` entry of the agent toolset, where each listed domain must be a plain hostname with no path; see [Restrict web search and web fetch domains](https://platform.claude.com/docs/en/managed-agents/tools#restrict-web-search-and-web-fetch-domains).450451### Content limits452453The `max_content_tokens` parameter limits the amount of content included in the context. If the fetched content exceeds this limit, the tool truncates it. This helps control token usage when fetching large documents. The limit applies to text content, not to binary content such as PDFs.454455<Note>456  The `max_content_tokens` parameter limit is approximate. The actual number of input tokens used can vary by a small amount.457</Note>458459On Claude Managed Agents, the `web_fetch` entry of the agent toolset also accepts `max_content_tokens`; see [Restrict web search and web fetch domains](https://platform.claude.com/docs/en/managed-agents/tools#restrict-web-search-and-web-fetch-domains).460461### Cache bypass462463<Note>464  Requires `web_fetch_20260309` or later (including `web_fetch_20260318`).465</Note>466467The `use_cache` parameter controls whether cached content may be returned. Set `"use_cache": false` to bypass the cache and fetch fresh content. The default is `true`. Only disable caching when the user explicitly requests fresh content or when fetching rapidly changing sources, because bypassing the cache increases latency.468469```json470{471  "tools": [472    {473      "type": "web_fetch_20260309",474      "name": "web_fetch",475      "use_cache": false476    }477  ]478}479```480481### Response inclusion482483<Note>484  Requires `web_fetch_20260318` or later.485</Note>486487The `response_inclusion` parameter controls how fetch result blocks appear in the API response when the result was consumed by a completed [code execution](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) call in the same turn. Set `"response_inclusion": "excluded"` to drop those nested `server_tool_use` and result block pairs entirely from the response, reducing output token costs for agentic workflows that don't need to echo raw page content back to the client. The default is `"full"`. Results from direct calls, or from code execution calls that paused before completing, are always returned in full so they can be sent back on the next turn.488489```json490{491  "tools": [492    {493      "type": "web_fetch_20260318",494      "name": "web_fetch",495      "response_inclusion": "excluded"496    }497  ]498}499```500501### Citations502503Unlike web search where citations are always enabled, citations are optional for web fetch and disabled by default. Set `"citations": {"enabled": true}` to enable Claude to cite specific passages from fetched documents.504505<Note>506  When displaying API outputs directly to end users, include citations to the original source. If you are making modifications to API outputs, including by reprocessing or combining them with your own material before displaying them to end users, display citations as appropriate based on consultation with your legal team.507</Note>508509## Response510511Here's an example response structure:512513```json Output514{515  "role": "assistant",516  "content": [517    // 1. Claude's decision to fetch518    {519      "type": "text",520      "text": "I'll fetch the content from the article to analyze it."521    },522    // 2. The fetch request523    {524      "type": "server_tool_use",525      "id": "srvtoolu_01234567890abcdef",526      "name": "web_fetch",527      "input": {528        "url": "https://example.com/article"529      }530    },531    // 3. Fetch results532    {533      "type": "web_fetch_tool_result",534      "tool_use_id": "srvtoolu_01234567890abcdef",535      "content": {536        "type": "web_fetch_result",537        "url": "https://example.com/article",538        "content": {539          "type": "document",540          "source": {541            "type": "text",542            "media_type": "text/plain",543            "data": "Full text content of the article..."544          },545          "title": "Article Title",546          "citations": { "enabled": true }547        },548        "retrieved_at": "2025-08-25T10:30:00Z"549      }550    },551    // 4. Claude's analysis with citations (if enabled)552    {553      "text": "Based on the article, ",554      "type": "text"555    },556    {557      "text": "the main argument presented is that artificial intelligence will transform healthcare",558      "type": "text",559      "citations": [560        {561          "type": "char_location",562          "document_index": 0,563          "document_title": "Article Title",564          "start_char_index": 1234,565          "end_char_index": 1456,566          "cited_text": "Artificial intelligence is poised to revolutionize healthcare delivery..."567        }568      ]569    }570  ],571  "id": "msg_a930390d3a",572  "usage": {573    "input_tokens": 25039,574    "output_tokens": 931,575    "server_tool_use": {576      "web_fetch_requests": 1577    }578  },579  "stop_reason": "end_turn"580}581```582583### Fetch results584585Fetch results include:586587* `url`: The URL that was fetched588* `content`: A document block containing the fetched content589* `retrieved_at`: Timestamp when the content was retrieved590591<Note>592  The web fetch tool caches results to improve performance and reduce redundant requests. The content returned may not always reflect the latest version available at the URL. The cache behavior is managed automatically and may change over time to optimize for different content types and usage patterns. To fetch fresh content, set `"use_cache": false` (see [Cache bypass](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#cache-bypass)).593</Note>594595For PDF documents, content is returned as base64-encoded data:596597```json Output598{599  "type": "web_fetch_tool_result",600  "tool_use_id": "srvtoolu_02",601  "content": {602    "type": "web_fetch_result",603    "url": "https://example.com/paper.pdf",604    "content": {605      "type": "document",606      "source": {607        "type": "base64",608        "media_type": "application/pdf",609        "data": "JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmo..."610      },611      "citations": { "enabled": true }612    },613    "retrieved_at": "2025-08-25T10:30:02Z"614  }615}616```617618### Errors619620When the web fetch tool encounters an error, the Claude API returns a 200 (success) response with the error represented in the response body. Claude sees the error result and continues the turn. For example:621622```json Output623{624  "type": "web_fetch_tool_result",625  "tool_use_id": "srvtoolu_a93jad",626  "content": {627    "type": "web_fetch_tool_result_error",628    "error_code": "url_not_accessible"629  }630}631```632633These are the possible error codes:634635* `invalid_tool_input`: Invalid tool input, such as a malformed URL or a non-HTTP(S) scheme636* `url_too_long`: URL exceeds maximum length (250 characters)637* `url_not_allowed`: URL blocked by domain filtering rules (including your organization's settings) or by Anthropic-side restrictions, such as private addresses and `robots.txt`638* `url_not_in_prior_context`: URL did not appear earlier in the conversation (see [URL validation](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool#url-validation))639* `url_not_accessible`: Failed to fetch content (HTTP error)640* `too_many_requests`: Rate limit exceeded641* `unsupported_content_type`: Content type not supported (only text, HTML, and PDF)642* `max_uses_exceeded`: Maximum web fetch tool uses exceeded643* `unavailable`: An internal error occurred644645## URL validation646647For security reasons, the web fetch tool can only fetch URLs that have previously appeared in the conversation context. This includes:648649* URLs in user messages650* URLs in client-side tool results651* URLs from previous web search or web fetch results652653The tool cannot fetch URLs that appear only in Claude's own output or only in the system prompt. To make a URL from the system prompt fetchable, also include it in a user message. Results of other server-side tools, such as [code execution](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool), the [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector), or [tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool), are not an allowed source either. Client-side tool results are an allowed source even when they echo text that Claude produced (for example, a command that prints its input, or an error message that quotes it).654655## Combined search and fetch656657When both the web search and web fetch tools are enabled, and the user names a specific page or document without providing a URL (for example, "read the README from the anthropics/anthropic-sdk-python repository"), Claude uses web search to locate it, then fetches the result. The following example asks for a search and an analysis in one request:658659<CodeGroup>660  ```bash cURL661  curl https://api.anthropic.com/v1/messages \662    -H "x-api-key: $ANTHROPIC_API_KEY" \663    -H "anthropic-version: 2023-06-01" \664    -H "content-type: application/json" \665    -d '{666      "model": "claude-opus-4-8",667      "max_tokens": 4096,668      "messages": [669        {670          "role": "user",671          "content": "Find recent articles about quantum computing and analyze the most relevant one in detail"672        }673      ],674      "tools": [675        {676          "type": "web_search_20250305",677          "name": "web_search",678          "max_uses": 3679        },680        {681          "type": "web_fetch_20250910",682          "name": "web_fetch",683          "max_uses": 5,684          "citations": {"enabled": true}685        }686      ]687    }'688  ```689690  ```bash CLI691  ant messages create <<'YAML'692  model: claude-opus-4-8693  max_tokens: 4096694  messages:695    - role: user696      content: >-697        Find recent articles about quantum computing698        and analyze the most relevant one in detail699  tools:700    - type: web_search_20250305701      name: web_search702      max_uses: 3703    - type: web_fetch_20250910704      name: web_fetch705      max_uses: 5706      citations:707        enabled: true708  YAML709  ```710711  ```python Python712  client = anthropic.Anthropic()713714  response = client.messages.create(715      model="claude-opus-4-8",716      max_tokens=4096,717      messages=[718          {719              "role": "user",720              "content": "Find recent articles about quantum computing and analyze the most relevant one in detail",721          }722      ],723      tools=[724          {"type": "web_search_20250305", "name": "web_search", "max_uses": 3},725          {726              "type": "web_fetch_20250910",727              "name": "web_fetch",728              "max_uses": 5,729              "citations": {"enabled": True},730          },731      ],732  )733  print(response)734  ```735736  ```typescript TypeScript737  const client = new Anthropic();738739  const response = await client.messages.create({740    model: "claude-opus-4-8",741    max_tokens: 4096,742    messages: [743      {744        role: "user",745        content:746          "Find recent articles about quantum computing and analyze the most relevant one in detail"747      }748    ],749    tools: [750      { type: "web_search_20250305", name: "web_search", max_uses: 3 },751      {752        type: "web_fetch_20250910",753        name: "web_fetch",754        max_uses: 5,755        citations: { enabled: true }756      }757    ]758  });759760  console.log(response);761  ```762763  ```csharp C#764  AnthropicClient client = new();765766  var parameters = new MessageCreateParams767  {768      Model = Model.ClaudeOpus4_8,769      MaxTokens = 4096,770      Messages = [new() { Role = Role.User, Content = "Find recent articles about quantum computing and analyze the most relevant one in detail" }],771      Tools = [772          new ToolUnion(new WebSearchTool20250305() { MaxUses = 3 }),773          new ToolUnion(new WebFetchTool20250910() { MaxUses = 5, Citations = new() { Enabled = true } })774      ]775  };776777  var message = await client.Messages.Create(parameters);778  Console.WriteLine(message);779  ```780781  ```go Go782  client := anthropic.NewClient()783784  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{785  	Model:     anthropic.ModelClaudeOpus4_8,786  	MaxTokens: 4096,787  	Messages: []anthropic.MessageParam{788  		anthropic.NewUserMessage(anthropic.NewTextBlock("Find recent articles about quantum computing and analyze the most relevant one in detail")),789  	},790  	Tools: []anthropic.ToolUnionParam{791  		{OfWebSearchTool20250305: &anthropic.WebSearchTool20250305Param{792  			MaxUses: anthropic.Int(3),793  		}},794  		{OfWebFetchTool20250910: &anthropic.WebFetchTool20250910Param{795  			MaxUses:   anthropic.Int(5),796  			Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},797  		}},798  	},799  })800  if err != nil {801  	log.Fatal(err)802  }803  fmt.Println(response.RawJSON())804  ```805806  ```java Java807  import com.anthropic.models.messages.CitationsConfigParam;808  // ...809  import com.anthropic.models.messages.WebFetchTool20250910;810  import com.anthropic.models.messages.WebSearchTool20250305;811812  void main() {813      AnthropicClient client = AnthropicOkHttpClient.fromEnv();814815      MessageCreateParams params = MessageCreateParams.builder()816          .model(Model.CLAUDE_OPUS_4_8)817          .maxTokens(4096L)818          .addUserMessage("Find recent articles about quantum computing and analyze the most relevant one in detail")819          .addTool(WebSearchTool20250305.builder()820              .maxUses(3L)821              .build())822          .addTool(WebFetchTool20250910.builder()823              .maxUses(5L)824              .citations(CitationsConfigParam.builder().enabled(true).build())825              .build())826          .build();827828      Message response = client.messages().create(params);829      IO.println(response);830  }831  ```832833  ```php PHP834  $client = new Client();835836  $message = $client->messages->create(837      maxTokens: 4096,838      messages: [839          ['role' => 'user', 'content' => 'Find recent articles about quantum computing and analyze the most relevant one in detail']840      ],841      model: 'claude-opus-4-8',842      tools: [843          [844              'type' => 'web_search_20250305',845              'name' => 'web_search',846              'max_uses' => 3,847          ],848          [849              'type' => 'web_fetch_20250910',850              'name' => 'web_fetch',851              'max_uses' => 5,852              'citations' => ['enabled' => true],853          ],854      ],855  );856  echo $message;857  ```858859  ```ruby Ruby860  client = Anthropic::Client.new861862  message = client.messages.create(863    model: "claude-opus-4-8",864    max_tokens: 4096,865    messages: [866      { role: "user", content: "Find recent articles about quantum computing and analyze the most relevant one in detail" }867    ],868    tools: [869      {870        type: "web_search_20250305",871        name: "web_search",872        max_uses: 3873      },874      {875        type: "web_fetch_20250910",876        name: "web_fetch",877        max_uses: 5,878        citations: { enabled: true }879      }880    ]881  )882  puts message883  ```884</CodeGroup>885886In this workflow, Claude:8878881. Uses web search to find relevant articles.8892. Selects the most promising results.8903. Uses web fetch to retrieve full content.8914. Provides detailed analysis with citations.892893## Prompt caching894895To cache tool definitions across turns, see [Tool use with prompt caching](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-use-with-prompt-caching).896897## Streaming898899With streaming enabled, fetch events are part of the stream with a pause during content retrieval:900901```sse Output902event: message_start903data: {"type": "message_start", "message": {"id": "msg_abc123", "type": "message"}}904905event: content_block_start906data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}907908// Claude's decision to fetch909910event: content_block_start911data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "web_fetch"}}912913// Fetch URL streamed914event: content_block_delta915data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"url\":\"https://example.com/article\"}"}}916917// Pause while fetch executes918919// Fetch results streamed920event: content_block_start921data: {"type": "content_block_start", "index": 2, "content_block": {"type": "web_fetch_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "web_fetch_result", "url": "https://example.com/article", "content": {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "Article content..."}}}}}922923// Claude's response continues...924```925926## Batch requests927928You can include the web fetch tool in the [Messages Batches API](https://platform.claude.com/docs/en/build-with-claude/batch-processing). Web fetch tool calls through the Messages Batches API are priced the same as those in regular Messages API requests.929930## Usage and pricing931932Web fetch usage has **no additional charges** beyond standard token costs:933934```json935{936  "usage": {937    "input_tokens": 25039,938    "output_tokens": 931,939    "cache_read_input_tokens": 0,940    "cache_creation_input_tokens": 0,941    "server_tool_use": {942      "web_fetch_requests": 1943    }944  }945}946```947948The web fetch tool is available on the Claude API at **no additional cost**. You only pay standard token costs for the fetched content that becomes part of your conversation context.949950To protect against inadvertently fetching large content that would consume excessive tokens, use the `max_content_tokens` parameter to set appropriate limits based on your use case and budget considerations.951952Example token usage for typical content:953954* Average web page (10 kB): \~2,500 tokens955* Large documentation page (100 kB): \~25,000 tokens956* Research paper PDF (500 kB): \~125,000 tokens957958## Next steps959960<CardGroup>961  <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool" title="Code execution tool" icon="code">962    Run Python and bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.963  </Card>964965  <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools" title="Server tools" icon="cloud">966    Work with Anthropic-executed tools: server\_tool\_use blocks, pause\_turn continuation, and domain filtering.967  </Card>968969  <Card href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-reference" title="Tool reference" icon="book">970    Directory of Anthropic-provided tools and reference for optional tool definition properties.971  </Card>972</CardGroup>973
Files main
Menu

Theme