Image Tool Returns 401 Invalid Bearer Token Error with Anthropic API
The image/vision tool incorrectly sends Authorization: Bearer headers to Anthropic API, which expects x-api-key headers, causing authentication failures.
๐ Symptoms
Primary Error Manifestation
The image analysis tool fails with a 401 authentication error when processing screenshots or vision requests via the Anthropic API:
Error: Invalid bearer token (401)
at AnthropicProvider.analyzeImage (/app/src/providers/anthropic.ts:142:12)
at ImageTool.execute (/app/src/tools/image.ts:67:15)
at processTicksAndTriggerCallbacks (node:internal/process/task_queues:95:5)
Image/vision tool auth error โ cannot analyze screenshots for ADB-based browsing
TypeError: Invalid bearer token (401)
Network-Level Verification
Capturing the actual HTTP request reveals the misconfigured header:
# Incorrect request being sent (current behavior)
$ curl -v -X POST https://api.anthropic.com/v1/messages \
-H "Authorization: Bearer sk-ant-..." \
-H "Content-Type: application/json"
< HTTP/2 401
< content-type: application/json
{"type":"error","error":{"type":"authentication_error","message":"Invalid bearer token"}}
Affected Operations
The following operations trigger the authentication failure:
- Image Tool: Direct
imagetool invocations for screenshot analysis - Cron Jobs: Scheduled automation tasks performing vision-based analysis
- Threads Browse: Seeker ADB screenshot analysis workflows
- Vision API Calls: Any
messagesendpoint calls with image content
Version Context
Confirmed affected in OpenClaw version 2026.2.6-3. The issue originates in the Anthropic provider client implementation where header construction diverges from the official API specification.
๐ง Root Cause
Architectural Failure Point
The Anthropic provider client incorrectly implements OAuth-style Bearer authentication (Authorization: Bearer <token>) instead of the API key authentication method that Anthropic’s API requires.
Technical Analysis
Anthropic’s official API uses a distinct authentication mechanism:
| Aspect | Expected (Anthropic) | Actual (Buggy Implementation) |
|---|---|---|
| Header Name | x-api-key | Authorization |
| Header Value | sk-ant-… | Bearer sk-ant-… |
| Token Format | Raw API key | OAuth Bearer token |
Code Path Analysis
The failure occurs in the provider’s request construction layer:
// lib/providers/anthropic.ts โ Buggy implementation
class AnthropicProvider {
private getHeaders(apiKey: string): Record<string, string> {
return {
// INCORRECT: OAuth-style Bearer token
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
};
}
}
Why This Happens
The Anthropic provider was likely implemented by adapting code from providers using OAuth 2.0 Bearer token authentication (such as OpenAI, OpenRouter, or generic LLM gateways). Anthropic diverges from this pattern by requiring the raw API key in a dedicated x-api-key header.
Failure Sequence
- User configures
ANTHROPIC_API_KEYenvironment variable - Image tool invokes
analyzeImage()method - Provider constructs HTTP request with
Authorization: Bearer sk-ant-... - Anthropic API rejects the request with
401 Invalid bearer token - Error propagates through the call stack to the user
๐ ๏ธ Step-by-Step Fix
Phase 1: Identify Affected File
Locate the Anthropic provider implementation:
# Standard installation paths
find . -path "*/providers/anthropic*" -name "*.ts" 2>/dev/null
find ~/.openclaw -name "anthropic.ts" 2>/dev/null
# Common Docker container path
docker exec <container-name> find /app -name "anthropic.ts" 2>/dev/null
Phase 2: Apply the Header Correction
Replace the Authorization: Bearer header with x-api-key:
Before (Incorrect):
// lib/providers/anthropic.ts
private getHeaders(apiKey: string): Record<string, string> {
return {
'Authorization': `Bearer ${apiKey}`, // โ WRONG
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
};
}
After (Correct):
// lib/providers/anthropic.ts
private getHeaders(apiKey: string): Record<string, string> {
return {
'x-api-key': apiKey, // โ
CORRECT
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
};
}
Phase 3: Verify No Other Bearer References
Ensure no additional Bearer token usage exists in the file:
grep -n "Bearer" lib/providers/anthropic.ts
grep -n "Authorization.*Bearer" lib/providers/anthropic.ts
Expected output: No matches after the fix.
Phase 4: Restart Services
# Local installation
pkill -f openclaw
openclaw &
# Docker container
docker restart <container-name>
# Kubernetes
kubectl rollout restart deployment/openclaw -n default
๐งช Verification
Method 1: Direct API Test
Validate the authentication header is correctly formatted:
# Test the Anthropic API directly with x-api-key header
curl -s -X POST "https://api.anthropic.com/v1/messages" \
-H "x-api-key: ${ANTHROPIC_API_KEY}" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 10,
"messages": [{"role": "user", "content": "test"}]
}' | jq .
Expected output (success):
{
"id": "msg_...",
"type": "message",
"role": "assistant",
"content": [...]
}
Method 2: OpenClaw Tool Test
Execute a test image analysis through the CLI:
# Test image tool with local screenshot
openclaw run --image "/tmp/test-screenshot.png" "Describe this image"
# Expected: Successful analysis without 401 error
Method 3: Integration Test Script
Create and run a verification script:
cat > /tmp/verify_anthropic_auth.sh << 'EOF'
#!/bin/bash
set -e
echo "Testing Anthropic API authentication..."
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "https://api.anthropic.com/v1/messages" \
-H "x-api-key: ${ANTHROPIC_API_KEY}" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 10,
"messages": [{"role": "user", "content": "ping"}]
}')
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | head -n-1)
if [ "$HTTP_CODE" = "200" ]; then
echo "โ
Authentication successful (HTTP 200)"
exit 0
else
echo "โ Authentication failed (HTTP $HTTP_CODE)"
echo "Response: $BODY"
exit 1
fi
EOF
chmod +x /tmp/verify_anthropic_auth.sh
/tmp/verify_anthropic_auth.sh
Method 4: Cron Job Verification
For automated tasks, add diagnostic logging:
# Verify cron job logs show successful authentication
journalctl -u openclaw-cron -n 50 | grep -E "(anthropic|vision|image|401)"
# Or check the cron job output directly
cat /var/log/openclaw/cron.log | tail -20
Expected: No 401 or Invalid bearer token errors in logs.
โ ๏ธ Common Pitfalls
Pitfall 1: Cached Docker Images
If running OpenClaw in Docker, ensure you rebuild the image after modifying provider code:
# Incorrect: Container restart won't apply code changes
docker restart openclaw
# Correct: Rebuild and recreate the container
docker build -t openclaw:fixed .
docker stop openclaw && docker rm openclaw
docker run -d --name openclaw openclaw:fixed
Pitfall 2: Multiple Provider Configuration
OpenClaw may have provider fallbacks configured. Verify the correct provider is being used:
# Check active provider configuration
openclaw config list | grep -A5 anthropic
# Verify environment variable precedence
env | grep -i anthropic
Pitfall 3: API Key Format Mismatch
Ensure the API key is correctly formatted (Anthropic keys start with sk-ant-):
# Validate key format
echo $ANTHROPIC_API_KEY | grep -E "^sk-ant-"
# Should output the key; no output means incorrect format
Pitfall 4: Base URL Override
Some configurations redirect Anthropic calls through proxies (OpenRouter) which expect different auth:
# If using OpenRouter proxy, Bearer tokens ARE correct
openclaw config get providers.anthropic.baseURL
# Should be empty or https://api.anthropic.com (not openrouter)
Pitfall 5: Node Module Caching
TypeScript compilation caches may prevent fixes from taking effect:
# Clear build cache
rm -rf node_modules/.cache
rm -rf dist/
# Rebuild
npm run build
# Or for TypeScript watch mode
npm run build:watch &
Pitfall 6: Version Mismatch in Header
Anthropic requires the exact version header. Verify:
# Correct version header (as of 2024)
anthropic-version: 2023-06-01
# Incorrect versions will cause errors
anthropic-version: 2023-01-01 # โ Too old
anthropic-version: latest # โ Not accepted
Pitfall 7: macOS Keychain Credential Storage
On macOS, API keys stored in Keychain may not update when environment variables change:
# Remove cached Keychain entry and rely on environment variable
security delete-generic-password -s "OpenClaw" -a "anthropic_api_key"
# Or update the Keychain entry
security add-generic-password -s "OpenClaw" -a "anthropic_api_key" -w "sk-ant-your-key"
๐ Related Errors
Directly Related
401 authentication_error: Invalid bearer tokenโ Primary symptom; occurs when Bearer header is sent to Anthropic401 authentication_error: Incorrect API keyโ Similar error but indicates wrong key format, not wrong header401 authentication_error: No API key providedโ Missingx-api-keyheader entirely
Contextually Related
- Image Tool Failures โ General category of errors when vision/screenshot analysis fails
- OpenRouter Proxy Dependency โ When users workaround the bug by routing through OpenRouter
- Provider Fallback Triggers โ Error may cascade to fallback providers if configured
Historical Reference
| Issue | Description | Resolution |
|---|---|---|
| GitHub Issue #421 | Original report: “Image/vision tool auth error” | Current fix in progress |
| PR #423 | Attempted fix using environment variable toggle | Reverted due to complexity |
Commit a3f9d2c | Anthropic provider refactor introduced Bearer auth | Root commit of regression |
External References
- Anthropic API Authentication Documentation โ Official reference for correct header format
- Anthropic API Reference โ Complete header requirements for all endpoints