import json, os, shutil, signal, sys, tempfile, threading, time
from fastcore.test import test_eq, test_fail
from unittest import mock
from claude_agent_sdk._internal.transport.subprocess_cli import SubprocessCLITransport
from fastcore.test import test_eq, test_failclaude
The wire
A turn either sends a message to a live Claude Code session or resumes a filed transcript with one query call. rishi calls the system prompt the briefing. It goes to Claude Code through Claude Code’s own system-prompt option.
By default, your tools travel as tags in the prompt. A managed MCP policy cannot remove them. Pass mcp_servers when Claude Code must reach an MCP server itself. Those tools run on Claude Code’s side, outside rishi’s approval, budget and result-length limits. rishi reports their calls in Resp.channels['server_tools'].
These defaults keep the backend working on locked-down machines:
strict_mcp_configis off for a turn. Enterprise configurations reject that flag. A one-shot turns it on, except on a machine with an enterprise MCP config (managed_mcp).api_key=FalseblanksANTHROPIC_API_KEYin the subprocess environment. The session then bills your subscription, not the API.api_key=Trueleaves the variable as it is.max_buffersets the limit on Claude Code’s output. The SDK rejects output that exceeds the configured limit instead of truncating it.
| limit | bytes |
|---|---|
| SDK default | 1 MiB (1048576) |
MAX_BUFFER, the rishi default for max_buffer |
10 MiB (10485760) |
The constants below are pinned model ids. claude_model accepts the short keys of CLAUDE_MODELS, such as 'opus5'. It passes the CLI’s own aliases (opus, sonnet, haiku, fable) through unchanged. Each alias follows the newest model of its tier on your plan. With no model, a chat uses opus5, which is claude-opus-5.
norm_claude converts Claude Code’s result to a Resp. A failed turn raises ClaudeError. ClaudeError carries the HTTP status when one can be found, and a caller can use it to decide whether to retry. A cancelled turn is not an error. The reply is whatever arrived before the cancel.
claude_version asks the binary for its version and gives it /dev/null as stdin. Claude Code is a Node program. A Node program that shares the caller’s terminal can leave the terminal non-blocking.
ClaudeMcpRefused
def ClaudeMcpRefused(
msg, status:NoneType=None, raw:NoneType=None, usage:NoneType=None, budget:bool=False
):Claude Code refused the MCP server tool_mode='native' declares. tool_mode='tags' still works.
ClaudeDeadline
def ClaudeDeadline(
elapsed, stopped
):A call outran its deadline. elapsed is the seconds it ran. stopped is True when the SDK stream closed within CLOSE_WAIT; when False the call may still finish and spend, and the caller must assume it does.
ClaudeStall
def ClaudeStall(
*args, **kwargs
):Claude Code sent nothing for the chat’s timeout seconds.
norm_claude
def norm_claude(
d, model:NoneType=None, asked:bool=False, tags:bool=True
):Convert a Claude Code result to a rishi Resp, reading <tool_call> tags from the text when tags and flagging an unreadable call for one resend unless asked.
claude_tool_use
def claude_tool_use(
b, sdk
):Convert a ToolUseBlock to a plain record, else return None.
claude_status
def claude_status(
d
):The HTTP status behind a failed result: what Claude Code reported, else one read out of the text.
ClaudeError
def ClaudeError(
msg, status:NoneType=None, raw:NoneType=None, usage:NoneType=None, budget:bool=False
):A failed Claude Code turn: what it said, the status behind it, the raw result, what it cost, and whether max_budget_usd stopped it.
norm_claude_usage
def norm_claude_usage(
u, model:NoneType=None, cost:NoneType=None
):Convert Claude Code’s usage block to a rishi usage dict, counting cache reads and writes as prompt tokens and keeping thinking tokens.
prune_sessions
def prune_sessions(
cwd:NoneType=None, keep:int=0, age:NoneType=None, entrypoint:str='sdk-py'
):Delete the transcripts rishi filed under cwd, sparing the newest keep and any younger than age seconds, and return the deleted paths.
sess_entrypoint
def sess_entrypoint(
p, mx:int=50
):Return a transcript’s entrypoint, if present in its first mx records.
claude_version
def claude_version(
bin:str='claude'
):Return the installed Claude Code version, cached per binary, or llmsurgery’s pinned version when it cannot be read.
claude_fallback
def claude_fallback(
models
):Resolve a list or comma-separated string of models, as claude_model does, into the value --fallback-model takes.
claude_model
def claude_model(
model:NoneType=None, dflt:str='claude-opus-5'
):Turn a CLAUDE_MODELS key such as 'opus5' into its model id, pass other names through, and return dflt for an empty name.
claude_bin
def claude_bin(
bin:str='claude'
):Absolute path to the claude binary, or a FileNotFoundError that says how to get one.
test_fail(lambda: claude_bin('definitely-not-the-claude-binary'), contains='is not on $PATH')
# a call nothing could read is flagged, so the loop asks for it again rather than ending the turn on the prose
bad = norm_claude({'result': 'Reading it.\n<tool_call>\nnot a call anyone can read\n</tool_call>', 'usage': {}})
test_eq((bad['content'], bad.get('tool_parse_failed'), bad.get('tool_calls')), ('Reading it.', True, None))
inv = norm_claude({'result': 'Reading it.\n<tool_call>\n<invoke name="view_file">\n<parameter name="path">a.md</parameter>\n</invoke>\n</tool_call>', 'usage': {}})
test_eq(([tc['function']['arguments'] for tc in inv['tool_calls']], inv.get('tool_parse_failed')), ([{'path': 'a.md'}], None))
# a name reaches `--model` three ways, and rishi never second-guesses one it does not know
test_eq(claude_model('opus5'), opus5) # a `CLAUDE_MODELS` key, resolved
test_eq(claude_model(opus5), opus5) # a pinned id, untouched
test_eq(claude_model('opus'), 'opus') # the CLI's own alias, which tracks your plan
test_eq(claude_model('claude-something-6'), 'claude-something-6')
test_eq(claude_model(None), opus5) # ...and nothing at all is rishi's default
test_eq(claude_model('', dflt=None), None)
test_eq(claude_fallback('opus5,haiku'), f'{opus5},haiku') # a chain, in the order it is tried
test_eq(claude_fallback(['sonnet46', '', 'haiku45']), f'{sonnet46},{haiku45}')
# the version a record claims is the binary's, not a constant that goes stale under it
test_eq(re.fullmatch(r'\d+\.\d+\.\d+', claude_version()) is not None, True)
test_eq(claude_version('definitely-not-the-claude-binary'), ant.CC_VERSION) # nothing to ask
# the probe reads end of file, so a line waiting on the caller's terminal stays there and the terminal stays blocking
import os, pty, sys, tempfile
fake = Path(tempfile.mkdtemp())/'claude'
fake.write_text(f'#!{sys.executable}\nimport os; t = os.isatty(0); os.set_blocking(0, False); print(f"{{int(t)}}.0.0")\n'); fake.chmod(0o755)
m, s = pty.openpty(); os.write(m, b'x\n')
probe = f"import os, select; from rishi.claude import claude_version; print(claude_version({str(fake)!r}), os.get_blocking(0), os.read(0, 9) if select.select([0], [], [], 1)[0] else b'')"
got = subprocess.run([sys.executable, '-c', probe], stdin=s, capture_output=True, text=True, timeout=60).stdout.split()
os.close(s); os.close(m)
test_eq(got, ['0.0.0', 'True', "b'x\\n'"])
r = norm_claude({'result': 'ok\n<tool_call>\n{"name": "ls", "arguments": {"path": "."}}\n</tool_call>',
'usage': {'input_tokens': 10, 'output_tokens': 5, 'cache_read_input_tokens': 90,
'cache_creation_input_tokens': 7}, 'cost': 0.0042}, opus5)
test_eq(resp_text(r), 'ok')
test_eq(r['tool_calls'][0]['function']['name'], 'ls')
test_eq(r['usage']['total_tokens'], 112) # cache reads and writes are prompt tokens too
test_eq(r['usage']['cache_creation_tokens'], 7)
test_eq(r['usage']['cost'], 0.0042) # what Claude Code itself billed, not a price table
assert 'reasoning_tokens' not in r['usage'] # not reported, so not claimed as 0
# thinking is part of `output_tokens`, counted again under `output_tokens_details`
th = norm_claude_usage({'input_tokens': 2, 'output_tokens': 840, 'output_tokens_details': {'thinking_tokens': 711}})
test_eq((th['completion_tokens'], th['reasoning_tokens']), (840, 711))
# Preserve status for retry policy.
try:
norm_claude({'is_error': True, 'result': 'API Error: 429 rate limited'}); assert False, 'no raise'
except ClaudeError as e:
test_eq(e.status, 429)
test_eq(e.raw['is_error'], True)
try: # a reported status wins over one read out of the text
norm_claude({'is_error': True, 'result': 'failed after 500 attempts', 'api_error_status': 529})
except ClaudeError as e: test_eq(e.status, 529)
try: # ...and no status at all is not an error
norm_claude({'is_error': True, 'subtype': 'error_during_execution'})
except ClaudeError as e: test_eq(e.status, None)
try: # nor is one Claude Code spells with a word
norm_claude({'is_error': True, 'result': 'nope', 'api_error_status': 'rate_limit'})
except ClaudeError as e: test_eq(e.status, None)
# a run Claude Code stopped at `max_budget_usd` was still paid for: the error keeps its cost and says it was the budget
try: norm_claude({'is_error': True, 'subtype': 'error_max_budget_usd', 'cost': 8.4, 'usage': {'input_tokens': 10, 'output_tokens': 5}}, 'sonnet'); assert False, 'no raise'
except ClaudeError as e: test_eq((e.budget, e.usage['cost'], e.usage['total_tokens']), (True, 8.4, 15)); assert 'budget' in str(e)
try: norm_claude({'is_error': True, 'result': 'nope', 'cost': 0.2})
except ClaudeError as e: test_eq((e.budget, e.usage['cost']), (False, 0.2)) # any failed result keeps what it cost
# `ClaudeError` is a `RuntimeError`, so anything already catching one still does
test_fail(lambda: norm_claude({'is_error': True, 'result': 'nope'}), contains='nope')
# an aborted turn is the user cancelling, not a failure: whatever arrived before is the reply
test_eq(resp_text(norm_claude({'is_error': True, 'terminal_reason': 'aborted', 'result': 'part'})), 'part')
for reason in ABORTED: norm_claude({'result': '', 'is_error': True, 'terminal_reason': reason})
# Claude Code's own "could not parse the call" error is a call to ask for again, until that was already asked
tpe = {'is_error': True, 'result': "The model's tool call could not be parsed (retry also failed).", 'usage': {}}
def test_tool_parse_err_flag():
test_eq(norm_claude(tpe).get('tool_parse_failed'), True)
test_fail(lambda: norm_claude(tpe, asked=True), contains='no resend left')
test_tool_parse_err_flag()The chat
One event loop
The SDK’s ClaudeSDKClient keeps a background task group running from connect to disconnect. Every call on the client must run on the event loop that created it. rishi’s code is synchronous. It uses fastcore.aio.run_sync and Urai’s sync_iter, which both run coroutines on fastcore’s one shared background event loop.
mk_claude_content builds content parts as Urai’s mk_content does. It also accepts documents such as PDFs and stores them as data URLs.
mk_claude_msg
def mk_claude_msg(
content, role:str='user'
):Build a message as mk_msg does, using mk_claude_content for each part.
mk_claude_content
def mk_claude_content(
o
):Build a content part as mk_content does, also carrying documents such as PDFs as data URLs.
ClaudeChat
def ClaudeChat(
model:NoneType=None, *, runtime:NoneType=None, model_path:NoneType=None, opts:NoneType=None,
permission_mode:str='auto', # Claude Code's gate on its *own* tools. Yours are rishi's
claude_tools:NoneType=None, # Claude Code's own tools, allowlisted. None -> none at all when this chat carries tools, its default set when it carries none
claude_disallowed:tuple=('Bash', 'Write', 'Edit', 'NotebookEdit'), # Claude Code tools it may never use
claude_server_tools:tuple=(), # its web tools, which run on its side and never reach rishi's loop
mcp_servers:NoneType=None, # MCP servers to declare. None -> none at all. See `The wire`
mcp_tools:NoneType=None, # which of their tools to allow. None -> every tool of every server named
strict_mcp_config:bool=False, # refused outright where an enterprise MCP config exists
workspace:NoneType=None, # directory Claude Code works in. None -> `CLAUDE_WORK_DIR`. See `_cwd`
fallback:NoneType=None, # model, or models tried in order, for when this one is overloaded or retired
cleanup:bool=True, # remove the transcripts this chat filed when it closes. See `prune_sessions`
bare:bool=True, # answer as a model: no CLAUDE.md, skills, plugins or hooks
stateful:bool=True, # keep one Claude Code session per chat. See `_connect`
transcript:bool=True, # file the conversation as records rather than prose. See `_file_sess`
api_key:bool=False, # False blanks `ANTHROPIC_API_KEY` in the subprocess; True lets it through. See `_opts`
max_buffer:int=10485760, # the SDK's stdout cap, in bytes
bin:str='claude', settings:NoneType=None,
timeout:int=240, # seconds of silence before the turn is ended and tried once more. See `Silence`
on_stall:NoneType=None, # called with a status note when that happens. None -> `warnings.warn`
timeout_hint:NoneType=None, # how a caller raises `timeout`, named in the error. None -> `ClaudeChat(timeout=SECONDS)`
**kw
):A Chat that drives your Claude Code installation through the Claude Agent SDK.
Options
Claude Code has tools of its own, such as Bash and Edit. These rules decide which of them a chat can use:
- A chat that carries rishi tools switches all Claude Code tools off. Your tools are the only ones Claude can call.
- A chat with no rishi tools keeps Claude Code’s default set, minus
claude_disallowed. By defaultclaude_disallowedholds Bash, Write, Edit and NotebookEdit. claude_tools=[]switches all Claude Code tools off and gives plain completions.bare=True, the default, stops Claude Code from loading project instructions (CLAUDE.md), skills, plugins and hooks. It does not restrict tools.
tool_mode='native' sends rishi’s tools through an in-process MCP server, not through the prompt. See Native tool calls.
claude_server_tools switches on Claude Code’s web tools, WebSearch and WebFetch. They run on Claude Code’s side.
fallback names a model, or a list of models tried in order. Claude Code uses them when the chosen model is overloaded or retired.
set_model switches the model of a live session without rebuilding the history.
effort sets the reasoning effort: low, medium, high, xhigh or max. It is the only generation setting that Claude Code takes. The chat ignores temperature, token limits and similar options.
When the effort of a call differs from the effort the live session opened with, the chat reconnects the session and resumes it from hist. A call with no effort runs at the chat’s own effort and reconnects in the same way.
managed_mcp
def managed_mcp()->bool:Whether this machine has an enterprise MCP config. Claude Code then refuses --strict-mcp-config outright.
Pictures and documents
Claude Code takes Anthropic content blocks. rishi converts its OpenAI-shaped history with aidialog and fastllm. An image becomes an image block. A PDF becomes a document block. A live session and a filed transcript both carry these blocks.
With stateful=False, transcript=False, the chat flattens the history into one text prompt. A text prompt cannot hold an image, so the chat refuses media. Claude Code takes no audio on any path.
Transcript records
Claude Code resumes a session from a JSONL transcript at ~/.claude/projects/<cwd>/<id>.jsonl. anth_msgs converts rishi’s history into Anthropic messages. llmsurgery.ant writes them as transcript records. anth_blocks keeps images and documents as typed blocks.
The chat files tool calls in the form that the session uses.
On the default tags channel, tag_calls files a call as <tool_call> text and files its result as prose. render_prompt sends them in the same form in a live session. Filing them as native tool_use blocks failed. A resumed session saw tools that the options no longer declared, and it ended its next turn after one sentence.
On the native channel, the chat files calls and results as tool_use and tool_result blocks. tu_id rewrites each id into Anthropic’s toolu_ form so that every pair matches. A tool that returned nothing is filed as (no output). The API rejects empty text blocks.
The chat always files assistant content as a list of blocks. Claude Code 2.1.238 calls .some() on it, and a plain string crashes it.
A session id is a hash of the messages plus a random value that is unique to each chat. Refiling the same chat gives the same id. Two chats that hold the same conversation get different files, and neither deletes the other’s file during cleanup.
A chat removes the transcripts it filed when it closes, unless cleanup=False. prune_sessions clears old transcripts that remain. Each record carries the version that the installed claude --version reports.
Two settings decide how the conversation travels:
stateful=True, the default, keeps one Claude Code process for the chat. It sends tool results mid-turn as text.stateful=Falsestarts a freshqueryeach turn and refiles the whole history as typed records. Addingtranscript=Falsesends the history as one flattened text prompt, which cannot carry media.
claude_prompt
def claude_prompt(
prompt
):A turn’s prompt for query: a string as it is, content blocks as the streaming-input shape.
anth_msgs
def anth_msgs(
hist, ant, tags:bool=False, prefix:str=''
):rishi’s history as Anthropic messages; tool calls as blocks named prefix + name, or as <tool_call> text when tags.
tag_calls
def tag_calls(
tcs
):Tool calls as <tool_call> text, spelled as render_prompt spells them.
tu_id
def tu_id(
tid, ant
):A tool call’s id as Anthropic spells one, the same way every time it is filed.
anth_blocks
def anth_blocks(
content
):rishi’s OpenAI-shaped message content as Anthropic content blocks.
A prompt list with raw parts, such as the picture bytes and the text that ramabana’s Agent.compose gives, becomes Anthropic content blocks. Before, the raw bytes went to the SDK as they were.
import io
from urai import run_coro
from PIL import Image
_b = io.BytesIO(); Image.new('RGB', (8, 8), 'white').save(_b, 'PNG')
async def _first(g): return [m async for m in g][0]
_c = run_coro(_first(claude_prompt([_b.getvalue(), 'Find its labels.'])))['message']['content']
test_eq([p['type'] for p in _c], ['image', 'text'])
test_eq(_c[0]['source']['type'], 'base64')
_blocks = [{'type': 'text', 'text': 'as it is'}]
test_eq(run_coro(_first(claude_prompt(_blocks)))['message']['content'], _blocks) # blocks pass as they areA stored call with unreadable arguments renders as an empty object. It does not send null to Anthropic.
for args in ("", "invalid", "[]", None, {"a": 1}):
msg = {"role": "assistant", "tool_calls": [{"id": "c", "function": {"name": "add", "arguments": args}}]}
rendered = anth_msgs([msg], ant)[0]["content"][0]
assert rendered["input"] == (args if isinstance(args, dict) else {})
renderedSession watermark
During a tool turn, the chat appends Claude’s reply and then the tool results to hist. The live session already holds its own reply. Sending the reply back would make Claude read its own words as new input.
_sent marks how much of hist the session has seen. Each request sends only what comes after that mark. When a chat connects by resuming a filed transcript, _sent starts at the length of the filed history. The first request then sends only the new user message.
set_opts changes the options the next Claude Code connect gets, such as max_budget_usd. A value set to None is dropped. A stateful chat keeps one Claude Code session, and Claude Code counts a budget over that session, so a changed value ends the open session; the next call resumes it from hist with the new options.
ClaudeChat.set_opts
def set_opts(
**kw
):Change the Claude Code options of the next connect; None drops one. A change ends an open session, which the next call resumes.
c = ClaudeChat(stateful=False, transcript=False)
gone = []; c._disconnect = lambda *a, **k: gone.append(1)
c.set_opts(max_budget_usd=3.0); test_eq((c.opts_['max_budget_usd'], gone), (3.0, [])) # nothing open: nothing to end
c.client = object()
c.set_opts(max_budget_usd=3.0); test_eq(gone, []) # the same value keeps the session
c.set_opts(max_budget_usd=1.5); test_eq((c.opts_['max_budget_usd'], gone), (1.5, [1])) # a new one ends it
c.set_opts(max_budget_usd=None); assert 'max_budget_usd' not in c.opts_
c.client = NoneNative tool calls
With tool_mode='native', rishi’s tools reach Claude as MCP tools, not as prompt text. The chat declares an in-process MCP server named rishi (RISHI_MCP). The server holds one tool per toolspec, with the toolspec’s JSON schema and descriptions. Only those tools are allowed, as mcp__rishi__NAME. Claude Code’s own tools stay off. The schemas leave the system prompt.
In this mode Claude Code runs the tool loop itself. One model step can hold several calls. Each call passes through the same pieces of Urai’s loop as a tagged call:
_approve1applies the approval gate, the step budget andbefore_tool_calls.call_toolruns the tool._record_tooltruncates the result totool_max_lenand appliesafter_tool_calls.
The chat writes the call and its result to hist. Transcripts, resumes and callbacks see them as they see tagged calls.
Calls run one at a time. Each call runs in a worker thread, inside a copy of the context of the thread that started the step. Context variables therefore reach the tool and the approver. The silence timer waits while a tool runs.
A refused call, a spent budget and a cancelled turn each answer Claude with the reason. A spent budget also interrupts the live session. A turn that ran a native tool is never tried again after a stall.
A machine with an enterprise MCP configuration refuses every MCP server a program declares. There the chat raises ClaudeMcpRefused, a ClaudeError that carries Claude Code’s own message. The caller can then switch to tool_mode='tags'. A tool name longer than MCP_NAME_MAX, 64 characters with the prefix, raises ValueError.
The two steps the tool loop drives
Urai’s tool loop asks a backend for one model step at a time, either whole (_model_step) or streamed (_stream_step), and runs any tool calls in between. cancel stops a turn and also tells a live session to stop generating. set_model switches the model, on a live session too. token_count returns what the live session last reported holding, or an estimate before it has reported, and never waits on the session.
ClaudeChat.set_model
def set_model(
model:NoneType=None
):Switch the model and return its resolved id.
ClaudeChat.cancel
def cancel():Stop the turn, and tell the session to stop generating rather than only stopping the reader.
Silence
Claude Code streams token deltas, so a working turn is never quiet for long. A turn that sends nothing at all, not even a stream event, for timeout seconds (240 by default) is stuck. _drain closes the stream, which ends the SDK’s query and its subprocess, and raises ClaudeStall. _with_retry then disconnects a live session, passes a status note to on_stall, and tries the turn once more.
What the retry sends depends on what was already shown:
- Nothing yet, or only thinking: the same turn again, from the same filed conversation. The thinking may show twice.
- Text: that text is not sent again. It is filed as the reply so far, and a fresh query asks Claude Code to finish it with
STALL_PROMPT. Only the continuation streams, and the turn’s result is the shown text plus the continuation. - A call to one of Claude Code’s own tools: no retry. A replay would run the tool again. The stall is raised.
- A native tool call: the timer waits while the tool runs. After one has run, a stall is raised and not retried.
- A whole tool call in the text: the turn ends there with that text, as it would have, and a live session reconnects on the next turn.
A failure while connecting gets the same one retry, with a status note to on_stall. On a live session, that is client.connect() failing with a CLIConnectionError or not finishing in timeout seconds. On a query, it is the same error, or Claude Code’s initialize request timing out, before any message arrives. Nothing has run at that point, so nothing is replayed. A missing claude binary (CLINotFoundError), a refusal of rishi’s MCP server, and any other error are raised at once. Another try would fail the same way.
Each wire call has one retry, shared by a failed connect, a stall and a session that died before it said anything. After a connect is retried, a stall is raised, not retried. A failed connect on the retry that follows a stall raises the connect error. A cancelled turn is never retried.
If the retry goes silent too, ClaudeStall names the limit and timeout_hint, which says how the caller raises it. The stalled attempt sent no result, so its tokens and cost are not counted. _oneshot is not retried.
A deadline
oneshot(prompt, deadline=SECONDS) bounds the whole call, from the SDK query’s creation to its result. timeout bounds silence only, and a stream that keeps sending is never silent. _drain waits for the shorter of timeout and the time left, and checks the deadline before every read, so a stream that never goes quiet is cut too.
At the deadline _drain cancels the pending read, closes the stream and raises ClaudeDeadline, a TimeoutError with elapsed, the seconds the call ran, and stopped. Each of the cancel and the close waits at most INTERRUPT_WAIT seconds. stopped is True when the stream closed cleanly in that time, which ends the SDK’s query and its subprocess. stopped is False when the close failed or hung. The call may then still finish and spend, and the caller must assume it does. Nothing is retried after a deadline. Only oneshot takes a deadline.
ClaudeChat.oneshot_stream
def oneshot_stream(
prompt, sp:str='', think:NoneType=None, max_tokens:NoneType=None, deadline:NoneType=None
):Yield the text of one reply to prompt as Claude Code sends it, without tools or history. Closing the iterator ends the Claude Code process. A deadline, cancel() or a silence past timeout raises after the text already yielded, and nothing is retried.
ClaudeChat.oneshot
def oneshot(
prompt, sp:str='', think:NoneType=None, max_tokens:NoneType=None, deadline:NoneType=None
):Return the text of one reply to prompt, without tools or history. deadline is the seconds the call may run; past it ClaudeDeadline is raised and nothing is retried. cancel() from any thread raises OneShotCancelled. When stopped is False on either the call may still finish and spend, and the caller must assume it does.
Streaming a one-shot
oneshot_stream(prompt, sp='', think=None, max_tokens=None, deadline=None) yields the text of one reply as Claude Code sends it, with no tools and no history. It reads the SDK’s partial messages (StreamEvent), so the first chunk arrives before the reply is complete. The whole AssistantMessage that follows adds only the text the deltas did not carry, so no text is yielded twice. oneshot returns the normalised final text.
oneshot_stream_ok, oneshot_deadline_ok and oneshot_max_tokens_ok say what a backend supports. ClaudeChat is True, True and False: Claude Code’s options carry no output-token cap, so max_tokens is ignored and the caller bounds a reply by what it has streamed. A backend with oneshot_deadline_ok False refuses a deadline before it calls the provider.
oneshot_use is the UsageStats of the latest oneshot or oneshot_stream call. It is zero before a call and is replaced, not added to, when the next call starts. Before each chunk it holds the usage the stream has reported so far (message_start and message_delta; the latest API message only, and without cost). A finished call holds the result’s usage and cost. A call that fails with ClaudeError holds the error’s usage. A call cut short by close(), ClaudeDeadline, ClaudeStall or OneShotCancelled holds what the stream had reported. use is not touched.
A one-shot gives Claude Code no tool. Its options carry tools=[], no allowed tool and no MCP server, whatever claude_tools, claude_server_tools, mcp_servers or set_opts say, and a normal turn keeps its own. It also passes --strict-mcp-config, so Claude Code loads no MCP server from any other configuration, its settings files included. Where an enterprise MCP configuration exists, Claude Code refuses that flag and the call raises ProcessError.
A one-shot has a ClaudeSDKClient of its own, and the call has ended only once that client has disconnected. claude_agent_sdk.query is not used, because closing it returns while the process still runs. disconnect closes the process’s stdin, waits 5 seconds for it to exit, sends SIGTERM, waits 5 more, then sends SIGKILL. Closing the iterator and reading it to the end wait for that, for at most CLOSE_WAIT seconds in all, and never cancel the SDK’s close. A close that has not finished by then raises OneShotCancelled with stopped False, and the caller must assume the call may still spend. After an error the original error is raised, with no second wait.
cancel() ends a one-shot with OneShotCancelled, from any thread, also while the call waits for a chunk. The flag is looked at every CANCEL_POLL seconds, and the error is raised once the process has exited or CLOSE_WAIT has passed. elapsed is the seconds since the call began, read then, and stopped says whether the process exited. A cancel() that arrives after the last message is not noticed. Text yielded before it is a partial reply, and a cancelled oneshot returns nothing. A cancel() that ended an earlier call is cleared when the next call starts. Nothing is retried after partial output. A deadline raises ClaudeDeadline and a silence past timeout raises ClaudeStall, both after the chunks already yielded.
c = ClaudeChat(stateful=False, transcript=False)
stop = {'is_error': True, 'subtype': 'error_max_budget_usd', 'cost': 8.4, 'usage': {'input_tokens': 10, 'output_tokens': 5}}
c._events = lambda: iter([('result', stop)])
test_fail(c._model_step, contains='budget')
test_eq(round(c.use.cost, 2), 8.4) # the stopped run was paid for, so `use` counts it, as a caller's turn total does
c._events = lambda: iter([('result', stop)])
test_fail(lambda: list(c._stream_step()), contains='budget')
test_eq(round(c.use.cost, 2), 16.8)Tests
The tests below check the SDK options, the transcript records, which chat owns which session file, and the boundary between the tool channels. None of them starts Claude Code.
def _fn(query: str) -> str:
"Search the code."
return ''
c = ClaudeChat('claude/claude-opus-5', sp='be brief', tools=[_fn], claude_disallowed=('Bash',))
c.hist = [{'role': 'user', 'content': 'what is 2 plus 2?'}]
test_eq(c.model_id, 'claude-opus-5') # the `claude/` prefix is stripped, the id is not
test_eq(ClaudeChat('claude/opus5').model_id, opus5) # ...and a short name is resolved to one
test_eq(ClaudeChat('claude/sonnet').model_id, 'sonnet') # the CLI's alias travels as written
test_eq(c.local, False)
o = c._opts(c._sp())
# The enterprise contract: no dynamic server is declared, and `strict_mcp_config` is *not* claimed.
# A managed machine refuses that flag outright, so asking for it is how this path used to fail.
test_eq(o.mcp_servers, {})
test_eq(o.strict_mcp_config, False)
test_eq(o.model, 'claude-opus-5')
test_eq(o.disallowed_tools, ['Bash'])
# rishi's tools are the only tool channel: Claude Code's own are off while this chat carries any
test_eq(o.tools, [])
test_eq(ClaudeChat()._opts('').tools, None) # with none of rishi's, its own are left as they were
# `claude_tools=[]` is a completion endpoint with or without rishi's tools: the real command line says `--tools ''`
def _argv(o):
t = SubprocessCLITransport(prompt='', options=o)
t._cli_path = t._cli_path or 'claude'
return t._build_command()
def _flag(argv, f): return argv[argv.index(f) + 1] if f in argv else None
def _tools_flag(**kw): return _flag(_argv(ClaudeChat(**kw)._opts('')), '--tools')
test_eq(_tools_flag(claude_tools=[]), '')
test_eq(_tools_flag(claude_tools=[], tools=[_fn]), '')
test_eq(_tools_flag(claude_tools=['Read'], tools=[_fn]), 'Read')
test_eq(_tools_flag(tools=[_fn]), '')
test_eq(_tools_flag(), None)
n = ClaudeChat(tools=[_fn], tool_mode='native', claude_tools=[])._opts('')
test_eq((n.tools, n.allowed_tools), ([], [MCP_PREFIX + '_fn']))
test_eq((_flag(_argv(n), '--tools'), _flag(_argv(n), '--allowedTools')), ('', MCP_PREFIX + '_fn'))
# a one-shot demands `--strict-mcp-config` and sends no `--mcp-config`, even with MCP servers configured; a turn keeps strict off
_srv = {'files': {'type': 'stdio', 'command': 'nothing-runs-here'}}
ms = ClaudeChat(mcp_servers=_srv)
_mm, MANAGED_MCP = MANAGED_MCP, () # a machine with no enterprise MCP config
try: one, turn = _argv(ms._opts('', mcp=False, tools=False)), _argv(ms._opts(''))
finally: MANAGED_MCP = _mm
test_eq(('--strict-mcp-config' in one, '--mcp-config' in one), (True, False))
test_eq(('--strict-mcp-config' in turn, '--mcp-config' in turn), (False, True))
# on a machine with an enterprise MCP config, Claude Code refuses `--strict-mcp-config`, so a one-shot leaves it off
# and still names no tool and no server
import tempfile
with tempfile.NamedTemporaryFile() as _f:
_mm, MANAGED_MCP = MANAGED_MCP, (_f.name,)
try: test_eq(managed_mcp(), True); one = _argv(ms._opts('', mcp=False, tools=False))
finally: MANAGED_MCP = _mm
test_eq(('--strict-mcp-config' in one, '--mcp-config' in one, one[one.index('--tools') + 1]), (False, False, ''))
_mm, MANAGED_MCP = MANAGED_MCP, ('/no/such/managed-mcp.json',)
try: test_eq(managed_mcp(), False)
finally: MANAGED_MCP = _mm
# ...so the schemas have to be somewhere, and the system prompt is where
test_eq('be brief' in o.system_prompt and '"_fn"' in o.system_prompt and '<tool_call>' in o.system_prompt, True)
test_eq('be brief' not in c._prompt(), True) # and the briefing is not also in the conversation
test_eq(c.tool_channel, 'tags')
# an ambient API key never reaches the subprocess: it would silently meter a subscription session
test_eq(o.env, {'ANTHROPIC_API_KEY': ''})
test_eq(ClaudeChat(api_key=True)._opts('').env, {})
# the SDK's own 1MB stdout cap raises rather than truncating, losing a long reply outright
test_eq(o.max_buffer_size, MAX_BUFFER)
# the Claude Code on $PATH runs, not the SDK's bundled copy, which lags and refuses newer models
test_eq(o.cli_path, shutil.which(CLAUDE_BIN))
test_eq(ClaudeChat(bin='definitely-not-the-claude-binary')._opts('').cli_path, None)
# the harness's own context is off by default: this is a model, not the user's IDE agent
test_eq((o.setting_sources, o.skills), ([], []))
test_eq(ClaudeChat(bare=False)._opts('').setting_sources, None)
# Claude Code's web tools are the one place its own tools are a feature, and they are opt-in
w = ClaudeChat(claude_server_tools=CLAUDE_SERVER_TOOLS)._opts('')
test_eq(w.tools, ['WebFetch', 'WebSearch'])
test_eq(w.allowed_tools, list(CLAUDE_SERVER_TOOLS))
# the conversation is resumed from a file, and the session's own turns stay out of that file
o2 = c._opts('', resume=c._file_sess([{'role': 'user', 'content': 'earlier'}]), fork=True)
test_eq(o2.fork_session, True)
assert o2.resume, 'no session to resume'
test_eq(ClaudeChat(transcript=False)._file_sess([{'role': 'user', 'content': 'x'}]), None)
# transcripts stay out of a real project unless you name one
test_eq(ClaudeChat()._cwd, CLAUDE_WORK_DIR.resolve())
test_eq(ClaudeChat(workspace='.')._cwd, Path('.').resolve())
# an overloaded or retired model moves down the chain instead of ending the turn
test_eq(ClaudeChat(fallback='sonnet46')._opts('').fallback_model, sonnet46)
test_eq(ClaudeChat(fallback=['opus', 'haiku45'])._opts('').fallback_model, f'opus,{haiku45}')
test_eq(o.fallback_model, None) # and no chain by default: one model, or a failed turn
# the model can change mid-conversation. With no session live that is just the next turn's option
m = ClaudeChat(sonnet46)
test_eq(m.set_model('haiku45'), haiku45)
test_eq(m._opts('').model, haiku45)
test_eq(m.set_model(), None) # ...and `None` hands the choice back to Claude Code
test_eq(m._opts('').model, None)MCP servers
Pass mcp_servers when Claude Code must reach an MCP server itself. Every tool of each named server is allowed unless mcp_tools narrows the list. These tools run inside Claude Code, outside rishi’s tool loop. rishi reports their calls in Resp.channels['server_tools'], not in tool_calls. Nothing waits on rishi to answer them.
import claude_agent_sdk as _sdksrv = {'files': {'type': 'stdio', 'command': 'nothing-runs-here'}}
# Nothing named, nothing declared: byte for byte the enterprise default above.
test_eq(ClaudeChat()._opts('').mcp_servers, {})
test_eq(ClaudeChat().mcp_toolnames, [])
# Named servers are declared, and every tool of each is allowed unless the caller narrows it.
m = ClaudeChat(tools=[_fn], mcp_servers=srv)
test_eq(m.mcp_toolnames, ['mcp__files'])
o = m._opts('')
test_eq(o.mcp_servers, srv)
test_eq(o.allowed_tools, ['mcp__files'])
test_eq(o.tools, ['mcp__files']) # available: these, and not Claude Code's own set
n = ClaudeChat(mcp_servers=srv, mcp_tools=['mcp__files__read'])
test_eq(n._opts('').allowed_tools, ['mcp__files__read'])
test_eq(ClaudeChat(mcp_servers=srv, mcp_tools=[])._opts('').allowed_tools, [])
# `strict_mcp_config` stays off unless asked for. It is refused where an enterprise config exists.
test_eq(m._opts('').strict_mcp_config, False)
test_eq(ClaudeChat(mcp_servers=srv, strict_mcp_config=True)._opts('').strict_mcp_config, True)
# Native mode carries rishi's tools on its own MCP server, so the prompt carries no schemas.
t = ClaudeChat(sp='be brief', tools=[_fn], mcp_servers=srv, tool_mode='native')
test_eq(t.tool_channel, 'native')
test_eq(ClaudeChat().tool_channel, 'tags') # `tool_mode` unset is the enterprise default
test_eq(t._sp(), 'be brief') # no schemas, because they travel somewhere else
assert '<tool_call>' in ClaudeChat(sp='be brief', tools=[_fn])._sp()
# A tool Claude Code ran on its own side is a report, not a call rishi has to answer.
use = claude_tool_use(_sdk.ToolUseBlock(id='t1', name='mcp__files__read', input={'p': 'x'}), _sdk)
test_eq(use, {'id': 't1', 'name': 'mcp__files__read', 'server': 'files', 'input': {'p': 'x'}})
test_eq(claude_tool_use(_sdk.ToolUseBlock(id='t2', name='WebSearch', input={}), _sdk)['server'], '')
test_eq(claude_tool_use(_sdk.TextBlock(text='hello'), _sdk), None)
r = norm_claude({'result': 'done', 'usage': {}, 'server_tools': [use]})
test_eq(r['channels']['server_tools'], [use])
test_eq(resp_text(r), 'done')
test_eq('tool_calls' in r, False) # nothing here is waiting on rishi
test_eq(norm_claude({'result': 'done', 'usage': {}}).get('channels'), None)A tagged tool round trip
Claude receives rishi’s tool schemas in the system prompt. When it writes a tagged call, norm_claude converts the tag to an ordinary tool call. Urai’s tool loop runs the Python function and records the result. Claude then writes the final reply. This test scripts the two replies from Claude. The parser, the tool loop, the function call and the history are real.
Against Claude Code with tagged tools
This cell uses the default live session. Claude receives the tool schema through _sp() and writes a tagged call. rishi parses the tag, runs the Python function and sends the result back to the same Claude Code session. The cell needs a signed-in Claude Code installation. The test run skips it.
from rishi.claude import ClaudeChat
from urai import resp_text
live_tag_calls = []
def live_tag_add(a: int, b: int) -> int:
"Add two integers and record the call."
live_tag_calls.append((a, b))
return a + b
live_tag = ClaudeChat('haiku', tools=[live_tag_add], default_cbs=False)
live_tag_reply = live_tag('Use live_tag_add once with a=2 and b=3. Then answer with only the result.')
assert live_tag_calls == [(2, 3)]
assert '5' in resp_text(live_tag_reply)
assert [m['role'] for m in live_tag.hist] == ['user', 'assistant', 'tool', 'assistant']
assert live_tag.hist[2]['content'] == '5'
assert live_tag.hist[2]['tool_call_id'] == live_tag.hist[1]['tool_calls'][0]['id']
assert 'server_tools' not in (live_tag_reply.get('channels') or {})
live_tag.close()MCP events from the SDK
MCP tools run inside Claude Code, not in Urai’s tool loop. _sdk_events picks up the SDK’s ToolUseBlock for each such call and passes it through to the final result. This test replaces the SDK’s query iterator, so no MCP server runs and Claude is not contacted.
A reply that goes on past its own tool call
A model can write a tool call and keep going in the same response as though the call had been answered. It writes more calls, then findings it never saw. Claude Code’s result holds only the last text block. Without a guard, the calls were lost and the invented findings reached the caller as the answer.
_drain stops at the first text block that holds a call. rishi shows and keeps nothing after that block. The turn’s text is what came before the stop. The call runs, and its real result comes back.
Against Claude Code and a local MCP server
This cell gives Claude Code a real MCP server running inside the Python process. Claude chooses and runs the MCP tool. The assertions check that the Python handler ran and that rishi received Claude Code’s report of the call. The cell needs a signed-in Claude Code installation. The test run skips it.
from claude_agent_sdk import create_sdk_mcp_server, tool
mcp_calls = []
@tool('add', 'Add two integers.', {'a': int, 'b': int})
async def mcp_add(args):
mcp_calls.append((args['a'], args['b']))
return {'content': [{'type': 'text', 'text': str(args['a'] + args['b'])}]}
calc = create_sdk_mcp_server('calc', tools=[mcp_add])
live_mcp = ClaudeChat('haiku', mcp_servers={'calc': calc}, mcp_tools=['mcp__calc__add'],
stateful=False, transcript=False, default_cbs=False)
live_reply = live_mcp('Use the calc add tool once with a=2 and b=3. Then answer with only the result.')
assert mcp_calls == [(2, 3)]
assert resp_text(live_reply).strip() == '5'
assert [x['name'] for x in live_reply['channels']['server_tools']] == ['mcp__calc__add']
live_mcp.close()