An intelligent Claude API proxy built on Cloudflare Workers that automatically fixes orphaned tool_result errors.
- Auto Error Fix: Automatically detects and removes orphaned
tool_resultblocks that cause 400 errors - Proactive Cleanup: Cleans messages before API calls to prevent errors
- Smart Retry: Falls back to reactive cleanup if proactive detection misses edge cases
- Transparent Proxy: Preserves all headers and client information
- Edge Computing: Runs on Cloudflare Workers for low latency worldwide
When using Claude with tools, the message history can become corrupted with orphaned tool_result blocks - results that reference tool_use calls that no longer exist in the conversation. This causes Claude API to return 400 errors:
tool_result block(s) that reference non-existent tool_use ids
BetterClaude automatically detects and removes these orphaned blocks, allowing the conversation to continue.
- Proactive Detection: Before making the API call, scans messages for orphaned
tool_resultblocks and removes them - API Call: Forwards the cleaned request to the target Claude API
- Reactive Fallback: If a 400 error still occurs, parses the error to identify remaining orphans and retries once
Prefix your Claude API endpoint with the gateway URL:
https://<YOUR_DOMAIN>/claude/<TARGET_HOST>/v1/messages
Direct Anthropic API:
https://api.anthropic.com/v1/messages
→ https://<YOUR_DOMAIN>/claude/api.anthropic.com/v1/messages
Third-party Claude API providers:
https://some-provider.com/v1/messages
→ https://<YOUR_DOMAIN>/claude/some-provider.com/v1/messages
-
Clone and install dependencies:
cd better_claude npm install -
Configure
wrangler.jsonc:- Set your worker name
- Add your domain routes
-
Deploy:
npm run deploy
npm run dev # Start local dev server at http://localhost:8787/better_claude/
├── src/
│ ├── index.ts # Main worker entry point
│ ├── router.ts # URL routing logic
│ ├── proxy.ts # Request proxying with retry
│ ├── retry-handler.ts # Retry logic with cleanup
│ ├── proactive-cleanup.ts # Orphan detection algorithm
│ ├── error-detector.ts # Error parsing utilities
│ ├── streaming-handler.ts # SSE stream handling
│ └── env.d.ts # Environment type definitions
├── wrangler.jsonc # Cloudflare Worker configuration
├── tsconfig.json # TypeScript configuration
└── package.json # Dependencies
| Endpoint | Description |
|---|---|
/ |
Info endpoint |
/health |
Health check |
/claude/{host}/{path} |
Proxy to Claude API |
The orphan detection algorithm:
- Build tool_use index: Scans all messages to find all
tool_useblocks and their IDs - Find orphans: Identifies
tool_resultblocks that reference non-existenttool_useIDs - Remove orphans: Filters out orphaned
tool_resultblocks from messages - Clean empty messages: Removes user messages that become empty after cleanup
MIT

{ "name": "your-worker-name", "main": "src/index.ts", "compatibility_date": "2025-12-13", "routes": [ { "pattern": "<YOUR_DOMAIN>/*", "zone_name": "<YOUR_ZONE>" } ] }