Evals

Claude Agent SDK

Test Claude Agent SDK agents end to end, the real Claude Code child process included, with a scripted model behind a local server.

Adapter status: built and tested in TypeScript (@anthropic-ai/claude-agent-sdk 0.3) and Python (claude-agent-sdk 0.2). Install the Python extra with viewport-evals[claude-agent-sdk].

What is captured

The SDK runs Claude Code as a child process, so capture has two halves. Use query from the adapter in place of the SDK's own; it has the same signature.

  • Tool calls come from hooks merged into your options; your own hooks still run. PreToolUse starts a call, PostToolUse ends it with the result, PostToolUseFailure with the error. SubagentStart and SubagentStop become agent events, and calls made inside a subagent are parented to it.
  • Model calls come from the message stream: one model_call per assistant message id (a message streamed in several parts counts once), with input and cache tokens.
  • The result message gives output, and its total_cost_usd is spread over the model calls by output share, so budget.cost_usd uses the cost Claude Code reported.

capture(options) merges only the hooks, for code that cannot swap query; it records tool calls but not model calls.

Record and replay. The model traffic leaves from the child process, where in-process interception cannot reach. Inside a recording or replaying trace(), the adapter points the child at a local replay proxy through ANTHROPIC_BASE_URL for the life of the query. Nothing to configure.

Test an agent

script(...).claudeAgentSdk() / .claude_agent_sdk() serves the script over HTTP on 127.0.0.1; spread its env into the query's options and close it when done. Everything except the model is real: in this example the Claude Code child process reads a file, edits it and runs the repo's tests in a temp workspace.

main.py
# `query` from the adapter has the SDK's signature. It merges capture hooks into your options (yours still run) and
# reads model calls, cost and the final result from the message stream.
async def coding_agent(prompt: str, options: ClaudeAgentOptions) -> str | None:
    result = None
    async for message in query(prompt=prompt, options=options):  # read to the end, so the child process exits cleanly
        if isinstance(message, ResultMessage) and message.subtype == "success":
            result = message.result
    return result

main.ts
// `query` from the adapter has the SDK's signature. It merges capture hooks into your options (yours still run) and
// reads model calls, cost and the final result from the message stream.
async function codingAgent(prompt: string, options: Options): Promise<string | undefined> {
  for await (const message of query({ prompt, options })) {
    if (message.type === "result" && message.subtype === "success") return message.result;
  }
  return undefined;
}
main.py
def make_repo(root: Path) -> Path:
    """A tiny repo with a failing test: "Ride Report: Day 2!" slugifies to "ride-report--day-2"."""
    (root / "slug.py").write_text(
        'import re\n\n\ndef slugify(s):\n    return re.sub(r"[^a-z0-9]", "-", s.lower()).strip("-")\n'
    )
    (root / "test_slug.py").write_text(
        "import unittest\n\nfrom slug import slugify\n\n\n"
        "class SlugTest(unittest.TestCase):\n"
        "    def test_collapses_punctuation_runs(self):\n"
        '        self.assertEqual(slugify("Ride Report: Day 2!"), "ride-report-day-2")\n'
    )
    return root / "slug.py"

main.ts
// A tiny repo with a failing test: "Ride Report: Day 2!" slugifies to "ride-report--day-2".
const repo = mkdtempSync(join(tmpdir(), "viewport-coding-"));
afterAll(() => rmSync(repo, { recursive: true, force: true }));
const slug = join(repo, "slug.mjs");
writeFileSync(
  slug,
  `export const slugify = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "-").replace(/^-|-$/g, "");\n`,
);
writeFileSync(
  join(repo, "slug.test.mjs"),
  `import assert from "node:assert/strict";
import { test } from "node:test";
import { slugify } from "./slug.mjs";

test("collapses punctuation runs", () => assert.equal(slugify("Ride Report: Day 2!"), "ride-report-day-2"));
`,
);
main.py
async def test_fixes_the_slug_bug_and_runs_the_tests(tmp_path: Path) -> None:
    slug = make_repo(tmp_path)
    model = script(
        tool_call("Read", file_path=str(slug)),
        tool_call("Edit", file_path=str(slug), old_string='r"[^a-z0-9]"', new_string='r"[^a-z0-9]+"'),
        tool_call("Bash", command="python3 -m unittest", description="Run the tests"),
        reply("Fixed: slugify now collapses runs of punctuation into one dash. The test passes."),
        model="claude-sonnet-4-6",
    )

    with model.claude_agent_sdk() as server:  # serves the script; `env` points Claude Code at it
        options = ClaudeAgentOptions(
            cwd=tmp_path, permission_mode="bypassPermissions", setting_sources=[], env={**os.environ, **server.env}
        )
        # The model is a script, so there is nothing to record or replay.
        async with trace(fixture=False) as t:
            t.output = await coding_agent("The slug test fails. Fix slugify and run the tests.", options)

    assert t.tool_names == ["Read", "Edit", "Bash"]
    assert t.called("Edit", file_path=ends_with("slug.py"), new_string=contains("]+"))
    assert t.called("Bash", command=starts_with("python3 -m unittest"))
    assert not t.called("Write")
    assert len(t.model_calls) == 4
    assert t.meets({"budget": {"tokens": 4000, "cost_usd": 0.05}})

    # The edit really happened, and the real test run saw it.
    assert 'r"[^a-z0-9]+"' in slug.read_text()
    assert "OK" in json.dumps(t.calls("Bash")[0].result)
    model.assert_consumed()

main.ts
test("fixes the slug bug and runs the tests", async () => {
  const model = script(
    toolCall("Read", { file_path: slug }),
    toolCall("Edit", { file_path: slug, old_string: "[^a-z0-9]/g", new_string: "[^a-z0-9]+/g" }),
    toolCall("Bash", { command: "node --test", description: "Run the tests" }),
    reply("Fixed: slugify now collapses runs of punctuation into one dash. The test passes."),
    { model: "claude-sonnet-4-6" },
  );
  const server = await model.claudeAgentSdk(); // serves the script; `env` points Claude Code at it
  const options: Options = {
    cwd: repo,
    permissionMode: "bypassPermissions",
    allowDangerouslySkipPermissions: true,
    settingSources: [],
    env: { ...process.env, ...server.env },
  };

  // The model is a script, so there is nothing to record or replay.
  const t = await trace(() => codingAgent("The slug test fails. Fix slugify and run the tests.", options), {
    fixture: false,
  }).finally(() => server.close());

  expect(t.toolNames).toEqual(["Read", "Edit", "Bash"]);
  expect(t).toHaveCalledTool("Edit", { file_path: endsWith("slug.mjs"), new_string: contains("]+") });
  expect(t).toHaveCalledTool("Bash", { command: startsWith("node --test") });
  expect(t).not.toHaveCalledTool("Write");
  expect(t).toHaveModelCalls(4);
  expect(t).toBeWithinBudget({ tokens: 4000, cost_usd: 0.05 });

  // The edit really happened, and the real test run saw it.
  expect(readFileSync(slug, "utf8")).toContain("[^a-z0-9]+/g");
  expect(JSON.stringify(t.calls("Bash")[0]?.result)).toContain("pass 1");
  model.assertConsumed();
});

The test checks the tool sequence, the arguments of the edit and the test command, the round trips and budget, the file on disk and the real test output. The Claude Code binary is an optional platform dependency of the SDK; the examples need it installed.

On this page