Claude Managed Agents Tutorial: Build a Hosted Agent in Python

If you’ve shipped an agent with the Claude Agent SDK or the OpenAI Agents SDK, you know the tax: a while loop around the model call, a tool dispatcher, a Docker sandbox, secret injection, and crash recovery β€” all before your agent does anything useful.

On April 8, 2026, Anthropic shipped Claude Managed Agents in public beta β€” a hosted agent platform that moves the loop, the sandbox, and the credential boundary off your machine. The core product is enabled by default for every API account, per the overview docs β€” no waitlist for the base functionality.

This claude managed agents tutorial walks through the minimum viable Python implementation β€” four SDK calls and an event loop β€” and explains one lifecycle pattern in the official Python quickstart that looks backwards at first glance.

What Managed Agents Actually Replaces

All of that scaffolding collapses into four SDK namespaces: client.beta.agents, client.beta.environments, client.beta.sessions, and the events stream hanging off sessions. Managed Agents is to the Claude Agent SDK what hosted Postgres is to self-managed Postgres β€” the harness, the sandbox, and the credential boundary become Anthropic’s problem.

If you need a headless Linux container for code and data tasks, this is the tool. If you need a virtual desktop with a mouse and keyboard, that’s still the Claude Computer Use API. The core product is enabled by default on every API account; three advanced features β€” outcomes, multi-agent, and memory β€” are gated behind a research-preview request.

The Four Concepts You Need Before Writing a Line of Code

The official overview is built around four concepts. Internalize these and the SDK stops looking arbitrary.

  1. Agent β€” a reusable, versioned configuration bundling the model, system prompt, tools, MCP servers, and skills. Create once, reuse across sessions.
  2. Environment β€” a cloud container template with pre-installed runtimes (Python, Node, Go) and network rules. Create once per deployment.
  3. Session β€” one running instance tying an agent to an environment for one task. Create per task.
  4. Events β€” the bidirectional SSE stream. User turns go in; agent messages, tool uses, and status updates come out. Persisted server-side.

The SDK splits these into three resource namespaces because they have three genuinely different lifecycles. Agents and environments are infrastructure you provision; sessions are the per-task ephemerals that ride on top. The SDK auto-injects the managed-agents-2026-04-01 beta header, so you only think about it when debugging raw HTTP.

Claude Managed Agents Tutorial: The Fibonacci Quickstart

Install the SDK and export your key:

pip install anthropic
export ANTHROPIC_API_KEY=sk-ant-...

Here is the full working example, adapted from the official quickstart. It asks Claude to write a Fibonacci script to a file, then run it.

from anthropic import Anthropic

client = Anthropic()

# 1. Create the agent (reusable config)
agent = client.beta.agents.create(
    name="fib-writer",
    model="claude-sonnet-4-6",
    system="You are a careful Python developer. Write code to files, then run it.",
    tools=[{"type": "agent_toolset_20260401"}],
)

# 2. Create the environment (cloud container template)
environment = client.beta.environments.create(
    name="fib-env",
    config={"type": "cloud", "networking": {"type": "unrestricted"}},
)

# 3. Create the session (agent + environment, one task)
session = client.beta.sessions.create(
    agent=agent.id,
    environment_id=environment.id,
    title="Fibonacci to file",
)

# 4. Open the stream inside a with-block, then send the user message
with client.beta.sessions.events.stream(session.id) as stream:
    client.beta.sessions.events.send(
        session.id,
        event={
            "type": "user.message",
            "content": [{"type": "text", "text":
                "Write a Python script that prints the first 20 Fibonacci "
                "numbers to fibonacci.txt, then run it."}],
        },
    )

    for event in stream:
        if event.type == "agent.message":
            for block in event.content:
                if block.type == "text":
                    print(block.text)
        elif event.type == "agent.tool_use":
            print(f"[tool] {event.name}")
        elif event.type == "session.status_idle":
            break

Five steps, under forty lines. The agent creates fibonacci.txt via the write tool, runs it via bash, and emits session.status_idle when finished. Your loop handles three event types: agent.message for Claude’s text, agent.tool_use for tool invocations, and session.status_idle as the signal to break.

Illustration: claude managed agents tutorial

Why the Python Quickstart Opens the Stream First

