From 0f4fbfeeaa63f8069132ba23008fb5330e5e6cae Mon Sep 17 00:00:00 2001 From: Scott Anderson Date: Sun, 22 Nov 2026 20:41:32 +1100 Subject: [PATCH] feat(client): accept extra_params on initialize_session and load_session Add an extra_params escape hatch so callers can send JSON-RPC fields the SDK does not yet model. Keys that match any modelled field raise ValueError before anything is sent. Closes #14 Co-Authored-By: Claude Opus 5.5 --- src/droid_sdk/client.py | 43 +++++++- tests/test_client_protocol_surface.py | 150 ++++++++++++++++++++++++++ 2 files changed, 192 insertions(+), 1 deletion(-) diff --git a/src/droid_sdk/client.py b/src/droid_sdk/client.py index 9b24d11..a0e68d3 100644 --- a/src/droid_sdk/client.py +++ b/src/droid_sdk/client.py @@ -18,7 +18,7 @@ import contextlib import dataclasses import logging -from collections.abc import AsyncIterator, Callable, Sequence +from collections.abc import AsyncIterator, Callable, Mapping, Sequence from types import TracebackType # noqa: TC003 from typing import TYPE_CHECKING, Any, Literal, cast, overload @@ -350,6 +350,7 @@ async def initialize_session( auto_reject_permission_requests: bool | None = None, disable_builtin_skills: bool | None = None, mcp_oauth_callback_uri: str | None = None, + extra_params: Mapping[str, Any] | None = None, ) -> InitializeSessionResult: """Initialize a new session. @@ -390,6 +391,11 @@ async def initialize_session( requests instead of forwarding them. disable_builtin_skills: Whether builtin skills are unavailable. mcp_oauth_callback_uri: OAuth callback URI for MCP. + extra_params: Additional JSON-RPC fields to send, keyed by wire name + (camelCase). This is the supported path for protocol fields newer + than the installed SDK. Keys are sent as-is; a key that collides + with a modelled field (including SDK-set fields such as + ``sessionOriginHint``) raises ``ValueError``. Returns: Typed ``InitializeSessionResult`` with session_id, session, @@ -398,6 +404,7 @@ async def initialize_session( Raises: ConnectionError: If the client has been closed. ProtocolError: If the server returns an error. + ValueError: If ``extra_params`` collides with a modelled field. """ self._ensure_not_closed() protocol = self._ensure_protocol() @@ -445,6 +452,9 @@ async def initialize_session( mcp_oauth_callback_uri=mcp_oauth_callback_uri, ) ) + params = _merge_extra_params( + params, extra_params, InitializeSessionRequestParams + ) response = await protocol.send_request( method=DroidServerMethod.INITIALIZE_SESSION.value, params=params, @@ -468,6 +478,7 @@ async def load_session( disable_builtin_skills: bool | None = None, session_location: str | None = None, session_source: SessionSource | dict[str, Any] | None = None, + extra_params: Mapping[str, Any] | None = None, ) -> LoadSessionResult: """Load an existing session. @@ -487,6 +498,11 @@ async def load_session( disable_builtin_skills: Whether builtin skills are unavailable. session_location: Optional session origin/location metadata. session_source: Optional structured session source metadata. + extra_params: Additional JSON-RPC fields to send, keyed by wire name + (camelCase). This is the supported path for protocol fields newer + than the installed SDK. Keys are sent as-is; a key that collides + with a modelled field (including SDK-set fields such as + ``sessionOriginHint``) raises ``ValueError``. Returns: Typed ``LoadSessionResult`` with session and settings. @@ -495,6 +511,7 @@ async def load_session( SessionNotFoundError: If the session does not exist. ProtocolError: If the server returns an error. ConnectionError: If the client has been closed. + ValueError: If ``extra_params`` collides with a modelled field. """ self._ensure_not_closed() protocol = self._ensure_protocol() @@ -519,6 +536,7 @@ async def load_session( session_origin_hint=SessionOrigin.Sdk, ) ) + params = _merge_extra_params(params, extra_params, LoadSessionRequestParams) response = await protocol.send_request( method=DroidServerMethod.LOAD_SESSION.value, params=params, @@ -2034,6 +2052,29 @@ def _serialize_params(model: BaseModel) -> dict[str, Any]: ) +def _merge_extra_params( + params: dict[str, Any], + extra_params: Mapping[str, Any] | None, + model_cls: type[BaseModel], +) -> dict[str, Any]: + """Merge caller-supplied wire fields into serialized request params. + + Keys are compared against every wire alias (camelCase) of + ``model_cls``, whether or not that field was set, so modelled fields + always go through the typed argument and its validation. + """ + if not extra_params: + return params + modelled = {f.alias or name for name, f in model_cls.model_fields.items()} + for key in extra_params: + if key in modelled: + raise ValueError( + f"extra_params key {key!r} collides with a modelled field; " + "use the corresponding keyword argument instead" + ) + return {**params, **extra_params} + + def _validate_session_tags( tags: Sequence[SessionTag | dict[str, Any]] | None, ) -> list[SessionTag] | None: diff --git a/tests/test_client_protocol_surface.py b/tests/test_client_protocol_surface.py index dab3297..7a6004b 100644 --- a/tests/test_client_protocol_surface.py +++ b/tests/test_client_protocol_surface.py @@ -883,3 +883,153 @@ async def test_fork_session_serializes_typed_tags(self) -> None: ] await client.close() + + +# --------------------------------------------------------------------------- +# extra_params escape hatch +# --------------------------------------------------------------------------- + +_INIT_RESULT: dict[str, Any] = { + "sessionId": "sess-1", + "session": {"id": "sess-1", "messages": []}, + "settings": {"modelId": "claude-sonnet-4", "reasoningEffort": "medium"}, +} +_LOAD_RESULT: dict[str, Any] = { + "session": {"id": "sess-1", "messages": []}, + "settings": {"modelId": "claude-sonnet-4", "reasoningEffort": "medium"}, +} + + +async def _connected() -> tuple[InMemoryTransport, DroidClient]: + transport = InMemoryTransport() + client = DroidClient(transport=transport) + await client.connect() + return transport, client + + +class TestExtraParams: + @pytest.mark.asyncio + async def test_initialize_session_forwards_extra_params(self) -> None: + transport, client = await _connected() + + sent, _ = await _call( + transport, + client.initialize_session( + machine_id="test", + cwd="/tmp", + extra_params={"experimentalFlag": True, "nested": {"a": 1}}, + ), + _INIT_RESULT, + ) + + assert sent["params"]["machineId"] == "test" + assert sent["params"]["cwd"] == "/tmp" + assert sent["params"]["experimentalFlag"] is True + assert sent["params"]["nested"] == {"a": 1} + + await client.close() + + @pytest.mark.asyncio + async def test_load_session_forwards_extra_params(self) -> None: + transport, client = await _connected() + + sent, _ = await _call( + transport, + client.load_session( + session_id="sess-1", extra_params={"experimentalFlag": True} + ), + _LOAD_RESULT, + ) + + assert sent["method"] == "droid.load_session" + assert sent["params"]["experimentalFlag"] is True + + await client.close() + + @pytest.mark.asyncio + async def test_initialize_session_rejects_collision_with_modelled_field( + self, + ) -> None: + transport, client = await _connected() + before = len(transport.sent_messages) + + with pytest.raises(ValueError, match="enabledToolIds"): + await client.initialize_session( + machine_id="test", + cwd="/tmp", + enabled_tool_ids=["read"], + extra_params={"enabledToolIds": []}, + ) + + assert len(transport.sent_messages) == before + + await client.close() + + @pytest.mark.asyncio + async def test_load_session_rejects_collision_with_modelled_field(self) -> None: + transport, client = await _connected() + before = len(transport.sent_messages) + + with pytest.raises(ValueError, match="sessionId"): + await client.load_session( + session_id="sess-1", extra_params={"sessionId": "other"} + ) + + assert len(transport.sent_messages) == before + + await client.close() + + @pytest.mark.asyncio + async def test_rejects_modelled_field_even_when_unset(self) -> None: + transport, client = await _connected() + + with pytest.raises(ValueError, match="modelId"): + await client.initialize_session( + machine_id="test", cwd="/tmp", extra_params={"modelId": "x"} + ) + + assert transport.sent_messages == [] + + await client.close() + + @pytest.mark.asyncio + async def test_extra_params_none_is_a_no_op(self) -> None: + transport, client = await _connected() + + baseline, _ = await _call( + transport, + client.initialize_session(machine_id="test", cwd="/tmp"), + _INIT_RESULT, + ) + with_none, _ = await _call( + transport, + client.initialize_session(machine_id="test", cwd="/tmp", extra_params=None), + _INIT_RESULT, + ) + with_empty, _ = await _call( + transport, + client.initialize_session(machine_id="test", cwd="/tmp", extra_params={}), + _INIT_RESULT, + ) + + assert with_none["params"] == baseline["params"] + assert with_empty["params"] == baseline["params"] + + await client.close() + + @pytest.mark.asyncio + async def test_extra_params_does_not_rename_keys(self) -> None: + transport, client = await _connected() + + sent, _ = await _call( + transport, + client.initialize_session( + machine_id="test", cwd="/tmp", extra_params={"snake_case_key": 1} + ), + _INIT_RESULT, + ) + + assert sent["params"]["snake_case_key"] == 1 + assert "snakeCaseKey" not in sent["params"] + + await client.close()