Skip to content

Commit 3fd9419

Browse files
authored
Merge pull request #5435 from modelcontextprotocol/v2/fix/5433-sequentialthinking-linear-thought-box
fix(sequentialthinking): bound the stderr thought box
2 parents f4f9928 + c583da0 commit 3fd9419

4 files changed

Lines changed: 208 additions & 15 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-sequential-thinking": patch
3+
---
4+
5+
Bound the thought box logged to stderr. Since the multi-line box, every row was padded to the thought's longest line, so a thought with one long line and many short ones logged their product: a 60 KB thought wrote 400 million characters and could exhaust the server's memory. The box is now at most 100 characters wide (longer lines, and a long branch ID in the header, wrap) and draws at most 1000 rows of thought text (it then says how many lines it left out), so the log no longer grows with the thought's line count times its longest line. The thought kept in the server's history and the tool result are unchanged.

‎src/sequentialthinking/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,8 @@ On Windows, use `cmd /c` to launch `npx`:
134134

135135
To disable logging of thought information set env var: `DISABLE_THOUGHT_LOGGING` to `true`.
136136

137+
Each thought is logged to stderr as a box, one row per line of the thought. The box is at most 100 characters wide, with longer lines (and a long branch ID in the header) wrapped, and draws at most 1000 rows of thought text; past that it ends with a row saying how many lines it left out. Only the log is shortened: the server keeps the whole thought in its history, and the tool result is unchanged.
138+
137139
To bound memory use, the server retains at most `MAX_THOUGHT_HISTORY` thoughts per connection (a positive integer; default `1000`). Past the cap the oldest thought is dropped, from its branch too, so `thoughtHistoryLength` in the result stops at the cap and a branch whose thoughts have all been dropped is no longer listed in `branches`.
138140

139141
### Usage with VS Code

‎src/sequentialthinking/__tests__/thought-logging.test.ts‎

Lines changed: 115 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// The server's other observable output: unless DISABLE_THOUGHT_LOGGING is
22
// "true" (any case), each accepted thought is drawn as a box on stderr, with
33
// a header that differs for plain thoughts, revisions and branches, and one
4-
// row per line of the thought. Thoughts
4+
// row per line of the thought, wrapped at MAX_BOX_TEXT_WIDTH and cut off
5+
// after MAX_BOX_ROWS. Thoughts
56
// are driven through the in-process client and stderr is captured by spying
67
// on console.error, which also keeps the boxes off the test output. chalk's
78
// colour level depends on the terminal the tests run in, so it is pinned to 0
@@ -18,6 +19,7 @@ import {
1819
type MockInstance,
1920
} from "vitest";
2021
import chalk from "chalk";
22+
import { MAX_BOX_ROWS, MAX_BOX_TEXT_WIDTH } from "../lib.js";
2123
import { connect, thought, type Connected } from "./helpers.js";
2224

2325
describe("sequentialthinking thought logging", () => {
@@ -229,11 +231,122 @@ ${rows.join("\n")}
229231
expect(new Set(rows.map((row) => row.length)).size).toBe(1);
230232
});
231233

