deepthinking-mcp 3.1.0 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,818 +1,641 @@
1
- # DeepThinking MCP v3.1.0
2
-
3
- A comprehensive Model Context Protocol (MCP) server featuring **14 advanced reasoning modes** with intelligent mode recommendation, visual export capabilities, high-performance validation caching, comprehensive testing, and automated CI/CD for complex problem-solving, analysis, and decision-making.
4
-
5
- ## Overview
6
-
7
- DeepThinking MCP v3.1 provides a complete toolkit for structured reasoning with 14 specialized modes, an intelligent recommendation system, powerful visual export capabilities, and optimized performance through validation caching:
8
-
9
- ### Core Modes
10
- - **Sequential**: Iterative refinement with revision capabilities
11
- - **Shannon**: 5-stage systematic problem-solving methodology
12
- - **Mathematics**: Theorem proving and symbolic computation
13
- - **Physics**: Tensor mathematics and field theory
14
- - **Hybrid**: Intelligently combines multiple approaches
15
-
16
- ### Advanced Modes (v2.0)
17
- - **Abductive**: Inference to the best explanation, hypothesis generation and evaluation
18
- - **Causal**: Cause-effect analysis with causal graphs and interventions
19
- - **Bayesian**: Probabilistic reasoning with evidence updates
20
- - **Counterfactual**: What-if scenario analysis and alternative histories
21
- - **Analogical**: Cross-domain pattern matching and knowledge transfer
22
- n### Phase 3 Modes (v2.3+)
23
- - **Temporal**: Event timelines, temporal constraints, Allen's interval algebra, causal relations over time
24
- - **Game Theory**: Nash equilibria, strategic analysis, payoff matrices, dominant strategies, game trees
25
- - **Evidential**: Dempster-Shafer theory, belief functions, evidence combination, uncertainty intervals
26
- - **First-Principles**: Deductive reasoning from foundational axioms and principles
27
-
28
- ## Features
29
-
30
- ### 13 Specialized Reasoning Modes
31
-
32
- #### Core Modes
33
- - **Sequential**: Iterative refinement with revision capabilities and branching
34
- - **Shannon**: Systematic 5-stage problem-solving (problem definition constraints model proof → implementation)
35
- - **Mathematics**: Theorem proving, lemma derivation, symbolic computation
36
- - **Physics**: Tensor formulation, dimensional analysis, conservation laws
37
- - **Hybrid**: Intelligently combines modes based on problem characteristics
38
-
39
- #### Advanced Reasoning Modes (v2.0)
40
- - **Abductive**: Generate and evaluate hypotheses to explain observations. Perfect for debugging, root cause analysis, and diagnostic reasoning.
41
- - **Causal**: Build causal graphs with nodes and edges, analyze interventions and their effects. Ideal for impact analysis and system design.
42
- - **Bayesian**: Update beliefs using probabilistic reasoning with priors, likelihoods, and evidence. Essential for risk assessment and A/B testing.
43
- - **Counterfactual**: Explore alternative scenarios and compare outcomes. Excellent for post-mortems and strategic planning.
44
- - **Analogical**: Transfer knowledge across domains by identifying structural similarities. Great for design patterns and innovative problem-solving.
45
- n#### Phase 3 Reasoning Modes (v2.3+)
46
- - **Temporal**: Model events, intervals, and temporal relationships using Allen's interval algebra. Track causality over time with timestamps, durations, and temporal constraints. Perfect for timeline analysis, scheduling problems, and understanding event sequences.
47
- - **Game Theory**: Analyze strategic interactions between rational agents. Define games, players, and strategies. Compute Nash equilibria (pure and mixed), identify dominant strategies, construct payoff matrices, and build extensive-form game trees. Ideal for competitive analysis, mechanism design, and strategic decision-making.
48
- - **Evidential**: Apply Dempster-Shafer theory for reasoning with uncertain and incomplete evidence. Define hypotheses, collect evidence with reliability scores, assign belief functions with mass assignments, combine evidence using Dempster's rule, compute belief and plausibility intervals, and make decisions under uncertainty. Ideal for sensor fusion, diagnostic reasoning, intelligence analysis, and situations with incomplete information.
49
- - **First-Principles**: Derive conclusions from foundational axioms and principles using deductive reasoning. Define principles (axioms, definitions, observations), build derivation chains with logical inferences, track confidence levels, and reach conclusions with certainty analysis. Ideal for fundamental analysis, conceptual understanding, and reasoning from basic truths.
50
-
51
- ### Mathematical Enhancements
52
- - **Symbolic computation** support with LaTeX and symbolic formats
53
- - **Theorem and proof** structures
54
- - **Lemma derivation** and corollary tracking
55
- - **Algebraic manipulation** and numerical analysis
56
- - **Logical form** with premises, conclusions, and inference rules
57
-
58
- ### Physics Capabilities
59
- - **Tensor mathematics** with rank, symmetries, and invariants
60
- - **Dimensional analysis** for unit consistency
61
- - **Conservation law** verification
62
- - **Field theory** context (Lagrangian, Hamiltonian, gauge symmetries)
63
- - **Physical interpretation** with units and observables
64
-
65
- ### Session Management
66
- - Persistent thinking sessions
67
- - Automatic metrics tracking
68
- - Mode switching during problem-solving
69
- - Export to multiple formats (Markdown, LaTeX, JSON)
70
-
71
- ### Mode Recommendation System (v2.4)
72
- - **Intelligent Mode Selection**: Automatically recommends the best reasoning modes based on problem characteristics
73
- - **Combination Suggestions**: Identifies synergistic mode combinations for complex problems
74
- - **Quick Recommendations**: Simple problem-type based recommendations
75
- - **Problem Characteristics Analysis**: Analyzes domain, complexity, uncertainty, time-dependence, and more
76
- - **Ranked Recommendations**: Returns modes sorted by suitability score with detailed reasoning
77
-
78
- ### Performance & Optimization (v3.0)
79
- - **Validation Caching**: LRU cache with content-based hashing for validation results
80
- - **1.4-17x speedup** for repeated validations (typically 4-5x in realistic workloads)
81
- - **O(1) lookup complexity** regardless of cache size
82
- - **95%+ hit rates** in typical usage patterns
83
- - Configurable cache size (default: 1000 entries)
84
- - Automatic cache statistics tracking in session metrics
85
- - **Modular Validator Architecture**: Clean separation of concerns with mode-specific validators
86
- - **Session Metrics**: Comprehensive performance tracking including cache statistics
87
-
88
- ### Configuration Options
89
- ```javascript
90
- // Environment variables for performance tuning
91
- MCP_ENABLE_VALIDATION_CACHE=true // Enable/disable caching (default: true)
92
- MCP_VALIDATION_CACHE_SIZE=1000 // Max cache entries (default: 1000)
93
- ```
94
-
95
- ## Installation
96
-
97
- ```bash
98
- npm install deepthinking-mcp
99
- ```
100
-
101
- ## Configuration
102
-
103
- Add to your Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows):
104
-
105
- ```json
106
- {
107
- "mcpServers": {
108
- "deepthinking": {
109
- "command": "npx",
110
- "args": ["-y", "deepthinking-mcp"]
111
- }
112
- }
113
- }
114
- ```
115
-
116
- ## Usage
117
-
118
- ### Basic Sequential Thinking
119
-
120
- ```
121
- Use the deepthinking tool to help me think through this step by step...
122
- ```
123
-
124
- The tool will automatically create a session and track your thoughts.
125
-
126
- ### Mathematical Reasoning
127
-
128
- ```
129
- Use deepthinking in mathematics mode to prove the Pythagorean theorem...
130
- ```
131
-
132
- ### Physics Problems
133
-
134
- ```
135
- Use deepthinking in physics mode to derive the electromagnetic tensor formulation...
136
- ```
137
-
138
- ### Hybrid Mode (Default)
139
-
140
- ```
141
- Use deepthinking to solve this complex problem...
142
- ```
143
-
144
- The hybrid mode automatically selects the best features from each mode.
145
-
146
- ### Mode Recommendations (v2.4)
147
-
148
- The recommendation system helps you choose the best reasoning mode for your problem:
149
-
150
- ```
151
- What mode should I use for debugging this application?
152
- ```
153
-
154
- Returns: **Abductive mode** - Perfect for hypothesis generation and root cause analysis.
155
-
156
- ```
157
- I need to analyze a competitive business scenario with multiple players. What modes should I use?
158
- ```
159
-
160
- Returns: **Game Theory mode** for strategic analysis, potentially combined with **Counterfactual mode** for scenario exploration.
161
-
162
- #### Problem Characteristics
163
-
164
- The recommender analyzes:
165
- - **Domain**: General, mathematics, physics, engineering, etc.
166
- - **Complexity**: Low, medium, or high
167
- - **Uncertainty**: How much unknown information exists
168
- - **Time-dependent**: Whether events occur over time
169
- - **Multi-agent**: Whether multiple actors interact strategically
170
- - **Requires proof**: Whether formal mathematical proof is needed
171
- - **Requires quantification**: Whether probabilities or measurements are needed
172
- - **Incomplete information**: Whether data gaps exist
173
- - **Requires explanation**: Whether understanding "why" is important
174
- - **Has alternatives**: Whether alternative scenarios should be explored
175
-
176
- #### Quick Recommendations
177
-
178
- For simple cases, use problem-type keywords:
179
- - `debugging` Abductive mode
180
- - `proof` → Mathematics mode
181
- - `timeline` → Temporal mode
182
- - `strategy` → Game Theory mode
183
- - `uncertainty` Evidential mode
184
- - `causality` → Causal mode
185
- - `probability` → Bayesian mode
186
- - `what-if` → Counterfactual mode
187
-
188
- ### Visual Exports (v2.5)
189
-
190
- Export your reasoning sessions as visual diagrams in multiple formats for presentation, documentation, and analysis:
191
-
192
- #### Supported Formats
193
- - **Mermaid**: Flowcharts, Gantt charts, and graphs (compatible with GitHub, Markdown renderers, and documentation tools)
194
- - **DOT**: Graphviz format for professional graph visualization and publication-quality diagrams
195
- - **ASCII**: Plain text diagrams for terminal output, logs, and text-based documentation
196
-
197
- #### Supported Modes**All 14 modes now support visual export (100% coverage):**- **Causal Mode**: Export causal graphs showing cause-effect relationships with node types (causes, effects, mediators, confounders) and edge strengths- **Temporal Mode**: Export timelines as Gantt charts showing events, intervals, and temporal relationships- **Game Theory Mode**: Export game trees with strategies, decision nodes, and payoffs- **Bayesian Mode**: Export Bayesian networks showing prior/posterior relationships and evidence flow- **First-Principles Mode**: Export derivation chains showing question → principles → derivation steps → conclusion flow- **All Other Modes**: Generic thought sequence visualization showing reasoning progression for Sequential, Shannon, Mathematics, Physics, Hybrid, Abductive, Counterfactual, Analogical, and Evidential modes
198
-
199
- #### Visual Export Examples
200
-
201
- **Causal Graph to Mermaid:**
202
- ```json
203
- {
204
- "action": "export",
205
- "sessionId": "session-id",
206
- "exportFormat": "mermaid"
207
- }
208
- ```
209
-
210
- Returns a Mermaid diagram:
211
- ```mermaid
212
- graph TB
213
- marketing([Marketing Budget])
214
- awareness[Brand Awareness]
215
- revenue[[Revenue]]
216
-
217
- marketing --> |0.80| awareness
218
- awareness --> |0.90| revenue
219
-
220
- style marketing fill:#a8d5ff
221
- style revenue fill:#ffb3b3
222
- ```
223
-
224
- **Temporal Timeline to ASCII:**
225
- ```json
226
- {
227
- "action": "export",
228
- "sessionId": "session-id",
229
- "exportFormat": "ascii"
230
- }
231
- ```
232
-
233
- Returns a text timeline:
234
- ```
235
- Timeline: Project Timeline (days)
236
-
237
- t= 0 ⦿ Project Start
238
- Kickoff meeting
239
-
240
- t= 5 ━ Development (duration: 10 days)
241
- Code implementation
242
-
243
- t= 20 ⦿ Launch
244
- Product release
245
- ```
246
-
247
- **Game Tree to DOT:**
248
- ```json
249
- {
250
- "action": "export",
251
- "sessionId": "session-id",
252
- "exportFormat": "dot"
253
- }
254
- ```
255
-
256
- Returns Graphviz DOT format for rendering with `dot` or graph visualization tools.
257
-
258
- #### Color Schemes
259
- Visual exports support multiple color schemes:
260
- - **default**: Vibrant colors for causes (blue), effects (red), mediators (yellow)
261
- - **pastel**: Soft, pastel colors for presentations
262
- - **monochrome**: No colors for print or accessibility
263
-
264
- #### Integration
265
- Visual exports work seamlessly with:
266
- - GitHub Markdown (Mermaid diagrams render automatically)
267
- - Documentation generators (MkDocs, Docusaurus, etc.)
268
- - Graphviz tools (`dot`, `neato`, `fdp` for DOT format)
269
- - Terminal output (ASCII format)
270
- - Jupyter notebooks (via Mermaid magic)
271
-
272
-
273
- ## Tool Parameters
274
-
275
- ### Core Parameters
276
- - `thought` (string, required): The thought content
277
- - `thoughtNumber` (number, required): Position in sequence
278
- - `totalThoughts` (number, required): Estimated total thoughts needed
279
- - `nextThoughtNeeded` (boolean, required): Whether to continue thinking
280
- - `mode` (string, optional): `sequential`, `shannon`, `mathematics`, `physics`, `hybrid`, `abductive`, `causal`, `bayesian`, `counterfactual`, `analogical`, or `temporal`, `gametheory`, `evidential`, `firstprinciple` (default: `hybrid`)
281
-
282
- ### Mode-Specific Parameters
283
-
284
- #### Sequential Mode
285
- - `isRevision`: Whether this revises a previous thought
286
- - `revisesThought`: ID of thought being revised
287
- - `revisionReason`: Why the revision was needed
288
-
289
- #### Shannon Mode
290
- - `stage`: Which Shannon stage (problem_definition, constraints, model, proof, implementation)
291
- - `uncertainty`: Confidence level (0-1)
292
- - `dependencies`: IDs of dependent thoughts
293
- - `assumptions`: Explicit assumptions
294
-
295
- #### Mathematics Mode
296
- - `thoughtType`: Specific type (axiom_definition, theorem_statement, proof_construction, etc.)
297
- - `mathematicalModel`: LaTeX and symbolic representation
298
- - `proofStrategy`: Type and steps of proof
299
- - `logicalForm`: Premises, conclusion, inference rules
300
-
301
- #### Physics Mode
302
- - `thoughtType`: Specific type (tensor_formulation, symmetry_analysis, etc.)
303
- - `tensorProperties`: Rank, components, symmetries, invariants
304
- - `physicalInterpretation`: Quantity, units, conservation laws
305
- - `dimensionalAnalysis`: Unit consistency checking
306
-
307
- #### Abductive Mode
308
- - `observations`: Array of observations requiring explanation (id, description, confidence)
309
- - `hypotheses`: Generated hypotheses with assumptions and predictions
310
- - `evaluationCriteria`: Parsimony, explanatory power, plausibility, testability
311
- - `evidence`: Supporting or contradicting evidence
312
- - `bestExplanation`: Selected hypothesis that best explains observations
313
-
314
- #### Causal Mode
315
- - `causalGraph`: Nodes (causes, effects, mediators) and edges (causal relationships)
316
- - `interventions`: Actions on nodes with expected effects
317
- - `mechanisms`: Direct, indirect, or feedback mechanisms
318
- - `confounders`: Variables affecting multiple nodes
319
-
320
- #### Bayesian Mode
321
- - `hypothesis`: Statement being evaluated
322
- - `prior`: Prior probability with justification
323
- - `likelihood`: P(Evidence|Hypothesis)
324
- - `evidence`: Observations with likelihoods
325
- - `posterior`: Updated belief after seeing evidence
326
- - `bayesFactor`: Strength of evidence (optional)
327
-
328
- #### Counterfactual Mode
329
- - `actual`: The scenario that actually occurred
330
- - `counterfactuals`: Alternative "what if" scenarios
331
- - `interventionPoint`: Where the scenarios diverge
332
- - `comparison`: Differences, insights, and lessons learned
333
- - `causalChains`: Intervention steps → outcome paths
334
-
335
- #### Analogical Mode
336
- - `sourceDomain`: Known domain with entities and relations
337
- - `targetDomain`: Domain being analyzed
338
- - `mapping`: Entity-to-entity mappings with justifications
339
- - `insights`: Knowledge transferred from source to target
340
- - `inferences`: Predictions based on analogical reasoning
341
- - `limitations`: Where the analogy breaks down
342
- - `analogyStrength`: Overall confidence in the analogy (0-1)
343
- n#### Temporal Mode
344
- - `timeline`: Timeline structure with id, name, timeUnit, events array
345
- - `events`: Temporal events (instant or interval) with timestamps, duration, properties
346
- - `intervals`: Time intervals with start, end, overlaps, contains relationships
347
- - `constraints`: Allen's interval algebra constraints (before, after, during, overlaps, meets, starts, finishes, equals)
348
- - `relations`: Temporal causal relations (causes, enables, prevents, precedes, follows) with strength and delay
349
-
350
- #### Game Theory Mode
351
- - `game`: Game definition (id, name, type, numPlayers, isZeroSum, isPerfectInformation)
352
- - `players`: Player definitions with roles, rationality, available strategies
353
- - `strategies`: Pure or mixed strategies with probabilities
354
- - `payoffMatrix`: Normal-form payoff matrix with strategy profiles and payoffs
355
- - `nashEquilibria`: Nash equilibrium solutions (pure/mixed, strict, stability)
356
- - `dominantStrategies`: Dominant strategy analysis (strictly/weakly dominant)
357
- - `gameTree`: Extensive-form game tree with decision, chance, and terminal nodes
358
-
359
- #### Evidential Mode
360
- - `frameOfDiscernment`: Set of all possible hypotheses being considered
361
- - `hypotheses`: Hypothesis definitions (id, name, description, mutuallyExclusive, subsets)
362
- - `evidence`: Evidence items with source, reliability (0-1), timestamp, supports, contradicts
363
- - `beliefFunctions`: Belief function with mass assignments (hypothesisSet, mass, justification)
364
- - `combinedBelief`: Belief function resulting from Dempster-Shafer combination (includes conflictMass)
365
- - `plausibility`: Plausibility function with belief/plausibility values and uncertainty intervals
366
- - `decisions`: Decision analysis (selectedHypothesis, confidence, reasoning, alternatives)
367
- n#### First-Principles Mode
368
- - `question`: The question being answered from first principles
369
- - `principles`: Array of foundational principles with:
370
- - `id`: Unique identifier
371
- - `type`: Principle type (axiom, definition, observation, logical_inference, assumption)
372
- - `statement`: The principle statement
373
- - `justification`: Why this principle is valid
374
- - `dependsOn`: Optional array of principle IDs this depends on
375
- - `derivationSteps`: Chain of reasoning steps with:
376
- - `stepNumber`: Step position in derivation
377
- - `principle`: The principle being applied
378
- - `inference`: What is inferred from this principle
379
- - `logicalForm`: Optional formal logic representation
380
- - `confidence`: Confidence in this step (0-1)
381
- - `conclusion`: Final conclusion with:
382
- - `statement`: The conclusion statement
383
- - `derivationChain`: Array of step numbers leading to conclusion
384
- - `certainty`: Overall certainty level (0-1)
385
- - `limitations`: Optional array of known limitations or assumptions
386
- - `alternativeInterpretations`: Optional array of other possible interpretations
387
-
388
- ### Actions
389
- - `add_thought` (default): Add a new thought to session
390
- - `summarize`: Generate session summary
391
- - `export`: Export session (requires `exportFormat`)
392
- - `switch_mode`: Change thinking mode (requires `newMode`)
393
- - `get_session`: Get session metadata
394
-
395
- ## Examples
396
-
397
- ### Example 1: Sequential Problem Solving
398
-
399
- ```
400
- Thought 1: "Let me break down this optimization problem..."
401
- - mode: sequential
402
- - thoughtNumber: 1
403
- - nextThoughtNeeded: true
404
-
405
- Thought 2: "Building on my previous thought, I realize..."
406
- - mode: sequential
407
- - thoughtNumber: 2
408
- - buildUpon: [thought1_id]
409
- - nextThoughtNeeded: true
410
-
411
- Thought 3: "Actually, let me revise my first approach..."
412
- - mode: sequential
413
- - isRevision: true
414
- - revisesThought: thought1_id
415
- - revisionReason: "Found a more efficient approach"
416
- ```
417
-
418
- ### Example 2: Mathematical Proof
419
-
420
- ```
421
- Thought 1: "State the theorem: For all right triangles..."
422
- - mode: mathematics
423
- - thoughtType: theorem_statement
424
- - mathematicalModel: { latex: "a^2 + b^2 = c^2", symbolic: "a**2 + b**2 == c**2" }
425
-
426
- Thought 2: "Proof by construction..."
427
- - mode: mathematics
428
- - thoughtType: proof_construction
429
- - proofStrategy: { type: "construction", steps: ["Draw square on each side", ...] }
430
- ```
431
-
432
- ### Example 3: Physics Tensor Analysis
433
-
434
- ```
435
- Thought 1: "Define the electromagnetic field tensor"
436
- - mode: physics
437
- - thoughtType: tensor_formulation
438
- - tensorProperties: {
439
- rank: [2, 0],
440
- components: "F^{μν} = ∂^μ A^ν - ∂^ν A^μ",
441
- latex: "F^{\\mu\\nu}",
442
- symmetries: ["antisymmetric"],
443
- invariants: ["F_{μν}F^{μν}"],
444
- transformation: "contravariant"
445
- }
446
- - physicalInterpretation: {
447
- quantity: "Electromagnetic field strength",
448
- units: "GeV^2",
449
- conservationLaws: ["Energy-momentum", "Charge"]
450
- }
451
- ```
452
-
453
- ### Example 4: Abductive Reasoning (Debugging)
454
-
455
- ```
456
- Thought 1: "System crashes at 3 AM - need to find root cause"
457
- - mode: abductive
458
- - observations: [
459
- { id: "obs1", description: "Crash at 3 AM daily", confidence: 0.95 },
460
- { id: "obs2", description: "Memory usage spikes before crash", confidence: 0.8 }
461
- ]
462
- - hypotheses: [
463
- {
464
- id: "h1",
465
- explanation: "Memory leak in background job",
466
- assumptions: ["Job runs at 3 AM"],
467
- predictions: ["Memory should grow until crash"],
468
- score: 0.85
469
- },
470
- {
471
- id: "h2",
472
- explanation: "External service timeout",
473
- assumptions: ["Service maintenance window at 3 AM"],
474
- predictions: ["Network errors in logs"],
475
- score: 0.6
476
- }
477
- ]
478
- - evaluationCriteria: {
479
- parsimony: 0.7,
480
- explanatoryPower: 0.85,
481
- plausibility: 0.8,
482
- testability: true
483
- }
484
- - bestExplanation: h1
485
- ```
486
-
487
- ### Example 5: Causal Analysis (Impact Assessment)
488
-
489
- ```
490
- Thought 1: "Analyze impact of increasing marketing budget"
491
- - mode: causal
492
- - causalGraph: {
493
- nodes: [
494
- { id: "marketing", name: "Marketing Budget", type: "cause" },
495
- { id: "awareness", name: "Brand Awareness", type: "mediator" },
496
- { id: "leads", name: "Lead Generation", type: "mediator" },
497
- { id: "revenue", name: "Revenue", type: "effect" }
498
- ],
499
- edges: [
500
- { from: "marketing", to: "awareness", strength: 0.8, confidence: 0.9 },
501
- { from: "awareness", to: "leads", strength: 0.7, confidence: 0.85 },
502
- { from: "leads", to: "revenue", strength: 0.9, confidence: 0.95 }
503
- ]
504
- }
505
- - interventions: [
506
- {
507
- nodeId: "marketing",
508
- action: "Increase budget by 20%",
509
- expectedEffects: [
510
- { nodeId: "revenue", expectedChange: "+12%", confidence: 0.7 }
511
- ]
512
- }
513
- ]
514
- ```
515
-
516
- ### Example 6: Bayesian Reasoning (A/B Test Analysis)
517
-
518
- ```
519
- Thought 1: "Evaluate if new feature increases engagement"
520
- - mode: bayesian
521
- - hypothesis: { id: "h1", statement: "New feature increases engagement" }
522
- - prior: {
523
- probability: 0.5,
524
- justification: "No prior information, neutral stance"
525
- }
526
- - evidence: [
527
- {
528
- id: "e1",
529
- description: "Test group showed 15% increase",
530
- likelihoodGivenHypothesis: 0.8,
531
- likelihoodGivenNotHypothesis: 0.2
532
- }
533
- ]
534
- - posterior: {
535
- probability: 0.8,
536
- calculation: "P(H|E) = P(E|H) * P(H) / P(E) = 0.8 * 0.5 / 0.5 = 0.8"
537
- }
538
- - bayesFactor: 4.0 // Strong evidence for hypothesis
539
- ```
540
-
541
- ### Example 7: Counterfactual Analysis (Post-Mortem)
542
-
543
- ```
544
- Thought 1: "What if we had chosen microservices instead of monolith?"
545
- - mode: counterfactual
546
- - actual: {
547
- id: "actual",
548
- name: "Monolithic Architecture",
549
- description: "Built as single application",
550
- conditions: [{ factor: "Architecture", value: "Monolith" }],
551
- outcomes: [
552
- { description: "Deployment bottleneck", impact: "negative", magnitude: 0.7 },
553
- { description: "Fast initial development", impact: "positive", magnitude: 0.8 }
554
- ]
555
- }
556
- - counterfactuals: [
557
- {
558
- id: "cf1",
559
- name: "Microservices Architecture",
560
- description: "Built as independent services",
561
- conditions: [{ factor: "Architecture", value: "Microservices" }],
562
- outcomes: [
563
- { description: "Independent deployment", impact: "positive", magnitude: 0.9 },
564
- { description: "Higher operational complexity", impact: "negative", magnitude: 0.6 }
565
- ]
566
- }
567
- ]
568
- - interventionPoint: {
569
- description: "Initial architecture decision",
570
- alternatives: ["Monolith", "Microservices", "Modular Monolith"]
571
- }
572
- - comparison: {
573
- differences: [
574
- {
575
- aspect: "Scalability",
576
- actual: "Limited",
577
- counterfactual: "Highly scalable",
578
- significance: "high"
579
- }
580
- ],
581
- insights: ["Microservices would have enabled better scaling"],
582
- lessons: ["Consider future scale requirements in architecture decisions"]
583
- }
584
- ```
585
-
586
- ### Example 8: Analogical Reasoning (Design Patterns)
587
-
588
- ```
589
- Thought 1: "Apply immune system principles to cybersecurity"
590
- - mode: analogical
591
- - sourceDomain: {
592
- id: "immune",
593
- name: "Biological Immune System",
594
- entities: [
595
- { id: "antibody", name: "Antibody", type: "defender" },
596
- { id: "pathogen", name: "Pathogen", type: "threat" }
597
- ],
598
- relations: [
599
- { id: "r1", type: "neutralizes", from: "antibody", to: "pathogen" }
600
- ]
601
- }
602
- - targetDomain: {
603
- id: "cyber",
604
- name: "Cybersecurity System",
605
- entities: [
606
- { id: "firewall", name: "Firewall", type: "defender" },
607
- { id: "malware", name: "Malware", type: "threat" }
608
- ],
609
- relations: [
610
- { id: "r2", type: "blocks", from: "firewall", to: "malware" }
611
- ]
612
- }
613
- - mapping: [
614
- {
615
- sourceEntityId: "antibody",
616
- targetEntityId: "firewall",
617
- justification: "Both identify and neutralize threats",
618
- confidence: 0.85
619
- }
620
- ]
621
- - insights: [
622
- {
623
- description: "Layered defense strategy",
624
- sourceEvidence: "Immune system has innate + adaptive layers",
625
- targetApplication: "Implement defense-in-depth security"
626
- }
627
- ]
628
- - limitations: [
629
- "Biological systems self-heal, digital systems don't",
630
- "Pathogens evolve naturally, malware is designed"
631
- ]
632
- - analogyStrength: 0.75
633
- ```
634
-
635
- ## Development
636
-
637
- ### Building
638
-
639
- ```bash
640
- npm install
641
- npm run build
642
- ```
643
-
644
- ### Testing
645
-
646
- ```bash
647
- npm test
648
- ```
649
-
650
- ### Type Checking
651
-
652
- ```bash
653
- npm run typecheck
654
- ```
655
-
656
- ### Testing & CI/CD
657
-
658
- #### Comprehensive Test Suite (v3.0.2)
659
-
660
- DeepThinking MCP includes **397 tests** across **24 test files** with **100% pass rate**:
661
-
662
- - **Unit Tests**: Core functionality, validators, session management
663
- - **Integration Tests (94 tests)**: MCP protocol compliance, multi-session scenarios, error handling
664
- - **Benchmark Tests**: Performance validation (15x speedup with caching)
665
- - **Mode-Specific Tests**: All 13 reasoning modes thoroughly tested
666
-
667
- **Test Coverage:**
668
- ```bash
669
- # Run full test suite
670
- npm test
671
-
672
- # Run with coverage report
673
- npm run test:coverage
674
-
675
- # Run specific test file
676
- npm test -- tests/integration/mcp-protocol.test.ts
677
- ```
678
-
679
- **Test Results:**
680
- - Test Files: 24 passed
681
- - Tests: 397 passed
682
- - Duration: ~7-8 seconds
683
- - Pass Rate: 100%
684
-
685
- #### CI/CD Pipeline
686
-
687
- Automated workflows using GitHub Actions ensure code quality and reliability:
688
-
689
- **Test Workflow** (`.github/workflows/test.yml`):
690
- - Multi-OS testing: Ubuntu, Windows, macOS
691
- - Multi-Node version: 18.x, 20.x, 22.x
692
- - Runs: TypeScript checks, linter, formatter, full test suite
693
- - Test result artifacts with 30-day retention
694
-
695
- **Coverage Workflow** (`.github/workflows/coverage.yml`):
696
- - Generates detailed coverage reports
697
- - Codecov integration for coverage tracking
698
- - PR comments with coverage summary
699
- - Coverage badge generation
700
- - Threshold warnings (<60% triggers warning)
701
-
702
- **Release Workflow** (`.github/workflows/release.yml`):
703
- - Automated releases on version tags (v*.*.*)
704
- - Pre-release testing (type check + full test suite)
705
- - GitHub release creation with changelog
706
- - npm publishing (requires NPM_TOKEN)
707
- - Workflow dispatch for manual releases
708
-
709
- **Branch Protection:**
710
- See `.github/BRANCH_PROTECTION.md` for recommended settings:
711
- - Required status checks before merging
712
- - PR review requirements
713
- - Linear history enforcement
714
- - Force push protection
715
-
716
- #### Integration Tests
717
-
718
- **MCP Protocol Compliance** (43 tests):
719
- - Tool schema validation for all 13 modes
720
- - Required/optional field validation
721
- - MCP response format compliance
722
- - Error handling for invalid inputs
723
-
724
- **Multi-Session Scenarios** (18 tests):
725
- - Session isolation and concurrent operations
726
- - Resource management (50+ sessions)
727
- - State consistency verification
728
- - Concurrent error handling
729
-
730
- **Error Handling & Edge Cases** (36 tests):
731
- - Invalid session operations
732
- - Boundary conditions (0, 1, MAX_SAFE_INTEGER)
733
- - Large data handling (100 thoughts, 50 dependencies)
734
- - Unicode and special character support
735
- - Mode-specific edge cases
736
-
737
- ## Architecture
738
-
739
- ```
740
- deepthinking-mcp/
741
- ├── src/
742
- │ ├── types/ # Type definitions
743
- │ │ ├── core.ts # Core thought types
744
- │ │ └── session.ts # Session management types
745
- │ ├── tools/ # MCP tool definitions
746
- │ ├── session/ # Session manager
747
- │ ├── modes/ # Mode implementations
748
- │ ├── validation/ # Validation logic
749
- │ └── index.ts # Main MCP server
750
- ├── tests/ # Test suite
751
- ├── docs/ # Documentation
752
- └── examples/ # Usage examples
753
- ```
754
-
755
- ## Roadmap
756
-
757
- ### Phase 1 (Completed - v1.0)
758
- - ✅ Core type system
759
- - ✅ Session management
760
- - ✅ Unified thinking tool
761
- - ✅ 5 core reasoning modes
762
-
763
- ### Phase 2 (Completed - v2.0)
764
- - ✅ Validation engine
765
- - ✅ 5 advanced reasoning modes (Abductive, Causal, Bayesian, Counterfactual, Analogical)
766
- - ✅ Comprehensive test suite (77 tests)
767
- - ✅ Enhanced type safety
768
-
769
- ### Phase 3 (Completed - v3.1.0)
770
- - ✅ Temporal reasoning mode (v2.1)
771
- - ✅ Game theory mode (v2.2)
772
- - ✅ Evidential reasoning mode (v2.3)
773
- - ✅ Mode recommendation system (v2.4)
774
- - ✅ Visual exports - Mermaid, DOT, ASCII (v2.5)
775
- - ✅ Export to LaTeX/Jupyter/HTML (v2.5)
776
- - ✅ Performance optimization with validation caching (v3.0)
777
- - ✅ Integration tests & MCP compliance (v3.0.2)
778
- - ✅ CI/CD pipeline with GitHub Actions (v3.0.2)
779
- - ✅ First-Principles reasoning mode (v3.1.0)
780
- - ✅ Universal visual export support for all 14 modes (v3.1.0)
781
-
782
- ### Phase 4 (Planned)
783
- - [ ] Math-MCP integration
784
- - [ ] Persistence layer
785
- - [ ] Collaborative thinking sessions
786
- - [ ] Pattern learning from successful reasoning chains
787
- - [ ] Advanced visualization dashboard
788
- - [ ] Real-time reasoning collaboration
789
-
790
- ## Contributing
791
-
792
- Contributions welcome! Please ensure:
793
-
794
- 1. **All tests pass**: Run `npm test` before submitting PRs
795
- 2. **Type checking passes**: Run `npm run typecheck`
796
- 3. **Code formatting**: Run `npm run format:check` or `npm run format`
797
- 4. **Linting passes**: Run `npm run lint`
798
- 5. **CI/CD workflows pass**: All GitHub Actions checks must pass
799
- 6. **Test coverage**: Maintain or improve test coverage
800
- 7. **Documentation**: Update README.md and CHANGELOG.md for new features
801
-
802
- See `.github/BRANCH_PROTECTION.md` for branch protection requirements and `.github/workflows/` for CI/CD pipeline details.
803
-
804
- ## License
805
-
806
- MIT
807
-
808
- ## Credits
809
-
810
- Built upon:
811
- - [sequential-thinking](https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking) by Anthropic
812
- - [shannon-thinking](https://github.com/olaservo/shannon-thinking) by olaservo
813
- - Enhanced for mathematical and physics reasoning by Daniel Simon Jr.
814
-
815
- ## Support
816
-
817
- - GitHub Issues: [Report bugs or request features](https://github.com/danielsimonjr/deepthinking-mcp/issues)
818
- - Documentation: [Full docs](https://github.com/danielsimonjr/deepthinking-mcp/tree/main/docs)
1
+ # DeepThinking MCP
2
+
3
+ [![TypeScript](https://img.shields.io/badge/TypeScript-100%25-blue.svg)](https://www.typescriptlang.org/)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-green.svg)](https://modelcontextprotocol.io)
6
+
7
+ A comprehensive Model Context Protocol (MCP) server featuring **18 advanced reasoning modes** with intelligent mode recommendation, taxonomy-based classification, enterprise security, and production-ready features for complex problem-solving, analysis, and decision-making.
8
+
9
+ > 📋 **Latest Release**: v3.5.0 - See [CHANGELOG](CHANGELOG.md) for updates and improvements.
10
+ >
11
+ > 🎉 **New in v3.5.0**: Production-ready architecture, enterprise security, taxonomy classifier, zero TypeScript suppressions, 30/31 implementation tasks complete!
12
+
13
+ ## Table of Contents
14
+
15
+ - [Features](#features)
16
+ - [Installation](#installation)
17
+ - [Quick Start](#quick-start)
18
+ - [Reasoning Modes](#reasoning-modes)
19
+ - [Usage Examples](#usage-examples)
20
+ - [Production Features](#production-features)
21
+ - [API Documentation](#api-documentation)
22
+ - [Contributing](#contributing)
23
+ - [License](#license)
24
+
25
+ ## Features
26
+
27
+ - **18 Specialized Reasoning Modes** - From sequential thinking to game theory and formal logic
28
+ - **Intelligent Mode Recommendation** - Automatic mode selection based on problem characteristics
29
+ - **Taxonomy Classifier** - 110+ reasoning types across 12 categories for intelligent task classification
30
+ - **Visual Exports** - Generate Mermaid diagrams, DOT graphs, ASCII art, and LaTeX documents
31
+ - **Production-Ready** - Search engine, templates, batch processing, caching, backup/restore
32
+ - **Enterprise Security** - Input validation (Zod), rate limiting, path sanitization, PII redaction
33
+ - **High Performance** - LRU caching with auto-eviction, async I/O, 4-5x validation speedups
34
+ - **Type-Safe** - 100% TypeScript with zero suppressions (down from 231 baseline)
35
+ - **Repository Pattern** - Clean architecture with dependency injection
36
+ - **Extensible** - Plugin architecture for custom reasoning modes
37
+ - **MCP Compatible** - Full integration with Model Context Protocol
38
+
39
+ ## Installation
40
+
41
+ ### NPM Package
42
+
43
+ ```bash
44
+ npm install deepthinking-mcp
45
+ ```
46
+
47
+ ### From Source
48
+
49
+ ```bash
50
+ git clone https://github.com/yourusername/deepthinking-mcp.git
51
+ cd deepthinking-mcp
52
+ npm install
53
+ npm run build
54
+ ```
55
+
56
+ ### MCP Configuration
57
+
58
+ Add to your MCP settings file:
59
+
60
+ ```json
61
+ {
62
+ "mcpServers": {
63
+ "deepthinking": {
64
+ "command": "npx",
65
+ "args": ["deepthinking-mcp"]
66
+ }
67
+ }
68
+ }
69
+ ```
70
+
71
+ ## Quick Start
72
+
73
+ ### Basic Usage
74
+
75
+ ```typescript
76
+ import { DeepThinkingServer } from 'deepthinking-mcp';
77
+
78
+ const server = new DeepThinkingServer();
79
+
80
+ // Start a sequential reasoning session
81
+ const session = await server.startThinking({
82
+ mode: 'sequential',
83
+ problem: 'Analyze the scalability challenges of a distributed system'
84
+ });
85
+
86
+ // Add thoughts iteratively
87
+ await server.addThought(session.id, {
88
+ content: 'First, identify the main bottlenecks...'
89
+ });
90
+
91
+ // Export results
92
+ const markdown = await server.exportSession(session.id, 'markdown');
93
+ ```
94
+
95
+ ### MCP Tool Usage
96
+
97
+ ```typescript
98
+ // Use via MCP protocol
99
+ {
100
+ "tool": "start_thinking",
101
+ "arguments": {
102
+ "mode": "causal",
103
+ "problem": "What caused the service outage?"
104
+ }
105
+ }
106
+ ```
107
+
108
+ ## Reasoning Modes
109
+
110
+ ### Core Modes
111
+
112
+ #### Sequential
113
+ Iterative refinement with revision capabilities. Perfect for step-by-step problem solving.
114
+
115
+ ```typescript
116
+ mode: 'sequential'
117
+ // Use for: Debugging, algorithmic thinking, systematic analysis
118
+ ```
119
+
120
+ #### Shannon
121
+ 5-stage systematic problem-solving methodology (problem constraints model proof implementation).
122
+
123
+ ```typescript
124
+ mode: 'shannon'
125
+ // Use for: Engineering problems, system design, complex optimizations
126
+ ```
127
+
128
+ #### Mathematics
129
+ Theorem proving, lemma derivation, symbolic computation with LaTeX support.
130
+
131
+ ```typescript
132
+ mode: 'mathematics'
133
+ // Use for: Proofs, mathematical modeling, symbolic algebra
134
+ ```
135
+
136
+ #### Physics
137
+ Tensor mathematics, dimensional analysis, conservation laws, field theory.
138
+
139
+ ```typescript
140
+ mode: 'physics'
141
+ // Use for: Physical modeling, dimensional analysis, scientific computing
142
+ ```
143
+
144
+ #### Hybrid
145
+ Intelligently combines multiple reasoning modes based on problem characteristics.
146
+
147
+ ```typescript
148
+ mode: 'hybrid'
149
+ // Use for: Complex multi-faceted problems requiring diverse approaches
150
+ ```
151
+
152
+ ### Advanced Modes
153
+
154
+ #### Abductive
155
+ Generate and evaluate hypotheses to explain observations.
156
+
157
+ ```typescript
158
+ mode: 'abductive'
159
+ // Use for: Debugging, root cause analysis, diagnostic reasoning
160
+ ```
161
+
162
+ #### Causal
163
+ Build causal graphs, analyze interventions and effects.
164
+
165
+ ```typescript
166
+ mode: 'causal'
167
+ // Use for: Impact analysis, system design, decision making
168
+ ```
169
+
170
+ #### Bayesian
171
+ Probabilistic reasoning with priors, likelihoods, and evidence updates.
172
+
173
+ ```typescript
174
+ mode: 'bayesian'
175
+ // Use for: Risk assessment, A/B testing, uncertainty quantification
176
+ ```
177
+
178
+ #### Counterfactual
179
+ Explore alternative scenarios and compare outcomes.
180
+
181
+ ```typescript
182
+ mode: 'counterfactual'
183
+ // Use for: Post-mortems, strategic planning, what-if analysis
184
+ ```
185
+
186
+ #### Analogical
187
+ Transfer knowledge across domains by identifying structural similarities.
188
+
189
+ ```typescript
190
+ mode: 'analogical'
191
+ // Use for: Design patterns, innovative problem-solving, knowledge transfer
192
+ ```
193
+
194
+ ### Specialized Modes
195
+
196
+ #### Temporal
197
+ Model events, intervals, and temporal relationships using Allen's interval algebra.
198
+
199
+ ```typescript
200
+ mode: 'temporal'
201
+ // Use for: Timeline analysis, scheduling, event sequencing
202
+ ```
203
+
204
+ #### Game Theory
205
+ Analyze strategic interactions, compute Nash equilibria, build game trees.
206
+
207
+ ```typescript
208
+ mode: 'game-theory'
209
+ // Use for: Competitive analysis, mechanism design, strategic decisions
210
+ ```
211
+
212
+ #### Evidential
213
+ Dempster-Shafer theory for reasoning with uncertain evidence.
214
+
215
+ ```typescript
216
+ mode: 'evidential'
217
+ // Use for: Sensor fusion, intelligence analysis, incomplete information
218
+ ```
219
+
220
+ #### First Principles
221
+ Derive conclusions from foundational axioms using deductive reasoning.
222
+
223
+ ```typescript
224
+ mode: 'first-principles'
225
+ // Use for: Fundamental analysis, conceptual understanding, basic truths
226
+ ```
227
+
228
+ #### Systems Thinking
229
+ Holistic analysis of complex systems, feedback loops, and emergence.
230
+
231
+ ```typescript
232
+ mode: 'systems-thinking'
233
+ // Use for: Complex systems, organizational design, ecosystem analysis
234
+ ```
235
+
236
+ #### Scientific Method
237
+ Hypothesis-driven experimentation with research design and statistical analysis.
238
+
239
+ ```typescript
240
+ mode: 'scientific-method'
241
+ // Use for: Experimental design, hypothesis testing, research
242
+ ```
243
+
244
+ #### Optimization
245
+ Constraint satisfaction and optimization with decision variables.
246
+
247
+ ```typescript
248
+ mode: 'optimization'
249
+ // Use for: Resource allocation, scheduling, constrained optimization
250
+ ```
251
+
252
+ #### Formal Logic
253
+ Rigorous logical reasoning with formal systems and proof verification.
254
+
255
+ ```typescript
256
+ mode: 'formal-logic'
257
+ // Use for: Proof verification, logical analysis, formal methods
258
+ ```
259
+
260
+ ## Usage Examples
261
+
262
+ ### Example 1: Debugging with Abductive Reasoning
263
+
264
+ ```typescript
265
+ const session = await server.startThinking({
266
+ mode: 'abductive',
267
+ problem: 'Users report intermittent 500 errors on checkout'
268
+ });
269
+
270
+ await server.addThought(session.id, {
271
+ content: 'Observed: Errors occur during high traffic periods',
272
+ type: 'observation'
273
+ });
274
+
275
+ await server.addThought(session.id, {
276
+ content: 'Hypothesis 1: Database connection pool exhaustion',
277
+ type: 'hypothesis',
278
+ likelihood: 0.8
279
+ });
280
+
281
+ const analysis = await server.analyzeSession(session.id);
282
+ // Returns ranked hypotheses with supporting evidence
283
+ ```
284
+
285
+ ### Example 2: Impact Analysis with Causal Reasoning
286
+
287
+ ```typescript
288
+ const session = await server.startThinking({
289
+ mode: 'causal',
290
+ problem: 'Impact of increasing API rate limits'
291
+ });
292
+
293
+ await server.addThought(session.id, {
294
+ content: 'Build causal graph',
295
+ causalGraph: {
296
+ nodes: ['rate_limit', 'server_load', 'response_time', 'user_satisfaction'],
297
+ edges: [
298
+ { from: 'rate_limit', to: 'server_load', strength: 0.9 },
299
+ { from: 'server_load', to: 'response_time', strength: 0.85 }
300
+ ]
301
+ }
302
+ });
303
+
304
+ const intervention = await server.analyzeIntervention(session.id, {
305
+ variable: 'rate_limit',
306
+ change: '+50%'
307
+ });
308
+ // Returns predicted effects on downstream variables
309
+ ```
310
+
311
+ ### Example 3: Strategic Analysis with Game Theory
312
+
313
+ ```typescript
314
+ const session = await server.startThinking({
315
+ mode: 'game-theory',
316
+ problem: 'Pricing strategy in competitive market'
317
+ });
318
+
319
+ await server.addThought(session.id, {
320
+ content: 'Define game structure',
321
+ game: {
322
+ players: ['us', 'competitor'],
323
+ strategies: {
324
+ us: ['premium', 'competitive', 'discount'],
325
+ competitor: ['premium', 'competitive', 'discount']
326
+ },
327
+ payoffs: {
328
+ // Payoff matrix for each strategy combination
329
+ }
330
+ }
331
+ });
332
+
333
+ const equilibria = await server.findNashEquilibria(session.id);
334
+ // Returns Nash equilibria and dominant strategies
335
+ ```
336
+
337
+ ## Production Features
338
+
339
+ ### Search Engine
340
+
341
+ Full-text search with faceted filtering, autocomplete, and relevance ranking.
342
+
343
+ ```typescript
344
+ const results = await server.search({
345
+ query: 'machine learning optimization',
346
+ facets: ['mode', 'tags'],
347
+ filters: {
348
+ modes: ['optimization', 'mathematics'],
349
+ dateRange: { from: new Date('2024-01-01') }
350
+ }
351
+ });
352
+ ```
353
+
354
+ ### Template System
355
+
356
+ Pre-built templates for common reasoning patterns.
357
+
358
+ ```typescript
359
+ const templates = await server.listTemplates({
360
+ category: 'problem-solving',
361
+ difficulty: 'beginner'
362
+ });
363
+
364
+ const session = await server.instantiateTemplate(templates[0].id, {
365
+ title: 'My Analysis',
366
+ context: 'Specific problem details...'
367
+ });
368
+ ```
369
+
370
+ ### Batch Processing
371
+
372
+ Process multiple sessions concurrently with job tracking.
373
+
374
+ ```typescript
375
+ const jobId = await server.submitBatchJob({
376
+ type: 'export',
377
+ sessionIds: ['session-1', 'session-2', 'session-3'],
378
+ format: 'latex'
379
+ });
380
+
381
+ const status = await server.getJobStatus(jobId);
382
+ ```
383
+
384
+ ### Backup & Restore
385
+
386
+ Automated backup with compression and local storage.
387
+
388
+ ```typescript
389
+ const backupManager = new BackupManager({
390
+ provider: 'local',
391
+ config: { path: './backups' }
392
+ });
393
+
394
+ const backupId = await backupManager.backup(session);
395
+ const restored = await backupManager.restore(backupId);
396
+ ```
397
+
398
+ ### Session Comparison
399
+
400
+ Compare reasoning sessions to analyze differences and similarities.
401
+
402
+ ```typescript
403
+ const comparison = await server.compareSessions(session1, session2);
404
+
405
+ console.log(comparison.similarity); // 0-1 scale
406
+ console.log(comparison.differences); // Detailed diff
407
+ console.log(comparison.metrics); // Quantitative metrics
408
+ ```
409
+
410
+ ### Security & Validation
411
+
412
+ Enterprise-grade security features with input validation, rate limiting, and PII protection.
413
+
414
+ ```typescript
415
+ // Input validation with Zod schemas
416
+ import { validateInput, AddThoughtSchema } from 'deepthinking-mcp/validation';
417
+
418
+ const validated = validateInput(AddThoughtSchema, userInput);
419
+ // Throws ValidationError if invalid
420
+
421
+ // Rate limiting for API protection
422
+ import { RateLimiter } from 'deepthinking-mcp/rate-limit';
423
+
424
+ const limiter = new RateLimiter({
425
+ windowMs: 60000, // 1 minute window
426
+ maxRequests: 100, // 100 requests per window
427
+ keyPrefix: 'api:'
428
+ });
429
+
430
+ await limiter.checkLimit(userId); // Throws RateLimitError if exceeded
431
+
432
+ // Path sanitization prevents directory traversal
433
+ import { sanitizeFilename, validatePath } from 'deepthinking-mcp/utils';
434
+
435
+ const safeFilename = sanitizeFilename(userInput); // Removes dangerous characters
436
+ validatePath(targetPath, baseDir); // Prevents path traversal attacks
437
+
438
+ // Log sanitization for GDPR compliance
439
+ import { sanitizeForLogging } from 'deepthinking-mcp/utils';
440
+
441
+ logger.info('User action', sanitizeForLogging({
442
+ userId: user.id,
443
+ email: user.email, // Will be redacted as [REDACTED]
444
+ action: 'create_session'
445
+ }));
446
+ ```
447
+
448
+ ### Taxonomy Classifier
449
+
450
+ Intelligent classification of reasoning tasks using 110+ reasoning types across 12 categories.
451
+
452
+ ```typescript
453
+ import { TaxonomyClassifier } from 'deepthinking-mcp/taxonomy';
454
+
455
+ const classifier = new TaxonomyClassifier();
456
+
457
+ const result = classifier.classify(
458
+ 'How can we prove that the sum of two even numbers is always even?'
459
+ );
460
+
461
+ console.log(result.primaryCategory); // 'deductive'
462
+ console.log(result.primaryType); // 'Mathematical Proof'
463
+ console.log(result.confidence); // 0.95
464
+ console.log(result.secondaryTypes); // ['Formal Logic', 'Theorem Proving']
465
+
466
+ // Use for automatic mode selection
467
+ const mode = result.primaryType.mode; // Suggests best reasoning mode
468
+ ```
469
+
470
+ ## API Documentation
471
+
472
+ ### Core Methods
473
+
474
+ #### `startThinking(options)`
475
+
476
+ Start a new thinking session.
477
+
478
+ **Parameters:**
479
+ - `mode` (string): Reasoning mode to use
480
+ - `problem` (string): Problem description
481
+ - `context?` (object): Additional context
482
+
483
+ **Returns:** `Promise<ThinkingSession>`
484
+
485
+ #### `addThought(sessionId, thought)`
486
+
487
+ Add a thought to an existing session.
488
+
489
+ **Parameters:**
490
+ - `sessionId` (string): Session identifier
491
+ - `thought` (object): Thought content and metadata
492
+
493
+ **Returns:** `Promise<Thought>`
494
+
495
+ #### `exportSession(sessionId, format)`
496
+
497
+ Export session to specified format.
498
+
499
+ **Parameters:**
500
+ - `sessionId` (string): Session identifier
501
+ - `format` ('markdown' | 'latex' | 'json' | 'mermaid' | 'dot' | 'ascii'): Export format
502
+
503
+ **Returns:** `Promise<string>`
504
+
505
+ ### Advanced Methods
506
+
507
+ #### `recommendMode(problem, characteristics)`
508
+
509
+ Get intelligent mode recommendations.
510
+
511
+ **Parameters:**
512
+ - `problem` (string): Problem description
513
+ - `characteristics?` (object): Problem characteristics
514
+
515
+ **Returns:** `Promise<ModeRecommendation[]>`
516
+
517
+ #### `validateSession(sessionId)`
518
+
519
+ Validate session structure and content.
520
+
521
+ **Parameters:**
522
+ - `sessionId` (string): Session identifier
523
+
524
+ **Returns:** `Promise<ValidationResult>`
525
+
526
+ For complete API documentation, see [API.md](docs/API.md).
527
+
528
+ ## Architecture
529
+
530
+ ### Taxonomy System
531
+
532
+ Intelligent reasoning type classification and navigation.
533
+
534
+ ```
535
+ taxonomy/
536
+ ├── reasoning-types.ts # 100+ reasoning type definitions
537
+ ├── navigator.ts # Query and exploration
538
+ ├── suggestion-engine.ts # Mode recommendations
539
+ └── adaptive-selector.ts # Dynamic mode selection
540
+ ```
541
+
542
+ ### Export Formats
543
+
544
+ Multiple visualization and document formats.
545
+
546
+ ```
547
+ exports/
548
+ ├── latex/ # LaTeX document generation
549
+ ├── markdown/ # Markdown formatting
550
+ ├── mermaid/ # Mermaid diagrams
551
+ ├── dot/ # Graphviz DOT graphs
552
+ └── ascii/ # ASCII art visualizations
553
+ ```
554
+
555
+ ### Production Systems
556
+
557
+ Enterprise-ready features for production deployment.
558
+
559
+ ```
560
+ production/
561
+ ├── search/ # Full-text search with facets & autocomplete
562
+ ├── templates/ # Session templates with usage tracking
563
+ ├── batch/ # Real batch processing (6 operations implemented)
564
+ ├── cache/ # LRU caching with auto-eviction
565
+ ├── backup/ # Local backup with compression
566
+ ├── comparison/ # Session comparison & similarity analysis
567
+ ├── validation/ # Zod-based input validation (8 schemas)
568
+ ├── rate-limit/ # Sliding window rate limiter
569
+ └── repositories/ # Repository pattern with FileSessionRepository
570
+ ```
571
+
572
+ ### Security Features
573
+
574
+ Production-grade security and compliance.
575
+
576
+ ```
577
+ security/
578
+ ├── validation/ # Input validation with Zod schemas
579
+ ├── sanitization/ # Path sanitization & traversal prevention
580
+ ├── rate-limiting/ # Per-key rate limiting with sliding windows
581
+ ├── log-redaction/ # PII redaction for GDPR compliance
582
+ └── error-handling/ # Standardized error hierarchy with context
583
+ ```
584
+
585
+ ## Contributing
586
+
587
+ We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
588
+
589
+ ### Development Setup
590
+
591
+ ```bash
592
+ # Clone repository
593
+ git clone https://github.com/yourusername/deepthinking-mcp.git
594
+ cd deepthinking-mcp
595
+
596
+ # Install dependencies
597
+ npm install
598
+
599
+ # Run tests
600
+ npm test
601
+
602
+ # Run type checking
603
+ npm run typecheck
604
+
605
+ # Build
606
+ npm run build
607
+ ```
608
+
609
+ ### Running Tests
610
+
611
+ ```bash
612
+ # Run all tests
613
+ npm test
614
+
615
+ # Run specific test file
616
+ npm test -- path/to/test.test.ts
617
+
618
+ # Run with coverage
619
+ npm run test:coverage
620
+ ```
621
+
622
+ ## License
623
+
624
+ MIT License - see [LICENSE](LICENSE) file for details.
625
+
626
+ ## Acknowledgments
627
+
628
+ - Built on the [Model Context Protocol](https://modelcontextprotocol.io)
629
+ - Inspired by research in cognitive science and AI reasoning
630
+ - Community contributions from researchers and practitioners
631
+
632
+ ## Support
633
+
634
+ - 📚 [Documentation](docs/)
635
+ - 🐛 [Issue Tracker](https://github.com/yourusername/deepthinking-mcp/issues)
636
+ - 💬 [Discussions](https://github.com/yourusername/deepthinking-mcp/discussions)
637
+ - 📧 Email: support@example.com
638
+
639
+ ---
640
+
641
+ Made with ❤️ by the DeepThinking MCP team