client
Class info¶
Classes¶
| Name | Children | Inherits |
|---|---|---|
| ClaudeSDKClient clawd_code_sdk.client Client for bidirectional, interactive conversations with Claude Code. |
||
| MessageParseError clawd_code_sdk._errors Raised when unable to parse a message from CLI output. |
||
| Query clawd_code_sdk._internal.query Handles bidirectional control protocol on top of Transport. |
🛈 DocStrings¶
Claude SDK Client for interacting with Claude Code.
STRICT_MESSAGES_ENV
module-attribute
¶
Env var: when truthy, an unknown CLI message type ends receive_messages with an error.
ClaudeSDKClient
¶
Client for bidirectional, interactive conversations with Claude Code.
Key features: - Bidirectional: Send and receive messages at any time - Stateful: Maintains conversation context across messages - Interactive: Send follow-ups based on responses - Control flow: Support for interrupts and session management
Caveat: As of v0.0.21, you cannot use a ClaudeSDKClient instance across different async runtime contexts (e.g., different trio nurseries or asyncio task groups). The client internally maintains a persistent anyio task group for reading messages that remains active from connect() until disconnect(). This means you must complete all operations with the client within the same async context where it was connected. Ideally, this limitation should not exist.
Source code in src/clawd_code_sdk/client.py
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | |
query_cost
instance-attribute
¶
Cost in USD for the current/last query only (reset on each query() call).
query_usage
instance-attribute
¶
Token usage for the current/last query only (reset on each query() call).
session_cost
instance-attribute
¶
Cumulative cost in USD across all queries in this session.
session_state
instance-attribute
¶
Cumulative token usage across all queries in this session.
status
instance-attribute
¶
Current client status, or None when idle.
__aenter__
async
¶
Enter async context - automatically connects with empty stream for interactive use.
__aexit__
async
¶
__init__
¶
__init__(options: ClaudeAgentOptions | None = None, transport: Transport | None = None) -> None
Initialize Claude SDK client.
Source code in src/clawd_code_sdk/client.py
apply_flag_settings
async
¶
apply_flag_settings(settings: ClaudeCodeSettings) -> None
Apply runtime settings overrides without restarting the session.
Flag settings are an in-memory settings source that gets merged with other sources (user, project, etc.) to produce the effective settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
ClaudeCodeSettings
|
Settings to apply. Only fields that were set explicitly (and are not None) are sent: defaults would override every other settings source. |
required |
Source code in src/clawd_code_sdk/client.py
background_tasks
async
¶
Move running foreground tasks (or a single tool use) to the background.
Returns:
| Type | Description |
|---|---|
bool
|
Whether anything was backgrounded. |
Source code in src/clawd_code_sdk/client.py
call_tool
async
¶
call_tool(
tool: str, arguments: dict[str, Any] | None = None, *, timeout: float | None = 600.0
) -> Any
Call a tool on the server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool
|
str
|
The name of the tool to call |
required |
arguments
|
dict[str, Any] | None
|
Optional dictionary of arguments for the tool |
None
|
timeout
|
float | None
|
Seconds to wait for the tool's result (None: no limit) |
600.0
|
Returns:
| Type | Description |
|---|---|
Any
|
The result of the tool call |
Source code in src/clawd_code_sdk/client.py
cancel_async_message
async
¶
Drop a pending async user message from the command queue by uuid.
Source code in src/clawd_code_sdk/client.py
channel_enable
async
¶
Enable MCP channel notifications for a marketplace plugin server.
Source code in src/clawd_code_sdk/client.py
claude_oauth_wait_for_completion
async
¶
claude_oauth_wait_for_completion(
*, timeout: float | None = None
) -> ClaudeOAuthWaitForCompletionResponse
Wait for an in-progress Claude OAuth flow to complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float | None
|
Seconds to wait for the user to finish the browser login (None, the default: no limit). |
None
|
Returns:
| Type | Description |
|---|---|
ClaudeOAuthWaitForCompletionResponse
|
Account details (email, organization, subscriptionType, etc.). |
Source code in src/clawd_code_sdk/client.py
connect
async
¶
Connect to Claude Code CLI and initialize the session.
Source code in src/clawd_code_sdk/client.py
disconnect
async
¶
end_session
async
¶
generate_session_title
async
¶
generate_session_title(
description: str, *, persist: bool = False, timeout: float | None = 120.0
) -> str | None
Generate a session title from description with the CLI's title model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
description
|
str
|
Text to title (the CLI reads its trailing ~1000 characters). |
required |
persist
|
bool
|
Store it as the current session's title; a session that has a title already returns that one. |
False
|
timeout
|
float | None
|
Seconds to wait for the model (None: no limit). |
120.0
|
Returns:
| Type | Description |
|---|---|
str | None
|
The title, or None when the text is too short to title. |
Source code in src/clawd_code_sdk/client.py
get_binary_version
async
¶
Get version info of the running Claude Code binary.
get_context_usage
async
¶
get_context_usage(
detail: Literal["summary", "full"] | None = None,
) -> SDKControlGetContextUsageResponse
Get a breakdown of current context window usage by category.
Source code in src/clawd_code_sdk/client.py
get_file
async
¶
get_file(path: str, max_bytes: int | None = None) -> SDKControlReadFileResponse
Get the contents of a file from the server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the file to read |
required |
max_bytes
|
int | None
|
Maximum number of bytes to read (default: None, no limit) |
None
|
Returns:
| Type | Description |
|---|---|
SDKControlReadFileResponse
|
The file contents and metadata |
Source code in src/clawd_code_sdk/client.py
get_hooks_listing
async
¶
Get the listing of configured hooks (same data as /hooks).
get_mcp_status
async
¶
get_mcp_status() -> list[McpServerStatusEntry]
Get current MCP server connection status.
Returns:
| Type | Description |
|---|---|
list[McpServerStatusEntry]
|
Validated MCP status response containing server statuses, |
list[McpServerStatusEntry]
|
configurations, tools, and connection information. |
Source code in src/clawd_code_sdk/client.py
get_server_info
async
¶
get_server_info() -> ClaudeCodeServerInfo | None
Get server initialization info including available commands and output styles.
Returns initialization information from the Claude Code server including: - Available commands (slash commands, system commands, etc.) - Current and available output styles - Server capabilities
Returns:
| Type | Description |
|---|---|
ClaudeCodeServerInfo | None
|
Parsed server info, or None if not yet initialized |
Source code in src/clawd_code_sdk/client.py
get_settings
async
¶
get_settings() -> GetSettingsResponse
Get the effective merged settings and raw per-source settings.
Source code in src/clawd_code_sdk/client.py
get_task_output
async
¶
get_task_output(task_id: str) -> SDKControlGetTaskOutputResponse
Read the output collected so far for a background task.
Source code in src/clawd_code_sdk/client.py
get_usage
async
¶
get_usage(*, skip_behaviors: bool = True) -> SDKControlGetUsageResponse
Get session usage and plan rate-limit windows (experimental, shape may change).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
skip_behaviors
|
bool
|
Skip the (slow) scan of local transcripts that fills
|
True
|
Source code in src/clawd_code_sdk/client.py
interrupt
async
¶
interrupt(*, cancel_queued: bool = False) -> SDKControlInterruptResponse | None
Send interrupt signal (only works with streaming mode).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cancel_queued
|
bool
|
Also cancel queued (not yet started) user messages. |
False
|
Returns:
| Type | Description |
|---|---|
SDKControlInterruptResponse | None
|
Which queued messages are still queued / were cancelled |
SDKControlInterruptResponse | None
|
(None on CLIs that don't report it). |
Source code in src/clawd_code_sdk/client.py
list_models
async
¶
list_models() -> list[ClaudeCodeModelInfo]
Fetch the list of available models from the CLI.
Source code in src/clawd_code_sdk/client.py
list_permission_rules
async
¶
List the effective permission rules (raw state payload).
Source code in src/clawd_code_sdk/client.py
mcp_authenticate
async
¶
mcp_authenticate(server_name: str) -> McpAuthenticateResponse
Trigger OAuth authentication for an MCP server.
Returns:
| Type | Description |
|---|---|
McpAuthenticateResponse
|
Response indicating whether user action is required and the auth URL if so. |
Source code in src/clawd_code_sdk/client.py
mcp_clear_auth
async
¶
Clear OAuth credentials for an MCP server.
Source code in src/clawd_code_sdk/client.py
mcp_oauth_callback_url
async
¶
Provide an OAuth redirect callback URL to complete an MCP server OAuth flow.
After the user completes browser-based OAuth, call this with the full redirect URL (containing the authorization code) to finish the flow.
Source code in src/clawd_code_sdk/client.py
mcp_reconnect
async
¶
Reconnect to an MCP server.
mcp_toggle
async
¶
Enable or disable an MCP server.
Source code in src/clawd_code_sdk/client.py
one_shot
async
classmethod
¶
one_shot(
*prompts: str | UserPrompt,
options: ClaudeAgentOptions | None = None,
transport: Transport | None = None,
) -> AsyncIterator[Message]
One-shot query convenience method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*prompts
|
str | UserPrompt
|
One or more content blocks to send. |
()
|
options
|
ClaudeAgentOptions | None
|
Optional configuration. |
None
|
transport
|
Transport | None
|
Optional transport implementation override. |
None
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[Message]
|
Messages from the conversation |
Source code in src/clawd_code_sdk/client.py
query
async
¶
query(
*prompts: str | UserPrompt,
session_id: str = "default",
parent_tool_use_id: str | None = None,
should_query: bool = True,
priority: MessagePriority | None = None,
uuid: str | None = None,
) -> None
Send a new user message with one or more content blocks.
Starts a new query: query_usage and query_cost count from here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*prompts
|
str | UserPrompt
|
One or more content blocks. Strings are converted to
UserTextPrompt automatically. Pass multiple to combine, e.g.
|
()
|
session_id
|
str
|
Session identifier for the message. |
'default'
|
parent_tool_use_id
|
str | None
|
If responding to a tool use, the tool_use block ID. |
None
|
should_query
|
bool
|
Whether to query the model for a response. Defaults to True. |
True
|
priority
|
MessagePriority | None
|
The priority of the message. Defaults to None. |
None
|
uuid
|
str | None
|
ID of the message; the CLI then reports its progress as
|
None
|
Source code in src/clawd_code_sdk/client.py
read_mcp_resource
async
¶
read_mcp_resource(server_name: str, uri: str) -> SDKControlMcpReadResourceResponse
Read a resource from a connected MCP server.
Source code in src/clawd_code_sdk/client.py
receive_messages
async
¶
receive_messages() -> AsyncIterator[Message]
Receive all messages from Claude.
Source code in src/clawd_code_sdk/client.py
receive_response
async
¶
receive_response() -> AsyncIterator[Message]
Receive messages from Claude until the response is complete.
This async iterator yields all messages in sequence and automatically
terminates when the session transitions to idle state — the
authoritative signal that the CLI has fully finished its turn
(held-back results flushed, background agent loops exited).
Stopping Behavior:
- Yields each message as it's received
- Terminates after yielding a SessionStateChangedMessage with
state='idle'
- The final message in the collected list will always be the idle
state-change message
Yields:
| Name | Type | Description |
|---|---|---|
Message |
AsyncIterator[Message]
|
Each message received |
Note
To collect all messages: messages = [msg async for msg in client.receive_response()]
Source code in src/clawd_code_sdk/client.py
register_repo_root
async
¶
register_repo_root(
directory: str | Path,
*,
reload_claude_md: bool | None = None,
reload_plugins: bool | None = None,
reload_skills: bool | None = None,
) -> None
Register an additional repository root for the session (like /add-dir).
Source code in src/clawd_code_sdk/client.py
reload_output_styles
async
¶
Re-scan output styles from disk and return the available style names.
Source code in src/clawd_code_sdk/client.py
reload_skills
async
¶
reload_skills() -> list[ClaudeCodeCommandInfo]
Re-scan skills from disk and return the refreshed skill list.
Source code in src/clawd_code_sdk/client.py
remote_control
async
¶
remote_control(*, enabled: bool) -> RemoteControlResponse | None
Toggle the remote control REPL bridge for external session access.
When enabled, starts a bridge that allows remote clients to send prompts, permission responses, interrupts, and model changes into the session.
Returns:
| Type | Description |
|---|---|
RemoteControlResponse | None
|
A |
RemoteControlResponse | None
|
when enabling, or |
Source code in src/clawd_code_sdk/client.py
rewind_files
async
¶
Rewind tracked files to their state at a specific user message.
Requires
enable_file_checkpointing=Trueto track file changesextra_args={"replay-user-messages": None}to receive UserMessage objects withuuidin the response stream
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_message_id
|
str
|
UUID of the user message to rewind to. This should be
the |
required |
Example
options = ClaudeAgentOptions(
enable_file_checkpointing=True,
extra_args={"replay-user-messages": None},
)
async with ClaudeSDKClient(options) as client:
await client.query("Make some changes to my files")
async for msg in client.receive_response():
if isinstance(msg, UserMessage) and msg.uuid:
checkpoint_id = msg.uuid # Save this for later
# Later, rewind to that point
await client.rewind_files(checkpoint_id)
Source code in src/clawd_code_sdk/client.py
seed_read_state
async
¶
Seed the CLI's readFileState cache with a path+mtime entry.
Use when the client observed a Read that has since been removed from context (e.g. by snip), so a subsequent Edit won't fail "file not read yet". If the file changed on disk since the given mtime, the seed is skipped and Edit will correctly require a fresh Read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the file that was previously Read |
required |
mtime
|
int
|
File mtime (floored ms) at the time of the observed Read |
required |
Source code in src/clawd_code_sdk/client.py
set_max_thinking_tokens
async
¶
set_max_thinking_tokens(
max_thinking_tokens: int | None,
thinking_display: Literal["summarized", "omitted", "highlights"] | None = None,
) -> None
Set the maximum number of thinking tokens (and optionally the display mode).
Source code in src/clawd_code_sdk/client.py
set_mcp_servers
async
¶
set_mcp_servers(servers: dict[str, ExternalMcpServerConfig]) -> McpSetServersResult
Add, replace, or remove MCP servers dynamically mid-session.
Allows dynamic registration of MCP servers without restarting the session. Pass an empty dict to remove all dynamic servers.
The server name is automatically injected from the dict key into each config, so callers don't need to specify it redundantly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
servers
|
dict[str, ExternalMcpServerConfig]
|
Dictionary mapping server names to server configurations. Values are typed MCP server configs (McpStdioServerConfig, McpSSEServerConfig, McpHttpServerConfig, or McpSdkServerConfig). |
required |
Returns:
| Type | Description |
|---|---|
McpSetServersResult
|
Dictionary with results: |
McpSetServersResult
|
|
McpSetServersResult
|
|
McpSetServersResult
|
|
Source code in src/clawd_code_sdk/client.py
set_model
async
¶
Change the AI model during conversation (only works with streaming mode).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | None
|
The model to use, or None to use default. Example: 'claude-sonnet-4-5' |
None
|
Source code in src/clawd_code_sdk/client.py
set_permission_mode
async
¶
set_permission_mode(mode: PermissionMode) -> SDKControlSetPermissionModeResponse | None
Change permission mode during conversation (only works with streaming mode).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
PermissionMode
|
The permission mode to set. Valid options: - 'default': CLI prompts for dangerous tools - 'acceptEdits': Auto-accept file edits - 'plan': Plan mode for planning tasks - 'bypassPermissions': Allow all tools (use with caution) |
required |
Returns:
| Type | Description |
|---|---|
SDKControlSetPermissionModeResponse | None
|
The mode now in effect (it can differ from |
SDKControlSetPermissionModeResponse | None
|
CLI answered without a payload (before Claude Code 2.1.332). |
Source code in src/clawd_code_sdk/client.py
side_question
async
¶
side_question(question: str, *, timeout: float | None = 600.0) -> SideQuestionResponse
Send a side question to the model using the current conversation context.
The model answers the question without it being added to the main conversation history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The question to ask the model. |
required |
timeout
|
float | None
|
Seconds to wait for the answer (None: no limit). |
600.0
|
Returns:
| Type | Description |
|---|---|
SideQuestionResponse
|
The model's answer, or None if no context was available. |
Source code in src/clawd_code_sdk/client.py
steer
async
¶
steer(
*prompts: str | UserPrompt, priority: MessagePriority = "now", session_id: str = "default"
) -> str
Send a user message into the running query instead of starting a new one.
query_usage and query_cost keep counting the running query. With
"now" the CLI takes the message in at once: it ends the cycle that is
generating (which reports a result of its own) or moves a running foreground
tool to the background, and works on the message in the same query. "later"
waits for the running cycle (e.g. while a permission request is open).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*prompts
|
str | UserPrompt
|
Content blocks of the message (strings become text blocks). |
()
|
priority
|
MessagePriority
|
When the CLI takes the message in. |
'now'
|
session_id
|
str
|
Session identifier for the message. |
'default'
|
Returns:
| Type | Description |
|---|---|
str
|
The message's uuid, which |
str
|
results' |
Source code in src/clawd_code_sdk/client.py
stop_task
async
¶
supported_agents
async
¶
supported_agents() -> list[ClaudeCodeAgentInfo]
Get the list of available subagents for the current session.
Returns:
| Type | Description |
|---|---|
list[ClaudeCodeAgentInfo]
|
List of available agents with their names, descriptions, and configuration. |
Source code in src/clawd_code_sdk/client.py
update_settings
async
¶
Persist settings to the local or user settings file.
Source code in src/clawd_code_sdk/client.py
parse_message
¶
parse_message(data: dict[str, Any]) -> Message
Parse message from CLI output into typed Message objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Raw message dictionary from CLI output |
required |
Returns:
| Type | Description |
|---|---|
Message
|
Parsed Message object |
Raises:
| Type | Description |
|---|---|
MessageParseError
|
If parsing fails or message type is unrecognized |
Source code in src/clawd_code_sdk/client.py
strict_messages
¶
Whether unknown message types raise instead of being skipped (CLAWD_STRICT_MESSAGES).
unknown_message_kind
¶
Return the type ("system/<subtype>" for system messages) if no model covers it.
Returns None for modelled types, also when the message itself is malformed.