Skip to content

Commit ceb2381

Browse files
committed
fix(sequentialthinking): prevent unbounded memory growth in thought history
The SequentialThinkingServer stores all thoughts in memory arrays that grow without bound across the lifetime of the server process. In long-running sessions (6-8+ hours), this can consume 10GB+ of RAM. Changes: - Add configurable max history limit (SEQUENTIAL_THINKING_MAX_HISTORY env var, default 1000) with automatic trimming of oldest thoughts - Add clearHistory() method to explicitly free memory - Register 'sequentialthinking_clear' tool so clients can reset state - Add tests for memory management and history clearing Fixes modelcontextprotocol#2912
1 parent 173d991 commit ceb2381

4 files changed

Lines changed: 131 additions & 1 deletion

File tree

‎src/sequentialthinking/README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,12 @@ Add this to your `claude_desktop_config.json`:
7777
}
7878
```
7979

80-
To disable logging of thought information set env var: `DISABLE_THOUGHT_LOGGING` to `true`.
80+
### Environment Variables
81+
82+
| Variable | Description | Default |
83+
|----------|-------------|---------|
84+
| `DISABLE_THOUGHT_LOGGING` | Set to `true` to disable logging thought output to stderr | `false` |
85+
| `SEQUENTIAL_THINKING_MAX_HISTORY` | Maximum number of thoughts retained in memory. Oldest thoughts are trimmed when exceeded. | `1000` |
8186
Comment
8287

8388
### Usage with VS Code

‎src/sequentialthinking/__tests__/lib.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,81 @@ describe('SequentialThinkingServer', () => {
251251
});
252252
});
253253

254+
describe('clearHistory', () => {
255+
it('should clear all thoughts and branches', () => {
256+
server.processThought({
257+
thought: 'First', thoughtNumber: 1, totalThoughts: 3, nextThoughtNeeded: true
258+
});
259+
server.processThought({
260+
thought: 'Branch', thoughtNumber: 2, totalThoughts: 3, nextThoughtNeeded: true,
261+
branchFromThought: 1, branchId: 'b1'
262+
});
263+
264+
const result = server.clearHistory();
265+
const data = JSON.parse(result.content[0].text);
266+
267+
expect(data.cleared).toBe(true);
268+
expect(data.previousThoughtCount).toBe(2);
269+
expect(data.previousBranchCount).toBe(1);
270+
271+
// Verify history is actually empty
272+
const nextResult = server.processThought({
273+
thought: 'After clear', thoughtNumber: 1, totalThoughts: 1, nextThoughtNeeded: false
274+
});
275+
const nextData = JSON.parse(nextResult.content[0].text);
276+
expect(nextData.thoughtHistoryLength).toBe(1);
277+
expect(nextData.branches).toEqual([]);
278+
});
279+
});
280+
281+
describe('memory management', () => {
282+
it('should trim history when exceeding max limit', () => {
283+
// Default max is 1000, but we can test the trimming behavior
284+
// by adding more thoughts than the limit
285+
const maxHistory = 1000;
286+
for (let i = 1; i <= maxHistory + 50; i++) {
287+
server.processThought({
288+
thought: `Thought ${i}`,
289+
thoughtNumber: i,
290+
totalThoughts: maxHistory + 50,
291+
nextThoughtNeeded: i < maxHistory + 50
292+
});
293+
}
294+
295+
const lastResult = server.processThought({
296+
thought: 'Final check',
297+
thoughtNumber: maxHistory + 51,
298+
totalThoughts: maxHistory + 51,
299+
nextThoughtNeeded: false
300+
});
301+
const data = JSON.parse(lastResult.content[0].text);
302+
// History should be capped at maxHistory
303+
expect(data.thoughtHistoryLength).toBeLessThanOrEqual(maxHistory);
304+
});
305+
306+
it('should respect SEQUENTIAL_THINKING_MAX_HISTORY env var', () => {
307+
process.env.SEQUENTIAL_THINKING_MAX_HISTORY = '5';
308+
const limitedServer = new SequentialThinkingServer();
309+
310+
for (let i = 1; i <= 10; i++) {
311+
limitedServer.processThought({
312+
thought: `Thought ${i}`,
313+
thoughtNumber: i,
314+
totalThoughts: 10,
315+
nextThoughtNeeded: i < 10
316+
});
317+
}
318+
319+
const result = limitedServer.processThought({
320+
thought: 'Check', thoughtNumber: 11, totalThoughts: 11, nextThoughtNeeded: false
321+
});
322+
const data = JSON.parse(result.content[0].text);
323+
expect(data.thoughtHistoryLength).toBeLessThanOrEqual(5);
324+
325+
delete process.env.SEQUENTIAL_THINKING_MAX_HISTORY;
326+
});
327+
});
328+
254329
describe('processThought - with logging enabled', () => {
255330
let serverWithLogging: SequentialThinkingServer;
256331

‎src/sequentialthinking/index.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,21 @@ You should:
106106
}
107107
);
108108

109+
server.registerTool(
110+
"sequentialthinking_clear",
111+
{
112+
title: "Clear Thinking History",
113+
description:
114+
"Clears all stored thought history and branch data to free memory. " +
115+
"Use this after completing a thinking session to prevent memory buildup " +
116+
"in long-running server instances.",
117+
inputSchema: {},
118+
},
119+
async () => {
120+
return thinkingServer.clearHistory();
121+
}
122+
);
123+
109124
async function runServer() {
110125
const transport = new StdioServerTransport();
111126
await server.connect(transport);

‎src/sequentialthinking/lib.ts‎

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

15+
// Default maximum number of thoughts to retain in history.
16+
// Can be overridden via the SEQUENTIAL_THINKING_MAX_HISTORY environment variable.
17+
const DEFAULT_MAX_HISTORY = 1000;
18+
1519
export class SequentialThinkingServer {
1620
private thoughtHistory: ThoughtData[] = [];
1721
private branches: Record<string, ThoughtData[]> = {};
1822
private disableThoughtLogging: boolean;
23+
private maxHistory: number;
1924

2025
constructor() {
2126
this.disableThoughtLogging = (process.env.DISABLE_THOUGHT_LOGGING || "").toLowerCase() === "true";
27+
const envMax = parseInt(process.env.SEQUENTIAL_THINKING_MAX_HISTORY || "", 10);
28+
this.maxHistory = Number.isFinite(envMax) && envMax > 0 ? envMax : DEFAULT_MAX_HISTORY;
2229
}
2330

2431
private formatThought(thoughtData: ThoughtData): string {
@@ -49,6 +56,27 @@ export class SequentialThinkingServer {
4956
└${border}┘`;
5057
}
5158

