techlist.io

Anthropic

30 posts

www.anthropic.com/engineering

Filter by tag

Anthropic2025-11-244 min readCurated summary

Introducing advanced tool use for Claude

# Anthropic's Advanced Tool Use: Tool Search, Programmatic Calling, and Usage Examples Anthropic argues that agents need to work with hundreds or thousands of tools without overloading their context window, call tools from code rather than one at a time, and learn correct usage from examples rather than schemas alone. To address this, the post introduces three beta features: Tool Search Tool, Programmatic Tool Calling, and Tool Use Examples. Internal testing shows these features cut token usage substantially while improving accuracy on tool-heavy tasks. ## Tool Search Tool Loading every tool definition upfront wastes context. A five-server MCP setup can consume about 55K tokens before a conversation starts, and Anthropic has seen definitions reach 134K tokens. Wrong tool selection is also common when names are similar, such as `notification-send-user` versus `notification-send-channel`. - Tools marked with `defer_loading: true` are excluded from the initial prompt. Claude sees only the search tool plus tools marked `defer_loading: false`. - When Claude needs a capability, it searches (regex, BM25, or a custom method such as embeddings), and only the matching tools expand into full definitions. - Entire MCP servers can be deferred with `mcp_toolset` configs, while frequently used tools stay loaded. - Because deferred tools are left out of the initial prompt, the system prompt and core tool definitions remain cacheable. - In the reported example, context use dropped from about 77K to 8.7K tokens, an 85% reduction. - Accuracy on MCP evaluations improved: Opus 4 went from 49% to 74%, and Opus 4.5 from 79.5% to 88.1%. - It suits setups with more than 10 tools or definitions over 10K tokens. It is less useful with fewer than 10 compact tools or tools used in every session, since the search step adds latency. ## Programmatic Tool Calling Conventional tool calling floods context with intermediate results and requires a full inference pass per call. Programmatic Tool Calling lets Claude write Python that orchestrates tools inside a sandboxed code execution environment, so Claude sees only the final output. - Tools opt in through `allowed_callers`, and the API exposes them as Python functions. - In the budget compliance example, a script fetches team members, budgets, and expenses for 20 people (about 200KB of raw data), and Claude receives only the one to three people who exceeded their limits (about 1KB). - Average token usage fell from 43,588 to 27,297 (37%) on complex research tasks, and accuracy improved on internal benchmarks. - Latency drops because 20+ tool calls can run in one code block instead of 20+ inference passes. - It is most useful for large datasets, workflows with three or more dependent calls, and parallel operations. Single calls and tasks where Claude must reason over every intermediate result gain little. - Claude for Excel uses this approach to handle spreadsheets with thousands of rows. ## Tool Use Examples JSON Schema defines structure but cannot show when optional parameters apply, which combinations make sense, or what format conventions an API expects. Ambiguous fields such as date formats, ID patterns, and nested objects often lead to malformed calls. - An `input_examples` array in the tool definition shows concrete calls, including minimal, partial, and full specifications. - Examples teach conventions such as `YYYY-MM-DD` dates, `USR-XXXXX` IDs, and which optional fields go with which priority levels. - In Anthropic's internal testing, accuracy on complex parameter handling rose from 72% to 90%. - Keep it to 1–5 realistic examples per tool, focused on ambiguity the schema doesn't resolve. Examples add tokens, so they are less useful for simple tools or standard formats like emails and URLs. ## Practical Recommendations Start with the bottleneck that limits your agent most: context bloat points to Tool Search, large intermediate results point to Programmatic Tool Calling, and parameter errors point to Tool Use Examples. The features complement each other, and clear tool names and descriptions improve search accuracy. The features are available in beta under the `advanced-tool-use-2025-11-20` header.

Anthropic2025-11-044 min readCurated summary

Code execution with MCP for efficient agents

Connecting AI agents to many tools through the Model Context Protocol (MCP) becomes inefficient at scale, because loading every tool definition upfront and passing intermediate results through the model's context window consumes large numbers of tokens. The post argues that presenting MCP servers as code APIs, which agents interact with by writing and running code, lets them load only the tools they need and process data outside the model. In the author's example, this cut token usage from about 150,000 to 2,000, a 98.7% reduction. ## Why Tool Use Becomes Expensive - **Tool definitions crowd the context window.** Most MCP clients load every tool's schema, description, and parameters into context up front. Agents connected to thousands of tools may need to process hundreds of thousands of tokens before they even read a request. - **Intermediate results pass through the model twice.** When the model moves data from one tool to another, such as copying a Google Drive transcript into a Salesforce record, the full content flows into context and then must be written out again. A two-hour meeting transcript can add around 50,000 tokens, and very large documents can exceed context limits entirely. Copying long data also increases the chance of errors. ## Presenting MCP Servers as Code - **Filesystem layout.** Each MCP server becomes a directory (e.g., `servers/google-drive/`, `servers/salesforce/`), and each tool becomes a typed TypeScript file such as `getDocument.ts` or `updateRecord.ts`, which wraps a call to `callMCPTool`. - **Workflows as scripts.** The Drive-to-Salesforce task becomes a short script that reads the document content into a variable and passes it directly to `updateRecord`, so the transcript never enters the model's context. - **Cloudflare's "Code Mode"** reached similar conclusions, based on the idea that LLMs write code well. ## Benefits of Code Execution - **Progressive disclosure.** The agent explores the directory tree to find servers and reads only the tool files it needs. Alternatively, a `search_tools` tool can return results at adjustable detail levels, such as name only, name plus description, or full schema. - **Filtering before the model sees data.** When fetching a 10,000-row spreadsheet, the script can filter for pending orders and log only a count and a sample of five rows, so the model sees a tiny fraction of the data. - **Native control flow.** Loops, conditionals, and retries run in code rather than through repeated model turns. For example, polling a Slack channel for a deployment message can happen in a single script with a sleep between checks, avoiding a model round-trip for each check. - **Privacy-preserving operations.** Intermediate results stay in the execution environment by default. An MCP client can also tokenize PII such as emails, phone numbers, and names before they reach the model, then restore the real values when data moves to the next tool. This keeps sensitive data out of the model while still letting it flow between systems, and it supports deterministic rules about where data may go. - **State persistence and reusable skills.** Agents can write intermediate files to a workspace to resume work later, and they can save working code as reusable functions. Adding a `SKILL.md` file turns these saved functions into structured skills that build up a toolbox over time. ## Trade-offs to Weigh Code execution requires a secure sandbox with resource limits and monitoring, which adds operational overhead and security concerns that direct tool calls avoid. Teams should weigh the savings in token cost, latency, and tool composition against these infrastructure costs. The author encourages anyone implementing this approach to share their findings with the MCP community.

Anthropic2025-10-203 min readCurated summary

Making Claude Code safer with sandboxing

