tainanfidelis' blogby Tainan Fidelis

Claude Managed Agents Tutorial: From Zero to Production in 15 Minutes

29 de abril de 2026

Claude Managed Agents Tutorial: From Zero to Production in 15 Minutes

I spent months building custom agent loops before Anthropic shipped Managed Agents on April 8. I’m talking: custom retry logic, session state serialization to Redis, my own heartbeat scheduler, tool call dispatch tables, error recovery handlers — all hand-rolled because there was no other way. It worked. It was also a full-time job just to keep the scaffolding running.

If you’re starting a Claude managed agents tutorial today, you’re getting in at the right time. Here’s what actually changed — and the two things I still wish were different.


What Is Claude Managed Agents?

Every team that builds agents eventually writes the same boilerplate: a loop that calls Claude, parses tool calls, executes tools, appends results, calls Claude again, and handles every edge case in between. Disconnections, token limits, rate limits, session state — you end up building an entire runtime just to run your agent.

Managed Agents is Anthropic’s answer to that. It’s a fully managed runtime for Claude agents — model, tools, and session state, all handled by the platform. You define the agent (system prompt, model, tools), call it via API, and the infrastructure disappears.

The positioning in the ecosystem looks like this:

| Layer | What it is | When to use | |---|---|---| | Raw Messages API | Call Claude directly, manage everything yourself | Maximum control, simple one-shot tasks | | Claude Agent SDK | Local orchestration library (Python/TS) | Custom workflows running on your infra | | Managed Agents | Cloud-hosted agents with managed state | Production agents where you want zero infra |

I use the Claude Agent SDK for local dev and Paperclip’s internal tooling. I use Managed Agents for anything customer-facing or anything that needs to run reliably without me babysitting a server.

The mental model: Managed Agents is like Lambda for agents. You define the function, the platform handles the rest.


Setting Up Your First Managed Agent (Python)

You need anthropic>=0.50.0 and a standard API key. No special signup — but you do need the beta header.

Note: Managed Agents launched April 8, 2026 and is in active beta. API shapes may change — check the official docs for the latest.

Install

pip install anthropic>=0.50.0

Create the agent

import anthropic
 
client = anthropic.Anthropic(
    api_key="your-api-key",
    default_headers={
        "anthropic-beta": "managed-agents-2026-04-01"
    }
)
 
agent = client.beta.agents.create(
    name="research-assistant",
    model="claude-opus-4-7",
    system_prompt="""You are a research assistant. When given a topic,
    you search for relevant information, summarize it, and return
    structured findings with source citations.
    
    Always respond in JSON with fields: summary, key_points, sources.""",
    tools=[
        {"type": "web_search"},
        {"type": "text_editor"}
    ]
)
 
print(f"Agent created: {agent.id}")
# Agent created: agt_01XyZaBcDeFgHiJk

Run it

session = client.beta.agents.sessions.create(
    agent_id=agent.id,
    metadata={"user_id": "usr_123", "task": "research"}
)
 
result = client.beta.agents.sessions.messages.create(
    agent_id=agent.id,
    session_id=session.id,
    messages=[{
        "role": "user",
        "content": "What are the main use cases for Claude Managed Agents in production?"
    }]
)
 
print(result.content[0].text)

What you get back is Claude’s final response after however many tool calls it decided to make internally. The agent SDK handles all the intermediate steps — you don’t see them unless you enable verbose logging.

The session_id is what I want you to pay attention to. More on that in a second.


Adding Tools and Memory

Built-in tools

Managed Agents ships with three built-in tools you don’t need to implement:

  • web_search — live web access via Anthropic’s search integration
  • text_editor — create, read, update files within the session sandbox
  • code_execution — run Python in an isolated environment, get stdout/stderr back

You can also define custom tools exactly like you would in the regular API:

agent = client.beta.agents.create(
    name="data-pipeline-agent",
    model="claude-sonnet-4-6",
    system_prompt="You process CSV data and return clean JSON.",
    tools=[
        {"type": "web_search"},
        {
            "name": "query_database",
            "description": "Query the production database and return rows as JSON",
            "input_schema": {
                "type": "object",
                "properties": {
                    "sql": {
                        "type": "string",
                        "description": "The SQL query to execute"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Max rows to return",
                        "default": 100
                    }
                },
                "required": ["sql"]
            }
        }
    ]
)

When the agent calls query_database, your code handles the tool execution and returns the result. The platform handles the loop.

Session persistence

This is the part I was most skeptical about — and the part that actually surprised me.

Sessions in Managed Agents persist across disconnections. If your API call times out at 30 seconds but the agent is still working, the session stays alive. You poll for completion or receive a webhook. Your agent doesn’t die.

import time
 
# Long-running task
session = client.beta.agents.sessions.create(
    agent_id=agent.id,
    metadata={"task_type": "deep_research"}
)
 
# Start the task
run = client.beta.agents.sessions.runs.create(
    agent_id=agent.id,
    session_id=session.id,
    messages=[{
        "role": "user",
        "content": "Analyze this 50-page report and extract all action items with owners and deadlines."
    }]
)
 
