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;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It describes the tool as engaging in 'step-by-step thinking' and 'creating a chain of reasoning,' which implies a cognitive process, but it doesn't disclose key behavioral traits like whether this is a read-only or mutative operation, how it handles errors, or if there are rate limits. For a tool with 7 parameters and no annotations, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded, consisting of two concise sentences that directly state the tool's purpose and method. Every sentence earns its place by explaining the core functionality without unnecessary details, making it efficient and well-structured for quick understanding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of 7 parameters, no annotations, and no output schema, the description is incomplete. It lacks details on behavioral traits, usage context, and expected outcomes, which are crucial for an AI agent to effectively invoke this tool. The description does not adequately compensate for the missing structured data, leaving significant gaps in understanding.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, meaning all parameters are documented in the input schema. The description adds no specific meaning beyond the schema, such as explaining how parameters interact or providing examples. Since the schema does the heavy lifting, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't detract.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as 'Engage in systematic step-by-step thinking to analyze complex problems, make decisions, or explore ideas,' which includes a specific verb ('engage') and resource ('thinking'). However, it doesn't explicitly distinguish this from sibling tools like 'reset_thinking' or 'get_thinking_summary,' which appear related to thinking processes, so it misses full sibling differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It mentions building thoughts sequentially but doesn't specify contexts, prerequisites, or exclusions, such as when to choose this over 'reset_thinking' or other analysis tools. This lack of explicit usage guidelines limits its helpfulness for an AI agent.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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