|
| 1 | +#!/usr/bin/env -S uv run --script |
| 2 | +# /// script |
| 3 | +# requires-python = ">=3.10" |
| 4 | +# dependencies = ["mcp>=0.1.0"] |
| 5 | +# |
| 6 | +# [project.optional-dependencies] |
| 7 | +# dev = ["pytest>=7.0", "pytest-asyncio>=0.21.0"] |
| 8 | +# /// |
| 9 | +""" |
| 10 | +`mcp_sequential_thinking.py` – **Model Context Protocol** server for dynamic, |
| 11 | +reflective problem-solving via a single `sequentialthinking` tool. |
| 12 | +
|
| 13 | +This server is a Python port of the official TypeScript ``sequential-thinking`` |
| 14 | +MCP server. It exposes one tool that lets a model record an evolving chain of |
| 15 | +thoughts, branch off to explore alternatives, revise earlier steps, and adjust |
| 16 | +the planned thought count on the fly. The server keeps the running history in |
| 17 | +memory for the lifetime of the process. |
| 18 | +
|
| 19 | +Tool exposed to LLMs |
| 20 | +-------------------- |
| 21 | +* **`sequentialthinking`** – Record one step in an iterative thinking process. |
| 22 | +
|
| 23 | +Environment variables |
| 24 | +--------------------- |
| 25 | +* ``DISABLE_THOUGHT_LOGGING`` – When set (case-insensitive) to ``"true"``, the |
| 26 | + server suppresses the formatted thought box that is otherwise written to |
| 27 | + stderr. All other behavior is unchanged. |
| 28 | +
|
| 29 | +String coercion (issue #3856) |
| 30 | +----------------------------- |
| 31 | +Some MCP clients (notably Claude Code) serialize numeric and boolean tool |
| 32 | +arguments as JSON strings. The original npm-released TypeScript server |
| 33 | +rejects those payloads. This Python port deliberately accepts BOTH the |
| 34 | +native Python type AND a string that coerces (``"1"`` → ``1``, |
| 35 | +``"true"`` → ``True``) for every numeric/boolean parameter, using pydantic |
| 36 | +``BeforeValidator`` annotations. |
| 37 | +
|
| 38 | +Quick start |
| 39 | +----------- |
| 40 | +```bash |
| 41 | +chmod +x mcp_sequential_thinking.py |
| 42 | +
|
| 43 | +# Run as MCP server (stdio transport) |
| 44 | +./mcp_sequential_thinking.py |
| 45 | +
|
| 46 | +# Run with thought logging suppressed |
| 47 | +DISABLE_THOUGHT_LOGGING=true ./mcp_sequential_thinking.py |
| 48 | +``` |
| 49 | +""" |
| 50 | + |
| 51 | +from __future__ import annotations |
| 52 | + |
| 53 | +import argparse |
| 54 | +import logging |
| 55 | +import os |
| 56 | +import sys |
| 57 | +from typing import Annotated, Any |
| 58 | + |
| 59 | +from mcp.server.fastmcp import FastMCP |
| 60 | +from pydantic import BeforeValidator, Field |
| 61 | + |
| 62 | +logging.basicConfig(level=logging.INFO, format="%(levelname)s | %(message)s") |
| 63 | +logger = logging.getLogger(__name__) |
| 64 | + |
| 65 | + |
| 66 | +# --------------------------------------------------------------------------- |
| 67 | +# String → native coercion helpers (for issue #3856) |
| 68 | +# --------------------------------------------------------------------------- |
| 69 | + |
| 70 | + |
| 71 | +def _coerce_bool(value: Any) -> Any: |
| 72 | + """Coerce JSON-string booleans to Python bools. |
| 73 | +
|
| 74 | + Accepts the native ``bool`` unchanged and converts the strings ``"true"`` |
| 75 | + and ``"false"`` (case-insensitive) to their Python equivalents. Any other |
| 76 | + value is passed through to pydantic for normal validation, which will |
| 77 | + raise if it cannot be interpreted as a boolean. |
| 78 | + """ |
| 79 | + if isinstance(value, bool): |
| 80 | + return value |
| 81 | + if isinstance(value, str): |
| 82 | + lowered = value.strip().lower() |
| 83 | + if lowered == "true": |
| 84 | + return True |
| 85 | + if lowered == "false": |
| 86 | + return False |
| 87 | + return value |
| 88 | + |
| 89 | + |
| 90 | +def _coerce_int(value: Any) -> Any: |
| 91 | + """Coerce JSON-string integers to Python ints. |
| 92 | +
|
| 93 | + Accepts the native ``int`` unchanged. A non-empty string of digits (with |
| 94 | + optional surrounding whitespace and an optional leading sign) is parsed |
| 95 | + via ``int()``. Anything else is passed through to pydantic. |
| 96 | + """ |
| 97 | + if isinstance(value, bool): |
| 98 | + return value |
| 99 | + if isinstance(value, int): |
| 100 | + return value |
| 101 | + if isinstance(value, str): |
| 102 | + stripped = value.strip() |
| 103 | + if stripped: |
| 104 | + try: |
| 105 | + return int(stripped) |
| 106 | + except ValueError: |
| 107 | + return value |
| 108 | + return value |
| 109 | + |
| 110 | + |
| 111 | +CoercedBool = Annotated[bool, BeforeValidator(_coerce_bool)] |
| 112 | +CoercedInt = Annotated[int, BeforeValidator(_coerce_int)] |
| 113 | +OptionalCoercedBool = Annotated[bool | None, BeforeValidator(_coerce_bool)] |
| 114 | +OptionalCoercedInt = Annotated[int | None, BeforeValidator(_coerce_int)] |
| 115 | + |
| 116 | + |
| 117 | +# --------------------------------------------------------------------------- |
| 118 | +# Core server class |
| 119 | +# --------------------------------------------------------------------------- |
| 120 | + |
| 121 | + |
| 122 | +class SequentialThinkingServer: |
| 123 | + """In-memory store for an evolving chain of thoughts. |
| 124 | +
|
| 125 | + The server keeps two structures: |
| 126 | +
|
| 127 | + * ``thought_history`` – an append-only list of every thought processed. |
| 128 | + * ``branches`` – a mapping of branch identifier to the list of thoughts |
| 129 | + recorded under that branch (only populated when both |
| 130 | + ``branchFromThought`` and ``branchId`` are supplied). |
| 131 | +
|
| 132 | + Whether thoughts are logged to stderr is controlled by the |
| 133 | + ``DISABLE_THOUGHT_LOGGING`` environment variable, which is read once when |
| 134 | + the instance is constructed (mirroring the behavior of the TypeScript |
| 135 | + reference implementation). |
| 136 | + """ |
| 137 | + |
| 138 | + def __init__(self) -> None: |
| 139 | + self.thought_history: list[dict[str, Any]] = [] |
| 140 | + self.branches: dict[str, list[dict[str, Any]]] = {} |
| 141 | + self.disable_thought_logging: bool = ( |
| 142 | + os.environ.get("DISABLE_THOUGHT_LOGGING", "").strip().lower() == "true" |
| 143 | + ) |
| 144 | + |
| 145 | + def _format_thought(self, thought_data: dict[str, Any]) -> str: |
| 146 | + """Render a thought as a Unicode box for stderr logging. |
| 147 | +
|
| 148 | + The header prefix is one of ``💭 Thought``, ``🔄 Revision``, or |
| 149 | + ``🌿 Branch`` depending on which optional fields are present, and the |
| 150 | + box is sized to fit whichever of the header or thought body is longer. |
| 151 | + """ |
| 152 | + thought_number = thought_data["thoughtNumber"] |
| 153 | + total_thoughts = thought_data["totalThoughts"] |
| 154 | + thought = thought_data["thought"] |
| 155 | + is_revision = thought_data.get("isRevision") |
| 156 | + revises_thought = thought_data.get("revisesThought") |
| 157 | + branch_from_thought = thought_data.get("branchFromThought") |
| 158 | + branch_id = thought_data.get("branchId") |
| 159 | + |
| 160 | + if is_revision: |
| 161 | + prefix = "🔄 Revision" |
| 162 | + context = f" (revising thought {revises_thought})" |
| 163 | + elif branch_from_thought: |
| 164 | + prefix = "🌿 Branch" |
| 165 | + context = f" (from thought {branch_from_thought}, ID: {branch_id})" |
| 166 | + else: |
| 167 | + prefix = "💭 Thought" |
| 168 | + context = "" |
| 169 | + |
| 170 | + header = f"{prefix} {thought_number}/{total_thoughts}{context}" |
| 171 | + border_width = max(len(header), len(thought)) + 4 |
| 172 | + border = "─" * border_width |
| 173 | + padded_thought = thought.ljust(border_width - 2) |
| 174 | + padded_header = header.ljust(border_width - 2) |
| 175 | + |
| 176 | + return ( |
| 177 | + f"\n┌{border}┐" |
| 178 | + f"\n│ {padded_header} │" |
| 179 | + f"\n├{border}┤" |
| 180 | + f"\n│ {padded_thought} │" |
| 181 | + f"\n└{border}┘" |
| 182 | + ) |
| 183 | + |
| 184 | + def process_thought(self, input_data: dict[str, Any]) -> dict[str, Any]: |
| 185 | + """Record a thought and return a summary of the current state. |
| 186 | +
|
| 187 | + ``input_data`` is expected to already contain validated keys matching |
| 188 | + the tool schema. If ``thoughtNumber`` exceeds ``totalThoughts`` the |
| 189 | + latter is bumped up so that the running estimate stays internally |
| 190 | + consistent. The returned dict mirrors the structured payload that the |
| 191 | + MCP tool layer surfaces to clients. |
| 192 | + """ |
| 193 | + if input_data["thoughtNumber"] > input_data["totalThoughts"]: |
| 194 | + input_data["totalThoughts"] = input_data["thoughtNumber"] |
| 195 | + |
| 196 | + self.thought_history.append(input_data) |
| 197 | + |
| 198 | + branch_from = input_data.get("branchFromThought") |
| 199 | + branch_id = input_data.get("branchId") |
| 200 | + if branch_from and branch_id: |
| 201 | + self.branches.setdefault(branch_id, []).append(input_data) |
| 202 | + |
| 203 | + if not self.disable_thought_logging: |
| 204 | + print(self._format_thought(input_data), file=sys.stderr) |
| 205 | + |
| 206 | + return { |
| 207 | + "thoughtNumber": input_data["thoughtNumber"], |
| 208 | + "totalThoughts": input_data["totalThoughts"], |
| 209 | + "nextThoughtNeeded": input_data["nextThoughtNeeded"], |
| 210 | + "branches": list(self.branches.keys()), |
| 211 | + "thoughtHistoryLength": len(self.thought_history), |
| 212 | + } |
| 213 | + |
| 214 | + |
| 215 | +# --------------------------------------------------------------------------- |
| 216 | +# Module-level helper for tests / non-MCP callers |
| 217 | +# --------------------------------------------------------------------------- |
| 218 | + |
| 219 | + |
| 220 | +def _process_thought_sync( |
| 221 | + server: SequentialThinkingServer, input_data: dict[str, Any] |
| 222 | +) -> dict[str, Any]: |
| 223 | + """Thin synchronous wrapper around ``process_thought``. |
| 224 | +
|
| 225 | + Mirrors the ``_query_sync`` pattern used elsewhere in this repo so that |
| 226 | + tests can exercise the core logic without spinning up an MCP server. |
| 227 | + """ |
| 228 | + return server.process_thought(input_data) |
| 229 | + |
| 230 | + |
| 231 | +# --------------------------------------------------------------------------- |
| 232 | +# MCP Server setup |
| 233 | +# --------------------------------------------------------------------------- |
| 234 | + |
| 235 | + |
| 236 | +_SEQUENTIAL_THINKING_DESCRIPTION = """A detailed tool for dynamic and reflective problem-solving through thoughts. |
| 237 | +This tool helps analyze problems through a flexible thinking process that can adapt and evolve. |
| 238 | +Each thought can build on, question, or revise previous insights as understanding deepens. |
| 239 | +
|
| 240 | +When to use this tool: |
| 241 | +- Breaking down complex problems into steps |
| 242 | +- Planning and design with room for revision |
| 243 | +- Analysis that might need course correction |
| 244 | +- Problems where the full scope might not be clear initially |
| 245 | +- Problems that require a multi-step solution |
| 246 | +- Tasks that need to maintain context over multiple steps |
| 247 | +- Situations where irrelevant information needs to be filtered out |
| 248 | +
|
| 249 | +Key features: |
| 250 | +- You can adjust total_thoughts up or down as you progress |
| 251 | +- You can question or revise previous thoughts |
| 252 | +- You can add more thoughts even after reaching what seemed like the end |
| 253 | +- You can express uncertainty and explore alternative approaches |
| 254 | +- Not every thought needs to build linearly - you can branch or backtrack |
| 255 | +- Generates a solution hypothesis |
| 256 | +- Verifies the hypothesis based on the Chain of Thought steps |
| 257 | +- Repeats the process until satisfied |
| 258 | +- Provides a correct answer |
| 259 | +
|
| 260 | +Parameters explained: |
| 261 | +- thought: Your current thinking step, which can include: |
| 262 | + * Regular analytical steps |
| 263 | + * Revisions of previous thoughts |
| 264 | + * Questions about previous decisions |
| 265 | + * Realizations about needing more analysis |
| 266 | + * Changes in approach |
| 267 | + * Hypothesis generation |
| 268 | + * Hypothesis verification |
| 269 | +- nextThoughtNeeded: True if you need more thinking, even if at what seemed like the end |
| 270 | +- thoughtNumber: Current number in sequence (can go beyond initial total if needed) |
| 271 | +- totalThoughts: Current estimate of thoughts needed (can be adjusted up/down) |
| 272 | +- isRevision: A boolean indicating if this thought revises previous thinking |
| 273 | +- revisesThought: If is_revision is true, which thought number is being reconsidered |
| 274 | +- branchFromThought: If branching, which thought number is the branching point |
| 275 | +- branchId: Identifier for the current branch (if any) |
| 276 | +- needsMoreThoughts: If reaching end but realizing more thoughts needed |
| 277 | +
|
| 278 | +You should: |
| 279 | +1. Start with an initial estimate of needed thoughts, but be ready to adjust |
| 280 | +2. Feel free to question or revise previous thoughts |
| 281 | +3. Don't hesitate to add more thoughts if needed, even at the "end" |
| 282 | +4. Express uncertainty when present |
| 283 | +5. Mark thoughts that revise previous thinking or branch into new paths |
| 284 | +6. Ignore information that is irrelevant to the current step |
| 285 | +7. Generate a solution hypothesis when appropriate |
| 286 | +8. Verify the hypothesis based on the Chain of Thought steps |
| 287 | +9. Repeat the process until satisfied with the solution |
| 288 | +10. Provide a single, ideally correct answer as the final output |
| 289 | +11. Only set nextThoughtNeeded to false when truly done and a satisfactory answer is reached""" |
| 290 | + |
| 291 | + |
| 292 | +mcp = FastMCP("Sequential Thinking") |
| 293 | +_thinking_server = SequentialThinkingServer() |
| 294 | + |
| 295 | + |
| 296 | +@mcp.tool(description=_SEQUENTIAL_THINKING_DESCRIPTION) |
| 297 | +async def sequentialthinking( |
| 298 | + thought: Annotated[str, Field(description="Your current thinking step")], |
| 299 | + nextThoughtNeeded: Annotated[ # noqa: N803 |
| 300 | + CoercedBool, |
| 301 | + Field(description="Whether another thought step is needed"), |
| 302 | + ], |
| 303 | + thoughtNumber: Annotated[ # noqa: N803 |
| 304 | + CoercedInt, |
| 305 | + Field(ge=1, description="Current thought number (>= 1)"), |
| 306 | + ], |
| 307 | + totalThoughts: Annotated[ # noqa: N803 |
| 308 | + CoercedInt, |
| 309 | + Field(ge=1, description="Estimated total thoughts needed (>= 1)"), |
| 310 | + ], |
| 311 | + isRevision: Annotated[ # noqa: N803 |
| 312 | + OptionalCoercedBool, |
| 313 | + Field(default=None, description="Whether this revises previous thinking"), |
| 314 | + ] = None, |
| 315 | + revisesThought: Annotated[ # noqa: N803 |
| 316 | + OptionalCoercedInt, |
| 317 | + Field(default=None, ge=1, description="Which thought is being reconsidered"), |
| 318 | + ] = None, |
| 319 | + branchFromThought: Annotated[ # noqa: N803 |
| 320 | + OptionalCoercedInt, |
| 321 | + Field(default=None, ge=1, description="Branching point thought number"), |
| 322 | + ] = None, |
| 323 | + branchId: Annotated[ # noqa: N803 |
| 324 | + str | None, |
| 325 | + Field(default=None, description="Branch identifier"), |
| 326 | + ] = None, |
| 327 | + needsMoreThoughts: Annotated[ # noqa: N803 |
| 328 | + OptionalCoercedBool, |
| 329 | + Field(default=None, description="If more thoughts are needed"), |
| 330 | + ] = None, |
| 331 | +) -> dict[str, Any]: |
| 332 | + """Record one step in a sequential thinking session.""" |
| 333 | + input_data: dict[str, Any] = { |
| 334 | + "thought": thought, |
| 335 | + "thoughtNumber": thoughtNumber, |
| 336 | + "totalThoughts": totalThoughts, |
| 337 | + "nextThoughtNeeded": nextThoughtNeeded, |
| 338 | + } |
| 339 | + if isRevision is not None: |
| 340 | + input_data["isRevision"] = isRevision |
| 341 | + if revisesThought is not None: |
| 342 | + input_data["revisesThought"] = revisesThought |
| 343 | + if branchFromThought is not None: |
| 344 | + input_data["branchFromThought"] = branchFromThought |
| 345 | + if branchId is not None: |
| 346 | + input_data["branchId"] = branchId |
| 347 | + if needsMoreThoughts is not None: |
| 348 | + input_data["needsMoreThoughts"] = needsMoreThoughts |
| 349 | + |
| 350 | + return _thinking_server.process_thought(input_data) |
| 351 | + |
| 352 | + |
| 353 | +# --------------------------------------------------------------------------- |
| 354 | +# CLI entry point |
| 355 | +# --------------------------------------------------------------------------- |
| 356 | + |
| 357 | + |
| 358 | +def main() -> None: |
| 359 | + """Run the FastMCP server over stdio.""" |
| 360 | + parser = argparse.ArgumentParser(description="Sequential Thinking MCP Server") |
| 361 | + parser.parse_known_args() |
| 362 | + logger.info("Sequential Thinking MCP Server starting on stdio") |
| 363 | + mcp.run() |
| 364 | + |
| 365 | + |
| 366 | +if __name__ == "__main__": |
| 367 | + main() |
0 commit comments