← Back to list

Claude Agent Management

Claude Agent Management is not just a single agent feature and Claude Managed Agents for a pre-built hosted agent runtime that handles…

DhanushKumar in Artificial Intelligence in Plain English · 2026-05-03 08:01 · 0 claps · 8.3 min read
#claude #anthropic-claude #agent-management #claude-code #multi-agent-systems
Open on Medium ↗
Wiki topics: LLM · Large Language Models AGT · AI Agents BIZ · Business Strategy

Claude Agent Management

Claude Agent Management is not just a single agent feature and Claude Managed Agents for a pre-built hosted agent runtime that handles long-running , asynchronous work in managed infrastructure .Managed Agents layer:a hosted runtime for building agents that need to work for minutes or hours, keep session state, execute tools in a secure container, and stream progress back to your application. The platform is organized around four primitives: Agent, Environment, Session, and Events. At the platform level, the managed-agent story is built around four core objects.An Agent holds the model choice, system prompt, tools, MCP servers, and skills. An Environment defines the container template and runtime settings such as packages and networking. A Session is the live running instance of an agent inside an environment, and it preserves conversation history while the task executes. Events are the messages exchanged between your application and the session, including user turns, tool results, and status updates.

Why this matters

The reason this is a real platform feature, and not just “another agent wrapper,” is that Anthropic is explicitly solving the hard operational parts for you: sandboxing, tool execution, persistent event history, session lifecycle, and streamed observability.The Managed Agents as the right choice for long-running execution , secure cloud infrastructure , stateful sessions , where you don’t want to build the own agent loop and sandboxing layer from scratch.

The practical results is that just stop thinking in terms of “one prompt, one response” and start thinking in terms of a managed workflow. On definng the behavior once, runtime constraints once, then launch many isolated sessions for many tasks or users.That separation is what makes the system reusable , auditable and much easier to operate in production.

The core mental model

The agent is the reusable configuration object. It is versioned, and then can pin a session to a specific agent version for reproducibility and staged rollouts.The environment is the reusable runtime template. Multiple sessions can share the same environment , but every session gets its own isolated container instance.The session is the actual execution unit , and it starts in idle , transitions to running , can briefly enter rescheduling and ends in terminated when execution cannot continue . Events are the lifecycle stream to use to drive and observe everything the agent does.

This event model is important because it makes agent behaviour explicit. The user sends a user.message event to start or steer work and receive agent.message, agent.tool_use, session.status_idle, session.status_terminated, and other event types back for observability. Also Anthropic states that event type strings follow a {domain}.{action} convention and that each event includes a processed_at timestamp so that can reason about ordering and queueing.

Workflow architecture

At a system level, the worflow is straightforward : the application cretes or reuses an agent , creates or reuses an environment , starts a session , sends a user event , streams session events , handle any tool confirmations or custom tool results, fetches outputs and archives the session when the work is done and also Anthropic’s docs show that session are state machines driven by events and the event stream is delivered over server-sent events so that the user can watch the run live.

The backend is ususally the orchestrator and claude managed agents is the execution plane.The backend owns authentication , business rules , user mapping and access control . The claude runtime owns the container , the agent loop , the tool execution context and the event stream .That division is what keeps the application secure and composable.

The backend is ususally the orchestrator and claude managed agents is the execution plane.The backend owns authentication , business rules , user mapping and access control . The claude runtime owns the container , the agent loop , the tool execution context and the event stream .That division is what keeps the application secure and composable.

Example :an autonomous data analysis agent

A strong example is a data analyst agent. Anthropic’s cookbook shows exactly this pattern: create a reusable cloud environment with data libraries preinstalled, create a reusable agent with a system prompt tailored for narrative analysis, upload a CSV as a file resource, mount that file into the session, send a user message asking for the analysis, stream the run, and retrieve the generated report from session outputs.

This use case is useful because it exercises the full lifecycle. The environment is where you control runtime dependencies such as Python packages and network access. The agent is where you encode analysis style, output format, and tool policy. The session is where the dataset is mounted and the actual analysis happens. The outputs directory is where the final report is persisted, and the event stream is how you watch the analysis unfold in real time.

Security, scalability, and observability in production

The most important security control is the environment network policy.Anthropic supports unrestricted networking, but for production they explicitly recommend an allowist approach instead of broad internet access.Vault then handle third party credentials at the session level , which means the user dont have to ship tokens through the prompts or keep the own secret store for every workflow.Anthropic also says token refresh is managed for OAuth-style MCP credentials.

From a scalability perspective, the desin is deliberately reusable . Then create an environment once and reuse it , create an agent once and reuse it , then start new sessions for each task or user interaction. Anthropic also exposes cumulative usage on the session object , including input tokens , otuput tokens , and prompt caching counters which lets the user build a cost control and usage alerts the acutal execution history.

