├── smithery.yaml ├── dist ├── server.d.ts ├── src │ ├── types │ │ ├── reasoning-patterns │ │ │ ├── pdr.js │ │ │ └── base.js │ │ └── index.js │ ├── utils │ │ └── execution.js │ └── config.js ├── utils │ ├── validation.d.ts │ └── validation.js ├── types │ ├── index.js │ └── reasoning-patterns │ │ ├── base.js │ │ ├── beam-search.js │ │ ├── tree-of-thought.js │ │ ├── graph-of-thought.js │ │ ├── mcts.js │ │ ├── index.js │ │ ├── index.d.ts │ │ └── tree-of-thought.d.ts ├── tools │ ├── index.d.ts │ ├── session-management.d.ts │ ├── metacognitive.d.ts │ ├── index.js │ ├── debugging-approach.d.ts │ ├── mental-model.d.ts │ ├── creative-thinking.d.ts │ ├── decision-framework.d.ts │ ├── collaborative-reasoning.d.ts │ ├── metacognitive.js │ ├── socratic-method.d.ts │ ├── creative-thinking.js │ ├── socratic-method.js │ ├── structured-argumentation.js │ ├── collaborative-reasoning.js │ ├── debugging-approach.js │ ├── visual-reasoning.js │ ├── scientific-method.d.ts │ ├── systems-thinking.js │ ├── decision-framework.js │ ├── scientific-method.js │ ├── mental-model.js │ ├── structured-argumentation.d.ts │ ├── sequential-thinking.d.ts │ ├── systems-thinking.d.ts │ ├── visual-reasoning.d.ts │ ├── session-management.js │ ├── mcts.js │ ├── mcts.d.ts │ ├── beam-search.js │ ├── tree-of-thought.d.ts │ └── tree-of-thought.js ├── state │ ├── SessionManager.d.ts │ └── SessionManager.js ├── unified-server.d.ts ├── index.js ├── index.d.ts ├── server.js ├── registry │ ├── tool-registry.d.ts │ └── tool-registry.js ├── config.d.ts ├── config.js ├── cli │ └── stdio-server.js └── handlers │ └── reasoning-patterns │ ├── tree-of-thought.d.ts │ ├── graph-of-thought.d.ts │ ├── beam-search.d.ts │ └── mcts.d.ts ├── .dockerignore ├── tsconfig.json ├── vitest.config.ts ├── src ├── tools │ └── operations │ │ ├── session │ │ ├── session-export.ts │ │ ├── session-info.ts │ │ └── session-import.ts │ │ ├── core │ │ ├── visual-reasoning.ts │ │ ├── scientific-method.ts │ │ ├── mental-model.ts │ │ ├── debugging-approach.ts │ │ ├── metacognitive-monitoring.ts │ │ └── creative-thinking.ts │ │ ├── registry.ts │ │ ├── base.ts │ │ ├── patterns │ │ ├── beam-search.ts │ │ ├── graph-of-thought.ts │ │ ├── tree-of-thought.ts │ │ └── mcts.ts │ │ ├── analysis │ │ └── research.ts │ │ └── collaborative │ │ └── systems-thinking.ts ├── utils │ ├── validation.ts │ └── execution.ts ├── types │ └── reasoning-patterns │ │ ├── pdr-config.ts │ │ ├── index.ts │ │ ├── pdr.ts │ │ └── tree-of-thought.ts └── resources │ └── examples │ ├── optimization.md │ ├── simulation.md │ ├── scientific-method.md │ ├── creative-thinking.md │ ├── systems-thinking.md │ ├── index.md │ ├── ethical-analysis.md │ └── causal-analysis.md ├── LICENSE ├── .gitignore ├── .npmignore ├── cli ├── server.ts └── stdio-server.ts ├── package.json ├── reports └── session-persistence-bug.md ├── refactoring-summary.md ├── CLAUDE.md └── docs └── clear-thought-operations.md /smithery.yaml: -------------------------------------------------------------------------------- 1 | runtime: "typescript" -------------------------------------------------------------------------------- /dist/server.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Server.ts - HTTP Server Entry Point 3 | * 4 | * Uses the unified server for HTTP deployments 5 | */ 6 | export {}; 7 | //# sourceMappingURL=server.d.ts.map -------------------------------------------------------------------------------- /dist/src/types/reasoning-patterns/pdr.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Progressive Deep Reasoning (PDR) Types 3 | * Based on Deep Research methodology for multi-pass exploration 4 | */ 5 | export {}; 6 | -------------------------------------------------------------------------------- /dist/utils/validation.d.ts: -------------------------------------------------------------------------------- 1 | import { JSONSchema7 } from "json-schema"; 2 | export declare function validateWithErrors(data: unknown, schema: JSONSchema7): void; 3 | //# sourceMappingURL=validation.d.ts.map -------------------------------------------------------------------------------- /dist/src/types/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Type definitions for the Clear Thought MCP server 3 | * 4 | * This file contains all the data structures used by the various thinking tools 5 | * in the Clear Thought MCP server. 6 | */ 7 | export {}; 8 | -------------------------------------------------------------------------------- /dist/src/types/reasoning-patterns/base.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Base types for all reasoning patterns 3 | * 4 | * These interfaces provide the foundation for implementing 5 | * various reasoning structures in the sequential thinking framework. 6 | */ 7 | export {}; 8 | -------------------------------------------------------------------------------- /dist/types/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Type definitions for the Clear Thought MCP server 3 | * 4 | * This file contains all the data structures used by the various thinking tools 5 | * in the Clear Thought MCP server. 6 | */ 7 | export {}; 8 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /dist/types/reasoning-patterns/base.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Base types for all reasoning patterns 3 | * 4 | * These interfaces provide the foundation for implementing 5 | * various reasoning structures in the sequential thinking framework. 6 | */ 7 | export {}; 8 | //# sourceMappingURL=base.js.map -------------------------------------------------------------------------------- /dist/types/reasoning-patterns/beam-search.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Beam Search Reasoning Pattern Types 3 | * 4 | * Maintains multiple promising paths simultaneously, exploring them 5 | * in parallel with periodic evaluation and pruning. 6 | */ 7 | export {}; 8 | //# sourceMappingURL=beam-search.js.map -------------------------------------------------------------------------------- /dist/types/reasoning-patterns/tree-of-thought.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Tree of Thought (ToT) Reasoning Pattern Types 3 | * 4 | * Enables systematic exploration of multiple reasoning paths with 5 | * explicit branching and evaluation. 6 | */ 7 | export {}; 8 | //# sourceMappingURL=tree-of-thought.js.map -------------------------------------------------------------------------------- /dist/types/reasoning-patterns/graph-of-thought.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Graph of Thought (GoT) Reasoning Pattern Types 3 | * 4 | * Enables non-hierarchical connections between thoughts with support 5 | * for complex reasoning patterns including cycles and multiple connections. 6 | */ 7 | export {}; 8 | //# sourceMappingURL=graph-of-thought.js.map -------------------------------------------------------------------------------- /dist/types/reasoning-patterns/mcts.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Monte Carlo Tree Search (MCTS) Reasoning Pattern Types 3 | * 4 | * Combines tree exploration with random sampling for decision-making 5 | * under uncertainty using the four phases: selection, expansion, 6 | * simulation, and backpropagation. 7 | */ 8 | export {}; 9 | //# sourceMappingURL=mcts.js.map -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .git 4 | .gitignore 5 | .dockerignore 6 | Dockerfile 7 | docker-compose.yml 8 | .env 9 | .env.* 10 | *.log 11 | .DS_Store 12 | coverage 13 | .nyc_output 14 | .vscode 15 | .idea 16 | *.md 17 | !README.md 18 | temp 19 | trees 20 | specs 21 | tests 22 | __tests__ 23 | *.test.ts 24 | *.spec.ts 25 | .github 26 | .eslintrc* 27 | .prettierrc* -------------------------------------------------------------------------------- /dist/tools/index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Tool Index - All tools self-register on import 3 | * This file serves as the central import point for tool registration 4 | */ 5 | export { ToolRegistry } from '../registry/tool-registry.js'; 6 | export declare function loadAllTools(): Promise; 7 | export declare function getToolStats(): { 8 | total: any; 9 | byCategory: any; 10 | names: any; 11 | }; 12 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2022", 4 | "module": "NodeNext", 5 | "moduleResolution": "NodeNext", 6 | "lib": ["ES2023"], 7 | "outDir": "./dist", 8 | "strict": true, 9 | "esModuleInterop": true, 10 | "skipLibCheck": true, 11 | "forceConsistentCasingInFileNames": true, 12 | "resolveJsonModule": true, 13 | "declaration": false, 14 | "sourceMap": false, 15 | "allowSyntheticDefaultImports": true 16 | }, 17 | "include": ["src/**/*"], 18 | "exclude": ["node_modules", "dist", "coverage", "**/*.test.ts", "tests/**/*"] 19 | } 20 | -------------------------------------------------------------------------------- /dist/types/reasoning-patterns/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Reasoning Patterns Type Definitions 3 | * 4 | * This module exports all type definitions for advanced reasoning patterns 5 | * that extend beyond traditional chain-of-thought sequential thinking. 6 | */ 7 | // Base types 8 | export * from './base.js'; 9 | // Tree of Thought 10 | export * from './tree-of-thought.js'; 11 | // Graph of Thought 12 | export * from './graph-of-thought.js'; 13 | // Beam Search 14 | export * from './beam-search.js'; 15 | // Monte Carlo Tree Search 16 | export * from './mcts.js'; 17 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import path from "node:path"; 2 | import { defineConfig } from "vitest/config"; 3 | 4 | export default defineConfig({ 5 | test: { 6 | globals: true, 7 | environment: "node", 8 | coverage: { 9 | provider: "v8", 10 | reporter: ["text", "json", "html"], 11 | exclude: [ 12 | "node_modules/", 13 | "dist/", 14 | "tests/", 15 | "**/*.d.ts", 16 | "**/*.config.*", 17 | "**/mockData.ts", 18 | ], 19 | }, 20 | }, 21 | resolve: { 22 | alias: { 23 | "@": path.resolve(__dirname, "./src"), 24 | }, 25 | extensions: [".ts", ".js"], 26 | }, 27 | }); 28 | -------------------------------------------------------------------------------- /src/tools/operations/session/session-export.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Session Export Operation 3 | * 4 | * Exports session data for persistence or analysis 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class SessionExportOperation extends BaseOperation { 10 | name = 'session_export'; 11 | category = 'session'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState } = context; 15 | 16 | return this.createResult({ 17 | sessionData: sessionState.export(), 18 | }); 19 | } 20 | } 21 | 22 | export default new SessionExportOperation(); -------------------------------------------------------------------------------- /dist/utils/validation.js: -------------------------------------------------------------------------------- 1 | import Ajv from "ajv"; 2 | const ajv = new Ajv({ allErrors: true }); 3 | export function validateWithErrors(data, schema) { 4 | const validate = ajv.compile(schema); 5 | const valid = validate(data); 6 | if (!valid) { 7 | const errors = validate.errors || []; 8 | const errorMessages = errors.map((err) => { 9 | const path = err.instancePath || ''; 10 | const message = err.message || 'Validation error'; 11 | return path ? `${path}: ${message}` : message; 12 | }); 13 | throw new Error(`Validation failed: ${errorMessages.join(', ')}`); 14 | } 15 | } 16 | //# sourceMappingURL=validation.js.map -------------------------------------------------------------------------------- /src/tools/operations/session/session-info.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Session Info Operation 3 | * 4 | * Returns current session information and statistics 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class SessionInfoOperation extends BaseOperation { 10 | name = 'session_info'; 11 | category = 'session'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState } = context; 15 | 16 | return this.createResult({ 17 | sessionId: sessionState.sessionId, 18 | stats: sessionState.getStats(), 19 | }); 20 | } 21 | } 22 | 23 | export default new SessionInfoOperation(); -------------------------------------------------------------------------------- /src/utils/validation.ts: -------------------------------------------------------------------------------- 1 | import Ajv from "ajv"; 2 | import type { JSONSchema7 } from "json-schema"; 3 | 4 | const ajv = new (Ajv as any)({ allErrors: true }); 5 | 6 | export function validateWithErrors(data: unknown, schema: JSONSchema7): void { 7 | const validate = ajv.compile(schema); 8 | const valid = validate(data); 9 | 10 | if (!valid) { 11 | const errors = validate.errors || []; 12 | const errorMessages = errors.map((err: any) => { 13 | const path = err.instancePath || ""; 14 | const message = err.message || "Validation error"; 15 | return path ? `${path}: ${message}` : message; 16 | }); 17 | 18 | throw new Error(`Validation failed: ${errorMessages.join(", ")}`); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/types/reasoning-patterns/pdr-config.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * PDR Configuration and Result Types 3 | */ 4 | 5 | /** 6 | * Configuration for PDR execution 7 | */ 8 | export interface PDRConfig { 9 | prompt: string; 10 | maxPasses?: number; 11 | confidenceThreshold?: number; 12 | timeoutSeconds?: number; 13 | mode?: "sequential" | "parallel" | "adaptive"; 14 | } 15 | 16 | /** 17 | * Result from PDR execution 18 | */ 19 | export interface PDRResult { 20 | sessionId: string; 21 | passNumber: number; 22 | passName: string; 23 | timestamp: number; 24 | confidence: number; 25 | insights: string[]; 26 | nextSteps: string[]; 27 | metrics: { 28 | nodesAnalyzed: number; 29 | clustersFound: number; 30 | gapsIdentified: number; 31 | }; 32 | } 33 | -------------------------------------------------------------------------------- /src/tools/operations/session/session-import.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Session Import Operation 3 | * 4 | * Imports session data to restore state 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class SessionImportOperation extends BaseOperation { 10 | name = 'session_import'; 11 | category = 'session'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | // Note: Actual import logic would need to be implemented in SessionState 15 | // This is a placeholder that returns success 16 | 17 | return this.createResult({ 18 | result: "Session import completed", 19 | }); 20 | } 21 | } 22 | 23 | export default new SessionImportOperation(); -------------------------------------------------------------------------------- /dist/state/SessionManager.d.ts: -------------------------------------------------------------------------------- 1 | import { SessionState } from './SessionState.js'; 2 | import { type ServerConfig } from '../config.js'; 3 | interface SessionInfo { 4 | id: string; 5 | state: SessionState; 6 | createdAt: Date; 7 | lastAccessedAt: Date; 8 | } 9 | export declare class SessionManager { 10 | private sessions; 11 | private maxSessions; 12 | private sessionTimeout; 13 | private config; 14 | constructor(config?: ServerConfig); 15 | getOrCreateSession(sessionId: string): SessionInfo; 16 | getSession(sessionId: string): SessionInfo | undefined; 17 | private cleanupOldSessions; 18 | getAllSessions(): SessionInfo[]; 19 | clearAllSessions(): void; 20 | } 21 | export {}; 22 | //# sourceMappingURL=SessionManager.d.ts.map -------------------------------------------------------------------------------- /dist/unified-server.d.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import { Server } from "@modelcontextprotocol/sdk/server/index.js"; 3 | import type { ServerConfig } from "./config.js"; 4 | export interface UnifiedServerOptions { 5 | transport?: "stdio" | "http"; 6 | port?: number; 7 | config?: ServerConfig; 8 | } 9 | export declare class ClearThoughtUnifiedServer { 10 | private mcpServer; 11 | private sessionManager; 12 | private toolRegistry; 13 | private options; 14 | constructor(options?: UnifiedServerOptions); 15 | private detectTransport; 16 | private setupHandlers; 17 | start(): Promise; 18 | private startStdio; 19 | getMcpServer(): Server; 20 | } 21 | export default function createServer(options?: UnifiedServerOptions): ClearThoughtUnifiedServer; 22 | //# sourceMappingURL=unified-server.d.ts.map -------------------------------------------------------------------------------- /dist/tools/session-management.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const SessionManagementSchema: z.ZodObject<{ 4 | action: z.ZodEnum<["export", "import", "clear", "stats", "summary"]>; 5 | data: z.ZodOptional; 6 | format: z.ZodOptional>; 7 | }, "strip", z.ZodTypeAny, { 8 | action: "stats" | "export" | "import" | "clear" | "summary"; 9 | data?: any; 10 | format?: "json" | "summary" | undefined; 11 | }, { 12 | action: "stats" | "export" | "import" | "clear" | "summary"; 13 | data?: any; 14 | format?: "json" | "summary" | undefined; 15 | }>; 16 | export type SessionManagementArgs = z.infer; 17 | declare function handleSessionManagement(args: SessionManagementArgs, session: SessionState): Promise<{ 18 | content: { 19 | type: "text"; 20 | text: string; 21 | }[]; 22 | }>; 23 | export { handleSessionManagement }; 24 | //# sourceMappingURL=session-management.d.ts.map -------------------------------------------------------------------------------- /dist/tools/metacognitive.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const MetacognitiveSchema: z.ZodObject<{ 4 | thinkingProcess: z.ZodString; 5 | observations: z.ZodArray; 6 | adjustments: z.ZodArray; 7 | effectiveness: z.ZodNumber; 8 | insights: z.ZodString; 9 | }, "strip", z.ZodTypeAny, { 10 | thinkingProcess: string; 11 | observations: string[]; 12 | adjustments: string[]; 13 | effectiveness: number; 14 | insights: string; 15 | }, { 16 | thinkingProcess: string; 17 | observations: string[]; 18 | adjustments: string[]; 19 | effectiveness: number; 20 | insights: string; 21 | }>; 22 | export type MetacognitiveArgs = z.infer; 23 | declare function handleMetacognitive(args: MetacognitiveArgs, session: SessionState): Promise<{ 24 | content: { 25 | type: "text"; 26 | text: string; 27 | }[]; 28 | }>; 29 | export { handleMetacognitive }; 30 | //# sourceMappingURL=metacognitive.d.ts.map -------------------------------------------------------------------------------- /dist/types/reasoning-patterns/index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Reasoning Patterns Type Definitions 3 | * 4 | * This module exports all type definitions for advanced reasoning patterns 5 | * that extend beyond traditional chain-of-thought sequential thinking. 6 | */ 7 | export * from './base.js'; 8 | export * from './tree-of-thought.js'; 9 | export * from './graph-of-thought.js'; 10 | export * from './beam-search.js'; 11 | export * from './mcts.js'; 12 | export type { BaseReasoningNode, BaseReasoningSession, ReasoningPatternType, UnifiedReasoningArgs, UnifiedReasoningResult, ReasoningPattern, PatternRegistryEntry } from './base.js'; 13 | export type { TreeOfThoughtNode, TreeOfThoughtSession, TreeOfThoughtOperations } from './tree-of-thought.js'; 14 | export type { GraphOfThoughtNode, GraphOfThoughtEdge, GraphOfThoughtSession, GraphOfThoughtOperations } from './graph-of-thought.js'; 15 | export type { BeamSearchNode, BeamSearchPath, BeamSearchSession, BeamSearchOperations } from './beam-search.js'; 16 | export type { MCTSNode, MCTSSession, MCTSOperations } from './mcts.js'; 17 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Anthropic, PBC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /dist/tools/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Tool Index - All tools self-register on import 3 | * This file serves as the central import point for tool registration 4 | */ 5 | // Intentionally do NOT import tool modules here to avoid eager loading. 6 | // The unified server performs Smithery-style lazy loading on demand. 7 | // Export registry for programmatic access 8 | export { ToolRegistry } from '../registry/tool-registry.js'; 9 | // Dynamic tool loading function 10 | export async function loadAllTools() { 11 | // No-op: tools are lazily loaded by the server 12 | } 13 | // Get tool statistics 14 | export function getToolStats() { 15 | const { ToolRegistry } = require('../registry/tool-registry.js'); 16 | const registry = ToolRegistry.getInstance(); 17 | const tools = registry.getAll(); 18 | return { 19 | total: tools.length, 20 | byCategory: tools.reduce((acc, tool) => { 21 | const category = tool.category || 'uncategorized'; 22 | acc[category] = (acc[category] || 0) + 1; 23 | return acc; 24 | }, {}), 25 | names: registry.getToolNames() 26 | }; 27 | } 28 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /src/tools/operations/core/visual-reasoning.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Visual Reasoning Operation 3 | * 4 | * Analyzes visual and spatial relationships 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class VisualReasoningOperation extends BaseOperation { 10 | name = 'visual_reasoning'; 11 | category = 'core'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState, prompt, parameters } = context; 15 | 16 | const visualData = { 17 | description: prompt, 18 | spatialRelations: this.getParam(parameters, 'spatialRelations', []), 19 | patterns: this.getParam(parameters, 'patterns', []), 20 | transformations: this.getParam(parameters, 'transformations', []), 21 | inference: this.getParam(parameters, 'inference', ''), 22 | }; 23 | 24 | return this.createResult({ 25 | ...visualData, 26 | sessionContext: { 27 | sessionId: sessionState.sessionId, 28 | stats: sessionState.getStats(), 29 | }, 30 | }); 31 | } 32 | } 33 | 34 | export default new VisualReasoningOperation(); -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /** 3 | * Clear Thought MCP Server - Main Entry Point 4 | * 5 | * Unified server supporting stdio and HTTP transports 6 | */ 7 | import { ClearThoughtUnifiedServer } from './unified-server.js'; 8 | // Export factory function for programmatic use 9 | export default function createClearThoughtServer(options) { 10 | const server = new ClearThoughtUnifiedServer(options ?? {}); 11 | // For host-managed HTTP environments, return the MCP server instance 12 | if (options?.returnMcpServer) { 13 | return server.getMcpServer(); 14 | } 15 | return server; 16 | } 17 | // Auto-start if executed directly 18 | if (process.argv[1]?.endsWith('index.ts') || process.argv[1]?.endsWith('index.js')) { 19 | const server = new ClearThoughtUnifiedServer(); 20 | server.start().catch(error => { 21 | console.error('Failed to start server:', error); 22 | process.exit(1); 23 | }); 24 | } 25 | export { ClearThoughtUnifiedServer } from './unified-server.js'; 26 | export { ToolRegistry } from './registry/tool-registry.js'; 27 | export { SessionState } from './state/SessionState.js'; 28 | export { SessionManager } from './state/SessionManager.js'; 29 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules/ 3 | 4 | # Build output 5 | build/ 6 | 7 | # Logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | 13 | # Environment variables 14 | .env 15 | .env.local 16 | .env.*.local 17 | 18 | # IDE 19 | .vscode/ 20 | .idea/ 21 | *.swp 22 | *.swo 23 | *~ 24 | 25 | # OS 26 | .DS_Store 27 | Thumbs.db 28 | 29 | # Testing 30 | coverage/ 31 | .nyc_output/ 32 | 33 | # Temporary files 34 | *.tmp 35 | *.temp 36 | .cache/ 37 | 38 | # Backup files 39 | *.bak 40 | *.bak2 41 | index-old-bloated.ts 42 | 43 | # Local development 44 | claude_code_mcp_config.json 45 | mcp_config_claude_code.json 46 | .claude/ 47 | trees/ 48 | specs/ 49 | temp/ 50 | systemprompt-mcp-reddit/ 51 | Effect-TS/ 52 | Effect-TS 53 | exa-mcp-server-websets/ 54 | exa-mcp-server-websets 55 | .claude-flow/ 56 | .swarm/ 57 | 58 | # Refactoring artifacts 59 | .refactoring-game/ 60 | .feature-implementation-game/ 61 | .hive-mind/ 62 | refactoring-*.md 63 | REFACTORING_SUMMARY.md 64 | analysis-operations-summary.md 65 | notebook-*.md 66 | notebooks-benefits.md 67 | tools-issues-*.md 68 | 69 | # Build artifacts 70 | dist/resources/ 71 | *.d.ts.map 72 | *.js.map 73 | 74 | # Test artifacts 75 | vitest.config.ts.timestamp-* 76 | test-results/ 77 | .vitest/ -------------------------------------------------------------------------------- /src/tools/operations/core/scientific-method.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Scientific Method Operation 3 | * 4 | * Applies scientific methodology to problem-solving 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class ScientificMethodOperation extends BaseOperation { 10 | name = 'scientific_method'; 11 | category = 'core'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState, prompt, parameters } = context; 15 | 16 | const scientificData = { 17 | observation: prompt, 18 | hypothesis: this.getParam(parameters, 'hypothesis', ''), 19 | experiment: this.getParam(parameters, 'experiment', {}), 20 | data: this.getParam(parameters, 'data', []), 21 | analysis: this.getParam(parameters, 'analysis', ''), 22 | conclusion: this.getParam(parameters, 'conclusion', ''), 23 | reproducibility: this.getParam(parameters, 'reproducibility', {}), 24 | peerReview: this.getParam(parameters, 'peerReview', []), 25 | }; 26 | 27 | return this.createResult({ 28 | ...scientificData, 29 | sessionContext: { 30 | sessionId: sessionState.sessionId, 31 | stats: sessionState.getStats(), 32 | }, 33 | }); 34 | } 35 | } 36 | 37 | export default new ScientificMethodOperation(); -------------------------------------------------------------------------------- /dist/tools/debugging-approach.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const DebuggingApproachSchema: z.ZodObject<{ 4 | approachName: z.ZodEnum<["binary_search", "reverse_engineering", "divide_conquer", "backtracking", "cause_elimination", "program_slicing"]>; 5 | issue: z.ZodString; 6 | steps: z.ZodArray; 7 | findings: z.ZodString; 8 | resolution: z.ZodString; 9 | }, "strip", z.ZodTypeAny, { 10 | steps: string[]; 11 | approachName: "binary_search" | "reverse_engineering" | "divide_conquer" | "backtracking" | "cause_elimination" | "program_slicing"; 12 | issue: string; 13 | findings: string; 14 | resolution: string; 15 | }, { 16 | steps: string[]; 17 | approachName: "binary_search" | "reverse_engineering" | "divide_conquer" | "backtracking" | "cause_elimination" | "program_slicing"; 18 | issue: string; 19 | findings: string; 20 | resolution: string; 21 | }>; 22 | export type DebuggingApproachArgs = z.infer; 23 | declare function handleDebuggingApproach(args: DebuggingApproachArgs, session: SessionState): Promise<{ 24 | content: { 25 | type: "text"; 26 | text: string; 27 | }[]; 28 | }>; 29 | export { handleDebuggingApproach }; 30 | //# sourceMappingURL=debugging-approach.d.ts.map -------------------------------------------------------------------------------- /src/tools/operations/core/mental-model.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Mental Model Operation 3 | * 4 | * Provides structured mental models like First Principles, Pareto, etc. 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class MentalModelOperation extends BaseOperation { 10 | name = 'mental_model'; 11 | category = 'core'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState, prompt, parameters } = context; 15 | 16 | const modelData = { 17 | modelName: this.getParam(parameters, 'model', 'first_principles'), 18 | problem: prompt, 19 | steps: this.getParam(parameters, 'steps', []), 20 | reasoning: this.getParam(parameters, 'reasoning', ''), 21 | conclusion: this.getParam(parameters, 'conclusion', ''), 22 | }; 23 | 24 | // Add to session state 25 | sessionState.addMentalModel(modelData as any); 26 | const allModels = sessionState.getMentalModels(); 27 | 28 | return this.createResult({ 29 | ...modelData, 30 | sessionContext: { 31 | sessionId: sessionState.sessionId, 32 | totalModels: allModels.length, 33 | recentModels: allModels 34 | .slice(-3) 35 | .map((m) => ({ modelName: m.modelName, problem: m.problem })), 36 | }, 37 | }); 38 | } 39 | } 40 | 41 | export default new MentalModelOperation(); -------------------------------------------------------------------------------- /dist/tools/mental-model.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const MentalModelSchema: z.ZodObject<{ 4 | modelName: z.ZodEnum<["first_principles", "opportunity_cost", "error_propagation", "rubber_duck", "pareto_principle", "occams_razor"]>; 5 | problem: z.ZodString; 6 | steps: z.ZodArray; 7 | reasoning: z.ZodString; 8 | conclusion: z.ZodString; 9 | sessionId: z.ZodOptional; 10 | }, "strip", z.ZodTypeAny, { 11 | reasoning: string; 12 | conclusion: string; 13 | modelName: "first_principles" | "opportunity_cost" | "error_propagation" | "rubber_duck" | "pareto_principle" | "occams_razor"; 14 | steps: string[]; 15 | problem: string; 16 | sessionId?: string | undefined; 17 | }, { 18 | reasoning: string; 19 | conclusion: string; 20 | modelName: "first_principles" | "opportunity_cost" | "error_propagation" | "rubber_duck" | "pareto_principle" | "occams_razor"; 21 | steps: string[]; 22 | problem: string; 23 | sessionId?: string | undefined; 24 | }>; 25 | export type MentalModelArgs = z.infer; 26 | declare function handleMentalModel(args: MentalModelArgs, session: SessionState): Promise<{ 27 | content: { 28 | type: "text"; 29 | text: string; 30 | }[]; 31 | }>; 32 | export { handleMentalModel }; 33 | //# sourceMappingURL=mental-model.d.ts.map -------------------------------------------------------------------------------- /dist/tools/creative-thinking.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const CreativeThinkingSchema: z.ZodObject<{ 4 | technique: z.ZodEnum<["brainstorming", "mind_mapping", "scamper", "six_thinking_hats", "lateral_thinking", "random_stimulation"]>; 5 | problem: z.ZodString; 6 | ideas: z.ZodArray; 7 | connections: z.ZodOptional>; 8 | evaluation: z.ZodOptional; 9 | }, "strip", z.ZodTypeAny, { 10 | technique: "brainstorming" | "mind_mapping" | "scamper" | "six_thinking_hats" | "lateral_thinking" | "random_stimulation"; 11 | problem: string; 12 | ideas: string[]; 13 | evaluation?: string | undefined; 14 | connections?: string[] | undefined; 15 | }, { 16 | technique: "brainstorming" | "mind_mapping" | "scamper" | "six_thinking_hats" | "lateral_thinking" | "random_stimulation"; 17 | problem: string; 18 | ideas: string[]; 19 | evaluation?: string | undefined; 20 | connections?: string[] | undefined; 21 | }>; 22 | export type CreativeThinkingArgs = z.infer; 23 | declare function handleCreativeThinking(args: CreativeThinkingArgs, session: SessionState): Promise<{ 24 | content: { 25 | type: "text"; 26 | text: string; 27 | }[]; 28 | }>; 29 | export { handleCreativeThinking }; 30 | //# sourceMappingURL=creative-thinking.d.ts.map -------------------------------------------------------------------------------- /src/tools/operations/core/debugging-approach.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Debugging Approach Operation 3 | * 4 | * Implements debugging methodologies like Binary Search, Root Cause Analysis, etc. 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class DebuggingApproachOperation extends BaseOperation { 10 | name = 'debugging_approach'; 11 | category = 'core'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState, prompt, parameters } = context; 15 | 16 | const debugData = { 17 | approachName: this.getParam(parameters, 'approach', 'binary_search'), 18 | issue: prompt, 19 | steps: this.getParam(parameters, 'steps', []), 20 | findings: this.getParam(parameters, 'findings', ''), 21 | resolution: this.getParam(parameters, 'resolution', ''), 22 | }; 23 | 24 | sessionState.addDebuggingSession(debugData as any); 25 | const allSessions = sessionState.getDebuggingSessions(); 26 | 27 | return this.createResult({ 28 | ...debugData, 29 | sessionContext: { 30 | sessionId: sessionState.sessionId, 31 | totalSessions: allSessions.length, 32 | recentSessions: allSessions 33 | .slice(-3) 34 | .map((s) => ({ approachName: s.approachName, issue: s.issue })), 35 | }, 36 | }); 37 | } 38 | } 39 | 40 | export default new DebuggingApproachOperation(); -------------------------------------------------------------------------------- /dist/index.d.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /** 3 | * Clear Thought MCP Server - Main Entry Point 4 | * 5 | * Unified server supporting stdio and HTTP transports 6 | */ 7 | import { ClearThoughtUnifiedServer } from './unified-server.js'; 8 | import type { UnifiedServerOptions } from './unified-server.js'; 9 | export interface CreateOptions extends UnifiedServerOptions { 10 | returnMcpServer?: boolean; 11 | } 12 | export default function createClearThoughtServer(options?: CreateOptions): ClearThoughtUnifiedServer | import("@modelcontextprotocol/sdk/server/index.js").Server<{ 13 | method: string; 14 | params?: { 15 | [x: string]: unknown; 16 | _meta?: { 17 | [x: string]: unknown; 18 | progressToken?: string | number | undefined; 19 | } | undefined; 20 | } | undefined; 21 | }, { 22 | method: string; 23 | params?: { 24 | [x: string]: unknown; 25 | _meta?: { 26 | [x: string]: unknown; 27 | } | undefined; 28 | } | undefined; 29 | }, { 30 | [x: string]: unknown; 31 | _meta?: { 32 | [x: string]: unknown; 33 | } | undefined; 34 | }>; 35 | export type { UnifiedServerOptions } from './unified-server.js'; 36 | export { ClearThoughtUnifiedServer } from './unified-server.js'; 37 | export { ToolRegistry } from './registry/tool-registry.js'; 38 | export { SessionState } from './state/SessionState.js'; 39 | export { SessionManager } from './state/SessionManager.js'; 40 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Source TypeScript files (keep dist/ only) 2 | src/ 3 | *.ts 4 | !dist/**/*.d.ts 5 | tsconfig.json 6 | 7 | # Configuration files 8 | .gitignore 9 | .npmignore 10 | biome.json 11 | vitest.config.ts 12 | .env 13 | .env.* 14 | 15 | # Development files 16 | .vscode/ 17 | .idea/ 18 | .claude/ 19 | claude_code_mcp_config.json 20 | mcp_config_claude_code.json 21 | .smithery/ 22 | 23 | # Testing 24 | tests/ 25 | test/ 26 | coverage/ 27 | .nyc_output/ 28 | *.test.* 29 | *.spec.* 30 | .vitest/ 31 | test-results/ 32 | 33 | # Documentation development 34 | specs/ 35 | trees/ 36 | docs/ 37 | *.md 38 | !README.md 39 | !LICENSE 40 | 41 | # Build tools 42 | Dockerfile 43 | smithery.yaml 44 | flake.nix 45 | flake.lock 46 | cli/ 47 | 48 | # Backup files 49 | *.bak 50 | *.bak2 51 | index-old-bloated.ts 52 | src/tools/index-refactored.ts 53 | 54 | # Logs 55 | *.log 56 | npm-debug.log* 57 | yarn-debug.log* 58 | yarn-error.log* 59 | 60 | # OS 61 | .DS_Store 62 | Thumbs.db 63 | 64 | # Temporary files 65 | *.tmp 66 | *.temp 67 | .cache/ 68 | 69 | # Game and refactoring artifacts 70 | .refactoring-game/ 71 | .feature-implementation-game/ 72 | .hive-mind/ 73 | .claude-flow/ 74 | .swarm/ 75 | refactoring-*.md 76 | REFACTORING_SUMMARY.md 77 | analysis-operations-summary.md 78 | notebook-*.md 79 | notebooks-benefits.md 80 | tools-issues-*.md 81 | 82 | # External projects 83 | systemprompt-mcp-reddit/ 84 | exa-mcp-server-websets/ 85 | Effect-TS/ 86 | 87 | # Git 88 | .git/ 89 | .github/ 90 | 91 | # Build artifacts not needed 92 | *.d.ts.map 93 | *.js.map -------------------------------------------------------------------------------- /dist/server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Server.ts - HTTP Server Entry Point 3 | * 4 | * Uses the unified server for HTTP deployments 5 | */ 6 | import { ClearThoughtUnifiedServer } from './unified-server.js'; 7 | // Get port from environment or use default 8 | const PORT = parseInt(process.env.PORT || '3000'); 9 | // Create and start the unified server in HTTP mode 10 | const server = new ClearThoughtUnifiedServer({ 11 | transport: 'http', 12 | port: PORT 13 | }); 14 | // Start the server 15 | server.start().then(() => { 16 | console.log(`Clear Thought MCP server running on port ${PORT}`); 17 | console.log(`Health check available at http://localhost:${PORT}/health`); 18 | console.log(`MCP endpoint available at http://localhost:${PORT}/mcp`); 19 | }).catch(error => { 20 | console.error('Failed to start server:', error); 21 | process.exit(1); 22 | }); 23 | // Graceful shutdown handling 24 | process.on('SIGTERM', () => { 25 | console.log('SIGTERM received, shutting down gracefully'); 26 | process.exit(0); 27 | }); 28 | process.on('SIGINT', () => { 29 | console.log('SIGINT received, shutting down gracefully'); 30 | process.exit(0); 31 | }); 32 | // Handle uncaught exceptions 33 | process.on('uncaughtException', (error) => { 34 | console.error('Uncaught Exception:', error); 35 | process.exit(1); 36 | }); 37 | // Handle unhandled promise rejections 38 | process.on('unhandledRejection', (reason, promise) => { 39 | console.error('Unhandled Rejection at:', promise, 'reason:', reason); 40 | process.exit(1); 41 | }); 42 | //# sourceMappingURL=server.js.map -------------------------------------------------------------------------------- /src/tools/operations/core/metacognitive-monitoring.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Metacognitive Monitoring Operation 3 | * 4 | * Monitors and evaluates thinking processes 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class MetacognitiveMonitoringOperation extends BaseOperation { 10 | name = 'metacognitive_monitoring'; 11 | category = 'core'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState, prompt, parameters } = context; 15 | 16 | const monitoringData = { 17 | currentThinking: prompt, 18 | awareness: this.getParam(parameters, 'awareness', ''), 19 | evaluation: this.getParam(parameters, 'evaluation', ''), 20 | strategies: this.getParam(parameters, 'strategies', []), 21 | adjustments: this.getParam(parameters, 'adjustments', []), 22 | confidence: this.getParam(parameters, 'confidence', 0.5), 23 | biasCheck: this.getParam(parameters, 'biasCheck', []), 24 | }; 25 | 26 | // Update confidence KPI 27 | sessionState.updateKPI( 28 | 'metacognitive_confidence', 29 | monitoringData.confidence, 30 | 'Thinking Confidence', 31 | 0.8, 32 | 'up' 33 | ); 34 | 35 | return this.createResult({ 36 | ...monitoringData, 37 | sessionContext: { 38 | sessionId: sessionState.sessionId, 39 | stats: sessionState.getStats(), 40 | kpis: sessionState.getKPIs(), 41 | }, 42 | }); 43 | } 44 | } 45 | 46 | export default new MetacognitiveMonitoringOperation(); -------------------------------------------------------------------------------- /dist/tools/decision-framework.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const DecisionFrameworkSchema: z.ZodObject<{ 4 | decisionStatement: z.ZodString; 5 | options: z.ZodArray, "many">; 15 | analysisType: z.ZodString; 16 | stage: z.ZodString; 17 | decisionId: z.ZodString; 18 | iteration: z.ZodNumber; 19 | nextStageNeeded: z.ZodBoolean; 20 | }, "strip", z.ZodTypeAny, { 21 | options: { 22 | name: string; 23 | description: string; 24 | }[]; 25 | iteration: number; 26 | decisionId: string; 27 | decisionStatement: string; 28 | analysisType: string; 29 | stage: string; 30 | nextStageNeeded: boolean; 31 | }, { 32 | options: { 33 | name: string; 34 | description: string; 35 | }[]; 36 | iteration: number; 37 | decisionId: string; 38 | decisionStatement: string; 39 | analysisType: string; 40 | stage: string; 41 | nextStageNeeded: boolean; 42 | }>; 43 | export type DecisionFrameworkArgs = z.infer; 44 | declare function handleDecisionFramework(args: DecisionFrameworkArgs, session: SessionState): Promise<{ 45 | content: { 46 | type: "text"; 47 | text: string; 48 | }[]; 49 | }>; 50 | export { handleDecisionFramework }; 51 | //# sourceMappingURL=decision-framework.d.ts.map -------------------------------------------------------------------------------- /cli/server.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import { createStatefulServer } from "@smithery/sdk"; 3 | import type { ServerConfig } from "../src/config.js"; 4 | import { ServerConfigSchema } from "../src/config.js"; 5 | import createClearThoughtServer from "../src/index.js"; 6 | 7 | // Parse command line arguments 8 | const args = process.argv.slice(2); 9 | const port = args[0] ? parseInt(args[0], 10) : 3000; 10 | 11 | if (Number.isNaN(port)) { 12 | console.error("Invalid port number. Usage: cli/server.ts [port]"); 13 | process.exit(1); 14 | } 15 | 16 | // Create the stateful server using the SDK pattern 17 | const { app } = createStatefulServer( 18 | ({ sessionId, config }) => { 19 | // Create and return the Clear Thought server for this session 20 | return createClearThoughtServer({ 21 | sessionId, 22 | config: config as ServerConfig, 23 | }); 24 | }, 25 | { 26 | // Use the Clear Thought config schema for validation 27 | schema: ServerConfigSchema, 28 | }, 29 | ); 30 | 31 | // Start the HTTP server 32 | app.listen(port, () => { 33 | console.log(`🧠 Clear Thought server running at http://localhost:${port}`); 34 | console.log(`📝 MCP endpoint: http://localhost:${port}/mcp`); 35 | console.log( 36 | `🔧 Config schema: http://localhost:${port}/.well-known/mcp-config`, 37 | ); 38 | console.log("\nPress Ctrl+C to stop the server"); 39 | }); 40 | 41 | // Handle graceful shutdown 42 | process.on("SIGINT", () => { 43 | console.log("\n👋 Shutting down Clear Thought server..."); 44 | process.exit(0); 45 | }); 46 | 47 | process.on("SIGTERM", () => { 48 | console.log("\n👋 Received SIGTERM, shutting down..."); 49 | process.exit(0); 50 | }); 51 | -------------------------------------------------------------------------------- /src/types/reasoning-patterns/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Reasoning Patterns Type Definitions 3 | * 4 | * This module exports all type definitions for advanced reasoning patterns 5 | * that extend beyond traditional chain-of-thought sequential thinking. 6 | */ 7 | 8 | // Re-export commonly used types for convenience 9 | export type { 10 | BaseReasoningNode, 11 | BaseReasoningSession, 12 | PatternRegistryEntry, 13 | ReasoningPattern, 14 | ReasoningPatternType, 15 | UnifiedReasoningArgs, 16 | UnifiedReasoningResult, 17 | } from "./base.js"; 18 | // Base types 19 | export * from "./base.js"; 20 | export type { 21 | BeamSearchNode, 22 | BeamSearchOperations, 23 | BeamSearchPath, 24 | BeamSearchSession, 25 | } from "./beam-search.js"; 26 | 27 | // Beam Search 28 | export * from "./beam-search.js"; 29 | export type { 30 | GraphOfThoughtEdge, 31 | GraphOfThoughtNode, 32 | GraphOfThoughtOperations, 33 | GraphOfThoughtSession, 34 | } from "./graph-of-thought.js"; 35 | // Graph of Thought 36 | export * from "./graph-of-thought.js"; 37 | export type { 38 | MCTSNode, 39 | MCTSOperations, 40 | MCTSSession, 41 | } from "./mcts.js"; 42 | // Monte Carlo Tree Search 43 | export * from "./mcts.js"; 44 | // Metagame patterns - import specific exports to avoid conflicts 45 | export { 46 | OODAHypothesis, 47 | OODAMetrics, 48 | OODANode, 49 | OODAPhase, 50 | OODASession, 51 | } from "./ooda-loop.js"; 52 | // Progressive Deep Reasoning 53 | export * from "./pdr.js"; 54 | export type { 55 | TreeOfThoughtNode, 56 | TreeOfThoughtOperations, 57 | TreeOfThoughtSession, 58 | } from "./tree-of-thought.js"; 59 | // Tree of Thought 60 | export * from "./tree-of-thought.js"; 61 | export * from "./ulysses-protocol.js"; 62 | -------------------------------------------------------------------------------- /dist/tools/collaborative-reasoning.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const CollaborativeReasoningSchema: z.ZodObject<{ 4 | topic: z.ZodString; 5 | perspectives: z.ZodArray, "many">; 18 | synthesis: z.ZodString; 19 | consensus: z.ZodOptional; 20 | sessionId: z.ZodOptional; 21 | }, "strip", z.ZodTypeAny, { 22 | synthesis: string; 23 | perspectives: { 24 | reasoning: string; 25 | agent: string; 26 | viewpoint: string; 27 | }[]; 28 | topic: string; 29 | consensus?: string | undefined; 30 | sessionId?: string | undefined; 31 | }, { 32 | synthesis: string; 33 | perspectives: { 34 | reasoning: string; 35 | agent: string; 36 | viewpoint: string; 37 | }[]; 38 | topic: string; 39 | consensus?: string | undefined; 40 | sessionId?: string | undefined; 41 | }>; 42 | export type CollaborativeReasoningArgs = z.infer; 43 | declare function handleCollaborativeReasoning(args: CollaborativeReasoningArgs, session: SessionState): Promise<{ 44 | content: { 45 | type: "text"; 46 | text: string; 47 | }[]; 48 | }>; 49 | export { handleCollaborativeReasoning }; 50 | //# sourceMappingURL=collaborative-reasoning.d.ts.map -------------------------------------------------------------------------------- /src/tools/operations/registry.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Operation registry for managing all Clear Thought operations 3 | */ 4 | 5 | import type { Operation } from './base.js'; 6 | 7 | /** 8 | * Central registry for all operations 9 | */ 10 | class OperationRegistry { 11 | private operations = new Map(); 12 | 13 | /** 14 | * Register an operation 15 | */ 16 | register(operation: Operation): void { 17 | if (this.operations.has(operation.name)) { 18 | console.warn(`Operation ${operation.name} is already registered, overwriting...`); 19 | } 20 | this.operations.set(operation.name, operation); 21 | } 22 | 23 | /** 24 | * Get an operation by name 25 | */ 26 | get(name: string): Operation | undefined { 27 | return this.operations.get(name); 28 | } 29 | 30 | /** 31 | * Check if an operation exists 32 | */ 33 | has(name: string): boolean { 34 | return this.operations.has(name); 35 | } 36 | 37 | /** 38 | * Get all registered operations 39 | */ 40 | getAll(): Map { 41 | return new Map(this.operations); 42 | } 43 | 44 | /** 45 | * Get operations by category 46 | */ 47 | getByCategory(category: string): Operation[] { 48 | return Array.from(this.operations.values()) 49 | .filter(op => op.category === category); 50 | } 51 | 52 | /** 53 | * Get all operation names 54 | */ 55 | getNames(): string[] { 56 | return Array.from(this.operations.keys()); 57 | } 58 | 59 | /** 60 | * Clear all registrations (useful for testing) 61 | */ 62 | clear(): void { 63 | this.operations.clear(); 64 | } 65 | } 66 | 67 | // Singleton instance 68 | export const operationRegistry = new OperationRegistry(); -------------------------------------------------------------------------------- /dist/tools/metacognitive.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const MetacognitiveSchema = z.object({ 3 | thinkingProcess: z.string().describe('Description of the thinking process'), 4 | observations: z.array(z.string()).describe('Observations about the thinking'), 5 | adjustments: z.array(z.string()).describe('Adjustments to improve thinking'), 6 | effectiveness: z.number().min(0).max(10).describe('Effectiveness rating 0-10'), 7 | insights: z.string().describe('Key insights gained') 8 | }); 9 | async function handleMetacognitive(args, session) { 10 | const metacognitiveData = { 11 | thinkingProcess: args.thinkingProcess, 12 | observations: args.observations, 13 | adjustments: args.adjustments, 14 | effectiveness: args.effectiveness, 15 | insights: args.insights, 16 | timestamp: new Date().toISOString() 17 | }; 18 | // Store in session 19 | const stats = session.getStats(); 20 | return { 21 | content: [{ 22 | type: 'text', 23 | text: JSON.stringify({ 24 | ...metacognitiveData, 25 | status: 'success', 26 | sessionContext: { 27 | sessionId: session.sessionId, 28 | stats 29 | } 30 | }) 31 | }] 32 | }; 33 | } 34 | // Self-register 35 | // ToolRegistry.getInstance().register({ 36 | // name: 'metacognitivemonitoring', 37 | // description: 'Monitor and adjust thinking processes in real-time', 38 | // schema: MetacognitiveSchema, 39 | // handler: handleMetacognitive, 40 | // category: 'metacognitive' 41 | // }); 42 | export { handleMetacognitive }; 43 | //# sourceMappingURL=metacognitive.js.map -------------------------------------------------------------------------------- /dist/tools/socratic-method.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const SocraticMethodSchema: z.ZodObject<{ 4 | initialStatement: z.ZodString; 5 | questions: z.ZodArray; 9 | }, "strip", z.ZodTypeAny, { 10 | question: string; 11 | purpose: string; 12 | response?: string | undefined; 13 | }, { 14 | question: string; 15 | purpose: string; 16 | response?: string | undefined; 17 | }>, "many">; 18 | assumptions: z.ZodArray; 19 | contradictions: z.ZodOptional>; 20 | refinedUnderstanding: z.ZodString; 21 | }, "strip", z.ZodTypeAny, { 22 | assumptions: string[]; 23 | questions: { 24 | question: string; 25 | purpose: string; 26 | response?: string | undefined; 27 | }[]; 28 | initialStatement: string; 29 | refinedUnderstanding: string; 30 | contradictions?: string[] | undefined; 31 | }, { 32 | assumptions: string[]; 33 | questions: { 34 | question: string; 35 | purpose: string; 36 | response?: string | undefined; 37 | }[]; 38 | initialStatement: string; 39 | refinedUnderstanding: string; 40 | contradictions?: string[] | undefined; 41 | }>; 42 | export type SocraticMethodArgs = z.infer; 43 | declare function handleSocraticMethod(args: SocraticMethodArgs, session: SessionState): Promise<{ 44 | content: { 45 | type: "text"; 46 | text: string; 47 | }[]; 48 | }>; 49 | export { handleSocraticMethod }; 50 | //# sourceMappingURL=socratic-method.d.ts.map -------------------------------------------------------------------------------- /dist/registry/tool-registry.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; 3 | import { SessionState } from '../state/SessionState.js'; 4 | export interface ToolDefinition { 5 | name: string; 6 | description: string; 7 | schema: z.ZodSchema; 8 | handler: (args: T, session: SessionState) => Promise; 9 | category?: 'reasoning' | 'metacognitive' | 'collaborative' | 'creative' | 'session'; 10 | annotations?: { 11 | audience?: string[]; 12 | priority?: number; 13 | available_operations?: string[]; 14 | docs?: string; 15 | quickstart?: string; 16 | }; 17 | } 18 | export interface ToolResult { 19 | content: Array<{ 20 | type: string; 21 | text: string; 22 | }>; 23 | } 24 | export declare class ToolRegistry { 25 | private static instance; 26 | private tools; 27 | static getInstance(): ToolRegistry; 28 | register(tool: ToolDefinition): void; 29 | getAll(): ToolDefinition[]; 30 | get(name: string): ToolDefinition | undefined; 31 | getByCategory(category: string): ToolDefinition[]; 32 | toMCPTools(): { 33 | name: string; 34 | description: string; 35 | inputSchema: import("zod-to-json-schema").JsonSchema7Type & { 36 | $schema?: string | undefined; 37 | definitions?: { 38 | [key: string]: import("zod-to-json-schema").JsonSchema7Type; 39 | } | undefined; 40 | }; 41 | }[]; 42 | validate(name: string, args: any): any; 43 | execute(name: string, args: any, session: SessionState): Promise; 44 | getToolNames(): string[]; 45 | has(name: string): boolean; 46 | clear(): void; 47 | } 48 | //# sourceMappingURL=tool-registry.d.ts.map -------------------------------------------------------------------------------- /dist/tools/creative-thinking.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const CreativeThinkingSchema = z.object({ 3 | technique: z.enum([ 4 | 'brainstorming', 5 | 'mind_mapping', 6 | 'scamper', 7 | 'six_thinking_hats', 8 | 'lateral_thinking', 9 | 'random_stimulation' 10 | ]).describe('Creative thinking technique'), 11 | problem: z.string().describe('Problem or challenge to address'), 12 | ideas: z.array(z.string()).describe('Generated ideas'), 13 | connections: z.array(z.string()).optional().describe('Connections between ideas'), 14 | evaluation: z.string().optional().describe('Evaluation of ideas') 15 | }); 16 | async function handleCreativeThinking(args, session) { 17 | const creativeData = { 18 | technique: args.technique, 19 | problem: args.problem, 20 | ideas: args.ideas, 21 | connections: args.connections || [], 22 | evaluation: args.evaluation, 23 | timestamp: new Date().toISOString() 24 | }; 25 | const stats = session.getStats(); 26 | return { 27 | content: [{ 28 | type: 'text', 29 | text: JSON.stringify({ 30 | ...creativeData, 31 | status: 'success', 32 | sessionContext: { 33 | sessionId: session.sessionId, 34 | stats 35 | } 36 | }) 37 | }] 38 | }; 39 | } 40 | // Self-register 41 | // ToolRegistry.getInstance().register({ 42 | // name: 'creativethinking', 43 | // description: 'Apply creative thinking techniques for innovative problem-solving', 44 | // schema: CreativeThinkingSchema, 45 | // handler: handleCreativeThinking, 46 | // category: 'creative' 47 | // }); 48 | export { handleCreativeThinking }; 49 | //# sourceMappingURL=creative-thinking.js.map -------------------------------------------------------------------------------- /dist/tools/socratic-method.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const SocraticMethodSchema = z.object({ 3 | initialStatement: z.string().describe('Initial statement or belief'), 4 | questions: z.array(z.object({ 5 | question: z.string(), 6 | purpose: z.string(), 7 | response: z.string().optional() 8 | })).describe('Socratic questions'), 9 | assumptions: z.array(z.string()).describe('Identified assumptions'), 10 | contradictions: z.array(z.string()).optional().describe('Discovered contradictions'), 11 | refinedUnderstanding: z.string().describe('Refined understanding after questioning') 12 | }); 13 | async function handleSocraticMethod(args, session) { 14 | const socraticData = { 15 | initialStatement: args.initialStatement, 16 | questions: args.questions, 17 | assumptions: args.assumptions, 18 | contradictions: args.contradictions || [], 19 | refinedUnderstanding: args.refinedUnderstanding, 20 | timestamp: new Date().toISOString() 21 | }; 22 | const stats = session.getStats(); 23 | return { 24 | content: [{ 25 | type: 'text', 26 | text: JSON.stringify({ 27 | ...socraticData, 28 | status: 'success', 29 | sessionContext: { 30 | sessionId: session.sessionId, 31 | stats 32 | } 33 | }) 34 | }] 35 | }; 36 | } 37 | // Self-register 38 | // ToolRegistry.getInstance().register({ 39 | // name: 'socraticmethod', 40 | // description: 'Use Socratic questioning to examine beliefs and uncover truth', 41 | // schema: SocraticMethodSchema, 42 | // handler: handleSocraticMethod, 43 | // category: 'reasoning' 44 | // }); 45 | export { handleSocraticMethod }; 46 | //# sourceMappingURL=socratic-method.js.map -------------------------------------------------------------------------------- /dist/tools/structured-argumentation.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const StructuredArgumentationSchema = z.object({ 3 | claim: z.string().describe('Main claim or thesis'), 4 | premises: z.array(z.object({ 5 | statement: z.string(), 6 | support: z.string(), 7 | strength: z.enum(['strong', 'moderate', 'weak']) 8 | })).describe('Supporting premises'), 9 | counterarguments: z.array(z.object({ 10 | argument: z.string(), 11 | rebuttal: z.string() 12 | })).optional().describe('Counterarguments and rebuttals'), 13 | conclusion: z.string().describe('Final conclusion'), 14 | validity: z.enum(['valid', 'invalid', 'uncertain']).describe('Argument validity') 15 | }); 16 | async function handleStructuredArgumentation(args, session) { 17 | const argumentData = { 18 | claim: args.claim, 19 | premises: args.premises, 20 | counterarguments: args.counterarguments || [], 21 | conclusion: args.conclusion, 22 | validity: args.validity, 23 | timestamp: new Date().toISOString() 24 | }; 25 | const stats = session.getStats(); 26 | return { 27 | content: [{ 28 | type: 'text', 29 | text: JSON.stringify({ 30 | ...argumentData, 31 | status: 'success', 32 | sessionContext: { 33 | sessionId: session.sessionId, 34 | stats 35 | } 36 | }) 37 | }] 38 | }; 39 | } 40 | // Self-register 41 | // ToolRegistry.getInstance().register({ 42 | // name: 'structuredargumentation', 43 | // description: 'Build and analyze structured logical arguments', 44 | // schema: StructuredArgumentationSchema, 45 | // handler: handleStructuredArgumentation, 46 | // category: 'reasoning' 47 | // }); 48 | export { handleStructuredArgumentation }; 49 | //# sourceMappingURL=structured-argumentation.js.map -------------------------------------------------------------------------------- /dist/config.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Configuration schema and types for the Clear Thought MCP server 3 | */ 4 | import { z } from 'zod'; 5 | /** 6 | * Configuration schema for the Clear Thought MCP server 7 | * 8 | * @property debug - Enable debug logging (default: false) 9 | * @property maxThoughtsPerSession - Maximum number of thoughts allowed per session (default: 100) 10 | * @property sessionTimeout - Session timeout in milliseconds (default: 3600000 - 1 hour) 11 | * @property enableMetrics - Enable metrics collection (default: false) 12 | */ 13 | export declare const ServerConfigSchema: z.ZodObject<{ 14 | debug: z.ZodDefault; 15 | maxThoughtsPerSession: z.ZodDefault; 16 | sessionTimeout: z.ZodDefault; 17 | enableMetrics: z.ZodDefault; 18 | }, "strip", z.ZodTypeAny, { 19 | debug: boolean; 20 | maxThoughtsPerSession: number; 21 | sessionTimeout: number; 22 | enableMetrics: boolean; 23 | }, { 24 | debug?: boolean | undefined; 25 | maxThoughtsPerSession?: number | undefined; 26 | sessionTimeout?: number | undefined; 27 | enableMetrics?: boolean | undefined; 28 | }>; 29 | /** 30 | * Inferred type from the configuration schema 31 | */ 32 | export type ServerConfig = z.infer; 33 | /** 34 | * Default configuration values 35 | */ 36 | export declare const defaultConfig: ServerConfig; 37 | /** 38 | * Validates and parses configuration 39 | * @param config - Raw configuration object 40 | * @returns Validated configuration 41 | * @throws {z.ZodError} If configuration is invalid 42 | */ 43 | export declare function parseConfig(config: unknown): ServerConfig; 44 | /** 45 | * Safely parses configuration with fallback to defaults 46 | * @param config - Raw configuration object 47 | * @returns Validated configuration or default configuration 48 | */ 49 | export declare function safeParseConfig(config: unknown): ServerConfig; 50 | //# sourceMappingURL=config.d.ts.map -------------------------------------------------------------------------------- /src/tools/operations/base.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Base interfaces for all Clear Thought operations 3 | */ 4 | 5 | import type { SessionState } from '../../state/SessionState.js'; 6 | 7 | /** 8 | * Context provided to each operation 9 | */ 10 | export interface OperationContext { 11 | sessionState: SessionState; 12 | prompt: string; 13 | parameters: Record; 14 | } 15 | 16 | /** 17 | * Standard result format for operations 18 | */ 19 | export interface OperationResult { 20 | toolOperation: string; 21 | [key: string]: unknown; 22 | } 23 | 24 | /** 25 | * Base interface for all operations 26 | */ 27 | export interface Operation { 28 | /** 29 | * Unique name of the operation (e.g., 'sequential_thinking') 30 | */ 31 | name: string; 32 | 33 | /** 34 | * Category for organization (e.g., 'core', 'collaborative') 35 | */ 36 | category: string; 37 | 38 | /** 39 | * Execute the operation with given context 40 | */ 41 | execute(context: OperationContext): Promise; 42 | 43 | /** 44 | * Optional validation of parameters before execution 45 | */ 46 | validateParameters?(parameters: Record): void; 47 | } 48 | 49 | /** 50 | * Abstract base class with common functionality 51 | */ 52 | export abstract class BaseOperation implements Operation { 53 | abstract name: string; 54 | abstract category: string; 55 | 56 | abstract execute(context: OperationContext): Promise; 57 | 58 | /** 59 | * Helper to get typed parameter with default value 60 | */ 61 | protected getParam( 62 | parameters: Record, 63 | key: string, 64 | defaultValue: T 65 | ): T { 66 | return (parameters[key] as T) ?? defaultValue; 67 | } 68 | 69 | /** 70 | * Create base result object 71 | */ 72 | protected createResult(data: Record): OperationResult { 73 | return { 74 | toolOperation: this.name, 75 | ...data 76 | }; 77 | } 78 | } -------------------------------------------------------------------------------- /src/utils/execution.ts: -------------------------------------------------------------------------------- 1 | import { spawn } from "node:child_process"; 2 | import fs from "node:fs"; 3 | import os from "node:os"; 4 | import path from "node:path"; 5 | import type { CodeExecutionResult } from "../types/index.js"; 6 | 7 | export async function executePython( 8 | code: string, 9 | pythonCommand: string, 10 | timeoutMs: number, 11 | ): Promise { 12 | const tempDir = await fs.promises.mkdtemp( 13 | path.join(os.tmpdir(), "ct-python-"), 14 | ); 15 | const scriptPath = path.join(tempDir, "snippet.py"); 16 | await fs.promises.writeFile(scriptPath, code, "utf-8"); 17 | 18 | return new Promise((resolve) => { 19 | const start = Date.now(); 20 | const child = spawn(pythonCommand, [scriptPath], { 21 | stdio: ["ignore", "pipe", "pipe"], 22 | }); 23 | 24 | let stdout = ""; 25 | let stderr = ""; 26 | 27 | const timer = setTimeout( 28 | () => { 29 | try { 30 | child.kill("SIGKILL"); 31 | } catch {} 32 | }, 33 | Math.max(1000, timeoutMs), 34 | ); 35 | 36 | child.stdout.setEncoding("utf-8"); 37 | child.stderr.setEncoding("utf-8"); 38 | 39 | child.stdout.on("data", (chunk: string) => { 40 | stdout += chunk; 41 | }); 42 | child.stderr.on("data", (chunk: string) => { 43 | stderr += chunk; 44 | }); 45 | 46 | child.on("close", async (code) => { 47 | clearTimeout(timer); 48 | try { 49 | await fs.promises.rm(tempDir, { recursive: true, force: true }); 50 | } catch {} 51 | resolve({ 52 | language: "python", 53 | stdout, 54 | stderr, 55 | exitCode: code ?? -1, 56 | durationMs: Date.now() - start, 57 | }); 58 | }); 59 | 60 | child.on("error", async () => { 61 | clearTimeout(timer); 62 | try { 63 | await fs.promises.rm(tempDir, { recursive: true, force: true }); 64 | } catch {} 65 | resolve({ 66 | language: "python", 67 | stdout: "", 68 | stderr: "Failed to start Python process", 69 | exitCode: -1, 70 | durationMs: Date.now() - start, 71 | }); 72 | }); 73 | }); 74 | } 75 | -------------------------------------------------------------------------------- /dist/config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Configuration schema and types for the Clear Thought MCP server 3 | */ 4 | import { z } from 'zod'; 5 | /** 6 | * Configuration schema for the Clear Thought MCP server 7 | * 8 | * @property debug - Enable debug logging (default: false) 9 | * @property maxThoughtsPerSession - Maximum number of thoughts allowed per session (default: 100) 10 | * @property sessionTimeout - Session timeout in milliseconds (default: 3600000 - 1 hour) 11 | * @property enableMetrics - Enable metrics collection (default: false) 12 | */ 13 | export const ServerConfigSchema = z.object({ 14 | debug: z.boolean().default(false).describe('Enable debug logging'), 15 | maxThoughtsPerSession: z.number().min(1).max(1000).default(100).describe('Maximum number of thoughts allowed per session'), 16 | sessionTimeout: z.number().min(60000).default(3600000).describe('Session timeout in milliseconds'), 17 | enableMetrics: z.boolean().default(false).describe('Enable metrics collection') 18 | }); 19 | /** 20 | * Default configuration values 21 | */ 22 | export const defaultConfig = { 23 | debug: false, 24 | maxThoughtsPerSession: 100, 25 | sessionTimeout: 3600000, // 1 hour 26 | enableMetrics: false 27 | }; 28 | /** 29 | * Validates and parses configuration 30 | * @param config - Raw configuration object 31 | * @returns Validated configuration 32 | * @throws {z.ZodError} If configuration is invalid 33 | */ 34 | export function parseConfig(config) { 35 | return ServerConfigSchema.parse(config); 36 | } 37 | /** 38 | * Safely parses configuration with fallback to defaults 39 | * @param config - Raw configuration object 40 | * @returns Validated configuration or default configuration 41 | */ 42 | export function safeParseConfig(config) { 43 | const result = ServerConfigSchema.safeParse(config); 44 | if (result.success) { 45 | return result.data; 46 | } 47 | console.warn('Invalid configuration provided, using defaults:', result.error.issues); 48 | return defaultConfig; 49 | } 50 | //# sourceMappingURL=config.js.map -------------------------------------------------------------------------------- /dist/registry/tool-registry.js: -------------------------------------------------------------------------------- 1 | import { zodToJsonSchema } from 'zod-to-json-schema'; 2 | export class ToolRegistry { 3 | static instance; 4 | tools = new Map(); 5 | static getInstance() { 6 | if (!this.instance) { 7 | this.instance = new ToolRegistry(); 8 | } 9 | return this.instance; 10 | } 11 | register(tool) { 12 | this.tools.set(tool.name, tool); 13 | } 14 | getAll() { 15 | return Array.from(this.tools.values()); 16 | } 17 | get(name) { 18 | return this.tools.get(name); 19 | } 20 | getByCategory(category) { 21 | return this.getAll().filter(tool => tool.category === category); 22 | } 23 | // Generate MCP tool format 24 | toMCPTools() { 25 | return this.getAll().map(tool => ({ 26 | name: tool.name, 27 | description: tool.description, 28 | inputSchema: zodToJsonSchema(tool.schema) 29 | })); 30 | } 31 | // Validate arguments using tool's schema 32 | validate(name, args) { 33 | const tool = this.get(name); 34 | if (!tool) { 35 | throw new Error(`Unknown tool: ${name}`); 36 | } 37 | return tool.schema.parse(args); 38 | } 39 | // Execute tool with validation and session 40 | async execute(name, args, session) { 41 | const tool = this.get(name); 42 | if (!tool) { 43 | throw new Error(`Unknown tool: ${name}`); 44 | } 45 | // Validate with Zod (single validation point) 46 | const validated = tool.schema.parse(args); 47 | // Execute with session 48 | return tool.handler(validated, session); 49 | } 50 | // Get tool names for autocomplete 51 | getToolNames() { 52 | return Array.from(this.tools.keys()); 53 | } 54 | // Check if tool exists 55 | has(name) { 56 | return this.tools.has(name); 57 | } 58 | // Clear registry (useful for testing) 59 | clear() { 60 | this.tools.clear(); 61 | } 62 | } 63 | //# sourceMappingURL=tool-registry.js.map -------------------------------------------------------------------------------- /dist/tools/collaborative-reasoning.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const CollaborativeReasoningSchema = z.object({ 3 | topic: z.string().describe('The topic being discussed'), 4 | perspectives: z.array(z.object({ 5 | agent: z.string().describe('Name or role of the agent'), 6 | viewpoint: z.string().describe('The agent\'s perspective'), 7 | reasoning: z.string().describe('Reasoning behind the viewpoint') 8 | })).describe('Different perspectives from multiple agents'), 9 | synthesis: z.string().describe('Synthesis of all perspectives'), 10 | consensus: z.string().optional().describe('Consensus reached, if any'), 11 | // NEW: Optional sessionId for continuation 12 | sessionId: z.string().optional().describe('Session ID for continuing existing collaborative session') 13 | }); 14 | async function handleCollaborativeReasoning(args, session) { 15 | const collaborativeData = { 16 | topic: args.topic, 17 | perspectives: args.perspectives, 18 | synthesis: args.synthesis, 19 | consensus: args.consensus, 20 | timestamp: new Date().toISOString() 21 | }; 22 | // Store in unified store or session 23 | const stats = session.getStats(); 24 | return { 25 | content: [{ 26 | type: 'text', 27 | text: JSON.stringify({ 28 | ...collaborativeData, 29 | status: 'success', 30 | sessionContext: { 31 | sessionId: session.sessionId, 32 | stats 33 | } 34 | }) 35 | }] 36 | }; 37 | } 38 | // Self-register 39 | // ToolRegistry.getInstance().register({ 40 | // name: 'collaborativereasoning', 41 | // description: 'Enable multi-agent collaborative reasoning and perspective synthesis', 42 | // schema: CollaborativeReasoningSchema, 43 | // handler: handleCollaborativeReasoning, 44 | // category: 'collaborative' 45 | // }); 46 | export { handleCollaborativeReasoning }; 47 | //# sourceMappingURL=collaborative-reasoning.js.map -------------------------------------------------------------------------------- /dist/tools/debugging-approach.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const DebuggingApproachSchema = z.object({ 3 | approachName: z.enum([ 4 | 'binary_search', 5 | 'reverse_engineering', 6 | 'divide_conquer', 7 | 'backtracking', 8 | 'cause_elimination', 9 | 'program_slicing' 10 | ]).describe('Debugging approach'), 11 | issue: z.string().describe('The issue being debugged'), 12 | steps: z.array(z.string()).describe('Steps taken to debug'), 13 | findings: z.string().describe('Findings during debugging'), 14 | resolution: z.string().describe('How the issue was resolved') 15 | }); 16 | async function handleDebuggingApproach(args, session) { 17 | const debugData = { 18 | approachName: args.approachName, 19 | issue: args.issue, 20 | steps: args.steps, 21 | findings: args.findings, 22 | resolution: args.resolution 23 | }; 24 | session.addDebuggingSession(debugData); 25 | // Get session context 26 | const stats = session.getStats(); 27 | const recentDebugging = session.getDebuggingSessions().slice(-3); 28 | return { 29 | content: [{ 30 | type: 'text', 31 | text: JSON.stringify({ 32 | ...debugData, 33 | status: 'success', 34 | sessionContext: { 35 | sessionId: session.sessionId, 36 | totalDebuggingSessions: session.getDebuggingSessions().length, 37 | recentSessions: recentDebugging, 38 | stats 39 | } 40 | }) 41 | }] 42 | }; 43 | } 44 | // Self-register 45 | // ToolRegistry.getInstance().register({ 46 | // name: 'debuggingapproach', 47 | // description: 'Apply systematic debugging approaches to identify and resolve issues', 48 | // schema: DebuggingApproachSchema, 49 | // handler: handleDebuggingApproach, 50 | // category: 'metacognitive' 51 | // }); 52 | export { handleDebuggingApproach }; 53 | //# sourceMappingURL=debugging-approach.js.map -------------------------------------------------------------------------------- /dist/tools/visual-reasoning.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const VisualReasoningSchema = z.object({ 3 | visualType: z.enum([ 4 | 'diagram', 5 | 'flowchart', 6 | 'mind_map', 7 | 'concept_map', 8 | 'graph', 9 | 'matrix' 10 | ]).describe('Type of visual representation'), 11 | elements: z.array(z.object({ 12 | id: z.string(), 13 | type: z.string(), 14 | label: z.string(), 15 | position: z.object({ 16 | x: z.number(), 17 | y: z.number() 18 | }).optional() 19 | })).describe('Visual elements'), 20 | connections: z.array(z.object({ 21 | from: z.string(), 22 | to: z.string(), 23 | label: z.string().optional(), 24 | type: z.string().optional() 25 | })).optional().describe('Connections between elements'), 26 | insights: z.string().describe('Insights from visual analysis') 27 | }); 28 | async function handleVisualReasoning(args, session) { 29 | const visualData = { 30 | visualType: args.visualType, 31 | elements: args.elements, 32 | connections: args.connections || [], 33 | insights: args.insights, 34 | timestamp: new Date().toISOString() 35 | }; 36 | const stats = session.getStats(); 37 | return { 38 | content: [{ 39 | type: 'text', 40 | text: JSON.stringify({ 41 | ...visualData, 42 | status: 'success', 43 | sessionContext: { 44 | sessionId: session.sessionId, 45 | stats 46 | } 47 | }) 48 | }] 49 | }; 50 | } 51 | // Self-register 52 | // ToolRegistry.getInstance().register({ 53 | // name: 'visualreasoning', 54 | // description: 'Use visual representations to analyze and understand complex information', 55 | // schema: VisualReasoningSchema, 56 | // handler: handleVisualReasoning, 57 | // category: 'reasoning' 58 | // }); 59 | export { handleVisualReasoning }; 60 | //# sourceMappingURL=visual-reasoning.js.map -------------------------------------------------------------------------------- /dist/tools/scientific-method.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const ScientificMethodSchema: z.ZodObject<{ 4 | hypothesis: z.ZodString; 5 | experimentDesign: z.ZodString; 6 | variables: z.ZodObject<{ 7 | independent: z.ZodArray; 8 | dependent: z.ZodArray; 9 | controlled: z.ZodArray; 10 | }, "strip", z.ZodTypeAny, { 11 | independent: string[]; 12 | dependent: string[]; 13 | controlled: string[]; 14 | }, { 15 | independent: string[]; 16 | dependent: string[]; 17 | controlled: string[]; 18 | }>; 19 | methodology: z.ZodString; 20 | expectedResults: z.ZodString; 21 | actualResults: z.ZodOptional; 22 | analysis: z.ZodOptional; 23 | conclusion: z.ZodOptional; 24 | }, "strip", z.ZodTypeAny, { 25 | hypothesis: string; 26 | experimentDesign: string; 27 | variables: { 28 | independent: string[]; 29 | dependent: string[]; 30 | controlled: string[]; 31 | }; 32 | methodology: string; 33 | expectedResults: string; 34 | analysis?: string | undefined; 35 | conclusion?: string | undefined; 36 | actualResults?: string | undefined; 37 | }, { 38 | hypothesis: string; 39 | experimentDesign: string; 40 | variables: { 41 | independent: string[]; 42 | dependent: string[]; 43 | controlled: string[]; 44 | }; 45 | methodology: string; 46 | expectedResults: string; 47 | analysis?: string | undefined; 48 | conclusion?: string | undefined; 49 | actualResults?: string | undefined; 50 | }>; 51 | export type ScientificMethodArgs = z.infer; 52 | declare function handleScientificMethod(args: ScientificMethodArgs, session: SessionState): Promise<{ 53 | content: { 54 | type: "text"; 55 | text: string; 56 | }[]; 57 | }>; 58 | export { handleScientificMethod }; 59 | //# sourceMappingURL=scientific-method.d.ts.map -------------------------------------------------------------------------------- /dist/tools/systems-thinking.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const SystemsThinkingSchema = z.object({ 3 | systemName: z.string().describe('Name of the system being analyzed'), 4 | components: z.array(z.object({ 5 | name: z.string(), 6 | function: z.string(), 7 | interactions: z.array(z.string()) 8 | })).describe('System components'), 9 | boundaries: z.string().describe('System boundaries'), 10 | inputs: z.array(z.string()).describe('System inputs'), 11 | outputs: z.array(z.string()).describe('System outputs'), 12 | feedbackLoops: z.array(z.object({ 13 | type: z.enum(['positive', 'negative']), 14 | description: z.string() 15 | })).optional().describe('Feedback loops'), 16 | emergentProperties: z.array(z.string()).optional().describe('Emergent properties') 17 | }); 18 | async function handleSystemsThinking(args, session) { 19 | const systemsData = { 20 | systemName: args.systemName, 21 | components: args.components, 22 | boundaries: args.boundaries, 23 | inputs: args.inputs, 24 | outputs: args.outputs, 25 | feedbackLoops: args.feedbackLoops || [], 26 | emergentProperties: args.emergentProperties || [], 27 | timestamp: new Date().toISOString() 28 | }; 29 | const stats = session.getStats(); 30 | return { 31 | content: [{ 32 | type: 'text', 33 | text: JSON.stringify({ 34 | ...systemsData, 35 | status: 'success', 36 | sessionContext: { 37 | sessionId: session.sessionId, 38 | stats 39 | } 40 | }) 41 | }] 42 | }; 43 | } 44 | // Self-register 45 | // ToolRegistry.getInstance().register({ 46 | // name: 'systemsthinking', 47 | // description: 'Analyze complex systems and their interactions', 48 | // schema: SystemsThinkingSchema, 49 | // handler: handleSystemsThinking, 50 | // category: 'reasoning' 51 | // }); 52 | export { handleSystemsThinking }; 53 | //# sourceMappingURL=systems-thinking.js.map -------------------------------------------------------------------------------- /src/resources/examples/optimization.md: -------------------------------------------------------------------------------- 1 | # Optimization Examples 2 | 3 | ## Resource Allocation 4 | 5 | ### Engineering Team Optimization 6 | 7 | ```json 8 | { 9 | "prompt": "Optimize team resource allocation across projects", 10 | "parameters": { 11 | "variables": { 12 | "frontend_hours": { "min": 0, "max": 160, "step": 20 }, 13 | "backend_hours": { "min": 0, "max": 160, "step": 20 }, 14 | "testing_hours": { "min": 0, "max": 80, "step": 10 }, 15 | "documentation_hours": { "min": 0, "max": 40, "step": 10 } 16 | }, 17 | "objective": "(frontend_hours * 1.2) + (backend_hours * 1.5) + (testing_hours * 0.8) + (documentation_hours * 0.5)", 18 | "constraints": "frontend_hours + backend_hours + testing_hours + documentation_hours <= 300", 19 | "method": "grid", 20 | "iterations": 100 21 | } 22 | } 23 | ``` 24 | 25 | ## Portfolio Optimization 26 | 27 | ### Investment Mix 28 | 29 | ```json 30 | { 31 | "prompt": "Optimize investment portfolio allocation", 32 | "parameters": { 33 | "variables": { 34 | "stocks": { "min": 0, "max": 100, "step": 5 }, 35 | "bonds": { "min": 0, "max": 100, "step": 5 }, 36 | "real_estate": { "min": 0, "max": 100, "step": 5 }, 37 | "cash": { "min": 0, "max": 100, "step": 5 } 38 | }, 39 | "objective": "(stocks * 0.12) + (bonds * 0.04) + (real_estate * 0.08) + (cash * 0.01)", 40 | "constraints": "stocks + bonds + real_estate + cash = 100", 41 | "method": "hill", 42 | "iterations": 200 43 | } 44 | } 45 | ``` 46 | 47 | ## Production Optimization 48 | 49 | ### Manufacturing Output 50 | 51 | ```json 52 | { 53 | "prompt": "Maximize production output with constraints", 54 | "parameters": { 55 | "variables": { 56 | "product_a": { "min": 0, "max": 1000, "step": 50 }, 57 | "product_b": { "min": 0, "max": 800, "step": 50 }, 58 | "product_c": { "min": 0, "max": 600, "step": 50 } 59 | }, 60 | "objective": "(product_a * 15) + (product_b * 20) + (product_c * 25)", 61 | "constraints": "(product_a * 2) + (product_b * 3) + (product_c * 4) <= 5000", 62 | "method": "grid", 63 | "iterations": 150 64 | } 65 | } 66 | ``` -------------------------------------------------------------------------------- /dist/tools/decision-framework.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const DecisionFrameworkSchema = z.object({ 3 | decisionStatement: z.string().describe('The decision to be made'), 4 | options: z.array(z.object({ 5 | name: z.string(), 6 | description: z.string() 7 | })).describe('Available options'), 8 | analysisType: z.string().describe('Type of analysis framework'), 9 | stage: z.string().describe('Current stage of decision process'), 10 | decisionId: z.string().describe('Unique identifier for this decision'), 11 | iteration: z.number().describe('Iteration number'), 12 | nextStageNeeded: z.boolean().describe('Whether next stage is needed') 13 | }); 14 | async function handleDecisionFramework(args, session) { 15 | const decisionData = { 16 | decisionStatement: args.decisionStatement, 17 | options: args.options, 18 | analysisType: args.analysisType, // Type will be validated by schema 19 | stage: args.stage, // Type will be validated by schema 20 | decisionId: args.decisionId, 21 | iteration: args.iteration, 22 | nextStageNeeded: args.nextStageNeeded 23 | }; 24 | session.addDecision(decisionData); 25 | const stats = session.getStats(); 26 | const decisions = session.getDecisions(); 27 | return { 28 | content: [{ 29 | type: 'text', 30 | text: JSON.stringify({ 31 | ...decisionData, 32 | status: 'success', 33 | sessionContext: { 34 | sessionId: session.sessionId, 35 | totalDecisions: decisions.length, 36 | stats 37 | } 38 | }) 39 | }] 40 | }; 41 | } 42 | // Self-register 43 | // ToolRegistry.getInstance().register({ 44 | // name: 'decisionframework', 45 | // description: 'Apply structured decision-making frameworks', 46 | // schema: DecisionFrameworkSchema, 47 | // handler: handleDecisionFramework, 48 | // category: 'metacognitive' 49 | // }); 50 | export { handleDecisionFramework }; 51 | //# sourceMappingURL=decision-framework.js.map -------------------------------------------------------------------------------- /dist/tools/scientific-method.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const ScientificMethodSchema = z.object({ 3 | hypothesis: z.string().describe('The hypothesis to test'), 4 | experimentDesign: z.string().describe('Design of the experiment'), 5 | variables: z.object({ 6 | independent: z.array(z.string()), 7 | dependent: z.array(z.string()), 8 | controlled: z.array(z.string()) 9 | }).describe('Experimental variables'), 10 | methodology: z.string().describe('Methodology description'), 11 | expectedResults: z.string().describe('Expected results'), 12 | actualResults: z.string().optional().describe('Actual results if available'), 13 | analysis: z.string().optional().describe('Analysis of results'), 14 | conclusion: z.string().optional().describe('Conclusion drawn') 15 | }); 16 | async function handleScientificMethod(args, session) { 17 | const scientificData = { 18 | hypothesis: args.hypothesis, 19 | experimentDesign: args.experimentDesign, 20 | variables: args.variables, 21 | methodology: args.methodology, 22 | expectedResults: args.expectedResults, 23 | actualResults: args.actualResults, 24 | analysis: args.analysis, 25 | conclusion: args.conclusion, 26 | timestamp: new Date().toISOString() 27 | }; 28 | const stats = session.getStats(); 29 | return { 30 | content: [{ 31 | type: 'text', 32 | text: JSON.stringify({ 33 | ...scientificData, 34 | status: 'success', 35 | sessionContext: { 36 | sessionId: session.sessionId, 37 | stats 38 | } 39 | }) 40 | }] 41 | }; 42 | } 43 | // Self-register 44 | // ToolRegistry.getInstance().register({ 45 | // name: 'scientificmethod', 46 | // description: 'Apply scientific method for hypothesis testing and experimentation', 47 | // schema: ScientificMethodSchema, 48 | // handler: handleScientificMethod, 49 | // category: 'reasoning' 50 | // }); 51 | export { handleScientificMethod }; 52 | //# sourceMappingURL=scientific-method.js.map -------------------------------------------------------------------------------- /cli/stdio-server.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; 3 | import { defaultConfig } from "../src/config.js"; 4 | import createClearThoughtServer from "../src/index.js"; 5 | 6 | async function main() { 7 | try { 8 | // Parse environment variables for diagnostic configuration 9 | const diagnosticEnabled = process.env.DIAGNOSTIC_ENABLED === 'true' || 10 | process.env.CT_DIAGNOSTIC_ENABLED === 'true'; 11 | const diagnosticVerbosity = process.env.DIAGNOSTIC_VERBOSITY || 12 | process.env.CT_DIAGNOSTIC_VERBOSITY || 'standard'; 13 | 14 | // Create config with diagnostic settings from environment 15 | const config = { 16 | ...defaultConfig, 17 | diagnosticEnabled, 18 | diagnosticVerbosity: diagnosticVerbosity as 'minimal' | 'standard' | 'verbose', 19 | }; 20 | 21 | // Log diagnostic status to stderr 22 | if (diagnosticEnabled) { 23 | console.error(`🔍 Glass Box Diagnostic Tracing ENABLED (verbosity: ${diagnosticVerbosity})`); 24 | } 25 | 26 | // Create the Clear Thought server instance 27 | const server = createClearThoughtServer({ 28 | sessionId: `stdio-session-${Date.now()}`, 29 | config, 30 | }); 31 | 32 | // Create stdio transport 33 | const transport = new StdioServerTransport(); 34 | 35 | // Connect server to transport 36 | await server.connect(transport); 37 | 38 | // Log to stderr (stdout is reserved for MCP communication) 39 | console.error("Clear Thought MCP server running in stdio mode"); 40 | console.error("Ready to receive commands..."); 41 | } catch (error) { 42 | console.error("Failed to start Clear Thought stdio server:", error); 43 | process.exit(1); 44 | } 45 | } 46 | 47 | // Handle graceful shutdown 48 | process.on("SIGINT", () => { 49 | console.error("\nShutting down Clear Thought stdio server..."); 50 | process.exit(0); 51 | }); 52 | 53 | process.on("SIGTERM", () => { 54 | console.error("Received SIGTERM, shutting down..."); 55 | process.exit(0); 56 | }); 57 | 58 | // Start the server 59 | main().catch((error) => { 60 | console.error("Fatal error:", error); 61 | process.exit(1); 62 | }); 63 | -------------------------------------------------------------------------------- /dist/tools/mental-model.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const MentalModelSchema = z.object({ 3 | modelName: z.enum([ 4 | 'first_principles', 5 | 'opportunity_cost', 6 | 'error_propagation', 7 | 'rubber_duck', 8 | 'pareto_principle', 9 | 'occams_razor' 10 | ]).describe('Name of the mental model'), 11 | problem: z.string().describe('The problem being analyzed'), 12 | steps: z.array(z.string()).describe('Steps to apply the model'), 13 | reasoning: z.string().describe('Reasoning process'), 14 | conclusion: z.string().describe('Conclusions drawn'), 15 | // NEW: Optional sessionId for continuation 16 | sessionId: z.string().optional().describe('Session ID for continuing existing mental model session') 17 | }); 18 | async function handleMentalModel(args, session) { 19 | const modelData = { 20 | modelName: args.modelName, 21 | problem: args.problem, 22 | steps: args.steps, 23 | reasoning: args.reasoning, 24 | conclusion: args.conclusion 25 | }; 26 | session.addMentalModel(modelData); 27 | // Get session context 28 | const stats = session.getStats(); 29 | const allModels = session.getMentalModels(); 30 | const recentModels = allModels.slice(-3); 31 | return { 32 | content: [{ 33 | type: 'text', 34 | text: JSON.stringify({ 35 | ...modelData, 36 | status: 'success', 37 | sessionContext: { 38 | sessionId: session.sessionId, 39 | totalModels: allModels.length, 40 | recentModels, 41 | stats 42 | } 43 | }) 44 | }] 45 | }; 46 | } 47 | // Self-register - DISABLED for ToolHost pattern 48 | // ToolRegistry.getInstance().register({ 49 | // name: 'mentalmodel', 50 | // description: 'Apply mental models to analyze problems systematically', 51 | // schema: MentalModelSchema, 52 | // handler: handleMentalModel, 53 | // category: 'metacognitive' 54 | // }); 55 | export { handleMentalModel }; 56 | //# sourceMappingURL=mental-model.js.map -------------------------------------------------------------------------------- /dist/src/utils/execution.js: -------------------------------------------------------------------------------- 1 | import { spawn } from "node:child_process"; 2 | import fs from "node:fs"; 3 | import os from "node:os"; 4 | import path from "node:path"; 5 | export async function executePython(code, pythonCommand, timeoutMs) { 6 | const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "ct-python-")); 7 | const scriptPath = path.join(tempDir, "snippet.py"); 8 | await fs.promises.writeFile(scriptPath, code, "utf-8"); 9 | return new Promise((resolve) => { 10 | const start = Date.now(); 11 | const child = spawn(pythonCommand, [scriptPath], { 12 | stdio: ["ignore", "pipe", "pipe"], 13 | }); 14 | let stdout = ""; 15 | let stderr = ""; 16 | const timer = setTimeout(() => { 17 | try { 18 | child.kill("SIGKILL"); 19 | } 20 | catch { } 21 | }, Math.max(1000, timeoutMs)); 22 | child.stdout.setEncoding("utf-8"); 23 | child.stderr.setEncoding("utf-8"); 24 | child.stdout.on("data", (chunk) => { 25 | stdout += chunk; 26 | }); 27 | child.stderr.on("data", (chunk) => { 28 | stderr += chunk; 29 | }); 30 | child.on("close", async (code) => { 31 | clearTimeout(timer); 32 | try { 33 | await fs.promises.rm(tempDir, { recursive: true, force: true }); 34 | } 35 | catch { } 36 | resolve({ 37 | language: "python", 38 | stdout, 39 | stderr, 40 | exitCode: code ?? -1, 41 | durationMs: Date.now() - start, 42 | }); 43 | }); 44 | child.on("error", async () => { 45 | clearTimeout(timer); 46 | try { 47 | await fs.promises.rm(tempDir, { recursive: true, force: true }); 48 | } 49 | catch { } 50 | resolve({ 51 | language: "python", 52 | stdout: "", 53 | stderr: "Failed to start Python process", 54 | exitCode: -1, 55 | durationMs: Date.now() - start, 56 | }); 57 | }); 58 | }); 59 | } 60 | -------------------------------------------------------------------------------- /dist/cli/stdio-server.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; 3 | import { defaultConfig } from "../src/config.js"; 4 | import createClearThoughtServer from "../src/index.js"; 5 | async function main() { 6 | try { 7 | // Parse environment variables for diagnostic configuration 8 | const diagnosticEnabled = process.env.DIAGNOSTIC_ENABLED === 'true' || 9 | process.env.CT_DIAGNOSTIC_ENABLED === 'true'; 10 | const diagnosticVerbosity = process.env.DIAGNOSTIC_VERBOSITY || 11 | process.env.CT_DIAGNOSTIC_VERBOSITY || 'standard'; 12 | // Create config with diagnostic settings from environment 13 | const config = { 14 | ...defaultConfig, 15 | diagnosticEnabled, 16 | diagnosticVerbosity: diagnosticVerbosity, 17 | }; 18 | // Log diagnostic status to stderr 19 | if (diagnosticEnabled) { 20 | console.error(`🔍 Glass Box Diagnostic Tracing ENABLED (verbosity: ${diagnosticVerbosity})`); 21 | } 22 | // Create the Clear Thought server instance 23 | const server = createClearThoughtServer({ 24 | sessionId: `stdio-session-${Date.now()}`, 25 | config, 26 | }); 27 | // Create stdio transport 28 | const transport = new StdioServerTransport(); 29 | // Connect server to transport 30 | await server.connect(transport); 31 | // Log to stderr (stdout is reserved for MCP communication) 32 | console.error("Clear Thought MCP server running in stdio mode"); 33 | console.error("Ready to receive commands..."); 34 | } 35 | catch (error) { 36 | console.error("Failed to start Clear Thought stdio server:", error); 37 | process.exit(1); 38 | } 39 | } 40 | // Handle graceful shutdown 41 | process.on("SIGINT", () => { 42 | console.error("\nShutting down Clear Thought stdio server..."); 43 | process.exit(0); 44 | }); 45 | process.on("SIGTERM", () => { 46 | console.error("Received SIGTERM, shutting down..."); 47 | process.exit(0); 48 | }); 49 | // Start the server 50 | main().catch((error) => { 51 | console.error("Fatal error:", error); 52 | process.exit(1); 53 | }); 54 | -------------------------------------------------------------------------------- /src/resources/examples/simulation.md: -------------------------------------------------------------------------------- 1 | # Simulation Examples 2 | 3 | ## Population Growth Model 4 | 5 | ### Basic Exponential Growth 6 | 7 | ```json 8 | { 9 | "prompt": "Simulate population growth over time", 10 | "parameters": { 11 | "initial": { 12 | "population": 1000, 13 | "growth_rate": 0.02, 14 | "carrying_capacity": 10000 15 | }, 16 | "updateRules": [ 17 | { 18 | "target": "population", 19 | "rule": "population * (1 + growth_rate * (1 - population / carrying_capacity))" 20 | }, 21 | { 22 | "target": "growth_rate", 23 | "rule": "growth_rate * 0.99" 24 | } 25 | ], 26 | "steps": 50 27 | } 28 | } 29 | ``` 30 | 31 | ## Economic Model 32 | 33 | ### Supply and Demand Dynamics 34 | 35 | ```json 36 | { 37 | "prompt": "Simulate market equilibrium", 38 | "parameters": { 39 | "initial": { 40 | "price": 100, 41 | "supply": 500, 42 | "demand": 600, 43 | "elasticity": 0.8 44 | }, 45 | "updateRules": [ 46 | { 47 | "target": "price", 48 | "rule": "price + 0.1 * (demand - supply)" 49 | }, 50 | { 51 | "target": "demand", 52 | "rule": "600 - elasticity * price" 53 | }, 54 | { 55 | "target": "supply", 56 | "rule": "400 + 0.5 * price" 57 | } 58 | ], 59 | "steps": 30 60 | } 61 | } 62 | ``` 63 | 64 | ## Disease Spread Model 65 | 66 | ### SIR Epidemic Model 67 | 68 | ```json 69 | { 70 | "prompt": "Simulate disease spread in population", 71 | "parameters": { 72 | "initial": { 73 | "susceptible": 9900, 74 | "infected": 100, 75 | "recovered": 0, 76 | "transmission_rate": 0.3, 77 | "recovery_rate": 0.1 78 | }, 79 | "updateRules": [ 80 | { 81 | "target": "susceptible", 82 | "rule": "susceptible - (transmission_rate * susceptible * infected / 10000)" 83 | }, 84 | { 85 | "target": "infected", 86 | "rule": "infected + (transmission_rate * susceptible * infected / 10000) - (recovery_rate * infected)" 87 | }, 88 | { 89 | "target": "recovered", 90 | "rule": "recovered + (recovery_rate * infected)" 91 | } 92 | ], 93 | "steps": 100 94 | } 95 | } 96 | ``` -------------------------------------------------------------------------------- /dist/tools/structured-argumentation.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const StructuredArgumentationSchema: z.ZodObject<{ 4 | claim: z.ZodString; 5 | premises: z.ZodArray; 9 | }, "strip", z.ZodTypeAny, { 10 | strength: "strong" | "moderate" | "weak"; 11 | statement: string; 12 | support: string; 13 | }, { 14 | strength: "strong" | "moderate" | "weak"; 15 | statement: string; 16 | support: string; 17 | }>, "many">; 18 | counterarguments: z.ZodOptional, "many">>; 28 | conclusion: z.ZodString; 29 | validity: z.ZodEnum<["valid", "invalid", "uncertain"]>; 30 | }, "strip", z.ZodTypeAny, { 31 | claim: string; 32 | conclusion: string; 33 | premises: { 34 | strength: "strong" | "moderate" | "weak"; 35 | statement: string; 36 | support: string; 37 | }[]; 38 | validity: "valid" | "uncertain" | "invalid"; 39 | counterarguments?: { 40 | argument: string; 41 | rebuttal: string; 42 | }[] | undefined; 43 | }, { 44 | claim: string; 45 | conclusion: string; 46 | premises: { 47 | strength: "strong" | "moderate" | "weak"; 48 | statement: string; 49 | support: string; 50 | }[]; 51 | validity: "valid" | "uncertain" | "invalid"; 52 | counterarguments?: { 53 | argument: string; 54 | rebuttal: string; 55 | }[] | undefined; 56 | }>; 57 | export type StructuredArgumentationArgs = z.infer; 58 | declare function handleStructuredArgumentation(args: StructuredArgumentationArgs, session: SessionState): Promise<{ 59 | content: { 60 | type: "text"; 61 | text: string; 62 | }[]; 63 | }>; 64 | export { handleStructuredArgumentation }; 65 | //# sourceMappingURL=structured-argumentation.d.ts.map -------------------------------------------------------------------------------- /dist/tools/sequential-thinking.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const SequentialThinkingSchema: z.ZodObject<{ 4 | thought: z.ZodString; 5 | thoughtNumber: z.ZodNumber; 6 | totalThoughts: z.ZodNumber; 7 | nextThoughtNeeded: z.ZodBoolean; 8 | sessionId: z.ZodOptional; 9 | isRevision: z.ZodOptional; 10 | revisesThought: z.ZodOptional; 11 | branchFromThought: z.ZodOptional; 12 | branchId: z.ZodOptional; 13 | needsMoreThoughts: z.ZodOptional; 14 | reasoningPattern: z.ZodOptional>; 15 | explorationDepth: z.ZodOptional; 16 | beamWidth: z.ZodOptional; 17 | }, "strip", z.ZodTypeAny, { 18 | thought: string; 19 | thoughtNumber: number; 20 | totalThoughts: number; 21 | nextThoughtNeeded: boolean; 22 | sessionId?: string | undefined; 23 | isRevision?: boolean | undefined; 24 | revisesThought?: number | undefined; 25 | branchFromThought?: number | undefined; 26 | branchId?: string | undefined; 27 | needsMoreThoughts?: boolean | undefined; 28 | reasoningPattern?: "tree" | "graph" | "beam" | "mcts" | "linear" | undefined; 29 | explorationDepth?: number | undefined; 30 | beamWidth?: number | undefined; 31 | }, { 32 | thought: string; 33 | thoughtNumber: number; 34 | totalThoughts: number; 35 | nextThoughtNeeded: boolean; 36 | sessionId?: string | undefined; 37 | isRevision?: boolean | undefined; 38 | revisesThought?: number | undefined; 39 | branchFromThought?: number | undefined; 40 | branchId?: string | undefined; 41 | needsMoreThoughts?: boolean | undefined; 42 | reasoningPattern?: "tree" | "graph" | "beam" | "mcts" | "linear" | undefined; 43 | explorationDepth?: number | undefined; 44 | beamWidth?: number | undefined; 45 | }>; 46 | export type SequentialThinkingArgs = z.infer; 47 | declare function handleSequentialThinking(args: SequentialThinkingArgs, session: SessionState): Promise<{ 48 | content: { 49 | type: "text"; 50 | text: string; 51 | }[]; 52 | }>; 53 | export { handleSequentialThinking }; 54 | //# sourceMappingURL=sequential-thinking.d.ts.map -------------------------------------------------------------------------------- /dist/handlers/reasoning-patterns/tree-of-thought.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Tree of Thought Pattern Handler Implementation 3 | * 4 | * Implements systematic exploration of multiple reasoning paths with 5 | * explicit branching and evaluation. 6 | */ 7 | import { TreeOfThoughtNode, TreeOfThoughtSession, TreeOfThoughtConfig, TreeOfThoughtOperations } from '../../types/reasoning-patterns/tree-of-thought.js'; 8 | import { ThoughtData } from '../../types/index.js'; 9 | export declare class TreeOfThoughtHandler implements TreeOfThoughtOperations { 10 | private readonly defaultConfig; 11 | /** 12 | * Initialize a new Tree of Thought session 13 | */ 14 | initializeSession(config?: Partial): TreeOfThoughtSession; 15 | /** 16 | * Create a new node in the tree 17 | */ 18 | createNode(content: string, parentId: string, session: TreeOfThoughtSession): TreeOfThoughtNode; 19 | /** 20 | * Expand a node by generating children 21 | */ 22 | expand(nodeId: string, session: TreeOfThoughtSession): TreeOfThoughtNode[]; 23 | /** 24 | * Evaluate a node's promise/score 25 | */ 26 | evaluate(nodeId: string, session: TreeOfThoughtSession): number; 27 | /** 28 | * Select next node to explore 29 | */ 30 | selectNext(session: TreeOfThoughtSession): string | null; 31 | /** 32 | * Prune a subtree 33 | */ 34 | prune(nodeId: string, reason: string, session: TreeOfThoughtSession): void; 35 | /** 36 | * Check if node meets solution criteria 37 | */ 38 | isSolution(nodeId: string, session: TreeOfThoughtSession): boolean; 39 | /** 40 | * Get path from root to node 41 | */ 42 | getPath(nodeId: string, session: TreeOfThoughtSession): string[]; 43 | /** 44 | * Get best path based on scores 45 | */ 46 | getBestPath(session: TreeOfThoughtSession): string[]; 47 | /** 48 | * Export session to sequential thinking format 49 | */ 50 | exportToSequentialFormat(session: TreeOfThoughtSession): ThoughtData[]; 51 | /** 52 | * Import from sequential thinking format 53 | */ 54 | importFromSequentialFormat(thoughts: ThoughtData[]): TreeOfThoughtSession; 55 | /** 56 | * Run one iteration of tree exploration 57 | */ 58 | runIteration(session: TreeOfThoughtSession): void; 59 | } 60 | export default TreeOfThoughtHandler; 61 | //# sourceMappingURL=tree-of-thought.d.ts.map -------------------------------------------------------------------------------- /dist/state/SessionManager.js: -------------------------------------------------------------------------------- 1 | import { SessionState } from './SessionState.js'; 2 | import { defaultConfig } from '../config.js'; 3 | export class SessionManager { 4 | sessions = new Map(); 5 | maxSessions = 100; 6 | sessionTimeout = 3600000; // 1 hour 7 | config; 8 | constructor(config) { 9 | this.config = config || defaultConfig; 10 | } 11 | getOrCreateSession(sessionId) { 12 | if (this.sessions.has(sessionId)) { 13 | const session = this.sessions.get(sessionId); 14 | session.lastAccessedAt = new Date(); 15 | return session; 16 | } 17 | // Clean up old sessions if at limit 18 | if (this.sessions.size >= this.maxSessions) { 19 | this.cleanupOldSessions(); 20 | } 21 | const sessionInfo = { 22 | id: sessionId, 23 | state: new SessionState(sessionId, this.config), 24 | createdAt: new Date(), 25 | lastAccessedAt: new Date() 26 | }; 27 | this.sessions.set(sessionId, sessionInfo); 28 | return sessionInfo; 29 | } 30 | getSession(sessionId) { 31 | const session = this.sessions.get(sessionId); 32 | if (session) { 33 | session.lastAccessedAt = new Date(); 34 | } 35 | return session; 36 | } 37 | cleanupOldSessions() { 38 | const now = Date.now(); 39 | const toDelete = []; 40 | for (const [id, session] of this.sessions) { 41 | if (now - session.lastAccessedAt.getTime() > this.sessionTimeout) { 42 | toDelete.push(id); 43 | } 44 | } 45 | for (const id of toDelete) { 46 | this.sessions.delete(id); 47 | } 48 | // If still over limit, remove oldest 49 | if (this.sessions.size >= this.maxSessions) { 50 | const sorted = Array.from(this.sessions.entries()) 51 | .sort((a, b) => a[1].lastAccessedAt.getTime() - b[1].lastAccessedAt.getTime()); 52 | const toRemove = sorted.slice(0, Math.floor(this.maxSessions / 4)); 53 | for (const [id] of toRemove) { 54 | this.sessions.delete(id); 55 | } 56 | } 57 | } 58 | getAllSessions() { 59 | return Array.from(this.sessions.values()); 60 | } 61 | clearAllSessions() { 62 | this.sessions.clear(); 63 | } 64 | } 65 | //# sourceMappingURL=SessionManager.js.map -------------------------------------------------------------------------------- /dist/tools/systems-thinking.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const SystemsThinkingSchema: z.ZodObject<{ 4 | systemName: z.ZodString; 5 | components: z.ZodArray; 9 | }, "strip", z.ZodTypeAny, { 10 | function: string; 11 | name: string; 12 | interactions: string[]; 13 | }, { 14 | function: string; 15 | name: string; 16 | interactions: string[]; 17 | }>, "many">; 18 | boundaries: z.ZodString; 19 | inputs: z.ZodArray; 20 | outputs: z.ZodArray; 21 | feedbackLoops: z.ZodOptional; 23 | description: z.ZodString; 24 | }, "strip", z.ZodTypeAny, { 25 | type: "positive" | "negative"; 26 | description: string; 27 | }, { 28 | type: "positive" | "negative"; 29 | description: string; 30 | }>, "many">>; 31 | emergentProperties: z.ZodOptional>; 32 | }, "strip", z.ZodTypeAny, { 33 | systemName: string; 34 | components: { 35 | function: string; 36 | name: string; 37 | interactions: string[]; 38 | }[]; 39 | boundaries: string; 40 | inputs: string[]; 41 | outputs: string[]; 42 | feedbackLoops?: { 43 | type: "positive" | "negative"; 44 | description: string; 45 | }[] | undefined; 46 | emergentProperties?: string[] | undefined; 47 | }, { 48 | systemName: string; 49 | components: { 50 | function: string; 51 | name: string; 52 | interactions: string[]; 53 | }[]; 54 | boundaries: string; 55 | inputs: string[]; 56 | outputs: string[]; 57 | feedbackLoops?: { 58 | type: "positive" | "negative"; 59 | description: string; 60 | }[] | undefined; 61 | emergentProperties?: string[] | undefined; 62 | }>; 63 | export type SystemsThinkingArgs = z.infer; 64 | declare function handleSystemsThinking(args: SystemsThinkingArgs, session: SessionState): Promise<{ 65 | content: { 66 | type: "text"; 67 | text: string; 68 | }[]; 69 | }>; 70 | export { handleSystemsThinking }; 71 | //# sourceMappingURL=systems-thinking.d.ts.map -------------------------------------------------------------------------------- /src/resources/examples/scientific-method.md: -------------------------------------------------------------------------------- 1 | # Scientific Method Examples 2 | 3 | ## Productivity Research 4 | 5 | ### Remote Work Impact Study 6 | 7 | ```json 8 | { 9 | "prompt": "Does remote work increase productivity?", 10 | "parameters": { 11 | "stage": "conclusion", 12 | "hypothesis": "Remote work increases productivity by 15% due to reduced commute stress and flexible hours", 13 | "experiment": "A/B test with control group in office and test group remote for 3 months", 14 | "observations": [ 15 | "Remote group completed 18% more tasks", 16 | "Remote group reported 25% higher satisfaction", 17 | "In-office group had better collaboration scores", 18 | "Remote group had 12% fewer sick days", 19 | "Meeting time decreased by 30% for remote group", 20 | "Code review turnaround improved by 22% remotely" 21 | ], 22 | "analysis": "Statistical significance achieved (p<0.05) for productivity increase. Effect size Cohen's d=0.7 indicating moderate to large effect.", 23 | "conclusion": "Remote work does increase individual productivity but may impact team collaboration. Hybrid model recommended." 24 | } 25 | } 26 | ``` 27 | 28 | ## User Experience Research 29 | 30 | ### Interface Design Testing 31 | 32 | ```json 33 | { 34 | "prompt": "Does dark mode reduce eye strain?", 35 | "parameters": { 36 | "stage": "analysis", 37 | "hypothesis": "Dark mode interfaces reduce eye strain by 30% in low-light conditions", 38 | "experiment": "Controlled study with 100 users, randomized between dark and light modes, measuring eye strain metrics", 39 | "observations": [ 40 | "Blink rate increased 15% with light mode", 41 | "Subjective discomfort scores 40% higher in light mode", 42 | "Reading speed 5% faster in dark mode", 43 | "Accuracy unchanged between modes", 44 | "Pupil dilation 20% less in dark mode", 45 | "Fatigue onset 25 minutes later with dark mode" 46 | ], 47 | "analysis": "Significant reduction in eye strain indicators with dark mode. Multiple metrics support hypothesis.", 48 | "conclusion": "" 49 | } 50 | } 51 | ``` 52 | 53 | ## Algorithm Performance Study 54 | 55 | ### Cache Optimization Research 56 | 57 | ```json 58 | { 59 | "prompt": "Will implementing an LRU cache improve API response times?", 60 | "parameters": { 61 | "stage": "experiment", 62 | "hypothesis": "LRU cache will reduce average API response time by 40% for frequently accessed data", 63 | "experiment": "Deploy cache to 50% of servers, measure response times over 2 weeks, control for request patterns", 64 | "observations": [], 65 | "analysis": "", 66 | "conclusion": "" 67 | } 68 | } 69 | ``` -------------------------------------------------------------------------------- /src/tools/operations/patterns/beam-search.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Beam Search Operation 3 | * 4 | * Implements beam search pattern for exploring top-k candidates 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | import { operationRegistry } from '../registry.js'; 9 | import { getPresetForPattern } from '../../../notebook/presets.js'; 10 | import { EphemeralNotebookStore } from '../../../notebook/EphemeralNotebook.js'; 11 | 12 | const notebookStore = new EphemeralNotebookStore(); 13 | 14 | export class BeamSearchOperation extends BaseOperation { 15 | name = 'beam_search'; 16 | category = 'patterns'; 17 | 18 | async execute(context: OperationContext): Promise { 19 | const { sessionState, prompt, parameters } = context; 20 | 21 | // Create notebook with preset if needed 22 | const sessionId = sessionState.sessionId; 23 | let notebook = notebookStore.getNotebookBySession(sessionId); 24 | 25 | if (!notebook && this.getParam(parameters, 'createNotebook', true)) { 26 | notebook = notebookStore.createNotebook(sessionId); 27 | const preset = getPresetForPattern('beam_search'); 28 | if (preset) { 29 | for (const cell of preset.cells) { 30 | notebookStore.addCell( 31 | notebook.id, 32 | cell.type, 33 | cell.source, 34 | cell.language, 35 | ); 36 | } 37 | } 38 | } 39 | 40 | // Delegate to sequential_thinking with beam pattern 41 | const sequentialOp = operationRegistry.get('sequential_thinking'); 42 | if (sequentialOp) { 43 | return await sequentialOp.execute({ 44 | sessionState, 45 | prompt, 46 | parameters: { 47 | pattern: 'beam', 48 | patternParams: { 49 | beamWidth: this.getParam(parameters, 'beamWidth', 3), 50 | candidates: this.getParam(parameters, 'candidates', []), 51 | scores: this.getParam(parameters, 'scores', []), 52 | iterations: this.getParam(parameters, 'iterations', 5), 53 | }, 54 | thoughtNumber: this.getParam(parameters, 'thoughtNumber', 1), 55 | totalThoughts: this.getParam(parameters, 'totalThoughts', 3), 56 | nextThoughtNeeded: this.getParam(parameters, 'nextThoughtNeeded', true), 57 | needsMoreThoughts: this.getParam(parameters, 'needsMoreThoughts', true), 58 | __disablePatternDispatch: true, 59 | notebookId: notebook?.id, 60 | }, 61 | }); 62 | } 63 | 64 | return this.createResult({ 65 | error: 'Sequential thinking operation not found', 66 | }); 67 | } 68 | } 69 | 70 | export default new BeamSearchOperation(); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@waldzellai/clear-thought-onepointfive", 3 | "version": "0.2.1", 4 | "description": "Clear Thought MCP server with modular architecture - 38 reasoning operations for systematic thinking", 5 | "license": "MIT", 6 | "author": "Waldzell AI", 7 | "homepage": "https://github.com/waldzellai/clear-thought-onepointfive.git", 8 | "bugs": { 9 | "url": "https://github.com/waldzellai/clear-thought-onepointfive/issues" 10 | }, 11 | "type": "module", 12 | "module": "./src/index.ts", 13 | "files": [ 14 | "dist/**/*", 15 | "README.md", 16 | "LICENSE", 17 | "package.json" 18 | ], 19 | "main": "dist/src/index.js", 20 | "types": "dist/src/index.d.ts", 21 | "exports": { 22 | ".": { 23 | "import": "./dist/src/index.js", 24 | "types": "./dist/src/index.d.ts" 25 | } 26 | }, 27 | "bin": { 28 | "clear-thought": "./dist/cli/stdio-server.js" 29 | }, 30 | "scripts": { 31 | "build:stdio": "tsc cli/stdio-server.ts --outDir dist --module esnext --target es2020 --moduleResolution node --esModuleInterop true", 32 | "build:http": "npx @smithery/cli build", 33 | "copy-resources": "mkdir -p dist/resources && cp -r src/resources/* dist/resources/", 34 | "build": "npm run build:stdio && npm run build:http && npm run copy-resources", 35 | "dev": "npx @smithery/cli dev", 36 | "typecheck": "tsc --noEmit", 37 | "check": "npx @biomejs/biome check --write --unsafe", 38 | "test": "vitest", 39 | "prepublishOnly": "npm run build && npm run typecheck", 40 | "version": "npm run check && git add -A", 41 | "postversion": "git push && git push --tags" 42 | }, 43 | "repository": { 44 | "type": "git", 45 | "url": "git+https://github.com/waldzellai/clear-thought-onepointfive.git" 46 | }, 47 | "dependencies": { 48 | "@mcp-ui/server": "^5.2.0", 49 | "@modelcontextprotocol/sdk": "^1.17.0", 50 | "@shinzolabs/instrumentation-mcp": "^1.0.8", 51 | "@smithery/sdk": "^1.5.5", 52 | "@types/marked": "^5.0.2", 53 | "json-schema": "^0.4.0", 54 | "marked": "^15.0.12", 55 | "zod": "^3.23.8" 56 | }, 57 | "devDependencies": { 58 | "@smithery/cli": "^1.2.4", 59 | "@types/node": "^22", 60 | "tsx": "^4.20.5", 61 | "typescript": "^5.3.3" 62 | }, 63 | "keywords": [ 64 | "mcp", 65 | "modelcontextprotocol", 66 | "reasoning", 67 | "sd", 68 | "complex-systems", 69 | "tree-of-thought", 70 | "mcts", 71 | "graph-of-thought", 72 | "beam-search", 73 | "chain-of-thought", 74 | "sequential-thinking", 75 | "mental-models", 76 | "james-clear", 77 | "cognitive-tools", 78 | "model-enhancement", 79 | "sequentialthinking" 80 | ], 81 | "engines": { 82 | "node": ">=18" 83 | }, 84 | "publishConfig": { 85 | "access": "public", 86 | "registry": "https://registry.npmjs.org/" 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/tools/operations/patterns/graph-of-thought.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Graph of Thought Operation 3 | * 4 | * Implements graph-based reasoning with nodes and edges 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | import { operationRegistry } from '../registry.js'; 9 | import { getPresetForPattern } from '../../../notebook/presets.js'; 10 | import { EphemeralNotebookStore } from '../../../notebook/EphemeralNotebook.js'; 11 | 12 | const notebookStore = new EphemeralNotebookStore(); 13 | 14 | export class GraphOfThoughtOperation extends BaseOperation { 15 | name = 'graph_of_thought'; 16 | category = 'patterns'; 17 | 18 | async execute(context: OperationContext): Promise { 19 | const { sessionState, prompt, parameters } = context; 20 | 21 | // Create notebook with preset if needed 22 | const sessionId = sessionState.sessionId; 23 | let notebook = notebookStore.getNotebookBySession(sessionId); 24 | 25 | if (!notebook && this.getParam(parameters, 'createNotebook', true)) { 26 | notebook = notebookStore.createNotebook(sessionId); 27 | const preset = getPresetForPattern('graph_of_thought'); 28 | if (preset) { 29 | for (const cell of preset.cells) { 30 | notebookStore.addCell( 31 | notebook.id, 32 | cell.type, 33 | cell.source, 34 | cell.language, 35 | ); 36 | } 37 | } 38 | } 39 | 40 | // Delegate to sequential_thinking with graph pattern 41 | const sequentialOp = operationRegistry.get('sequential_thinking'); 42 | if (sequentialOp) { 43 | return await sequentialOp.execute({ 44 | sessionState, 45 | prompt, 46 | parameters: { 47 | pattern: 'graph', 48 | patternParams: { 49 | nodes: this.getParam(parameters, 'nodes', []), 50 | edges: this.getParam(parameters, 'edges', []), 51 | paths: this.getParam(parameters, 'paths', []), 52 | optimalPath: this.getParam(parameters, 'optimalPath', null), 53 | }, 54 | thoughtNumber: this.getParam(parameters, 'thoughtNumber', 1), 55 | totalThoughts: this.getParam(parameters, 'totalThoughts', 3), 56 | nextThoughtNeeded: this.getParam(parameters, 'nextThoughtNeeded', true), 57 | needsMoreThoughts: this.getParam(parameters, 'needsMoreThoughts', true), 58 | __disablePatternDispatch: true, 59 | notebookId: notebook?.id, 60 | }, 61 | }); 62 | } 63 | 64 | return this.createResult({ 65 | error: 'Sequential thinking operation not found', 66 | }); 67 | } 68 | } 69 | 70 | export default new GraphOfThoughtOperation(); -------------------------------------------------------------------------------- /src/tools/operations/patterns/tree-of-thought.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Tree of Thought Operation 3 | * 4 | * Implements tree-based reasoning with branching exploration 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | import { operationRegistry } from '../registry.js'; 9 | import { getPresetForPattern } from '../../../notebook/presets.js'; 10 | import { EphemeralNotebookStore } from '../../../notebook/EphemeralNotebook.js'; 11 | 12 | const notebookStore = new EphemeralNotebookStore(); 13 | 14 | export class TreeOfThoughtOperation extends BaseOperation { 15 | name = 'tree_of_thought'; 16 | category = 'patterns'; 17 | 18 | async execute(context: OperationContext): Promise { 19 | const { sessionState, prompt, parameters } = context; 20 | 21 | // Create notebook with preset if needed 22 | const sessionId = sessionState.sessionId; 23 | let notebook = notebookStore.getNotebookBySession(sessionId); 24 | 25 | if (!notebook && this.getParam(parameters, 'createNotebook', true)) { 26 | notebook = notebookStore.createNotebook(sessionId); 27 | const preset = getPresetForPattern('tree_of_thought'); 28 | if (preset) { 29 | for (const cell of preset.cells) { 30 | notebookStore.addCell( 31 | notebook.id, 32 | cell.type, 33 | cell.source, 34 | cell.language, 35 | ); 36 | } 37 | } 38 | } 39 | 40 | // Delegate to sequential_thinking with tree pattern 41 | const sequentialOp = operationRegistry.get('sequential_thinking'); 42 | if (sequentialOp) { 43 | return await sequentialOp.execute({ 44 | sessionState, 45 | prompt, 46 | parameters: { 47 | pattern: 'tree', 48 | patternParams: { 49 | depth: this.getParam(parameters, 'depth', 3), 50 | breadth: this.getParam(parameters, 'breadth', 3), 51 | branches: this.getParam(parameters, 'branches', []), 52 | evaluations: this.getParam(parameters, 'evaluations', []), 53 | selectedPath: this.getParam(parameters, 'selectedPath', null), 54 | }, 55 | thoughtNumber: this.getParam(parameters, 'thoughtNumber', 1), 56 | totalThoughts: this.getParam(parameters, 'totalThoughts', 3), 57 | nextThoughtNeeded: this.getParam(parameters, 'nextThoughtNeeded', true), 58 | needsMoreThoughts: this.getParam(parameters, 'needsMoreThoughts', true), 59 | __disablePatternDispatch: true, 60 | notebookId: notebook?.id, 61 | }, 62 | }); 63 | } 64 | 65 | return this.createResult({ 66 | error: 'Sequential thinking operation not found', 67 | }); 68 | } 69 | } 70 | 71 | export default new TreeOfThoughtOperation(); -------------------------------------------------------------------------------- /src/tools/operations/patterns/mcts.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Monte Carlo Tree Search Operation 3 | * 4 | * Implements MCTS pattern for decision-making under uncertainty 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | import { operationRegistry } from '../registry.js'; 9 | import { getPresetForPattern } from '../../../notebook/presets.js'; 10 | import { EphemeralNotebookStore } from '../../../notebook/EphemeralNotebook.js'; 11 | 12 | const notebookStore = new EphemeralNotebookStore(); 13 | 14 | export class MCTSOperation extends BaseOperation { 15 | name = 'mcts'; 16 | category = 'patterns'; 17 | 18 | async execute(context: OperationContext): Promise { 19 | const { sessionState, prompt, parameters } = context; 20 | 21 | // Create notebook with preset if needed 22 | const sessionId = sessionState.sessionId; 23 | let notebook = notebookStore.getNotebookBySession(sessionId); 24 | 25 | if (!notebook && this.getParam(parameters, 'createNotebook', true)) { 26 | notebook = notebookStore.createNotebook(sessionId); 27 | const preset = getPresetForPattern('mcts'); 28 | if (preset) { 29 | for (const cell of preset.cells) { 30 | notebookStore.addCell( 31 | notebook.id, 32 | cell.type, 33 | cell.source, 34 | cell.language, 35 | ); 36 | } 37 | } 38 | } 39 | 40 | // Delegate to sequential_thinking with MCTS pattern 41 | const sequentialOp = operationRegistry.get('sequential_thinking'); 42 | if (sequentialOp) { 43 | return await sequentialOp.execute({ 44 | sessionState, 45 | prompt, 46 | parameters: { 47 | pattern: 'mcts', 48 | patternParams: { 49 | simulations: this.getParam(parameters, 'simulations', 100), 50 | explorationConstant: this.getParam(parameters, 'explorationConstant', Math.SQRT2), 51 | tree: this.getParam(parameters, 'tree', { 52 | root: { visits: 0, value: 0, children: [] }, 53 | }), 54 | bestAction: this.getParam(parameters, 'bestAction', null), 55 | }, 56 | thoughtNumber: this.getParam(parameters, 'thoughtNumber', 1), 57 | totalThoughts: this.getParam(parameters, 'totalThoughts', 3), 58 | nextThoughtNeeded: this.getParam(parameters, 'nextThoughtNeeded', true), 59 | needsMoreThoughts: this.getParam(parameters, 'needsMoreThoughts', true), 60 | __disablePatternDispatch: true, 61 | notebookId: notebook?.id, 62 | }, 63 | }); 64 | } 65 | 66 | return this.createResult({ 67 | error: 'Sequential thinking operation not found', 68 | }); 69 | } 70 | } 71 | 72 | export default new MCTSOperation(); -------------------------------------------------------------------------------- /src/tools/operations/core/creative-thinking.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Creative Thinking Operation 3 | * 4 | * Facilitates creative problem-solving through various techniques 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class CreativeThinkingOperation extends BaseOperation { 10 | name = 'creative_thinking'; 11 | category = 'core'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState, prompt, parameters } = context; 15 | 16 | const technique = this.getParam(parameters, 'technique', 'brainstorming'); 17 | const ideas = (parameters.ideas as string[]) || []; 18 | const constraints = (parameters.constraints as string[]) || []; 19 | const evaluation = this.getParam(parameters, 'evaluation', ''); 20 | 21 | // Generate ideas if none provided 22 | const generatedIdeas = ideas.length === 0 ? this.generateIdeas(prompt, technique) : ideas; 23 | 24 | const creativeData = { 25 | technique, 26 | challenge: prompt, 27 | ideas: generatedIdeas, 28 | constraints, 29 | evaluation, 30 | selectedIdea: this.getParam(parameters, 'selectedIdea', null), 31 | combinedConcepts: this.getParam(parameters, 'combinedConcepts', []), 32 | }; 33 | 34 | return this.createResult({ 35 | ...creativeData, 36 | sessionContext: { 37 | sessionId: sessionState.sessionId, 38 | stats: sessionState.getStats(), 39 | }, 40 | }); 41 | } 42 | 43 | private generateIdeas(prompt: string, technique: string): string[] { 44 | const ideas: string[] = []; 45 | 46 | switch (technique) { 47 | case 'brainstorming': 48 | ideas.push( 49 | 'Explore alternative approaches', 50 | 'Consider opposite perspectives', 51 | 'Break down into smaller components' 52 | ); 53 | break; 54 | case 'scamper': 55 | ideas.push( 56 | 'Substitute: What can be substituted?', 57 | 'Combine: What can be combined?', 58 | 'Adapt: What can be adapted?', 59 | 'Modify: What can be modified?', 60 | 'Put to other uses: How else can this be used?', 61 | 'Eliminate: What can be removed?', 62 | 'Reverse: What can be reversed?' 63 | ); 64 | break; 65 | case 'random_word': 66 | const randomWords = ['bridge', 'cloud', 'seed', 'mirror', 'wave']; 67 | const randomWord = randomWords[Math.floor(Math.random() * randomWords.length)]; 68 | ideas.push(`How does "${randomWord}" relate to ${prompt}?`); 69 | break; 70 | default: 71 | ideas.push('Generate creative solutions'); 72 | } 73 | 74 | return ideas; 75 | } 76 | } 77 | 78 | export default new CreativeThinkingOperation(); -------------------------------------------------------------------------------- /src/tools/operations/analysis/research.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Research Operation 3 | * 4 | * Structures research intent and placeholders for downstream web tooling 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | import type { ResearchFinding, ResearchSource, ResearchResult } from '../../../types/index.js'; 9 | 10 | export class ResearchOperation extends BaseOperation { 11 | name = 'research'; 12 | category = 'analysis'; 13 | 14 | async execute(context: OperationContext): Promise { 15 | const { prompt, parameters } = context; 16 | 17 | const subqueries = (parameters.subqueries as string[]) || []; 18 | let findings = (parameters.findings as ResearchFinding[]) || []; 19 | let citations = (parameters.citations as ResearchSource[]) || []; 20 | 21 | // If no structured input, create placeholder findings from prompt 22 | if (findings.length === 0 && prompt) { 23 | findings = this.generatePlaceholderFindings(prompt); 24 | } 25 | 26 | // Generate sub-queries if none provided 27 | let derivedSubqueries = subqueries; 28 | if (derivedSubqueries.length === 0 && prompt) { 29 | derivedSubqueries = this.generateSubqueries(prompt); 30 | } 31 | 32 | const result: ResearchResult = { 33 | query: prompt, 34 | findings, 35 | citations, 36 | }; 37 | 38 | return this.createResult({ 39 | ...result, 40 | subqueries: derivedSubqueries, 41 | note: "This operation structures research intent. Use external tools for actual web search and data gathering." 42 | }); 43 | } 44 | 45 | private generatePlaceholderFindings(prompt: string): ResearchFinding[] { 46 | const findings: ResearchFinding[] = []; 47 | const sentences = prompt.split(/[.!?]+/).filter(s => s.trim().length > 0); 48 | 49 | for (const sentence of sentences.slice(0, 3)) { 50 | const trimmed = sentence.trim(); 51 | if (trimmed) { 52 | findings.push({ 53 | claim: `Research needed: ${trimmed}`, 54 | evidence: "[Evidence to be gathered]", 55 | confidence: 0.0, 56 | sources: [] 57 | }); 58 | } 59 | } 60 | 61 | return findings; 62 | } 63 | 64 | private generateSubqueries(prompt: string): string[] { 65 | const subqueries: string[] = []; 66 | const questionStarters = ['What', 'How', 'Why', 'When', 'Where', 'Who']; 67 | const keywords = prompt.split(/\s+/).filter(w => w.length > 3).slice(0, 3); 68 | 69 | for (const starter of questionStarters.slice(0, 3)) { 70 | for (const keyword of keywords.slice(0, 2)) { 71 | subqueries.push(`${starter} ${keyword.toLowerCase()}?`); 72 | } 73 | } 74 | 75 | return subqueries.slice(0, 5); 76 | } 77 | } 78 | 79 | export default new ResearchOperation(); -------------------------------------------------------------------------------- /src/resources/examples/creative-thinking.md: -------------------------------------------------------------------------------- 1 | # Creative Thinking Examples 2 | 3 | ## Product Innovation 4 | 5 | ### Mobile App for Elderly Users 6 | 7 | ```json 8 | { 9 | "prompt": "Design a new mobile app for elderly users", 10 | "parameters": { 11 | "techniques": ["SCAMPER", "brainstorming", "lateral_thinking"], 12 | "numIdeas": 10, 13 | "ideas": [ 14 | "Voice-first interface with large buttons", 15 | "Medication reminder with family notifications", 16 | "Simplified video calling with one-touch access", 17 | "Health monitoring integration with wearables", 18 | "Emergency contact speed dial with location sharing", 19 | "Digital photo album with voice narration", 20 | "Grocery list with voice input and sharing", 21 | "Daily news summary with adjustable text size", 22 | "Virtual companion with conversation features", 23 | "Exercise reminders with gentle guided routines" 24 | ] 25 | } 26 | } 27 | ``` 28 | 29 | ## Business Model Innovation 30 | 31 | ### Subscription Service Ideas 32 | 33 | ```json 34 | { 35 | "prompt": "Create innovative subscription business models", 36 | "parameters": { 37 | "techniques": ["SCAMPER", "blue_ocean"], 38 | "numIdeas": 8, 39 | "ideas": [ 40 | "Substitute ownership with access - tool library subscription", 41 | "Combine fitness and mental health - holistic wellness platform", 42 | "Adapt restaurant model - chef-at-home subscription", 43 | "Modify traditional education - micro-learning capsules", 44 | "Put to other use unused spaces - parking spot sharing", 45 | "Eliminate middlemen - direct farmer produce boxes", 46 | "Reverse the model - customers teach skills to each other", 47 | "Amplify community aspect - neighborhood resource sharing" 48 | ] 49 | } 50 | } 51 | ``` 52 | 53 | ## Marketing Campaign Concepts 54 | 55 | ### Eco-Friendly Product Launch 56 | 57 | ```json 58 | { 59 | "prompt": "Generate creative marketing ideas for eco-friendly product", 60 | "parameters": { 61 | "techniques": ["brainstorming", "lateral_thinking", "metaphorical_thinking"], 62 | "numIdeas": 12, 63 | "ideas": [ 64 | "Plant a tree for every purchase campaign", 65 | "AR app showing environmental impact reduction", 66 | "User-generated content challenge #MyGreenStory", 67 | "Partnership with schools for education program", 68 | "Transparent supply chain documentary series", 69 | "Gamified recycling rewards program", 70 | "Pop-up experiences in urban parks", 71 | "Influencer swap challenge - trade products for a week", 72 | "Time-lapse of product biodegrading vs competitors", 73 | "Community cleanup events with product demos", 74 | "Carbon footprint calculator integration", 75 | "Virtual forest showing collective impact" 76 | ] 77 | } 78 | } 79 | ``` -------------------------------------------------------------------------------- /dist/handlers/reasoning-patterns/graph-of-thought.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Graph of Thought Pattern Handler Implementation 3 | * 4 | * Implements non-hierarchical connections between thoughts with support 5 | * for complex reasoning patterns including cycles and multiple connections. 6 | */ 7 | import { GraphOfThoughtNode, GraphOfThoughtEdge, GraphOfThoughtSession, GraphOfThoughtConfig, GraphOfThoughtOperations, GraphEdgeType, NodeCluster } from '../../types/reasoning-patterns/graph-of-thought.js'; 8 | import { ThoughtData } from '../../types/index.js'; 9 | export declare class GraphOfThoughtHandler implements GraphOfThoughtOperations { 10 | private readonly defaultConfig; 11 | /** 12 | * Initialize a new Graph of Thought session 13 | */ 14 | initializeSession(config?: Partial): GraphOfThoughtSession; 15 | /** 16 | * Add a node to the graph 17 | */ 18 | addNode(nodeData: Omit, session: GraphOfThoughtSession): GraphOfThoughtNode; 19 | /** 20 | * Connect two nodes with an edge 21 | */ 22 | connectNodes(sourceId: string, targetId: string, edgeType: GraphEdgeType, weight: number, session: GraphOfThoughtSession): GraphOfThoughtEdge; 23 | /** 24 | * Find paths between two nodes 25 | */ 26 | findPaths(startId: string, endId: string, session: GraphOfThoughtSession, maxPaths?: number): string[][]; 27 | /** 28 | * Get node neighbors 29 | */ 30 | getNeighbors(nodeId: string, direction: 'incoming' | 'outgoing' | 'both', session: GraphOfThoughtSession): string[]; 31 | /** 32 | * Calculate node centrality (PageRank-like algorithm) 33 | */ 34 | calculateCentrality(session: GraphOfThoughtSession): Map; 35 | /** 36 | * Detect communities/clusters using simple connected components 37 | */ 38 | detectCommunities(session: GraphOfThoughtSession): NodeCluster[]; 39 | /** 40 | * Find contradictions in the graph 41 | */ 42 | findContradictions(session: GraphOfThoughtSession): Array<{ 43 | nodeIds: string[]; 44 | description: string; 45 | }>; 46 | /** 47 | * Merge similar nodes 48 | */ 49 | mergeNodes(nodeIds: string[], session: GraphOfThoughtSession): GraphOfThoughtNode; 50 | /** 51 | * Export to sequential thinking format 52 | */ 53 | exportToSequentialFormat(session: GraphOfThoughtSession): ThoughtData[]; 54 | /** 55 | * Import from sequential thinking format 56 | */ 57 | importFromSequentialFormat(thoughts: ThoughtData[]): GraphOfThoughtSession; 58 | private wouldCreateCycle; 59 | private updateGraphStats; 60 | private exploreCluster; 61 | private calculateClusterCohesion; 62 | private findClusterCentroid; 63 | private findCycles; 64 | private removeNode; 65 | private removeEdge; 66 | } 67 | export default GraphOfThoughtHandler; 68 | //# sourceMappingURL=graph-of-thought.d.ts.map -------------------------------------------------------------------------------- /dist/tools/visual-reasoning.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const VisualReasoningSchema: z.ZodObject<{ 4 | visualType: z.ZodEnum<["diagram", "flowchart", "mind_map", "concept_map", "graph", "matrix"]>; 5 | elements: z.ZodArray>; 19 | }, "strip", z.ZodTypeAny, { 20 | type: string; 21 | id: string; 22 | label: string; 23 | position?: { 24 | x: number; 25 | y: number; 26 | } | undefined; 27 | }, { 28 | type: string; 29 | id: string; 30 | label: string; 31 | position?: { 32 | x: number; 33 | y: number; 34 | } | undefined; 35 | }>, "many">; 36 | connections: z.ZodOptional; 40 | type: z.ZodOptional; 41 | }, "strip", z.ZodTypeAny, { 42 | from: string; 43 | to: string; 44 | type?: string | undefined; 45 | label?: string | undefined; 46 | }, { 47 | from: string; 48 | to: string; 49 | type?: string | undefined; 50 | label?: string | undefined; 51 | }>, "many">>; 52 | insights: z.ZodString; 53 | }, "strip", z.ZodTypeAny, { 54 | insights: string; 55 | visualType: "flowchart" | "graph" | "diagram" | "mind_map" | "concept_map" | "matrix"; 56 | elements: { 57 | type: string; 58 | id: string; 59 | label: string; 60 | position?: { 61 | x: number; 62 | y: number; 63 | } | undefined; 64 | }[]; 65 | connections?: { 66 | from: string; 67 | to: string; 68 | type?: string | undefined; 69 | label?: string | undefined; 70 | }[] | undefined; 71 | }, { 72 | insights: string; 73 | visualType: "flowchart" | "graph" | "diagram" | "mind_map" | "concept_map" | "matrix"; 74 | elements: { 75 | type: string; 76 | id: string; 77 | label: string; 78 | position?: { 79 | x: number; 80 | y: number; 81 | } | undefined; 82 | }[]; 83 | connections?: { 84 | from: string; 85 | to: string; 86 | type?: string | undefined; 87 | label?: string | undefined; 88 | }[] | undefined; 89 | }>; 90 | export type VisualReasoningArgs = z.infer; 91 | declare function handleVisualReasoning(args: VisualReasoningArgs, session: SessionState): Promise<{ 92 | content: { 93 | type: "text"; 94 | text: string; 95 | }[]; 96 | }>; 97 | export { handleVisualReasoning }; 98 | //# sourceMappingURL=visual-reasoning.d.ts.map -------------------------------------------------------------------------------- /dist/tools/session-management.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | const SessionManagementSchema = z.object({ 3 | action: z.enum([ 4 | 'export', 5 | 'import', 6 | 'clear', 7 | 'stats', 8 | 'summary' 9 | ]).describe('Session management action'), 10 | data: z.any().optional().describe('Data for import action'), 11 | format: z.enum(['json', 'summary']).optional().describe('Export format') 12 | }); 13 | async function handleSessionManagement(args, session) { 14 | let result = {}; 15 | switch (args.action) { 16 | case 'export': 17 | result = { 18 | action: 'export', 19 | data: { 20 | thoughts: session.getThoughts(), 21 | models: session.getMentalModels(), 22 | debugging: session.getDebuggingSessions(), 23 | decisions: session.getDecisions() 24 | }, 25 | format: args.format || 'json' 26 | }; 27 | break; 28 | case 'import': 29 | if (args.data) { 30 | // Import logic would go here 31 | result = { 32 | action: 'import', 33 | status: 'success', 34 | message: 'Session data import pending implementation' 35 | }; 36 | } 37 | else { 38 | result = { 39 | action: 'import', 40 | status: 'error', 41 | message: 'No data provided for import' 42 | }; 43 | } 44 | break; 45 | case 'clear': 46 | // Clear logic would reset session state 47 | result = { 48 | action: 'clear', 49 | status: 'success', 50 | message: 'Session clear pending implementation' 51 | }; 52 | break; 53 | case 'stats': 54 | result = { 55 | action: 'stats', 56 | data: session.getStats() 57 | }; 58 | break; 59 | case 'summary': 60 | result = { 61 | action: 'summary', 62 | data: { 63 | sessionId: session.sessionId, 64 | stats: session.getStats(), 65 | thoughtCount: session.getThoughts().length, 66 | modelCount: session.getMentalModels().length, 67 | debugCount: session.getDebuggingSessions().length, 68 | decisionCount: session.getDecisions().length 69 | } 70 | }; 71 | break; 72 | } 73 | return { 74 | content: [{ 75 | type: 'text', 76 | text: JSON.stringify(result) 77 | }] 78 | }; 79 | } 80 | // Self-register 81 | // ToolRegistry.getInstance().register({ 82 | // name: 'sessionmanagement', 83 | // description: 'Manage thinking session state - export, import, clear, and analyze', 84 | // schema: SessionManagementSchema, 85 | // handler: handleSessionManagement, 86 | // category: 'session' 87 | // }); 88 | export { handleSessionManagement }; 89 | //# sourceMappingURL=session-management.js.map -------------------------------------------------------------------------------- /dist/handlers/reasoning-patterns/beam-search.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Beam Search Pattern Handler Implementation 3 | * 4 | * Maintains multiple promising paths simultaneously, exploring them 5 | * in parallel with periodic evaluation and pruning. 6 | */ 7 | import { BeamSearchNode, BeamSearchPath, BeamSearchSession, BeamSearchConfig, BeamSearchOperations } from '../../types/reasoning-patterns/beam-search.js'; 8 | import { ThoughtData } from '../../types/index.js'; 9 | export declare class BeamSearchHandler implements BeamSearchOperations { 10 | private readonly defaultConfig; 11 | private readonly defaultConvergenceCriteria; 12 | /** 13 | * Initialize a new Beam Search session 14 | */ 15 | initializeSession(beamWidth?: number, config?: Partial): BeamSearchSession; 16 | /** 17 | * Generate next generation of nodes 18 | */ 19 | generateNextGeneration(session: BeamSearchSession): BeamSearchNode[]; 20 | /** 21 | * Expand a specific path 22 | */ 23 | expandPath(pathId: string, session: BeamSearchSession): BeamSearchNode[]; 24 | /** 25 | * Evaluate and score paths 26 | */ 27 | evaluatePaths(session: BeamSearchSession): Map; 28 | /** 29 | * Calculate score for a path 30 | */ 31 | private calculatePathScore; 32 | /** 33 | * Calculate diversity of a path compared to other active paths 34 | */ 35 | private calculatePathDiversity; 36 | /** 37 | * Calculate similarity between two paths 38 | */ 39 | private calculatePathSimilarity; 40 | /** 41 | * Prune paths to maintain beam width 42 | */ 43 | prunePaths(session: BeamSearchSession): string[]; 44 | /** 45 | * Check for convergence 46 | */ 47 | checkConvergence(session: BeamSearchSession): boolean; 48 | /** 49 | * Calculate consensus among active paths 50 | */ 51 | private calculateConsensus; 52 | /** 53 | * Calculate score improvement over recent generations 54 | */ 55 | private calculateScoreImprovement; 56 | /** 57 | * Merge similar paths 58 | */ 59 | mergePaths(pathIds: string[], session: BeamSearchSession): BeamSearchPath; 60 | /** 61 | * Merge node sequences from multiple paths 62 | */ 63 | private mergeNodeSequences; 64 | /** 65 | * Get best path 66 | */ 67 | getBestPath(session: BeamSearchSession): BeamSearchPath | null; 68 | /** 69 | * Calculate diversity across all active paths 70 | */ 71 | calculateDiversity(session: BeamSearchSession): number; 72 | /** 73 | * Export to sequential thinking format 74 | */ 75 | exportToSequentialFormat(session: BeamSearchSession): ThoughtData[]; 76 | /** 77 | * Import from sequential thinking format 78 | */ 79 | importFromSequentialFormat(thoughts: ThoughtData[]): BeamSearchSession; 80 | /** 81 | * Run one iteration of beam search 82 | */ 83 | runIteration(session: BeamSearchSession): void; 84 | /** 85 | * Attempt to merge similar paths 86 | */ 87 | private attemptPathMerging; 88 | /** 89 | * Update session statistics 90 | */ 91 | private updateStatistics; 92 | } 93 | export default BeamSearchHandler; 94 | //# sourceMappingURL=beam-search.d.ts.map -------------------------------------------------------------------------------- /src/resources/examples/systems-thinking.md: -------------------------------------------------------------------------------- 1 | # Systems Thinking Examples 2 | 3 | ## Healthcare System Analysis 4 | 5 | ### Example Parameters Structure 6 | 7 | ```json 8 | { 9 | "prompt": "Analyze the healthcare system", 10 | "parameters": { 11 | "components": [ 12 | "patients", 13 | "doctors", 14 | "hospitals", 15 | "insurance", 16 | "pharmaceuticals", 17 | "government" 18 | ], 19 | "relationships": [ 20 | { 21 | "from": "patients", 22 | "to": "doctors", 23 | "type": "dependency", 24 | "strength": 0.9 25 | }, 26 | { 27 | "from": "doctors", 28 | "to": "hospitals", 29 | "type": "affiliation", 30 | "strength": 0.7 31 | }, 32 | { 33 | "from": "insurance", 34 | "to": "patients", 35 | "type": "coverage", 36 | "strength": 0.8 37 | }, 38 | { 39 | "from": "government", 40 | "to": "insurance", 41 | "type": "regulation", 42 | "strength": 0.6 43 | } 44 | ], 45 | "feedbackLoops": [ 46 | { 47 | "components": ["patients", "insurance", "costs"], 48 | "type": "negative", 49 | "description": "Higher costs reduce patient access, reducing insurance claims" 50 | } 51 | ], 52 | "emergentProperties": [ 53 | "healthcare accessibility", 54 | "system efficiency", 55 | "cost inflation" 56 | ], 57 | "leveragePoints": [ 58 | "insurance reform", 59 | "preventive care programs" 60 | ] 61 | } 62 | } 63 | ``` 64 | 65 | ## Software Development System 66 | 67 | ### Example Parameters Structure 68 | 69 | ```json 70 | { 71 | "prompt": "Analyze the software development lifecycle", 72 | "parameters": { 73 | "components": [ 74 | "requirements", 75 | "design", 76 | "development", 77 | "testing", 78 | "deployment", 79 | "maintenance", 80 | "users", 81 | "stakeholders" 82 | ], 83 | "relationships": [ 84 | { 85 | "from": "requirements", 86 | "to": "design", 87 | "type": "input", 88 | "strength": 1.0 89 | }, 90 | { 91 | "from": "design", 92 | "to": "development", 93 | "type": "specification", 94 | "strength": 0.9 95 | }, 96 | { 97 | "from": "development", 98 | "to": "testing", 99 | "type": "validation", 100 | "strength": 0.8 101 | }, 102 | { 103 | "from": "users", 104 | "to": "requirements", 105 | "type": "feedback", 106 | "strength": 0.7 107 | } 108 | ], 109 | "feedbackLoops": [ 110 | { 111 | "components": ["testing", "development", "design"], 112 | "type": "positive", 113 | "description": "Bugs found in testing drive development fixes and design improvements" 114 | } 115 | ], 116 | "emergentProperties": [ 117 | "technical debt", 118 | "system reliability", 119 | "user satisfaction" 120 | ], 121 | "leveragePoints": [ 122 | "automated testing", 123 | "continuous integration", 124 | "user feedback loops" 125 | ] 126 | } 127 | } 128 | ``` -------------------------------------------------------------------------------- /src/tools/operations/collaborative/systems-thinking.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Systems Thinking Operation 3 | * 4 | * Analyzes complex systems by identifying components, relationships, and feedback loops 5 | */ 6 | 7 | import { BaseOperation, type OperationContext, type OperationResult } from '../base.js'; 8 | 9 | export class SystemsThinkingOperation extends BaseOperation { 10 | name = 'systems_thinking'; 11 | category = 'collaborative'; 12 | 13 | async execute(context: OperationContext): Promise { 14 | const { sessionState, prompt, parameters } = context; 15 | 16 | // Use provided parameters or default to empty arrays 17 | const components = (parameters.components as string[]) || []; 18 | const relationships = (parameters.relationships as any[]) || []; 19 | let feedbackLoops = (parameters.feedbackLoops as any[]) || []; 20 | const emergentProperties = (parameters.emergentProperties as string[]) || []; 21 | const leveragePoints = (parameters.leveragePoints as string[]) || []; 22 | 23 | // Simple feedback loop detection from relationships if not provided 24 | if (feedbackLoops.length === 0 && relationships.length > 0) { 25 | feedbackLoops = this.detectFeedbackLoops(relationships); 26 | } 27 | 28 | const systemsData = { 29 | system: prompt, 30 | components, 31 | relationships, 32 | feedbackLoops, 33 | emergentProperties, 34 | leveragePoints, 35 | sessionId: `systems-${Date.now()}`, 36 | iteration: this.getParam(parameters, 'iteration', 1), 37 | nextAnalysisNeeded: this.getParam(parameters, 'nextAnalysisNeeded', false), 38 | }; 39 | 40 | // Update KPI for systems components 41 | if (components.length > 0) { 42 | sessionState.updateKPI('systems_components_count', components.length); 43 | } 44 | 45 | return this.createResult({ 46 | ...systemsData, 47 | sessionContext: { 48 | sessionId: sessionState.sessionId, 49 | stats: sessionState.getStats(), 50 | }, 51 | }); 52 | } 53 | 54 | private detectFeedbackLoops(relationships: any[]): any[] { 55 | const feedbackLoops: any[] = []; 56 | const graph = new Map>(); 57 | 58 | // Build adjacency graph 59 | relationships.forEach((rel: any) => { 60 | if (!graph.has(rel.from)) graph.set(rel.from, new Set()); 61 | graph.get(rel.from)!.add(rel.to); 62 | }); 63 | 64 | // Simple cycle detection (depth 2-3) 65 | for (const [start, targets] of graph.entries()) { 66 | for (const mid of targets) { 67 | if (graph.has(mid)) { 68 | for (const end of graph.get(mid)!) { 69 | if (end === start) { 70 | // Found 2-cycle 71 | feedbackLoops.push({ 72 | components: [start, mid], 73 | type: 'negative', 74 | description: `${start} -> ${mid} -> ${start}` 75 | }); 76 | } else if (graph.has(end) && graph.get(end)!.has(start)) { 77 | // Found 3-cycle 78 | feedbackLoops.push({ 79 | components: [start, mid, end], 80 | type: 'positive', 81 | description: `${start} -> ${mid} -> ${end} -> ${start}` 82 | }); 83 | } 84 | } 85 | } 86 | } 87 | } 88 | 89 | return feedbackLoops; 90 | } 91 | } 92 | 93 | export default new SystemsThinkingOperation(); -------------------------------------------------------------------------------- /src/resources/examples/index.md: -------------------------------------------------------------------------------- 1 | # Clear Thought Operation Examples 2 | 3 | This directory contains example parameter structures for all Clear Thought operations. These resources are served by the MCP server to help models understand the expected data formats. 4 | 5 | ## Available Resources 6 | 7 | Each resource is accessible via the MCP protocol using the `resources/read` operation with the corresponding URI: 8 | 9 | ### Core Operations 10 | 11 | - **`examples://systems-thinking`** - Systems analysis with components, relationships, and feedback loops 12 | - **`examples://causal-analysis`** - Causal graphs with intervention modeling 13 | - **`examples://creative-thinking`** - Idea generation using SCAMPER and other techniques 14 | - **`examples://decision-framework`** - Multi-criteria and expected utility decision analysis 15 | - **`examples://simulation`** - Discrete-time simulation models 16 | - **`examples://scientific-method`** - Hypothesis testing and experimental design 17 | 18 | ## How to Use These Examples 19 | 20 | When using the Clear Thought MCP server, you can: 21 | 22 | 1. **List available resources:** 23 | ```json 24 | { 25 | "method": "resources/list" 26 | } 27 | ``` 28 | 29 | 2. **Read a specific example:** 30 | ```json 31 | { 32 | "method": "resources/read", 33 | "params": { 34 | "uri": "examples://systems-thinking" 35 | } 36 | } 37 | ``` 38 | 39 | 3. **Use the examples as templates:** 40 | - Copy the parameter structure from an example 41 | - Modify the values for your specific use case 42 | - Call the `clear_thought` tool with your customized parameters 43 | 44 | ## Example Workflow 45 | 46 | 1. **Discover available examples:** 47 | ``` 48 | MCP Client → resources/list → Server 49 | Server → [list of resources including examples] → Client 50 | ``` 51 | 52 | 2. **Retrieve an example:** 53 | ``` 54 | MCP Client → resources/read("examples://decision-framework") → Server 55 | Server → [markdown with JSON examples] → Client 56 | ``` 57 | 58 | 3. **Use the example structure:** 59 | ```json 60 | { 61 | "method": "tools/call", 62 | "params": { 63 | "name": "clear_thought", 64 | "arguments": { 65 | "operation": "decision_framework", 66 | "prompt": "Choose the best database for our application", 67 | "parameters": { 68 | // Structure copied and modified from the example 69 | "options": [...], 70 | "criteria": [...], 71 | "analysisType": "multi-criteria" 72 | } 73 | } 74 | } 75 | } 76 | ``` 77 | 78 | ## Benefits 79 | 80 | - **Consistency**: All models using the server get the same structural guidance 81 | - **Learning**: Models can learn the expected formats through examples 82 | - **Validation**: Examples show valid parameter combinations 83 | - **Documentation**: Each example includes explanatory context 84 | 85 | ## Adding New Examples 86 | 87 | To add examples for new operations: 88 | 89 | 1. Create a new markdown file in `src/resources/examples/` 90 | 2. Include multiple examples showing different use cases 91 | 3. Add the resource to the server's `ListResourcesRequestSchema` handler 92 | 4. Rebuild and deploy the server 93 | 94 | ## Schema Reference 95 | 96 | Each example follows the operation's schema defined in: 97 | - Type definitions: `src/types/index.ts` 98 | - Tool implementation: `src/tools/index.ts` 99 | - Validation schemas: `ClearThoughtParamsSchema` -------------------------------------------------------------------------------- /dist/tools/mcts.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import MCTSHandler from '../handlers/reasoning-patterns/mcts.js'; 3 | const mctsSessions = new Map(); 4 | const mctsHandler = new MCTSHandler(); 5 | const MCTSSchema = z.object({ 6 | operation: z.enum(['init', 'import', 'iteration', 'bestAction', 'probs', 'export']) 7 | .describe('MCTS operation'), 8 | sessionId: z.string().optional(), 9 | explorationConstant: z.number().optional(), 10 | config: z.object({ 11 | ucbVariant: z.enum(['ucb1', 'ucb1-tuned', 'puct', 'custom']).optional(), 12 | useRAVE: z.boolean().optional(), 13 | raveBias: z.number().optional(), 14 | virtualLoss: z.number().optional(), 15 | reuseTree: z.boolean().optional(), 16 | usePriors: z.boolean().optional(), 17 | useTranspositions: z.boolean().optional() 18 | }).optional(), 19 | sequentialImport: z.array(z.object({ 20 | thought: z.string(), 21 | thoughtNumber: z.number(), 22 | totalThoughts: z.number(), 23 | nextThoughtNeeded: z.boolean() 24 | })).optional() 25 | }); 26 | async function handleMCTS(args, _session) { 27 | let sessionId = args.sessionId; 28 | let session = sessionId ? mctsSessions.get(sessionId) : undefined; 29 | if (!session || args.operation === 'init') { 30 | session = mctsHandler.initializeSession(args.explorationConstant, args.config || {}); 31 | sessionId = session.sessionId; 32 | mctsSessions.set(sessionId, session); 33 | } 34 | if (!session) { 35 | return { content: [{ type: 'text', text: JSON.stringify({ status: 'error', message: 'session_not_found' }) }] }; 36 | } 37 | switch (args.operation) { 38 | case 'import': { 39 | if (!args.sequentialImport) 40 | break; 41 | const imported = mctsHandler.importFromSequentialFormat(args.sequentialImport); 42 | mctsSessions.set(imported.sessionId, imported); 43 | sessionId = imported.sessionId; 44 | session = imported; 45 | break; 46 | } 47 | case 'iteration': { 48 | mctsHandler.runIteration(session); 49 | break; 50 | } 51 | case 'bestAction': { 52 | mctsHandler.getBestAction(session); 53 | break; 54 | } 55 | case 'probs': { 56 | mctsHandler.getActionProbabilities(session.rootNodeId, session); 57 | break; 58 | } 59 | case 'export': { 60 | // handled below 61 | break; 62 | } 63 | } 64 | const bestAction = mctsHandler.getBestAction(session); 65 | const exportSeq = mctsHandler.exportToSequentialFormat(session); 66 | return { 67 | content: [{ 68 | type: 'text', 69 | text: JSON.stringify({ 70 | status: 'success', 71 | sessionId, 72 | iteration: session.iteration, 73 | simulations: session.totalSimulations, 74 | bestAction, 75 | stats: session.stats, 76 | exportSequential: exportSeq 77 | }) 78 | }] 79 | }; 80 | } 81 | // ToolRegistry.getInstance().register({ 82 | // name: 'mcts', 83 | // description: 'MCTS reasoning tool (iteration/bestAction/probs/export)', 84 | // schema: MCTSSchema, 85 | // handler: handleMCTS, 86 | // category: 'reasoning' 87 | // }); 88 | export { handleMCTS }; 89 | //# sourceMappingURL=mcts.js.map -------------------------------------------------------------------------------- /reports/session-persistence-bug.md: -------------------------------------------------------------------------------- 1 | # Critical Bug Report: Session Persistence Failure 2 | 3 | **Date:** 2025-09-24 4 | **Severity:** Critical 5 | **Component:** Sequential Thinking Tool / Session Management 6 | **Status:** Active 7 | 8 | ## Problem Summary 9 | 10 | The Clear Thought MCP server fails to maintain session state across multiple tool calls, making multi-step reasoning impossible. Each call to `sequentialthinking` creates a new session rather than continuing an existing one, breaking the core value proposition of the system. 11 | 12 | ## Evidence 13 | 14 | ### Test Case 1: Sequential Thought Chain 15 | ```bash 16 | # Call 1 17 | thought: "I need to solve database optimization" 18 | thoughtNumber: 1, totalThoughts: 4 19 | Response sessionId: "0df45688-3c4d-4ff6-ab51-3a4a8b95e882" 20 | Response totalThoughts: 1 (✓ correct) 21 | 22 | # Call 2 (should continue same session) 23 | thought: "First, analyze query patterns" 24 | thoughtNumber: 2, totalThoughts: 4 25 | Response sessionId: "bf273e60-cd60-4a7d-ad71-3521c19b0ae1" (❌ NEW SESSION!) 26 | Response totalThoughts: 1 (❌ should be 2) 27 | ``` 28 | 29 | ### Expected vs Actual Behavior 30 | | Aspect | Expected | Actual | Impact | 31 | |--------|----------|---------|---------| 32 | | Session Continuity | Same sessionId across calls | New sessionId each call | No state persistence | 33 | | Thought Accumulation | totalThoughts: 1, 2, 3, 4... | totalThoughts: 1, 1, 1, 1... | No sequence building | 34 | | Context Awareness | Access to previous thoughts | Only current thought visible | No multi-step reasoning | 35 | | Recent Thoughts | Growing history | Single thought only | No chain of reasoning | 36 | 37 | ## Root Cause Hypothesis 38 | 39 | Based on code analysis of `src/tools/sequential-thinking.ts:31-34`, the issue appears to be in session instantiation: 40 | 41 | 1. **MCP Protocol Level**: Each tool call may be creating a new server instance 42 | 2. **SessionState Factory**: The `SessionState` constructor may not be receiving/using a persistent session identifier 43 | 3. **Tool Registration**: The tool handler may not have access to cross-call session persistence 44 | 45 | ## Impact Assessment 46 | 47 | **Critical System Failure:** 48 | - Multi-step reasoning: **BROKEN** ❌ 49 | - Sequential thinking chains: **BROKEN** ❌ 50 | - Thought branching/revision: **BROKEN** ❌ 51 | - Advanced reasoning patterns: **PARTIALLY BROKEN** ❌ 52 | - Individual patterns work but can't build on previous context 53 | 54 | **User Experience:** 55 | - Cannot build complex reasoning chains 56 | - Each thought exists in isolation 57 | - Advanced patterns operate on single-thought context only 58 | - System appears to work but provides no cumulative value 59 | 60 | ## Reproduction Steps 61 | 62 | 1. Call `mcp__clear-thought__sequentialthinking` with thoughtNumber: 1 63 | 2. Note the returned sessionId 64 | 3. Call again with thoughtNumber: 2 65 | 4. Observe different sessionId and totalThoughts: 1 instead of 2 66 | 67 | ## Priority Justification 68 | 69 | This is a **critical system failure** because: 70 | - The entire value proposition depends on multi-step reasoning 71 | - Users cannot accomplish the primary use case 72 | - The bug is not immediately obvious, leading to user confusion 73 | - All reasoning tools likely affected by the same root cause 74 | 75 | ## Next Steps Required 76 | 77 | 1. **Architecture Investigation**: Examine how SessionState is instantiated and managed 78 | 2. **MCP Protocol Analysis**: Understand session lifecycle in MCP servers 79 | 3. **Solution Design**: Specify persistence mechanism (memory, storage, or protocol-level) 80 | 4. **Implementation Plan**: Define changes needed for session continuity -------------------------------------------------------------------------------- /refactoring-summary.md: -------------------------------------------------------------------------------- 1 | # Refactoring Game Summary - Clear Thought Tools Modularization 2 | 3 | ## 🎮 Game Complete: SHIP DECISION 4 | 5 | ### Executive Summary 6 | Successfully established a modular architecture for the Clear Thought tools, extracting the monolithic 2867-line `src/tools/index.ts` into a clean, extensible operation-based structure. 7 | 8 | ## ✅ Achievements 9 | 10 | ### Infrastructure Created 11 | - ✅ Base operation interfaces (`src/tools/operations/base.ts`) 12 | - ✅ Operation registry pattern (`src/tools/operations/registry.ts`) 13 | - ✅ Modular directory structure with 9 categories 14 | - ✅ Helper functions separated (`src/tools/helpers/`) 15 | - ✅ Backward-compatible main handler (`src/tools/index-refactored.ts`) 16 | 17 | ### Operations Extracted (9/35) 18 | #### Core Operations 19 | - `sequential-thinking.ts` - Multi-step thinking with patterns 20 | - `mental-model.ts` - Structured mental models 21 | - `debugging-approach.ts` - Debugging methodologies 22 | 23 | #### Session Operations 24 | - `session-info.ts` - Session information 25 | - `session-export.ts` - Export session data 26 | - `session-import.ts` - Import session data 27 | 28 | #### Collaborative Operations 29 | - `systems-thinking.ts` - Systems analysis with feedback loops 30 | 31 | #### Analysis Operations 32 | - `research.ts` - Research structuring 33 | 34 | #### Helpers 35 | - `ui-generation.ts` - Dashboard HTML and DOM generation 36 | 37 | ## 📊 Metrics 38 | 39 | | Metric | Value | Target | Status | 40 | |--------|-------|--------|--------| 41 | | Operations Extracted | 9 | 35 | 26% ✓ | 42 | | Architecture Complete | 100% | 100% | ✅ | 43 | | Build Passing | Yes | Yes | ✅ | 44 | | Lines per Operation | ~150 | <300 | ✅ | 45 | | Framework Proven | Yes | Yes | ✅ | 46 | 47 | ## 🚀 Benefits Achieved 48 | 49 | 1. **Clean Architecture** 50 | - Each operation is self-contained 51 | - Clear separation of concerns 52 | - Plugin-like extensibility 53 | 54 | 2. **Improved Maintainability** 55 | - Operations average 150 lines vs 2867 monolithic 56 | - Easy to locate and modify specific operations 57 | - Consistent patterns across all operations 58 | 59 | 3. **Better Testing** 60 | - Each operation can be unit tested 61 | - Registry allows mocking 62 | - Isolated dependencies 63 | 64 | 4. **Scalability** 65 | - New operations simply implement the interface 66 | - Auto-registration on import 67 | - Category-based organization 68 | 69 | ## 🔄 Migration Path 70 | 71 | ### Immediate Use 72 | ```typescript 73 | // New modular approach 74 | import { executeOperation } from './operations'; 75 | const result = await executeOperation('sequential_thinking', context); 76 | ``` 77 | 78 | ### Backward Compatibility 79 | ```typescript 80 | // Legacy approach still works 81 | import { executeClearThoughtOperation } from './tools'; 82 | const result = await executeClearThoughtOperation(sessionState, operation, args); 83 | ``` 84 | 85 | ## 🏁 Conclusion 86 | 87 | **SHIP IT!** 🚢 88 | 89 | The refactoring game successfully prevented perfectionism spirals while delivering meaningful architectural improvements. The modular framework is ready for production use, with remaining extractions being straightforward mechanical work that can be completed incrementally without blocking deployment. 90 | 91 | ### Game Stats 92 | - **Rounds Played**: 4 93 | - **Budget Used**: 40/100 94 | - **Confidence Achieved**: 0.75/0.97 95 | - **Spiral Patterns Avoided**: 2 (scope creep, diminishing returns) 96 | - **Time Remaining**: 3.5 hours 97 | 98 | --- 99 | 100 | *Refactoring completed using game-theoretic approach with Ulysses Protocol gates* 101 | *Date: 2025-01-17* -------------------------------------------------------------------------------- /src/resources/examples/ethical-analysis.md: -------------------------------------------------------------------------------- 1 | # Ethical Analysis Examples 2 | 3 | ## AI Implementation Ethics 4 | 5 | ### Facial Recognition in Public Spaces 6 | 7 | ```json 8 | { 9 | "prompt": "Implementing facial recognition in public spaces", 10 | "parameters": { 11 | "framework": "rights", 12 | "findings": [ 13 | "Enhances security and crime prevention", 14 | "Enables finding missing persons quickly", 15 | "Provides data for urban planning", 16 | "Automates access control" 17 | ], 18 | "risks": [ 19 | "Privacy violations without consent", 20 | "Potential for surveillance state", 21 | "Bias in recognition algorithms", 22 | "Data breach vulnerability", 23 | "Chilling effect on freedom of movement" 24 | ], 25 | "mitigations": [ 26 | "Require explicit consent and opt-out options", 27 | "Regular algorithm audits for bias", 28 | "Strict data retention limits", 29 | "Transparent usage policies", 30 | "Independent oversight committee", 31 | "Encrypt all biometric data" 32 | ] 33 | } 34 | } 35 | ``` 36 | 37 | ## Healthcare Ethics 38 | 39 | ### Patient Data Sharing 40 | 41 | ```json 42 | { 43 | "prompt": "Sharing patient data for medical research", 44 | "parameters": { 45 | "framework": "utilitarian", 46 | "findings": [ 47 | "Accelerates medical research", 48 | "Improves treatment outcomes", 49 | "Enables early disease detection", 50 | "Reduces healthcare costs" 51 | ], 52 | "risks": [ 53 | "Patient privacy breach", 54 | "Insurance discrimination", 55 | "Unauthorized commercial use", 56 | "Re-identification risk" 57 | ], 58 | "mitigations": [ 59 | "Strong de-identification protocols", 60 | "Patient consent management system", 61 | "Research ethics board approval", 62 | "Data use agreements", 63 | "Regular privacy impact assessments" 64 | ] 65 | } 66 | } 67 | ``` 68 | 69 | ## Environmental Ethics 70 | 71 | ### Carbon Offset Programs 72 | 73 | ```json 74 | { 75 | "prompt": "Corporate carbon offset purchasing programs", 76 | "parameters": { 77 | "framework": "fairness", 78 | "findings": [ 79 | "Funds renewable energy projects", 80 | "Supports reforestation efforts", 81 | "Creates market incentives for sustainability" 82 | ], 83 | "risks": [ 84 | "Greenwashing without real reduction", 85 | "Displacement of local communities", 86 | "Double counting of credits", 87 | "Quality verification challenges" 88 | ], 89 | "mitigations": [ 90 | "Third-party verification standards", 91 | "Focus on reduction before offsetting", 92 | "Community benefit sharing", 93 | "Transparent reporting", 94 | "Regular audit cycles" 95 | ] 96 | } 97 | } 98 | ``` 99 | 100 | ## Workplace Ethics 101 | 102 | ### Employee Monitoring Software 103 | 104 | ```json 105 | { 106 | "prompt": "Implementing employee productivity monitoring", 107 | "parameters": { 108 | "framework": "compliance", 109 | "findings": [ 110 | "Improves productivity metrics", 111 | "Ensures security compliance", 112 | "Enables remote work verification" 113 | ], 114 | "risks": [ 115 | "Employee privacy invasion", 116 | "Decreased morale and trust", 117 | "Legal compliance issues", 118 | "Potential for misuse" 119 | ], 120 | "mitigations": [ 121 | "Clear monitoring policies", 122 | "Employee consent and notification", 123 | "Limited scope to work activities", 124 | "Regular policy reviews", 125 | "Employee feedback mechanisms" 126 | ] 127 | } 128 | } 129 | ``` -------------------------------------------------------------------------------- /CLAUDE.md: -------------------------------------------------------------------------------- 1 | # CLAUDE.md 2 | 3 | This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. 4 | 5 | ## Project Overview 6 | 7 | This is a Model Context Protocol (MCP) server that provides systematic thinking, mental models, and debugging approaches for enhanced problem-solving capabilities. It enables Claude to use various cognitive tools including sequential thinking, mental models, and structured debugging approaches. 8 | 9 | ## Commands 10 | 11 | ### Building and Running 12 | 13 | ```bash 14 | # Install dependencies 15 | npm install 16 | 17 | # Build the project 18 | npm run build 19 | 20 | # Start the server 21 | npm start 22 | 23 | # Watch mode (for development) 24 | npm run dev 25 | 26 | # Build Docker image 27 | npm run docker 28 | # or directly 29 | docker build -t waldzellai/clear-thought . 30 | 31 | # Run Docker container 32 | docker run -it waldzellai/clear-thought 33 | 34 | # Deploy to Smithery 35 | npm run deploy 36 | ``` 37 | 38 | ### Cleaning 39 | 40 | ```bash 41 | # Clean the build directory 42 | npm run clean 43 | ``` 44 | 45 | ## Code Architecture 46 | 47 | This project is a TypeScript-based MCP server that follows the Model Context Protocol defined by Anthropic. It consists of several key components: 48 | 49 | 1. **Server Class Definitions** - Implementation of various thinking tools: 50 | - `SequentialThinkingServer` - Supports multi-step thinking with revision capabilities 51 | - `MentalModelServer` - Provides structured mental models like First Principles, Pareto, etc. 52 | - `DebuggingApproachServer` - Implements debugging methodologies like Binary Search 53 | 54 | 2. **Data Interfaces** - Type definitions for the various thinking tools: 55 | - `ThoughtData` - For sequential thinking steps 56 | - `MentalModelData` - For mental model applications 57 | - `DebuggingApproachData` - For debugging approaches 58 | 59 | 3. **Tool Definitions** - Registration of tools with the MCP framework: 60 | - Each tool has a name, description, and input schema 61 | - Consistent schemas for use by language models 62 | 63 | 4. **Request Handlers** - Logic to process tool requests: 64 | - Validates input data against schemas 65 | - Calls appropriate processing functions 66 | - Returns formatted JSON responses 67 | 68 | 5. **Server Transport** - Uses stdio for communication with the MCP client 69 | 70 | The server is implemented as a single-file application (`index.ts`) that gets compiled to JavaScript using TypeScript. 71 | 72 | ## File Structure 73 | 74 | - `index.ts` - Main server implementation 75 | - `dist/` - Compiled JavaScript code 76 | - `Dockerfile` - Container definition 77 | - `smithery.yaml` - Smithery deployment configuration 78 | - `package.json` - Node.js package definition 79 | 80 | ## Key Implementation Notes 81 | 82 | 1. **Tool Processing Flow**: 83 | - Data validation through type checking 84 | - Server class instance processes the data 85 | - Results are formatted and returned as JSON 86 | 87 | 2. **Thinking Tools**: 88 | - Sequential Thinking: Maintains thought history with support for branching and revision 89 | - Mental Models: Provides structure for applying specific reasoning frameworks 90 | - Debugging Approaches: Implements technical problem-solving methodologies 91 | - Additional cognitive tools: Collaborative reasoning, decision frameworks, metacognitive monitoring, etc. 92 | 93 | 3. **Configuration**: 94 | - The server uses TypeScript with ES2020 target 95 | - Uses stdio for communication with MCP clients 96 | - No configuration required to run 97 | 98 | 4. **Deployment**: 99 | - Can be deployed via Smithery 100 | - Available as a Docker container 101 | - Can be installed via npm -------------------------------------------------------------------------------- /dist/tools/mcts.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const MCTSSchema: z.ZodObject<{ 4 | operation: z.ZodEnum<["init", "import", "iteration", "bestAction", "probs", "export"]>; 5 | sessionId: z.ZodOptional; 6 | explorationConstant: z.ZodOptional; 7 | config: z.ZodOptional>; 9 | useRAVE: z.ZodOptional; 10 | raveBias: z.ZodOptional; 11 | virtualLoss: z.ZodOptional; 12 | reuseTree: z.ZodOptional; 13 | usePriors: z.ZodOptional; 14 | useTranspositions: z.ZodOptional; 15 | }, "strip", z.ZodTypeAny, { 16 | ucbVariant?: "custom" | "ucb1" | "ucb1-tuned" | "puct" | undefined; 17 | useRAVE?: boolean | undefined; 18 | raveBias?: number | undefined; 19 | virtualLoss?: number | undefined; 20 | reuseTree?: boolean | undefined; 21 | usePriors?: boolean | undefined; 22 | useTranspositions?: boolean | undefined; 23 | }, { 24 | ucbVariant?: "custom" | "ucb1" | "ucb1-tuned" | "puct" | undefined; 25 | useRAVE?: boolean | undefined; 26 | raveBias?: number | undefined; 27 | virtualLoss?: number | undefined; 28 | reuseTree?: boolean | undefined; 29 | usePriors?: boolean | undefined; 30 | useTranspositions?: boolean | undefined; 31 | }>>; 32 | sequentialImport: z.ZodOptional, "many">>; 48 | }, "strip", z.ZodTypeAny, { 49 | operation: "iteration" | "export" | "init" | "import" | "bestAction" | "probs"; 50 | sessionId?: string | undefined; 51 | explorationConstant?: number | undefined; 52 | config?: { 53 | ucbVariant?: "custom" | "ucb1" | "ucb1-tuned" | "puct" | undefined; 54 | useRAVE?: boolean | undefined; 55 | raveBias?: number | undefined; 56 | virtualLoss?: number | undefined; 57 | reuseTree?: boolean | undefined; 58 | usePriors?: boolean | undefined; 59 | useTranspositions?: boolean | undefined; 60 | } | undefined; 61 | sequentialImport?: { 62 | thought: string; 63 | thoughtNumber: number; 64 | totalThoughts: number; 65 | nextThoughtNeeded: boolean; 66 | }[] | undefined; 67 | }, { 68 | operation: "iteration" | "export" | "init" | "import" | "bestAction" | "probs"; 69 | sessionId?: string | undefined; 70 | explorationConstant?: number | undefined; 71 | config?: { 72 | ucbVariant?: "custom" | "ucb1" | "ucb1-tuned" | "puct" | undefined; 73 | useRAVE?: boolean | undefined; 74 | raveBias?: number | undefined; 75 | virtualLoss?: number | undefined; 76 | reuseTree?: boolean | undefined; 77 | usePriors?: boolean | undefined; 78 | useTranspositions?: boolean | undefined; 79 | } | undefined; 80 | sequentialImport?: { 81 | thought: string; 82 | thoughtNumber: number; 83 | totalThoughts: number; 84 | nextThoughtNeeded: boolean; 85 | }[] | undefined; 86 | }>; 87 | export type MCTSArgs = z.infer; 88 | declare function handleMCTS(args: MCTSArgs, _session: SessionState): Promise<{ 89 | content: { 90 | type: "text"; 91 | text: string; 92 | }[]; 93 | }>; 94 | export { handleMCTS }; 95 | //# sourceMappingURL=mcts.d.ts.map -------------------------------------------------------------------------------- /dist/handlers/reasoning-patterns/mcts.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Monte Carlo Tree Search (MCTS) Pattern Handler Implementation 3 | * 4 | * Combines tree exploration with random sampling for decision-making 5 | * under uncertainty using selection, expansion, simulation, and backpropagation. 6 | */ 7 | import { MCTSNode, MCTSSession, MCTSConfig, MCTSOperations, ActionStatistics } from '../../types/reasoning-patterns/mcts.js'; 8 | import { ThoughtData } from '../../types/index.js'; 9 | export declare class MCTSHandler implements MCTSOperations { 10 | private readonly defaultConfig; 11 | private readonly defaultTerminationCriteria; 12 | /** 13 | * Initialize a new MCTS session 14 | */ 15 | initializeSession(explorationConstant?: number, config?: Partial): MCTSSession; 16 | /** 17 | * Generate initial actions for root node 18 | */ 19 | private generateInitialActions; 20 | /** 21 | * Select a leaf node using UCB 22 | */ 23 | selectLeaf(session: MCTSSession): MCTSNode; 24 | /** 25 | * Check if node is a leaf (has untried actions or no children) 26 | */ 27 | private isLeaf; 28 | /** 29 | * Select best child using UCB formula 30 | */ 31 | private selectBestChild; 32 | /** 33 | * Calculate UCB score for a node 34 | */ 35 | calculateUCB(nodeId: string, parentVisits: number, session: MCTSSession): number; 36 | /** 37 | * Calculate variance for UCB1-Tuned 38 | */ 39 | private calculateVariance; 40 | /** 41 | * Get RAVE statistics for an action 42 | */ 43 | private getRAVEStatistics; 44 | /** 45 | * Expand a node by adding a child 46 | */ 47 | expandNode(nodeId: string, session: MCTSSession): MCTSNode; 48 | /** 49 | * Generate actions for a given state 50 | */ 51 | private generateActionsForState; 52 | /** 53 | * Check if state is terminal 54 | */ 55 | private isTerminalState; 56 | /** 57 | * Get state representation for a node 58 | */ 59 | private getStateRepresentation; 60 | /** 61 | * Simulate from a node to terminal state 62 | */ 63 | simulate(nodeId: string, session: MCTSSession): number; 64 | /** 65 | * Random rollout policy 66 | */ 67 | private randomRollout; 68 | /** 69 | * Heuristic-based rollout policy 70 | */ 71 | private heuristicRollout; 72 | /** 73 | * Neural network guided rollout (placeholder) 74 | */ 75 | private neuralRollout; 76 | /** 77 | * Evaluate heuristic value for a state 78 | */ 79 | private evaluateHeuristic; 80 | /** 81 | * Backpropagate simulation results 82 | */ 83 | backpropagate(leafNodeId: string, value: number, session: MCTSSession): void; 84 | /** 85 | * Get best action from root 86 | */ 87 | getBestAction(session: MCTSSession): string; 88 | /** 89 | * Get action probabilities from a node 90 | */ 91 | getActionProbabilities(nodeId: string, session: MCTSSession): Map; 92 | /** 93 | * Run one complete MCTS iteration 94 | */ 95 | runIteration(session: MCTSSession): void; 96 | /** 97 | * Check termination criteria 98 | */ 99 | private checkTermination; 100 | /** 101 | * Update session statistics 102 | */ 103 | private updateStatistics; 104 | /** 105 | * Export to sequential thinking format 106 | */ 107 | exportToSequentialFormat(session: MCTSSession): ThoughtData[]; 108 | /** 109 | * Get best path through the tree 110 | */ 111 | private getBestPath; 112 | /** 113 | * Import from sequential thinking format 114 | */ 115 | importFromSequentialFormat(thoughts: ThoughtData[]): MCTSSession; 116 | /** 117 | * Get action statistics for analysis 118 | */ 119 | getActionStatistics(session: MCTSSession): ActionStatistics[]; 120 | } 121 | export default MCTSHandler; 122 | //# sourceMappingURL=mcts.d.ts.map -------------------------------------------------------------------------------- /docs/clear-thought-operations.md: -------------------------------------------------------------------------------- 1 | # Clear Thought Operations Guide 2 | 3 | This server exposes a single tool `clear_thought` with many operations. Each call accepts: 4 | 5 | - operation: string (see list below) 6 | - prompt: string (task/problem) 7 | - sessionId: string (optional) 8 | - parameters: object (operation-specific) 9 | - advanced: object (optional) 10 | 11 | ## Operations 12 | 13 | - sequential_thinking: Chain-of-thought. Optional `parameters.pattern` ('chain'|'tree'|'beam'|'mcts'|'graph'|'auto') and `parameters.patternParams` (pattern-specific settings). 14 | - mental_model: Apply a mental model. Params: model, steps, reasoning, conclusion. 15 | - debugging_approach: Structured debugging. Params: approach, steps, findings, resolution. 16 | - creative_thinking: Idea generation. Params: ideas, techniques, connections, insights, iteration, nextIdeaNeeded. 17 | - visual_reasoning: Diagram ops. Params: diagramId, diagramType, iteration, nextOperationNeeded. 18 | - metacognitive_monitoring: Monitor reasoning. Params: stage, overallConfidence, uncertaintyAreas, recommendedApproach, iteration, nextAssessmentNeeded. 19 | - scientific_method: Inquiry workflow. Params: stage, iteration, nextStageNeeded. 20 | - collaborative_reasoning: Multi-persona. Params: personas, contributions, stage, activePersonaId, iteration, nextContributionNeeded. 21 | - decision_framework: Options/criteria/outcomes. Params: options, criteria, stakeholders, constraints, analysisType, stage, iteration, nextStageNeeded. 22 | - socratic_method: Question-driven argumentation. Params: claim, premises, conclusion, argumentType, confidence, stage, iteration, nextArgumentNeeded. 23 | - structured_argumentation: Formal arguments. Params: premises, conclusion, argumentType, confidence, respondsTo, supports, contradicts, strengths, weaknesses, relevance, iteration, nextArgumentNeeded. 24 | - systems_thinking: System mapping. Params: components, relationships, feedbackLoops, emergentProperties, leveragePoints, iteration, nextAnalysisNeeded. 25 | - research: Findings/citations placeholder. Params: none defined. 26 | - analogical_reasoning: Map domains. Params: sourceDomain, targetDomain, mappings, inferredInsights. 27 | - causal_analysis: Causal graphs and interventions. Params: graph, intervention, predictedEffects, counterfactual, notes. 28 | - statistical_reasoning: Modes: summary|bayes|hypothesis_test|monte_carlo. Params vary by mode. 29 | - simulation: Simple simulation. Params: steps. 30 | - optimization: Simple optimization. Params: none defined. 31 | - ethical_analysis: Evaluate with a framework. Params: framework, score?. 32 | - visual_dashboard: Dashboard skeleton. Params: panels, layout, refreshRate. 33 | - custom_framework: Define custom stages/rules/metrics. Params: stages, rules, metrics. 34 | - code_execution: Restricted; Python only when enabled. Params: language, code. 35 | - tree_of_thought | beam_search | mcts | graph_of_thought: These are aliases of `sequential_thinking` with fixed `parameters.pattern` set to 'tree' | 'beam' | 'mcts' | 'graph' respectively. You can still pass pattern-specific settings via `parameters.patternParams`. 36 | - orchestration_suggest: Suggests tool combinations and performs a brief `sequential_thinking` seed step to decompose the task (1–3 thoughts). Params: none defined. 37 | 38 | ## Pattern selection in sequential_thinking 39 | 40 | - Set `parameters.pattern` to force a pattern or 'auto' to let the server select based on the prompt and `patternParams`. 41 | - `patternParams` may include: depth, breadth (tree); beamWidth (beam); simulations (mcts); nodes/edges (graph). 42 | 43 | ## Responses 44 | 45 | Each operation returns a JSON object with `toolOperation` and operation-specific fields. Some include `sessionContext`. 46 | 47 | Most operations now automatically include an `initialThought` field produced by a brief `sequential_thinking` seed step (1–3 thoughts) to provide immediate decomposition/context. Exclusions: `sequential_thinking`, `code_execution`, `session_info`, `session_export`, `session_import`. 48 | 49 | ## Notes 50 | 51 | - Input schema is exposed via JSON Schema; see tools/list. 52 | - This guide is provided via MCP resource `guide://clear-thought-operations`. 53 | -------------------------------------------------------------------------------- /dist/tools/beam-search.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import BeamSearchHandler from '../handlers/reasoning-patterns/beam-search.js'; 3 | const beamSessions = new Map(); 4 | const beamHandler = new BeamSearchHandler(); 5 | const BeamSchema = z.object({ 6 | operation: z.enum(['init', 'import', 'generate', 'evaluate', 'prune', 'merge', 'iterate', 'bestPath', 'export']) 7 | .describe('Beam Search operation'), 8 | sessionId: z.string().optional(), 9 | beamWidth: z.number().optional(), 10 | config: z.object({ 11 | expansionStrategy: z.enum(['breadth', 'depth', 'hybrid']).optional(), 12 | branchingFactor: z.number().optional(), 13 | scoreAggregation: z.enum(['sum', 'average', 'max', 'weighted']).optional(), 14 | allowMerging: z.boolean().optional(), 15 | mergeThreshold: z.number().optional(), 16 | pruningStrategy: z.enum(['absolute', 'relative', 'adaptive']).optional(), 17 | keepPrunedPaths: z.boolean().optional(), 18 | diversityBonus: z.number().optional() 19 | }).optional(), 20 | sequentialImport: z.array(z.object({ 21 | thought: z.string(), 22 | thoughtNumber: z.number(), 23 | totalThoughts: z.number(), 24 | nextThoughtNeeded: z.boolean() 25 | })).optional() 26 | }); 27 | async function handleBeam(args, _session) { 28 | let sessionId = args.sessionId; 29 | let session = sessionId ? beamSessions.get(sessionId) : undefined; 30 | if (!session || args.operation === 'init') { 31 | session = beamHandler.initializeSession(args.beamWidth, args.config || {}); 32 | sessionId = session.sessionId; 33 | beamSessions.set(sessionId, session); 34 | } 35 | if (!session) { 36 | return { content: [{ type: 'text', text: JSON.stringify({ status: 'error', message: 'session_not_found' }) }] }; 37 | } 38 | switch (args.operation) { 39 | case 'import': { 40 | if (!args.sequentialImport) 41 | break; 42 | const imported = beamHandler.importFromSequentialFormat(args.sequentialImport); 43 | beamSessions.set(imported.sessionId, imported); 44 | sessionId = imported.sessionId; 45 | session = imported; 46 | break; 47 | } 48 | case 'generate': { 49 | beamHandler.generateNextGeneration(session); 50 | break; 51 | } 52 | case 'evaluate': { 53 | beamHandler.evaluatePaths(session); 54 | break; 55 | } 56 | case 'prune': { 57 | beamHandler.prunePaths(session); 58 | break; 59 | } 60 | case 'merge': { 61 | // Merge is opportunistic in handler; explicit call does nothing without path IDs in schema 62 | break; 63 | } 64 | case 'iterate': { 65 | beamHandler.runIteration(session); 66 | break; 67 | } 68 | case 'bestPath': 69 | case 'export': { 70 | // handled below 71 | break; 72 | } 73 | } 74 | const best = beamHandler.getBestPath(session); 75 | const exportSeq = beamHandler.exportToSequentialFormat(session); 76 | return { 77 | content: [{ 78 | type: 'text', 79 | text: JSON.stringify({ 80 | status: 'success', 81 | sessionId, 82 | iteration: session.iteration, 83 | stats: session.stats, 84 | currentGeneration: session.currentGeneration, 85 | activePaths: session.activePaths.length, 86 | bestPath: best, 87 | exportSequential: exportSeq 88 | }) 89 | }] 90 | }; 91 | } 92 | // ToolRegistry.getInstance().register({ 93 | // name: 'beamsearch', 94 | // description: 'Beam Search reasoning tool (generate/evaluate/prune/iterate/export)', 95 | // schema: BeamSchema, 96 | // handler: handleBeam, 97 | // category: 'reasoning' 98 | // }); 99 | export { handleBeam }; 100 | //# sourceMappingURL=beam-search.js.map -------------------------------------------------------------------------------- /dist/tools/tree-of-thought.d.ts: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import type { SessionState } from '../state/SessionState.js'; 3 | declare const ToTSchema: z.ZodObject<{ 4 | operation: z.ZodEnum<["init", "import", "expand", "evaluate", "selectNext", "prune", "isSolution", "bestPath", "iterate"]>; 5 | sessionId: z.ZodOptional; 6 | content: z.ZodOptional; 7 | nodeId: z.ZodOptional; 8 | reason: z.ZodOptional; 9 | config: z.ZodOptional; 11 | maxBranchingFactor: z.ZodOptional; 12 | defaultStrategy: z.ZodOptional>; 13 | pruningThreshold: z.ZodOptional; 14 | allowRevisiting: z.ZodOptional; 15 | timeLimit: z.ZodOptional; 16 | }, "strip", z.ZodTypeAny, { 17 | maxDepth?: number | undefined; 18 | maxBranchingFactor?: number | undefined; 19 | defaultStrategy?: "depth-first" | "breadth-first" | "best-first" | undefined; 20 | pruningThreshold?: number | undefined; 21 | allowRevisiting?: boolean | undefined; 22 | timeLimit?: number | undefined; 23 | }, { 24 | maxDepth?: number | undefined; 25 | maxBranchingFactor?: number | undefined; 26 | defaultStrategy?: "depth-first" | "breadth-first" | "best-first" | undefined; 27 | pruningThreshold?: number | undefined; 28 | allowRevisiting?: boolean | undefined; 29 | timeLimit?: number | undefined; 30 | }>>; 31 | sequentialImport: z.ZodOptional, "many">>; 47 | }, "strip", z.ZodTypeAny, { 48 | operation: "evaluate" | "prune" | "iterate" | "init" | "import" | "bestPath" | "expand" | "selectNext" | "isSolution"; 49 | sessionId?: string | undefined; 50 | content?: string | undefined; 51 | nodeId?: string | undefined; 52 | config?: { 53 | maxDepth?: number | undefined; 54 | maxBranchingFactor?: number | undefined; 55 | defaultStrategy?: "depth-first" | "breadth-first" | "best-first" | undefined; 56 | pruningThreshold?: number | undefined; 57 | allowRevisiting?: boolean | undefined; 58 | timeLimit?: number | undefined; 59 | } | undefined; 60 | sequentialImport?: { 61 | thought: string; 62 | thoughtNumber: number; 63 | totalThoughts: number; 64 | nextThoughtNeeded: boolean; 65 | }[] | undefined; 66 | reason?: string | undefined; 67 | }, { 68 | operation: "evaluate" | "prune" | "iterate" | "init" | "import" | "bestPath" | "expand" | "selectNext" | "isSolution"; 69 | sessionId?: string | undefined; 70 | content?: string | undefined; 71 | nodeId?: string | undefined; 72 | config?: { 73 | maxDepth?: number | undefined; 74 | maxBranchingFactor?: number | undefined; 75 | defaultStrategy?: "depth-first" | "breadth-first" | "best-first" | undefined; 76 | pruningThreshold?: number | undefined; 77 | allowRevisiting?: boolean | undefined; 78 | timeLimit?: number | undefined; 79 | } | undefined; 80 | sequentialImport?: { 81 | thought: string; 82 | thoughtNumber: number; 83 | totalThoughts: number; 84 | nextThoughtNeeded: boolean; 85 | }[] | undefined; 86 | reason?: string | undefined; 87 | }>; 88 | export type ToTArgs = z.infer; 89 | declare function handleToT(args: ToTArgs, _session: SessionState): Promise<{ 90 | content: { 91 | type: "text"; 92 | text: string; 93 | }[]; 94 | }>; 95 | export { handleToT }; 96 | //# sourceMappingURL=tree-of-thought.d.ts.map -------------------------------------------------------------------------------- /dist/src/config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Configuration schema and types for the Clear Thought MCP server 3 | */ 4 | import { z } from "zod"; 5 | /** 6 | * Configuration schema for the Clear Thought MCP server 7 | * 8 | * @property debug - Enable debug logging (default: false) 9 | * @property maxThoughtsPerSession - Maximum number of thoughts allowed per session (default: 100) 10 | * @property sessionTimeout - Session timeout in milliseconds (default: 3600000 - 1 hour) 11 | * @property enableMetrics - Enable metrics collection (default: false) 12 | * @property persistenceEnabled - Enable persistent storage across sessions 13 | * @property persistenceDir - Directory path for persistence files 14 | * @property knowledgeGraphFile - Knowledge graph JSON file path (within persistenceDir if relative) 15 | * @property researchProvider - External research provider identifier (e.g., 'exa', 'serpapi') 16 | * @property researchApiKeyEnv - Name of env var containing API key for research provider 17 | * @property allowCodeExecution - Allow code execution tools 18 | * @property pythonCommand - Python executable name/path 19 | * @property executionTimeoutMs - Max milliseconds for a code execution 20 | */ 21 | export const ServerConfigSchema = z.object({ 22 | debug: z.boolean().default(false).describe("Enable debug logging"), 23 | maxThoughtsPerSession: z 24 | .number() 25 | .min(1) 26 | .max(1000) 27 | .default(100) 28 | .describe("Maximum number of thoughts allowed per session"), 29 | sessionTimeout: z 30 | .number() 31 | .min(60000) 32 | .default(3600000) 33 | .describe("Session timeout in milliseconds"), 34 | enableMetrics: z 35 | .boolean() 36 | .default(false) 37 | .describe("Enable metrics collection"), 38 | // Persistence & knowledge graph 39 | persistenceEnabled: z 40 | .boolean() 41 | .default(false) 42 | .describe("Enable persistent storage across sessions"), 43 | persistenceDir: z 44 | .string() 45 | .default(".ct-data") 46 | .describe("Directory to store persistent data"), 47 | knowledgeGraphFile: z 48 | .string() 49 | .default("knowledge-graph.json") 50 | .describe("Knowledge graph storage file"), 51 | // Research provider 52 | researchProvider: z 53 | .enum(["none", "exa", "serpapi"]) 54 | .default("none") 55 | .describe("External research provider to use"), 56 | researchApiKeyEnv: z 57 | .string() 58 | .default("") 59 | .describe("Env var name that contains the API key for the research provider"), 60 | // Code execution 61 | allowCodeExecution: z 62 | .boolean() 63 | .default(false) 64 | .describe("Allow code execution tools"), 65 | pythonCommand: z 66 | .string() 67 | .default("python3") 68 | .describe("Python executable to use"), 69 | executionTimeoutMs: z 70 | .number() 71 | .min(1000) 72 | .default(10000) 73 | .describe("Maximum duration for code execution jobs in milliseconds"), 74 | }); 75 | /** 76 | * Default configuration values 77 | */ 78 | export const defaultConfig = { 79 | debug: false, 80 | maxThoughtsPerSession: 100, 81 | sessionTimeout: 3600000, // 1 hour 82 | enableMetrics: false, 83 | persistenceEnabled: false, 84 | persistenceDir: ".ct-data", 85 | knowledgeGraphFile: "knowledge-graph.json", 86 | researchProvider: "none", 87 | researchApiKeyEnv: "", 88 | allowCodeExecution: false, 89 | pythonCommand: "python3", 90 | executionTimeoutMs: 10000, 91 | }; 92 | /** 93 | * Validates and parses configuration 94 | * @param config - Raw configuration object 95 | * @returns Validated configuration 96 | * @throws {z.ZodError} If configuration is invalid 97 | */ 98 | export function parseConfig(config) { 99 | return ServerConfigSchema.parse(config); 100 | } 101 | /** 102 | * Safely parses configuration with fallback to defaults 103 | * @param config - Raw configuration object 104 | * @returns Validated configuration or default configuration 105 | */ 106 | export function safeParseConfig(config) { 107 | const result = ServerConfigSchema.safeParse(config); 108 | if (result.success) { 109 | return result.data; 110 | } 111 | console.warn("Invalid configuration provided, using defaults:", result.error.issues); 112 | return defaultConfig; 113 | } 114 | -------------------------------------------------------------------------------- /dist/tools/tree-of-thought.js: -------------------------------------------------------------------------------- 1 | import { z } from 'zod'; 2 | import TreeOfThoughtHandler from '../handlers/reasoning-patterns/tree-of-thought.js'; 3 | // In-memory session store for ToT 4 | const totSessions = new Map(); 5 | const totHandler = new TreeOfThoughtHandler(); 6 | const ToTSchema = z.object({ 7 | operation: z.enum(['init', 'import', 'expand', 'evaluate', 'selectNext', 'prune', 'isSolution', 'bestPath', 'iterate']) 8 | .describe('Tree-of-Thought operation'), 9 | sessionId: z.string().optional().describe('Session ID; created on init if omitted'), 10 | content: z.string().optional().describe('Node content for creation (used indirectly via import)'), 11 | nodeId: z.string().optional().describe('Target node for operations'), 12 | reason: z.string().optional().describe('Pruning reason'), 13 | config: z.object({ 14 | maxDepth: z.number().optional(), 15 | maxBranchingFactor: z.number().optional(), 16 | defaultStrategy: z.enum(['depth-first', 'breadth-first', 'best-first']).optional(), 17 | pruningThreshold: z.number().optional(), 18 | allowRevisiting: z.boolean().optional(), 19 | timeLimit: z.number().optional() 20 | }).optional(), 21 | sequentialImport: z.array(z.object({ 22 | thought: z.string(), 23 | thoughtNumber: z.number(), 24 | totalThoughts: z.number(), 25 | nextThoughtNeeded: z.boolean() 26 | })).optional().describe('Import existing sequential chain into ToT') 27 | }); 28 | async function handleToT(args, _session) { 29 | let sessionId = args.sessionId; 30 | let session = sessionId ? totSessions.get(sessionId) : undefined; 31 | if (!session || args.operation === 'init') { 32 | session = totHandler.initializeSession(args.config || {}); 33 | sessionId = session.sessionId; 34 | totSessions.set(sessionId, session); 35 | } 36 | if (!session) { 37 | return { content: [{ type: 'text', text: JSON.stringify({ status: 'error', message: 'session_not_found' }) }] }; 38 | } 39 | switch (args.operation) { 40 | case 'import': { 41 | if (!args.sequentialImport) 42 | break; 43 | const imported = totHandler.importFromSequentialFormat(args.sequentialImport); 44 | totSessions.set(imported.sessionId, imported); 45 | sessionId = imported.sessionId; 46 | session = imported; 47 | break; 48 | } 49 | case 'expand': { 50 | if (!args.nodeId) 51 | break; 52 | totHandler.expand(args.nodeId, session); 53 | break; 54 | } 55 | case 'evaluate': { 56 | if (!args.nodeId) 57 | break; 58 | totHandler.evaluate(args.nodeId, session); 59 | break; 60 | } 61 | case 'selectNext': { 62 | totHandler.selectNext(session); 63 | break; 64 | } 65 | case 'prune': { 66 | if (!args.nodeId) 67 | break; 68 | totHandler.prune(args.nodeId, args.reason || 'unspecified', session); 69 | break; 70 | } 71 | case 'isSolution': { 72 | if (!args.nodeId) 73 | break; 74 | totHandler.isSolution(args.nodeId, session); 75 | break; 76 | } 77 | case 'bestPath': { 78 | // No-op here; computed in response 79 | break; 80 | } 81 | case 'iterate': { 82 | totHandler.runIteration(session); 83 | break; 84 | } 85 | } 86 | const exportSeq = totHandler.exportToSequentialFormat(session); 87 | const bestPath = totHandler.getBestPath(session); 88 | return { 89 | content: [{ 90 | type: 'text', 91 | text: JSON.stringify({ 92 | status: 'success', 93 | sessionId, 94 | iteration: session.iteration, 95 | stats: session.stats, 96 | bestPath, 97 | exportSequential: exportSeq 98 | }) 99 | }] 100 | }; 101 | } 102 | // ToolRegistry.getInstance().register({ 103 | // name: 'treeofthought', 104 | // description: 'Tree-of-Thought reasoning tool (expand/evaluate/select/prune/iterate)', 105 | // schema: ToTSchema, 106 | // handler: handleToT, 107 | // category: 'reasoning' 108 | // }); 109 | export { handleToT }; 110 | //# sourceMappingURL=tree-of-thought.js.map -------------------------------------------------------------------------------- /src/types/reasoning-patterns/pdr.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Progressive Deep Reasoning (PDR) Types 3 | * Based on Deep Research methodology for multi-pass exploration 4 | */ 5 | 6 | export type PDRApproach = 7 | | "sequential" 8 | | "tree" 9 | | "beam" 10 | | "mcts" 11 | | "graph" 12 | | "auto"; 13 | 14 | export type EdgeType = 15 | | "supports" 16 | | "contradicts" 17 | | "refines" 18 | | "questions" 19 | | "leads-to" 20 | | "relates-to" 21 | | "derived-from" 22 | | "clusters-with"; 23 | 24 | export type NodeType = 25 | | "subject" 26 | | "concept" 27 | | "evidence" 28 | | "question" 29 | | "insight"; 30 | 31 | export interface PDRNode { 32 | id: string; 33 | content: string; 34 | type: NodeType; 35 | 36 | // Hierarchical properties 37 | depth: number; 38 | parentId?: string; 39 | childrenIds: Set; 40 | 41 | // Graph properties 42 | incomingEdges: Set; 43 | outgoingEdges: Set; 44 | 45 | // Scoring and metadata 46 | scores: { 47 | confidence: number; 48 | centrality: number; 49 | passScores: Map; 50 | }; 51 | 52 | metadata: { 53 | createdInPass: string; 54 | lastModified: string; 55 | tags: Set; 56 | patternUsed?: PDRApproach; 57 | selected: boolean; 58 | }; 59 | 60 | // Content artifacts 61 | artifacts?: { 62 | reasoning?: string; 63 | evidence?: string[]; 64 | citations?: Citation[]; 65 | }; 66 | } 67 | 68 | export interface PDREdge { 69 | id: string; 70 | sourceId: string; 71 | targetId: string; 72 | type: EdgeType; 73 | weight: number; 74 | 75 | metadata: { 76 | createdInPass: string; 77 | confidence: number; 78 | justification?: string; 79 | bidirectional: boolean; 80 | }; 81 | } 82 | 83 | export interface Citation { 84 | source: string; 85 | confidence: number; 86 | excerpt?: string; 87 | } 88 | 89 | export interface PDRSubject { 90 | id: string; 91 | title: string; 92 | description?: string; 93 | tags?: string[]; 94 | passScores: Record; 95 | confidence?: number; 96 | selected?: boolean; 97 | metadata?: Record; 98 | } 99 | 100 | export interface PDRSelectionCriteria { 101 | minScore?: number; 102 | topK?: number; 103 | diversity?: number; 104 | custom?: string; 105 | } 106 | 107 | export interface PDRPassPolicy { 108 | id: string; 109 | name: "scan" | "cluster" | "select" | "deepen" | "synthesize"; 110 | defaultApproach?: PDRApproach; 111 | perSubjectApproach?: { 112 | rules?: Array<{ 113 | when: string; 114 | use: PDRApproach; 115 | }>; 116 | fallback?: PDRApproach; 117 | }; 118 | selection?: PDRSelectionCriteria; 119 | budget?: { 120 | subjectsLimit?: number; 121 | timeMs?: number; 122 | }; 123 | } 124 | 125 | export interface PDRPassTrace { 126 | id: string; 127 | policyId: string; 128 | startedAt: string; 129 | completedAt?: string; 130 | processedSubjectIds: string[]; 131 | approachBySubject: Record; 132 | resultsBySubject: Record< 133 | string, 134 | { 135 | score?: number; 136 | confidence?: number; 137 | notes?: string; 138 | artifacts?: Array<{ 139 | kind: "markdown" | "mermaid" | "json" | "code"; 140 | content: string; 141 | }>; 142 | } 143 | >; 144 | } 145 | 146 | export interface PDRSession { 147 | id: string; 148 | subjects: Map; 149 | passes: PDRPassPolicy[]; 150 | traces: PDRPassTrace[]; 151 | maxPasses: number; 152 | globalSelection?: PDRSelectionCriteria; 153 | stopConditions?: { 154 | maxTimeMs?: number; 155 | minImprovement?: number; 156 | confidenceThreshold?: number; 157 | }; 158 | summary?: { 159 | chosenSubjectIds: string[]; 160 | synthesis?: string; 161 | decisions?: Array<{ 162 | subjectId: string; 163 | decision: string; 164 | rationale?: string; 165 | }>; 166 | }; 167 | } 168 | 169 | export interface KnowledgeGap { 170 | type: "missing-link" | "weak-evidence" | "contradiction" | "isolated-cluster"; 171 | nodeIds: string[]; 172 | priority: number; 173 | description: string; 174 | } 175 | 176 | export interface GraphMetrics { 177 | nodeCount: number; 178 | edgeCount: number; 179 | avgDegree: number; 180 | maxDepth: number; 181 | clusterCount: number; 182 | gaps: KnowledgeGap[]; 183 | } 184 | 185 | export interface HierarchicalStructure { 186 | root: string; 187 | levels: Map>; 188 | parentChild: Map; 189 | } 190 | 191 | export interface Cluster { 192 | id: string; 193 | nodeIds: Set; 194 | centroid?: string; 195 | coherence: number; 196 | } 197 | -------------------------------------------------------------------------------- /dist/types/reasoning-patterns/tree-of-thought.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Tree of Thought (ToT) Reasoning Pattern Types 3 | * 4 | * Enables systematic exploration of multiple reasoning paths with 5 | * explicit branching and evaluation. 6 | */ 7 | import { BaseReasoningNode, BaseReasoningSession } from './base.js'; 8 | /** 9 | * Node in a Tree of Thought structure 10 | */ 11 | export interface TreeOfThoughtNode extends BaseReasoningNode { 12 | /** Parent node ID (null for root) */ 13 | parentId?: string; 14 | /** IDs of child nodes */ 15 | childrenIds: string[]; 16 | /** Depth in the tree (0 for root) */ 17 | depth: number; 18 | /** Evaluation score for this node/path */ 19 | score?: number; 20 | /** Current status of the node */ 21 | status: 'active' | 'explored' | 'pruned' | 'solution'; 22 | /** Extended metadata for ToT */ 23 | metadata?: TreeOfThoughtMetadata; 24 | } 25 | /** 26 | * Metadata specific to Tree of Thought nodes 27 | */ 28 | export interface TreeOfThoughtMetadata { 29 | /** Strategy used for exploration */ 30 | explorationStrategy?: 'depth-first' | 'breadth-first' | 'best-first'; 31 | /** Reason for pruning (if pruned) */ 32 | pruningReason?: string; 33 | /** Confidence in this path (0.0-1.0) */ 34 | confidenceScore?: number; 35 | /** Heuristic value for prioritization */ 36 | heuristicValue?: number; 37 | /** Time spent exploring this node (ms) */ 38 | explorationTime?: number; 39 | /** Domain-specific evaluation metrics */ 40 | domainMetrics?: Record; 41 | } 42 | /** 43 | * Tree of Thought session state 44 | */ 45 | export interface TreeOfThoughtSession extends BaseReasoningSession { 46 | /** Session identifier */ 47 | sessionId: string; 48 | /** Root node ID */ 49 | rootNodeId: string; 50 | /** All nodes in the tree */ 51 | nodes: Map; 52 | /** Currently active/focused node */ 53 | currentNodeId: string; 54 | /** Maximum nodes to explore */ 55 | explorationBudget: number; 56 | /** Criteria for evaluating nodes */ 57 | evaluationCriteria: string[]; 58 | /** Criteria for identifying solutions */ 59 | solutionCriteria: string; 60 | /** IDs forming the best path found so far */ 61 | bestPathIds?: string[]; 62 | /** Configuration for the session */ 63 | config: TreeOfThoughtConfig; 64 | /** Statistics about the exploration */ 65 | stats: TreeOfThoughtStats; 66 | } 67 | /** 68 | * Configuration for Tree of Thought 69 | */ 70 | export interface TreeOfThoughtConfig { 71 | /** Maximum depth to explore */ 72 | maxDepth: number; 73 | /** Maximum children per node */ 74 | maxBranchingFactor: number; 75 | /** Default exploration strategy */ 76 | defaultStrategy: 'depth-first' | 'breadth-first' | 'best-first'; 77 | /** Minimum score to continue exploration */ 78 | pruningThreshold?: number; 79 | /** Whether to allow revisiting nodes */ 80 | allowRevisiting?: boolean; 81 | /** Time limit for exploration (ms) */ 82 | timeLimit?: number; 83 | } 84 | /** 85 | * Statistics for Tree of Thought exploration 86 | */ 87 | export interface TreeOfThoughtStats { 88 | /** Total nodes created */ 89 | nodesCreated: number; 90 | /** Nodes explored */ 91 | nodesExplored: number; 92 | /** Nodes pruned */ 93 | nodesPruned: number; 94 | /** Solutions found */ 95 | solutionsFound: number; 96 | /** Maximum depth reached */ 97 | maxDepthReached: number; 98 | /** Total exploration time (ms) */ 99 | totalTime: number; 100 | /** Average score of explored nodes */ 101 | averageScore?: number; 102 | } 103 | /** 104 | * Operations specific to Tree of Thought 105 | */ 106 | export interface TreeOfThoughtOperations { 107 | /** Expand a node by generating children */ 108 | expand(nodeId: string, session: TreeOfThoughtSession): TreeOfThoughtNode[]; 109 | /** Evaluate a node's promise/score */ 110 | evaluate(nodeId: string, session: TreeOfThoughtSession): number; 111 | /** Select next node to explore */ 112 | selectNext(session: TreeOfThoughtSession): string | null; 113 | /** Prune a subtree */ 114 | prune(nodeId: string, reason: string, session: TreeOfThoughtSession): void; 115 | /** Check if node meets solution criteria */ 116 | isSolution(nodeId: string, session: TreeOfThoughtSession): boolean; 117 | /** Get path from root to node */ 118 | getPath(nodeId: string, session: TreeOfThoughtSession): string[]; 119 | /** Get best path based on scores */ 120 | getBestPath(session: TreeOfThoughtSession): string[]; 121 | } 122 | //# sourceMappingURL=tree-of-thought.d.ts.map -------------------------------------------------------------------------------- /src/resources/examples/causal-analysis.md: -------------------------------------------------------------------------------- 1 | # Causal Analysis Examples 2 | 3 | ## Project Delays Analysis 4 | 5 | ### Causal Graph with Intervention 6 | 7 | ```json 8 | { 9 | "prompt": "Analyze causes of project delays", 10 | "parameters": { 11 | "graph": { 12 | "nodes": [ 13 | "scope_creep", 14 | "resource_shortage", 15 | "poor_planning", 16 | "delays", 17 | "budget_overrun", 18 | "team_morale", 19 | "quality_issues" 20 | ], 21 | "edges": [ 22 | { 23 | "from": "scope_creep", 24 | "to": "delays", 25 | "weight": 0.8 26 | }, 27 | { 28 | "from": "resource_shortage", 29 | "to": "delays", 30 | "weight": 0.7 31 | }, 32 | { 33 | "from": "poor_planning", 34 | "to": "scope_creep", 35 | "weight": 0.6 36 | }, 37 | { 38 | "from": "poor_planning", 39 | "to": "resource_shortage", 40 | "weight": 0.5 41 | }, 42 | { 43 | "from": "delays", 44 | "to": "budget_overrun", 45 | "weight": 0.9 46 | }, 47 | { 48 | "from": "delays", 49 | "to": "team_morale", 50 | "weight": -0.6 51 | }, 52 | { 53 | "from": "team_morale", 54 | "to": "quality_issues", 55 | "weight": -0.7 56 | } 57 | ] 58 | }, 59 | "intervention": { 60 | "variable": "poor_planning", 61 | "change": -0.5 62 | } 63 | } 64 | } 65 | ``` 66 | 67 | ## Economic System Analysis 68 | 69 | ### Supply and Demand Dynamics 70 | 71 | ```json 72 | { 73 | "prompt": "Analyze economic factors affecting product pricing", 74 | "parameters": { 75 | "graph": { 76 | "nodes": [ 77 | "supply", 78 | "demand", 79 | "price", 80 | "competition", 81 | "production_cost", 82 | "consumer_income", 83 | "market_share" 84 | ], 85 | "edges": [ 86 | { 87 | "from": "supply", 88 | "to": "price", 89 | "weight": -0.8 90 | }, 91 | { 92 | "from": "demand", 93 | "to": "price", 94 | "weight": 0.9 95 | }, 96 | { 97 | "from": "price", 98 | "to": "demand", 99 | "weight": -0.6 100 | }, 101 | { 102 | "from": "competition", 103 | "to": "price", 104 | "weight": -0.5 105 | }, 106 | { 107 | "from": "production_cost", 108 | "to": "supply", 109 | "weight": -0.7 110 | }, 111 | { 112 | "from": "consumer_income", 113 | "to": "demand", 114 | "weight": 0.8 115 | }, 116 | { 117 | "from": "price", 118 | "to": "market_share", 119 | "weight": -0.4 120 | } 121 | ] 122 | }, 123 | "intervention": { 124 | "variable": "production_cost", 125 | "change": -0.3 126 | } 127 | } 128 | } 129 | ``` 130 | 131 | ## Climate Impact Analysis 132 | 133 | ### Environmental Cause-Effect Chain 134 | 135 | ```json 136 | { 137 | "prompt": "Analyze climate change causal relationships", 138 | "parameters": { 139 | "graph": { 140 | "nodes": [ 141 | "greenhouse_gases", 142 | "temperature", 143 | "ice_melt", 144 | "sea_level", 145 | "extreme_weather", 146 | "agriculture", 147 | "migration" 148 | ], 149 | "edges": [ 150 | { 151 | "from": "greenhouse_gases", 152 | "to": "temperature", 153 | "weight": 0.9 154 | }, 155 | { 156 | "from": "temperature", 157 | "to": "ice_melt", 158 | "weight": 0.8 159 | }, 160 | { 161 | "from": "ice_melt", 162 | "to": "sea_level", 163 | "weight": 0.9 164 | }, 165 | { 166 | "from": "temperature", 167 | "to": "extreme_weather", 168 | "weight": 0.7 169 | }, 170 | { 171 | "from": "extreme_weather", 172 | "to": "agriculture", 173 | "weight": -0.8 174 | }, 175 | { 176 | "from": "sea_level", 177 | "to": "migration", 178 | "weight": 0.6 179 | }, 180 | { 181 | "from": "agriculture", 182 | "to": "migration", 183 | "weight": 0.5 184 | } 185 | ] 186 | }, 187 | "intervention": { 188 | "variable": "greenhouse_gases", 189 | "change": -0.2 190 | } 191 | } 192 | } 193 | ``` -------------------------------------------------------------------------------- /src/types/reasoning-patterns/tree-of-thought.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Tree of Thought (ToT) Reasoning Pattern Types 3 | * 4 | * Enables systematic exploration of multiple reasoning paths with 5 | * explicit branching and evaluation. 6 | */ 7 | 8 | import type { BaseReasoningNode, BaseReasoningSession } from "./base.js"; 9 | 10 | /** 11 | * Node in a Tree of Thought structure 12 | */ 13 | export interface TreeOfThoughtNode extends BaseReasoningNode { 14 | /** Parent node ID (null for root) */ 15 | parentId?: string; 16 | 17 | /** IDs of child nodes */ 18 | childrenIds: string[]; 19 | 20 | /** Depth in the tree (0 for root) */ 21 | depth: number; 22 | 23 | /** Evaluation score for this node/path */ 24 | score?: number; 25 | 26 | /** Current status of the node */ 27 | status: "active" | "explored" | "pruned" | "solution"; 28 | 29 | /** Extended metadata for ToT */ 30 | metadata?: TreeOfThoughtMetadata; 31 | } 32 | 33 | /** 34 | * Metadata specific to Tree of Thought nodes 35 | */ 36 | export interface TreeOfThoughtMetadata { 37 | /** Strategy used for exploration */ 38 | explorationStrategy?: "depth-first" | "breadth-first" | "best-first"; 39 | 40 | /** Reason for pruning (if pruned) */ 41 | pruningReason?: string; 42 | 43 | /** Confidence in this path (0.0-1.0) */ 44 | confidenceScore?: number; 45 | 46 | /** Heuristic value for prioritization */ 47 | heuristicValue?: number; 48 | 49 | /** Time spent exploring this node (ms) */ 50 | explorationTime?: number; 51 | 52 | /** Domain-specific evaluation metrics */ 53 | domainMetrics?: Record; 54 | } 55 | 56 | /** 57 | * Tree of Thought session state 58 | */ 59 | export interface TreeOfThoughtSession extends BaseReasoningSession { 60 | /** Session identifier */ 61 | sessionId: string; 62 | 63 | /** Root node ID */ 64 | rootNodeId: string; 65 | 66 | /** All nodes in the tree */ 67 | nodes: Map; 68 | 69 | /** Currently active/focused node */ 70 | currentNodeId: string; 71 | 72 | /** Maximum nodes to explore */ 73 | explorationBudget: number; 74 | 75 | /** Criteria for evaluating nodes */ 76 | evaluationCriteria: string[]; 77 | 78 | /** Criteria for identifying solutions */ 79 | solutionCriteria: string; 80 | 81 | /** IDs forming the best path found so far */ 82 | bestPathIds?: string[]; 83 | 84 | /** Configuration for the session */ 85 | config: TreeOfThoughtConfig; 86 | 87 | /** Statistics about the exploration */ 88 | stats: TreeOfThoughtStats; 89 | } 90 | 91 | /** 92 | * Configuration for Tree of Thought 93 | */ 94 | export interface TreeOfThoughtConfig { 95 | /** Maximum depth to explore */ 96 | maxDepth: number; 97 | 98 | /** Maximum children per node */ 99 | maxBranchingFactor: number; 100 | 101 | /** Default exploration strategy */ 102 | defaultStrategy: "depth-first" | "breadth-first" | "best-first"; 103 | 104 | /** Minimum score to continue exploration */ 105 | pruningThreshold?: number; 106 | 107 | /** Whether to allow revisiting nodes */ 108 | allowRevisiting?: boolean; 109 | 110 | /** Time limit for exploration (ms) */ 111 | timeLimit?: number; 112 | } 113 | 114 | /** 115 | * Statistics for Tree of Thought exploration 116 | */ 117 | export interface TreeOfThoughtStats { 118 | /** Total nodes created */ 119 | nodesCreated: number; 120 | 121 | /** Nodes explored */ 122 | nodesExplored: number; 123 | 124 | /** Nodes pruned */ 125 | nodesPruned: number; 126 | 127 | /** Solutions found */ 128 | solutionsFound: number; 129 | 130 | /** Maximum depth reached */ 131 | maxDepthReached: number; 132 | 133 | /** Total exploration time (ms) */ 134 | totalTime: number; 135 | 136 | /** Average score of explored nodes */ 137 | averageScore?: number; 138 | } 139 | 140 | /** 141 | * Operations specific to Tree of Thought 142 | */ 143 | export interface TreeOfThoughtOperations { 144 | /** Expand a node by generating children */ 145 | expand(nodeId: string, session: TreeOfThoughtSession): TreeOfThoughtNode[]; 146 | 147 | /** Evaluate a node's promise/score */ 148 | evaluate(nodeId: string, session: TreeOfThoughtSession): number; 149 | 150 | /** Select next node to explore */ 151 | selectNext(session: TreeOfThoughtSession): string | null; 152 | 153 | /** Prune a subtree */ 154 | prune(nodeId: string, reason: string, session: TreeOfThoughtSession): void; 155 | 156 | /** Check if node meets solution criteria */ 157 | isSolution(nodeId: string, session: TreeOfThoughtSession): boolean; 158 | 159 | /** Get path from root to node */ 160 | getPath(nodeId: string, session: TreeOfThoughtSession): string[]; 161 | 162 | /** Get best path based on scores */ 163 | getBestPath(session: TreeOfThoughtSession): string[]; 164 | } 165 | --------------------------------------------------------------------------------