SkillAgentSearch skills...

Thinkchain

🧠 Advanced Claude streaming interface with interleaved thinking, dynamic tool discovery, and MCP integration. Watch Claude think through problems in real-time while executing tools with live progress updates.

Install / Use

/learn @martinbowling/Thinkchain
About this skill

Quality Score

0/100

Supported Platforms

Claude Code
Claude Desktop
Cursor

README

ThinkChain

A Python demonstration project showcasing Claude's advanced capabilities through interleaved thinking, fine-grained tool streaming, and dynamic tool discovery with MCP (Model Context Protocol) integration.

Created by Martin BowlingGitHubTwitter/X

Overview

ThinkChain demonstrates the power of Claude's streaming interface with advanced features like:

  • Interleaved and extended thinking - Claude thinks through problems step-by-step in real-time
  • Fine-grained tool streaming - Watch tools execute with live progress updates
  • Early interception of tool_use blocks - Tool results are injected back into Claude's thinking process
  • Multiple tool calls per turn - Execute multiple tools simultaneously for complex workflows
  • Pydantic-validated inputs - Robust type checking and validation for all tool interactions

The system combines local Python tools with MCP servers to create a unified, extensible tool ecosystem that works seamlessly with Claude's streaming capabilities.

🚀 Quick Start

Option 1: Zero-Setup with uv run (Recommended)

# Clone the repository
git clone https://github.com/martinbowling/ThinkChain.git
cd ThinkChain

# Set up your API key
echo "ANTHROPIC_API_KEY=your_api_key_here" > .env

# Run immediately - uv handles all dependencies automatically!
uv run thinkchain.py     # Enhanced UI with rich formatting
uv run thinkchain_cli.py # Minimal CLI version  
uv run run.py            # Smart launcher (auto-detects best UI)

Option 2: Traditional Installation

# Clone and set up
git clone https://github.com/martinbowling/ThinkChain.git
cd ThinkChain

# Install dependencies
uv pip install -r requirements.txt
# or: pip install -r requirements.txt

# Set up your API key
echo "ANTHROPIC_API_KEY=your_api_key_here" > .env

# Run the application
python run.py            # Smart launcher
python thinkchain.py     # Enhanced UI
python thinkchain_cli.py # CLI version

✨ Key Features

🧠 Advanced Thinking Integration

The core innovation of ThinkChain is how tool execution results are injected back into Claude's thinking stream. When Claude calls a tool:

  1. The tool executes and returns results
  2. Results are immediately fed back into Claude's thinking process
  3. Claude can reason about the results before responding to the user
  4. This creates a natural thinking → tool → thinking → response flow

🔧 Dynamic Tool Discovery

  • Local Tools: Automatically discovers Python tools from the /tools directory
  • MCP Integration: Connects to Model Context Protocol servers for extended functionality
  • Hot Reloading: Use refresh command to reload tools during development
  • Unified Registry: All tools (local + MCP) work identically in the streaming interface

🎨 Enhanced CLI Interface

  • Rich formatting with colors, borders, and progress indicators
  • Interactive tool browser with categorized displays
  • Command autocomplete and history
  • Real-time thinking visualization with syntax highlighting
  • Graceful degradation to standard text interface

⚡ Streaming Architecture

  • Server-sent events (SSE) for real-time communication
  • Fine-grained streaming of tool execution progress
  • Concurrent tool execution when possible
  • Robust error handling and recovery

🔧 Developer Experience

  • Zero-setup execution with uv run - no virtual environments or dependency installation needed
  • Automatic tool discovery from /tools directory
  • Hot reloading with /refresh command during development
  • Rich error messages and graceful degradation when dependencies are missing

🛠 Technical Architecture

Tool Injection System

The key technical innovation is the tool result injection mechanism:

# Tool results are injected back into Claude's thinking process
async def stream_once(messages, tools):
    # Start streaming with thinking enabled
    async with client.messages.stream(
        model="claude-sonnet-4-20250514",
        messages=messages,
        tools=tools,
        betas=["interleaved-thinking-2025-05-14", "fine-grained-tool-streaming-2025-05-14"],
        thinking_budget=1024
    ) as stream:
        
        async for event in stream:
            if event.type == "tool_use":
                # Execute tool and inject result back into stream
                result = await execute_tool(event.name, event.input)
                
                # This result becomes part of Claude's thinking context
                # for the remainder of the response
                yield {"type": "tool_result", "content": result}

This creates a feedback loop where:

  1. Claude's initial thinking leads to tool use
  2. Tool results inform continued thinking
  3. Final response incorporates both reasoning and tool outcomes

