clawd-code-sdk 1.5.0__tar.gz → 1.5.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/PKG-INFO +2 -2
  2. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/pyproject.toml +2 -2
  3. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/query.py +59 -0
  4. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/transport/subprocess_utils.py +9 -6
  5. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/client.py +12 -0
  6. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/content_blocks.py +1 -1
  7. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/control.py +26 -0
  8. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/options.py +52 -0
  9. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/storage/chain.py +71 -1
  10. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/storage/models.py +6 -0
  11. clawd_code_sdk-1.5.2/tests/test_initialize_fields.py +103 -0
  12. clawd_code_sdk-1.5.2/tests/test_permission_flags.py +16 -0
  13. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_storage_chain.py +35 -1
  14. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/.gitignore +0 -0
  15. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/LICENSE +0 -0
  16. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/README.md +0 -0
  17. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/__init__.py +0 -0
  18. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_bundled/.gitignore +0 -0
  19. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_errors.py +0 -0
  20. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/__init__.py +0 -0
  21. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/mcp_compat.py +0 -0
  22. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/sdk_mcp_bridge.py +0 -0
  23. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/session_mutations.py +0 -0
  24. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/sessions.py +0 -0
  25. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/transport/__init__.py +0 -0
  26. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_internal/transport/subprocess_cli.py +0 -0
  27. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/_version.py +0 -0
  28. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/anthropic_stream.py +0 -0
  29. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/instrumentation.py +0 -0
  30. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/mcp_utils.py +0 -0
  31. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/__init__.py +0 -0
  32. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/agents.py +0 -0
  33. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/anthropic_types.py +0 -0
  34. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/base.py +0 -0
  35. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/context_usage.py +0 -0
  36. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/hooks.py +0 -0
  37. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/input_types.py +0 -0
  38. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/mcp.py +0 -0
  39. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/messages.py +0 -0
  40. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/output_types.py +0 -0
  41. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/permissions.py +0 -0
  42. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/prompt_requests.py +0 -0
  43. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/prompts.py +0 -0
  44. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/server_info.py +0 -0
  45. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/session.py +0 -0
  46. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/settings.py +0 -0
  47. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/system_messages.py +0 -0
  48. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/thinking.py +0 -0
  49. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/models/usage.py +0 -0
  50. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/py.typed +0 -0
  51. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/session.py +0 -0
  52. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/storage/ARCHITECTURE.md +0 -0
  53. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/storage/__init__.py +0 -0
  54. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/storage/helpers.py +0 -0
  55. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/src/clawd_code_sdk/storage/replay.py +0 -0
  56. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/__init__.py +0 -0
  57. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/conftest.py +0 -0
  58. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/__init__.py +0 -0
  59. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_agents_and_settings.py +0 -0
  60. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_dynamic_control.py +0 -0
  61. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_hook_events.py +0 -0
  62. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_hooks.py +0 -0
  63. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_include_partial_messages.py +0 -0
  64. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_mcp_resources.py +0 -0
  65. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_mcp_tools.py +0 -0
  66. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_sdk_mcp_resources.py +0 -0
  67. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_sdk_mcp_tools.py +0 -0
  68. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_slash_commands.py +0 -0
  69. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_stderr_callback.py +0 -0
  70. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_storage_parsing.py +0 -0
  71. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_structured_output.py +0 -0
  72. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_subagent_invocation.py +0 -0
  73. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/e2e/test_tool_permissions.py +0 -0
  74. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/mcp_server.py +0 -0
  75. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/mock_claude_server.py +0 -0
  76. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_api_content_blocks.py +0 -0
  77. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_apply_flag_settings.py +0 -0
  78. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_changelog.py +0 -0
  79. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_client.py +0 -0
  80. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_elicitation_mcp_conversion.py +0 -0
  81. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_errors.py +0 -0
  82. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_get_usage.py +0 -0
  83. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_image.png +0 -0
  84. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_integration.py +0 -0
  85. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_line_framing.py +0 -0
  86. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_mcp_delivery.py +0 -0
  87. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_message_parser.py +0 -0
  88. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_result_error.py +0 -0
  89. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_sandbox_settings.py +0 -0
  90. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_sdk_0_3_types.py +0 -0
  91. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_sdk_mcp_integration.py +0 -0
  92. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_session.py +0 -0
  93. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_session_mutations.py +0 -0
  94. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_session_title.py +0 -0
  95. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_sessions.py +0 -0
  96. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_steer.py +0 -0
  97. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_storage_entries.py +0 -0
  98. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_streaming_client.py +0 -0
  99. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_subprocess_buffering.py +0 -0
  100. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_tool_callbacks.py +0 -0
  101. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_transport.py +0 -0
  102. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_transport_close.py +0 -0
  103. {clawd_code_sdk-1.5.0 → clawd_code_sdk-1.5.2}/tests/test_unknown_entries.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: clawd-code-sdk
