npm package: @gotza02/mathinking
Description: MCP Server with sequential thinking (The Brain) and orchestrator (The Body) capabilities
Latest version: 3.1.9
Deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

# 🧠 Mathinking MCP Server (Reflective Graph Thinking)

A powerful, autonomous Model Context Protocol (MCP) server that empowers AI agents with structured reasoning, self-reflection, and real-world execution capabilities.

- **🧠 The Brain** (`mathinking_brain`) - Deep iterative reasoning with self-critique, branch merging, and autonomous execution.
- **🤖 The Body** (`mathinking_body`) - Real-world task execution with parallel processing, conditional logic, and tool orchestration.

## 🚀 Features

### 🧠 The Brain (Autonomous Agent Ready)
- **Keyword Trigger:** Start any prompt with **"mathinking"** (e.g., "mathinking build a bot") to automatically trigger the full reasoning and execution protocol.
- **Autonomous Bridge:** Directly trigger the Body (mathinking_body) from a thinking conclusion using `execute_conclusion`.
- **Iterative Reasoning:** Think step-by-step with adjustable depth.
- **Self-Critique:** Evaluate current reasoning for risks, bias, or errors.
- **Branch Merging:** Combine multiple thinking paths into a consolidated synthesis.
- **Context Summarization:** Condense long thought histories to maintain focus.
- **Persistent Memory:** Sessions and thoughts are saved automatically to `~/.mathinking/sessions.json`.
- **Branching & Revision:** Explore alternative paths and correct previous thoughts.
- **Hypothesis Testing:** Formulate and verify theories with evidence.

### 🤖 The Body (mathinking_body)
- **Real-World Execution:**
    - **Web Search:** Integrated search capabilities (Scraping/API).
    - **Real Fetch:** Fetch real data from URLs (JSON/Text).
    - **File System:** Read, write, and list local files and directories.
    - **Shell Execute:** Run bash commands directly.
- **Conditional Logic (`runIf`):** Tasks can run conditionally based on previous results.
- **Parallel Processing:** Group independent tasks into layers for concurrent execution.
- **Dependency Resolution:** Automatic DAG (Directed Acyclic Graph) management.
- **Long-term Memory:** Save and query facts/preferences via `memory_save` and `memory_query`.
- **🛡️ Safety & Flood Protection:** Automatic rate-limiting (800ms-1000ms delay) to prevent AI provider bans.

---

## 💡 How to Use (Pro-tip)

If you use **Gemini CLI** or **Claude CLI**, you can prefix your request with the keyword **`mathinking`**:

> **You:** mathinking write a script to monitor disk space and email me if it is low.

The agent will immediately:
1.  **Think** and analyze the requirements using `mathinking_brain`.
2.  **Critique** the plan for safety and efficiency.
3.  **Merge** findings into a final deployment plan.
4.  **Execute** the script using `mathinking_body` via the autonomous bridge.

---

## 🛠️ Installation

You can run Mathinking immediately without manual cloning using `npx`:

```bash
npx -y @gotza02/mathinking
```

---

## ⚙️ Configuration

### Environment Variables

Set these environment variables to enable enhanced search capabilities:

| Variable | Required | Description |
|----------|----------|-------------|
| `BRAVE_SEARCH_API_KEY` | Optional | For Brave Search (Recommended - Fast & Free tier) |
| `EXA_API_KEY` | Optional | For Exa.ai Search (AI-Native Search) |
| `GOOGLE_SEARCH_API_KEY` | Optional | Google Custom Search JSON API |
| `GOOGLE_SEARCH_CX` | Optional | Google Custom Search Engine ID |

**Note:** At least one search provider API key is required for `web_search` to function. The system will try providers in this priority order:
1. Brave Search → 2. Exa.ai → 3. Google → 4. Return "Configuration Required" message

### Quick Setup (~/.bashrc)

Add these lines to your `~/.bashrc`:

```bash
# Brave Search (Recommended - Get free key at https://api.search.brave.com/app/keys)
export BRAVE_SEARCH_API_KEY="your_brave_key_here"

# Exa.ai Search (Get key at https://exa.ai)
export EXA_API_KEY="your_exa_key_here"

# Google Custom Search (Get key at https://console.cloud.google.com/apis/credentials)
export GOOGLE_SEARCH_API_KEY="your_google_key_here"
export GOOGLE_SEARCH_CX="your_search_engine_id"
```

Then reload: `source ~/.bashrc`

---

### 1. Gemini CLI
Add to your `~/.gemini/settings.json`:

```json
{
  "mcpServers": {
    "mathinking": {
      "command": "npx",
      "args": ["-y", "@gotza02/mathinking"],
      "env": {
        "BRAVE_SEARCH_API_KEY": "your_key",
        "EXA_API_KEY": "your_key"
      }
    }
  }
}
```

### 2. Claude Desktop
Add to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "mathinking": {
      "command": "npx",
      "args": ["-y", "@gotza02/mathinking"],
      "env": {
        "BRAVE_SEARCH_API_KEY": "your_key",
        "EXA_API_KEY": "your_key"
      }
    }
  }
}
```

---

## 🔍 Web Search Configuration

The `web_search` tool is **automatically registered** and available in `mathinking_body`. However, it requires at least one of the following API keys to function:

### Provider Priority (Fallback Chain)

1. **Brave Search** (Recommended - Fast & Reliable)
   - Set `BRAVE_SEARCH_API_KEY`
   - Get your key at: https://api.search.brave.com/app/keys
   - Free tier available

2. **Exa.ai** (AI-Native Search)
   - Set `EXA_API_KEY`
   - Get your key at: https://exa.ai
   - Excellent for semantic searches

3. **Google Custom Search** (Legacy)
   - Set both `GOOGLE_SEARCH_API_KEY` and `GOOGLE_SEARCH_CX`
   - Get API key at: https://console.cloud.google.com/apis/credentials
   - Create Custom Search Engine at: https://programmablesearchengine.google.com

### Behavior Without API Keys

If no API keys are configured, `web_search` will return:
```json
{
  "query": "your search query",
  "source": "System",
  "results": [{
    "title": "Configuration Required",
    "snippet": "Web search requires API keys. Configure BRAVE_SEARCH_API_KEY, EXA_API_KEY, or GOOGLE_SEARCH_API_KEY.",
    "url": "https://github.com/gotza02/mathinking#configuration"
  }]
}
```

### Usage Example

```json
{
  "id": "search_task",
  "name": "Search for latest news",
  "toolName": "web_search",
  "toolInput": {
    "query": "TypeScript latest features",
    "numResults": 5,
    "freshness": "week"
  }
}
```

---

## 🤖 การตั้งค่าสำหรับ Claude และ Gemini (Memory/Instructions)

เพื่อให้ AI เข้าใจการใช้งาน Mathinking ได้อย่างมีประสิทธิภาพสูงสุด ควรตั้งค่าใน **Custom Instructions** (Claude) หรือ **System Instruction** (Gemini) ดังนี้:

**คำแนะนำสำหรับ AI (System Prompt):**

```text
เมื่อผู้ใช้พิมพ์เริ่มต้นข้อความด้วยคำว่า "mathinking" (เช่น "mathinking ช่วยเขียนสคริปต์...") ให้คุณเปลี่ยนโหมดการทำงานเข้าสู่ Mathinking Protocol ทันทีโดย:
1. เรียกใช้ mathinking_brain (The Brain) เพื่อวิเคราะห์และวางแผนงานอย่างละเอียด
2. ใช้ self_critique เพื่อประเมินความเสี่ยงและข้อผิดพลาด
3. เมื่อได้ข้อสรุปที่ชัดเจน ให้ระบุ ExecutionPlan ในรูปแบบ JSON และใช้ execute_conclusion เพื่อส่งต่อให้ mathinking_body (The Body) ทำงานจริงโดยอัตโนมัติ
```

**วิธีตั้งค่า:**
- **Gemini CLI:** เพิ่มคำแนะนำข้างต้นลงในส่วน `systemInstruction` ในไฟล์ `settings.json` หรือระบุผ่าน context ตอนเริ่มต้น
- **Claude Desktop:** เพิ่มลงใน **Custom Instructions** ในส่วนของการตั้งค่า Profile

---

## 🤖 Orchestrator Built-in Tools

| Tool | Description | Input Examples |
|------|-------------|-------|
| `fetch` | Real HTTP request | `{ "url": "https://api.github.com/repos/..." }` |
| `web_search` | Search (Priority: Brave/Exa > Google > Scraper) | `{ "query": "latest news", "freshness": "week" }` |
| `shell_execute` | Run bash commands | `{ "command": "ls -la" }` |
| `read_file` | Read local file | `{ "path": "./config.json" }` |
| `write_file` | Write local file | `{ "path": "notes.txt", "content": "hello" }` |
| `memory_save` | Save fact to memory | `{ "key": "user_pref", "value": "likes rust" }` |
| `memory_query` | Query memory | `{ "query": "preference" }` |
| `memory_delete` | Delete memory | `{ "query": "user_pref" }` |
| `compute` | Math evaluation | `{ "expression": "a * 2", "variables": { "a": 10 } }` |
| `transform` | Text transforms | `uppercase`, `lowercase`, `reverse`, `length` |
| `aggregate` | Combine results | `sum`, `concat`, `array`, `count` |

---

## 💡 Advanced Example: Conditional Logic

You can define tasks that only run if a certain condition is met:

```json
{
  "id": "backup_plan",
  "name": "Run if primary fails",
  "toolName": "shell_execute",
  "toolInput": { "command": "./fix_script.sh" },
  "runIf": "${primary_task.status} === 'failed' || ${primary_task.data.length} === 0",
  "dependencies": ["primary_task"]
}
```

---

## 📝 Changelog

**Full changelog available in [CHANGELOG.md](CHANGELOG.md)**

### v3.1.9 (Current) - 🛡️ Reliability & Data Safety
- **Fixed:** Implemented **Atomic Writes** to prevent data corruption during crashes.
- **Added:** Automatic backup for corrupted storage files (no more data loss on read errors).
- **Improved:** Robustness of `MemoryManager` and `SequentialThinkingManager` storage.

### v3.1.8 - 🛡️ Type Safety & Stability
- **Fixed:** Critical syntax errors in Regex parsing within the Orchestrator.
- **Improved:** Enhanced Type Safety across the codebase, removing unused variables and unsafe `any` types.
- **Fixed:** Logic bug in `resolvePlaceholder` causing undefined results when accessing string properties (like `.length`).
- **Improved:** Cleaned up dead code and unused imports for better maintainability.

### v3.1.7 - 🛡️ Reliability & Validation
- **Enhanced Plan Validation:** Added strict structural checks for `ExecutionPlan` (ensures `id`, `toolName`, `toolInput`, and `dependencies` exist).
- **Self-Healing Bridge:** Improved `execute_conclusion` to automatically detect malformed plans and fallback to a safe default "Auto-Plan" to prevent execution crashes.
- **Clearer Error Reporting:** Validation errors now provide specific details about missing fields instead of generic `undefined` errors.
- **Improved Security:** Added extra checks for tool registration during plan validation.

### v3.1.4 - 📝 Documentation
- **Added:** Comprehensive "Environment Variables" table with all search provider keys
- **Added:** "Quick Setup (~/.bashrc)" section with copy-paste ready examples
- **Clarified:** At least one API key is required for web_search to function
- **Improved:** Distinguished between global setup (~/.bashrc) and MCP-specific config

### v3.1.2 - 📝 Documentation
- **Added:** Comprehensive web_search configuration section with provider details
- **Clarified:** web_search tool registration status and API key requirements
- **Added:** Provider priority fallback chain documentation (Brave > Exa > Google)
- **Added:** Usage examples for web_search tool

### v3.1.1 - 🐛 Bug Fixes
- **Critical:** Fixed array mutation bug in `evaluateOptions`
- **Critical:** Fixed empty array access with validation
- **High:** Fixed unsafe type casting with `Array.isArray()` check
- **Medium:** Added null safety checks in all `estimate*` methods

### v3.1.0 - 🧠 Major Brain Enhancement
- **Tree of Thoughts (ToT) Implementation:**
  - ✨ Added `generateOptions` - Generate 3 distinct options (Conservative, Balanced, Aggressive)
  - ✨ Added `evaluateOptions` - Multi-criteria scoring (feasibility 40%, impact 40%, risk 20%)
  - 🔧 Enhanced `selectOption` - Shows scores, uncertainty, and suggests next actions
- **Learning System:**
  - ✨ Added automatic learning from every execution (success/failure patterns)
  - ✨ Added `queryPastSolutions` - Cross-session learning via semantic search
  - 🔧 Enhanced `startSession` - Automatically queries similar past problems
- **Enhanced Types:**
  - ✨ Added `GeneratedOption`, `EvaluatedOption`, `LessonLearned`, `PastSolution`
  - ✨ Enhanced `ThoughtStep` with `uncertainty`, `reasoning`, `alternativeViews`
- **Technical:**
  - 🐛 Fixed TypeScript compilation errors
  - 🔧 Fixed VectorMemory integration (`search` method)

### v3.0.2
- **Docs:** Improved README usability by wrapping AI instructions and system prompts in copyable code blocks.

### v3.0.1
- **Docs:** Added Thai instructions for AI Agent memory and "mathinking" trigger configuration.

### v3.0.0 (Major Release)
- **Security:** Added strict directory path validation (`ALLOWED_ROOTS`) to prevent directory traversal attacks.
- **Resilience:** Enhanced `Auto-Mkdir` with security checks and command escaping.
- **Reliability:** Added configurable rate limiting and periodic session cleanup for the Brain.
- **Persistence:** Added backup storage system for session data to prevent data loss on corruption.
- **Scalability:** Added concurrency limits for Orchestrator tasks to prevent resource exhaustion.
- **Performance:** Optimized session loading and LRU cache age updates.

### v2.9.0
- **Improved:** Integrated full test system with Vitest support.
- **Added:** Formal unit tests for Orchestrator logic and conditional execution.

### v2.8.0
- **Security:** RCE protection via `vm` sandbox for `runIf` and `compute`.
- **Intelligence:** Smarter memory search using TF-IDF (`natural`).
- **Reliability:** Exponential backoff for task retries.

### v2.7.0
- **Improved:** `conclude` action is now non-blocking. If pending hypotheses exist, the system will automatically mark them as 'unverified' and allow the session to complete with a warning. This prevents workflow deadlocks.

### v2.6.2
- **Fixed:** Relaxed `verify_hypothesis` logic to allow updating *any* matching hypothesis regardless of its current status (e.g., re-verifying a 'refuted' hypothesis).

### v2.6.1
- **Improved: Smarter Hypothesis Matching.** `verify_hypothesis` now searches for the specific hypothesis text if provided. This prevents the "No pending hypothesis found" error when a hypothesis was already partially verified (status was no longer 'pending').

### v2.6.0
- **Added: `delete_thought` action.** Allows deleting specific thoughts from history (e.g., to remove an irrelevant pending hypothesis). The history is automatically re-indexed.
- **Added: `force` flag for `conclude`.** You can now force a conclusion even if there are pending hypotheses by setting `force: true`.
- **Improved:** Error messages for pending hypotheses now suggest using `force` or `delete_thought`.

### v2.5.2
- **Fixed: Deep Parameter Recovery.** The server can now recover `sessionId` even if the AI client accidentally injects it into the `action` string using XML-like tags (e.g., `verify_hypothesis<arg_key>...`). This significantly improves resilience against mangled tool calls.
- **Improved:** Smarter error handling for session lookup when parameters are malformed.

### v2.5.0
- **Added: "latest" Session Shortcut.** You can now use the keyword `"latest"` as a `sessionId` in any action. This prevents errors caused by AI hallucinating or mistyping long UUIDs.
- **Added: `list_sessions` action.** Easily list all available thinking sessions with their status and problem statements.
- **Fixed:** Robust action parsing to handle cases where AI clients might inject XML-like tags into the tool arguments.
- **Improved:** Automatic `lastSessionId` tracking across server restarts for better persistence.

### v2.3.0
- **Added: Auto-Plan Generation**. The Brain now automatically generates a valid `ExecutionPlan` if one isn't found in the conclusion, based on keywords and session context. This makes the autonomous bridge significantly more resilient and truly "auto-specifying".
- **Improved:** Heuristic-based intent detection for Thai and English keywords in conclusions.

### v2.2.2
- **Improved:** Autonomous Bridge error messages are now more descriptive, guiding the agent to include a JSON ExecutionPlan.
- **Improved:** Multi-process consistency: The Brain now reloads session data from disk on every action to ensure consistency when multiple instances are running.
- **Improved:** `errorResponse` now preserves the actual session status instead of defaulting to `in_progress`.

### v2.2.0
- **Improved:** `conclude` action logic: `thought` parameter is now optional, using the last thought or a default message if missing.
- **Fixed:** MCP error reporting: added `isError: true` flag to tool responses when an action fails, ensuring AI agents correctly recognize and recover from errors.
- **Improved:** Suggested actions: The system now provides more context-aware suggestions, including `execute_conclusion` after completing a session.
- **Improved:** Error messaging for pending hypotheses during conclusion.

### v2.1.0
- **Added:** New **"mathinking"** keyword trigger support for Gemini/Claude CLI protocols.
- **Improved:** Documentation and "How to Use" guides for autonomous workflows.
- **Optimized:** Tool descriptions for better AI context understanding.

### v2.0.0 (Major Release - Breaking Changes)
- **Renamed:** `sequential_thinking` → `mathinking_brain`.
- **Renamed:** `orchestrator` → `mathinking_body`.
- **Branding:** Realigned tool names with the "Brain & Body" architecture.
- **Improved:** Performance and stability for autonomous execution.

### v1.6.0
- **Added:** **Autonomous Brain-Body Bridge**. The Brain can now directly trigger the Body using the `execute_conclusion` action. If a conclusion contains a JSON `ExecutionPlan`, it can be executed automatically.
- **Improved:** AI Agents can now perform end-to-end tasks (Think -> Plan -> Execute) without user intervention between steps.

### v1.5.0
- **Upgraded:** Sequential Thinking is now **Reflective Graph Thinking**.
- **Added:** `self_critique` action to analyze risks and improve reasoning quality.
- **Added:** `merge_branches` action to synthesize information from multiple paths.
- **Added:** `summarize_history` action to condense context and maintain focus.

### v1.4.1
- **Added:** Anti-flood protection with automatic rate-limiting (800ms-1000ms cooldown between actions). This prevents AI providers (Gemini/Claude) from banning users due to excessive tool calls in tight loops.

### v1.4.0
- **Added:** New actions for session management: `clear_history` and `delete_session` for Sequential Thinking.
- **Added:** New action `delete_plan` for Orchestrator history.
- **Improved:** Web search scraper is now more robust with multiple regex patterns and title-link fallback.
- **Improved:** Automatic session pruning (keeps 100 most recent sessions) to manage disk space.
- **Improved:** Increased test coverage with a new extended test suite (`test-extended.ts`).

### v1.3.2
- **Added:** New `memory_delete` tool to the Orchestrator for managing the Knowledge Base.
- **Improved:** Robustness of JSON loading for both Sequential Thinking and Memory management.
- **Fixed:** Potential race condition in `mathinking_brain` initialization during server startup.

### v1.3.1
- **Fixed:** Critical bug in `mathinking_brain` where corrupted or empty session storage files would crash the server. Added robust error handling to initialize with fresh storage in these cases.

---

## 📜 License

MIT - Created by @gotza02