Anthropic's Claude Code can edit files, run commands, and navigate a codebase, which creates real risk when it is exposed to prompt injection. To address this, Anthropic introduced two features built on sandboxing: a sandboxed bash tool that lets Claude run commands without a permission prompt for each action, and Claude Code on the web, which runs each session in an isolated cloud sandbox. Anthropic reports that sandboxing reduced internal permission prompts by 84%, showing that defined boundaries can improve both security and autonomy. ## The Problem with Permission Prompts - By default, Claude Code is read-only and asks for approval before modifying files or running most commands. Only safe commands such as `echo` and `cat` are auto-allowed. - Constant approval requests slow development and cause "approval fatigue," where users stop scrutinizing what they approve, which makes development less safe. ## Sandboxing: Fixed Boundaries Instead of Per-Action Approval Sandboxing sets pre-defined limits within which Claude can act freely. It is built on operating system features and enforces two kinds of isolation: - **Filesystem isolation:** Claude can access only specific directories, which prevents a prompt-injected agent from modifying sensitive system files. - **Network isolation:** Claude can connect only to approved servers, which prevents data leaks and malware downloads. Anthropic stresses that both are required. Network isolation alone lets a compromised agent exfiltrate files such as SSH keys, and filesystem isolation alone lets it escape the sandbox and reach the network. ## Sandboxed Bash Tool - Anthropic released the sandbox runtime in beta as an open-source research preview. It restricts which directories and network hosts a process can use, without the overhead of containers, and can wrap arbitrary processes, agents, and MCP servers. - In Claude Code, the runtime sandboxes the bash tool. Commands run without prompts inside the limits, and any attempt to go outside them triggers a notification so the user can allow or deny it. - It is built on Linux bubblewrap and macOS seatbelt, so restrictions apply to subprocesses and scripts the command spawns, not just Claude's direct actions. - Filesystem access allows reads and writes in the current working directory and blocks modifications elsewhere. - Network access goes only through a Unix domain socket to a proxy running outside the sandbox. The proxy enforces domain allowlists, asks the user to confirm new domains, and can be customized with arbitrary outbound rules. - Both the file paths and domains are configurable. Users enable the feature with `/sandbox`. ## Claude Code on the Web - Each session runs in an isolated cloud sandbox with full access to its own server. - Sensitive credentials, such as git credentials and signing keys, never enter the sandbox, so compromised code cannot easily cause further harm. - A custom proxy handles all git operations. Inside the sandbox, git authenticates with a scoped credential. The proxy checks that the credential is valid and that the operation matches the allowed scope (for example, pushing only to the configured branch), then attaches the real token before forwarding the request to GitHub. ## Recommendation Developers who use Claude for engineering work can run `/sandbox` in Claude Code to reduce prompts while improving safety, or try Claude Code on the web at claude.com/code. Teams building their own agents can also adopt the open-sourced sandboxing code.

Anthropic2025-10-164 min readCurated summary

Equipping agents with Agent Skills

# Agent Skills: Packaging Procedural Knowledge for Agents Anthropic introduces Agent Skills, organized folders of instructions, scripts, and resources that agents can discover and load on demand to perform specialized tasks. The core argument is that as general-purpose agents gain access to full computing environments, they need a composable, scalable, and portable way to acquire domain expertise, rather than relying on fragmented, custom-built agents for each use case. Skills are published as an open standard and are supported across Claude.ai, Claude Code, the Claude Agent SDK, and the Claude Developer Platform. ## Anatomy of a Skill - At its simplest, a skill is a directory containing a `SKILL.md` file. - The file begins with YAML frontmatter that includes two required fields, `name` and `description`. - At startup, the agent preloads the name and description of every installed skill into its system prompt, so it knows when each skill applies without loading the full content. - If a skill seems relevant, Claude reads the full `SKILL.md` into context. - Complex skills can bundle additional files (for example, `reference.md` or `forms.md`) that `SKILL.md` references by name. Claude loads these only when needed. - The PDF skill used as the example keeps form-filling instructions in a separate file, so the core skill stays lean. ## Progressive Disclosure - Skills load information in levels: metadata first, then the core instructions, then linked files as needed. This works like a manual with a table of contents, chapters, and an appendix. - Agents with filesystem and code execution access don't need to load an entire skill into context, so the amount of material a skill can contain is effectively unbounded. ## Skills and the Context Window - The context starts with the system prompt, the metadata for installed skills, and the user's message. - When a request matches a skill, Claude uses a Bash tool to read that skill's `SKILL.md`. - Claude then decides whether to read any bundled files, such as `forms.md`, before completing the task. ## Executable Code in Skills - Skills can include scripts that Claude runs as tools. - Code suits operations that LLMs handle poorly or expensively, such as sorting or deterministic processing. Running a script is also consistent and repeatable. - The PDF skill includes a Python script that extracts form fields from a PDF. Claude can run it without loading the script or the PDF into context. ## Developing and Evaluating Skills - **Start with evaluation:** Run agents on representative tasks, find where they struggle, and build skills to close those gaps incrementally. - **Structure for scale:** Split large `SKILL.md` files into referenced files, keep rarely combined paths separate to save tokens, and make clear whether scripts should be executed or read. - **Think from Claude's perspective:** Observe how Claude uses skills in practice. The `name` and `description` fields matter most, since Claude uses them to decide whether to trigger a skill. - **Iterate with Claude:** Have Claude capture successful approaches and common mistakes into the skill, and ask it to self-reflect when it goes off track. ## Security Considerations - Malicious skills can introduce vulnerabilities or direct Claude to exfiltrate data or take unintended actions. - Install skills only from trusted sources. For less-trusted skills, audit bundled files, especially dependencies, scripts, and instructions that connect to external networks. ## Looking Ahead - Anthropic plans to add features covering the full skill lifecycle: creating, editing, discovering, sharing, and using skills. - Skills may complement Model Context Protocol (MCP) servers by teaching agents multi-step workflows that involve external tools. - The longer-term goal is for agents to create, edit, and evaluate their own skills, codifying their behavior into reusable capabilities. Skills are intentionally simple in concept and format, which makes it easier for organizations, developers, and end users to build customized agents. Developers can start with the Skills docs and cookbook.

Anthropic2025-09-295 min readCurated summary

Effective context engineering for AI agents

