Skip to content
Back to search

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.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/martinbowling--thinkchain/badge.svg)](/listings/martinbowling--thinkchain)

HTML

<a href="/listings/martinbowling--thinkchain"><img src="/api/listings/martinbowling--thinkchain/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

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

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md ยท README ยท 525 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # ThinkChain
  2. 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.
  3. **Created by [Martin Bowling](https://martinbowling.com)** โ€ข [GitHub](https://github.com/martinbowling) โ€ข [Twitter/X](https://x.com/martinbowling)
  4. ## Overview
  5. ThinkChain demonstrates the power of Claude's streaming interface with advanced features like:
  6. - **Interleaved and extended thinking** - Claude thinks through problems step-by-step in real-time
  7. - **Fine-grained tool streaming** - Watch tools execute with live progress updates
  8. - **Early interception of tool_use blocks** - Tool results are injected back into Claude's thinking process
  9. - **Multiple tool calls per turn** - Execute multiple tools simultaneously for complex workflows
  10. - **Pydantic-validated inputs** - Robust type checking and validation for all tool interactions
  11. The system combines local Python tools with MCP servers to create a unified, extensible tool ecosystem that works seamlessly with Claude's streaming capabilities.
  12. ## ๐Ÿš€ Quick Start
  13. ### Option 1: Zero-Setup with `uv run` (Recommended)
  14. ```bash
  15. # Clone the repository
  16. git clone https://github.com/martinbowling/ThinkChain.git
  17. cd ThinkChain
  18. # Set up your API key
  19. echo "ANTHROPIC_API_KEY=your_api_key_here" > .env
  20. # Run immediately - uv handles all dependencies automatically!
  21. uv run thinkchain.py # Enhanced UI with rich formatting
  22. uv run thinkchain_cli.py # Minimal CLI version
  23. uv run run.py # Smart launcher (auto-detects best UI)
  24. ```
  25. ### Option 2: Traditional Installation
  26. ```bash
  27. # Clone and set up
  28. git clone https://github.com/martinbowling/ThinkChain.git
  29. cd ThinkChain
  30. # Install dependencies
  31. uv pip install -r requirements.txt
  32. # or: pip install -r requirements.txt
  33. # Set up your API key
  34. echo "ANTHROPIC_API_KEY=your_api_key_here" > .env
  35. # Run the application
  36. python run.py # Smart launcher
  37. python thinkchain.py # Enhanced UI
  38. python thinkchain_cli.py # CLI version
  39. ```
  40. ## โœจ Key Features
  41. ### ๐Ÿง  Advanced Thinking Integration
  42. The core innovation of ThinkChain is how tool execution results are **injected back into Claude's thinking stream**. When Claude calls a tool:
  43. 1. The tool executes and returns results
  44. 2. Results are immediately fed back into Claude's thinking process
  45. 3. Claude can reason about the results before responding to the user
  46. 4. This creates a natural thinking โ†’ tool โ†’ thinking โ†’ response flow
  47. ### ๐Ÿ”ง Dynamic Tool Discovery
  48. - **Local Tools**: Automatically discovers Python tools from the `/tools` directory
  49. - **MCP Integration**: Connects to Model Context Protocol servers for extended functionality
  50. - **Hot Reloading**: Use `refresh` command to reload tools during development
  51. - **Unified Registry**: All tools (local + MCP) work identically in the streaming interface
  52. ### ๐ŸŽจ Enhanced CLI Interface
  53. - Rich formatting with colors, borders, and progress indicators
  54. - Interactive tool browser with categorized displays
  55. - Command autocomplete and history
  56. - Real-time thinking visualization with syntax highlighting
  57. - Graceful degradation to standard text interface
  58. ### โšก Streaming Architecture
  59. - Server-sent events (SSE) for real-time communication
  60. - Fine-grained streaming of tool execution progress
  61. - Concurrent tool execution when possible
  62. - Robust error handling and recovery
  63. ### ๐Ÿ”ง Developer Experience
  64. - **Zero-setup execution** with `uv run` - no virtual environments or dependency installation needed
  65. - **Automatic tool discovery** from `/tools` directory
  66. - **Hot reloading** with `/refresh` command during development
  67. - **Rich error messages** and graceful degradation when dependencies are missing
  68. ## ๐Ÿ›  Technical Architecture
  69. ### Tool Injection System
  70. The key technical innovation is the **tool result injection mechanism**:
  71. ```python
  72. # Tool results are injected back into Claude's thinking process
  73. async def stream_once(messages, tools):
  74. # Start streaming with thinking enabled
  75. async with client.messages.stream(
  76. model="claude-sonnet-4-20250514",
  77. messages=messages,
  78. tools=tools,
  79. betas=["interleaved-thinking-2025-05-14", "fine-grained-tool-streaming-2025-05-14"],
  80. thinking_budget=1024
  81. ) as stream:
  82. async for event in stream:
  83. if event.type == "tool_use":
  84. # Execute tool and inject result back into stream
  85. result = await execute_tool(event.name, event.input)
  86. # This result becomes part of Claude's thinking context
  87. # for the remainder of the response
  88. yield {"type": "tool_result", "content": result}
  89. ```
  90. This creates a feedback loop where:
  91. 1. Claude's initial thinking leads to tool use
  92. 2. Tool results inform continued thinking
  93. 3. Final response incorporates both reasoning and tool outcomes
  94. ### Tool Discovery Pipeline
  95. ```
  96. Local Tools (/tools/*.py) โ†’ Validation โ†’ Registry
  97. โ†“
  98. MCP Servers (config.json) โ†’ Connection โ†’ Registry โ†’ Unified Tool List โ†’ Claude API
  99. ```
  100. Each tool must implement the `BaseTool` interface:
  101. ```python
  102. class BaseTool:
  103. @property
  104. def name(self) -> str: ...
  105. @property
  106. def description(self) -> str: ...
  107. @property
  108. def input_schema(self) -> Dict[str, Any]: ...
  109. def execute(self, **kwargs) -> str: ...
  110. ```
  111. ### Streaming Event Flow
  112. ```
  113. User Input โ†’ Claude API โ†’ Thinking Stream โ†’ Tool Detection โ†’ Tool Execution
  114. โ†‘ โ†“
  115. Response โ† Thinking Integration โ† Tool Result Injection โ† Tool Output
  116. ```
  117. ## ๐Ÿ“š Available Tools
  118. ### Local Tools (`/tools` directory)
  119. **๐ŸŒ Web & Data Tools:**
  120. - **weathertool**: Real weather data from wttr.in API for any location worldwide
  121. - **duckduckgotool**: Live DuckDuckGo search results for web queries and restaurant searches
  122. - **webscrapertool**: Enhanced web scraper that extracts main content from any webpage
  123. **๐Ÿ“ File & Development Tools:**
  124. - **filecreatortool**: Creates new files with specified content and directory structure
  125. - **fileedittool**: Advanced file editing with full/partial content replacement and search/replace
  126. - **filecontentreadertool**: Reads and returns content from multiple files simultaneously
  127. - **createfolderstool**: Creates directories and nested folder structures
  128. - **diffeditortool**: Precise text snippet replacement in files
  129. **โš™๏ธ Development & Package Management:**
  130. - **uvpackagemanager**: Complete interface to uv package manager for Python projects
  131. - **lintingtool**: Runs Ruff linter on Python files to detect and fix code issues
  132. - **toolcreator**: Dynamically creates new tools based on natural language descriptions
  133. ### MCP Server Support
  134. Configure in `mcp_config.json`:
  135. - **SQLite**: Database operations and queries
  136. - **Puppeteer**: Web browser automation
  137. - **Filesystem**: Advanced file system operations
  138. - **Brave Search**: Real web search integration
  139. ## ๐ŸŽฎ Interactive Commands
  140. While chatting with Claude, you can use these slash commands:
  141. - `/refresh` or `/reload` - Refresh tool discovery (picks up new tools)
  142. - `/tools` - Browse all available tools by category
  143. - `/status` - Show comprehensive system status
  144. - `/clear` - Clear screen while preserving status bar
  145. - `/config` - Show current configuration
  146. - `/config model <model_name>` - Switch between Claude models (sonnet/opus)
  147. - `/config thinking <1024-16000>` - Adjust thinking token budget
  148. - `/help` - Show help information
  149. - `/exit` or `/quit` - End the conversation
  150. **Legacy Support**: All commands work without the `/` prefix for backward compatibility.
  151. ## โš™๏ธ Configuration
  152. ### Environment Setup
  153. Create `.env` file:
  154. ```bash
  155. ANTHROPIC_API_KEY=your_api_key_here
  156. ```
  157. ### MCP Server Configuration
  158. Edit `mcp_config.json`:
  159. ```json
  160. {
  161. "mcpServers": {
  162. "sqlite": {
  163. "command": "uvx",
  164. "args": ["mcp-server-sqlite", "--db-path", "./database.db"],
  165. "enabled": true
  166. },
  167. "puppeteer": {
  168. "command": "npx",
  169. "args": ["-y", "@modelcontextprotocol/server-puppeteer"],
  170. "enabled": false
  171. }
  172. }
  173. }
  174. ```
  175. ### Model Configuration
  176. The system supports both Claude models with configurable settings:
  177. **Available Models:**
  178. - `claude-sonnet-4-20250514` (default) - Fast and efficient
  179. - `claude-opus-4-20250514` - Most capable, slower
  180. **Configurable Settings:**
  181. - Thinking budget: 1024-16000 tokens (default: 1024)
  182. - Max response tokens: 1024
  183. - Beta features: `interleaved-thinking-2025-05-14`, `fine-grained-tool-streaming-2025-05-14`
  184. **Runtime Configuration:**
  185. ```bash
  186. # Change model during conversation
  187. /config model claude-opus-4-20250514
  188. # Increase thinking budget for complex problems
  189. /config thinking 8192
  190. ```
  191. ## ๐Ÿ”ง Development
  192. ### Creating New Local Tools
  193. Creating a new tool is straightforward - just follow these steps:
  194. #### 1. Create Tool File
  195. Create a new Python file in the `/tools/` directory (e.g., `/tools/mytool.py`):
  196. ```python
  197. from tools.base import BaseTool
  198. class MyTool(BaseTool):
  199. name = "mytool"
  200. description = """
  201. A detailed description of what your tool does.
  202. Use this tool when users ask about:
  203. - Specific use case 1
  204. - Specific use case 2
  205. - "Keywords that should trigger this tool"
  206. """
  207. input_schema = {
  208. "type": "object",
  209. "properties": {
  210. "input_param": {
  211. "type": "string",
  212. "description": "Description of this parameter"
  213. },
  214. "optional_param": {
  215. "type": "integer",
  216. "description": "Optional parameter with default",
  217. "default": 10
  218. }
  219. },
  220. "required": ["input_param"]
  221. }
  222. def execute(self, **kwargs) -> str:
  223. input_param = kwargs.get("input_param")
  224. optional_param = kwargs.get("optional_param", 10)
  225. # Your tool logic here
  226. result = f"Processed: {input_param} with {optional_param}"
  227. return result
  228. ```
  229. #### 2. Key Requirements
  230. - **Class name**: Must match filename (e.g., `MyTool` for `mytool.py`)
  231. - **Inherit from BaseTool**: Import from `tools.base`
  232. - **Four required attributes**: `name`, `description`, `input_schema`, `execute()` method
  233. - **Return strings**: The `execute()` method must return a string result
  234. #### 3. Tool Discovery
  235. - Tools are automatically discovered on startup
  236. - Use `/refresh` command to reload tools without restarting
  237. - Check with `/tools` command to see your new tool listed
  238. #### 4. Best Practices
  239. - **Descriptive names**: Use clear, action-oriented names
  240. - **Rich descriptions**: Include use cases and keywords that should trigger the tool
  241. - **Input validation**: Use comprehensive JSON schemas
  242. - **Error handling**: Wrap risky operations in try/catch blocks
  243. - **Helpful output**: Return formatted, readable results
  244. ### Adding MCP (Model Context Protocol) Servers
  245. MCP allows integration with external servers that provide additional tools:
  246. #### 1. Install MCP Server
  247. Most MCP servers can be installed via `uvx` or `npx`:
  248. ```bash
  249. # Install SQLite MCP server
  250. uvx install mcp-server-sqlite
  251. # Install Puppeteer MCP server (requires Node.js)
  252. npm install -g @modelcontextprotocol/server-puppeteer
  253. # Install Brave Search MCP server
  254. npm install -g @modelcontextprotocol/server-brave-search
  255. ```
  256. #### 2. Configure MCP Server
  257. Edit `mcp_config.json` to add your server:
  258. ```json
  259. {
  260. "mcpServers": {
  261. "my-server": {
  262. "command": "uvx",
  263. "args": ["my-mcp-server", "--custom-arg", "value"],
  264. "description": "Description of what this server provides",
  265. "enabled": true,
  266. "env": {
  267. "API_KEY": "your_api_key_if_needed"
  268. }
  269. }
  270. }
  271. }
  272. ```
  273. #### 3. Available MCP Servers
  274. Popular MCP servers you can integrate:
  275. **Data & Storage:**
  276. - `mcp-server-sqlite` - Database operations
  277. - `mcp-server-postgres` - PostgreSQL integration
  278. - `mcp-server-redis` - Redis cache operations
  279. **Web & Automation:**
  280. - `@modelcontextprotocol/server-puppeteer` - Browser automation
  281. - `@modelcontextprotocol/server-brave-search` - Web search
  282. - `@modelcontextprotocol/server-filesystem` - File operations
  283. **APIs & Services:**
  284. - `@modelcontextprotocol/server-github` - GitHub integration
  285. - `@modelcontextprotocol/server-slack` - Slack integration
  286. - `mcp-server-aws` - AWS operations
  287. #### 4. Test MCP Integration
  288. After adding a server, test it:
  289. ```bash
  290. # Test MCP functionality
  291. python test_mcp.py
  292. # Start ThinkChain and check tools
  293. python thinkchain.py
  294. /tools # Should show both local and MCP tools
  295. ```
  296. ### Development Workflow
  297. #### 1. Tool Development Cycle
  298. ```bash
  299. # Create tool
  300. vim tools/newtool.py
  301. # Test tool
  302. python thinkchain.py
  303. /refresh # Reload tools
  304. "Use my new tool for X" # Test with Claude
  305. # Iterate and improve
  306. vim tools/newtool.py
  307. /refresh # Reload again
  308. ```
  309. #### 2. Debugging Tools
  310. - Use `print()` statements in your `execute()` method - they'll show in console
  311. - Return error messages as strings for Claude to see
  312. - Check the tool discovery logs on startup
  313. ### Running Different Interfaces
  314. ```bash
  315. # Traditional Python execution
  316. python run.py # Smart launcher
  317. python thinkchain.py # Full-featured UI
  318. python thinkchain_cli.py # Minimal dependencies
  319. # Using uv run (handles dependencies automatically)
  320. uv run run.py # Smart launcher
  321. uv run thinkchain.py # Full-featured UI
  322. uv run thinkchain_cli.py # Minimal dependencies
  323. ```
  324. ## ๐Ÿ“‹ Dependencies
  325. ### Core Requirements
  326. - `anthropic>=0.25.0` - Claude API client
  327. - `sseclient-py` - Server-sent events handling
  328. - `pydantic` - Data validation and schemas
  329. - `python-dotenv` - Environment variable management
  330. ### Enhanced UI (Optional)
  331. - `rich` - Terminal formatting and colors
  332. - `prompt_toolkit` - Interactive command line features
  333. ### MCP Integration (Optional)
  334. - `mcp` - Model Context Protocol client
  335. - MCP server packages (installed via `uvx` or `npx`)
  336. ### Tool Dependencies (Optional)
  337. Some tools require additional packages that are installed automatically:
  338. **Web Tools:** (weathertool, duckduckgotool, webscrapertool)
  339. - `requests` - HTTP requests
  340. - `beautifulsoup4` - HTML parsing
  341. **Note**: Missing dependencies are handled gracefully - tools that can't import will be skipped during discovery with informative error messages.
  342. ### UV Run Support
  343. All main scripts include inline dependency declarations that make them compatible with `uv run`:
  344. ```python
  345. #!/usr/bin/env python3
  346. # /// script
  347. # dependencies = [
  348. # "anthropic>=0.25.0",
  349. # "sseclient-py",
  350. # "pydantic",
  351. # "python-dotenv",
  352. # "rich>=13.0.0",
  353. # "requests",
  354. # "beautifulsoup4",
  355. # "mcp",
  356. # "httpx",
  357. # ]
  358. # ///
  359. ```
  360. **Benefits of `uv run`:**
  361. - โœ… **Zero setup** - No need to create virtual environments or install dependencies
  362. - โœ… **Automatic dependency management** - uv handles everything
  363. - โœ… **Isolated execution** - Each run gets a clean environment
  364. - โœ… **Cross-platform** - Works identically on macOS, Linux, and Windows
  365. ```bash
  366. # All these work immediately after cloning:
  367. uv run thinkchain.py # Enhanced UI with all features
  368. uv run thinkchain_cli.py # Minimal CLI version
  369. uv run run.py # Smart launcher
  370. uv run test_mcp.py # Test MCP integration
  371. ```
  372. ## ๐Ÿค Contributing
  373. This project is designed to be **forked and extended**! Here are some ideas:
  374. - **Add new local tools** for your specific use cases
  375. - **Integrate additional MCP servers** from the growing ecosystem
  376. - **Enhance the UI** with new visualization features
  377. - **Extend the streaming architecture** for custom event types
  378. - **Build domain-specific tool collections** (data science, web dev, etc.)
  379. ### Getting Started with Your Fork
  380. The process is straightforward with `uv run`:
  381. ```bash
  382. # Fork and clone
  383. git clone https://github.com/yourusername/your-thinkchain-fork.git
  384. cd your-thinkchain-fork
  385. # Set up API key
  386. echo "ANTHROPIC_API_KEY=your_key" > .env
  387. # Create your first tool
  388. vim tools/yourtool.py
  389. # Test immediately with uv run (no setup needed!)
  390. uv run thinkchain.py
  391. /refresh # Loads your new tool
  392. "Use my new tool for X" # Test with Claude
  393. ```
  394. ### Fork Ideas
  395. - **Data Science ThinkChain**: Add pandas, matplotlib, jupyter tools
  396. - **Web Development ThinkChain**: Add React, npm, git, deployment tools
  397. - **DevOps ThinkChain**: Add Docker, Kubernetes, AWS/GCP tools
  398. - **Research ThinkChain**: Add academic paper search, citation tools
  399. ## ๐Ÿ“„ License
  400. MIT License - see the [LICENSE](LICENSE) file for details.
  401. ## ๐Ÿ™ Acknowledgments
  402. - Inspired by [Pietro Schirano's chain of tools concept](https://x.com/skirano/status/1933208161244086430) - we loved the idea and decided to crank out our own version!
  403. - Built with [Anthropic's Claude API](https://www.anthropic.com/)
  404. - MCP integration powered by the [Model Context Protocol](https://modelcontextprotocol.io/)
  405. - Enhanced UI built with [Rich](https://github.com/Textualize/rich) and [Prompt Toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit)
  406. ---
  407. **Ready to think differently about AI tool integration?** Fork ThinkChain and start building! ๐Ÿš€

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If itโ€™s helped, pass it on.