Back to Home

Proxy Claude API for OpenClaw: code and tool use

Proxy server restores access to Claude in openclaw after Anthropic block. Browser emulation with curl_cffi, tool use support via XML prompts and auto-fix JSON. Full code, config and integration for developers.

Restore Claude in OpenClaw: proxy with tool use
Advertisement 728x90

Claude API Proxy via Web Session: OpenClaw Integration with Tool Use

Anthropic has blocked Claude use in third-party apps like OpenClaw. Pro subscribers ($100/month) got $100 in extra usage credits, but that doesn't fix agent integration. The fix? A proxy server that mimics a Claude.ai browser session with an OpenAI-compatible API. It lets you run Claude Sonnet/Opus in OpenClaw with full tool use support.

Built in Python using curl_cffi for Chrome TLS fingerprinting. Cookies and device ID come from your active session. Each request spins up a fresh conversation, streaming completions via SSE.

Basic Session and Header Setup

The session impersonates Chrome with real browser cookies. Tested with anti-detection browser Camoufox.

Google AdInline article slot
def make_session() -> cf_requests.Session:
    """Create a new curl_cffi session with Chrome TLS fingerprint."""
    cookies = get_cookies()
    session = cf_requests.Session(impersonate=IMPERSONATE)
    session.cookies.update(cookies)
    return session

def get_headers(cookies: dict) -> dict:
    return {
        "User-Agent": (
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
            "(KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
        ),
        "Origin": "https://claude.ai",
        "Referer": "https://claude.ai/new",
        "anthropic-device-id": cookies.get("anthropic-device-id", ""),
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
    }

Completion Request Logic

  • POST to /api/organizations/{org_id}/chat_conversations to create a conversation.
  • POST to /chat_conversations/{conv_id}/completion with text/event-stream.
def claude_complete(
    prompt: str,
    internal_model: str,
) -> Generator[str, None, None]:
    """Sync generator that yields SSE lines from claude.ai completion."""
    cookies = get_cookies()
    org_id = cookies["lastActiveOrg"]
    headers = get_headers(cookies)

    session = make_session()

    # 1. Create conversation
    r = session.post(
        f"https://claude.ai/api/organizations/{org_id}/chat_conversations",
        json={"uuid": None, "name": ""},
        headers=headers,
        timeout=15,
    )
    r.raise_for_status()
    conv_id = r.json()["uuid"]
    log.info(f"Conv created: {conv_id} model={internal_model}")

    # 2. Stream completion
    payload = {
        "prompt": prompt,
        "model": internal_model,
        "timezone": "Europe/Moscow",
        "attachments": [],
        "files": [],
    }
    r2 = session.post(
        f"https://claude.ai/api/organizations/{org_id}/chat_conversations/{conv_id}/completion",
        json=payload,
        headers={**headers, "Accept": "text/event-stream"},
        stream=True,
        timeout=60,
    )
    r2.raise_for_status()
    for line in r2.iter_lines():
        yield line

The API server uses aiohttp with routes for /v1/models, /v1/chat/completions, /health. Runs on 127.0.0.1:8787.

def make_app() -> web.Application:
    app = web.Application()
    app.router.add_get("/v1/models", handle_models)
    app.router.add_get("/health", handle_health)
    app.router.add_post("/v1/chat/completions", handle_chat_completions)
    return app

OpenClaw Integration

Provider config:

"claude-web": {
    "baseUrl": "http://127.0.0.1:8787/v1",
    "apiKey": "dummy",
    "api": "openai-completions",
    "models": [
      {
        "id": "claude-sonnet-4-6-web",
        "name": "Claude Sonnet 4.6 (Web)",
        "reasoning": false,
        "input": ["text"],
        "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
        "contextWindow": 200000,
        "maxTokens": 32000
      }
    ]
}

Text generation works out of the box. Tool use needs tweaks.

Google AdInline article slot

Tool Use Support: Prompt Injection

System prompt forces Claude to output tool calls in XML format:

TOOL_SYSTEM_PROMPT = """You have access to tools. When you need to call a tool, output ONLY the tool call block — no explanation, no text before or after it:

<tool_call>
{{
"name": "tool_name_here", "arguments": {{"param1": "value1", "param2": "value2"}}
}}
</tool_call>

RULES:
- The JSON inside <tool_call> must be valid — no trailing commas, no comments
- You may output multiple <tool_call> blocks in sequence
- After receiving <tool_result> blocks, continue your response normally
- If you are not calling a tool, respond normally without any <tool_call> tags

Available tools:
{tools_json}"""

Parsing uses regex with auto-fixes for JSON errors (trailing commas, comments).

Final Tool Calls and Results Handling

  • Parser extracts <tool_call> blocks, fixes JSON, converts to OpenAI format.
  • Tool results injected as XML <tool_result id="...">content</tool_result> into user messages.
def parse_tool_calls(text: str) -> tuple[list[dict], str]:
    tool_calls = []
    for match in TOOL_CALL_RE.finditer(text):
        raw_json = match.group(1).strip()
        obj = None
        try:
            obj = json.loads(raw_json)
        except json.JSONDecodeError:
            fixed = _try_fix_json(raw_json)
            obj = json.loads(fixed)
        if obj:
            tool_calls.append({
                "id": f"call_{uuid.uuid4().hex[:12]}",
                "type": "function",
                "function": {
                    "name": obj.get("name", ""),
                    "arguments": json.dumps(obj.get("arguments", {})),
                },
            })
    remaining = TOOL_CALL_RE.sub("", text).strip()
    return tool_calls, remaining

def inject_tool_results(messages: list[dict], tools: list[dict]) -> list[dict]:
    # Convert OpenAI tool_calls/results to XML for Claude
    # ... (batching and XML generation logic)

Key Features

  • Full Compatibility: OpenAI API with tool use for OpenClaw/Claude Sonnet 4.6 (200k context).
  • Stealth Mode: curl_cffi + real cookies/device ID, Chrome TLS.
  • Auto-Fix: Handles Claude's common JSON glitches (trailing commas, comments).
  • Streaming: SSE from web API, fresh conversation per request.
  • Limits: Stays within Pro subscription, no extra usage.

Limitations and Improvements

Relies on Claude.ai web API stability. Potential issues:

Google AdInline article slot
  • Captchas on the site.
  • Session timeouts.
  • Endpoint changes.

Workarounds: Cookie refresh via automation, device ID rotation, error handling.

— Editorial Team

Advertisement 728x90

Read Next