234+
// #5433: past MAX_BOX_ROWS the box stops drawing and says how many lines
235+
// it left out; the call itself is unaffected.
232236
it("draws a thought with very many lines", async () => {
233237
const lines = Array.from({ length: 200_000 }, (_, i) => `${i % 10}`);
234238
const result = await conn!.think(thought({ thought: lines.join("\n") }));
235239
expect(result.isError).toBeFalsy();
236-
expect(logged()[0].split("\n")).toHaveLength(200_000 + 5);
240+
const out = logged()[0].split("\n");
241+
expect(out).toHaveLength(MAX_BOX_ROWS + 1 + 5);
242+
expect(out.at(-2)).toContain(
243+
`… ${200_000 - MAX_BOX_ROWS} more lines not shown`,
244+
);
245+
// The summary is wider than every one-character line and the header,
246+
// so it sets the box's width; it must not stick out of it.
247+
expect(new Set(out.slice(1).map((r) => r.length)).size).toBe(1);
248+
});
249+
});
250+
251+
// #5433: the box is never wider than MAX_BOX_TEXT_WIDTH. A longer line, or
252+
// a longer header, wraps onto rows of that width, so the box grows linearly
253+
// with the thought instead of as its longest line times its line count.
254+
describe("a thought wider than the box", () => {
255+
const W = MAX_BOX_TEXT_WIDTH;
256+
const border = "─".repeat(W + 4);
257+
const row = (text: string) => `│ ${text.padEnd(border.length - 2)} │`;
258+
259+
beforeEach(async () => {
260+
conn = await connect({ disableThoughtLogging: undefined });
261+
});
262+
263+
it("wraps a long line onto rows of the capped width", async () => {
264+
const text = `${"a".repeat(W)}${"b".repeat(W)}${"c".repeat(5)}`;
265+
await conn!.think(thought({ thought: `${text}\nshort` }));
266+
expect(logged()).toEqual([
267+
`
268+
┌${border}┐
269+
${row("💭 Thought 1/3")}
270+
├${border}┤
271+
${row("a".repeat(W))}
272+
${row("b".repeat(W))}
273+
${row("c".repeat(5))}
274+
${row("short")}
275+
└${border}┘`,
276+
]);
277+
});
278+
279+
it("stays bounded for one long line and many short ones", async () => {
280+
// The case from the review of #5430: before the cap, every one of the
281+
// 19,999 short rows was padded to 20,000 characters, 400 million in all.
282+
const n = 20_000;
283+
const text = `${"x".repeat(n)}${"\ny".repeat(n - 1)}`;
284+
const result = await conn!.think(thought({ thought: text }));
285+
expect(result.isError).toBeFalsy();
286+
const out = logged()[0];
287+
// 200 wrapped rows for the long line, short lines up to the row cap,
288+
// then the summary row; each row is W + 6 characters and a newline.
289+
const shortShown = MAX_BOX_ROWS - n / W;
290+
expect(out.split("\n")).toHaveLength(MAX_BOX_ROWS + 1 + 5);
291+
expect(out).toContain(`… ${n - 1 - shortShown} more lines not shown`);
292+
expect(out.length).toBeLessThan((MAX_BOX_ROWS + 10) * (W + 7));
293+
});
294+
295+
it("counts a line the row cap cuts off as not shown", async () => {
296+
const text = `${"s\n".repeat(MAX_BOX_ROWS - 1)}${"L".repeat(2 * W)}`;
297+
await conn!.think(thought({ thought: text }));
298+
const rows = logged()[0].split("\n");
299+
expect(rows).toHaveLength(MAX_BOX_ROWS + 1 + 5);
300+
expect(rows.at(-3)).toBe(row("L".repeat(W)));
301+
expect(rows.at(-2)).toBe(row("… 1 more line not shown"));
302+
});
303+
304+
it("draws a thought that exactly fills the cap with no summary row", async () => {
305+
const text = Array.from({ length: MAX_BOX_ROWS }, () => "s").join("\n");
306+
await conn!.think(thought({ thought: text }));
307+
const rows = logged()[0].split("\n");
308+
expect(rows).toHaveLength(MAX_BOX_ROWS + 5);
309+
expect(logged()[0]).not.toContain("not shown");
310+
});
311+
312+
it("draws every row the same width", async () => {
313+
await conn!.think(thought({ thought: `${"z".repeat(3 * W + 7)}\nend` }));
314+
const rows = logged()[0].split("\n").slice(1);
315+
expect(new Set(rows.map((r) => r.length))).toEqual(new Set([W + 6]));
316+
});
317+
318+
it("wraps a header longer than the cap, and keeps the box linear", async () => {
319+
const branchId = "b".repeat(2 * W);
320+
const lines = 1_000;
321+
await conn!.think(
322+
thought({
323+
thought: Array.from({ length: lines }, () => "s").join("\n"),
324+
branchFromThought: 1,
325+
branchId,
326+
}),
327+
);
328+
const out = logged()[0];
329+
const rows = out.split("\n").slice(1);
330+
expect(new Set(rows.map((r) => r.length))).toEqual(new Set([W + 6]));
331+
const header = `🌿 Branch 1/3 (from thought 1, ID: ${branchId})`;
332+
const headerRows = rows.slice(1, rows.indexOf(`├${border}┤`));
333+
expect(headerRows.map((r) => r.slice(2, -2).trimEnd()).join("")).toBe(
334+
header,
335+
);
336+
// Each row is W + 6 characters and a newline. Uncapped, the header would
337+
// have set every row's width to its own length of more than 2 × W.
338+
expect(out.length).toBeLessThan((lines + 10) * (W + 7));
339+
});
340+
341+
it("never splits an emoji across rows", async () => {
342+
// The emoji's two UTF-16 halves would straddle the cut at W.
343+
const text = `${"a".repeat(W - 1)}😀tail`;
344+
await conn!.think(thought({ thought: text }));
345+
const rows = logged()[0].split("\n").slice(4, -1);
346+
expect(rows.map((r) => r.slice(2, -2).trimEnd())).toEqual([
347+
"a".repeat(W - 1),
348+
"😀tail",
349+
]);
237350
});
238351
});
239352

‎src/sequentialthinking/lib.ts‎

Lines changed: 86 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,50 @@ export interface ThoughtData {
1212
nextThoughtNeeded: boolean;
1313
}
1414

15+
/**
16+
* The widest the text inside a thought box gets (#5433). A longer line, or a
17+
* longer header, wraps onto further rows of this width. Without the cap every
18+
* row was padded to the longest line, so one long line and many short ones
19+
* made the box grow as their product: a 60 KB thought logged 400 million
20+
* characters. Capped, the box grows linearly with the thought.
21+
*/
22+
export const MAX_BOX_TEXT_WIDTH = 100;
23+
24+
/**
25+
* The most rows of thought text a box draws (#5433). Each row is padded to
26+
* the box's width, so a thought of many short lines would still log about a
27+
* hundred times its own size; past this many rows the box ends with one row
28+
* saying how many lines it left out. Header rows (a long branchId) are not
29+
* counted. Only stderr is cut: the thought kept in thoughtHistory is whole,
30+
* and the tool result, which carries no thought text, is unchanged.
31+
*/
32+
export const MAX_BOX_ROWS = 1000;
33+
34+
/**
35+
* `text` cut into rows of at most `width` UTF-16 code units, never between
36+
* the two halves of a surrogate pair, so an emoji is never split across rows.
37+
* An empty string is one empty row.
38+
*/
39+
function wrapRow(text: string, width: number): string[] {
40+
const rows: string[] = [];
41+
let start = 0;
42+
do {
43+
let end = Math.min(start + width, text.length);
44+
const last = text.charCodeAt(end - 1);
45+
if (
46+
end < text.length &&
47+
end - start > 1 &&
48+
last >= 0xd800 &&
49+
last <= 0xdbff
50+
) {
51+
end -= 1;
52+
}
53+
rows.push(text.slice(start, end));
54+
start = end;
55+
} while (start < text.length);
56+
return rows;
57+
}
58+
1559
/**
1660
* How many thoughts one server instance retains when MAX_THOUGHT_HISTORY is
1761
* unset (#2912). A server lives as long as its client's connection, so without
@@ -104,25 +148,54 @@ export class SequentialThinkingServer {
104148
const lines = thought.split(/\r\n|\r|\n/);
105149
// A reduce rather than Math.max(...lengths): spreading one argument per
106150
// line would overflow the call stack on a thought with very many lines.
107-
const width = lines.reduce(
108-
(widest, line) => Math.max(widest, line.length),
109-
visibleHeader.length,
151+
// #5433: never wider than MAX_BOX_TEXT_WIDTH; longer lines wrap below.
152+
const wrapWidth = Math.min(
153+
MAX_BOX_TEXT_WIDTH,
154+
lines.reduce(
155+
(widest, line) => Math.max(widest, line.length),
156+
visibleHeader.length,
157+
),
110158
);
159+
// A header longer than the cap (a long branchId) wraps like a thought
160+
// line; only its first row, which starts with the label, is coloured.
161+
const headerTexts = wrapRow(visibleHeader, wrapWidth);
162+
// Rows are drawn up to MAX_BOX_ROWS; the lines left over are counted, not
163+
// drawn, so a huge thought costs no more than the cap.
164+
const texts: string[] = [];
165+
// Lines drawn in full; a line cut off by the cap counts as hidden.
166+
let whole = 0;
167+
for (const line of lines) {
168+
const wrapped = wrapRow(line, wrapWidth);
169+
const room = MAX_BOX_ROWS - texts.length;
170+
texts.push(...wrapped.slice(0, room));
171+
if (wrapped.length > room) break;
172+
whole++;
173+
}
174+
const hidden = lines.length - whole;
175+
const summary =
176+
hidden > 0
177+
? `… ${hidden} more line${hidden === 1 ? "" : "s"} not shown`
178+
: "";
179+
if (summary) texts.push(summary);
180+
// The summary row can be wider than every line it follows, so the box is
181+
// sized after it. Widening cannot change the wrapping above: below the cap
182+
// no line wrapped, and at the cap the summary (under 40 characters) fits.
183+
const width = Math.max(wrapWidth, summary.length);
111184
const border = "─".repeat(width + 4);
112-
// The header row is padded to the border's width like the thought rows, by
113-
// the visible text's length. Each label's emoji is one surrogate pair, so
114-
// its length of 2 is also its display width in a terminal.
115-
const padding = " ".repeat(border.length - 2 - visibleHeader.length);
116-
const header = `${colour(label)}${counts}${padding}`;
117-
const rows = lines
118-
.map((line) => `│ ${line.padEnd(border.length - 2)} │`)
119-
.join("\n");
185+
// Every row, header rows included, is padded to the border's width by the
186+
// visible text's length. Each label's emoji is one surrogate pair, so its
187+
// length of 2 is also its display width in a terminal.
188+
const row = (text: string) => `│ ${text.padEnd(border.length - 2)} │`;
189+
const headerRows = headerTexts.map((text, i) =>
190+
i === 0 ? row(text).replace(label, colour(label)) : row(text),
191+
);
192+
const rows = texts.map(row);
120193

121194
return `
122195
┌${border}┐
123-
│ ${header} │
196+
${headerRows.join("\n")}
124197
├${border}┤
125-
${rows}
198+
${rows.join("\n")}
126199
└${border}┘`;
127200
}
128201

0 commit comments

Comments
 (0)