How the Claude Web Probe Captures Usage Data from claude.ai

The Claude Web Probe extracts a sessionKey from browser cookies, calls the Claude AI web API to fetch organization metadata and usage statistics, and parses the JSON response into structured rate-limit data.

The Claude Web Probe is a macOS-specific component of the CodexBar open-source project that communicates directly with the https://claude.ai/api endpoints to retrieve real-time usage information without requiring the Claude CLI. This article examines the implementation in ClaudeWebAPIFetcher.swift to explain how the probe authenticates, queries, and parses usage data from Anthropic's web interface.

How Session Key Extraction Works

The probe begins every operation by locating a valid Claude session key, which serves as the authentication credential for all subsequent API calls.

The extraction logic resides in ClaudeWebAPIFetcher.extractSessionKeyInfo, which iterates over the browsers defined by ProviderDefaults.metadata[.claude]?.browserCookieOrder. For each browser, it queries BrowserCookieClient for records matching the domain claude.ai. When a cookie named sessionKey with a value starting with the prefix sk-ant- is discovered, the probe constructs a SessionKeyInfo instance containing the key value and metadata.

The underlying findSessionKey helper (lines 30-38) performs the domain-specific cookie lookup and validation, ensuring only properly formatted session keys are accepted.

Fetching Organization Metadata

Once a session key is obtained, the probe must identify the user's active organization—the entity that owns the chat capability and usage quotas.

The fetchOrganizationInfo method (lines 44-57) constructs a GET request to the /api/organizations endpoint, injecting the session key into the Cookie header and setting Accept: application/json. The response is processed by parseOrganizationResponse (lines 71-89), which extracts the organization ID and optional name into an OrganizationInfo struct. This organization ID becomes a required path parameter for all usage queries.

Retrieving Claude Usage Statistics

With the organization ID and a valid session key, the probe retrieves detailed consumption metrics.

Querying the Usage Endpoint

The fetchUsageData method calls /organizations/{org_id}/usage, passing the session key in the cookie header. The JSON payload returned by Anthropic contains several critical fields:

  • five_hour – Session-based usage window data
  • seven_day – Weekly aggregate usage statistics
  • seven_day_sonnet and seven_day_opus – Model-specific Opus usage tracking

Parsing the Usage Response

The parseUsageResponse method (lines 106-126) normalizes this data into a WebUsageData structure. It handles edge cases by converting a missing five_hour object into a "0% placeholder" while preserving a hasLiveSessionWindow boolean flag. The parser also extracts percentage values, reset dates, and any extra-rate windows that indicate throttled or over-limit usage.

Optional Data Enrichment

After capturing core usage metrics, the probe can augment the dataset with additional account metadata.

Extra Usage Cost: The ClaudeWebExtraUsageCost.fetch method queries /organizations/{org_id}/overage_spend_limit to retrieve overage billing information.

Account Information: The fetchAccountInfo method calls /account to fetch profile details and plan tiers.

Both enrichment methods reuse the existing session key and update the internal renewalTracker, which monitors Set-Cookie headers for session key rotation events.

Request Serialization and Concurrency Control

To prevent race conditions when reading browser cookies—a shared system resource—the probe implements strict concurrency controls.

The fetchUsageSerialized method (lines 12-20) coordinates the entire fetch workflow through ClaudeWebBrowserFetchSerialization.run. This serialization gate (implemented in ClaudeWebBrowserFetchGate.swift, lines 35-72) guarantees that only one fetch operation executes at a time per process. The system also handles error states including FetchError.unauthorized (expired session) and FetchError.noSessionKeyFound (missing authentication).

Diagnostic Endpoint Probing

For troubleshooting and development, the probe provides a generic probeEndpoints method (lines 81-90) that accepts arbitrary URL paths or full URLs (e.g., /api/organizations, https://claude.ai/profile).

After extracting the session key, it performs GET requests against each endpoint and feeds responses to parseProbeBody (lines 332-360). The resulting ProbeResult objects contain HTTP status codes, content-types, top-level JSON keys, extracted email addresses, plan hints, and optional body previews for manual inspection.

Implementation Examples

The following Swift examples demonstrate how to interact with the Claude Web Probe API:

import CodexBarCore

// Simple usage fetch using system-wide browser detection
let usage = try await ClaudeWebAPIFetcher.fetchUsage(
    browserDetection: BrowserDetection(cacheTTL: 0)
)

// Manual cookie header for debugging or headless environments
let usage2 = try await ClaudeWebAPIFetcher.fetchUsage(
    cookieHeader: "sessionKey=sk-ant-12345; other=foo"
)

// Probing arbitrary endpoints for diagnostics
let probeResults = try await ClaudeWebAPIFetcher.probeEndpoints(
    [
        "/api/organizations",
        "/api/organizations/{orgId}/usage",
        "https://claude.ai/profile"
    ],
    browserDetection: BrowserDetection(cacheTTL: 0),
    includePreview: true
)

for result in probeResults {
    print("🔗 \(result.url) → \(result.statusCode ?? 0)")
    if let preview = result.bodyPreview {
        print("   preview: \(preview)")
    }
}

Summary

  • Authentication: The probe extracts sessionKey cookies (prefixed with sk-ant-) from macOS system browsers using extractSessionKeyInfo and BrowserCookieClient.
  • Organization Discovery: It queries /api/organizations via fetchOrganizationInfo to obtain the active organization ID required for usage lookups.
  • Usage Capture: The /organizations/{org_id}/usage endpoint provides session (five_hour), weekly (seven_day), and model-specific (seven_day_opus) consumption data parsed by parseUsageResponse.
  • Safety: ClaudeWebBrowserFetchSerialization serializes concurrent requests to prevent cookie-read race conditions.
  • Extensibility: Optional enrichment via overage endpoints and account metadata, plus arbitrary endpoint probing for diagnostics.

Frequently Asked Questions

How does the Claude Web Probe find my session key without manual input?

The probe automatically searches browser cookies using ProviderDefaults.metadata[.claude]?.browserCookieOrder to determine search priority, then queries each browser's cookie store via BrowserCookieClient for any sessionKey value starting with sk-ant- on the claude.ai domain. This process requires no manual configuration on macOS systems where the browsers are installed.

What happens if my session key expires during a fetch operation?

The probe implements a renewalTracker that monitors Set-Cookie headers in API responses. If the server rotates the session key or returns an unauthorized error, the fetcher can invalidate the cached header and trigger a re-authentication flow on the next request, though the current operation will fail with FetchError.unauthorized.

Can I use the Claude Web Probe on platforms other than macOS?

No. The ClaudeWebAPIFetcher and its browser cookie extraction mechanisms are specifically implemented for macOS. The probe relies on BrowserCookieClient to access the macOS keychain and browser-specific cookie stores, which are not available on Linux or Windows systems.

What rate limit information does the probe return?

According to the parseUsageResponse implementation, the probe returns percentage utilization for the current five-hour session window (five_hour), seven-day rolling window (seven_day), and Opus-specific tracking (seven_day_opus). It also captures reset dates and hasLiveSessionWindow flags to indicate active throttling periods.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →