# Directory Structure
```
├── .changeset
│ ├── config.json
│ └── README.md
├── .gitignore
├── .prettierignore
├── .prettierrc
├── CHANGELOG.md
├── LICENSE
├── package.json
├── pnpm-lock.yaml
├── README.md
├── renovate.json
├── src
│ ├── index.ts
│ ├── schema.ts
│ └── types.ts
└── tsconfig.json
```
# Files
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
```
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock
```
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
```
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 70,
"proseWrap": "always"
}
```
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
# Dependencies
node_modules/
.pnpm-store/
# Build output
dist/
build/
# Environment variables
.env
.env.local
.env.*.local
# IDE
.vscode/
.idea/
*.swp
*.swo
# Logs
*.log
npm-debug.log*
pnpm-debug.log*
# Testing
coverage/
# Database files
*.db
*.db-journal
# OS
.DS_Store
Thumbs.db
```
--------------------------------------------------------------------------------
/.changeset/README.md:
--------------------------------------------------------------------------------
```markdown
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
# mcp-sequentialthinking-tools
An adaptation of the
[MCP Sequential Thinking Server](https://github.com/modelcontextprotocol/servers/blob/main/src/sequentialthinking/index.ts)
designed to guide tool usage in problem-solving. This server helps
break down complex problems into manageable steps and provides
recommendations for which MCP tools would be most effective at each
stage.
<a href="https://glama.ai/mcp/servers/zl990kfusy">
<img width="380" height="200" src="https://glama.ai/mcp/servers/zl990kfusy/badge" />
</a>
A Model Context Protocol (MCP) server that combines sequential
thinking with intelligent tool suggestions. For each step in the
problem-solving process, it provides confidence-scored recommendations
for which tools to use, along with rationale for why each tool would
be appropriate.
## Features
- 🤔 Dynamic and reflective problem-solving through sequential
thoughts
- 🔄 Flexible thinking process that adapts and evolves
- 🌳 Support for branching and revision of thoughts
- 🛠️ Intelligent tool recommendations for each step
- 📊 Confidence scoring for tool suggestions
- 🔍 Detailed rationale for tool recommendations
- 📝 Step tracking with expected outcomes
- 🔄 Progress monitoring with previous and remaining steps
- 🎯 Alternative tool suggestions for each step
## How It Works
This server analyses each step of your thought process and recommends
appropriate MCP tools to help accomplish the task. Each recommendation
includes:
- A confidence score (0-1) indicating how well the tool matches the
current need
- A clear rationale explaining why the tool would be helpful
- A priority level to suggest tool execution order
- Alternative tools that could also be used
The server works with any MCP tools available in your environment. It
provides recommendations based on the current step's requirements, but
the actual tool execution is handled by the consumer (like Claude).
## Example Usage
Here's an example of how the server guides tool usage:
```json
{
"thought": "Initial research step to understand what universal reactivity means in Svelte 5",
"current_step": {
"step_description": "Gather initial information about Svelte 5's universal reactivity",
"expected_outcome": "Clear understanding of universal reactivity concept",
"recommended_tools": [
{
"tool_name": "search_docs",
"confidence": 0.9,
"rationale": "Search Svelte documentation for official information",
"priority": 1
},
{
"tool_name": "tavily_search",
"confidence": 0.8,
"rationale": "Get additional context from reliable sources",
"priority": 2
}
],
"next_step_conditions": [
"Verify information accuracy",
"Look for implementation details"
]
},
"thought_number": 1,
"total_thoughts": 5,
"next_thought_needed": true
}
```
The server tracks your progress and supports:
- Creating branches to explore different approaches
- Revising previous thoughts with new information
- Maintaining context across multiple steps
- Suggesting next steps based on current findings
## Configuration
This server requires configuration through your MCP client. Here are
examples for different environments:
### Cline Configuration
Add this to your Cline MCP settings:
```json
{
"mcpServers": {
"mcp-sequentialthinking-tools": {
"command": "npx",
"args": ["-y", "mcp-sequentialthinking-tools"]
}
}
}
```
### Claude Desktop with WSL Configuration
For WSL environments, add this to your Claude Desktop configuration:
```json
{
"mcpServers": {
"mcp-sequentialthinking-tools": {
"command": "wsl.exe",
"args": [
"bash",
"-c",
"source ~/.nvm/nvm.sh && /home/username/.nvm/versions/node/v20.12.1/bin/npx mcp-sequentialthinking-tools"
]
}
}
}
```
## API
The server implements a single MCP tool with configurable parameters:
### sequentialthinking_tools
A tool for dynamic and reflective problem-solving through thoughts,
with intelligent tool recommendations.
Parameters:
- `thought` (string, required): Your current thinking step
- `next_thought_needed` (boolean, required): Whether another thought
step is needed
- `thought_number` (integer, required): Current thought number
- `total_thoughts` (integer, required): Estimated total thoughts
needed
- `is_revision` (boolean, optional): Whether this revises previous
thinking
- `revises_thought` (integer, optional): Which thought is being
reconsidered
- `branch_from_thought` (integer, optional): Branching point thought
number
- `branch_id` (string, optional): Branch identifier
- `needs_more_thoughts` (boolean, optional): If more thoughts are
needed
- `current_step` (object, optional): Current step recommendation with:
- `step_description`: What needs to be done
- `recommended_tools`: Array of tool recommendations with confidence
scores
- `expected_outcome`: What to expect from this step
- `next_step_conditions`: Conditions for next step
- `previous_steps` (array, optional): Steps already recommended
- `remaining_steps` (array, optional): High-level descriptions of
upcoming steps
## Development
### Setup
1. Clone the repository
2. Install dependencies:
```bash
pnpm install
```
3. Build the project:
```bash
pnpm build
```
4. Run in development mode:
```bash
pnpm dev
```
### Publishing
The project uses changesets for version management. To publish:
1. Create a changeset:
```bash
pnpm changeset
```
2. Version the package:
```bash
pnpm changeset version
```
3. Publish to npm:
```bash
pnpm release
```
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
MIT License - see the [LICENSE](LICENSE) file for details.
## Acknowledgments
- Built on the
[Model Context Protocol](https://github.com/modelcontextprotocol)
- Adapted from the
[MCP Sequential Thinking Server](https://github.com/modelcontextprotocol/servers/blob/main/src/sequentialthinking/index.ts)
```
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
```json
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:recommended"
]
}
```
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
```markdown
# mcp-sequentialthinking-tools
## 0.0.2
### Patch Changes
- add glama badge
## 0.0.1
### Patch Changes
- init
```
--------------------------------------------------------------------------------
/.changeset/config.json:
--------------------------------------------------------------------------------
```json
{
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
```
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"outDir": "dist",
"rootDir": "src",
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
```
--------------------------------------------------------------------------------
/src/types.ts:
--------------------------------------------------------------------------------
```typescript
import { Tool } from '@modelcontextprotocol/sdk/types.js';
export interface ToolRecommendation {
tool_name: string;
confidence: number; // 0-1 indicating how confident we are this tool is appropriate
rationale: string; // Why this tool is recommended
priority: number; // Order in the recommendation sequence
suggested_inputs?: Record<string, unknown>; // Optional suggested parameters
alternatives?: string[]; // Alternative tools that could be used
}
export interface StepRecommendation {
step_description: string; // What needs to be done
recommended_tools: ToolRecommendation[]; // Tools recommended for this step
expected_outcome: string; // What to expect from this step
next_step_conditions?: string[]; // Conditions to consider for the next step
}
export interface ThoughtData {
thought: string;
thought_number: number;
total_thoughts: number;
is_revision?: boolean;
revises_thought?: number;
branch_from_thought?: number;
branch_id?: string;
needs_more_thoughts?: boolean;
next_thought_needed: boolean;
// Recommendation-related fields
current_step?: StepRecommendation; // Current step being considered
previous_steps?: StepRecommendation[]; // Steps already recommended
remaining_steps?: string[]; // High-level descriptions of upcoming steps
}
export interface ServerConfig {
available_tools: Map<string, Tool>;
}
```
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
```json
{
"name": "mcp-sequentialthinking-tools",
"version": "0.0.2",
"description": "MCP server for Sequential Thinking Tools",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
"mcp-sequentialthinking-tools": "./dist/index.js"
},
"files": [
"dist",
"README.md",
"LICENSE"
],
"scripts": {
"build": "tsc && chmod +x dist/index.js",
"start": "node dist/index.js",
"dev": "npx @modelcontextprotocol/inspector dist/index.js",
"changeset": "changeset",
"version": "changeset version",
"release": "pnpm run build && changeset publish"
},
"keywords": [
"mcp",
"model-context-protocol",
"sequential-thinking",
"problem-solving",
"tool-recommendation",
"decision-making",
"thought-process",
"step-by-step",
"llm",
"ai",
"branching-thoughts",
"thought-revision",
"tool-analysis",
"problem-breakdown",
"solution-planning",
"adaptive-thinking",
"reflective-analysis",
"tool-confidence"
],
"author": "Scott Spence",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/spences10/mcp-sequentialthinking-tools.git"
},
"bugs": {
"url": "https://github.com/spences10/mcp-sequentialthinking-tools/issues"
},
"homepage": "https://github.com/spences10/mcp-sequentialthinking-tools#readme",
"dependencies": {
"@modelcontextprotocol/sdk": "1.6.1",
"chalk": "^5.4.1"
},
"devDependencies": {
"@changesets/cli": "^2.28.1",
"@types/node": "^22.13.10",
"typescript": "^5.8.2"
}
}
```
--------------------------------------------------------------------------------
/src/schema.ts:
--------------------------------------------------------------------------------
```typescript
import { Tool } from '@modelcontextprotocol/sdk/types.js';
const TOOL_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.
Each thought can build on, question, or revise previous insights as understanding deepens.
IMPORTANT: When initializing this tool, you must pass all available tools that you want the sequential thinking process to be able to use. The tool will analyze these tools and provide recommendations for their use.
When to use this tool:
- Breaking down complex problems into steps
- Planning and design with room for revision
- Analysis that might need course correction
- Problems where the full scope might not be clear initially
- Problems that require a multi-step solution
- Tasks that need to maintain context over multiple steps
- Situations where irrelevant information needs to be filtered out
- When you need guidance on which tools to use and in what order
Key features:
- You can adjust total_thoughts up or down as you progress
- You can question or revise previous thoughts
- You can add more thoughts even after reaching what seemed like the end
- You can express uncertainty and explore alternative approaches
- Not every thought needs to build linearly - you can branch or backtrack
- Generates a solution hypothesis
- Verifies the hypothesis based on the Chain of Thought steps
- Recommends appropriate tools for each step
- Provides rationale for tool recommendations
- Suggests tool execution order and parameters
- Tracks previous recommendations and remaining steps
Parameters explained:
- thought: Your current thinking step, which can include:
* Regular analytical steps
* Revisions of previous thoughts
* Questions about previous decisions
* Realizations about needing more analysis
* Changes in approach
* Hypothesis generation
* Hypothesis verification
* Tool recommendations and rationale
- next_thought_needed: True if you need more thinking, even if at what seemed like the end
- thought_number: Current number in sequence (can go beyond initial total if needed)
- total_thoughts: Current estimate of thoughts needed (can be adjusted up/down)
- is_revision: A boolean indicating if this thought revises previous thinking
- revises_thought: If is_revision is true, which thought number is being reconsidered
- branch_from_thought: If branching, which thought number is the branching point
- branch_id: Identifier for the current branch (if any)
- needs_more_thoughts: If reaching end but realizing more thoughts needed
- current_step: Current step recommendation, including:
* step_description: What needs to be done
* recommended_tools: Tools recommended for this step
* expected_outcome: What to expect from this step
* next_step_conditions: Conditions to consider for the next step
- previous_steps: Steps already recommended
- remaining_steps: High-level descriptions of upcoming steps
You should:
1. Start with an initial estimate of needed thoughts, but be ready to adjust
2. Feel free to question or revise previous thoughts
3. Don't hesitate to add more thoughts if needed, even at the "end"
4. Express uncertainty when present
5. Mark thoughts that revise previous thinking or branch into new paths
6. Ignore information that is irrelevant to the current step
7. Generate a solution hypothesis when appropriate
8. Verify the hypothesis based on the Chain of Thought steps
9. Consider available tools that could help with the current step
10. Provide clear rationale for tool recommendations
11. Suggest specific tool parameters when appropriate
12. Consider alternative tools for each step
13. Track progress through the recommended steps
14. Provide a single, ideally correct answer as the final output
15. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`;
export const SEQUENTIAL_THINKING_TOOL: Tool = {
name: 'sequentialthinking_tools',
description: TOOL_DESCRIPTION,
inputSchema: {
type: 'object',
properties: {
thought: {
type: 'string',
description: 'Your current thinking step',
},
next_thought_needed: {
type: 'boolean',
description: 'Whether another thought step is needed',
},
thought_number: {
type: 'integer',
description: 'Current thought number',
minimum: 1,
},
total_thoughts: {
type: 'integer',
description: 'Estimated total thoughts needed',
minimum: 1,
},
is_revision: {
type: 'boolean',
description: 'Whether this revises previous thinking',
},
revises_thought: {
type: 'integer',
description: 'Which thought is being reconsidered',
minimum: 1,
},
branch_from_thought: {
type: 'integer',
description: 'Branching point thought number',
minimum: 1,
},
branch_id: {
type: 'string',
description: 'Branch identifier',
},
needs_more_thoughts: {
type: 'boolean',
description: 'If more thoughts are needed',
},
current_step: {
type: 'object',
description: 'Current step recommendation',
properties: {
step_description: {
type: 'string',
description: 'What needs to be done'
},
recommended_tools: {
type: 'array',
description: 'Tools recommended for this step',
items: {
type: 'object',
properties: {
tool_name: {
type: 'string',
description: 'Name of the tool being recommended'
},
confidence: {
type: 'number',
description: '0-1 indicating confidence in recommendation',
minimum: 0,
maximum: 1
},
rationale: {
type: 'string',
description: 'Why this tool is recommended'
},
priority: {
type: 'number',
description: 'Order in the recommendation sequence'
},
suggested_inputs: {
type: 'object',
description: 'Optional suggested parameters'
},
alternatives: {
type: 'array',
description: 'Alternative tools that could be used',
items: {
type: 'string'
}
}
},
required: ['tool_name', 'confidence', 'rationale', 'priority']
}
},
expected_outcome: {
type: 'string',
description: 'What to expect from this step'
},
next_step_conditions: {
type: 'array',
description: 'Conditions to consider for the next step',
items: {
type: 'string'
}
}
},
required: ['step_description', 'recommended_tools', 'expected_outcome']
},
previous_steps: {
type: 'array',
description: 'Steps already recommended',
items: {
type: 'object',
properties: {
step_description: {
type: 'string',
description: 'What needs to be done'
},
recommended_tools: {
type: 'array',
description: 'Tools recommended for this step',
items: {
type: 'object',
properties: {
tool_name: {
type: 'string',
description: 'Name of the tool being recommended'
},
confidence: {
type: 'number',
description: '0-1 indicating confidence in recommendation',
minimum: 0,
maximum: 1
},
rationale: {
type: 'string',
description: 'Why this tool is recommended'
},
priority: {
type: 'number',
description: 'Order in the recommendation sequence'
},
suggested_inputs: {
type: 'object',
description: 'Optional suggested parameters'
},
alternatives: {
type: 'array',
description: 'Alternative tools that could be used',
items: {
type: 'string'
}
}
},
required: ['tool_name', 'confidence', 'rationale', 'priority']
}
},
expected_outcome: {
type: 'string',
description: 'What to expect from this step'
},
next_step_conditions: {
type: 'array',
description: 'Conditions to consider for the next step',
items: {
type: 'string'
}
}
},
required: ['step_description', 'recommended_tools', 'expected_outcome']
}
},
remaining_steps: {
type: 'array',
description: 'High-level descriptions of upcoming steps',
items: {
type: 'string'
}
}
},
required: [
'thought',
'next_thought_needed',
'thought_number',
'total_thoughts',
],
},
};
```
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
```typescript
#!/usr/bin/env node
// adapted from https://github.com/modelcontextprotocol/servers/blob/main/src/sequentialthinking/index.ts
// for use with mcp tools
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
Tool,
} from '@modelcontextprotocol/sdk/types.js';
import chalk from 'chalk';
import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { SEQUENTIAL_THINKING_TOOL } from './schema.js';
import { ThoughtData, ToolRecommendation, StepRecommendation } from './types.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const pkg = JSON.parse(
readFileSync(join(__dirname, '..', 'package.json'), 'utf8'),
);
const { name, version } = pkg;
// Create MCP server instance with tools capability
const server = new Server(
{
name,
version,
},
{
capabilities: {
tools: {},
},
},
);
interface ServerOptions {
available_tools?: Tool[];
}
class ToolAwareSequentialThinkingServer {
private thought_history: ThoughtData[] = [];
private branches: Record<string, ThoughtData[]> = {};
private available_tools: Map<string, Tool> = new Map();
public getAvailableTools(): Tool[] {
return Array.from(this.available_tools.values());
}
constructor(options: ServerOptions = {}) {
// Always include the sequential thinking tool
const tools = [
SEQUENTIAL_THINKING_TOOL,
...(options.available_tools || []),
];
// Initialize with provided tools
tools.forEach((tool) => {
if (this.available_tools.has(tool.name)) {
console.error(
`Warning: Duplicate tool name '${tool.name}' - using first occurrence`,
);
return;
}
this.available_tools.set(tool.name, tool);
});
console.error(
'Available tools:',
Array.from(this.available_tools.keys()),
);
}
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.thought_number ||
typeof data.thought_number !== 'number'
) {
throw new Error('Invalid thought_number: must be a number');
}
if (
!data.total_thoughts ||
typeof data.total_thoughts !== 'number'
) {
throw new Error('Invalid total_thoughts: must be a number');
}
if (typeof data.next_thought_needed !== 'boolean') {
throw new Error(
'Invalid next_thought_needed: must be a boolean',
);
}
const validated: ThoughtData = {
thought: data.thought,
thought_number: data.thought_number,
total_thoughts: data.total_thoughts,
next_thought_needed: data.next_thought_needed,
is_revision: data.is_revision as boolean | undefined,
revises_thought: data.revises_thought as number | undefined,
branch_from_thought: data.branch_from_thought as
| number
| undefined,
branch_id: data.branch_id as string | undefined,
needs_more_thoughts: data.needs_more_thoughts as
| boolean
| undefined,
};
// Validate recommendation-related fields if present
if (data.current_step) {
validated.current_step = data.current_step as StepRecommendation;
}
if (data.previous_steps) {
if (!Array.isArray(data.previous_steps)) {
throw new Error('previous_steps must be an array');
}
validated.previous_steps = data.previous_steps as StepRecommendation[];
}
if (data.remaining_steps) {
if (!Array.isArray(data.remaining_steps)) {
throw new Error('remaining_steps must be an array');
}
validated.remaining_steps = data.remaining_steps as string[];
}
return validated;
}
private formatRecommendation(step: StepRecommendation): string {
const tools = step.recommended_tools
.map((tool) => {
const alternatives = tool.alternatives?.length
? ` (alternatives: ${tool.alternatives.join(', ')})`
: '';
const inputs = tool.suggested_inputs
? `\n Suggested inputs: ${JSON.stringify(tool.suggested_inputs)}`
: '';
return ` - ${tool.tool_name} (priority: ${tool.priority})${alternatives}
Rationale: ${tool.rationale}${inputs}`;
})
.join('\n');
return `Step: ${step.step_description}
Recommended Tools:
${tools}
Expected Outcome: ${step.expected_outcome}${
step.next_step_conditions
? `\nConditions for next step:\n - ${step.next_step_conditions.join('\n - ')}`
: ''
}`;
}
private formatThought(thoughtData: ThoughtData): string {
const {
thought_number,
total_thoughts,
thought,
is_revision,
revises_thought,
branch_from_thought,
branch_id,
current_step,
} = thoughtData;
let prefix = '';
let context = '';
if (is_revision) {
prefix = chalk.yellow('🔄 Revision');
context = ` (revising thought ${revises_thought})`;
} else if (branch_from_thought) {
prefix = chalk.green('🌿 Branch');
context = ` (from thought ${branch_from_thought}, ID: ${branch_id})`;
} else {
prefix = chalk.blue('💭 Thought');
context = '';
}
const header = `${prefix} ${thought_number}/${total_thoughts}${context}`;
let content = thought;
// Add recommendation information if present
if (current_step) {
content = `${thought}\n\nRecommendation:\n${this.formatRecommendation(current_step)}`;
}
const border = '─'.repeat(
Math.max(header.length, content.length) + 4,
);
return `
┌${border}┐
│ ${header} │
├${border}┤
│ ${content.padEnd(border.length - 2)} │
└${border}┘`;
}
public async processThought(input: unknown): Promise<{
content: Array<{ type: string; text: string }>;
isError?: boolean;
}> {
try {
const validatedInput = this.validateThoughtData(input);
if (
validatedInput.thought_number > validatedInput.total_thoughts
) {
validatedInput.total_thoughts = validatedInput.thought_number;
}
// Store the current step in thought history
if (validatedInput.current_step) {
if (!validatedInput.previous_steps) {
validatedInput.previous_steps = [];
}
validatedInput.previous_steps.push(validatedInput.current_step);
}
this.thought_history.push(validatedInput);
if (
validatedInput.branch_from_thought &&
validatedInput.branch_id
) {
if (!this.branches[validatedInput.branch_id]) {
this.branches[validatedInput.branch_id] = [];
}
this.branches[validatedInput.branch_id].push(validatedInput);
}
const formattedThought = this.formatThought(validatedInput);
console.error(formattedThought);
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
thought_number: validatedInput.thought_number,
total_thoughts: validatedInput.total_thoughts,
next_thought_needed:
validatedInput.next_thought_needed,
branches: Object.keys(this.branches),
thought_history_length: this.thought_history.length,
current_step: validatedInput.current_step,
previous_steps: validatedInput.previous_steps,
remaining_steps: validatedInput.remaining_steps,
},
null,
2,
),
},
],
};
} catch (error) {
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
error:
error instanceof Error
? error.message
: String(error),
status: 'failed',
},
null,
2,
),
},
],
isError: true,
};
}
}
private async execute_tool(
tool: Tool,
inputs: Record<string, unknown>,
): Promise<unknown> {
try {
// Call the tool through the server's request method
const response = await server.request(
{
method: 'callTool',
params: {
name: tool.name,
arguments: inputs,
},
},
CallToolRequestSchema,
);
// Extract the result from the response
if (
'content' in response &&
Array.isArray(response.content) &&
response.content.length > 0
) {
const content = response.content[0];
if ('text' in content && typeof content.text === 'string') {
try {
// Attempt to parse JSON result
return JSON.parse(content.text);
} catch {
// If not JSON, return as-is
return content.text;
}
}
}
throw new Error('Tool execution returned no content');
} catch (error) {
throw new Error(
`Failed to execute tool ${tool.name}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
}
const thinkingServer = new ToolAwareSequentialThinkingServer({
available_tools: [],
});
// Expose all available tools
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: thinkingServer.getAvailableTools(),
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'sequentialthinking_tools') {
return thinkingServer.processThought(request.params.arguments);
}
return {
content: [
{
type: 'text',
text: `Unknown tool: ${request.params.name}`,
},
],
isError: true,
};
});
async function runServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('Sequential Thinking MCP Server running on stdio');
}
runServer().catch((error) => {
console.error('Fatal error running server:', error);
process.exit(1);
});
```