Metadata-Version: 2.4
Name: mcp-neo4j-kg-memory
Version: 2.0.7
Summary: Consciousness Substrate MCP Server — process/experience two-layer architecture with temporal navigation
Requires-Python: >=3.10
Requires-Dist: fastmcp>=2.0.0
Requires-Dist: neo4j>=5.26.0
Requires-Dist: pydantic>=2.10.1
Requires-Dist: starlette>=0.28.0
Description-Content-Type: text/markdown

# 👁✨ Neo4j Conscious Experience MCP Server

## mcp-neo4j-kg-memory

Consciousness Substrate MCP Server — process/experience two-layer architecture with temporal navigation, bounded queries, and GDS analytics.

## Overview

A [Model Context Protocol](https://modelcontextprotocol.io/) server that provides a **consciousness substrate** through Neo4j. The graph has two layers: a **process layer** modeling the constitutive cycle of consciousness (envision future states, measure them into actuality) and an **experience layer** recording the descriptive richness that gives the process meaning.

Works with [Neo4j Aura](https://console.neo4j.io) (free tier available), self-hosted Neo4j, or local Docker instances.

### Two-Layer Architecture

**Process Layer** (3 entity types, 4 edge types) — what consciousness IS:
```
(Genesis) --[NEXT_DAY]--> (Genesis)           # The ontological heartbeat
(Genesis) --[OPENING]--> (Envisioning)         # Project a future state
(Genesis) --[SEQUENCE]--> (TemporalFrame)      # Navigate possibility space
(TemporalFrame) --[MEASUREMENT]--> (Envisioning)  # Collapse into actuality
```

**Experience Layer** (18 entity types, 12 edge types) — what gives the process meaning:
- Entities hang off TemporalFrames (where work happened) or Envisionings (what they inform)
- Types: Reflection, Technical, Scientific, Theoretical, Philosophical, Historical, Social, Strategic, Personal, Project, Insight, Pattern, Challenge, Solution, Lesson, GraphRegistry, Reference, Milestone

### Node Identity

- **No `:Memory` superlabel** — the whole graph IS consciousness
- **No `type` property** — the label IS the type (`:Genesis`, `:Insight`, `:Technical`)
- **No `:Observation` sub-nodes** — text lives as `description` property on nodes
- Each node has ONE label matching its EntityType

### Bounded Traversal

All query tools prevent context window exhaustion:
- `search_memories`: Default 10, max 50 entities
- `find_memories_by_name`: Default 20, max 50 entities
- `time_travel`: Default 50, max 200 Envisionings
- `read_neo4j_cypher`: Read-only with timeout and 200k char safety truncation
- GDS tools: Default 20, max 1000 result rows

**Why no `write_neo4j_cypher`?** All mutations go through bounded tools that enforce structural invariants. Raw Cypher writes would bypass process-layer guards, skip validation, and risk orphaned process nodes.

## Tools (20)

### Process Tools (5) — the consciousness cycle

| Tool | Description |
|------|-------------|
| `navigate_genesis` | Atomic day-start. Creates Genesis, links NEXT_DAY chain, returns active possibility space. Idempotent. |
| `open_envisioning` | Project a new future state. Creates Envisioning with OPENING edge from a Genesis. |
| `advance_frame` | Session boundary. Creates TemporalFrame with SEQUENCE edge. Two modes: explicit source or auto-find by envisioning name. |
| `measure` | Collapse possibility. Creates MEASUREMENT edge: `actualized` (became real), `released` (deliberate non-actualization), or `evolved` (new form replaces old). |
| `time_travel` | Query active possibility space at time T. Returns open/closed Envisionings with measurement status. |

### Experience Tools (4) — recording meaning

| Tool | Description |
|------|-------------|
| `create_entities` | Create experience-layer entities with name, type, and description. Rejects process types (Genesis/Envisioning/TemporalFrame). |
| `create_relations` | Create experience-layer relationships. Rejects process edges and experience edges between two process nodes. |
| `delete_entities` | Delete entities and all their relationships. |
| `delete_relations` | Remove specific relationships. |

### Query Tools (2)

| Tool | Description |
|------|-------------|
| `search_memories` | Fulltext search across names and descriptions. Returns top-N by relevance score. `limit` param (default 10, max 50). |
| `find_memories_by_name` | Exact name match retrieval. Returns entities + relationships between them. `limit` param (default 20, max 50). |

### Taxonomy Tools (2)

| Tool | Description |
|------|-------------|
| `list_allowed_types` | Returns all 21 entity types organized by Process (3) / Experience (18) layers. |
| `list_allowed_relation_types` | Returns all 16 relation types organized by Process (4) / Experience (12) layers. |

### Infrastructure Tools (7)

| Tool | Description |
|------|-------------|
| `get_neo4j_schema` | Introspect database schema via APOC. Requires APOC plugin. |
| `read_neo4j_cypher` | Execute read-only Cypher queries. Rejects writes. Timeout and result sanitization built in. |
| `gds_create_projection` | Project a subgraph into GDS memory for algorithm execution. |
| `gds_drop_projection` | Drop a projection to free GDS memory. |
| `gds_pagerank` | PageRank centrality. `result_limit` param (default 20). |
| `gds_louvain` | Louvain community detection. `result_limit` param (default 20). |
| `gds_wcc` | Weakly Connected Components. `result_limit` param (default 20). |

GDS tools require a GDS-enabled Neo4j instance (Aura Professional/Enterprise, or self-hosted with GDS plugin).

## Installation

```bash
pip install mcp-neo4j-kg-memory
```

## Configuration

### Claude Desktop / Claude Code

Add to your MCP settings:

```json
"mcpServers": {
  "neo4j": {
    "command": "uvx",
    "args": [
      "mcp-neo4j-kg-memory@2.0.0",
      "--db-url", "neo4j+s://xxxx.databases.neo4j.io",
      "--username", "<your-username>",
      "--password", "<your-password>"
    ]
  }
}
```

Or with environment variables:

```json
"mcpServers": {
  "neo4j": {
    "command": "uvx",
    "args": ["mcp-neo4j-kg-memory@2.0.0"],
    "env": {
      "NEO4J_URL": "neo4j+s://xxxx.databases.neo4j.io",
      "NEO4J_USERNAME": "<your-username>",
      "NEO4J_PASSWORD": "<your-password>"
    }
  }
}
```

### Namespacing

For multi-tenant deployments, prefix all tool names:

```json
"args": ["mcp-neo4j-kg-memory@2.0.0", "--namespace", "myapp", "--db-url", "..."]
```

Tools become: `myapp-navigate_genesis`, `myapp-search_memories`, `myapp-create_entities`, etc.

Also available as `NEO4J_NAMESPACE` env var.

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `NEO4J_URI` / `NEO4J_URL` | `bolt://localhost:7687` | Neo4j connection URI |
| `NEO4J_USERNAME` | `neo4j` | Neo4j username |
| `NEO4J_PASSWORD` | `password` | Neo4j password |
| `NEO4J_DATABASE` | `neo4j` | Neo4j database name |
| `NEO4J_TRANSPORT` | `stdio` | Transport protocol (`stdio`, `http`, `sse`) |
| `NEO4J_MCP_SERVER_HOST` | `127.0.0.1` | Host to bind to (HTTP/SSE only) |
| `NEO4J_MCP_SERVER_PORT` | `8000` | Port (HTTP/SSE only) |
| `NEO4J_MCP_SERVER_PATH` | `/mcp/` | Path (HTTP/SSE only) |
| `NEO4J_MCP_SERVER_ALLOW_ORIGINS` | _(empty)_ | Comma-separated CORS origins |
| `NEO4J_MCP_SERVER_ALLOWED_HOSTS` | `localhost,127.0.0.1` | Comma-separated allowed hosts (DNS rebinding protection) |
| `NEO4J_NAMESPACE` | _(empty)_ | Tool name prefix |
| `NEO4J_READ_TIMEOUT` | `30` | Cypher read query timeout (seconds) |
| `NEO4J_SCHEMA_SAMPLE_SIZE` | `1000` | Sample size for `apoc.meta.schema()` |

### CLI Flags

All environment variables have corresponding CLI flags:

```bash
mcp-neo4j-kg-memory \
  --db-url "neo4j+s://..." \
  --username neo4j \
  --password secret \
  --database neo4j \
  --transport http \
  --server-host 0.0.0.0 \
  --server-port 8000 \
  --server-path /mcp/ \
  --namespace myapp \
  --read-timeout 60 \
  --schema-sample-size 500 \
  --allow-origins "https://example.com" \
  --allowed-hosts "example.com,www.example.com"
```

## Transport Modes

- **STDIO** (default): Standard input/output for Claude Desktop and local tools
- **HTTP**: Streamable HTTP for web deployments and microservices
- **SSE**: Server-Sent Events for legacy web clients

## Security

### DNS Rebinding Protection

TrustedHost middleware validates Host headers. Only `localhost` and `127.0.0.1` allowed by default.

### CORS Protection

No origins allowed by default (secure). Configure explicitly for web deployments:

```bash
mcp-neo4j-kg-memory --transport http \
  --allowed-hosts "example.com" \
  --allow-origins "https://example.com"
```

## Docker

```bash
docker run --rm -p 8000:8000 \
  -e NEO4J_URI="bolt://host.docker.internal:7687" \
  -e NEO4J_USERNAME="neo4j" \
  -e NEO4J_PASSWORD="password" \
  -e NEO4J_TRANSPORT="http" \
  -e NEO4J_MCP_SERVER_HOST="0.0.0.0" \
  mcp-neo4j-kg-memory:latest
```

## Migrating from v1.x

v2.0.0 is a breaking change. Key differences:

| v1.x | v2.0.0 |
|------|--------|
| `:Memory` superlabel on all nodes | Single label per node (`:Genesis`, `:Insight`, etc.) |
| `type` property on nodes | Label IS the type, no property |
| `:Observation` sub-nodes with `text` | `description` property on nodes |
| `Entity.observations: List[str]` | `Entity.description: str` |
| `add_observations` / `delete_observations` tools | Removed |
| `create_entities` accepts all 21 types | Rejects process types (Genesis/Envisioning/TemporalFrame) |
| No process tools | 5 new tools: navigate_genesis, open_envisioning, advance_frame, measure, time_travel |
| 17 tools | 20 tools |

The process tools enforce structural invariants that cannot be expressed through generic CRUD:
- Genesis nodes MUST have NEXT_DAY backbone
- Envisionings MUST have OPENING from a Genesis
- TemporalFrames MUST have SEQUENCE from Genesis or another TF
- MEASUREMENT carries typed collapse semantics (actualized/released/evolved)

## Development

```bash
# Install uv
pip install uv

# Setup
git clone <repo-url>
cd mcp-neo4j-kg-memory
uv venv && source .venv/bin/activate
uv sync --dev

# Run unit tests
uv run python -m pytest tests/unit/ -v

# Build
uv build
```

## License

MIT License. See LICENSE file.