Anthropic argues that context engineering is the natural successor to prompt engineering. Instead of only writing better instructions, engineers must curate the full set of tokens an LLM sees during inference, because models have a finite "attention budget" that degrades as context grows. As agents run longer, they need strategies such as just-in-time retrieval, compaction, structured note-taking, and sub-agent architectures to keep that context small and high-signal. ## From Prompt Engineering to Context Engineering - Prompt engineering focuses on writing and organizing instructions, particularly system prompts. - Context engineering covers everything that lands in the context window during inference: system prompts, tools, external data, message history, and more. - Agents that run in loops generate new information every turn, so context must be continually curated and refined. ## Why Context Is a Finite Resource - **Context rot:** As the token count grows, a model's ability to accurately recall information from its context declines. This happens across all models, though degradation rates vary. - **Architectural limits:** Transformers let every token attend to every other token, creating n² pairwise relationships, which stretches attention thin as context grows. - **Training skew:** Models see shorter sequences more often in training, so they have less experience with long-range dependencies. - **Gradual degradation:** Techniques like position encoding interpolation extend context length with some loss in positional precision. The result is a performance gradient, not a hard cliff. ## Anatomy of Effective Context - **System prompts:** Aim for the "right altitude," between brittle hardcoded logic and vague high-level guidance. Organize sections with XML tags or Markdown headers, and start with a minimal prompt, then add instructions based on observed failures. - **Tools:** Keep tool sets minimal and non-overlapping, since a human who can't pick the right tool can't expect an agent to either. Tools should return token-efficient output and have clear, unambiguous parameters. - **Examples:** Curate a small set of diverse, canonical few-shot examples instead of listing every edge case in the prompt. ## Retrieval: From Pre-Loading to Just-in-Time Context - Anthropic defines an agent simply as "LLMs autonomously using tools in a loop." - Embedding-based retrieval before inference is common, but agents increasingly use "just-in-time" retrieval. They keep lightweight identifiers such as file paths, stored queries, or links, and load data on demand with tools. - Claude Code analyzes large databases by writing targeted queries and using commands like `head` and `tail`, without loading full datasets into context. - Metadata such as folder names, file names, and timestamps helps agents infer purpose and relevance. A `test_utils.py` in `tests/` means something different from one in `src/core_logic/`. - **Progressive disclosure:** Agents build understanding incrementally, with each step informing the next. - **Trade-offs:** Runtime exploration is slower and needs good tool design and heuristics, or agents can waste context on dead ends. - **Hybrid approach:** Claude Code drops `CLAUDE.md` files into context up front and uses `glob` and `grep` for on-demand retrieval. Less dynamic domains like legal or finance may suit this hybrid model well. ## Context Engineering for Long-Horizon Tasks Tasks like large migrations or extended research exceed the context window, so Anthropic recommends three techniques. Waiting for bigger windows isn't enough, since context pollution and relevance problems persist at every size. ### Compaction - Summarize a conversation nearing the context limit and start a new window with the summary. - Claude Code preserves architectural decisions, unresolved bugs, and implementation details, discards redundant tool outputs, and keeps the five most recently accessed files. - Tune the compaction prompt first for recall, then for precision. - **Tool result clearing** is a light-touch form of compaction: once a tool result is deep in history, the raw output is often no longer needed. ### Structured Note-Taking - The agent writes persistent notes outside the context window and reloads them later, such as a to-do list or a `NOTES.md` file. - Claude playing Pokémon tracked training progress over thousands of steps, mapped explored regions, and kept combat notes, then resumed multi-hour sequences after context resets. - The memory tool, released in public beta with Sonnet 4.5, supports file-based storage for knowledge that persists across sessions. ### Sub-agent Architectures - A lead agent coordinates a high-level plan while specialized sub-agents handle focused tasks in clean context windows. - Each sub-agent may use tens of thousands of tokens but returns a condensed summary, often 1,000–2,000 tokens. - This pattern substantially outperformed single-agent systems on complex research tasks. ### Choosing an Approach - **Compaction:** Extensive back-and-forth conversations. - **Note-taking:** Iterative development with clear milestones. - **Multi-agent architectures:** Complex research where parallel exploration pays off. ## Conclusion The guiding principle is to find the smallest set of high-signal tokens that makes the desired outcome most likely. Anthropic expects smarter models to need less prescriptive engineering, but treating context as a finite resource will stay central to building reliable agents. Its advice is to "do the simplest thing that works."

Anthropic2025-09-175 min readCurated summary

A postmortem of three recent issues

Between August and early September, three overlapping infrastructure bugs intermittently degraded Claude's response quality across Anthropic's first-party API, Amazon Bedrock, and Google Cloud Vertex AI. Anthropic states that model quality is never reduced because of demand, time of day, or server load, and that the reported problems came only from these bugs. The post is a postmortem covering what went wrong, why detection took so long, and what Anthropic is changing. ### How Claude Is Served - Claude runs across AWS Trainium, NVIDIA GPUs, and Google TPUs to serve millions of users worldwide. - Each platform needs its own optimizations, but Anthropic holds all of them to strict equivalence standards so users get the same quality regardless of hardware. - Any infrastructure change therefore needs validation across all platforms and configurations. ### Timeline of the Incidents - A first bug was introduced on August 5, affecting about 0.8% of Sonnet 4 requests. - Two more bugs came from deployments on August 25 and 26. - A load balancing change on August 29 sharply increased the affected traffic, while other users saw normal performance, which made the reports look contradictory. ### The Three Bugs #### Context Window Routing Error - Some short-context Sonnet 4 requests were routed to servers configured for the upcoming 1M-token context window. - At the worst hour, on August 31, 16% of Sonnet 4 requests were affected. - About 30% of Claude Code users who made requests during this period had at least one message misrouted. - Routing is "sticky," so follow-up messages often landed on the same bad server, making some users' experience worse. - The fix shipped September 4 and finished rolling out by September 16 on the first-party platform and Vertex AI, and by September 18 on Bedrock. #### Output Corruption - A misconfiguration on the TPU servers, combined with a runtime optimization, sometimes gave high probability to tokens that should rarely appear. Examples include Thai or Chinese characters in English responses and obvious syntax errors in code. - It affected Opus 4.1 and Opus 4 from August 25 to 28, and Sonnet 4 from August 25 to September 2. Third-party platforms were not affected. - The change was rolled back on September 2, and Anthropic added detection tests for unexpected character output to its deployment process. #### Approximate Top-k XLA:TPU Miscompilation - A change to how Claude selects tokens triggered a latent bug in the XLA:TPU compiler. It was confirmed for Haiku 3.5 and likely affected some Sonnet 4 and Opus 3 requests. - Haiku 3.5 was rolled back on September 4 and Opus 3 on September 12. Sonnet 4 was rolled back as a precaution, though the bug could not be reproduced on it. - Anthropic switched to exact top-k with higher precision. ### Deep Dive: The XLA Compiler Bug - Claude samples the next token using top-p sampling, which requires sorting probabilities across tens of TPU chips. - A December 2024 workaround addressed a case where the most probable token was dropped at temperature zero. - The root cause was a precision mismatch. Probabilities were computed in bf16, but the compiler's `xla_allow_excess_precision` optimization (default `true`) moved some operations to fp32. This made operations disagree about the top token. - An August 26 sampling rewrite removed the December workaround, which had been masking a deeper bug in the approximate top-k operation. That bug returned wrong results only for certain batch sizes and model configurations. - The bug was inconsistent: the same prompt could succeed or fail depending on surrounding operations and whether debugging tools were enabled. - Anthropic moved to exact top-k, which no longer carried a prohibitive cost, and standardized more operations on fp32, accepting a minor efficiency cost. - Tokens near the top-p threshold may now be included slightly differently, so a few users may need to re-tune their top-p setting. ### Why Detection Took So Long - Benchmarks, safety evaluations, spot checks, and canary deployments did not capture the degradation, partly because Claude often recovers from isolated mistakes. - Privacy controls limit engineers' access to conversations that users did not submit as feedback, which made the problematic interactions hard to examine. - Each bug produced different symptoms on different platforms at different rates, so the reports looked random. - Anthropic relied too heavily on noisy evaluations and did not quickly connect the August 29 spike in reports to the load balancing change. ### What Anthropic Is Changing - Developing evaluations that more reliably separate working implementations from broken ones. - Running quality evaluations continuously on production systems, not only in regular testing. - Building debugging tools that work with community feedback without compromising user privacy. - Encouraging direct feedback through `/bug` in Claude Code or the thumbs-down button in the Claude apps. Developers with new evaluation methods can reach out to feedback@anthropic.com. If you use top-p sampling, it's worth checking your settings after these fixes. And if Claude produces unexpected output, the `/bug` command or thumbs-down button helps Anthropic catch problems like these sooner.

Anthropic2025-09-114 min readCurated summary

Writing effective tools for AI agents

