Repository navigation
feat(server): add read-only MCP usage tools - #750
Open
tannerpolley wants to merge 2 commits into
Open
tannerpolley wants to merge 2 commits into
tannerpolley wants to merge 2 commits into
Conversation
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.mdanddocs/user/usage.md.Performance.
t3_usage_summaryreads the existing usage cache (provisional, noawaitRefresh) 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_threadsdoes not scan turns by date: it takes the 200 newest active threads from the active-thread index (LIMIT 201so truncation is visible), then reads those threads' turns through thethread_idindex and the latest context reading through the usage index. Both queries run on the read-only connection.t3_usage_limitsreturns 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 acompleted_atindex 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 linton the touched server files,vp test runofusageReport.test.ts,UsageAnalytics.test.ts, andhandlers.test.ts(9 tests), andeffect-tsgo tsrs --noEmitinapps/server.The handler test calls
t3_usage_limitsas a read-only outside client. The analytics test checks that a 32-day window is rejected before any scan, that a summary asks forprovisional: trueandskipServiceTierResolution: true, and that thread totals drop local-command turns, out-of-window turns, archived threads (unlessthreadIdis 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: truemeans 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 }] }inputTokensalready includes cache reads and writes.otherTokensis native subagent and compaction usage.fillRatiois 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 undernearAutoCompaction.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_summaryalso takes optionalresolution(dayorhour),sinceTime,untilTime(required together forhour, at most 24 hours), andmodelFilter.t3_usage_threadsalso takes optionalprojectId,threadId, andlimit(1–50, default 20).t3_usage_limitstakes only optionalenvironmentId.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.