Skip to content

Commit 8ed58af

Browse files
qing-antclaude
andauthored
fix: send permission updates in the shape the CLI accepts (#1502)
Fixes #1308. Covers the same ground as #1272 (`ruleContent`) and #1330 (`destination`); thanks to both authors. ## What was wrong When `can_use_tool` returns `PermissionResultAllow(updated_permissions=[...])`, the CLI checks every update against its schema. If one doesn't fit, it ignores the whole list: the call is allowed, nothing is remembered, and the user is asked again. `PermissionUpdate.to_dict()` could produce such an update from values its own types allow. The common case: suggestions for whole tools (WebSearch, MCP tools) arrive without `ruleContent`, became `None`, and went back as `null`, so echoing `context.suggestions` lost every update. ## The change | Python value | Before | After | | --- | --- | --- | | `rule_content=None` | `"ruleContent": null`, list dropped | key left out | | `destination=None` | key left out, list dropped | `"session"`, for every type | | `rules`, `behavior`, `mode` or `directories` is `None` where the type needs it, or unknown `type` | key left out, list dropped silently | `to_dict()` raises `ValueError`; the SDK sends no updates from that answer and logs a warning; the call is still allowed | It's all or nothing because the update that failed may be a restriction the others were meant to come with. The `"session"` default applies to every type so that a grant made without a destination can be revoked the same way. **Release note:** updates the CLI silently ignored before now take effect. A callback that returns whole-tool rules (`rule_content=None`) or updates with no destination will start changing permissions. For example, a whole-tool allow rule with `destination="projectSettings"` is now written to `.claude/settings.json`. Updates that were already valid go out unchanged. ## Testing - `pytest tests/`: 1742 passed, 6 skipped; 24 of the new and updated tests fail without the fix. `ruff check`, `ruff format --check` and `mypy` are clean. - End to end against CLI 2.1.323 and a local stub of the Messages API, calling an in-process MCP tool twice: - echoing suggestions: asked twice on `main`, once now, and the rule is saved to `.claude/settings.local.json`; - `addRules` with no destination: asked twice on `main`, once now, nothing written to disk; - `addRules` then `removeRules`, both with no destination: the next call is asked again; - a suggestion next to a `setMode` with no `mode`: asked twice either way, now with a warning. --- _Generated by [Claude Code](https://claude.ai/code/session_01V6QzNKqmcgRvd2GFCBx9Xd)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3e19ce8 commit 8ed58af

4 files changed

Lines changed: 336 additions & 32 deletions

File tree

‎src/claude_agent_sdk/_internal/query.py‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,31 @@ def _error_result_text(message: dict[str, Any]) -> str:
115115
return "unknown error"
116116

117117

118+
def _permission_updates_to_wire(
119+
updates: list[PermissionUpdate],
120+
) -> list[dict[str, Any]] | None:
121+
"""Convert the permission updates of a ``can_use_tool`` allow result.
122+
123+
Returns ``None``, and logs a warning, if any update cannot be converted.
124+
The updates are sent all together or not at all, because the one that
125+
failed may be a restriction the others were meant to come with.
126+
"""
127+
wire: list[dict[str, Any]] = []
128+
for index, update in enumerate(updates):
129+
try:
130+
wire.append(update.to_dict())
131+
except ValueError as e:
132+
logger.warning(
133+
"The can_use_tool callback allowed the tool call, but none of its "
134+
"permission updates were applied, because updated_permissions[%d] "
135+
"cannot be sent: %s",
136+
index,
137+
e,
138+
)
139+
return None
140+
return wire
141+
142+
118143
def _convert_hook_output_for_cli(hook_output: dict[str, Any]) -> dict[str, Any]:
119144
"""Convert Python-safe field names to CLI-expected field names.
120145
@@ -653,10 +678,11 @@ async def _handle_control_request(self, request: SDKControlRequest) -> None:
653678
),
654679
}
655680
if response.updated_permissions is not None:
656-
response_data["updatedPermissions"] = [
657-
permission.to_dict()
658-
for permission in response.updated_permissions
659-
]
681+
updates = _permission_updates_to_wire(
682+
response.updated_permissions
683+
)
684+
if updates is not None:
685+
response_data["updatedPermissions"] = updates
660686
elif isinstance(response, PermissionResultDeny):
661687
response_data = {"behavior": "deny", "message": response.message}
662688
if response.interrupt:

‎src/claude_agent_sdk/types.py‎

Lines changed: 65 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,8 @@ class PermissionRuleValue:
140140

141141
tool_name: str
142142
rule_content: str | None = None
143+
"""What the rule matches within the tool, e.g. ``"npm test"`` for Bash.
144+
``None`` (or an empty string) makes a rule that covers every use of the tool."""
143145

144146

145147
@dataclass
@@ -159,43 +161,76 @@ class PermissionUpdate:
159161
mode: PermissionMode | None = None
160162
directories: list[str] | None = None
161163
destination: PermissionUpdateDestination | None = None
164+
"""Where the update applies and is kept: ``"session"`` (in memory until
165+
the session ends), ``"localSettings"``, ``"projectSettings"`` or
166+
``"userSettings"``. ``None`` is sent as ``"session"``."""
162167

163168
def to_dict(self) -> dict[str, Any]:
164-
"""Convert PermissionUpdate to dictionary format matching TypeScript control protocol."""
169+
"""Convert PermissionUpdate to the control protocol dict format.
170+
171+
Claude Code rejects an update that lacks a field its type needs, or
172+
whose ``ruleContent`` is ``null``, and then ignores every update in
173+
the same response. So this method:
174+
175+
- leaves ``ruleContent`` out when ``rule_content`` is ``None``, which
176+
is how Claude Code expects a rule for the whole tool;
177+
- sends ``"session"`` when ``destination`` is ``None``, so the update
178+
changes only the current session;
179+
- raises ``ValueError`` when a field the type needs is ``None``:
180+
``rules`` and ``behavior`` for ``addRules``, ``replaceRules`` and
181+
``removeRules``, ``mode`` for ``setMode``, and ``directories`` for
182+
``addDirectories`` and ``removeDirectories``;
183+
- raises ``ValueError`` when ``type`` is none of those six.
184+
"""
165185
result: dict[str, Any] = {
166186
"type": self.type,
187+
"destination": self.destination or "session",
167188
}
168189

169-
# Add destination for all variants
170-
if self.destination is not None:
171-
result["destination"] = self.destination
172-
173-
# Handle different type variants
174-
if self.type in ["addRules", "replaceRules", "removeRules"]:
175-
# Rules-based variants require rules and behavior
176-
if self.rules is not None:
177-
result["rules"] = [
178-
{
179-
"toolName": rule.tool_name,
180-
"ruleContent": rule.rule_content,
181-
}
182-
for rule in self.rules
183-
]
184-
if self.behavior is not None:
185-
result["behavior"] = self.behavior
190+
if self.type in ("addRules", "replaceRules", "removeRules"):
191+
if self.rules is None:
192+
raise ValueError(
193+
f"PermissionUpdate(type={self.type!r}) has no rules. "
194+
"Set rules to a list of PermissionRuleValue."
195+
)
196+
if self.behavior is None:
197+
raise ValueError(
198+
f"PermissionUpdate(type={self.type!r}) has no behavior. "
199+
"Set behavior to 'allow', 'deny' or 'ask'."
200+
)
201+
rules: list[dict[str, Any]] = []
202+
for rule in self.rules:
203+
wire_rule: dict[str, Any] = {"toolName": rule.tool_name}
204+
if rule.rule_content is not None:
205+
wire_rule["ruleContent"] = rule.rule_content
206+
rules.append(wire_rule)
207+
result["rules"] = rules
208+
result["behavior"] = self.behavior
186209

187210
elif self.type == "setMode":
188-
# Mode variant requires mode
189-
if self.mode is not None:
190-
result["mode"] = self.mode
191-
192-
elif (
193-
self.type in ["addDirectories", "removeDirectories"]
194-
and self.directories is not None
195-
):
196-
# Directory variants require directories
211+
if self.mode is None:
212+
raise ValueError(
213+
"PermissionUpdate(type='setMode') has no mode. "
214+
"Set mode to a permission mode such as 'acceptEdits'."
215+
)
216+
result["mode"] = self.mode
217+
218+
elif self.type in ("addDirectories", "removeDirectories"):
219+
if self.directories is None:
220+
raise ValueError(
221+
f"PermissionUpdate(type={self.type!r}) has no directories. "
222+
"Set directories to a list of paths."
223+
)
197224
result["directories"] = self.directories
198225

226+
else:
227+
raise ValueError(
228+
f"PermissionUpdate has type {self.type!r}, which this version "
229+
"of the SDK cannot send. Use one of addRules, replaceRules, "
230+
"removeRules, setMode, addDirectories or removeDirectories, or "
231+
"upgrade the SDK if this update came from Claude Code."
232+
)
233+
199234
return result
200235

201236
@classmethod
@@ -264,6 +299,9 @@ class PermissionResultAllow:
264299
behavior: Literal["allow"] = "allow"
265300
updated_input: dict[str, Any] | None = None
266301
updated_permissions: list[PermissionUpdate] | None = None
302+
"""Permission updates to apply along with this allow. If any of them cannot
303+
be sent (``PermissionUpdate.to_dict`` raises ``ValueError``), none are
304+
sent and a warning is logged; the tool call is still allowed."""
267305

268306

269307
@dataclass

‎tests/test_tool_callbacks.py‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,121 @@ async def always_allow(
149149
sent = response["response"]["response"]["updatedPermissions"]
150150
assert sent == [wire_suggestion]
151151

152+
@pytest.mark.anyio
153+
async def test_permission_callback_echoes_whole_tool_suggestion(self):
154+
"""A suggestion without ruleContent goes back without it, not as null.
155+
156+
Claude Code rejects a null ruleContent and then ignores every update in
157+
the response.
158+
"""
159+
160+
async def accept_suggestions(
161+
tool_name: str, input_data: dict, context: ToolPermissionContext
162+
) -> PermissionResultAllow:
163+
return PermissionResultAllow(updated_permissions=context.suggestions)
164+
165+
transport = MockTransport()
166+
query = Query(
167+
transport=transport,
168+
is_streaming_mode=True,
169+
can_use_tool=accept_suggestions,
170+
hooks=None,
171+
)
172+
173+
wire_suggestions = [
174+
{
175+
"type": "addRules",
176+
"destination": "localSettings",
177+
"behavior": "allow",
178+
"rules": [{"toolName": "WebSearch"}],
179+
},
180+
{
181+
"type": "addRules",
182+
"destination": "session",
183+
"behavior": "allow",
184+
"rules": [{"toolName": "Bash", "ruleContent": "git status"}],
185+
},
186+
{"type": "setMode", "mode": "acceptEdits", "destination": "session"},
187+
]
188+
request = {
189+
"type": "control_request",
190+
"request_id": "test-whole-tool",
191+
"request": {
192+
"subtype": "can_use_tool",
193+
"tool_name": "WebSearch",
194+
"input": {"query": "weather"},
195+
"permission_suggestions": wire_suggestions,
196+
},
197+
}
198+
199+
await query._handle_control_request(request)
200+
201+
assert len(transport.written_messages) == 1
202+
response = json.loads(transport.written_messages[0])
203+
assert response["response"]["subtype"] == "success"
204+
sent = response["response"]["response"]["updatedPermissions"]
205+
assert sent == wire_suggestions
206+
207+
@pytest.mark.anyio
208+
async def test_permission_callback_sends_no_updates_if_one_is_malformed(
209+
self, caplog
210+
):
211+
"""If one update lacks a required field, none are sent; the allow stands.
212+
213+
The malformed one may be a restriction the others depend on.
214+
"""
215+
from claude_agent_sdk.types import PermissionRuleValue, PermissionUpdate
216+
217+
async def allow_with_updates(
218+
tool_name: str, input_data: dict, context: ToolPermissionContext
219+
) -> PermissionResultAllow:
220+
return PermissionResultAllow(
221+
updated_permissions=[
222+
PermissionUpdate(
223+
type="addRules",
224+
rules=[PermissionRuleValue(tool_name="Read")],
225+
behavior="allow",
226+
destination="session",
227+
),
228+
PermissionUpdate(
229+
type="addRules",
230+
rules=[
231+
PermissionRuleValue(tool_name="Bash", rule_content="ls")
232+
],
233+
),
234+
PermissionUpdate(type="setMode", mode="acceptEdits"),
235+
]
236+
)
237+
238+
transport = MockTransport()
239+
query = Query(
240+
transport=transport,
241+
is_streaming_mode=True,
242+
can_use_tool=allow_with_updates,
243+
hooks=None,
244+
)
245+
request = {
246+
"type": "control_request",
247+
"request_id": "test-malformed-update",
248+
"request": {
249+
"subtype": "can_use_tool",
250+
"tool_name": "Read",
251+
"input": {"file_path": "/tmp/x"},
252+
"permission_suggestions": [],
253+
},
254+
}
255+
256+
with caplog.at_level("WARNING", logger="claude_agent_sdk._internal.query"):
257+
await query._handle_control_request(request)
258+
259+
assert len(transport.written_messages) == 1
260+
response = json.loads(transport.written_messages[0])
261+
assert response["response"]["subtype"] == "success"
262+
assert response["response"]["response"]["behavior"] == "allow"
263+
assert "updatedPermissions" not in response["response"]["response"]
264+
assert "updated_permissions[1] cannot be sent" in caplog.text
265+
assert "has no behavior" in caplog.text
266+
152267
@pytest.mark.anyio
153268
async def test_permission_callback_deny(self):
154269
"""Test callback that denies tool execution."""

0 commit comments

Comments
 (0)