3
- Version: 1.5.0
3
+ Version: 1.5.2
4
4
  Summary: Python SDK for Claude Code
5
5
  Project-URL: Documentation, https://github.com/phil65/claude-agent-sdk-python
6
6
  Project-URL: Homepage, https://github.com/phil65/claude-agent-sdk-python
@@ -21,7 +21,7 @@ Requires-Dist: anthropic>=2.9.0
21
21
  Requires-Dist: anyenv>=2.0.15
22
22
  Requires-Dist: anyio>=4.0.0
23
23
  Requires-Dist: jsonschema>=4.20.0
24
- Requires-Dist: logfire>=4.31.0
24
+ Requires-Dist: logfire>=4.32.1
25
25
  Requires-Dist: mcp<3.0.0,>=1.23.0
26
26
  Requires-Dist: python-dotenv>=1.2.1
27
27
  Provides-Extra: dev
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "clawd-code-sdk"
3
- version = "1.5.0"
3
+ version = "1.5.2"
4
4
  description = "Python SDK for Claude Code"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.13"
@@ -23,7 +23,7 @@ dependencies = [
23
23
  "anyenv>=2.0.15",
24
24
  "anyio>=4.0.0",
25
25
  "jsonschema>=4.20.0",
26
- "logfire>=4.31.0",
26
+ "logfire>=4.32.1", # BlobPart.media_type (was mime_type)
27
27
  "mcp>=1.23.0,<3.0.0",
28
28
  "python-dotenv>=1.2.1",
29
29
  ]
@@ -64,9 +64,41 @@ if TYPE_CHECKING:
64
64
  RequestId,
65
65
  SDKControlRequest,
66
66
  )
67
+ from clawd_code_sdk.models.control import SdkMcpServerManifest
67
68
 
68
69
  logger = logging.getLogger(__name__)
69
70
 
71
+ MANIFEST_CAPTURE_TIMEOUT = 10.0
72
+ """Seconds an in-process MCP server gets to answer the handshake captured for the CLI."""
73
+
74
+
75
+ async def _handshake(name: str, bridge: SdkMcpBridge) -> SdkMcpServerManifest | None:
76
+ """``name``'s handshake results (initialize, first tools/list), or None if it errs."""
77
+ from mcp.types import LATEST_PROTOCOL_VERSION
78
+
79
+ from clawd_code_sdk._version import __version__
80
+
81
+ params = {
82
+ "protocolVersion": LATEST_PROTOCOL_VERSION,
83
+ "capabilities": {},
84
+ "clientInfo": {"name": "clawd-code-sdk", "version": __version__},
85
+ }
86
+ request = {"jsonrpc": "2.0", "id": f"manifest:{name}:initialize", "method": "initialize"}
87
+ answer = await bridge.handle({**request, "params": params})
88
+ if answer is None or not isinstance(result := answer.get("result"), dict):
89
+ logger.warning("SDK MCP server %r answered initialize with an error: %s", name, answer)
90
+ return None
91
+ await bridge.handle({"jsonrpc": "2.0", "method": "notifications/initialized"})
92
+ manifest: SdkMcpServerManifest = {"initializeResult": result}
93
+ capabilities = result.get("capabilities")
94
+ if isinstance(capabilities, dict) and capabilities.get("tools") is not None:
95
+ listing = {"jsonrpc": "2.0", "id": f"manifest:{name}:tools-list", "method": "tools/list"}
96
+ listed = await bridge.handle(listing)
97
+ tools = listed.get("result") if listed is not None else None
98
+ if isinstance(tools, dict) and tools.get("nextCursor") is None: # Not paginated
99
+ manifest["toolsListResult"] = tools
100
+ return manifest
101
+
70
102
 
71
103
  def get_jsonrpc_request_id(message: JSONRPCMessage) -> RequestId:
72
104
  """Extract the request ID from a JSON-RPC message if available. Falls back to 0."""
@@ -195,6 +227,33 @@ class Query:
195
227
  hooks_config[event].append(matcher_cfg)
196
228
  return hooks_config or None
197
229
 
230
+ async def capture_sdk_mcp_manifests(
231
+ self, timeout: float = MANIFEST_CAPTURE_TIMEOUT
232
+ ) -> dict[str, SdkMcpServerManifest] | None:
233
+ """Handshake the in-process MCP servers here, for the initialize request.
234
+
235
+ Each server gets ``initialize`` (no client capabilities), ``notifications/initialized``
236
+ and, if it has tools, ``tools/list``; the results go to the CLI verbatim
237
+ (``sdkMcpServerManifests``), which then connects the servers without control round
238
+ trips. The bridges' sessions stay up, so the CLI's ``mcp_message`` traffic goes on
239
+ as before (also a handshake of its own). A server that fails or takes longer than
240
+ ``timeout`` seconds is left out: the CLI handshakes it over the control channel.
241
+ """
242
+ manifests: dict[str, SdkMcpServerManifest] = {}
243
+
244
+ async def capture(name: str, bridge: SdkMcpBridge) -> None:
245
+ try:
246
+ with anyio.fail_after(timeout):
247
+ if (manifest := await _handshake(name, bridge)) is not None:
248
+ manifests[name] = manifest
249
+ except Exception as exc:
250
+ logger.warning("SDK MCP server %r: no manifest (%s), CLI handshakes it", name, exc)
251
+
252
+ async with anyio.create_task_group() as tg:
253
+ for name, bridge in self._sdk_mcp_bridges.items():
254
+ tg.start_soon(capture, name, bridge)
255
+ return manifests or None
256
+
198
257
  async def start(self) -> None:
199
258
  """Start reading messages from transport."""
200
259
  if self._read_task is None:
@@ -225,9 +225,7 @@ def to_cli_args(options: ClaudeAgentOptions) -> list[str]:
225
225
  if servers_for_cli := options.argv_mcp_servers():
226
226
  dct = anyenv.dump_json({"mcpServers": servers_for_cli})
227
227
  cmd.extend(["--mcp-config", dct])
228
- if options.initialize_mcp_servers() is not None:
229
- # The CLI reads the initialize request (with the other servers) at launch
230
- cmd.append("--await-initialize")
228
+
231
229
  case str() | Path() as path if str(path):
232
230
  cmd.extend(["--mcp-config", str(path)])
233
231
 
@@ -235,7 +233,8 @@ def to_cli_args(options: ClaudeAgentOptions) -> list[str]:
235
233
  cmd.extend(["--agent", options.agent])
236
234
 
237
235
  if options.allow_dangerously_skip_permissions:
238
- cmd.append("--dangerously-skip-permissions")
236
+ # Allows switching to bypassPermissions; --dangerously-skip-permissions would start in it
237
+ cmd.append("--allow-dangerously-skip-permissions")
239
238
 
240
239
  if options.debug_file:
241
240
  cmd.extend(["--debug-file", options.debug_file])
@@ -262,8 +261,12 @@ def to_cli_args(options: ClaudeAgentOptions) -> list[str]:
262
261
  sources_value = ",".join(options.setting_sources or [])
263
262
  cmd.extend(["--setting-sources", sources_value])
264
263
 
265
- # Add plugin directories
266
- for plugin in options.plugins:
264
+ if options.reads_initialize_at_launch():
265
+ # The CLI reads the initialize request (MCP servers, plugins) at launch
266
+ cmd.append("--await-initialize")
267
+
268
+ # Add plugin directories (unless they go in the initialize request)
269
+ for plugin in options.plugins if options.initialize_plugins() is None else ():
267
270
  match plugin:
268
271
  case SdkPluginConfig(skip_mcp_discovery=True):
269
272
  cmd.extend(["--plugin-dir-no-mcp", plugin.path])
@@ -218,6 +218,10 @@ class ClaudeSDKClient:
218
218
  case _:
219
219
  title = None
220
220
  hooks_config = query.build_hooks_config()