From an observability perspective , the event stream is the source of truth .Anthropic’s console exposes session traces , token counts ,even history , and tool execution details and the APIs let tstreams or list events programmatically . That means it cn log progress , debug failures and inspect tool calls , then build operational dashboards without guessing what the agent did.

Skills, MCP, and extensibility

Skills are reusable , filesystem based expertise that the agent invokes when relevant. Also Anthropic supports both pre-built skills and custom skills and the docs note a max of 20 skills per session across all participating agents. In practice , skills are lever for specializing an agent in domains like Excel analysis , document generation or organization specific workflows without bloating the core system prompt .

If the agent needs to interact with the external systems through MCP , vaults become even more important because the session can reference stored credentials at creation time.Anthropic also documents a multi-agent pattern where multiple agents can share the same container and filesystem while keeping separate session threads and context isolation.That is useful for co-ordinator worker designs and where one agent plans and another executes.

Python code Implementation

"""
End-to-end Claude Managed Agents example.

This script:
1. Creates a reusable environment.
2. Creates a reusable agent.
3. Uploads a CSV file.
4. Starts a session and mounts the CSV.
5. Sends a user message to begin analysis.
6. Streams the event loop until the session goes idle.
7. Lists and downloads the generated report.
8. Archives the session and reusable resources.

Requirements:
    pip install "anthropic>=0.91.0" python-dotenv
    export ANTHROPIC_API_KEY="..."
"""

from __future__ import annotations

import os 
from pathlib import Path 
from typing import Optional

from anthropic import Anthropic
from dotenv import load_dotenv

MODEL = "claude-sonnet-4-6"
BETA = "managed-agents-2026-04-01"

class ManagedAgentsDemoError(RuntimeError):
    """Raised when the managed agents workflow fails."""

def _require_api_key() -> None:
    """Ensure the Anthropic API key is present in the environment."""
    if not os.getenv("ANTHROPIC_API_KEY"):
        raise ManagedAgentsDemoError(
            "ANTHROPIC_API_KEY is missing. Set it before running this script."
        )

def create_environment(client: Anthropic):
    """
    Create a reusable cloud environment with Python libraries preinstalled.

    Returns:
        The created environment object.
    """
    try:
        return client.beta.environments.create(
            name="blog-demo-data-analyst-env",
            config={
                "type": "cloud",
                "networking": {
                    "type": "limited"
                },
                "packages": {
                    "type": "packages",
                    "pip": ["pandas", "plotly"],
                },
            },
        )
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to create environment: {exc}") from exc

def create_agent(client: Anthropic):
    """
    Create a reusable agent for data analysis.

    Returns:
        The created agent object.
    """
    system_prompt = """
You are a senior data analyst producing a concise but publication-quality report.
Read the mounted dataset, identify the key patterns, write the report clearly,
and save the final HTML artifact into /mnt/session/outputs/report.html.
"""

    try:
        return client.beta.agents.create(
            name="blog-demo-data-analyst",
            model=MODEL,
            system=system_prompt.strip(),
            tools=[
                {
                    "type": "agent_toolset_20260401",
                    "default_config": {
                        "enabled": True,
                        "permission_policy": {"type": "always_allow"},
                    },
                    "configs": [
                        {"name": "web_search", "enabled": False},
                        {"name": "web_fetch", "enabled": False},
                    ],
                }
            ],
        )
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to create agent: {exc}") from exc

def upload_csv(client: Anthropic, csv_path: Path):
    """
    Upload a CSV file to Anthropic file storage.

    Args:
        client: Anthropic API client.
        csv_path: Path to the CSV file.

    Returns:
        The uploaded file object.
    """
    if not csv_path.exists():
        raise ManagedAgentsDemoError(f"CSV file does not exist: {csv_path}")

    try:
        with csv_path.open("rb") as f:
            return client.beta.files.upload(
                file=(csv_path.name, f, "text/csv")
            )
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to upload CSV: {exc}") from exc

def create_session(client: Anthropic, env_id: str, agent_id: str, agent_version: int, file_id: str, csv_name: str):
    """
    Create a session and mount the uploaded CSV into the container.

    Returns:
        The created session object.
    """
    mount_path = f"/mnt/session/uploads/{csv_name}"

    try:
        return client.beta.sessions.create(
            environment_id=env_id,
            agent={"type": "agent", "id": agent_id, "version": agent_version},
            resources=[
                {
                    "type": "file",
                    "file_id": file_id,
                    "mount_path": mount_path,
                }
            ],
            title="Managed Agents blog demo",
        )
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to create session: {exc}") from exc

def send_user_task(client: Anthropic, session_id: str, mount_path: str) -> None:
    """
    Send the agent its task prompt.
    """
    prompt = f"""
Analyze the CSV mounted at {mount_path}.

Produce:
1. Revenue by category.
2. Revenue by region.
3. One anomaly worth investigating.
4. A short management summary.

Write the final report to /mnt/session/outputs/report.html.
"""

    try:
        client.beta.sessions.events.send(
            session_id=session_id,
            events=[
                {
                    "type": "user.message",
                    "content": [{"type": "text", "text": prompt.strip()}],
                }
            ],
        )
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to send task event: {exc}") from exc

