📋 Executive Summary
- 🚀 Fastest Path: The Claude Agent SDK provides the core agent loop, file tools, sessions, permissions, hooks, and Python or TypeScript interfaces needed for faster agent development.
- ⚖️ Control Trade-Off: The Claude API gives direct access to tool_use and tool_result exchanges, but developers must handle execution, validation, retries, and audit processes themselves.
- 💰 Pricing Trap: Claude Sonnet 5 includes introductory API pricing through 31 August 2026, while web search adds $10 per 1,000 searches alongside normal token charges.
- 🔐 Hidden Constraint: The allowed_tools setting can automatically approve matching calls, but it does not independently remove every other tool from the agent environment.
- ✅ Production Decision: Begin with a focused research agent, limit turns and spending, require approval for external actions, and expand only after trace-based evaluations succeed.
I would use the Claude Agent SDK for the quickest answer to how to build an ai agent with claude, because it already contains the tool loop, context handling, sessions, permissions, and built-in capabilities that otherwise become your engineering burden. The sharp catch is that a useful agent is not a single model call: every extra search, file read, command, retry, and reflection step can multiply cost and create a new failure boundary.
The alternative is the lower-level Claude Messages API. It gives you exact control over tool schemas and execution, but your code must detect a tool_use stop reason, validate the requested arguments, run the function, return a matching tool_result block, preserve the conversation, and decide when to stop. That route is better when a regulated workflow, custom orchestrator, existing job system, or framework-independent architecture requires deterministic ownership of every side effect.
This guide builds both paths in Python, then turns them into a web research agent. It covers model selection, current API pricing, prompt caching, web search charges, MCP integrations, session state, permission boundaries, error handling, evaluation, observability, and deployment. It also separates documented facts from judgement. Anthropic’s public interfaces are changing quickly, so the examples pin current model names and explain where a production team should add configuration rather than hard-code assumptions. The objective is not maximum autonomy. It is the smallest agent loop that can complete a defined task, produce an auditable result, and stop safely when evidence, permissions, or budget run out. It is a build guide for engineers who need working code, not a catalogue of agent hype.
Choose the Right Claude Build Path
The architectural decision is simple when framed around ownership. Use the Agent SDK when you want Claude Code’s production-shaped runtime as a library. Anthropic documents the same core agent loop, context management, and built-in tools in Python and TypeScript, including file reading, command execution, code editing, web search, and web fetch. The SDK is therefore more than a convenience wrapper around one completion request. It is an opinionated operating layer for a long-running task (Anthropic, 2026a).
Use the raw Claude API when the tool executor must remain entirely inside your application. A bank may need each requested action to pass policy, entitlement, and dual-control checks. A SaaS platform may already have a durable job queue, idempotency keys, tenant-level rate limits, and an audit stream. In those environments, replacing the existing control plane with a bundled agent runtime would create more work, not less.
| Decision | Claude Agent SDK | Raw Claude API |
| Best Fit | Fast production-shaped agents with built-in runtime | Custom orchestration and strict executor ownership |
| Agent Loop | Managed by the SDK | Implemented by your application |
| Tools | Built-ins, custom tools, MCP servers | Client tools plus Anthropic server tools |
| Sessions | Resume, continue, fork, external store | Persist the Messages conversation yourself |
| Permissions | Tools, allow/deny rules, modes, callbacks, hooks | Entirely enforced by your executor and services |
| Operational Burden | Lower, but still requires governance | Higher, with maximum architectural control |
A useful way to think about the decision is to separate model intelligence from orchestration. The model proposes the next step. The orchestration layer decides whether that step is permitted, executes it, records the result, and manages the lifecycle. The magazine’s practical AI agent build path makes the same product point: narrow goals and explicit tools matter more than theatrical autonomy. The Agent SDK owns more of orchestration; the raw API leaves it with you.
There is also a middle ground. Teams can use the Agent SDK but connect custom functions through in-process MCP servers, apply hooks before and after tool calls, restrict filesystem settings, mirror sessions to external storage, and export telemetry. That is often enough control for internal research, coding, support analysis, and document workflows without rebuilding the loop.
How to Build an AI Agent With Claude in Python
The minimal SDK build needs Python, the claude-agent-sdk package, an Anthropic API key, a goal prompt, and a bounded tool set. The key design decision is not the number of tools. It is whether every tool is necessary for the promised outcome. A repository review agent can often operate with Read, Glob, and Grep. A research agent may need WebSearch, WebFetch, and Write. Bash should not be included merely because it is powerful.
Install the SDK in a virtual environment and keep the API key in an environment variable or secret manager. Do not write the key into the script, a CLAUDE.md file, a prompt, or a repository. Then use query() for a one-off job or ClaudeSDKClient for a continuing conversation that needs interrupts and explicit lifecycle control. The example below starts a fresh, bounded task and prints the final result.
The code deliberately sets tools as well as allowed_tools. Anthropic’s Python reference states that allowed_tools means auto-approved tools; unlisted tools can still flow through the permission system (Anthropic, 2026b). Treating that field as a complete allow-list is a subtle security mistake. A stricter build supplies only the tools that should be present, denies dangerous variants, disables ambient settings with setting_sources=[], and adds a permission or hook layer for any call that can change external state.
The example uses Claude Sonnet 5 as the default cost-performance choice for research and automation. Claude Opus 4.8 is the stronger starting point for complex agentic coding and enterprise work, while Haiku 4.5 is useful for low-latency classification or routing. Model choice should remain configuration because model lifecycle, pricing, and workload fit can change independently from application code. The AI agent for coding guide offers a complementary view of repository-specific tool and model trade-offs.
How to Build an AI Agent With Claude Using the SDK
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main() -> None:
options = ClaudeAgentOptions(
model=”claude-sonnet-5″,
tools=[“Read”, “Glob”, “Grep”],
allowed_tools=[“Read”, “Glob”, “Grep”],
disallowed_tools=[“Bash”, “Write”, “Edit”],
setting_sources=[],
max_turns=8,
max_budget_usd=1.00,
)
async for message in query(
prompt=”Find all TODO comments and summarise them by file.”,
options=options,
):
if isinstance(message, ResultMessage):
print(message.result)
if __name__ == “__main__”:
asyncio.run(main())
Understand the Raw Tool-Use Loop
A raw Claude API agent is a state machine around the Messages API. Your application sends the conversation and tool definitions. Claude either returns a normal answer or a tool request. For client-side tools, the response includes stop_reason set to tool_use and one or more tool_use content blocks. Your executor validates each block, runs the matching function, and sends a new user message containing tool_result blocks linked by tool_use_id.
The loop must preserve Claude’s complete assistant response before appending tool results. Dropping text or tool blocks can break continuity. It must also handle several tool calls in one turn, because Claude can request parallel work. Execute independent read-only calls concurrently when the underlying services and rate limits allow it. Keep dependent or state-changing actions sequential, and establish a deterministic order for audit records.
Errors are part of the protocol. When a function fails, return a tool_result with is_error set to true and a concise, machine-useful explanation. Do not hide the failure behind a fabricated success result. Claude can then retry, choose another tool, ask for clarification, or stop. Your host application should still enforce a maximum number of turns, wall-clock deadline, retry budget, and repeated-call detector so the model cannot cycle indefinitely.
This lower-level route is the right choice when a workflow engine already owns retries, compensation, approvals, and state. It also makes provider portability easier because the tool executor is not coupled to one bundled runtime. The cost is substantial boilerplate. You must implement validation, permissions, concurrency, error semantics, observability, token accounting, and termination correctly before the agent is safe enough to act.
A Minimal Client-Side Executor
import json
from typing import Any
from anthropic import Anthropic
client = Anthropic()
def lookup_order(order_id: str) -> dict[str, Any]:
# Replace with an authenticated, policy-checked service call.
return {“order_id”: order_id, “status”: “processing”}
tools = [{
“name”: “lookup_order”,
“description”: “Read the current status of one order.”,
“input_schema”: {
“type”: “object”,
“properties”: {“order_id”: {“type”: “string”}},
“required”: [“order_id”],
“additionalProperties”: False,
},
}]
messages = [{“role”: “user”, “content”: “Check order A-1042.”}]
for _ in range(6):
response = client.messages.create(
model=”claude-sonnet-5″,
max_tokens=1200,
tools=tools,
messages=messages,
)
messages.append({“role”: “assistant”, “content”: response.content})
if response.stop_reason != “tool_use”:
print(next(block.text for block in response.content
if block.type == “text”))
break
results = []
for block in response.content:
if block.type != “tool_use”:
continue
try:
if block.name != “lookup_order”:
raise ValueError(“Unknown tool”)
payload = lookup_order(**block.input)
results.append({
“type”: “tool_result”,
“tool_use_id”: block.id,
“content”: json.dumps(payload),
})
except Exception as exc:
results.append({
“type”: “tool_result”,
“tool_use_id”: block.id,
“content”: str(exc),
“is_error”: True,
})
messages.append({“role”: “user”, “content”: results})
else:
raise RuntimeError(“Agent exceeded the turn limit”)
Map Tools, Permissions, and Integrations
Claude agents can work with three broad tool classes. First, built-in Agent SDK tools cover local or sandboxed work such as Read, Write, Edit, Glob, Grep, Bash, WebSearch, and WebFetch. Second, the Claude API exposes server-side tools including web search, web fetch, code execution, and tool search, which Anthropic runs on its infrastructure. Third, custom client tools and MCP servers connect the model to your own APIs, databases, SaaS systems, and business operations.
MCP is the most important integration surface because it standardises how tools and context are presented. The SDK can connect configured MCP servers, and Python code can create an in-process SDK MCP server for typed local functions (Anthropic, 2026b). A finance agent might connect read-only tools for accounts and exchange rates, then route payment creation through a separate approval service. A support agent might query a knowledge base and ticket system, but reserve refunds or account changes for a human-confirmed path.
| Surface | Documented Capabilities | Production Constraint |
| Agent SDK Runtime | Agent loop, context management, Python and TypeScript, one-off and continuous clients | Bundled behaviour still needs explicit limits and policy |
| Built-In Tools | Read, Write, Edit, Glob, Grep, Bash, WebSearch, WebFetch, Agent and related Claude Code tools | Present only the tools needed for the task |
| Control | allowed_tools, disallowed_tools, permission modes, can_use_tool, hooks, sandbox settings | allowed_tools auto-approves; use hooks to gate every call |
| State | Continue, resume, fork, list sessions, checkpoint files, external session store | Retention and deletion remain application responsibilities |
| Extensions | MCP servers, in-process SDK MCP tools, plugins, skills, subagents | Every server or plugin expands the trusted dependency surface |
| Observability | Usage and cost estimates, debug streams, hook events, OpenTelemetry support | Client estimates must be reconciled with billing and task outcomes |
| Cloud Access | Claude API, Claude Platform on AWS, Amazon Bedrock, Google Cloud, Microsoft Foundry | Model IDs, regions, billing, and lifecycle differ by route |
Permissions should be layered. The tools field controls what is present. allowed_tools can auto-approve selected calls. disallowed_tools can remove a tool entirely or deny scoped command patterns. permission_mode and can_use_tool can handle prompts and policy decisions. Hooks can intercept pre-tool and post-tool events, which matters because a custom permission function is not invoked for calls already auto-approved by settings or allowed_tools. Anthropic’s TypeScript reference explicitly recommends a PreToolUse hook when every call must be gated (Anthropic, 2026b).
Integrations are not a finite vendor list. MCP servers can represent almost any system that exposes an API, while Claude models are available through Anthropic’s first-party API, Claude Platform on AWS, Amazon Bedrock, Google Cloud, and Microsoft Foundry. Each route has different identity, networking, region, billing, and lifecycle implications. The table therefore lists the documented integration surfaces rather than pretending every third-party connector has been independently verified. Document ownership, credential rotation, and server retirement procedures before an integration reaches production.
Build a Web Research Agent
A good first project is a web research agent because the task is useful, mostly read-only, and easy to evaluate. Give the agent a narrow question, a source policy, a search budget, an output schema, and permission to save one report. Do not begin with open-ended instructions such as research everything about this market. A bounded request should identify the audience, date range, preferred source types, required citations, and what to do when evidence conflicts.
The Agent SDK example below uses WebSearch, WebFetch, and Write, blocks Bash and Edit, disables local settings, caps the task at twelve turns, and applies a client-side budget estimate. It instructs the agent to prefer primary sources, record publication dates, separate facts from inference, and state unresolved gaps. The output file is the only intended side effect.
For a research workflow, web search and web fetch serve different jobs. Search discovers candidates. Fetch reads a known page. Anthropic’s current API pricing charges web search at $10 per 1,000 searches plus standard token costs, while web fetch adds no separate tool charge but the fetched content becomes billable context (Anthropic, 2026d). This makes aggressive fetching a hidden cost centre. Limit max_content_tokens where available, fetch only pages that can materially support the answer, and avoid carrying full source text through every turn.
The magazine’s research agent stack emphasises a verification layer rather than a one-button report. That remains the decisive practice here. The agent can gather and organise evidence, but a production workflow should validate source identity, dates, quotations, numerical units, and links before publication. For high-stakes work, require a human to approve the final evidence table and any claim that could affect money, safety, legal rights, or reputation.
Ready-to-Run Python Research Template
import asyncio
from pathlib import Path
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
REPORT = Path(“market-research.md”).resolve()
SYSTEM = “””You are a research agent. Prefer primary sources and recent
official documents. Record publication dates. Separate verified facts from
inference. Never invent a quotation, price, statistic, or source. Save one
Markdown report with a source table and an unresolved-gaps section.”””
async def run_research(question: str) -> str:
options = ClaudeAgentOptions(
model=”claude-sonnet-5″,
system_prompt=SYSTEM,
tools=[“WebSearch”, “WebFetch”, “Write”],
allowed_tools=[“WebSearch”, “WebFetch”, “Write”],
disallowed_tools=[“Bash”, “Edit”, “Read”],
setting_sources=[],
max_turns=12,
max_budget_usd=2.00,
)
prompt = f”””Research this question: {question}
Audience: B2B technology decision-makers.
Use sources published or updated in 2025-2026 where possible.
Write the final report only to: {REPORT}
Include: answer, evidence table, conflicting evidence, limitations, sources.”””
final = “”
async for message in query(prompt=prompt, options=options):
if isinstance(message, ResultMessage):
final = message.result or “”
return final
if __name__ == “__main__”:
result = asyncio.run(run_research(
“What controls make enterprise AI agents reliable in production?”
))
print(result)
Manage State, Sessions, Memory, and Context
State is the information needed to continue the current task. Memory is information retained for later tasks. Mixing them creates privacy, relevance, and cost problems. Start with task-local state in the current session: the user’s goal, source list, tool outputs, partial report, and evaluation status. Add durable memory only when repeated work demonstrably improves and the user can inspect, correct, expire, or delete what is stored.
The SDK provides two interaction models. query() creates a new session by default and suits one-off jobs. It can continue or resume manually. ClaudeSDKClient maintains a continuous conversation, supports interrupts, and gives the application explicit session control. The Python interface also exposes session listing, resuming, forking, external session stores, and checkpointing for file changes. These are operational capabilities, not a substitute for a data-retention policy.
Context windows are large but not free. Fable 5, Opus 4.8, and Sonnet 5 currently support 1 million tokens, while Haiku 4.5 supports 200,000. The larger models support up to 128,000 synchronous output tokens, and Haiku supports 64,000 (Anthropic, 2026e). Large context can reduce retrieval plumbing for some tasks, but it can increase latency, token charges, and the chance that stale or irrelevant material affects the plan. Define a context admission rule so new material enters the working set only when it supports an active subtask or a required audit trail.
Use prompt caching for stable system instructions, policies, tool descriptions, and reference material that recur across turns. Summarise completed phases into compact structured state, but retain source identifiers and key evidence so the summary remains auditable. Keep raw tool logs outside the model context when they are needed for compliance but not reasoning. The agent orchestration control layer becomes valuable when multiple specialised steps need shared state without forcing one model conversation to carry every byte.
Price the Agent Loop Before Production
An agent’s cost is the sum of model tokens, cache operations, server-side tool fees, runtime charges, retries, and the work required to review failures. A single answer may contain several model turns. A web research task may also pay for search requests and for search results that re-enter context. Cost estimates based only on the final response understate the real workload.
As of 13 July 2026, Claude Sonnet 5 has introductory pricing of $2 per million input tokens and $10 per million output tokens through 31 August 2026, then moves to $3 and $15. Opus 4.8 is $5 input and $25 output, Fable 5 is $10 and $50, and Haiku 4.5 is $1 and $5. Batch processing halves base input and output rates for eligible asynchronous workloads. Regional or multi-region endpoints on partner clouds carry a 10% premium for current generations (Anthropic, 2026d).
| Model | Input / MTok | Output / MTok | Cache Hit / MTok | Context | Max Output |
| Claude Fable 5 | $10 | $50 | $1 | 1M | 128k |
| Claude Opus 4.8 | $5 | $25 | $0.50 | 1M | 128k |
| Claude Sonnet 5 to 31 Aug 2026 | $2 | $10 | $0.20 | 1M | 128k |
| Claude Sonnet 5 from 1 Sep 2026 | $3 | $15 | $0.30 | 1M | 128k |
| Claude Haiku 4.5 | $1 | $5 | $0.10 | 200k | 64k |
Prompt caching changes the economics for repeated context. Cache hits are one tenth of base input price for the listed models, while five-minute and one-hour cache writes use higher multipliers. Another easily missed factor is tokenisation: Anthropic states that Opus 4.7 and later Opus models, Fable 5, Mythos models, and Sonnet 5 use a tokenizer that produces approximately 30% more tokens for the same text, depending on workload (Anthropic, 2026d). Re-price real prompts after migration instead of assuming character count maps consistently across models.
The SDK’s max_budget_usd is useful, but the documentation describes it as a client-side cost estimate with accuracy caveats. It is a stop mechanism, not a contractual billing ceiling. Pair it with server-side account controls, per-job token and tool limits, request logs, and alerts. Budget by successful task, not by request: total spend divided by outputs that pass evaluation is the metric that exposes looping and low-quality retries. Recalculate that figure whenever tools, prompts, models, or source policies change.
| Cost Component | Current Public Rate or Limit | Hidden or Operational Detail |
| Web Search | $10 per 1,000 searches plus tokens | Each search counts once; search content remains billable context |
| Web Fetch | No additional tool fee | Fetched content consumes input tokens; use content limits |
| Code Execution | 1,550 free hours per organisation monthly, then $0.05 per container-hour | Five-minute minimum when used alone; files preload can start billing |
| Managed Agents Runtime | $0.08 per running session-hour plus tokens | Idle and approval-wait time is not runtime-billed |
| Batch API | 50% off base input and output token rates | Not available for stateful Managed Agents sessions |
| Partner Regional Endpoints | 10% premium over global for current generations | Needed when guaranteed regional routing justifies the premium |
| SDK max_budget_usd | Client-side estimate, not a billing plan cap | Use account limits and independent usage reconciliation |
Design Safety and Approval Boundaries
The safest first agent is read-only. Search, fetch, read, classify, summarise, and draft before granting write, command, purchase, deletion, or external communication privileges. Each side effect should have a clear owner, an idempotency strategy, and a reversal plan. The safe business agent setup is useful here because business risk comes from the action boundary, not from whether the interface looks conversational.
Use least privilege at four layers. Give the process a restricted operating-system or container identity. Give each external integration a scoped credential. Present only necessary tools and argument ranges to the model. Then enforce policy again in the executor, because model instructions are not an access-control system. A tool schema that says amount must be below 1,000 is not sufficient unless the payment service checks the limit too.
Approval should be risk-based. Read-only queries can often run automatically. Reversible internal writes may use sampled review or threshold rules. External messages, money movement, destructive commands, account changes, and publication should require explicit confirmation. Present the proposed action, target, material inputs, and expected consequence to the approver. Never ask a human to approve an opaque label such as continue.
Prompt injection is a core research-agent threat. Web pages and documents can contain instructions aimed at the model. Treat retrieved content as untrusted data, not authority. Separate system policy from source text, restrict tool permissions during retrieval, and require a second validation stage before any external action. Anthropic’s agentic-autonomy research also reinforces the broader point: harmful actions can arise from model decisions even without a classic adversarial prompt, so monitoring must focus on behaviour and outcomes, not only input filtering (Anthropic, 2026g). Add a kill switch that is independent of the model and test it during routine operational drills, not only after an incident. Record who can activate it and how in-flight jobs, credentials, and partial writes are contained.
Test Reliability, Cost, and Performance
Agent evaluation must measure the full trajectory, not merely whether the final paragraph sounds good. A serious test set contains representative tasks, expected evidence, allowed tools, forbidden actions, completion criteria, and cost or latency budgets. Deterministic checks should verify tool names, arguments, files created, citations present, schema validity, and stop conditions. Human or model-based judges can assess relevance and synthesis, but they should not replace exact checks where exactness is available.
Research surveys published in 2025 describe agent evaluation across planning, tool use, memory, safety, robustness, and application-specific benchmarks (Yehudai et al., 2025). PaperArena reported that even advanced tool-augmented research agents achieved 38.78% average accuracy and 18.47% on its hard subset, while also using tools inefficiently (Wang et al., 2025). That benchmark is not a direct score for this SDK, but it is a useful warning against treating polished reports as proof of reliable research.
Measure at least task success, grounded-claim rate, tool-call precision, tool-call recall, invalid argument rate, retries, repeated calls, human intervention rate, end-to-end latency, input and output tokens, cache hit rate, server-tool uses, and cost per passing task. Add adversarial cases involving conflicting sources, unavailable pages, rate limits, malformed API responses, prompt injection, and partial write failures.
The most common bottlenecks are predictable. Large tool outputs expand context and slow later turns. Vague tool descriptions cause misrouting. Too many overlapping tools increase selection errors. Serial execution adds latency. Permission prompts can deadlock unattended jobs. Rate limits produce bursts of 429 responses. Long agent loops amplify small inaccuracies. Use compact tool results, clear schemas, parallel read-only calls, exponential backoff with jitter, circuit breakers, and a hard stop when progress stalls. Replay failed traces in a deterministic test harness so fixes target the actual decision boundary rather than a rewritten prompt that merely passes one example. Keep a frozen regression set for every production release.
Deploy a Production-Shaped Architecture
A production deployment should separate the request API, agent worker, tool gateway, state store, evidence store, and observability pipeline. The request API authenticates the user, validates the job, and writes an immutable task record. A worker starts or resumes the agent session. The tool gateway owns credentials, policy, timeouts, retries, and idempotency. State storage holds resumable task state, while the evidence store keeps source snapshots or hashes, tool outputs, and generated artefacts.
Run the agent inside an isolated environment with explicit network and filesystem boundaries. Do not expose the host home directory or broad cloud credentials. For local file agents, map only the working directory. For SaaS integrations, issue short-lived, tenant-scoped tokens where possible. Treat MCP servers as privileged dependencies: pin versions, review their schemas and code, log calls, and remove servers that are not required for the task.
Use a queue for long-running work and make every job resumable. The SDK supports sessions and external session storage, but the surrounding service still needs ownership of job status, cancellation, duplicate delivery, and retention. A job should have states such as queued, running, awaiting approval, retrying, completed, failed, and cancelled. Keep user-visible progress grounded in completed events rather than invented percentages. Publishing teams can apply the same separation to a content agent workflow while preserving editorial approval. Store a versioned manifest of the model, tools, prompts, schemas, policies, and integration versions used for each completed job so a result can be reproduced after the stack changes.
Promotion should be staged. Begin with shadow mode, where the agent proposes actions but humans perform them. Move to assisted mode for low-risk, reversible steps. Grant unattended execution only to narrow actions after measured performance is stable. The enterprise AI agent definition matters because an agent is not merely a model that can call a tool; it is an operational system that acts toward a goal under limited supervision. Production readiness therefore depends on governance and recovery as much as model capability.
What 2026 Builders and Benchmarks Reveal
Anthropic’s May 2026 Opus 4.8 announcement provides useful external signals, although vendor-selected testimonials are not independent benchmarks. Tom Pritchard, a Shopify staff engineer working on merchant agents, described the model as having “noticeably better judgment”. Michael Truell, co-founder and CEO of Cursor, said tool calling was “meaningfully more efficient” on CursorBench. These comments point to two qualities that matter more than raw fluency: questioning a weak plan and completing work with fewer unnecessary steps.
Scott Wu, co-founder and CEO of Cognition, said Opus 4.8 “uses tools cleanly” in autonomous engineering workloads. Hanlin Tang, Databricks’ CTO of Neural Networks, called the improvement “a step change in agentic reasoning” for multistep data and knowledge work. Niko Grupen, Head of Applied Research at Harvey, reported the “first model to break 10% overall” on its strict all-pass benchmark. The last figure is especially sobering: a record result can still be low in absolute terms when every sub-condition must pass.
The practical interpretation is not that every Claude agent should use Opus. It is that model selection should be tied to failure cost and measured task performance. Use a faster, cheaper model for routing, extraction, and low-risk repetitive work. Escalate to Opus or Fable when the task needs complex planning, long-horizon consistency, or judgement that justifies the premium. Keep a fallback model only when the application can tolerate behavioural differences and evaluation covers both paths.
Benchmarks also need workload context. A browser score, legal all-pass score, coding benchmark, or vendor customer evaluation does not predict performance on a private workflow with different tools and data. During our 2026 implementation review, the most decision-useful technical facts were not headline scores. They were controllable boundaries: pinned model IDs, explicit effort, tool visibility, turn caps, search limits, cached context, and trace-level evaluation. Those levers are also easier for engineering and risk teams to inspect than a broad claim that a newer model is simply smarter.
Our Content Testing Methodology
We verified the build paths against Anthropic’s live Agent SDK overview, Python SDK reference, Claude tool-use documentation, model catalogue, pricing page, web search documentation, rate-limit guidance, and the May 2026 Opus 4.8 announcement. We cross-checked the SDK’s query() and ClaudeSDKClient behaviours, allowed_tools semantics, disallowed tool patterns, sessions, MCP configuration, hooks, checkpointing, cost estimates, and model IDs. The Python examples were syntax-reviewed as complete templates, but they were not executed against a paid Anthropic account because no user API key or external credentials were available in the editorial environment.
For pricing, we recorded public rates visible on 13 July 2026, including Sonnet 5’s introductory period, base tokens, cache writes, cache hits, batch rates, web search, web fetch, code execution, managed-agent runtime, context windows, and output caps. We treated vendor testimonials as qualitative evidence and used the 2025 agent-evaluation survey and PaperArena research to frame benchmark limitations. Claims that could not be confirmed from primary or research sources were excluded or labelled as implementation judgement.
This article was researched and drafted with AI assistance and reviewed by the Sami Ullah Khan editorial desk at Perplexity AI Magazine. All data, citations, pricing figures, and named quotes have been independently verified against primary sources before publication.
Conclusion
The simplest production-minded route is to start with the Claude Agent SDK and a narrow, read-only task. It removes the need to build the basic agent loop, supplies practical tools and sessions, and still exposes permissions, hooks, MCP integrations, budgets, checkpoints, and telemetry. That combination is appropriate for research, repository analysis, and internal workflow assistants where speed to a controlled prototype matters.
The raw Claude API becomes the better foundation when every tool request must pass through an existing control plane or when framework independence is a strategic requirement. It is more work because the application owns tool execution, errors, parallelism, state, approvals, and stopping. That work is justified only when it creates meaningful control.
The open questions are operational rather than cosmetic. Benchmark gains do not remove the need for private evaluations. Million-token context does not make irrelevant context free. Budget parameters do not guarantee a final invoice. MCP expands integration reach while expanding the dependency surface. The durable design principle is therefore restraint: fewer tools, clearer goals, tighter permissions, measurable success, and explicit human authority over consequential actions.
Frequently Asked Questions
What Is the Easiest Way to Build a Claude Agent?
Use the Claude Agent SDK. It provides the agent loop, built-in tools, context management, sessions, permissions, and Python or TypeScript interfaces. Start with a one-off query(), a narrow prompt, and only the read-only tools the task needs.
Do I Need the Agent SDK to Use Claude Tools?
No. The raw Claude Messages API supports tool use directly. You define JSON schemas, inspect tool_use blocks, execute functions in your application, and return tool_result blocks. This offers more control but requires your own loop, validation, retries, permissions, and state.
Can a Claude Agent Search the Web?
Yes. The Agent SDK exposes WebSearch and WebFetch tools, and the Claude API offers server-side web search and web fetch. Web search currently adds $10 per 1,000 searches plus token costs; fetched content also consumes context tokens.
Which Claude Model Should an Agent Use?
Sonnet 5 is a practical default for speed and intelligence. Opus 4.8 suits complex agentic coding and higher-stakes planning. Haiku 4.5 suits low-latency routing and extraction. Select with task-specific evaluations, not a universal ranking.
How Do I Stop an Agent From Running Forever?
Set maximum turns, a wall-clock deadline, tool-use limits, repeated-call detection, retry caps, and a spend threshold. Define explicit completion criteria and return a controlled failure when the agent stops making measurable progress.
Is allowed_tools a Strict Allow-List?
Not by itself. In the Python SDK it auto-approves matching tools; unlisted tools can still pass through permission handling. Restrict the presented tools, use disallowed_tools, disable ambient settings where appropriate, and gate sensitive calls with hooks or an executor policy.
How Should I Evaluate a Claude Agent?
Use representative tasks and inspect the full trace. Measure task success, grounded claims, tool selection, argument validity, forbidden actions, retries, latency, token use, search calls, cost per passing task, and human intervention. Include adversarial and failure cases.
References
Anthropic. (2026a). Agent SDK overview.
Anthropic. (2026b). Agent SDK reference – Python.
Anthropic. (2026c). Tool use with Claude.
Anthropic. (2026d). Claude Platform pricing.
Anthropic. (2026e). Models overview.
Anthropic. (2026f). Introducing Claude Opus 4.8.
Anthropic. (2026g). Measuring AI agent autonomy in practice.
Yehudai, A., Eden, L., Li, A., Uziel, G., Zhao, Y., Bar-Haim, R., Cohan, A., & Shmueli-Scheuer, M.. (2025). Survey on evaluation of LLM-based agents [Preprint]. arXiv.
Wang, D., Cheng, M., Liu, Q., Yu, S., Liu, Z., & Guo, Z.. (2025). PaperArena: An evaluation benchmark for tool-augmented agentic reasoning on scientific literature [Preprint]. arXiv.