Skip to content

Commit d048463

Browse files
committed
fix(cursor): bound serialized tool catalogs (#190)
1 parent 2ea15d8 commit d048463

11 files changed

Lines changed: 241 additions & 35 deletions

‎src/adapters/cursor/cursor-errors.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@ export function classifyCursorError(message: string): string {
4848

4949
if (
5050
lower.includes("resource_exhausted") ||
51-
lower.includes("resource exhausted") ||
51+
lower.includes("resource exhausted")
52+
) return "Cursor resource limit exceeded";
53+
54+
if (
5255
lower.includes("rate limit") ||
5356
lower.includes("rate-limit") ||
5457
lower.includes("too many requests") ||
@@ -106,7 +109,9 @@ export function classifyCursorError(message: string): string {
106109
* Mirrors `safeKiroErrorMessage` / `safeKiroHttpErrorMessage` in kiro-errors.ts.
107110
*/
108111
export function safeCursorErrorMessage(rawMessage: string): string {
109-
const detail = sanitize(rawMessage).slice(0, 500);
110112
const prefix = classifyCursorError(rawMessage);
113+
const detail = sanitize(rawMessage)
114+
.replace(/resource[_ ]exhausted/gi, "resource limit exceeded")
115+
.slice(0, 500);
111116
return detail ? `${prefix}: ${detail}` : prefix;
112117
}

‎src/adapters/cursor/request-builder.ts‎

Lines changed: 90 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,89 @@ import type {
66
OcxToolCall,
77
OcxToolResultMessage,
88
} from "../../types";
9-
import { namespacedToolName } from "../../types";
9+
import { isAllowedToolChoice, namespacedToolName, toolChoiceAliases, type OcxTool, type OcxToolChoice } from "../../types";
1010
import type { CursorRequestMessage, CursorRunRequest } from "./types";
1111
import { cursorCodexToWireModelId } from "./discovery";
1212
import { cursorEffortSuffix } from "./effort-map";
13+
import {
14+
cursorMcpToolEncodedSize,
15+
cursorMcpToolsEncodedSize,
16+
cursorToolAllowedByChoice,
17+
cursorToolWireName,
18+
cursorToolsForActivePrompt,
19+
} from "./tool-definitions";
20+
21+
/** Probe-verified Cursor Connect boundaries, with byte headroom for the enclosing field. */
22+
export const CURSOR_TOOL_COUNT_LIMIT = 330;
23+
export const CURSOR_TOOL_BYTES_LIMIT = 120_000;
24+
25+
interface CursorToolBudgetResult {
26+
tools: OcxTool[];
27+
omitted: OcxTool[];
28+
}
29+
30+
function explicitlySelectedNames(choice: OcxToolChoice | undefined): Set<string> {
31+
if (!choice || choice === "auto" || choice === "none" || choice === "required") return new Set();
32+
return new Set("name" in choice ? [choice.name] : isAllowedToolChoice(choice) ? choice.allowedTools : []);
33+
}
34+
35+
function toolPriority(tool: OcxTool, selectedNames: ReadonlySet<string>): number {
36+
if (toolChoiceAliases(tool).some(name => selectedNames.has(name))) return 0;
37+
if (tool.loadedFromToolSearch) return 1;
38+
if (!tool.namespace) return 2;
39+
return 3;
40+
}
41+
42+
/**
43+
* Select one catalog used by both Cursor protobuf registration and call recognition.
44+
* Actual McpTools serialization is measured after every candidate so descriptions,
45+
* names, provider identifiers, and schemas all count toward the byte ceiling.
46+
*/
47+
export function applyCursorToolBudget(
48+
tools: readonly OcxTool[] | undefined,
49+
toolChoice: OcxToolChoice | undefined,
50+
): CursorToolBudgetResult {
51+
const eligible = (tools ?? []).filter(tool => cursorToolAllowedByChoice(tool, toolChoice));
52+
if (
53+
eligible.length <= CURSOR_TOOL_COUNT_LIMIT
54+
&& cursorMcpToolsEncodedSize(eligible, toolChoice) <= CURSOR_TOOL_BYTES_LIMIT
55+
) return { tools: [...eligible], omitted: [] };
56+
57+
const selectedNames = explicitlySelectedNames(toolChoice);
58+
const candidates = eligible
59+
.map((tool, index) => ({ tool, index, priority: toolPriority(tool, selectedNames) }))
60+
.sort((a, b) => a.priority - b.priority || a.index - b.index);
61+
const kept: OcxTool[] = [];
62+
const keptSet = new Set<OcxTool>();
63+
let keptBytes = 0;
64+
65+
for (const candidate of candidates) {
66+
if (kept.length >= CURSOR_TOOL_COUNT_LIMIT) continue;
67+
// Repeated protobuf message fields serialize as concatenated tag/length/value entries,
68+
// so each one-entry wrapper size is the exact additive contribution to McpTools.
69+
const candidateBytes = cursorMcpToolEncodedSize(candidate.tool, toolChoice);
70+
if (keptBytes + candidateBytes > CURSOR_TOOL_BYTES_LIMIT) continue;
71+
kept.push(candidate.tool);
72+
keptSet.add(candidate.tool);
73+
keptBytes += candidateBytes;
74+
}
75+
76+
return {
77+
tools: eligible.filter(tool => keptSet.has(tool)),
78+
omitted: eligible.filter(tool => !keptSet.has(tool)),
79+
};
80+
}
81+
82+
function catalogLimitNote(kept: readonly OcxTool[], omitted: readonly OcxTool[]): string | undefined {
83+
if (omitted.length === 0) return undefined;
84+
const recoverable = kept.some(tool => tool.toolSearch || cursorToolWireName(tool) === "tool_search");
85+
const names = omitted.slice(0, 12).map(cursorToolWireName);
86+
const remainder = omitted.length - names.length;
87+
const omittedSummary = `${names.join(", ")}${remainder > 0 ? `, and ${remainder} more` : ""}`;
88+
return recoverable
89+
? `[opencodex] Cursor's transport limit allows ${kept.length} of ${kept.length + omitted.length} client tools this turn. Omitted: ${omittedSummary}. Use tool_search for a needed omitted tool; tools returned by tool_search are prioritized on the next turn.`
90+
: `[opencodex] Cursor's transport limit allows ${kept.length} of ${kept.length + omitted.length} client tools this turn. Omitted and unavailable this turn: ${omittedSummary}.`;
91+
}
1392

1493
/**
1594
* Resolve a `cursor/<model>` selection + Codex reasoning effort to the actual Cursor model id. Cursor
@@ -80,19 +159,24 @@ export function generatedCursorConversationId(): string {
80159
}
81160

82161
export function createCursorRequest(parsed: OcxParsedRequest): CursorRunRequest {
162+
const messages = parsed.context.messages
163+
.map(requestMessage)
164+
.filter((message): message is CursorRequestMessage => !!message && message.content.length > 0);
165+
const activeText = [...messages].reverse().find(message => message.role === "user" || message.role === "developer")?.content ?? "";
166+
const visibleTools = cursorToolsForActivePrompt(parsed.context.tools, activeText, parsed.options.toolChoice);
167+
const budget = applyCursorToolBudget(visibleTools, parsed.options.toolChoice);
168+
const limitNote = catalogLimitNote(budget.tools, budget.omitted);
83169
return {
84170
modelId: normalizeCursorModelId(parsed.modelId, parsed.options.reasoning),
85171
// The Cursor conversation id comes ONLY from remembered state (_cursorConversationId). Do NOT fall
86172
// back to the OpenAI Responses previous_response_id (resp_*): that is a Responses-chain id in a
87173
// different namespace and would start an unrelated Cursor conversation, breaking tool-result
88174
// continuation. If we have no remembered Cursor conversation, start a fresh one.
89175
conversationId: parsed._cursorConversationId ?? generatedCursorConversationId(),
90-
system: [...(parsed.context.systemPrompt ?? [])],
91-
messages: parsed.context.messages
92-
.map(requestMessage)
93-
.filter((message): message is CursorRequestMessage => !!message && message.content.length > 0),
176+
system: [...(parsed.context.systemPrompt ?? []), ...(limitNote ? [limitNote] : [])],
177+
messages,
94178
rawMessages: parsed.context.messages,
95-
...(parsed.context.tools?.length ? { tools: parsed.context.tools } : {}),
179+
...(budget.tools.length ? { tools: budget.tools } : {}),
96180
...(parsed.options.toolChoice ? { toolChoice: parsed.options.toolChoice } : {}),
97181
...(parsed.options.parallelToolCalls !== undefined ? { parallelToolCalls: parsed.options.parallelToolCalls } : {}),
98182
};

‎src/adapters/cursor/tool-definitions.ts‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { create, fromJson, toBinary, type JsonValue } from "@bufbuild/protobuf";
22
import { ValueSchema } from "@bufbuild/protobuf/wkt";
33
import type { OcxRequestOptions, OcxTool } from "../../types";
44
import { namespacedToolName } from "../../types";
5-
import { McpToolDefinitionSchema, type McpToolDefinition } from "./gen/agent_pb";
5+
import { McpToolDefinitionSchema, McpToolsSchema, type McpToolDefinition } from "./gen/agent_pb";
66

77
export const OCX_RESPONSES_TOOL_PROVIDER = "opencodex-responses";
88
export const CODEX_EXEC_COMMAND_TOOL = "exec_command";
@@ -50,7 +50,7 @@ export function cursorRequestAdvertisesApplyPatch(
5050
tools: readonly Pick<OcxTool, "namespace" | "name" | "freeform">[] | undefined,
5151
toolChoice?: OcxRequestOptions["toolChoice"],
5252
): boolean {
53-
return tools?.some(tool => !tool.namespace && tool.name === CODEX_APPLY_PATCH_TOOL && tool.freeform === true && toolChoiceAllows(tool, toolChoice)) ?? false;
53+
return tools?.some(tool => !tool.namespace && tool.name === CODEX_APPLY_PATCH_TOOL && tool.freeform === true && cursorToolAllowedByChoice(tool, toolChoice)) ?? false;
5454
}
5555

5656
export function cursorToolWireName(tool: Pick<OcxTool, "namespace" | "name">): string {
@@ -176,7 +176,7 @@ export function cursorToolsForActivePrompt<T extends Pick<OcxTool, "namespace" |
176176
): readonly T[] | undefined {
177177
if (!shouldUseNativeExecOnlyForGenericToolUse(tools, activeText)) return tools;
178178
const execTools = tools?.filter(isBareCodexExecCommandTool);
179-
if (execTools?.length && !execTools.some(tool => toolChoiceAllows(tool, toolChoice))) return tools;
179+
if (execTools?.length && !execTools.some(tool => cursorToolAllowedByChoice(tool, toolChoice))) return tools;
180180
return execTools && execTools.length > 0 ? execTools : tools;
181181
}
182182

@@ -199,7 +199,7 @@ export function appendCursorShellAliasHint(
199199
return `${text}${text.endsWith("\n") ? "\n" : "\n\n"}${CURSOR_SHELL_ALIAS_USER_HINT}`;
200200
}
201201

202-
function toolChoiceAllows(tool: Pick<OcxTool, "namespace" | "name">, toolChoice: OcxRequestOptions["toolChoice"] | undefined): boolean {
202+
export function cursorToolAllowedByChoice(tool: Pick<OcxTool, "namespace" | "name">, toolChoice: OcxRequestOptions["toolChoice"] | undefined): boolean {
203203
if (!toolChoice || toolChoice === "auto" || toolChoice === "required") return true;
204204
if (toolChoice === "none") return false;
205205
if ("allowedTools" in toolChoice) {
@@ -232,7 +232,7 @@ export function buildCursorToolGuidanceSystemNote(
232232
if (!tools?.length) return undefined;
233233
const wireNames = [...new Set(
234234
tools
235-
.filter(tool => toolChoiceAllows(tool, toolChoice))
235+
.filter(tool => cursorToolAllowedByChoice(tool, toolChoice))
236236
.map(tool => cursorToolWireName(tool)),
237237
)];
238238
if (wireNames.length === 0) return undefined;
@@ -291,7 +291,7 @@ export function buildCursorToolDefinitions(
291291
toolChoice?: OcxRequestOptions["toolChoice"],
292292
): McpToolDefinition[] {
293293
if (!tools?.length) return [];
294-
return tools.filter(tool => toolChoiceAllows(tool, toolChoice)).map(tool => {
294+
return tools.filter(tool => cursorToolAllowedByChoice(tool, toolChoice)).map(tool => {
295295
const wireName = cursorToolWireName(tool);
296296
return create(McpToolDefinitionSchema, {
297297
name: wireName,
@@ -302,3 +302,20 @@ export function buildCursorToolDefinitions(
302302
});
303303
});
304304
}
305+
306+
/** Exact byte size of the protobuf field value Cursor receives for client tool registration. */
307+
export function cursorMcpToolsEncodedSize(
308+
tools: readonly OcxTool[] | undefined,
309+
toolChoice?: OcxRequestOptions["toolChoice"],
310+
): number {
311+
const definitions = buildCursorToolDefinitions(tools, toolChoice);
312+
return toBinary(McpToolsSchema, create(McpToolsSchema, { mcpTools: definitions })).byteLength;
313+
}
314+
315+
/** Exact additive contribution of one repeated McpToolDefinition entry. */
316+
export function cursorMcpToolEncodedSize(
317+
tool: OcxTool,
318+
toolChoice?: OcxRequestOptions["toolChoice"],
319+
): number {
320+
return cursorMcpToolsEncodedSize([tool], toolChoice);
321+
}

‎src/lib/errors.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,9 @@ export function classifyError(status: number, type: string, message: string): Oc
9999
) {
100100
return { message, type: "invalid_request_error", code: "context_length_exceeded" };
101101
}
102+
if (text.includes("cursor resource limit exceeded")) {
103+
return { message, type: "invalid_request_error", code: "tool_catalog_too_large" };
104+
}
102105
if (
103106
text.includes("insufficient_quota") ||
104107
text.includes("exceeded your current quota") ||
@@ -199,6 +202,7 @@ export function inferHttpStatusFromAdapterMessage(message: string): number {
199202
const lower = message.toLowerCase();
200203
// Client aborts (e.g. mid web-search loop) must not look like upstream 502s in /api/logs.
201204
if (isClientClosedMessage(lower)) return 499;
205+
if (lower.includes("cursor resource limit exceeded")) return 400;
202206
if (
203207
lower.includes("resource_exhausted") ||
204208
lower.includes("resource exhausted") ||

‎src/responses/parser.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -525,13 +525,18 @@ export function parseRequest(body: unknown): OcxParsedRequest {
525525

526526
const declaredTools = buildTools(data.tools as unknown[] | undefined) ?? [];
527527
const loadedTools = buildTools(loadedToolSpecs) ?? [];
528+
const loadedToolNames = new Set(loadedTools.map(t => namespacedToolName(t.namespace, t.name)));
528529
const seenTools = new Set<string>();
529-
const mergedTools = [...declaredTools, ...loadedTools].filter(t => {
530-
const k = namespacedToolName(t.namespace, t.name);
531-
if (seenTools.has(k)) return false;
532-
seenTools.add(k);
533-
return true;
534-
});
530+
const mergedTools = [...declaredTools, ...loadedTools]
531+
.filter(t => {
532+
const k = namespacedToolName(t.namespace, t.name);
533+
if (seenTools.has(k)) return false;
534+
seenTools.add(k);
535+
return true;
536+
})
537+
.map(t => loadedToolNames.has(namespacedToolName(t.namespace, t.name))
538+
? { ...t, loadedFromToolSearch: true }
539+
: t);
535540
const context: OcxContext = {
536541
...(systemPrompt.length > 0 ? { systemPrompt } : {}),
537542
messages,

‎src/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,8 @@ export interface OcxTool {
122122
freeform?: boolean;
123123
/** Client-executed tool discovery (tool_search): the model's call must be relayed as a tool_search_call. */
124124
toolSearch?: boolean;
125+
/** Tool definition restored from a prior tool_search output; transports may prioritize it when catalogs are bounded. */
126+
loadedFromToolSearch?: boolean;
125127
/** Synthetic web_search tool: the model's call is executed by the gpt-5.4-mini sidecar, not relayed to Codex. */
126128
webSearch?: boolean;
127129
}

‎tests/adapter-error-inline.test.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -59,23 +59,24 @@ describe("inline error envelope in a 200 stream (F1)", () => {
5959
expect(frames.some(f => f.event === "response.completed")).toBe(false);
6060
});
6161

62-
test("Cursor resource_exhausted maps to 429 rate_limit_error in response.failed", async () => {
62+
test("Cursor tool-catalog resource exhaustion maps to an actionable 400", async () => {
63+
const message = "Cursor resource limit exceeded: Cursor Connect error resource limit exceeded: tool catalog too large";
6364
async function* gen(): AsyncGenerator<AdapterEvent> {
6465
yield {
6566
type: "error",
66-
message: "Cursor rate limit exceeded: Cursor Connect error resource_exhausted: too many requests",
67+
message,
6768
};
6869
}
6970
const frames = await collectSse(bridgeToResponsesSSE(gen(), "cursor/gpt-5"));
7071
const failed = frames.find(f => f.event === "response.failed");
7172
expect(failed).toBeDefined();
7273
expect((failed!.data.response as Record<string, unknown>).error).toMatchObject({
73-
type: "rate_limit_error",
74-
code: "rate_limit_exceeded",
74+
type: "invalid_request_error",
75+
code: "tool_catalog_too_large",
7576
});
76-
expect(adapterFailureFromMessage("Cursor rate limit exceeded: Cursor Connect error resource_exhausted: too many requests")).toMatchObject({
77-
httpStatus: 429,
78-
error: { type: "rate_limit_error", code: "rate_limit_exceeded" },
77+
expect(adapterFailureFromMessage(message)).toMatchObject({
78+
httpStatus: 400,
79+
error: { type: "invalid_request_error", code: "tool_catalog_too_large" },
7980
});
8081
});
8182
});

‎tests/cursor-errors.test.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import {
66
} from "../src/adapters/cursor/cursor-errors";
77

88
describe("classifyCursorError", () => {
9-
test("rate limit / resource exhausted", () => {
10-
expect(classifyCursorError("resource_exhausted: too many concurrent requests")).toBe("Cursor rate limit exceeded");
9+
test("rate limit and resource exhaustion stay distinct", () => {
10+
expect(classifyCursorError("resource_exhausted: tool registration too large")).toBe("Cursor resource limit exceeded");
1111
expect(classifyCursorError("rate limit exceeded for model")).toBe("Cursor rate limit exceeded");
1212
});
1313

@@ -73,4 +73,11 @@ describe("safeCursorErrorMessage", () => {
7373
const long = "x".repeat(1000);
7474
expect(safeCursorErrorMessage(long).length).toBeLessThanOrEqual(530);
7575
});
76+
77+
test("does not present resource exhaustion as a billing or quota rate limit", () => {
78+
const msg = safeCursorErrorMessage("resource_exhausted: tool catalog too large");
79+
expect(msg).toContain("Cursor resource limit exceeded");
80+
expect(msg).not.toContain("resource_exhausted");
81+
expect(msg).not.toContain("rate limit");
82+
});
7683
});

0 commit comments

Comments
 (0)