Skip to content

feat(server): add read-only MCP usage tools - #750

Open
tannerpolley wants to merge 2 commits into
mainfrom
cursor/mcp-usage-tools-ef8c
Open

tannerpolley wants to merge 2 commits into
mainfrom
cursor/mcp-usage-tools-ef8c

Conversation

@tannerpolley

Copy link
Copy Markdown
Owner

Problem

Outside agents connected to the official MCP server can read and steer threads, but they cannot see token, cost, or subscription-limit analytics. A read-only bot that is supposed to suggest better token use has nothing to read.

Change

Add three read-only tools on the environment MCP server:

  • t3_usage_summary — token, cache, and estimated cost totals by provider, model, and day.
  • t3_usage_threads — top projects and threads by recorded tokens, plus threads near automatic compaction.
  • t3_usage_limits — cached subscription windows, reset times, and banked reset-credit counts.

Access. All three use the MCP read gate (McpToolAccess.reads). A connection approved as Read only can call them. They do not write, probe providers, or redeem credits. Responses omit prompts, message text, filesystem paths, emails, credential fingerprints, and reset-credit ids. The tools are hidden from in-thread agents' tool lists, so they do not grow the coding-agent context budget. Docs: docs/user/outside-agents.md and docs/user/usage.md.

Performance. t3_usage_summary reads the existing usage cache (provisional, no awaitRefresh) and skips the Codex speed lookup that scans provider turns. A cache miss still scans session files, the same way opening Usage does, and does not query the orchestration database. The window is at most 31 days. t3_usage_threads does not scan turns by date: it takes the 200 newest active threads from the active-thread index (LIMIT 201 so truncation is visible), then reads those threads' turns through the thread_id index and the latest context reading through the usage index. Both queries run on the read-only connection. t3_usage_limits returns the in-memory provider and hub snapshots and does not start a probe.

The Nov 23 budget-report commit (135f3f591) is not reusable. It depended on fork-only turn fields and a completed_at index this tree does not have, and its query joined message rows.

Scope

Requested for this fork so an outside agent (Token Optimizer) can read usage. One change: the read-only usage tools, their tests, and the user docs.

Verification

vp lint on the touched server files, vp test run of usageReport.test.ts, UsageAnalytics.test.ts, and handlers.test.ts (9 tests), and effect-tsgo tsrs --noEmit in apps/server.

The handler test calls t3_usage_limits as a read-only outside client. The analytics test checks that a 32-day window is rejected before any scan, that a summary asks for provisional: true and skipServiceTierResolution: true, and that thread totals drop local-command turns, out-of-window turns, archived threads (unless threadId is set), and workspace paths.

Example: t3_usage_summary

{
  "timeZone": "UTC",
  "sinceDay": "2026-11-22",
  "untilDay": "2026-11-28",
  "refreshing": true,
  "totals": {
    "tokens": {
      "uncachedInputTokens": 110,
      "cachedInputTokens": 300,
      "cacheCreationTokens": 50,
      "outputTokens": 45,
      "reasoningTokens": 10,
      "totalTokens": 505
    },
    "cacheHitRate": 0.6522,
    "costUsd": 1.7,
    "cacheSavingsUsd": 0.4,
    "costPerMillionUsd": 3366.3366
  },
  "byProvider": [{ "provider": "claude" }, { "provider": "codex" }],
  "byModel": [{ "provider": "claude", "model": "opus", "cacheHitRate": 0.6667, "costPerMillionUsd": 3061.2245 }]
}

Reasoning tokens are included in output. Cache hit rate is cached input divided by uncached input, cache reads, and cache writes. Cost is an API-equivalent estimate, not the subscription bill. refreshing: true means the cache is behind the latest session files.

Example: t3_usage_threads

{
  "since": "2026-11-22T00:00:00.000Z",
  "until": "2026-11-29T00:00:00.000Z",
  "candidates": 2,
  "truncated": false,
  "projects": [{ "projectId": "project-a", "title": "Analytics", "threads": 2, "totalTokens": 1072, "cacheHitRate": 0.7921 }],
  "threads": [{
    "threadId": "thread-a",
    "title": "Compile the report",
    "projectTitle": "Analytics",
    "model": "gpt-test",
    "serviceTier": "priority",
    "inputTokens": 1000,
    "cachedInputTokens": 800,
    "outputTokens": 50,
    "otherTokens": 12,
    "totalTokens": 1062,
    "cacheHitRate": 0.8,
    "turns": 1
  }],
  "nearAutoCompaction": [{
    "threadId": "thread-a",
    "usedTokens": 180000,
    "maxTokens": 200000,
    "autoCompactThreshold": 190000,
    "fillRatio": 0.9474
  }]
}

inputTokens already includes cache reads and writes. otherTokens is native subagent and compaction usage. fillRatio is used tokens divided by the auto-compact threshold when the provider reports one, otherwise the context window. Threads at or above 0.8 are listed under nearAutoCompaction.

Example: t3_usage_limits

{
  "accounts": [{
    "sourceKind": "provider",
    "driver": "codex",
    "instanceId": "codex",
    "label": "Codex",
    "checkedAt": "2026-11-28T00:00:00.000Z",
    "windows": [
      { "id": "primary", "kind": "session", "label": "5-hour", "usedPercent": 42, "remainingPercent": 58, "resetsAt": "2026-11-28T05:00:00.000Z" },
      { "id": "weekly", "kind": "weekly", "label": "Weekly", "usedPercent": 80, "remainingPercent": 20, "resetsAt": "2026-12-01T00:00:00.000Z" }
    ],
    "resetCredits": { "availableCount": 2, "nextExpiresAt": "2026-12-01T00:00:00.000Z" }
  }]
}

Schemas

Shared window fields on the summary and thread tools: optional environmentId, sinceDay, untilDay, timeZone (IANA, default UTC). Omit both dates for the last 7 days. A range longer than 31 days is rejected.

  • t3_usage_summary also takes optional resolution (day or hour), sinceTime, untilTime (required together for hour, at most 24 hours), and modelFilter.
  • t3_usage_threads also takes optional projectId, threadId, and limit (1–50, default 20).
  • t3_usage_limits takes only optional environmentId.

What Tanner needs to do

Rebuild or reinstall the server so this process is the one serving /mcp, then have the outside agent refresh its tool list (reconnect the MCP server). The existing Read only approval is enough; there is no new OAuth scope. In-thread agents will not see the tools.

Grok 4.7 via Cursor.

Open in Web Open in Cursor 

cursoragent and others added 2 commits November 28, 2026 01:17
Outside agents could read threads but not token, cost, or limit analytics.
Add three read-only tools that use the usage cache and bounded thread lookups.

Co-authored-by: Tanner Polley <tannerwpolley@gmail.com>
Knip rejected constants and helpers that only the report module uses.

Co-authored-by: Tanner Polley <tannerwpolley@gmail.com>

This branch has not been deployed

No deployments
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.

2 participants