Skip to main content

AsyncClient

Struct AsyncClient 

Source
pub struct AsyncClient { /* private fields */ }
Expand description

Asynchronous client for communicating with Claude

Implementations§

Source§

impl AsyncClient

Source

pub fn new(child: Child) -> Result<Self>

Create a new async client from a tokio Child process

Source

pub async fn with_defaults() -> Result<Self>

Create a client with default settings (using logic from start_claude)

Source

pub async fn with_model(model: &str) -> Result<Self>

Create a client with a specific model

Source

pub async fn from_builder(builder: ClaudeCliBuilder) -> Result<Self>

Create a client from a custom builder

Source

pub async fn resume_session(session_uuid: Uuid) -> Result<Self>

Resume a previous session by UUID This creates a new client that resumes an existing session

Source

pub async fn resume_session_with_model( session_uuid: Uuid, model: &str, ) -> Result<Self>

Resume a previous session with a specific model

Source

pub async fn query(&mut self, text: &str) -> Result<Vec<ClaudeOutput>>

Send a query and collect all responses until Result message This is the simplified version that collects all responses

Source

pub async fn query_with_session( &mut self, text: &str, session_id: Uuid, ) -> Result<Vec<ClaudeOutput>>

Send a query with a custom session ID and collect all responses

Source

pub async fn query_stream(&mut self, text: &str) -> Result<ResponseStream<'_>>

Send a query and return an async iterator over responses Returns a stream that yields ClaudeOutput until Result message is received

Source

pub async fn query_stream_with_session( &mut self, text: &str, session_id: Uuid, ) -> Result<ResponseStream<'_>>

Send a query with session ID and return an async iterator over responses

Source

pub async fn send(&mut self, input: &ClaudeInput) -> Result<()>

Send a ClaudeInput directly

Source

pub async fn receive(&mut self) -> Result<ClaudeOutput>

Receive a single response from Claude.

§Important: Polling Frequency

This method should be polled frequently to prevent the OS pipe buffer from filling up. Claude can emit very large JSON messages (hundreds of KB), and if the pipe buffer overflows, data may be truncated.

In a tokio::select! loop with other async operations, ensure receive() is given priority or called frequently. For high-throughput scenarios, consider spawning a dedicated task to drain stdout into an unbounded channel.

§Returns
  • Ok(ClaudeOutput) - A parsed message from Claude
  • Err(Error::ConnectionClosed) - Claude process has exited
  • Err(Error::Deserialization) - Failed to parse the message
Source

pub fn is_alive(&mut self) -> bool

Check if the Claude process is still running

Source

pub async fn shutdown(self) -> Result<()>

Gracefully shutdown the client

Source

pub fn pid(&self) -> Option<u32>

Get the process ID

Source

pub fn take_stderr(&mut self) -> Option<BufReader<ChildStderr>>

Take the stderr reader (can only be called once)

Source

pub fn session_uuid(&self) -> Result<Uuid>

Get the session UUID if available Returns an error if no response has been received yet

Source

pub async fn ping(&mut self) -> bool

Test if the Claude connection is working by sending a ping message Returns true if Claude responds with “pong”, false otherwise

Source

pub async fn enable_tool_approval(&mut self) -> Result<()>

Enable the tool approval protocol by performing the initialization handshake.

After calling this method, the CLI will send ControlRequest messages when Claude wants to use a tool. You must handle these by calling send_control_response() with an appropriate response.

Important: The client must have been created with ClaudeCliBuilder::permission_prompt_tool("stdio") for this to work.

§Example
use claude_codes::{AsyncClient, ClaudeCliBuilder, ClaudeOutput, ControlRequestPayload};

let child = ClaudeCliBuilder::new()
    .model("sonnet")
    .permission_prompt_tool("stdio")
    .spawn()
    .await?;

let mut client = AsyncClient::new(child)?;
client.enable_tool_approval().await?;

// Now when you receive messages, you may get ControlRequest messages
// that need responses
Source

pub async fn send_control_response( &mut self, response: ControlResponse, ) -> Result<()>

Send a control response back to the CLI.

Use this to respond to ControlRequest messages received during tool approval. The easiest way to create responses is using the helper methods on ToolPermissionRequest:

§Example
use claude_codes::{AsyncClient, ClaudeOutput, ControlRequestPayload};

if let ClaudeOutput::ControlRequest(req) = output {
    if let ControlRequestPayload::CanUseTool(perm_req) = &req.request {
        // Use the ergonomic helpers on ToolPermissionRequest
        let response = if perm_req.tool_name == "Bash" {
            perm_req.deny("Bash commands not allowed", &req.request_id)
        } else {
            perm_req.allow(&req.request_id)
        };
        client.send_control_response(response).await?;
    }
}
Source

pub fn is_tool_approval_enabled(&self) -> bool

Check if tool approval protocol is enabled

Trait Implementations§

Source§

impl Drop for AsyncClient

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.