# Designing Tools for AI Agents Tools for agents are a different kind of software: they form a contract between deterministic systems and non-deterministic agents, so they must be designed for how agents perceive and act, not simply wrapped around existing functions or APIs. The post argues that effective tools come from an evaluation-driven loop: build a quick prototype, measure it against realistic multi-step tasks, analyze agent transcripts, and iterate, often with agents like Claude Code doing the refactoring themselves. ## Building and Evaluating Tools - Prototype quickly by wrapping tools in a local MCP server or Desktop extension, connecting them to Claude Code (`claude mcp add`) or Claude Desktop, or passing them directly into API calls. - Provide LLM-friendly documentation (such as `llms.txt` files) to Claude when it helps write the tools. - Generate evaluation tasks grounded in realistic data and services, avoiding simplistic sandboxes. Strong tasks often require dozens of tool calls, while weak ones are single lookups. - Pair each task with a verifiable outcome, using exact matching or an LLM judge, and avoid verifiers that reject correct answers over formatting differences. - Run evaluations programmatically with simple agentic loops, one per task, and ask agents to output reasoning and feedback before their responses to encourage chain-of-thought behavior. - Track accuracy alongside runtime, total tool calls, token consumption, and tool errors. Frequent redundant calls can suggest consolidation opportunities. - Analyze transcripts for confusion, not just final answers, since agents often omit what matters most. Use held-out test sets to avoid overfitting. ## Choosing the Right Tools - Avoid tools that merely mirror API endpoints. Agents have limited context, so a `list_contacts` tool that dumps everything wastes it, while `search_contacts` returns only what's relevant. - Consolidate multi-step workflows into single tools, such as `schedule_event` instead of separate list and create calls, `search_logs` instead of `read_logs`, or `get_customer_context` instead of three separate lookups. - Give each tool a clear, distinct purpose, since overlapping tools distract agents from efficient strategies. ## Namespacing and Response Design - Group related tools under prefixes by service and resource (e.g., `asana_projects_search`) so agents can select the right tool. Prefix versus suffix choice affects results and should be tested per model. - Return high-signal fields like `name` or `file_type` rather than low-level identifiers like `uuid` or `mime_type`. Resolving UUIDs to human-readable identifiers reduced hallucinations in retrieval tasks. - Add a `response_format` enum (e.g., `concise` or `detailed`) so agents can choose between readable names and technical IDs needed for downstream calls. The post's example shows a 206-token detailed response versus a 72-token concise one. - Response structure (XML, JSON, Markdown) also affects performance, and the best choice varies by task and model. ## Token Efficiency and Error Handling - Use pagination, range selection, filtering, and truncation with sensible defaults. Claude Code caps tool responses at 25,000 tokens by default. - When truncating, guide agents toward efficient strategies, such as many small targeted searches instead of one broad search. - Write error messages that state specific, actionable fixes rather than opaque codes or tracebacks. ## Prompt-Engineering Tool Descriptions - Write descriptions as if onboarding a new hire, making implicit context explicit: query formats, niche terminology, and resource relationships. - Use unambiguous parameter names (`user_id` rather than `user`) and enforce inputs and outputs with strict data models. - Small description refinements can yield large gains. The post reports that precise description changes helped Claude Sonnet 3.5 reach state-of-the-art on SWE-bench Verified. - Tool annotations can disclose whether a tool needs open-world access or makes destructive changes. ## Conclusion Effective agent tools are clearly defined, use context judiciously, combine well across workflows, and let agents solve real tasks intuitively. Because the mechanisms agents use will keep evolving, a systematic, evaluation-driven process is the most reliable way to keep tools improving alongside the models that use them.

Anthropic2025-06-263 min readCurated summary

Desktop Extensions: One-click MCP installs

# Desktop Extensions: One-Click Installation for Local MCP Servers Anthropic is introducing Desktop Extensions, a packaging format that bundles a local MCP server and all its dependencies into a single `.mcpb` file that installs with one click. The change addresses the friction that kept powerful local MCP servers out of reach for non-technical users, who previously needed developer tools, hand-edited configuration files, and manual dependency management. The format is open-sourced and versioned as 0.1, with a curated extension directory and enterprise controls built into Claude Desktop. ## Problems with Manual MCP Installation - Users needed Node.js, Python, or other runtimes installed beforehand - Each server required manually editing `claude_desktop_config.json` - Dependency conflicts and version mismatches had to be resolved by hand - Finding useful servers meant searching GitHub - Updating a server meant reinstalling it manually ## How Desktop Extensions Work A Desktop Extension is a ZIP archive with the `.mcpb` extension. The only required file is `manifest.json`, which describes the extension's metadata, features, user configuration, and runtime requirements. The archive typically also contains the server code and bundled dependencies, such as a `server/` directory with an entry point and a `node_modules/` or `lib/` directory for Python packages. - **Built-in runtime:** Claude Desktop ships with Node.js, so no external runtime is needed - **Automatic updates:** Extensions update when new versions are available - **Secure secrets:** Sensitive values such as API keys are stored in the OS keychain - **Configuration gating:** Claude won't enable an extension until required user settings are supplied - **Variable substitution:** Placeholders like `${user_config.api_key}`, `${__dirname}`, `${HOME}`, and `${TEMP}` are resolved at launch - **Platform overrides:** The `platforms` block lets developers set different commands or environment variables for Windows and macOS ## Manifest and Packaging - The manifest declares user configuration fields with types, defaults, validation rules, and a `sensitive` flag - Configuration can be passed to the server as environment variables or command-line arguments - Developers can declare tools and prompts up front so users see capabilities before installing - The `npx @anthropic-ai/mcpb init` command generates a manifest interactively, and `npx @anthropic-ai/mcpb pack` validates it and produces the archive - Users can test a package by dragging the `.mcpb` file into Claude Desktop's Settings window ## Ecosystem and Enterprise Controls Anthropic is open-sourcing the MCPB specification, packaging and validation tools, reference implementations, and TypeScript types and schemas. The goal is for the format to work across other AI desktop applications, so developers can package a server once. For enterprises, Desktop Extensions support Group Policy on Windows and MDM on macOS, pre-installation of approved extensions, blocklists by extension or publisher, disabling the extension directory, and private extension directories. Users can audit installed extensions. ## Practical Takeaway MCP server developers can package an existing server by running `npm install -g @anthropic-ai/mcpb`, then `mcpb init` and `mcpb pack`. Anthropic also notes that Claude Code can build extensions with little intervention when given the MCPB specification links and a short description of the desired behavior. Internally, the team has used the format to package experimental servers, including one that lets Claude play a GameBoy game through the PyBoy emulator.

Anthropic2025-06-184 min readCurated summary

Confidential Inference via trusted VMs

