Skip to content

fix: sanitize tool_use.id on session resume to prevent 400 error#876

Open
UmmeHabiba1312 wants to merge 2 commits intoanthropics:mainfrom
UmmeHabiba1312:fix/invalid-tool-use-id-on-resume
Open

fix: sanitize tool_use.id on session resume to prevent 400 error#876
UmmeHabiba1312 wants to merge 2 commits intoanthropics:mainfrom
UmmeHabiba1312:fix/invalid-tool-use-id-on-resume

Conversation

@UmmeHabiba1312
Copy link
Copy Markdown

Description

This PR fixes the "Invalid tool_use.id format" 400 Bad Request error that occurs when resuming a session using --resume or continue_conversation.

Root Cause

When resuming a previous session, the SDK loads the full conversation history, which may contain tool_use.id values that do not follow the strict format required by the Claude API / CLI (toolu_[a-zA-Z0-9_-]+).
These malformed IDs (e.g., plain UUIDs, numeric strings, or IDs with invalid characters) cause the backend to reject the request with a 400 error.

Solution

  • Added a new utility function sanitize_tool_use_ids() in src/claude_agent_sdk/_utils.py.
  • This function ensures every tool_use.id and corresponding tool_result.tool_use_id follows the correct format by:
    • Adding the required toolu_ prefix if missing.
    • Replacing any invalid characters with underscores.
  • Applied the sanitization in two places for maximum coverage:
    • In SubprocessCLITransport.connect() for initial resumed history.
    • In SubprocessCLITransport.write() for any subsequent streamed messages containing tool blocks.

This change is non-destructive, safe, and only modifies IDs when they are invalid.

Testing

  • Verified that sessions with previously invalid tool_use.id values now resume successfully without 400 errors.
  • Existing functionality (new sessions, normal tool use) remains unaffected.

Checklist

  • Added sanitize_tool_use_ids() helper
  • Updated subprocess_cli.py to apply sanitization on resume paths
  • Updated CHANGELOG.md under Unreleased section
  • Code passes linting and import tests

Related Issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Invalid tool_use.id format during session resume causes API 400 error

1 participant