| 1 |
# Message Helpers |
| 2 |
|
| 3 |
## Streaming Responses |
| 4 |
|
| 5 |
```python |
| 6 |
async with client.messages.stream( |
| 7 |
max_tokens=1024, |
| 8 |
messages=[ |
| 9 |
{ |
| 10 |
"role": "user", |
| 11 |
"content": "Say hello there!", |
| 12 |
} |
| 13 |
], |
| 14 |
model="claude-sonnet-5", |
| 15 |
) as stream: |
| 16 |
async for text in stream.text_stream: |
| 17 |
print(text, end="", flush=True) |
| 18 |
print() |
| 19 |
``` |
| 20 |
|
| 21 |
`client.messages.stream()` returns a `MessageStreamManager`, which is a context manager that yields a `MessageStream` which is iterable, emits events and accumulates messages. |
| 22 |
|
| 23 |
Alternatively, you can use `client.messages.create(..., stream=True)` which returns an |
| 24 |
iterable of the events in the stream and uses less memory (most notably, it does not accumulate a final message |
| 25 |
object for you). |
| 26 |
|
| 27 |
The stream will be cancelled when the context manager exits but you can also close it prematurely by calling `stream.close()`. |
| 28 |
|
| 29 |
See an example of streaming helpers in action in [`examples/messages_stream.py`](examples/messages_stream.py). |
| 30 |
|
| 31 |
> [!NOTE] |
| 32 |
> The synchronous client has the same interface just without `async/await`. |
| 33 |
|
| 34 |
### Lenses |
| 35 |
|
| 36 |
#### `.text_stream` |
| 37 |
|
| 38 |
Provides an iterator over just the text deltas in the stream: |
| 39 |
|
| 40 |
```py |
| 41 |
async for text in stream.text_stream: |
| 42 |
print(text, end="", flush=True) |
| 43 |
print() |
| 44 |
``` |
| 45 |
|
| 46 |
### Events |
| 47 |
|
| 48 |
The events listed here are just the event types that the SDK extends, for a full list of the events returned by the API, see [these docs](https://docs.anthropic.com/en/api/messages-streaming#event-types). |
| 49 |
|
| 50 |
```py |
| 51 |
from anthropic import AsyncAnthropic |
| 52 |
|
| 53 |
client = AsyncAnthropic() |
| 54 |
|
| 55 |
async with client.messages.stream( |
| 56 |
max_tokens=1024, |
| 57 |
messages=[ |
| 58 |
{ |
| 59 |
"role": "user", |
| 60 |
"content": "Say hello there!", |
| 61 |
} |
| 62 |
], |
| 63 |
model="claude-sonnet-5", |
| 64 |
) as stream: |
| 65 |
async for event in stream: |
| 66 |
if event.type == "text": |
| 67 |
print(event.text, end="", flush=True) |
| 68 |
elif event.type == 'content_block_stop': |
| 69 |
print('\n\ncontent block finished accumulating:', event.content_block) |
| 70 |
|
| 71 |
print() |
| 72 |
|
| 73 |
# you can still get the accumulated final message outside of |
| 74 |
# the context manager, as long as the entire stream was consumed |
| 75 |
# inside of the context manager |
| 76 |
accumulated = await stream.get_final_message() |
| 77 |
print("accumulated message: ", accumulated.to_json()) |
| 78 |
``` |
| 79 |
|
| 80 |
#### `text` |
| 81 |
|
| 82 |
This event is yielded whenever a text `content_block_delta` event is returned by the API & includes the delta and the accumulated snapshot, e.g. |
| 83 |
|
| 84 |
```py |
| 85 |
if event.type == "text": |
| 86 |
event.text # " there" |
| 87 |
event.snapshot # "Hello, there" |
| 88 |
``` |
| 89 |
|
| 90 |
#### `input_json` |
| 91 |
|
| 92 |
This event is yielded whenever a JSON `content_block_delta` event is returned by the API & includes the delta and the accumulated snapshot, e.g. |
| 93 |
|
| 94 |
```py |
| 95 |
if event.type == "input_json": |
| 96 |
event.partial_json # ' there"' |
| 97 |
event.snapshot # '{"message": "Hello, there"' |
| 98 |
``` |
| 99 |
|
| 100 |
#### `message_stop` |
| 101 |
|
| 102 |
The event is fired when a full Message object has been accumulated. |
| 103 |
|
| 104 |
```py |
| 105 |
if event.type == "message_stop": |
| 106 |
event.message # Message |
| 107 |
``` |
| 108 |
|
| 109 |
#### `content_block_stop` |
| 110 |
|
| 111 |
The event is fired when a full ContentBlock object has been accumulated. |
| 112 |
|
| 113 |
```py |
| 114 |
if event.type == "content_block_stop": |
| 115 |
event.content_block # ContentBlock |
| 116 |
``` |
| 117 |
|
| 118 |
### Methods |
| 119 |
|
| 120 |
#### `await .close()` |
| 121 |
|
| 122 |
Aborts the request. |
| 123 |
|
| 124 |
#### `await .until_done()` |
| 125 |
|
| 126 |
Blocks until the stream has been read to completion. |
| 127 |
|
| 128 |
#### `await .get_final_message()` |
| 129 |
|
| 130 |
Blocks until the stream has been read to completion and returns the accumulated `Message` object. |
| 131 |
|
| 132 |
#### `await .get_final_text()` |
| 133 |
|
| 134 |
> [!NOTE] |
| 135 |
> Currently the API will only ever return 1 content block |
| 136 |
|
| 137 |
Blocks until the stream has been read to completion and returns all `text` content blocks concatenated together. |
| 138 |
|
| 139 |
## MCP Helpers |
| 140 |
|
| 141 |
This SDK provides helpers for integrating with [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers. These helpers convert MCP types to Anthropic API types, reducing boilerplate when working with MCP tools, prompts, and resources. |
| 142 |
|
| 143 |
> **Note:** The Claude API also supports an [`mcp_servers` parameter](https://docs.anthropic.com/en/docs/agents-and-tools/mcp) that lets Claude connect directly to remote MCP servers. |
| 144 |
> |
| 145 |
> - Use `mcp_servers` when you have remote servers accessible via URL and only need tool support. |
| 146 |
> - Use the MCP helpers when you need local MCP servers, prompts, resources, or more control over the MCP connection. |
| 147 |
|
| 148 |
> **Requires:** `pip install anthropic[mcp]` (Python 3.10+) |
| 149 |
|
| 150 |
### Using MCP tools with tool_runner |
| 151 |
|
| 152 |
```py |
| 153 |
from anthropic import AsyncAnthropic |
| 154 |
from anthropic.lib.tools.mcp import async_mcp_tool |
| 155 |
from mcp import ClientSession |
| 156 |
from mcp.client.stdio import stdio_client, StdioServerParameters |
| 157 |
|
| 158 |
client = AsyncAnthropic() |
| 159 |
|
| 160 |
async with stdio_client(StdioServerParameters(command="mcp-server")) as (read, write): |
| 161 |
async with ClientSession(read, write) as mcp_client: |
| 162 |
await mcp_client.initialize() |
| 163 |
|
| 164 |
tools_result = await mcp_client.list_tools() |
| 165 |
runner = await client.beta.messages.tool_runner( |
| 166 |
model="claude-sonnet-5", |
| 167 |
max_tokens=1024, |
| 168 |
messages=[{"role": "user", "content": "Use the available tools"}], |
| 169 |
tools=[async_mcp_tool(t, mcp_client) for t in tools_result.tools], |
| 170 |
) |
| 171 |
async for message in runner: |
| 172 |
print(message) |
| 173 |
``` |
| 174 |
|
| 175 |
> [!TIP] |
| 176 |
> If you're using the sync client, replace `async_mcp_tool` with `mcp_tool`. |
| 177 |
|
| 178 |
### Using MCP prompts |
| 179 |
|
| 180 |
```py |
| 181 |
from anthropic.lib.tools.mcp import mcp_message |
| 182 |
|
| 183 |
prompt = await mcp_client.get_prompt(name="my-prompt") |
| 184 |
response = await client.beta.messages.create( |
| 185 |
model="claude-sonnet-5", |
| 186 |
max_tokens=1024, |
| 187 |
messages=[mcp_message(m) for m in prompt.messages], |
| 188 |
) |
| 189 |
``` |
| 190 |
|
| 191 |
### Using MCP resources as content |
| 192 |
|
| 193 |
```py |
| 194 |
from anthropic.lib.tools.mcp import mcp_resource_to_content |
| 195 |
|
| 196 |
resource = await mcp_client.read_resource(uri="file:///path/to/doc.txt") |
| 197 |
response = await client.beta.messages.create( |
| 198 |
model="claude-sonnet-5", |
| 199 |
max_tokens=1024, |
| 200 |
messages=[{ |
| 201 |
"role": "user", |
| 202 |
"content": [ |
| 203 |
mcp_resource_to_content(resource), |
| 204 |
{"type": "text", "text": "Summarize this document"}, |
| 205 |
], |
| 206 |
}], |
| 207 |
) |
| 208 |
``` |
| 209 |
|
| 210 |
### Uploading MCP resources as files |
| 211 |
|
| 212 |
```py |
| 213 |
from anthropic.lib.tools.mcp import mcp_resource_to_file |
| 214 |
|
| 215 |
resource = await mcp_client.read_resource(uri="file:///path/to/data.json") |
| 216 |
uploaded = await client.files.upload(file=mcp_resource_to_file(resource)) |
| 217 |
``` |
| 218 |
|
| 219 |
### Error handling |
| 220 |
|
| 221 |
The conversion functions raise `UnsupportedMCPValueError` if an MCP value cannot be converted to a format supported by the Claude API (e.g., unsupported content type like audio, unsupported MIME type). |
| 222 |
|
| 223 |
# Self-Hosted Environment Runner |
| 224 |
|
| 225 |
For running a managed agent's tools locally against a self-hosted environment, the SDK exposes three pieces: |
| 226 |
|
| 227 |
- `client.beta.environments.work.worker(...)` — the full worker (an `EnvironmentWorker`; also |
| 228 |
constructible directly as `EnvironmentWorker(client, ...)` from `anthropic.lib.environments`): |
| 229 |
polls the environment for work, and for each claimed session sets up the workdir + downloads the |
| 230 |
session agent's skills, runs your tools against the session's `agent.tool_use` / |
| 231 |
`agent.custom_tool_use` events while heartbeating the work-item lease, force-stops the work on |
| 232 |
exit, and loops. `worker.handle_item(...)` |
| 233 |
runs that same per-item flow for a single work item you've already claimed; with no arguments it |
| 234 |
reads the work id / environment id / session id from `ANTHROPIC_WORK_ID` / |
| 235 |
`ANTHROPIC_ENVIRONMENT_ID` / `ANTHROPIC_SESSION_ID` and the environment key from |
| 236 |
`ANTHROPIC_ENVIRONMENT_KEY` (the env vars `ant worker poll --on-work` sets). `environment_id` |
| 237 |
passed to `worker()` is only needed by `run()`'s poll loop; `environment_key` is the worker's |
| 238 |
single credential — `handle_item()` falls back to the value passed to `worker()` and then to |
| 239 |
`ANTHROPIC_ENVIRONMENT_KEY`. Async only; built on `anyio`, so it works under either `asyncio` or |
| 240 |
`trio`. |
| 241 |
- `client.beta.sessions.events.tool_runner(...)` — the sessions-side counterpart to |
| 242 |
`client.beta.messages.tool_runner`: a `SessionToolRunner`, an async iterable that attaches to a |
| 243 |
session's event stream, runs the matching tool for each tool-call event — `agent.tool_use` |
| 244 |
(built-in tools) answered with `user.tool_result`, and `agent.custom_tool_use` (custom tools) |
| 245 |
answered with `user.custom_tool_result` — posts the result back, and yields one |
| 246 |
`DispatchedToolCall` per completed call. Use it directly when you want to observe each dispatch |
| 247 |
(the worker drives one internally). Async only. |
| 248 |
- `client.beta.environments.work.poller(...)` — the control-plane only piece: claims work items, |
| 249 |
ack's each one, and yields each claimed work item. Async only — available on `AsyncAnthropic` |
| 250 |
(its `worker(...)` companion is async too, so the sync client does not expose either). |
| 251 |
|
| 252 |
The standard `agent_toolset_20260401` implementations (`bash`, `read`, `write`, `edit`, `glob`, |
| 253 |
`grep`) plus the workdir/skills `AgentToolContext` live in `anthropic.lib.tools.agent_toolset`. |
| 254 |
|
| 255 |
The high-level worker is one object: |
| 256 |
|
| 257 |
```python |
| 258 |
import os, asyncio |
| 259 |
from anthropic import AsyncAnthropic |
| 260 |
from anthropic.lib.tools import beta_async_tool |
| 261 |
from anthropic.lib.tools.agent_toolset import beta_agent_toolset_20260401 |
| 262 |
|
| 263 |
client = AsyncAnthropic() |
| 264 |
|
| 265 |
|
| 266 |
@beta_async_tool |
| 267 |
async def deploy(target: str) -> str: |
| 268 |
... |
| 269 |
|
| 270 |
|
| 271 |
# `client.beta.environments.work.worker(...)` builds an `EnvironmentWorker`; you can also construct |
| 272 |
# one directly with `EnvironmentWorker(client, ...)` from `anthropic.lib.environments`. |
| 273 |
await client.beta.environments.work.worker( |
| 274 |
environment_id=os.environ["ANTHROPIC_ENVIRONMENT_ID"], |
| 275 |
environment_key=os.environ["ANTHROPIC_ENVIRONMENT_KEY"], |
| 276 |
workdir="/workspace", |
| 277 |
# `tools` is a fixed list or a factory invoked per session with that session's `AgentToolContext` |
| 278 |
# (use the factory form to bind `beta_agent_toolset_20260401` to the right session). Defaults to |
| 279 |
# `beta_agent_toolset_20260401(env)`. |
| 280 |
tools=lambda env: [*beta_agent_toolset_20260401(env), deploy], |
| 281 |
).run() # loops forever; cancel the task / wrap in asyncio.wait_for to bound it |
| 282 |
``` |
| 283 |
|
| 284 |
If you already hold a claimed work item — e.g. an `ant worker poll --on-work` script handed one to a |
| 285 |
fresh process — call `handle_item` to run just the per-item flow (build the workdir + skills, run the |
| 286 |
session's tools while heartbeating the lease, force-stop on exit). Inside that command the work id / |
| 287 |
environment id / session id / environment key are already in the environment, so the sandbox case is |
| 288 |
just: |
| 289 |
|
| 290 |
```python |
| 291 |
await client.beta.environments.work.worker(workdir="/workspace", tools=tools).handle_item() |
| 292 |
``` |
| 293 |
|
| 294 |
Pass the values explicitly when you have the objects in hand (e.g. you iterate the poller yourself): |
| 295 |
|
| 296 |
```python |
| 297 |
await client.beta.environments.work.worker(workdir="/workspace", tools=tools).handle_item( |
| 298 |
work_id=work.id, |
| 299 |
environment_id=work.environment_id, |
| 300 |
session_id=work.data.id, |
| 301 |
environment_key=environment_key, |
| 302 |
) |
| 303 |
``` |
| 304 |
|
| 305 |
If you want to observe each tool call (or wire up the workdir / poller yourself), use the |
| 306 |
session tool runner directly: |
| 307 |
|
| 308 |
```python |
| 309 |
from anthropic import AsyncAnthropic |
| 310 |
from anthropic.lib.tools.agent_toolset import AgentToolContext, beta_agent_toolset_20260401 |
| 311 |
|
| 312 |
client = AsyncAnthropic() |
| 313 |
|
| 314 |
async for work in client.beta.environments.work.poller( |
| 315 |
environment_id=..., environment_key=environment_key, |
| 316 |
): |
| 317 |
if work.data.type != "session": |
| 318 |
continue |
| 319 |
# Fetch the session once; passing `client` and `session` makes `AgentToolContext` download |
| 320 |
# each of the session agent's skills into `{workdir}/skills/<name>/` on enter. |
| 321 |
session = await client.beta.sessions.retrieve(work.data.id) |
| 322 |
async with AgentToolContext(workdir="/workspace", client=client, session=session) as env: |
| 323 |
async for call in client.beta.sessions.events.tool_runner( |
| 324 |
work.data.id, |
| 325 |
tools=beta_agent_toolset_20260401(env), |
| 326 |
environment_key=environment_key, |
| 327 |
): |
| 328 |
print(f"{call.name} -> {'error' if call.is_error else 'ok'}") |
| 329 |
``` |
| 330 |
|
| 331 |
`beta_agent_toolset_20260401(env)` returns a plain `list[BetaAsyncFunctionTool]`. Filter or extend |
| 332 |
it directly: |
| 333 |
|
| 334 |
```python |
| 335 |
from anthropic.lib.tools import beta_async_tool |
| 336 |
from anthropic.lib.tools.agent_toolset import beta_read_tool, beta_agent_toolset_20260401 |
| 337 |
|
| 338 |
tools = [*beta_agent_toolset_20260401(env), deploy] |
| 339 |
tools = [t for t in beta_agent_toolset_20260401(env) if t.name != "bash"] |
| 340 |
``` |
| 341 |
|
| 342 |
> **Run stateful tools under the session tool runner, not the Messages tool runner.** The `bash` |
| 343 |
> tool owns a persistent `/bin/bash` subprocess that is only torn down by its `close` cleanup hook. |
| 344 |
> Only `client.beta.sessions.events.tool_runner(...)` (the `SessionToolRunner`) and the |
| 345 |
> `EnvironmentWorker` built on it call that hook. `client.beta.messages.tool_runner(...)` does |
| 346 |
> **not** call `close`, so handing it this toolset leaks one orphaned shell per run. Use the |
| 347 |
> session tool runner / environment worker for the agent toolset, or drop `bash` (as in the second |
| 348 |
> line above) before passing the toolset to the Messages tool runner. |
| 349 |
|
| 350 |
> **Keep async tools non-blocking.** The environment worker heartbeats the work-item lease on the |
| 351 |
> same event loop that runs your async tools (`@beta_async_tool`), so a blocking call inside one can |
| 352 |
> cost the worker its lease. Push blocking or CPU-bound work to `anyio.to_thread.run_sync`, or write |
| 353 |
> a sync tool instead (`@beta_tool`, `BetaBuiltinFunctionTool`). Sync tools run on a worker thread |
| 354 |
> and may block freely, but must use `anyio.from_thread.run` to call async code. Each call has a |
| 355 |
> 150 s limit. A sync tool that runs past it is reported to the agent as timed out while its thread |
| 356 |
> keeps running, so a long-running sync tool should tolerate being called again before an earlier |
| 357 |
> run has returned. |
| 358 |
|
| 359 |
The `bash` tool runs an unrestricted `/bin/bash` and executes file operations and shell commands |
| 360 |
directly on the host. Run the worker inside a container or other isolation boundary you control. |
| 361 |
(The file tools — `read`/`write`/`edit`/`glob`/`grep` — confine to the workdir with a symlink-aware |
| 362 |
check, so they are safe without a sandbox; `bash` is not.) `bash` does not inherit the runner's |
| 363 |
`ANTHROPIC_*` credentials; pass `AgentToolContext(env=...)` to control the subprocess environment. |
| 364 |
|
| 365 |
See [`examples/managed-agents-self-hosted-sandbox-worker.py`](examples/managed-agents-self-hosted-sandbox-worker.py) for a complete example. |