Anthropic is researching "Confidential Inference," a set of tools that lets it process user data in encrypted form and prove that the data is readable only inside servers it can verify as trustworthy. The approach serves two goals: protecting frontier model weights from increasingly capable threat actors, and giving users a cryptographic guarantee that their sensitive prompts stay private. The post, written with Pattern Labs, presents this as early research meant to start a discussion, not a finished product. ## Core Principle: Encrypted Except During Processing Sensitive data should stay encrypted everywhere except at the moment it is processed. Anthropic enforces this with confidential computing, building a chain of trust that attests to the security of its software and then uses that attestation to decide which software may access the encryption keys. - Two components handle cleartext user data: the API Server, which tokenizes prompts and runs most request logic, and the Inference Server, which runs the model on hardware accelerators. - For model weights, only the Inference Server handles sensitive data. - The post focuses on the Inference Server. The API Server's security is acknowledged as equally important but is outside its scope. ## Trusted Model Loader Design Because not all accelerators fully support confidential computing, Anthropic is exploring a design built around a small, secure "model loader and invoker": - The loader accepts encrypted data, decrypts it, and sends it to the accelerator. - It invokes accelerator operations and returns encrypted results to the caller. - Only the trusted loader can see decrypted data. The rest of the Inference Server is untrusted and can change often without affecting overall security, since it can only send requests to the loader. - In Anthropic's implementation, the loader runs on a separate virtual machine isolated by the hypervisor and presents itself as a "virtual accelerator" that is agnostic to model architecture. - The virtual accelerator accepts only programs signed by Anthropic's secure CI server, which ensures multiple engineers have reviewed any code that runs. If the loader runs correctly, confidentiality holds regardless of what the rest of the system does, so verifying that the loader is running correctly is critical. ## Establishing a Trusted Environment The loader runs in a confidential computing environment with three properties: - **Encrypted, hardware-isolated memory** separated from other workloads. This guards against some physical attacks and a malicious hypervisor, but sharing encrypted host memory with an accelerator is not yet well established. Until that gap closes, Anthropic relies on its compute providers for physical datacenter and hypervisor security. - **Disabled debugging features.** - **Cryptographic proof** that the correct code is running. The last two are achievable with widely supported practices, using a Trusted Platform Module (TPM) as the root of trust. The TPM measures each boot stage and produces a hash that attests the loader is isolated as expected, runs signed and reviewed code, and has debugging disabled. A keyserver checks this proof and releases decryption keys only to environments that prove they are secure. The keyserver ultimately decides what counts as trusted. Anthropic is also exploring setups where independent parties validate the trusted code and run their own keyservers, which could offer stronger confidentiality guarantees for each piece of data. ## Future Safeguards As models become more capable, Anthropic may add protections at the loader layer, such as: - Additional egress bandwidth limits on servers that hold cleartext model weights. - Requiring a signature from a safety classifier before inference can run. ## End-to-End Request Flow - The request is encrypted before it reaches Anthropic's servers. - The API Server decrypts, processes, and re-encrypts it before passing it on. - The Inference Server handles the request in encrypted form and decrypts it only when sending it to the trusted loader. - Completions are encrypted before leaving the loader and return to the caller through the API Server. - Model weights can be stored encrypted, decrypted only at the loader, and never released from it. ## Recommendation for Hardware Designers Chip makers that have not yet done so should build confidential computing into their hardware. A hardware root of trust attached to the accelerator would significantly shrink the trust boundary of systems like this one.

Anthropic2025-06-135 min readCurated summary

How we built our multi-agent research system

Anthropic's engineering team describes how they built the multi-agent Research feature for Claude, where a lead agent plans a query and spawns parallel subagents that search simultaneously. Their internal evaluation found the multi-agent setup (Claude Opus 4 lead, Sonnet 4 subagents) outperformed a single Opus 4 agent by 90.2%, mainly because it spends more tokens on hard, parallelizable problems. The post argues that this gain comes with roughly 15× the token cost of chat, so it only suits high-value, breadth-first tasks. Moving these systems to production, they add, is much harder than building a prototype. ## Why Multi-Agent Systems Help Research - Research is open-ended and path-dependent, so the steps can't be hardcoded in advance, and a linear pipeline can't handle it. - Subagents compress information by working in parallel, each with its own context window, and returning only the most important findings to the lead agent. - Token usage explained about 80% of performance variance on the BrowseComp evaluation, with tool calls and model choice explaining most of the rest, so distributing work across agents adds reasoning capacity. - Agents use about 4× the tokens of chat, and multi-agent systems about 15×, so they fit only tasks valuable enough to justify the cost. - Coding tasks, which have fewer parallelizable subtasks and need shared context, are a poor fit today. ## Architecture: Orchestrator-Worker Pattern - The lead agent analyzes the query, develops a strategy, and spawns subagents that iteratively search and return condensed results. - Unlike static RAG, which fetches chunks similar to the query once, this design runs multi-step searches that adapt to new findings. ## Prompt Engineering Principles - **Simulate the agents:** Running the exact prompts and tools step by step revealed failure modes such as agents continuing after they already had enough results, using overly verbose queries, or picking the wrong tools. - **Delegate with detail:** Vague instructions caused duplicated work and gaps. Each subagent needs an objective, an output format, tool guidance, and clear task boundaries. - **Scale effort to complexity:** Simple fact-finding uses 1 agent with 3–10 tool calls, comparisons use 2–4 subagents with 10–15 calls each, and complex research uses more than 10 subagents. Without these rules, early versions overinvested in simple queries. - **Design tools deliberately:** Each tool needs a distinct purpose and clear description, and agents should examine available tools first and match tool choice to user intent. - **Let Claude improve its own tools:** A tool-testing agent that rewrote flawed MCP tool descriptions reduced task completion time by 40%. - **Start wide, then narrow:** Agents should begin with short, broad queries and refine from there, instead of starting with long, specific ones. - **Use extended thinking as a scratchpad:** The lead agent plans and sets subagent roles, and subagents evaluate tool results with interleaved thinking. - **Parallelize:** The lead agent spins up 3–5 subagents in parallel, and subagents use 3+ tools in parallel, cutting research time by up to 90% on complex queries. ## Evaluating Multi-Agent Systems - Agents can reach the same correct answer by different valid paths, so evaluations should judge outcomes and reasonable process rather than fixed steps. - Start with about 20 representative queries. Early changes have large effects, so small samples reveal them. - An LLM judge using a single prompt that outputs 0.0–1.0 scores and a pass/fail grade agreed best with human judgment. It scores factual accuracy, citation accuracy, completeness, source quality, and tool efficiency. - Human testing caught problems automation missed, such as early agents favoring SEO-optimized content farms over authoritative academic PDFs or personal blogs. Adding source-quality heuristics fixed this. ## Production Reliability Challenges - **Stateful errors compound:** Agents run for long periods, so the system checkpoints and resumes from the failure point rather than restarting, combining model adaptability with retry logic. - **Debugging is hard:** Because agents are non-deterministic, the team added full production tracing and monitors decision patterns, without reading individual conversation contents, to protect privacy. - **Deployment is delicate:** Agents may be mid-process during updates, so rainbow deployments gradually shift traffic between old and new versions while both run. - **Synchronous execution is a bottleneck:** Lead agents wait for each subagent batch to finish and can't steer subagents mid-task. Asynchronous execution would add parallelism but complicates result coordination, state consistency, and error propagation. ## Conclusion The authors conclude that multi-agent research systems can run reliably at scale, but only with careful engineering, extensive testing, detailed prompt and tool design, and close collaboration across research, product, and engineering. Users reported finding business opportunities, navigating healthcare options, fixing technical bugs, and saving days of research work. ## Appendix Tips - **End-state evaluation:** For agents that change persistent state, judge whether the final state is correct, using checkpoints for complex workflows. - **Long-horizon memory:** Agents summarize completed phases, store essential information externally, and hand off to fresh subagents when context limits approach. - **Filesystem artifacts:** Subagents store outputs such as code, reports, or data visualizations in external systems and pass lightweight references to the coordinator, which avoids information loss and reduces token overhead.

