Skip to content

Troubleshooting

Fresh

Solutions to common errors and issues.

API Errors

Authentication Errors

ERROR: 401 Unauthorized / Invalid API Key

CausesSolutions
API key not set or incorrect1. Verify key is set: echo $ANTHROPIC_API_KEY
Key revoked or expired2. Check key format: Should start with sk-ant-api03-
Wrong environment variable3. Regenerate key at console.anthropic.com

Rate Limits

ERROR: 429 Too Many Requests

Causes:

  • Exceeded requests per minute
  • Exceeded tokens per minute

Solutions:

  1. Implement exponential backoff:
python
import time
for attempt in range(5):
    try:
        return client.messages.create(...)
    except anthropic.RateLimitError:
        time.sleep(2 ** attempt)
  1. Use batch processing with delays
  2. Request rate limit increase

Context Length Exceeded

ERROR: Context length exceeded / Too many tokens

Causes:

  • Message history too long
  • Single message exceeds limit

Solutions:

  1. Truncate message history:
python
messages = messages[-10:]  # Keep last 10
  1. Summarize older messages:
python
summary = summarize(old_messages)
messages = [{"role": "user", "content": summary}] + recent
  1. Chunk large documents

Tool Use Issues

Tool Not Called

ISSUE: Claude doesn't use the tool

Causes:

  • Unclear tool description
  • Prompt doesn't suggest tool use
  • Tool not appropriate for request

Solutions:

  1. Improve tool description: "Use this tool when user asks about weather conditions"

  2. Be explicit in prompt: "Use the get_weather tool to find..."

  3. Use tool_choice parameter:

python
tool_choice={"type": "tool", "name": "get_weather"}

Tool Result Not Processed

ISSUE: Claude ignores tool result

Causes:

  • tool_use_id mismatch
  • Incorrect message structure
  • Result not in expected format

Solutions:

  1. Ensure correct ID:
python
tool_result = {
    "type": "tool_result",
    "tool_use_id": tool_use_block.id,  # Must match!
    "content": json.dumps(result)
}
  1. Check message order:
    • User message
    • Assistant message (with tool_use)
    • User message (with tool_result)

MCP Issues

Server Won't Start

ISSUE: MCP server fails to start

Check these in order:

  1. Verify Python/Node path is correct
  2. Check for import errors: python -c "import mcp"
  3. Test server standalone: python server.py
  4. Check Claude Desktop logs:
    • macOS: ~/Library/Logs/Claude/
    • Windows: %APPDATA%\Claude\logs\
  5. Validate JSON config syntax

Connection Timeout

ISSUE: MCP connection times out

TransportChecks
STDIOServer must not print to stdout (use stderr for logs), Check for blocking operations in startup
HTTPVerify port is not blocked by firewall, Check CORS headers if cross-origin, Ensure server is listening on correct interface

Debug:

  • Add logging to track connection lifecycle
  • Test with MCP Inspector tool

Claude Code Issues

Installation Failed

ISSUE: Claude Code won't install

Solutions:

  1. Check Node.js version (18+ required): node --version

  2. Try different install method:

bash
npm install -g @anthropic-ai/claude-code
# or
npx @anthropic-ai/claude-code
  1. Clear npm cache: npm cache clean --force

  2. Check permissions (Linux/macOS): sudo npm install -g @anthropic-ai/claude-code

Authentication Required

ISSUE: "Please authenticate" message

Solutions:

  1. Run authentication: claude auth login

  2. Or set API key directly: export ANTHROPIC_API_KEY="sk-ant-..."

  3. Check auth status: claude auth status

Common Patterns

Retry with Backoff

python
import time
import anthropic

def call_with_retry(func, max_retries=5):
    for attempt in range(max_retries):
        try:
            return func()
        except anthropic.RateLimitError:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)
        except anthropic.APIError as e:
            if e.status_code >= 500:
                time.sleep(2 ** attempt)
            else:
                raise

Error Logging

python
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

try:
    response = client.messages.create(...)
except anthropic.APIError as e:
    logger.error(f"API Error: {e.status_code} - {e.message}")
    raise

Based on Anthropic Academy courses