perf(mcp): index tool contracts, skip unadvertised projection, parallelize status probes, and stream tool result sizing (#13263)

* perf(mcp): index tool contracts, skip unadvertised projection, parallelize status probes, and stream tool result sizing

* fix(mcp): await readiness before session status and defer omission worklist
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 03:42:23 +00:00
1 parent 264c398c0d
commit 7a2e8da495
8 files changed
+402 -70

No files matched your search

+73 -6
View File
@@ -91,6 +91,76 @@ export const measureMcpResultWithinBudget = (
return { ok: true, bytes };
};
const measureJsonPart = (
part: string,
): {
readonly rawBytes: number;
readonly escapedBytes: number;
readonly escapedCodeUnits: number;
} => {
let rawBytes = 0;
let escapedBytes = 0;
let escapedCodeUnits = 0;
const length = part.length;
for (let i = 0; i < length; i += 1) {
const code = part.charCodeAt(i);
if (code < 0x80) {
rawBytes += 1;
if (
code === 0x22 ||
code === 0x5c ||
code === 0x08 ||
code === 0x09 ||
code === 0x0a ||
code === 0x0c ||
code === 0x0d
) {
escapedBytes += 2;
escapedCodeUnits += 2;
} else if (code < 0x20) {
escapedBytes += 6;
escapedCodeUnits += 6;
} else {
escapedBytes += 1;
escapedCodeUnits += 1;
}
continue;
}
if (code < 0x800) {
rawBytes += 2;
escapedBytes += 2;
escapedCodeUnits += 1;
continue;
}
if (code >= 0xd800 && code <= 0xdbff) {
if (i + 1 < length) {
const next = part.charCodeAt(i + 1);
if (next >= 0xdc00 && next <= 0xdfff) {
rawBytes += 4;
escapedBytes += 4;
escapedCodeUnits += 2;
i += 1;
continue;
}
}
rawBytes += 3;
escapedBytes += 6;
escapedCodeUnits += 6;
continue;
}
if (code >= 0xdc00 && code <= 0xdfff) {
rawBytes += 3;
escapedBytes += 6;
escapedCodeUnits += 6;
continue;
}
rawBytes += 3;
escapedBytes += 3;
escapedCodeUnits += 1;
}
return { rawBytes, escapedBytes, escapedCodeUnits };
};
/** Account for the delivered JSON representations before allocating the complete text. */
export const encodeToolResult = (
value: JsonValue,
@@ -105,12 +175,9 @@ export const encodeToolResult = (
(targetContent ? TARGET_CONTENT_META_BYTES : 0);
let codeUnits = bytes;
for (const part of bufferedJsonParts(jsonParts(value))) {
const escapedPart = JSON.stringify(part);
bytes +=
(structured ? Buffer.byteLength(part) : 0) +
Buffer.byteLength(escapedPart) -
2;
codeUnits += (structured ? part.length : 0) + escapedPart.length - 2;
const measured = measureJsonPart(part);
bytes += (structured ? measured.rawBytes : 0) + measured.escapedBytes;
codeUnits += (structured ? part.length : 0) + measured.escapedCodeUnits;
if (bytes > budgetBytes || codeUnits > MCP_RESULT_STRING_LIMIT)
return {
ok: false,