def wait_for_idle(client: Anthropic, session_id: str) -> None:
    """
    Stream events until the session becomes idle.

    This is the simplest streaming pattern for a run that does not require
    custom tool approvals or custom tool callbacks.
    """
    try:
        with client.beta.sessions.events.stream(session_id) as stream:
            for ev in stream:
                if ev.type == "agent.message":
                    for block in ev.content:
                        if block.type == "text":
                            print(block.text, end="", flush=True)
                elif ev.type in ("agent.tool_use", "agent.mcp_tool_use"):
                    print(f"\n[{ev.name}]")
                elif ev.type == "session.status_idle":
                    return
                elif ev.type == "session.status_terminated":
                    raise ManagedAgentsDemoError(
                        "Session terminated unexpectedly before reaching idle."
                    )
    except Exception as exc:
        if isinstance(exc, ManagedAgentsDemoError):
            raise
        raise ManagedAgentsDemoError(f"Streaming failed: {exc}") from exc

def download_report(client: Anthropic, session_id: str, output_dir: Path) -> Path:
    """
    Download report.html from the session output scope.
    """
    try:
        outputs = client.beta.files.list(
            scope_id=session_id,
            betas=[BETA],
        )
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to list session outputs: {exc}") from exc

    report = next((f for f in outputs.data if f.filename == "report.html"), None)
    if report is None:
        raise ManagedAgentsDemoError("report.html was not produced by the session.")

    try:
        content = client.beta.files.download(report.id)
        output_dir.mkdir(parents=True, exist_ok=True)
        target_path = output_dir / "report.html"
        target_path.write_bytes(content.read())
        return target_path
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to download report.html: {exc}") from exc

def cleanup(client: Anthropic, session_id: str, env_id: str, agent_id: str) -> None:
    """
    Archive session, environment, and agent after the run.

    Archiving preserves history while preventing new events.
    """
    try:
        client.beta.sessions.archive(session_id)
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to archive session: {exc}") from exc

    try:
        client.beta.environments.archive(env_id)
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to archive environment: {exc}") from exc

    try:
        client.beta.agents.archive(agent_id)
    except Exception as exc:
        raise ManagedAgentsDemoError(f"Failed to archive agent: {exc}") from exc

def main() -> None:
    """
    Execute the full managed-agents workflow end to end.
    """
    load_dotenv()
    _require_api_key()

    client = Anthropic()
    csv_path = Path("sales_data.csv")

    env = create_environment(client)
    agent = create_agent(client)
    dataset = upload_csv(client, csv_path)

    session = create_session(
        client=client,
        env_id=env.id,
        agent_id=agent.id,
        agent_version=agent.version,
        file_id=dataset.id,
        csv_name=csv_path.name,
    )

    mount_path = f"/mnt/session/uploads/{csv_path.name}"
    send_user_task(client, session.id, mount_path)
    wait_for_idle(client, session.id)

    report_path = download_report(client, session.id, Path("./artifacts"))
    print(f"\nDownloaded report to: {report_path}")

    cleanup(client, session.id, env.id, agent.id)
    print("Cleaned up by archiving session, environment, and agent.")

if __name__ == "__main__":
    main()

In this implementation the environment first, agent second, file upload third, session creation with mounted resources fourth, user.message event fifth, streaming loop sixth, output retrieval from /mnt/session/outputs/ seventh, and archive at the end.

Architectural trade-offs

The biggest trade-off is control versus convenience. Managed Agents gives you a hosted session model, built-in containers, event streaming, and resource lifecycle management, which removes a lot of infrastructure work. The trade-off is that you are operating inside Anthropic’s managed execution model, so if you need fully custom control over every tool call, every scheduling decision, or your own deployment topology, Anthropic recommends the Claude Agent SDK instead.

A second trade-off is between flexibility and guardrails. Unrestricted networking makes demos easy, but for production Anthropic recommends allowlisted networking. Skills and MCP add power, but they also increase context and operational complexity, so the right production design is usually a narrow agent, a tightly scoped environment, a small number of skills, and explicit session-level credentials.

A message from our Founder

Hey, Sunil here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.

If you want to show some love, please take a moment to follow me on LinkedIn, TikTok, Instagram. You can also subscribe to our weekly newsletter. And before you go, don’t forget to clap and follow the writer️!


메타데이터
post_id
b00eeca54484
slug
claude-agent-management-b00eeca54484
url
https://ai.plainenglish.io/claude-agent-management-b00eeca54484
canonical_url
https://ai.plainenglish.io/claude-agent-management-b00eeca54484
author_url
https://medium.com/@danushidk507
status
ok
fetched_at
2026-07-17 11:44:46