Cognitive Diagram Navigation MCP Server
Cognitive Diagram Navigation MCP Server
An advanced MCP server implementing diagrammatic reasoning with memory-augmented spatial exploration, enabling structured chain-of-thought reasoning through visual reasoning spaces.
Overview
This MCP server combines three research domains:
Diagrammatic Reasoning (Quantomatic-inspired)
String diagrams for formal proof construction
Graph rewriting with double-pushout semantics
Pattern matching and structural transformation
Cognitive Navigation (Hippocampal-inspired)
Place cell-like encoding of reasoning points
Reward-based spatial navigation
Memory-augmented exploration of reasoning spaces
Chain-of-Thought Reasoning
Sequential logic bonds stronger than keywords
Multi-step derivation tracking
Formal proof verification
Related MCP server: krusch-sequential-mcp
Features
Core Capabilities
Diagram Creation: Build reasoning graphs from node/edge specifications
Guided Navigation: Find optimal paths through reasoning spaces
Breadth-First Exploration: Systematically discover diagram structure
Pattern Matching: Locate subgraph patterns for formal rule application
Double-Pushout (DPO) Rewriting: Apply formal structural transformations
Hierarchical Reasoning: Extract sub-diagrams into composite nodes
Reachability Analysis: Understand connectivity and distance metrics
Structural Metrics: Compute graph properties (chain length, branching factor, etc.)
Advanced Reasoning
Proof Derivation: Automatic tracking of transformation history
Proof Export: Export structured or natural language proof chains
Equivalence Checking: Verify if two diagrams are structurally identical (isomorphic)
State Space Exploration: Discover all possible diagrams reachable via a set of rules
Curiosity-Driven Exploration: Wander reasoning spaces based on "surprise" metrics
Production Features
Automatic Persistence: Diagrams are automatically saved to disk as JSON
LRU Memory Management: Efficiently manages memory by evicting least-recently used diagrams
Persistence Management: Tools to manually save, list, and delete diagrams on disk
Encrypted/Safe Randomization: Uses
SystemRandomfor non-cryptographic but robust stochasticity
Installation
Prerequisites
Python 3.12+
uv package manager (recommended)
Setup
# Clone the repository
cd cognitive-diagram-nav-mcp
# Create virtual environment with uv
uv venv
# Activate virtual environment
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install project in development mode
uv pip install -e ".[dev]"
# Or with just the MCP dependencies
uv pip install -e .Usage
Starting the Server
# Using uv
uv run src/cognitive_diagram_nav/server.py
# Or with Python directly
python src/cognitive_diagram_nav/server.pyThe server will start on stdio by default and be ready to accept MCP connections.
Configuring with Claude
Add to your Claude configuration (usually ~/.config/Claude/claude_desktop_config.json or %AppData%\Claude\claude_desktop_config.json on Windows):
{
"mcpServers": {
"cognitive-diagram-nav": {
"command": "uv",
"args": [
"--directory",
"/your-path-to/cognitive-diagram-nav-mcp",
"run",
"cognitive-diagram-nav"
]
}
}
}Replace /path/to/ with the actual path to the project.
Examples
Example 1: Create and Navigate a Simple Diagram
# This would be executed through Claude's MCP interface
# Create a simple reasoning diagram
diagram = diagram_create(
nodes=[
{"id": "premise1", "label": "Premise 1", "type": "terminal"},
{"id": "logic", "label": "Logical operation", "type": "operation"},
{"id": "conclusion", "label": "Conclusion", "type": "terminal"},
],
edges=[
{"source": "premise1", "target": "logic", "label": "input"},
{"source": "logic", "target": "conclusion", "label": "output"},
]
)
# Returns: diagram_id = "abc123..."
# Explore the diagram
result = navigate_breadth_first(
diagram_id="abc123...",
start_node="premise1",
max_depth=3
)
# Shows connected nodes and structureExample 2: Find Optimal Path
# Find shortest reasoning path
path_result = navigate_guided(
diagram_id="abc123...",
start_node="premise1",
goal_node="conclusion",
heuristic="distance"
)
# Returns path with cost and stepsExample 3: Analyze Reachability
# Understand what can be reached from a starting point
reachability = analyze_reachability(
diagram_id="abc123...",
source="premise1",
targets=["logic", "conclusion"]
)
# Shows all reachable nodes and distancesPersistence
By default, the server persists diagrams to the local filesystem:
Location:
~/.cognitive_diagram_nav/diagrams/Format: JSON with full structural and transformation metadata.
LRU Cache: Memory is managed using an LRU policy (default 100 diagrams); diagrams are seamlessly reloaded from disk on demand.
Tools
Category | Tool | Description |
Management |
| Create a new diagram |
| Load diagram structure from memory/disk | |
| Force immediate sync to disk | |
| List all diagram IDs on disk | |
| Permanently remove from memory and disk | |
Navigation |
| Level-by-level exploration |
| Target-guided shortest path | |
| Connectivity and distance analysis | |
| Curiosity-based wandering | |
Reasoning |
| Find structural patterns |
| Apply formal DPO transformation | |
| Abstract subgraph into composite node | |
| View transformation history as proof | |
| Check for isomorphism | |
| Generate state-space from rules | |
Metrics |
| Graph-theoretic complexity metrics |
| Search nodes by vector embedding | |
| Metadata and capability discovery |
Architecture
Components
┌─────────────────────────────────┐
│ MCP Client (Claude/LLM) │
└────────────────┬────────────────┘
│ JSON-RPC 2.0
┌────────────────▼────────────────┐
│ FastMCP Server │
├─────────────────────────────────┤
│ Tools Layer (MCP Interface) │
├─────────────────────────────────┤
│ GraphEngine (Core Logic) │
│ - Navigation & Exploration │
│ - DPO Rewriting & Matching │
│ - Memory & LRU Caching │
├─────────────────────────────────┤
│ StorageManager (Persistence) │
│ - JSON Serialization │
│ - Disk I/O (Async Syncing) │
├─────────────────────────────────┤
│ Models (Data Structures) │
│ - Diagram / Node / Edge │
│ - DerivationStep (Proofs) │
│ - NavigationMemory │
└─────────────────────────────────┘Key Classes
Diagram: Complete reasoning graph with nodes, edges, and transformation metadata.GraphEngine: Core reasoning engine with navigation, DPO rewriting, and LRU cache.StorageManager: Handles atomic JSON serialization and disk persistence.Pattern: Specification for structural subgraph matching.NavigationMemory: Tracks traversal history and position for curiosity-based exploration.DerivationStep: Represents a single transformation for formal proof tracking.
Development
Running Tests
# Run all tests
uv run pytest
# With coverage
uv run pytest --cov=src/cognitive_diagram_nav
# Specific test
uv run pytest tests/test_models.pyCode Quality
# Format code
uv run black src tests
# Lint
uv run ruff check src tests
# Type checking
uv run mypy srcBuilding Documentation
cd docs
uv run sphinx-build -b html . _buildRoadmap
Phase 1: Foundation ✅
Core data structures (Diagram, Pattern, NavigationMemory)
GraphEngine implementation
Basic MCP tools (create, load, navigate)
Comprehensive testing (Pytest suite)
Phase 2: Advanced Navigation ✅
Memory-augmented exploration with vectorized embeddings
Hierarchical reasoning with diagram composition
Vector-assisted search and guided navigation
Phase 3: Pattern & Rewriting ✅
Structural pattern matching
Double-pushout (DPO) rewriting mathematical engine
Phase 4: Reasoning Integration ✅
Proof derivation chain construction
Isomorphism checking (Structural Equivalence)
State-space exploration (Reasoning Space Discovery)
Phase 5: Production & Resilience ✅
Persistence layer (Atomic JSON Storage)
LRU Eviction Policy
Advanced error handling & Resilience Audit
Fully typed and lint-clean codebase
Security Considerations
Input Validation: All diagram specifications validated before processing
Resource Limits: Max diagrams and exploration depth configurable
Error Handling: Comprehensive exception handling with logging
Isolation: Each diagram is independent; no cross-contamination
Performance Notes
Scalability: Designed to handle 100s-1000s of nodes efficiently
Memory: In-memory storage; configurable max diagram count
Algorithms: Uses NetworkX for optimized graph operations
Caching: NetworkX graphs cached after initial construction
References
Kissinger & Zamdzhiev (2015): "Quantomatic: A Proof Assistant for Diagrammatic Reasoning"
Hippocampal place cells and reward-based navigation research
Chain-of-Thought prompting literature
Model Context Protocol (MCP) specification
License
MIT - See LICENSE file
Contributing
Contributions welcome! Please:
Fork the repository
Create a feature branch
Ensure tests pass and code is formatted
Submit a pull request
Contact
For questions or feedback about this MCP server, please open an issue on GitHub.
Status: Beta (v0.5.0) - Core reasoning, production persistence, and advanced DPO transformations complete.
Live Demo Trace: Creation: Built a logic diagram for $(A \land B) \to (B \land A)$. Exploration: Used the curiosity-based explore_reasoning_space to "wander" and successfully discover the reasoning path. Abstraction: Extracted the internal logic steps into a Composite Node, creating a hierarchical proof structure. Persistence: Forced a sync to disk with diagram_save and verified it with the diagram_list_saved tool. Proof: Exported a structural trace confirming the transformation history. The system handled everything—from the sub-diagram creation to the atomic disk persistence—while maintaining a valid logical structure.
Please see docs/demo_results.md for the full trace and proof.
Available Tools
18 toolsanalyze_reachabilityB
Analyze reachability from source node.
Computes all nodes reachable from source and their distances.
Args: diagram_id: ID of diagram source: Source node ID targets: Optional specific nodes to check
Returns: dict with reachable_nodes list, distances, target_reachability
Inputs: source (required), diagram_id (required), targets. Returns: object
apply_rewrite_ruleA
Apply a formal Double-Pushout (DPO) rewrite rule to a diagram.
Args: diagram_id: Target diagram ID rule_spec: Serialize RewriteRule dict with 'lhs' and 'rhs' patterns match_mapping: Mapping of rule LHS node IDs to diagram node IDs (from pattern_match)
Returns: dict containing success status and modified diagram stats
Inputs: rule_spec (required), diagram_id (required), match_mapping (required). Returns: object
check_diagram_equivalenceC
Check if two diagrams are structurally equivalent (isomorphic).
Args: diagram_id_1: First diagram ID diagram_id_2: Second diagram ID
Returns: dict with equivalence status
Inputs: diagram_id_1 (required), diagram_id_2 (required). Returns: object
compute_metricsB
Compute structural metrics on diagram.
Computes graph-theoretic properties useful for understanding complexity.
Args: diagram_id: ID of diagram metrics: List of metrics to compute. Options: - 'chain_length': Longest path in DAG - 'branching_factor': Average out-degree - 'density': Overall connectivity - 'num_nodes': Node count - 'num_edges': Edge count - 'is_dag': Whether diagram is acyclic
Returns: dict with computed metrics
Inputs: metrics (required), diagram_id (required). Returns: object
diagram_createA
Create a new diagram with specified nodes and edges.
A diagram is the primary unit of reasoning, representing a directed acyclic graph.
Args: nodes: List of node specifications. Each must have: - id: Unique identifier (string) - label: Human-readable label (string) - type: One of 'operation', 'terminal', 'control', 'composite' - metadata: Optional dict of additional properties - embedding: Optional list of floats for semantic search
edges: List of edge specifications. Each must have:
- source: Source node ID (string)
- target: Target node ID (string)
- label: Relationship label (string)
- weight: Optional numeric weight (default: 1.0)
- properties: Optional dict of additional propertiesReturns: dict with diagram_id, num_nodes, num_edges, validity
Inputs: edges (required), nodes (required). Returns: object
diagram_deleteB
Delete a diagram from both active memory and persisted storage.
Args: diagram_id: ID of diagram to delete
Returns: dict containing success status
Inputs: diagram_id (required). Returns: object
diagram_extractC
Extract a subgraph into a composite node.
Args: diagram_id: Source diagram ID node_ids: List of nodes to extract composite_label: Label for the new composite node
Returns: dict containing success status, new diagram ID, and new composite node ID
Inputs: node_ids (required), diagram_id (required), composite_label. Returns: object
diagram_list_savedA
List all diagram IDs currently persisted on disk.
Returns: dict with list of saved diagram IDs
Inputs: no named parameters. Returns: object
diagram_loadC
Load and return complete diagram structure.
Args: diagram_id: ID of diagram to load
Returns: dict with full diagram structure or error
Inputs: diagram_id (required). Returns: object
diagram_saveC
Force an immediate sync of a specific diagram to disk.
Args: diagram_id: ID of diagram to save
Returns: dict containing success status
Inputs: diagram_id (required). Returns: object
explore_equivalent_statesA
Explore alternative diagram states reachable via rewrite rules.
Constructs a meta-graph of structurally unique diagram configurations.
Args: diagram_id: Starting diagram ID rules: List of serialized RewriteRule dicts max_depth: Maximum BFS depth max_states: Maximum number of unique states to discover
Returns: dict with metadata about discovery and unique states
Inputs: rules (required), diagram_id (required), max_depth, max_states. Returns: object
explore_reasoning_spaceB
Wander the diagram based on a curiosity metric using NavigationMemory.
Prioritizes nodes that have a low exploration_count.
Args: diagram_id: ID of diagram start_node: Starting node ID steps: Number of steps to take (default: 5) temperature: Exploration factor (0.0 = greedy unvisited, 1.0 = highly random)
Returns: dict with path, steps_taken, and updated exploration_counts
Inputs: diagram_id (required), start_node (required), steps, temperature. Returns: object
export_proofB
Export a diagram's transformation history as a structured proof.
Args: diagram_id: ID of diagram to export proof for output_format: 'text' (natural language) or 'json' (structured)
Returns: dict with proof steps and metadata
Inputs: diagram_id (required), output_format. Returns: object
node_semantic_searchB
Search for nodes semantically similar to a target embedding.
Args: diagram_id: ID of diagram target_embedding: The embedding vector (list of floats) to compare against top_k: Maximum number of results to return (default: 5) threshold: Minimum cosine similarity score to include (default: 0.5)
Returns: dict with similar nodes and similarity scores
Inputs: diagram_id (required), target_embedding (required), top_k, threshold. Returns: object
pattern_matchB
Find all pattern matches within a diagram.
Implements subgraph matching to locate structural patterns.
Args: diagram_id: ID of diagram to search pattern: Pattern spec with 'nodes' (dict) and 'edges' (list) Each edge tuple: (source_id, target_id, constraints_dict)
Returns: dict with matches list, num_matches
Inputs: pattern (required), diagram_id (required). Returns: object
server_infoA
Return server capabilities and status information.
Returns: dict with version, capabilities, active_diagrams, resources
Inputs: no named parameters. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 18 tools
Most tools have distinct purposes, but there is a cluster of overlapping traversal tools (navigate_breadth_first, navigate_guided, analyze_reachability, explore_reasoning_space) and two 'explore' tools (explore_equivalent_states, explore_reasoning_space) that could be confused. Pattern_match vs check_diagram_equivalence and compute_metrics vs analyze_reachability also have fuzzy boundaries, though descriptions help distinguish them.
Most names follow a verb_noun pattern, but prefixing is inconsistent: some tools use a 'diagram_' prefix (diagram_load, diagram_save, diagram_create, diagram_delete, diagram_list_saved), while others in the same domain omit it (pattern_match, export_proof, compute_metrics). Readable but not predictable.
18 tools is on the heavy side for what is essentially a graph/diagram reasoning server, and the traversal/exploration family feels padded with several variants (BFS, guided, curiosity, reachability) that partially duplicate each other.
Strong lifecycle coverage: create, load, save, list, delete, plus analysis (metrics, reachability, equivalence, pattern match), navigation, rewrite rules, semantic search, and proof export. The main gap is no direct node/edge-level edit/add/remove operation outside of rewrite rules, which agents may occasionally need.
Maintenance
Related MCP Connectors
Cloud-hosted MCP server for durable AI memory
Hosted Screenshots MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
MCP server teaching AI agents to implement TideCloak: auth, E2EE, IGA, security analysis
Capability registry for the agentic economy. Semantic search over verified MCP server listings.
Related MCP Servers
- AlicenseAqualityDmaintenanceAn MCP server that enhances sequential thinking with meta-cognitive capabilities including confidence tracking, hypothesis testing, and organized memory storage through graph-based libraries and structured JSON documents.1012MIT
- AlicenseBqualityDmaintenanceAn advanced MCP server for reflective chain-of-thought with Semantic Plausibility Gating and DBOS PostgreSQL persistence.110 npmMIT
- AlicenseNot gradedqualityBmaintenanceAn MCP server that structures AI reasoning as directed acyclic graphs of semantic thoughts, enabling explicit dependencies, assumption tracking, and cascade invalidation for transparent decision-making.7 npm5MIT
- AlicenseAqualityDmaintenanceAn MCP server that gives LLMs structured, verifiable memory by storing facts in a knowledge graph and enabling logic-based reasoning through natural dialogue.143MIT