221
+ capture = options.capture_sdk_mcp_manifests and not os.environ.get(
222
+ "CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS"
223
+ )
224
+ manifests = await query.capture_sdk_mcp_manifests() if capture else None
221
225
  request = SDKControlInitializeRequest(
222
226
  hooks=hooks_config,
223
227
  agents={name: d.to_wire_model() for name, d in (options.agents or {}).items()} or None,
@@ -227,6 +231,9 @@ class ClaudeSDKClient:
227
231
  prompt_suggestions=options.prompt_suggestions,
228
232
  exclude_dynamic_sections=options.exclude_dynamic_sections,
229
233
  sdk_mcp_servers=list(query.sdk_mcp_servers.keys()) or None,
234
+ sdk_mcp_server_configs=options.sdk_mcp_server_configs(),
235
+ sdk_mcp_server_manifests=manifests,
236
+ plugins=(plugins := options.initialize_plugins()),
230
237
  mcp_servers=(mcp_servers := options.initialize_mcp_servers()),
231
238
  agent_progress_summaries=options.agent_progress_summaries,
232
239
  title=title,
@@ -245,6 +252,11 @@ class ClaudeSDKClient:
245
252
  "Claude Code did not take the MCP servers sent in the initialize request. "
246
253
  'Update Claude Code (2.1.261 or newer) or set mcp_servers_delivery="argv".'
247
254
  )
