Skip to main content

QueryCommand

Struct QueryCommand 

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

Builder for claude -p <prompt> (oneshot print-mode queries).

This is the primary command for programmatic use. It runs a single prompt through Claude and returns the result.

§Example

use claude_wrapper::{Claude, ClaudeCommand, QueryCommand, OutputFormat};

let claude = Claude::builder().build()?;

let output = QueryCommand::new("explain this error: file not found")
    .model("sonnet")
    .output_format(OutputFormat::Json)
    .max_turns(1)
    .execute(&claude)
    .await?;

Implementations§

Source§

impl QueryCommand

Source

pub fn new(prompt: impl Into<String>) -> Self

Create a new query command with the given prompt.

Source

pub fn model(self, model: impl Into<String>) -> Self

Set the model to use (e.g. “sonnet”, “opus”, or a full model ID).

Source

pub fn system_prompt(self, prompt: impl Into<String>) -> Self

Set a custom system prompt (replaces the default).

Source

pub fn append_system_prompt(self, prompt: impl Into<String>) -> Self

Append to the default system prompt.

Source

pub fn output_format(self, format: OutputFormat) -> Self

Set the output format.

Source

pub fn max_budget_usd(self, budget: f64) -> Self

Set the maximum budget in USD.

Source

pub fn permission_mode(self, mode: PermissionMode) -> Self

Set the permission mode.

Source

pub fn allowed_tools<I, T>(self, tools: I) -> Self
where I: IntoIterator<Item = T>, T: Into<ToolPattern>,

Add allowed tool patterns.

Accepts anything convertible into ToolPattern, including bare strings (e.g. "Bash", "Bash(git log:*)", "mcp__my-server__*") and values produced by ToolPattern’s constructors.

use claude_wrapper::{QueryCommand, ToolPattern};

let cmd = QueryCommand::new("hi")
    .allowed_tools(["Bash", "Read"]) // raw strings still work
    .allowed_tool(ToolPattern::tool_with_args("Bash", "git log:*"))
    .allowed_tool(ToolPattern::all("Write"));
Source

pub fn allowed_tool(self, tool: impl Into<ToolPattern>) -> Self

Add a single allowed tool pattern.

Source

pub fn disallowed_tools<I, T>(self, tools: I) -> Self
where I: IntoIterator<Item = T>, T: Into<ToolPattern>,

Add disallowed tool patterns.

Source

pub fn disallowed_tool(self, tool: impl Into<ToolPattern>) -> Self

Add a single disallowed tool pattern.

Source

pub fn mcp_config(self, path: impl Into<String>) -> Self

Add an MCP config file path.

Source

pub fn add_dir(self, dir: impl Into<String>) -> Self

Add an additional directory for tool access.

Source

pub fn effort(self, effort: Effort) -> Self

Set the effort level.

Source

pub fn max_turns(self, turns: u32) -> Self

Set the maximum number of turns.

Source

pub fn json_schema(self, schema: impl Into<String>) -> Self

Set a JSON schema for structured output validation.

Source

pub fn continue_session(self) -> Self

Continue the most recent conversation.

Source

pub fn resume(self, session_id: impl Into<String>) -> Self

Resume a specific session by ID.

Source

pub fn session_id(self, id: impl Into<String>) -> Self

Use a specific session ID.

Source

pub fn fallback_model(self, model: impl Into<String>) -> Self

Set a fallback model for when the primary model is overloaded.

Source

pub fn no_session_persistence(self) -> Self

Disable session persistence (sessions won’t be saved to disk).

Source

pub fn forward_subagent_text(self) -> Self

Forward nested subagent text and thinking as stream-json messages (--forward-subagent-text). Parent tool-use IDs remain in the raw events. Only meaningful with stream-json output; duplex sessions already use it.

Source

pub fn allow_dangerously_skip_permissions(self) -> Self

Make bypass mode available without activating it (--allow-dangerously-skip-permissions). This does not select a bypass permission mode or disable permission checks by itself.

Source

pub fn dangerously_skip_permissions(self) -> Self

Bypass all permission checks. Only use in sandboxed environments.

Source

pub fn agent(self, agent: impl Into<String>) -> Self

Pin the session to a named subagent (--agent <name>).