Anthropic2025-04-186 min readCurated summary

Claude Code Best Practices

Claude Code is deliberately low-level and unopinionated, which makes it a flexible, scriptable, and safe tool but also gives it a learning curve. This Anthropic post collects patterns that work for internal teams and external engineers across many codebases. It covers how to configure the environment, extend Claude's tools, structure common workflows, and run multiple Claude instances in parallel. The author presents these as starting points to experiment with, not fixed rules. ## Customizing Your Setup - **CLAUDE.md files** are loaded automatically at the start of a conversation. They are a good place to record common bash commands, core files and utilities, code style, testing instructions, repository etiquette, environment quirks, and project-specific warnings. The format is free, but the files should be concise and readable. - **Placement** can vary. A root-level CLAUDE.md should be checked into git for team sharing, while CLAUDE.local.md is git-ignored for personal notes. Parent directories suit monorepos, child directories load on demand, and `~/.claude/CLAUDE.md` applies to every session. `/init` generates a starter file. - **Tuning** matters because these files become part of the prompt. Pressing `#` adds an instruction to CLAUDE.md, and emphasis such as "IMPORTANT" or "YOU MUST" can improve adherence. - **Tool permissions** are conservative by default. You can allow tools through the "Always allow" prompt option, the `/permissions` command, `.claude/settings.json` or `~/.claude.json`, or the `--allowedTools` flag. Examples include `Edit` and `Bash(git commit:*)`. - **GitHub integration** works best with the `gh` CLI installed, though the GitHub API or an MCP server also works. ## Giving Claude More Tools - **Bash tools:** Claude inherits your shell environment. Tell it about custom tools with usage examples, ask it to run `--help`, or document them in CLAUDE.md. - **MCP servers:** Claude Code can act as both MCP server and client. Servers can be configured per project, globally, or in a checked-in `.mcp.json` so a whole team gets them. The `--mcp-debug` flag helps diagnose configuration problems. - **Custom slash commands:** Markdown prompt templates in `.claude/commands` (shared via git) or `~/.claude/commands` (personal) become slash commands. The `$ARGUMENTS` keyword passes input through, so a `fix-github-issue.md` template can be invoked as `/project:fix-github-issue 1234`. ## Common Workflows - **Explore, plan, code, commit:** Have Claude read relevant files without writing code, then ask for a plan. Phrases like "think," "think hard," "think harder," and "ultrathink" map to increasing thinking budgets. Save the plan as a document or issue, implement it while checking the solution, then commit and open a PR. The research and planning steps are the most important, since they keep Claude from jumping straight to code. Subagents help verify details without consuming main-context space. - **Test-driven development:** Have Claude write tests from expected input/output pairs, confirm they fail, and commit them. Then have it write code that passes the tests without modifying them, iterating until they pass. Independent subagents can check for overfitting. Clear targets like tests or mockups make iteration effective. - **Visual iteration:** Give Claude a way to take screenshots (for example, through the Puppeteer MCP server) and a visual mock to match. Output typically improves noticeably after two or three iterations. - **Safe YOLO mode:** `--dangerously-skip-permissions` removes approval prompts, which suits tasks like fixing lint errors. The author recommends running it only in a container without internet access because of risks such as data loss and prompt-injection-driven exfiltration. - **Codebase Q&A:** Claude can answer onboarding questions about logging, endpoints, edge cases, or why a particular call was made, without special prompting. - **Git and GitHub:** Many Anthropic engineers use Claude for over 90% of their git work, including history searches, commit messages, rebase conflicts, PR creation, addressing simple review comments, fixing failing builds, and triaging issues. - **Jupyter notebooks:** Keep Claude Code and the `.ipynb` file open side by side in VS Code. Claude can read outputs, including images, and polish notebooks by asking for "aesthetically pleasing" visualizations. ## Optimizing Your Workflow - **Specific instructions** get better results. For example, "write a new test case for foo.py covering the logged-out edge case, avoid mocks" beats "add tests for foo.py." - **Context inputs** include pasted or dragged screenshots (on macOS, `cmd+ctrl+shift+4` copies a screenshot to the clipboard for `ctrl+v`), file paths, tab-completed file references, and URLs. Domains can be allowlisted through `/permissions`. - **Course correction** works through several controls: asking for a plan before code, pressing Escape to interrupt, double-tapping Escape to edit an earlier prompt, and asking Claude to undo changes. - **Context hygiene** comes from running `/clear` between tasks so irrelevant history doesn't crowd out the current work. - **Checklists and scratchpads** help with large tasks. For example, have Claude write lint errors into a Markdown checklist, then work through them one by one. - **Data input** can be pasted, piped (`cat foo.txt | claude`), pulled through bash or MCP tools, or read from files and URLs. ## Headless Mode and Automation - The `-p` flag runs Claude non-interactively for CI, pre-commit hooks, and build scripts. `--output-format stream-json` streams JSON output. Headless sessions do not persist. - Examples include GitHub-triggered issue triage that applies labels, and using Claude as a subjective linter to catch typos, stale comments, and misleading names. ## Multi-Claude Workflows - **Separate writer and reviewer:** One Claude writes code, then a fresh instance (after `/clear` or in another terminal) reviews it. A similar split works for tests and implementation. Scratchpads let instances pass information to each other. - **Multiple checkouts:** Some engineers run 3–4 checkouts in separate terminal tabs, each with its own task. - **Git worktrees:** `git worktree add ../project-feature-a feature-a` creates an isolated working directory for each independent task, avoiding merge conflicts. Tips include consistent naming, one terminal tab per worktree, iTerm2 notifications, and cleanup with `git worktree remove`. - **Headless fan-out and pipelines:** A script can generate a task list (such as 2,000 files to migrate) and call `claude -p` for each item with restricted `--allowedTools`. Alternatively, `claude -p ... --json` can feed into the next step of a data pipeline. The `--verbose` flag helps debugging. ## Getting Started The most practical starting point is a short, shared CLAUDE.md, followed by the explore-plan-code-commit loop with specific prompts and frequent `/clear`. The author encourages adapting these patterns to your own workflow. The post is by Boris Cherny and notes that it is no longer maintained in favor of the official Claude Code documentation.

Anthropic2025-03-203 min readCurated summary

The "think" tool for complex tool use

