### runServer Source: https://context7.com/mettamatt/code-reasoning/llms.txt Programmatically bootstraps and starts the full MCP server, including tool registration, prompt handler setup, and transport configuration. ```APIDOC ## `runServer` — Programmatic Server Bootstrap ### Description The exported `runServer` function starts the full MCP server programmatically. It registers the `code-reasoning` tool, sets up prompt handlers, connects the stdio transport, and installs signal handlers for clean shutdown. ### Usage Start in normal mode: ```typescript import { runServer } from './src/server.js'; await runServer(); ``` Start with debug logging enabled: ```typescript // Equivalent to CLI --debug flag await runServer(true); ``` ### Expected stderr output on startup: ``` [info] Server initialized { version: '0.7.0', promptsEnabled: true } Using config directory: /home/user/.code-reasoning Prompt values will be stored at: /home/user/.code-reasoning/prompt_values.json PromptManager initialized with 5 prompts [info] Code-Reasoning logic ready { config: { debug: false, promptsEnabled: true } } [notice] šŸš€ Code-Reasoning MCP Server ready. ``` ``` -------------------------------- ### Run Start Commands Source: https://github.com/mettamatt/code-reasoning/blob/main/AGENTS.md Start the application in normal or debug mode. ```bash npm run start ``` ```bash npm run debug ``` -------------------------------- ### VS Code Settings with MCP Configuration Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Example VS Code settings file demonstrating font configuration and MCP server setup for code-reasoning. ```json { "editor.fontFamily": "Fira Code, monospace", "editor.fontSize": 14, "mcp": { "servers": { "code-reasoning": { "command": "code-reasoning", "args": ["--debug"] } } } } ``` -------------------------------- ### Install Code-Reasoning MCP Server Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/README.md Install the server using npx for immediate use or npm for global installation. ```bash # Option 1: Use with npx (recommended for most users) npx @mettamatt/code-reasoning ``` ```bash # Option 2: Install globally npm install -g @mettamatt/code-reasoning ``` -------------------------------- ### Example Log Output from Code-Reasoning Server Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Illustrates the server startup and initial thought processing logs when debug mode is enabled. ```text Starting Code-Reasoning MCP Server (streamlined v0.5.0)... { "logLevel": "INFO", "debug": true, "pid": 12345 } Code Reasoning Server logic handler initialized { "config": { "maxThoughtLength": 20000, "timeoutMs": 30000, "maxThoughts": 20, "logLevel": "INFO", "debug": true } } Received ListTools request šŸ’­ Thought 1/5 --- First, let's understand the problem: we need to design a simple calculator function. --- Thought processed successfully { "thought_number": 1, "is_revision": false, "branch_id": null, "next_thought_needed": true, "processingTimeMs": 5 } ``` -------------------------------- ### Comprehensive claude_desktop_config.json Example Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md A detailed configuration for Claude Desktop, including multiple MCP servers, default model, and session settings. ```json { "mcpServers": { "code-reasoning": { "command": "code-reasoning", "args": ["--debug"] }, "another-server": { "command": "another-command", "args": [] } }, "defaultModel": "claude-3-7-sonnet", "sessionDefaults": { "enableMultiModal": true } } ``` -------------------------------- ### Install Code Reasoning MCP Server Globally Source: https://context7.com/mettamatt/code-reasoning/llms.txt Install the server globally using npm for command-line access. Alternatively, use npx to run it directly without installation. ```bash npm install -g @mettamatt/code-reasoning ``` ```bash npx @mettamatt/code-reasoning ``` ```bash npx @mettamatt/code-reasoning --debug ``` -------------------------------- ### Programmatic Server Bootstrap (TypeScript) Source: https://context7.com/mettamatt/code-reasoning/llms.txt Demonstrates starting the Code-Reasoning MCP server programmatically using the `runServer` function. It can be started in normal mode or with debug logging enabled. ```typescript import { runServer } from './src/server.js'; // Start in normal mode await runServer(); // Start with debug logging enabled (equivalent to CLI --debug flag) await runServer(true); ``` -------------------------------- ### Prompt Persistence and Completion Source: https://context7.com/mettamatt/code-reasoning/llms.txt Shows how to get a prompt and then complete it, verifying that context like 'working_directory' is persisted. ```typescript // Prompt persistence + completion round-trip await client.getPrompt({ name: 'bug-analysis', arguments: { ..., working_directory: '/tmp/demo' } }); const comp = await client.complete({ ref: { type: 'ref/prompt', name: 'bug-analysis' }, argument: { name: 'working_directory', value: '' } }); assert.ok(comp.completion.values.includes('/tmp/demo')); ``` -------------------------------- ### Example Prompt for Sequential Thinking Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Use this prompt to guide Claude in breaking down tasks using the code-reasoning tool's sequential thinking capability. ```text Please help me design a simple REST API for a todo application. Use code-reasoning to break down the design process into steps. ``` ```text Please analyze this algorithm implementation and identify any bugs or inefficiencies. Use code-reasoning to break down your analysis step by step. ``` -------------------------------- ### Run Code-Reasoning MCP Server Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/configuration.md Basic command to start the MCP server. Use the --debug flag for more verbose output. ```bash code-reasoning ``` ```bash code-reasoning --debug ``` ```bash code-reasoning --help ``` ```bash code-reasoning --config-dir=/path/to/config ``` -------------------------------- ### Build Configuration with Debug Flag Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/configuration.md Example of building the server configuration, conditionally enabling debug mode based on a flag. The buildConfig helper is stateless and override-friendly. ```typescript import { buildConfig } from './utils/config.js'; const config = buildConfig(debugFlag ? { debug: true } : undefined); ``` -------------------------------- ### Thought Branching Example in JSON Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Illustrates exploring multiple approaches to a problem by branching thoughts. Use this to map out different design paths. ```json // Thought 1 (Main path) { "thought": "We need to design a system that can efficiently process large batches of data. Let's consider the main approaches.", "thought_number": 1, "total_thoughts": 6, "next_thought_needed": true } ``` ```json // Thought 2 (Main path) { "thought": "Main Approach: We could use a streaming architecture with message queues for handling data in real-time batches.", "thought_number": 2, "total_thoughts": 6, "next_thought_needed": true } ``` ```json // Thought 3 (Branch from Thought 1) { "thought": "Alternative Approach: We could also consider batch processing with scheduled ETL jobs instead of real-time processing.", "thought_number": 3, "total_thoughts": 6, "branch_from_thought": 1, "branch_id": "BatchETL", "next_thought_needed": true } ``` ```json // Thought 3 (Main path) { "thought": "For the streaming approach, we'll need components like: data producers, message broker (Kafka/RabbitMQ), stream processors, and data storage.", "thought_number": 3, "total_thoughts": 6, "next_thought_needed": true } ``` ```json // Thought 4 (BatchETL branch) { "thought": "For batch ETL, we'll need: data extraction jobs, transformation pipelines, data warehousing, and orchestration tools like Airflow.", "thought_number": 4, "total_thoughts": 6, "branch_from_thought": 3, "branch_id": "BatchETL", "next_thought_needed": true } ``` ```json // Thought 4 (Main path) { "thought": "Main approach implementation: 1) Set up Kafka topics, 2) Implement data producers with retry logic, 3) Create stream processors with Kafka Streams, 4) Store in timeseries DB.", "thought_number": 4, "total_thoughts": 6, "next_thought_needed": true } ``` ```json // Thought 5 (BatchETL branch) { "thought": "The batch approach is simpler and more cost-effective for this use case. Implementing with: 1) Daily data dumps, 2) Spark processing, 3) Data warehouse loading.", "thought_number": 5, "total_thoughts": 6, "branch_from_thought": 4, "branch_id": "BatchETL", "next_thought_needed": false } ``` ```json // Thought 5 (Main path) { "thought": "After comparing both approaches, the streaming architecture is preferred due to real-time requirements, despite higher complexity and cost.", "thought_number": 5, "total_thoughts": 6, "next_thought_needed": false } ``` -------------------------------- ### Thought Revision Example in JSON and Python Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Demonstrates correcting reasoning and code by revising previous thoughts. Use this to refine algorithms or design choices. ```json // Thought 1 { "thought": "I need to implement a sort algorithm. Based on requirements, quicksort seems appropriate due to average case O(n log n) performance.", "thought_number": 1, "total_thoughts": 4, "next_thought_needed": true } ``` ```python def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[0] left = [x for x in arr[1:] if x < pivot] right = [x for x in arr[1:] if x >= pivot] return quicksort(left) + [pivot] + quicksort(right) ``` ```json // Thought 3 (Revision of Thought 1) { "thought": "On second thought, I overlooked the fact that the data might be already partially sorted, which is quicksort's worst-case scenario (O(n²)). Also, stability is required. Mergesort would be a better choice since it guarantees O(n log n) regardless of input and is stable.", "thought_number": 3, "total_thoughts": 5, "is_revision": true, "revises_thought": 1, "next_thought_needed": true } ``` ```python def mergesort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = mergesort(arr[:mid]) right = mergesort(arr[mid:]) return merge(left, right) def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: # Note: <= preserves stability result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) result.extend(right[j:]) return result ``` ```json // Thought 4 (Revision of Thought 2) { "thought": "Let's implement mergesort instead:\n\ndef mergesort(arr):\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left = mergesort(arr[:mid])\n right = mergesort(arr[mid:])\n \n return merge(left, right)\n\ndef merge(left, right):\n result = []\n i = j = 0\n \n while i < len(left) and j < len(right):\n if left[i] <= right[j]: # Note: <= preserves stability\n result.append(left[i])\n i += 1\n else:\n result.append(right[j])\n j += 1\n \n result.extend(left[i:])\n result.extend(right[j:])\n return result", "thought_number": 4, "total_thoughts": 5, "is_revision": true, "revises_thought": 2, "next_thought_needed": true } ``` ```json // Thought 5 { "thought": "The mergesort implementation meets all requirements: O(n log n) worst-case time complexity, stability, and works well with the expected data patterns. The trade-off is O(n) extra space, but this is acceptable given the reliability benefits.", "thought_number": 5, "total_thoughts": 5, "next_thought_needed": false } ``` -------------------------------- ### Error Response Format for Invalid Thoughts Source: https://context7.com/mettamatt/code-reasoning/llms.txt When a thought payload fails validation or exceeds limits, an `isError: true` response is returned with structured guidance. This example shows an invalid call and its corresponding error response. ```json { "thought": "", "thought_number": 0, "total_thoughts": 0, "next_thought_needed": true } ``` ```json { "status": "failed", "error": "Validation Error: thought: Thought cannot be empty., thought_number: Number must be greater than 0, total_thoughts: Number must be greater than 0", "guidance": "The 'thought' field is empty or invalid. Must be a non-empty string below 20000 characters.", "example": { "thought": "Initial exploration of the problem.", "thought_number": 1, "total_thoughts": 5, "next_thought_needed": true } } ``` -------------------------------- ### Initialize and Use Code Reasoning Client Source: https://context7.com/mettamatt/code-reasoning/llms.txt Demonstrates how to initialize the client, connect to the transport, list available prompts, and apply the 'bug-analysis' prompt. Ensure the client is closed after use. ```typescript import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; const transport = new StdioClientTransport({ command: 'npx', args: ['-y', '@mettamatt/code-reasoning'], }); const client = new Client({ name: 'my-client', version: '1.0.0' }); await client.connect(transport); // List all available prompts const { prompts } = await client.listPrompts(); console.log(prompts.map(p => p.name)); // → ['architecture-decision', 'bug-analysis', 'code-review', 'feature-planning', 'refactoring-plan'] // Apply bug-analysis prompt — returns a message array ready to send to Claude const result = await client.getPrompt({ name: 'bug-analysis', arguments: { bug_behavior: 'Server crashes with SIGABRT on startup when PORT=443.', expected_behavior: 'Server should bind to port 443 and start normally.', affected_components: 'src/server.ts', reproduction_steps: '1. Set PORT=443\n2. Run npm start', working_directory: '/home/user/my-project', }, }); // result.messages[0].content.text contains structured Bug Analysis Process markdown console.log(result.messages[0].role); // 'user' console.log(result.messages[0].content.type); // 'text' // Text begins: "# Bug Analysis Process\nWorking Directory: /home/user/my-project\n..." await client.close(); ``` -------------------------------- ### Run Build Command Source: https://github.com/mettamatt/code-reasoning/blob/main/AGENTS.md Execute the build process for the project. ```bash npm run build ``` -------------------------------- ### List Tools and Call Code Reasoning Tool Source: https://context7.com/mettamatt/code-reasoning/llms.txt Demonstrates how to list available tools, find the 'code-reasoning' tool, and make a valid call to it for sequential thinking. ```typescript // Tool listing const { tools } = await client.listTools(); const tool = tools.find(t => t.name === 'code-reasoning'); assert.ok(tool.description.includes('sequential thinking')); // Valid thought round-trip const ok = await client.callTool({ name: 'code-reasoning', arguments: { thought: 'Test.', thought_number: 1, total_thoughts: 3, next_thought_needed: true }, }); assert.strictEqual(ok.isError, false); assert.strictEqual(JSON.parse(ok.content[0].text).status, 'processed'); ``` -------------------------------- ### PromptManager API Usage (TypeScript) Source: https://context7.com/mettamatt/code-reasoning/llms.txt Demonstrates instantiation, listing prompts, applying prompts with argument merging, retrieving stored values, and registering custom prompts at runtime. Ensure necessary imports are present. ```typescript import { PromptManager } from './src/prompts/manager.js'; import type { Prompt, PromptResult } from './src/prompts/types.js'; // Instantiate with a custom config directory (defaults to ~/.code-reasoning) const pm = new PromptManager('/tmp/my-config'); // List all registered prompts const all = pm.getAllPrompts(); console.log(all.map(p => p.name)); // → ['architecture-decision', 'bug-analysis', 'code-review', 'feature-planning', 'refactoring-plan'] // Apply a prompt — merges provided args with persisted values; provided args win const result: PromptResult = pm.applyPrompt('code-review', { code_path: 'src/utils/config.ts', requirements: 'Must export PATHS constant', working_directory: '/home/user/my-project', }); console.log(result.messages[0].content.text.substring(0, 60)); // → '# Code Review Template\n\nWorking Directory: /home/user/my' // Retrieve previously stored values for auto-complete const stored = pm.getStoredValues('code-review'); console.log(stored.working_directory); // '/home/user/my-project' console.log(stored.code_path); // 'src/utils/config.ts' // Register a custom prompt at runtime const customPrompt: Prompt = { name: 'security-audit', description: 'Audit code for security vulnerabilities', arguments: [ { name: 'target_path', description: 'File or directory to audit', required: true }, { name: 'threat_model', description: 'Known threats to check against', required: false }, ], }; pm.registerPrompt(customPrompt, (args) => ({ messages: [{ role: 'user', content: { type: 'text', text: `Use code-reasoning to audit ${args.target_path} for security issues.\nThreat model: ${args.threat_model ?? 'OWASP Top 10'}`, }, }], })); const auditResult = pm.applyPrompt('security-audit', { target_path: 'src/auth/' }); console.log(auditResult.messages[0].content.text); // → 'Use code-reasoning to audit src/auth/ for security issues.\nThreat model: OWASP Top 10' ``` -------------------------------- ### Configure Claude Desktop for Code-Reasoning Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/README.md Integrate the Code-Reasoning MCP Server into Claude Desktop by adding its configuration to the Claude Desktop settings file. ```json { "mcpServers": { "code-reasoning": { "command": "npx", "args": ["-y", "@mettamatt/code-reasoning"] } } } ``` -------------------------------- ### Run Format Commands Source: https://github.com/mettamatt/code-reasoning/blob/main/AGENTS.md Format the codebase according to Prettier rules, with an option to check formatting. ```bash npm run format ``` ```bash npm run format:check ``` -------------------------------- ### Configuration Paths (TypeScript) Source: https://context7.com/mettamatt/code-reasoning/llms.txt Shows how to import and use constants for filesystem paths related to prompt persistence. PATHS is a frozen object combining configuration directory and prompt values file paths. ```typescript import { CONFIG_DIR, PROMPT_VALUES_FILE, PATHS } from './src/utils/config.js'; console.log(CONFIG_DIR); // '/home/user/.code-reasoning' console.log(PROMPT_VALUES_FILE); // '/home/user/.code-reasoning/prompt_values.json' // PATHS is a frozen object combining both: console.log(PATHS.configDir); // '/home/user/.code-reasoning' console.log(PATHS.promptFile); // '/home/user/.code-reasoning/prompt_values.json' ``` -------------------------------- ### Basic Code-Reasoning MCP Server Configuration Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Configure the code-reasoning MCP server with a basic command and no arguments. ```json // claude_desktop_config.json { "mcpServers": { "code-reasoning": { "command": "code-reasoning", "args": [] } } } ``` -------------------------------- ### Configuration Paths Source: https://context7.com/mettamatt/code-reasoning/llms.txt Exposes filesystem paths used by the prompt persistence system, including the main configuration directory and the prompt values file. ```APIDOC ## Configuration Paths (`src/utils/config.ts`) ### Description Filesystem paths used by the prompt persistence system. ### Constants - **`CONFIG_DIR`** (string): The default configuration directory. - **`PROMPT_VALUES_FILE`** (string): The path to the file where prompt values are stored. - **`PATHS`** (object): A frozen object combining `configDir` and `promptFile`. ### Usage ```typescript import { CONFIG_DIR, PROMPT_VALUES_FILE, PATHS } from './src/utils/config.js'; console.log(CONFIG_DIR); // '/home/user/.code-reasoning' console.log(PROMPT_VALUES_FILE); // '/home/user/.code-reasoning/prompt_values.json' // PATHS is a frozen object combining both: console.log(PATHS.configDir); // '/home/user/.code-reasoning' console.log(PATHS.promptFile); // '/home/user/.code-reasoning/prompt_values.json' ``` ``` -------------------------------- ### Run Default Quality Gate Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/testing.md Executes the default quality gate, which currently includes linting. ```bash npm test ``` -------------------------------- ### Run Test Command Source: https://github.com/mettamatt/code-reasoning/blob/main/AGENTS.md Execute the test suite, which includes ESLint. ```bash npm run test ``` -------------------------------- ### Basic Sequential Thinking with code-reasoning Tool Source: https://context7.com/mettamatt/code-reasoning/llms.txt Demonstrates a basic sequential reasoning flow for solving a programming problem. Ensure `next_thought_needed` is `false` only when the reasoning is complete. The tool enforces limits on the number of thoughts and their length. ```json // ── Basic sequential flow ────────────────────────────────────────────────── // Thought 1 { "thought": "Problem: implement a function that finds duplicate elements in an array. Multiple approaches exist: nested loops O(n²), hash table O(n), sorting O(n log n).", "thought_number": 1, "total_thoughts": 3, "next_thought_needed": true } // → Response: { "status": "processed", "thought_number": 1, "total_thoughts": 3, "next_thought_needed": true, "branches": [], "thought_history_length": 1 } ``` ```json // Thought 2 { "thought": "Choosing hash table approach for O(n) time. Use a Set to track seen elements, a second Set to accumulate duplicates.", "thought_number": 2, "total_thoughts": 3, "next_thought_needed": true } ``` ```json // Thought 3 — final { "thought": "function findDuplicates(arr) { const seen = new Set(); const dups = new Set(); for (const x of arr) { seen.has(x) ? dups.add(x) : seen.add(x); } return [...dups]; } // findDuplicates([1,2,3,2,4,1]) → [2, 1]", "thought_number": 3, "total_thoughts": 3, "next_thought_needed": false } // → Response: { "status": "processed", "thought_number": 3, "total_thoughts": 3, "next_thought_needed": false, "branches": [], "thought_history_length": 3 } ``` -------------------------------- ### Running Tests (Bash) Source: https://context7.com/mettamatt/code-reasoning/llms.txt Commands for building and running the ESLint and regression test suite, or running regression tests only after a prior build. ```bash # Build then run ESLint + regression test suite against the compiled output npm test # Regression tests only (requires prior build) npm run test:regression ``` -------------------------------- ### Project Structure Overview Source: https://github.com/mettamatt/code-reasoning/blob/main/README.md An overview of the main directories and files within the Code Reasoning MCP Server project. ```plaintext ā”œā”€ā”€ index.ts # Entry point ā”œā”€ā”€ src/ # Implementation source files └── test/ # Placeholder for future test utilities ``` -------------------------------- ### Code-Reasoning MCP Server Configuration with Debugging Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Configure the code-reasoning MCP server with the debug flag enabled for detailed logging. ```json // claude_desktop_config.json { "mcpServers": { "code-reasoning": { "command": "code-reasoning", "args": ["--debug"] } } } ``` -------------------------------- ### Run Lint Commands Source: https://github.com/mettamatt/code-reasoning/blob/main/AGENTS.md Perform linting on the codebase, with an option to fix issues. ```bash npm run lint ``` ```bash npm run lint:fix ``` -------------------------------- ### Configure VS Code for Code Reasoning Source: https://context7.com/mettamatt/code-reasoning/llms.txt Integrate the code-reasoning MCP server into VS Code by adding its configuration to your user settings or a workspace-specific mcp.json file. ```json { "mcp": { "servers": { "code-reasoning": { "command": "npx", "args": ["-y", "@mettamatt/code-reasoning", "--debug"] } } } } ``` -------------------------------- ### Debug Recursive Fibonacci with Stack Overflow Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Illustrates debugging a recursive Fibonacci function, addressing stack overflow and inefficiency by adding base cases, memoization, and finally an iterative solution. ```json // Thought 1 { "thought": "The problem is a stack overflow error in a recursive function to calculate Fibonacci numbers. Let's first understand the current implementation.", "thought_number": 1, "total_thoughts": 5, "next_thought_needed": true } ``` ```javascript // Thought 2 { "thought": "Here's the problematic code:\n\nfunction fibonacci(n) {\n return fibonacci(n - 1) + fibonacci(n - 2);\n}\n The issue is there's no base case, so it recurses infinitely. Also, this is extremely inefficient due to recalculating values repeatedly.", "thought_number": 2, "total_thoughts": 5, "next_thought_needed": true } ``` ```javascript // Thought 3 { "thought": "Let's fix the base case issue first:\n\nfunction fibonacci(n) {\n if (n <= 0) return 0; if (n === 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } This prevents infinite recursion, but is still inefficient for large n values.", "thought_number": 3, "total_thoughts": 5, "next_thought_needed": true } ``` ```javascript // Thought 4 { "thought": "To improve efficiency, we should use memoization to store previously calculated values:\n\nfunction fibonacci(n, memo = {}) {\n if (n <= 0) return 0; if (n === 1) return 1; if (memo[n]) return memo[n]; memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo); return memo[n]; } This caches results to prevent redundant calculations.", "thought_number": 4, "total_thoughts": 5, "next_thought_needed": true } ``` ```javascript // Thought 5 { "thought": "For even better performance, we could use an iterative approach instead of recursion:\n\nfunction fibonacci(n) {\n if (n <= 0) return 0; if (n === 1) return 1; let a = 0, b = 1; for (let i = 2; i <= n; i++) { const temp = a + b; a = b; b = temp; } return b; } This iterative solution has O(n) time complexity and constant space complexity, avoiding both stack overflow and inefficiency issues.", "thought_number": 5, "total_thoughts": 5, "next_thought_needed": false } ``` -------------------------------- ### Enable Debug Logging for Code-Reasoning Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Run the code-reasoning command with the --debug flag to enable detailed logging output. ```bash code-reasoning --debug ``` -------------------------------- ### Prompt Value Persistence Structure Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/configuration.md Illustrates the JSON structure for storing prompt argument values, including global and prompt-specific settings. ```json { "global": { "working_directory": "/path/to/project" }, "prompts": { "architecture-decision": { "decision_context": "Previous value", "constraints": "Previous constraints", "options": "Previous options" } // Other prompts... } } ``` -------------------------------- ### Claude Desktop MCP Server Configuration Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/configuration.md JSON configuration for integrating the MCP server with Claude Desktop. Specifies the command and arguments to launch the server. ```json { "mcpServers": { "code-reasoning": { "command": "code-reasoning", "args": ["--debug"] } } } ``` -------------------------------- ### PromptManager API Source: https://context7.com/mettamatt/code-reasoning/llms.txt The PromptManager class allows for managing prompt registration, argument validation, stored value merging, and persistence. It can be instantiated directly for custom configurations. ```APIDOC ## PromptManager API (TypeScript) ### Description The `PromptManager` class manages prompt registration, argument validation, stored-value merging, and persistence. It is instantiated internally by the server but can also be used directly. ### Instantiation ```typescript import { PromptManager } from './src/prompts/manager.js'; // Instantiate with a custom config directory (defaults to ~/.code-reasoning) const pm = new PromptManager('/tmp/my-config'); ``` ### Methods #### `getAllPrompts()` **Description**: Lists all registered prompts. **Usage**: ```typescript const all = pm.getAllPrompts(); console.log(all.map(p => p.name)); // → ['architecture-decision', 'bug-analysis', 'code-review', 'feature-planning', 'refactoring-plan'] ``` #### `applyPrompt(promptName, args)` **Description**: Applies a prompt, merging provided arguments with persisted values. Provided arguments take precedence. **Parameters**: - `promptName` (string): The name of the prompt to apply. - `args` (object): An object containing arguments for the prompt. **Usage**: ```typescript const result = pm.applyPrompt('code-review', { code_path: 'src/utils/config.ts', requirements: 'Must export PATHS constant', working_directory: '/home/user/my-project', }); console.log(result.messages[0].content.text.substring(0, 60)); // → '# Code Review Template\n\nWorking Directory: /home/user/my' ``` #### `getStoredValues(promptName)` **Description**: Retrieves previously stored values for a given prompt, useful for auto-completion. **Parameters**: - `promptName` (string): The name of the prompt to retrieve stored values for. **Usage**: ```typescript const stored = pm.getStoredValues('code-review'); console.log(stored.working_directory); // '/home/user/my-project' console.log(stored.code_path); // 'src/utils/config.ts' ``` #### `registerPrompt(prompt, handler)` **Description**: Registers a custom prompt at runtime. **Parameters**: - `prompt` (Prompt): The prompt definition object. - `handler` (function): A function that generates the prompt messages based on arguments. **Prompt Definition Example**: ```typescript const customPrompt = { name: 'security-audit', description: 'Audit code for security vulnerabilities', arguments: [ { name: 'target_path', description: 'File or directory to audit', required: true }, { name: 'threat_model', description: 'Known threats to check against', required: false }, ], }; ``` **Usage**: ```typescript pm.registerPrompt(customPrompt, (args) => ({ messages: [{ role: 'user', content: { type: 'text', text: `Use code-reasoning to audit ${args.target_path} for security issues.\nThreat model: ${args.threat_model ?? 'OWASP Top 10'}`, }, }], })); const auditResult = pm.applyPrompt('security-audit', { target_path: 'src/auth/' }); console.log(auditResult.messages[0].content.text); // → 'Use code-reasoning to audit src/auth/ for security issues.\nThreat model: OWASP Top 10' ``` ``` -------------------------------- ### Implement Array Duplicate Finder with Hash Table Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Demonstrates a sequential thought process for implementing an efficient O(n) solution to find duplicate elements in an array using a Set in JavaScript. ```json // Thought 1 { "thought": "First, let's understand the problem: we need to implement a function that finds duplicate elements in an array.", "thought_number": 1, "total_thoughts": 4, "next_thought_needed": true } ``` ```json // Thought 2 { "thought": "There are multiple approaches we could take: using nested loops (O(n²)), using a hash table (O(n)), or sorting and then finding adjacent duplicates (O(n log n)).", "thought_number": 2, "total_thoughts": 4, "next_thought_needed": true } ``` ```json // Thought 3 { "thought": "Let's implement the hash table approach since it's efficient in terms of time complexity (O(n)). We'll use a Set or Map to track elements we've seen.", "thought_number": 3, "total_thoughts": 4, "next_thought_needed": true } ``` ```javascript // Thought 4 { "thought": "Here's the JavaScript implementation:\n\nfunction findDuplicates(arr) {\n const seen = new Set();\n const duplicates = new Set();\n \n for (const item of arr) {\n if (seen.has(item)) {\n duplicates.add(item);\n } else {\n seen.add(item);\n }\n }\n \n return Array.from(duplicates);\n}\n This solution is O(n) in time complexity and handles edge cases properly.", "thought_number": 4, "total_thoughts": 4, "next_thought_needed": false } ``` -------------------------------- ### Default Configuration Values Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/configuration.md Shows default values for the configuration object, including the boolean flag for enabling prompt functionality. ```typescript { promptsEnabled: true, // Enables prompt functionality // Other configuration values... } ``` -------------------------------- ### Run Full Validation Pipeline Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/testing.md Executes the full validation pipeline, including formatting sources, applying lint fixes, and rebuilding TypeScript output. ```bash npm run validate ``` -------------------------------- ### VS Code MCP Server Configuration Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/examples.md Configure the code-reasoning MCP server within VS Code settings for integration. ```json // settings.json or .vscode/mcp.json { "mcp": { "servers": { "code-reasoning": { "command": "code-reasoning", "args": ["--debug"] } } } } ``` -------------------------------- ### Enable Prompts in Configuration Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/configuration.md Check if prompts are enabled in the configuration object before initializing the PromptManager. Requires the CONFIG_DIR to be set. ```typescript if (config.promptsEnabled) { promptManager = new PromptManager(CONFIG_DIR); console.error('Prompts capability enabled'); } ``` -------------------------------- ### Prompt Argument Auto-Completion Source: https://context7.com/mettamatt/code-reasoning/llms.txt Utilizes the `complete` method to retrieve previously stored argument values for a prompt, enabling client-side auto-filling. Values are automatically persisted on `GetPrompt` calls. ```typescript // After a prior getPrompt call stored working_directory = '/home/user/my-project' const completion = await client.complete({ ref: { type: 'ref/prompt', name: 'bug-analysis' }, argument: { name: 'working_directory', value: '' }, }); console.log(completion.completion.values); // → ['/home/user/my-project'] ← retrieved from ~/.code-reasoning/prompt_values.json ``` -------------------------------- ### VS Code User Settings for MCP Server Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/configuration.md JSON configuration for VS Code user settings to integrate the MCP server. Defines the command and arguments for the server. ```json { "mcp": { "servers": { "code-reasoning": { "command": "code-reasoning", "args": ["--debug"] } } } } ``` -------------------------------- ### Read File Operation Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/prompts.md Use this command to read the content of a specific file. Ensure you provide the absolute path to the file. ```python read_file("/path/to/file") ``` -------------------------------- ### List Directory Contents Operation Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/prompts.md This command lists the contents of a specified directory. Provide the absolute path to the directory. ```python list_directory("/path/to/directory") ``` -------------------------------- ### VS Code Workspace Settings for MCP Server Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/configuration.md JSON configuration for VS Code workspace settings to integrate the MCP server. Defines the command and arguments for the server. ```json { "servers": { "code-reasoning": { "command": "code-reasoning", "args": ["--debug"] } } } ``` -------------------------------- ### Trigger MCP Server in Chat Source: https://github.com/mettamatt/code-reasoning/blob/main/README.md Append this phrase to your chat messages to activate the Code Reasoning MCP server for sequential thinking. ```text Use sequential thinking to reason about this. ``` -------------------------------- ### Configure VS Code MCP Servers Source: https://github.com/mettamatt/code-reasoning/blob/main/README.md Integrate the code-reasoning MCP server into your VS Code settings. This enables VS Code to leverage the server for programming tasks. ```json { "mcp": { "servers": { "code-reasoning": { "command": "npx", "args": ["-y", "@mettamatt/code-reasoning"] } } } } ``` -------------------------------- ### Branching Thoughts with `branch_from_thought` and `branch_id` Source: https://context7.com/mettamatt/code-reasoning/llms.txt Use `branch_from_thought` and `branch_id` together to explore alternative solution paths without losing the main thread. These fields cannot be combined with revision fields. ```json { "thought": "Design a batch data pipeline. Two main candidates: real-time streaming vs. scheduled ETL.", "thought_number": 1, "total_thoughts": 6, "next_thought_needed": true } ``` ```json { "thought": "Streaming: Kafka topics + Kafka Streams processors + time-series DB. Low latency, high complexity.", "thought_number": 2, "total_thoughts": 6, "next_thought_needed": true } ``` ```json { "thought": "ETL branch: daily Spark jobs → data warehouse. Higher latency, simpler ops, lower cost.", "thought_number": 3, "total_thoughts": 6, "branch_from_thought": 1, "branch_id": "batch-etl", "next_thought_needed": true } ``` ```json { "thought": "ETL conclusion: given non-realtime SLA and small team, batch ETL is preferred. Recommend Airflow + Spark + Snowflake.", "thought_number": 4, "total_thoughts": 6, "branch_from_thought": 3, "branch_id": "batch-etl", "next_thought_needed": false } ``` ```json { "thought": "After evaluating both branches, streaming wins only if sub-second latency is required. For this use case, adopt the batch-etl recommendation.", "thought_number": 5, "total_thoughts": 6, "next_thought_needed": false } ``` -------------------------------- ### Search Code Operation Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/prompts.md Use this command to search for specific patterns within files in a directory. Specify the directory path and the search pattern. ```python search_code("/path/to/directory", "search pattern") ``` -------------------------------- ### Call Code Reasoning Tool with Validation Error Source: https://context7.com/mettamatt/code-reasoning/llms.txt Illustrates how the 'code-reasoning' tool handles validation errors when provided with invalid arguments. ```typescript // Validation error path const err = await client.callTool({ name: 'code-reasoning', arguments: { thought: '', thought_number: 0, total_thoughts: 0, next_thought_needed: true }, }); assert.strictEqual(err.isError, true); assert.match(JSON.parse(err.content[0].text).error, /Validation Error/); ``` -------------------------------- ### Target MCP Regression Suite Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/testing.md Rebuilds the project and targets only the MCP regression suite for execution. ```bash npm run test:regression ``` -------------------------------- ### Edit File Block Operation Source: https://github.com/mettamatt/code-reasoning/blob/main/docs/prompts.md This command allows modification of a specific text block within a file. Provide the file path, the old text to be replaced, and the new text. ```python edit_block("/path/to/file", "old_text", "new_text") ``` -------------------------------- ### Revising Thoughts with `is_revision` and `revises_thought` Source: https://context7.com/mettamatt/code-reasoning/llms.txt Use `is_revision: true` and `revises_thought` together to mark a thought as correcting earlier reasoning. Branch fields must be absent when using revision fields. ```json { "thought": "Use quicksort: average O(n log n) performance is sufficient.", "thought_number": 1, "total_thoughts": 4, "next_thought_needed": true } ``` ```python def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[0] return quicksort([x for x in arr[1:] if x < pivot]) + [pivot] + quicksort([x for x in arr[1:] if x >= pivot]) ``` ```json { "thought": "Correction: data is nearly sorted (quicksort worst-case O(n²)) AND stability is required. Mergesort is the correct choice: O(n log n) guaranteed, stable.", "thought_number": 3, "total_thoughts": 5, "is_revision": true, "revises_thought": 1, "next_thought_needed": true } ``` ```python def mergesort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 L, R = mergesort(arr[:mid]), mergesort(arr[mid:]) res, i, j = [], 0, 0 while i < len(L) and j < len(R): if L[i] <= R[j]: res.append(L[i]); i += 1 else: res.append(R[j]); j += 1 return res + L[i:] + R[j:] ``` ```json { "thought": "Mergesort satisfies all constraints: stable, O(n log n) worst-case, O(n) extra space (acceptable). Solution complete.", "thought_number": 5, "total_thoughts": 5, "next_thought_needed": false } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.