ClaudeSDKClient R6 Class
ClaudeSDKClient R6 Class
Details
Provides a stateful, bidirectional connection to the Claude Code CLI. Supports sending multiple prompts, receiving streamed responses, runtime permission-mode changes, interrupts, and MCP server management.
Lifecycle
client <- ClaudeSDKClient$new(ClaudeAgentOptions(model = "claude-opus-4-6"))
client$connect()
client$send("Hello, Claude!")
coro::loop(for (msg in client$receive_response()) {
if (inherits(msg, "AssistantMessage")) cat(msg$content[[1]]$text)
})
client$disconnect()Methods
Method new()
Create a new ClaudeSDKClient.
Usage
ClaudeSDKClient$new(options = ClaudeAgentOptions(), transport = NULL)Arguments
optionsA
ClaudeAgentOptionsfromClaudeAgentOptions().transportOptional
SubprocessCLITransport. When supplied the client uses it directly instead of creating one.
Method query()
Send a new request in streaming mode.
Alias for send() that matches the Python SDK's client.query() API.
Method poll_messages()
Non-blocking single-cycle poll. Returns a list of
messages available right now (may be empty). Designed for
Shiny observe() + invalidateLater() polling patterns where
later::later()-based approaches starve input processing.
Method receive_messages()
Return a coro generator that yields ALL messages
(no automatic stop). Use receive_response() for a single
request/response cycle.
Method receive_response()
Return a coro generator that yields messages until
and including the next ResultMessage, then stops.
Method receive_response_async()
Return a promises::promise that resolves to the next
ResultMessage. Each intermediate message is passed to on_message
as it arrives. Requires the promises package (listed in Suggests).
Designed for Shiny ExtendedTask integration: the promise keeps the
Shiny session unblocked while on_message streams intermediate
results (e.g., into a reactiveVal) for real-time UI updates.
Arguments
on_messageFunction(msg) or NULL. Called for every message (AssistantMessage, SystemMessage, StreamEvent, PermissionRequestMessage, etc.) except the final ResultMessage. Handle
PermissionRequestMessagehere and callclient$approve_tool()/client$deny_tool()to continue.poll_intervalNumeric. Seconds between non-blocking polls (default 0.01 = 10 ms).
Returns
A promises::promise that resolves to the ResultMessage.
Method approve_tool()
Approve a pending tool request.
Call this after receiving a PermissionRequestMessage from the
message stream to allow the tool to execute.
Method rewind_files()
Rewind tracked files to their state at a specific
user message. Requires enable_file_checkpointing = TRUE.
Examples
if (FALSE) { # \dontrun{
# Multi-turn conversation
client <- ClaudeSDKClient$new(ClaudeAgentOptions(max_turns = 3L))
client$connect()
client$send("What is the capital of France?")
coro::loop(for (msg in client$receive_response()) {
if (inherits(msg, "AssistantMessage")) {
for (blk in msg$content)
if (inherits(blk, "TextBlock")) cat(blk$text, "\n")
}
})
client$disconnect()
} # }