Skip to main content
Glama
beeltec

context-usage-mcp

by beeltec

context-usage-mcp

A tiny Model Context Protocol server (TypeScript/Node, stdio) that exposes a single tool, get_context_usage, reporting the current session's raw token usage — so an agent can check after each task whether context has grown large and branch its behavior on an absolute threshold. Runs under both Claude Code and OpenAI Codex CLI, reading each host's own session transcript/rollout behind an auto-detected host-adapter layer.

What it does

Neither host hands an stdio MCP server the live token counts, so this server reads usage indirectly from the host's own on-disk session file, behind an auto-detected host-adapter layer. The output shape is identical across hosts.

Claude Code passes only CLAUDE_PROJECT_DIR (no session id, transcript path, or counts):

  1. Derive the project folder from CLAUDE_PROJECT_DIR (non-alphanumerics → -).

  2. Pick the most-recently-modified *.jsonl in ~/.claude/projects/<folder>/ as the current session (its transcript is being written while the tool is called).

  3. Scan backward for the last assistant message carrying a usage block.

  4. Sum input_tokens + cache_creation_input_tokens + cache_read_input_tokenscontext_tokens.

The ~/.claude root can be relocated with CLAUDE_CONFIG_DIR.

OpenAI Codex CLI passes no project/session env var at all, but launches the server with its working directory set to the session's project dir. So the server uses process.cwd():

  1. Resolve the Codex root (CODEX_HOME, else ~/.codex); rollouts live under <root>/sessions/YYYY/MM/DD/rollout-*.jsonl.

  2. Scan recent day-folders (today + yesterday, widening to ~7 days), reading only each candidate's first session_meta line to match its cwd against process.cwd(); pick the freshest match.

  3. Scan backward for the last token_count event and read its per-turn last_token_usage.

  4. Map to the shared, disjoint breakdown. Codex's cached_input_tokens is a subset of input_tokens (verified in source), so inputinput − cached; then context_tokens = input + cache_read + cache_creation — no double-count.

Output is output_tokens + reasoning_output_tokens. The Codex model_context_window is ignored (raw counts only, strict parity with the Claude host).

Related MCP server: Claude Telemetry MCP

Install & run

Run the published package directly with npx — no clone or build required:

npx -y @beeltec/context-usage-mcp

This is the recommended way to wire it into a host (see the registration sections below). The -y flag skips the install prompt on first run.

Run from source (local dev) — for hacking on the server itself:

npm install
npm run build          # tsc → dist/, sets +x on dist/index.js
npm test               # parser unit tests

Then register the absolute path to dist/index.js (see the "from source" note in each registration section).

Host detection

The server auto-detects its host: CLAUDE_PROJECT_DIR set → Claude Code; else CODEX_HOME set or ~/.codex/sessions present → Codex; else it falls back to Claude. Set the environment variable CONTEXT_USAGE_HOST=claude|codex to force a host (the override wins over auto-detection).

Register with Claude Code (user scope)

claude mcp add --scope user context-usage -- npx -y @beeltec/context-usage-mcp

Verify with claude mcp list. Because MCP servers are loaded at session start, start a new Claude Code session before calling the tool.

From source: register the absolute path to this repo's built binary instead:

claude mcp add --scope user context-usage -- node /absolute/path/to/dist/index.js

Register with Codex CLI

Add an entry to ~/.codex/config.toml (root movable with CODEX_HOME):

[mcp_servers.context-usage]
command = "npx"
args = ["-y", "@beeltec/context-usage-mcp"]

Or use the CLI equivalent:

codex mcp add context-usage -- npx -y @beeltec/context-usage-mcp

Do not set a custom cwd for the server: Codex passes no project/session identifier, so discovery relies on the server inheriting the session's working directory via process.cwd(). Setting cwd breaks the cwd-match. MCP servers load at session start, so start a new Codex session before calling the tool.

From source: use command = "node" with args = ["/absolute/path/to/dist/index.js"] (or codex mcp add context-usage -- node /absolute/path/to/dist/index.js).

Distribution

Published to npm as @beeltec/context-usage-mcp and run via npx (see Install & run). Releases are published from CI with provenance on each GitHub Release; running from a local build is also supported for development.

The tool: get_context_usage

No arguments. Returns raw counts only — no percentage, no context-window detection. It may be unavailable early in a session before the first model response. Both a JSON text block and typed structuredContent (declared outputSchema) are returned with the same object. The shape is identical under Claude Code and Codex.

Available:

{
  "available": true,
  "context_tokens": 86026,
  "breakdown": {
    "input_tokens": 2,
    "cache_creation_input_tokens": 1001,
    "cache_read_input_tokens": 85023,
    "output_tokens": 225
  },
  "session_id": "…",
  "model": "claude-opus-4-8",
  "timestamp": "2026-07-20T14:17:50.751Z",
  "reason": null
}

