How to Add Web Search to the Claude Agent SDK (MCP)
The Claude Agent SDK gives you the same agent loop that powers Claude Code as a library: you call query() from Python or TypeScript, and Claude plans, calls tools and keeps going until the task is done. Out of the box it can read files and run commands, but anything that changed after the model's training cut-off (a new release, today's docs, a fresh error message) needs a tool that reaches the live web.
The SDK speaks MCP natively, so the fastest way to add web search to the Claude Agent SDK is to plug in an MCP server. This guide uses AgentSearch's MCP server, @agentsearchhq/agentsearch-mcp, which you start with one npx command. Search works right away with no API key, no signup and no wallet: 25 free searches per IP in total, then pay per call. That 25 is a lifetime allowance per IP, not a daily one, and it does not reset.
You will get:
- A Python agent and a TypeScript agent that search the web and cite sources
- Page reading (URL to clean markdown) and news search from the same server
- A clear path to paid calls over x402 when the free allowance runs out
- A few production guardrails: tool allow-lists, turn limits and untrusted-content handling
What you need
- Python 3.10+ or Node.js 18+ (Node is needed either way, because
npxstarts the MCP server) - An Anthropic API key in
ANTHROPIC_API_KEYfor the model itself - Nothing for AgentSearch: no key, no account
Install the SDK for your language:
# Python
pip install claude-agent-sdk
# TypeScript / JavaScript
npm install @anthropic-ai/claude-agent-sdk
You don't need to install the MCP server separately. npx -y @agentsearchhq/agentsearch-mcp downloads the current version (1.8.7 at the time of writing) the first time the agent starts.
The tools your agent gets
The AgentSearch MCP server exposes these tools. In the Claude Agent SDK, MCP tools are named mcp__<server-name>__<tool-name>, so with a server called agentsearch you get:
| Tool | SDK name | What it does |
|---|---|---|
agentsearch_web_search |
mcp__agentsearch__agentsearch_web_search |
Real-time web search, ranked results with URLs and snippets |
agentsearch_extract |
mcp__agentsearch__agentsearch_extract |
Any public URL to clean markdown for the model |
agentsearch_render |
mcp__agentsearch__agentsearch_render |
Renders JavaScript-heavy pages first, for when Extract comes back empty |
agentsearch_search_and_read |
mcp__agentsearch__agentsearch_search_and_read |
Search plus the top pages' markdown in one call |
agentsearch_news_search |
mcp__agentsearch__agentsearch_news_search |
Recent news results |
agentsearch_screenshot |
mcp__agentsearch__agentsearch_screenshot |
A screenshot of a page |
With no wallet configured, search uses the free allowance and Extract and Render run on a small free trial (5 extract and 3 render calls per day per IP). More on paid calls below.
Python: a research agent with web search
Pass the server in mcp_servers and list the tools you want Claude to use without asking in allowed_tools:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
options = ClaudeAgentOptions(
mcp_servers={
"agentsearch": {
"command": "npx",
"args": ["-y", "@agentsearchhq/agentsearch-mcp"],
}
},
allowed_tools=[
"mcp__agentsearch__agentsearch_web_search",
"mcp__agentsearch__agentsearch_extract",
],
system_prompt=(
"You are a research assistant. Use agentsearch_web_search for anything "
"that may have changed recently, read the best result with "
"agentsearch_extract when snippets are not enough, and cite every URL you use."
),
max_turns=8,
)
async def main():
async for message in query(
prompt="What changed in the latest Python release? Cite sources.",
options=options,
):
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
Run it with ANTHROPIC_API_KEY set. On the first turn the SDK starts the MCP server over stdio and lists its tools; Claude then decides when to search and when to read a page.
See which tools the agent called
While you're developing, it helps to watch the tool calls go by. Assistant messages carry ToolUseBlock items:
from claude_agent_sdk import AssistantMessage, ToolUseBlock
async def main():
async for message in query(prompt="Latest stable Node.js LTS version?", options=options):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, ToolUseBlock):
print("tool:", block.name, block.input)
elif isinstance(message, ResultMessage) and message.subtype == "success":
print("\nanswer:", message.result)
If you never see mcp__agentsearch__... in that output, check that npx is on the PATH of the process running your script and that the tool names in allowed_tools match exactly.
TypeScript: the same agent
The TypeScript SDK takes the same shape, with camelCase option names:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Summarize this week's most important MCP spec changes, with links.",
options: {
mcpServers: {
agentsearch: {
command: "npx",
args: ["-y", "@agentsearchhq/agentsearch-mcp"],
},
},
allowedTools: [
"mcp__agentsearch__agentsearch_web_search",
"mcp__agentsearch__agentsearch_news_search",
"mcp__agentsearch__agentsearch_extract",
],
maxTurns: 8,
},
})) {
if (message.type === "assistant") {
for (const block of message.message.content) {
if (block.type === "tool_use") console.log("tool:", block.name);
}
}
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
You can also allow every tool from the server with a wildcard, "mcp__agentsearch__*". Listing tools one by one is better in production, because it keeps paid tools out of the loop until you mean to use them.
Keep the config in .mcp.json instead
If you'd rather not hard-code the server, put it in a .mcp.json file at your project root. The SDK loads it when the project setting source is enabled, which it is with default query() options:
{
"mcpServers": {
"agentsearch": {
"command": "npx",
"args": ["-y", "@agentsearchhq/agentsearch-mcp"]
}
}
}
The same file works in Claude Code, so your interactive sessions and your SDK agents share one setup. You still list the tools in allowed_tools / allowedTools.
Prefer no local process at all? AgentSearch also runs a hosted MCP endpoint over Streamable HTTP with no key and no sign-in. The SDK accepts "type": "http" servers, and the URL and setup are on the MCP page.
Search, then read: the pattern that makes answers good
Search snippets are short. For questions where the details matter (an API's parameters, a changelog, a pricing page) the agent should read the page itself. Two ways to get there:
- Two tools. Allow
agentsearch_web_searchandagentsearch_extract, and tell the agent in the system prompt to read the top one or two results before answering. Claude is good at picking which URL is worth reading. - One call. Allow
agentsearch_search_and_read, which returns the top results with each page's markdown in a single call. Fewer round trips, and a good default for "research this and summarize" tasks.
If Extract returns an empty or near-empty page, the site probably builds its content with JavaScript. That's what agentsearch_render is for: it loads the page in a headless browser first. More on that in Render.
When the free allowance runs out: pay per call with x402
The 25 free searches are per IP, in total. After that, the server tells the agent the free allowance is used up and points to wallet setup. You don't sign up for a plan or create an API key. Instead, AgentSearch's API takes per-call payments over x402: USDC on Base, no minimums, and failed or empty answers are not charged.
Current prices (from the live pricing endpoint):
- Search: $0.003 per call
- News: $0.003 per call
- Extract: $0.002 per call
- Search + Read: $0.005 per call
To turn it on, give the MCP server a wallet. Use a fresh wallet that holds only a few dollars of USDC on Base (no ETH is needed for gas):
import os
options = ClaudeAgentOptions(
mcp_servers={
"agentsearch": {
"command": "npx",
"args": ["-y", "@agentsearchhq/agentsearch-mcp"],
"env": {
"AGENTSEARCH_WALLET_PRIVATE_KEY": os.environ["AGENTSEARCH_WALLET_PRIVATE_KEY"],
"AGENTSEARCH_MODE": "paid",
},
}
},
allowed_tools=["mcp__agentsearch__agentsearch_web_search", "mcp__agentsearch__agentsearch_extract"],
)
With a wallet set, Extract and Render are paid. On the 1.8.x server, search pays only when AGENTSEARCH_MODE=paid is set, so leave it out if you want search to stay on the free allowance. The server also enforces spending caps by default: $0.020 per call and $1.00 per session. The wallet setup guide walks through creating and funding a wallet.
Keep the private key in an environment variable or a secret manager, never in code or in .mcp.json committed to git.
Production checklist
- Allow-list tools. Name each tool in
allowed_toolsrather than using a wildcard, especially once a wallet is attached. - Turn off the built-in web tools if you want one source. The SDK has its own
WebSearchandWebFetchtools. If you want every lookup to go through AgentSearch, add them todisallowed_tools/disallowedTools. - Cap the loop. Set
max_turns/maxTurnsso a confused agent can't search forever. - Treat web content as untrusted. A page can contain text written to steer an AI. Don't let page text trigger actions (file writes, shell commands, emails) your agent wouldn't take otherwise, and keep risky tools out of the same agent that browses.
- Mind the first-turn wait. Stdio MCP servers delay the first turn until they connect, up to
MCP_TIMEOUT(30 seconds by default). The firstnpxdownload takes the longest; later starts use the npm cache. - Shared IPs share the allowance. In CI or on a cloud host, the 25 free searches count against that machine's outgoing IP, which other workloads may have used already. Attach a wallet for anything that runs unattended.
FAQ
Does the Claude Agent SDK support MCP servers?
Yes. Pass them in mcp_servers (Python) or mcpServers (TypeScript), or load them from .mcp.json. Stdio, HTTP and SSE servers all work, plus in-process SDK servers.
Do I need an API key for web search?
Not for AgentSearch. You get 25 free searches per IP in total with no key, account or wallet, then pay per call over x402. You still need your Anthropic key for the model.
Why doesn't my agent call the search tool?
Usually the tool isn't allowed or the name is off by a character. MCP tools in the SDK are mcp__<server>__<tool>, so the server name in mcp_servers has to match the middle part. A system prompt that says when to search also helps.
Can I use this with LangChain or the OpenAI Agents SDK instead?
Yes. There are framework packages for those too: see LangChain and the OpenAI Agents SDK.
Next steps
- How to add web search to Claude Code (MCP), the interactive side of the same setup
- A Claude Code web research workflow
- Search and read in one paid call
- x402 in Python for AI agent web search
- All MCP clients on the AgentSearch MCP page
Add one entry to mcp_servers, allow mcp__agentsearch__agentsearch_web_search, and ask your agent about something that changed last week. Search is free for the first 25 calls per IP, then $0.003 per search.
More from the blog
- How to Add Free Web Search to Claude Code with MCP
- Add Web Search to the OpenAI Agents SDK
- How to Add Web Search to a LangChain Agent in Python (No API Key)
- Free Remote MCP Server for Web Search: Hosted, No Install, No API Key
Service pages: Web Search API · Web Extract API · Search + Read API · Web Render API