fix(sequential-thinking): convert to modern TypeScript SDK APIs (#3014)

* fix(sequential-thinking): convert to modern TypeScript SDK APIs

Convert the sequential-thinking server to use the modern McpServer API
instead of the low-level Server API.

Key changes:
- Replace Server with McpServer from @modelcontextprotocol/sdk/server/mcp.js
- Use registerTool() method instead of manual request handlers
- Use Zod schemas directly in inputSchema/outputSchema
- Add structuredContent to tool responses
- Fix type literals to use 'as const' assertions

The modern API provides:
- Less boilerplate code
- Better type safety with Zod
- More declarative tool registration
- Cleaner, more maintainable code

* fix: exclude test files from TypeScript build

Add exclude for test files and vitest.config.ts to tsconfig

* refactor: remove redundant validation now handled by Zod

Zod schema already validates all required fields and types. Removed
validateThoughtData() method and kept only business logic validation
(adjusting totalThoughts if needed).

* fix(sequentialthinking): add Zod validation to processThought method

The modern API migration removed manual validation from processThought(),
but tests call this method directly, bypassing the Zod validation in the
tool registration layer. This commit adds Zod validation directly in the
processThought() method to ensure validation works both when called via
MCP and when called directly (e.g., in tests).

Also improves error message formatting to match the expected error
messages in the tests.

* refactor: simplify by removing redundant validation

Since processThought() is only called through the tool registration in
production, validation always happens via Zod schemas at that layer.
Removed redundant validation logic from processThought() and updated
tests to reflect this architectural decision.

Changes:
- Remove Zod validation from processThought() method
- Accept ThoughtData type instead of unknown
- Remove 10 validation tests that are now handled at tool registration
- Add comment explaining validation approach
This commit is contained in:
adam jones 2025-11-20 19:05:30 +00:00 • committed by GitHub
commit 88a2ac4360
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 76 additions and 271 deletions

View file

@ -22,107 +22,8 @@ describe('SequentialThinkingServer', () => {
server = new SequentialThinkingServer(); server = new SequentialThinkingServer();
}); });
describe('processThought - validation', () => { // Note: Input validation tests removed - validation now happens at the tool
it('should reject input with missing thought', () => { // registration layer via Zod schemas before processThought is called
const input = {
thoughtNumber: 1,
totalThoughts: 3,
nextThoughtNeeded: true
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid thought');
});
it('should reject input with non-string thought', () => {
const input = {
thought: 123,
thoughtNumber: 1,
totalThoughts: 3,
nextThoughtNeeded: true
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid thought');
});
it('should reject input with missing thoughtNumber', () => {
const input = {
thought: 'Test thought',
totalThoughts: 3,
nextThoughtNeeded: true
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid thoughtNumber');
});
it('should reject input with non-number thoughtNumber', () => {
const input = {
thought: 'Test thought',
thoughtNumber: '1',
totalThoughts: 3,
nextThoughtNeeded: true
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid thoughtNumber');
});
it('should reject input with missing totalThoughts', () => {
const input = {
thought: 'Test thought',
thoughtNumber: 1,
nextThoughtNeeded: true
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid totalThoughts');
});
it('should reject input with non-number totalThoughts', () => {
const input = {
thought: 'Test thought',
thoughtNumber: 1,
totalThoughts: '3',
nextThoughtNeeded: true
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid totalThoughts');
});
it('should reject input with missing nextThoughtNeeded', () => {
const input = {
thought: 'Test thought',
thoughtNumber: 1,
totalThoughts: 3
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid nextThoughtNeeded');
});
it('should reject input with non-boolean nextThoughtNeeded', () => {
const input = {
thought: 'Test thought',
thoughtNumber: 1,
totalThoughts: 3,
nextThoughtNeeded: 'true'
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid nextThoughtNeeded');
});
});
describe('processThought - valid inputs', () => { describe('processThought - valid inputs', () => {
it('should accept valid basic thought', () => { it('should accept valid basic thought', () => {
@ -275,19 +176,6 @@ describe('SequentialThinkingServer', () => {
}); });
describe('processThought - edge cases', () => { describe('processThought - edge cases', () => {
it('should reject empty thought string', () => {
const input = {
thought: '',
thoughtNumber: 1,
totalThoughts: 1,
nextThoughtNeeded: false
};
const result = server.processThought(input);
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('Invalid thought');
});
it('should handle very long thought strings', () => { it('should handle very long thought strings', () => {
const input = { const input = {
thought: 'a'.repeat(10000), thought: 'a'.repeat(10000),
@ -349,25 +237,6 @@ describe('SequentialThinkingServer', () => {
expect(result.content[0]).toHaveProperty('text'); expect(result.content[0]).toHaveProperty('text');
}); });
it('should return correct error structure on failure', () => {
const input = {
thought: 'Test',
thoughtNumber: 1,
totalThoughts: 1
// missing nextThoughtNeeded
};
const result = server.processThought(input);
expect(result).toHaveProperty('isError', true);
expect(result).toHaveProperty('content');
expect(Array.isArray(result.content)).toBe(true);
const errorData = JSON.parse(result.content[0].text);
expect(errorData).toHaveProperty('error');
expect(errorData).toHaveProperty('status', 'failed');
});
it('should return valid JSON in response', () => { it('should return valid JSON in response', () => {
const input = { const input = {
thought: 'Test thought', thought: 'Test thought',

View file

@ -1,16 +1,21 @@
#!/usr/bin/env node #!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { import { z } from "zod";
CallToolRequestSchema,
ListToolsRequestSchema,
Tool,
} from "@modelcontextprotocol/sdk/types.js";
import { SequentialThinkingServer } from './lib.js'; import { SequentialThinkingServer } from './lib.js';
const SEQUENTIAL_THINKING_TOOL: Tool = { const server = new McpServer({
name: "sequentialthinking", name: "sequential-thinking-server",
version: "0.2.0",
});
const thinkingServer = new SequentialThinkingServer();
server.registerTool(
"sequentialthinking",
{
title: "Sequential Thinking",
description: `A detailed tool for dynamic and reflective problem-solving through thoughts. description: `A detailed tool for dynamic and reflective problem-solving through thoughts.
This tool helps analyze problems through a flexible thinking process that can adapt and evolve. This tool helps analyze problems through a flexible thinking process that can adapt and evolve.
Each thought can build on, question, or revise previous insights as understanding deepens. Each thought can build on, question, or revise previous insights as understanding deepens.
@ -66,84 +71,40 @@ You should:
10. Provide a single, ideally correct answer as the final output 10. Provide a single, ideally correct answer as the final output
11. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`, 11. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`,
inputSchema: { inputSchema: {
type: "object", thought: z.string().describe("Your current thinking step"),
properties: { nextThoughtNeeded: z.boolean().describe("Whether another thought step is needed"),
thought: { thoughtNumber: z.number().int().min(1).describe("Current thought number (numeric value, e.g., 1, 2, 3)"),
type: "string", totalThoughts: z.number().int().min(1).describe("Estimated total thoughts needed (numeric value, e.g., 5, 10)"),
description: "Your current thinking step" isRevision: z.boolean().optional().describe("Whether this revises previous thinking"),
revisesThought: z.number().int().min(1).optional().describe("Which thought is being reconsidered"),
branchFromThought: z.number().int().min(1).optional().describe("Branching point thought number"),
branchId: z.string().optional().describe("Branch identifier"),
needsMoreThoughts: z.boolean().optional().describe("If more thoughts are needed")
}, },
nextThoughtNeeded: { outputSchema: {
type: "boolean", thoughtNumber: z.number(),
description: "Whether another thought step is needed" totalThoughts: z.number(),
nextThoughtNeeded: z.boolean(),
branches: z.array(z.string()),
thoughtHistoryLength: z.number()
}, },
thoughtNumber: {
type: "integer",
description: "Current thought number (numeric value, e.g., 1, 2, 3)",
minimum: 1
}, },
totalThoughts: { async (args) => {
type: "integer", const result = thinkingServer.processThought(args);
description: "Estimated total thoughts needed (numeric value, e.g., 5, 10)",
minimum: 1
},
isRevision: {
type: "boolean",
description: "Whether this revises previous thinking"
},
revisesThought: {
type: "integer",
description: "Which thought is being reconsidered",
minimum: 1
},
branchFromThought: {
type: "integer",
description: "Branching point thought number",
minimum: 1
},
branchId: {
type: "string",
description: "Branch identifier"
},
needsMoreThoughts: {
type: "boolean",
description: "If more thoughts are needed"
}
},
required: ["thought", "nextThoughtNeeded", "thoughtNumber", "totalThoughts"]
}
};
const server = new Server( if (result.isError) {
{ return result;
name: "sequential-thinking-server",
version: "0.2.0",
},
{
capabilities: {
tools: {},
},
} }
);
const thinkingServer = new SequentialThinkingServer(); // Parse the JSON response to get structured content
const parsedContent = JSON.parse(result.content[0].text);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [SEQUENTIAL_THINKING_TOOL],
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "sequentialthinking") {
return thinkingServer.processThought(request.params.arguments);
}
return { return {
content: [{ content: result.content,
type: "text", structuredContent: parsedContent
text: `Unknown tool: ${request.params.name}`
}],
isError: true
}; };
}); }
);
async function runServer() { async function runServer() {
const transport = new StdioServerTransport(); const transport = new StdioServerTransport();

View file

@ -21,35 +21,6 @@ export class SequentialThinkingServer {
this.disableThoughtLogging = (process.env.DISABLE_THOUGHT_LOGGING || "").toLowerCase() === "true"; this.disableThoughtLogging = (process.env.DISABLE_THOUGHT_LOGGING || "").toLowerCase() === "true";
} }
private validateThoughtData(input: unknown): ThoughtData {
const data = input as Record<string, unknown>;
if (!data.thought || typeof data.thought !== 'string') {
throw new Error('Invalid thought: must be a string');
}
if (!data.thoughtNumber || typeof data.thoughtNumber !== 'number') {
throw new Error('Invalid thoughtNumber: must be a number');
}
if (!data.totalThoughts || typeof data.totalThoughts !== 'number') {
throw new Error('Invalid totalThoughts: must be a number');
}
if (typeof data.nextThoughtNeeded !== 'boolean') {
throw new Error('Invalid nextThoughtNeeded: must be a boolean');
}
return {
thought: data.thought,
thoughtNumber: data.thoughtNumber,
totalThoughts: data.totalThoughts,
nextThoughtNeeded: data.nextThoughtNeeded,
isRevision: data.isRevision as boolean | undefined,
revisesThought: data.revisesThought as number | undefined,
branchFromThought: data.branchFromThought as number | undefined,
branchId: data.branchId as string | undefined,
needsMoreThoughts: data.needsMoreThoughts as boolean | undefined,
};
}
private formatThought(thoughtData: ThoughtData): string { private formatThought(thoughtData: ThoughtData): string {
const { thoughtNumber, totalThoughts, thought, isRevision, revisesThought, branchFromThought, branchId } = thoughtData; const { thoughtNumber, totalThoughts, thought, isRevision, revisesThought, branchFromThought, branchId } = thoughtData;
@ -78,35 +49,35 @@ export class SequentialThinkingServer {
└${border}┘`; └${border}┘`;
} }
public processThought(input: unknown): { content: Array<{ type: string; text: string }>; isError?: boolean } { public processThought(input: ThoughtData): { content: Array<{ type: "text"; text: string }>; isError?: boolean } {
try { try {
const validatedInput = this.validateThoughtData(input); // Validation happens at the tool registration layer via Zod
// Adjust totalThoughts if thoughtNumber exceeds it
if (validatedInput.thoughtNumber > validatedInput.totalThoughts) { if (input.thoughtNumber > input.totalThoughts) {
validatedInput.totalThoughts = validatedInput.thoughtNumber; input.totalThoughts = input.thoughtNumber;
} }
this.thoughtHistory.push(validatedInput); this.thoughtHistory.push(input);
if (validatedInput.branchFromThought && validatedInput.branchId) { if (input.branchFromThought && input.branchId) {
if (!this.branches[validatedInput.branchId]) { if (!this.branches[input.branchId]) {
this.branches[validatedInput.branchId] = []; this.branches[input.branchId] = [];
} }
this.branches[validatedInput.branchId].push(validatedInput); this.branches[input.branchId].push(input);
} }
if (!this.disableThoughtLogging) { if (!this.disableThoughtLogging) {
const formattedThought = this.formatThought(validatedInput); const formattedThought = this.formatThought(input);
console.error(formattedThought); console.error(formattedThought);
} }
return { return {
content: [{ content: [{
type: "text", type: "text" as const,
text: JSON.stringify({ text: JSON.stringify({
thoughtNumber: validatedInput.thoughtNumber, thoughtNumber: input.thoughtNumber,
totalThoughts: validatedInput.totalThoughts, totalThoughts: input.totalThoughts,
nextThoughtNeeded: validatedInput.nextThoughtNeeded, nextThoughtNeeded: input.nextThoughtNeeded,
branches: Object.keys(this.branches), branches: Object.keys(this.branches),
thoughtHistoryLength: this.thoughtHistory.length thoughtHistoryLength: this.thoughtHistory.length
}, null, 2) }, null, 2)
@ -115,7 +86,7 @@ export class SequentialThinkingServer {
} catch (error) { } catch (error) {
return { return {
content: [{ content: [{
type: "text", type: "text" as const,
text: JSON.stringify({ text: JSON.stringify({
error: error instanceof Error ? error.message : String(error), error: error instanceof Error ? error.message : String(error),
status: 'failed' status: 'failed'

View file

@ -2,9 +2,13 @@
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist",
"rootDir": ".", "rootDir": "."
"moduleResolution": "NodeNext",
"module": "NodeNext"
}, },
"include": ["./**/*.ts"] "include": [
"./**/*.ts"
],
"exclude": [
"**/*.test.ts",
"vitest.config.ts"
]
} }