59+
/**
60+
* Clears all stored thought history and branch data.
61+
* Useful for freeing memory in long-running sessions.
62+
*/
63+
public clearHistory(): { content: Array<{ type: "text"; text: string }> } {
64+
const previousLength = this.thoughtHistory.length;
65+
const previousBranches = Object.keys(this.branches).length;
66+
this.thoughtHistory = [];
67+
this.branches = {};
68+
return {
69+
content: [{
70+
type: "text" as const,
71+
text: JSON.stringify({
72+
cleared: true,
73+
previousThoughtCount: previousLength,
74+
previousBranchCount: previousBranches
75+
}, null, 2)
76+
}]
77+
};
78+
}
79+
5280
public processThought(input: ThoughtData): { content: Array<{ type: "text"; text: string }>; isError?: boolean } {
5381
try {
5482
// Validation happens at the tool registration layer via Zod
@@ -59,6 +87,13 @@ export class SequentialThinkingServer {
5987

6088
this.thoughtHistory.push(input);
6189

90+
// Trim history when it exceeds the configured maximum to prevent
91+
// unbounded memory growth during long-running sessions (see #2912).
92+
if (this.thoughtHistory.length > this.maxHistory) {
93+
const excess = this.thoughtHistory.length - this.maxHistory;
94+
this.thoughtHistory.splice(0, excess);
95+
}
96+
6297
if (input.branchFromThought && input.branchId) {
6398
if (!this.branches[input.branchId]) {
6499
this.branches[input.branchId] = [];

0 commit comments

Comments
 (0)