name is resolved by the CLI in this order: inline definitions from Self::agents_json, then user-level ~/.claude/agents/<name>.md files, then project-level dirs loaded by the active --setting-sources.

Caveat: as of Claude Code 2.1.143, the CLI silently ignores an unknown name and falls back to the default behavior – no warning, no error. Callers that want a hard “agent must exist” semantics should validate the name out of band (e.g. via crate::artifacts::AgentsRoot::get) before passing it here.

Source

pub fn agents_json(self, json: impl Into<String>) -> Self

Inline subagent definitions for this session (--agents <json>).

json is a JSON object keyed by agent name, with each value carrying at least description and prompt. Inline definitions take precedence over on-disk ~/.claude/agents/*.md of the same name. Pass Self::agent to select which one to use as the session’s persona.

Example: {"reviewer": {"description": "Reviews code", "prompt": "You are a code reviewer"}}.

Source

pub fn tools(self, tools: impl IntoIterator<Item = impl Into<String>>) -> Self

Set the list of available built-in tools.

Use "" to disable all tools, "default" for all tools, or specific tool names like ["Bash", "Edit", "Read"]. This is different from allowed_tools which controls MCP tool permissions.

Source

pub fn file(self, spec: impl Into<String>) -> Self

Add a file resource to download at startup.

Format: file_id:relative_path (e.g. file_abc:doc.txt).

Source

pub fn include_partial_messages(self) -> Self

Include partial message chunks as they arrive.

Only works with --output-format stream-json.

Source

pub fn input_format(self, format: InputFormat) -> Self

Set the input format.

Source

pub fn strict_mcp_config(self) -> Self

Only use MCP servers from --mcp-config, ignoring all other MCP configurations.

Source

pub fn settings(self, settings: impl Into<String>) -> Self

Path to a settings JSON file or a JSON string.

Source

pub fn fork_session(self) -> Self

When resuming, create a new session ID instead of reusing the original.

Source

pub fn worktree(self) -> Self

Create a new git worktree for this session, providing an isolated working directory.

Source

pub fn worktree_named(self, name: impl Into<String>) -> Self

Create a new git worktree with an explicit name, providing an isolated working directory.

Equivalent to Self::worktree but emits --worktree NAME, pinning the worktree’s directory/branch name rather than letting the CLI auto-generate one.

§Example
use claude_wrapper::{Claude, ClaudeCommand, QueryCommand};

let claude = Claude::builder().build()?;

let output = QueryCommand::new("refactor the parser")
    .worktree_named("parser-refactor")
    .execute(&claude)
    .await?;
Source

pub fn brief(self) -> Self

Enable brief mode, which activates the SendUserMessage tool for agent-to-user communication.

Source

pub fn debug_filter(self, filter: impl Into<String>) -> Self

Enable debug logging with an optional filter (e.g., “api,hooks”).

Source

pub fn debug_file(self, path: impl Into<String>) -> Self

Write debug logs to the specified file path.

Source

pub fn betas(self, betas: impl Into<String>) -> Self

Beta feature headers for API key authentication.

Source

pub fn plugin_dir(self, dir: impl Into<String>) -> Self

Load plugins from the specified directory for this session.

Source

pub fn plugin_url(self, url: impl Into<String>) -> Self

Fetch a plugin .zip from a URL for this session only (--plugin-url). Repeatable; the URL-based counterpart to Self::plugin_dir.

Source

pub fn setting_sources(self, sources: impl Into<String>) -> Self

Comma-separated list of setting sources to load (e.g., “user,project,local”).

Source

pub fn hermetic(self) -> Self

Seal the ambient ~/.claude config for a reproducible run (HermeticScope::Full).

Equivalent to hermetic_scoped(HermeticScope::Full): drops all ambient setting sources (--setting-sources ""), restricts MCP to --mcp-config servers (--strict-mcp-config), and moves per-machine sections out of the system prompt (--exclude-dynamic-system-prompt-sections). Provide everything the run needs explicitly via Self::append_system_prompt, Self::mcp_config, Self::add_dir, and friends.

This is not Self::bare: a hermetic seal leaves OAuth and keychain auth working, whereas --bare forces API-key billing. A later Self::setting_sources call overrides the seal scope.

Source

pub fn hermetic_scoped(self, scope: HermeticScope) -> Self

Seal the ambient ~/.claude config at an explicit HermeticScope.

See Self::hermetic for the flag set. Use HermeticScope::Project to keep the user’s global ~/.claude while sealing project and local ambient config.

Source

pub fn tmux(self) -> Self

Create a tmux session for the worktree.

Source

pub fn bare(self) -> Self

Run in minimal mode (--bare).

Skips hooks, LSP, plugin sync, attribution, auto-memory, background prefetches, keychain reads, and CLAUDE.md auto-discovery. Sets CLAUDE_CODE_SIMPLE=1 inside the child. Anthropic auth is restricted to ANTHROPIC_API_KEY or apiKeyHelper via --settings; OAuth and keychain are never read. Third-party providers (Bedrock/Vertex/Foundry) use their own credentials as normal.

Intended for headless/CI use where you want deterministic context: provide everything explicitly via --system-prompt, --append-system-prompt, --add-dir, --mcp-config, --settings, --agents, and --plugin-dir. Skills still resolve via explicit /skill-name references.

Source

pub fn disable_slash_commands(self) -> Self

Disable all slash-command skills (--disable-slash-commands).

Source

pub fn safe_mode(self) -> Self

Start with all customizations disabled (--safe-mode).

Disables CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands and agents, output styles, and other customizations for troubleshooting a broken configuration. Admin-managed (policy) settings still apply. Auth, model selection, built-in tools, and permissions work normally. Sets CLAUDE_CODE_SAFE_MODE=1 inside the child.

Source

pub fn include_hook_events(self) -> Self

Include every hook lifecycle event in the stream-json output (--include-hook-events). Only meaningful with OutputFormat::StreamJson.

Source

pub fn exclude_dynamic_system_prompt_sections(self) -> Self

Move per-machine sections (cwd, env info, memory paths, git status) out of the system prompt and into the first user message (--exclude-dynamic-system-prompt-sections). Improves cross-user prompt-cache reuse. Only applies with the default system prompt; ignored with --system-prompt.

Source

pub fn name(self, name: impl Into<String>) -> Self

Set a display name for this session (--name). Shown in the prompt box, /resume picker, and terminal title.

Source

pub fn from_pr(self, pr: impl Into<String>) -> Self

Resume a session linked to a PR by number or URL (--from-pr <value>).

This wrapper only supports the valued form; the CLI’s no-value mode opens an interactive picker and would hang a headless caller.

Source

pub fn verbose(self, value: bool) -> Self

Enable verbose logging (--verbose), overriding the CLI’s configured verbose-mode setting.

Note: OutputFormat::StreamJson already forces --verbose on (the CLI requires it alongside --print), so this builder only changes behavior for the text and JSON output formats. Either path emits the flag at most once.

Source

pub fn prompt_suggestions(self, value: bool) -> Self

Emit a predicted next-user-prompt after each turn (--prompt-suggestions).

In print/SDK mode the CLI emits a prompt_suggestion message alongside the normal result. Off by default.

Source

pub fn replay_user_messages(self, value: bool) -> Self

Re-emit user messages from stdin back on stdout (--replay-user-messages).

Only meaningful for bidirectional stream-json flows: the CLI requires both InputFormat::StreamJson and OutputFormat::StreamJson for this to take effect. Off by default.

Source

pub fn retry(self, policy: RetryPolicy) -> Self

Set a per-command retry policy, overriding the client default.

§Example
use claude_wrapper::{Claude, ClaudeCommand, QueryCommand, RetryPolicy};
use std::time::Duration;

let claude = Claude::builder().build()?;

let output = QueryCommand::new("explain quicksort")
    .retry(RetryPolicy::new()
        .max_attempts(5)
        .initial_backoff(Duration::from_secs(2))
        .exponential()
        .retry_on_timeout(true))
    .execute(&claude)
    .await?;
Source

pub fn extra_arg(self, arg: impl Into<String>) -> Self

Append one unvalidated Claude CLI argument to this query.

Extra arguments are emitted in insertion order after all generated options and before the -- prompt separator. In stdin mode they are the final arguments. Pass a flag and its value as separate arguments; no shell splitting or escaping is performed.

This escape hatch does not validate conflicts with typed options. Claude determines how duplicate or unsupported options behave. Callers that require a particular input or output format must prevent extra arguments from changing it.

Source

pub fn extra_args( self, args: impl IntoIterator<Item = impl Into<String>>, ) -> Self

Append unvalidated Claude CLI arguments to this query.

Preserves order across calls to this method and Self::extra_arg. See Self::extra_arg for placement and conflict semantics.

use claude_wrapper::{ClaudeCommand, QueryCommand};

let cmd = QueryCommand::new("summarize the project")
    .extra_args(["--plugin-dir", "/path with spaces/plugins"])
    .extra_arg("--brief");
assert_eq!(cmd.args(), [
    "--print", "--plugin-dir", "/path with spaces/plugins", "--brief",
    "--", "summarize the project",
]);
Source

pub fn to_command_string(&self, claude: &Claude) -> String

Return the full command as a string that could be run in a shell.

Constructs a command string using the binary path from the Claude instance, the client’s global args, and the arguments from this query – the same assembly the exec path performs, so the preview matches what actually runs. Arguments containing spaces or special shell characters are shell-quoted to be safe for shell execution.

§Example
use claude_wrapper::{Claude, QueryCommand};

let claude = Claude::builder().build()?;

let cmd = QueryCommand::new("explain quicksort")
    .model("sonnet");

let command_str = cmd.to_command_string(&claude);
println!("Would run: {}", command_str);
Source

pub async fn execute_cancellable<C>( &self, claude: &Claude, cancel: C, ) -> Result<CommandOutput>
where C: Future<Output = ()> + Send,

Execute the query with an explicit cancellation signal.

Cancellation and the client timeout terminate the owned process group and reap the direct child before returning. Retry does not apply.

Source

pub async fn execute_json(&self, claude: &Claude) -> Result<QueryResult>

Execute the query and parse the JSON result.

This is a convenience method that sets OutputFormat::Json and deserializes the response into a QueryResult.

Source

pub async fn execute_json_cancellable<C>( &self, claude: &Claude, cancel: C, ) -> Result<QueryResult>
where C: Future<Output = ()> + Send,

Execute the query cancellably and parse the JSON result.

Process cleanup is complete before a cancellation, timeout, or stdin communication error is returned.

Source

pub fn execute_sync(&self, claude: &Claude) -> Result<CommandOutput>

Blocking analog of QueryCommand::execute that honours the configured RetryPolicy.

Overrides the blanket ClaudeCommandSyncExt::execute_sync impl so retries still fire on the sync path.

Source

pub fn execute_json_sync(&self, claude: &Claude) -> Result<QueryResult>

Blocking mirror of QueryCommand::execute_json.

Source

pub fn prompt_via_stdin(self, value: bool) -> Self

Route the prompt through stdin rather than argv.

When set, the prompt body does not appear in the spawned process’s argument list (ps, /proc/PID/cmdline, APM agents). Use this for any prompt that contains sensitive content: private code, internal design notes, orchestrator dispatch specs.

Requires that claude --print read from stdin when no positional prompt is supplied (verified as of claude 2.1.x).

Note: retry is skipped when stdin mode is active – the stdin pipe is consumed after the first attempt and cannot be rewound.

§Example
use claude_wrapper::{Claude, ClaudeCommand, QueryCommand};
let claude = Claude::builder().build()?;
let out = QueryCommand::new("my secret prompt")
    .prompt_via_stdin(true)
    .execute(&claude)
    .await?;

Trait Implementations§

Source§

impl ClaudeCommand for QueryCommand

Source§

type Output = CommandOutput

The typed result of executing this command.
Source§

fn args(&self) -> Vec<String>

Build the CLI argument list for this command.
Source§

async fn execute(&self, claude: &Claude) -> Result<CommandOutput>

Execute the command using the given claude client. Read more
Source§

impl Clone for QueryCommand

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for QueryCommand

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. 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> ClaudeCommandSyncExt for T
where T: ClaudeCommand<Output = CommandOutput>,

Source§

fn execute_sync(&self, claude: &Claude) -> Result<CommandOutput, Error>

Blocking analog of ClaudeCommand::execute for commands producing CommandOutput.
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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