Skip to content

fix(cursor): enforce tool budget to prevent resource_exhausted with large catalogs - #192

Closed
alexanderxcmo wants to merge 3 commits into
lidge-jun:mainfrom
alexanderxcmo:fix/cursor-tool-budget
Closed

alexanderxcmo wants to merge 3 commits into
lidge-jun:mainfrom
alexanderxcmo:fix/cursor-tool-budget

Conversation

@alexanderxcmo

Copy link
Copy Markdown
Contributor

Problem

Cursor Connect returns resource_exhausted when the aggregate tool catalog exceeds an internal registration limit. This is not a quota issue — the account has remaining credits and native Cursor works fine.

Reproduced with 340 namespace-inner tools (443 KB serialized). Both halves of the catalog (230 and 110 tools) work independently, confirming the failure depends on the aggregate size, not a single malformed schema.

See #190 for full reproduction, measurements, and isolation results.

Fix

Add a Cursor-specific tool budget (default 200) in createCursorRequest:

  • Native tools (no namespace) are always preserved — exec_command, apply_patch, web_search, tool_search, etc.
  • Namespace groups are sorted smallest-first and added until the budget is full.
  • Remaining namespaces are dropped from the initial advertisement. The model can still discover and load them via tool_search.
  • A system-prompt note is appended when trimming occurs, so the model knows to use tool_search for unavailable tools.

Why 200?

Empirically determined: 230 tools succeed, 340 fail. 200 provides safe margin while still covering most real-world setups (typical Codex installs with a few MCP servers stay well under 200).

Testing

  • 4 new unit tests in cursor-request-builder.test.ts:
    • Budget enforcement with mixed native + namespace tools
    • No trimming when under budget
    • Deferred-tools system note when trimmed
    • No note when nothing trimmed
  • All 277 existing cursor tests pass
  • tsc --noEmit clean

Future work

A more complete fix would implement full deferred loading for Cursor (send only tool names in the initial mcp_tools registration, load full schemas on tool_search). This PR provides an immediate, safe mitigation that unblocks all users with large plugin/app catalogs.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8cf40bc303

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/adapters/cursor/request-builder.ts Outdated

