pub struct ClaudeClient { /* private fields */ }Expand description
Bidirectional client for streaming Claude interactions.
ClaudeClient provides a full-featured interface for interactive
conversations with Claude. Unlike the simple query
function, this client maintains a persistent connection and supports
multiple queries, callbacks, and runtime configuration changes.
§Examples
§Basic Usage
use claude_agents_sdk::ClaudeClient;
use tokio_stream::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
// Send first query
client.query("What is Rust?").await?;
// Process responses
while let Some(msg) = client.receive_messages().next().await {
println!("{:?}", msg?);
}
client.disconnect().await?;
Ok(())
}§With Tool Permission Callback
use claude_agents_sdk::{ClaudeClient, ClaudeAgentOptions, PermissionResult};
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let options = ClaudeAgentOptions::new()
.with_can_use_tool(|tool_name, input, _ctx| async move {
println!("Tool request: {} with {:?}", tool_name, input);
PermissionResult::allow()
});
let mut client = ClaudeClient::new(Some(options));
client.connect().await?;
// Queries will now invoke the callback for tool permissions
Ok(())
}Implementations§
Source§impl ClaudeClient
impl ClaudeClient
Sourcepub fn new(options: Option<ClaudeAgentOptions>) -> Self
pub fn new(options: Option<ClaudeAgentOptions>) -> Self
Create a new Claude client.
§Arguments
options- Optional configuration for the client
§Examples
use claude_agents_sdk::{ClaudeClient, ClaudeAgentOptions, PermissionMode};
// Default configuration
let client = ClaudeClient::new(None);
// With custom options
let options = ClaudeAgentOptions::new()
.with_model("claude-3-opus")
.with_permission_mode(PermissionMode::AcceptEdits);
let client = ClaudeClient::new(Some(options));Sourcepub async fn connect(&mut self) -> Result<()>
pub async fn connect(&mut self) -> Result<()>
Connect to the Claude CLI.
This establishes a connection to the CLI process and initializes the streaming session. Must be called before sending queries.
§Errors
Returns an error if:
- The CLI is not found
- The CLI version is incompatible
- Connection fails
§Examples
use claude_agents_sdk::ClaudeClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
// Client is now ready for queries
Ok(())
}Sourcepub async fn query(&mut self, prompt: &str) -> Result<()>
pub async fn query(&mut self, prompt: &str) -> Result<()>
Send a query to Claude.
Sends a new prompt to Claude. Responses can be received using
receive_messages or
receive_response.
§Arguments
prompt- The prompt to send
§Errors
Returns an error if the client is not connected.
§Examples
use claude_agents_sdk::ClaudeClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
client.query("Hello!").await?;
client.query("Follow-up question").await?;
Ok(())
}Sourcepub fn receive_messages(&mut self) -> impl Stream<Item = Result<Message>> + '_
pub fn receive_messages(&mut self) -> impl Stream<Item = Result<Message>> + '_
Get a stream of messages from the current query.
Returns a stream that yields messages as they are received from Claude. The stream ends when a result message is received.
§Examples
use claude_agents_sdk::{ClaudeClient, Message};
use tokio_stream::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
client.query("Tell me a joke").await?;
while let Some(msg) = client.receive_messages().next().await {
match msg? {
Message::Assistant(asst) => println!("{}", asst.text()),
Message::Result(_) => break,
_ => {}
}
}
Ok(())
}Sourcepub async fn receive_response(&mut self) -> Result<(String, ResultMessage)>
pub async fn receive_response(&mut self) -> Result<(String, ResultMessage)>
Receive the complete response for the current query.
Collects all messages until a result message is received and returns the combined response text along with the result metadata.
§Returns
A tuple of (response_text, result_message).
§Examples
use claude_agents_sdk::ClaudeClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
client.query("What is 2 + 2?").await?;
let (response, result) = client.receive_response().await?;
println!("Response: {}", response);
println!("Turns: {}", result.num_turns);
Ok(())
}Sourcepub async fn interrupt(&self) -> Result<()>
pub async fn interrupt(&self) -> Result<()>
Interrupt the current operation.
Sends an interrupt signal to Claude, stopping the current response.
§Examples
use claude_agents_sdk::ClaudeClient;
use tokio::time::{timeout, Duration};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
client.query("Write a very long story").await?;
// Interrupt after 5 seconds
tokio::time::sleep(Duration::from_secs(5)).await;
client.interrupt().await?;
Ok(())
}Sourcepub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()>
pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()>
Change the permission mode for the session.
§Arguments
mode- The new permission mode
§Examples
use claude_agents_sdk::{ClaudeClient, PermissionMode};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
// Switch to accept edits mode
client.set_permission_mode(PermissionMode::AcceptEdits).await?;
Ok(())
}Sourcepub async fn set_model(&self, model: impl Into<String>) -> Result<()>
pub async fn set_model(&self, model: impl Into<String>) -> Result<()>
Change the model for the session.
§Arguments
model- The new model identifier
§Examples
use claude_agents_sdk::ClaudeClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
// Switch to a different model
client.set_model("claude-3-opus").await?;
Ok(())
}Sourcepub async fn rewind_files(
&self,
user_message_id: impl Into<String>,
) -> Result<()>
pub async fn rewind_files( &self, user_message_id: impl Into<String>, ) -> Result<()>
Rewind files to a specific user message.
This is only available when file checkpointing is enabled.
§Arguments
user_message_id- The UUID of the user message to rewind to
§Examples
use claude_agents_sdk::{ClaudeClient, ClaudeAgentOptions};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut options = ClaudeAgentOptions::new();
options.enable_file_checkpointing = true;
let mut client = ClaudeClient::new(Some(options));
client.connect().await?;
// Later, rewind to a previous state
client.rewind_files("user-message-uuid").await?;
Ok(())
}Sourcepub async fn get_server_info(&self) -> Option<Value>
pub async fn get_server_info(&self) -> Option<Value>
Get server initialization info.
Returns the initialization response from the CLI, which includes available commands, output styles, and server capabilities.
§Returns
Some(Value) with server info if connected and initialized, None otherwise.
§Examples
use claude_agents_sdk::ClaudeClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
if let Some(info) = client.get_server_info().await {
println!("Commands: {:?}", info.get("commands"));
println!("Output style: {:?}", info.get("output_style"));
}
Ok(())
}Sourcepub async fn get_mcp_status(&self) -> Result<Value>
pub async fn get_mcp_status(&self) -> Result<Value>
Get current MCP server connection status (streaming mode only).
Sourcepub async fn disconnect(&mut self) -> Result<()>
pub async fn disconnect(&mut self) -> Result<()>
Disconnect from the Claude CLI.
Gracefully closes the connection to the CLI process.
§Examples
use claude_agents_sdk::ClaudeClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
// Use the client...
client.disconnect().await?;
Ok(())
}Sourcepub fn is_connected(&self) -> bool
pub fn is_connected(&self) -> bool
Check if the client is connected.
Source§impl ClaudeClient
impl ClaudeClient
Sourcepub fn into_guard(self) -> ClientGuard
pub fn into_guard(self) -> ClientGuard
Convert this client into a guard that automatically disconnects on drop.
This is the Rust equivalent of Python’s async with ClaudeSDKClient() as client:
pattern.