Skip to main content
Glama

sequential_thinking

Break down complex problems into manageable steps using structured sequential reasoning to analyze, decide, or explore ideas systematically.

Instructions

Engage in systematic step-by-step thinking to analyze complex problems, make decisions, or explore ideas. Each thought builds on the previous ones, creating a chain of reasoning.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
thoughtYesYour current thought or analysis step
reasoningNoOptional: Explain why this thought follows from previous ones
categoryNoOptional: Categorize this thought (analysis, synthesis, evaluation, etc.)
revise_stepNoOptional: Revise a previous step by its number
branch_from_stepNoOptional: Create a new reasoning branch from a specific step number
target_stepsNoOptional: Target number of thinking steps for this session
complete_thinkingNoOptional: Mark the thinking session as complete

Implementation Reference

  • Registration of the sequential_thinking MCP tool, including description, Zod input schema, and complete inline asynchronous handler function that implements step-by-step thinking logic with state persistence.
    server.tool(
      "sequential_thinking",
      "Engage in systematic step-by-step thinking to analyze complex problems, make decisions, or explore ideas. Each thought builds on the previous ones, creating a chain of reasoning.",
      {
        thought: z.string().describe("Your current thought or analysis step"),
        reasoning: z.string().optional().describe("Optional: Explain why this thought follows from previous ones"),
        category: z.string().optional().describe("Optional: Categorize this thought (analysis, synthesis, evaluation, etc.)"),
        revise_step: z.number().optional().describe("Optional: Revise a previous step by its number"),
        branch_from_step: z.number().optional().describe("Optional: Create a new reasoning branch from a specific step number"),
        target_steps: z.number().optional().describe("Optional: Target number of thinking steps for this session"),
        complete_thinking: z.boolean().optional().describe("Optional: Mark the thinking session as complete")
      },
      async ({ thought, reasoning, category, revise_step, branch_from_step, target_steps, complete_thinking }) => {
        try {
          const timestamp = new Date().toISOString();
          
          // Handle revision of existing step
          if (revise_step !== undefined) {
            const stepIndex = thinkingSession.currentSteps.findIndex(step => step.id === revise_step);
            if (stepIndex !== -1) {
              thinkingSession.currentSteps[stepIndex] = {
                ...thinkingSession.currentSteps[stepIndex],
                thought,
                reasoning,
                category,
                timestamp
              };
            } else {
              return {
                content: [{
                  type: "text",
                  text: `❌ Step ${revise_step} not found. Available steps: ${thinkingSession.currentSteps.map(s => s.id).join(', ')}`
                }]
              };
            }
          }
          // Handle branching from existing step  
          else if (branch_from_step !== undefined) {
            const branchPoint = thinkingSession.currentSteps.find(step => step.id === branch_from_step);
            if (!branchPoint) {
              return {
                content: [{
                  type: "text",
                  text: `❌ Cannot branch from step ${branch_from_step}. Step not found.`
                }]
              };
            }
            
            // Create new branch
            thinkingSession.totalSteps++;
            const newStep: ThinkingStep = {
              id: thinkingSession.totalSteps,
              thought: `[Branch from Step ${branch_from_step}] ${thought}`,
              reasoning,
              category,
              timestamp
            };
            thinkingSession.currentSteps.push(newStep);
          }
          // Add new step
          else {
            thinkingSession.totalSteps++;
            const newStep: ThinkingStep = {
              id: thinkingSession.totalSteps,
              thought,
              reasoning,
              category,
              timestamp
            };
            thinkingSession.currentSteps.push(newStep);
          }
          
          // Handle completion
          if (complete_thinking) {
            thinkingSession.isComplete = true;
            thinkingSession.summary = `Sequential thinking completed with ${thinkingSession.currentSteps.length} steps.`;
          }
          
          // Update target if provided
          if (target_steps) {
            thinkingSession.metadata = { ...thinkingSession.metadata, target_steps };
          }
          
          // Auto-save state
          await saveThinkingState();
          
          // Generate progress report
          const progress = target_steps ? ` (${thinkingSession.currentSteps.length}/${target_steps})` : '';
          const recentSteps = thinkingSession.currentSteps.slice(-3);
          
          let content = `🧠 **Sequential Thinking${progress}**\n\n`;
          
          if (revise_step !== undefined) {
            content += `πŸ“ **Step ${revise_step} Revised**\n\n`;
          } else if (branch_from_step !== undefined) {
            content += `🌿 **New Branch from Step ${branch_from_step}**\n\n`;
          } else {
            content += `πŸ’­ **Step ${thinkingSession.totalSteps} Added**\n\n`;
          }
          
          content += "**Recent Thinking Chain:**\n";
          recentSteps.forEach(step => {
            const categoryLabel = step.category ? ` [${step.category}]` : '';
            content += `**${step.id}.${categoryLabel}** ${step.thought}\n`;
            if (step.reasoning) {
              content += `   *Reasoning: ${step.reasoning}*\n`;
            }
            content += '\n';
          });
          
          if (thinkingSession.isComplete) {
            content += `βœ… **Thinking Complete**: ${thinkingSession.summary}\n\n`;
          }
          
          content += `*Continue with next thought or use 'get_thinking_summary' to review all steps*`;
          
          return {
            content: [{
              type: "text",
              text: content
            }]
          };
          
        } catch (error) {
          return {
            content: [{
              type: "text",
              text: `❌ **Error in sequential thinking**: ${error instanceof Error ? error.message : String(error)}`
            }]
          };
        }
      }
    );
  • Core handler logic for the sequential_thinking tool: processes input to add/revise/branch thinking steps, persists session state to JSON file, generates formatted progress reports with recent steps.
    async ({ thought, reasoning, category, revise_step, branch_from_step, target_steps, complete_thinking }) => {
      try {
        const timestamp = new Date().toISOString();
        
        // Handle revision of existing step
        if (revise_step !== undefined) {
          const stepIndex = thinkingSession.currentSteps.findIndex(step => step.id === revise_step);
          if (stepIndex !== -1) {
            thinkingSession.currentSteps[stepIndex] = {
              ...thinkingSession.currentSteps[stepIndex],
              thought,
              reasoning,
              category,
              timestamp
            };
          } else {
            return {
              content: [{
                type: "text",
                text: `❌ Step ${revise_step} not found. Available steps: ${thinkingSession.currentSteps.map(s => s.id).join(', ')}`
              }]
            };
          }
        }
        // Handle branching from existing step  
        else if (branch_from_step !== undefined) {
          const branchPoint = thinkingSession.currentSteps.find(step => step.id === branch_from_step);
          if (!branchPoint) {
            return {
              content: [{
                type: "text",
                text: `❌ Cannot branch from step ${branch_from_step}. Step not found.`
              }]
            };
          }
          
          // Create new branch
          thinkingSession.totalSteps++;
          const newStep: ThinkingStep = {
            id: thinkingSession.totalSteps,
            thought: `[Branch from Step ${branch_from_step}] ${thought}`,
            reasoning,
            category,
            timestamp
          };
          thinkingSession.currentSteps.push(newStep);
        }
        // Add new step
        else {
          thinkingSession.totalSteps++;
          const newStep: ThinkingStep = {
            id: thinkingSession.totalSteps,
            thought,
            reasoning,
            category,
            timestamp
          };
          thinkingSession.currentSteps.push(newStep);
        }
        
        // Handle completion
        if (complete_thinking) {
          thinkingSession.isComplete = true;
          thinkingSession.summary = `Sequential thinking completed with ${thinkingSession.currentSteps.length} steps.`;
        }
        
        // Update target if provided
        if (target_steps) {
          thinkingSession.metadata = { ...thinkingSession.metadata, target_steps };
        }
        
        // Auto-save state
        await saveThinkingState();
        
        // Generate progress report
        const progress = target_steps ? ` (${thinkingSession.currentSteps.length}/${target_steps})` : '';
        const recentSteps = thinkingSession.currentSteps.slice(-3);
        
        let content = `🧠 **Sequential Thinking${progress}**\n\n`;
        
        if (revise_step !== undefined) {
          content += `πŸ“ **Step ${revise_step} Revised**\n\n`;
        } else if (branch_from_step !== undefined) {
          content += `🌿 **New Branch from Step ${branch_from_step}**\n\n`;
        } else {
          content += `πŸ’­ **Step ${thinkingSession.totalSteps} Added**\n\n`;
        }
        
        content += "**Recent Thinking Chain:**\n";
        recentSteps.forEach(step => {
          const categoryLabel = step.category ? ` [${step.category}]` : '';
          content += `**${step.id}.${categoryLabel}** ${step.thought}\n`;
          if (step.reasoning) {
            content += `   *Reasoning: ${step.reasoning}*\n`;
          }
          content += '\n';
        });
        
        if (thinkingSession.isComplete) {
          content += `βœ… **Thinking Complete**: ${thinkingSession.summary}\n\n`;
        }
        
        content += `*Continue with next thought or use 'get_thinking_summary' to review all steps*`;
        
        return {
          content: [{
            type: "text",
            text: content
          }]
        };
        
      } catch (error) {
        return {
          content: [{
            type: "text",
            text: `❌ **Error in sequential thinking**: ${error instanceof Error ? error.message : String(error)}`
          }]
        };
      }
    }
  • Zod schema defining input parameters for the sequential_thinking tool.
    {
      thought: z.string().describe("Your current thought or analysis step"),
      reasoning: z.string().optional().describe("Optional: Explain why this thought follows from previous ones"),
      category: z.string().optional().describe("Optional: Categorize this thought (analysis, synthesis, evaluation, etc.)"),
      revise_step: z.number().optional().describe("Optional: Revise a previous step by its number"),
      branch_from_step: z.number().optional().describe("Optional: Create a new reasoning branch from a specific step number"),
      target_steps: z.number().optional().describe("Optional: Target number of thinking steps for this session"),
      complete_thinking: z.boolean().optional().describe("Optional: Mark the thinking session as complete")
  • TypeScript interfaces defining ThinkingStep and ThinkingSession structures used by the sequential_thinking tool for state management.
    interface ThinkingStep {
      id: number;
      thought: string;
      reasoning?: string;
      timestamp: string;
      category?: string;
    }
    
    interface ThinkingSession {
      currentSteps: ThinkingStep[];
      totalSteps: number;
      isComplete: boolean;
      summary?: string;
      metadata?: Record<string, any>;
      pdfContext?: {
        filename?: string;
        content?: string;
        metadata?: Record<string, any>;
      };
    }
    
    let thinkingSession: ThinkingSession = {
      currentSteps: [],
      totalSteps: 0,
      isComplete: false
    };
  • Persistent storage helper functions for saving and loading the thinking session state to/from a JSON file in user home directory.
    const STORAGE_FILE = path.join(os.homedir(), '.mcp-sequential-thinking.json');
    
    async function initializeStorage() {
      try {
        const data = await fs.readFile(STORAGE_FILE, 'utf-8');
        const saved = JSON.parse(data);
        thinkingSession = { ...thinkingSession, ...saved };
        console.error(`LOADED: thinking state: ${thinkingSession.currentSteps.length} steps`);
      } catch (error) {
        console.error("INIT: Starting with fresh thinking state");
      }
    }
    
    async function saveThinkingState() {
      try {
        await fs.writeFile(STORAGE_FILE, JSON.stringify(thinkingSession, null, 2));
      } catch (error) {
        console.error("⚠️ Failed to save thinking state:", error);
      }
    }
    
    async function loadThinkingState() {
      return thinkingSession;
    }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/multiluca2020/visum-thinker-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server