Skip to main content

Overview

The query() function is the simplest way to interact with Claude Code. It’s perfect for one-shot questions, batch processing, and scenarios where you know all your inputs upfront.
For interactive conversations with back-and-forth messaging, use ClaudeSDKClient instead.

When to Use query()

Use query() when you need:
  • Simple one-off questions - “What is 2+2?”
  • Batch processing - Processing multiple independent prompts
  • Code generation - Creating files or analyzing code
  • Automation scripts - CI/CD pipelines, automated tasks
  • Fire-and-forget - When all inputs are known upfront

Basic Example

Here’s the simplest way to use query():

Working with Message Types

The query() function yields different message types. Here’s how to handle them:

Using Options

Customize Claude’s behavior with ClaudeAgentOptions:

Permission Modes

Control how Claude handles potentially dangerous operations:
1

Default Mode

Claude prompts before executing dangerous operations:
2

Accept Edits

Automatically accept file edits (but still prompt for other operations):
3

Bypass Permissions

Allow all operations without prompts (use with caution):

Complete Example

Here’s a practical example that creates a file and handles all message types:

Streaming Mode

For advanced use cases, you can stream multiple prompts:
Streaming mode is still unidirectional - all prompts are sent first, then all responses are received. For true bidirectional communication, use ClaudeSDKClient.

Best Practices

Always handle AssistantMessage, UserMessage, SystemMessage, and ResultMessage types to capture the full conversation flow.
Use the most restrictive permission mode that works for your use case. Start with default and only escalate if needed.
When working with files, always set cwd in options to ensure Claude operates in the correct directory.
Use allowed_tools to restrict which tools Claude can use, improving security and reducing unexpected behavior.
Provide clear context through system_prompt to guide Claude’s responses and improve result quality.

Next Steps

Interactive Conversations

Learn how to use ClaudeSDKClient for bidirectional conversations

Custom Tools

Create custom tools to extend Claude’s capabilities

Configuration Options

Explore all available ClaudeAgentOptions

Message Types

Deep dive into message types and content blocks