# The "Think" Tool for Claude Agents Anthropic found that giving Claude a dedicated "think" tool, a scratchpad it can write to mid-response, improves agentic tool use. The tool helps with following policies, making consistent decisions, and handling multi-step problems, and it requires little implementation effort. The post notes that extended thinking now covers most of these cases, so the dedicated tool is recommended mainly for specific scenarios. The benefits come from giving Claude room to reason about new information gathered from tool outputs, not from extended reasoning before it acts. ## How the "Think" Tool Differs from Extended Thinking - Extended thinking happens before Claude generates a response and plans its approach in advance. - The "think" tool happens during response generation, letting Claude pause after receiving tool results to check whether it has what it needs to continue. - The tool suits complex tool calls, long tool-call chains, policy-heavy environments, and sequential decisions where mistakes are costly. - Extended thinking suits simpler tool use, non-sequential calls, and tasks like coding, math, and physics that don't involve tools. - The tool is defined with a single `thought` string input. It doesn't obtain new information or change any state. It only logs the thought. ## Results on τ-Bench τ-bench simulates customer service conversations and measures pass^k, the probability that all k trials of a task succeed, which captures consistency. - **Airline domain (the hardest):** The "think" tool with an optimized prompt reached 0.570 pass^1, versus 0.370 for the baseline, a 54% relative improvement. The prompt included worked examples of how to reason about policies. The tool alone and extended thinking performed similarly, both better than baseline but well behind the combined approach. - **Retail domain (easier):** The "think" tool alone reached 0.812 pass^1, versus 0.783 for the baseline, with no extra prompting needed. - Gains held up across k=1 to k=5, which points to better handling of edge cases and more consistent policy adherence. ## Results on SWE-Bench - A "think" tool with a description tailored to software debugging was added to the SWE-bench setup for Claude 3.7 Sonnet, which contributed to a state-of-the-art score of 0.623. - The isolated effect was a 1.6% average improvement, statistically significant (Welch's t-test, p < .001). ## Implementation Guidance - **Use it for:** tool output analysis that may require backtracking, policy-heavy environments requiring compliance checks, and sequential decisions where each step depends on the last. - **Skip it for:** single or parallel tool calls, and simple instruction following where default behavior is already adequate. - **Prompting:** Domain-specific examples help the most on difficult tasks. Examples cover the expected level of detail, how to break instructions into steps, decision trees, and checks for missing information. - **Placement:** For long or complex guidance, put instructions in the system prompt rather than the tool description. - **Costs and risks:** The tool adds prompt length and output tokens. It doesn't change external behavior unless Claude calls it, so it's low-risk to add. The post concludes that the "think" tool is not a universal fix, but for the right workloads it offers meaningful reliability gains with minimal implementation work. The authors also note that the results generalize to Claude 3.5 Sonnet (New).

Anthropic2025-01-064 min readCurated summary

Claude SWE-Bench performance

The upgraded Claude 3.5 Sonnet scored 49% on SWE-bench Verified, beating the previous state-of-the-art of 45%. The authors achieved this with a deliberately minimal agent: one prompt and two general-purpose tools, with as much control as possible left to the model. They argue that tool design and scaffolding matter as much as the model itself, since SWE-bench measures the whole agent rather than the model alone. ## Measuring Agents with SWE-bench - SWE-bench tests whether a model can resolve real GitHub issues from popular open-source Python repositories. The model receives a configured environment and a checkout of the repository from just before the fix, then must understand, modify, and test the code. - Solutions are graded against the unit tests from the pull request that originally closed the issue. - The benchmark is attractive for several reasons: it uses real engineering tasks rather than competition-style questions, it is not saturated (no model had crossed 50% on SWE-bench Verified), and it evaluates a full agent, so open-source developers can improve scores by optimizing scaffolding around the same model. - The authors use SWE-bench Verified, a 500-task subset that humans reviewed to remove tasks that cannot be solved from the issue text alone, such as those requiring specific error messages not stated in the issue. ## A Minimal Tool-Using Agent - The agent consists of a prompt, a Bash tool for running shell commands, and an edit tool for viewing, creating, and editing files and directories. - The model is sampled repeatedly until it decides it is finished or exceeds its 200k-token context window. There are no hardcoded workflow stages. - The prompt suggests an approach (explore the repo, write a reproduction script, edit the source, rerun, consider edge cases) without being overly long or prescriptive. The authors note that explicitly encouraging long responses can help when token cost is not a concern. ## Tool Design and Error-Proofing - Tool descriptions were tested and revised to预empt misunderstandings. For example, the Bash tool description specifies that commands need not be XML-escaped, that there is no internet access, and how to run long-lived commands in the background. - The edit tool requires absolute paths. This prevents errors when the agent has moved away from the repository root. - Of the edit strategies tested, exact string replacement was the most reliable. The model specifies `old_str` and `new_str`, and the replacement happens only if `old_str` matches exactly once. Otherwise, the model receives an error and can retry. - The edit tool also supports `view` (with optional line ranges), `create`, `insert`, and `undo_edit`. ## Results | Model | SWE-bench Verified | |---|---| | Claude 3.5 Sonnet (new) | 49% | | Previous SOTA | 45% | | Claude 3.5 Sonnet (old) | 33% | | Claude 3 Opus | 22% | - All models were run with the same agent scaffold. - Compared with older models, the upgraded Claude 3.5 Sonnet self-corrects more often and tries several different solutions instead of repeating the same mistake. ## Example Agent Trajectory - The example is a scikit-learn issue in which `RidgeClassifierCV` rejects a `store_cv_values` argument, even though its attributes depend on that parameter. - The model first viewed the repository structure, then wrote and ran a script that reproduced the `TypeError`. - It then identified that the subclass constructor did not forward `store_cv_values` to the base class, edited the constructor to accept and pass the parameter, and reran the script. - The task was solved in 12 steps. Other tasks took over 100 turns, and some runs ran out of context. ## Challenges in Running SWE-bench - **Cost and duration:** Successful runs sometimes took hundreds of turns and more than 100k tokens. The model is persistent, which is effective but expensive. - **Grading errors:** Some apparent failures were caused by environment setup issues or install patches applied twice, not by the model. - **Hidden tests:** The model cannot see the grading tests, so it may believe it succeeded when it has not. Some solutions were applied at the wrong level of abstraction, such as a bandage rather than a deeper refactor. Others were correct but did not match the original unit tests. - **Multimodal limits:** The agent could not view image files saved to disk or referenced by URL, which made Matplotlib tasks especially hard and led to hallucinations. The authors identify this as an opportunity for improvement. The post closes by noting that developers building with the upgraded model will likely find better ways to improve SWE-bench scores than those demonstrated here.

Anthropic2024-12-196 min readCurated summary

Building effective AI agents

