Check what can execute before your agent's permission controls
Know what can execute before relying on an agent's tool approvals. Startup configuration can create an execution path before those controls run.
Anthropic's Python Claude Agent SDK advisory describes a concrete case: an application passed untrusted input into the resume option; a dash-prefixed value became a CLI flag. The advisory reports that an injected MCP configuration could launch a local server command at startup, bypassing SDK permission controls. The listed affected versions are below 0.2.121; that version contains the fix.
Our suggested review for affected deployments:
1. Find application paths that accept session identifiers from users or external systems.
2. Confirm the deployed SDK includes the fix, including packaged or pinned copies.
3. Review who can change local MCP server commands and startup configuration, and what host permissions those processes inherit.
4. In an authorized test environment, verify malformed session identifiers are rejected without starting an unexpected process.
The broader lesson is to review process startup alongside tool authorization. A permission decision later in the workflow cannot stop a command that has already executed.
Sources:
- github.com/anthropics/claude-agent-sdk-python/sec…
- github.com/anthropics/claude-agent-sdk-python/rel…
1 point
El modelo se alquila, el andamiaje es tuyo: cómo hacer un agente de IA que no dependa del modelo
---
title: "El modelo se alquila, el andamiaje es tuyo: cómo hacer un agente de IA que no dependa del modelo"
published: true
description: "Cómo hacer que un agente de IA no dependa del modelo: el modelo entiende y propone; el harness decide qué lee, qué toca y qué queda registrado. Cuatro prácticas para separarlos."
tags: ai, llm, agents, spanish
ai_disclosure_level: some_ai
canonical_url: blog.getwerk.ai
cover_image: blog.getwerk.ai
---
Quien programa tiene Claude Code o Codex. Quien trabaja en una oficina tiene Claude Cowork o ChatGPT Work. Cada uno es un harness: el andamiaje que rodea a un modelo de IA para que haga un trabajo real, con herramientas, contexto y reglas. Quien instala paneles en un techo no tiene uno pensado para su trabajo.
En Werk lo construimos para equipos en movimiento, y la primera decisión fue separarlo del modelo: el modelo entiende y propone, y el harness decide qué lee, qué toca y qué queda registrado. Lo hacemos posible con cuatro prácticas: hablar con los modelos a través de una interfaz propia, que cada agente pida un nivel de trabajo y no un modelo, darles a todos los modelos el mismo formato y poner primero lo que no cambia. Con este post empieza una serie sobre cómo está hecho. Por qué existe Werk lo contamos en Por qué creamos Werk.
Qué hace el modelo y qué hace el harness
Pensemos en una nota de voz de cuatro segundos, grabada arriba de un techo: "Listo lo de Novak". Para que esa frase quede bien registrada hacen falta dos trabajos distintos.
El modelo entiende el pedido: se terminó un trabajo, y de las tarjetas que tiene delante, la de Novak es la que se nombra. El harness hace todo lo demás: elige qué tarjetas mostrarle, revisa que esa persona pueda modificarla, registra el cambio una sola vez aunque el mensaje se procese dos veces y avisa a quien tiene que enterarse.
Un estudio publicado en arXiv en 2026 leyó el código fuente de once harnesses de programación, entre ellos Claude Code, Codex, Gemini CLI, Hermes y Pi. Lo define como lo que conecta al modelo con las herramientas, el contexto, la seguridad, la orquestación y las extensiones. En simple: el modelo entiende y propone. El harness decide qué lee, qué toca y qué queda registrado.
El mismo estudio encontró que ninguno de los once harnesses estudiados importa un framework general de agentes: todos usan loops escritos a mano. Anthropic llegó a lo mismo en Building effective agents (2024): las implementaciones más exitosas que vio no usaban frameworks complejos, y su consejo es empezar llamando directamente a las APIs de los modelos.
Cómo separar el harness del modelo
Si el harness es el que decide, conviene que no dependa de un modelo en particular. Los modelos mejoran cada pocos meses, no todos rinden igual en todo, y ningún servicio en la nube está disponible el 100% del tiempo: los propios proveedores lo informan con transparencia en sus páginas de estado, como las de Anthropic y OpenAI. Estas son las cuatro prácticas que usamos para que la nota de Novak funcione igual, cambie el modelo que cambie.
Para llegar a ellas leímos el código de más de quince proyectos con licencia abierta (MIT o Apache 2.0), como Codex, Gemini CLI, OpenHands, Aider y Pi, y la documentación de otros. Tomamos ideas, no código.
La primera es hablar con los modelos a través de una interfaz propia. Ninguna parte del harness llama directamente a un proveedor: el proveedor es configuración. Trabajamos con los principales de la industria, y pasar de uno a otro es un cambio de configuración que medimos antes de hacerlo.
!Diagrama: el equipo manda notas de voz, fotos, mensajes y archivos; el harness (router, contexto, herramientas, código y verificación) los convierte en el registro del equipo y en avisos; debajo, una interfaz propia conecta con proveedores de modelos intercambiables.
La segunda es que cada agente pida un nivel de trabajo, no un modelo. El agente que marca como hecha la tarjeta de Novak no sabe qué modelo lo atiende: declara el nivel que necesita, y qué modelo ocupa ese lugar lo decide nuestra batería de casos, agente por agente.
La tercera es un formato que todos los modelos lean igual. Seguimos lo que recomienda la industria, por ejemplo las guías de Anthropic y de OpenAI: cada tipo de dato dentro de su propia etiqueta, para que el modelo sepa dónde empieza y dónde termina cada cosa. Así, la conversación, las tarjetas y la nota de voz llegan con la misma forma a cualquier modelo.
> Ninguno de los once harnesses estudiados importa un framework general de agentes.
>
> (Barbaste, Darrigol, Vu y Wiltberger, 2026)
La cuarta es poner lo estable adelante y lo que cambia al final. Las instrucciones de cada agente son las mismas en cada mensaje; la nota de Novak, no. Si lo estable va primero, el proveedor reutiliza lo que ya procesó y la respuesta llega antes y cuesta menos: con DeepSeek Harness, un usuario midió un 98% de aciertos de caché en 650 pedidos. La optimización del caché da para un artículo propio, que vamos a escribir más adelante.
Lo que ningún SDK puede resolver por ti
Los SDK de agentes, como el Agents SDK de OpenAI o el Claude Agent SDK, son una muy buena forma de empezar: resuelven el ciclo de llamar al modelo, ejecutar herramientas y repetir. Los estudiamos a fondo, junto con LangGraph, Vercel AI SDK, Pydantic AI y Mastra. Pero lo más difícil de la nota de Novak no está en ese ciclo.
Está en lo que es propio de un equipo. La tarjeta de Novak vive en un registro que comparten varias personas, cada una con sus permisos. Si Werk pregunta cuál de dos tarjetas es y la respuesta llega como "la segunda", esa respuesta tiene que quedar atada a lo que esa persona vio en pantalla. Eso depende de cada producto, y los buenos SDK lo dicen con claridad: la documentación de Mastra recomienda que una aprobación quede atada a los argumentos exactos que vio quien aprobó.
Tampoco alcanza con un agente personal. Hermes Agent y OpenClaw, dos de los proyectos abiertos que leímos, están pensados para una persona. Hermes lo explica en su política de seguridad: es un agente personal de un solo usuario, y todos los que tienen acceso reciben la misma confianza. Para un agente personal es lo correcto. En un equipo, cada persona ve lo suyo y lo que comparte el proyecto, y el modelo nunca decide quién ve qué.
> El modelo entiende y propone. El harness decide qué lee, qué toca y qué queda registrado.
Por eso armamos un harness propio, y por eso la próxima parte de la serie cuenta su pieza central: el router, que recibe la nota de Novak y la reparte al agente que corresponde.
El modelo cambia, el harness queda
Como las decisiones importantes viven en el harness, el modelo se puede elegir, comparar y cambiar cuando aparece uno mejor. El harness es lo propio: qué lee cada agente, qué verifica el código antes de tocar el registro, cómo se detecta un error y cómo se corrige sin romper otra cosa.
Los modelos van a seguir mejorando. Con un harness bien separado, cada mejora llega sola al uso diario: una nota de voz mejor entendida, la tarjeta correcta, el aviso a quien tiene que enterarse.
Los equipos que usan Werk no tienen que hacer nada para aprovecharla. Ese trabajo lo hace el harness.
Las ideas y las decisiones son mías; usé IA para ayudar a editar el texto.
Rent the model, own the harness: how to build a model-agnostic AI agent
---
title: "Rent the model, own the harness: how to build a model-agnostic AI agent"
published: true
description: "How to keep an AI agent independent of the model: the model understands and proposes, the harness decides what it reads, touches and records. Four practices to keep them apart."
tags: ai, llm, agents, architecture
canonical_url: blog.getwerk.ai
cover_image: blog.getwerk.ai
---
Developers have Claude Code or Codex. Office workers have Claude Cowork or ChatGPT Work. Each of these is a harness: the scaffolding around an AI model that lets it do real work, with tools, context and rules. The person installing solar panels on a roof has nothing built for their work.
At Werk we built one for teams on the move, and our first decision was to keep it separate from the model: the model understands and proposes, and the harness decides what it reads, what it touches and what gets recorded. Four practices make that possible: talk to models through an interface of your own, have each agent ask for a level of work instead of a model, give every model the same format, and put what stays the same first. This post starts a series on how it is built. Why Werk exists is in Why we built Werk.
What the model does and what the harness does
Take a four-second voice note recorded on a roof: "Done with the Novak job." Getting that sentence recorded correctly takes two different kinds of work.
The model understands the request: a job is finished, and of the cards in front of it, Novak's is the one being named. The harness does everything else. It chooses which cards to show the model, checks that this person may change the card, records the change once even if the message is processed twice, and tells whoever needs to know.
A study published on arXiv in 2026 read the source code of eleven coding harnesses, including Claude Code, Codex, Gemini CLI, Hermes and Pi. It defines a harness as what connects a model to tools, context, safety, orchestration and extensions. Put simply: the model understands and proposes. The harness decides what it reads, what it touches and what gets recorded.
The same study found that none of the eleven harnesses studied imports a general-purpose agent framework; all of them run hand-written loops. Anthropic reached the same conclusion in Building effective agents (2024): the most successful implementations it saw did not use complex frameworks, and its advice is to start by calling model APIs directly.
How to keep the harness separate from the model
If the harness makes the decisions, it should not depend on any one model. Models improve every few months, no model is best at everything, and no cloud service is up 100% of the time, as providers report openly on their status pages, such as Anthropic's and OpenAI's. These are the four practices that keep the Novak note working whatever model is behind it.
We arrived at them by reading the code of more than fifteen open-source projects (MIT or Apache 2.0), such as Codex, Gemini CLI, OpenHands, Aider and Pi, and the documentation of others. We took ideas, not code.
The first is to talk to models through an interface of your own. No part of the harness calls a provider directly: the provider is configuration. We work with the major providers in the industry, and moving from one to another is a configuration change we measure before we make it.
!Diagram: the team sends voice notes, photos, messages and files; the harness (router, context, tools, code and verification) turns them into the team's record and notices; below, an interface of its own connects to swappable model providers.
The second is that each agent asks for a level of work, not a model. The agent that marks Novak's card as done does not know which model serves it. It declares the level it needs, and our battery of test cases decides, agent by agent, which model fills that slot.
The third is a format every model reads the same way. We follow what the industry recommends, for example the guides from Anthropic and OpenAI: each kind of data inside its own tag, so the model knows where each piece starts and ends. The conversation, the cards and the voice note reach any model in the same shape.
> None of the eleven harnesses studied imports a general-purpose agent framework.
>
> (Barbaste, Darrigol, Vu and Wiltberger, 2026)
The fourth is to put what stays the same first and what changes last. Each agent's instructions are identical on every message; the Novak note is not. With the stable part first, the provider reuses what it has already processed, so the answer arrives sooner and costs less: with DeepSeek Harness, one user measured a 98% cache hit rate across 650 requests. Cache optimization deserves a post of its own, and we will write it.
What no SDK can solve for you
Agent SDKs such as the OpenAI Agents SDK and the Claude Agent SDK are a great way to start: they handle the cycle of calling the model, running tools and repeating. We studied them closely, along with LangGraph, the Vercel AI SDK, Pydantic AI and Mastra. But the hardest part of the Novak note is not in that cycle.
It is in what belongs to a team. Novak's card lives in a record that several people share, each with their own permissions. If Werk asks which of two cards was meant and the answer comes back as "the second one," that answer has to stay tied to what that person saw on screen. That depends on each product, and the good SDKs say so plainly: Mastra's documentation recommends binding an approval to the exact arguments the approver saw.
A personal agent is not enough either. Hermes Agent and OpenClaw, two of the open-source projects we read, are built for one person. Hermes says so in its security policy: it is a single-tenant personal agent, and everyone with access is equally trusted. For a personal agent, that is the right call. On a team, each person sees their own work and what the project shares, and the model never decides who sees what.
> The model understands and proposes. The harness decides what it reads, what it touches and what gets recorded.
That is why we built our own harness, and why the next part of this series covers its central piece: the router, which receives the Novak note and hands it to the right agent.
The model changes, the harness stays
Because the important decisions live in the harness, the model can be chosen, compared and replaced when a better one comes along. The harness is what is yours: what each agent reads, what the code checks before touching the record, how an error is caught and how it is fixed without breaking something else.
Models will keep getting better. With a well-separated harness, each improvement reaches daily use on its own: a voice note understood better, the right card, the notice to whoever needs to know.
Teams that use Werk do not have to do anything to benefit. The harness does that work.
_The ideas and decisions are mine; I used AI to help edit the text._
Claude Agent SDK: What It Is and How to Build Your First Agent (2026)
Most people meet the Claude Agent SDK as a package name in someone else's repo and have no idea what it is. Is it the API client? Is it Claude Code? Is it a framework? The answer is none of those, and the confusion costs people time, because the SDK is a different tool from each of them.
I went through the official docs and both GitHub repos to write this. Everything below is checked against Anthropic's documentation on October 23, 2026, and the sources are listed at the end. If you want the wider landscape first, my [AI agent frameworks comparison](/blog/ai-agent-frameworks-comparison-2026/) covers how the SDK sits next to LangGraph, the Vercel AI SDK and others.
What Is the Claude Agent SDK?
The Claude Agent SDK is a library, available for Python and TypeScript, that gives your own application the agent loop, built-in tools, permissions and context management that power Claude Code. You pass a prompt and options to query(), and it streams back messages while Claude reads files, runs commands and edits code on its own.
That is the whole idea. Claude Code is the product you use in a terminal. The Agent SDK is the same engine, exposed as a library, so you can embed it in a script, a backend service or a CI job. Anthropic's own phrasing is "Claude Code as a library."
The SDK used to be called the Claude Code SDK. The GitHub README for the TypeScript package says the Claude Code SDK is now the Claude Agent SDK and points to a migration guide for the breaking changes. If you find an old tutorial that imports @anthropic-ai/claude-code, that is the old package. The current ones are named below.
Claude Agent SDK vs the Messages API vs Claude Code
These are three different ways to put Claude to work, and they differ in who runs the loop. Anthropic's overview page compares the Agent SDK, the CLI, the Client SDK and Managed Agents. Here is the version I use when a teammate asks which one to reach for:
| | Messages API (Client SDK) | Claude Agent SDK | Claude Code CLI |
|---|---|---|---|
| What it is | Direct access to the Claude API from your code | Claude Code's agent as a library for Python and TypeScript | The terminal interface for daily interactive use |
| Who runs the tool loop | You, or the client SDK's beta tool runner | The SDK, using the Claude Code agent loop | Claude Code itself |
| Built-in tools | None. You define every tool | File read, write and edit, shell commands, web search and more | The same built-in tools |
| Permissions, sessions, hooks | You build them | Included | Included |
| Where it runs | Anywhere you can call the API | A process you operate | Your terminal, or non-interactively with claude -p |
| Best for | Chat, extraction, classification, custom agent loops | Embedding a coding-capable agent in your own app | Interactive development and one-off tasks |
A fourth option exists. Managed Agents is a hosted agent harness where Anthropic runs the loop in a managed cloud sandbox, configured through the Claude API. The Agent SDK is the opposite end: the agent runs in your process, on your machine or your servers.
One detail from the docs is worth knowing. The SDK is not a thin wrapper around HTTP calls. Both packages bundle a native Claude Code binary, and the SDK drives it. That is why you get Claude Code's exact behavior, and also why a few install setups need extra care (more on that in the install section).
How to Install the Claude Agent SDK
There are two packages, one per language. Both need an Anthropic API key.
| | TypeScript | Python |
|---|---|---|
| Package | @anthropic-ai/claude-agent-sdk | claude-agent-sdk |
| Install | npm install @anthropic-ai/claude-agent-sdk | pip install claude-agent-sdk or uv add claude-agent-sdk |
| Runtime | Node.js 18 or later | Python 3.10 or later |
| Version when I checked | 0.3.308 on npm | 0.2.172 on PyPI |
| Source | anthropics/claude-agent-sdk-typescript | anthropics/claude-agent-sdk-python |
Both are 0.x versions, so expect the API to keep moving. Pin the version in your lockfile and read the changelog in each repo before you upgrade.
For a new TypeScript project, the quickstart uses this setup:
mkdir my-agent
cd my-agent
npm init -y
npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
Setting "type": "module" lets the script use top-level await, and tsx runs TypeScript files directly. If your existing project uses CommonJS, name the script agent.mts instead.
Then set your key in the shell where the agent will run:
export ANTHROPIC_API_KEY=your-api-key
The SDK reads the key from the process environment. It does not load .env files for you, so load them yourself with something like dotenv if that is where your key lives. The SDK also supports Amazon Bedrock (CLAUDE_CODE_USE_BEDROCK=1), Google Cloud (CLAUDE_CODE_USE_VERTEX=1) and Microsoft Foundry (CLAUDE_CODE_USE_FOUNDRY=1), each with its own cloud credentials.
Two install caveats from the docs. If pip installs the Python source distribution instead of a platform wheel (ARM64 Windows is the example given), no binary is bundled, and you need to install Claude Code natively so the SDK can find it on your PATH. On the TypeScript side, the binary arrives through npm optional dependencies, so npm ci --omit=optional leaves you without one. Reinstall without that flag, or point pathToClaudeCodeExecutable at a native install.
Build a Minimal Claude Agent in TypeScript
This is the quickstart agent. It reviews a file for crash bugs and fixes them. Create a utils.py with two obvious bugs first, since that is the file the agent will edit:
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
return total / len(numbers)
def get_user_name(user):
return user["name"].upper()
calculate_average([]) divides by zero and get_user_name(None) raises a TypeError. Now the agent, in agent.ts:
// Agentic loop: streams messages as Claude works
for await (const message of query({
prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options: {
allowedTools: ["Read", "Edit", "Glob"], // Auto-approve these tools
permissionMode: "acceptEdits" // Auto-approve file edits
}
})) {
// Print human-readable output
if (message.type === "assistant" && message.message?.content) {
for (const block of message.message.content) {
if ("text" in block) {
console.log(block.text); // Claude's reasoning
} else if ("name" in block) {
console.log(`Tool: ${block.name}`); // Tool being called
}
}
} else if (message.type === "result") {
console.log(`Done: ${message.subtype}`); // Final result
}
}
Run it with npx tsx agent.ts. You should see the agent's reasoning and each tool it calls, ending with Done: success, and utils.py will have guards for the empty list and the null user.
Three things are happening in that file:
- query() is the entry point. It returns an async iterator, and each iteration yields one message: Claude's reasoning, a tool call, a tool result or the final outcome.
- prompt is the task. You do not tell Claude which tools to use. It picks them based on the task.
- options configures the agent. Here, allowedTools pre-approves three tools and permissionMode: "acceptEdits" approves file edits.
The loop ends when Claude finishes the task or hits an error. The SDK handles orchestration, tool execution, context management and retries, so your code only consumes the stream. If you do not need live output, for example in a background job, you can collect all messages at once instead.
Build the Same Agent in Python
The Python version of the same quickstart agent uses ClaudeAgentOptions and the message classes:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
async def main():
# Agentic loop: streams messages as Claude works
async for message in query(
prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"], # Auto-approve these tools
permission_mode="acceptEdits", # Auto-approve file edits
),
):
# Print human-readable output
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text) # Claude's reasoning
elif hasattr(block, "name"):
print(f"Tool: {block.name}") # Tool being called
elif isinstance(message, ResultMessage):
print(f"Done: {message.subtype}") # Final result
asyncio.run(main())
Run it with python agent.py (or uv run agent.py). The shape matches the TypeScript one, with snake_case option names. For multi-turn conversations, bidirectional streaming, custom tools and hooks in Python, the repo also offers ClaudeSDKClient, which you use as an async context manager and talk to with client.query(...) followed by client.receive_response().
Tools and Permissions in the Claude Agent SDK
The built-in tools are the same ones Claude Code uses: reading, writing and editing files, running commands, searching and web access. The quickstart groups the common combinations like this:
| Tools | What the agent can do |
|---|---|
| Read, Glob, Grep | Read-only analysis |
| Read, Edit, Glob | Analyze and modify code |
| Read, Edit, Bash, Glob, Grep | Full automation |
The part people get wrong is what allowedTools actually does. It is not an allowlist of which tools exist. It is a permission rule list: the tools you name are auto-approved. Any tool you leave out is still available to Claude, and a call to it that needs approval falls through to the permission mode and your canUseTool callback. To remove a tool from Claude's context entirely, put its bare name in disallowedTools. A scoped rule such as Bash(rm *) leaves Bash available but denies matching calls, in every mode.
The docs describe a fixed evaluation order for each tool request: hooks first, then deny rules, then ask rules, then the permission mode, then allow rules, and finally the canUseTool callback. A deny rule wins even in bypassPermissions mode.
The SDK supports six permission modes:
| Mode | What it does |
|---|---|
| default | No mode-based auto-approvals. Calls that need approval and match no allow rule go to your canUseTool callback |
| dontAsk | Denies anything that would prompt, without calling canUseTool |
| acceptEdits | Auto-approves file edits and filesystem commands like mkdir, touch, rm, mv, cp and sed inside the working directory |
| bypassPermissions | Tools run without prompts, apart from a few actions no mode auto-approves. Use with caution |
| plan | Claude explores and plans without editing your source files |
| auto | A classifier model reviews actions such as shell commands and network requests and allows or blocks each one |
For a locked-down read-only agent, the docs suggest pairing allowedTools with dontAsk:
const options = {
allowedTools: ["Read", "Glob", "Grep"],
permissionMode: "dontAsk"
};
One warning from the docs deserves repeating. allowedTools does not constrain bypassPermissions. If you set allowedTools: ["Read"] with permissionMode: "bypassPermissions", every tool is still approved, including Bash, Write and Edit. If you need bypass mode but want specific tools blocked, use disallowedTools. I wrote up the wider least-privilege approach, including the --dangerously-skip-permissions flag in the CLI, in [coding agent permissions and least privilege](/blog/coding-agent-permissions-least-privilege-2026/).
Also note that the SDK now starts in default mode unless you set a mode or your settings files do. In default mode with no way to approve, a tool call that needs approval is denied. If your first agent run reports denied tool calls, that is the usual reason, and the fix is an allow rule or a canUseTool callback, not bypass mode.
Add MCP Servers and Custom Tools
The SDK speaks the Model Context Protocol, so your agent can use any MCP server. You pass servers in the mcpServers option. The docs show stdio servers (a command to run), HTTP and SSE servers (a URL), and in-process SDK servers (tools defined in your own code). This example connects to the Claude Code docs MCP server over HTTP:
for await (const message of query({
prompt: "Use the docs MCP server to explain what hooks are in Claude Code",
options: {
mcpServers: {
"claude-code-docs": {
type: "http",
url: "https://code.claude.com/docs/mcp"
}
},
allowedTools: ["mcp__claude-code-docs__*"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
MCP tools are named mcp__<server-name>__<tool-name>, and they need explicit permission before Claude can call them. The wildcard in allowedTools grants every tool from one server and nothing else. The docs recommend this over broad permission modes: acceptEdits does not auto-approve MCP tools, and bypassPermissions approves them but also switches off most other safety prompts.
If you would rather write your own tools than run a separate server, define them with tool() and wrap them in createSdkMcpServer(). The server runs in-process inside your application. This is the docs' own example, trimmed to one tool:
const getTemperature = tool(
"get_temperature",
"Get the current temperature at a location",
{
latitude: z.number().describe("Latitude coordinate"),
longitude: z.number().describe("Longitude coordinate")
},
async (args) => {
const response = await fetch(
`https://api.open-meteo.com/v1/forecast?latitude=${args.latitude}&longitude=${args.longitude}¤t=temperature_2m&temperature_unit=fahrenheit`
);
const data: any = await response.json();
return {
content: [{ type: "text", text: `Temperature: ${data.current.temperature_2m}°F` }]
};
}
);
const weatherServer = createSdkMcpServer({
name: "weather",
version: "1.0.0",
tools: [getTemperature]
});
for await (const message of query({
prompt: "What's the temperature in San Francisco?",
options: {
mcpServers: { weather: weatherServer },
allowedTools: ["mcp__weather__get_temperature"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}
A tool has four parts: a name, a description Claude reads to decide when to call it, an input schema (a Zod schema in TypeScript) and an async handler that returns a content array. Return isError: true when something fails so Claude can react to it instead of treating an error as data. If you are building a standalone server rather than an in-process one, my guide to [building an MCP server in TypeScript](/blog/build-mcp-server-developer-guide-2026/) covers that path, and the same tool design rules apply to both.
Subagents in the Claude Agent SDK
Subagents are separate agent instances your main agent can spawn for a focused subtask. The docs list four reasons to use them: context isolation (only the subagent's final message returns to the parent), parallelization, specialized instructions, and tool restrictions.
You define them programmatically with the agents option, and Claude invokes them through the Agent tool, so Agent has to be reachable in your session. This version is trimmed from the docs:
for await (const message of query({
prompt: "Review the authentication module for security issues",
options: {
allowedTools: ["Read", "Grep", "Glob", "Agent"],
agents: {
"code-reviewer": {
description:
"Expert code review specialist. Use for quality, security, and maintainability reviews.",
prompt: "You are a code review specialist. Identify security vulnerabilities and suggest specific improvements.",
tools: ["Read", "Grep", "Glob"],
model: "sonnet"
}
}
}
})) {
if ("result" in message) console.log(message.result);
}
description and prompt are required. tools, model and several other fields are optional. If you omit tools, the subagent inherits every tool available to subagents, so list them explicitly when you want a read-only reviewer. The description is what Claude uses to decide when to delegate, and if it keeps answering directly instead, name the subagent in your prompt.
Three details are easy to miss. A subagent starts with a fresh context: it does not see the parent's conversation, so put file paths and decisions in the prompt you hand it. A subagent runs in the parent's permission mode, and if the parent is in bypassPermissions, the subagent is too. And a subagent can spawn subagents of its own, so one prompt can grow into a tree. The docs describe three caps: CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH (default 3), CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS (default 20) and a maxBudgetUsd option (TypeScript) or max_budget_usd (Python) for spend. I would set a budget on any agent that can delegate. For the Claude Code side of this feature, see my [subagents guide](/blog/claude-code-subagents-guide-2026/).
Hooks in the Claude Agent SDK
Hooks are callback functions that run your code at points in the agent lifecycle. They are the right place for checks that must run on every tool call, because hooks run before every other step in the permission flow, and a hook deny applies even in bypassPermissions mode.
This example blocks writes to .env files:
const protectEnvFiles: HookCallback = async (input, toolUseID, { signal }) => {
const preInput = input as PreToolUseHookInput;
const toolInput = preInput.tool_input as Record<string, unknown>;
const filePath = toolInput?.file_path as string;
const fileName = filePath?.split("/").pop();
if (fileName?.toLowerCase() === ".env") {
return {
hookSpecificOutput: {
hookEventName: preInput.hook_event_name,
permissionDecision: "deny",
permissionDecisionReason: "Cannot modify .env files"
}
};
}
return {};
};
for await (const message of query({
prompt: "Create a .env file with the standard local development database configuration",
options: {
hooks: {
PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnvFiles] }]
}
}
})) {
if (message.type === "assistant" || message.type === "result") {
console.log(message);
}
}
The matcher filters by tool name only, not by file path, which is why the path check lives inside the callback. Returning {} allows the operation. A PreToolUse hook can also rewrite a tool's input with updatedInput.
The same example shows a real limit. The Write|Edit matcher does not stop Claude from writing .env through a Bash command, because the hook never runs for that tool. The docs point to the sandbox configuration for blocking Bash writes.
Available events include PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SubagentStop, PreCompact, PermissionRequest and Notification in both SDKs. Many others, including SessionStart and SessionEnd, are TypeScript only. If you also use shell command hooks in Claude Code, the [hooks guide](/blog/claude-code-hooks-guide-2026/) covers that side. SDK callbacks use the same JSON output format as those shell hooks.
When to Use the Agent SDK, the Messages API or claude -p
Here is how I decide, using the distinctions from the docs.
Use the Messages API (Client SDK) when you want the model to produce an answer, not take actions on a machine. Chat, extraction, classification, summaries, and tool use where you control the loop and the tools. You write the tool loop yourself, or use the client SDK's beta tool runner. You get full control and nothing you did not ask for.
Use the Agent SDK when the task is "go do this in a codebase or a file system." Reading files, editing them, running tests, searching the web, delegating to subagents, with permissions and sessions already built. You are embedding Claude Code's agent in a Python or TypeScript process that you operate.
Use claude -p when you want the same agent from a shell script or a CI step, or from a language that is not Python or TypeScript. The overview says to run the CLI as a subprocess with -p and --output-format json to drive the same agent loop from another language. A minimal call looks like this:
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
The headless docs also document --output-format json for structured results with a session ID and cost, --json-schema for schema-conforming output, and --continue and --resume for multi-step conversations. For CI, they recommend --bare, which skips auto-discovery of hooks, skills, plugins, MCP servers and CLAUDE.md so every machine behaves the same. The docs say --bare will become the default for -p in a future release.
If you are driving this from Node or Python and need structured outputs, tool approval callbacks and native message objects, the SDK is the better fit. If you need a one-line command in a pipeline, claude -p is. And if you want Anthropic to host the agent, that is Managed Agents, a different product.
Licensing and Branding Rules
Two rules in the overview matter if you plan to ship a product on top of the SDK. Unless previously approved, Anthropic does not allow third-party developers to offer claude.ai login or rate limits in their products, including agents built on the SDK. Use API key authentication instead. And branding: you may call your agent "Claude Agent" in a menu, or "YourAgentName Powered by Claude," but not "Claude Code" or "Claude Code Agent," and your product should not look like Claude Code. Use of the SDK is governed by Anthropic's Commercial Terms of Service.
Frequently Asked
What is the Claude Agent SDK? It is a Python and TypeScript library that runs Claude Code's agent loop, built-in tools, permissions, sessions and hooks inside your own application. You call query() with a prompt and options, and it streams messages as Claude works on the task.
What is the difference between the Claude SDK and the Claude Agent SDK? "Claude SDK" is a loose term. Anthropic's Client SDK gives you direct access to the Claude API, and you write the tool loop yourself. The Agent SDK runs the Claude Code agent loop for you, with built-in tools. If you searched for "Claude SDK" to build an autonomous agent, you want the Agent SDK. If you want plain API calls, you want the Client SDK.
How do I install the Claude Agent SDK? For TypeScript, run npm install @anthropic-ai/claude-agent-sdk (Node.js 18 or later). For Python, run pip install claude-agent-sdk or uv add claude-agent-sdk (Python 3.10 or later). Then set ANTHROPIC_API_KEY in your environment.
Is the Claude Agent SDK the same as Claude Code? It is the same agent engine, packaged differently. Claude Code is the terminal product for interactive work. The SDK is a library that lets you run that agent from your own code. Both packages bundle a native Claude Code binary.
Was the Claude Code SDK renamed? Yes. The Claude Code SDK is now the Claude Agent SDK, and the official repos point to a migration guide for the breaking changes. Older tutorials may use the previous package name.
Do I need an API key? Yes. The quickstart uses an Anthropic API key from the Claude Console. Amazon Bedrock, Google Cloud and Microsoft Foundry are supported through environment variables and their own credentials. Anthropic does not allow third-party products to offer claude.ai login for SDK agents unless previously approved.
Can the Claude Agent SDK use MCP servers? Yes. Pass servers in mcpServers as stdio, HTTP or SSE servers, or build in-process tools with createSdkMcpServer(). Grant access with allowedTools, using the mcp__<server>__<tool> naming and a wildcard for a whole server.
Does allowedTools restrict which tools Claude can use? No. It pre-approves the tools you list. Unlisted tools stay available, and calls to them fall through to the permission mode. To remove a tool entirely, add its bare name to disallowedTools.
Can I run the Agent SDK from another language? Not as a native package. The docs say to run the CLI as a subprocess with claude -p and --output-format json to drive the same agent loop from other languages.
Sources: Anthropic's Agent SDK documentation on the overview, quickstart, permissions, MCP, custom tools, subagents, hooks and running Claude Code programmatically; the TypeScript and Python SDK repositories; package versions from npm and PyPI, all checked October 23, 2026.
Claude Agent SDKのPython版に、セッション再開IDがCLIの引数として解釈され、権限管理を迂回したコマンド実行につながる問題があった。アプリが外部入力を再開IDへ渡す場合に成立し、0.2.121で修正済み。9月に公開され、10月16日にGitHubの脆弱性DBへ掲載された。
github.com/anthropics/claude-agent-sdk-python/sec… t.co
1 like · 642 views
The Definitive Guide to the Claude Agent SDK
!The Definitive Guide to the Claude Agent SDK
TL;DR
- The Claude Agent SDK programmatically exposes the agent harness powering Claude Code, managing the autonomous context, reasoning, and tool-execution loop in local application processes.
- Native capabilities include built-in file operations, shell execution via Bash, Model Context Protocol (MCP) server support, context compaction, and subagent orchestration.
- Developers can configure the SDK in TypeScript or Python with fine-grained permission modes, deterministic lifecycle hooks, and cross-session state resumption.
- In production, routing agent requests through Bifrost provides multi-provider failover, virtual key budgets, and 11 microseconds of gateway overhead at 5,000 requests per second.
- Endpoint AI governance tools like Bifrost Edge extend gateway-level security policies directly to local developer environments executing agent tasks.
Building autonomous agents with raw foundation model APIs has historically required teams to handcraft fragile tool loops, manually parse structured responses, and engineer custom context window truncation routines. The Claude Agent SDK, developed by Anthropic as the programmatic engine behind Claude Code, fundamentally shifts this paradigm by packaging an autonomous execution harness directly into a client library. Bifrost, an open-source AI gateway built in Go by Maxim AI, pairs naturally with the SDK by handling routing, rate limits, and governance whenever agent loops invoke underlying language models in production. This guide provides a comprehensive technical exploration of the SDK architecture, implementation patterns, and enterprise operational practices.
What is the Claude Agent SDK?
The Claude Agent SDK is a developer library in TypeScript and Python that provides an autonomous agent harness, executing multi-turn tool loops, managing dynamic context compaction, and orchestrating external tools on local machines.
Originally distributed as the Claude Code SDK, Anthropic renamed the package to the Claude Agent SDK to reflect a broader vision beyond command-line interface utilities. While the standard Anthropic Messages API client (@anthropic-ai/sdk in TypeScript or anthropic in Python) merely sends messages and receives static completions, the Agent SDK operates as an autonomous agent runtime.
When using the raw Messages API, application code must inspect every model response, detect tool invocation requests, execute the requested functions locally, package the outputs as tool result blocks, and submit a follow-up request. If an agent requires eight iterative queries to resolve a database migration script, the application must execute eight separate orchestration cycles.
The Claude Agent SDK internalizes this entire execution lifecycle. A developer specifies a high-level goal through a unified query interface, provisions permissions and tools, and allows the SDK to manage tool evaluation, output parsing, error retries, and intermediate reasoning steps until the task reaches completion.
| Capability Dimension | Anthropic Messages API Client | Claude Agent SDK |
| :--- | :--- | :--- |
| Execution Model | Single-turn request and response | Autonomous multi-turn agent loop |
| Tool Orchestration | Manual execution and feedback loops | Built-in execution engine for tools |
| Built-in System Tools | None (user supplies all schemas) | File system, Bash, Grep, Glob, Web fetch |
| Context Management | Manual message array slicing | Automatic context compaction and pruning |
| Protocol Integration | Manual API bindings | Native Model Context Protocol (MCP) support |
| Session Persistence | Application-managed database state | Built-in session saving and resumption |
Core Architecture: The Claude Agent Loop and Execution Model
The internal runtime of the Claude Agent SDK is structured around a continuous loop: Context Assembly, Thought Formulation, Action Invocation, and Observation Processing.
┌──────────────────────────┐
│ User Task / Trigger │
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
┌─────────▶│ Context Assembly │
│ │ (System, History, Caching)
│ └────────────┬─────────────┘
│ │
│ ▼
│ ┌──────────────────────────┐
│ │ Thought Formulation │
│ │ (Reasoning / CoT Step) │
│ └────────────┬─────────────┘
│ │
Loop Continuation ▼
(Observation Ingestion)┌──────────────────────────┐
│ │ Action Invocation │
│ │ (Built-in Tools / MCP) │
│ └────────────┬─────────────┘
│ │
│ ▼
│ ┌──────────────────────────┐
│ │ Observation Processing │
│ │ (Output Parsing / Errors)│
│ └────────────┬─────────────┘
│ │
└───────────────────────┴────────────── [Task Complete?] ──▶ Final Result
During Context Assembly, the engine gathers project settings, active environment parameters, available tool declarations, and prior conversation turns. The SDK applies prompt caching techniques to minimize latency and token expenditures during repeated turns.
In the Thought Formulation phase, Claude generates structured reasoning regarding which steps are required to achieve the objective. The SDK exposes this process via streaming response chunks, enabling real-time visibility into the internal plan before execution begins.
During Action Invocation, the runtime intercepts the tool call generated by the model, evaluates user-defined permission rules, and initiates execution. Depending on configuration, the tool might execute directly in the local process, trigger an external shell command, or dispatch a payload to a remote server.
Finally, Observation Processing takes the execution payload, formats stdout, stderr, or structured JSON data, and inserts the result back into the agent context. If the observation contains error output (such as a compiler failure or syntax issue), Claude parses the diagnostic information on the subsequent turn and self-corrects.
Context management remains a core strength of this architecture. Long-running agent tasks naturally accumulate tens of thousands of tokens. The SDK incorporates automatic context compaction routines, summarizing older message turns, discarding transient tool outputs that are no longer necessary, and preserving critical state flags to prevent context exhaustion.
!An intricate brass-and-sapphire mechanical clockwork mechanism where interlocking gears rotate smoothly in an infinite l
Built-in System Tools
To eliminate repetitive boilerplate, the Claude Agent SDK includes a suite of native tools configured to run safely inside the executing host environment:
- File System Operations (Read, Write, Edit): These primitives allow agents to inspect directory structures, load source files, and execute precise replacements. The Edit tool performs targeted string substitutions rather than rewriting entire files, significantly conserving completion tokens.
- Code Navigation (Glob, Grep): Rather than relying on slow, sequential folder walks, the SDK integrates optimized search utilities. Agents can quickly locate files matching glob patterns or search entire trees for regular expressions to build contextual awareness before modifying code.
- Shell Execution (Bash): The Bash tool gives the agent terminal execution capabilities, allowing it to invoke linters, test runners, build systems, or deployment scripts. Developers can restrict execution through working directory parameters and timeout boundaries.
- Network and Retrieval (WebSearch, WebFetch): Agents can retrieve external web content, research live API documentation, or inspect remote endpoints to resolve technical requirements without human intervention.
Permission modes govern how these tools execute. By default, developers can select from multiple permission tiers:
1. default: Prompts the host or invokes user approval callbacks before executing destructive operations (such as arbitrary shell scripts or file overwrites).
2. plan: Restricts the agent to read-only tools (Read, Glob, Grep), preventing modifications until an explicit execution plan is reviewed.
3. bypassPermissions: Allows fully autonomous execution without human-in-the-loop validation, typically reserved for ephemeral containers or sandboxed cloud workers.
Extending Agents with the Model Context Protocol (MCP)
While built-in tools cover local system operations, production agent deployments require access to proprietary databases, internal microservices, and SaaS platforms. The Claude Agent SDK natively implements the Model Context Protocol (MCP), an open standard specifying how foundation models discover and execute external tools.
The SDK can instantiate in-process MCP servers or connect to remote servers over standard transport layers (such as standard input/output or Server-Sent Events). By utilizing an MCP gateway like Bifrost, engineering teams can centralize tool definitions, enforce authentication credentials, and decouple agent logic from backend integrations.
import { query, createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
// Define custom tool logic using the SDK MCP helper
const databaseServer = createSdkMcpServer({
name: "internal-analytics",
version: "1.0.0",
tools: [
tool(
"query_user_metrics",
"Retrieves daily active metrics for a specified account tier",
{ tier: z.enum(["starter", "growth", "enterprise"]) },
async ({ tier }) => {
// Implementation logic connecting to internal database
const metrics = await fetchMetricsFromDatabase(tier);
return { content: [{ type: "text", text: JSON.stringify(metrics) }] };
}
)
]
});
// Pass the custom MCP server into the query context
const agentStream = query({
prompt: "Analyze enterprise customer drop-offs over the last seven days.",
options: {
mcpServers: [databaseServer],
allowedTools: ["query_user_metrics", "Read", "Write"],
permissionMode: "default"
}
});
Using Bifrost as an MCP gateway enables teams to register internal APIs as MCP tools without rewriting application code. Furthermore, administrators can apply MCP tool filtering across various projects to ensure agents only see the specific tools authorized for their role.
Production Patterns: Subagents, Hooks, and Session Resumption
Moving beyond simple scripts requires patterns that support state isolation, deterministic control, and operational resilience. The Claude Agent SDK provides native primitives for these advanced workflows:
Subagent Delegation
Complex tasks often overwhelm a single agent's reasoning trajectory. The SDK supports spawning specialized subagents with isolated context windows. A primary coordinator agent can spin up a dedicated "Code Reviewer" agent or "Security Auditor" agent, pass it a scoped prompt, collect its synthesized findings, and continue without cluttering the primary agent's token budget.
┌────────────────────────────────┐
│ Coordinator Agent Loop │
│ (Main Orchestration Context) │
└───────┬────────────────┬───────┘
│ │
Spawn Subagent │ │ Spawn Subagent
▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐
│ Security Auditor │ │ Dependency Checker │
│ Isolated Context & │ │ Scoped File Access & │
│ Static Analysis Tools │ │ Package Manifest View │
└────────────┬────────────┘ └────────────┬────────────┘
│ │
└───────────────┬────────────────┘
│ Return Findings
▼
┌────────────────────────────────┐
│ Synthesized Action Plan │
└────────────────────────────────┘
Lifecycle Hooks
To integrate agents with enterprise security monitoring and audit logging, the SDK exposes deterministic hooks at key execution phases:
- beforeTurn: Inspects or alters the prompt before submission to the model.
- onToolCall: Intercepts specific tool invocations to log arguments, sanitize inputs, or block disallowed flags.
- afterTurn: Processes model outputs, calculates intermediate costs, or emits custom metrics to external telemetry collectors.
Session Resumption and Persistence
Autonomous workflows may run across several hours or pause while waiting for human authorization. The SDK manages session state via deterministic identifiers. Developers can serialize an active session, terminate the runtime process, and later restore the identical execution tree using resumeSession(), maintaining complete conversational memory and tool history without replay overhead.
Governing and Securing Claude Agent SDK Workflows
Deploying the Claude Agent SDK inside organizations introduces operational challenges around credential isolation, unbounded cost loops, and data exfiltration. Because agents run in autonomous loops, an unconstrained prompt can trigger hundreds of successive model calls in minutes, quickly consuming API budgets or triggering rate limits.
Centralized control requires separating the agent execution environment from the model access credentials. Using an AI gateway solves this by enforcing policies upstream from the LLM provider. Beyond routing, Bifrost applies governance and security controls (virtual keys, budgets, guardrails, audit logs) centrally, and Bifrost Edge extends that same governance and security to AI traffic on employee machines, with endpoint enforcement on each device.
!A fortified glass and steel gateway structure spanning across dual digital pathways, directing bright energy conduits wh
To prevent unauthorized operations on developer laptops, Bifrost Edge runs locally to monitor developer tooling, inspect outgoing agent traffic, and apply app governance alongside MCP governance. If an agent attempts to invoke an unauthorized MCP server or transmit unredacted API tokens, policies enforced at the endpoint block the request before network egress occurs.
At the gateway layer, virtual keys restrict individual agent instances to predefined token allocations and budget limits. Real-time guardrails scan incoming and outgoing payloads for personally identifiable information (PII) or hardcoded credentials, while immutable audit logs maintain verifiable records for SOC 2, HIPAA, and GDPR compliance.
Routing and Multi-Provider Infrastructure with Bifrost
While the Claude Agent SDK relies on Anthropic's Messages protocol, enterprise architectures often demand redundancy across multiple cloud hosts, including direct Anthropic endpoints, Amazon Bedrock, and Google Vertex AI. If direct Anthropic endpoints encounter 5xx errors or sudden rate limit restrictions, autonomous agent loops fail abruptly unless upstream failover handles the disruption.
Bifrost addresses this by providing an Anthropic-compatible reverse proxy endpoint. The Agent SDK communicates directly with Bifrost over HTTP by configuring standard environment variables.
┌──────────────────────────────────┐
│ Claude Agent SDK Client │
│ (TypeScript or Python Process) │
└────────────────┬─────────────────┘
│
ANTHROPIC_BASE_URL (HTTP)
▼
┌──────────────────────────────────┐
│ Bifrost AI Gateway │
│ - 11µs Latency Overhead │
│ - Virtual Keys & Budgets │
│ - Semantic Caching │
└────┬───────────┬────────────┬────┘
│ │ │
Primary Path │ │ Fallback 1 │ Fallback 2
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│Anthropic │ │AWS │ │Google │
│Direct API│ │Bedrock │ │Vertex AI │
└──────────┘ └──────────┘ └──────────┘
When an agent executes, Bifrost adds only 11 microseconds of overhead per request at 5,000 requests per second in sustained benchmarks. If the primary Anthropic API experiences service disruption, Bifrost automatically executes automatic fallbacks, translating the request payload to AWS Bedrock or Google Vertex AI transparently. The agent process maintains uninterrupted execution without modifying code or restarting active sessions.
Additionally, semantic caching optimizes agent workloads. Identical exploration queries (such as running repetitive directory scans or static codebase queries) return cached responses instantly, significantly reducing execution latency and model costs across extensive testing suites.
Practical Implementation: Building an End-to-End Autonomous Agent
Setting up a resilient agent using the Claude Agent SDK in Python or TypeScript requires only a few steps. The following implementation configures an autonomous code refactoring agent that routes its requests through a secure gateway.
1. Environment Configuration
Point the Anthropic client configuration to your local or VPC-hosted gateway instance and specify a virtual key for budget tracking:
# Point the SDK to the Bifrost gateway
export ANTHROPIC_BASE_URL="http://localhost:8080/v1"
export ANTHROPIC_API_KEY="vk-agent-refactor-prod-4820"
2. Python Agent Implementation
The Python package (claude-agent-sdk) manages the underlying process and streams events as execution advances:
import asyncio
import os
from claude_agent_sdk import query, AgentOptions
async def run_refactor_agent():
# Configure agent parameters and runtime options
options = AgentOptions(
cwd="/workspace/service-auth",
allowed_tools=["Read", "Edit", "Glob", "Grep", "Bash"],
permission_mode="default",
max_turns=25,
env={
"ANTHROPIC_BASE_URL": os.environ.get("ANTHROPIC_BASE_URL"),
"ANTHROPIC_API_KEY": os.environ.get("ANTHROPIC_API_KEY")
}
)
prompt = (
"Scan the repository for deprecated cryptographic hashing functions. "
"Replace SHA-1 usages with SHA-256 in all utility helpers, run test suites "
"via pytest, and output a markdown summary of altered files."
)
print("Initiating Claude Agent execution loop...")
# Execute query and stream output events
async for message in query(prompt=prompt, options=options):
if message.type == "thought":
print(f"[REASONING]: {message.content}")
elif message.type == "tool_use":
print(f"[ACTION]: Invoking {message.tool} with parameters: {message.input}")
elif message.type == "tool_result":
print(f"[OBSERVATION]: Tool completed with status {message.status}")
elif message.type == "result":
print("\n=== FINAL REPORT ===")
print(message.result)
if __name__ == "__main__":
asyncio.run(run_refactor_agent())
3. TypeScript Agent Implementation
For teams standardizing on Node.js or Bun runtimes, the TypeScript package (@anthropic-ai/claude-agent-sdk) offers complete type definitions and Zod validation:
import { query } from "@anthropic-ai/claude-agent-sdk";
async function main() {
const agentEvents = query({
prompt: "Audit internal dependencies in package.json, upgrade minor versions, and verify the build.",
options: {
cwd: process.cwd(),
allowedTools: ["Read", "Edit", "Bash"],
permissionMode: "plan", // Require plan validation before altering files
maxTurns: 15
}
});
for await (const event of agentEvents) {
switch (event.type) {
case "thought":
console.log(`[Thinking]: ${event.text}`);
break;
case "tool_call":
console.log(`[Tool Call]: ${event.toolName}`);
break;
case "result":
console.log("Execution finished successfully:", event.result);
break;
case "error":
console.error("Agent error encountered:", event.error);
break;
}
}
}
main().catch(console.error);
To monitor these executions at scale, Bifrost outputs distributed traces using native OpenTelemetry integration, allowing operations teams to visualize total turn durations, individual tool latency, and token consumption directly inside platforms like Grafana, Datadog, or New Relic.
Comparison: Claude Agent SDK vs. Alternative Frameworks
Choosing the right layer of abstraction depends on application requirements, desired customization depth, and model diversity.
| Evaluation Factor | Claude Agent SDK | Raw Messages API | LangChain / LangGraph |
| :--- | :--- | :--- | :--- |
| Primary Focus | Autonomous local execution and coding | Raw LLM prompt-response | Multi-model graph workflows |
| Model Compatibility | Claude models (expandable via gateway) | Claude family exclusively | Provider-agnostic |
| Tool Loop Management | Fully automated internal runtime | Manual implementation required | Framework-orchestrated nodes |
| System Tools | Native file system and terminal tools | Custom code required | Modular library connectors |
| MCP Integration | Native client and server hooks | Custom JSON-RPC wrappers | Third-party community adapters |
| Overhead | Low (compiled CLI runtime harness) | Minimal (stateless HTTP) | Moderate (heavy abstractions) |
| Context Management | Native automatic compaction | Manual array slicing | Memory modules and checkpointers |
The Claude Agent SDK offers unmatched speed and developer convenience when deploying autonomous agents focused on local code manipulation, file system interaction, and command execution. Conversely, teams building multi-model pipelines with complex DAG routing structures across disparate non-Claude models often rely on LangGraph or custom runtimes.
Frequently Asked Questions
What is the difference between Claude Code and the Claude Agent SDK?
Claude Code is an interactive, terminal-based AI coding assistant designed for direct human interaction. The Claude Agent SDK is the programmatic software library that extracts and exposes the underlying agent harness of Claude Code, enabling developers to build custom headless agents, automated background workflows, and programmatic integrations using Python or TypeScript.
Can the Claude Agent SDK use models other than Claude?
By default, the SDK communicates using Anthropic Messages formatting and targets the Claude model family. However, by setting the ANTHROPIC_BASE_URL environment variable to point to Bifrost, teams can use translation layers to route requests to other models or distribute calls across AWS Bedrock and Google Vertex AI while maintaining full agent loop functionality.
How does the Claude Agent SDK handle context window exhaustion?
The SDK includes built-in context compaction algorithms that continuously track active message tokens. When approaching model limits, the harness summarizes earlier conversational turns, prunes verbose tool output blocks, and retains essential state variables, allowing the agent to sustain multi-hour operations without encountering maximum token errors.
What tools are available by default in the Claude Agent SDK?
The SDK includes native implementations for Read, Write, and Edit for file system manipulation; Glob and Grep for code search; Bash for terminal command execution; and WebSearch and WebFetch for internet access. Additional capabilities can be attached dynamically via custom functions or Model Context Protocol (MCP) servers.
How can teams control costs and prevent runaway agent loops?
Teams can configure maxTurns directly within the SDK options to enforce turn limits on tasks. In enterprise environments, routing traffic through an AI gateway like Bifrost allows platform engineers to assign virtual keys with hard financial spending caps and rate limits, cutting off agent loops automatically if usage exceeds allocated budgets.
Does the Claude Agent SDK support human-in-the-loop approvals?
Yes, the SDK provides configurable permission modes such as plan and default, alongside custom permission callbacks. When an agent attempts an operation marked as sensitive, such as executing terminal commands or updating source files, the runtime halts and requests authorization before applying modifications.
Getting Started with Production Agent Infrastructure
The Claude Agent SDK provides a modern foundation for building autonomous AI agents that manipulate files, execute shell commands, and interact with complex developer toolchains. Moving these autonomous loops into production environments requires dedicated infrastructure to handle protocol translation, provider redundancy, and spend governance.
Engineering teams deploying agentic systems at scale can explore the Bifrost overview, review documentation on governing CLI agents, inspect the open-source GitHub repository, or request a Bifrost demo to implement centralized multi-provider routing and security controls.
Sources
- Anthropic Claude Agent SDK TypeScript Repository: anthropics/claude-agent-sdk-typescript
- Anthropic Claude Agent SDK Python Repository: anthropics/claude-agent-sdk-python
- Model Context Protocol (MCP) Specification: modelcontextprotocol.io
- Anthropic Research on Building Effective Agents: anthropic.com
State of AI Instruction Quality: Coding Agent Comparison
Claude Code, Codex, Copilot, Cursor and Gemini are the five coding agents in the Q3 report. We compared them across the 10,000 most-starred repos that ship an instruction file, and put the companies that make them through the same check, using their own repos.
Claude Code is everywhere. It's set up in 69 of the 100 most-starred repos and in 6 of the top 10. Copilot is in 26 of the top 100, Gemini in 11, Cursor in 7 and Codex in 3.
The file Claude Code reads is losing anyway. One CLAUDE.md in five is a line or two telling the agent to go read AGENTS.md.
Which coding agents the top repos use
| Agent | Top 10 | Top 100 | Top 1,000 | All 10,000 |
|---|--:|--:|--:|--:|
| Claude Code | 6 | 69 | 646 | 6,030 |
| AGENTS.md (shared) | 6 | 72 | 678 | 6,125 |
| Copilot | 2 | 26 | 225 | 1,756 |
| Gemini | 2 | 11 | 51 | 430 |
| Cursor | 1 | 7 | 96 | 734 |
| Codex | 0 | 3 | 32 | 162 |
!Share of repos that set up each agent, in the 100 most-starred repos against the 9,784 of the 10,000 with a setup: Claude Code 69% against 61.6%, AGENTS.md 72% against 62.6%, Copilot 26% against 17.9%, Gemini 11% against 4.4%, Cursor 7% against 7.5%, Codex 3% against 1.7%.
The most-starred repo in the set, freeCodeCamp, uses Copilot. React uses Claude Code. Gemini punches above its size at the top: 430 of the 10,000 set it up, and 11 of the top 100 do.
Many repos don't pick one. 4,213 of the 9,784 with a setup (43.1%) use two or more coding agents, and the most common pairing is Claude Code plus AGENTS.md, in 2,399 repos.
AGENTS.md is winning
998 of the 5,464 CLAUDE.md files in the 10,000 (18.3%) are 25 words or fewer and point at AGENTS.md. Going the other way, 39 of 6,128 AGENTS.md files point at CLAUDE.md. That's 26 to 1. 11.3% of GEMINI.md files point to AGENTS.md too, and 4.0% of Copilot's instructions files do.
The CLAUDE.md files people do write are the least instruction-like main files of any agent. About a quarter of what's in them tells the agent what to do. The rest describes the project.
!Median share of items in each agent's main file that are directives or constraints: CLAUDE.md 26.1%, GEMINI.md 35.2%, AGENTS.md 36.4%, Codex's AGENTS.md 38.1%, copilot-instructions.md 38.9%, .cursorrules 46.0%. Pointer files left out.
Claude Code setups hedge less. The "should" and "try to" kind runs at a median 3.3 per 100 instructions, against 4.7 for the other agents.
The instructions moved into skills
While the debate is still ongoing between AGENTS.md and other provider-specific files, most of the instructions moved to a different location. Skills hold 42.3% of every directive and constraint in the set. All the main files together hold 31.3%.
!Share of all directives and constraints in the 10,000: skills 42.3% (13,190 SKILL.md files plus their reference files), main files 31.3% (13,375 CLAUDE.md, AGENTS.md and other main files), everything else 26.4% (rules, sub-agents, commands).
Peculiar oddity, but only a quarter of repos (2,348) have any skills, and 249 repos hold half of all skill instructions between them. There are almost as many SKILL.md files as main files: 13,190 against 13,375.
They spread like packages, without a package manager. 977 SKILL.md files are byte-for-byte copies of one in another repo. The most-copied, frontend-design, sits unchanged in 14 repos. A fix upstream reaches none of the copies.
Two names, one file, and copies drifting apart
3,562 repos carry main files for two or more agents. A third of them (1,246) keep the same text under two names, mostly a CLAUDE.md identical to the AGENTS.md beside it. Another third use a pointer.
!How the 3,562 repos with main files for two or more agents relate the second file to the first: the same text under two names 1,246 repos (35.0%), a pointer to the other file 1,158 (32.5%), different files 937 (26.3%), copies drifting apart 221 (6.2%).
221 repos keep two copies that have already drifted. The typical pair shares 32 lines, and each side has two or three lines the other lacks.
In 92 of 430 Gemini setups (21.4%), GEMINI.md and AGENTS.md hold the same text, and Gemini reads both. For the other agents, the same shape turns up in 1.3% of setups. Gemini setups are also the heaviest at startup: 8.1% hand the agent more than 5,000 words before the first prompt, against 2.3% across the field.
Cursor goes the other way. 66.3% of Cursor setups carry rule files, and a third (33.5%) have no main file at all. The other agents' setups almost always have one.
The makers, by their own repos
| Company | Agent | Repos in the 10,000 | Median score | Share of repos with custom sub-agents |
|---|---|--:|--:|--:|
| Anthropic | Claude Code | 11 | 7.0 | 27% |
| OpenAI | Codex | 13 | 6.8 | 0% |
| Google | Gemini | 28 | 7.2 | 4% |
| GitHub | Copilot | 11 | 7.9 | 45% |
| Cursor | Cursor | 2 | 8.6 | 0% |
| All repos | | 10,000 | 7.5 | 5.7% |
The scores cluster around the field's. What each company builds is where they split.
!Which agents each company sets up in its own repos: Anthropic, 11 repos: Claude Code 11, AGENTS.md 1, Copilot 0, Gemini 0, Cursor 0. OpenAI, 13 repos: Claude Code 2, AGENTS.md 12, Copilot 1, Gemini 0, Cursor 0. Google with its Gemini orgs, 28 repos: Claude Code 5, AGENTS.md 15, Copilot 1, Gemini 18, Cursor 1. GitHub, 11 repos: Claude Code 1, AGENTS.md 5, Copilot 10, Gemini 0, Cursor 0. Cursor, 2 repos: Claude Code 0, AGENTS.md 1, Copilot 0, Gemini 0, Cursor 2.
GitHub builds its own agents. 5 of its 11 repos ship custom sub-agents, eight times the field's rate of 5.7%. One of them is spreading: an agentic-workflows sub-agent for GitHub's own workflow tool sits in 44 repos across the 10,000, the second most common sub-agent role after code-reviewer.
The agents' own repos shout too. A third of the 10,000 write rules in capitals. Anthropic's prompting guide tells users of its newest models to dial back that kind of language: "Where you might have said 'CRITICAL: You MUST use this tool when...', you can use more normal prompting like 'Use this tool when...'." Claude Code's own repo ships a triage command that says "IMPORTANT: Don't post any comments or messages to the issue." Codex's own AGENTS.md says "Features that change the agent logic MUST add an integration test", and a Gemini CLI command tells the agent "you MUST first consult the getting started documentation".
OpenAI's repos leave the agent guessing. Of every writing habit we compared across the makers, only one difference held up statistically. OpenAI's median repo leaves 48.7 of every 100 instructions without a file, command or tool to act on, against 30.8 for the field. One of its SDKs opens a section with:
> Solve the narrow problem with the simplest implementation. Avoid unrelated refactors, reformatting, dependency or lockfile churn, generated-file edits, speculative abstractions, compatibility shims, and capabilities not requested.
A senior engineer would agree with every word. An agent gets two judgment calls, "the narrow problem" and "the simplest implementation", and nothing to check its work against.
Cursor's two repos score highest, 8.6, with the fewest instructions left vague. One still carries the hedged kind, a skill that says "subtask_prompt should read like a standalone request".
Who checks the makers
These companies write the agents, the documentation and the prompting guides. Their engineers know their codebases far better than any tool does, and that's how the gaps get in. To the person who wrote it, "the narrow problem" has an obvious answer. The agent reading the file has the file, and nothing else.
The agent can't flag the gap either. It does what the line says, and when the line names nothing, it guesses. A company reviewing its own files reads them with the same knowledge that left the gap there.
ails check reads every instruction file with the same deterministic rules, whoever wrote it. The 10,000 most-starred repos and the companies that build the agents get the same treatment, and the findings above are what came back.
!Lines 26 to 41 of the AGENTS.md in OpenAI's openai-node repo, the section "Keep changes small and coherent", with ails check's Specificity Gap finding beside seven of its lines: 28, 31, 32, 34, 36, 37 and 38. Line 28 reads "Solve the narrow problem with the simplest implementation."
Check one yourself
Every repo in this post is public. Clone one and run the same check:
npx @reporails/cli check
It lists each finding by file, so you can read the instructions and decide whether we counted fairly.
This is the last post from the Q3 report. The data behind all of them is in the 2026-Q3 folder of reporails/reports.
---
From The State of AI Instruction Quality: Q3 2026: 10,000 of the most-starred GitHub repos that ship an instruction file, September 2026 snapshot; 9,784 have a setup we could map. "Top 100" and "top 1,000" rank the 10,000 by stars at the snapshot. A setup is one repo and one agent; repos often have several, so agent counts add up to more than the repos. Codex counts repos with a Codex marker in .codex/ (a config.toml, rules/, agents/ or hooks.json) or an AGENTS.override.md; a plain AGENTS.md setup sits in the shared row. A pointer is a main file of 25 words or fewer that names or imports another agent's main file. Items are what the instrument maps from a file; directives and constraints are the items that tell the agent what to do. "Skills" include the reference files beside SKILL.md; setups above the batch's 90-file cap are outside the run, so the skills share is a floor. "The same text" cannot tell a symlink from a copy; only the drifted pairs are certainly two files. "Gemini reads both" is the instrument's model of Gemini, which concatenates AGENTS.md and GEMINI.md. Companies are the GitHub organizations that ship each agent: anthropics, openai, google with google-gemini and gemini-cli-extensions, github and cursor; Cursor's two repos carry no test. Group differences are two-sided Mann-Whitney or Fisher's exact tests, read against a Bonferroni threshold for all 209 comparisons in the run; the top-100 shares are counts. Scores are each company's median repo score on ails check's 0 to 10 scale; for Anthropic, OpenAI, Google and GitHub the 95% bootstrap interval includes the field's 7.5. Vague instructions name no file, command or tool (CORE:C:0042), per 100 directives and constraints, in repos with at least 5.
Repos measured. anthropics: anthropic-sdk-typescript, buffa, claude-agent-sdk-python, claude-code, claude-code-action, claude-code-base-action, claude-for-legal, commerce-agents, defending-code-reference-harness, financial-services, launch-your-agent. openai: apps-sdk-ui, codex, codex-security, harmony, openai-agents-js, openai-cli, openai-cookbook, openai-dotnet, openai-go, openai-java, openai-node, openai-python, realtime-voice-component. google: adk-go, adk-java, adk-python, benchmark, clusterfuzz, comprehensive-rust, docsy, dotprompt, filament, go-github, gvisor, heir, mantis, nomulus, oss-fuzz, osv-scanner, osv.dev, perfetto, play-services-plugins, sam, site-kit-wp, syzkaller, xls. google-gemini: gemini-cli. gemini-cli-extensions: code-review, nanobanana, security, workspace. github: branch-deploy, codeql, codeql-action, copilot-cli-for-beginners, copilot-sdk, docs, gh-aw, gh-skyline, gh-stack, github-mcp-server, spec-kit. cursor: community-plugins, cookbook.
---
I work on Reporails, deterministic diagnostics and governance for the instruction files, rules, and prompts that steer coding agents. It reads the instruction files your coding agent loads, from CLAUDE.md to Copilot and Cursor rules, measures which instructions couple to behavior, and points to the lines worth tightening.
7 reactions
oh-my-mermaid × Codex で Anthropic・OpenAI の公式リポジトリ5つを構成図にしてみた
はじめに
oh-my-mermaid(omm)は、Claude Code や Codex などの AI コーディングツールにスキルを登録し、リポジトリを解析させて Mermaid の構成図と説明を .omm/ フォルダに残す CLI です。
Anthropic と OpenAI の公式リポジトリ5つを、同じ条件で omm+Codex CLI に解析させ、できた図を並べてみました。
結論
- 5つとも1回で構成図と日本語の説明ができ、omm validate(図の文法・規約の検査)も全件通った
- 1リポジトリあたり 68〜89秒、3.2万〜4.7万トークン(5つで約21.6万トークン)
- 図を並べると、Claude Agent SDK は「Claude Code CLI をサブプロセスで動かす薄い層」、OpenAI Agents SDK は「Runner がモデル・ツール・履歴・トレースを束ねる自前の実行系」と、設計の違いがひと目でわかった
- 費用を抑えるため「観点は3つまで・2段まで」に制限したので、15万行の SDK でも図は5〜7ノードの粗い要約になる
環境
- WSL2 の Ubuntu 22.04(隔離した試用環境)
- oh-my-mermaid 0.2.0、Codex CLI 0.162.1(OpenAI の API キーで実行)
手順
前提: Codex CLI を OpenAI の API キーで動かすため、環境変数 CODEX_API_KEY に API キーを設定済みであること(キーの値はここには書きません)。解析ごとに API の料金がかかります。
npm install -g oh-my-mermaid@0.2.0 @openai/codex@0.162.1
omm setup codex # ~/.agents/skills/oh-my-mermaid/ にスキルを登録
git clone --depth 1 https://github.com/anthropics/claude-agent-sdk-python.git
cd claude-agent-sdk-python
omm config language ja # 説明を日本語にする
codex exec --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox \
"Use the omm-scan skill (~/.agents/skills/oh-my-mermaid/omm-scan/SKILL.md) to scan this repository (focus on the src/claude_agent_sdk package) and generate .omm/ documentation. To limit cost: choose at most 3 perspectives, recurse at most 2 levels below each perspective, and keep each field short. Do not run the project's code or install anything." \
< /dev/null > ../scan.log 2>&1
omm status
omm validate
- プロンプトの括弧内(解析の対象)だけをリポジトリごとに変えました
- --dangerously-bypass-approvals-and-sandbox は承認なしでコマンドを実行させるオプションです。今回は使い捨ての隔離環境の中なので使いました。普段の PC では使わないでください
結果
| リポジトリ | 対象の規模(Python) | 秒 | トークン | 観点 | 図 |
|---|---|---|---|---|---|
| anthropics/claude-agent-sdk-python | 26ファイル・13,295行 | 86 | 47,259 | 2 | 6 |
| anthropics/anthropic-sdk-python | 2,288ファイル・155,171行 | 85 | 43,285 | 2 | 7 |
| anthropics/claude-code | 22ファイル・7,914行+プラグイン等 | 89 | 46,626 | 2 | 8 |
| openai/openai-agents-python | 320ファイル・135,502行 | 71 | 47,227 | 3 | 4 |
| openai/swarm | 6ファイル・512行 | 68 | 31,587 | 2 | 3 |
観点(perspective)は AI が選びます。全件で全体構成(overall-architecture)が選ばれ、ほかにデータの流れ(data-flow)、リクエストの流れ(request-lifecycle)、拡張点(extension-points)が選ばれました。
規模が300倍違っても、時間・トークン数はほぼ同じでした。上限をかけたため、大きいリポジトリほど粗く要約されるということです。
Claude Agent SDK(Python)
graph LR
public-api["公開API\nsrc/claude_agent_sdk/"]
runtime["非同期実行\nsrc/claude_agent_sdk/_internal/"]
transport["通信\nsrc/claude_agent_sdk/_internal/transport/"]
session-services["セッション管理\nsrc/claude_agent_sdk/_internal/session*.py"]
sdk-tools["SDKツール\nsrc/claude_agent_sdk/__init__.py"]
contracts["型・例外\nsrc/claude_agent_sdk/types.py"]
public-api -->|"実行を委譲"| runtime
runtime -->|"制御・入出力"| transport
public-api -->|"履歴APIを公開"| session-services
runtime -->|"再開・ミラー保存"| session-services
sdk-tools -->|"MCPサーバーを提供"| runtime
public-api -->|"型を公開"| contracts
通信層の実体は SubprocessCLITransport(Claude Code CLI をサブプロセスで起動)で、create_sdk_mcp_server で Python の関数を MCP ツールとして渡せる、という構造がソースと一致しました。
OpenAI Agents SDK(Python)
graph LR
agent-definition["Agent 定義\nsrc/agents/agent.py"]
runtime["実行制御\nsrc/agents/run.py"]
models["モデル接続\nsrc/agents/models/"]
tools["ツールと MCP\nsrc/agents/tool.py"]
state["履歴と再開\nsrc/agents/memory/"]
tracing["トレース\nsrc/agents/tracing/"]
media["音声経路\nsrc/agents/realtime/"]
agent-definition -->|"設定を渡す"| runtime
runtime -->|"応答を要求"| models
runtime -->|"呼び出しを実行"| tools
runtime -->|"履歴を読書き・中断を保存"| state
runtime -->|"スパンを記録"| tracing
media -->|"共通トレースを利用"| tracing
Claude Agent SDK がエージェントのループを CLI 側に任せるのに対し、こちらは Runner(run.py)が自前でループを回し、履歴(SQLite などのセッション)やトレースまで持っています。
Anthropic SDK(Python)
graph LR
client["公開クライアント\nsrc/anthropic/_client.py"]
resources["API リソース\nsrc/anthropic/resources/"]
transport["共通通信基盤\nsrc/anthropic/_base_client.py"]
schemas["型とモデル\nsrc/anthropic/types/"]
helpers["高水準の補助機能\nsrc/anthropic/lib/"]
client -->|"リソースを公開"| resources
client -->|"継承して通信"| transport
resources -->|"HTTP 操作を委譲"| transport
resources -->|"入出力型を参照"| schemas
transport -->|"応答モデルを構築"| schemas
helpers -->|"クライアントを拡張"| client
resources -->|"stream・parse を利用"| helpers
懸念(concern)の欄に「生成 API と手書き補助層が混在」と書かれました。15万行の大半は自動生成のコードで、図では resources/ の1ノードにまとまっています。
Claude Code(公開リポジトリ)
graph LR
plugins["公開プラグイン\nplugins/"]
examples["導入例\nexamples/"]
automation["運用自動化\nscripts/; .github/"]
mods["組み込み mod\nmods/"]
dev-environment["開発環境\n.devcontainer/; Script/"]
claude-host["Claude Code ホスト\n外部配布 CLI"]
plugins -->|"拡張を読み込む"| claude-host
examples -->|"設定・導入のひな形"| claude-host
mods -->|"組み込みフックを提供"| claude-host
automation -->|"Action・mod 検証で利用"| claude-host
dev-environment -->|"実行環境を用意"| claude-host
公開リポジトリには CLI 本体の実装が無く、プラグインや周辺資産が中心です。omm も説明に「CLI 本体の実装全体ではなく、周辺資産と mods のソースを収録」と正しく書きました。
Swarm
graph LR
public-api["公開 API\nswarm/__init__.py"]
core["実行エンジン\nswarm/core.py"]
models["データ型\nswarm/types.py"]
utilities["補助関数\nswarm/util.py"]
repl["対話ループ\nswarm/repl/repl.py"]
public-api -->|"Swarm・Agent・Response を公開"| core
public-api -->|"型を公開"| models
core -->|"状態と戻り値を表現"| models
core -->|"スキーマ化・差分結合・ログ"| utilities
repl -->|"run を呼び出す"| public-api
制約の欄に「呼び出し間の状態は呼び出し側が保持。永続ストアや HTTP サーバーはない」とあり、教育用の軽量フレームワークという性格をよく表しています。
内容はソースと合っているか
全部は確認していませんが、各リポジトリで1〜2点を grep で抜き取り確認し、すべて一致しました。
| リポジトリ | 図の関係 | ソース |
|---|---|---|
| claude-agent-sdk-python | 通信は CLI のサブプロセス | _internal/transport/subprocess_cli.py の class SubprocessCLITransport(Transport) |
| claude-agent-sdk-python | SDK が MCP サーバーを提供 | __init__.py の def create_sdk_mcp_server( |
| anthropic-sdk-python | クライアントが通信基盤を継承 | _client.py の class Anthropic(SyncAPIClient) |
| openai-agents-python | 実行制御がトレースを記録 | run.py の run_state.set_trace(get_current_trace()) |
| swarm | 対話ループが run を呼ぶ | repl/repl.py の client.run( |
所感
- 知らない SDK を読み始める前の「入口の地図」として便利です。5つとも同じ形(観点・図・説明)で出るので、横に並べて比べやすいのが良い点でした
- 説明は1〜2文と短めです。大きいリポジトリを深く知りたいときは、上限を緩めるか、サブフォルダごとに解析するのがよさそうです(未確認)
- 結果はテキストなので git で管理でき、omm diff で前回の図との差分も見られます
- 注意: ビューア(omm view)は試した版(0.2.0)では全インターフェースで待ち受けました。共有のネットワークで使うときは気を付けてください
参考
- oh-my-mermaid/oh-my-mermaid
- anthropics/claude-agent-sdk-python
- anthropics/anthropic-sdk-python
- anthropics/claude-code
- openai/openai-agents-python
- openai/swarm
Mentions
Check what can execute before your agent's permission controls Know what can execute before relying on an agent's tool approvals. Startup configuration can create an execution path before those controls run. Anthropic's Python Claude Agent SDK advisory describes a concrete case: an application passed untrusted input into the resume option; a dash-prefixed value became a CLI flag. The advisory reports that an injected MCP configuration could launch a local server command at startup, bypassing SDK permission controls. The listed affected versions are below 0.2.121; that version contains the fix. Our suggested review for affected deployments: 1. Find application paths that accept session identifiers from users or external systems. 2. Confirm the deployed SDK includes the fix, including packaged or pinned copies. 3. Review who can change local MCP server commands and startup configuration, and what host permissions those processes inherit. 4. In an authorized test environment, verify malformed session identifiers are rejected without starting an unexpected process. The broader lesson is to review process startup alongside tool authorization. A permission decision later in the workflow cannot stop a command that has already executed. Sources: - github.com/anthropics/claude-agent-sdk-python/sec… - github.com/anthropics/claude-agent-sdk-python/rel…
El modelo se alquila, el andamiaje es tuyo: cómo hacer un agente de IA que no dependa del modelo --- title: "El modelo se alquila, el andamiaje es tuyo: cómo hacer un agente de IA que no dependa del modelo" published: true description: "Cómo hacer que un agente de IA no dependa del modelo: el modelo entiende y propone; el harness decide qué lee, qué toca y qué queda registrado. Cuatro prácticas para separarlos." tags: ai, llm, agents, spanish ai_disclosure_level: some_ai canonical_url: blog.getwerk.ai cover_image: blog.getwerk.ai --- Quien programa tiene Claude Code o Codex. Quien trabaja en una oficina tiene Claude Cowork o ChatGPT Work. Cada uno es un harness: el andamiaje que rodea a un modelo de IA para que haga un trabajo real, con herramientas, contexto y reglas. Quien instala paneles en un techo no tiene uno pensado para su trabajo. En Werk lo construimos para equipos en movimiento, y la primera decisión fue separarlo del modelo: el modelo entiende y propone, y el harness decide qué lee, qué toca y qué queda registrado. Lo hacemos posible con cuatro prácticas: hablar con los modelos a través de una interfaz propia, que cada agente pida un nivel de trabajo y no un modelo, darles a todos los modelos el mismo formato y poner primero lo que no cambia. Con este post empieza una serie sobre cómo está hecho. Por qué existe Werk lo contamos en Por qué creamos Werk. Qué hace el modelo y qué hace el harness Pensemos en una nota de voz de cuatro segundos, grabada arriba de un techo: "Listo lo de Novak". Para que esa frase quede bien registrada hacen falta dos trabajos distintos. El modelo entiende el pedido: se terminó un trabajo, y de las tarjetas que tiene delante, la de Novak es la que se nombra. El harness hace todo lo demás: elige qué tarjetas mostrarle, revisa que esa persona pueda modificarla, registra el cambio una sola vez aunque el mensaje se procese dos veces y avisa a quien tiene que enterarse. Un estudio publicado en arXiv en 2026 leyó el código fuente de once harnesses de programación, entre ellos Claude Code, Codex, Gemini CLI, Hermes y Pi. Lo define como lo que conecta al modelo con las herramientas, el contexto, la seguridad, la orquestación y las extensiones. En simple: el modelo entiende y propone. El harness decide qué lee, qué toca y qué queda registrado. El mismo estudio encontró que ninguno de los once harnesses estudiados importa un framework general de agentes: todos usan loops escritos a mano. Anthropic llegó a lo mismo en Building effective agents (2024): las implementaciones más exitosas que vio no usaban frameworks complejos, y su consejo es empezar llamando directamente a las APIs de los modelos. Cómo separar el harness del modelo Si el harness es el que decide, conviene que no dependa de un modelo en particular. Los modelos mejoran cada pocos meses, no todos rinden igual en todo, y ningún servicio en la nube está disponible el 100% del tiempo: los propios proveedores lo informan con transparencia en sus páginas de estado, como las de Anthropic y OpenAI. Estas son las cuatro prácticas que usamos para que la nota de Novak funcione igual, cambie el modelo que cambie. Para llegar a ellas leímos el código de más de quince proyectos con licencia abierta (MIT o Apache 2.0), como Codex, Gemini CLI, OpenHands, Aider y Pi, y la documentación de otros. Tomamos ideas, no código. La primera es hablar con los modelos a través de una interfaz propia. Ninguna parte del harness llama directamente a un proveedor: el proveedor es configuración. Trabajamos con los principales de la industria, y pasar de uno a otro es un cambio de configuración que medimos antes de hacerlo. !Diagrama: el equipo manda notas de voz, fotos, mensajes y archivos; el harness (router, contexto, herramientas, código y verificación) los convierte en el registro del equipo y en avisos; debajo, una interfaz propia conecta con proveedores de modelos intercambiables. La segunda es que cada agente pida un nivel de trabajo, no un modelo. El agente que marca como hecha la tarjeta de Novak no sabe qué modelo lo atiende: declara el nivel que necesita, y qué modelo ocupa ese lugar lo decide nuestra batería de casos, agente por agente. La tercera es un formato que todos los modelos lean igual. Seguimos lo que recomienda la industria, por ejemplo las guías de Anthropic y de OpenAI: cada tipo de dato dentro de su propia etiqueta, para que el modelo sepa dónde empieza y dónde termina cada cosa. Así, la conversación, las tarjetas y la nota de voz llegan con la misma forma a cualquier modelo. > Ninguno de los once harnesses estudiados importa un framework general de agentes. > > (Barbaste, Darrigol, Vu y Wiltberger, 2026) La cuarta es poner lo estable adelante y lo que cambia al final. Las instrucciones de cada agente son las mismas en cada mensaje; la nota de Novak, no. Si lo estable va primero, el proveedor reutiliza lo que ya procesó y la respuesta llega antes y cuesta menos: con DeepSeek Harness, un usuario midió un 98% de aciertos de caché en 650 pedidos. La optimización del caché da para un artículo propio, que vamos a escribir más adelante. Lo que ningún SDK puede resolver por ti Los SDK de agentes, como el Agents SDK de OpenAI o el Claude Agent SDK, son una muy buena forma de empezar: resuelven el ciclo de llamar al modelo, ejecutar herramientas y repetir. Los estudiamos a fondo, junto con LangGraph, Vercel AI SDK, Pydantic AI y Mastra. Pero lo más difícil de la nota de Novak no está en ese ciclo. Está en lo que es propio de un equipo. La tarjeta de Novak vive en un registro que comparten varias personas, cada una con sus permisos. Si Werk pregunta cuál de dos tarjetas es y la respuesta llega como "la segunda", esa respuesta tiene que quedar atada a lo que esa persona vio en pantalla. Eso depende de cada producto, y los buenos SDK lo dicen con claridad: la documentación de Mastra recomienda que una aprobación quede atada a los argumentos exactos que vio quien aprobó. Tampoco alcanza con un agente personal. Hermes Agent y OpenClaw, dos de los proyectos abiertos que leímos, están pensados para una persona. Hermes lo explica en su política de seguridad: es un agente personal de un solo usuario, y todos los que tienen acceso reciben la misma confianza. Para un agente personal es lo correcto. En un equipo, cada persona ve lo suyo y lo que comparte el proyecto, y el modelo nunca decide quién ve qué. > El modelo entiende y propone. El harness decide qué lee, qué toca y qué queda registrado. Por eso armamos un harness propio, y por eso la próxima parte de la serie cuenta su pieza central: el router, que recibe la nota de Novak y la reparte al agente que corresponde. El modelo cambia, el harness queda Como las decisiones importantes viven en el harness, el modelo se puede elegir, comparar y cambiar cuando aparece uno mejor. El harness es lo propio: qué lee cada agente, qué verifica el código antes de tocar el registro, cómo se detecta un error y cómo se corrige sin romper otra cosa. Los modelos van a seguir mejorando. Con un harness bien separado, cada mejora llega sola al uso diario: una nota de voz mejor entendida, la tarjeta correcta, el aviso a quien tiene que enterarse. Los equipos que usan Werk no tienen que hacer nada para aprovecharla. Ese trabajo lo hace el harness. Las ideas y las decisiones son mías; usé IA para ayudar a editar el texto.
Rent the model, own the harness: how to build a model-agnostic AI agent --- title: "Rent the model, own the harness: how to build a model-agnostic AI agent" published: true description: "How to keep an AI agent independent of the model: the model understands and proposes, the harness decides what it reads, touches and records. Four practices to keep them apart." tags: ai, llm, agents, architecture canonical_url: blog.getwerk.ai cover_image: blog.getwerk.ai --- Developers have Claude Code or Codex. Office workers have Claude Cowork or ChatGPT Work. Each of these is a harness: the scaffolding around an AI model that lets it do real work, with tools, context and rules. The person installing solar panels on a roof has nothing built for their work. At Werk we built one for teams on the move, and our first decision was to keep it separate from the model: the model understands and proposes, and the harness decides what it reads, what it touches and what gets recorded. Four practices make that possible: talk to models through an interface of your own, have each agent ask for a level of work instead of a model, give every model the same format, and put what stays the same first. This post starts a series on how it is built. Why Werk exists is in Why we built Werk. What the model does and what the harness does Take a four-second voice note recorded on a roof: "Done with the Novak job." Getting that sentence recorded correctly takes two different kinds of work. The model understands the request: a job is finished, and of the cards in front of it, Novak's is the one being named. The harness does everything else. It chooses which cards to show the model, checks that this person may change the card, records the change once even if the message is processed twice, and tells whoever needs to know. A study published on arXiv in 2026 read the source code of eleven coding harnesses, including Claude Code, Codex, Gemini CLI, Hermes and Pi. It defines a harness as what connects a model to tools, context, safety, orchestration and extensions. Put simply: the model understands and proposes. The harness decides what it reads, what it touches and what gets recorded. The same study found that none of the eleven harnesses studied imports a general-purpose agent framework; all of them run hand-written loops. Anthropic reached the same conclusion in Building effective agents (2024): the most successful implementations it saw did not use complex frameworks, and its advice is to start by calling model APIs directly. How to keep the harness separate from the model If the harness makes the decisions, it should not depend on any one model. Models improve every few months, no model is best at everything, and no cloud service is up 100% of the time, as providers report openly on their status pages, such as Anthropic's and OpenAI's. These are the four practices that keep the Novak note working whatever model is behind it. We arrived at them by reading the code of more than fifteen open-source projects (MIT or Apache 2.0), such as Codex, Gemini CLI, OpenHands, Aider and Pi, and the documentation of others. We took ideas, not code. The first is to talk to models through an interface of your own. No part of the harness calls a provider directly: the provider is configuration. We work with the major providers in the industry, and moving from one to another is a configuration change we measure before we make it. !Diagram: the team sends voice notes, photos, messages and files; the harness (router, context, tools, code and verification) turns them into the team's record and notices; below, an interface of its own connects to swappable model providers. The second is that each agent asks for a level of work, not a model. The agent that marks Novak's card as done does not know which model serves it. It declares the level it needs, and our battery of test cases decides, agent by agent, which model fills that slot. The third is a format every model reads the same way. We follow what the industry recommends, for example the guides from Anthropic and OpenAI: each kind of data inside its own tag, so the model knows where each piece starts and ends. The conversation, the cards and the voice note reach any model in the same shape. > None of the eleven harnesses studied imports a general-purpose agent framework. > > (Barbaste, Darrigol, Vu and Wiltberger, 2026) The fourth is to put what stays the same first and what changes last. Each agent's instructions are identical on every message; the Novak note is not. With the stable part first, the provider reuses what it has already processed, so the answer arrives sooner and costs less: with DeepSeek Harness, one user measured a 98% cache hit rate across 650 requests. Cache optimization deserves a post of its own, and we will write it. What no SDK can solve for you Agent SDKs such as the OpenAI Agents SDK and the Claude Agent SDK are a great way to start: they handle the cycle of calling the model, running tools and repeating. We studied them closely, along with LangGraph, the Vercel AI SDK, Pydantic AI and Mastra. But the hardest part of the Novak note is not in that cycle. It is in what belongs to a team. Novak's card lives in a record that several people share, each with their own permissions. If Werk asks which of two cards was meant and the answer comes back as "the second one," that answer has to stay tied to what that person saw on screen. That depends on each product, and the good SDKs say so plainly: Mastra's documentation recommends binding an approval to the exact arguments the approver saw. A personal agent is not enough either. Hermes Agent and OpenClaw, two of the open-source projects we read, are built for one person. Hermes says so in its security policy: it is a single-tenant personal agent, and everyone with access is equally trusted. For a personal agent, that is the right call. On a team, each person sees their own work and what the project shares, and the model never decides who sees what. > The model understands and proposes. The harness decides what it reads, what it touches and what gets recorded. That is why we built our own harness, and why the next part of this series covers its central piece: the router, which receives the Novak note and hands it to the right agent. The model changes, the harness stays Because the important decisions live in the harness, the model can be chosen, compared and replaced when a better one comes along. The harness is what is yours: what each agent reads, what the code checks before touching the record, how an error is caught and how it is fixed without breaking something else. Models will keep getting better. With a well-separated harness, each improvement reaches daily use on its own: a voice note understood better, the right card, the notice to whoever needs to know. Teams that use Werk do not have to do anything to benefit. The harness does that work. _The ideas and decisions are mine; I used AI to help edit the text._
Claude Agent SDK: What It Is and How to Build Your First Agent (2026) Most people meet the Claude Agent SDK as a package name in someone else's repo and have no idea what it is. Is it the API client? Is it Claude Code? Is it a framework? The answer is none of those, and the confusion costs people time, because the SDK is a different tool from each of them. I went through the official docs and both GitHub repos to write this. Everything below is checked against Anthropic's documentation on October 23, 2026, and the sources are listed at the end. If you want the wider landscape first, my [AI agent frameworks comparison](/blog/ai-agent-frameworks-comparison-2026/) covers how the SDK sits next to LangGraph, the Vercel AI SDK and others. What Is the Claude Agent SDK? The Claude Agent SDK is a library, available for Python and TypeScript, that gives your own application the agent loop, built-in tools, permissions and context management that power Claude Code. You pass a prompt and options to query(), and it streams back messages while Claude reads files, runs commands and edits code on its own. That is the whole idea. Claude Code is the product you use in a terminal. The Agent SDK is the same engine, exposed as a library, so you can embed it in a script, a backend service or a CI job. Anthropic's own phrasing is "Claude Code as a library." The SDK used to be called the Claude Code SDK. The GitHub README for the TypeScript package says the Claude Code SDK is now the Claude Agent SDK and points to a migration guide for the breaking changes. If you find an old tutorial that imports @anthropic-ai/claude-code, that is the old package. The current ones are named below. Claude Agent SDK vs the Messages API vs Claude Code These are three different ways to put Claude to work, and they differ in who runs the loop. Anthropic's overview page compares the Agent SDK, the CLI, the Client SDK and Managed Agents. Here is the version I use when a teammate asks which one to reach for: | | Messages API (Client SDK) | Claude Agent SDK | Claude Code CLI | |---|---|---|---| | What it is | Direct access to the Claude API from your code | Claude Code's agent as a library for Python and TypeScript | The terminal interface for daily interactive use | | Who runs the tool loop | You, or the client SDK's beta tool runner | The SDK, using the Claude Code agent loop | Claude Code itself | | Built-in tools | None. You define every tool | File read, write and edit, shell commands, web search and more | The same built-in tools | | Permissions, sessions, hooks | You build them | Included | Included | | Where it runs | Anywhere you can call the API | A process you operate | Your terminal, or non-interactively with claude -p | | Best for | Chat, extraction, classification, custom agent loops | Embedding a coding-capable agent in your own app | Interactive development and one-off tasks | A fourth option exists. Managed Agents is a hosted agent harness where Anthropic runs the loop in a managed cloud sandbox, configured through the Claude API. The Agent SDK is the opposite end: the agent runs in your process, on your machine or your servers. One detail from the docs is worth knowing. The SDK is not a thin wrapper around HTTP calls. Both packages bundle a native Claude Code binary, and the SDK drives it. That is why you get Claude Code's exact behavior, and also why a few install setups need extra care (more on that in the install section). How to Install the Claude Agent SDK There are two packages, one per language. Both need an Anthropic API key. | | TypeScript | Python | |---|---|---| | Package | @anthropic-ai/claude-agent-sdk | claude-agent-sdk | | Install | npm install @anthropic-ai/claude-agent-sdk | pip install claude-agent-sdk or uv add claude-agent-sdk | | Runtime | Node.js 18 or later | Python 3.10 or later | | Version when I checked | 0.3.308 on npm | 0.2.172 on PyPI | | Source | anthropics/claude-agent-sdk-typescript | anthropics/claude-agent-sdk-python | Both are 0.x versions, so expect the API to keep moving. Pin the version in your lockfile and read the changelog in each repo before you upgrade. For a new TypeScript project, the quickstart uses this setup: mkdir my-agent cd my-agent npm init -y npm pkg set type=module npm install @anthropic-ai/claude-agent-sdk npm install --save-dev tsx Setting "type": "module" lets the script use top-level await, and tsx runs TypeScript files directly. If your existing project uses CommonJS, name the script agent.mts instead. Then set your key in the shell where the agent will run: export ANTHROPIC_API_KEY=your-api-key The SDK reads the key from the process environment. It does not load .env files for you, so load them yourself with something like dotenv if that is where your key lives. The SDK also supports Amazon Bedrock (CLAUDE_CODE_USE_BEDROCK=1), Google Cloud (CLAUDE_CODE_USE_VERTEX=1) and Microsoft Foundry (CLAUDE_CODE_USE_FOUNDRY=1), each with its own cloud credentials. Two install caveats from the docs. If pip installs the Python source distribution instead of a platform wheel (ARM64 Windows is the example given), no binary is bundled, and you need to install Claude Code natively so the SDK can find it on your PATH. On the TypeScript side, the binary arrives through npm optional dependencies, so npm ci --omit=optional leaves you without one. Reinstall without that flag, or point pathToClaudeCodeExecutable at a native install. Build a Minimal Claude Agent in TypeScript This is the quickstart agent. It reviews a file for crash bugs and fixes them. Create a utils.py with two obvious bugs first, since that is the file the agent will edit: def calculate_average(numbers): total = 0 for num in numbers: total += num return total / len(numbers) def get_user_name(user): return user["name"].upper() calculate_average([]) divides by zero and get_user_name(None) raises a TypeError. Now the agent, in agent.ts: // Agentic loop: streams messages as Claude works for await (const message of query({ prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.", options: { allowedTools: ["Read", "Edit", "Glob"], // Auto-approve these tools permissionMode: "acceptEdits" // Auto-approve file edits } })) { // Print human-readable output if (message.type === "assistant" && message.message?.content) { for (const block of message.message.content) { if ("text" in block) { console.log(block.text); // Claude's reasoning } else if ("name" in block) { console.log(`Tool: ${block.name}`); // Tool being called } } } else if (message.type === "result") { console.log(`Done: ${message.subtype}`); // Final result } } Run it with npx tsx agent.ts. You should see the agent's reasoning and each tool it calls, ending with Done: success, and utils.py will have guards for the empty list and the null user. Three things are happening in that file: - query() is the entry point. It returns an async iterator, and each iteration yields one message: Claude's reasoning, a tool call, a tool result or the final outcome. - prompt is the task. You do not tell Claude which tools to use. It picks them based on the task. - options configures the agent. Here, allowedTools pre-approves three tools and permissionMode: "acceptEdits" approves file edits. The loop ends when Claude finishes the task or hits an error. The SDK handles orchestration, tool execution, context management and retries, so your code only consumes the stream. If you do not need live output, for example in a background job, you can collect all messages at once instead. Build the Same Agent in Python The Python version of the same quickstart agent uses ClaudeAgentOptions and the message classes: import asyncio from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage async def main(): # Agentic loop: streams messages as Claude works async for message in query( prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.", options=ClaudeAgentOptions( allowed_tools=["Read", "Edit", "Glob"], # Auto-approve these tools permission_mode="acceptEdits", # Auto-approve file edits ), ): # Print human-readable output if isinstance(message, AssistantMessage): for block in message.content: if hasattr(block, "text"): print(block.text) # Claude's reasoning elif hasattr(block, "name"): print(f"Tool: {block.name}") # Tool being called elif isinstance(message, ResultMessage): print(f"Done: {message.subtype}") # Final result asyncio.run(main()) Run it with python agent.py (or uv run agent.py). The shape matches the TypeScript one, with snake_case option names. For multi-turn conversations, bidirectional streaming, custom tools and hooks in Python, the repo also offers ClaudeSDKClient, which you use as an async context manager and talk to with client.query(...) followed by client.receive_response(). Tools and Permissions in the Claude Agent SDK The built-in tools are the same ones Claude Code uses: reading, writing and editing files, running commands, searching and web access. The quickstart groups the common combinations like this: | Tools | What the agent can do | |---|---| | Read, Glob, Grep | Read-only analysis | | Read, Edit, Glob | Analyze and modify code | | Read, Edit, Bash, Glob, Grep | Full automation | The part people get wrong is what allowedTools actually does. It is not an allowlist of which tools exist. It is a permission rule list: the tools you name are auto-approved. Any tool you leave out is still available to Claude, and a call to it that needs approval falls through to the permission mode and your canUseTool callback. To remove a tool from Claude's context entirely, put its bare name in disallowedTools. A scoped rule such as Bash(rm *) leaves Bash available but denies matching calls, in every mode. The docs describe a fixed evaluation order for each tool request: hooks first, then deny rules, then ask rules, then the permission mode, then allow rules, and finally the canUseTool callback. A deny rule wins even in bypassPermissions mode. The SDK supports six permission modes: | Mode | What it does | |---|---| | default | No mode-based auto-approvals. Calls that need approval and match no allow rule go to your canUseTool callback | | dontAsk | Denies anything that would prompt, without calling canUseTool | | acceptEdits | Auto-approves file edits and filesystem commands like mkdir, touch, rm, mv, cp and sed inside the working directory | | bypassPermissions | Tools run without prompts, apart from a few actions no mode auto-approves. Use with caution | | plan | Claude explores and plans without editing your source files | | auto | A classifier model reviews actions such as shell commands and network requests and allows or blocks each one | For a locked-down read-only agent, the docs suggest pairing allowedTools with dontAsk: const options = { allowedTools: ["Read", "Glob", "Grep"], permissionMode: "dontAsk" }; One warning from the docs deserves repeating. allowedTools does not constrain bypassPermissions. If you set allowedTools: ["Read"] with permissionMode: "bypassPermissions", every tool is still approved, including Bash, Write and Edit. If you need bypass mode but want specific tools blocked, use disallowedTools. I wrote up the wider least-privilege approach, including the --dangerously-skip-permissions flag in the CLI, in [coding agent permissions and least privilege](/blog/coding-agent-permissions-least-privilege-2026/). Also note that the SDK now starts in default mode unless you set a mode or your settings files do. In default mode with no way to approve, a tool call that needs approval is denied. If your first agent run reports denied tool calls, that is the usual reason, and the fix is an allow rule or a canUseTool callback, not bypass mode. Add MCP Servers and Custom Tools The SDK speaks the Model Context Protocol, so your agent can use any MCP server. You pass servers in the mcpServers option. The docs show stdio servers (a command to run), HTTP and SSE servers (a URL), and in-process SDK servers (tools defined in your own code). This example connects to the Claude Code docs MCP server over HTTP: for await (const message of query({ prompt: "Use the docs MCP server to explain what hooks are in Claude Code", options: { mcpServers: { "claude-code-docs": { type: "http", url: "https://code.claude.com/docs/mcp" } }, allowedTools: ["mcp__claude-code-docs__*"] } })) { if (message.type === "result" && message.subtype === "success") { console.log(message.result); } } MCP tools are named mcp__<server-name>__<tool-name>, and they need explicit permission before Claude can call them. The wildcard in allowedTools grants every tool from one server and nothing else. The docs recommend this over broad permission modes: acceptEdits does not auto-approve MCP tools, and bypassPermissions approves them but also switches off most other safety prompts. If you would rather write your own tools than run a separate server, define them with tool() and wrap them in createSdkMcpServer(). The server runs in-process inside your application. This is the docs' own example, trimmed to one tool: const getTemperature = tool( "get_temperature", "Get the current temperature at a location", { latitude: z.number().describe("Latitude coordinate"), longitude: z.number().describe("Longitude coordinate") }, async (args) => { const response = await fetch( `https://api.open-meteo.com/v1/forecast?latitude=${args.latitude}&longitude=${args.longitude}¤t=temperature_2m&temperature_unit=fahrenheit` ); const data: any = await response.json(); return { content: [{ type: "text", text: `Temperature: ${data.current.temperature_2m}°F` }] }; } ); const weatherServer = createSdkMcpServer({ name: "weather", version: "1.0.0", tools: [getTemperature] }); for await (const message of query({ prompt: "What's the temperature in San Francisco?", options: { mcpServers: { weather: weatherServer }, allowedTools: ["mcp__weather__get_temperature"] } })) { if (message.type === "result" && message.subtype === "success") { console.log(message.result); } } A tool has four parts: a name, a description Claude reads to decide when to call it, an input schema (a Zod schema in TypeScript) and an async handler that returns a content array. Return isError: true when something fails so Claude can react to it instead of treating an error as data. If you are building a standalone server rather than an in-process one, my guide to [building an MCP server in TypeScript](/blog/build-mcp-server-developer-guide-2026/) covers that path, and the same tool design rules apply to both. Subagents in the Claude Agent SDK Subagents are separate agent instances your main agent can spawn for a focused subtask. The docs list four reasons to use them: context isolation (only the subagent's final message returns to the parent), parallelization, specialized instructions, and tool restrictions. You define them programmatically with the agents option, and Claude invokes them through the Agent tool, so Agent has to be reachable in your session. This version is trimmed from the docs: for await (const message of query({ prompt: "Review the authentication module for security issues", options: { allowedTools: ["Read", "Grep", "Glob", "Agent"], agents: { "code-reviewer": { description: "Expert code review specialist. Use for quality, security, and maintainability reviews.", prompt: "You are a code review specialist. Identify security vulnerabilities and suggest specific improvements.", tools: ["Read", "Grep", "Glob"], model: "sonnet" } } } })) { if ("result" in message) console.log(message.result); } description and prompt are required. tools, model and several other fields are optional. If you omit tools, the subagent inherits every tool available to subagents, so list them explicitly when you want a read-only reviewer. The description is what Claude uses to decide when to delegate, and if it keeps answering directly instead, name the subagent in your prompt. Three details are easy to miss. A subagent starts with a fresh context: it does not see the parent's conversation, so put file paths and decisions in the prompt you hand it. A subagent runs in the parent's permission mode, and if the parent is in bypassPermissions, the subagent is too. And a subagent can spawn subagents of its own, so one prompt can grow into a tree. The docs describe three caps: CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH (default 3), CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS (default 20) and a maxBudgetUsd option (TypeScript) or max_budget_usd (Python) for spend. I would set a budget on any agent that can delegate. For the Claude Code side of this feature, see my [subagents guide](/blog/claude-code-subagents-guide-2026/). Hooks in the Claude Agent SDK Hooks are callback functions that run your code at points in the agent lifecycle. They are the right place for checks that must run on every tool call, because hooks run before every other step in the permission flow, and a hook deny applies even in bypassPermissions mode. This example blocks writes to .env files: const protectEnvFiles: HookCallback = async (input, toolUseID, { signal }) => { const preInput = input as PreToolUseHookInput; const toolInput = preInput.tool_input as Record<string, unknown>; const filePath = toolInput?.file_path as string; const fileName = filePath?.split("/").pop(); if (fileName?.toLowerCase() === ".env") { return { hookSpecificOutput: { hookEventName: preInput.hook_event_name, permissionDecision: "deny", permissionDecisionReason: "Cannot modify .env files" } }; } return {}; }; for await (const message of query({ prompt: "Create a .env file with the standard local development database configuration", options: { hooks: { PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnvFiles] }] } } })) { if (message.type === "assistant" || message.type === "result") { console.log(message); } } The matcher filters by tool name only, not by file path, which is why the path check lives inside the callback. Returning {} allows the operation. A PreToolUse hook can also rewrite a tool's input with updatedInput. The same example shows a real limit. The Write|Edit matcher does not stop Claude from writing .env through a Bash command, because the hook never runs for that tool. The docs point to the sandbox configuration for blocking Bash writes. Available events include PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SubagentStop, PreCompact, PermissionRequest and Notification in both SDKs. Many others, including SessionStart and SessionEnd, are TypeScript only. If you also use shell command hooks in Claude Code, the [hooks guide](/blog/claude-code-hooks-guide-2026/) covers that side. SDK callbacks use the same JSON output format as those shell hooks. When to Use the Agent SDK, the Messages API or claude -p Here is how I decide, using the distinctions from the docs. Use the Messages API (Client SDK) when you want the model to produce an answer, not take actions on a machine. Chat, extraction, classification, summaries, and tool use where you control the loop and the tools. You write the tool loop yourself, or use the client SDK's beta tool runner. You get full control and nothing you did not ask for. Use the Agent SDK when the task is "go do this in a codebase or a file system." Reading files, editing them, running tests, searching the web, delegating to subagents, with permissions and sessions already built. You are embedding Claude Code's agent in a Python or TypeScript process that you operate. Use claude -p when you want the same agent from a shell script or a CI step, or from a language that is not Python or TypeScript. The overview says to run the CLI as a subprocess with -p and --output-format json to drive the same agent loop from another language. A minimal call looks like this: claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash" The headless docs also document --output-format json for structured results with a session ID and cost, --json-schema for schema-conforming output, and --continue and --resume for multi-step conversations. For CI, they recommend --bare, which skips auto-discovery of hooks, skills, plugins, MCP servers and CLAUDE.md so every machine behaves the same. The docs say --bare will become the default for -p in a future release. If you are driving this from Node or Python and need structured outputs, tool approval callbacks and native message objects, the SDK is the better fit. If you need a one-line command in a pipeline, claude -p is. And if you want Anthropic to host the agent, that is Managed Agents, a different product. Licensing and Branding Rules Two rules in the overview matter if you plan to ship a product on top of the SDK. Unless previously approved, Anthropic does not allow third-party developers to offer claude.ai login or rate limits in their products, including agents built on the SDK. Use API key authentication instead. And branding: you may call your agent "Claude Agent" in a menu, or "YourAgentName Powered by Claude," but not "Claude Code" or "Claude Code Agent," and your product should not look like Claude Code. Use of the SDK is governed by Anthropic's Commercial Terms of Service. Frequently Asked What is the Claude Agent SDK? It is a Python and TypeScript library that runs Claude Code's agent loop, built-in tools, permissions, sessions and hooks inside your own application. You call query() with a prompt and options, and it streams messages as Claude works on the task. What is the difference between the Claude SDK and the Claude Agent SDK? "Claude SDK" is a loose term. Anthropic's Client SDK gives you direct access to the Claude API, and you write the tool loop yourself. The Agent SDK runs the Claude Code agent loop for you, with built-in tools. If you searched for "Claude SDK" to build an autonomous agent, you want the Agent SDK. If you want plain API calls, you want the Client SDK. How do I install the Claude Agent SDK? For TypeScript, run npm install @anthropic-ai/claude-agent-sdk (Node.js 18 or later). For Python, run pip install claude-agent-sdk or uv add claude-agent-sdk (Python 3.10 or later). Then set ANTHROPIC_API_KEY in your environment. Is the Claude Agent SDK the same as Claude Code? It is the same agent engine, packaged differently. Claude Code is the terminal product for interactive work. The SDK is a library that lets you run that agent from your own code. Both packages bundle a native Claude Code binary. Was the Claude Code SDK renamed? Yes. The Claude Code SDK is now the Claude Agent SDK, and the official repos point to a migration guide for the breaking changes. Older tutorials may use the previous package name. Do I need an API key? Yes. The quickstart uses an Anthropic API key from the Claude Console. Amazon Bedrock, Google Cloud and Microsoft Foundry are supported through environment variables and their own credentials. Anthropic does not allow third-party products to offer claude.ai login for SDK agents unless previously approved. Can the Claude Agent SDK use MCP servers? Yes. Pass servers in mcpServers as stdio, HTTP or SSE servers, or build in-process tools with createSdkMcpServer(). Grant access with allowedTools, using the mcp__<server>__<tool> naming and a wildcard for a whole server. Does allowedTools restrict which tools Claude can use? No. It pre-approves the tools you list. Unlisted tools stay available, and calls to them fall through to the permission mode. To remove a tool entirely, add its bare name to disallowedTools. Can I run the Agent SDK from another language? Not as a native package. The docs say to run the CLI as a subprocess with claude -p and --output-format json to drive the same agent loop from other languages. Sources: Anthropic's Agent SDK documentation on the overview, quickstart, permissions, MCP, custom tools, subagents, hooks and running Claude Code programmatically; the TypeScript and Python SDK repositories; package versions from npm and PyPI, all checked October 23, 2026.
Claude Agent SDKのPython版に、セッション再開IDがCLIの引数として解釈され、権限管理を迂回したコマンド実行につながる問題があった。アプリが外部入力を再開IDへ渡す場合に成立し、0.2.121で修正済み。9月に公開され、10月16日にGitHubの脆弱性DBへ掲載された。 github.com/anthropics/claude-agent-sdk-python/sec… t.co
The Definitive Guide to the Claude Agent SDK !The Definitive Guide to the Claude Agent SDK TL;DR - The Claude Agent SDK programmatically exposes the agent harness powering Claude Code, managing the autonomous context, reasoning, and tool-execution loop in local application processes. - Native capabilities include built-in file operations, shell execution via Bash, Model Context Protocol (MCP) server support, context compaction, and subagent orchestration. - Developers can configure the SDK in TypeScript or Python with fine-grained permission modes, deterministic lifecycle hooks, and cross-session state resumption. - In production, routing agent requests through Bifrost provides multi-provider failover, virtual key budgets, and 11 microseconds of gateway overhead at 5,000 requests per second. - Endpoint AI governance tools like Bifrost Edge extend gateway-level security policies directly to local developer environments executing agent tasks. Building autonomous agents with raw foundation model APIs has historically required teams to handcraft fragile tool loops, manually parse structured responses, and engineer custom context window truncation routines. The Claude Agent SDK, developed by Anthropic as the programmatic engine behind Claude Code, fundamentally shifts this paradigm by packaging an autonomous execution harness directly into a client library. Bifrost, an open-source AI gateway built in Go by Maxim AI, pairs naturally with the SDK by handling routing, rate limits, and governance whenever agent loops invoke underlying language models in production. This guide provides a comprehensive technical exploration of the SDK architecture, implementation patterns, and enterprise operational practices. What is the Claude Agent SDK? The Claude Agent SDK is a developer library in TypeScript and Python that provides an autonomous agent harness, executing multi-turn tool loops, managing dynamic context compaction, and orchestrating external tools on local machines. Originally distributed as the Claude Code SDK, Anthropic renamed the package to the Claude Agent SDK to reflect a broader vision beyond command-line interface utilities. While the standard Anthropic Messages API client (@anthropic-ai/sdk in TypeScript or anthropic in Python) merely sends messages and receives static completions, the Agent SDK operates as an autonomous agent runtime. When using the raw Messages API, application code must inspect every model response, detect tool invocation requests, execute the requested functions locally, package the outputs as tool result blocks, and submit a follow-up request. If an agent requires eight iterative queries to resolve a database migration script, the application must execute eight separate orchestration cycles. The Claude Agent SDK internalizes this entire execution lifecycle. A developer specifies a high-level goal through a unified query interface, provisions permissions and tools, and allows the SDK to manage tool evaluation, output parsing, error retries, and intermediate reasoning steps until the task reaches completion. | Capability Dimension | Anthropic Messages API Client | Claude Agent SDK | | :--- | :--- | :--- | | Execution Model | Single-turn request and response | Autonomous multi-turn agent loop | | Tool Orchestration | Manual execution and feedback loops | Built-in execution engine for tools | | Built-in System Tools | None (user supplies all schemas) | File system, Bash, Grep, Glob, Web fetch | | Context Management | Manual message array slicing | Automatic context compaction and pruning | | Protocol Integration | Manual API bindings | Native Model Context Protocol (MCP) support | | Session Persistence | Application-managed database state | Built-in session saving and resumption | Core Architecture: The Claude Agent Loop and Execution Model The internal runtime of the Claude Agent SDK is structured around a continuous loop: Context Assembly, Thought Formulation, Action Invocation, and Observation Processing. ┌──────────────────────────┐ │ User Task / Trigger │ └────────────┬─────────────┘ │ ▼ ┌──────────────────────────┐ ┌─────────▶│ Context Assembly │ │ │ (System, History, Caching) │ └────────────┬─────────────┘ │ │ │ ▼ │ ┌──────────────────────────┐ │ │ Thought Formulation │ │ │ (Reasoning / CoT Step) │ │ └────────────┬─────────────┘ │ │ Loop Continuation ▼ (Observation Ingestion)┌──────────────────────────┐ │ │ Action Invocation │ │ │ (Built-in Tools / MCP) │ │ └────────────┬─────────────┘ │ │ │ ▼ │ ┌──────────────────────────┐ │ │ Observation Processing │ │ │ (Output Parsing / Errors)│ │ └────────────┬─────────────┘ │ │ └───────────────────────┴────────────── [Task Complete?] ──▶ Final Result During Context Assembly, the engine gathers project settings, active environment parameters, available tool declarations, and prior conversation turns. The SDK applies prompt caching techniques to minimize latency and token expenditures during repeated turns. In the Thought Formulation phase, Claude generates structured reasoning regarding which steps are required to achieve the objective. The SDK exposes this process via streaming response chunks, enabling real-time visibility into the internal plan before execution begins. During Action Invocation, the runtime intercepts the tool call generated by the model, evaluates user-defined permission rules, and initiates execution. Depending on configuration, the tool might execute directly in the local process, trigger an external shell command, or dispatch a payload to a remote server. Finally, Observation Processing takes the execution payload, formats stdout, stderr, or structured JSON data, and inserts the result back into the agent context. If the observation contains error output (such as a compiler failure or syntax issue), Claude parses the diagnostic information on the subsequent turn and self-corrects. Context management remains a core strength of this architecture. Long-running agent tasks naturally accumulate tens of thousands of tokens. The SDK incorporates automatic context compaction routines, summarizing older message turns, discarding transient tool outputs that are no longer necessary, and preserving critical state flags to prevent context exhaustion. !An intricate brass-and-sapphire mechanical clockwork mechanism where interlocking gears rotate smoothly in an infinite l Built-in System Tools To eliminate repetitive boilerplate, the Claude Agent SDK includes a suite of native tools configured to run safely inside the executing host environment: - File System Operations (Read, Write, Edit): These primitives allow agents to inspect directory structures, load source files, and execute precise replacements. The Edit tool performs targeted string substitutions rather than rewriting entire files, significantly conserving completion tokens. - Code Navigation (Glob, Grep): Rather than relying on slow, sequential folder walks, the SDK integrates optimized search utilities. Agents can quickly locate files matching glob patterns or search entire trees for regular expressions to build contextual awareness before modifying code. - Shell Execution (Bash): The Bash tool gives the agent terminal execution capabilities, allowing it to invoke linters, test runners, build systems, or deployment scripts. Developers can restrict execution through working directory parameters and timeout boundaries. - Network and Retrieval (WebSearch, WebFetch): Agents can retrieve external web content, research live API documentation, or inspect remote endpoints to resolve technical requirements without human intervention. Permission modes govern how these tools execute. By default, developers can select from multiple permission tiers: 1. default: Prompts the host or invokes user approval callbacks before executing destructive operations (such as arbitrary shell scripts or file overwrites). 2. plan: Restricts the agent to read-only tools (Read, Glob, Grep), preventing modifications until an explicit execution plan is reviewed. 3. bypassPermissions: Allows fully autonomous execution without human-in-the-loop validation, typically reserved for ephemeral containers or sandboxed cloud workers. Extending Agents with the Model Context Protocol (MCP) While built-in tools cover local system operations, production agent deployments require access to proprietary databases, internal microservices, and SaaS platforms. The Claude Agent SDK natively implements the Model Context Protocol (MCP), an open standard specifying how foundation models discover and execute external tools. The SDK can instantiate in-process MCP servers or connect to remote servers over standard transport layers (such as standard input/output or Server-Sent Events). By utilizing an MCP gateway like Bifrost, engineering teams can centralize tool definitions, enforce authentication credentials, and decouple agent logic from backend integrations. import { query, createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk"; import { z } from "zod"; // Define custom tool logic using the SDK MCP helper const databaseServer = createSdkMcpServer({ name: "internal-analytics", version: "1.0.0", tools: [ tool( "query_user_metrics", "Retrieves daily active metrics for a specified account tier", { tier: z.enum(["starter", "growth", "enterprise"]) }, async ({ tier }) => { // Implementation logic connecting to internal database const metrics = await fetchMetricsFromDatabase(tier); return { content: [{ type: "text", text: JSON.stringify(metrics) }] }; } ) ] }); // Pass the custom MCP server into the query context const agentStream = query({ prompt: "Analyze enterprise customer drop-offs over the last seven days.", options: { mcpServers: [databaseServer], allowedTools: ["query_user_metrics", "Read", "Write"], permissionMode: "default" } }); Using Bifrost as an MCP gateway enables teams to register internal APIs as MCP tools without rewriting application code. Furthermore, administrators can apply MCP tool filtering across various projects to ensure agents only see the specific tools authorized for their role. Production Patterns: Subagents, Hooks, and Session Resumption Moving beyond simple scripts requires patterns that support state isolation, deterministic control, and operational resilience. The Claude Agent SDK provides native primitives for these advanced workflows: Subagent Delegation Complex tasks often overwhelm a single agent's reasoning trajectory. The SDK supports spawning specialized subagents with isolated context windows. A primary coordinator agent can spin up a dedicated "Code Reviewer" agent or "Security Auditor" agent, pass it a scoped prompt, collect its synthesized findings, and continue without cluttering the primary agent's token budget. ┌────────────────────────────────┐ │ Coordinator Agent Loop │ │ (Main Orchestration Context) │ └───────┬────────────────┬───────┘ │ │ Spawn Subagent │ │ Spawn Subagent ▼ ▼ ┌─────────────────────────┐ ┌─────────────────────────┐ │ Security Auditor │ │ Dependency Checker │ │ Isolated Context & │ │ Scoped File Access & │ │ Static Analysis Tools │ │ Package Manifest View │ └────────────┬────────────┘ └────────────┬────────────┘ │ │ └───────────────┬────────────────┘ │ Return Findings ▼ ┌────────────────────────────────┐ │ Synthesized Action Plan │ └────────────────────────────────┘ Lifecycle Hooks To integrate agents with enterprise security monitoring and audit logging, the SDK exposes deterministic hooks at key execution phases: - beforeTurn: Inspects or alters the prompt before submission to the model. - onToolCall: Intercepts specific tool invocations to log arguments, sanitize inputs, or block disallowed flags. - afterTurn: Processes model outputs, calculates intermediate costs, or emits custom metrics to external telemetry collectors. Session Resumption and Persistence Autonomous workflows may run across several hours or pause while waiting for human authorization. The SDK manages session state via deterministic identifiers. Developers can serialize an active session, terminate the runtime process, and later restore the identical execution tree using resumeSession(), maintaining complete conversational memory and tool history without replay overhead. Governing and Securing Claude Agent SDK Workflows Deploying the Claude Agent SDK inside organizations introduces operational challenges around credential isolation, unbounded cost loops, and data exfiltration. Because agents run in autonomous loops, an unconstrained prompt can trigger hundreds of successive model calls in minutes, quickly consuming API budgets or triggering rate limits. Centralized control requires separating the agent execution environment from the model access credentials. Using an AI gateway solves this by enforcing policies upstream from the LLM provider. Beyond routing, Bifrost applies governance and security controls (virtual keys, budgets, guardrails, audit logs) centrally, and Bifrost Edge extends that same governance and security to AI traffic on employee machines, with endpoint enforcement on each device. !A fortified glass and steel gateway structure spanning across dual digital pathways, directing bright energy conduits wh To prevent unauthorized operations on developer laptops, Bifrost Edge runs locally to monitor developer tooling, inspect outgoing agent traffic, and apply app governance alongside MCP governance. If an agent attempts to invoke an unauthorized MCP server or transmit unredacted API tokens, policies enforced at the endpoint block the request before network egress occurs. At the gateway layer, virtual keys restrict individual agent instances to predefined token allocations and budget limits. Real-time guardrails scan incoming and outgoing payloads for personally identifiable information (PII) or hardcoded credentials, while immutable audit logs maintain verifiable records for SOC 2, HIPAA, and GDPR compliance. Routing and Multi-Provider Infrastructure with Bifrost While the Claude Agent SDK relies on Anthropic's Messages protocol, enterprise architectures often demand redundancy across multiple cloud hosts, including direct Anthropic endpoints, Amazon Bedrock, and Google Vertex AI. If direct Anthropic endpoints encounter 5xx errors or sudden rate limit restrictions, autonomous agent loops fail abruptly unless upstream failover handles the disruption. Bifrost addresses this by providing an Anthropic-compatible reverse proxy endpoint. The Agent SDK communicates directly with Bifrost over HTTP by configuring standard environment variables. ┌──────────────────────────────────┐ │ Claude Agent SDK Client │ │ (TypeScript or Python Process) │ └────────────────┬─────────────────┘ │ ANTHROPIC_BASE_URL (HTTP) ▼ ┌──────────────────────────────────┐ │ Bifrost AI Gateway │ │ - 11µs Latency Overhead │ │ - Virtual Keys & Budgets │ │ - Semantic Caching │ └────┬───────────┬────────────┬────┘ │ │ │ Primary Path │ │ Fallback 1 │ Fallback 2 ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ │Anthropic │ │AWS │ │Google │ │Direct API│ │Bedrock │ │Vertex AI │ └──────────┘ └──────────┘ └──────────┘ When an agent executes, Bifrost adds only 11 microseconds of overhead per request at 5,000 requests per second in sustained benchmarks. If the primary Anthropic API experiences service disruption, Bifrost automatically executes automatic fallbacks, translating the request payload to AWS Bedrock or Google Vertex AI transparently. The agent process maintains uninterrupted execution without modifying code or restarting active sessions. Additionally, semantic caching optimizes agent workloads. Identical exploration queries (such as running repetitive directory scans or static codebase queries) return cached responses instantly, significantly reducing execution latency and model costs across extensive testing suites. Practical Implementation: Building an End-to-End Autonomous Agent Setting up a resilient agent using the Claude Agent SDK in Python or TypeScript requires only a few steps. The following implementation configures an autonomous code refactoring agent that routes its requests through a secure gateway. 1. Environment Configuration Point the Anthropic client configuration to your local or VPC-hosted gateway instance and specify a virtual key for budget tracking: # Point the SDK to the Bifrost gateway export ANTHROPIC_BASE_URL="http://localhost:8080/v1" export ANTHROPIC_API_KEY="vk-agent-refactor-prod-4820" 2. Python Agent Implementation The Python package (claude-agent-sdk) manages the underlying process and streams events as execution advances: import asyncio import os from claude_agent_sdk import query, AgentOptions async def run_refactor_agent(): # Configure agent parameters and runtime options options = AgentOptions( cwd="/workspace/service-auth", allowed_tools=["Read", "Edit", "Glob", "Grep", "Bash"], permission_mode="default", max_turns=25, env={ "ANTHROPIC_BASE_URL": os.environ.get("ANTHROPIC_BASE_URL"), "ANTHROPIC_API_KEY": os.environ.get("ANTHROPIC_API_KEY") } ) prompt = ( "Scan the repository for deprecated cryptographic hashing functions. " "Replace SHA-1 usages with SHA-256 in all utility helpers, run test suites " "via pytest, and output a markdown summary of altered files." ) print("Initiating Claude Agent execution loop...") # Execute query and stream output events async for message in query(prompt=prompt, options=options): if message.type == "thought": print(f"[REASONING]: {message.content}") elif message.type == "tool_use": print(f"[ACTION]: Invoking {message.tool} with parameters: {message.input}") elif message.type == "tool_result": print(f"[OBSERVATION]: Tool completed with status {message.status}") elif message.type == "result": print("\n=== FINAL REPORT ===") print(message.result) if __name__ == "__main__": asyncio.run(run_refactor_agent()) 3. TypeScript Agent Implementation For teams standardizing on Node.js or Bun runtimes, the TypeScript package (@anthropic-ai/claude-agent-sdk) offers complete type definitions and Zod validation: import { query } from "@anthropic-ai/claude-agent-sdk"; async function main() { const agentEvents = query({ prompt: "Audit internal dependencies in package.json, upgrade minor versions, and verify the build.", options: { cwd: process.cwd(), allowedTools: ["Read", "Edit", "Bash"], permissionMode: "plan", // Require plan validation before altering files maxTurns: 15 } }); for await (const event of agentEvents) { switch (event.type) { case "thought": console.log(`[Thinking]: ${event.text}`); break; case "tool_call": console.log(`[Tool Call]: ${event.toolName}`); break; case "result": console.log("Execution finished successfully:", event.result); break; case "error": console.error("Agent error encountered:", event.error); break; } } } main().catch(console.error); To monitor these executions at scale, Bifrost outputs distributed traces using native OpenTelemetry integration, allowing operations teams to visualize total turn durations, individual tool latency, and token consumption directly inside platforms like Grafana, Datadog, or New Relic. Comparison: Claude Agent SDK vs. Alternative Frameworks Choosing the right layer of abstraction depends on application requirements, desired customization depth, and model diversity. | Evaluation Factor | Claude Agent SDK | Raw Messages API | LangChain / LangGraph | | :--- | :--- | :--- | :--- | | Primary Focus | Autonomous local execution and coding | Raw LLM prompt-response | Multi-model graph workflows | | Model Compatibility | Claude models (expandable via gateway) | Claude family exclusively | Provider-agnostic | | Tool Loop Management | Fully automated internal runtime | Manual implementation required | Framework-orchestrated nodes | | System Tools | Native file system and terminal tools | Custom code required | Modular library connectors | | MCP Integration | Native client and server hooks | Custom JSON-RPC wrappers | Third-party community adapters | | Overhead | Low (compiled CLI runtime harness) | Minimal (stateless HTTP) | Moderate (heavy abstractions) | | Context Management | Native automatic compaction | Manual array slicing | Memory modules and checkpointers | The Claude Agent SDK offers unmatched speed and developer convenience when deploying autonomous agents focused on local code manipulation, file system interaction, and command execution. Conversely, teams building multi-model pipelines with complex DAG routing structures across disparate non-Claude models often rely on LangGraph or custom runtimes. Frequently Asked Questions What is the difference between Claude Code and the Claude Agent SDK? Claude Code is an interactive, terminal-based AI coding assistant designed for direct human interaction. The Claude Agent SDK is the programmatic software library that extracts and exposes the underlying agent harness of Claude Code, enabling developers to build custom headless agents, automated background workflows, and programmatic integrations using Python or TypeScript. Can the Claude Agent SDK use models other than Claude? By default, the SDK communicates using Anthropic Messages formatting and targets the Claude model family. However, by setting the ANTHROPIC_BASE_URL environment variable to point to Bifrost, teams can use translation layers to route requests to other models or distribute calls across AWS Bedrock and Google Vertex AI while maintaining full agent loop functionality. How does the Claude Agent SDK handle context window exhaustion? The SDK includes built-in context compaction algorithms that continuously track active message tokens. When approaching model limits, the harness summarizes earlier conversational turns, prunes verbose tool output blocks, and retains essential state variables, allowing the agent to sustain multi-hour operations without encountering maximum token errors. What tools are available by default in the Claude Agent SDK? The SDK includes native implementations for Read, Write, and Edit for file system manipulation; Glob and Grep for code search; Bash for terminal command execution; and WebSearch and WebFetch for internet access. Additional capabilities can be attached dynamically via custom functions or Model Context Protocol (MCP) servers. How can teams control costs and prevent runaway agent loops? Teams can configure maxTurns directly within the SDK options to enforce turn limits on tasks. In enterprise environments, routing traffic through an AI gateway like Bifrost allows platform engineers to assign virtual keys with hard financial spending caps and rate limits, cutting off agent loops automatically if usage exceeds allocated budgets. Does the Claude Agent SDK support human-in-the-loop approvals? Yes, the SDK provides configurable permission modes such as plan and default, alongside custom permission callbacks. When an agent attempts an operation marked as sensitive, such as executing terminal commands or updating source files, the runtime halts and requests authorization before applying modifications. Getting Started with Production Agent Infrastructure The Claude Agent SDK provides a modern foundation for building autonomous AI agents that manipulate files, execute shell commands, and interact with complex developer toolchains. Moving these autonomous loops into production environments requires dedicated infrastructure to handle protocol translation, provider redundancy, and spend governance. Engineering teams deploying agentic systems at scale can explore the Bifrost overview, review documentation on governing CLI agents, inspect the open-source GitHub repository, or request a Bifrost demo to implement centralized multi-provider routing and security controls. Sources - Anthropic Claude Agent SDK TypeScript Repository: anthropics/claude-agent-sdk-typescript - Anthropic Claude Agent SDK Python Repository: anthropics/claude-agent-sdk-python - Model Context Protocol (MCP) Specification: modelcontextprotocol.io - Anthropic Research on Building Effective Agents: anthropic.com
State of AI Instruction Quality: Coding Agent Comparison Claude Code, Codex, Copilot, Cursor and Gemini are the five coding agents in the Q3 report. We compared them across the 10,000 most-starred repos that ship an instruction file, and put the companies that make them through the same check, using their own repos. Claude Code is everywhere. It's set up in 69 of the 100 most-starred repos and in 6 of the top 10. Copilot is in 26 of the top 100, Gemini in 11, Cursor in 7 and Codex in 3. The file Claude Code reads is losing anyway. One CLAUDE.md in five is a line or two telling the agent to go read AGENTS.md. Which coding agents the top repos use | Agent | Top 10 | Top 100 | Top 1,000 | All 10,000 | |---|--:|--:|--:|--:| | Claude Code | 6 | 69 | 646 | 6,030 | | AGENTS.md (shared) | 6 | 72 | 678 | 6,125 | | Copilot | 2 | 26 | 225 | 1,756 | | Gemini | 2 | 11 | 51 | 430 | | Cursor | 1 | 7 | 96 | 734 | | Codex | 0 | 3 | 32 | 162 | !Share of repos that set up each agent, in the 100 most-starred repos against the 9,784 of the 10,000 with a setup: Claude Code 69% against 61.6%, AGENTS.md 72% against 62.6%, Copilot 26% against 17.9%, Gemini 11% against 4.4%, Cursor 7% against 7.5%, Codex 3% against 1.7%. The most-starred repo in the set, freeCodeCamp, uses Copilot. React uses Claude Code. Gemini punches above its size at the top: 430 of the 10,000 set it up, and 11 of the top 100 do. Many repos don't pick one. 4,213 of the 9,784 with a setup (43.1%) use two or more coding agents, and the most common pairing is Claude Code plus AGENTS.md, in 2,399 repos. AGENTS.md is winning 998 of the 5,464 CLAUDE.md files in the 10,000 (18.3%) are 25 words or fewer and point at AGENTS.md. Going the other way, 39 of 6,128 AGENTS.md files point at CLAUDE.md. That's 26 to 1. 11.3% of GEMINI.md files point to AGENTS.md too, and 4.0% of Copilot's instructions files do. The CLAUDE.md files people do write are the least instruction-like main files of any agent. About a quarter of what's in them tells the agent what to do. The rest describes the project. !Median share of items in each agent's main file that are directives or constraints: CLAUDE.md 26.1%, GEMINI.md 35.2%, AGENTS.md 36.4%, Codex's AGENTS.md 38.1%, copilot-instructions.md 38.9%, .cursorrules 46.0%. Pointer files left out. Claude Code setups hedge less. The "should" and "try to" kind runs at a median 3.3 per 100 instructions, against 4.7 for the other agents. The instructions moved into skills While the debate is still ongoing between AGENTS.md and other provider-specific files, most of the instructions moved to a different location. Skills hold 42.3% of every directive and constraint in the set. All the main files together hold 31.3%. !Share of all directives and constraints in the 10,000: skills 42.3% (13,190 SKILL.md files plus their reference files), main files 31.3% (13,375 CLAUDE.md, AGENTS.md and other main files), everything else 26.4% (rules, sub-agents, commands). Peculiar oddity, but only a quarter of repos (2,348) have any skills, and 249 repos hold half of all skill instructions between them. There are almost as many SKILL.md files as main files: 13,190 against 13,375. They spread like packages, without a package manager. 977 SKILL.md files are byte-for-byte copies of one in another repo. The most-copied, frontend-design, sits unchanged in 14 repos. A fix upstream reaches none of the copies. Two names, one file, and copies drifting apart 3,562 repos carry main files for two or more agents. A third of them (1,246) keep the same text under two names, mostly a CLAUDE.md identical to the AGENTS.md beside it. Another third use a pointer. !How the 3,562 repos with main files for two or more agents relate the second file to the first: the same text under two names 1,246 repos (35.0%), a pointer to the other file 1,158 (32.5%), different files 937 (26.3%), copies drifting apart 221 (6.2%). 221 repos keep two copies that have already drifted. The typical pair shares 32 lines, and each side has two or three lines the other lacks. In 92 of 430 Gemini setups (21.4%), GEMINI.md and AGENTS.md hold the same text, and Gemini reads both. For the other agents, the same shape turns up in 1.3% of setups. Gemini setups are also the heaviest at startup: 8.1% hand the agent more than 5,000 words before the first prompt, against 2.3% across the field. Cursor goes the other way. 66.3% of Cursor setups carry rule files, and a third (33.5%) have no main file at all. The other agents' setups almost always have one. The makers, by their own repos | Company | Agent | Repos in the 10,000 | Median score | Share of repos with custom sub-agents | |---|---|--:|--:|--:| | Anthropic | Claude Code | 11 | 7.0 | 27% | | OpenAI | Codex | 13 | 6.8 | 0% | | Google | Gemini | 28 | 7.2 | 4% | | GitHub | Copilot | 11 | 7.9 | 45% | | Cursor | Cursor | 2 | 8.6 | 0% | | All repos | | 10,000 | 7.5 | 5.7% | The scores cluster around the field's. What each company builds is where they split. !Which agents each company sets up in its own repos: Anthropic, 11 repos: Claude Code 11, AGENTS.md 1, Copilot 0, Gemini 0, Cursor 0. OpenAI, 13 repos: Claude Code 2, AGENTS.md 12, Copilot 1, Gemini 0, Cursor 0. Google with its Gemini orgs, 28 repos: Claude Code 5, AGENTS.md 15, Copilot 1, Gemini 18, Cursor 1. GitHub, 11 repos: Claude Code 1, AGENTS.md 5, Copilot 10, Gemini 0, Cursor 0. Cursor, 2 repos: Claude Code 0, AGENTS.md 1, Copilot 0, Gemini 0, Cursor 2. GitHub builds its own agents. 5 of its 11 repos ship custom sub-agents, eight times the field's rate of 5.7%. One of them is spreading: an agentic-workflows sub-agent for GitHub's own workflow tool sits in 44 repos across the 10,000, the second most common sub-agent role after code-reviewer. The agents' own repos shout too. A third of the 10,000 write rules in capitals. Anthropic's prompting guide tells users of its newest models to dial back that kind of language: "Where you might have said 'CRITICAL: You MUST use this tool when...', you can use more normal prompting like 'Use this tool when...'." Claude Code's own repo ships a triage command that says "IMPORTANT: Don't post any comments or messages to the issue." Codex's own AGENTS.md says "Features that change the agent logic MUST add an integration test", and a Gemini CLI command tells the agent "you MUST first consult the getting started documentation". OpenAI's repos leave the agent guessing. Of every writing habit we compared across the makers, only one difference held up statistically. OpenAI's median repo leaves 48.7 of every 100 instructions without a file, command or tool to act on, against 30.8 for the field. One of its SDKs opens a section with: > Solve the narrow problem with the simplest implementation. Avoid unrelated refactors, reformatting, dependency or lockfile churn, generated-file edits, speculative abstractions, compatibility shims, and capabilities not requested. A senior engineer would agree with every word. An agent gets two judgment calls, "the narrow problem" and "the simplest implementation", and nothing to check its work against. Cursor's two repos score highest, 8.6, with the fewest instructions left vague. One still carries the hedged kind, a skill that says "subtask_prompt should read like a standalone request". Who checks the makers These companies write the agents, the documentation and the prompting guides. Their engineers know their codebases far better than any tool does, and that's how the gaps get in. To the person who wrote it, "the narrow problem" has an obvious answer. The agent reading the file has the file, and nothing else. The agent can't flag the gap either. It does what the line says, and when the line names nothing, it guesses. A company reviewing its own files reads them with the same knowledge that left the gap there. ails check reads every instruction file with the same deterministic rules, whoever wrote it. The 10,000 most-starred repos and the companies that build the agents get the same treatment, and the findings above are what came back. !Lines 26 to 41 of the AGENTS.md in OpenAI's openai-node repo, the section "Keep changes small and coherent", with ails check's Specificity Gap finding beside seven of its lines: 28, 31, 32, 34, 36, 37 and 38. Line 28 reads "Solve the narrow problem with the simplest implementation." Check one yourself Every repo in this post is public. Clone one and run the same check: npx @reporails/cli check It lists each finding by file, so you can read the instructions and decide whether we counted fairly. This is the last post from the Q3 report. The data behind all of them is in the 2026-Q3 folder of reporails/reports. --- From The State of AI Instruction Quality: Q3 2026: 10,000 of the most-starred GitHub repos that ship an instruction file, September 2026 snapshot; 9,784 have a setup we could map. "Top 100" and "top 1,000" rank the 10,000 by stars at the snapshot. A setup is one repo and one agent; repos often have several, so agent counts add up to more than the repos. Codex counts repos with a Codex marker in .codex/ (a config.toml, rules/, agents/ or hooks.json) or an AGENTS.override.md; a plain AGENTS.md setup sits in the shared row. A pointer is a main file of 25 words or fewer that names or imports another agent's main file. Items are what the instrument maps from a file; directives and constraints are the items that tell the agent what to do. "Skills" include the reference files beside SKILL.md; setups above the batch's 90-file cap are outside the run, so the skills share is a floor. "The same text" cannot tell a symlink from a copy; only the drifted pairs are certainly two files. "Gemini reads both" is the instrument's model of Gemini, which concatenates AGENTS.md and GEMINI.md. Companies are the GitHub organizations that ship each agent: anthropics, openai, google with google-gemini and gemini-cli-extensions, github and cursor; Cursor's two repos carry no test. Group differences are two-sided Mann-Whitney or Fisher's exact tests, read against a Bonferroni threshold for all 209 comparisons in the run; the top-100 shares are counts. Scores are each company's median repo score on ails check's 0 to 10 scale; for Anthropic, OpenAI, Google and GitHub the 95% bootstrap interval includes the field's 7.5. Vague instructions name no file, command or tool (CORE:C:0042), per 100 directives and constraints, in repos with at least 5. Repos measured. anthropics: anthropic-sdk-typescript, buffa, claude-agent-sdk-python, claude-code, claude-code-action, claude-code-base-action, claude-for-legal, commerce-agents, defending-code-reference-harness, financial-services, launch-your-agent. openai: apps-sdk-ui, codex, codex-security, harmony, openai-agents-js, openai-cli, openai-cookbook, openai-dotnet, openai-go, openai-java, openai-node, openai-python, realtime-voice-component. google: adk-go, adk-java, adk-python, benchmark, clusterfuzz, comprehensive-rust, docsy, dotprompt, filament, go-github, gvisor, heir, mantis, nomulus, oss-fuzz, osv-scanner, osv.dev, perfetto, play-services-plugins, sam, site-kit-wp, syzkaller, xls. google-gemini: gemini-cli. gemini-cli-extensions: code-review, nanobanana, security, workspace. github: branch-deploy, codeql, codeql-action, copilot-cli-for-beginners, copilot-sdk, docs, gh-aw, gh-skyline, gh-stack, github-mcp-server, spec-kit. cursor: community-plugins, cookbook. --- I work on Reporails, deterministic diagnostics and governance for the instruction files, rules, and prompts that steer coding agents. It reads the instruction files your coding agent loads, from CLAUDE.md to Copilot and Cursor rules, measures which instructions couple to behavior, and points to the lines worth tightening.
oh-my-mermaid × Codex で Anthropic・OpenAI の公式リポジトリ5つを構成図にしてみた はじめに oh-my-mermaid(omm)は、Claude Code や Codex などの AI コーディングツールにスキルを登録し、リポジトリを解析させて Mermaid の構成図と説明を .omm/ フォルダに残す CLI です。 Anthropic と OpenAI の公式リポジトリ5つを、同じ条件で omm+Codex CLI に解析させ、できた図を並べてみました。 結論 - 5つとも1回で構成図と日本語の説明ができ、omm validate(図の文法・規約の検査)も全件通った - 1リポジトリあたり 68〜89秒、3.2万〜4.7万トークン(5つで約21.6万トークン) - 図を並べると、Claude Agent SDK は「Claude Code CLI をサブプロセスで動かす薄い層」、OpenAI Agents SDK は「Runner がモデル・ツール・履歴・トレースを束ねる自前の実行系」と、設計の違いがひと目でわかった - 費用を抑えるため「観点は3つまで・2段まで」に制限したので、15万行の SDK でも図は5〜7ノードの粗い要約になる 環境 - WSL2 の Ubuntu 22.04(隔離した試用環境) - oh-my-mermaid 0.2.0、Codex CLI 0.162.1(OpenAI の API キーで実行) 手順 前提: Codex CLI を OpenAI の API キーで動かすため、環境変数 CODEX_API_KEY に API キーを設定済みであること(キーの値はここには書きません)。解析ごとに API の料金がかかります。 npm install -g oh-my-mermaid@0.2.0 @openai/codex@0.162.1 omm setup codex # ~/.agents/skills/oh-my-mermaid/ にスキルを登録 git clone --depth 1 https://github.com/anthropics/claude-agent-sdk-python.git cd claude-agent-sdk-python omm config language ja # 説明を日本語にする codex exec --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox \ "Use the omm-scan skill (~/.agents/skills/oh-my-mermaid/omm-scan/SKILL.md) to scan this repository (focus on the src/claude_agent_sdk package) and generate .omm/ documentation. To limit cost: choose at most 3 perspectives, recurse at most 2 levels below each perspective, and keep each field short. Do not run the project's code or install anything." \ < /dev/null > ../scan.log 2>&1 omm status omm validate - プロンプトの括弧内(解析の対象)だけをリポジトリごとに変えました - --dangerously-bypass-approvals-and-sandbox は承認なしでコマンドを実行させるオプションです。今回は使い捨ての隔離環境の中なので使いました。普段の PC では使わないでください 結果 | リポジトリ | 対象の規模(Python) | 秒 | トークン | 観点 | 図 | |---|---|---|---|---|---| | anthropics/claude-agent-sdk-python | 26ファイル・13,295行 | 86 | 47,259 | 2 | 6 | | anthropics/anthropic-sdk-python | 2,288ファイル・155,171行 | 85 | 43,285 | 2 | 7 | | anthropics/claude-code | 22ファイル・7,914行+プラグイン等 | 89 | 46,626 | 2 | 8 | | openai/openai-agents-python | 320ファイル・135,502行 | 71 | 47,227 | 3 | 4 | | openai/swarm | 6ファイル・512行 | 68 | 31,587 | 2 | 3 | 観点(perspective)は AI が選びます。全件で全体構成(overall-architecture)が選ばれ、ほかにデータの流れ(data-flow)、リクエストの流れ(request-lifecycle)、拡張点(extension-points)が選ばれました。 規模が300倍違っても、時間・トークン数はほぼ同じでした。上限をかけたため、大きいリポジトリほど粗く要約されるということです。 Claude Agent SDK(Python) graph LR public-api["公開API\nsrc/claude_agent_sdk/"] runtime["非同期実行\nsrc/claude_agent_sdk/_internal/"] transport["通信\nsrc/claude_agent_sdk/_internal/transport/"] session-services["セッション管理\nsrc/claude_agent_sdk/_internal/session*.py"] sdk-tools["SDKツール\nsrc/claude_agent_sdk/__init__.py"] contracts["型・例外\nsrc/claude_agent_sdk/types.py"] public-api -->|"実行を委譲"| runtime runtime -->|"制御・入出力"| transport public-api -->|"履歴APIを公開"| session-services runtime -->|"再開・ミラー保存"| session-services sdk-tools -->|"MCPサーバーを提供"| runtime public-api -->|"型を公開"| contracts 通信層の実体は SubprocessCLITransport(Claude Code CLI をサブプロセスで起動)で、create_sdk_mcp_server で Python の関数を MCP ツールとして渡せる、という構造がソースと一致しました。 OpenAI Agents SDK(Python) graph LR agent-definition["Agent 定義\nsrc/agents/agent.py"] runtime["実行制御\nsrc/agents/run.py"] models["モデル接続\nsrc/agents/models/"] tools["ツールと MCP\nsrc/agents/tool.py"] state["履歴と再開\nsrc/agents/memory/"] tracing["トレース\nsrc/agents/tracing/"] media["音声経路\nsrc/agents/realtime/"] agent-definition -->|"設定を渡す"| runtime runtime -->|"応答を要求"| models runtime -->|"呼び出しを実行"| tools runtime -->|"履歴を読書き・中断を保存"| state runtime -->|"スパンを記録"| tracing media -->|"共通トレースを利用"| tracing Claude Agent SDK がエージェントのループを CLI 側に任せるのに対し、こちらは Runner(run.py)が自前でループを回し、履歴(SQLite などのセッション)やトレースまで持っています。 Anthropic SDK(Python) graph LR client["公開クライアント\nsrc/anthropic/_client.py"] resources["API リソース\nsrc/anthropic/resources/"] transport["共通通信基盤\nsrc/anthropic/_base_client.py"] schemas["型とモデル\nsrc/anthropic/types/"] helpers["高水準の補助機能\nsrc/anthropic/lib/"] client -->|"リソースを公開"| resources client -->|"継承して通信"| transport resources -->|"HTTP 操作を委譲"| transport resources -->|"入出力型を参照"| schemas transport -->|"応答モデルを構築"| schemas helpers -->|"クライアントを拡張"| client resources -->|"stream・parse を利用"| helpers 懸念(concern)の欄に「生成 API と手書き補助層が混在」と書かれました。15万行の大半は自動生成のコードで、図では resources/ の1ノードにまとまっています。 Claude Code(公開リポジトリ) graph LR plugins["公開プラグイン\nplugins/"] examples["導入例\nexamples/"] automation["運用自動化\nscripts/; .github/"] mods["組み込み mod\nmods/"] dev-environment["開発環境\n.devcontainer/; Script/"] claude-host["Claude Code ホスト\n外部配布 CLI"] plugins -->|"拡張を読み込む"| claude-host examples -->|"設定・導入のひな形"| claude-host mods -->|"組み込みフックを提供"| claude-host automation -->|"Action・mod 検証で利用"| claude-host dev-environment -->|"実行環境を用意"| claude-host 公開リポジトリには CLI 本体の実装が無く、プラグインや周辺資産が中心です。omm も説明に「CLI 本体の実装全体ではなく、周辺資産と mods のソースを収録」と正しく書きました。 Swarm graph LR public-api["公開 API\nswarm/__init__.py"] core["実行エンジン\nswarm/core.py"] models["データ型\nswarm/types.py"] utilities["補助関数\nswarm/util.py"] repl["対話ループ\nswarm/repl/repl.py"] public-api -->|"Swarm・Agent・Response を公開"| core public-api -->|"型を公開"| models core -->|"状態と戻り値を表現"| models core -->|"スキーマ化・差分結合・ログ"| utilities repl -->|"run を呼び出す"| public-api 制約の欄に「呼び出し間の状態は呼び出し側が保持。永続ストアや HTTP サーバーはない」とあり、教育用の軽量フレームワークという性格をよく表しています。 内容はソースと合っているか 全部は確認していませんが、各リポジトリで1〜2点を grep で抜き取り確認し、すべて一致しました。 | リポジトリ | 図の関係 | ソース | |---|---|---| | claude-agent-sdk-python | 通信は CLI のサブプロセス | _internal/transport/subprocess_cli.py の class SubprocessCLITransport(Transport) | | claude-agent-sdk-python | SDK が MCP サーバーを提供 | __init__.py の def create_sdk_mcp_server( | | anthropic-sdk-python | クライアントが通信基盤を継承 | _client.py の class Anthropic(SyncAPIClient) | | openai-agents-python | 実行制御がトレースを記録 | run.py の run_state.set_trace(get_current_trace()) | | swarm | 対話ループが run を呼ぶ | repl/repl.py の client.run( | 所感 - 知らない SDK を読み始める前の「入口の地図」として便利です。5つとも同じ形(観点・図・説明)で出るので、横に並べて比べやすいのが良い点でした - 説明は1〜2文と短めです。大きいリポジトリを深く知りたいときは、上限を緩めるか、サブフォルダごとに解析するのがよさそうです(未確認) - 結果はテキストなので git で管理でき、omm diff で前回の図との差分も見られます - 注意: ビューア(omm view)は試した版(0.2.0)では全インターフェースで待ち受けました。共有のネットワークで使うときは気を付けてください 参考 - oh-my-mermaid/oh-my-mermaid - anthropics/claude-agent-sdk-python - anthropics/anthropic-sdk-python - anthropics/claude-code - openai/openai-agents-python - openai/swarm