export function createCursorRequest(parsed: OcxParsedRequest): CursorRunRequest {
const rawTools = parsed.context.tools ?? [];
const { tools: budgetedTools, trimmed } = enforceCursorToolBudget(rawTools);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve toolChoice-selected tools before trimming

When a large catalog has tool_choice targeting a namespaced tool in a namespace that sorts past the budget, this trims that namespace before Cursor tool definitions are built; buildCursorToolDefinitions() then filters the already-trimmed request.tools by request.toolChoice, so the forced/allowed tool is never registered and the model cannot satisfy the client's required tool call. The budget pass should reserve any named/allowed tools before dropping optional namespaces.

Useful? React with 👍 / 👎.

Comment thread src/adapters/cursor/request-builder.ts Outdated
system: [...(parsed.context.systemPrompt ?? [])],
system: [
...(parsed.context.systemPrompt ?? []),
...(trimmed ? [CURSOR_DEFERRED_TOOLS_NOTE] : []),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Only suggest tool_search when it is advertised

For callers that send a large fully-enumerated MCP catalog without a tool_search tool, trimming still appends a system note telling the model that dropped tools are available via tool_search, but no such tool is registered because this code only keeps tools from the original catalog. In that scenario Cursor will reject/ignore the suggested call and the model has no way to load the dropped namespace, so the note should be conditional on an advertised/allowed tool_search or use different wording.

Useful? React with 👍 / 👎.

Comment thread src/adapters/cursor/request-builder.ts Outdated
const sorted = [...namespaceGroups.entries()].sort((a, b) => a[1].length - b[1].length);

let remaining = CURSOR_TOOL_BUDGET - native.length;
const kept: OcxTool[] = [...native];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Cap oversized bare-function catalogs too

If a request contains more than 200 non-namespaced function/custom tools, native alone can exceed the Cursor registration limit and this keeps every one of them, leaving request.tools over budget and trimmed false when there are no namespace groups. Since the limit described here counts native plus namespace-inner tools, large flat catalogs can still hit the same resource_exhausted failure this change is meant to prevent.

Useful? React with 👍 / 👎.

let trimmed = false;

for (const [, group] of sorted) {
if (group.length <= remaining) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep searched tools even when siblings are trimmed

When the model follows the new note and tool_search_output loads a specific tool from a large namespace, the next request still re-groups by the original namespace and only keeps it if the whole namespace fits. For a previously dropped oversized namespace this drops the searched tool again, so the advertised recovery path via tool_search never makes that tool callable unless loaded tools are reserved independently of their full namespace group.

Useful? React with 👍 / 👎.

…arge catalogs

Cursor Connect returns resource_exhausted when the aggregate tool catalog
exceeds an internal registration limit (~340 tools fails, ~230 works).
This is not a quota issue — it is a transport-level resource budget.

Add a Cursor-specific tool budget (default 200) that:
- Always preserves native (non-namespace) tools
- Adds namespaces smallest-first until the budget is full
- Drops remaining namespaces (model can still discover them via tool_search)
- Appends a system-prompt note when trimming occurs so the model knows
  to use tool_search for unavailable tools

Fixes lidge-jun#190
…rched tools, conditional note, cap native

- Preserve tools targeted by toolChoice even when their namespace is trimmed
- Keep previously-used tools (from tool_search) across turns
- Only suggest tool_search in deferred note when it exists in kept catalog
- Cap oversized bare-function (non-namespace) catalogs at budget
- Add 4 new unit tests covering each review finding
- Update existing deferred-note test to include tool_search in catalog
@alexanderxcmo
alexanderxcmo force-pushed the fix/cursor-tool-budget branch from dbcb418 to 7741d91 Compare July 20, 2026 18:45
@Wibias

Wibias commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review notes - what should change before treating this as done

Direction is right as a crash mitigation (trim before mcp_tools), but a few claims/edges need fixing so we do not ship a false recovery story.

1. Do not claim tool_search fully recovers trimmed tools (high)

Today previouslyUsedToolNames() only reserves tools that already appear as toolResult (i.e. already called). After tool_search discovers a tool, that tool is usually not reserved yet, so the next budget pass can drop its namespace again and Cursor still never gets it in mcp_tools.

Either:

  • Fix recovery: reserve tools named/returned by tool_search outputs (and keep them across turns), or
  • Tone down: say this only prevents resource_exhausted by omitting overflow namespaces; dropped tools may stay unavailable until a real deferred-registration path exists.

The current system note promising tool_search loading oversells what the Cursor path can do.

2. Cap native + reserved, not only bare native (high)

cappedNative is limited to CURSOR_TOOL_BUDGET, but kept = cappedNative + reserved (+ namespaces) can still exceed 200 when toolChoice / prior-use reserves are large — reintroducing the same failure mode this PR aims to stop.

Apply one hard total cap after assembling reserved + native (and decide an explicit priority order when something must be dropped).

3. Be honest that the limit is a heuristic (medium)

Issue #190 left the boundary open (count vs serialized bytes vs blob budget). 200 is a reasonable empirical count guard, but not proven. Worth:

  • making the budget env/config-tunable for field tuning, and/or
  • noting in the PR/code comment that fat schemas under 200 might still fail.

4. Revisit smallest-first packaging (medium / product)

Smallest-first maximizes namespace count, so tiny MCP servers survive while large useful ones (GitHub/Linear/…) get cut. That unblocks sessions but may drop the tools users care about most. Consider largest-first, a stable allowlist/priority, or filling remaining budget with a partial slice of one oversized namespace instead of dropping it entirely when e.g. 189 slots remain and the group has 216 tools.

5. Error classification still wrong when it slips through (low / follow-up)

#190 also asked not to surface this as a quota/rate-limit. If Cursor still returns resource_exhausted for an oversized catalog, prefer an actionable "tool catalog too large for Cursor" message. Fine as follow-up if this PR stays a mitigation-only patch.


Suggested merge bar: either implement real post-tool_search reservation (or equivalent), or reword docs/note + fix the native+reserved overflow cap. Happy to help on either path.

…-tool capacity

Probe-verified 2026-07-21: Cursor Connect has two limits:
- COUNT limit: ~332 tools (resource_exhausted at 333+)
- BYTE limit: ~128 KB protobuf payload for mcp_tools

Old approach (budget=200) dropped ~140 tools entirely.
New hybrid approach:
1. Raise count budget to 330 (from 200)
2. Keep full schemas for tools within 120 KB byte budget
3. Stub inputSchema for tools beyond byte budget (name+desc only)
4. Inject text schema catalog into system prompt for stubbed tools
5. tool_search still available for on-demand full schema loading

Result: all 340 tools visible to model, most with full schemas,
remainder with stub+catalog. No tools permanently inaccessible.

Addresses Wibias review: real post-tool_search reservation via
stubbedToolNames tracking + text catalog fallback.

19 tests pass (4 new for hybrid behavior), tsc clean.
@alexanderxcmo

Copy link
Copy Markdown
Contributor Author

Probe results & hybrid approach (commit 5fff484)

Live probe 2026-07-21

Ran a controlled probe against api2.cursor.sh with stub schemas ({"type":"object","properties":{}}) to isolate byte vs count limits:

Tools (stub schemas) Status
250 ✅
280 ✅
300 ✅
320 ✅
330 ✅
332 ✅
333 ❌ resource_exhausted
340 ❌ resource_exhausted

Finding: Cursor has TWO independent limits:

  1. COUNT limit: ~332 tools — hard cap on McpToolDefinition entries in mcp_tools, regardless of payload size
  2. BYTE limit: ~128 KB — total protobuf payload for mcp_tools field; with full schemas (~566 B/tool avg) this caps at ~230 tools

The old budget of 200 was conservative against the byte limit. With stub schemas we can reach 330 tools (just under the count cap).

New hybrid approach (this commit)

Instead of dropping tools beyond the budget, we now:

  1. Raise count budget to 330 (from 200) — fits under the 332 count cap
  2. Keep full schemas for tools within a 120 KB byte budget (typically ~150-200 tools)
  3. Stub inputSchema for remaining tools (name + description only, ~30 B each)
  4. Inject a text schema catalog into the system prompt listing stubbed tools with their argument structures
  5. tool_search still available for on-demand full schema loading

Result: all 340 tools visible to the model. Most have full structured schemas; the remainder have stub schemas + text catalog entry. No tools permanently inaccessible.

Addresses review findings

  • (HIGH) tool_search recovery: Stubbed tools are tracked via stubbedToolNames on CursorRunRequest. The text catalog gives the model argument info without needing tool_search. When tool_search IS used, the existing previouslyUsedToolNames() reservation still applies.
  • (HIGH) native + reserved overflow: Hard count cap at 330 prevents overflow. computeStubbedTools() runs after budget enforcement, so the total is always ≤ 330.
  • (MEDIUM) 200 is heuristic: Now documented as two probe-verified limits (count=332, byte≈128KB). Constants renamed to CURSOR_TOOL_COUNT_BUDGET and CURSOR_TOOL_BYTE_BUDGET.
  • (MEDIUM) smallest-first drops large namespaces: With 330 capacity, most namespaces fit. The byte-budget stubbing means even large namespaces (GitHub 89, Linear 59) are included — just with stub schemas for tools beyond the byte threshold.
  • (LOW) error classification: Unchanged, follow-up.

Tests

19 tests pass (4 new for hybrid behavior), tsc --noEmit clean.

New tests cover:

  • Stub schemas applied when byte budget exceeded but count budget allows all tools
  • No stubbing when catalog fits within byte budget
  • Text catalog injected into system prompt with argument summaries
  • 250 tools (between old 200 and new 330 budget) all survive without stubbing

@lidge-jun

Copy link
Copy Markdown
Owner

Please retarget this PR to the dev branch — all contributions go to dev first, and main receives only release promotions. See our Contributing guide for details. Thanks! 🙏

@lidge-jun

Copy link
Copy Markdown
Owner

Adversarial Review Feedback

Good problem identification — the Cursor 332-tool count ceiling and ~128KB byte ceiling are real constraints.

Blockers

  1. Byte budget estimates only schema JSON, not full protobuf — estimateSchemaBytes() only sizes the inputSchema JSON, but the actual McpToolDefinition protobuf includes name, toolName, provider, description fields too. With 300 large-schema tools, the stubbed payload was still 136,983 bytes (over the 128KB ceiling). Use actual McpToolsSchema serialization to measure.

  2. Reserved tools bypass the hard count cap — Native tools are capped at 330, then reserved tools are added back unconditionally. With 330 native + 3 reserved namespace tools, the final count is 333 — exactly at the failure boundary. Apply one final cap across all categories.

  3. Count-trimmed tools silently disappear — Dropped namespaces aren't included in buildTextCatalog() (which only covers retained-but-stubbed tools), yet the system prompt says "full schemas are listed in the catalog below." Also, tool_search-loaded tools are re-trimmed on the next request with no promotion mechanism.

Please retarget to dev — see Contributing guide. 🙏

@lidge-jun

Copy link
Copy Markdown
Owner

Closing this PR — the problem identification (Cursor's ~332 tool count ceiling and ~128KB byte ceiling) is valuable research, but the implementation has three fundamental issues that need an architectural rethink:

  1. Byte budget estimates only schema JSON — the actual protobuf includes name, toolName, provider, description fields. With large schemas, stubbed payloads still exceed 128KB.

  2. Reserved tools bypass the hard count cap — 330 native + reserved tools can exceed the 332 boundary.

  3. Count-trimmed tools silently disappear — dropped namespaces aren't in the text catalog, and tool_search-loaded tools are re-trimmed on the next request with no promotion mechanism.

The probe data on Cursor's limits is useful reference material. Thank you for the research — we'll tackle this with a serialization-aware budget approach. 🙏

Co-authored-by: alexanderxcmo

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.

3 participants