Unavailable (never throws): numeric fields are null and reason explains why (no transcript/rollout found, empty file, or no usage-bearing message/token_count event yet).

Field

Meaning

available

Whether a reading was obtained

context_tokens

input + cache_creation + cache_read (the context fed back to the model)

breakdown

Raw per-category counts, including output_tokens

session_id / model / timestamp

Metadata from the source message/event

reason

Why the reading is unavailable (null when available)

Intended usage

The server returns raw numbers only; the agent decides what "too long" means. The pattern: call get_context_usage after each task and branch on an absolute token threshold defined in the agent's prompt/CLAUDE.md (e.g. wrap up or hand off when context_tokens exceeds a limit).

Known risks

  • Internal file format. Both the Claude transcript JSONL and the Codex rollout JSONL are undocumented internal formats that may change between host versions; parsing them directly is an accepted fragility.

  • Concurrent-session race. The freshest-file heuristic (freshest *.jsonl for Claude; freshest cwd-matching rollout-*.jsonl for Codex) is racy if multiple sessions run in the same project at once — it may pick another session's file.

Available Tools

1 tool
get_context_usageGet context usageA

Reports the current session's raw token usage, read directly from the host's own session transcript/rollout (auto-detected: Claude Code or OpenAI Codex CLI). Returns raw counts only — context_tokens (input + cache_creation + cache_read) plus a full breakdown and session metadata (session_id, model, timestamp) — with no percentage or context-window detection. May be unavailable early in a session before the first model response; then it returns { available: false, reason } instead of failing.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
modelYes
reasonYes
availableYes
breakdownYes
timestampYes
session_idYes
context_tokensYes

TDQS

A4.7/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries full burden and delivers richly. It discloses the source (host's session transcript/rollout), exactly what is returned (raw counts with breakdown and metadata), what is not included (percentages, context-window detection), and the fallback behavior when unavailable ({ available: false, reason }). This is a model of behavioral transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose, then adds essential details about what is returned, what is excluded, and edge-case behavior. It is concise given the information density—every sentence contributes meaning without redundancy or fluff.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with no parameters, no annotations, and no siblings, the description fully covers the tool's behavior: return contents, source, limitations, and failure mode. An output schema exists for structured return data, so the description doesn't need to enumerate every field—it complements the schema well. The description is complete for effective selection and invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters, so the schema is empty and schema coverage is 100%. The rubric assigns a baseline of 4 for zero-parameter tools. The description doesn't need to explain parameters, and it adds value by detailing return semantics instead, which is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Reports the current session's raw token usage'. It specifies the resource (current session's token usage) and the action (reports), which is specific and non-tautological. No sibling tools are present, so differentiation isn't applicable, but the description still achieves full clarity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives clear context on when the tool is useful (e.g., for raw token counts) and its limitations (no percentage/context-window detection; may be unavailable early in a session). However, it stops short of explicitly naming alternatives or saying 'use for X, not for Y', so it lacks explicit exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 1 tool updatev0.1.1
    • First observedget_context_usage

TDQS

A4.5/5.0
Disambiguation5/5

With only one tool, there is no possibility of ambiguity or misselection. The tool's purpose is clearly defined and distinct by default.

Naming Consistency5/5

The single tool name 'get_context_usage' follows a clear verb_noun pattern. Consistency is trivially maintained as there are no other tools to contrast with.

Tool Count3/5

The server has only one tool, which feels thin for a typical server but is arguably sufficient for its narrow purpose. It is not trivial, but the count is on the lower end of the acceptable range.

Completeness3/5

The tool covers the core raw token usage reporting, but it explicitly lacks percentage or context-window detection, leaving a notable gap for users who need derived insights. The domain is narrowly focused, but the surface is somewhat incomplete.

Maintenance

ActivityNo data
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    B
    quality
    Not graded
    maintenance
    Provides comprehensive telemetry and usage analytics for Claude Code sessions, including token usage tracking, cost monitoring, and tool usage patterns. Enables users to monitor their Claude usage with detailed metrics, warnings, and trend analysis.
    12
    -
  • F
    license
    Not graded
    quality
    Not graded
    maintenance
    Provides intelligent analysis of token usage patterns and optimization recommendations to improve efficiency and reduce costs in Claude Code sessions. Offers real-time analysis, cost metrics, and actionable insights for better context window and tool usage optimization.
    3
    -
  • A
    license
    A
    quality
    D
    maintenance
    Provides Claude Code with programmatic session awareness to track context usage, session history, and task progress. It enables intelligent context reset recommendations and automatic synchronization of project planning documentation.
    5
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/beeltec/context-usage-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server