Build a Claude Agent SDK agent on Steel
The Claude Agent SDK runs the agent loop of Claude Code in your program. Claude chooses a tool, the SDK runs it, and the result goes back to Claude. The agent starts with Claude Code's own tools, such as Bash and file editing. For a browser agent, you turn those off and give the agent your own tools as an in-process MCP server. The tools send Commands to a Steel session: Claude reads each page as a snapshot, and clicks and types on its elements by ref. Each page loads in a cloud browser, with the session's proxies, CAPTCHA solving and live view. The SDK has TypeScript and Python versions.
Before you begin
- Node.js 20 or later, or Python 3.10 or later.
- A Steel API key in the
STEEL_API_KEYenvironment variable. See API keys. - An Anthropic API key in the
ANTHROPIC_API_KEYenvironment variable. The Agent SDK reads it from there.
Install the Agent SDK and the Steel SDK. The tools send Commands with the Steel SDK, so you do not install Playwright.
npm install @anthropic-ai/claude-agent-sdk steel-sdk zodpython3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk steel-sdkSet up the integration
Give the agent browser tools
This program gives a Claude agent five browser tools over a Steel session.
import { createSdkMcpServer, query, tool } from "@anthropic-ai/claude-agent-sdk";
import Steel from "steel-sdk";
import { z } from "zod";
const steel = new Steel();
const session = await steel.sessions.create();
console.log("Session viewer:", session.sessionViewerUrl);
type Commands = Parameters<typeof steel.sessions.commands>[1]["commands"];
let after: string | undefined;
async function run(commands: Commands, mode: "snapshot" | "diff") {
const response = await steel.sessions.commands(session.id, { commands, after, observe: { mode } });
after = response.next ?? after;
const failed = response.results.find((result) => !result.ok);
const text = [
response.page ? `${response.page.title} (${response.page.url})` : "",
failed?.error ? `${failed.command} failed: ${failed.error.message}` : "",
response.observe?.snapshot ?? response.observe?.diff ?? "",
]
.filter(Boolean)
.join("\n");
return { content: [{ type: "text" as const, text }] };
}
try {
const steelTools = createSdkMcpServer({
name: "steel",
tools: [
tool(
"navigate",
"Open a URL. Returns the page as a snapshot: its text, and a ref such as e5 for each element that you can act on.",
{ url: z.string() },
({ url }) => run([{ command: "navigate", url }], "snapshot"),
),
tool("snapshot", "Read the current page again, as a snapshot with refs.", {}, () =>
run([{ command: "snapshot" }], "snapshot"),
),
tool(
"click",
"Click the element with this ref. Returns the lines of the snapshot that changed.",
{ ref: z.string() },
({ ref }) => run([{ command: "click", target: ref }], "diff"),
),
tool(
"fill",
"Replace the text in the field with this ref. Returns the lines of the snapshot that changed.",
{ ref: z.string(), value: z.string() },
({ ref, value }) => run([{ command: "fill", target: ref, value }], "diff"),
),
tool(
"press",
"Press a key, such as Enter, in the element that has focus. Returns the lines of the snapshot that changed.",
{ key: z.string() },
({ key }) => run([{ command: "press", key }], "diff"),
),
],
});
for await (const message of query({
prompt:
"Open https://demo.playwright.dev/todomvc, add the todos Buy milk and Walk the dog, mark Buy milk as completed, and report how many items are left.",
options: {
model: "claude-sonnet-5-5",
systemPrompt: [
"You operate a Steel cloud browser via tools.",
"Call navigate to open a URL. To act on an element, pass its ref from the latest snapshot.",
"Do not invent data.",
].join(" "),
mcpServers: { steel: steelTools },
tools: [],
allowedTools: ["mcp__steel__navigate", "mcp__steel__snapshot", "mcp__steel__click", "mcp__steel__fill", "mcp__steel__press"],
settingSources: [],
maxTurns: 20,
},
})) {
if (message.type === "result") {
console.log(message.subtype === "success" ? message.result : `Run ended: ${message.subtype}`);
}
}
} finally {
await steel.sessions.release(session.id);
}import asyncio
from typing import Any, Literal, Optional
from claude_agent_sdk import (
ClaudeAgentOptions,
ResultMessage,
create_sdk_mcp_server,
query,
tool,
)
from steel import AsyncSteel, omit
from steel.types import CommandParam
steel = AsyncSteel()
session_id = ""
after: Optional[str] = None
async def run(commands: list[CommandParam], mode: Literal["snapshot", "diff"]) -> dict[str, Any]:
global after
response = await steel.sessions.commands(
session_id, commands=commands, after=after or omit, observe={"mode": mode}
)
after = response.next or after
lines = []
if response.page:
lines.append(f"{response.page.title} ({response.page.url})")
for result in response.results:
if not result.ok and result.error:
lines.append(f"{result.command} failed: {result.error.message}")
if response.observe:
lines.append(response.observe.snapshot or response.observe.diff or "")
return {"content": [{"type": "text", "text": "\n".join(lines)}]}
@tool(
"navigate",
"Open a URL. Returns the page as a snapshot: its text, and a ref such as e5 "
"for each element that you can act on.",
{"url": str},
)
async def navigate(args: dict[str, Any]) -> dict[str, Any]:
return await run([{"command": "navigate", "url": args["url"]}], "snapshot")
@tool("snapshot", "Read the current page again, as a snapshot with refs.", {})
async def snapshot(args: dict[str, Any]) -> dict[str, Any]:
return await run([{"command": "snapshot"}], "snapshot")
@tool("click", "Click the element with this ref. Returns the lines of the snapshot that changed.", {"ref": str})
async def click(args: dict[str, Any]) -> dict[str, Any]:
return await run([{"command": "click", "target": args["ref"]}], "diff")
@tool(
"fill",
"Replace the text in the field with this ref. Returns the lines of the snapshot that changed.",
{"ref": str, "value": str},
)
async def fill(args: dict[str, Any]) -> dict[str, Any]:
return await run([{"command": "fill", "target": args["ref"], "value": args["value"]}], "diff")
@tool(
"press",
"Press a key, such as Enter, in the element that has focus. "
"Returns the lines of the snapshot that changed.",
{"key": str},
)
async def press(args: dict[str, Any]) -> dict[str, Any]:
return await run([{"command": "press", "key": args["key"]}], "diff")
TOOLS = [navigate, snapshot, click, fill, press]
options = ClaudeAgentOptions(
model="claude-sonnet-5-5",
system_prompt=(
"You operate a Steel cloud browser via tools. "
"Call navigate to open a URL. To act on an element, pass its ref from the latest snapshot. "
"Do not invent data."
),
mcp_servers={"steel": create_sdk_mcp_server(name="steel", tools=TOOLS)},
tools=[],
allowed_tools=[f"mcp__steel__{t.name}" for t in TOOLS],
setting_sources=[],
max_turns=20,
)
async def main():
global session_id
session = await steel.sessions.create()
session_id = session.id
print("Session viewer:", session.session_viewer_url)
try:
async for message in query(
prompt=(
"Open https://demo.playwright.dev/todomvc, add the todos Buy milk and Walk the dog, "
"mark Buy milk as completed, and report how many items are left."
),
options=options,
):
if isinstance(message, ResultMessage):
print(message.result if message.subtype == "success" else f"Run ended: {message.subtype}")
finally:
await steel.sessions.release(session.id)
asyncio.run(main())tool() defines each tool, and createSdkMcpServer() (create_sdk_mcp_server() in Python) serves them to the agent as the MCP server steel. The agent calls a tool by its full name, such as mcp__steel__click. Each tool sends one request with sessions.commands, through the run function, and returns its result as text. navigate and snapshot return the page as a snapshot, with a ref for each element. click, fill and press act on a ref, and return only the lines that changed. When a command fails, for example on a ref that left the page, Claude reads the error and can take a new snapshot.
run sends the next of the last response as after, so that a retried request runs its commands once. Build your own agent harness explains both fields. The program releases the session in finally.
Three options keep the agent to the browser:
tools: []turns off Claude Code's own tools, so the agent cannot run commands or edit files on your machine.allowedTools(allowed_tools) lets the agent call the five Steel tools without asking you for permission.settingSources: [](setting_sources=[]) keeps the SDK from loading your Claude Code settings, from~/.claudeand the project's.claudefolder. Without it, the SDK loads them, as Claude Code does.
Run the program
npx tsx agent.mtspython agent.pyThe program prints the session viewer URL first. Open it to watch Claude work in the browser.
Session viewer: https://app.steel.dev/sessions/2e506075-5aed-418b-8355-96d1e28276e9In the viewer, Claude types each todo into the field and presses Enter, then checks the box next to Buy milk. The program then prints Claude's answer: one item is left, Walk the dog. The wording changes from run to run.
Add tools and Steel features
- To give the agent more actions, add tools that send other commands, such as
select,scrollorwait, and add each new tool's full name toallowedTools. Commands reference lists each command and its fields. - To add Steel features, pass them to
steel.sessions.create(), for exampleuseProxy(use_proxy) for a Steel proxy andsolveCaptcha(solve_captcha) for CAPTCHA solving. The Agent SDK does not see them. Session configuration lists every option.
Next steps
- Claude Agent SDK documentation
- Cookbook starters: TypeScript and Python, with four tools that read GitHub's trending page.