This post, from Anthropic, argues that the most effective LLM agent systems are built from simple, composable patterns rather than complex frameworks. It distinguishes predefined workflows from autonomous agents and advises starting with the simplest solution, adding complexity only when measured results justify it. The authors cover five workflow patterns, when to use full agents, and how to design tools for them. ### Workflows Versus Agents - Workflows orchestrate LLMs and tools through predefined code paths. - Agents let the LLM dynamically direct its own processes and tool usage, keeping control over how it accomplishes tasks. - Both are grouped as "agentic systems," but the distinction is architecturally important. ### When to Use Agents and Frameworks - Agentic systems often trade latency and cost for better task performance, so the tradeoff must be justified. - Workflows suit well-defined tasks that need predictability, while agents suit open-ended problems that need flexibility and model-driven decisions at scale. - Many applications only need a single LLM call optimized with retrieval and in-context examples. - Frameworks such as the Claude Agent SDK, Strands Agents SDK, Rivet, and Vellum simplify setup, but their abstractions can hide prompts and responses, making debugging harder and tempting developers to add unnecessary complexity. - The authors recommend starting with LLM APIs directly, and understanding the framework's underlying code if you do use one. ### The Augmented LLM Building Block - The foundation of agentic systems is an LLM enhanced with retrieval, tools, and memory, which it can use actively by generating search queries, selecting tools, and deciding what to retain. - Key considerations are tailoring these capabilities to the use case and exposing them through a clear, well-documented interface. - The Model Context Protocol is one way to integrate third-party tools using a simple client implementation. ### Core Workflow Patterns - **Prompt chaining:** Decomposes a task into sequential LLM calls, with optional programmatic "gates" between steps. It trades latency for accuracy. Examples include writing marketing copy and then translating it, or drafting an outline, checking it against criteria, and then writing the document. - **Routing:** Classifies an input and sends it to a specialized follow-up task, which separates concerns and allows specialized prompts. Examples include directing customer service queries to different processes, or sending simple questions to a smaller model like Claude Haiku 4.5 and hard ones to Claude Sonnet 4.5. - **Parallelization:** Runs LLM calls simultaneously and aggregates the outputs programmatically, in two variations: - *Sectioning* splits a task into independent subtasks, such as running a guardrail model alongside the core response model, or evaluating different aspects of a model's output separately. - *Voting* runs the same task multiple times for diverse outputs, such as several prompts reviewing code for vulnerabilities. - **Orchestrator-workers:** A central LLM dynamically breaks down a task, delegates subtasks to worker LLMs, and synthesizes the results. Unlike parallelization, subtasks aren't predefined. This suits coding tasks where the required file changes depend on the input, and multi-source search. - **Evaluator-optimizer:** One LLM generates a response while another evaluates it and provides feedback in a loop. This works best when evaluation criteria are clear and iterative refinement measurably helps, as with literary translation or multi-round search. ### Agents in Production - Agents begin with a command or interactive discussion with the user, then plan and operate independently, checking "ground truth" from the environment, such as tool results or code execution, at each step. - They can pause for human feedback at checkpoints or blockers, and should include stopping conditions, such as a maximum number of iterations. - Structurally, agents are often just LLMs using tools in a loop, so the design of toolsets and their documentation is critical. - Agents suit open-ended problems where the number of steps is unpredictable, but their autonomy raises costs and the risk of compounding errors, so extensive sandbox testing and guardrails are essential. - Anthropic's own examples include a coding agent for SWE-bench tasks and the "computer use" reference implementation. ### Combining Patterns and Guiding Principles - The patterns are not prescriptive. They are starting points to shape and combine for specific use cases. - Success depends on measuring performance and iterating. Added complexity should only be kept when it demonstrably improves outcomes. - The authors suggest three principles for agents: keep the design simple, make planning steps transparent, and carefully craft the agent-computer interface (ACI) through thorough tool documentation and testing. ### Agents in Practice - **Customer support:** Suits agents because conversations need external data (customer records, order history, knowledge base articles), actions like refunds can be handled programmatically, and success is measurable through user-defined resolutions. Some companies charge only for successful resolutions. - **Coding agents:** Suit agents because solutions can be verified with automated tests, agents can iterate on test feedback, and output quality can be measured objectively. Anthropic's agent can solve real GitHub issues from SWE-bench Verified based on the pull request description alone, though human review remains essential. ### Prompt Engineering Your Tools - Tool definitions deserve as much prompt-engineering effort as the main prompts, since Claude invokes tools through structured tool-use blocks in the API. - Some formats are much harder for LLMs to produce than others. For example, diffs require counting lines in chunk headers before writing code, and code inside JSON requires escaping newlines and quotes. - Format guidelines: - Give the model enough tokens to reason before committing to an output. - Stick to formats common in internet text. - Avoid formatting overhead like line counting or string escaping. - Designing the agent-computer interface deserves as much care as the human-computer interface. Put yourself in the model's shoes, write documentation like a docstring for a junior developer (with examples, edge cases, and input requirements), test the tools on many inputs, and "poka-yoke" them so mistakes are harder to make. - In the SWE-bench agent, the team spent more time on tools than on the prompt. Requiring absolute file paths eliminated errors that occurred after the agent changed directories. ### Practical Takeaway Start with the simplest prompts and direct API calls, and measure results carefully. Add workflows or autonomous agents only when simpler approaches fall short, and invest heavily in tool design and testing, since they largely determine whether an agent succeeds.

Anthropic2024-09-194 min readCurated summary

Contextual retrieval in AI systems

# Contextual Retrieval: Improving RAG Accuracy by Adding Chunk Context The post argues that traditional RAG systems lose critical information when documents are split into chunks, causing retrieval failures. Its proposed fix, Contextual Retrieval, prepends chunk-specific explanatory context to each chunk before embedding and BM25 indexing. Combined with BM25 and reranking, this cuts the top-20-chunk retrieval failure rate from 5.7% to 1.9%, a 67% reduction. ## When Simple Prompting Is Enough - If the knowledge base is under about 200,000 tokens (roughly 500 pages), it can be placed directly in the prompt without RAG. - Prompt caching makes this approach faster and cheaper, with latency reduced by more than 2x and costs by up to 90%. - Larger knowledge bases still need a retrieval system. ## How Traditional RAG Works and Where It Falls Short - Documents are split into chunks of a few hundred tokens, converted to vector embeddings, and stored in a vector database for semantic search. - Embeddings can miss exact matches, such as an error code like "TS-999." BM25, a lexical ranking function built on TF-IDF, handles these well. - Combining embeddings and BM25 with rank fusion improves results, but chunks often lose context. A chunk like "The company's revenue grew by 3% over the previous quarter" doesn't name the company or the time period. ## Contextual Embeddings and Contextual BM25 - Each chunk is prepended with a short, 50–100 token context situating it within the whole document before embedding and BM25 indexing. - Claude (Claude 3 Haiku in the post) generates this context from the full document and the chunk, using a prompt that asks for a succinct explanation to improve search retrieval. - Manually annotating millions of chunks is impractical, so the model automates the process. - Other context-adding approaches, such as generic document summaries, hypothetical document embeddings, and summary-based indexing, showed limited gains in the authors' tests. ## Keeping Costs Down with Prompt Caching - The full document is cached once and referenced for every chunk, so it isn't resent each time. - With 800-token chunks, 8k-token documents, and 100 tokens of context per chunk, the one-time cost is about $1.02 per million document tokens. ## Experimental Results - Tests covered codebases, fiction, ArXiv papers, and science papers, across several embedding models and retrieval strategies. - Using Gemini Text 004 and top-20 retrieval, contextual embeddings alone reduced the failure rate by 35% (5.7% → 3.7%). - Contextual embeddings combined with contextual BM25 reduced it by 49% (5.7% → 2.9%). - Adding reranking brought the failure rate down to 1.9%, a 67% reduction. ## Implementation Considerations - Chunk size, boundaries, and overlap all affect retrieval performance. - Gemini and Voyage embeddings performed best among the models tested, though contextualization helped every model. - Custom contextualizer prompts, such as ones that include a glossary of domain terms, may improve results further. - Passing 20 chunks to the model outperformed 5 or 10, though more chunks can also distract the model. - Evaluate on your own use case, and consider clearly separating the context from the chunk text during response generation. ## Reranking - Initial retrieval fetches a larger candidate set (the authors used the top 150). - A reranking model, such as Cohere's, scores each chunk against the query, and the top 20 go to the generator. - Reranking improves accuracy and lowers the cost and latency of generation, but it adds a small amount of latency itself. The number of chunks to rerank is a trade-off between accuracy and speed. ## Practical Takeaway The authors recommend combining contextual embeddings (using Voyage or Gemini), contextual BM25, reranking, and passing the top 20 chunks to the model. They provide a cookbook for implementing the approach.