
Claude Managed Agents: Build a Long-Running Agent in Python
Summary
Stand up an autonomous agent with sessions, streaming events, and webhooks - no agent loop required.
Claude Managed Agents: Build a Long-Running Agent in Python
If you have ever wired up an agent by hand, you know the tax. You write the while-loop, parse tool calls, spawn a sandbox, stream deltas, checkpoint state so a crash does not lose an hour of work, and then babysit all of it in production. Claude Managed Agents is Anthropic's answer to that tax: a hosted agent harness that runs the loop, the sandbox, and the tool execution for you. You define an agent once, point a session at it, and send messages. Claude reads files, runs bash, browses the web, and executes code inside a managed sandbox until the task is done.
It is worth building now for two reasons. First, the harness went into open beta earlier this year behind the managed-agents-2026-04-01 header and is enabled by default on every API account, so there is nothing to request. Second, the July 2026 additions closed the two gaps that kept people on their own loops: lifecycle webhooks (get pinged when a session goes idle instead of polling) and per-session agent overrides (reuse one agent definition but swap the model or tools for a single run). This guide walks the whole path in Python: agent, environment, session, streaming, steering, cost tracking, and webhooks.
By the end you will have a working nightly repo-triage agent that reads a repository, writes a report, and notifies your service the moment it finishes - with real, doc-accurate code you can paste and run.
Prerequisites
- A Claude Console account and an API key from platform.claude.com/settings/keys.
- Python 3.9+ and the official SDK:
pip install anthropic(a version with beta Managed Agents support). - Optional: the
antCLI for quick one-off calls. Everything here also works from Python. - Basic familiarity with server-sent events (SSE). You do not need to implement SSE yourself; the SDK does it.
- The beta header
managed-agents-2026-04-01is required on every request. The SDK sets it automatically, so you rarely touch it directly.
The mental model: four objects
Managed Agents is built on four concepts. Keep them straight and the API stops feeling like magic:
| Object | What it is | Lifetime |
|---|---|---|
| Agent | Model + system prompt + tools + MCP servers + skills | Reusable, versioned |
| Environment | Where sessions run (cloud sandbox or self-hosted) | Reusable |
| Session | One running agent instance doing one task | Long-running, resumable |
| Events | Messages between your app and the agent | Streamed per session |
You create an agent and an environment once, then spin up as many sessions as you need. A session keeps its own conversation history and its own sandbox filesystem.
Step 1 - Install and authenticate
Set your key and construct the client. The client reads ANTHROPIC_API_KEY from the environment.
export ANTHROPIC_API_KEY="sk-ant-..."
pip install anthropic
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
# All Managed Agents calls live under client.beta.*
# The SDK adds the managed-agents-2026-04-01 beta header for you.
Step 2 - Create an agent
The agent is your reusable configuration. The agent_toolset_20260401 tool type turns on the full pre-built toolkit: bash, file read/write/edit/glob/grep, and web search and fetch. Save the returned agent.id - you reference it in every session.
agent = client.beta.agents.create(
name="Repo Triage Agent",
model={"id": "claude-opus-4-8"},
system=(
"You are a senior engineer doing repository triage. "
"Read the codebase, summarize what it does, flag risky files, "
"and write findings to report.md. Be concrete and cite file paths."
),
tools=[{"type": "agent_toolset_20260401"}],
)
print("agent id:", agent.id) # agnt_01...
# Agents are versioned. Passing the id as a string later uses the LATEST version.
Step 3 - Create an environment
The environment defines the sandbox. A cloud sandbox with unrestricted networking is the simplest starting point; lock the networking down later. Save the environment.id.
environment = client.beta.environments.create(
name="triage-env",
config={"type": "cloud", "networking": {"type": "unrestricted"}},
)
print("environment id:", environment.id) # envr_01...
Step 4 - Start a session and stream the work
A session has a two-step lifecycle. Creating it provisions the sandbox but does not start work. You start work by sending a user.message event. Open the stream first, then send the message inside it so you do not miss the first tokens.
session = client.beta.sessions.create(
agent=agent.id,
environment_id=environment.id,
title="Nightly triage - 2026-07-02",
)
print("session id:", session.id) # sesn_01...
with client.beta.sessions.events.stream(session.id) as stream:
# Send the task after the stream is open
client.beta.sessions.events.send(
session.id,
events=[{
"type": "user.message",
"content": [{
"type": "text",
"text": (
"Clone github.com/pallets/flask into the sandbox, read the "
"source, and write a 200-word triage report to report.md "
"listing the three files most worth reviewing and why."
),
}],
}],
)
for event in stream:
match event.type:
case "agent.message":
for block in event.content:
print(block.text, end="")
case "agent.tool_use":
print(f"\n[tool: {event.name}]")
case "session.status_idle":
print("\n\n-- agent finished --")
break
Example output (trimmed) looks like this. Notice the agent decides the tool sequence itself - you never told it to run git or write a file:
I'll clone the repo and read the source before writing the report.
[tool: bash]
[tool: bash]
[tool: read]
[tool: read]
Based on the source, the highest-signal files are app.py, blueprints.py,
and ctx.py. Writing the report now.
[tool: write]
report.md written (3 files flagged with rationale).
-- agent finished --
The key event is session.status_idle: the harness emits it when the agent has nothing left to do. That is your signal to stop reading the stream. Every event also carries a processed_at timestamp; a null value means the event is queued behind earlier ones.
Step 5 - Steer, inject context, and resume
Because the session persists, you can keep talking to it. Send another user.message to add a follow-up turn - the sandbox filesystem and history are still there:
client.beta.sessions.events.send(
session.id,
events=[{
"type": "user.message",
"content": [{"type": "text",
"text": "Now run the test suite and append pass/fail to report.md."}],
}],
)
To change system-level guidance mid-run - a new persona, a fresh constraint, runtime context - send a system.message event instead of a user turn. Unlike the fixed system field on the agent, this updates the prompt between turns:
client.beta.sessions.events.send(
session.id,
events=[{
"type": "system.message",
"content": [{"type": "text",
"text": "The user's timezone is America/New_York. Prefer concise output."}],
}],
)
# Note: system.message is currently only supported by Claude Opus 4.8, and cannot
# be sent while the session is idle waiting on a required action.
When a session goes idle its sandbox is checkpointed - filesystem, installed packages, created files - so you can resume cleanly later by sending another user.message. One gotcha: checkpoints live for 30 days after last activity. If a workflow needs the sandbox to survive longer, send a periodic message to reset the inactivity timer.
Step 6 - Track token usage and cost
The session object exposes cumulative token stats. Fetch the session after it idles and read usage to enforce budgets or log spend:
s = client.beta.sessions.retrieve(session.id)
u = s.usage
print(u.input_tokens, u.output_tokens,
u.cache_creation_input_tokens, u.cache_read_input_tokens)
# input_tokens = uncached input; output_tokens = total output across all model calls.
# Cache entries use a 5-minute TTL, so back-to-back turns get cheap cache reads.
A realistic single triage run prints something like 5000 3200 2000 20000: 5k fresh input tokens, 3.2k output, and 20k tokens served from cache instead of re-billed. That cache read is why keeping a session warm is cheaper than starting cold every turn.
Step 7 - Replace polling with webhooks
For a nightly job you do not want to hold an SSE stream open for hours. Webhooks are the fix: register an HTTPS endpoint in Console under Manage > Webhooks, subscribe to session events, and Anthropic pings you on state changes. Webhook payloads carry only the event type and id - you then fetch the full object by ID, which avoids stale data on retries.
from flask import Flask, request
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_WEBHOOK_SIGNING_KEY from env
app = Flask(__name__)
@app.route("/webhook", methods=["POST"])
def webhook():
try:
# unwrap() verifies the X-Webhook-Signature header and parses the body.
# It raises if the signature is invalid or the payload is >5 min old.
event = client.beta.webhooks.unwrap(
request.get_data(as_text=True),
headers=dict(request.headers),
)
except Exception:
return "invalid signature", 400
if event.data.type == "session.status_idled":
session = client.beta.sessions.retrieve(event.data.id)
notify_user(session) # your logic: Slack ping, DB write, etc.
return "", 204
The event body is small and predictable:
{
"type": "event",
"id": "event_01ABC...",
"created_at": "2026-07-02T14:05:22Z",
"data": {
"type": "session.status_idled",
"id": "sesn_01XYZ...",
"organization_id": "8a3d...",
"workspace_id": "c7b0..."
}
}
Two rules that bite people: ordering is not guaranteed (sort by created_at if it matters), and the top-level event.id is unique per event, not per delivery - if you see the same id twice, it is a retry, so make your handler idempotent and discard the duplicate.
Worked example: a nightly repo-triage agent
Put the pieces together into something you would actually schedule. Create the agent and environment once (store the IDs), then each night start a fresh session, kick off the task, and let a webhook tell you when the report is ready. The launcher stays tiny because the harness owns the loop:
import anthropic
client = anthropic.Anthropic()
AGENT_ID = "agnt_01..." # created once, in Step 2
ENV_ID = "envr_01..." # created once, in Step 3
def launch_nightly_triage(repo_url: str) -> str:
session = client.beta.sessions.create(
agent=AGENT_ID,
environment_id=ENV_ID,
title=f"triage {repo_url}",
)
client.beta.sessions.events.send(
session.id,
events=[{
"type": "user.message",
"content": [{"type": "text", "text":
f"Clone {repo_url}, review it, and write report.md with the "
f"top 3 files to review and any security smells you find."}],
}],
)
# Return immediately. The webhook handler from Step 7 fires on idle,
# fetches the session, and downloads report.md for you.
return session.id
if __name__ == "__main__":
sid = launch_nightly_triage("github.com/pallets/flask")
print("launched", sid)
That is the whole point of the harness: your code is a launcher and a webhook, not an agent runtime. Pin a specific agent version when you want reproducible runs by passing an object instead of a string: agent={"type": "agent", "id": AGENT_ID, "version": 1}.
Common pitfalls and gotchas
- Forgetting the two-step start. Creating a session does not run anything. No
user.messageevent means the sandbox sits provisioned and idle. Always send an event to begin work. - Opening the stream after sending the message. Send the first user event inside the open stream (as in Step 4). Reverse the order and you can miss the earliest
agent.messagetokens. - Waiting on the wrong stop condition. Break on
session.status_idle. If it carriesstop_reason: requires_action, the agent is blocked on a tool confirmation or custom tool result - handle those event IDs, do not treat it as done. - Assuming checkpoints are permanent. Sandbox checkpoints expire 30 days after last activity. Long-lived workflows must ping the session periodically or re-provision.
- Trusting webhook order or delivery-once. Ordering is best-effort and retries reuse
event.id. Sort bycreated_atand dedupe onevent.id. - Skipping signature verification. Always verify with
webhooks.unwrap()and setANTHROPIC_WEBHOOK_SIGNING_KEY. An endpoint that returns a 3xx redirect or points at a private IP gets auto-disabled. - Using system.message on the wrong model. Mid-conversation system injection is currently Opus 4.8 only; other models reject it with a
model_does_not_support_mid_conversation_systemerror. - Zero-data-retention assumptions. Managed Agents is stateful by design and is not currently ZDR or HIPAA BAA eligible. Delete sessions and uploaded files explicitly when you need cleanup.
Quick reference
| Task | Call |
|---|---|
| Create agent | client.beta.agents.create(name, model, system, tools) |
| Create environment | client.beta.environments.create(name, config) |
| Create session | client.beta.sessions.create(agent, environment_id, title) |
| Start / steer work | client.beta.sessions.events.send(id, events=[user.message]) |
| Stream responses | client.beta.sessions.events.stream(id) |
| Change prompt mid-run | events.send(system.message) # Opus 4.8 only |
| Read usage / cost | client.beta.sessions.retrieve(id).usage |
| Verify a webhook | client.beta.webhooks.unwrap(body, headers) |
| Done signal | event.type == 'session.status_idle' |
| Beta header | managed-agents-2026-04-01 (SDK sets it) |
Next steps
- Add MCP servers to the agent and authenticate them at session creation with
vault_ids, so Anthropic manages OAuth token refresh for you. - Add a permission policy so risky tools pause for a
user.tool_confirmationbefore running - useful when the agent can touch production. - Move recurring runs onto scheduled deployments (cron) instead of launching sessions yourself.
- Pin agent versions in production and stage new versions with per-session overrides before rolling them out.
- Wire the webhook handler to your existing alerting so a finished or errored session shows up where your team already looks.
You now have the full arc: define an agent, provision a sandbox, run a long-horizon task, steer it live, watch the cost, and get notified on completion without polling. The harness owns the loop so your code can stay a thin launcher - which is exactly what you want when an agent runs for an hour unattended.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,604 newsletter subscribers.