Tool Discovery Pipeline

Local Tools (/tools/*.py) → Validation → Registry
                                         ↓
MCP Servers (config.json) → Connection → Registry → Unified Tool List → Claude API

Each tool must implement the BaseTool interface:

class BaseTool:
    @property
    def name(self) -> str: ...
    
    @property  
    def description(self) -> str: ...
    
    @property
    def input_schema(self) -> Dict[str, Any]: ...
    
    def execute(self, **kwargs) -> str: ...

Streaming Event Flow

User Input → Claude API → Thinking Stream → Tool Detection → Tool Execution
     ↑                                                            ↓
Response ← Thinking Integration ← Tool Result Injection ← Tool Output

📚 Available Tools

Local Tools (/tools directory)

🌐 Web & Data Tools:

  • weathertool: Real weather data from wttr.in API for any location worldwide
  • duckduckgotool: Live DuckDuckGo search results for web queries and restaurant searches
  • webscrapertool: Enhanced web scraper that extracts main content from any webpage

📁 File & Development Tools:

  • filecreatortool: Creates new files with specified content and directory structure
  • fileedittool: Advanced file editing with full/partial content replacement and search/replace
  • filecontentreadertool: Reads and returns content from multiple files simultaneously
  • createfolderstool: Creates directories and nested folder structures
  • diffeditortool: Precise text snippet replacement in files

⚙️ Development & Package Management:

  • uvpackagemanager: Complete interface to uv package manager for Python projects
  • lintingtool: Runs Ruff linter on Python files to detect and fix code issues
  • toolcreator: Dynamically creates new tools based on natural language descriptions

MCP Server Support

Configure in mcp_config.json:

  • SQLite: Database operations and queries
  • Puppeteer: Web browser automation
  • Filesystem: Advanced file system operations
  • Brave Search: Real web search integration

🎮 Interactive Commands

While chatting with Claude, you can use these slash commands:

  • /refresh or /reload - Refresh tool discovery (picks up new tools)
  • /tools - Browse all available tools by category
  • /status - Show comprehensive system status
  • /clear - Clear screen while preserving status bar
  • /config - Show current configuration
  • /config model <model_name> - Switch between Claude models (sonnet/opus)
  • /config thinking <1024-16000> - Adjust thinking token budget
  • /help - Show help information
  • /exit or /quit - End the conversation

Legacy Support: All commands work without the / prefix for backward compatibility.

⚙️ Configuration

Environment Setup

Create .env file:

ANTHROPIC_API_KEY=your_api_key_here

MCP Server Configuration

Edit mcp_config.json:

{
  "mcpServers": {
    "sqlite": {
      "command": "uvx",
      "args": ["mcp-server-sqlite", "--db-path", "./database.db"],
      "enabled": true
    },
    "puppeteer": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-puppeteer"],
      "enabled": false
    }
  }
}

Model Configuration

The system supports both Claude models with configurable settings:

Available Models:

  • claude-sonnet-4-20250514 (default) - Fast and efficient
  • claude-opus-4-20250514 - Most capable, slower

Configurable Settings:

  • Thinking budget: 1024-16000 tokens (default: 1024)
  • Max response tokens: 1024
  • Beta features: interleaved-thinking-2025-05-14, fine-grained-tool-streaming-2025-05-14

Runtime Configuration:

# Change model during conversation
/config model claude-opus-4-20250514

# Increase thinking budget for complex problems  
/config thinking 8192

🔧 Development

Creating New Local Tools

Creating a new tool is straightforward - just follow these steps:

1. Create Tool File

Create a new Python file in the /tools/ directory (e.g., /tools/mytool.py):

from tools.base import BaseTool

class MyTool(BaseTool):
    name = "mytool"
    description = """
    A detailed description of what your tool does.
    
    Use this tool when users ask about:
    - Specific use case 1
    - Specific use case 2
    - "Keywords that should trigger this tool"
    """
    
    input_schema = {
        "type": "object",
        "properties": {
            "input_param": {
                "type": "string",
                "description": "Description of this parameter"
            },
            "optional_param": {
                "type": "integer", 
                "description": "Optional parameter with default",
                "default": 10
            }
        },
        "required": ["input_param"]
    }
    
    def execute(self, **kwargs) -> str:
        input_param = kwargs.get("input_param")
        optional_param = kwargs.get("optional_param", 10)
        
        # Your tool logic here
        result = f"Processed: {input_param} with {opt
View on GitHub
GitHub Stars184
CategoryDevelopment
Updated1mo ago
Forks22

Languages

Python

Security Score

80/100

Audited on Feb 12, 2026

No findings