Skip to main content

Query

Struct Query 

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

Low-level query session handler for Claude Code CLI communication.

Manages the bidirectional JSON stream protocol between the SDK and the CLI. On startup, a background tokio task is spawned to continuously read messages from the transport and route them:

  • Control responses are delivered to the waiting control-request caller via oneshot channels.
  • Control requests (permissions, hooks, MCP) are handled by the background task.
  • SDK messages (user, assistant, system, result) are parsed and delivered via an mpsc channel.

This architecture mirrors the Python SDK’s task-group model and enables concurrent send and receive operations.

Implementations§

Source§

impl Query

Source

pub async fn initialize( &mut self, hooks_config: Map<String, Value>, ) -> Result<Option<Value>>

Sends the initialization handshake to the CLI.

Registers hook callbacks and agent definitions with the CLI process, and waits for the initialization response.

Returns the initialization response payload, or None if not in streaming mode.

§Example
use claude_code::Query;
use serde_json::Map;
use serde_json::Value;

let _ = query.initialize(Map::<String, Value>::new()).await?;
Source

pub fn initialization_result(&self) -> Option<Value>

Returns the initialization result from the CLI handshake.

Returns None if initialize() has not been called yet.

§Example
use claude_code::Query;

fn demo(query: &Query) {
    let _info = query.initialization_result();
}
Source

pub async fn send_user_message( &self, prompt: &str, session_id: &str, ) -> Result<()>

Sends a user text message to the CLI.

§Example
use claude_code::Query;

query.send_user_message("hello", "default").await?;
Source

pub async fn send_raw_message(&self, message: Value) -> Result<()>

Sends a raw JSON message to the CLI without any transformation.

§Example
use claude_code::Query;
use serde_json::json;

query.send_raw_message(json!({"type":"user","message":{"role":"user","content":"hi"}})).await?;
Source

pub async fn send_input_messages(&self, messages: Vec<Value>) -> Result<()>

Sends multiple input messages to the CLI without closing stdin.

§Example
use claude_code::Query;
use serde_json::json;

query
    .send_input_messages(vec![json!({"type":"user","message":{"role":"user","content":"hello"}})])
    .await?;
Source

pub async fn send_input_from_stream<S>(&self, messages: S) -> Result<()>
where S: Stream<Item = Value> + Unpin,

Sends streamed input messages to the CLI without closing stdin.

§Example
use claude_code::Query;
use futures::stream;
use serde_json::json;

query
    .send_input_from_stream(stream::iter(vec![json!({"type":"user","message":{"role":"user","content":"hello"}})]))
    .await?;
Source

pub fn spawn_input_from_stream<S>( &self, messages: S, ) -> Result<JoinHandle<Result<()>>>
where S: Stream<Item = Value> + Send + Unpin + 'static,

Spawns a background task that streams input messages to the CLI.

This is useful for long-lived or unbounded input streams where the caller should continue processing messages concurrently.

The returned task completes when the input stream ends or a write error occurs. It does not close stdin.

§Example
use claude_code::Query;
use futures::stream;
use serde_json::json;

let handle = query.spawn_input_from_stream(stream::iter(vec![
    json!({"type":"user","message":{"role":"user","content":"hello"}}),
]))?;
handle.await??;
Source

pub async fn stream_input(&self, messages: Vec<Value>) -> Result<()>

Streams multiple messages to the CLI and closes the input stream.

If SDK MCP servers or hooks are present, stdin close is deferred until the first result message is received (or a timeout expires).

§Example
use claude_code::Query;
use serde_json::json;

query
    .stream_input(vec![json!({"type":"user","message":{"role":"user","content":"hello"}})])
    .await?;
Source

pub async fn stream_input_from_stream<S>(&self, messages: S) -> Result<()>
where S: Stream<Item = Value> + Unpin,

Streams messages from an async stream source and closes the input stream.

§Example
use claude_code::Query;
use futures::stream;
use serde_json::json;

query
    .stream_input_from_stream(stream::iter(vec![json!({"type":"user","message":{"role":"user","content":"hello"}})]))
    .await?;
Source

pub async fn end_input(&self) -> Result<()>

Closes the input stream without sending any messages.

§Example
use claude_code::Query;

query.end_input().await?;
Source

pub async fn receive_next_message(&mut self) -> Result<Option<Message>>

Receives the next content message from the CLI.

Messages are delivered by the background reader task via an mpsc channel. Control messages are handled transparently by the background task.

Returns None when the stream is exhausted (no more messages).

§Example
use claude_code::Query;

while let Some(message) = query.receive_next_message().await? {
    println!("{message:?}");
}
Source

pub async fn get_mcp_status(&self) -> Result<McpStatusResponse>

Queries the status of connected MCP servers via the CLI.

§Example
use claude_code::Query;

let _status = query.get_mcp_status().await?;
Source

pub async fn interrupt(&self) -> Result<()>

Sends an interrupt signal to the CLI to stop the current operation.

§Example
use claude_code::Query;

query.interrupt().await?;
Source

pub async fn set_permission_mode(&self, mode: &str) -> Result<()>

Changes the permission mode via a control request.

§Example
use claude_code::Query;

query.set_permission_mode("plan").await?;
Source

pub async fn set_model(&self, model: Option<&str>) -> Result<()>

Changes the model used by the CLI via a control request.

§Example
use claude_code::Query;

query.set_model(Some("sonnet")).await?;
Source

pub async fn rewind_files(&self, user_message_id: &str) -> Result<()>

Rewinds file changes to a specific user message checkpoint.

§Example
use claude_code::Query;

query.rewind_files("user-msg-1").await?;
Source

pub async fn reconnect_mcp_server(&self, server_name: &str) -> Result<()>

Reconnects a disconnected or failed MCP server.

Source

pub async fn toggle_mcp_server( &self, server_name: &str, enabled: bool, ) -> Result<()>

Enables or disables an MCP server.

Source

pub async fn stop_task(&self, task_id: &str) -> Result<()>

Stops a running task.

Source

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

Closes the query session.

§Example
use claude_code::Query;

query.close().await?;

Trait Implementations§

Source§

impl Drop for Query

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl Freeze for Query

§

impl !RefUnwindSafe for Query

§

impl Send for Query

§

impl Sync for Query

§

impl Unpin for Query

§

impl UnsafeUnpin for Query

§

impl !UnwindSafe for Query

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more