# Poll for completion (or use webhooks)
while run.status in ["in_progress", "queued"]:
    time.sleep(2)
    run = client.beta.agents.sessions.runs.retrieve(
        agent_id=agent.id,
        session_id=session.id,
        run_id=run.id
    )
 
print(run.output)

The session also maintains memory across messages within the same session. Send ten follow-up messages and the agent remembers everything from the first one. This is table stakes for any real workflow.

Structured outputs for reliability

In production, I always use structured outputs. Agents that return freeform text are debugging nightmares.

from pydantic import BaseModel
from typing import List
 
class ResearchOutput(BaseModel):
    summary: str
    key_points: List[str]
    confidence: float
    sources: List[str]
 
agent = client.beta.agents.create(
    name="structured-researcher",
    model="claude-opus-4-7",
    system_prompt="You are a research agent. Always respond with valid JSON matching the schema.",
    response_format={
        "type": "json_schema",
        "json_schema": ResearchOutput.model_json_schema()
    }
)

When you lock the output to a schema, you stop debugging malformed JSON at 2am. Worth it every time.


Multi-Agent Orchestration

Here’s where things get interesting — and where most tutorials stop too early.

Real production systems don’t have one agent. They have hierarchies: a parent agent that plans and delegates, worker agents that execute specific tasks, and sometimes a third tier for specialized subtasks. This is the pattern we run in Paperclip.

Spawning sub-agents from a parent

ORCHESTRATOR_PROMPT = """You are an orchestrator agent. Given a complex task:
1. Break it into parallel subtasks
2. Spawn a worker agent for each subtask using the spawn_agent tool
3. Wait for all workers to complete
4. Synthesize their outputs into a final result
 
Use spawn_agent when tasks can be done in parallel to save time."""
 
orchestrator = client.beta.agents.create(
    name="orchestrator",
    model="claude-opus-4-7",
    system_prompt=ORCHESTRATOR_PROMPT,
    tools=[
        {
            "name": "spawn_agent",
            "description": "Spawn a worker agent for a specific subtask. Returns the worker's output when complete.",
            "input_schema": {
                "type": "object",
                "properties": {
                    "task": {"type": "string", "description": "The specific task for this worker"},
                    "context": {"type": "string", "description": "Context and data the worker needs"}
                },
                "required": ["task"]
            }
        }
    ]
)

When the orchestrator calls spawn_agent, your tool handler creates a new Managed Agent session and returns its output:

def handle_spawn_agent(task: str, context: str = "") -> str:
    worker_session = client.beta.agents.sessions.create(
        agent_id=worker_agent.id
    )
    
    result = client.beta.agents.sessions.messages.create(
        agent_id=worker_agent.id,
        session_id=worker_session.id,
        messages=[{
            "role": "user",
            "content": f"Task: {task}
 
Context: {context}"
        }]
    )
    
    return result.content[0].text

The heartbeat → worker pattern

The architecture I run in Paperclip looks like this:

Heartbeat Scheduler
       │
       ▼
Orchestrator Agent (Managed)
  ├── plans work
  ├── spawns workers
  └── synthesizes results
         │
    ┌────┼────┐
    ▼    ▼    ▼
Worker  Worker  Worker
Agent   Agent   Agent
(write) (search) (review)

The orchestrator wakes on a schedule, picks up pending tasks from the issue board, spawns workers for parallel execution, and posts a synthesis comment when done. Each worker is a short-lived Managed Agent session — created, run, and discarded.

This pattern has three properties I care about:

  1. Stateless workers — each run starts fresh, no accumulated state bugs
  2. Natural parallelism — workers run concurrently, orchestrator waits
  3. Cost visibility — each session is billed separately, easy to trace

Passing context safely

Don’t pass raw data in the system prompt. Pass it in the first user message, structured:

def run_worker(task_data: dict) -> str:
    context = json.dumps(task_data, indent=2)
    
    result = client.beta.agents.sessions.messages.create(
        agent_id=worker_agent.id,
        session_id=session.id,
        messages=[{
            "role": "user",
            "content": f"""<task>
{task_data['instruction']}
</task>
 
<context>
{context}
</context>"""
        }]
    )
    return result.content[0].text

XML tags for structure, context in the message not the system prompt — this keeps your system prompt cacheable and reduces cost by 90% on repeat runs.


Cost and Performance Reality

The pricing is $0.08/session-hour. That’s the compute cost for the managed runtime on top of normal token costs.

In practice, here’s what a typical Paperclip heartbeat costs:

| Task | Session time | Runtime cost | Token cost (est.) | Total | |---|---|---|---|---| | Simple content review | ~45 sec | ~$0.001 | ~$0.004 | ~$0.005 | | Research + write 1500-word blog | ~8 min | ~$0.011 | ~$0.08 | ~$0.09 | | Multi-agent orchestration (5 workers) | ~12 min | ~$0.016 | ~$0.25 | ~$0.27 |

The session-hour cost is noise. The token cost is what you optimize.

Token usage in multi-agent chains

Every message in a chain carries the full conversation history. If your orchestrator talks to 5 workers and each worker has a 3-turn conversation, you’re paying for:

  • Orchestrator context (grows with each worker result appended)
  • Each worker’s own input context