255
+ if plugins is not None and info.plugins_applied is not True:
256
+ raise CLIConnectionError(
257
+ "Claude Code did not load the plugins sent in the initialize request. "
258
+ 'Update Claude Code or set plugin_delivery="argv".'
259
+ )
248
260
  blocks_on_failure = any(
249
261
  m.on_failure not in (None, "continue")
250
262
  for matchers in (options.hooks or {}).values()
@@ -161,7 +161,7 @@ class ImageBlock(BaseContentBlock):
161
161
  return BlobPart(
162
162
  type="blob",
163
163
  content=self.source.data,
164
- mime_type=self.source.media_type,
164
+ media_type=self.source.media_type,
165
165
  modality="image",
166
166
  )
167
167
 
@@ -103,6 +103,15 @@ class SDKControlPermissionRequest(_ControlBase):
103
103
  (e.g. sensitive-file paths). Absent when no safetyCheck is involved."""
104
104
 
105
105
 
106
+ class SdkMcpServerManifest(TypedDict, total=False):
107
+ """An in-process MCP server's handshake output, verbatim (``sdkMcpServerManifests``)."""
108
+
109
+ initializeResult: dict[str, Any]
110
+ """The server's JSON-RPC ``initialize`` result."""
111
+ toolsListResult: dict[str, Any]
112
+ """Its first ``tools/list`` result (left out when not captured or paginated)."""
113
+
114
+
106
115
  class SDKControlInitializeRequest(_ControlBase):
107
116
  """SDK control initialize request."""
108
117
 
@@ -110,6 +119,23 @@ class SDKControlInitializeRequest(_ControlBase):
110
119
  hooks: dict[HookEvent, Any] | None = None
111
120
  agents: dict[str, AgentWireDefinition] | None = None
112
121
  sdk_mcp_servers: list[str] | None = Field(default=None, serialization_alias="sdkMcpServers")
122
+ sdk_mcp_server_configs: dict[str, dict[str, Any]] | None = Field(
123
+ default=None, serialization_alias="sdkMcpServerConfigs"
124
+ )
125
+ """Settings of the in-process servers in ``sdk_mcp_servers``, by name: ``timeout`` (ms per
126
+ tool call, when first registered) and ``tools`` (per-tool permission policy)."""
127
+ sdk_mcp_server_manifests: dict[str, SdkMcpServerManifest] | None = Field(
128
+ default=None, serialization_alias="sdkMcpServerManifests"
129
+ )
130
+ """The in-process servers' handshake results, captured by the host (a one-shot cache
131
+ for the connect that follows; ``sdk_mcp_manifests_parked`` reports each entry)."""
132
+ sdk_mcp_server_manifests_origin: Literal["host_per_send"] | None = Field(
133
+ default=None, serialization_alias="sdkMcpServerManifestsOrigin"
134
+ )
135
+ """That the manifests were captured for this send (only needed over a remote session
136
+ transport; the CLI's own stdio transport needs no marker)."""
137
+ plugins: list[dict[str, Any]] | None = None
138
+ """Plugins to load at launch (``plugin_delivery="initialize"``, ``--await-initialize``)."""
113
139
  mcp_servers: dict[str, dict[str, Any]] | None = Field(
114
140
  default=None, serialization_alias="mcpServers"
115
141
  )
@@ -325,6 +325,25 @@ class ClaudeAgentOptions:
325
325
  """SubAgent definitions."""
326
326
  plugins: list[SdkPluginConfig] = field(default_factory=list)
327
327
  """"Plugin configurations to load."""
328
+ plugin_delivery: Literal["argv", "initialize"] = "argv"
329
+ """How ``plugins`` reach Claude Code.
330
+
331
+ - ``"argv"`` (default): one ``--plugin-dir`` flag per plugin. Works with any Claude Code
332
+ version, but the command line grows with the plugin count (Windows refuses one past
333
+ 32,767 characters).
334
+ - ``"initialize"``: in the initialize request over stdin (the CLI is started with
335
+ ``--await-initialize``); connecting fails if the CLI does not load them
336
+ (``plugins_applied``). A launch with ``--sdk-url`` in ``extra_args`` always uses argv.
337
+ """
338
+ capture_sdk_mcp_manifests: bool = True
339
+ """Do the in-process MCP servers' handshake before connecting and send its results.
340
+
341
+ The initialize request then carries each server's ``initialize`` and first
342
+ ``tools/list`` results (``sdkMcpServerManifests``), so the CLI connects them without
343
+ control round trips before the first turn. A server whose handshake fails, or that the
344
+ CLI does not take, is handshaken over the control channel as before. Off when the
345
+ ``CLAUDE_AGENT_SDK_DISABLE_MCP_MANIFESTS`` environment variable is set (as upstream).
346
+ """
328
347
  output_schema: dict[str, Any] | type | None = None
329
348
  """JSON schema for structured output.
330
349
 
@@ -480,6 +499,39 @@ class ClaudeAgentOptions:
480
499
  }
481
500
  return servers or None
482
501
 
502
+ def initialize_plugins(self) -> list[dict[str, Any]] | None:
503
+ """The plugins to send in the initialize request, or None to pass them as flags."""
504
+ if self.plugin_delivery != "initialize" or "sdk-url" in self.extra_args:
505
+ return None
506
+ plugins = [p.model_dump(by_alias=True, exclude_none=True) for p in self.plugins]
507
+ return plugins or None
508
+
509
+ def reads_initialize_at_launch(self) -> bool:
510
+ """Whether the CLI waits for the initialize request (``--await-initialize``)."""
511
+ return self.initialize_mcp_servers() is not None or self.initialize_plugins() is not None
512
+
513
+ def sdk_mcp_server_configs(self) -> dict[str, dict[str, Any]] | None:
514
+ """Settings of the in-process MCP servers (timeout, tool policy), by server name."""
515
+ from clawd_code_sdk.models.mcp import McpSdkServerConfig
516
+
517
+ if not isinstance(self.mcp_servers, dict):
518
+ return None
519
+ configs: dict[str, dict[str, Any]] = {}
520
+ for name, config in self.mcp_servers.items():
521
+ if not isinstance(config, McpSdkServerConfig):
522
+ continue
523
+ settings: dict[str, Any] = {}
524
+ if config.timeout is not None:
525
+ settings["timeout"] = config.timeout
526
+ if config.tools is not None:
527
+ settings["tools"] = [
528
+ {k: v for k, v in dataclasses.asdict(t).items() if v is not None}
529
+ for t in config.tools
530
+ ]
531
+ if settings:
532
+ configs[name] = settings
533
+ return configs or None
534
+
483
535
  def argv_mcp_servers(self) -> dict[str, dict[str, Any]]:
484
536
  """The servers for ``--mcp-config``.
485
537
 
@@ -10,11 +10,18 @@ tool-result entry's parent is the assistant entry holding its own ``tool_use``.
10
10
  A plain walk from the leaf only follows the branch the next turn continued from
11
11
  and loses the other calls and results; :func:`resolve_chain` puts them back
12
12
  (as upstream's ``get_session_messages`` and Claude Code itself do).
13
+
14
+ For a single walk over a large transcript, validating every entry costs far more
15
+ than the walk. The ``raw`` functions walk the parsed JSON instead (as upstream does)
16
+ and :func:`validate_chain_entries` types only the entries actually needed.
13
17
  """
14
18
 
15
19
  from __future__ import annotations
16
20
 
17
- from typing import TYPE_CHECKING
21
+ from typing import TYPE_CHECKING, Any
22
+
23
+ import anyenv
24
+ from pydantic import ValidationError
18
25
 
19
26
  from clawd_code_sdk.models import ToolResultBlock, ToolUseBlock
20
27
  from clawd_code_sdk.storage.models import (
@@ -23,14 +30,19 @@ from clawd_code_sdk.storage.models import (
23
30
  ClaudeEntryBase,
24
31
  ClaudeModelRefusalFallbackEntry,
25
32
  ClaudeUserEntry,
33
+ chain_entry_types,
26
34
  )
27
35
 
28
36
 
29
37
  if TYPE_CHECKING:
30
38
  from collections.abc import Iterable
39
+ from pathlib import Path
31
40
 
32
41
  from clawd_code_sdk.storage.models import ClaudeJSONLEntry
33
42
 
43
+ RawEntry = dict[str, Any]
44
+ """A transcript line as parsed JSON, not validated."""
45
+
34
46
 
35
47
  def index_chain_entries(entries: Iterable[ClaudeJSONLEntry]) -> dict[str, ClaudeChainEntry]:
36
48
  """Index all chain entries by ``uuid``, in file order."""
@@ -197,3 +209,61 @@ def _recover_parallel_tool_calls(
197
209
  result_chain.append(entry)
198
210
  result_chain.extend(inserts.get(entry.uuid, ()))
199
211
  return result_chain
212
+
213
+
214
+ def read_raw_chain_entries(session_path: Path) -> dict[str, RawEntry]:
215
+ """The chain entries of a transcript as parsed JSON, by ``uuid``, in file order.
216
+
217
+ Only parses JSON: about as fast as reading the file, much faster than
218
+ :func:`~clawd_code_sdk.storage.helpers.read_session` on large transcripts.
219
+ Corrupt lines are skipped.
220
+ """
221
+ from clawd_code_sdk.storage.helpers import _gc_paused
222
+
223
+ types = chain_entry_types()
224
+ index: dict[str, RawEntry] = {}
225
+ if not session_path.exists():
226
+ return index
227
+ with _gc_paused(), session_path.open("rb") as f:
228
+ for line in f:
229
+ if not line.strip():
230
+ continue
231
+ try:
232
+ data = anyenv.load_json(line, return_type=dict)
233
+ except anyenv.JsonLoadError:
234
+ continue
235
+ uuid = data.get("uuid")
236
+ if data.get("type") in types and isinstance(uuid, str):
237
+ index[uuid] = data
238
+ return index
239
+
240
+
241
+ def walk_raw_ancestry(
242
+ index: dict[str, RawEntry], uuid: str, *, include_start: bool = True
243
+ ) -> list[RawEntry]:
244
+ """Like :func:`walk_ancestry`, over parsed JSON: leaf first, stops at a cycle."""
245
+ chain: list[RawEntry] = []
246
+ seen: set[str] = set()
247
+ current = index.get(uuid)
248
+ while current is not None and current["uuid"] not in seen: # indexed: uuid is a str
249
+ seen.add(current["uuid"])
250
+ chain.append(current)
251
+ parent = current.get("parentUuid")
252
+ current = index.get(parent) if isinstance(parent, str) else None
253
+ return chain if include_start else chain[1:]
254
+
255
+
256
+ def validate_chain_entries(raw_entries: Iterable[RawEntry]) -> list[ClaudeChainEntry]:
257
+ """Validate parsed entries into their models, keeping the chain entries that pass."""
258
+ from clawd_code_sdk.storage.helpers import _entry_adapter
259
+
260
+ adapter = _entry_adapter()
261
+ entries: list[ClaudeChainEntry] = []
262
+ for raw in raw_entries:
263
+ try:
264
+ entry = adapter.validate_python(raw)
265
+ except ValidationError:
266
+ continue
267
+ if isinstance(entry, ClaudeChainEntry):
268
+ entries.append(entry)
269
+ return entries
@@ -1244,6 +1244,12 @@ def _entry_tags(annotation: Any) -> set[str]:
1244
1244
  return {tag for arg in get_args(annotation) for tag in _entry_tags(arg)}
1245
1245
 
1246
1246
 
1247
+ @cache
1248
+ def chain_entry_types() -> frozenset[str]:
1249
+ """The ``type`` tags of :data:`ClaudeChainEntry` (entries that take part in the chain)."""
1250
+ return frozenset(_entry_tags(ClaudeChainEntry))
1251
+
1252
+
1247
1253
  @cache
1248
1254
  def known_entry_types() -> frozenset[str]:
1249
1255
  """The ``type`` tags of :data:`KnownClaudeJSONLEntry`."""
@@ -0,0 +1,103 @@
1
+ """Launch flags and initialize request fields that follow the upstream SDK (0.3.331)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from clawd_code_sdk import ClaudeAgentOptions, create_sdk_mcp_server, tool
8
+ from clawd_code_sdk._internal.query import Query
9
+ from clawd_code_sdk._internal.transport import Transport
10
+ from clawd_code_sdk._internal.transport.subprocess_utils import to_cli_args
11
+ from clawd_code_sdk.models.mcp import McpServerToolPolicy, SdkPluginConfig
12
+
13
+
14
+ if TYPE_CHECKING:
15
+ from collections.abc import AsyncIterator
16
+
17
+
18
+ class _NullTransport(Transport):
19
+ async def connect(self) -> None:
20
+ pass
21
+
22
+ async def write(self, data: str) -> None:
23
+ pass
24
+
25
+ async def read_messages(self) -> AsyncIterator[dict[str, Any]]:
26
+ return
27
+ yield
28
+
29
+ async def close(self) -> None:
30
+ pass
31
+
32
+ async def end_input(self) -> None:
33
+ pass
34
+
35
+
36
+ def test_plugins_go_as_flags_by_default() -> None:
37
+ options = ClaudeAgentOptions(plugins=[SdkPluginConfig(path="/p")], mcp_servers={})
38
+ args = to_cli_args(options)
39
+ assert args[args.index("--plugin-dir") + 1] == "/p"
40
+ assert "--await-initialize" not in args
41
+ assert options.initialize_plugins() is None
42
+
43
+
44
+ def test_plugins_in_the_initialize_request() -> None:
45
+ plugins = [SdkPluginConfig(path="/p"), SdkPluginConfig(path="/q", skip_mcp_discovery=True)]
46
+ options = ClaudeAgentOptions(plugins=plugins, plugin_delivery="initialize", mcp_servers={})
47
+ args = to_cli_args(options)
48
+ assert "--plugin-dir" not in args
49
+ assert "--plugin-dir-no-mcp" not in args
50
+ assert args.count("--await-initialize") == 1 # The CLI reads them at launch
51
+ assert options.initialize_plugins() == [
52
+ {"type": "local", "path": "/p"},
53
+ {"type": "local", "path": "/q", "skipMcpDiscovery": True},
54
+ ]
55
+
56
+
57
+ def test_sdk_server_settings_are_sent_by_server() -> None:
58
+ plain = create_sdk_mcp_server("plain")
59
+ tuned = create_sdk_mcp_server("tuned")
60
+ tuned.timeout = 30_000
61
+ tuned.tools = [McpServerToolPolicy(name="delete", permission_policy="always_ask")]
62
+ options = ClaudeAgentOptions(mcp_servers={"plain": plain, "tuned": tuned})
63
+ assert options.sdk_mcp_server_configs() == {
64
+ "tuned": {
65
+ "timeout": 30_000,
66
+ "tools": [{"name": "delete", "permission_policy": "always_ask"}],
67
+ }
68
+ }
69
+
70
+
71
+ async def test_in_process_servers_are_handshaken_for_the_cli() -> None:
72
+ @tool("greet", "Greet someone", {"name": str})
73
+ async def greet(args: dict[str, Any]) -> dict[str, Any]:
74
+ return {"content": [{"type": "text", "text": f"Hello, {args['name']}!"}]}
75
+
76
+ config = create_sdk_mcp_server("greeter", tools=[greet])
77
+ query = Query(transport=_NullTransport(), sdk_mcp_servers={"greeter": config.instance})
78
+ try:
79
+ manifests = await query.capture_sdk_mcp_manifests()
80
+ assert manifests is not None
81
+ manifest = manifests["greeter"]
82
+ assert manifest["initializeResult"]["protocolVersion"]
83
+ assert [t["name"] for t in manifest["toolsListResult"]["tools"]] == ["greet"]
84
+ # The CLI then calls tools over mcp_message, without a handshake of its own
85
+ message = {
86
+ "jsonrpc": "2.0",
87
+ "id": 7,
88
+ "method": "tools/call",
89
+ "params": {"name": "greet", "arguments": {"name": "Ada"}},
90
+ }
91
+ response = await query._handle_sdk_mcp_request("greeter", message) # type: ignore[arg-type]
92
+ assert response is not None
93
+ assert response["result"]["content"][0]["text"] == "Hello, Ada!"
94
+ finally:
95
+ await query.close()
96
+
97
+
98
+ async def test_no_in_process_servers_no_manifests() -> None:
99
+ query = Query(transport=_NullTransport())
100
+ try:
101
+ assert await query.capture_sdk_mcp_manifests() is None
102
+ finally:
103
+ await query.close()
@@ -0,0 +1,16 @@
1
+ """The permission flags passed to the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from clawd_code_sdk import ClaudeAgentOptions
6
+ from clawd_code_sdk._internal.transport.subprocess_utils import to_cli_args
7
+
8
+
9
+ def test_allowing_bypass_does_not_start_in_bypass() -> None:
10
+ """``--allow-…`` permits switching to bypassPermissions; the other flag starts in it."""
11
+ args = to_cli_args(
12
+ ClaudeAgentOptions(permission_mode="default", allow_dangerously_skip_permissions=True)
13
+ )
14
+ assert "--allow-dangerously-skip-permissions" in args
15
+ assert "--dangerously-skip-permissions" not in args
16
+ assert args[args.index("--permission-mode") + 1] == "default"
@@ -2,7 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Any
5
+ import json
6
+ from typing import TYPE_CHECKING, Any
6
7
 
7
8
  from pydantic import TypeAdapter
8
9
 
@@ -10,13 +11,20 @@ from clawd_code_sdk.models import AssistantMessage, UserMessage
10
11
  from clawd_code_sdk.storage.chain import (
11
12
  find_leaf,
12
13
  index_chain_entries,
14
+ read_raw_chain_entries,
13
15
  resolve_chain,
16
+ validate_chain_entries,
14
17
  walk_ancestry,
18
+ walk_raw_ancestry,
15
19
  )
16
20
  from clawd_code_sdk.storage.models import ClaudeJSONLEntry
17
21
  from clawd_code_sdk.storage.replay import replay_entries
18
22
 
19
23
 
24
+ if TYPE_CHECKING:
25
+ from pathlib import Path
26
+
27
+
20
28
  ADAPTER = TypeAdapter[list[ClaudeJSONLEntry]](list[ClaudeJSONLEntry])
21
29
  _clock = iter(range(10_000))
22
30
 
@@ -169,3 +177,29 @@ def test_messages_withdrawn_by_a_refusal_are_left_out() -> None:
169
177
  # The walk passes through the withdrawn message, but it is not returned.
170
178
  assert uuids(resolve_chain(entries)) == ["u1", "sy1", "a2"]
171
179
  assert "a1" in uuids(walk_ancestry(index_chain_entries(entries), "a2"))
180
+
181
+
182
+ def test_raw_walk_matches_the_typed_walk(tmp_path: Path) -> None:
183
+ rows = [
184
+ attachment("at1", None),
185
+ user("u1", "at1"),
186
+ attachment("at2", "u1"),
187
+ assistant("a1", "at2", "msg_1"),
188
+ system("sy1", "a1"),
189
+ user("u2", "sy1"),
190
+ assistant("a2", "u2", "msg_2"),
191
+ {"type": "custom-title", "customTitle": "not a chain entry", "sessionId": "s1"},
192
+ ]
193
+ path = tmp_path / "s.jsonl"
194
+ path.write_text("".join(json.dumps(row) + "\n" for row in rows) + "not json\n")
195
+ typed = walk_ancestry(index_chain_entries(load(*rows)), "a2")
196
+ raw = walk_raw_ancestry(read_raw_chain_entries(path), "a2")
197
+ assert [entry["uuid"] for entry in raw] == uuids(typed)
198
+ assert uuids(validate_chain_entries(raw)) == uuids(typed)
199
+
200
+
201
+ def test_raw_walk_stops_on_cycle(tmp_path: Path) -> None:
202
+ path = tmp_path / "s.jsonl"
203
+ path.write_text(json.dumps(user("x1", "x2")) + "\n" + json.dumps(user("x2", "x1")) + "\n")
204
+ raw = walk_raw_ancestry(read_raw_chain_entries(path), "x2")
205
+ assert [entry["uuid"] for entry in raw] == ["x2", "x1"]
File without changes
File without changes