How do I trace an agent built with the Claude Agent SDK and deployed to a Docker container?
Rius traces a Claude Agent SDK agent in Docker with one init call at startup, an observe wrapper per task and a manual generation filled from the run result. Call init once in the container’s entrypoint, name the agent with service_name, and shut the client down when the container stops. Each task then shows as a root agent span with a model call carrying tokens and cost.
How it works
The Claude Agent SDK drives the Claude Code runtime in a separate process, so no model client runs in your process and there is nothing for auto-instrumentation to hook. Coverage is manual and has two parts:
- An
observewrapper withkind=SpanKind.AGENTmakes each task the root span. Itsnameis the span name in the trace. - A manual generation wraps the
query()loop. You fill it from the run’sResultMessagewith token usage, the real model id and the answer. Rius computes cost on the server from the model and tokens.
A container changes three decisions:
- Where init runs. Call
rius.init()once, at module level in the file your container starts, before the first task. Nothing in the container needs a second call. - How spans leave. Spans are queued in the process and exported in batches from a background thread. On a normal Python exit, an exit hook drains what is left, but
docker stopsendsSIGTERM, and Python’s default response ends the process without running that hook. The SDK installs no signal handlers, so handleSIGTERMyourself. - What the agent is called.
service_namesets the service name, and the agent is grouped under it unless you setRIUS_AGENT_NAME.
The Claude Agent SDK integration is available in Python only. See Integrations for the full support matrix.
Set it up
-
Install the SDK and the framework in the image. The base SDK is enough, because no extra applies:
pip install glassflow-rius claude-agent-sdkThe
claudeCLI must also be installed and authenticated inside the container. The runtime uses whatever auth Claude Code has, and an exportedANTHROPIC_API_KEYtakes precedence over a claude.ai login. For the SDK itself,RIUS_API_KEYandRIUS_SERVICE_NAMEare read from the environment, so pass them as container environment variables from your secret store instead of writing them in code. -
Call
initonce at startup, wrap each task, and fill the generation from the result. Use a full model id such asclaude-haiku-4-5, not an alias likehaiku. Cost is computed from the requested model, and an alias gives a generation with no cost.import asyncio import signal import sys import rius from claude_agent_sdk import ( AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, query, ) from rius import SpanKind client = rius.init() # reads RIUS_API_KEY and RIUS_SERVICE_NAME signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) # runs the finally block MODEL = "claude-haiku-4-5" @rius.observe(name="handle-task", kind=SpanKind.AGENT) async def handle_task(task: str) -> str: options = ClaudeAgentOptions(model=MODEL, max_turns=1) parts = [] with rius.start_as_current_generation( "claude_agent_turn", model=MODEL, provider="anthropic", input=task ) as gen: async for message in query(prompt=task, options=options): if isinstance(message, AssistantMessage): parts.extend( b.text for b in message.content if isinstance(b, TextBlock) ) elif isinstance(message, ResultMessage): usage = message.usage or {} gen.set_usage( input_tokens=usage.get("input_tokens"), output_tokens=usage.get("output_tokens"), cache_read_input_tokens=usage.get("cache_read_input_tokens"), # Anthropic's payload still calls the write count "cache creation" cache_write_input_tokens=usage.get("cache_creation_input_tokens"), ) models = list((message.model_usage or {}).keys()) if models: gen.set_response_model(models[0]) answer = "".join(parts) gen.set_output(answer) return answer if __name__ == "__main__": try: print(asyncio.run(handle_task("Summarize today's open tickets"))) finally: client.flush(timeout_millis=30_000) # export before the container exits client.shutdown() # sends the final stopped heartbeatKeep
provider="anthropic"on the generation. With it,set_usage()adds the cache counts to the input tokens for you, so pass them as the snippet does. -
Pick the exit path that matches your container:
- Long-running worker or server: call
client.shutdown()from aSIGTERMhandler, or from your server’s shutdown hook if it already handles the signal, such as a FastAPI lifespan under uvicorn. - One-shot task container: flush and shut down in the
finallyblock, as above. TheSIGTERMhandler makesdocker stoprun that block. - Start the app in exec form (
CMD ["python", "app.py"]) so it is PID 1 and receives the signal. Docker waits 10 seconds beforeSIGKILL; raise that with--stop-timeoutorstop_grace_periodin Compose if needed. - Never call
flush()inside a request handler, because it blocks until the export completes.
- Long-running worker or server: call
-
Name the agent.
service_nameis the agent’s name on the Agents page. SetRIUS_AGENT_NAMEonly if you want a different grouping name. Use one stable name per agent, so every container you start groups under it.
For retries, queue limits and the batching variables, see Reliability. For what each part of the Claude Agent SDK maps to in a trace, see Claude Agent SDK.
What you get
- One trace per task: a root agent span named
handle-task, with a child model call namedclaude_agent_turnthat carries the model, tokens and cost. - Cost computed by Rius from the real model id and token counts, including cache reads and writes. Costs are list-price estimates in US dollars.
- In a long-running container, the agent appears on the Agents page at
init(), with one instance per process while the heartbeat is on and an API key is set. Callingshutdown()sends the finalstoppedping, so a clean exit looks different from a crash. - Spans that reach Rius when a one-shot container ends, because you flushed before exit.
The runtime’s inner work, such as tool calls, sub-turns and file operations, happens inside the Claude Code process and produces no spans. The generation records the turn’s totals only. A failed run does not raise: it ends with a ResultMessage whose is_error is true, so check that field if you want the task to fail.
When something else fits
- If your container runs a different framework or calls a model client directly, use that integration, which captures model calls without a manual generation.
- If you need to see tool calls inside the Claude Code runtime, this manual setup does not show them. It records the turn’s totals only.