Rough multiplier: 3–10x base token cost depending on chain depth and result verbosity.

How I manage this:

  1. Summarize, don’t append raw — workers return structured summaries, not full transcripts
  2. Cache the system prompt — use the cache_control header on static content
  3. Scope worker tasks tightly — a worker that does one thing produces less output

When Managed Agents beats self-hosted

Use Managed Agents when:

  • You need session persistence without building state infrastructure
  • You’re running parallel workflows and want isolation
  • You want Anthropic to handle rate limiting and retries
  • You’re moving fast and infra isn’t the product

Stick with the Claude Agent SDK (or roll your own) when:

  • You need custom scheduling logic that doesn’t fit the platform model
  • You’re processing high volumes where session-hour cost compounds
  • You have specific security/compliance requirements about where code runs
  • You need tight integration with local tooling or file systems

I use both. Managed Agents for the production-facing stuff, Agent SDK for the internal Paperclip plumbing.


Production Patterns and Gotchas

Idempotency in agent runs

Agents are not idempotent by default. If you retry a failed run, you might get double work. Fix this with idempotency keys:

import hashlib
 
def idempotent_run(agent_id: str, task: dict) -> str:
    # Derive a deterministic key from the task content
    task_hash = hashlib.sha256(json.dumps(task, sort_keys=True).encode()).hexdigest()[:16]
    
    session = client.beta.agents.sessions.create(
        agent_id=agent_id,
        metadata={
            "idempotency_key": task_hash,
            "task_id": task.get("id")
        }
    )
    
    # Check if this task already completed
    existing = find_completed_session(task_hash)  # your lookup logic
    if existing:
        return existing.output
    
    result = client.beta.agents.sessions.messages.create(
        agent_id=agent_id,
        session_id=session.id,
        messages=[{"role": "user", "content": json.dumps(task)}]
    )
    
    store_result(task_hash, result)  # your storage logic
    return result.content[0].text

Store your results keyed by the idempotency hash. Retry logic becomes: “did this task already succeed?” not “did this API call succeed?”

Handling long-running sessions

Anything over 2 minutes should use async polling, not synchronous calls. The platform will time out your HTTP connection before the agent finishes.

# Don't do this for long tasks:
result = client.beta.agents.sessions.messages.create(...)  # blocks until done
 
# Do this instead:
run = client.beta.agents.sessions.runs.create(
    agent_id=agent_id,
    session_id=session_id,
    messages=[{"role": "user", "content": task}],
    stream=False  # async mode
)
 
# Poll with backoff
for attempt in range(60):  # max 5 minutes at 5s intervals
    run = client.beta.agents.sessions.runs.retrieve(
        agent_id=agent_id,
        session_id=session_id,
        run_id=run.id
    )
    if run.status == "completed":
        break
    elif run.status == "failed":
        raise RuntimeError(f"Agent run failed: {run.error}")
    time.sleep(5)

Or set up webhooks and let Anthropic push the result. That’s cleaner for anything production.

Debugging: what the logs actually tell you

The run.steps field is your friend. It contains every tool call, every intermediate model response, and timing data. When something goes wrong:

run = client.beta.agents.sessions.runs.retrieve(
    agent_id=agent_id,
    session_id=session_id,
    run_id=run.id,
    include=["steps"]  # request step data
)
 
for step in run.steps:
    print(f"Step {step.index}: {step.type}")
    if step.type == "tool_use":
        print(f"  Tool: {step.tool_name}")
        print(f"  Input: {json.dumps(step.tool_input, indent=2)}")
        print(f"  Output: {step.tool_output[:200]}")
    print(f"  Duration: {step.duration_ms}ms")

Three things I look for when debugging:

  1. Tool input malformation — Claude passing wrong types or missing required fields
  2. Tool output verbosity — if a tool returns 10,000 tokens of output, the agent starts hallucinating by step 5
  3. Stalled steps — a step taking 10s longer than usual usually means a tool call is hanging

Trim your tool outputs. Return structured summaries, not raw data dumps. The agent performs better and costs less.


What I’d Tell Myself Six Months Ago

Build the structured output schema first. Not after you have a working agent — before. Every time I’ve skipped this and tried to parse freeform text “temporarily,” I paid for it in debugging time that was longer than building the schema would have been.

Start with the simplest possible agent and add tools one at a time. The failure modes compound quickly with tool count. An agent with 8 tools is 8 ways to misunderstand instructions.

And if you’re building anything multi-agent: the orchestrator’s system prompt is your architecture document. Write it like it matters, because it does.

If you want to go deeper on the foundations before building agents, my context engineering tutorial covers why and how Claude processes long context, and my MCP server tutorial shows how to expose your own tools reliably.


What’s Next

We’re building exactly this kind of stack inside DevFellowship — real AI engineering, with real systems, not toy demos. Fellows work on production agents, learn to architect multi-agent orchestration, and ship code that matters.

If you want to learn AI engineering by building real things, follow along. The next cohort opens soon.

— Tainan

Thanks,
Tainan Fidelis.


Edit on GitHub