claude-agent-sdk-python icon indicating copy to clipboard operation
claude-agent-sdk-python copied to clipboard

PermissionUpdate.to_dict() sends "ruleContent": null; the CLI silently drops the update, so "always allow" never sticks for content-less rules

Open kosio-dev opened this issue 2 months ago • 1 comments

Versions: claude-agent-sdk 0.2.157–0.2.159 (Python), Claude Code CLI 2.1.278–2.1.281 (bundled), Linux. Still reproduces on the latest.

What happens

When a can_use_tool callback returns PermissionResultAllow(updated_permissions=[...]) with a rule that has no content (for example the suggestion the CLI itself offers for WebSearch: PermissionRuleValue(tool_name="WebSearch", rule_content=None)), PermissionUpdate.to_dict() serialises it as:

{"type": "addRules", "destination": "session", "behavior": "allow",
 "rules": [{"toolName": "WebSearch", "ruleContent": null}]}

The rule is never applied and no error is reported: the next call to the same tool triggers can_use_tool again. The same update with the ruleContent key omitted works.

Repro

Model haiku, tools=["WebSearch"], a prompt asking for two sequential searches; the callback returns the CLI's own suggestion (destination set to session) as updated_permissions.

ruleContent permission prompts for 2 searches
null (SDK default) 2
key omitted 1
import asyncio, os
from claude_agent_sdk import (ClaudeAgentOptions, ClaudeSDKClient,
                              PermissionResultAllow, PermissionUpdate)


class OmitNull(PermissionUpdate):
    def to_dict(self):
        d = super().to_dict()
        for r in d.get("rules") or []:
            if r.get("ruleContent") is None:
                r.pop("ruleContent", None)
        return d


async def run(omit: bool) -> int:
    calls = 0

    async def can_use_tool(name, inp, ctx):
        nonlocal calls
        calls += 1
        sugg = list(ctx.suggestions or [])
        for s in sugg:
            s.destination = "session"
        if omit:
            sugg = [OmitNull(**vars(s)) for s in sugg]
        return PermissionResultAllow(updated_permissions=sugg)

    cwd = os.path.abspath("sdk-null-test")
    os.makedirs(cwd, exist_ok=True)
    opts = ClaudeAgentOptions(
        model="haiku", tools=["WebSearch"], cwd=cwd, setting_sources=[],
        can_use_tool=can_use_tool, max_turns=6)
    async with ClaudeSDKClient(opts) as c:
        await c.query("Do two separate WebSearch calls, one after the other "
                      "(not in parallel): first 'Python 3.13 release date', "
                      "then 'Debian 13 release date'. Reply with one line.")
        async for _ in c.receive_response():
            pass
    return calls


async def main():
    print("ruleContent null:   ", await run(False), "prompts")
    print("ruleContent omitted:", await run(True), "prompts")


asyncio.run(main())

Rules that have content (e.g. WebFetch with domain:example.com) are unaffected.

Expected

to_dict() should omit ruleContent when it is None, as in the TypeScript SDK types, where the field is optional. Alternatively the CLI should accept null, or at least report the rejected update instead of dropping it silently.

Workaround

Subclass PermissionUpdate and drop ruleContent when it is None in to_dict() (the OmitNull class above).

kosio-dev avatar Sep 24 '26 21:09 kosio-dev

Reproduced end to end on Windows 11 with SDK 0.2.159 (main 6c3df98) against the globally installed Claude Code CLI 2.1.257, and again against 2.1.282, the version main pins in _cli_version.py, installed from npm into a local folder. Same results on both. No model calls were made: every CLAUDE* and ANTHROPIC* variable was stripped from the environment, the CLI got a dummy key, and its API base URL pointed at a local mock of the Messages API. The mock asks for Bash twice, and the can_use_tool callback allows every request and returns addRules [{toolName: "Bash"}] for the session each time.

With ruleContent sent as null (the current to_dict), the callback is asked twice. With the key omitted, it's asked once. The CLI debug log shows why. With null it logs this once per prompt:

[WARN] Malformed updatedPermissions from SDK host ignored: Invalid input: expected string, received null

With the key omitted it logs nothing. In 2.1.257 the rule schema is an optional string, so a missing key passes and null doesn't. It's also bigger than whole-tool rules: one rule with null content makes the CLI drop the whole updatedPermissions list, so a valid exact-command rule for the second call, returned alongside it, is lost too and the callback is still asked twice, with 2 warnings. The tool call itself goes through, so the only error signal is that debug line (2.1.282 logs it without the text after "Invalid input").

The fix is in PermissionUpdate.to_dict: leave ruleContent out when rule_content is None. Note that test_from_dict_to_dict_roundtrip_add_rules currently expects "ruleContent": None on the wire, so it pins the broken form. With the fix and that test updated, the unit suite passes (1538 passed, 15 skipped), and the repro drops to one prompt with no warning, including the mixed case. I can open the PR if that helps. Tools used: Claude Code wrote the harness and the fix, and the results above come from runs on my machine.

ohad6k avatar Sep 25 '26 18:09 ohad6k