Skip to content

ClaudeSDKClient

🛈 DocStrings

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
class 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.
    """

    def __init__(
        self,
        options: ClaudeAgentOptions | None = None,
        transport: Transport | None = None,
    ) -> None:
        """Initialize Claude SDK client."""
        options = options or ClaudeAgentOptions()
        self.options = options
        self._custom_transport = transport
        self._query: Query | None = None
        self._initialization_result: ClaudeCodeServerInfo | None = None
        self.session_usage: Usage = Usage()
        self.session_state: SessionState = "idle"
        """Cumulative token usage across all queries in this session."""
        self.query_usage: Usage = Usage()
        """Token usage for the current/last query only (reset on each query() call)."""
        self.session_cost: float = 0.0
        """Cumulative cost in USD across all queries in this session."""
        self.query_cost: float = 0.0
        """Cost in USD for the current/last query only (reset on each query() call)."""
        self.status: SDKStatus | None = None
        """Current client status, or None when idle."""

        self._logfire_prompt: str | None = None
        self._cli_version_checked = False

    def _ensure_connected(self) -> Query:
        """Return the active Query, raising if not connected."""
        if not self._query:
            raise CLIConnectionError("Not connected. Call connect() first.")
        return self._query

    async def connect(self) -> None:
        """Connect to Claude Code CLI and initialize the session."""
        # Use provided custom transport or create subprocess transport
        warn_if_can_use_tool_shadowed(self.options)
        self._query = Query.from_options(self.options, self._custom_transport)
        try:
            await self._query.transport.connect()
            await self._query.start()
            await self._initialize()
        except BaseException:
            # `async with` never reaches __aexit__ when connect() fails: don't leak the
            # CLI process and the reader task.
            # Shielded: an anyio scope that cancelled connect() stays cancelled.
            with anyio.CancelScope(shield=True), contextlib.suppress(Exception):
                await self.disconnect()  # the connect error is the one to see
            self._query = None
            raise

    async def _initialize(self) -> None:
        """Send the initialize control request to the CLI."""
        query = self._ensure_connected()
        options = self.options
        match options.system_prompt, options.include_builtin_system_prompt:
            case None, False:
                system_prompt: list[str] | None = [""]  # Clear the builtin prompt
                append_system_prompt: str | None = None
            case None, True:
                system_prompt = None  # Use the builtin prompt
                append_system_prompt = None
            case str() as prompt_str, True:
                system_prompt = None
                append_system_prompt = prompt_str
            case list() as prompt_list, True:
                system_prompt = None
                append_system_prompt = "\n".join(prompt_list)
            case str() as prompt_str, False:
                system_prompt = [prompt_str]
                append_system_prompt = None
            case list() as prompt_list, False:
                system_prompt = prompt_list
                append_system_prompt = None

        # Calculate initialize timeout
        initialize_timeout_ms = int(os.environ.get("CLAUDE_CODE_STREAM_CLOSE_TIMEOUT", "60000"))
        initialize_timeout = max(initialize_timeout_ms / 1000.0, 60.0)
        match options.get_session():
            case NewSession() as s:
                title = s.title
            case _:
                title = None
        hooks_config = query.build_hooks_config()
        capture = options.capture_sdk_mcp_manifests and not os.environ.get(
            "CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS"
        )
        manifests = await query.capture_sdk_mcp_manifests() if capture else None
        request = SDKControlInitializeRequest(
            hooks=hooks_config,
            agents={name: d.to_wire_model() for name, d in (options.agents or {}).items()} or None,
            system_prompt=system_prompt,
            append_system_prompt=append_system_prompt,
            json_schema=options.get_json_schema(),
            prompt_suggestions=options.prompt_suggestions,
            exclude_dynamic_sections=options.exclude_dynamic_sections,
            sdk_mcp_servers=list(query.sdk_mcp_servers.keys()) or None,
            sdk_mcp_server_configs=options.sdk_mcp_server_configs(),
            sdk_mcp_server_manifests=manifests,
            plugins=(plugins := options.initialize_plugins()),
            mcp_servers=(mcp_servers := options.initialize_mcp_servers()),
            agent_progress_summaries=options.agent_progress_summaries,
            title=title,
            skills=options.skills,
            plan_mode_instructions=options.plan_mode_instructions,
            system_prompt_snapshot=options.system_prompt_snapshot,
            forward_subagent_text=options.forward_subagent_text or None,
            tool_aliases=options.tool_aliases,
            per_task_stop_affordance=options.per_task_stop_affordance,
        )
        response = await query._send_control_request(request, timeout=initialize_timeout)
        self._initialization_result = info = ClaudeCodeServerInfo.model_validate(response)
        # CLIs that predate the field: checked on the first system/init message instead
        if info.claude_code_version is not None:
            check_claude_version(info.claude_code_version)
            self._cli_version_checked = True
        if mcp_servers is not None and info.mcp_servers_applied is not True:
            # Absent on CLIs that predate the field: they never read `mcpServers`
            raise CLIConnectionError(
                "Claude Code did not take the MCP servers sent in the initialize request. "
                'Update Claude Code (2.1.261 or newer) or set mcp_servers_delivery="argv".'
            )
        if plugins is not None and info.plugins_applied is not True:
            raise CLIConnectionError(
                "Claude Code did not load the plugins sent in the initialize request. "
                'Update Claude Code or set plugin_delivery="argv".'
            )
        blocks_on_failure = any(
            m.on_failure not in (None, "continue")
            for matchers in (options.hooks or {}).values()
            for m in matchers
        )
        if blocks_on_failure:
            if not info.hook_on_failure_supported:
                raise CLIConnectionError(
                    "The process answering initialize does not honor on_failure on hook "
                    "matchers, so a failing hook would not block. "
                    'Update Claude Code or remove on_failure="block".'
                )
            if info.hooks_applied is False:
                raise CLIConnectionError(
                    "This session was already running and did not register your hooks, "
                    'so a hook set to on_failure="block" would never run.'
                )

    async def receive_messages(self) -> AsyncIterator[Message]:
        """Receive all messages from Claude."""
        query = self._ensure_connected()
        async for data in query.receive_messages():
            try:
                message = parse_message(data)
            except MessageParseError:
                # A newer CLI may send message types this SDK does not model yet: skip
                # them unless CLAWD_STRICT_MESSAGES is set. Malformed known types raise.
                if (kind := unknown_message_kind(data)) is None or strict_messages():
                    raise
                if kind not in _warned_unknown_kinds:
                    _warned_unknown_kinds.add(kind)
                    logger.warning(
                        "Skipping unknown Claude Code message type %r (set %s=1 to raise)",
                        kind,
                        STRICT_MESSAGES_ENV,
                    )
                continue
            match message:
                case AssistantMessage():
                    message.raise_if_api_error()
                case StatusSystemMessage(status=status):
                    self.status = status
                case InitSystemMessage(claude_code_version=version) if (
                    not self._cli_version_checked
                ):
                    check_claude_version(version)
                    self._cli_version_checked = True
                case SessionStateChangedMessage(state=state):
                    self.session_state = state
                case (
                    ResultSuccessMessage(usage=usage, total_cost_usd=total_cost)
                    | ResultErrorMessage(usage=usage, total_cost_usd=total_cost)
                ):
                    self.query_usage.accumulate(usage)
                    self.session_usage.accumulate(usage)
                    # total_cost_usd is cumulative; a query adds the delta of each of its
                    # results (a steered query has one per cycle)
                    self.query_cost += total_cost - self.session_cost
                    self.session_cost = total_cost
            yield message

    async def query(
        self,
        *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.

        Args:
            *prompts: One or more content blocks. Strings are converted to
                UserTextPrompt automatically. Pass multiple to combine, e.g.
                ``query(image_prompt, "What's in this image?")``.
            session_id: Session identifier for the message.
            parent_tool_use_id: If responding to a tool use, the tool_use block ID.
            should_query: Whether to query the model for a response. Defaults to True.
            priority: The priority of the message. Defaults to None.
            uuid: ID of the message; the CLI then reports its progress as
                ``CommandLifecycleMessage`` frames and names it in results.
        """
        prompt = prompts[0] if prompts else None
        self._logfire_prompt = str(prompt)
        self.query_usage.reset()
        self.query_cost = 0.0
        await self._send_user_message(
            prompts,
            session_id=session_id,
            parent_tool_use_id=parent_tool_use_id,
            should_query=should_query,
            priority=priority,
            uuid=uuid,
        )

    async def steer(
        self,
        *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).

        Args:
            *prompts: Content blocks of the message (strings become text blocks).
            priority: When the CLI takes the message in.
            session_id: Session identifier for the message.

        Returns:
            The message's uuid, which ``CommandLifecycleMessage.command_uuid`` and the
            results' ``user_message_uuids`` refer to.
        """
        message_uuid = str(uuid4())
        await self._send_user_message(
            prompts, session_id=session_id, priority=priority, uuid=message_uuid
        )
        return message_uuid

    async def _send_user_message(
        self,
        prompts: tuple[str | UserPrompt, ...],
        *,
        session_id: str,
        parent_tool_use_id: str | None = None,
        should_query: bool = True,
        priority: MessagePriority | None = None,
        uuid: str | None = None,
    ) -> None:
        self._ensure_connected()
        if not self._query:
            raise CLIConnectionError("Not connected. Call connect() first.")
        if not prompts:
            raise ValueError("At least one prompt is required")
        # Collect content blocks
        blocks = [UserTextPrompt(text=p) if isinstance(p, str) else p for p in prompts]
        # message_content = [b.to_content_block() for b in blocks]
        # wire_message = UserMessage(
        #     parent_tool_use_id=parent_tool_use_id,
        #     session_id=session_id,
        #     message=MessageParam(content=message_content),
        # )
        message_content = [cast(dict[str, Any], b.to_content_block()) for b in blocks]
        wire_message = {
            "type": "user",
            "message": {"role": "user", "content": message_content},
            "parent_tool_use_id": parent_tool_use_id,
            "session_id": session_id,
            "shouldQuery": should_query,
            "priority": priority,
        }
        if uuid is not None:
            wire_message["uuid"] = uuid
        if self.options.verbatim_prompts:
            wire_message["client_composed"] = True
        await self._query.write_json(wire_message)

    async def interrupt(self, *, cancel_queued: bool = False) -> SDKControlInterruptResponse | None:
        """Send interrupt signal (only works with streaming mode).

        Args:
            cancel_queued: Also cancel queued (not yet started) user messages.

        Returns:
            Which queued messages are still queued / were cancelled
            (None on CLIs that don't report it).
        """
        query = self._ensure_connected()
        request = SDKControlInterruptRequest(cancel_queued=cancel_queued or None)
        result = await query._send_control_request(request)
        return SDKControlInterruptResponse.model_validate(result) if result else None

    async def set_permission_mode(
        self, mode: PermissionMode
    ) -> SDKControlSetPermissionModeResponse | None:
        """Change permission mode during conversation (only works with streaming mode).

        Args:
            mode: 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)

        Returns:
            The mode now in effect (it can differ from ``mode``), or None if the
            CLI answered without a payload (before Claude Code 2.1.332).
        """
        query = self._ensure_connected()
        request = SDKControlSetPermissionModeRequest(mode=mode)
        result = await query._send_control_request(request)
        return SDKControlSetPermissionModeResponse.model_validate(result) if result else None

    async def set_model(self, model: str | None = None) -> None:
        """Change the AI model during conversation (only works with streaming mode).

        Args:
            model: The model to use, or None to use default. Example: 'claude-sonnet-4-5'
        """
        query = self._ensure_connected()
        request = SDKControlSetModelRequest(model=model)
        await query._send_control_request(request)

    async def cancel_async_message(self, message_uuid: str) -> None:
        """Drop a pending async user message from the command queue by uuid."""
        query = self._ensure_connected()
        request = SDKControlCancelAsyncMessageRequest(message_uuid=message_uuid)
        await query._send_control_request(request)

    async def stop_task(self, task_id: str) -> None:
        """Stop a running task."""
        query = self._ensure_connected()
        request = SDKControlStopTaskRequest(task_id=task_id)
        await query._send_control_request(request)

    async def rewind_files(self, user_message_id: str) -> None:
        """Rewind tracked files to their state at a specific user message.

        Requires:
            - `enable_file_checkpointing=True` to track file changes
            - `extra_args={"replay-user-messages": None}` to receive UserMessage
              objects with `uuid` in the response stream

        Args:
            user_message_id: UUID of the user message to rewind to. This should be
                the `uuid` field from a `UserMessage` received during the conversation.

        Example:
            ```python
            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)
            ```
        """
        query = self._ensure_connected()
        req = SDKControlRewindFilesRequest(user_message_id=user_message_id)
        await query._send_control_request(req)

    async def seed_read_state(self, path: str, mtime: int) -> None:
        """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.

        Args:
            path: Path to the file that was previously Read
            mtime: File mtime (floored ms) at the time of the observed Read
        """
        query = self._ensure_connected()
        req = SDKControlSeedReadStateRequest(path=path, mtime=mtime)
        await query._send_control_request(req)

    async def get_mcp_status(self) -> list[McpServerStatusEntry]:
        """Get current MCP server connection status.

        Returns:
            Validated MCP status response containing server statuses,
            configurations, tools, and connection information.
        """
        query = self._ensure_connected()
        request = SDKControlMcpStatusRequest()
        result = await query._send_control_request(request)
        response = McpStatusResponse.model_validate(result)
        return response.mcp_servers

    async def set_mcp_servers(
        self, 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.

        Args:
            servers: Dictionary mapping server names to server configurations.
                Values are typed MCP server configs (McpStdioServerConfig,
                McpSSEServerConfig, McpHttpServerConfig, or McpSdkServerConfig).

        Returns:
            Dictionary with results:
            - 'added': List of server names that were added
            - 'removed': List of server names that were removed
            - 'errors': Dict mapping server names to error messages (if any)
        """
        query = self._ensure_connected()
        request = SDKControlMcpSetServersRequest(servers=servers)
        result = await query._send_control_request(request)
        return McpSetServersResult.model_validate(result)

    async def mcp_reconnect(self, server_name: str) -> None:
        """Reconnect to an MCP server."""
        query = self._ensure_connected()
        request = SDKControlMcpReconnectRequest(server_name=server_name)
        await query._send_control_request(request)

    async def mcp_toggle(self, server_name: str, *, enabled: bool) -> None:
        """Enable or disable an MCP server."""
        query = self._ensure_connected()
        request = SDKControlMcpToggleRequest(server_name=server_name, enabled=enabled)
        await query._send_control_request(request)

    async def generate_session_title(
        self, description: str, *, persist: bool = False, timeout: float | None = 120.0
    ) -> str | None:
        """Generate a session title from ``description`` with the CLI's title model.

        Args:
            description: Text to title (the CLI reads its trailing ~1000 characters).
            persist: Store it as the current session's title; a session that has a title
                already returns that one.
            timeout: Seconds to wait for the model (None: no limit).

        Returns:
            The title, or None when the text is too short to title.
        """
        query = self._ensure_connected()
        request = SDKControlGenerateSessionTitleRequest(description=description, persist=persist)
        result = await query._send_control_request(request, timeout=timeout)
        title = (result or {}).get("title")
        return title if isinstance(title, str) and title else None

    async def end_session(self) -> None:
        """End the current session."""
        query = self._ensure_connected()
        request = SDKControlEndSessionRequest()
        await query._send_control_request(request)

    async def remote_control(self, *, 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:
            A ``RemoteControlResponse`` with session URLs and environment ID
            when enabling, or ``None`` when disabling.
        """
        query = self._ensure_connected()
        req = SDKControlRemoteControlRequest(enabled=enabled)
        result = await query._send_control_request(req)
        if not result:
            return None
        return RemoteControlResponse.model_validate(result)

    async def apply_flag_settings(self, 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.

        Args:
            settings: Settings to apply. Only fields that were set explicitly (and are
                not None) are sent: defaults would override every other settings source.
        """
        query = self._ensure_connected()
        serialized = settings.model_dump(by_alias=True, exclude_unset=True, exclude_none=True)
        req = SDKControlApplyFlagSettingsRequest(settings=serialized)
        await query._send_control_request(req)

    async def get_settings(self) -> GetSettingsResponse:
        """Get the effective merged settings and raw per-source settings."""
        query = self._ensure_connected()
        request = SDKControlGetSettingsRequest()
        result = await query._send_control_request(request)
        return GetSettingsResponse.model_validate(result)

    async def get_context_usage(
        self, detail: Literal["summary", "full"] | None = None
    ) -> SDKControlGetContextUsageResponse:
        """Get a breakdown of current context window usage by category."""
        query = self._ensure_connected()
        request = SDKControlGetContextUsageRequest(detail=detail)
        result = await query._send_control_request(request)
        return SDKControlGetContextUsageResponse.model_validate(result)

    # async def get_session_cost(self) -> SDKControlGetSessionCostResponse:
    #     """Get the formatted session cost summary (the same text as /usage)."""
    #     query = self._ensure_connected()
    #     request = SDKControlGetSessionCostRequest()
    #     result = await query._send_control_request(request)
    #     return SDKControlGetSessionCostResponse.model_validate(result)

    async def mcp_authenticate(self, server_name: str) -> McpAuthenticateResponse:
        """Trigger OAuth authentication for an MCP server.

        Returns:
            Response indicating whether user action is required and the auth URL if so.
        """
        query = self._ensure_connected()
        req = SDKControlMcpAuthenticateRequest(server_name=server_name)
        result = await query._send_control_request(req)
        return McpAuthenticateResponse.model_validate(result)

    async def mcp_clear_auth(self, server_name: str) -> None:
        """Clear OAuth credentials for an MCP server."""
        query = self._ensure_connected()
        req = SDKControlMcpClearAuthRequest(server_name=server_name)
        await query._send_control_request(req)

    async def mcp_oauth_callback_url(self, server_name: str, callback_url: str) -> None:
        """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.
        """
        query = self._ensure_connected()
        req = SDKControlMcpOAuthCallbackUrlRequest(
            server_name=server_name, callback_url=callback_url
        )
        await query._send_control_request(req)

    async def claude_oauth_wait_for_completion(
        self, *, timeout: float | None = None
    ) -> ClaudeOAuthWaitForCompletionResponse:
        """Wait for an in-progress Claude OAuth flow to complete.

        Args:
            timeout: Seconds to wait for the user to finish the browser login
                (None, the default: no limit).

        Returns:
            Account details (email, organization, subscriptionType, etc.).
        """
        query = self._ensure_connected()
        req = SDKControlClaudeOAuthWaitForCompletionRequest()
        data = await query._send_control_request(req, timeout=timeout)
        return ClaudeOAuthWaitForCompletionResponse.model_validate(data)

    async def side_question(
        self, 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.

        Args:
            question: The question to ask the model.
            timeout: Seconds to wait for the answer (None: no limit).

        Returns:
            The model's answer, or None if no context was available.
        """
        query = self._ensure_connected()
        req = SDKControlSideQuestionRequest(question=question)
        data = await query._send_control_request(req, timeout=timeout)
        return SideQuestionResponse.model_validate(data)

    async def channel_enable(self, server_name: str) -> None:
        """Enable MCP channel notifications for a marketplace plugin server."""
        query = self._ensure_connected()
        req = SDKControlChannelEnableRequest(server_name=server_name)
        await query._send_control_request(req)

    async def set_max_thinking_tokens(
        self,
        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)."""
        query = self._ensure_connected()
        request = SDKControlSetMaxThinkingTokensRequest(
            max_thinking_tokens=max_thinking_tokens, thinking_display=thinking_display
        )
        await query._send_control_request(request)

    async def background_tasks(self, tool_use_id: str | None = None) -> bool:
        """Move running foreground tasks (or a single tool use) to the background.

        Returns:
            Whether anything was backgrounded.
        """
        query = self._ensure_connected()
        request = SDKControlBackgroundTasksRequest(tool_use_id=tool_use_id)
        result = await query._send_control_request(request)
        return bool((result or {}).get("backgrounded", True))

    async def get_task_output(self, task_id: str) -> SDKControlGetTaskOutputResponse:
        """Read the output collected so far for a background task."""
        query = self._ensure_connected()
        request = SDKControlGetTaskOutputRequest(task_id=task_id)
        result = await query._send_control_request(request)
        return SDKControlGetTaskOutputResponse.model_validate(result)

    async def get_usage(self, *, skip_behaviors: bool = True) -> SDKControlGetUsageResponse:
        """Get session usage and plan rate-limit windows (experimental, shape may change).

        Args:
            skip_behaviors: Skip the (slow) scan of local transcripts that fills
                ``behaviors``.
        """
        query = self._ensure_connected()
        request = SDKControlGetUsageRequest(skip_behaviors=skip_behaviors or None)
        result = await query._send_control_request(request)
        return SDKControlGetUsageResponse.model_validate(result)

    async def get_binary_version(self) -> dict[str, Any]:
        """Get version info of the running Claude Code binary."""
        query = self._ensure_connected()
        return await query._send_control_request(SDKControlGetBinaryVersionRequest())

    async def list_models(self) -> list[ClaudeCodeModelInfo]:
        """Fetch the list of available models from the CLI."""
        query = self._ensure_connected()
        result = await query._send_control_request(SDKControlListModelsRequest())
        return [ClaudeCodeModelInfo.model_validate(m) for m in (result or {}).get("models", [])]

    async def reload_skills(self) -> list[ClaudeCodeCommandInfo]:
        """Re-scan skills from disk and return the refreshed skill list."""
        query = self._ensure_connected()
        result = await query._send_control_request(SDKControlReloadSkillsRequest())
        return SDKControlReloadSkillsResponse.model_validate(result).skills

    async def reload_output_styles(self) -> list[str]:
        """Re-scan output styles from disk and return the available style names."""
        query = self._ensure_connected()
        result = await query._send_control_request(SDKControlReloadOutputStylesRequest())
        return SDKControlReloadOutputStylesResponse.model_validate(result).available_output_styles

    async def read_mcp_resource(
        self, server_name: str, uri: str
    ) -> SDKControlMcpReadResourceResponse:
        """Read a resource from a connected MCP server."""
        query = self._ensure_connected()
        request = SDKControlMcpReadResourceRequest(server_name=server_name, uri=uri)
        result = await query._send_control_request(request)
        return SDKControlMcpReadResourceResponse.model_validate(result)

    async def update_settings(
        self,
        source: Literal["localSettings", "userSettings"],
        settings: dict[str, Any],
    ) -> None:
        """Persist settings to the local or user settings file."""
        query = self._ensure_connected()
        request = SDKControlUpdateSettingsRequest(source=source, settings=settings)
        await query._send_control_request(request)

    async def list_permission_rules(self) -> dict[str, Any]:
        """List the effective permission rules (raw ``state`` payload)."""
        query = self._ensure_connected()
        result = await query._send_control_request(SDKControlListPermissionRulesRequest())
        state: dict[str, Any] = (result or {}).get("state", {})
        return state

    async def register_repo_root(
        self,
        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)."""
        query = self._ensure_connected()
        request = SDKControlRegisterRepoRootRequest(
            directory=str(directory),
            reload_claude_md=reload_claude_md,
            reload_plugins=reload_plugins,
            reload_skills=reload_skills,
        )
        await query._send_control_request(request)

    async def get_hooks_listing(self) -> dict[str, Any]:
        """Get the listing of configured hooks (same data as /hooks)."""
        query = self._ensure_connected()
        return await query._send_control_request(SDKControlGetHooksListingRequest())

    async def supported_agents(self) -> list[ClaudeCodeAgentInfo]:
        """Get the list of available subagents for the current session.

        Returns:
            List of available agents with their names, descriptions, and configuration.
        """
        if self._initialization_result is None:
            raise RuntimeError("Not initialized. Call connect() first.")
        return self._initialization_result.agents

    async def get_file(self, path: str, max_bytes: int | None = None) -> SDKControlReadFileResponse:
        """Get the contents of a file from the server.

        Args:
            path: Path to the file to read
            max_bytes: Maximum number of bytes to read (default: None, no limit)

        Returns:
            The file contents and metadata
        """
        query = self._ensure_connected()
        request = SDKControlReadFileRequest(path=path, max_bytes=max_bytes)
        result = await query._send_control_request(request)
        return SDKControlReadFileResponse.model_validate(result)

    async def call_tool(
        self,
        tool: str,
        arguments: dict[str, Any] | None = None,
        *,
        timeout: float | None = 600.0,
    ) -> Any:
        """Call a tool on the server.

        Args:
            tool: The name of the tool to call
            arguments: Optional dictionary of arguments for the tool
            timeout: Seconds to wait for the tool's result (None: no limit)

        Returns:
            The result of the tool call
        """
        query = self._ensure_connected()
        request = SDKControlMcpCallRequest(tool=tool, arguments=arguments)
        return await query._send_control_request(request, timeout=timeout)

    async def get_server_info(self) -> 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:
            Parsed server info, or None if not yet initialized
        """
        return self._initialization_result

    async def receive_response_instrumented(self) -> AsyncIterator[Message]:
        from logfire import Logfire
        from logfire._internal.integrations.llm_providers.semconv import (
            INPUT_MESSAGES,
            OPERATION_NAME,
            PROVIDER_NAME,
            REQUEST_MODEL,
            RESPONSE_MODEL,
            SYSTEM,
            SYSTEM_INSTRUCTIONS,
            ChatMessage,
            TextPart,
        )
        from logfire._internal.utils import handle_internal_errors

        from clawd_code_sdk.instrumentation import ConversationState, record_result
        from clawd_code_sdk.models.content_blocks import ToolResultBlock, ToolUseBlock

        logfire_instance = Logfire()
        logfire_claude = logfire_instance.with_settings(custom_scope_suffix="clawd_code_sdk")

        input_messages: list[ChatMessage] = []
        if prompt := self._logfire_prompt:
            part = TextPart(type="text", content=prompt)
            input_messages = [ChatMessage(role="user", parts=[part])]

        span_data: dict[str, Any] = {
            OPERATION_NAME: "invoke_agent",
            PROVIDER_NAME: "anthropic",
            SYSTEM: "anthropic",
        }
        if input_messages:
            span_data[INPUT_MESSAGES] = input_messages
        if self.options and (system_prompt := self.options.system_prompt):
            text = str(system_prompt)
            span_data[SYSTEM_INSTRUCTIONS] = [TextPart(type="text", content=text)]

        with logfire_claude.span("invoke_agent", **span_data) as root_span:
            state = ConversationState(
                logfire=logfire_claude,
                root_span=root_span,
                input_messages=input_messages,
                system_instructions=span_data.get(SYSTEM_INSTRUCTIONS),
            )
            # Open the first chat span now — the LLM call starts at query time.
            state.open_chat_span()

            try:
                async for msg in self.receive_response():
                    with handle_internal_errors:  # ty:ignore[invalid-context-manager]
                        match msg:
                            case AssistantMessage():
                                state.handle_assistant_message(msg)
                                # Open tool spans for any tool_use blocks.
                                tool_blocks = [
                                    b for b in msg.content if isinstance(b, ToolUseBlock)
                                ]
                                state.open_tool_spans(tool_blocks)
                            case UserMessage():
                                # Close tool spans from tool results before
                                # opening the next chat span.
                                content = msg.message.content
                                if isinstance(content, (list, tuple)):
                                    result_blocks = [
                                        b for b in content if isinstance(b, ToolResultBlock)
                                    ]
                                    state.close_tool_spans(result_blocks)
                                state.handle_user_message()
                            case ResultSuccessMessage() | ResultErrorMessage():
                                record_result(root_span, msg)
                                if state.model:
                                    root_span.set_attribute(REQUEST_MODEL, state.model)
                                    root_span.set_attribute(RESPONSE_MODEL, state.model)
                            case _:
                                pass
                    yield msg
            finally:
                state.close()

    async def receive_response(self) -> 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:
            Message: Each message received

        Note:
            To collect all messages: `messages = [msg async for msg in client.receive_response()]`
        """
        async for message in self.receive_messages():
            yield message
            if isinstance(message, SessionStateChangedMessage) and message.state == "idle":
                return

    async def disconnect(self) -> None:
        """Disconnect from Claude."""
        if self._query:
            await self._query.close()
            self._query = None

    @classmethod
    async def one_shot(
        cls,
        *prompts: str | UserPrompt,
        options: ClaudeAgentOptions | None = None,
        transport: Transport | None = None,
    ) -> AsyncIterator[Message]:
        """One-shot query convenience method.

        Args:
            *prompts: One or more content blocks to send.
            options: Optional configuration.
            transport: Optional transport implementation override.

        Yields:
            Messages from the conversation
        """
        client = cls(options=options, transport=transport)
        try:
            await client.connect()
            await client.query(*prompts)
            async for message in client.receive_response():
                yield message
        finally:
            await client.disconnect()

    async def __aenter__(self) -> Self:
        """Enter async context - automatically connects with empty stream for interactive use."""
        await self.connect()
        return self

    async def __aexit__(self, *args: object) -> None:
        """Exit async context - always disconnects."""
        await self.disconnect()

query_cost instance-attribute

query_cost: float = 0.0

Cost in USD for the current/last query only (reset on each query() call).

query_usage instance-attribute

query_usage: Usage = Usage()

Token usage for the current/last query only (reset on each query() call).

session_cost instance-attribute

session_cost: float = 0.0

Cumulative cost in USD across all queries in this session.

session_state instance-attribute

session_state: SessionState = 'idle'

Cumulative token usage across all queries in this session.

status instance-attribute

status: SDKStatus | None = None

Current client status, or None when idle.

__aenter__ async

__aenter__() -> Self

Enter async context - automatically connects with empty stream for interactive use.

Source code in src/clawd_code_sdk/client.py
async def __aenter__(self) -> Self:
    """Enter async context - automatically connects with empty stream for interactive use."""
    await self.connect()
    return self

__aexit__ async

__aexit__(*args: object) -> None

Exit async context - always disconnects.

Source code in src/clawd_code_sdk/client.py
async def __aexit__(self, *args: object) -> None:
    """Exit async context - always disconnects."""
    await self.disconnect()

__init__

__init__(options: ClaudeAgentOptions | None = None, transport: Transport | None = None) -> None

Initialize Claude SDK client.

Source code in src/clawd_code_sdk/client.py
def __init__(
    self,
    options: ClaudeAgentOptions | None = None,
    transport: Transport | None = None,
) -> None:
    """Initialize Claude SDK client."""
    options = options or ClaudeAgentOptions()
    self.options = options
    self._custom_transport = transport
    self._query: Query | None = None
    self._initialization_result: ClaudeCodeServerInfo | None = None
    self.session_usage: Usage = Usage()
    self.session_state: SessionState = "idle"
    """Cumulative token usage across all queries in this session."""
    self.query_usage: Usage = Usage()
    """Token usage for the current/last query only (reset on each query() call)."""
    self.session_cost: float = 0.0
    """Cumulative cost in USD across all queries in this session."""
    self.query_cost: float = 0.0
    """Cost in USD for the current/last query only (reset on each query() call)."""
    self.status: SDKStatus | None = None
    """Current client status, or None when idle."""

    self._logfire_prompt: str | None = None
    self._cli_version_checked = False

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
async def apply_flag_settings(self, 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.

    Args:
        settings: Settings to apply. Only fields that were set explicitly (and are
            not None) are sent: defaults would override every other settings source.
    """
    query = self._ensure_connected()
    serialized = settings.model_dump(by_alias=True, exclude_unset=True, exclude_none=True)
    req = SDKControlApplyFlagSettingsRequest(settings=serialized)
    await query._send_control_request(req)

background_tasks async

background_tasks(tool_use_id: str | None = None) -> bool

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
async def background_tasks(self, tool_use_id: str | None = None) -> bool:
    """Move running foreground tasks (or a single tool use) to the background.

    Returns:
        Whether anything was backgrounded.
    """
    query = self._ensure_connected()
    request = SDKControlBackgroundTasksRequest(tool_use_id=tool_use_id)
    result = await query._send_control_request(request)
    return bool((result or {}).get("backgrounded", True))

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
async def call_tool(
    self,
    tool: str,
    arguments: dict[str, Any] | None = None,
    *,
    timeout: float | None = 600.0,
) -> Any:
    """Call a tool on the server.

    Args:
        tool: The name of the tool to call
        arguments: Optional dictionary of arguments for the tool
        timeout: Seconds to wait for the tool's result (None: no limit)

    Returns:
        The result of the tool call
    """
    query = self._ensure_connected()
    request = SDKControlMcpCallRequest(tool=tool, arguments=arguments)
    return await query._send_control_request(request, timeout=timeout)

cancel_async_message async

cancel_async_message(message_uuid: str) -> None

Drop a pending async user message from the command queue by uuid.

Source code in src/clawd_code_sdk/client.py
async def cancel_async_message(self, message_uuid: str) -> None:
    """Drop a pending async user message from the command queue by uuid."""
    query = self._ensure_connected()
    request = SDKControlCancelAsyncMessageRequest(message_uuid=message_uuid)
    await query._send_control_request(request)

channel_enable async

channel_enable(server_name: str) -> None

Enable MCP channel notifications for a marketplace plugin server.

Source code in src/clawd_code_sdk/client.py
async def channel_enable(self, server_name: str) -> None:
    """Enable MCP channel notifications for a marketplace plugin server."""
    query = self._ensure_connected()
    req = SDKControlChannelEnableRequest(server_name=server_name)
    await query._send_control_request(req)

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
async def claude_oauth_wait_for_completion(
    self, *, timeout: float | None = None
) -> ClaudeOAuthWaitForCompletionResponse:
    """Wait for an in-progress Claude OAuth flow to complete.

    Args:
        timeout: Seconds to wait for the user to finish the browser login
            (None, the default: no limit).

    Returns:
        Account details (email, organization, subscriptionType, etc.).
    """
    query = self._ensure_connected()
    req = SDKControlClaudeOAuthWaitForCompletionRequest()
    data = await query._send_control_request(req, timeout=timeout)
    return ClaudeOAuthWaitForCompletionResponse.model_validate(data)

connect async

connect() -> None

Connect to Claude Code CLI and initialize the session.

Source code in src/clawd_code_sdk/client.py
async def connect(self) -> None:
    """Connect to Claude Code CLI and initialize the session."""
    # Use provided custom transport or create subprocess transport
    warn_if_can_use_tool_shadowed(self.options)
    self._query = Query.from_options(self.options, self._custom_transport)
    try:
        await self._query.transport.connect()
        await self._query.start()
        await self._initialize()
    except BaseException:
        # `async with` never reaches __aexit__ when connect() fails: don't leak the
        # CLI process and the reader task.
        # Shielded: an anyio scope that cancelled connect() stays cancelled.
        with anyio.CancelScope(shield=True), contextlib.suppress(Exception):
            await self.disconnect()  # the connect error is the one to see
        self._query = None
        raise

disconnect async

disconnect() -> None

Disconnect from Claude.

Source code in src/clawd_code_sdk/client.py
async def disconnect(self) -> None:
    """Disconnect from Claude."""
    if self._query:
        await self._query.close()
        self._query = None

end_session async

end_session() -> None

End the current session.

Source code in src/clawd_code_sdk/client.py
async def end_session(self) -> None:
    """End the current session."""
    query = self._ensure_connected()
    request = SDKControlEndSessionRequest()
    await query._send_control_request(request)

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
async def generate_session_title(
    self, description: str, *, persist: bool = False, timeout: float | None = 120.0
) -> str | None:
    """Generate a session title from ``description`` with the CLI's title model.

    Args:
        description: Text to title (the CLI reads its trailing ~1000 characters).
        persist: Store it as the current session's title; a session that has a title
            already returns that one.
        timeout: Seconds to wait for the model (None: no limit).

    Returns:
        The title, or None when the text is too short to title.
    """
    query = self._ensure_connected()
    request = SDKControlGenerateSessionTitleRequest(description=description, persist=persist)
    result = await query._send_control_request(request, timeout=timeout)
    title = (result or {}).get("title")
    return title if isinstance(title, str) and title else None

get_binary_version async

get_binary_version() -> dict[str, Any]

Get version info of the running Claude Code binary.

Source code in src/clawd_code_sdk/client.py
async def get_binary_version(self) -> dict[str, Any]:
    """Get version info of the running Claude Code binary."""
    query = self._ensure_connected()
    return await query._send_control_request(SDKControlGetBinaryVersionRequest())

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
async def get_context_usage(
    self, detail: Literal["summary", "full"] | None = None
) -> SDKControlGetContextUsageResponse:
    """Get a breakdown of current context window usage by category."""
    query = self._ensure_connected()
    request = SDKControlGetContextUsageRequest(detail=detail)
    result = await query._send_control_request(request)
    return SDKControlGetContextUsageResponse.model_validate(result)

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
async def get_file(self, path: str, max_bytes: int | None = None) -> SDKControlReadFileResponse:
    """Get the contents of a file from the server.

    Args:
        path: Path to the file to read
        max_bytes: Maximum number of bytes to read (default: None, no limit)

    Returns:
        The file contents and metadata
    """
    query = self._ensure_connected()
    request = SDKControlReadFileRequest(path=path, max_bytes=max_bytes)
    result = await query._send_control_request(request)
    return SDKControlReadFileResponse.model_validate(result)

get_hooks_listing async

get_hooks_listing() -> dict[str, Any]

Get the listing of configured hooks (same data as /hooks).

Source code in src/clawd_code_sdk/client.py
async def get_hooks_listing(self) -> dict[str, Any]:
    """Get the listing of configured hooks (same data as /hooks)."""
    query = self._ensure_connected()
    return await query._send_control_request(SDKControlGetHooksListingRequest())

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
async def get_mcp_status(self) -> list[McpServerStatusEntry]:
    """Get current MCP server connection status.

    Returns:
        Validated MCP status response containing server statuses,
        configurations, tools, and connection information.
    """
    query = self._ensure_connected()
    request = SDKControlMcpStatusRequest()
    result = await query._send_control_request(request)
    response = McpStatusResponse.model_validate(result)
    return response.mcp_servers

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
async def get_server_info(self) -> 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:
        Parsed server info, or None if not yet initialized
    """
    return self._initialization_result

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
async def get_settings(self) -> GetSettingsResponse:
    """Get the effective merged settings and raw per-source settings."""
    query = self._ensure_connected()
    request = SDKControlGetSettingsRequest()
    result = await query._send_control_request(request)
    return GetSettingsResponse.model_validate(result)

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
async def get_task_output(self, task_id: str) -> SDKControlGetTaskOutputResponse:
    """Read the output collected so far for a background task."""
    query = self._ensure_connected()
    request = SDKControlGetTaskOutputRequest(task_id=task_id)
    result = await query._send_control_request(request)
    return SDKControlGetTaskOutputResponse.model_validate(result)

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 behaviors.

True
Source code in src/clawd_code_sdk/client.py
async def get_usage(self, *, skip_behaviors: bool = True) -> SDKControlGetUsageResponse:
    """Get session usage and plan rate-limit windows (experimental, shape may change).

    Args:
        skip_behaviors: Skip the (slow) scan of local transcripts that fills
            ``behaviors``.
    """
    query = self._ensure_connected()
    request = SDKControlGetUsageRequest(skip_behaviors=skip_behaviors or None)
    result = await query._send_control_request(request)
    return SDKControlGetUsageResponse.model_validate(result)

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
async def interrupt(self, *, cancel_queued: bool = False) -> SDKControlInterruptResponse | None:
    """Send interrupt signal (only works with streaming mode).

    Args:
        cancel_queued: Also cancel queued (not yet started) user messages.

    Returns:
        Which queued messages are still queued / were cancelled
        (None on CLIs that don't report it).
    """
    query = self._ensure_connected()
    request = SDKControlInterruptRequest(cancel_queued=cancel_queued or None)
    result = await query._send_control_request(request)
    return SDKControlInterruptResponse.model_validate(result) if result else None

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
async def list_models(self) -> list[ClaudeCodeModelInfo]:
    """Fetch the list of available models from the CLI."""
    query = self._ensure_connected()
    result = await query._send_control_request(SDKControlListModelsRequest())
    return [ClaudeCodeModelInfo.model_validate(m) for m in (result or {}).get("models", [])]

list_permission_rules async

list_permission_rules() -> dict[str, Any]

List the effective permission rules (raw state payload).

Source code in src/clawd_code_sdk/client.py
async def list_permission_rules(self) -> dict[str, Any]:
    """List the effective permission rules (raw ``state`` payload)."""
    query = self._ensure_connected()
    result = await query._send_control_request(SDKControlListPermissionRulesRequest())
    state: dict[str, Any] = (result or {}).get("state", {})
    return state

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
async def mcp_authenticate(self, server_name: str) -> McpAuthenticateResponse:
    """Trigger OAuth authentication for an MCP server.

    Returns:
        Response indicating whether user action is required and the auth URL if so.
    """
    query = self._ensure_connected()
    req = SDKControlMcpAuthenticateRequest(server_name=server_name)
    result = await query._send_control_request(req)
    return McpAuthenticateResponse.model_validate(result)

mcp_clear_auth async

mcp_clear_auth(server_name: str) -> None

Clear OAuth credentials for an MCP server.

Source code in src/clawd_code_sdk/client.py
async def mcp_clear_auth(self, server_name: str) -> None:
    """Clear OAuth credentials for an MCP server."""
    query = self._ensure_connected()
    req = SDKControlMcpClearAuthRequest(server_name=server_name)
    await query._send_control_request(req)

mcp_oauth_callback_url async

mcp_oauth_callback_url(server_name: str, callback_url: str) -> None

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
async def mcp_oauth_callback_url(self, server_name: str, callback_url: str) -> None:
    """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.
    """
    query = self._ensure_connected()
    req = SDKControlMcpOAuthCallbackUrlRequest(
        server_name=server_name, callback_url=callback_url
    )
    await query._send_control_request(req)

mcp_reconnect async

mcp_reconnect(server_name: str) -> None

Reconnect to an MCP server.

Source code in src/clawd_code_sdk/client.py
async def mcp_reconnect(self, server_name: str) -> None:
    """Reconnect to an MCP server."""
    query = self._ensure_connected()
    request = SDKControlMcpReconnectRequest(server_name=server_name)
    await query._send_control_request(request)

mcp_toggle async

mcp_toggle(server_name: str, *, enabled: bool) -> None

Enable or disable an MCP server.

Source code in src/clawd_code_sdk/client.py
async def mcp_toggle(self, server_name: str, *, enabled: bool) -> None:
    """Enable or disable an MCP server."""
    query = self._ensure_connected()
    request = SDKControlMcpToggleRequest(server_name=server_name, enabled=enabled)
    await query._send_control_request(request)

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
@classmethod
async def one_shot(
    cls,
    *prompts: str | UserPrompt,
    options: ClaudeAgentOptions | None = None,
    transport: Transport | None = None,
) -> AsyncIterator[Message]:
    """One-shot query convenience method.

    Args:
        *prompts: One or more content blocks to send.
        options: Optional configuration.
        transport: Optional transport implementation override.

    Yields:
        Messages from the conversation
    """
    client = cls(options=options, transport=transport)
    try:
        await client.connect()
        await client.query(*prompts)
        async for message in client.receive_response():
            yield message
    finally:
        await client.disconnect()

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. query(image_prompt, "What's in this image?").

()
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 CommandLifecycleMessage frames and names it in results.

None
Source code in src/clawd_code_sdk/client.py
async def query(
    self,
    *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.

    Args:
        *prompts: One or more content blocks. Strings are converted to
            UserTextPrompt automatically. Pass multiple to combine, e.g.
            ``query(image_prompt, "What's in this image?")``.
        session_id: Session identifier for the message.
        parent_tool_use_id: If responding to a tool use, the tool_use block ID.
        should_query: Whether to query the model for a response. Defaults to True.
        priority: The priority of the message. Defaults to None.
        uuid: ID of the message; the CLI then reports its progress as
            ``CommandLifecycleMessage`` frames and names it in results.
    """
    prompt = prompts[0] if prompts else None
    self._logfire_prompt = str(prompt)
    self.query_usage.reset()
    self.query_cost = 0.0
    await self._send_user_message(
        prompts,
        session_id=session_id,
        parent_tool_use_id=parent_tool_use_id,
        should_query=should_query,
        priority=priority,
        uuid=uuid,
    )

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
async def read_mcp_resource(
    self, server_name: str, uri: str
) -> SDKControlMcpReadResourceResponse:
    """Read a resource from a connected MCP server."""
    query = self._ensure_connected()
    request = SDKControlMcpReadResourceRequest(server_name=server_name, uri=uri)
    result = await query._send_control_request(request)
    return SDKControlMcpReadResourceResponse.model_validate(result)

receive_messages async

receive_messages() -> AsyncIterator[Message]

Receive all messages from Claude.

Source code in src/clawd_code_sdk/client.py
async def receive_messages(self) -> AsyncIterator[Message]:
    """Receive all messages from Claude."""
    query = self._ensure_connected()
    async for data in query.receive_messages():
        try:
            message = parse_message(data)
        except MessageParseError:
            # A newer CLI may send message types this SDK does not model yet: skip
            # them unless CLAWD_STRICT_MESSAGES is set. Malformed known types raise.
            if (kind := unknown_message_kind(data)) is None or strict_messages():
                raise
            if kind not in _warned_unknown_kinds:
                _warned_unknown_kinds.add(kind)
                logger.warning(
                    "Skipping unknown Claude Code message type %r (set %s=1 to raise)",
                    kind,
                    STRICT_MESSAGES_ENV,
                )
            continue
        match message:
            case AssistantMessage():
                message.raise_if_api_error()
            case StatusSystemMessage(status=status):
                self.status = status
            case InitSystemMessage(claude_code_version=version) if (
                not self._cli_version_checked
            ):
                check_claude_version(version)
                self._cli_version_checked = True
            case SessionStateChangedMessage(state=state):
                self.session_state = state
            case (
                ResultSuccessMessage(usage=usage, total_cost_usd=total_cost)
                | ResultErrorMessage(usage=usage, total_cost_usd=total_cost)
            ):
                self.query_usage.accumulate(usage)
                self.session_usage.accumulate(usage)
                # total_cost_usd is cumulative; a query adds the delta of each of its
                # results (a steered query has one per cycle)
                self.query_cost += total_cost - self.session_cost
                self.session_cost = total_cost
        yield message

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
async def receive_response(self) -> 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:
        Message: Each message received

    Note:
        To collect all messages: `messages = [msg async for msg in client.receive_response()]`
    """
    async for message in self.receive_messages():
        yield message
        if isinstance(message, SessionStateChangedMessage) and message.state == "idle":
            return

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
async def register_repo_root(
    self,
    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)."""
    query = self._ensure_connected()
    request = SDKControlRegisterRepoRootRequest(
        directory=str(directory),
        reload_claude_md=reload_claude_md,
        reload_plugins=reload_plugins,
        reload_skills=reload_skills,
    )
    await query._send_control_request(request)

reload_output_styles async

reload_output_styles() -> list[str]

Re-scan output styles from disk and return the available style names.

Source code in src/clawd_code_sdk/client.py
async def reload_output_styles(self) -> list[str]:
    """Re-scan output styles from disk and return the available style names."""
    query = self._ensure_connected()
    result = await query._send_control_request(SDKControlReloadOutputStylesRequest())
    return SDKControlReloadOutputStylesResponse.model_validate(result).available_output_styles

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
async def reload_skills(self) -> list[ClaudeCodeCommandInfo]:
    """Re-scan skills from disk and return the refreshed skill list."""
    query = self._ensure_connected()
    result = await query._send_control_request(SDKControlReloadSkillsRequest())
    return SDKControlReloadSkillsResponse.model_validate(result).skills

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 with session URLs and environment ID

RemoteControlResponse | None

when enabling, or None when disabling.

Source code in src/clawd_code_sdk/client.py
async def remote_control(self, *, 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:
        A ``RemoteControlResponse`` with session URLs and environment ID
        when enabling, or ``None`` when disabling.
    """
    query = self._ensure_connected()
    req = SDKControlRemoteControlRequest(enabled=enabled)
    result = await query._send_control_request(req)
    if not result:
        return None
    return RemoteControlResponse.model_validate(result)

rewind_files async

rewind_files(user_message_id: str) -> None

Rewind tracked files to their state at a specific user message.

Requires
  • enable_file_checkpointing=True to track file changes
  • extra_args={"replay-user-messages": None} to receive UserMessage objects with uuid in the response stream

Parameters:

Name Type Description Default
user_message_id str

UUID of the user message to rewind to. This should be the uuid field from a UserMessage received during the conversation.

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
async def rewind_files(self, user_message_id: str) -> None:
    """Rewind tracked files to their state at a specific user message.

    Requires:
        - `enable_file_checkpointing=True` to track file changes
        - `extra_args={"replay-user-messages": None}` to receive UserMessage
          objects with `uuid` in the response stream

    Args:
        user_message_id: UUID of the user message to rewind to. This should be
            the `uuid` field from a `UserMessage` received during the conversation.

    Example:
        ```python
        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)
        ```
    """
    query = self._ensure_connected()
    req = SDKControlRewindFilesRequest(user_message_id=user_message_id)
    await query._send_control_request(req)

seed_read_state async

seed_read_state(path: str, mtime: int) -> None

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
async def seed_read_state(self, path: str, mtime: int) -> None:
    """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.

    Args:
        path: Path to the file that was previously Read
        mtime: File mtime (floored ms) at the time of the observed Read
    """
    query = self._ensure_connected()
    req = SDKControlSeedReadStateRequest(path=path, mtime=mtime)
    await query._send_control_request(req)

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
async def set_max_thinking_tokens(
    self,
    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)."""
    query = self._ensure_connected()
    request = SDKControlSetMaxThinkingTokensRequest(
        max_thinking_tokens=max_thinking_tokens, thinking_display=thinking_display
    )
    await query._send_control_request(request)

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
  • 'added': List of server names that were added
McpSetServersResult
  • 'removed': List of server names that were removed
McpSetServersResult
  • 'errors': Dict mapping server names to error messages (if any)
Source code in src/clawd_code_sdk/client.py
async def set_mcp_servers(
    self, 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.

    Args:
        servers: Dictionary mapping server names to server configurations.
            Values are typed MCP server configs (McpStdioServerConfig,
            McpSSEServerConfig, McpHttpServerConfig, or McpSdkServerConfig).

    Returns:
        Dictionary with results:
        - 'added': List of server names that were added
        - 'removed': List of server names that were removed
        - 'errors': Dict mapping server names to error messages (if any)
    """
    query = self._ensure_connected()
    request = SDKControlMcpSetServersRequest(servers=servers)
    result = await query._send_control_request(request)
    return McpSetServersResult.model_validate(result)

set_model async

set_model(model: str | None = None) -> None

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
async def set_model(self, model: str | None = None) -> None:
    """Change the AI model during conversation (only works with streaming mode).

    Args:
        model: The model to use, or None to use default. Example: 'claude-sonnet-4-5'
    """
    query = self._ensure_connected()
    request = SDKControlSetModelRequest(model=model)
    await query._send_control_request(request)

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 mode), or None if the

SDKControlSetPermissionModeResponse | None

CLI answered without a payload (before Claude Code 2.1.332).

Source code in src/clawd_code_sdk/client.py
async def set_permission_mode(
    self, mode: PermissionMode
) -> SDKControlSetPermissionModeResponse | None:
    """Change permission mode during conversation (only works with streaming mode).

    Args:
        mode: 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)

    Returns:
        The mode now in effect (it can differ from ``mode``), or None if the
        CLI answered without a payload (before Claude Code 2.1.332).
    """
    query = self._ensure_connected()
    request = SDKControlSetPermissionModeRequest(mode=mode)
    result = await query._send_control_request(request)
    return SDKControlSetPermissionModeResponse.model_validate(result) if result else None

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
async def side_question(
    self, 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.

    Args:
        question: The question to ask the model.
        timeout: Seconds to wait for the answer (None: no limit).

    Returns:
        The model's answer, or None if no context was available.
    """
    query = self._ensure_connected()
    req = SDKControlSideQuestionRequest(question=question)
    data = await query._send_control_request(req, timeout=timeout)
    return SideQuestionResponse.model_validate(data)

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 CommandLifecycleMessage.command_uuid and the

str

results' user_message_uuids refer to.

Source code in src/clawd_code_sdk/client.py
async def steer(
    self,
    *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).

    Args:
        *prompts: Content blocks of the message (strings become text blocks).
        priority: When the CLI takes the message in.
        session_id: Session identifier for the message.

    Returns:
        The message's uuid, which ``CommandLifecycleMessage.command_uuid`` and the
        results' ``user_message_uuids`` refer to.
    """
    message_uuid = str(uuid4())
    await self._send_user_message(
        prompts, session_id=session_id, priority=priority, uuid=message_uuid
    )
    return message_uuid

stop_task async

stop_task(task_id: str) -> None

Stop a running task.

Source code in src/clawd_code_sdk/client.py
async def stop_task(self, task_id: str) -> None:
    """Stop a running task."""
    query = self._ensure_connected()
    request = SDKControlStopTaskRequest(task_id=task_id)
    await query._send_control_request(request)

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
async def supported_agents(self) -> list[ClaudeCodeAgentInfo]:
    """Get the list of available subagents for the current session.

    Returns:
        List of available agents with their names, descriptions, and configuration.
    """
    if self._initialization_result is None:
        raise RuntimeError("Not initialized. Call connect() first.")
    return self._initialization_result.agents

update_settings async

update_settings(source: Literal['localSettings', 'userSettings'], settings: dict[str, Any]) -> None

Persist settings to the local or user settings file.

Source code in src/clawd_code_sdk/client.py
async def update_settings(
    self,
    source: Literal["localSettings", "userSettings"],
    settings: dict[str, Any],
) -> None:
    """Persist settings to the local or user settings file."""
    query = self._ensure_connected()
    request = SDKControlUpdateSettingsRequest(source=source, settings=settings)
    await query._send_control_request(request)

:fa-brands-github: Show source on GitHub