Skip to content

feat: add get_context_usage() method to ClaudeSDKClient#764

Merged
qing-ant merged 1 commit intomainfrom
feat/get-context-usage
Mar 28, 2026
Merged

feat: add get_context_usage() method to ClaudeSDKClient#764
qing-ant merged 1 commit intomainfrom
feat/get-context-usage

Conversation

@qing-ant
Copy link
Copy Markdown
Contributor

Summary

Adds ClaudeSDKClient.get_context_usage() which returns a breakdown of the current context window usage by category, matching the data shown by the /context command in the CLI.

The CLI already supports the get_context_usage control request and the TypeScript SDK exposes it as getContextUsage() on the Query interface (shipped in v0.2.86). This brings the Python SDK to parity.

Fixes #507

Usage

async with ClaudeSDKClient() as client:
    await client.query("Analyze this codebase")
    async for _ in client.receive_response():
        pass

    usage = await client.get_context_usage()
    print(f"Using {usage['percentage']:.1f}% of context")
    for cat in usage['categories']:
        print(f"  {cat['name']}: {cat['tokens']} tokens")

Changes

  • types.py: Add ContextUsageCategory and ContextUsageResponse TypedDicts
  • _internal/query.py: Add get_context_usage() that sends {"subtype": "get_context_usage"} control request
  • client.py: Add public get_context_usage() wrapper following the existing get_mcp_status() pattern
  • __init__.py: Export the new types
  • test_streaming_client.py: Add 2 tests (shape verification + not-connected error)

Response shape

ContextUsageResponse includes:

  • categories — per-category token breakdown (system prompt, tools, messages, etc.)
  • totalTokens / maxTokens / rawMaxTokens / percentage — overall usage
  • model — which model the usage is calculated for
  • mcpTools / memoryFiles / agents — detailed per-item breakdowns
  • messageBreakdown / skills / slashCommands / systemTools — optional detailed sections
  • isAutoCompactEnabled / autoCompactThreshold — autocompact state

Nested detail fields use list[dict[str, Any]] rather than fully-typed nested TypedDicts to stay forward-compatible as the CLI adds fields.

Verification

  • 411 tests pass (409 existing + 2 new)
  • ruff check + mypy src/ clean
  • Verified end-to-end with a live SDK instance: get_context_usage() returned 6 categories with correct token counts, model name, and percentage after a simple query

Adds ClaudeSDKClient.get_context_usage() which returns a breakdown of
the current context window usage by category, matching the data shown
by the /context command in the CLI.

The CLI already supports the get_context_usage control request and the
TypeScript SDK exposes it as getContextUsage() on the Query interface.
This brings the Python SDK to parity.

Returns a ContextUsageResponse TypedDict with:
- categories: per-category token breakdown (system prompt, tools, messages)
- totalTokens / maxTokens / percentage: overall usage
- mcpTools / memoryFiles / agents: detailed per-item breakdowns
- messageBreakdown / skills / slashCommands: optional detailed sections

Fixes #507
Copy link
Copy Markdown
Contributor

@claude claude bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, straightforward addition following the established get_mcp_status() pattern.

Extended reasoning...

Overview

This PR adds a get_context_usage() method to ClaudeSDKClient across 5 files: new TypedDicts in types.py, a 3-line delegate in query.py, a public wrapper in client.py, exports in __init__.py, and 2 tests in test_streaming_client.py. Every layer follows the exact same pattern as the existing get_mcp_status() method.

Security risks

None. The method sends a read-only control request (get_context_usage) to the CLI subprocess and returns the response. No user input is interpolated, no new permissions are granted, and no external systems are contacted.

Level of scrutiny

Low scrutiny appropriate. This is a mechanical, pattern-following addition with no novel logic. The TypedDict fields use dict[str, Any] for nested detail fields (forward-compatible), and the required fields match the CLI wire format. The tests mirror the existing test_get_mcp_status test structure exactly.

Other factors

  • No CODEOWNERS file blocking approval.
  • No outstanding reviewer comments.
  • No prior reviews from me on this PR.
  • The 2 new tests cover the happy path (shape verification) and the error path (not-connected). Test structure is copy-paste from the MCP status tests with appropriate substitutions.

@qing-ant qing-ant enabled auto-merge (squash) March 28, 2026 19:59
@qing-ant qing-ant merged commit ac900bd into main Mar 28, 2026
10 checks passed
@qing-ant qing-ant deleted the feat/get-context-usage branch March 28, 2026 20:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] Add /context command support to SDK for programmatic context inspection

2 participants