/ Каталог / Песочница / Neo4j
● Официальный neo4j-contrib 🔑 Нужен свой ключ

Neo4j

автор neo4j-contrib · neo4j-contrib/mcp-neo4j

Query and evolve a Neo4j graph in Cypher via Claude — schema introspection plus read/write Cypher with guardrails.

Neo4j Labs' MCP collection covers Cypher execution (mcp-neo4j-cypher), schema management, and Aura admin. The default cypher server exposes read and write Cypher against any Bolt endpoint. Pair with a read-only Neo4j user for safe production exploration.

Зачем использовать

Ключевые функции

Живое демо

Как выглядит на практике

neo4j.replay ▶ готово
0/0

Установка

Выберите клиент

~/Library/Application Support/Claude/claude_desktop_config.json  · Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "neo4j": {
      "command": "uvx",
      "args": [
        "mcp-neo4j-cypher"
      ]
    }
  }
}

Откройте Claude Desktop → Settings → Developer → Edit Config. Перезапустите после сохранения.

~/.cursor/mcp.json · .cursor/mcp.json
{
  "mcpServers": {
    "neo4j": {
      "command": "uvx",
      "args": [
        "mcp-neo4j-cypher"
      ]
    }
  }
}

Cursor использует ту же схему mcpServers, что и Claude Desktop. Конфиг проекта приоритетнее глобального.

VS Code → Cline → MCP Servers → Edit
{
  "mcpServers": {
    "neo4j": {
      "command": "uvx",
      "args": [
        "mcp-neo4j-cypher"
      ]
    }
  }
}

Щёлкните значок MCP Servers на боковой панели Cline, затем "Edit Configuration".

~/.codeium/windsurf/mcp_config.json
{
  "mcpServers": {
    "neo4j": {
      "command": "uvx",
      "args": [
        "mcp-neo4j-cypher"
      ]
    }
  }
}

Тот же формат, что и Claude Desktop. Перезапустите Windsurf для применения.

~/.continue/config.json
{
  "mcpServers": [
    {
      "name": "neo4j",
      "command": "uvx",
      "args": [
        "mcp-neo4j-cypher"
      ]
    }
  ]
}

Continue использует массив объектов серверов, а не map.

~/.config/zed/settings.json
{
  "context_servers": {
    "neo4j": {
      "command": {
        "path": "uvx",
        "args": [
          "mcp-neo4j-cypher"
        ]
      }
    }
  }
}

Добавьте в context_servers. Zed перезагружается автоматически.

claude mcp add neo4j -- uvx mcp-neo4j-cypher

Однострочная команда. Проверить: claude mcp list. Удалить: claude mcp remove.

Сценарии использования

Реальные сценарии: Neo4j

Explore an unfamiliar graph schema in 5 minutes

👤 Engineers / analysts inheriting a Neo4j DB ⏱ ~15 min beginner

Когда использовать: You got handed a graph DB with no docs. You need a mental model before you can write useful queries.

Предварительные требования
  • Neo4j Bolt URL + user/passwordNEO4J_URI=bolt://host:7687, NEO4J_USERNAME, NEO4J_PASSWORD
  • Read-only user recommended for explorationCREATE USER claude SET PASSWORD '...' SET ROLES reader
Поток
  1. Get schema overview
    Call get_neo4j_schema. Summarize node labels, relationship types, and the most common (label)-[rel]->(label) patterns.✓ Скопировано
    → Schema summary with sample triples
  2. Sample representative nodes
    For the 3 most common labels, MATCH (n:Label) RETURN n LIMIT 3 each. Describe what each label seems to represent.✓ Скопировано
    → Semantic descriptions of labels
  3. Draw the likely ER model
    Based on schema + samples, describe in prose the 'entity' story of this graph. What's the main object, what connects to it, what's peripheral?✓ Скопировано
    → Clear domain model description

Итог: A one-page domain model you can validate with the original authors.

Подводные камни
  • Sampling tiny graphs gives misleading patterns — Also MATCH (n)-[r]->() RETURN type(r), count(*) to see which rels dominate
Сочетать с: filesystem

Write graph queries to detect fraud rings

👤 Risk / fraud analysts ⏱ ~40 min advanced

Когда использовать: You suspect shared-device or shared-address fraud rings across accounts.

Предварительные требования
  • Graph with User, Device, Address, Payment nodes and :USED, :LIVES_AT, :PAID relationships — Typical fraud-graph shape
Поток
  1. Find shared devices
    Find devices used by 3+ different users in the last 30 days. Return device_id + list of user_ids + last-used ts per pair.✓ Скопировано
    → Ring candidates
  2. Score by connected-component size
    Using GDS or pure Cypher, compute connected components over User-(:USED)-Device-(:USED)-User. Return top 10 components by size.✓ Скопировано
    → Suspicious clusters
  3. Produce an actionable list
    For each top cluster, list distinct users, total transaction volume, and earliest/latest activity. Flag clusters > $10k as high-priority review.✓ Скопировано
    → Analyst queue entries

Итог: A prioritized fraud-review queue with the exact Cypher preserved.

Подводные камни
  • Naïve traversals blow up on hubs (shared public wifi device with 10k users) — Cap depth and filter out hub nodes by degree before traversing
Сочетать с: postgres

Prototype a content recommendation query

👤 Product engineers building 'users who also liked' ⏱ ~30 min intermediate

Когда использовать: You have User-LIKED->Item and want to recommend items from similar users.

Поток
  1. Pick a user and find neighbors
    For user <id>, find 20 users who share the most LIKED items. Return user_id and overlap count.✓ Скопировано
    → Similar users ranked
  2. Recommend items those users liked
    For those top 20 similar users, list items they liked that <id> has NOT liked. Rank by number of similar users who liked it.✓ Скопировано
    → Top-N recommendations
  3. Turn it into a reusable query
    Parameterize as a callable Cypher with $user_id; add indexes needed for speed.✓ Скопировано
    → Production-ready query + CREATE INDEX statements

Итог: A working collaborative-filtering query, fast enough to serve online.

Подводные камни
  • Forgetting an index on :User(id) makes startup queries linear — CREATE INDEX FOR (u:User) ON (u.id) and EXPLAIN to confirm it's used

Load relational data into Neo4j from a staging table

👤 Data engineers moving from SQL to graph ⏱ ~40 min advanced

Когда использовать: You have users + follows in Postgres and want a graph representation.

Предварительные требования
  • Writable Neo4j user — Role with CREATE on the target database
Поток
  1. Plan the node/edge mapping
    Given tables users(id, name) and follows(from_id, to_id), propose the Neo4j model. Label(s)? Relationship direction?✓ Скопировано
    → (:User {id,name})-[:FOLLOWS]->(:User)
  2. Create constraints first
    Generate CREATE CONSTRAINT FOR (u:User) REQUIRE u.id IS UNIQUE. Run it.✓ Скопировано
    → Constraint created
  3. Bulk load with MERGE
    From the provided user rows, run UNWIND $rows AS r MERGE (:User {id:r.id}) ... then follows with MERGE (a)-[:FOLLOWS]->(b). Batch 10k at a time.✓ Скопировано
    → All rows loaded idempotently

Итог: A re-runnable ETL that loads your relational data into a graph shape.

Подводные камни
  • CREATE instead of MERGE creates duplicate nodes on re-run — Always MERGE for upserts, and require a uniqueness constraint before bulk MERGE for speed
Сочетать с: postgres

Answer natural-language questions over a knowledge graph

👤 Internal teams with a domain KG ⏱ ~25 min intermediate

Когда использовать: You built a small ontology (products, features, customers) and want Claude to answer 'which customers use feature X' without learning Cypher.

Поток
  1. Ground Claude in the schema
    Here's the schema [paste get_neo4j_schema output]. From now on, translate my questions to Cypher before running them.✓ Скопировано
    → Claude echoes the schema understanding
  2. Ask a question, get Cypher + answer
    Which customers use feature 'export-csv' in the last quarter?✓ Скопировано
    → Cypher shown + result table
  3. Refine when Cypher is wrong
    That Cypher missed the :USED relationship to Session. Fix it to go through sessions.✓ Скопировано
    → Corrected Cypher re-run

Итог: A lightweight NL-to-Cypher interface for non-technical teammates.

Подводные камни
  • Claude invents labels that don't exist — Pin it: 'only use labels/rels from the provided schema; otherwise say unknown'

Комбинации

Сочетайте с другими MCP — эффект x10

neo4j + postgres

Sync relational data to a graph representation

Pull users + follows from Postgres, then MERGE into Neo4j as (:User)-[:FOLLOWS]->(:User).✓ Скопировано
neo4j + qdrant

Graph-enhanced RAG: use Qdrant for semantic recall, Neo4j for precise relationships

Qdrant finds docs similar to the question; then traverse Neo4j from matched entities to pull structured facts for the answer.✓ Скопировано
neo4j + filesystem

Export a Cypher-generated report as CSV/Markdown

Run the fraud-ring Cypher, export top 50 clusters as /reports/fraud-<date>.csv.✓ Скопировано

Инструменты

Что предоставляет этот MCP

ИнструментВходные данныеКогда вызыватьСтоимость
get_neo4j_schema Always first in a new session free
read_neo4j_cypher query: str, params?: object Any MATCH / RETURN — read-only free
write_neo4j_cypher query: str, params?: object CREATE/MERGE/SET/DELETE — mutations free

Стоимость и лимиты

Во что обходится

Квота API
Bounded by your Neo4j instance. Aura Free: 200k nodes/400k rels.
Токенов на вызов
Schema: ~500 tokens. Query results: depends on rows+properties.
Деньги
Free for Community / self-hosted. Aura Free tier exists. Aura paid from ~$65/mo.
Совет
Always EXPLAIN first on large graphs; a missing index on a startup label turns a 5ms query into a 5min scan.

Безопасность

Права, секреты, радиус поражения

Минимальные скоупы: reader role for read-only exploration
Хранение учётных данных: NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD in env
Исходящий трафик: Direct Bolt connection to your Neo4j (self-hosted or Aura)
Никогда не давайте: admin role PUBLIC write access

Устранение неполадок

Частые ошибки и исправления

ServiceUnavailable: Connection refused

Neo4j not running or wrong Bolt port (default 7687). Check with cypher-shell -a bolt://host:7687.

Проверить: nc -zv host 7687
Neo.ClientError.Security.Unauthorized

Wrong username/password. Reset via CALL dbms.security.changePassword('new') from an admin session.

Neo.ClientError.Statement.SyntaxError

Claude's Cypher has a typo — paste the exact error, ask for a corrected query.

Writes fail: Write operation not allowed in read-only mode

You're connected with a reader role; switch to a user with WRITE or use a separate writer connection.

Альтернативы

Neo4j в сравнении

АльтернативаКогда использоватьКомпромисс
Memgraph MCPYou need streaming graph analytics; Memgraph is Cypher-compatibleSmaller ecosystem, fewer hosted options
ArangoDB MCPYou want multi-model (graph + document + KV)AQL instead of Cypher; learning curve
Postgres + Apache AGEYou're mostly relational with some graph needsGraph performance worse than native Neo4j on large traversals

Ещё

Ресурсы

📖 Читать официальный README на GitHub

🐙 Открытые задачи

🔍 Все 400+ MCP-серверов и Skills