Read step four again. The Python example opens the stream before it sends the user message β€” the opposite of every other Anthropic SDK call, which is plain request/response. Ordering is not load-bearing: Anthropic’s bash example sends first and streams second, and the API buffers events until a consumer attaches, so nothing is lost either way. The Python quickstart still picks stream-first for a lifecycle reason.

The with block is a context manager, and Python context managers exist to guarantee cleanup. If the agent crashes, your process dies, or the task finishes early, the stream connection closes deterministically on block exit. Putting the send call inside that block also keeps the data flow linear top-to-bottom β€” open, send, iterate, exit β€” instead of stranding a send statement a few lines above an async iterator it’s semantically tied to.

Locking Down the Toolset

That one-line agent_toolset_20260401 declaration enables eight tools by default: bash, read, write, edit, glob, grep, web_fetch, and web_search. Convenient for demos, but the Fibonacci task only needs bash and write. Everything else is unnecessary blast radius.

Flip to opt-in mode per the tools reference:

tools=[{
    "type": "agent_toolset_20260401",
    "default_config": {"enabled": False},
    "configs": [
        {"name": "bash", "enabled": True},
        {"name": "write", "enabled": True},
    ],
}]

Anthropic’s engineering post on the sandbox architecture explains that credentials are held structurally outside the container where Claude-generated code runs β€” git tokens wired into local remotes at provisioning, custom-tool OAuth reached via an MCP proxy. As the Anthropic team puts it, “the harness doesn’t know whether the sandbox is a container, a phone, or a PokΓ©mon emulator.” You still decide which tools are live.

What This Costs β€” and How to Structure Production Code

Runtime pricing is $0.08 per active session-hour on top of standard Sonnet 4.6 token rates, per the Claude Platform pricing page. “Active” means wall-clock while the session is running; once session.status_idle fires, the runtime meter stops.

Put that in context. A three-minute Fibonacci task costs $0.004 in runtime β€” less than a single Sonnet 4.6 request. An hour of deep research costs eight cents. You are paying a rounding error to skip building a sandbox.

For production code, split provisioning from execution. Agents and environments are versioned, reusable resources β€” not per-task throwaways. A provisioning script creates the agent and environment once, writes their IDs to config, and exits. A session script loads those IDs and spins up sessions per task. Re-creating agents on every request wastes the versioning and walks straight into the 60-creates-per-minute org rate limit.

What’s Still Coming: Research-Preview Features

Three features sit behind a research-preview request form: outcomes (agents self-evaluate against success criteria and iterate β€” Anthropic’s internal testing showed up to 10-point improvement on structured file tasks), multi-agent (agents coordinate parallel work, overlapping in scope with Anthropic’s own Google ADK tutorial territory), and memory (cross-session persistence).

Outcomes is the most interesting of the three. Instead of babysitting a long-running agent with custom eval code, you declare what success looks like and let the harness iterate until the criteria hit or a budget trips. It’s the same pattern that makes test-driven development productive β€” write the assertion first, let the tool converge β€” and it pushes the most fragile part of production agent work (deciding when to stop) onto Anthropic’s side of the wire. Multi-agent opens parallel coordination without you wiring the message bus. Memory extends the event log across sessions so a researcher agent can pick up where yesterday left off. None are required to ship a working agent today, but they signal where the platform is going.

Where Managed Agents Lands

The managed harness is locked to Anthropic’s implementation β€” that’s the whole point, and also the whole risk. The question nobody can answer yet: is the versioned Agent/Environment/Session model expressive enough for the workflows teams actually want to run, or do developers hit the edges of the hosted harness and end up back in self-hosted territory?

The stream context manager in the Python quickstart is the giveaway. Managed Agents is stateful infrastructure β€” an append-only event log with a harness attached β€” not a dressed-up request/response API. See sessions that way and the rest of the SDK stops looking arbitrary: versioned agents, durable sessions, crash recovery via event replay, buffered events. It’s the only shape that fits.

The catalyst to watch is outcomes and multi-agent graduating from research preview to general access. That’s when the hosted platform gets decisively more powerful than the self-hosted Agent SDK for production workloads β€” and when every team still running their own while loop will need a reason to keep doing so.

Get the Daily Pulse

Sharp analysis on what's actually moving in AI. No hype, no filler, no weekly digest.

Get the Daily Pulse

Sharp AI analysis, daily. Two minutes, every morning.

Get the Daily PulseTwo minutes, every morning