You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hugegraph.apache.org by ji...@apache.org on 2026/09/26 12:27:28 UTC
(hugegraph-ai) 01/11: feat(mcp): add server and workspace integration
This is an automated email from the ASF dual-hosted git repository.
imbajin pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/hugegraph-ai.git
commit 949365078bbd6a1e6f300dd268951ad692823681
Author: duyifeng01 <du...@baidu.com>
AuthorDate: Fri Aug 14 14:32:06 2026 +0800
feat(mcp): add server and workspace integration
- Introduce the MCP server, configuration, and tool modules.
- Integrate the standalone package into development workflows.
- Preserve the existing repository workflow configuration.
Co-authored-by: github-actions[bot] <gi...@users.noreply.github.com>
---
.github/workflows/ruff.yml | 40 -
.gitignore | 3 +
docker/docker-compose-network.yml | 2 +-
hugegraph-mcp/README.md | 255 +++
hugegraph-mcp/README.zh-CN.md | 257 +++
hugegraph-mcp/docs/p0a-integration-checklist.md | 828 ++++++++
hugegraph-mcp/hugegraph_mcp/__init__.py | 12 +
hugegraph-mcp/hugegraph_mcp/config.py | 243 +++
.../hugegraph_mcp/confirmable_workflow.py | 227 +++
hugegraph-mcp/hugegraph_mcp/confirmation_store.py | 245 +++
hugegraph-mcp/hugegraph_mcp/envelope.py | 260 +++
hugegraph-mcp/hugegraph_mcp/error_mapping.py | 132 ++
hugegraph-mcp/hugegraph_mcp/gremlin_policy.py | 371 ++++
hugegraph-mcp/hugegraph_mcp/gremlin_safety.py | 34 +
hugegraph-mcp/hugegraph_mcp/gremlin_tools.py | 499 +++++
hugegraph-mcp/hugegraph_mcp/guard.py | 85 +
hugegraph-mcp/hugegraph_mcp/hugegraph_ai_client.py | 299 +++
hugegraph-mcp/hugegraph_mcp/hugegraph_client.py | 39 +
hugegraph-mcp/hugegraph_mcp/plan_hash.py | 209 ++
hugegraph-mcp/hugegraph_mcp/schema_tools.py | 125 ++
hugegraph-mcp/hugegraph_mcp/server.py | 613 ++++++
hugegraph-mcp/hugegraph_mcp/tools/__init__.py | 16 +
.../hugegraph_mcp/tools/extract_graph_data.py | 207 ++
.../hugegraph_mcp/tools/generate_gremlin.py | 197 ++
.../hugegraph_mcp/tools/graph_data_execute.py | 805 ++++++++
.../hugegraph_mcp/tools/graph_data_gremlin.py | 140 ++
.../hugegraph_mcp/tools/graph_data_mapping.py | 195 ++
.../hugegraph_mcp/tools/graph_data_validate.py | 492 +++++
.../hugegraph_mcp/tools/ingest_graph_data.py | 1337 +++++++++++++
hugegraph-mcp/hugegraph_mcp/tools/inspect_graph.py | 199 ++
.../hugegraph_mcp/tools/inspect_schema.py | 291 +++
hugegraph-mcp/hugegraph_mcp/tools/live_schema.py | 39 +
.../hugegraph_mcp/tools/manage_graph_data.py | 411 ++++
hugegraph-mcp/hugegraph_mcp/tools/manage_schema.py | 1592 ++++++++++++++++
.../hugegraph_mcp/tools/mutate_graph_properties.py | 760 ++++++++
.../hugegraph_mcp/tools/query_graph_data.py | 480 +++++
.../hugegraph_mcp/tools/refresh_vid_embeddings.py | 88 +
hugegraph-mcp/hugegraph_mcp/tools/schema_utils.py | 205 ++
hugegraph-mcp/pyproject.toml | 60 +
hugegraph-mcp/tests/conftest.py | 22 +
.../tests/integration/test_real_write_path.py | 844 +++++++++
hugegraph-mcp/tests/test_config.py | 299 +++
hugegraph-mcp/tests/test_envelope.py | 124 ++
hugegraph-mcp/tests/test_error_handling.py | 546 ++++++
hugegraph-mcp/tests/test_execute_gremlin_read.py | 215 +++
hugegraph-mcp/tests/test_execute_gremlin_write.py | 78 +
hugegraph-mcp/tests/test_extract_graph_data.py | 148 ++
hugegraph-mcp/tests/test_generate_gremlin.py | 343 ++++
hugegraph-mcp/tests/test_get_live_schema.py | 162 ++
hugegraph-mcp/tests/test_gremlin_policy.py | 175 ++
hugegraph-mcp/tests/test_gremlin_safety.py | 110 ++
hugegraph-mcp/tests/test_guard.py | 76 +
hugegraph-mcp/tests/test_hugegraph_ai_client.py | 506 +++++
hugegraph-mcp/tests/test_import_graph_data_tool.py | 182 ++
hugegraph-mcp/tests/test_ingest_graph_data.py | 1306 +++++++++++++
hugegraph-mcp/tests/test_inspect_graph.py | 349 ++++
hugegraph-mcp/tests/test_inspect_schema_tool.py | 119 ++
hugegraph-mcp/tests/test_manage_graph_data.py | 1838 ++++++++++++++++++
hugegraph-mcp/tests/test_manage_schema.py | 1998 ++++++++++++++++++++
.../tests/test_mutate_graph_properties_tool.py | 780 ++++++++
hugegraph-mcp/tests/test_plan_hash.py | 714 +++++++
hugegraph-mcp/tests/test_query_graph_data.py | 37 +
hugegraph-mcp/tests/test_query_graph_data_tool.py | 437 +++++
hugegraph-mcp/tests/test_readonly_mode.py | 140 ++
hugegraph-mcp/tests/test_refresh_vid_embeddings.py | 69 +
hugegraph-mcp/tests/test_schema_utils.py | 140 ++
hugegraph-mcp/tests/test_v1_stable_tools.py | 539 ++++++
pyproject.toml | 11 +-
68 files changed, 24556 insertions(+), 43 deletions(-)
diff --git a/.github/workflows/ruff.yml b/.github/workflows/ruff.yml
index f88bd856..da3c3172 100644
--- a/.github/workflows/ruff.yml
+++ b/.github/workflows/ruff.yml
@@ -49,43 +49,3 @@ jobs:
- name: Lint code with Ruff
run: |
uv run ruff check .
-
- ty-check:
- runs-on: ubuntu-latest
- strategy:
- matrix:
- python-version: ["3.10", "3.11"] # hugegraph-llm requires <3.12
-
- steps:
- - uses: actions/checkout@v4
-
- - name: Setup Python ${{ matrix.python-version }}
- uses: actions/setup-python@v5
- with:
- python-version: ${{ matrix.python-version }}
-
- - name: Install uv
- run: |
- curl -LsSf https://astral.sh/uv/install.sh | sh
- echo "$HOME/.cargo/bin" >> $GITHUB_PATH
-
- - name: Cache dependencies
- id: cache-deps
- uses: actions/cache@v4
- with:
- path: |
- ~/.cache/uv
- ~/.cache/pip
- key: ${{ runner.os }}-uv-${{ matrix.python-version }}-${{ hashFiles('**/pyproject.toml') }}
- restore-keys: |
- ${{ runner.os }}-uv-${{ matrix.python-version }}-
-
- - name: Install dev + runtime extras
- run: |
- uv sync --extra dev --extra llm --extra python-client
-
- - name: Type check with ty (non-blocking)
- run: uv run ty check hugegraph-llm/src hugegraph-python-client/src
- continue-on-error: true
- # TODO: extend scope to hugegraph-ml once heavy optional deps (DGL, PyTorch) are handled
- # TODO: add graph-mcp once the module is introduced
diff --git a/.gitignore b/.gitignore
index 58bf72ff..dc56cc31 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,6 +41,9 @@ MANIFEST
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
+# Exception: allow .spec/ directory to be tracked
+!.spec/
+!.spec/**
# Installer logs
pip-log.txt
diff --git a/docker/docker-compose-network.yml b/docker/docker-compose-network.yml
index 43c3aecc..42e99fc4 100644
--- a/docker/docker-compose-network.yml
+++ b/docker/docker-compose-network.yml
@@ -5,7 +5,7 @@ networks:
services:
# HugeGraph Server
hugegraph-server:
- image: hugegraph/hugegraph
+ image: hugegraph/hugegraph:1.7.0
container_name: server
restart: unless-stopped
ports:
diff --git a/hugegraph-mcp/README.md b/hugegraph-mcp/README.md
new file mode 100644
index 00000000..90ed2e73
--- /dev/null
+++ b/hugegraph-mcp/README.md
@@ -0,0 +1,255 @@
+# HugeGraph MCP
+
+[中文文档](README.zh-CN.md)
+
+HugeGraph MCP is a Model Context Protocol server for HugeGraph. It is designed as a safe, controlled, thin adapter layer: it exposes a small set of stable tools and centralizes configuration, permission checks, read-only Gremlin validation, the dry-run/confirm write safety chain, and the unified response envelope.
+
+**Requires HugeGraph Server >= 1.7.0** (MCP defaults to `graphspace=DEFAULT` and relies on graphspace-scoped API routes that are not available in older versions).
+
+## Quick Start
+
+Install [uv](https://docs.astral.sh/uv/getting-started/installation/) if it is not already available. Then, from the repository root, install the MCP extra and start the stdio server:
+
+```bash
+uv sync --extra mcp --extra dev
+
+export HUGEGRAPH_URL=http://127.0.0.1:8080
+export HUGEGRAPH_GRAPH_PATH=DEFAULT/hugegraph
+export HUGEGRAPH_USER=admin
+export HUGEGRAPH_PASSWORD=admin
+export HUGEGRAPH_MCP_READONLY=true
+
+uv run --project hugegraph-mcp hugegraph-mcp
+```
+
+The process speaks MCP JSON-RPC on stdout; connect it from an MCP client. Keep
+`HUGEGRAPH_MCP_READONLY=true` unless you have a deliberate write-validation
+plan. The default toolset is `v2_core`; set `HUGEGRAPH_MCP_TOOLSET=v1` before
+startup when an older client requires the 10-tool compatibility contract.
+
+## Developer Notes
+
+### Design Boundary
+
+HugeGraph MCP does not turn MCP into a second business kernel. The MCP layer is responsible for:
+
+- Exposing stable MCP tool interfaces
+- Reading runtime configuration
+- Enforcing permission and readonly guards
+- Validating whether Gremlin is read-only
+- Generating and validating `plan_hash`
+- Returning a unified response envelope
+- Forwarding AI capabilities to HugeGraph-AI, or graph reads/writes to HugeGraph Server
+
+### Public Tool Surface
+
+The default `v2_core` toolset registers 13 MCP tools: 11 normal user-facing stable tools plus 2 admin/debug tools that are registered but blocked by default.
+
+The normal user-facing stable tools are:
+
+- `inspect_graph_tool`
+- `inspect_schema_tool`
+- `query_graph_data_tool`
+- `generate_gremlin_tool`
+- `execute_gremlin_read_tool`
+- `extract_graph_data_tool`
+- `design_schema_tool`
+- `apply_schema_tool`
+- `mutate_graph_properties_tool`
+- `import_graph_data_tool`
+- `delete_graph_data_tool`
+
+These tools are still registered in MCP, but they are admin/debug capabilities and are blocked by default when `HUGEGRAPH_MCP_ADMIN_MODE=false`. Write-capable admin tools also require `HUGEGRAPH_MCP_READONLY=false`:
+
+- `execute_gremlin_write_tool`
+- `refresh_vid_embeddings_tool`
+
+`execute_gremlin_write_tool` is the sole break-glass exception to the write safety chain. It executes arbitrary Gremlin writes without a preview, dry-run, plan hash, or confirmation. Enable it only on an isolated transport available to trusted administrators; do not enable it on a shared agent or client endpoint.
+
+### Toolset Selection
+
+`HUGEGRAPH_MCP_TOOLSET` controls the public tool contract:
+
+| Value | Tools | Intended use |
+|-------|------:|--------------|
+| `v1` | 10 | Compatibility mode for old clients; exposes the original stable tools and admin/debug tools, hides the three `v2_core` tools, and keeps `apply_schema_tool(mode="apply")` disabled |
+| `v2_core` | 13 | New deployment default; exposes the V1 tools plus `inspect_schema_tool`, `query_graph_data_tool`, and `mutate_graph_properties_tool`, and enables the P0a schema create apply path |
+
+When `HUGEGRAPH_MCP_TOOLSET` is unset, the server defaults to `v2_core`. Any value other than exact `v1` is treated as `v2_core`.
+Toolset selection is applied when the MCP server starts and registers tools; restart the MCP server after changing this variable.
+
+### Unified Response Envelope
+
+High-level tools return a unified envelope:
+
+```json
+{
+ "ok": true,
+ "data": {},
+ "error": null,
+ "warnings": [],
+ "next_actions": [],
+ "meta": {
+ "request_id": "req-...",
+ "graph": "hugegraph",
+ "graphspace": "DEFAULT",
+ "readonly": true,
+ "duration_ms": 12.3
+ }
+}
+```
+
+When a call fails, `ok=false` and `error` uses this structure:
+
+```json
+{
+ "type": "READONLY_VIOLATION",
+ "message": "DATA_WRITE capability is disabled in read-only mode",
+ "suggestion": "Disable HUGEGRAPH_MCP_READONLY to allow this operation.",
+ "retryable": false,
+ "source": "hugegraph-mcp",
+ "details": {}
+}
+```
+
+## Tool Reference
+
+### User-Facing Tool Overview
+
+| Tool | Description |
+|------|-------------|
+| `inspect_graph_tool` | Inspect HugeGraph Server status, schema summary, vertex/edge counts, readonly state, AI availability, and current MCP tool contract fields |
+| `inspect_schema_tool` | Inspect schema objects, relations, and index labels; supports filtering by property key, vertex label, edge label, or index label |
+| `query_graph_data_tool` | Query vertices or edges by typed operations (`get_by_id`, `get_by_ids`, `page`, `condition`) with explicit limits and no Gremlin full-scan fallback |
+| `generate_gremlin_tool` | Generate Gremlin from natural language; defaults to generation only; `execute=true` still requires read-only validation |
+| `execute_gremlin_read_tool` | Execute read-only Gremlin queries; rejects queries whose safety cannot be confirmed and supports `limit_policy` for unbounded reads |
+| `extract_graph_data_tool` | Extract candidate graph data from natural language text and return vertex/edge structures without writing to HugeGraph |
+| `import_graph_data_tool` | Structured graph data import entrypoint; real writes must pass `dry_run -> plan_hash -> confirm` |
+| `delete_graph_data_tool` | Controlled delete entrypoint; supports only exact vertex or edge deletion, not conditional bulk delete or cascade delete |
+| `design_schema_tool` | Provide schema design guidance from proposed schema operations without modifying the database |
+| `apply_schema_tool` | Validate schema operations and dry-run the P0a apply scope; in `v2_core`, dry-run and confirmed `apply` support only `create_property_key`, `create_vertex_label`, and `create_edge_label`; in `v1`, real `apply` remains disabled |
+| `mutate_graph_properties_tool` | Append or eliminate properties on one exact vertex or edge; both operations require `dry_run -> plan_hash -> confirm` and reject stale targets |
+| `execute_gremlin_write_tool` | Execute direct Gremlin writes; disabled by default and available only when `HUGEGRAPH_MCP_ADMIN_MODE=true` and `HUGEGRAPH_MCP_READONLY=false` |
+| `refresh_vid_embeddings_tool` | Refresh VID embeddings and mutate index state; disabled by default and available only when `HUGEGRAPH_MCP_ADMIN_MODE=true` and `HUGEGRAPH_MCP_READONLY=false` |
+
+The old `query_graph_tool`, `manage_schema_tool`, and `manage_graph_data_tool` are no longer exposed as user interfaces. New integrations should use the stable tools listed above.
+
+## Write Safety Chain
+
+All normal user-facing write operations must follow this chain. The admin-only `execute_gremlin_write_tool` break-glass exception described above does not:
+
+```text
+dry_run=true
+ -> user/agent reviews preview, warnings, matched_count, mutation_summary
+ -> records plan_hash, nonce, expires_at
+ -> dry_run=false + confirm=true + original payload + plan_hash + nonce + expires_at
+ -> MCP revalidates target, permission, schema, payload digest, and expiry
+ -> executes the write
+ -> returns write/delete results and failure details
+```
+
+`plan_hash` is not just a payload hash. It binds at least:
+
+- Tool name
+- Operation mode
+- Graph URL
+- Graph name
+- Graph space
+- MCP readonly state
+- Current schema hash
+- Normalized payload digest
+- Nonce
+- Expiry
+
+The confirm phase must fully revalidate the plan. If the dry-run result expires, the target graph changes, the schema changes, the payload changes, or permissions change, confirm must fail and require a new dry run.
+
+### Import Semantics
+
+`import_graph_data_tool(mode="ingest")` is the structured import path shared by `v2_core` and the `v1` compatibility toolset. It uses local schema validation, dry-run/hash/confirm, and direct Gremlin writes through `manage_graph_data()`; it does not call the HugeGraph-AI `/graph-import` HTTP path. The legacy/internal AI-backed function is named `ingest_graph_data_via_ai()`.
+
+When `import_graph_data_tool(mode="ingest")` executes a create operation, it returns one of three states:
+
+- `success`: all writes succeeded
+- `partial` / `degraded`: some writes succeeded, some failed, or the final state cannot be fully confirmed
+- `error`: the write failed
+
+The response should include written counts, failure details, and compensation suggestions to avoid an untraceable partial write.
+
+#### Edge Endpoint Contract
+
+Edge endpoints accept both object and scalar forms:
+
+```text
+object source/target -> forwarded as-is
+ {"id": "1:Alice"} -> HugeGraph vertex id match
+ {"name": "Alice"} -> complete primary-key match; arbitrary property
+ matching is not part of the public graph_data contract
+
+scalar source/target -> if the live schema says the endpoint label has exactly
+ one primary key, match by that primary key first;
+ otherwise fall back to {"id": value}
+
+outV / inV / vertex id in payload -> always HugeGraph vertex id, with no
+ primary-key remapping
+```
+
+The scalar endpoint form is a same-payload import convenience, but under a single-primary-key live schema it is resolved as a primary-key match and may match an already existing vertex in the graph. It is not limited to vertices in the current payload, so edge-only or edge-to-existing-vertex payloads are valid when the dry-run live match resolves each endpoint to exactly one vertex.
+
+### Delete Semantics
+
+`delete_graph_data_tool` is a controlled delete tool:
+
+- The dry-run phase must resolve the concrete objects that would be deleted
+- The confirm phase must re-match and verify that the target is unchanged
+- The tool must verify after deletion that the target no longer exists
+- Vertex deletion is rejected by default when the vertex has associated edges
+
+Therefore, when deleting a vertex with associated edges, explicitly dry-run and delete the related edges first, then dry-run and delete the vertex.
+
+## Configuration
+
+All configuration is read from environment variables.
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `HUGEGRAPH_URL` | `http://127.0.0.1:8080` | HugeGraph Server URL |
+| `HUGEGRAPH_GRAPH_PATH` | `DEFAULT/hugegraph` | Graph path in `GRAPH_SPACE/GRAPH_NAME` format |
+| `HUGEGRAPH_GRAPHSPACE` | unset | Override graph space separately |
+| `HUGEGRAPH_GRAPH` | unset | Override graph name separately |
+| `HUGEGRAPH_USER` | `admin` | HugeGraph username |
+| `HUGEGRAPH_PASSWORD` | `""` | HugeGraph password |
+| `HUGEGRAPH_MCP_TOOLSET` | `v2_core` | Public tool contract: `v1` for 10-tool compatibility mode, `v2_core` for the 13-tool default |
+| `HUGEGRAPH_MCP_READONLY` | `true` | Whether readonly mode is enabled |
+| `HUGEGRAPH_MCP_ALLOW_AI` | `false` | Whether HugeGraph-AI calls are allowed |
+| `HUGEGRAPH_MCP_ADMIN_MODE` | `false` | Whether admin/debug tools are enabled |
+| `HUGEGRAPH_AI_URL` | `http://127.0.0.1:8001` | HugeGraph-AI URL |
+| `HUGEGRAPH_AI_TOKEN` | unset | Bearer token for an authenticated HugeGraph-AI service; public MCP tools configure this through the environment (an internal HTTP caller may override it per request) |
+| `HUGEGRAPH_AI_GRAPH_URL` | unset | Graph URL used by HugeGraph-AI; defaults to `HUGEGRAPH_URL` when unset |
+| `HUGEGRAPH_MCP_TIMEOUT_SECONDS` | `30` | AI call timeout in seconds |
+| `HUGEGRAPH_MCP_MAX_REPEAT_TIMES` | `10` | Recommended maximum for read-cost warnings on `repeat().times(n)` |
+| `HUGEGRAPH_MCP_STATE_DIR` | `$XDG_STATE_HOME/hugegraph-mcp`, or `~/.local/state/hugegraph-mcp` when `XDG_STATE_HOME` is unset | Local state directory for the persistent single-use confirmation ledger |
+
+`HUGEGRAPH_MCP_TIMEOUT_SECONDS` only applies to HugeGraph-AI HTTP calls; it does not apply to PyHugeClient Gremlin queries. Read-only Gremlin cost boundaries are reported as non-blocking read cost guard warnings for bare full-graph scans, `repeat()` without a `times()` bound, and `path` / `group` / `profile` without `limit` or `range`.
+
+Boolean configuration accepts `1`, `true`, `yes`, or `on` and `0`, `false`, `no`, or `off`, ignoring case and surrounding whitespace. Empty or invalid values fail closed: `HUGEGRAPH_MCP_READONLY` remains enabled, while `HUGEGRAPH_MCP_ALLOW_AI` and `HUGEGRAPH_MCP_ADMIN_MODE` remain disabled.
+
+The confirmation ledger persists server-issued dry-run plans and consumed nonce digests. Confirm accepts only a matching server-issued plan, enforces the server's 10-minute maximum TTL, and atomically consumes it so a write plan can be used only once across local process restarts and workers sharing the same state directory. On POSIX platforms, HugeGraph MCP restricts the state directory to mode `0700` and the ledger database to mode `0600`.
+
+Recommended safe defaults:
+
+- `HUGEGRAPH_MCP_READONLY=true`
+- `HUGEGRAPH_MCP_ALLOW_AI=false`
+- `HUGEGRAPH_MCP_ADMIN_MODE=false`
+
+Common combinations:
+
+| Scenario | Configuration |
+|----------|---------------|
+| Read-only graph query | `HUGEGRAPH_MCP_READONLY=true`, `HUGEGRAPH_MCP_ALLOW_AI=false` |
+| AI Gremlin generation / text extraction | `HUGEGRAPH_MCP_READONLY=true`, `HUGEGRAPH_MCP_ALLOW_AI=true` |
+| Controlled import and delete | `HUGEGRAPH_MCP_READONLY=false`, set `HUGEGRAPH_MCP_ALLOW_AI=true` as needed |
+| Administration/debugging | `HUGEGRAPH_MCP_READONLY=false`, `HUGEGRAPH_MCP_ADMIN_MODE=true` |
+
+## License
+
+Apache License 2.0
diff --git a/hugegraph-mcp/README.zh-CN.md b/hugegraph-mcp/README.zh-CN.md
new file mode 100644
index 00000000..6ad6d040
--- /dev/null
+++ b/hugegraph-mcp/README.zh-CN.md
@@ -0,0 +1,257 @@
+# HugeGraph MCP
+
+[English](README.md)
+
+HugeGraph MCP 是 HugeGraph 的 Model Context Protocol Server。它的定位是安全、可控的薄适配层:对外暴露少量稳定工具,内部统一处理配置、权限、只读 Gremlin 校验、dry-run/confirm 写入安全链和统一响应格式。
+
+**要求 HugeGraph Server >= 1.7.0**(MCP 默认使用 `graphspace=DEFAULT` 并依赖 graphspace 路由 API,旧版本不支持)。
+
+## 快速开始
+
+如果尚未安装,请先安装 [uv](https://docs.astral.sh/uv/getting-started/installation/)。然后,在仓库根目录安装 MCP 依赖并启动 stdio server:
+
+```bash
+uv sync --extra mcp --extra dev
+
+export HUGEGRAPH_URL=http://127.0.0.1:8080
+export HUGEGRAPH_GRAPH_PATH=DEFAULT/hugegraph
+export HUGEGRAPH_USER=admin
+export HUGEGRAPH_PASSWORD=admin
+export HUGEGRAPH_MCP_READONLY=true
+
+uv run --project hugegraph-mcp hugegraph-mcp
+```
+
+进程通过 stdout 输出 MCP JSON-RPC,请由 MCP 客户端连接。除非已经有明确的写入验证计划,否则保持
+`HUGEGRAPH_MCP_READONLY=true`。默认工具集是 `v2_core`;旧客户端需要 10 工具兼容契约时,在启动前设置
+`HUGEGRAPH_MCP_TOOLSET=v1`。
+
+## 开发者说明
+
+### 设计边界
+
+HugeGraph MCP 不把 MCP 做成另一套业务内核。MCP 层负责:
+
+- 暴露稳定 MCP 工具接口
+- 读取运行时配置
+- 执行权限和 readonly guard
+- 校验 Gremlin 是否只读
+- 生成并校验 `plan_hash`
+- 统一响应 envelope
+- 将 AI 能力转发给 HugeGraph-AI,或将图读写转发给 HugeGraph Server
+
+
+
+### 对外工具面
+
+默认 `v2_core` 工具集注册 13 个 MCP 工具:其中 11 个是普通用户稳定工具,另外 2 个是管理/调试工具,默认注册但受 admin mode 阻断。
+
+普通用户稳定工具包括:
+
+- `inspect_graph_tool`
+- `inspect_schema_tool`
+- `query_graph_data_tool`
+- `generate_gremlin_tool`
+- `execute_gremlin_read_tool`
+- `extract_graph_data_tool`
+- `design_schema_tool`
+- `apply_schema_tool`
+- `mutate_graph_properties_tool`
+- `import_graph_data_tool`
+- `delete_graph_data_tool`
+
+以下工具仍注册在 MCP 中,但属于管理/调试能力,默认受 `HUGEGRAPH_MCP_ADMIN_MODE=false` 阻断。具备写入能力的管理工具还要求 `HUGEGRAPH_MCP_READONLY=false`:
+
+- `execute_gremlin_write_tool`
+- `refresh_vid_embeddings_tool`
+
+`execute_gremlin_write_tool` 是写入安全链唯一的 break-glass(紧急直通)例外。它不提供预览、dry-run、plan hash 或确认步骤,可直接执行任意 Gremlin 写语句。只能在隔离且仅受信管理员可访问的 transport 上启用,禁止在共享 Agent 或客户端端点启用。
+
+### 工具集选择
+
+`HUGEGRAPH_MCP_TOOLSET` 控制对外工具契约:
+
+| 取值 | 工具数 | 用途 |
+|------|------:|------|
+| `v1` | 10 | 兼容旧客户端;只暴露原有稳定工具和管理/调试工具,隐藏三个 `v2_core` 新工具,并保持 `apply_schema_tool(mode="apply")` 禁用 |
+| `v2_core` | 13 | 新部署默认值;在 V1 工具基础上增加 `inspect_schema_tool`、`query_graph_data_tool`、`mutate_graph_properties_tool`,并启用 P0a 范围内的 schema create apply 路径 |
+
+未设置 `HUGEGRAPH_MCP_TOOLSET` 时,服务默认使用 `v2_core`。除精确的 `v1` 之外,其他取值都会按 `v2_core` 处理。
+工具集选择在 MCP server 启动并注册工具时生效;修改该变量后需要重启 MCP server。
+
+
+### 统一响应格式
+
+高层工具返回统一 envelope:
+
+```json
+{
+ "ok": true,
+ "data": {},
+ "error": null,
+ "warnings": [],
+ "next_actions": [],
+ "meta": {
+ "request_id": "req-...",
+ "graph": "hugegraph",
+ "graphspace": "DEFAULT",
+ "readonly": true,
+ "duration_ms": 12.3
+ }
+}
+```
+
+失败时 `ok=false`,`error` 使用统一结构:
+
+```json
+{
+ "type": "READONLY_VIOLATION",
+ "message": "DATA_WRITE capability is disabled in read-only mode",
+ "suggestion": "Disable HUGEGRAPH_MCP_READONLY to allow this operation.",
+ "retryable": false,
+ "source": "hugegraph-mcp",
+ "details": {}
+}
+```
+
+
+## 工具参考
+
+### 用户可用工具总览
+
+| 工具 | 说明 |
+|------|------|
+| `inspect_graph_tool` | 查看 HugeGraph Server 状态、schema 摘要、点边计数、readonly 状态、AI 可用性和当前 MCP 工具契约字段 |
+| `inspect_schema_tool` | 查看 schema 对象、关系和索引标签;支持按 property key、vertex label、edge label 或 index label 过滤 |
+| `query_graph_data_tool` | 通过类型化操作查询点或边(`get_by_id`、`get_by_ids`、`page`、`condition`),有显式 limit,不自动降级为 Gremlin 全图扫描 |
+| `generate_gremlin_tool` | 根据自然语言生成 Gremlin;默认只生成,不执行;`execute=true` 时也必须通过只读校验 |
+| `execute_gremlin_read_tool` | 执行只读 Gremlin 查询;无法确认安全时拒绝执行,并支持 `limit_policy` 处理无界读取 |
+| `extract_graph_data_tool` | 从自然语言文本抽取候选图数据,返回点和边结构,不写入 HugeGraph |
+| `import_graph_data_tool` | 结构化图数据导入入口;真实写入必须经过 `dry_run -> plan_hash -> confirm` |
+| `delete_graph_data_tool` | 受控删除入口;只支持精确删除点或边,不支持条件批量删除和级联删除 |
+| `design_schema_tool` | 根据 schema 操作草案给出设计建议,不修改数据库 |
+| `apply_schema_tool` | 校验 schema 操作并 dry-run P0a apply 范围;`v2_core` 中 dry-run 和确认后的 `apply` 只支持 `create_property_key`、`create_vertex_label`、`create_edge_label`;`v1` 中真实 `apply` 仍禁用 |
+| `mutate_graph_properties_tool` | 对单个精确点或边追加/淘汰属性;两种操作都必须经过 `dry_run -> plan_hash -> confirm`,目标变更时拒绝执行 |
+| `execute_gremlin_write_tool` | 直接执行 Gremlin 写语句;默认禁用,仅 `HUGEGRAPH_MCP_ADMIN_MODE=true` 且 `HUGEGRAPH_MCP_READONLY=false` 时可用 |
+| `refresh_vid_embeddings_tool` | 刷新 VID embeddings,会改变索引状态;默认禁用,仅 `HUGEGRAPH_MCP_ADMIN_MODE=true` 且 `HUGEGRAPH_MCP_READONLY=false` 时可用 |
+
+
+
+
+## 写入安全链
+
+所有普通用户可触达的写操作都必须经过以下安全链。上文所述仅管理员可用的 `execute_gremlin_write_tool` break-glass 例外不经过此链:
+
+```text
+dry_run=true
+ -> 用户/agent 审查 preview、warnings、matched_count、mutation_summary
+ -> 记录 plan_hash、nonce、expires_at
+ -> dry_run=false + confirm=true + 原始 payload + plan_hash + nonce + expires_at
+ -> MCP 重新校验目标、权限、schema、payload digest 和过期时间
+ -> 执行写入
+ -> 返回写入/删除结果和失败明细
+```
+
+`plan_hash` 不是简单的 payload 哈希。它至少绑定:
+
+- 工具名
+- 操作 mode
+- graph url
+- graph name
+- graph space
+- MCP readonly 状态
+- 当前 schema hash
+- normalized payload digest
+- nonce
+- expiry
+
+confirm 阶段必须全量重验。dry-run 结果过期、目标图变化、schema 变化、payload 变化或权限变化时,confirm 必须失败并要求重新 dry-run。
+
+### 导入语义
+
+`import_graph_data_tool(mode="ingest")` 是 `v2_core` 与 `v1` 兼容工具集共用的结构化导入路径。它使用本地 schema 校验、dry-run/hash/confirm 和 `manage_graph_data()` 的 direct Gremlin 写入;不会调用 HugeGraph-AI `/graph-import` HTTP 路径。legacy/internal 的 AI-backed 函数命名为 `ingest_graph_data_via_ai()`。
+
+`import_graph_data_tool(mode="ingest")` 执行创建时返回三类状态:
+
+- `success`:全部写入成功
+- `partial` / `degraded`:部分写入成功,部分失败或结果不可完全确认
+- `error`:写入失败
+
+响应需要包含已写数量、失败明细和可补偿建议,避免出现“半写半崩但不可追踪”。
+
+#### 边端点契约
+
+边端点同时支持 object 和 scalar 写法:
+
+```text
+object source/target -> 原样透传
+ {"id": "1:Alice"} -> 按 HugeGraph vertex id 匹配
+ {"name": "Alice"} -> 按完整主键匹配;任意属性匹配不属于 public graph_data 契约
+
+scalar source/target -> 如果 live schema 中该端点 label 恰好是单主键,
+ 优先按该主键匹配;否则回退为 {"id": value}
+
+outV / inV / payload 中显式 vertex id -> 始终表示 HugeGraph vertex id,
+ 不做主键改写
+```
+
+scalar 端点是 same-payload import 的便捷写法,但在单主键 live schema 下会按主键解析,可能匹配图中已存在的顶点;它不只在当前 payload 内查找。因此 edge-only 或连接 payload 外已有顶点的输入是合法的,前提是 dry-run 的 live match 能把每个端点唯一解析到一个顶点。
+
+### 删除语义
+
+`delete_graph_data_tool` 的删除是受控删除:
+
+- dry-run 阶段必须查出将被删除的具体对象
+- confirm 阶段必须重新匹配并校验目标一致
+- 删除后必须反查确认目标不存在
+- 顶点有关联边时默认拒绝删除
+
+因此,删除一个有关联边的点时,应先 dry-run 并删除相关边,再 dry-run 并删除该点。
+
+## 配置说明
+
+所有配置通过环境变量读取。
+
+| 变量 | 默认值 | 说明 |
+|------|--------|------|
+| `HUGEGRAPH_URL` | `http://127.0.0.1:8080` | HugeGraph Server 地址 |
+| `HUGEGRAPH_GRAPH_PATH` | `DEFAULT/hugegraph` | 图路径,格式为 `GRAPH_SPACE/GRAPH_NAME` |
+| `HUGEGRAPH_GRAPHSPACE` | 未设置 | 单独覆盖 graph space |
+| `HUGEGRAPH_GRAPH` | 未设置 | 单独覆盖 graph name |
+| `HUGEGRAPH_USER` | `admin` | HugeGraph 用户名 |
+| `HUGEGRAPH_PASSWORD` | `""` | HugeGraph 密码 |
+| `HUGEGRAPH_MCP_TOOLSET` | `v2_core` | 对外工具契约:`v1` 为 10 工具兼容模式,`v2_core` 为 13 工具默认模式 |
+| `HUGEGRAPH_MCP_READONLY` | `true` | 是否启用只读模式 |
+| `HUGEGRAPH_MCP_ALLOW_AI` | `false` | 是否允许调用 HugeGraph-AI |
+| `HUGEGRAPH_MCP_ADMIN_MODE` | `false` | 是否启用管理/调试工具 |
+| `HUGEGRAPH_AI_URL` | `http://127.0.0.1:8001` | HugeGraph-AI 地址 |
+| `HUGEGRAPH_AI_TOKEN` | 未设置 | HugeGraph-AI 开启认证时使用的 Bearer Token;公开 MCP 工具通过环境变量配置(内部 HTTP 调用方可按请求覆盖) |
+| `HUGEGRAPH_AI_GRAPH_URL` | 未设置 | AI 侧使用的图地址,未设置时使用 `HUGEGRAPH_URL` |
+| `HUGEGRAPH_MCP_TIMEOUT_SECONDS` | `30` | AI 调用超时时间 |
+| `HUGEGRAPH_MCP_MAX_REPEAT_TIMES` | `10` | `repeat().times(n)` 只读成本 warning 的建议最大值 |
+| `HUGEGRAPH_MCP_STATE_DIR` | `$XDG_STATE_HOME/hugegraph-mcp`;未设置 `XDG_STATE_HOME` 时为 `~/.local/state/hugegraph-mcp` | 持久化一次性确认账本的本地状态目录 |
+
+`HUGEGRAPH_MCP_TIMEOUT_SECONDS` 仅作用于 HugeGraph-AI HTTP 调用,不作用于 PyHugeClient 的 Gremlin 查询。只读 Gremlin 的成本边界由 read cost guard 以非阻塞 warning 形式提示,包括裸全图扫描、`repeat()` 无 `times()` 上限、以及 `path` / `group` / `profile` 无 `limit` 或 `range`。
+
+Boolean 配置只接受 `1`、`true`、`yes`、`on` 和 `0`、`false`、`no`、`off`,忽略大小写和首尾空白。空值或非法值会 fail closed:`HUGEGRAPH_MCP_READONLY` 保持开启,`HUGEGRAPH_MCP_ALLOW_AI` 和 `HUGEGRAPH_MCP_ADMIN_MODE` 保持关闭。
+
+确认账本记录服务端签发的 dry-run 计划和已消费 nonce 的摘要。confirm 只接受匹配的服务端签发计划,执行服务端 10 分钟最大 TTL,并通过原子消费保证一个写计划在本地进程重启后以及共享同一状态目录的多个 worker 之间最多使用一次。POSIX 平台上,HugeGraph MCP 将状态目录权限限制为 `0700`,账本数据库权限限制为 `0600`。状态无法安全持久化时,写入会在执行前被阻断。
+
+推荐默认安全姿态:
+
+- `HUGEGRAPH_MCP_READONLY=true`
+- `HUGEGRAPH_MCP_ALLOW_AI=false`
+- `HUGEGRAPH_MCP_ADMIN_MODE=false`
+
+常见组合:
+
+| 场景 | 配置 |
+|------|------|
+| 只读图查询 | `HUGEGRAPH_MCP_READONLY=true`,`HUGEGRAPH_MCP_ALLOW_AI=false` |
+| AI 生成只读 Gremlin / 文本抽取 | `HUGEGRAPH_MCP_READONLY=true`,`HUGEGRAPH_MCP_ALLOW_AI=true` |
+| 允许受控导入和删除 | `HUGEGRAPH_MCP_READONLY=false`,按需设置 `HUGEGRAPH_MCP_ALLOW_AI=true` |
+| 管理/调试 | `HUGEGRAPH_MCP_READONLY=false`,`HUGEGRAPH_MCP_ADMIN_MODE=true` |
+
+## License
+
+Apache License 2.0
diff --git a/hugegraph-mcp/docs/p0a-integration-checklist.md b/hugegraph-mcp/docs/p0a-integration-checklist.md
new file mode 100644
index 00000000..5e27507d
--- /dev/null
+++ b/hugegraph-mcp/docs/p0a-integration-checklist.md
@@ -0,0 +1,828 @@
+# P0a Integration Checklist
+
+This checklist is for the next person running P0a integration validation against a real HugeGraph Server. It expands the six-step path from the P0a design into concrete MCP tool calls and expected responses.
+
+Use a disposable graph. Do not run this checklist against a production graph.
+
+## Prerequisites
+
+### Start HugeGraph Server
+
+Use the repository's existing Docker path:
+
+```bash
+cd <YOUR_PROJECT_PATH>
+cp docker/env.template docker/.env
+sed -i.bak "s|PROJECT_PATH=path_to_project|PROJECT_PATH=<YOUR_PROJECT_PATH>|" docker/.env
+cd docker
+docker compose -f docker-compose-network.yml up -d --wait hugegraph-server
+curl -fsS http://127.0.0.1:8080/versions
+```
+
+`docker-compose-network.yml` pins HugeGraph Server 1.7.0 and also defines the RAG service, but P0a validation below only needs HugeGraph Server. HugeGraph MCP requires HugeGraph Server >= 1.7.0 because the default graphspace route is `DEFAULT/<graph>`. The `--wait` option prevents the checklist from continuing before the server health check passes.
+
+### Configure MCP
+
+Set these variables in the shell or MCP client process that launches `hugegraph-mcp`:
+
+```bash
+cd <YOUR_PROJECT_PATH>/hugegraph-mcp
+export HUGEGRAPH_URL=http://127.0.0.1:8080
+export HUGEGRAPH_GRAPHSPACE=DEFAULT
+export YOUR_GRAPH_NAME=p0a_check_20260705
+export HUGEGRAPH_GRAPH_PATH="$HUGEGRAPH_GRAPHSPACE/$YOUR_GRAPH_NAME"
+export HUGEGRAPH_USER=admin
+export HUGEGRAPH_PASSWORD=admin
+export HUGEGRAPH_MCP_TOOLSET=v2_core
+export HUGEGRAPH_MCP_READONLY=false
+export HUGEGRAPH_MCP_ALLOW_AI=false
+export HUGEGRAPH_MCP_ADMIN_MODE=false
+```
+
+Use a fresh `$YOUR_GRAPH_NAME`, for example `p0a_check_20260705`. First list
+the graphs in the target graphspace and verify that the graph exists:
+
+```bash
+curl -fsS -u "$HUGEGRAPH_USER:$HUGEGRAPH_PASSWORD" \
+ "$HUGEGRAPH_URL/graphspaces/$HUGEGRAPH_GRAPHSPACE/graphs"
+```
+
+If the graph is missing, create it through the HugeGraph REST API before
+continuing. For a RocksDB graph on a server version that supports dynamic graph
+creation:
+
+```bash
+curl -fsS -u "$HUGEGRAPH_USER:$HUGEGRAPH_PASSWORD" \
+ -H 'Content-Type: application/json' \
+ -X POST \
+ -d "{\"gremlin.graph\":\"org.apache.hugegraph.auth.HugeFactoryAuthProxy\",\"backend\":\"rocksdb\",\"serializer\":\"binary\",\"store\":\"$YOUR_GRAPH_NAME\"}" \
+ "$HUGEGRAPH_URL/graphspaces/$HUGEGRAPH_GRAPHSPACE/graphs/$YOUR_GRAPH_NAME"
+```
+
+HugeGraph 1.7.0 has a known dynamic-graph-creation limitation; use the
+pre-created default graph or a server version containing the fix when that
+endpoint is unavailable. Never run the checklist against a production graph.
+
+Start the MCP server with the same environment:
+
+```bash
+uv run hugegraph-mcp
+```
+
+Confirmed write plans are single-use. The server persists only a SHA-256 digest
+of each nonce and atomically consumes it before the first write side effect. A
+second call with the same confirmation returns `PLAN_ALREADY_USED`, including
+after an execution timeout, failure, or partial apply. Inspect the target state
+and run a new dry-run instead of retrying an already submitted confirmation.
+
+The request examples below show MCP `tools/call` payloads. Paste the `name` and `arguments` into your MCP client. Replace every `<RUN_ID>` with one short unique suffix, for example `20260705a`, and keep the same suffix through all steps. Replace `<EXPIRES_AT_...>` placeholders with the numeric `expires_at` value from the dry-run response, not a quoted string.
+
+## Step 1: Inspect Tool Contract
+
+Safety decision verified: `inspect_graph_tool` must expose the runtime contract version and confirm that this server is running the `v2_core` toolset before any write path is tested.
+
+Call:
+
+```json
+{
+ "name": "inspect_graph_tool",
+ "arguments": {
+ "include_raw_schema": false
+ }
+}
+```
+
+Expected key fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "graph": "<YOUR_GRAPH_NAME>",
+ "graphspace": "DEFAULT",
+ "hugegraph_server_status": "available",
+ "readonly": false,
+ "mcp_tool_contract_version": "2.0",
+ "toolset": "v2_core"
+ },
+ "meta": {
+ "readonly": false,
+ "mcp_tool_contract_version": "2.0",
+ "toolset": "v2_core"
+ }
+}
+```
+
+Continue only when `data.toolset` is `v2_core` and `data.readonly` is `false`. If `hugegraph_ai_status` is `unavailable`, ignore it for this P0a checklist.
+
+## Step 2: Create Minimal Schema Through Dry-Run And Confirm
+
+Safety decision verified: `apply_schema_tool(mode="apply")` is unlocked only for P0a create operations, and real schema writes must use the `dry_run -> plan_hash -> confirm` chain. The confirm step also verifies by post-reading live schema.
+
+Dry-run call:
+
+```json
+{
+ "name": "apply_schema_tool",
+ "arguments": {
+ "mode": "dry_run",
+ "operations": [
+ {
+ "type": "create_property_key",
+ "name": "p0a_name_<RUN_ID>",
+ "data_type": "TEXT",
+ "cardinality": "SINGLE"
+ },
+ {
+ "type": "create_property_key",
+ "name": "p0a_note_<RUN_ID>",
+ "data_type": "TEXT",
+ "cardinality": "SINGLE"
+ },
+ {
+ "type": "create_vertex_label",
+ "name": "p0a_person_<RUN_ID>",
+ "properties": ["p0a_name_<RUN_ID>", "p0a_note_<RUN_ID>"],
+ "primary_keys": ["p0a_name_<RUN_ID>"],
+ "nullable_keys": ["p0a_note_<RUN_ID>"]
+ },
+ {
+ "type": "create_edge_label",
+ "name": "p0a_knows_<RUN_ID>",
+ "source_label": "p0a_person_<RUN_ID>",
+ "target_label": "p0a_person_<RUN_ID>"
+ }
+ ]
+ }
+}
+```
+
+Expected dry-run fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "valid": true,
+ "confirmable": true,
+ "plan_hash": "<32 hex chars>",
+ "plan_context": {
+ "nonce": "<nonce>",
+ "expires_at": 1780000000,
+ "graph_name": "<YOUR_GRAPH_NAME>",
+ "graphspace": "DEFAULT",
+ "readonly": false
+ },
+ "mutation_summary": "Schema operations planned: create_edge_label=1, create_property_key=2, create_vertex_label=1"
+ }
+}
+```
+
+Confirm call. Copy `plan_hash`, `plan_context.nonce`, and `plan_context.expires_at` exactly from the dry-run response:
+
+```json
+{
+ "name": "apply_schema_tool",
+ "arguments": {
+ "mode": "apply",
+ "operations": [
+ {
+ "type": "create_property_key",
+ "name": "p0a_name_<RUN_ID>",
+ "data_type": "TEXT",
+ "cardinality": "SINGLE"
+ },
+ {
+ "type": "create_property_key",
+ "name": "p0a_note_<RUN_ID>",
+ "data_type": "TEXT",
+ "cardinality": "SINGLE"
+ },
+ {
+ "type": "create_vertex_label",
+ "name": "p0a_person_<RUN_ID>",
+ "properties": ["p0a_name_<RUN_ID>", "p0a_note_<RUN_ID>"],
+ "primary_keys": ["p0a_name_<RUN_ID>"],
+ "nullable_keys": ["p0a_note_<RUN_ID>"]
+ },
+ {
+ "type": "create_edge_label",
+ "name": "p0a_knows_<RUN_ID>",
+ "source_label": "p0a_person_<RUN_ID>",
+ "target_label": "p0a_person_<RUN_ID>"
+ }
+ ],
+ "confirm": true,
+ "plan_hash": "<PLAN_HASH_FROM_DRY_RUN>",
+ "nonce": "<NONCE_FROM_DRY_RUN>",
+ "expires_at": <EXPIRES_AT_FROM_DRY_RUN>
+ }
+}
+```
+
+Expected confirm fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "status": "applied",
+ "valid": true,
+ "applied_operations": [
+ {"type": "create_property_key", "name": "p0a_name_<RUN_ID>"},
+ {"type": "create_property_key", "name": "p0a_note_<RUN_ID>"},
+ {"type": "create_vertex_label", "name": "p0a_person_<RUN_ID>"},
+ {"type": "create_edge_label", "name": "p0a_knows_<RUN_ID>"}
+ ],
+ "schema_summary": {
+ "propertykeys": [
+ {"name": "p0a_name_<RUN_ID>"},
+ {"name": "p0a_note_<RUN_ID>"}
+ ],
+ "vertexlabels": [
+ {"name": "p0a_person_<RUN_ID>"}
+ ],
+ "edgelabels": [
+ {"name": "p0a_knows_<RUN_ID>"}
+ ]
+ }
+ }
+}
+```
+
+Verify with `inspect_schema_tool`:
+
+```json
+{
+ "name": "inspect_schema_tool",
+ "arguments": {
+ "include_raw_schema": false,
+ "include_relations": true,
+ "include_index_labels": true,
+ "filter_kind": "vertex_label",
+ "filter_name": "p0a_person_<RUN_ID>"
+ }
+}
+```
+
+Expected key fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "filtered": {
+ "name": "p0a_person_<RUN_ID>",
+ "properties": ["p0a_name_<RUN_ID>", "p0a_note_<RUN_ID>"],
+ "primary_keys": ["p0a_name_<RUN_ID>"],
+ "nullable_keys": ["p0a_note_<RUN_ID>"]
+ }
+ }
+}
+```
+
+Do not add `create_index_label` to this step. P0a apply intentionally rejects index create and rebuild work.
+
+## Step 3: Import Two Vertices And One Edge
+
+Safety decision verified: `import_graph_data_tool(mode="ingest")` remains the structured graph-data write path, and it must keep the same `dry_run -> plan_hash -> confirm` safety chain before writing data.
+
+Dry-run call:
+
+```json
+{
+ "name": "import_graph_data_tool",
+ "arguments": {
+ "mode": "ingest",
+ "graph_data": {
+ "vertices": [
+ {
+ "label": "p0a_person_<RUN_ID>",
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice"
+ }
+ },
+ {
+ "label": "p0a_person_<RUN_ID>",
+ "properties": {
+ "p0a_name_<RUN_ID>": "Bob"
+ }
+ }
+ ],
+ "edges": [
+ {
+ "label": "p0a_knows_<RUN_ID>",
+ "source_label": "p0a_person_<RUN_ID>",
+ "source": {
+ "p0a_name_<RUN_ID>": "Alice"
+ },
+ "target_label": "p0a_person_<RUN_ID>",
+ "target": {
+ "p0a_name_<RUN_ID>": "Bob"
+ }
+ }
+ ]
+ }
+ }
+}
+```
+
+Expected dry-run fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "valid": true,
+ "confirmable": true,
+ "plan_hash": "<32 hex chars>",
+ "plan_context": {
+ "nonce": "<nonce>",
+ "expires_at": 1780000000,
+ "readonly": false
+ },
+ "mutation_summary": {
+ "create_vertex": 2,
+ "create_edge": 1
+ }
+ }
+}
+```
+
+Confirm call. Copy `plan_hash`, `nonce`, and `expires_at` exactly from the dry-run response:
+
+```json
+{
+ "name": "import_graph_data_tool",
+ "arguments": {
+ "mode": "ingest",
+ "graph_data": {
+ "vertices": [
+ {
+ "label": "p0a_person_<RUN_ID>",
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice"
+ }
+ },
+ {
+ "label": "p0a_person_<RUN_ID>",
+ "properties": {
+ "p0a_name_<RUN_ID>": "Bob"
+ }
+ }
+ ],
+ "edges": [
+ {
+ "label": "p0a_knows_<RUN_ID>",
+ "source_label": "p0a_person_<RUN_ID>",
+ "source": {
+ "p0a_name_<RUN_ID>": "Alice"
+ },
+ "target_label": "p0a_person_<RUN_ID>",
+ "target": {
+ "p0a_name_<RUN_ID>": "Bob"
+ }
+ }
+ ]
+ },
+ "dry_run": false,
+ "confirm": true,
+ "plan_hash": "<PLAN_HASH_FROM_DRY_RUN>",
+ "nonce": "<NONCE_FROM_DRY_RUN>",
+ "expires_at": <EXPIRES_AT_FROM_DRY_RUN>
+ }
+}
+```
+
+Expected confirm fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "status": "success",
+ "success": true,
+ "planned": {
+ "create_vertex": 2,
+ "create_edge": 1
+ },
+ "written": {
+ "create_vertex": 2,
+ "create_edge": 1
+ },
+ "failed_items": []
+ }
+}
+```
+
+If this returns `INVALID_GRAPH_DATA` or `SCHEMA_MISMATCH`, verify that Step 2 used the same `<RUN_ID>` and that both vertex payloads include the primary key property `p0a_name_<RUN_ID>`.
+
+## Step 4: Query A Vertex By ID
+
+Safety decision verified: `query_graph_data_tool` must provide typed bounded reads without falling back to unbounded Gremlin scans. This step proves that exact ID lookup works after import.
+
+HugeGraph backend vertex IDs may encode the label and primary key together in a format that varies by server version and configuration. Do not assume a specific format; always read the exact ID string back from a bounded query before using it. If your import response does not show the exact ID, first find Alice with a bounded page query:
+
+```json
+{
+ "name": "query_graph_data_tool",
+ "arguments": {
+ "target": "vertex",
+ "operation": "page",
+ "label": "p0a_person_<RUN_ID>",
+ "limit": 10
+ }
+}
+```
+
+Expected page fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "target": "vertex",
+ "operation": "page",
+ "items": [
+ {
+ "id": "<ALICE_VERTEX_ID>",
+ "label": "p0a_person_<RUN_ID>",
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice"
+ }
+ }
+ ],
+ "count": 2,
+ "limit": 10
+ }
+}
+```
+
+Copy Alice's `items[].id` into `<ALICE_VERTEX_ID>`, then run the exact lookup:
+
+```json
+{
+ "name": "query_graph_data_tool",
+ "arguments": {
+ "target": "vertex",
+ "operation": "get_by_id",
+ "id": "<ALICE_VERTEX_ID>"
+ }
+}
+```
+
+Expected key fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "target": "vertex",
+ "operation": "get_by_id",
+ "items": [
+ {
+ "id": "<ALICE_VERTEX_ID>",
+ "label": "p0a_person_<RUN_ID>",
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice"
+ }
+ }
+ ],
+ "count": 1
+ }
+}
+```
+
+If you use `operation="condition"` instead, HugeGraph may return `NO_INDEX` because P0a intentionally does not create indexes. That is expected for this checklist and is covered in the troubleshooting table.
+
+## Step 5: Append A Property And Reject A Stale Eliminate Plan
+
+Safety decision verified: `mutate_graph_properties_tool` treats append and eliminate as write operations with the same dry-run/confirm chain. The stale eliminate confirm must be rejected with `TARGET_CHANGED`, proving the target snapshot digest blocks concurrent changes from being confirmed with an old plan.
+
+### 5.1 Append A Property
+
+Dry-run append call:
+
+```json
+{
+ "name": "mutate_graph_properties_tool",
+ "arguments": {
+ "target": "vertex",
+ "operation": "append",
+ "id": "<ALICE_VERTEX_ID>",
+ "properties": {
+ "p0a_note_<RUN_ID>": "first-note"
+ }
+ }
+}
+```
+
+Expected dry-run fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "status": "planned",
+ "confirmable": true,
+ "risk_level": "medium",
+ "before": {
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice"
+ }
+ },
+ "after": {
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice",
+ "p0a_note_<RUN_ID>": "first-note"
+ }
+ },
+ "plan_hash": "<32 hex chars>",
+ "plan_context": {
+ "nonce": "<nonce>|ts:<snapshot-prefix>",
+ "expires_at": 1780000000,
+ "readonly": false
+ }
+ }
+}
+```
+
+Confirm append:
+
+```json
+{
+ "name": "mutate_graph_properties_tool",
+ "arguments": {
+ "target": "vertex",
+ "operation": "append",
+ "id": "<ALICE_VERTEX_ID>",
+ "properties": {
+ "p0a_note_<RUN_ID>": "first-note"
+ },
+ "dry_run": false,
+ "confirm": true,
+ "plan_hash": "<APPEND_PLAN_HASH>",
+ "nonce": "<APPEND_NONCE>",
+ "expires_at": <APPEND_EXPIRES_AT>
+ }
+}
+```
+
+Expected confirm fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "status": "applied",
+ "after": {
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice",
+ "p0a_note_<RUN_ID>": "first-note"
+ }
+ }
+ }
+}
+```
+
+### 5.2 Prepare An Eliminate Plan
+
+Dry-run eliminate call. Do not confirm it yet:
+
+```json
+{
+ "name": "mutate_graph_properties_tool",
+ "arguments": {
+ "target": "vertex",
+ "operation": "eliminate",
+ "id": "<ALICE_VERTEX_ID>",
+ "properties": {
+ "p0a_note_<RUN_ID>": "first-note"
+ }
+ }
+}
+```
+
+Expected dry-run fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "status": "planned",
+ "risk_level": "high",
+ "before": {
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice",
+ "p0a_note_<RUN_ID>": "first-note"
+ }
+ },
+ "after": {
+ "properties": {
+ "p0a_name_<RUN_ID>": "Alice"
+ }
+ },
+ "plan_hash": "<ELIMINATE_PLAN_HASH>",
+ "plan_context": {
+ "nonce": "<ELIMINATE_NONCE>",
+ "expires_at": 1780000000
+ }
+ }
+}
+```
+
+Save `ELIMINATE_PLAN_HASH`, `ELIMINATE_NONCE`, and `ELIMINATE_EXPIRES_AT`.
+
+### 5.3 Change The Target Before Confirm
+
+Use another append dry-run/confirm to modify Alice after the eliminate dry-run:
+
+```json
+{
+ "name": "mutate_graph_properties_tool",
+ "arguments": {
+ "target": "vertex",
+ "operation": "append",
+ "id": "<ALICE_VERTEX_ID>",
+ "properties": {
+ "p0a_note_<RUN_ID>": "changed-before-eliminate-confirm"
+ }
+ }
+}
+```
+
+Confirm that second append with the returned `plan_hash`, `nonce`, and `expires_at`:
+
+```json
+{
+ "name": "mutate_graph_properties_tool",
+ "arguments": {
+ "target": "vertex",
+ "operation": "append",
+ "id": "<ALICE_VERTEX_ID>",
+ "properties": {
+ "p0a_note_<RUN_ID>": "changed-before-eliminate-confirm"
+ },
+ "dry_run": false,
+ "confirm": true,
+ "plan_hash": "<SECOND_APPEND_PLAN_HASH>",
+ "nonce": "<SECOND_APPEND_NONCE>",
+ "expires_at": <SECOND_APPEND_EXPIRES_AT>
+ }
+}
+```
+
+Expected second append result:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "status": "applied",
+ "after": {
+ "properties": {
+ "p0a_note_<RUN_ID>": "changed-before-eliminate-confirm"
+ }
+ }
+ }
+}
+```
+
+### 5.4 Confirm The Old Eliminate Plan
+
+Now confirm the old eliminate plan saved in 5.2:
+
+```json
+{
+ "name": "mutate_graph_properties_tool",
+ "arguments": {
+ "target": "vertex",
+ "operation": "eliminate",
+ "id": "<ALICE_VERTEX_ID>",
+ "properties": {
+ "p0a_note_<RUN_ID>": "first-note"
+ },
+ "dry_run": false,
+ "confirm": true,
+ "plan_hash": "<ELIMINATE_PLAN_HASH>",
+ "nonce": "<ELIMINATE_NONCE>",
+ "expires_at": <ELIMINATE_EXPIRES_AT>
+ }
+}
+```
+
+Expected rejection:
+
+```json
+{
+ "ok": false,
+ "error": {
+ "type": "TARGET_CHANGED",
+ "message": "Target changed since dry_run; property mutation was not applied.",
+ "source": "mutate_graph_properties_tool"
+ },
+ "next_actions": [
+ "Call query_graph_data_tool to inspect the current target."
+ ]
+}
+```
+
+This failure is the expected pass condition for stale-plan protection. If this call succeeds, P0a concurrency protection failed.
+
+## Step 6: Reject An Unbounded Gremlin Read
+
+Safety decision verified: `execute_gremlin_read_tool(limit_policy="reject_unbounded")` must reject safe-but-unbounded full graph reads instead of silently appending a limit or executing an unbounded scan.
+
+Call:
+
+```json
+{
+ "name": "execute_gremlin_read_tool",
+ "arguments": {
+ "gremlin_query": "g.V()",
+ "limit_policy": "reject_unbounded"
+ }
+}
+```
+
+Expected fields:
+
+```json
+{
+ "ok": false,
+ "error": {
+ "type": "VALIDATION_ERROR",
+ "message": "Gremlin read query is unbounded and limit_policy='reject_unbounded'."
+ },
+ "warnings": [
+ "Unbounded traversal ..."
+ ]
+}
+```
+
+Confirm that `executed_gremlin` is absent. The query must be rejected before execution.
+
+Run a bounded read to confirm the read path itself still works:
+
+```json
+{
+ "name": "execute_gremlin_read_tool",
+ "arguments": {
+ "gremlin_query": "g.V().hasLabel('p0a_person_<RUN_ID>').limit(10)",
+ "limit_policy": "reject_unbounded"
+ }
+}
+```
+
+Expected bounded-read fields:
+
+```json
+{
+ "ok": true,
+ "data": {
+ "is_read": true,
+ "limit_policy": "reject_unbounded",
+ "original_gremlin": "g.V().hasLabel('p0a_person_<RUN_ID>').limit(10)",
+ "executed_gremlin": "g.V().hasLabel('p0a_person_<RUN_ID>').limit(10)",
+ "total": 2
+ }
+}
+```
+
+## Troubleshooting
+
+| Error type | Where it appears | Meaning | Action |
+|---|---|---|---|
+| `CONNECTION_FAILED` | `inspect_schema_tool`, `apply_schema_tool`, `import_graph_data_tool`, `mutate_graph_properties_tool`, Gremlin reads | MCP could not reach HugeGraph Server, read schema, or read a target object. | Check `docker compose ps`, `curl http://127.0.0.1:8080/versions`, `HUGEGRAPH_URL`, `HUGEGRAPH_GRAPH_PATH`, `HUGEGRAPH_USER`, and `HUGEGRAPH_PASSWORD`. Retry after the server is healthy. |
+| `READONLY_VIOLATION` | Any confirm call for schema/data/property writes | `HUGEGRAPH_MCP_READONLY=true` at confirm time. Dry-run may be preview-only in readonly mode. | Set `HUGEGRAPH_MCP_READONLY=false`, restart or reconfigure the MCP process, rerun dry-run, then confirm with the new `plan_hash`. |
+| `PLAN_HASH_MISMATCH` | Confirm calls for schema/data/property writes | The submitted payload, graph target, schema hash, readonly state, principal, `nonce`, or `expires_at` no longer matches the dry-run plan. | Do not edit the payload between dry-run and confirm. Rerun dry-run and copy the new `plan_hash`, `nonce`, and `expires_at`. |
+| `PLAN_EXPIRED` | Confirm calls after waiting too long | The dry-run plan expired. Default plan TTL is 10 minutes. | Rerun dry-run and confirm within the returned `expires_at` window. |
+| `PLAN_ALREADY_USED` | A confirm call repeats a nonce that already entered execution | Confirmation nonces are globally single-use. A prior call may have succeeded, failed, timed out, or partially applied. | Inspect the current graph or schema state, then rerun dry-run and use its new `plan_hash`, `nonce`, and `expires_at`. Do not retry the old confirmation. |
+| `TARGET_CHANGED` | Step 5 stale eliminate confirm | The vertex or edge was changed after dry-run and before confirm. | Treat this as a successful stale-plan rejection in Step 5. For real work, rerun `query_graph_data_tool`, review current state, then create a new dry-run plan. |
+| `NO_INDEX` | `query_graph_data_tool(operation="condition")` or Gremlin `has()` filters | HugeGraph requires an index for that property query, and P0a does not create indexes. | Use `get_by_id` or bounded `page` for this checklist. Index create/rebuild belongs to the P0b workflow. |
+| `PARTIAL_APPLY` | `apply_schema_tool(mode="apply")` | At least one schema operation may have been applied before a later operation failed. | Call `inspect_schema_tool`, remove already-applied operations, rerun dry-run for the remaining operations only. Do not blindly retry the original full batch. |
+| `INVALID_GRAPH_DATA` or `SCHEMA_MISMATCH` | Import dry-run or property mutation dry-run | Payload does not match live schema: missing primary key, unknown property, wrong endpoint label, duplicate identity, or property not defined on the target label. | Compare the payload with `inspect_schema_tool`. In this checklist, ensure all names use the same `<RUN_ID>` and that `p0a_note_<RUN_ID>` was included in the vertex label properties. |
+| `VALIDATION_ERROR` | Query parameter validation or Step 6 unbounded Gremlin rejection | Input violates the public tool contract, or the unbounded Gremlin query was rejected by policy. | Fix the input. For Step 6, `VALIDATION_ERROR` is expected for `g.V()` with `reject_unbounded`. |
+
+## Acceptance Conclusion Template
+
+Use this checklist as the final run record:
+
+```text
+P0a integration acceptance
+Graph path: DEFAULT/<YOUR_GRAPH_NAME>
+Run id: <RUN_ID>
+HugeGraph Server URL: <HUGEGRAPH_URL>
+Executed by:
+Date:
+
+[ ] Step 1 passed: inspect_graph_tool returned ok=true, toolset=v2_core, readonly=false.
+[ ] Step 2 passed: apply_schema_tool dry-run returned plan_hash and confirm applied property keys, vertex label, and edge label.
+[ ] Step 3 passed: import_graph_data_tool dry-run returned plan_hash and confirm wrote 2 vertices + 1 edge.
+[ ] Step 4 passed: query_graph_data_tool get_by_id returned Alice by exact vertex id.
+[ ] Step 5 passed: append property applied, and stale eliminate confirm returned TARGET_CHANGED.
+[ ] Step 6 passed: g.V() with reject_unbounded was rejected before execution, while bounded read succeeded.
+
+Overall result: PASS / FAIL
+Notes:
+```
diff --git a/hugegraph-mcp/hugegraph_mcp/__init__.py b/hugegraph-mcp/hugegraph_mcp/__init__.py
new file mode 100644
index 00000000..402359c1
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/__init__.py
@@ -0,0 +1,12 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/hugegraph-mcp/hugegraph_mcp/config.py b/hugegraph-mcp/hugegraph_mcp/config.py
new file mode 100644
index 00000000..83dbf980
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/config.py
@@ -0,0 +1,243 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""统一配置层 — 所有 MCP 工具通过 MCPConfig.from_env() 获取配置。
+
+环境变量优先级高于默认值,避免硬编码连接信息。"""
+
+import logging
+import os
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+
+TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
+FALSE_VALUES = frozenset({"0", "false", "no", "off"})
+LOGGER = logging.getLogger("hugegraph_mcp.config")
+CONFIG_ENV_NAMES = (
+ "HUGEGRAPH_URL",
+ "HUGEGRAPH_GRAPH_PATH",
+ "HUGEGRAPH_GRAPH",
+ "HUGEGRAPH_GRAPHSPACE",
+ "HUGEGRAPH_USER",
+ "HUGEGRAPH_PASSWORD",
+ "HUGEGRAPH_MCP_READONLY",
+ "HUGEGRAPH_AI_URL",
+ "HUGEGRAPH_AI_TOKEN",
+ "HUGEGRAPH_AI_GRAPH_URL",
+ "HUGEGRAPH_MCP_ALLOW_AI",
+ "HUGEGRAPH_MCP_ADMIN_MODE",
+ "HUGEGRAPH_MCP_TIMEOUT_SECONDS",
+ "HUGEGRAPH_MCP_STATE_DIR",
+ "XDG_STATE_HOME",
+)
+_CONFIG_CACHE: tuple[tuple[tuple[str, str | None], ...], "MCPConfig"] | None = None
+
+
+@dataclass
+class MCPConfig:
+ """MCP 服务器统一配置,所有字段从环境变量读取,有合理默认值。"""
+
+ url: str = "http://127.0.0.1:8080"
+ graph: str = "hugegraph"
+ graphspace: str | None = "DEFAULT"
+ user: str = "admin"
+ password: str = ""
+ readonly: bool = True
+ ai_url: str = "http://127.0.0.1:8001"
+ ai_token: str | None = None
+ ai_graph_url: str | None = None
+ allow_ai: bool = False
+ admin_mode: bool = False
+ timeout_seconds: int = 30
+ state_dir: Path = field(
+ default_factory=lambda: Path.home() / ".local" / "state" / "hugegraph-mcp"
+ )
+ warnings: tuple[str, ...] = field(default_factory=tuple)
+
+ @classmethod
+ def from_env(cls, env: Mapping[str, str] | None = None) -> "MCPConfig":
+ global _CONFIG_CACHE
+
+ use_cache = env is None
+ if use_cache:
+ # Read each setting once, then use that same snapshot for both the
+ # cache key and parsing. Reading os.environ once for the key and
+ # again below could otherwise cache a permissive configuration
+ # under a fail-closed key when the environment changes mid-call.
+ env = _environment_snapshot(os.environ)
+ cache_key = _env_cache_key(env)
+ if _CONFIG_CACHE is not None and cache_key == _CONFIG_CACHE[0]:
+ return _CONFIG_CACHE[1]
+ else:
+ cache_key = None
+
+ warnings: list[str] = []
+
+ path_graphspace, path_graph = _parse_graph_path(
+ env.get("HUGEGRAPH_GRAPH_PATH", "DEFAULT/hugegraph")
+ )
+ graphspace = path_graphspace
+ graph = path_graph
+
+ split_graphspace = env.get("HUGEGRAPH_GRAPHSPACE")
+ split_graph = env.get("HUGEGRAPH_GRAPH")
+ if env.get("HUGEGRAPH_GRAPH_PATH") is not None and (
+ split_graphspace is not None or split_graph is not None
+ ):
+ warnings.append(
+ "HUGEGRAPH_GRAPHSPACE/HUGEGRAPH_GRAPH override HUGEGRAPH_GRAPH_PATH"
+ )
+
+ if split_graphspace is not None:
+ graphspace = _non_empty(split_graphspace, "DEFAULT")
+ if split_graph is not None:
+ graph = _non_empty(split_graph, "hugegraph")
+
+ readonly = _parse_bool(
+ env.get("HUGEGRAPH_MCP_READONLY"),
+ "HUGEGRAPH_MCP_READONLY",
+ True,
+ warnings,
+ )
+ allow_ai = _parse_bool(
+ env.get("HUGEGRAPH_MCP_ALLOW_AI"),
+ "HUGEGRAPH_MCP_ALLOW_AI",
+ False,
+ warnings,
+ )
+ admin_mode = _parse_bool(
+ env.get("HUGEGRAPH_MCP_ADMIN_MODE"),
+ "HUGEGRAPH_MCP_ADMIN_MODE",
+ False,
+ warnings,
+ )
+
+ config = cls(
+ url=env.get("HUGEGRAPH_URL", "http://127.0.0.1:8080"),
+ graph=graph,
+ graphspace=graphspace,
+ user=env.get("HUGEGRAPH_USER", "admin"),
+ password=env.get("HUGEGRAPH_PASSWORD", ""),
+ readonly=readonly,
+ ai_url=env.get("HUGEGRAPH_AI_URL", "http://127.0.0.1:8001"),
+ ai_token=_optional_non_empty(env.get("HUGEGRAPH_AI_TOKEN")),
+ ai_graph_url=_optional_non_empty(env.get("HUGEGRAPH_AI_GRAPH_URL")),
+ allow_ai=allow_ai,
+ admin_mode=admin_mode,
+ timeout_seconds=_parse_int(env.get("HUGEGRAPH_MCP_TIMEOUT_SECONDS"), 30),
+ state_dir=_state_dir(env),
+ warnings=tuple(warnings),
+ )
+ for warning in config.warnings:
+ LOGGER.warning(warning)
+ if use_cache:
+ assert cache_key is not None
+ # Store key and value as one object so concurrent readers can
+ # never observe a key paired with a different configuration.
+ _CONFIG_CACHE = (cache_key, config)
+ return config
+
+ def is_readonly(self) -> bool:
+ return self.readonly
+
+
+def _parse_graph_path(graph_path: str) -> tuple[str, str]:
+ if "/" in graph_path:
+ graphspace, graph = graph_path.split("/", 1)
+ else:
+ graphspace, graph = "DEFAULT", graph_path
+
+ return _non_empty(graphspace, "DEFAULT"), _non_empty(graph, "hugegraph")
+
+
+def _parse_bool(
+ value: str | None,
+ env_name: str,
+ safe_default: bool,
+ warnings: list[str],
+) -> bool:
+ if value is None:
+ return safe_default
+ normalized = value.strip().lower()
+ if normalized in TRUE_VALUES:
+ return True
+ if normalized in FALSE_VALUES:
+ return False
+ warnings.append(f"Invalid boolean configuration: {env_name}; using safe default")
+ return safe_default
+
+
+def _parse_int(value: str | None, default: int) -> int:
+ if value is None or value.strip() == "":
+ return default
+ try:
+ parsed = int(value)
+ except ValueError:
+ LOGGER.warning(
+ "Invalid integer config value %r; using default %s", value, default
+ )
+ return default
+ if parsed <= 0:
+ LOGGER.warning(
+ "Invalid integer config value %r; using default %s", value, default
+ )
+ return default
+ return parsed
+
+
+def _non_empty(value: str, default: str) -> str:
+ return value.strip() or default
+
+
+def _optional_non_empty(value: str | None) -> str | None:
+ if value is None:
+ return None
+ stripped = value.strip()
+ return stripped or None
+
+
+def _state_dir(env: Mapping[str, str]) -> Path:
+ explicit = env.get("HUGEGRAPH_MCP_STATE_DIR")
+ if explicit is not None and explicit.strip():
+ return Path(explicit).expanduser()
+ xdg_state_home = env.get("XDG_STATE_HOME")
+ if xdg_state_home is not None and xdg_state_home.strip():
+ return Path(xdg_state_home).expanduser() / "hugegraph-mcp"
+ return Path.home() / ".local" / "state" / "hugegraph-mcp"
+
+
+def _env_cache_key(env: Mapping[str, str]) -> tuple[tuple[str, str | None], ...]:
+ return tuple((name, env.get(name)) for name in CONFIG_ENV_NAMES)
+
+
+def _environment_snapshot(env: Mapping[str, str]) -> dict[str, str]:
+ snapshot: dict[str, str] = {}
+ for name in CONFIG_ENV_NAMES:
+ value = env.get(name)
+ if value is not None:
+ snapshot[name] = value
+ return snapshot
+
+
+class RuntimeConfigProxy:
+ """Compatibility proxy for code that imports config directly."""
+
+ def __getattr__(self, name: str):
+ return getattr(MCPConfig.from_env(), name)
+
+ def is_readonly(self) -> bool:
+ return MCPConfig.from_env().is_readonly()
+
+
+config = RuntimeConfigProxy()
diff --git a/hugegraph-mcp/hugegraph_mcp/confirmable_workflow.py b/hugegraph-mcp/hugegraph_mcp/confirmable_workflow.py
new file mode 100644
index 00000000..24815bc2
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/confirmable_workflow.py
@@ -0,0 +1,227 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Small helpers for dry-run -> plan_hash -> confirm write workflows."""
+
+from typing import Any
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.confirmation_store import (
+ ConfirmationAlreadyUsedError,
+ ConfirmationNotIssuedError,
+ ConfirmationPlanExpiredError,
+ ConfirmationPlanMismatchError,
+ ConfirmationStore,
+ ConfirmationStoreUnavailableError,
+)
+from hugegraph_mcp.envelope import ErrorType, envelope_err
+from hugegraph_mcp.plan_hash import PlanContext, verify_plan_hash
+
+
+def issue_plan(context: PlanContext, plan_hash: str) -> dict[str, Any] | None:
+ """Persist a server-issued plan before its dry-run response is returned."""
+ try:
+ ConfirmationStore.from_config().issue(
+ nonce=context.nonce,
+ plan_hash=plan_hash,
+ expires_at=context.expires_at,
+ )
+ except ConfirmationPlanExpiredError:
+ return plan_hash_error(
+ error_type=ErrorType.PLAN_EXPIRED,
+ details={"reason": "The generated plan TTL is outside the allowed window."},
+ mismatch_message="The generated confirmation plan is invalid.",
+ expired_message="The generated confirmation plan is invalid.",
+ suggestion="Run dry_run again.",
+ )
+ except ConfirmationPlanMismatchError:
+ return plan_hash_error(
+ error_type=ErrorType.PLAN_HASH_MISMATCH,
+ details={"reason": "The nonce is already bound to another issued plan."},
+ mismatch_message="The confirmation nonce conflicts with another plan.",
+ suggestion="Run dry_run again without supplying a nonce.",
+ )
+ except ConfirmationStoreUnavailableError:
+ return plan_hash_error(
+ error_type=ErrorType.SERVER_ERROR,
+ details={"reason": "Confirmation state is unavailable."},
+ mismatch_message="Confirmation state could not be recorded safely.",
+ suggestion="Restore writable persistent confirmation state, then retry.",
+ )
+ return None
+
+
+def replayed_plan_error(
+ nonce: str | None, *, source: str | None = None
+) -> dict[str, Any] | None:
+ """Return a replay error before live-state validation when already consumed."""
+ try:
+ consumed = ConfirmationStore.from_config().has_consumed(nonce)
+ except ConfirmationStoreUnavailableError:
+ # Unknown state is not treated as unused. Full validation continues and
+ # the atomic consume remains fail-closed before the first write.
+ return None
+ if not consumed:
+ return None
+ return plan_hash_error(
+ error_type=ErrorType.PLAN_ALREADY_USED,
+ details={
+ "reason": (
+ "This confirmation has already been used. Inspect the target "
+ "state and run dry_run again."
+ )
+ },
+ mismatch_message="This confirmation plan has already been used.",
+ suggestion="Inspect the current target state, then run dry_run again.",
+ source=source,
+ )
+
+
+def verify_and_consume_plan(
+ *,
+ submitted_hash: str,
+ tool_name: str,
+ mode: str,
+ payload_digest: str,
+ schema_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+ extra_context: dict[str, Any] | None = None,
+) -> tuple[bool, ErrorType | None, dict[str, Any] | None]:
+ """Validate a plan without side effects, then atomically consume its nonce."""
+ valid, error_type, details = verify_plan_hash(
+ submitted_hash=submitted_hash,
+ tool_name=tool_name,
+ mode=mode,
+ payload_digest=payload_digest,
+ schema_hash=schema_hash,
+ nonce=nonce,
+ expires_at=expires_at,
+ extra_context=extra_context,
+ )
+ if not valid:
+ return False, error_type, details
+
+ if MCPConfig.from_env().is_readonly():
+ return (
+ False,
+ ErrorType.READONLY_VIOLATION,
+ {"reason": "Write confirmation is disabled in readonly mode."},
+ )
+
+ try:
+ ConfirmationStore.from_config().consume(
+ nonce=nonce or "",
+ plan_hash=submitted_hash,
+ expires_at=int(expires_at or 0),
+ )
+ except ConfirmationAlreadyUsedError:
+ return (
+ False,
+ ErrorType.PLAN_ALREADY_USED,
+ {
+ "reason": (
+ "This confirmation has already been used. Inspect the target "
+ "state and run dry_run again."
+ )
+ },
+ )
+ except ConfirmationNotIssuedError:
+ return (
+ False,
+ ErrorType.PLAN_HASH_MISMATCH,
+ {"reason": "No server-issued dry-run plan matches this confirmation."},
+ )
+ except ConfirmationPlanMismatchError:
+ return (
+ False,
+ ErrorType.PLAN_HASH_MISMATCH,
+ {"reason": "The confirmation does not match the server-issued plan."},
+ )
+ except ConfirmationPlanExpiredError:
+ return (
+ False,
+ ErrorType.PLAN_EXPIRED,
+ {"reason": "The server-issued plan has expired."},
+ )
+ except ConfirmationStoreUnavailableError:
+ return (
+ False,
+ ErrorType.SERVER_ERROR,
+ {
+ "reason": (
+ "Confirmation state is unavailable. The write was blocked "
+ "before execution."
+ )
+ },
+ )
+ return True, None, None
+
+
+def mark_readonly_preview(
+ payload: dict[str, Any],
+ *,
+ warning: str,
+ next_action: str,
+) -> tuple[dict[str, Any], list[str], list[str]]:
+ payload["confirmable"] = False
+ payload["readonly_preview_only"] = True
+ return payload, [warning], [next_action]
+
+
+def confirm_required_error(
+ *,
+ message: str,
+ suggestion: str,
+ source: str | None = None,
+) -> dict[str, Any]:
+ return envelope_err(
+ ErrorType.CONFIRM_REQUIRED,
+ message,
+ suggestion=suggestion,
+ source=source,
+ )
+
+
+def plan_hash_error(
+ *,
+ error_type: ErrorType | None,
+ details: dict[str, Any],
+ mismatch_message: str,
+ expired_message: str | None = None,
+ suggestion: str,
+ source: str | None = None,
+) -> dict[str, Any]:
+ resolved_error_type = error_type or ErrorType.PLAN_HASH_MISMATCH
+ if resolved_error_type == ErrorType.PLAN_EXPIRED and expired_message:
+ message = expired_message
+ elif resolved_error_type == ErrorType.PLAN_ALREADY_USED:
+ message = "This confirmation plan has already been used."
+ suggestion = (
+ "Inspect the current target state, then run dry_run again and use the "
+ "new confirmation plan."
+ )
+ elif resolved_error_type == ErrorType.SERVER_ERROR:
+ message = "Confirmation state could not be recorded safely."
+ suggestion = (
+ "Restore writable persistent confirmation state, then run dry_run again."
+ )
+ else:
+ message = mismatch_message
+ return envelope_err(
+ resolved_error_type,
+ message,
+ suggestion=suggestion,
+ source=source,
+ details=details,
+ )
diff --git a/hugegraph-mcp/hugegraph_mcp/confirmation_store.py b/hugegraph-mcp/hugegraph_mcp/confirmation_store.py
new file mode 100644
index 00000000..6a543776
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/confirmation_store.py
@@ -0,0 +1,245 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Persistent, atomic ledger for single-use write confirmations."""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import sqlite3
+import time
+from pathlib import Path
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.plan_hash import DEFAULT_PLAN_TTL_SECONDS
+
+
+class ConfirmationAlreadyUsedError(Exception):
+ """The nonce has already authorized a write attempt."""
+
+
+class ConfirmationStoreUnavailableError(Exception):
+ """The durable confirmation ledger cannot safely record a write."""
+
+
+class ConfirmationNotIssuedError(Exception):
+ """The submitted plan was not issued by a server-side dry-run."""
+
+
+class ConfirmationPlanMismatchError(Exception):
+ """The submitted confirmation does not match the issued plan."""
+
+
+class ConfirmationPlanExpiredError(Exception):
+ """The server-issued plan is expired or exceeds the allowed TTL."""
+
+
+class ConfirmationStore:
+ """SQLite-backed confirmation ledger with a globally unique nonce digest."""
+
+ DATABASE_NAME = "confirmations.sqlite3"
+
+ def __init__(self, state_dir: Path):
+ self.state_dir = Path(state_dir)
+ self.database_path = self.state_dir / self.DATABASE_NAME
+
+ @classmethod
+ def from_config(cls) -> ConfirmationStore:
+ return cls(MCPConfig.from_env().state_dir)
+
+ def has_consumed(self, nonce: str | None) -> bool:
+ """Check whether a nonce was consumed without creating persistent state."""
+ if not nonce or not self.database_path.exists():
+ return False
+ nonce_digest = hashlib.sha256(nonce.encode("utf-8")).hexdigest()
+ try:
+ with sqlite3.connect(self.database_path, timeout=30) as connection:
+ row = connection.execute(
+ """
+ SELECT 1 FROM consumed_confirmations
+ WHERE nonce_digest = ? LIMIT 1
+ """,
+ (nonce_digest,),
+ ).fetchone()
+ except (OSError, sqlite3.Error) as exc:
+ raise ConfirmationStoreUnavailableError from exc
+ return row is not None
+
+ def issue(self, *, nonce: str, plan_hash: str, expires_at: int) -> None:
+ """Persist a server-issued dry-run plan before returning it to the caller."""
+ nonce_digest = hashlib.sha256(nonce.encode("utf-8")).hexdigest()
+ issued_at = int(time.time())
+ expires_at = int(expires_at)
+ if expires_at <= issued_at or expires_at > issued_at + DEFAULT_PLAN_TTL_SECONDS:
+ raise ConfirmationPlanExpiredError
+
+ try:
+ self._prepare_storage()
+ with sqlite3.connect(self.database_path, timeout=30) as connection:
+ connection.execute("PRAGMA synchronous = FULL")
+ self._ensure_schema(connection)
+ self._cleanup_expired(connection, issued_at)
+ connection.execute(
+ """
+ INSERT INTO issued_confirmations (
+ nonce_digest, plan_hash, expires_at, issued_at
+ ) VALUES (?, ?, ?, ?)
+ ON CONFLICT(nonce_digest) DO UPDATE SET
+ plan_hash = excluded.plan_hash,
+ expires_at = excluded.expires_at,
+ issued_at = excluded.issued_at
+ WHERE issued_confirmations.plan_hash = excluded.plan_hash
+ """,
+ (nonce_digest, plan_hash, expires_at, issued_at),
+ )
+ row = connection.execute(
+ """
+ SELECT plan_hash, expires_at FROM issued_confirmations
+ WHERE nonce_digest = ?
+ """,
+ (nonce_digest,),
+ ).fetchone()
+ if row != (plan_hash, expires_at):
+ raise ConfirmationPlanMismatchError
+ except (ConfirmationPlanExpiredError, ConfirmationPlanMismatchError):
+ raise
+ except (OSError, sqlite3.Error) as exc:
+ raise ConfirmationStoreUnavailableError from exc
+
+ def consume(self, *, nonce: str, plan_hash: str, expires_at: int) -> None:
+ """Atomically validate and consume a server-issued dry-run plan."""
+ nonce_digest = hashlib.sha256(nonce.encode("utf-8")).hexdigest()
+ consumed_at = int(time.time())
+
+ try:
+ self._prepare_storage()
+ with sqlite3.connect(self.database_path, timeout=30) as connection:
+ connection.execute("PRAGMA synchronous = FULL")
+ self._ensure_schema(connection)
+ try:
+ self._cleanup_expired(connection, consumed_at)
+ except sqlite3.Error:
+ connection.rollback()
+ try:
+ connection.execute("BEGIN IMMEDIATE")
+ consumed = connection.execute(
+ """
+ SELECT 1 FROM consumed_confirmations
+ WHERE nonce_digest = ? LIMIT 1
+ """,
+ (nonce_digest,),
+ ).fetchone()
+ if consumed is not None:
+ raise ConfirmationAlreadyUsedError
+ issued = connection.execute(
+ """
+ SELECT plan_hash, expires_at, issued_at
+ FROM issued_confirmations WHERE nonce_digest = ?
+ """,
+ (nonce_digest,),
+ ).fetchone()
+ if issued is None:
+ raise ConfirmationNotIssuedError
+ issued_hash, issued_expires_at, issued_at = issued
+ if issued_hash != plan_hash or issued_expires_at != int(expires_at):
+ raise ConfirmationPlanMismatchError
+ if (
+ consumed_at > issued_expires_at
+ or issued_expires_at > issued_at + DEFAULT_PLAN_TTL_SECONDS
+ ):
+ raise ConfirmationPlanExpiredError
+ connection.execute(
+ """
+ INSERT INTO consumed_confirmations (
+ nonce_digest, plan_hash, expires_at, consumed_at
+ ) VALUES (?, ?, ?, ?)
+ """,
+ (nonce_digest, plan_hash, int(expires_at), consumed_at),
+ )
+ connection.execute(
+ "DELETE FROM issued_confirmations WHERE nonce_digest = ?",
+ (nonce_digest,),
+ )
+ connection.commit()
+ except sqlite3.IntegrityError as exc:
+ raise ConfirmationAlreadyUsedError from exc
+ except (
+ ConfirmationAlreadyUsedError,
+ ConfirmationNotIssuedError,
+ ConfirmationPlanMismatchError,
+ ConfirmationPlanExpiredError,
+ ):
+ raise
+ except (OSError, sqlite3.Error) as exc:
+ raise ConfirmationStoreUnavailableError from exc
+
+ def _cleanup_expired(
+ self, connection: sqlite3.Connection, current_time: int
+ ) -> None:
+ """Best-effort cleanup that never authorizes or blocks a current plan."""
+ connection.execute(
+ "DELETE FROM consumed_confirmations WHERE expires_at < ?",
+ (current_time,),
+ )
+ connection.execute(
+ "DELETE FROM issued_confirmations WHERE expires_at < ?",
+ (current_time,),
+ )
+ connection.commit()
+
+ def _ensure_schema(self, connection: sqlite3.Connection) -> None:
+ """Create additive tables so existing confirmation databases remain valid."""
+ connection.execute(
+ """
+ CREATE TABLE IF NOT EXISTS consumed_confirmations (
+ nonce_digest TEXT PRIMARY KEY,
+ plan_hash TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ consumed_at INTEGER NOT NULL
+ )
+ """
+ )
+ connection.execute(
+ """
+ CREATE TABLE IF NOT EXISTS issued_confirmations (
+ nonce_digest TEXT PRIMARY KEY,
+ plan_hash TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ issued_at INTEGER NOT NULL
+ )
+ """
+ )
+ connection.commit()
+
+ def _prepare_storage(self) -> None:
+ self.state_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
+ _restrict_permissions(self.state_dir, 0o700)
+
+ descriptor = os.open(
+ self.database_path,
+ os.O_CREAT | os.O_APPEND | os.O_WRONLY,
+ 0o600,
+ )
+ os.close(descriptor)
+ _restrict_permissions(self.database_path, 0o600)
+
+
+def _restrict_permissions(path: Path, mode: int) -> None:
+ try:
+ path.chmod(mode)
+ except (NotImplementedError, OSError):
+ if os.name == "posix":
+ raise
diff --git a/hugegraph-mcp/hugegraph_mcp/envelope.py b/hugegraph-mcp/hugegraph_mcp/envelope.py
new file mode 100644
index 00000000..e8294f8b
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/envelope.py
@@ -0,0 +1,260 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""统一响应信封 — 所有 MCP 工具通过 envelope_ok/envelope_err 返回一致结构。
+
+强制格式: {ok, data, error, warnings, next_actions, meta}
+前端/Agent 无需猜测返回形状,始终可安全解析。"""
+
+import json
+import re
+from enum import Enum
+from typing import Any
+from uuid import uuid4
+
+from hugegraph_mcp.config import MCPConfig
+
+REDACTED_VALUE = "***REDACTED***"
+SENSITIVE_KEY_PARTS = (
+ "api_key",
+ "authorization",
+ "password",
+ "passwd",
+ "pwd",
+ "secret",
+ "token",
+)
+
+
+class ErrorType(str, Enum):
+ """标准化错误类型枚举 — 按能力域划分,便于 Agent 分类处理。"""
+
+ CONNECTION_FAILED = "CONNECTION_FAILED"
+ AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"
+ AUTHORIZATION_FAILED = "AUTHORIZATION_FAILED"
+ VALIDATION_ERROR = "VALIDATION_ERROR"
+ READONLY_VIOLATION = "READONLY_VIOLATION"
+ CONFIRM_REQUIRED = "CONFIRM_REQUIRED"
+ PLAN_HASH_MISMATCH = "PLAN_HASH_MISMATCH"
+ PLAN_EXPIRED = "PLAN_EXPIRED"
+ PLAN_ALREADY_USED = "PLAN_ALREADY_USED"
+ TARGET_CHANGED = "TARGET_CHANGED"
+ PARTIAL_APPLY = "PARTIAL_APPLY"
+ NOT_FOUND = "NOT_FOUND"
+ NO_INDEX = "NO_INDEX"
+ UNSAFE_GREMLIN = "UNSAFE_GREMLIN"
+ QUERY_SYNTAX_ERROR = "QUERY_SYNTAX_ERROR"
+ SERVER_ERROR = "SERVER_ERROR"
+ SCHEMA_MISMATCH = "SCHEMA_MISMATCH"
+ INVALID_GRAPH_DATA = "INVALID_GRAPH_DATA"
+ HUGEGRAPH_AI_UNAVAILABLE = "HUGEGRAPH_AI_UNAVAILABLE"
+ FEATURE_DISABLED = "FEATURE_DISABLED"
+ FLOW_EXECUTION_FAILED = "FLOW_EXECUTION_FAILED"
+ LLM_FAILED = "LLM_FAILED"
+ EMBEDDING_FAILED = "EMBEDDING_FAILED"
+ TIMEOUT = "TIMEOUT"
+
+
+def generate_request_id() -> str:
+ return f"req-{uuid4().hex[:12]}"
+
+
+def sanitize_for_response(value: Any) -> Any:
+ """Redact common secret shapes before returning MCP envelopes."""
+
+ if isinstance(value, dict):
+ return {
+ key: REDACTED_VALUE
+ if _is_sensitive_key(key)
+ else sanitize_for_response(item)
+ for key, item in value.items()
+ }
+ if isinstance(value, list):
+ return [sanitize_for_response(item) for item in value]
+ if isinstance(value, tuple):
+ return tuple(sanitize_for_response(item) for item in value)
+ if isinstance(value, bytes):
+ value = value.decode("utf-8", errors="replace")
+ if isinstance(value, str):
+ return _sanitize_text(value)
+ return value
+
+
+def _is_sensitive_key(key: Any) -> bool:
+ key_lower = str(key).lower()
+ return any(part in key_lower for part in SENSITIVE_KEY_PARTS)
+
+
+def _sanitize_text(value: str) -> str:
+ if not _may_contain_sensitive_marker(value):
+ return _redact_url_userinfo(value)
+ try:
+ parsed = json.loads(value)
+ except json.JSONDecodeError:
+ redacted = re.sub(
+ r'(?i)("?[a-z0-9_-]*(?:api_key|authorization|password|passwd|pwd|secret|token)[a-z0-9_-]*"?\s*[:=]\s*)"[^"]*"',
+ rf"\1\"{REDACTED_VALUE}\"",
+ value,
+ )
+ redacted = re.sub(
+ r"(?i)(api_key|authorization|password|passwd|pwd|secret|token)=([^&\s]+)",
+ rf"\1={REDACTED_VALUE}",
+ redacted,
+ )
+ redacted = re.sub(
+ r"(?i)((?:api_key|authorization|password|passwd|pwd|secret|token)\s*:\s*)"
+ r"([^,\"'\n]+)",
+ rf"\1{REDACTED_VALUE}",
+ redacted,
+ )
+ redacted = re.sub(
+ r"(?i)('[a-z0-9_-]*(?:api_key|authorization|password|passwd|pwd|secret|token)"
+ r"[a-z0-9_-]*'\s*:\s*)'[^']*'",
+ rf"\1'{REDACTED_VALUE}'",
+ redacted,
+ )
+ redacted = re.sub(
+ r"(?i)\b(api_key|authorization|password|passwd|pwd|secret|token)"
+ r"(\s*[:=]?\s+)([a-z0-9_.\-]{4,})\b",
+ rf"\1\2{REDACTED_VALUE}",
+ redacted,
+ )
+ return _redact_url_userinfo(redacted)
+ return json.dumps(sanitize_for_response(parsed), ensure_ascii=False)
+
+
+def _may_contain_sensitive_marker(value: str) -> bool:
+ lowered = value.lower()
+ return any(part in lowered for part in SENSITIVE_KEY_PARTS) or "://" in lowered
+
+
+def _redact_url_userinfo(value: str) -> str:
+ return re.sub(r"(https?://)([^/@\s]+)@", rf"\1{REDACTED_VALUE}@", value)
+
+
+def build_meta(
+ *,
+ duration_ms: float | None = None,
+ request_id: str | None = None,
+ graph: str | None = None,
+ graphspace: str | None = None,
+ readonly: bool | None = None,
+ extra_meta: dict[str, Any] | None = None,
+ **kwargs: Any,
+) -> dict[str, Any]:
+ cfg = MCPConfig.from_env()
+ meta = {
+ "request_id": request_id or generate_request_id(),
+ "graph": cfg.graph if graph is None else graph,
+ "graphspace": cfg.graphspace if graphspace is None else graphspace,
+ "readonly": cfg.readonly if readonly is None else readonly,
+ }
+
+ if duration_ms is not None:
+ meta["duration_ms"] = duration_ms
+ if extra_meta:
+ meta.update(extra_meta)
+ if kwargs:
+ meta.update(kwargs)
+
+ return meta
+
+
+def envelope_ok(
+ data: Any = None,
+ *,
+ duration_ms: float | None = None,
+ warnings: list[str] | tuple[str, ...] | None = None,
+ next_actions: list[str] | None = None,
+ meta: dict[str, Any] | None = None,
+ request_id: str | None = None,
+ graph: str | None = None,
+ graphspace: str | None = None,
+ readonly: bool | None = None,
+ **meta_fields: Any,
+) -> dict[str, Any]:
+ envelope_meta = build_meta(
+ duration_ms=duration_ms,
+ request_id=request_id,
+ graph=graph,
+ graphspace=graphspace,
+ readonly=readonly,
+ extra_meta=meta,
+ **meta_fields,
+ )
+ return {
+ "ok": True,
+ "data": data,
+ "error": None,
+ "warnings": list(warnings or []),
+ "next_actions": list(next_actions or []),
+ "meta": envelope_meta,
+ }
+
+
+def envelope_err(
+ error_type: ErrorType | str,
+ message: str,
+ *,
+ suggestion: str | None = None,
+ retryable: bool = False,
+ source: str = "hugegraph-mcp",
+ details: Any = None,
+ duration_ms: float | None = None,
+ warnings: list[str] | tuple[str, ...] | None = None,
+ next_actions: list[str] | None = None,
+ meta: dict[str, Any] | None = None,
+ request_id: str | None = None,
+ graph: str | None = None,
+ graphspace: str | None = None,
+ readonly: bool | None = None,
+ **meta_fields: Any,
+) -> dict[str, Any]:
+ error_value = (
+ error_type.value if isinstance(error_type, ErrorType) else str(error_type)
+ )
+ error: dict[str, Any] = {
+ "type": error_value,
+ "message": sanitize_for_response(message),
+ "suggestion": sanitize_for_response(suggestion),
+ "retryable": retryable,
+ "source": source,
+ "details": sanitize_for_response(details) if details is not None else {},
+ }
+
+ envelope_meta = build_meta(
+ duration_ms=duration_ms,
+ request_id=request_id,
+ graph=graph,
+ graphspace=graphspace,
+ readonly=readonly,
+ extra_meta=meta,
+ **meta_fields,
+ )
+ return {
+ "ok": False,
+ "data": None,
+ "error": error,
+ "warnings": list(warnings or []),
+ "next_actions": list(next_actions or []),
+ "meta": envelope_meta,
+ }
+
+
+# Backward-compatible aliases — older code may use several names for the same function.
+make_ok_envelope = envelope_ok
+make_err_envelope = envelope_err
+ok_envelope = envelope_ok
+err_envelope = envelope_err
+ok = envelope_ok
+err = envelope_err
diff --git a/hugegraph-mcp/hugegraph_mcp/error_mapping.py b/hugegraph-mcp/hugegraph_mcp/error_mapping.py
new file mode 100644
index 00000000..068a4cbd
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/error_mapping.py
@@ -0,0 +1,132 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Shared HugeGraph exception classification helpers."""
+
+from dataclasses import dataclass
+
+from pyhugegraph.utils.exceptions import (
+ DataFormatError,
+ InvalidParameterError,
+ NotAuthorizedError,
+ NotFoundError,
+ ResponseParseError,
+ ServerError,
+ ServiceUnavailableError,
+)
+
+from hugegraph_mcp.envelope import ErrorType
+
+
+@dataclass(frozen=True)
+class ErrorClassification:
+ error_type: ErrorType
+ retryable: bool
+ suggestion: str
+ reason: str
+
+
+NO_INDEX_MARKERS = (
+ "noindexexception",
+ "no index",
+ "not indexed",
+ "may not match secondary condition",
+)
+SCHEMA_MISSING_MARKERS = (
+ "property key does not exist",
+ "propertykey does not exist",
+ "vertex label does not exist",
+ "vertexlabel does not exist",
+ "edge label does not exist",
+ "edgelabel does not exist",
+ "schema does not exist",
+)
+NOT_FOUND_MARKERS = (
+ "404",
+ "notfound",
+ "not found",
+ "not exist",
+ "does not exist",
+)
+
+
+def classify_hugegraph_exception(exc: Exception) -> ErrorClassification:
+ if isinstance(exc, NotAuthorizedError):
+ return ErrorClassification(
+ error_type=ErrorType.AUTHENTICATION_FAILED,
+ retryable=False,
+ suggestion="Check HUGEGRAPH_USER and HUGEGRAPH_PASSWORD.",
+ reason="authentication_error",
+ )
+ if isinstance(exc, NotFoundError):
+ return ErrorClassification(
+ error_type=ErrorType.NOT_FOUND,
+ retryable=False,
+ suggestion="Verify the graph, graphspace, and endpoint before retrying.",
+ reason="not_found_error",
+ )
+ if isinstance(exc, (InvalidParameterError, DataFormatError)):
+ return ErrorClassification(
+ error_type=ErrorType.VALIDATION_ERROR,
+ retryable=False,
+ suggestion="Check the request parameters and data format.",
+ reason="validation_error",
+ )
+ if isinstance(exc, ServiceUnavailableError):
+ return ErrorClassification(
+ error_type=ErrorType.SERVER_ERROR,
+ retryable=True,
+ suggestion="Retry after checking HugeGraph Server availability.",
+ reason="server_error",
+ )
+ if isinstance(exc, ResponseParseError):
+ return ErrorClassification(
+ error_type=ErrorType.SERVER_ERROR,
+ retryable=False,
+ suggestion="Check the HugeGraph response and client/server compatibility.",
+ reason="server_error",
+ )
+ if isinstance(exc, ServerError):
+ return classify_hugegraph_error_message(str(exc))
+ return classify_hugegraph_error_message(str(exc))
+
+
+def classify_hugegraph_error_message(message: str) -> ErrorClassification:
+ lowered = message.lower()
+ if any(marker in lowered for marker in NO_INDEX_MARKERS):
+ return ErrorClassification(
+ error_type=ErrorType.NO_INDEX,
+ retryable=False,
+ suggestion="Create an index for this condition query or retry with exact id lookup.",
+ reason="no_index",
+ )
+ if any(marker in lowered for marker in SCHEMA_MISSING_MARKERS):
+ return ErrorClassification(
+ error_type=ErrorType.SCHEMA_MISMATCH,
+ retryable=False,
+ suggestion="Check the live schema, label, and property key before retrying.",
+ reason="schema_missing",
+ )
+ if any(marker in lowered for marker in NOT_FOUND_MARKERS):
+ return ErrorClassification(
+ error_type=ErrorType.NOT_FOUND,
+ retryable=False,
+ suggestion="Verify the id, target type, graph, and graphspace before retrying.",
+ reason="not_found",
+ )
+ return ErrorClassification(
+ error_type=ErrorType.SERVER_ERROR,
+ retryable=True,
+ suggestion="Check query parameters and HugeGraph Server availability.",
+ reason="server_error",
+ )
diff --git a/hugegraph-mcp/hugegraph_mcp/gremlin_policy.py b/hugegraph-mcp/hugegraph_mcp/gremlin_policy.py
new file mode 100644
index 00000000..5afd387f
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/gremlin_policy.py
@@ -0,0 +1,371 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""GremlinPolicy — 统一的 Gremlin 安全策略层。
+
+所有 MCP Gremlin 读执行路径通过 GremlinPolicy.check_read() 做安全检查。
+返回结构化决策,包含 allowed、classification、reason、error_type、suggestion。
+
+本模块同时拥有 Gremlin 安全分类器的实现(原 gremlin_safety.py)。
+gremlin_safety.py 保留为兼容 wrapper,重新导出公共 API。
+"""
+
+from __future__ import annotations
+
+import os
+import re
+from dataclasses import dataclass
+from typing import Literal
+
+GremlinClassification = Literal["safe", "unsafe", "uncertain"]
+GremlinSafety = GremlinClassification # Compatibility alias.
+
+# ========== Classifier constants ==========
+
+_METHOD_RE = re.compile(r"\.\s*([A-Za-z_][A-Za-z0-9_]*)\s*\(")
+_QUOTED_OR_DYNAMIC_MEMBER_RE = re.compile(r"\.\s*(?:['\"]|\()")
+_READ_START_RE = re.compile(r"^\s*g\s*\.\s*(?:V|E)\s*\(", re.IGNORECASE)
+_DYNAMIC_MARKERS = ("${", "#{", "->")
+_MAX_REPEAT_TIMES = 10
+_ALLOWED_ARG_TOKENS = {"true", "false", "null"}
+_WRITE_METHODS = {
+ "addv",
+ "adde",
+ "drop",
+ "dropv",
+ "drope",
+ "remove",
+ "clear",
+ "sideeffect",
+ "io",
+ "call",
+ "program",
+}
+_READ_METHODS = {
+ "v",
+ "e",
+ "count",
+ "limit",
+ "range",
+ "has",
+ "haslabel",
+ "hasid",
+ "values",
+ "valuemap",
+ "id",
+ "label",
+ "keys",
+ "elementmap",
+ "properties",
+ "out",
+ "in",
+ "both",
+ "oute",
+ "ine",
+ "bothe",
+ "outv",
+ "inv",
+ "bothv",
+ "otherv",
+ "path",
+ "order",
+ "group",
+ "groupcount",
+ "by",
+ "dedup",
+ "sample",
+ "where",
+ "not",
+ "and",
+ "or",
+ "as",
+ "select",
+ "unfold",
+ "coalesce",
+ "optional",
+ "repeat",
+ "times",
+ "until",
+ "emit",
+ "simplepath",
+ "cyclicpath",
+ "skip",
+ "tail",
+ "tolist",
+ "toset",
+ "explain",
+ "profile",
+}
+_ANONYMOUS_READ_METHODS = {"outv", "inv", "bothv", "otherv"}
+
+
+# ========== Classifier implementation ==========
+
+
+def classify_gremlin_read_safety(gremlin_query: str) -> GremlinSafety:
+ """Classify a Gremlin query for use by the read-only execution tool.
+
+ The classifier intentionally rejects ambiguous queries. It is a conservative
+ safety gate, not a complete Gremlin parser.
+ """
+
+ if not isinstance(gremlin_query, str) or not gremlin_query.strip():
+ return "uncertain"
+
+ query_without_strings = _strip_string_literals(gremlin_query)
+ methods = _extract_method_names(query_without_strings)
+ lowered_methods = [method.lower() for method in methods]
+
+ if _has_unsafe_write_steps(query_without_strings, lowered_methods):
+ return "unsafe"
+
+ if _has_dynamic_construction_markers(gremlin_query, query_without_strings):
+ return "uncertain"
+
+ if not _READ_START_RE.search(query_without_strings):
+ return "uncertain"
+
+ if any(method not in _READ_METHODS for method in lowered_methods):
+ return "uncertain"
+
+ return "safe"
+
+
+def is_safe_gremlin_read(gremlin_query: str) -> bool:
+ """Return True only when the query is confidently read-only."""
+ return classify_gremlin_read_safety(gremlin_query) == "safe"
+
+
+def _extract_method_names(query_without_strings: str) -> list[str]:
+ return _METHOD_RE.findall(query_without_strings)
+
+
+def _has_unsafe_write_steps(
+ query_without_strings: str, lowered_methods: list[str]
+) -> bool:
+ if any(method in _WRITE_METHODS for method in lowered_methods):
+ return True
+
+ if "property" in lowered_methods:
+ return True
+
+ if "iterate" in lowered_methods:
+ return True
+
+ return bool(
+ re.search(r"\.\s*[VE]\s*\([^)]*\)\s*\.\s*drop\s*\(", query_without_strings)
+ )
+
+
+def _has_dynamic_construction_markers(
+ original_query: str, query_without_strings: str
+) -> bool:
+ # Groovy permits quoted and parenthesized member names (for example
+ # `g.V().'drop'()`), which disappear when string literals are stripped.
+ # Treat them as ambiguous so a write step cannot masquerade as a read.
+ if _QUOTED_OR_DYNAMIC_MEMBER_RE.search(original_query):
+ return True
+
+ if any(marker in original_query for marker in _DYNAMIC_MARKERS):
+ return True
+
+ if "+" in query_without_strings:
+ return True
+
+ if "{" in query_without_strings or "}" in query_without_strings:
+ return True
+
+ if ";" in query_without_strings:
+ return True
+
+ if re.search(
+ r"(?:^|[;\s])(?:def|var|String|query)\s+\w+\s*=", query_without_strings
+ ):
+ return True
+
+ return _has_bare_identifier_arguments(query_without_strings)
+
+
+def _has_bare_identifier_arguments(query_without_strings: str) -> bool:
+ cleaned = re.sub(
+ r"\.\s*[A-Za-z_][A-Za-z0-9_]*",
+ " ",
+ query_without_strings,
+ )
+ for method in _ANONYMOUS_READ_METHODS:
+ cleaned = re.sub(
+ rf"\b{method}\s*\(",
+ "(",
+ cleaned,
+ flags=re.IGNORECASE,
+ )
+ cleaned = re.sub(r"^\s*[gG]\b", " ", cleaned)
+ for token_match in re.finditer(r"\b[A-Za-z_][A-Za-z0-9_]*\b", cleaned):
+ token = token_match.group(0).lower()
+ if token not in _ALLOWED_ARG_TOKENS:
+ return True
+
+ return False
+
+
+def _strip_string_literals(query: str) -> str:
+ """Replace string literal contents with spaces while preserving structure."""
+
+ result: list[str] = []
+ quote: str | None = None
+ escaped = False
+
+ for char in query:
+ if quote is None:
+ if char in {"'", '"'}:
+ quote = char
+ result.append(char)
+ else:
+ result.append(char)
+ continue
+
+ if escaped:
+ escaped = False
+ result.append(" ")
+ elif char == "\\":
+ escaped = True
+ result.append(" ")
+ elif char == quote:
+ quote = None
+ result.append(char)
+ else:
+ result.append(" ")
+
+ if quote is not None:
+ return query
+
+ return "".join(result)
+
+
+# ========== Structured decision ==========
+
+
+@dataclass(frozen=True)
+class GremlinDecision:
+ """Gremlin 安全检查的结构化决策。"""
+
+ allowed: bool
+ classification: GremlinClassification
+ reason: str
+ error_type: str | None
+ suggestion: str | None
+
+
+class GremlinPolicy:
+ """统一的 Gremlin 安全策略。
+
+ 所有 MCP Gremlin 读执行路径必须通过 check_read() 检查。
+ """
+
+ def check_read(self, gremlin_query: str) -> GremlinDecision:
+ """检查 Gremlin 查询是否允许作为只读查询执行。"""
+ classification = classify_gremlin_read_safety(gremlin_query)
+
+ if classification == "safe":
+ return GremlinDecision(
+ allowed=True,
+ classification="safe",
+ reason="Query is a known read-only traversal.",
+ error_type=None,
+ suggestion=None,
+ )
+
+ if classification == "unsafe":
+ return GremlinDecision(
+ allowed=False,
+ classification="unsafe",
+ reason="Query contains write or mutate operations.",
+ error_type="UNSAFE_GREMLIN",
+ suggestion=(
+ "Use execute_gremlin_write for write operations "
+ "when write access is enabled."
+ ),
+ )
+
+ # classification == "uncertain"
+ return GremlinDecision(
+ allowed=False,
+ classification="uncertain",
+ reason="Query contains unknown or ambiguous steps; cannot confirm read-only safety.",
+ error_type="UNSAFE_GREMLIN",
+ suggestion="Use a clearly read-only Gremlin traversal starting with g.V() or g.E().",
+ )
+
+
+# Module-level singleton.
+_policy = GremlinPolicy()
+
+
+def check_gremlin_read(gremlin_query: str) -> GremlinDecision:
+ """便捷函数:使用默认策略检查 Gremlin 查询。"""
+ return _policy.check_read(gremlin_query)
+
+
+def _parse_repeat_threshold() -> int:
+ value = os.getenv("HUGEGRAPH_MCP_MAX_REPEAT_TIMES")
+ if value is None or value.strip() == "":
+ return _MAX_REPEAT_TIMES
+ try:
+ parsed = int(value)
+ except ValueError:
+ return _MAX_REPEAT_TIMES
+ if parsed <= 0:
+ return _MAX_REPEAT_TIMES
+ return parsed
+
+
+def gremlin_cost_warnings(gremlin_query: str) -> list[str]:
+ """轻量成本边界检查:只产 warning 不阻断。非完整 parser,仅挡明显风险。"""
+
+ query_without_strings = _strip_string_literals(gremlin_query)
+ methods = [
+ method.lower() for method in _extract_method_names(query_without_strings)
+ ]
+ method_set = set(methods)
+ warnings: list[str] = []
+
+ if method_set.isdisjoint({"limit", "range", "count"}):
+ warnings.append(
+ "Unbounded traversal: result set is not limited; consider adding "
+ ".limit() or .range()."
+ )
+
+ if "repeat" in method_set:
+ if "times" not in method_set:
+ warnings.append(
+ "repeat() without times() may recurse without an explicit depth bound."
+ )
+ else:
+ max_times = _parse_repeat_threshold()
+ match = re.search(r"times\(\s*(\d+)\s*\)", query_without_strings)
+ if match is not None:
+ depth = int(match.group(1))
+ if depth > max_times:
+ warnings.append(
+ f"repeat().times(n) depth {depth} exceeds recommended "
+ f"maximum {max_times}."
+ )
+
+ if any(
+ method in method_set for method in ("path", "group", "profile")
+ ) and method_set.isdisjoint({"limit", "range"}):
+ warnings.append(
+ "Heavy step (path/group/profile) without limit/range may be expensive."
+ )
+
+ return list(dict.fromkeys(warnings))
diff --git a/hugegraph-mcp/hugegraph_mcp/gremlin_safety.py b/hugegraph-mcp/hugegraph_mcp/gremlin_safety.py
new file mode 100644
index 00000000..087a9420
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/gremlin_safety.py
@@ -0,0 +1,34 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Gremlin 安全分类器 — 兼容 wrapper。
+
+.. deprecated::
+ 实际实现已迁入 gremlin_policy.py。本模块保留公共 API 以兼容现有导入。
+ 新代码应使用 gremlin_policy.check_gremlin_read() 或 GremlinPolicy.check_read()。
+
+原模块文档:
+ 不是完整的 Gremlin parser,而是保守的安全门:
+ - safe: 明确只读遍历(g.V()/g.E() + 已知只读方法)
+ - unsafe: 检测到 write/mutate 方法或模式
+ - uncertain: 无法确定 → 拒绝执行
+
+ 宁可误拒 ambiguous 查询,也不放行潜在写操作。
+"""
+
+# Compatibility imports: re-export the public API from gremlin_policy.
+from hugegraph_mcp.gremlin_policy import ( # noqa: F401
+ GremlinSafety,
+ classify_gremlin_read_safety,
+ is_safe_gremlin_read,
+)
diff --git a/hugegraph-mcp/hugegraph_mcp/gremlin_tools.py b/hugegraph-mcp/hugegraph_mcp/gremlin_tools.py
new file mode 100644
index 00000000..5d58fa60
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/gremlin_tools.py
@@ -0,0 +1,499 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Gremlin 执行层 — 封装 HugeGraph Gremlin 读写客户端。
+
+所有 Gremlin 查询统一通过 GremlinExecutor 执行,对连接失败/认证错误/
+HTTP 错误/语法错误做结构化错误收集,不抛异常到上层。
+"""
+
+import time
+from typing import Any
+
+import requests
+from pyhugegraph.client import PyHugeClient
+from pyhugegraph.utils.exceptions import (
+ DataFormatError,
+ InvalidParameterError,
+ NotAuthorizedError,
+ NotFoundError,
+ ResponseParseError,
+ ServerError,
+ ServiceUnavailableError,
+)
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+from hugegraph_mcp.error_mapping import classify_hugegraph_exception
+from hugegraph_mcp.gremlin_policy import check_gremlin_read, gremlin_cost_warnings
+from hugegraph_mcp.guard import Capability, guard_write
+from hugegraph_mcp.hugegraph_client import build_hugegraph_client
+
+
+class GremlinExecutor:
+ """封装 HugeGraph Gremlin 读写客户端,自动处理 graphspace 兼容性。
+
+ HugeGraph 1.7.0+ 支持 graph space,配置为空时回退到默认客户端。
+ """
+
+ def __init__(self, cfg: MCPConfig) -> None:
+ self._cfg = cfg
+
+ def _build_client(self) -> PyHugeClient:
+ return build_hugegraph_client(self._cfg, client_cls=PyHugeClient)
+
+ def get_read_client(self):
+ return self._build_client().gremlin()
+
+ def get_write_client(self):
+ return self._build_client().gremlin()
+
+
+_GREMLIN_ERROR_TYPE_MAP = {
+ "connection_error": ErrorType.CONNECTION_FAILED,
+ "timeout_error": ErrorType.TIMEOUT,
+ "authentication_error": ErrorType.AUTHENTICATION_FAILED,
+ "authorization_error": ErrorType.AUTHORIZATION_FAILED,
+ "no_index_error": ErrorType.NO_INDEX,
+ "query_syntax_error": ErrorType.QUERY_SYNTAX_ERROR,
+ "server_error": ErrorType.SERVER_ERROR,
+ "http_error": ErrorType.SERVER_ERROR,
+ "not_found_error": ErrorType.NOT_FOUND,
+ "unknown_error": ErrorType.SERVER_ERROR,
+ **{error_type.value: error_type for error_type in ErrorType},
+}
+LIMIT_POLICIES = frozenset({"warn", "reject_unbounded", "auto_append"})
+
+
+def _get_read_client():
+ return GremlinExecutor(MCPConfig.from_env()).get_read_client()
+
+
+def _get_write_client():
+ return GremlinExecutor(MCPConfig.from_env()).get_write_client()
+
+
+def _gremlin_error_envelope(result: dict[str, Any]) -> dict[str, Any]:
+ error_type = _GREMLIN_ERROR_TYPE_MAP.get(
+ result.get("error_type"),
+ ErrorType.SERVER_ERROR,
+ )
+ suggestions = result.get("suggestions") or []
+ suggestion = "; ".join(suggestions) if suggestions else None
+ return envelope_err(
+ error_type,
+ result.get("message", "Gremlin query failed"),
+ suggestion=suggestion,
+ retryable=_gremlin_error_retryable(result),
+ details=result,
+ duration_ms=result.get("duration_ms"),
+ )
+
+
+def _gremlin_error_retryable(result: dict[str, Any]) -> bool:
+ if "retryable" in result:
+ return bool(result["retryable"])
+ error_type = result.get("error_type")
+ if error_type in {"connection_error", "timeout_error"}:
+ return True
+ if error_type not in {"server_error", "http_error"}:
+ return False
+
+ try:
+ status_code = int(result.get("status_code"))
+ except (TypeError, ValueError):
+ return error_type == "server_error"
+ return status_code in {500, 502, 503, 504}
+
+
+def _gremlin_result_count(data: Any) -> int:
+ """Return the number of result items from HugeGraph/PyHugeGraph shapes."""
+ if data is None:
+ return 0
+ if isinstance(data, dict) and "data" in data:
+ inner_data = data.get("data")
+ if inner_data is None:
+ return 0
+ if isinstance(inner_data, (list, tuple, set)):
+ return len(inner_data)
+ return 1
+ if isinstance(data, (list, tuple, set)):
+ return len(data)
+ return 1
+
+
+def _is_no_index_error(message: Any) -> bool:
+ lowered = str(message).lower()
+ return "noindexexception" in lowered or "no index" in lowered
+
+
+def _no_index_error_result(
+ message: str,
+ duration_ms: float,
+ operation_type: str,
+) -> dict[str, Any]:
+ return {
+ "success": False,
+ "error_type": "no_index_error",
+ "message": message,
+ "suggestions": [
+ "Create an index for the queried property before using has() filters",
+ "Use primary-key based lookups when possible",
+ "Check HugeGraph schema index labels with inspect_graph_tool",
+ ],
+ "duration_ms": duration_ms,
+ "operation_type": operation_type,
+ }
+
+
+def _get_client_address(client) -> str:
+ """Extract server address from a pyhugegraph client for error messages.
+
+ pyhugegraph does not expose a public URL getter; we read the private
+ ``_url`` attribute with a ``hasattr`` guard as a last resort. This is
+ safe for error-reporting purposes only and should not be relied on for
+ logic.
+ """
+ if client is not None and hasattr(client, "_url"):
+ return str(client._url)
+ return "unknown address"
+
+
+def _execute_gremlin_with_error_handling(
+ client, gremlin_query: str, operation_type: str = "read"
+) -> dict[str, Any]:
+ """执行 Gremlin 查询并做结构化错误处理。
+
+ 连接失败、HTTP 错误、语法错误等均返回结构化 dict 而非抛异常,
+ 便于上层统一处理。区分 401/403/404/500 等状态码给出针对性建议。
+ """
+ start = time.perf_counter()
+ actual_client = None
+
+ try:
+ actual_client = client() if callable(client) else client
+ data = actual_client.exec(gremlin_query)
+ duration_ms = (time.perf_counter() - start) * 1000.0
+
+ return {
+ "success": True,
+ "data": data,
+ "count": _gremlin_result_count(data),
+ "duration_ms": duration_ms,
+ "operation_type": operation_type,
+ }
+
+ except requests.exceptions.ConnectionError:
+ address = _get_client_address(actual_client)
+ return {
+ "success": False,
+ "error_type": "connection_error",
+ "message": f"Cannot connect to HugeGraph server at {address}",
+ "suggestions": [
+ "Check if HugeGraph server is running",
+ "Verify the HUGEGRAPH_URL environment variable",
+ "Check network connectivity to the server",
+ ],
+ "duration_ms": (time.perf_counter() - start) * 1000.0,
+ "operation_type": operation_type,
+ }
+
+ except requests.exceptions.Timeout:
+ address = _get_client_address(actual_client)
+ return {
+ "success": False,
+ "error_type": "timeout_error",
+ "message": f"HugeGraph request timed out at {address}",
+ "suggestions": [
+ "Retry the request after checking HugeGraph server health",
+ "Verify the query is bounded and can complete within the client timeout",
+ "Check network latency to the server",
+ ],
+ "duration_ms": (time.perf_counter() - start) * 1000.0,
+ "operation_type": operation_type,
+ }
+
+ except requests.exceptions.HTTPError as e:
+ status_code = (
+ e.response.status_code
+ if hasattr(e, "response") and e.response
+ else "unknown"
+ )
+
+ if status_code == 401:
+ error_type = "authentication_error"
+ message = "Authentication failed - invalid credentials"
+ suggestions = [
+ "Check HUGEGRAPH_USER and HUGEGRAPH_PASSWORD environment variables",
+ "Verify user permissions in HugeGraph",
+ ]
+ elif status_code == 403:
+ error_type = "authorization_error"
+ message = "Authorization failed - insufficient permissions"
+ suggestions = [
+ "Check if the user has permission to execute Gremlin queries",
+ "Verify graph space permissions if using graph spaces",
+ ]
+ elif status_code == 404:
+ error_type = "not_found_error"
+ message = "Graph or endpoint not found"
+ suggestions = [
+ "Check if the graph name is correct",
+ "Verify the graph exists in HugeGraph",
+ ]
+ elif status_code == 500:
+ error_type = "server_error"
+ # Try to extract detailed HugeGraph error information from the response body.
+ detail_message = ""
+ try:
+ if hasattr(e, "response") and e.response is not None:
+ error_json = e.response.json()
+ detail_message = error_json.get("exception") or ""
+ if not detail_message:
+ detail_message = (
+ error_json.get("message")
+ or error_json.get("detail")
+ or error_json.get("error")
+ or str(error_json)
+ )
+ except Exception: # noqa: BLE001, S110 - best-effort error-body parsing
+ pass
+
+ if detail_message:
+ if _is_no_index_error(detail_message):
+ return _no_index_error_result(
+ f"Query requires an index: {detail_message}",
+ (time.perf_counter() - start) * 1000.0,
+ operation_type,
+ )
+ message = f"HugeGraph server internal error: {detail_message}"
+ else:
+ message = "HugeGraph server internal error"
+ suggestions = [
+ "Check the Gremlin query syntax",
+ "Verify all referenced vertex/edge labels exist",
+ "Check HugeGraph server logs for details",
+ "Ensure the query doesn't violate graph constraints",
+ ]
+ else:
+ error_type = "http_error"
+ message = f"HTTP error {status_code}"
+ suggestions = ["Check HugeGraph server status", "Verify the request format"]
+
+ return {
+ "success": False,
+ "error_type": error_type,
+ "message": message,
+ "status_code": status_code,
+ "suggestions": suggestions,
+ "duration_ms": (time.perf_counter() - start) * 1000.0,
+ "operation_type": operation_type,
+ }
+
+ except (
+ NotAuthorizedError,
+ NotFoundError,
+ InvalidParameterError,
+ DataFormatError,
+ ServiceUnavailableError,
+ ResponseParseError,
+ ServerError,
+ ) as e:
+ duration_ms = (time.perf_counter() - start) * 1000.0
+ if isinstance(e, (InvalidParameterError, DataFormatError)):
+ return {
+ "success": False,
+ "error_type": "query_syntax_error",
+ "message": str(e) or type(e).__name__,
+ "suggestions": ["Check the Gremlin query syntax and parameters."],
+ "retryable": False,
+ "duration_ms": duration_ms,
+ "operation_type": operation_type,
+ }
+ classification = classify_hugegraph_exception(e)
+ if classification.error_type == ErrorType.NO_INDEX:
+ return _no_index_error_result(str(e), duration_ms, operation_type)
+ return {
+ "success": False,
+ # Keep the internal reason for diagnostics; _gremlin_error_envelope
+ # maps it to the canonical public ErrorType.
+ "error_type": classification.reason,
+ "message": str(e) or type(e).__name__,
+ "suggestions": [classification.suggestion],
+ "retryable": classification.retryable,
+ "duration_ms": duration_ms,
+ "operation_type": operation_type,
+ }
+
+ except ValueError as e:
+ return {
+ "success": False,
+ "error_type": "query_syntax_error",
+ "message": f"Gremlin query syntax error: {e!s}",
+ "suggestions": [
+ "Check Gremlin query syntax",
+ "Verify all steps and parameters are valid",
+ "Ensure proper use of Gremlin traversal steps",
+ ],
+ "duration_ms": (time.perf_counter() - start) * 1000.0,
+ "operation_type": operation_type,
+ }
+
+ except Exception as e: # noqa: BLE001 - normalize every client failure
+ duration_ms = (time.perf_counter() - start) * 1000.0
+ message = f"Unexpected error: {e!s}"
+ if _is_no_index_error(message):
+ return _no_index_error_result(message, duration_ms, operation_type)
+ return {
+ "success": False,
+ "error_type": "unknown_error",
+ "message": message,
+ "suggestions": [
+ "Check HugeGraph server logs",
+ "Verify the query format and parameters",
+ "Try a simpler query to test connectivity",
+ ],
+ "duration_ms": duration_ms,
+ "operation_type": operation_type,
+ }
+
+
+def execute_gremlin_read(
+ gremlin_query: str,
+ *,
+ limit_policy: str = "warn",
+) -> dict[str, Any]:
+ """执行只读 Gremlin 查询。
+
+ 通过 GremlinPolicy.check_read() 做安全检查,
+ 拒绝写入类和无法确定的查询,只放行明确安全的遍历。
+ limit_policy:
+ - warn: 兼容默认,仅返回 unbounded warning。
+ - reject_unbounded: 安全但无界时拒绝执行。
+ - auto_append: 对简单无界遍历追加 .limit(100),并返回原始/实际查询。
+ 返回 {data, total, duration_ms, is_read}。
+ """
+ if limit_policy not in LIMIT_POLICIES:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ f"Unsupported limit_policy: {limit_policy!r}.",
+ suggestion="Use one of: warn, reject_unbounded, auto_append.",
+ details={"limit_policy": limit_policy},
+ )
+
+ decision = check_gremlin_read(gremlin_query)
+ if not decision.allowed:
+ return envelope_err(
+ ErrorType.UNSAFE_GREMLIN,
+ decision.reason,
+ suggestion=decision.suggestion,
+ details={"classification": decision.classification},
+ )
+
+ original_gremlin = gremlin_query
+ rewrite_reason = None
+ cost_warnings = gremlin_cost_warnings(gremlin_query)
+ unbounded = _has_unbounded_warning(cost_warnings)
+ if limit_policy == "reject_unbounded" and unbounded:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "Gremlin read query is unbounded and limit_policy='reject_unbounded'.",
+ suggestion="Add .limit(n) or .range(start, end), or use limit_policy='warn'.",
+ details={"gremlin_query": gremlin_query, "warnings": cost_warnings},
+ warnings=cost_warnings,
+ )
+ if limit_policy == "auto_append" and unbounded:
+ rewritten = _auto_append_limit(gremlin_query)
+ if rewritten is None:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "Cannot safely auto-append limit to this Gremlin query.",
+ suggestion=(
+ "Add an explicit .limit(n) yourself, or use limit_policy='warn'."
+ ),
+ details={"gremlin_query": gremlin_query, "warnings": cost_warnings},
+ warnings=cost_warnings,
+ )
+ gremlin_query = rewritten
+ rewrite_reason = "limit_policy='auto_append' added .limit(100) to an unbounded read traversal."
+ cost_warnings = gremlin_cost_warnings(gremlin_query)
+
+ result = _execute_gremlin_with_error_handling(
+ _get_read_client, gremlin_query, "read"
+ )
+
+ if result.get("success"):
+ duration_ms = result["duration_ms"]
+ return envelope_ok(
+ {
+ "data": result["data"],
+ "total": result["count"],
+ "duration_ms": duration_ms,
+ "is_read": True,
+ "limit_policy": limit_policy,
+ "original_gremlin": original_gremlin,
+ "executed_gremlin": gremlin_query,
+ "rewrite_reason": rewrite_reason,
+ },
+ duration_ms=duration_ms,
+ warnings=cost_warnings,
+ )
+ else:
+ return _gremlin_error_envelope(result)
+
+
+def _has_unbounded_warning(warnings: list[str]) -> bool:
+ return any("Unbounded traversal" in warning for warning in warnings)
+
+
+def _auto_append_limit(gremlin_query: str) -> str | None:
+ stripped = gremlin_query.strip()
+ if not stripped.endswith(")"):
+ return None
+ lowered = stripped.lower()
+ if any(step in lowered for step in (".group(", ".path(", ".profile(", ".repeat(")):
+ return None
+ return f"{stripped}.limit(100)"
+
+
+def execute_gremlin_write(
+ gremlin_query: str,
+ *,
+ capability: Capability = Capability.DATA_WRITE,
+) -> dict[str, Any]:
+ """执行 Gremlin 写查询。
+
+ readonly 模式下通过 guard_write 拒绝执行,
+ 正常模式返回 {success, affected, duration_ms, is_write}。
+ """
+
+ violation = guard_write(capability)
+ if violation is not None:
+ return violation
+
+ result = _execute_gremlin_with_error_handling(
+ _get_write_client, gremlin_query, "write"
+ )
+
+ if result.get("success"):
+ duration_ms = result["duration_ms"]
+ return envelope_ok(
+ {
+ "affected": result["count"],
+ "duration_ms": duration_ms,
+ "is_write": True,
+ },
+ duration_ms=duration_ms,
+ )
+ else:
+ return _gremlin_error_envelope(result)
diff --git a/hugegraph-mcp/hugegraph_mcp/guard.py b/hugegraph-mcp/hugegraph_mcp/guard.py
new file mode 100644
index 00000000..4c968b59
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/guard.py
@@ -0,0 +1,85 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""权限守卫 — 统一的能力检查入口。
+
+readonly 模式下只允许 READ + GENERATE 能力,其他操作返回 READONLY_VIOLATION 信封。
+不抛异常:调用方检查返回值是否是 envelope_err 即可。"""
+
+from enum import Enum
+from typing import Any
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import ErrorType, envelope_err
+
+
+class Capability(str, Enum):
+ READ = "READ"
+ GENERATE = "GENERATE"
+ DATA_WRITE = "DATA_WRITE"
+ SCHEMA_WRITE = "SCHEMA_WRITE"
+ INDEX_WRITE = "INDEX_WRITE"
+ DEBUG_WRITE = "DEBUG_WRITE"
+
+
+READONLY_ALLOWED_CAPABILITIES = frozenset(
+ {
+ Capability.READ,
+ Capability.GENERATE,
+ }
+)
+
+
+def is_allowed_in_readonly(capability: Capability) -> bool:
+ return capability in READONLY_ALLOWED_CAPABILITIES
+
+
+def guard(
+ capability: Capability,
+ *,
+ cfg: MCPConfig | None = None,
+) -> dict[str, Any] | None:
+ cfg = cfg or MCPConfig.from_env()
+ readonly = cfg.is_readonly()
+
+ if not readonly or is_allowed_in_readonly(capability):
+ return None
+
+ return envelope_err(
+ ErrorType.READONLY_VIOLATION,
+ f"{capability.value} capability is disabled in read-only mode",
+ suggestion="Disable HUGEGRAPH_MCP_READONLY to allow this operation.",
+ readonly=readonly,
+ graph=cfg.graph,
+ graphspace=cfg.graphspace,
+ capability=capability.value,
+ )
+
+
+def guard_write(
+ capability: Capability = Capability.DATA_WRITE,
+ *,
+ cfg: MCPConfig | None = None,
+) -> dict[str, Any] | None:
+ return guard(capability, cfg=cfg)
+
+
+def require_capability(
+ capability: Capability,
+ *,
+ cfg: MCPConfig | None = None,
+) -> None:
+ violation = guard(capability, cfg=cfg)
+ if violation is not None:
+ message = violation["error"]["message"]
+ raise PermissionError(message)
diff --git a/hugegraph-mcp/hugegraph_mcp/hugegraph_ai_client.py b/hugegraph-mcp/hugegraph_mcp/hugegraph_ai_client.py
new file mode 100644
index 00000000..cd6b59e0
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/hugegraph_ai_client.py
@@ -0,0 +1,299 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""HugeGraph-AI HTTP 客户端 — 统一请求层。
+
+所有 AI 调用经 request() 统一处理:allow_ai 开关检查、超时控制、
+Bearer Token 注入、结构化错误返回。不抛异常。
+"""
+
+import time
+from typing import Any
+from urllib.parse import urlsplit
+
+import requests
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+
+
+def request(
+ method: str,
+ path: str,
+ *,
+ cfg: MCPConfig | None = None,
+ json: Any = None,
+ params: dict[str, Any] | None = None,
+ headers: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ """调用 HugeGraph-AI 并返回标准化信封。
+
+ allow_ai=False 时直接拒绝,连接超时/HTTP 错误/JSON 解析失败均返回
+ 结构化错误信封,不抛异常。
+ """
+
+ start = time.perf_counter()
+ cfg = cfg or MCPConfig.from_env()
+ method = method.upper()
+
+ if not _is_relative_path(path):
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "Absolute URLs are not allowed; use a relative HugeGraph-AI path",
+ retryable=False,
+ duration_ms=_duration_ms(start),
+ details={"method": method, "reason": "absolute_url_not_allowed"},
+ )
+
+ url = _build_url(cfg.ai_url, path)
+
+ if not cfg.allow_ai:
+ return envelope_err(
+ ErrorType.FEATURE_DISABLED,
+ "AI calls are disabled by configuration",
+ suggestion=(
+ "Set HUGEGRAPH_MCP_ALLOW_AI=true and restart the MCP server, "
+ "or use tools that do not require HugeGraph-AI."
+ ),
+ retryable=False,
+ duration_ms=_duration_ms(start),
+ details={"method": method, "url": url, "reason": "allow_ai_false"},
+ )
+
+ try:
+ request_headers = dict(headers) if headers is not None else {}
+ if cfg.ai_token and not any(
+ name.lower() == "authorization" for name in request_headers
+ ):
+ request_headers["Authorization"] = f"Bearer {cfg.ai_token}"
+ kwargs: dict[str, Any] = {
+ "params": params,
+ "headers": request_headers or None,
+ "timeout": cfg.timeout_seconds,
+ }
+ if json is not None:
+ kwargs["json"] = json
+ response = requests.request(method, url, **kwargs)
+ try:
+ data = response.json()
+ except ValueError:
+ # Preserve status-aware handling for empty/HTML HTTP error bodies.
+ response.raise_for_status()
+ raise
+ if _is_thin_api_envelope(data) and not data["ok"]:
+ return _normalize_response(data, duration_ms=_duration_ms(start))
+ response.raise_for_status()
+ return _normalize_response(data, duration_ms=_duration_ms(start))
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as exc:
+ return _ai_error(
+ _exception_message("HugeGraph-AI is unavailable", exc),
+ duration_ms=_duration_ms(start),
+ retryable=True,
+ details={"method": method, "url": url},
+ )
+ except requests.exceptions.HTTPError as exc:
+ status_code = _status_code(exc)
+ details = {"method": method, "url": url, "status_code": status_code}
+ if status_code in {401, 403}:
+ return envelope_err(
+ ErrorType.AUTHORIZATION_FAILED,
+ _exception_message("HugeGraph-AI authorization failed", exc),
+ retryable=False,
+ details=details,
+ duration_ms=_duration_ms(start),
+ )
+ if isinstance(status_code, int) and 400 <= status_code < 500:
+ return _ai_error(
+ _exception_message("HugeGraph-AI request failed", exc),
+ duration_ms=_duration_ms(start),
+ retryable=status_code == 429,
+ details=details,
+ )
+ return _ai_error(
+ _exception_message("HugeGraph-AI is unavailable", exc),
+ duration_ms=_duration_ms(start),
+ retryable=True,
+ details=details,
+ )
+ except ValueError as exc:
+ return _ai_error(
+ _exception_message("HugeGraph-AI returned invalid JSON", exc),
+ duration_ms=_duration_ms(start),
+ details={"method": method, "url": url},
+ )
+ except requests.exceptions.RequestException as exc:
+ return _ai_error(
+ _exception_message("HugeGraph-AI request failed", exc),
+ duration_ms=_duration_ms(start),
+ retryable=True,
+ details={"method": method, "url": url},
+ )
+
+
+def get(
+ path: str,
+ *,
+ cfg: MCPConfig | None = None,
+ params: dict[str, Any] | None = None,
+ headers: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ return request("GET", path, cfg=cfg, params=params, headers=headers)
+
+
+def post(
+ path: str,
+ *,
+ cfg: MCPConfig | None = None,
+ json: Any = None,
+ params: dict[str, Any] | None = None,
+ headers: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ return request("POST", path, cfg=cfg, json=json, params=params, headers=headers)
+
+
+def health_check(*, cfg: MCPConfig | None = None) -> dict[str, Any]:
+ """尽力而为的 AI 健康检查 — 尝试多个端点探测 HugeGraph-AI 可用性。
+
+ 优先探查 /graph-index-info,失败时回退到 /openapi.json,
+ 401/403 立即返回不重试。
+ """
+
+ attempts: list[str] = []
+ last_result: dict[str, Any] | None = None
+ for path in ("/graph-index-info", "/openapi.json"):
+ result = get(path, cfg=cfg)
+ if result.get("ok"):
+ data = result.get("data")
+ if isinstance(data, dict):
+ result["data"] = {
+ "status": "available",
+ "health_endpoint": path,
+ **data,
+ }
+ else:
+ result["data"] = {
+ "status": "available",
+ "health_endpoint": path,
+ "response": data,
+ }
+ if attempts:
+ result["warnings"] = [*result.get("warnings", []), *attempts]
+ return result
+
+ last_result = result
+ error = result.get("error") or {}
+ details = error.get("details") or {}
+ status_code = details.get("status_code")
+ attempts.append(f"{path}: {error.get('message', 'unavailable')}")
+ if status_code in {401, 403}:
+ return result
+
+ if last_result is not None and attempts:
+ last_result["warnings"] = [*last_result.get("warnings", []), *attempts]
+ return last_result or get("/openapi.json", cfg=cfg)
+
+
+def _build_url(base_url: str, path: str) -> str:
+ return f"{base_url.rstrip('/')}/{path.lstrip('/')}"
+
+
+def _is_relative_path(path: str) -> bool:
+ try:
+ parsed = urlsplit(path)
+ except (TypeError, ValueError):
+ return False
+ return not parsed.scheme and not parsed.netloc
+
+
+def _duration_ms(start: float) -> float:
+ return (time.perf_counter() - start) * 1000.0
+
+
+def _status_code(exc: requests.exceptions.HTTPError) -> int | None:
+ response = getattr(exc, "response", None)
+ return getattr(response, "status_code", None)
+
+
+def _exception_message(prefix: str, exc: Exception) -> str:
+ message = str(exc).strip()
+ return f"{prefix}: {message}" if message else prefix
+
+
+def _ai_error(
+ message: str,
+ *,
+ duration_ms: float,
+ retryable: bool = False,
+ details: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ return envelope_err(
+ ErrorType.HUGEGRAPH_AI_UNAVAILABLE,
+ message,
+ retryable=retryable,
+ details=details,
+ duration_ms=duration_ms,
+ )
+
+
+def _normalize_response(data: Any, *, duration_ms: float) -> dict[str, Any]:
+ """Convert a Thin API envelope without wrapping it in a second envelope."""
+ if not _is_thin_api_envelope(data):
+ return envelope_ok(data, duration_ms=duration_ms)
+
+ remote_meta = data.get("meta") if isinstance(data.get("meta"), dict) else {}
+ request_id = remote_meta.get("request_id")
+ warnings = data.get("warnings") if isinstance(data.get("warnings"), list) else []
+ next_actions = (
+ data.get("next_actions") if isinstance(data.get("next_actions"), list) else []
+ )
+ if data["ok"]:
+ return envelope_ok(
+ data.get("data"),
+ duration_ms=duration_ms,
+ warnings=warnings,
+ next_actions=next_actions,
+ request_id=request_id,
+ )
+
+ error = data.get("error") if isinstance(data.get("error"), dict) else {}
+ return envelope_err(
+ error.get("type", ErrorType.HUGEGRAPH_AI_UNAVAILABLE),
+ error.get("message", "HugeGraph-AI request failed"),
+ suggestion=error.get("suggestion"),
+ retryable=(
+ error.get("retryable", False)
+ if isinstance(error.get("retryable", False), bool)
+ else False
+ ),
+ source=error.get("source", "hugegraph-llm"),
+ details=error.get("details"),
+ duration_ms=duration_ms,
+ warnings=warnings,
+ next_actions=next_actions,
+ request_id=request_id,
+ )
+
+
+def _is_thin_api_envelope(data: Any) -> bool:
+ meta = data.get("meta") if isinstance(data, dict) else None
+ return (
+ isinstance(data, dict)
+ and isinstance(data.get("ok"), bool)
+ and "data" in data
+ and (data.get("error") is None or isinstance(data.get("error"), dict))
+ and isinstance(data.get("warnings"), list)
+ and isinstance(data.get("next_actions"), list)
+ and isinstance(meta, dict)
+ and isinstance(meta.get("request_id"), str)
+ and isinstance(meta.get("duration_ms"), (int, float))
+ )
diff --git a/hugegraph-mcp/hugegraph_mcp/hugegraph_client.py b/hugegraph-mcp/hugegraph_mcp/hugegraph_client.py
new file mode 100644
index 00000000..6bdf9b08
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/hugegraph_client.py
@@ -0,0 +1,39 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""HugeGraph Server client construction helpers."""
+
+from typing import Any
+
+from pyhugegraph.client import PyHugeClient
+
+from hugegraph_mcp.config import MCPConfig
+
+
+def build_hugegraph_client(
+ cfg: MCPConfig,
+ *,
+ client_cls: type[Any] = PyHugeClient,
+) -> Any:
+ """Build a PyHugeClient while preserving optional graphspace compatibility."""
+
+ graphspace = cfg.graphspace.strip() if cfg.graphspace else ""
+ kwargs = {
+ "url": cfg.url,
+ "graph": cfg.graph,
+ "user": cfg.user,
+ "pwd": cfg.password,
+ }
+ if graphspace:
+ kwargs["graphspace"] = graphspace
+ return client_cls(**kwargs)
diff --git a/hugegraph-mcp/hugegraph_mcp/plan_hash.py b/hugegraph-mcp/hugegraph_mcp/plan_hash.py
new file mode 100644
index 00000000..df5f5eec
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/plan_hash.py
@@ -0,0 +1,209 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Target-bound plan hash — 防止跨图、跨用户、过期重放。
+
+PlanContext 将工具名、模式、图目标、主体、readonly、payload 摘要、
+schema 摘要、nonce 和过期时间绑定到一个哈希中。
+confirm 时重新计算并比较,拒绝不匹配或过期的计划。
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import time
+from dataclasses import asdict, dataclass, field
+from typing import Any
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import ErrorType
+
+# Default plan lifetime in seconds.
+DEFAULT_PLAN_TTL_SECONDS = 600 # 10 minutes.
+
+
+@dataclass(frozen=True)
+class PlanContext:
+ """计划上下文 — 绑定到特定工具、目标和时间窗口。"""
+
+ tool_name: str
+ mode: str
+ graph_url: str
+ graph_name: str
+ graphspace: str
+ principal: str
+ readonly: bool
+ payload_digest: str
+ schema_hash: str | None
+ nonce: str
+ expires_at: int
+ extra_context: dict[str, Any] = field(default_factory=dict)
+
+
+def compute_plan_hash(context: PlanContext) -> str:
+ """计算目标绑定的计划哈希。
+
+ 使用 canonical JSON 序列化(sorted keys, stable normalization),
+ 对完整 PlanContext 做 SHA256 哈希。expires_at 参与哈希,防止
+ 调用方在 confirm 时延长计划有效期。
+ """
+ payload = asdict(context)
+ payload = _canonicalize(payload)
+ encoded = json.dumps(payload, sort_keys=True, default=str)
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:32]
+
+
+def build_plan_context(
+ tool_name: str,
+ mode: str,
+ payload_digest: str,
+ schema_hash: str | None = None,
+ nonce: str | None = None,
+ ttl_seconds: int = DEFAULT_PLAN_TTL_SECONDS,
+ extra_context: dict[str, Any] | None = None,
+) -> tuple[PlanContext, str]:
+ """构建 PlanContext 并计算 plan_hash。
+
+ Returns:
+ (PlanContext, plan_hash) 元组。
+ """
+ cfg = MCPConfig.from_env()
+ now = int(time.time())
+
+ if nonce is None:
+ nonce = _generate_nonce()
+
+ context = PlanContext(
+ tool_name=tool_name,
+ mode=mode,
+ graph_url=cfg.url,
+ graph_name=cfg.graph,
+ graphspace=cfg.graphspace or "DEFAULT",
+ principal=cfg.user,
+ readonly=cfg.is_readonly(),
+ payload_digest=payload_digest,
+ schema_hash=schema_hash,
+ nonce=nonce,
+ expires_at=now + ttl_seconds,
+ extra_context=extra_context or {},
+ )
+
+ plan_hash = compute_plan_hash(context)
+ return context, plan_hash
+
+
+def verify_plan_hash(
+ submitted_hash: str,
+ tool_name: str,
+ mode: str,
+ payload_digest: str,
+ schema_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+ extra_context: dict[str, Any] | None = None,
+) -> tuple[bool, str | None, dict[str, Any] | None]:
+ """验证提交的 plan_hash。
+
+ 重新读取 config 和 schema,重新计算哈希,检查过期。
+
+ Returns:
+ (valid, error_type, details) 元组。
+ valid=True 时 error_type 和 details 为 None。
+ """
+ cfg = MCPConfig.from_env()
+
+ if nonce is None:
+ return (
+ False,
+ ErrorType.PLAN_HASH_MISMATCH,
+ {"reason": "Missing nonce in plan context."},
+ )
+
+ expires_at_seconds = _coerce_expires_at(expires_at)
+
+ # Check expiration. expires_at is returned in the dry-run plan context and
+ # must be sent back during confirmation; missing or malformed values are
+ # treated as expired so None cannot bypass the lifetime check.
+ if expires_at_seconds is None or int(time.time()) > expires_at_seconds:
+ return (
+ False,
+ ErrorType.PLAN_EXPIRED,
+ {
+ "expires_at": expires_at,
+ "current_time": int(time.time()),
+ "reason": "Plan has expired. Run dry_run again.",
+ },
+ )
+
+ # Rebuild the context using the current config, not the submitted config.
+ context = PlanContext(
+ tool_name=tool_name,
+ mode=mode,
+ graph_url=cfg.url,
+ graph_name=cfg.graph,
+ graphspace=cfg.graphspace or "DEFAULT",
+ principal=cfg.user,
+ readonly=cfg.is_readonly(),
+ payload_digest=payload_digest,
+ schema_hash=schema_hash,
+ nonce=nonce,
+ expires_at=expires_at_seconds,
+ extra_context=extra_context or {},
+ )
+
+ expected_hash = compute_plan_hash(context)
+
+ if submitted_hash != expected_hash:
+ return (
+ False,
+ ErrorType.PLAN_HASH_MISMATCH,
+ {
+ "provided_hash": submitted_hash,
+ "reason": "Plan context has changed since dry_run.",
+ },
+ )
+
+ return True, None, None
+
+
+def compute_payload_digest(payload: Any) -> str:
+ """计算 payload 的规范化摘要。"""
+ normalized = _canonicalize(payload)
+ encoded = json.dumps(normalized, sort_keys=True, default=str)
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:32]
+
+
+def _canonicalize(obj: Any) -> Any:
+ """Canonical JSON 序列化 — 递归排序 dict keys。"""
+ if isinstance(obj, dict):
+ return {k: _canonicalize(v) for k, v in sorted(obj.items())}
+ if isinstance(obj, (list, tuple)):
+ return [_canonicalize(item) for item in obj]
+ return obj
+
+
+def _generate_nonce() -> str:
+ """生成随机 nonce。"""
+ from uuid import uuid4
+
+ return uuid4().hex[:12]
+
+
+def _coerce_expires_at(value: float | None) -> int | None:
+ if value is None:
+ return None
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
diff --git a/hugegraph-mcp/hugegraph_mcp/schema_tools.py b/hugegraph-mcp/hugegraph_mcp/schema_tools.py
new file mode 100644
index 00000000..238077be
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/schema_tools.py
@@ -0,0 +1,125 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""HugeGraph Schema 操作层 — schema 读取和设计指导。
+
+get_live_schema() 从 HugeGraph 拉取全量 schema 并生成 LLM 精简版,
+design_schema() 提供链式思维引导的 schema 设计框架。
+"""
+
+from typing import Any
+
+from pyhugegraph.client import PyHugeClient
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.hugegraph_client import build_hugegraph_client
+
+
+def _build_client() -> PyHugeClient:
+ return build_hugegraph_client(MCPConfig.from_env(), client_cls=PyHugeClient)
+
+
+def _simple_schema(schema: dict[str, Any]) -> dict[str, Any]:
+ """精简 schema 供 LLM 消费 — 去掉冗余字段,只保留 name/properties/source_label/target_label。
+
+ 与 hugegraph_llm.SchemaManager.simple_schema 行为一致。
+ """
+
+ mini_schema: dict[str, Any] = {}
+
+ if schema.get("vertexlabels"):
+ mini_schema["vertexlabels"] = []
+ for vertex in schema["vertexlabels"]:
+ new_vertex = {
+ key: vertex[key]
+ for key in ("id", "name", "properties")
+ if key in vertex
+ }
+ mini_schema["vertexlabels"].append(new_vertex)
+
+ if schema.get("edgelabels"):
+ mini_schema["edgelabels"] = []
+ for edge in schema["edgelabels"]:
+ new_edge = {
+ key: edge[key]
+ for key in ("name", "source_label", "target_label", "properties")
+ if key in edge
+ }
+ mini_schema["edgelabels"].append(new_edge)
+
+ return mini_schema
+
+
+def get_live_schema() -> dict[str, Any]:
+ """从 HugeGraph 拉取活跃 schema,同时返回原始版和 LLM 精简版。
+
+ 返回: {schema, simple_schema, graphspace?, readonly}
+ """
+
+ client = _build_client()
+ raw_schema = client.schema().getSchema()
+
+ if raw_schema is None:
+ raise ValueError("Failed to retrieve schema from HugeGraph server")
+
+ result: dict[str, Any] = {
+ "schema": raw_schema,
+ "simple_schema": _simple_schema(raw_schema),
+ }
+
+ graphspace = MCPConfig.from_env().graphspace
+ if graphspace:
+ result["graphspace"] = graphspace
+
+ result["readonly"] = MCPConfig.from_env().is_readonly()
+
+ return result
+
+
+def design_schema(
+ thought: str,
+ thought_number: int,
+ total_thoughts: int = 4,
+ next_thought_needed: bool = True,
+ is_revision: bool = False,
+ revision_of: int | None = None,
+) -> dict:
+ """Schema 设计引导工具 — 参考 Sequential Thinking 模式。
+
+ HugeGraph 使用 schema-based 图模型,数据写入前必须先定义 PropertyKeys、
+ VertexLabels、EdgeLabels、IndexLabels。本函数提供分步引导框架。
+
+ Args:
+ thought: reserved for future use (no-op, accepted for Sequential Thinking
+ protocol compatibility)
+ thought_number: current thought step number
+ total_thoughts: estimated total thought steps
+ next_thought_needed: whether the caller expects another step
+ is_revision: reserved for future use (no-op)
+ revision_of: reserved for future use (no-op)
+
+ 【最佳实践】
+ 1. 先定义 PropertyKeys — 所有属性必须在 VertexLabel/EdgeLabel 中预定义
+ 2. 选择合适的 DataType (TEXT/INT/DATE/DOUBLE) 和 Cardinality (SINGLE/SET/LIST)
+ 3. VertexLabel 需指定 primaryKeys 用于顶点唯一标识
+ 4. EdgeLabel 需指定 sourceLabel 和 targetLabel
+ 5. EdgeLabel 的 frequency 可选 SINGLE 或 MULTIPLE
+ 6. 使用 nullableKeys 允许属性为空
+ 7. 为常用查询字段创建 IndexLabels (secondary/range/search)
+ """
+
+ return {
+ "thought_number": thought_number,
+ "total_thoughts": total_thoughts,
+ "next_thought_needed": next_thought_needed,
+ }
diff --git a/hugegraph-mcp/hugegraph_mcp/server.py b/hugegraph-mcp/hugegraph_mcp/server.py
new file mode 100644
index 00000000..56aa46ed
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/server.py
@@ -0,0 +1,613 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""FastMCP 服务器入口 — MCP 工具注册和轻量 mode 路由。
+
+每个 @mcp.tool() 装饰的函数就是一个对外暴露的 MCP 工具。
+server.py 只负责参数校验和 mode 分发,具体业务逻辑委托给 tools/ 下的模块。
+"""
+
+import logging
+import logging.handlers
+import os
+import time
+from typing import Any
+
+# ---- Startup patch: prevent module-level pyhugegraph logging from writing files. ----
+# pyhugegraph creates a RotatingFileHandler under 'logs/' during import. In MCP
+# stdio mode this would corrupt the JSON protocol stream, so intercept makedirs
+# and RotatingFileHandler.
+
+_original_makedirs = os.makedirs
+
+
+def _safe_makedirs(name, mode=0o777, exist_ok=False):
+ if _is_logs_dir(name):
+ return None
+ return _original_makedirs(name, mode, exist_ok)
+
+
+def _is_logs_dir(name) -> bool:
+ try:
+ path = os.fspath(name)
+ except TypeError:
+ return False
+ return os.path.basename(os.path.normpath(path)).lower() == "logs"
+
+
+_OriginalRotatingFileHandler = logging.handlers.RotatingFileHandler
+
+
+class _NoOpFileHandler(logging.NullHandler):
+ """无操作日志处理器 — 用于禁用文件日志记录。"""
+
+ def __init__(self, *args, **kwargs):
+ super().__init__()
+
+
+def _patched_rotating_handler(filename, *args, **kwargs):
+ if _is_logs_file(filename):
+ return _NoOpFileHandler()
+ return _OriginalRotatingFileHandler(filename, *args, **kwargs)
+
+
+def _is_logs_file(filename) -> bool:
+ try:
+ path = os.path.normpath(os.fspath(filename))
+ except TypeError:
+ return False
+ return any(part.lower() == "logs" for part in path.split(os.sep))
+
+
+logging.handlers.RotatingFileHandler = _patched_rotating_handler
+
+os.makedirs = _safe_makedirs
+
+try:
+ # ---- Safely import pyhugegraph-dependent modules within the patch scope. ----
+ from fastmcp import FastMCP
+
+ from hugegraph_mcp.config import MCPConfig
+ from hugegraph_mcp.envelope import ErrorType, envelope_err
+ from hugegraph_mcp.gremlin_tools import execute_gremlin_read, execute_gremlin_write
+ from hugegraph_mcp.guard import Capability
+ from hugegraph_mcp.tools.extract_graph_data import extract_graph_data
+ from hugegraph_mcp.tools.generate_gremlin import generate_gremlin
+ from hugegraph_mcp.tools.inspect_graph import inspect_graph
+ from hugegraph_mcp.tools.inspect_schema import inspect_schema
+ from hugegraph_mcp.tools.manage_graph_data import manage_graph_data
+ from hugegraph_mcp.tools.manage_schema import manage_schema
+ from hugegraph_mcp.tools.mutate_graph_properties import mutate_graph_properties
+ from hugegraph_mcp.tools.query_graph_data import query_graph_data
+ from hugegraph_mcp.tools.refresh_vid_embeddings import refresh_vid_embeddings
+finally:
+ os.makedirs = _original_makedirs
+ logging.handlers.RotatingFileHandler = _OriginalRotatingFileHandler
+
+READONLY = MCPConfig.from_env().is_readonly()
+MCP_TOOL_CONTRACT_VERSION = "2.0"
+DEFAULT_TOOLSET = "v2_core"
+
+mcp = FastMCP("HugeGraph MCP")
+
+
+def _active_toolset() -> str:
+ value = os.getenv("HUGEGRAPH_MCP_TOOLSET", DEFAULT_TOOLSET).strip()
+ return "v1" if value == "v1" else DEFAULT_TOOLSET
+
+
+def _register_v2_core_tool(func):
+ if _active_toolset() == "v1":
+ return func
+ return mcp.tool()(func)
+
+
+def _align_public_tool_envelope(
+ result: dict[str, Any],
+ *,
+ tool_name: str,
+ duration_ms: float,
+) -> dict[str, Any]:
+ """Add public wrapper metadata without changing the inner tool payload."""
+ aligned = dict(result)
+ meta = dict(aligned.get("meta") or {})
+ meta.setdefault("duration_ms", duration_ms)
+ aligned["meta"] = meta
+
+ if aligned.get("ok") is False and isinstance(aligned.get("error"), dict):
+ error = dict(aligned["error"])
+ error["source"] = tool_name
+ aligned["error"] = error
+
+ return aligned
+
+
+def _call_public_tool(tool_name: str, func, *args, **kwargs) -> dict[str, Any]:
+ start = time.perf_counter()
+ try:
+ result = func(*args, **kwargs)
+ except Exception as exc: # noqa: BLE001 - tool boundary returns an envelope
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ f"{tool_name} failed: {exc!s}",
+ source=tool_name,
+ details={"tool": tool_name},
+ duration_ms=(time.perf_counter() - start) * 1000.0,
+ )
+ return _align_public_tool_envelope(
+ result,
+ tool_name=tool_name,
+ duration_ms=(time.perf_counter() - start) * 1000.0,
+ )
+
+
+def _is_admin_mode_enabled() -> bool:
+ return MCPConfig.from_env().admin_mode
+
+
+def _admin_gate(tool_name: str, *, requires_write: bool = False) -> dict | None:
+ """Return FEATURE_DISABLED envelope if admin mode is not enabled, else None."""
+ if not _is_admin_mode_enabled():
+ enable_env = {"admin_mode": "HUGEGRAPH_MCP_ADMIN_MODE"}
+ required_env = {"HUGEGRAPH_MCP_ADMIN_MODE": "true"}
+ suggestion = f"Set HUGEGRAPH_MCP_ADMIN_MODE=true to enable {tool_name}."
+ if requires_write:
+ enable_env["readonly"] = "HUGEGRAPH_MCP_READONLY"
+ required_env["HUGEGRAPH_MCP_READONLY"] = "false"
+ suggestion = (
+ f"Set HUGEGRAPH_MCP_ADMIN_MODE=true and HUGEGRAPH_MCP_READONLY=false "
+ f"to enable {tool_name}."
+ )
+ return envelope_err(
+ ErrorType.FEATURE_DISABLED,
+ f"{tool_name} is an admin/debug tool and is disabled by default.",
+ suggestion=suggestion,
+ source=tool_name,
+ details={
+ "tool": tool_name,
+ "toolset": _active_toolset(),
+ "enable_env": enable_env,
+ "required_env": required_env,
+ },
+ )
+
+ if requires_write and MCPConfig.from_env().is_readonly():
+ return envelope_err(
+ ErrorType.READONLY_VIOLATION,
+ f"{tool_name} requires HUGEGRAPH_MCP_READONLY=false.",
+ suggestion=(
+ "Set HUGEGRAPH_MCP_ADMIN_MODE=true and HUGEGRAPH_MCP_READONLY=false "
+ "before retrying this admin write tool."
+ ),
+ source=tool_name,
+ details={
+ "tool": tool_name,
+ "required_env": {
+ "HUGEGRAPH_MCP_ADMIN_MODE": "true",
+ "HUGEGRAPH_MCP_READONLY": "false",
+ },
+ },
+ readonly=True,
+ )
+ return None
+
+
+# ========== Tool 1: inspect graph status and schema ==========
+
+
+@mcp.tool()
+def inspect_graph_tool(include_raw_schema: bool = False) -> dict:
+ """检视 HugeGraph 服务器状态、schema 摘要、点边计数和 AI 状态。
+
+ Capability: READ.
+ 推荐作为连接后第一个调用的工具。
+ """
+ result = _call_public_tool(
+ "inspect_graph_tool",
+ inspect_graph,
+ include_raw_schema=include_raw_schema,
+ )
+ if result.get("ok") and isinstance(result.get("data"), dict):
+ result["data"]["mcp_tool_contract_version"] = MCP_TOOL_CONTRACT_VERSION
+ result["data"]["toolset"] = _active_toolset()
+ meta = dict(result.get("meta") or {})
+ meta["mcp_tool_contract_version"] = MCP_TOOL_CONTRACT_VERSION
+ meta["toolset"] = _active_toolset()
+ result["meta"] = meta
+ return result
+
+
+@_register_v2_core_tool
+def inspect_schema_tool(
+ include_raw_schema: bool = False,
+ include_relations: bool = True,
+ include_index_labels: bool = True,
+ filter_kind: str | None = None,
+ filter_name: str | None = None,
+) -> dict:
+ """Inspect HugeGraph schema objects and relations.
+
+ Capability: READ.
+ filter_kind values: property_key, vertex_label, edge_label, index_label.
+ filter_name requires filter_kind and selects one schema object by name.
+ include_raw_schema returns the raw HugeGraph schema; include_relations and
+ include_index_labels control relation/index sections.
+ """
+ return _call_public_tool(
+ "inspect_schema_tool",
+ inspect_schema,
+ include_raw_schema=include_raw_schema,
+ include_relations=include_relations,
+ include_index_labels=include_index_labels,
+ filter_kind=filter_kind,
+ filter_name=filter_name,
+ )
+
+
+@_register_v2_core_tool
+def query_graph_data_tool(
+ target: str,
+ operation: str,
+ id: Any = None,
+ ids: list[Any] | None = None,
+ label: str | None = None,
+ properties: dict[str, Any] | None = None,
+ limit: int | None = None,
+ page: str | None = None,
+ vertex_id: Any = None,
+ direction: str | None = None,
+) -> dict:
+ """Query HugeGraph vertices or edges by typed GraphManager operations.
+
+ Capability: READ.
+ target values: vertex, edge.
+ operation values and required fields:
+ - get_by_id: requires id.
+ - get_by_ids: requires non-empty ids.
+ - page: vertex requires label; edge may use label and/or vertex_id+direction.
+ - condition: exact-match properties only; no Gremlin full-scan fallback.
+ limit defaults to 100 and rejects values above 500. For edge page/condition,
+ direction is required when vertex_id is provided.
+ """
+ return _call_public_tool(
+ "query_graph_data_tool",
+ query_graph_data,
+ target=target,
+ operation=operation,
+ id=id,
+ ids=ids,
+ label=label,
+ properties=properties,
+ limit=limit,
+ page=page,
+ vertex_id=vertex_id,
+ direction=direction,
+ )
+
+
+# ========== V1 stable tools ==========
+
+
+@mcp.tool()
+def generate_gremlin_tool(
+ query: str,
+ execute: bool = False,
+ output_types: list[str] | None = None,
+ limit_policy: str = "warn",
+) -> dict:
+ """V1 稳定工具:自然语言 → Gremlin 生成。
+
+ 默认不执行(execute=false),返回生成的 Gremlin 查询。
+ 设置 execute=true 可执行生成的只读 Gremlin。Capability: GENERATE.
+ limit_policy 仅在 execute=true 时传给只读执行:warn、reject_unbounded、
+ auto_append。auto_append 会返回 original_gremlin/executed_gremlin/rewrite_reason。
+ """
+ return _call_public_tool(
+ "generate_gremlin_tool",
+ generate_gremlin,
+ query=query,
+ execute=execute,
+ output_types=output_types,
+ limit_policy=limit_policy,
+ )
+
+
+@mcp.tool()
+def execute_gremlin_read_tool(gremlin_query: str, limit_policy: str = "warn") -> dict:
+ """V1 稳定工具:执行只读 Gremlin 遍历查询。
+
+ Capability: READ.
+ 经过 GremlinPolicy 安全检查后执行。
+ limit_policy values:
+ - warn: execute and return cost warnings for unbounded reads.
+ - reject_unbounded: reject safe but unbounded reads before execution.
+ - auto_append: append .limit(100) to simple unbounded g.V()/g.E() queries and
+ return original_gremlin/executed_gremlin/rewrite_reason.
+ """
+ return _call_public_tool(
+ "execute_gremlin_read_tool",
+ execute_gremlin_read,
+ gremlin_query,
+ limit_policy=limit_policy,
+ )
+
+
+@mcp.tool()
+def extract_graph_data_tool(
+ text: str,
+ graph_schema: dict | None = None,
+ example_prompt: str | None = None,
+) -> dict:
+ """V1 稳定工具:自然语言文本 → 候选 graph_data(不写入)。
+
+ 返回提取的顶点和边数据,供后续导入使用。
+ graph_schema 可传入 HugeGraph schema;为空时从当前 HugeGraph 读取 live schema,
+ 并在 schema_ref 中返回图目标和 schema fingerprint。
+ """
+ return _call_public_tool(
+ "extract_graph_data_tool",
+ extract_graph_data,
+ text=text,
+ schema=graph_schema,
+ example_prompt=example_prompt,
+ )
+
+
+@mcp.tool()
+def design_schema_tool(operations: list[dict] | None = None) -> dict:
+ """V1 稳定工具:schema 设计指导。
+
+ 提供 schema 设计建议和最佳实践。
+ """
+ return _call_public_tool(
+ "design_schema_tool",
+ manage_schema,
+ mode="design",
+ operations=operations,
+ )
+
+
+@mcp.tool()
+def apply_schema_tool(
+ mode: str,
+ operations: list[dict] | None = None,
+ confirm: bool = False,
+ plan_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+) -> dict:
+ """Schema design/validate/dry_run/apply entry point.
+
+ Capability: SCHEMA_WRITE for mode=apply; READ-like validation for other modes.
+ mode values:
+ - design: schema design guidance; operations optional.
+ - validate: validate operations against live schema.
+ - dry_run: validate P0a create operations and return plan_hash/nonce/expires_at.
+ - apply: P0a only. Requires confirm=true, plan_hash, nonce, expires_at from
+ dry_run. Supports create_property_key, create_vertex_label, create_edge_label.
+ Rejects create_index_label, schema append/eliminate, remove/drop.
+ """
+ start = time.perf_counter()
+ if mode == "apply" and _active_toolset() == "v1":
+ return envelope_err(
+ ErrorType.FEATURE_DISABLED,
+ "Schema apply is disabled in V1. Use validate or dry_run mode.",
+ suggestion="Use mode='validate' or mode='dry_run' to preview schema changes.",
+ source="apply_schema_tool",
+ details={"mode": mode, "tool": "apply_schema_tool"},
+ duration_ms=(time.perf_counter() - start) * 1000.0,
+ )
+ return _call_public_tool(
+ "apply_schema_tool",
+ manage_schema,
+ mode=mode,
+ operations=operations,
+ confirm=confirm,
+ plan_hash=plan_hash,
+ nonce=nonce,
+ expires_at=expires_at,
+ )
+
+
+@_register_v2_core_tool
+def mutate_graph_properties_tool(
+ target: str,
+ operation: str,
+ id: Any,
+ properties: dict[str, Any],
+ dry_run: bool = True,
+ confirm: bool = False,
+ plan_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+) -> dict:
+ """Append or eliminate properties on one vertex or edge.
+
+ Capability: DATA_WRITE.
+ target values: vertex, edge.
+ operation values: append, eliminate. Both require the same chain:
+ dry_run=true -> review before/after and plan_hash -> dry_run=false,
+ confirm=true with plan_hash, nonce, and expires_at.
+ The confirm step re-reads schema and target; changed targets return
+ TARGET_CHANGED and are not mutated.
+ """
+ return _call_public_tool(
+ "mutate_graph_properties_tool",
+ mutate_graph_properties,
+ target=target,
+ operation=operation,
+ id=id,
+ properties=properties,
+ dry_run=dry_run,
+ confirm=confirm,
+ plan_hash=plan_hash,
+ nonce=nonce,
+ expires_at=expires_at,
+ )
+
+
+# ========== Graph data import entry point ==========
+
+
+@mcp.tool()
+def import_graph_data_tool(
+ mode: str,
+ text: str | None = None,
+ graph_schema: dict | None = None,
+ example_prompt: str | None = None,
+ graph_data: dict | None = None,
+ dry_run: bool = True,
+ confirm: bool = False,
+ plan_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+) -> dict:
+ """V1 图数据导入入口。
+
+ mode="extract": 自然语言文本 → 候选 graph_data
+ mode="ingest": MCP 本地校验+dry_run/confirm+Gremlin 导入 graph_data
+ mode="table": 当前 MCP contract 不支持(返回 FEATURE_DISABLED)
+ """
+ start = time.perf_counter()
+
+ if mode == "extract":
+ if not text:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "text is required for mode='extract'",
+ source="import_graph_data_tool",
+ duration_ms=(time.perf_counter() - start) * 1000.0,
+ )
+ return _call_public_tool(
+ "import_graph_data_tool",
+ extract_graph_data,
+ text=text,
+ schema=graph_schema,
+ example_prompt=example_prompt,
+ )
+
+ if mode == "ingest":
+ if graph_data is None:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "graph_data is required for mode='ingest'",
+ source="import_graph_data_tool",
+ duration_ms=(time.perf_counter() - start) * 1000.0,
+ )
+ return _call_public_tool(
+ "import_graph_data_tool",
+ manage_graph_data,
+ mode="import",
+ graph_data=graph_data,
+ dry_run=dry_run,
+ confirm=confirm,
+ plan_hash=plan_hash,
+ nonce=nonce,
+ expires_at=expires_at,
+ plan_tool_name="import_graph_data_tool",
+ )
+
+ if mode == "table":
+ return envelope_err(
+ ErrorType.FEATURE_DISABLED,
+ "Table import is not supported by the current MCP contract.",
+ suggestion=(
+ "Use import_graph_data_tool(mode='extract') for text extraction, "
+ "then import_graph_data_tool(mode='ingest') for validated graph_data."
+ ),
+ source="import_graph_data_tool",
+ details={"mode": mode, "tool": "import_graph_data_tool"},
+ duration_ms=(time.perf_counter() - start) * 1000.0,
+ )
+
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ f"Unknown mode: {mode!r}. Use 'extract' or 'ingest'.",
+ source="import_graph_data_tool",
+ details={"mode": mode},
+ duration_ms=(time.perf_counter() - start) * 1000.0,
+ )
+
+
+# ========== Controlled graph data deletion entry point ==========
+
+
+@mcp.tool()
+def delete_graph_data_tool(
+ change_plan: dict,
+ dry_run: bool = True,
+ confirm: bool = False,
+ plan_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+) -> dict:
+ """V1 稳定工具:受控删除图数据。
+
+ 只支持精确 delete_vertex/delete_edge change_plan。
+ 必须经过 dry_run -> plan_hash -> confirm;不支持批量条件删除或级联删除。
+ """
+ return _call_public_tool(
+ "delete_graph_data_tool",
+ manage_graph_data,
+ mode="delete",
+ change_plan=change_plan,
+ dry_run=dry_run,
+ confirm=confirm,
+ plan_hash=plan_hash,
+ nonce=nonce,
+ expires_at=expires_at,
+ plan_tool_name="delete_graph_data_tool",
+ )
+
+
+# ========== Advanced debugging tools ==========
+
+
+@mcp.tool()
+def refresh_vid_embeddings_tool(confirm: bool = False) -> dict:
+ """手动刷新 VID 嵌入 — 需 admin mode 且 readonly=false。"""
+ blocked = _admin_gate("refresh_vid_embeddings_tool", requires_write=True)
+ if blocked:
+ return blocked
+ return _call_public_tool(
+ "refresh_vid_embeddings_tool",
+ refresh_vid_embeddings,
+ confirm=confirm,
+ )
+
+
+@mcp.tool()
+def execute_gremlin_write_tool(gremlin_query: str) -> dict:
+ """Break-glass direct Gremlin write for an isolated trusted admin transport.
+
+ This is the sole write-safety-chain exception: it has no preview, dry-run,
+ plan hash, or confirmation step. It requires admin mode and readonly=false.
+ """
+ blocked = _admin_gate("execute_gremlin_write_tool", requires_write=True)
+ if blocked:
+ return blocked
+ return _call_public_tool(
+ "execute_gremlin_write_tool",
+ execute_gremlin_write,
+ gremlin_query,
+ capability=Capability.DEBUG_WRITE,
+ )
+
+
+def main() -> None:
+ """CLI 入口 — 默认 stdio 模式。"""
+ mcp.run()
+
+
+if __name__ == "__main__": # pragma: no cover - manual launch
+ main()
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/__init__.py b/hugegraph-mcp/hugegraph_mcp/tools/__init__.py
new file mode 100644
index 00000000..b1312a09
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/__init__.py
@@ -0,0 +1,16 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/extract_graph_data.py b/hugegraph-mcp/hugegraph_mcp/tools/extract_graph_data.py
new file mode 100644
index 00000000..8ce3a081
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/extract_graph_data.py
@@ -0,0 +1,207 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""自然语言抽取图数据 — 从文本中提取候选 vertices/edges,不写入 HugeGraph。
+
+通过 HugeGraph-AI /graph-extract 端点将自然语言描述转为结构化的
+{vertices: [...], edges: [...]} 图数据,供用户审阅后再导入。
+"""
+
+import hashlib
+import json
+from typing import Any
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+from hugegraph_mcp.hugegraph_ai_client import post
+from hugegraph_mcp.tools.live_schema import fetch_live_schema_or_none
+from hugegraph_mcp.tools.schema_utils import schema_payload
+
+DEFAULT_GRAPH_EXTRACT_PROMPT_ZH = """## 主要任务
+只抽取输入文本和给定图谱 schema 共同支持的顶点与边。只返回合法 JSON。
+
+## 输出格式
+必须返回唯一 JSON 对象:{"vertices": [...], "edges": [...]}。
+顶点对象:{"id":"顶点 id","label":"顶点标签","properties":{"属性名":"属性值", ...}}。
+边对象:{"label":"边标签","outV":"源顶点 id","outVLabel":"源顶点标签","inV":"目标顶点 id","inVLabel":"目标顶点标签","properties":{"属性名":"属性值", ...}}。
+
+## 抽取规则
+1. 只能使用 schema 中已经存在的 vertex label、edge label 和 property key。
+2. 可以把中文关系语义映射到 schema 中已有的英文标签,例如"同事"可映射为 schema 中的 colleague;但不要创造 schema 中不存在的标签。
+3. 顶点 id 必须按 schema 的 vertexlabels[].id 与 primary_keys 生成;单主键格式为 "{vertexLabelID}:{properties.<primary_key>}"。
+4. outV 和 inV 必须引用本次输出 vertices 中的 id,outVLabel/inVLabel 必须匹配边 schema 的 source_label/target_label。
+5. 保持属性类型,移除空属性,不要编造文本中没有的事实。
+6. 不要输出 Markdown、解释、注释或额外文本。"""
+
+
+def extract_graph_data(
+ text: str,
+ schema: dict[str, Any] | str | None = None,
+ example_prompt: str | None = None,
+) -> dict[str, Any]:
+ """从自然语言文本中抽取候选图数据 — 不写入 HugeGraph。
+
+ 返回 standard envelope,其中 graph_data 含 vertices/edges 供用户审阅。
+ """
+
+ cfg = MCPConfig.from_env()
+ if schema is None and not cfg.allow_ai:
+ # Preserve the capability gate without requiring HugeGraph connectivity.
+ schema_message = cfg.graph
+ schema_ref = _schema_ref(cfg, "graph", None)
+ else:
+ schema_message, schema_ref = _schema_context(schema, cfg)
+ if schema_message is None:
+ return envelope_err(
+ ErrorType.CONNECTION_FAILED,
+ "Cannot read the live HugeGraph schema for graph extraction.",
+ suggestion="Check HugeGraph connectivity and retry the extraction.",
+ details={"graph": cfg.graph, "graphspace": cfg.graphspace},
+ )
+ prompt_message = _example_prompt_message(example_prompt)
+ ai_result = post(
+ "/graph-extract",
+ json={
+ "text": text,
+ "schema": schema_message,
+ "example_prompt": prompt_message,
+ "language": "zh",
+ },
+ )
+ if not ai_result.get("ok"):
+ return ai_result
+
+ payload = _unwrap_ai_payload(ai_result.get("data"))
+ if isinstance(payload, dict) and payload.get("ok") is False:
+ return payload
+
+ graph_data = _extract_graph_data(payload)
+ if graph_data is None:
+ return envelope_err(
+ ErrorType.INVALID_GRAPH_DATA,
+ "HugeGraph-AI did not return graph_data with vertices and edges.",
+ details={"data": payload},
+ )
+
+ return envelope_ok(
+ {
+ "graph_data": {
+ "schema_ref": schema_ref,
+ "vertices": graph_data.get("vertices", []),
+ "edges": graph_data.get("edges", []),
+ "warnings": graph_data.get("warnings", []),
+ "raw": graph_data.get("raw"),
+ },
+ "raw_summary": graph_data.get("raw_summary"),
+ "schema_warnings": graph_data.get("schema_warnings", []),
+ }
+ )
+
+
+def _schema_context(
+ schema: dict[str, Any] | str | None, cfg: MCPConfig
+) -> tuple[str | None, dict[str, Any]]:
+ """Resolve schema input and provenance from one graph target.
+
+ A missing schema is read from MCP's HugeGraph connection and sent inline to
+ HugeGraph-AI. This keeps extraction and provenance tied to the same target.
+ """
+ schema_source = "provided"
+ raw_schema: Any = schema
+ if schema is None:
+ live_schema = fetch_live_schema_or_none()
+ raw_schema = schema_payload(live_schema)
+ schema_source = "live"
+ if raw_schema is None:
+ return None, _schema_ref(cfg, schema_source, None)
+
+ if isinstance(raw_schema, dict):
+ schema_message = json.dumps(raw_schema, sort_keys=True, default=str)
+ fingerprint = _schema_fingerprint(raw_schema)
+ elif isinstance(raw_schema, str) and raw_schema.strip():
+ schema_message = raw_schema
+ try:
+ parsed = json.loads(raw_schema)
+ except json.JSONDecodeError:
+ parsed = None
+ fingerprint = _schema_fingerprint(parsed) if isinstance(parsed, dict) else None
+ else:
+ return None, _schema_ref(cfg, schema_source, None)
+
+ return schema_message, _schema_ref(cfg, schema_source, fingerprint)
+
+
+def _schema_ref(
+ cfg: MCPConfig, schema_source: str, fingerprint: str | None
+) -> dict[str, Any]:
+ return {
+ "schema_source": schema_source,
+ "graph": cfg.graph,
+ "graphspace": cfg.graphspace,
+ "version": None,
+ "fingerprint": fingerprint,
+ }
+
+
+def _schema_fingerprint(schema: dict[str, Any]) -> str:
+ encoded = json.dumps(schema, sort_keys=True, separators=(",", ":"), default=str)
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
+
+
+def _example_prompt_message(example_prompt: str | None) -> str:
+ if example_prompt is None:
+ return DEFAULT_GRAPH_EXTRACT_PROMPT_ZH
+ return example_prompt
+
+
+def _unwrap_ai_payload(data: Any) -> Any:
+ """解包 AI 返回的双层信封 {ok, data} -> 内层 data。"""
+ if isinstance(data, dict) and "ok" in data and "data" in data:
+ if data.get("ok") is False:
+ return data
+ return data.get("data")
+ return data
+
+
+def _extract_graph_data(data: Any) -> dict[str, Any] | None:
+ parsed = _parse_json_if_needed(data)
+ if isinstance(parsed, dict) and "graph_data" in parsed:
+ parsed = _parse_json_if_needed(parsed.get("graph_data"))
+
+ if not isinstance(parsed, dict):
+ return None
+
+ vertices = parsed.get("vertices")
+ edges = parsed.get("edges")
+ if not isinstance(vertices, list) or not isinstance(edges, list):
+ return None
+
+ return {
+ "vertices": vertices,
+ "edges": edges,
+ "warnings": parsed.get("warnings", []),
+ "raw": parsed.get("raw"),
+ "raw_summary": parsed.get("raw_summary"),
+ "schema_warnings": parsed.get("schema_warnings", []),
+ }
+
+
+def _parse_json_if_needed(data: Any) -> Any:
+ """AI 可能返回 JSON 字符串而非已解析对象,这里做兼容处理。"""
+ if not isinstance(data, str):
+ return data
+
+ try:
+ return json.loads(data)
+ except json.JSONDecodeError:
+ return data
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/generate_gremlin.py b/hugegraph-mcp/hugegraph_mcp/tools/generate_gremlin.py
new file mode 100644
index 00000000..4fabeac4
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/generate_gremlin.py
@@ -0,0 +1,197 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""NL-to-Gremlin 生成 — 通过 HugeGraph-AI /text2gremlin 将自然语言转为 Gremlin。
+
+默认只返回生成的 Gremlin + 安全元数据,不自动执行。
+execute=True 且安全分类为 safe 时才自动执行,不安全查询只返回不执行。
+"""
+
+from typing import Any
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+from hugegraph_mcp.gremlin_policy import check_gremlin_read
+from hugegraph_mcp.gremlin_tools import execute_gremlin_read
+from hugegraph_mcp.hugegraph_ai_client import post
+
+_GENERATION_OUTPUT_TYPES = frozenset(
+ {
+ "match_result",
+ "template_gremlin",
+ "raw_gremlin",
+ }
+)
+
+
+def generate_gremlin(
+ query: str,
+ execute: bool = False,
+ output_types: list[str] | None = None,
+ limit_policy: str = "warn",
+) -> dict[str, Any]:
+ """将自然语言转为 Gremlin — 默认只生成不执行。
+
+ execute=True 时通过 GremlinPolicy 检查安全性:只有 safe 的查询才会执行。
+ limit_policy 透传给 execute_gremlin_read,默认 warn 保持兼容。
+ """
+
+ invalid_output_types = sorted(
+ {
+ output_type if isinstance(output_type, str) else repr(output_type)
+ for output_type in (output_types or [])
+ if not isinstance(output_type, str)
+ or output_type not in _GENERATION_OUTPUT_TYPES
+ }
+ )
+ if invalid_output_types:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "generate_gremlin only accepts generation output types.",
+ suggestion=(
+ "Use match_result, template_gremlin, or raw_gremlin. "
+ "Execute generated Gremlin through the MCP read execution path."
+ ),
+ details={
+ "invalid_output_types": invalid_output_types,
+ "allowed_output_types": sorted(_GENERATION_OUTPUT_TYPES),
+ },
+ )
+
+ cfg = MCPConfig.from_env()
+ client_config = {
+ "graph": cfg.graph,
+ }
+ if cfg.graphspace:
+ client_config["gs"] = cfg.graphspace
+ payload: dict[str, Any] = {
+ "query": query,
+ "client_config": client_config,
+ }
+ if output_types is not None:
+ payload["output_types"] = output_types
+
+ ai_result = post("/text2gremlin", json=payload)
+ if not ai_result.get("ok"):
+ return ai_result
+
+ ai_data = ai_result.get("data") or {}
+ if not isinstance(ai_data, dict):
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ "HugeGraph-AI returned an invalid text2gremlin response.",
+ details={"response": ai_data},
+ )
+
+ template_gremlin = ai_data.get("template_gremlin")
+ raw_gremlin = ai_data.get("raw_gremlin")
+ match_result = ai_data.get("match_result")
+ requested = set(output_types or [])
+ gremlin_candidates = []
+ if not requested or "template_gremlin" in requested:
+ gremlin_candidates.append(template_gremlin)
+ if not requested or "raw_gremlin" in requested:
+ gremlin_candidates.append(raw_gremlin)
+ if not requested:
+ gremlin_candidates.append(ai_data.get("gremlin"))
+ gremlin = next(
+ (
+ candidate
+ for candidate in gremlin_candidates
+ if isinstance(candidate, str) and candidate.strip()
+ ),
+ None,
+ )
+ requires_gremlin = not requested or bool(
+ requested & {"template_gremlin", "raw_gremlin"}
+ )
+ if requires_gremlin and gremlin is None:
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ "HugeGraph-AI did not return Gremlin.",
+ details={"response": ai_data},
+ )
+
+ requires_index = ai_data.get("requires_index", False)
+ assumptions = ai_data.get("assumptions")
+
+ decision = check_gremlin_read(gremlin) if gremlin else None
+ safety = decision.classification if decision else "uncertain"
+ is_readonly = decision.allowed if decision else False
+ risk_level = _risk_level(safety)
+
+ data = {
+ "gremlin": gremlin,
+ "template_gremlin": template_gremlin,
+ "raw_gremlin": raw_gremlin,
+ "match_result": match_result,
+ "is_readonly": is_readonly,
+ "risk_level": risk_level,
+ "requires_index": requires_index,
+ "assumptions": assumptions,
+ "executed": False,
+ "execution_result": None,
+ }
+
+ if not execute:
+ return envelope_ok(data)
+
+ if not is_readonly:
+ return envelope_err(
+ ErrorType.UNSAFE_GREMLIN,
+ "Generated Gremlin is not safe to execute automatically",
+ details={
+ "classification": safety,
+ "gremlin": gremlin,
+ "risk_level": risk_level,
+ },
+ )
+
+ data["executed"] = True
+ execution_result = execute_gremlin_read(gremlin, limit_policy=limit_policy)
+ if isinstance(execution_result, dict) and execution_result.get("ok") is False:
+ data["execution_result"] = execution_result
+ error = execution_result.get("error") or {}
+ return envelope_err(
+ error.get("type", ErrorType.FLOW_EXECUTION_FAILED),
+ error.get("message", "Generated Gremlin execution failed."),
+ suggestion=error.get("suggestion"),
+ retryable=error.get("retryable", False),
+ details={
+ "gremlin": gremlin,
+ "generation": data,
+ "execution_error": error,
+ },
+ warnings=execution_result.get("warnings", []),
+ )
+ if isinstance(execution_result, dict) and execution_result.get("success") is False:
+ data["execution_result"] = execution_result
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ "Generated Gremlin execution failed.",
+ details={"gremlin": gremlin, "generation": data},
+ )
+ if isinstance(execution_result, dict) and execution_result.get("ok") is True:
+ data["execution_result"] = execution_result.get("data")
+ data["execution_meta"] = execution_result.get("meta")
+ else:
+ data["execution_result"] = execution_result
+ return envelope_ok(data)
+
+
+def _risk_level(safety: str) -> str:
+ if safety == "safe":
+ return "low"
+ if safety == "unsafe":
+ return "high"
+ return "medium"
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/graph_data_execute.py b/hugegraph-mcp/hugegraph_mcp/tools/graph_data_execute.py
new file mode 100644
index 00000000..b061bc3e
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/graph_data_execute.py
@@ -0,0 +1,805 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Graph data change plan execution.
+
+Dry-run preview, write execution, pre-execution matched_count verification,
+and plan hash computation.
+"""
+
+import hashlib
+import json
+from typing import Any
+
+from hugegraph_mcp import gremlin_tools
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+from hugegraph_mcp.guard import Capability
+from hugegraph_mcp.tools.graph_data_gremlin import (
+ _edge_match_query,
+ _g,
+ _source_vertex_match_query,
+ _target_vertex_match_query,
+ _vertex_match_query,
+ _write_query,
+)
+from hugegraph_mcp.tools.graph_data_validate import (
+ WRITE_OPS,
+ ValidationError,
+ _operations,
+ _validation_error,
+ validate_graph_change_plan,
+)
+from hugegraph_mcp.tools.live_schema import fetch_live_schema_or_none
+from hugegraph_mcp.tools.schema_utils import (
+ normalized_schema_summary,
+ primary_key_names,
+ schema_payload,
+)
+
+# ---- Gremlin execution helpers ----
+
+
+def _read_count(gremlin_query: str) -> dict[str, Any]:
+ result = gremlin_tools.execute_gremlin_read(f"{gremlin_query}.count()")
+ # execute_gremlin_read is migrating to the unified envelope, but retain
+ # the legacy success=false shape so lower-level format differences do not
+ # break the dry-run safety chain.
+ if isinstance(result, dict) and result.get("ok") is False:
+ return result
+ if isinstance(result, dict) and result.get("success") is False:
+ return envelope_err(
+ ErrorType.CONNECTION_FAILED,
+ "HugeGraph read query failed during graph change dry run.",
+ details=result,
+ retryable=True,
+ )
+ data = result.get("data") if isinstance(result, dict) else result
+ count = _extract_count_value(data)
+ try:
+ matched_count = int(count)
+ except (TypeError, ValueError):
+ return envelope_err(
+ ErrorType.INVALID_GRAPH_DATA,
+ "HugeGraph count query returned a non-numeric result.",
+ details={"query": gremlin_query, "data": data},
+ )
+ return envelope_ok({"matched_count": matched_count})
+
+
+def _extract_count_value(data: Any) -> Any:
+ if isinstance(data, dict) and "data" in data:
+ return _extract_count_value(data.get("data"))
+ if isinstance(data, list):
+ if not data:
+ return 0
+ return _extract_count_value(data[0])
+ return data
+
+
+def _read_values(gremlin_query: str) -> dict[str, Any]:
+ result = gremlin_tools.execute_gremlin_read(gremlin_query)
+ if isinstance(result, dict) and result.get("ok") is False:
+ return result
+ if isinstance(result, dict) and result.get("success") is False:
+ return envelope_err(
+ ErrorType.CONNECTION_FAILED,
+ "HugeGraph read query failed during graph change dry run.",
+ details=result,
+ retryable=True,
+ )
+ data = result.get("data") if isinstance(result, dict) else result
+ if isinstance(data, dict) and "data" in data:
+ data = data["data"]
+ return envelope_ok({"values": data if isinstance(data, list) else [data]})
+
+
+def _mutation_summary(operations: list[dict[str, Any]]) -> dict[str, int]:
+ counts: dict[str, int] = {}
+ for operation in operations:
+ op = str(operation.get("op") or operation.get("type") or "unknown")
+ counts[op] = counts.get(op, 0) + 1
+ return counts
+
+
+# ---- Plan hash calculation — tamper-resistance check ----
+
+
+def calculate_graph_change_plan_hash(
+ change_plan: Any,
+ graph: str | None = None,
+ graphspace: str | None = None,
+ schema_summary: dict[str, Any] | None = None,
+ extra_hash_context: dict[str, Any] | None = None,
+) -> str:
+ """基于 change_plan + graph/schema 上下文计算确定性哈希。
+
+ 用于防篡改安全链:dry_run 返回 plan_hash,执行时校验匹配。
+ """
+ cfg = MCPConfig.from_env()
+ payload: dict[str, Any] = {
+ "change_plan": change_plan,
+ "graph": cfg.graph if graph is None else graph,
+ "graphspace": cfg.graphspace if graphspace is None else graphspace,
+ }
+ if schema_summary is not None:
+ payload["schema_summary"] = schema_summary
+ if extra_hash_context is not None:
+ # Upstream callers may include source summaries and mapping configuration
+ # in the extra context so different sources do not reuse one confirmation hash.
+ payload["extra_hash_context"] = extra_hash_context
+ encoded = json.dumps(payload, sort_keys=True, default=str)
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:32]
+
+
+# ---- Dry-run preview ----
+
+
+def dry_run_graph_change_plan(
+ change_plan: Any,
+ live_schema: dict[str, Any],
+ extra_hash_context: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """干跑 — 校验 + 预览每个操作的影响(matched_count),不执行写入。
+
+ delete 操作通过只读 Gremlin 查询验证 matched_count==1,
+ delete_vertex cascade=false 时检查关联边。
+ """
+ validation = validate_graph_change_plan(change_plan, live_schema)
+ if not validation["valid"]:
+ return validation
+
+ operations = _operations(change_plan)
+ preview: list[dict[str, Any]] = []
+ errors: list[ValidationError] = []
+
+ for idx, operation in enumerate(operations):
+ op = str(operation.get("op") or operation.get("type"))
+ item = {
+ "operation_index": idx,
+ "op": op,
+ "label": operation.get("label"),
+ "action": op,
+ }
+ if op == "create_edge":
+ endpoint_failed = _append_edge_endpoint_counts(
+ idx=idx,
+ operation=operation,
+ op=op,
+ item=item,
+ errors=errors,
+ planned_operations=operations,
+ )
+ preview.append(item)
+ if endpoint_failed:
+ continue
+ item["matched_count"] = None
+ continue
+
+ if op == "create_vertex":
+ _append_create_vertex_identity_counts(
+ idx=idx,
+ operation=operation,
+ item=item,
+ errors=errors,
+ live_schema=live_schema,
+ )
+ item["matched_count"] = None
+ preview.append(item)
+ continue
+
+ if op not in WRITE_OPS:
+ # create operations do not need to match one existing record; schema
+ # and payload validity was checked during validation, so dry-run only
+ # displays the plan.
+ item["matched_count"] = None
+ preview.append(item)
+ continue
+
+ if op == "delete_edge":
+ # For edge deletion, verify both endpoints are unique before verifying
+ # the edge itself, so errors identify source/target rather than a vague
+ # edge-matching failure.
+ endpoint_failed = _append_edge_endpoint_counts(
+ idx=idx,
+ operation=operation,
+ op=op,
+ item=item,
+ errors=errors,
+ )
+ if endpoint_failed:
+ preview.append(item)
+ continue
+
+ match_query = (
+ _edge_match_query(operation)
+ if op == "delete_edge"
+ else _vertex_match_query(operation)
+ )
+ count_result = _read_count(match_query)
+ if not count_result.get("ok"):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "matched_count query failed",
+ "Verify HugeGraph Server is available and retry the dry run.",
+ )
+ )
+ continue
+ matched_count = count_result["data"]["matched_count"]
+ item["matched_count"] = matched_count
+
+ if op in {"delete_vertex", "delete_edge"} and matched_count != 1:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{op} matched_count must be 1, got {matched_count}",
+ "Narrow the match criteria so exactly one graph element is affected.",
+ )
+ )
+
+ if (
+ op == "delete_vertex"
+ and operation.get("cascade", False) is False
+ and matched_count == 1
+ ):
+ # By default, refuse to delete vertices with incident edges to avoid
+ # unpredictable data loss from HugeGraph-side cascading behavior.
+ # Users must explicitly delete the incident edges first.
+ edge_count_result = _read_count(f"{match_query}.bothE()")
+ if not edge_count_result.get("ok"):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "associated edge count query failed",
+ "Verify HugeGraph Server is available and retry the dry run.",
+ )
+ )
+ else:
+ edge_count = edge_count_result["data"]["matched_count"]
+ item["associated_edge_count"] = edge_count
+ if edge_count > 0:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "delete_vertex cascade=false but vertex has associated edges",
+ "Set cascade=true or delete associated edges first.",
+ "BLOCKED_BY_RELATIONSHIPS",
+ )
+ )
+ elif op == "delete_vertex" and operation.get("cascade", False) is True:
+ edge_result = _read_values(f"{match_query}.bothE().elementMap()")
+ if not edge_result.get("ok"):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "associated edge preview query failed",
+ "Verify HugeGraph Server is available and retry the dry run.",
+ )
+ )
+ else:
+ item["associated_edges"] = edge_result["data"]["values"]
+ # cascade=true currently previews incident edges only and does not
+ # perform cascading deletion. This conservative behavior is
+ # intentional; real cascading deletion needs separate product
+ # decisions and test coverage.
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "delete_vertex cascade=true is not enabled in this phase",
+ "Delete associated edges explicitly, then delete the vertex with cascade=false.",
+ "CASCADE_NOT_ENABLED",
+ )
+ )
+ preview.append(item)
+
+ if errors:
+ return {
+ "valid": False,
+ "errors": errors,
+ "warnings": validation.get("warnings", []),
+ "preview": preview,
+ }
+
+ return {
+ "valid": True,
+ "plan_hash": calculate_graph_change_plan_hash(
+ change_plan,
+ schema_summary=normalized_schema_summary(live_schema),
+ extra_hash_context=extra_hash_context,
+ ),
+ "mutation_summary": _mutation_summary(operations),
+ "preview": preview,
+ "warnings": validation.get("warnings", []),
+ }
+
+
+def _append_edge_endpoint_counts(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ op: str,
+ item: dict[str, Any],
+ errors: list[ValidationError],
+ planned_operations: list[Any] | None = None,
+) -> bool:
+ endpoint_failed = False
+ for endpoint, endpoint_query in (
+ ("source", _source_vertex_match_query(operation)),
+ ("target", _target_vertex_match_query(operation)),
+ ):
+ planned_count = _planned_endpoint_match_count(
+ operation=operation,
+ endpoint=endpoint,
+ planned_operations=planned_operations,
+ )
+ endpoint_count_result = _read_count(endpoint_query)
+ if not endpoint_count_result.get("ok"):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{endpoint} endpoint count query failed",
+ "Verify HugeGraph Server is available and retry the dry run.",
+ )
+ )
+ endpoint_failed = True
+ continue
+ live_count = endpoint_count_result["data"]["matched_count"]
+ total_count = planned_count + live_count
+ item[f"{endpoint}_planned_count"] = planned_count
+ item[f"{endpoint}_live_count"] = live_count
+ item[f"{endpoint}_matched_count"] = total_count
+ if total_count != 1:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{op} {endpoint} endpoint matched_count must be 1, got {total_count}",
+ "Narrow the endpoint match criteria so exactly one vertex is selected.",
+ )
+ )
+ endpoint_failed = True
+ return endpoint_failed
+
+
+def _planned_endpoint_match_count(
+ *,
+ operation: dict[str, Any],
+ endpoint: str,
+ planned_operations: list[Any] | None,
+) -> int:
+ if not planned_operations:
+ return 0
+
+ if endpoint == "source":
+ label = operation.get("source_label") or operation.get("outVLabel")
+ match = operation.get("source_match")
+ else:
+ label = operation.get("target_label") or operation.get("inVLabel")
+ match = operation.get("target_match")
+
+ if not isinstance(label, str) or not isinstance(match, dict):
+ return 0
+
+ count = 0
+ for planned in planned_operations:
+ if not isinstance(planned, dict):
+ continue
+ planned_op = str(planned.get("op") or planned.get("type") or "")
+ if planned_op != "create_vertex" or planned.get("label") != label:
+ continue
+ if _planned_vertex_matches(planned, match):
+ count += 1
+ return count
+
+
+def _planned_vertex_matches(operation: dict[str, Any], match: dict[str, Any]) -> bool:
+ for key, value in match.items():
+ if key == "id":
+ if operation.get("id") != value:
+ return False
+ continue
+ properties = operation.get("properties")
+ if not isinstance(properties, dict) or properties.get(key) != value:
+ return False
+ return bool(match)
+
+
+# ---- Execute — recheck matched_count before writing ----
+
+
+def execute_graph_change_plan(
+ change_plan: Any,
+ live_schema: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """执行变更计划 — 写入前对每个操作再次校验 matched_count。
+
+ 防止 dry_run 和 execute 之间状态变化导致的误操作。
+ """
+ operations = _operations(change_plan)
+ results: list[dict[str, Any]] = []
+ for idx, operation in enumerate(operations):
+ op = str(operation.get("op") or operation.get("type"))
+ if op == "create_vertex":
+ conflict = _create_vertex_identity_conflict(
+ operation=operation,
+ operation_index=idx,
+ live_schema=live_schema,
+ )
+ if conflict is not None:
+ return _execution_failure(conflict, operation, idx, results)
+
+ if op == "create_edge":
+ for endpoint, endpoint_query in (
+ ("source", _source_vertex_match_query(operation)),
+ ("target", _target_vertex_match_query(operation)),
+ ):
+ endpoint_count_result = _read_count(endpoint_query)
+ if not endpoint_count_result.get("ok"):
+ return _execution_failure(
+ endpoint_count_result, operation, idx, results
+ )
+ endpoint_count = endpoint_count_result["data"]["matched_count"]
+ if endpoint_count != 1:
+ return _execution_failure(
+ envelope_err(
+ ErrorType.INVALID_GRAPH_DATA,
+ f"{op} {endpoint} endpoint matched_count must be 1 before execution.",
+ details={
+ "operation_index": idx,
+ "matched_count": endpoint_count,
+ },
+ ),
+ operation,
+ idx,
+ results,
+ )
+
+ if op in WRITE_OPS:
+ # Read matched_count again before execution to handle graph changes
+ # between dry-run and confirmation. If the match is no longer unique,
+ # refuse the write to avoid TOCTOU issues.
+ if op == "delete_edge":
+ for endpoint, endpoint_query in (
+ ("source", _source_vertex_match_query(operation)),
+ ("target", _target_vertex_match_query(operation)),
+ ):
+ endpoint_count_result = _read_count(endpoint_query)
+ if not endpoint_count_result.get("ok"):
+ return _execution_failure(
+ endpoint_count_result, operation, idx, results
+ )
+ endpoint_count = endpoint_count_result["data"]["matched_count"]
+ if endpoint_count != 1:
+ return _execution_failure(
+ envelope_err(
+ ErrorType.INVALID_GRAPH_DATA,
+ f"{op} {endpoint} endpoint matched_count must be 1 before execution.",
+ details={
+ "operation_index": idx,
+ "matched_count": endpoint_count,
+ },
+ ),
+ operation,
+ idx,
+ results,
+ )
+ match_query = (
+ _edge_match_query(operation)
+ if op == "delete_edge"
+ else _vertex_match_query(operation)
+ )
+ count_result = _read_count(match_query)
+ if not count_result.get("ok"):
+ return _execution_failure(count_result, operation, idx, results)
+ matched_count = count_result["data"]["matched_count"]
+ if matched_count != 1:
+ return _execution_failure(
+ envelope_err(
+ ErrorType.INVALID_GRAPH_DATA,
+ f"{op} matched_count must be 1 before execution.",
+ details={
+ "operation_index": idx,
+ "matched_count": matched_count,
+ },
+ ),
+ operation,
+ idx,
+ results,
+ )
+ if op == "delete_vertex" and operation.get("cascade", False) is False:
+ edge_count_result = _read_count(f"{match_query}.bothE()")
+ if not edge_count_result.get("ok"):
+ return _execution_failure(
+ edge_count_result, operation, idx, results
+ )
+ edge_count = edge_count_result["data"]["matched_count"]
+ if edge_count > 0:
+ return _execution_failure(
+ envelope_err(
+ "BLOCKED_BY_RELATIONSHIPS",
+ "delete_vertex cascade=false but vertex has associated edges.",
+ suggestion="Delete associated edges first, then retry the vertex delete.",
+ details={
+ "operation_index": idx,
+ "associated_edge_count": edge_count,
+ },
+ ),
+ operation,
+ idx,
+ results,
+ )
+ if op == "delete_vertex" and operation.get("cascade", False) is True:
+ return _execution_failure(
+ envelope_err(
+ "CASCADE_NOT_ENABLED",
+ "delete_vertex cascade=true is not enabled in this phase.",
+ suggestion="Delete associated edges explicitly, then delete the vertex with cascade=false.",
+ details={"operation_index": idx},
+ ),
+ operation,
+ idx,
+ results,
+ )
+ write_result = gremlin_tools.execute_gremlin_write(
+ _write_query(operation),
+ capability=Capability.DATA_WRITE,
+ )
+ if isinstance(write_result, dict) and write_result.get("ok") is False:
+ return _execution_failure(write_result, operation, idx, results)
+ if isinstance(write_result, dict) and write_result.get("success") is False:
+ return _execution_failure(
+ envelope_err(
+ ErrorType.CONNECTION_FAILED,
+ "HugeGraph write query failed during graph change execution.",
+ details=write_result,
+ retryable=True,
+ ),
+ operation,
+ idx,
+ results,
+ )
+ if op in {"create_vertex", "create_edge"}:
+ affected = _write_affected_count(write_result)
+ if affected != 1:
+ return _execution_failure(
+ envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ f"{op} execution affected {affected if affected is not None else 'unknown'} element(s), expected 1.",
+ details={
+ "operation_index": idx,
+ "op": op,
+ "affected": affected,
+ "write_result": write_result,
+ },
+ ),
+ operation,
+ idx,
+ results,
+ )
+ if op in {"delete_vertex", "delete_edge"}:
+ # Recheck immediately after deletion to ensure HugeGraph actually
+ # removed the target. This catches silent backend failures and async
+ # state anomalies instead of trusting only the write response.
+ verify_query = (
+ _edge_match_query(operation)
+ if op == "delete_edge"
+ else _vertex_match_query(operation)
+ )
+ verify_result = _read_count(verify_query)
+ if not verify_result.get("ok"):
+ return _execution_failure(verify_result, operation, idx, results)
+ if verify_result["data"]["matched_count"] != 0:
+ return _execution_failure(
+ envelope_err(
+ "DELETE_VERIFY_FAILED",
+ f"{op} execution did not remove the matched element.",
+ suggestion="Inspect the graph state and retry after confirming the match criteria.",
+ details={
+ "operation_index": idx,
+ "op": op,
+ "matched_count": verify_result["data"]["matched_count"],
+ },
+ ),
+ operation,
+ idx,
+ results,
+ )
+ results.append(
+ {
+ "operation_index": idx,
+ "op": op,
+ "label": operation.get("label"),
+ "result": write_result,
+ }
+ )
+ return {
+ "success": True,
+ "results": results,
+ "mutation_summary": _mutation_summary(operations),
+ }
+
+
+def _write_affected_count(write_result: Any) -> int | None:
+ data = write_result
+ if isinstance(write_result, dict) and "ok" in write_result:
+ data = write_result.get("data")
+ if not isinstance(data, dict):
+ return None
+ for key in ("affected", "count"):
+ if key not in data:
+ continue
+ try:
+ return int(data.get(key))
+ except (TypeError, ValueError):
+ return None
+ return None
+
+
+def _append_create_vertex_identity_counts(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ item: dict[str, Any],
+ errors: list[ValidationError],
+ live_schema: dict[str, Any] | None,
+) -> None:
+ for identity_type, query in _create_vertex_identity_queries(
+ operation,
+ live_schema,
+ ):
+ count_result = _read_count(query)
+ if not count_result.get("ok"):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"create_vertex {identity_type} identity count query failed",
+ "Verify HugeGraph Server is available and retry the dry run.",
+ )
+ )
+ continue
+ live_count = count_result["data"]["matched_count"]
+ item[f"{identity_type}_live_count"] = live_count
+ if live_count > 0:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"create_vertex {identity_type} identity already exists in live graph",
+ "Use a new vertex identity or remove the existing vertex before importing.",
+ ErrorType.INVALID_GRAPH_DATA.value,
+ )
+ )
+
+
+def _create_vertex_identity_conflict(
+ *,
+ operation: dict[str, Any],
+ operation_index: int,
+ live_schema: dict[str, Any] | None,
+) -> dict[str, Any] | None:
+ for identity_type, query in _create_vertex_identity_queries(
+ operation,
+ live_schema,
+ ):
+ count_result = _read_count(query)
+ if not count_result.get("ok"):
+ return count_result
+ live_count = count_result["data"]["matched_count"]
+ if live_count > 0:
+ return envelope_err(
+ ErrorType.INVALID_GRAPH_DATA,
+ f"create_vertex {identity_type} identity already exists before execution.",
+ details={
+ "operation_index": operation_index,
+ "identity_type": identity_type,
+ "matched_count": live_count,
+ },
+ )
+ return None
+
+
+def _create_vertex_identity_queries(
+ operation: dict[str, Any],
+ live_schema: dict[str, Any] | None,
+) -> list[tuple[str, str]]:
+ label = operation.get("label")
+ if not isinstance(label, str) or not label:
+ return []
+
+ queries: list[tuple[str, str]] = []
+ explicit_id = operation.get("id")
+ if explicit_id not in (None, ""):
+ queries.append(("id", f"g.V().hasLabel({_g(label)}).hasId({_g(explicit_id)})"))
+
+ primary_keys = _create_vertex_primary_keys(label, live_schema)
+ properties = operation.get("properties")
+ if (
+ primary_keys
+ and isinstance(properties, dict)
+ and all(
+ pk in properties and properties.get(pk) not in (None, "")
+ for pk in primary_keys
+ )
+ ):
+ query = f"g.V().hasLabel({_g(label)})" + "".join(
+ f".has({_g(pk)},{_g(properties[pk])})" for pk in primary_keys
+ )
+ queries.append(("primary_key", query))
+
+ return queries
+
+
+def _create_vertex_primary_keys(
+ label: str,
+ live_schema: dict[str, Any] | None,
+) -> list[str]:
+ raw_schema = schema_payload(live_schema) or {}
+ for vertex_label in raw_schema.get("vertexlabels", []):
+ if not isinstance(vertex_label, dict):
+ continue
+ if vertex_label.get("name") == label:
+ return primary_key_names(vertex_label)
+ return []
+
+
+def _execution_failure(
+ error_result: dict[str, Any],
+ operation: dict[str, Any],
+ operation_index: int,
+ results: list[dict[str, Any]],
+) -> dict[str, Any]:
+ if not results:
+ return error_result
+
+ error = _extract_execution_error(error_result)
+ return {
+ "success": False,
+ "status": "partial",
+ "results": results,
+ "failed_items": [
+ {
+ "operation_index": operation_index,
+ "op": operation.get("op") or operation.get("type"),
+ "label": operation.get("label"),
+ "error": error,
+ }
+ ],
+ "warnings": ["Graph change execution stopped after a partial write."],
+ "mutation_summary": _mutation_summary(_operations({"operations": results})),
+ }
+
+
+def _extract_execution_error(error_result: dict[str, Any]) -> dict[str, Any]:
+ if isinstance(error_result, dict) and isinstance(error_result.get("error"), dict):
+ return error_result["error"]
+ return {
+ "type": ErrorType.CONNECTION_FAILED.value,
+ "message": "Graph change execution failed.",
+ "details": error_result if isinstance(error_result, dict) else {},
+ }
+
+
+# ---- Fetch live schema ----
+
+
+def _fetch_live_schema() -> dict[str, Any] | None:
+ return fetch_live_schema_or_none()
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/graph_data_gremlin.py b/hugegraph-mcp/hugegraph_mcp/tools/graph_data_gremlin.py
new file mode 100644
index 00000000..a5e364e4
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/graph_data_gremlin.py
@@ -0,0 +1,140 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Gremlin query generation for graph data change operations.
+
+Uses conservative literal escaping for injection prevention.
+"""
+
+import json
+from typing import Any
+
+# ---- Gremlin query generation — single-quoted strings prevent Groovy GString interpolation. ----
+
+
+def _g(value: Any) -> str:
+ if isinstance(value, str):
+ escaped = _escape_groovy_single_quoted(value)
+ return f"'{escaped}'"
+ if isinstance(value, dict):
+ # Groovy/Gremlin map literal uses [...] not {...}
+ items = ", ".join(f"{_g(k)}: {_g(v)}" for k, v in sorted(value.items()))
+ return f"[{items}]"
+ if isinstance(value, (list, tuple)):
+ items = ", ".join(_g(v) for v in value)
+ return f"[{items}]"
+ return json.dumps(value)
+
+
+def _escape_groovy_single_quoted(value: str) -> str:
+ chars: list[str] = []
+ for char in value:
+ if char == "\\":
+ chars.append("\\\\")
+ elif char == "'":
+ chars.append("\\'")
+ elif char == "\n":
+ chars.append("\\n")
+ elif char == "\r":
+ chars.append("\\r")
+ elif char == "\t":
+ chars.append("\\t")
+ elif char == "\b":
+ chars.append("\\b")
+ elif char == "\f":
+ chars.append("\\f")
+ elif ord(char) < 0x20:
+ chars.append(f"\\u{ord(char):04x}")
+ else:
+ chars.append(char)
+ return "".join(chars)
+
+
+def _has_steps(match: dict[str, Any]) -> str:
+ steps: list[str] = []
+ for key, value in match.items():
+ if key == "id":
+ steps.append(f".hasId({_g(value)})")
+ else:
+ steps.append(f".has({_g(key)},{_g(value)})")
+ return "".join(steps)
+
+
+def _vertex_match_query(operation: dict[str, Any]) -> str:
+ return f"g.V().hasLabel({_g(operation['label'])}){_has_steps(operation['match'])}"
+
+
+def _edge_match_query(operation: dict[str, Any]) -> str:
+ source_label = operation.get("source_label") or operation.get("outVLabel")
+ target_label = operation.get("target_label") or operation.get("inVLabel")
+ return (
+ f"g.V().hasLabel({_g(source_label)}){_has_steps(operation['source_match'])}"
+ f".outE({_g(operation['label'])})"
+ f".where(inV().hasLabel({_g(target_label)}){_has_steps(operation['target_match'])})"
+ )
+
+
+def _source_vertex_match_query(operation: dict[str, Any]) -> str:
+ source_label = operation.get("source_label") or operation.get("outVLabel")
+ return f"g.V().hasLabel({_g(source_label)}){_has_steps(operation['source_match'])}"
+
+
+def _target_vertex_match_query(operation: dict[str, Any]) -> str:
+ target_label = operation.get("target_label") or operation.get("inVLabel")
+ return f"g.V().hasLabel({_g(target_label)}){_has_steps(operation['target_match'])}"
+
+
+# ---- Gremlin write-statement generation — labels and values are schema-constrained and JSON-escaped. ----
+
+
+def _create_vertex_query(operation: dict[str, Any]) -> str:
+ query = f"g.addV({_g(operation['label'])})"
+ if operation.get("id") not in (None, ""):
+ query += f".property(T.id,{_g(operation['id'])})"
+ for prop, value in (operation.get("properties") or {}).items():
+ query += f".property({_g(prop)},{_g(value)})"
+ return query
+
+
+def _create_edge_query(operation: dict[str, Any]) -> str:
+ source_label = operation.get("source_label") or operation.get("outVLabel")
+ target_label = operation.get("target_label") or operation.get("inVLabel")
+ query = (
+ f"g.V().hasLabel({_g(source_label)}){_has_steps(operation['source_match'])}.as('s')"
+ f".V().hasLabel({_g(target_label)}){_has_steps(operation['target_match'])}"
+ f".addE({_g(operation['label'])}).from('s')"
+ )
+ for prop, value in (operation.get("properties") or {}).items():
+ query += f".property({_g(prop)},{_g(value)})"
+ return query
+
+
+def _delete_vertex_query(operation: dict[str, Any]) -> str:
+ return f"{_vertex_match_query(operation)}.drop()"
+
+
+def _delete_edge_query(operation: dict[str, Any]) -> str:
+ return f"{_edge_match_query(operation)}.drop()"
+
+
+def _write_query(operation: dict[str, Any]) -> str:
+ op = str(operation.get("op") or operation.get("type"))
+ if op == "create_vertex":
+ return _create_vertex_query(operation)
+ if op == "create_edge":
+ return _create_edge_query(operation)
+ if op == "delete_vertex":
+ return _delete_vertex_query(operation)
+ if op == "delete_edge":
+ return _delete_edge_query(operation)
+ raise ValueError(f"Unsupported op: {op}")
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/graph_data_mapping.py b/hugegraph-mcp/hugegraph_mcp/tools/graph_data_mapping.py
new file mode 100644
index 00000000..3af2a5e4
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/graph_data_mapping.py
@@ -0,0 +1,195 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""graph_data → change_plan 映射层 — 将用户输入的 {vertices, edges} 转为内部变更计划。
+
+graph_data_to_change_plan() 是核心转换函数:
+- 每个 vertex → create_vertex 操作
+- 每个 edge → create_edge 操作(含端点匹配)
+- 数字 id 和字符串 id 归一化处理
+
+该模块不依赖 manage_graph_data.py,避免循环导入。
+"""
+
+from typing import Any
+
+from hugegraph_mcp.tools.schema_utils import primary_key_names, schema_payload
+
+GraphChangePlan = dict[str, list[dict[str, Any]]]
+
+
+def _change_plan_from_operations(operations: list[dict[str, Any]]) -> GraphChangePlan:
+ return {"operations": operations}
+
+
+def graph_data_to_change_plan(
+ graph_data: dict[str, Any],
+ live_schema: dict[str, Any] | None = None,
+) -> GraphChangePlan:
+ """将图数据 {vertices, edges} 转为 change_plan {operations: [...]}。
+
+ vertices 全部映射为 create_vertex,edges 全部映射为 create_edge。
+ 边端点优先保留 extract_graph_data 输出的 id 契约,避免退化成非唯一属性匹配。
+ """
+ operations: list[dict[str, Any]] = []
+ vertex_ids = _vertex_ids_by_label(graph_data)
+ single_primary_keys = _single_primary_keys_by_label(live_schema)
+ primary_key_values = _vertex_primary_key_values(
+ graph_data,
+ single_primary_keys=single_primary_keys,
+ )
+ for vertex in graph_data.get("vertices") or []:
+ if not isinstance(vertex, dict):
+ continue
+ operation = {
+ "op": "create_vertex",
+ "label": vertex.get("label"),
+ "properties": vertex.get("properties") or {},
+ }
+ if vertex.get("id") not in (None, ""):
+ operation["id"] = vertex.get("id")
+ operations.append(operation)
+ for edge in graph_data.get("edges") or []:
+ if not isinstance(edge, dict):
+ continue
+ source_label = edge.get("source_label") or edge.get("outVLabel")
+ target_label = edge.get("target_label") or edge.get("inVLabel")
+ operations.append(
+ {
+ "op": "create_edge",
+ "label": edge.get("label"),
+ "source_label": source_label,
+ "target_label": target_label,
+ "source_match": _edge_endpoint_match(
+ edge=edge,
+ endpoint="source",
+ endpoint_label=source_label,
+ vertex_ids=vertex_ids,
+ single_primary_keys=single_primary_keys,
+ primary_key_values=primary_key_values,
+ ),
+ "target_match": _edge_endpoint_match(
+ edge=edge,
+ endpoint="target",
+ endpoint_label=target_label,
+ vertex_ids=vertex_ids,
+ single_primary_keys=single_primary_keys,
+ primary_key_values=primary_key_values,
+ ),
+ "properties": edge.get("properties") or {},
+ }
+ )
+ return _change_plan_from_operations(operations)
+
+
+def _vertex_ids_by_label(graph_data: dict[str, Any]) -> dict[tuple[str, str], Any]:
+ ids: dict[tuple[str, str], Any] = {}
+ for vertex in graph_data.get("vertices") or []:
+ if not isinstance(vertex, dict):
+ continue
+ label = vertex.get("label")
+ vertex_id = vertex.get("id")
+ if isinstance(label, str) and vertex_id not in (None, ""):
+ ids[(label, str(vertex_id))] = vertex_id
+ return ids
+
+
+def _single_primary_keys_by_label(
+ live_schema: dict[str, Any] | None,
+) -> dict[str, str]:
+ raw_schema = schema_payload(live_schema)
+ if raw_schema is None:
+ return {}
+
+ result: dict[str, str] = {}
+ for vertex_label in raw_schema.get("vertexlabels") or []:
+ if not isinstance(vertex_label, dict):
+ continue
+ label = vertex_label.get("name")
+ primary_keys = primary_key_names(vertex_label)
+ if isinstance(label, str) and len(primary_keys) == 1:
+ result[label] = primary_keys[0]
+ return result
+
+
+def _vertex_primary_key_values(
+ graph_data: dict[str, Any],
+ *,
+ single_primary_keys: dict[str, str],
+) -> dict[tuple[str, str], Any]:
+ values: dict[tuple[str, str], Any] = {}
+ for vertex in graph_data.get("vertices") or []:
+ if not isinstance(vertex, dict):
+ continue
+ label = vertex.get("label")
+ if not isinstance(label, str):
+ continue
+ primary_key = single_primary_keys.get(label)
+ properties = vertex.get("properties")
+ if primary_key is None or not isinstance(properties, dict):
+ continue
+ value = properties.get(primary_key)
+ if value not in (None, ""):
+ values[(label, str(value))] = value
+ return values
+
+
+def _edge_endpoint_match(
+ *,
+ edge: dict[str, Any],
+ endpoint: str,
+ endpoint_label: str | None,
+ vertex_ids: dict[tuple[str, str], Any],
+ single_primary_keys: dict[str, str],
+ primary_key_values: dict[tuple[str, str], Any],
+) -> dict[str, Any]:
+ """确定边端点的匹配条件。
+
+ source/target 对象保持原样;scalar 在单主键 schema 下优先匹配主键,
+ 允许指向已存在顶点;显式 payload id 与 outV/inV 始终保持 id 语义。
+ """
+ explicit_endpoint = endpoint in edge
+ if endpoint == "source":
+ explicit = edge.get("source")
+ vertex_id = edge.get("outV")
+ else:
+ explicit = edge.get("target")
+ vertex_id = edge.get("inV")
+
+ if isinstance(explicit, dict):
+ return explicit
+ fallback_id = explicit if explicit not in (None, "") else vertex_id
+ if isinstance(endpoint_label, str) and fallback_id not in (None, ""):
+ identity_key = (endpoint_label, str(fallback_id))
+ matched_vertex_id = vertex_ids.get(identity_key)
+ if matched_vertex_id is not None:
+ return {"id": matched_vertex_id}
+
+ if explicit_endpoint:
+ primary_key = single_primary_keys.get(endpoint_label)
+ primary_key_value = primary_key_values.get(identity_key)
+ if (
+ primary_key_value is None
+ and isinstance(fallback_id, str)
+ and ":" in fallback_id
+ ):
+ primary_key_value = primary_key_values.get(
+ (endpoint_label, fallback_id.split(":", 1)[1])
+ )
+ if primary_key is not None:
+ return {
+ primary_key: primary_key_value
+ if primary_key_value is not None
+ else fallback_id
+ }
+ return {"id": fallback_id}
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/graph_data_validate.py b/hugegraph-mcp/hugegraph_mcp/tools/graph_data_validate.py
new file mode 100644
index 00000000..9be4b608
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/graph_data_validate.py
@@ -0,0 +1,492 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Graph data change plan validation.
+
+Schema checks, property field validation, primary key match verification.
+"""
+
+from typing import Any
+
+from hugegraph_mcp.tools.graph_data_mapping import GraphChangePlan
+from hugegraph_mcp.tools.schema_utils import (
+ edge_schema_endpoint_label as _edge_schema_endpoint_label,
+)
+from hugegraph_mcp.tools.schema_utils import (
+ normalized_schema_summary,
+ schema_name,
+ schema_payload,
+)
+from hugegraph_mcp.tools.schema_utils import (
+ primary_key_names as _primary_key_names,
+)
+from hugegraph_mcp.tools.schema_utils import (
+ property_names as _property_names,
+)
+
+ALLOWED_OPS = frozenset(
+ {
+ "create_vertex",
+ "create_edge",
+ "delete_vertex",
+ "delete_edge",
+ }
+)
+
+VERTEX_OPS = frozenset({"create_vertex", "delete_vertex"})
+EDGE_OPS = frozenset({"create_edge", "delete_edge"})
+WRITE_OPS = frozenset({"delete_vertex", "delete_edge"})
+# Each mode allows only specific operation types to prevent misuse.
+MODE_OPS = {
+ "import": frozenset({"create_vertex", "create_edge"}),
+ "delete": frozenset({"delete_vertex", "delete_edge"}),
+}
+
+ValidationError = dict[str, Any]
+
+
+# ---- Schema helpers ----
+
+
+def _schema_payload(live_schema: dict[str, Any] | None) -> dict[str, Any]:
+ # Keep compatibility with old tests that reference this private helper;
+ # the actual implementation is centralized in schema_utils.
+ return schema_payload(live_schema) or {}
+
+
+def _schema_name(item: Any) -> str | None:
+ # Support both string and object property representations in HugeGraph schemas.
+ return schema_name(item)
+
+
+def _vertex_labels(raw_schema: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ labels: dict[str, dict[str, Any]] = {}
+ for label in raw_schema.get("vertexlabels", []):
+ if not isinstance(label, dict):
+ continue
+ name = label.get("name")
+ if isinstance(name, str):
+ labels[name] = label
+ return labels
+
+
+def _edge_labels(raw_schema: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ labels: dict[str, dict[str, Any]] = {}
+ for label in raw_schema.get("edgelabels", []):
+ if not isinstance(label, dict):
+ continue
+ name = label.get("name")
+ if isinstance(name, str):
+ labels[name] = label
+ return labels
+
+
+def _schema_summary(live_schema: dict[str, Any] | None) -> dict[str, Any] | None:
+ return normalized_schema_summary(live_schema)
+
+
+def _operations(change_plan: Any) -> list[Any]:
+ if isinstance(change_plan, list):
+ return change_plan
+ if not isinstance(change_plan, dict):
+ return []
+ operations = change_plan.get("operations")
+ return operations if isinstance(operations, list) else []
+
+
+def _validation_error(
+ operation_index: int,
+ operation: Any,
+ reason: str,
+ suggestion: str,
+ error_type: str | None = None,
+) -> ValidationError:
+ error = {
+ "operation_index": operation_index,
+ "operation": operation,
+ "reason": reason,
+ "suggestion": suggestion,
+ }
+ if error_type is not None:
+ error["error_type"] = error_type
+ return error
+
+
+# ---- Validation helpers ----
+
+
+def _validate_field_map(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ field: str,
+ allowed_properties: set[str],
+ errors: list[ValidationError],
+ allow_id: bool = False,
+) -> None:
+ values = operation.get(field)
+ if values is None:
+ return
+ if not isinstance(values, dict):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must be an object",
+ f"Use an object mapping property names to values for {field}.",
+ )
+ )
+ return
+ allowed = set(allowed_properties)
+ if allow_id:
+ allowed.add("id")
+ unknown = sorted(set(values) - allowed)
+ if unknown:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} references property not on label: {', '.join(unknown)}",
+ "Use only properties defined on the referenced label.",
+ )
+ )
+
+
+def _validate_primary_key_match(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ field: str,
+ primary_keys: list[str],
+ errors: list[ValidationError],
+) -> None:
+ match = operation.get(field)
+ if not isinstance(match, dict):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must be an object",
+ f"Use {field} to identify a vertex by its primary key.",
+ )
+ )
+ return
+ if match.get("id") not in (None, ""):
+ return
+ missing = [
+ pk for pk in primary_keys if pk not in match or match.get(pk) in (None, "")
+ ]
+ if missing:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must contain primary key(s): {', '.join(missing)}",
+ "Include every primary key from the referenced vertex label.",
+ )
+ )
+
+
+# ---- Change-plan validation ----
+
+
+def validate_graph_change_plan(
+ change_plan: Any,
+ live_schema: dict[str, Any],
+) -> dict[str, Any]:
+ """校验 change_plan 中的操作是否与 live schema 兼容。
+
+ 检查项:op 类型白名单、label 存在性、properties/match 字段合法性、
+ 主键匹配、边端点合法性。
+ """
+ errors: list[ValidationError] = []
+ warnings: list[str] = []
+
+ if not isinstance(change_plan, (dict, list)):
+ return {
+ "valid": False,
+ "errors": [
+ _validation_error(
+ -1,
+ change_plan,
+ "change_plan must be an object with operations",
+ "Pass {'operations': [...]} as the graph change plan.",
+ )
+ ],
+ "warnings": [],
+ }
+
+ if isinstance(change_plan, dict) and not isinstance(
+ change_plan.get("operations"), list
+ ):
+ return {
+ "valid": False,
+ "errors": [
+ _validation_error(
+ -1,
+ change_plan,
+ "change_plan.operations must be a list",
+ "Pass graph change operations as a JSON array.",
+ )
+ ],
+ "warnings": [],
+ }
+
+ operations = _operations(change_plan)
+ raw_schema = _schema_payload(live_schema)
+ # Index the live schema by label/name first so each operation uses O(1)
+ # lookups, while ensuring validation always uses one schema snapshot.
+ vertex_labels = _vertex_labels(raw_schema)
+ edge_labels = _edge_labels(raw_schema)
+ vertex_properties = {
+ label: _property_names(schema.get("properties"))
+ for label, schema in vertex_labels.items()
+ }
+ edge_properties = {
+ label: _property_names(schema.get("properties"))
+ for label, schema in edge_labels.items()
+ }
+ primary_keys = {
+ label: _primary_key_names(schema) for label, schema in vertex_labels.items()
+ }
+
+ for idx, operation in enumerate(operations):
+ if not isinstance(operation, dict):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "operation must be an object",
+ "Replace this item with a graph change operation object.",
+ )
+ )
+ continue
+
+ op = str(operation.get("op") or operation.get("type") or "")
+ if op not in ALLOWED_OPS:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"unsupported op: {op}",
+ "Use one of: create_vertex, create_edge, delete_vertex, delete_edge.",
+ )
+ )
+ continue
+
+ label = operation.get("label")
+ if not isinstance(label, str) or not label:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "missing required field: label",
+ "Add the schema label targeted by this operation.",
+ )
+ )
+ continue
+
+ if "set" in operation:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "set is not supported by V1 graph data operations",
+ "Use properties for create operations, or submit update support in a later V2 change.",
+ )
+ )
+
+ if op in VERTEX_OPS:
+ if label not in vertex_labels:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"label references undefined vertex label: {label}",
+ "Use an existing vertex label from the live schema.",
+ )
+ )
+ continue
+ allowed = vertex_properties.get(label, set())
+ pks = primary_keys.get(label, [])
+ if not pks:
+ warnings.append(
+ f"operation {idx} references vertex label '{label}' with no primary_keys"
+ )
+ # properties/match may reference only properties defined for the label.
+ # First apply the field allowlist, then enforce stricter op constraints.
+ _validate_field_map(
+ idx=idx,
+ operation=operation,
+ field="properties",
+ allowed_properties=allowed,
+ errors=errors,
+ )
+ _validate_field_map(
+ idx=idx,
+ operation=operation,
+ field="match",
+ allowed_properties=allowed,
+ errors=errors,
+ allow_id=True,
+ )
+ if op == "delete_vertex":
+ _validate_primary_key_match(
+ idx=idx,
+ operation=operation,
+ field="match",
+ primary_keys=pks,
+ errors=errors,
+ )
+ else:
+ if label not in edge_labels:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"label references undefined edge label: {label}",
+ "Use an existing edge label from the live schema.",
+ )
+ )
+ continue
+ edge_schema = edge_labels[label]
+ source_label = operation.get("source_label") or operation.get("outVLabel")
+ target_label = operation.get("target_label") or operation.get("inVLabel")
+ # Edge operations must satisfy two constraints:
+ # 1. The endpoint labels in the request exist.
+ # 2. The endpoint direction matches the direction defined by the edge label.
+ for endpoint_name, endpoint_label in (
+ ("source_label", source_label),
+ ("target_label", target_label),
+ ):
+ if (
+ not isinstance(endpoint_label, str)
+ or endpoint_label not in vertex_labels
+ ):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{endpoint_name} references undefined vertex label: {endpoint_label}",
+ "Use existing source and target vertex labels from the live schema.",
+ )
+ )
+ expected_source = _edge_schema_endpoint_label(edge_schema, "source")
+ expected_target = _edge_schema_endpoint_label(edge_schema, "target")
+ if expected_source and source_label and source_label != expected_source:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"source_label does not match edge label '{label}' source_label '{expected_source}'",
+ "Use the source label defined by the edge schema.",
+ )
+ )
+ if expected_target and target_label and target_label != expected_target:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"target_label does not match edge label '{label}' target_label '{expected_target}'",
+ "Use the target label defined by the edge schema.",
+ )
+ )
+ allowed = edge_properties.get(label, set())
+ _validate_field_map(
+ idx=idx,
+ operation=operation,
+ field="properties",
+ allowed_properties=allowed,
+ errors=errors,
+ )
+ if isinstance(source_label, str) and source_label in vertex_labels:
+ _validate_primary_key_match(
+ idx=idx,
+ operation=operation,
+ field="source_match",
+ primary_keys=primary_keys.get(source_label, []),
+ errors=errors,
+ )
+ _validate_field_map(
+ idx=idx,
+ operation=operation,
+ field="source_match",
+ allowed_properties=vertex_properties.get(source_label, set()),
+ errors=errors,
+ allow_id=True,
+ )
+ if isinstance(target_label, str) and target_label in vertex_labels:
+ _validate_primary_key_match(
+ idx=idx,
+ operation=operation,
+ field="target_match",
+ primary_keys=primary_keys.get(target_label, []),
+ errors=errors,
+ )
+ _validate_field_map(
+ idx=idx,
+ operation=operation,
+ field="target_match",
+ allowed_properties=vertex_properties.get(target_label, set()),
+ errors=errors,
+ allow_id=True,
+ )
+
+ return {"valid": not bool(errors), "errors": errors, "warnings": warnings}
+
+
+# ---- Mode operation constraints ----
+
+
+def _validate_mode_operations(
+ mode: str, change_plan: GraphChangePlan
+) -> dict[str, Any]:
+ """确保 mode 下的所有操作类型匹配,例如 import 模式不允许删除。"""
+ allowed = MODE_OPS.get(mode)
+ if allowed is None:
+ return {
+ "valid": False,
+ "errors": [
+ _validation_error(
+ -1,
+ change_plan,
+ f"unknown mode: {mode}",
+ "Use mode='import' or mode='delete'.",
+ )
+ ],
+ "warnings": [],
+ }
+
+ errors = []
+ for idx, operation in enumerate(_operations(change_plan)):
+ if not isinstance(operation, dict):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "operation must be an object",
+ "Replace this item with a graph change operation object.",
+ )
+ )
+ continue
+ op = str(operation.get("op") or operation.get("type") or "")
+ if op not in allowed:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"op {op} is not allowed in mode='{mode}'",
+ f"Use only {', '.join(sorted(allowed))} operations for mode='{mode}'.",
+ )
+ )
+ return {"valid": not bool(errors), "errors": errors, "warnings": []}
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/ingest_graph_data.py b/hugegraph-mcp/hugegraph_mcp/tools/ingest_graph_data.py
new file mode 100644
index 00000000..a03c66a2
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/ingest_graph_data.py
@@ -0,0 +1,1337 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""图数据导入 — 结构化 graph_data 校验和 legacy AI-backed 写入链路。
+
+=== MCP V1 导入路径说明 ===
+
+当前存在两条导入路径:
+
+1. **Public V1 路径(推荐)**
+ import_graph_data_tool(mode="ingest") 路由到 manage_graph_data()
+ → graph_data_to_change_plan() → 本地 Gremlin 写入。
+ 此路径在 server.py:_import_graph_data() 中分发,不依赖
+ HugeGraph-AI 服务。
+
+2. **Legacy AI-backed 路径(兼容保留)**
+ ingest_graph_data() 真实实现为 ingest_graph_data_via_ai(),
+ 通过 HugeGraph-AI /graph-import HTTP 接口写入。
+ 仅供需要 AI 辅助属性映射的内部/legacy 场景使用,
+ 不做为 MCP V1 公共工具的默认导入链路。
+
+validate_graph_payload() 对 vertices/edges 做全面 schema 校验:
+- label 是否存在于 live schema
+- properties 字段是否在对应 label 中定义
+- 主键是否提供
+- 边端点是否可解析
+- 类型匹配
+"""
+
+import json
+from copy import deepcopy
+from typing import Any
+from uuid import uuid4
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.confirmable_workflow import (
+ issue_plan,
+ mark_readonly_preview,
+ plan_hash_error,
+ replayed_plan_error,
+ verify_and_consume_plan,
+)
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+from hugegraph_mcp.guard import Capability, guard
+from hugegraph_mcp.hugegraph_ai_client import post
+from hugegraph_mcp.tools.live_schema import fetch_live_schema_or_none
+from hugegraph_mcp.tools.schema_utils import (
+ edge_schema_endpoint_label as _edge_schema_endpoint_label,
+)
+from hugegraph_mcp.tools.schema_utils import (
+ normalized_schema_summary,
+)
+from hugegraph_mcp.tools.schema_utils import (
+ primary_key_names as _primary_key_names,
+)
+from hugegraph_mcp.tools.schema_utils import (
+ property_names as _property_names,
+)
+from hugegraph_mcp.tools.schema_utils import (
+ schema_payload as _schema_payload,
+)
+
+_DATA_TYPE_ALIASES = {"INTEGER": "INT", "BOOL": "BOOLEAN"}
+_SUPPORTED_DATA_TYPES = {
+ "TEXT",
+ "UUID",
+ "INT",
+ "LONG",
+ "DOUBLE",
+ "FLOAT",
+ "BOOLEAN",
+ "DATE",
+ "BYTE",
+ "BLOB",
+ "OBJECT",
+}
+_SUPPORTED_CARDINALITIES = {"SINGLE", "LIST", "SET"}
+
+
+def _property_specs(raw_schema: dict[str, Any]) -> dict[str, tuple[str, str]]:
+ specs: dict[str, tuple[str, str]] = {}
+ normalized_schema = normalized_schema_summary(raw_schema) or {}
+ for prop in normalized_schema.get("propertykeys", []):
+ if not isinstance(prop, dict):
+ continue
+ name = prop.get("name")
+ data_type = prop.get("data_type")
+ if isinstance(name, str) and isinstance(data_type, str):
+ cardinality = prop.get("cardinality") or "SINGLE"
+ normalized_data_type = data_type.strip().upper()
+ specs[name] = (
+ _DATA_TYPE_ALIASES.get(normalized_data_type, normalized_data_type),
+ str(cardinality).strip().upper(),
+ )
+ return specs
+
+
+def _value_matches_type(value: Any, data_type: str) -> bool:
+ if value is None:
+ return True
+ if data_type in {"TEXT", "UUID"}:
+ return isinstance(value, str)
+ if data_type in {"INT", "LONG", "BYTE"}:
+ return isinstance(value, int) and not isinstance(value, bool)
+ if data_type in {"FLOAT", "DOUBLE"}:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+ if data_type == "BOOLEAN":
+ return isinstance(value, bool)
+ if data_type in {"DATE", "BLOB"}:
+ return isinstance(value, str)
+ if data_type == "OBJECT":
+ return isinstance(value, dict)
+ return False
+
+
+def _property_value_error(
+ *,
+ item_kind: str,
+ item_index: int,
+ property_name: str,
+ value: Any,
+ spec: tuple[str, str] | None,
+) -> str | None:
+ if spec is None:
+ return None
+
+ data_type, cardinality = spec
+ prefix = f"{item_kind} {item_index} property '{property_name}'"
+ if data_type not in _SUPPORTED_DATA_TYPES:
+ return f"{prefix} unsupported data_type '{data_type}'"
+ if cardinality not in _SUPPORTED_CARDINALITIES:
+ return f"{prefix} unsupported cardinality '{cardinality}'"
+ if cardinality in {"LIST", "SET"}:
+ if value is None:
+ return None
+ if not isinstance(value, list):
+ return (
+ f"{prefix} expects {cardinality} of {data_type}, "
+ f"got {type(value).__name__}"
+ )
+ for element_index, element in enumerate(value):
+ if element is None or not _value_matches_type(element, data_type):
+ return (
+ f"{prefix} element {element_index} expects {data_type}, "
+ f"got {type(element).__name__}"
+ )
+ return None
+
+ if not _value_matches_type(value, data_type):
+ return f"{prefix} expects {data_type}, got {type(value).__name__}"
+ return None
+
+
+def _indexed_labels(raw_schema: dict[str, Any]) -> dict[str, set[str]]:
+ indexed = {"VERTEX": set(), "EDGE": set()}
+ for index in raw_schema.get("indexlabels", []):
+ if not isinstance(index, dict):
+ continue
+ base_label = index.get("base_label") or index.get("baseLabel")
+ if not isinstance(base_label, str):
+ continue
+ base_type = str(index.get("base_type") or index.get("baseType") or "").upper()
+ if base_type in {"VERTEX", "VERTEX_LABEL"}:
+ indexed["VERTEX"].add(base_label)
+ elif base_type in {"EDGE", "EDGE_LABEL"}:
+ indexed["EDGE"].add(base_label)
+ return indexed
+
+
+def _edge_endpoint(edge: dict[str, Any], endpoint: str) -> tuple[Any, Any]:
+ if endpoint == "source":
+ label = edge.get("source_label") or edge.get("outVLabel")
+ value = edge.get("source") if "source" in edge else edge.get("outV")
+ else:
+ label = edge.get("target_label") or edge.get("inVLabel")
+ value = edge.get("target") if "target" in edge else edge.get("inV")
+ return label, value
+
+
+def _has_mixed_endpoint_forms(edge: dict[str, Any], endpoint: str) -> bool:
+ if endpoint == "source":
+ return "source" in edge and "outV" in edge
+ return "target" in edge and "inV" in edge
+
+
+def _identity_value_present(value: Any) -> bool:
+ return value is not None and value != ""
+
+
+def _format_endpoint_value(value: Any) -> str:
+ return repr(value)
+
+
+def _endpoint_identities(
+ label: str,
+ value: Any,
+ schema_primary_keys: dict[str, list[str]],
+) -> tuple[list[tuple[str, str, Any]], str | None]:
+ # Edge endpoints support backend IDs or objects keyed by vertex primary keys.
+ # Multiple candidate identities support both inputs such as "1:alice" and
+ # {"name": "alice"}.
+ identities: list[tuple[str, str, Any]] = []
+ primary_keys = schema_primary_keys.get(label, [])
+
+ if isinstance(value, dict):
+ explicit_id = value.get("id")
+ if _identity_value_present(explicit_id):
+ identities.append((label, "id", explicit_id))
+ if primary_keys:
+ missing = [
+ pk
+ for pk in primary_keys
+ if pk not in value or not _identity_value_present(value.get(pk))
+ ]
+ if missing:
+ if identities:
+ return identities, None
+ return identities, missing[0]
+ identities.append(
+ (label, "pk", tuple(value.get(pk) for pk in primary_keys))
+ )
+ return identities, None
+
+ if _identity_value_present(value):
+ identities.append((label, "id", value))
+ if len(primary_keys) == 1:
+ pk_value = value
+ if isinstance(value, str) and ":" in value:
+ pk_value = value.split(":", 1)[1]
+ identities.append((label, "pk", (pk_value,)))
+ return identities, None
+
+
+def _schema_plan_summary(live_schema: dict[str, Any] | None) -> dict[str, Any] | None:
+ raw = _schema_payload(live_schema)
+ if raw is None:
+ return None
+ return {
+ "vertexlabels": raw.get("vertexlabels", []),
+ "edgelabels": raw.get("edgelabels", []),
+ "propertykeys": raw.get("propertykeys", []),
+ "indexlabels": raw.get("indexlabels", []),
+ }
+
+
+def _canonical_json_key(value: Any) -> str:
+ return json.dumps(value, sort_keys=True, default=str, separators=(",", ":"))
+
+
+def _normalize_value(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {
+ key: _normalize_value(value[key])
+ for key in sorted(value, key=lambda item: str(item))
+ }
+ if isinstance(value, list):
+ return [_normalize_value(item) for item in value]
+ return value
+
+
+def _vertex_sort_key(
+ vertex: Any,
+ schema_primary_keys: dict[str, list[str]],
+) -> tuple[str, str]:
+ if not isinstance(vertex, dict):
+ return ("", _canonical_json_key(vertex))
+ label = str(vertex.get("label") or "")
+ if _identity_value_present(vertex.get("id")):
+ identity = vertex.get("id")
+ else:
+ props = vertex.get("properties")
+ primary_keys = schema_primary_keys.get(label, [])
+ if isinstance(props, dict) and primary_keys:
+ identity = props.get(primary_keys[0])
+ elif isinstance(props, dict) and props:
+ first_key = min(props, key=lambda item: str(item))
+ identity = props.get(first_key)
+ else:
+ identity = None
+ return (label, _canonical_json_key(identity))
+
+
+def _edge_sort_key(edge: Any) -> tuple[str, str, str, str]:
+ if not isinstance(edge, dict):
+ return ("", "", "", _canonical_json_key(edge))
+ source_label, source = _edge_endpoint(edge, "source")
+ target_label, target = _edge_endpoint(edge, "target")
+ return (
+ str(edge.get("label") or ""),
+ str(source_label or ""),
+ str(target_label or ""),
+ _canonical_json_key(
+ {
+ "source": source,
+ "target": target,
+ "properties": edge.get("properties", {}),
+ }
+ ),
+ )
+
+
+def _normalize_graph_data(
+ graph_data: dict[str, Any],
+ schema_summary: dict[str, Any] | None,
+) -> dict[str, Any]:
+ # plan_hash must be independent of input order: the same vertices/edges should
+ # produce the same hash even when JSON array order differs. Security-relevant
+ # values such as properties and schema primary keys must still be included.
+ normalized = _normalize_value(graph_data)
+ if not isinstance(normalized, dict):
+ return normalized
+
+ schema_primary_keys: dict[str, list[str]] = {}
+ if schema_summary:
+ for vertex_label in schema_summary.get("vertexlabels", []):
+ if isinstance(vertex_label, dict):
+ name = vertex_label.get("name")
+ primary_keys = vertex_label.get("primary_keys")
+ if isinstance(name, str) and isinstance(primary_keys, list):
+ schema_primary_keys[name] = primary_keys
+
+ vertices = normalized.get("vertices")
+ if isinstance(vertices, list):
+ normalized["vertices"] = sorted(
+ vertices,
+ key=lambda vertex: _vertex_sort_key(vertex, schema_primary_keys),
+ )
+
+ edges = normalized.get("edges")
+ if isinstance(edges, list):
+ normalized["edges"] = sorted(edges, key=_edge_sort_key)
+
+ return normalized
+
+
+def _schema_vertex_info(raw_schema: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ info: dict[str, dict[str, Any]] = {}
+ for vertex_label in raw_schema.get("vertexlabels", []):
+ if not isinstance(vertex_label, dict):
+ continue
+ name = vertex_label.get("name")
+ if isinstance(name, str):
+ info[name] = {
+ "id": vertex_label.get("id"),
+ "id_strategy": str(
+ vertex_label.get("id_strategy")
+ or vertex_label.get("idStrategy")
+ or "PRIMARY_KEY"
+ ).upper(),
+ "primary_keys": _primary_key_names(vertex_label),
+ }
+ return info
+
+
+def _canonical_primary_key_id(
+ label: str,
+ values: tuple[Any, ...],
+ vertex_info: dict[str, dict[str, Any]],
+) -> str | None:
+ label_id = vertex_info.get(label, {}).get("id")
+ if label_id is None:
+ return None
+ return f"{label_id}:{'!'.join(str(value) for value in values)}"
+
+
+def _vertex_backend_id(
+ vertex: dict[str, Any],
+ vertex_info: dict[str, dict[str, Any]],
+) -> Any:
+ # A HugeGraph PRIMARY_KEY vertex backend ID combines the label ID and primary-key
+ # value. Filling in IDs before import lets endpoints reliably reference vertices
+ # created in the same payload.
+ explicit_id = vertex.get("id")
+ if _identity_value_present(explicit_id):
+ return explicit_id
+
+ label = vertex.get("label")
+ props = vertex.get("properties")
+ if not isinstance(label, str) or not isinstance(props, dict):
+ return None
+
+ primary_keys = vertex_info.get(label, {}).get("primary_keys", [])
+ if not primary_keys:
+ return None
+ if not all(
+ pk in props and _identity_value_present(props.get(pk)) for pk in primary_keys
+ ):
+ return None
+
+ values = tuple(props.get(pk) for pk in primary_keys)
+ return _canonical_primary_key_id(label, values, vertex_info)
+
+
+def _vertex_identity_map(
+ vertices: list[Any],
+ raw_schema: dict[str, Any],
+) -> tuple[dict[tuple[str, str, Any], Any], dict[str, list[str]]]:
+ # Build a mapping from user-expressible identities to HugeGraph backend IDs.
+ # A vertex may have an explicit ID, a PRIMARY_KEY backend ID, and a primary-key
+ # tuple; resolving any of them must target the same backend vertex.
+ vertex_info = _schema_vertex_info(raw_schema)
+ schema_primary_keys = {
+ label: info.get("primary_keys", []) for label, info in vertex_info.items()
+ }
+ identities: dict[tuple[str, str, Any], Any] = {}
+
+ for vertex in vertices:
+ if not isinstance(vertex, dict):
+ continue
+ label = vertex.get("label")
+ if not isinstance(label, str):
+ continue
+
+ backend_id = _vertex_backend_id(vertex, vertex_info)
+ if _identity_value_present(backend_id):
+ vertex.setdefault("id", backend_id)
+ identities[(label, "id", backend_id)] = backend_id
+
+ explicit_id = vertex.get("id")
+ if _identity_value_present(explicit_id):
+ identities[(label, "id", explicit_id)] = backend_id or explicit_id
+
+ props = vertex.get("properties")
+ primary_keys = schema_primary_keys.get(label, [])
+ if (
+ isinstance(props, dict)
+ and primary_keys
+ and all(
+ pk in props and _identity_value_present(props.get(pk))
+ for pk in primary_keys
+ )
+ ):
+ values = tuple(props.get(pk) for pk in primary_keys)
+ identities[(label, "pk", values)] = backend_id or explicit_id
+
+ return identities, schema_primary_keys
+
+
+def _endpoint_backend_id(
+ label: str,
+ value: Any,
+ identities: dict[tuple[str, str, Any], Any],
+ schema_primary_keys: dict[str, list[str]],
+ vertex_info: dict[str, dict[str, Any]],
+) -> Any:
+ # Resolve endpoints against vertices in the current payload first, so batch
+ # imports can create vertices before edges without requiring backend IDs upfront.
+ endpoint_identities, _missing_pk = _endpoint_identities(
+ label,
+ value,
+ schema_primary_keys,
+ )
+ for identity in endpoint_identities:
+ if identity in identities:
+ return identities[identity]
+
+ if isinstance(value, dict):
+ explicit_id = value.get("id")
+ if _identity_value_present(explicit_id):
+ return explicit_id
+
+ primary_keys = schema_primary_keys.get(label, [])
+ if primary_keys and all(
+ pk in value and _identity_value_present(value.get(pk))
+ for pk in primary_keys
+ ):
+ values = tuple(value.get(pk) for pk in primary_keys)
+ return _canonical_primary_key_id(label, values, vertex_info)
+ return None
+
+ if _identity_value_present(value):
+ return value
+ return None
+
+
+def _prepare_graph_import_data(
+ graph_data: dict[str, Any],
+ live_schema: dict[str, Any],
+) -> dict[str, Any]:
+ # HugeGraph-AI's graph-import endpoint requires outV/inV/outVLabel/inVLabel.
+ # MCP exposes the friendlier source/target fields, so convert them before writing.
+ prepared = deepcopy(graph_data)
+ raw_schema = _schema_payload(live_schema) or {}
+ vertex_info = _schema_vertex_info(raw_schema)
+ vertices = prepared.get("vertices") or []
+ edges = prepared.get("edges") or []
+ identities, schema_primary_keys = _vertex_identity_map(vertices, raw_schema)
+
+ for edge in edges:
+ if not isinstance(edge, dict):
+ continue
+ src_label, source = _edge_endpoint(edge, "source")
+ tgt_label, target = _edge_endpoint(edge, "target")
+ edge.setdefault("properties", {})
+
+ if isinstance(src_label, str):
+ source_id = _endpoint_backend_id(
+ src_label,
+ source,
+ identities,
+ schema_primary_keys,
+ vertex_info,
+ )
+ if _identity_value_present(source_id):
+ edge["outV"] = source_id
+ edge.setdefault("outVLabel", src_label)
+
+ if isinstance(tgt_label, str):
+ target_id = _endpoint_backend_id(
+ tgt_label,
+ target,
+ identities,
+ schema_primary_keys,
+ vertex_info,
+ )
+ if _identity_value_present(target_id):
+ edge["inV"] = target_id
+ edge.setdefault("inVLabel", tgt_label)
+
+ return prepared
+
+
+def validate_graph_payload(
+ graph_data: Any,
+ live_schema: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """校验 graph_data (vertices/edges) 与 live schema 的兼容性。
+
+ 覆盖:label 存在性、properties 字段合法性、主键完整性、
+ 边端点可解析性、类型匹配、重复检测、索引建议。
+ """
+ errors: list[str] = []
+ warnings: list[str] = []
+
+ if not isinstance(graph_data, dict):
+ return {
+ "valid": False,
+ "errors": ["graph_data must be an object"],
+ "warnings": warnings,
+ }
+
+ vertices = graph_data.get("vertices")
+ edges = graph_data.get("edges")
+
+ if not isinstance(vertices, list):
+ errors.append("vertices must be a list")
+ if not isinstance(edges, list):
+ errors.append("edges must be a list")
+
+ schema_vlabels: set[str] = set()
+ schema_props: dict[str, set[str]] = {}
+ schema_primary_keys: dict[str, list[str]] = {}
+ schema_id_strategies: dict[str, str] = {}
+ schema_property_specs: dict[str, tuple[str, str]] = {}
+ schema_elabels: dict[str, dict[str, Any]] = {}
+ schema_eprops: dict[str, set[str]] = {}
+ indexed_labels = {"VERTEX": set(), "EDGE": set()}
+ raw = _schema_payload(live_schema) if live_schema is not None else None
+ schema_available = raw is not None
+ if schema_available:
+ # Reduce the live schema to a label -> properties/primary-keys/types table.
+ # Later validation uses this snapshot to avoid inconsistent repeated reads.
+ schema_property_specs = _property_specs(raw)
+ for vl in raw.get("vertexlabels", []):
+ if not isinstance(vl, dict):
+ continue
+ name = vl.get("name")
+ if name:
+ schema_vlabels.add(name)
+ schema_props[name] = _property_names(vl.get("properties", []))
+ schema_primary_keys[name] = _primary_key_names(vl)
+ schema_id_strategies[name] = str(
+ vl.get("id_strategy") or vl.get("idStrategy") or "PRIMARY_KEY"
+ ).upper()
+ for el in raw.get("edgelabels", []):
+ if not isinstance(el, dict):
+ continue
+ name = el.get("name")
+ if isinstance(name, str):
+ schema_elabels[name] = el
+ schema_eprops[name] = _property_names(el.get("properties", []))
+ indexed_labels = _indexed_labels(raw)
+
+ vertex_labels: set[str] = set()
+ vertex_identity_index: dict[tuple[str, str, Any], int] = {}
+ if isinstance(vertices, list):
+ for idx, vertex in enumerate(vertices):
+ if not isinstance(vertex, dict):
+ errors.append(f"vertex {idx} must be an object")
+ continue
+ label = vertex.get("label")
+ if label in (None, ""):
+ errors.append(f"vertex {idx} missing required field: label")
+ continue
+ vertex_labels.add(label)
+ if schema_available and label not in schema_vlabels:
+ errors.append(f"vertex {idx} label '{label}' does not exist in schema")
+
+ props = vertex.get("properties")
+ if isinstance(props, dict):
+ schema_prop_names = schema_props.get(label, set())
+ for prop_name, prop_value in props.items():
+ if prop_value is None or prop_value == "":
+ warnings.append(
+ f"vertex {idx} property '{prop_name}' has empty value"
+ )
+ if (
+ schema_available
+ and label in schema_props
+ and prop_name not in schema_prop_names
+ ):
+ errors.append(
+ f"vertex {idx} property '{prop_name}' does not exist on label '{label}'"
+ )
+ value_error = _property_value_error(
+ item_kind="vertex",
+ item_index=idx,
+ property_name=prop_name,
+ value=prop_value,
+ spec=schema_property_specs.get(prop_name),
+ )
+ if value_error:
+ errors.append(value_error)
+ primary_keys = schema_primary_keys.get(label, [])
+ id_strategy = schema_id_strategies.get(label)
+ explicit_id = vertex.get("id")
+ if id_strategy == "CUSTOMIZE_STRING":
+ if not _identity_value_present(explicit_id):
+ errors.append(
+ f"vertex {idx} missing required id for CUSTOMIZE_STRING label '{label}'"
+ )
+ elif not isinstance(explicit_id, str):
+ errors.append(
+ f"vertex {idx} id for CUSTOMIZE_STRING label '{label}' must be a string, "
+ f"got {type(explicit_id).__name__}"
+ )
+ elif id_strategy == "CUSTOMIZE_NUMBER":
+ if not _identity_value_present(explicit_id):
+ errors.append(
+ f"vertex {idx} missing required id for CUSTOMIZE_NUMBER label '{label}'"
+ )
+ elif not isinstance(explicit_id, int) or isinstance(explicit_id, bool):
+ errors.append(
+ f"vertex {idx} id for CUSTOMIZE_NUMBER label '{label}' must be an integer, "
+ f"got {type(explicit_id).__name__}"
+ )
+ if primary_keys:
+ # PRIMARY_KEY labels must provide complete primary keys; otherwise HugeGraph
+ # cannot construct a stable ID and later endpoint resolution may fail.
+ if not isinstance(props, dict):
+ props = {}
+ for pk in primary_keys:
+ if pk not in props or not _identity_value_present(props.get(pk)):
+ errors.append(
+ f"vertex {idx} missing primary key value for label '{label}': {pk}"
+ )
+ if all(
+ pk in props and _identity_value_present(props.get(pk))
+ for pk in primary_keys
+ ):
+ identity = (
+ label,
+ "pk",
+ tuple(props.get(pk) for pk in primary_keys),
+ )
+ if identity in vertex_identity_index:
+ errors.append(
+ f"vertex {idx} duplicate primary key identity for label '{label}': "
+ f"values={tuple(props.get(pk) for pk in primary_keys)} "
+ f"already used by vertex {vertex_identity_index[identity]}"
+ )
+ else:
+ vertex_identity_index[identity] = idx
+ if _identity_value_present(explicit_id):
+ # A payload must not contain duplicate IDs or primary-key identities, preventing
+ # endpoint resolution from targeting an ambiguous vertex.
+ identity = (label, "id", explicit_id)
+ if identity in vertex_identity_index:
+ errors.append(
+ f"vertex {idx} duplicate id '{explicit_id}' for label '{label}' "
+ f"already used by vertex {vertex_identity_index[identity]}"
+ )
+ else:
+ vertex_identity_index[identity] = idx
+
+ edge_labels: set[str] = set()
+ if isinstance(edges, list):
+ for idx, edge in enumerate(edges):
+ if not isinstance(edge, dict):
+ errors.append(f"edge {idx} must be an object")
+ continue
+ label = edge.get("label")
+ src_label, source = _edge_endpoint(edge, "source")
+ tgt_label, target = _edge_endpoint(edge, "target")
+ if _has_mixed_endpoint_forms(edge, "source"):
+ errors.append(
+ f"edge {idx} mixes source and outV endpoint forms; use either source/source_label or outV/outVLabel, not both"
+ )
+ if _has_mixed_endpoint_forms(edge, "target"):
+ errors.append(
+ f"edge {idx} mixes target and inV endpoint forms; use either target/target_label or inV/inVLabel, not both"
+ )
+ if label in (None, ""):
+ errors.append(f"edge {idx} missing required field: label")
+ if src_label in (None, ""):
+ errors.append(f"edge {idx} missing required field: source_label")
+ if tgt_label in (None, ""):
+ errors.append(f"edge {idx} missing required field: target_label")
+ if label:
+ edge_labels.add(label)
+ if schema_available and label not in schema_elabels:
+ errors.append(
+ f"edge {idx} label '{label}' does not exist in schema"
+ )
+ if schema_available:
+ if src_label and src_label not in schema_vlabels:
+ errors.append(
+ f"edge {idx} source_label '{src_label}' does not exist in schema"
+ )
+ if tgt_label and tgt_label not in schema_vlabels:
+ errors.append(
+ f"edge {idx} target_label '{tgt_label}' does not exist in schema"
+ )
+ if label and label in schema_elabels:
+ schema_edge = schema_elabels[label]
+ expected_src = _edge_schema_endpoint_label(schema_edge, "source")
+ expected_tgt = _edge_schema_endpoint_label(schema_edge, "target")
+ if src_label and expected_src and src_label != expected_src:
+ errors.append(
+ f"edge {idx} source_label '{src_label}' does not match edge label '{label}' source_label '{expected_src}'"
+ )
+ if tgt_label and expected_tgt and tgt_label != expected_tgt:
+ errors.append(
+ f"edge {idx} target_label '{tgt_label}' does not match edge label '{label}' target_label '{expected_tgt}'"
+ )
+ props = edge.get("properties")
+ if isinstance(props, dict):
+ schema_prop_names = schema_eprops.get(label, set())
+ for prop_name, prop_value in props.items():
+ if prop_value is None or prop_value == "":
+ warnings.append(
+ f"edge {idx} property '{prop_name}' has empty value"
+ )
+ if (
+ schema_available
+ and label in schema_eprops
+ and prop_name not in schema_prop_names
+ ):
+ errors.append(
+ f"edge {idx} property '{prop_name}' does not exist on label '{label}'"
+ )
+ value_error = _property_value_error(
+ item_kind="edge",
+ item_index=idx,
+ property_name=prop_name,
+ value=prop_value,
+ spec=schema_property_specs.get(prop_name),
+ )
+ if value_error:
+ errors.append(value_error)
+ if source is None and target is None:
+ continue
+ if source is None:
+ errors.append(f"edge {idx} has target but missing source")
+ if target is None:
+ errors.append(f"edge {idx} has source but missing target")
+ for endpoint_name, endpoint_label, endpoint_value in (
+ ("source", src_label, source),
+ ("target", tgt_label, target),
+ ):
+ if endpoint_value is None or not isinstance(endpoint_label, str):
+ continue
+ identities, missing_pk = _endpoint_identities(
+ endpoint_label,
+ endpoint_value,
+ schema_primary_keys,
+ )
+ if missing_pk:
+ # Report an error when an endpoint object lacks a primary key; do not fall back
+ # to string matching, which could silently write invalid dangling edges.
+ errors.append(
+ f"edge {idx} {endpoint_name} endpoint missing primary key for label '{endpoint_label}': {missing_pk}"
+ )
+ continue
+ if not identities:
+ # No missing_pk but no identities is a degraded state; report it explicitly
+ # instead of silently accepting it, such as when endpoint_value is {}.
+ errors.append(
+ f"edge {idx} {endpoint_name} endpoint has no resolvable identity "
+ f"for label '{endpoint_label}': {_format_endpoint_value(endpoint_value)}"
+ )
+ continue
+ matched_vertex_indices = {
+ vertex_identity_index[identity]
+ for identity in identities
+ if identity in vertex_identity_index
+ }
+ if len(matched_vertex_indices) > 1:
+ errors.append(
+ f"edge {idx} {endpoint_name} scalar endpoint is ambiguous for "
+ f"label '{endpoint_label}': {_format_endpoint_value(endpoint_value)} "
+ "matches different vertices by id and primary key"
+ )
+
+ if isinstance(edges, list):
+ edge_pairs = []
+ for e in edges:
+ if isinstance(e, dict):
+ edge_pairs.append(
+ (
+ e.get("label"),
+ e.get("source_label"),
+ e.get("target_label"),
+ e.get("source"),
+ e.get("target"),
+ )
+ )
+ if len(edge_pairs) > len({json.dumps(p, sort_keys=True) for p in edge_pairs}):
+ warnings.append("potential duplicate edges detected")
+
+ if indexed_labels["VERTEX"] or indexed_labels["EDGE"]:
+ for label in sorted(vertex_labels - indexed_labels["VERTEX"]):
+ warnings.append(f"no vertex index found in schema for label: {label}")
+ for label in sorted(edge_labels - indexed_labels["EDGE"]):
+ warnings.append(f"no edge index found in schema for label: {label}")
+ elif vertex_labels or edge_labels:
+ warnings.append("verify that appropriate indexes exist for queried properties")
+
+ return {
+ "valid": not bool(errors),
+ "errors": errors,
+ "warnings": warnings,
+ }
+
+
+def calculate_plan_hash(
+ graph_data: dict[str, Any],
+ live_schema: dict[str, Any] | None = None,
+) -> str:
+ """计算图数据导入的计划哈希(兼容旧接口)。"""
+ from hugegraph_mcp.plan_hash import compute_payload_digest
+
+ cfg = MCPConfig.from_env()
+ schema_summary = normalized_schema_summary(live_schema)
+ payload = {
+ "graph_data": _normalize_graph_data(graph_data, schema_summary),
+ "graph": cfg.graph,
+ "graphspace": cfg.graphspace,
+ }
+ if schema_summary is not None:
+ payload["schema_summary"] = schema_summary
+ return compute_payload_digest(payload)
+
+
+def _fetch_live_schema() -> dict[str, Any] | None:
+ return fetch_live_schema_or_none()
+
+
+def ingest_graph_data(
+ graph_data: dict[str, Any],
+ dry_run: bool = True,
+ confirm: bool = False,
+ plan_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+) -> dict[str, Any]:
+ """兼容入口:通过 HugeGraph-AI /graph-import 导入图数据。
+
+ Public MCP V1 `import_graph_data_tool(mode="ingest")` 不调用此函数;
+ 它使用 manage_graph_data() 的本地校验、dry-run/hash/confirm 和 direct Gremlin 写入。
+ """
+
+ return ingest_graph_data_via_ai(
+ graph_data=graph_data,
+ dry_run=dry_run,
+ confirm=confirm,
+ plan_hash=plan_hash,
+ nonce=nonce,
+ expires_at=expires_at,
+ )
+
+
+def ingest_graph_data_via_ai(
+ graph_data: dict[str, Any],
+ dry_run: bool = True,
+ confirm: bool = False,
+ plan_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+) -> dict[str, Any]:
+ """AI-backed 图数据导入 — legacy/internal 安全链入口。
+
+ dry_run=True: schema 校验 + plan_hash 生成,不写入
+ dry_run=False + confirm=True + plan_hash 匹配: 执行写入
+ nonce/expires_at: dry_run 返回的 plan_context 中的字段,confirm 时必须传回
+ """
+ if not dry_run and confirm:
+ replay_error = replayed_plan_error(nonce)
+ if replay_error is not None:
+ return replay_error
+
+ live_schema = _fetch_live_schema()
+ if live_schema is None:
+ return envelope_err(
+ ErrorType.CONNECTION_FAILED,
+ "Cannot read live schema from HugeGraph Server. Schema validation is required before import.",
+ suggestion="Ensure HugeGraph Server is running and accessible, then retry.",
+ retryable=True,
+ )
+ validation = validate_graph_payload(graph_data, live_schema=live_schema)
+ if not validation["valid"]:
+ return envelope_err(
+ ErrorType.SCHEMA_MISMATCH,
+ "Graph data does not match live schema.",
+ details={"errors": validation["errors"]},
+ )
+
+ from hugegraph_mcp.plan_hash import (
+ build_plan_context,
+ compute_payload_digest,
+ compute_plan_hash,
+ )
+
+ mutation_summary = _mutation_summary(graph_data)
+ warnings = validation["warnings"]
+
+ # Build the target-bound plan context, including url, user, readonly, nonce, and expires_at.
+ cfg = MCPConfig.from_env()
+ schema_summary = normalized_schema_summary(live_schema)
+ payload_for_digest = {
+ "graph_data": _normalize_graph_data(graph_data, schema_summary),
+ "graph": cfg.graph,
+ "graphspace": cfg.graphspace,
+ }
+ if schema_summary is not None:
+ payload_for_digest["schema_summary"] = schema_summary
+
+ payload_digest = compute_payload_digest(payload_for_digest)
+ schema_hash = compute_payload_digest(schema_summary) if schema_summary else None
+ plan_context, _ = build_plan_context(
+ tool_name="ingest_graph_data",
+ mode="import",
+ payload_digest=payload_digest,
+ schema_hash=schema_hash,
+ nonce=nonce,
+ )
+
+ if dry_run:
+ plan_hash_value = compute_plan_hash(plan_context)
+ payload = {
+ "plan_hash": plan_hash_value,
+ "plan_context": {
+ "nonce": plan_context.nonce,
+ "expires_at": plan_context.expires_at,
+ "graph_url": plan_context.graph_url,
+ "graph_name": plan_context.graph_name,
+ "graphspace": plan_context.graphspace,
+ "principal": plan_context.principal,
+ "readonly": plan_context.readonly,
+ },
+ "mutation_summary": mutation_summary,
+ "warnings": warnings,
+ "confirmable": True,
+ }
+ next_actions: list[str] = []
+ if MCPConfig.from_env().is_readonly():
+ payload, readonly_warnings, next_actions = mark_readonly_preview(
+ payload,
+ warning=(
+ "This dry-run was generated while HUGEGRAPH_MCP_READONLY=true. "
+ "Set HUGEGRAPH_MCP_READONLY=false and rerun dry_run before confirming."
+ ),
+ next_action=(
+ "Set HUGEGRAPH_MCP_READONLY=false and rerun dry_run before confirm."
+ ),
+ )
+ warnings = list(warnings) + readonly_warnings
+ else:
+ issue_error = issue_plan(plan_context, plan_hash_value)
+ if issue_error is not None:
+ return issue_error
+ return envelope_ok(payload, warnings=warnings, next_actions=next_actions)
+
+ violation = guard(Capability.DATA_WRITE)
+ if violation is not None:
+ return violation
+
+ if not confirm:
+ return envelope_err(
+ ErrorType.CONFIRM_REQUIRED,
+ "Graph data import requires confirm=True after a dry_run.",
+ suggestion="Run dry_run=True, review mutation_summary and warnings, then pass confirm=True with the returned plan_hash.",
+ )
+
+ # Validate against the target by rereading config and schema and recomputing the hash.
+ # nonce must be returned from the plan_context produced by dry_run.
+ valid, error_type, details = verify_and_consume_plan(
+ submitted_hash=plan_hash,
+ tool_name="ingest_graph_data",
+ mode="import",
+ payload_digest=payload_digest,
+ schema_hash=schema_hash,
+ nonce=nonce or plan_context.nonce,
+ expires_at=expires_at,
+ )
+ if not valid:
+ return plan_hash_error(
+ error_type=error_type,
+ details=details,
+ mismatch_message=(
+ "Plan hash mismatch: config, schema, or payload has changed since dry_run."
+ ),
+ expired_message=(
+ "Plan has expired. Run dry_run=True again and use the returned plan_hash."
+ ),
+ suggestion="Run dry_run=True again and use the returned plan_hash.",
+ )
+
+ batch_id = f"batch-{uuid4().hex[:12]}"
+ request_id = f"req-{uuid4().hex[:12]}"
+ cfg = MCPConfig.from_env()
+ planned = mutation_summary
+
+ import_data = _prepare_graph_import_data(graph_data, live_schema)
+ # Actual writes still use HugeGraph-AI's graph-import HTTP endpoint. MCP handles
+ # schema validation, safety confirmation, and payload normalization rather than
+ # invoking the hugegraph-llm import flow directly.
+ try:
+ ai_result = post(
+ "/graph-import",
+ json={"data": json.dumps(import_data, sort_keys=True), "schema": cfg.graph},
+ )
+ except Exception as exc: # noqa: BLE001 - normalize import boundary failures
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ f"Import execution failed: {exc}",
+ details=_import_error_result(
+ planned=planned, batch_id=batch_id, request_id=request_id, cfg=cfg
+ ),
+ )
+
+ if not ai_result.get("ok"):
+ # M5: Normalize AI error responses instead of passing through raw results.
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ "HugeGraph-AI import returned an error.",
+ details=_normalize_import_result(
+ ai_result=None,
+ planned=planned,
+ batch_id=batch_id,
+ request_id=request_id,
+ cfg=cfg,
+ ),
+ )
+
+ import_result = _unwrap_ai_payload(ai_result.get("data"))
+ if isinstance(import_result, dict) and import_result.get("ok") is False:
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ "HugeGraph-AI import returned an error in payload.",
+ details=_normalize_import_result(
+ ai_result=None,
+ planned=planned,
+ batch_id=batch_id,
+ request_id=request_id,
+ cfg=cfg,
+ ),
+ )
+
+ # M5: Normalize the import result.
+ normalized = _normalize_import_result(
+ ai_result=import_result,
+ planned=planned,
+ batch_id=batch_id,
+ request_id=request_id,
+ cfg=cfg,
+ )
+
+ if normalized.get("status") != "success":
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ "Graph data import did not complete successfully.",
+ retryable=bool(normalized.get("retryable")),
+ details=normalized,
+ warnings=normalized.get("warnings", []),
+ )
+
+ return envelope_ok(normalized, warnings=normalized.get("warnings", []))
+
+
+def _mutation_summary(graph_data: dict[str, Any]) -> dict[str, int]:
+ return {
+ "vertices": len(graph_data.get("vertices") or []),
+ "edges": len(graph_data.get("edges") or []),
+ }
+
+
+def _unwrap_ai_payload(data: Any) -> Any:
+ if isinstance(data, dict) and "ok" in data and "data" in data:
+ if data.get("ok") is False:
+ return data
+ return data.get("data")
+ return data
+
+
+def _normalize_import_result(
+ ai_result: Any,
+ planned: dict[str, int],
+ batch_id: str,
+ request_id: str,
+ cfg: MCPConfig,
+) -> dict[str, Any]:
+ """将 AI 导入结果规范化为 V1 标准格式。
+
+ M5: success / partial / degraded / error
+ """
+ target = {
+ "graph_url": cfg.url,
+ "graph_name": cfg.graph,
+ "graphspace": cfg.graphspace or "DEFAULT",
+ }
+
+ if ai_result is None or (
+ isinstance(ai_result, dict) and ai_result.get("ok") is False
+ ):
+ return {
+ "status": "error",
+ "planned": planned,
+ "written": {"vertices": 0, "edges": 0},
+ "failed_items": [],
+ "warnings": [],
+ "retryable": False,
+ "compensation_suggestions": ["Retry the import with dry_run first."],
+ "target": target,
+ "batch_id": batch_id,
+ "request_id": request_id,
+ }
+
+ written, count_source = _extract_written_counts(ai_result, planned)
+ failed_items = _extract_failed_items(ai_result)
+ warnings = _extract_import_warnings(ai_result)
+ remote_success = ai_result.get("success") if isinstance(ai_result, dict) else None
+ remote_status = (
+ str(ai_result.get("status")).lower()
+ if isinstance(ai_result, dict) and ai_result.get("status") is not None
+ else None
+ )
+
+ if written is None:
+ if failed_items:
+ written = {"vertices": 0, "edges": 0}
+ status = "error" if remote_success is False else "degraded"
+ warnings.append(
+ "HugeGraph-AI import returned failures without explicit written counts."
+ )
+ elif remote_success is False:
+ written = {"vertices": 0, "edges": 0}
+ status = "error"
+ warnings.append(
+ "HugeGraph-AI import reported failure without explicit written counts."
+ )
+ else:
+ written = {"vertices": 0, "edges": 0}
+ status = (
+ remote_status
+ if remote_status in {"partial", "error", "degraded"}
+ else "degraded"
+ )
+ warnings.append(
+ "HugeGraph-AI import did not return explicit written counts; write outcome is unknown."
+ )
+ elif remote_success is False and (written["vertices"] > 0 or written["edges"] > 0):
+ status = "partial"
+ elif remote_success is False:
+ status = "error"
+ elif remote_status in {"partial", "error", "degraded"}:
+ status = remote_status
+ elif written == planned and not failed_items:
+ status = "success"
+ elif written["vertices"] > 0 or written["edges"] > 0:
+ status = "partial"
+ elif failed_items:
+ status = "error"
+ else:
+ status = "degraded"
+
+ if count_source == "total":
+ warnings.append(
+ "HugeGraph-AI import returned only a total written count; vertices/edges were estimated from the planned import order."
+ )
+
+ return {
+ "status": status,
+ "planned": planned,
+ "written": written,
+ "failed_items": failed_items,
+ "warnings": warnings,
+ "retryable": False,
+ "compensation_suggestions": (
+ ["Review failed_items, inspect graph state, and run a fresh dry-run."]
+ if status in {"partial", "degraded", "error"}
+ else []
+ ),
+ "target": target,
+ "batch_id": batch_id,
+ "request_id": request_id,
+ }
+
+
+def _extract_written_counts(
+ ai_result: Any, planned: dict[str, int]
+) -> tuple[dict[str, int] | None, str | None]:
+ """从 AI 结果中提取写入计数。
+
+ 返回 (counts, source),无法识别时 counts 为 None。source="total" 表示
+ 只有总数,vertices/edges 是按导入顺序估算出来的。
+ """
+ if not isinstance(ai_result, dict):
+ return None, None
+
+ # Common AI response formats.
+ for key in ("written", "imported", "created", "result"):
+ data = ai_result.get(key)
+ if isinstance(data, dict):
+ verts = data.get("vertices")
+ if verts is None:
+ verts = data.get("vertex_count")
+ edges = data.get("edges")
+ if edges is None:
+ edges = data.get("edge_count")
+ if verts is not None or edges is not None:
+ return {
+ "vertices": _safe_int(verts),
+ "edges": _safe_int(edges),
+ }, "explicit"
+
+ # Counts provided directly at the top level.
+ verts = ai_result.get("vertices_written")
+ if verts is None:
+ verts = ai_result.get("vertex_count")
+ edges = ai_result.get("edges_written")
+ if edges is None:
+ edges = ai_result.get("edge_count")
+ if verts is not None or edges is not None:
+ return {
+ "vertices": _safe_int(verts),
+ "edges": _safe_int(edges),
+ }, "explicit"
+
+ for key in ("inserted", "total_inserted", "created_count", "imported_count"):
+ if key in ai_result:
+ return _split_total_written(_safe_int(ai_result.get(key)), planned), "total"
+
+ return None, None
+
+
+def _safe_int(value: Any) -> int:
+ if value in (None, ""):
+ return 0
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _split_total_written(total: int, planned: dict[str, int]) -> dict[str, int]:
+ total = max(0, total)
+ planned_vertices = max(0, int(planned.get("vertices", 0)))
+ planned_edges = max(0, int(planned.get("edges", 0)))
+ vertices = min(planned_vertices, total)
+ edges = min(planned_edges, max(0, total - vertices))
+ return {"vertices": vertices, "edges": edges}
+
+
+def _extract_failed_items(ai_result: Any) -> list[dict[str, Any]]:
+ """从 AI 结果中提取失败项,统一为对象数组。"""
+ if not isinstance(ai_result, dict):
+ return []
+
+ for key in ("failed_items", "errors", "failures"):
+ items = ai_result.get(key)
+ if isinstance(items, list):
+ normalized = []
+ for item in items[:100]:
+ if isinstance(item, dict):
+ normalized.append(item)
+ elif isinstance(item, str):
+ normalized.append({"message": item})
+ else:
+ normalized.append({"item": str(item)})
+ return normalized
+
+ return []
+
+
+def _extract_import_warnings(ai_result: Any) -> list[str]:
+ if not isinstance(ai_result, dict):
+ return []
+ raw_warnings = ai_result.get("warnings")
+ if not isinstance(raw_warnings, list):
+ return []
+ return [str(warning) for warning in raw_warnings[:100]]
+
+
+def _import_error_result(
+ planned: dict[str, int],
+ batch_id: str,
+ request_id: str,
+ cfg: MCPConfig,
+) -> dict[str, Any]:
+ """构建导入执行错误的规范化结果。"""
+ return {
+ "status": "error",
+ "planned": planned,
+ "written": {"vertices": 0, "edges": 0},
+ "failed_items": [],
+ "warnings": ["Import execution failed before any writes."],
+ "retryable": False,
+ "compensation_suggestions": ["Check HugeGraph-AI service availability."],
+ "target": {
+ "graph_url": cfg.url,
+ "graph_name": cfg.graph,
+ "graphspace": cfg.graphspace or "DEFAULT",
+ },
+ "batch_id": batch_id,
+ "request_id": request_id,
+ }
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/inspect_graph.py b/hugegraph-mcp/hugegraph_mcp/tools/inspect_graph.py
new file mode 100644
index 00000000..25294f3d
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/inspect_graph.py
@@ -0,0 +1,199 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""图状态检视 — Agent 连接后的首个推荐工具。
+
+inspect_graph() 做尽力而为的状态检查:HugeGraph Server 连接、schema 摘要、
+点边计数、HugeGraph-AI 可用性。任何环节失败都不抛异常,
+而是作为 warning 包含在 ok 信封中返回。
+"""
+
+import time
+from typing import Any
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import envelope_ok
+from hugegraph_mcp.gremlin_tools import execute_gremlin_read
+from hugegraph_mcp.hugegraph_ai_client import health_check
+from hugegraph_mcp.schema_tools import get_live_schema
+
+
+def _extract_count(result: dict[str, Any]) -> int | None:
+ if result.get("ok") is False or result.get("success") is False:
+ return None
+
+ return _extract_count_value(result.get("data"))
+
+
+def _extract_count_value(data: Any) -> int | None:
+ if isinstance(data, dict) and "data" in data:
+ return _extract_count_value(data.get("data"))
+ if isinstance(data, list):
+ if not data:
+ return 0
+ first = data[0]
+ return first if isinstance(first, int) else None
+ if isinstance(data, int):
+ return data
+ return None
+
+
+def _count_indexes(raw_schema: dict[str, Any] | None) -> int | None:
+ if raw_schema is None:
+ return None
+ index_labels = raw_schema.get("indexlabels")
+ if isinstance(index_labels, list):
+ return len(index_labels)
+ return 0
+
+
+def _has_graph_index_info(graph_index_info: Any) -> bool:
+ if graph_index_info is None:
+ return False
+ if isinstance(graph_index_info, dict):
+ if graph_index_info.get("health_endpoint") == "/openapi.json":
+ return False
+ explicit_values = (
+ graph_index_info.get("vid_embedding"),
+ graph_index_info.get("vid_embedding_status"),
+ graph_index_info.get("vid_index"),
+ graph_index_info.get("vid_index_status"),
+ graph_index_info.get("embedding_index"),
+ graph_index_info.get("embedding_index_status"),
+ graph_index_info.get("index_status"),
+ )
+ return any(_is_ready_index_value(value) for value in explicit_values)
+ return False
+
+
+def _is_ready_index_value(value: Any) -> bool:
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, dict):
+ if value.get("available") is True or value.get("ready") is True:
+ return True
+ status = value.get("status") or value.get("state")
+ return _is_ready_index_value(status)
+ if isinstance(value, str):
+ return value.strip().lower() in {"available", "ready", "loaded", "enabled"}
+ return False
+
+
+def _warning_from_exception(prefix: str, exc: Exception) -> str:
+ message = str(exc).strip()
+ return f"{prefix}: {message}" if message else prefix
+
+
+def _check_ai_status(cfg: MCPConfig) -> tuple[str, Any, list[str]]:
+ """探测 HugeGraph-AI 是否可用 — 复用统一客户端的认证、超时和回退逻辑。"""
+
+ result = health_check(cfg=cfg)
+ warnings = list(result.get("warnings") or [])
+ if result.get("ok"):
+ return "available", result.get("data"), warnings
+
+ error = result.get("error") or {}
+ message = error.get("message", "HugeGraph-AI is unavailable")
+ return "unavailable", None, [message, *warnings]
+
+
+def inspect_graph(include_raw_schema: bool = False) -> dict[str, Any]:
+ """检视 HugeGraph 服务器状态、schema 摘要、点边计数和 AI 状态。
+
+ 这是 Agent 连接后的推荐第一个工具。全部失败信息作为 warnings 包含在 ok 信封中,
+ 不会因为某个组件不可用而阻断整体返回。
+ """
+
+ start = time.time()
+ cfg = MCPConfig.from_env()
+ warnings: list[str] = []
+
+ server_status = "available"
+ schema_summary: dict[str, Any] | None = None
+ raw_schema: dict[str, Any] | None = None
+ simple_schema: dict[str, Any] | None = None
+ readonly: bool | None = None
+ vertex_count: int | None = None
+ edge_count: int | None = None
+
+ try:
+ schema_result = get_live_schema()
+ simple_schema = schema_result.get("simple_schema")
+ schema_summary = simple_schema
+ raw_schema = schema_result.get("schema")
+ readonly = schema_result.get("readonly")
+ except Exception as exc: # noqa: BLE001 - inspect is best effort
+ server_status = "unavailable"
+ warnings.append(_warning_from_exception("HugeGraph Server is unavailable", exc))
+
+ if server_status == "available":
+ vertex_count = _run_count_query("g.V().count()", "vertex", warnings)
+ edge_count = _run_count_query("g.E().count()", "edge", warnings)
+
+ ai_status, graph_index_info, ai_warnings = _check_ai_status(cfg)
+ warnings.extend(ai_warnings)
+
+ data: dict[str, Any] = {
+ "graph": cfg.graph,
+ "graphspace": cfg.graphspace,
+ "hugegraph_server_status": server_status,
+ "hugegraph_ai_status": ai_status,
+ "vid_embedding_status": "available"
+ if _has_graph_index_info(graph_index_info)
+ else "unknown",
+ "schema_summary": schema_summary,
+ "vertex_count": vertex_count,
+ "edge_count": edge_count,
+ "index_status": {"total": _count_indexes(raw_schema)},
+ "readonly": readonly if readonly is not None else cfg.is_readonly(),
+ }
+ if include_raw_schema:
+ data["raw_schema"] = raw_schema
+ data["simple_schema"] = simple_schema
+
+ duration_ms = (time.time() - start) * 1000.0
+ return envelope_ok(
+ data,
+ duration_ms=duration_ms,
+ warnings=warnings,
+ next_actions=_next_actions(data),
+ readonly=data["readonly"],
+ )
+
+
+def _run_count_query(query: str, label: str, warnings: list[str]) -> int | None:
+ try:
+ result = execute_gremlin_read(query)
+ count = _extract_count(result)
+ if count is None:
+ warnings.append(f"Failed to fetch {label} count")
+ return count
+ except Exception as exc: # noqa: BLE001 - inspect is best effort
+ warnings.append(_warning_from_exception(f"Failed to fetch {label} count", exc))
+ return None
+
+
+def _next_actions(data: dict[str, Any]) -> list[str]:
+ """根据当前状态给出下一步建议,引导 Agent 使用正确的后续工具。"""
+ actions = [
+ "Use inspect_graph_tool with include_raw_schema=true for full schema details"
+ ]
+ if data.get("hugegraph_server_status") == "available":
+ actions.append("Use execute_gremlin_read_tool for read-only graph exploration")
+ else:
+ actions.append("Check HugeGraph Server URL, graph name, and credentials")
+ if data.get("hugegraph_ai_status") != "available":
+ actions.append(
+ "Check HugeGraph-AI URL if embedding or graph index features are needed"
+ )
+ return actions
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/inspect_schema.py b/hugegraph-mcp/hugegraph_mcp/tools/inspect_schema.py
new file mode 100644
index 00000000..d1966e44
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/inspect_schema.py
@@ -0,0 +1,291 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Schema inspection tool for v2_core."""
+
+from typing import Any
+
+from pyhugegraph.client import PyHugeClient
+
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+from hugegraph_mcp.hugegraph_client import build_hugegraph_client
+from hugegraph_mcp.tools.schema_utils import (
+ edge_schema_endpoint_label,
+ primary_key_names,
+ property_names,
+ schema_name,
+ schema_payload,
+)
+
+FILTER_KINDS = frozenset({"property_key", "vertex_label", "edge_label", "index_label"})
+
+
+def _schema_manager():
+ return build_hugegraph_client(
+ MCPConfig.from_env(), client_cls=PyHugeClient
+ ).schema()
+
+
+def inspect_schema(
+ *,
+ include_raw_schema: bool = False,
+ include_relations: bool = True,
+ include_index_labels: bool = True,
+ filter_kind: str | None = None,
+ filter_name: str | None = None,
+) -> dict[str, Any]:
+ """Inspect HugeGraph schema objects and relations.
+
+ Capability: READ.
+
+ filter_kind values: property_key, vertex_label, edge_label, index_label.
+ filter_name may be used only with filter_kind and must name one schema object.
+ include_raw_schema controls whether the raw server schema is returned.
+ """
+
+ filter_kind = _normalize_optional_str(filter_kind)
+ filter_name = _normalize_optional_str(filter_name)
+
+ validation_error = _validate_filter(filter_kind, filter_name)
+ if validation_error is not None:
+ return validation_error
+
+ try:
+ manager = _schema_manager()
+ raw_schema = manager.getSchema()
+ if raw_schema is None:
+ return envelope_err(
+ ErrorType.CONNECTION_FAILED,
+ "HugeGraph Server returned an empty schema response.",
+ retryable=True,
+ source="inspect_schema_tool",
+ next_actions=[
+ "Check HugeGraph Server health and retry inspect_schema_tool.",
+ ],
+ )
+ relations = _safe_get_relations(manager) if include_relations else []
+ except Exception as exc: # noqa: BLE001 - return structured dependency error
+ return _schema_dependency_error(exc)
+
+ raw_payload = schema_payload(raw_schema) or raw_schema
+ summary = _build_summary(raw_payload, include_index_labels=include_index_labels)
+ all_summary = (
+ summary
+ if include_index_labels
+ else _build_summary(raw_payload, include_index_labels=True)
+ )
+ filtered = _filter_schema(raw_payload, filter_kind, filter_name, all_summary)
+ if filtered is None:
+ return envelope_err(
+ ErrorType.NOT_FOUND,
+ f"{filter_kind} not found: {filter_name}",
+ source="inspect_schema_tool",
+ details={"filter_kind": filter_kind, "filter_name": filter_name},
+ next_actions=[
+ "Call inspect_schema_tool without filter_name to list available schema objects.",
+ ],
+ )
+
+ data: dict[str, Any] = {
+ "summary": summary,
+ "relations": relations,
+ "index_labels": summary["index_labels"] if include_index_labels else [],
+ "filtered": filtered,
+ }
+ if include_raw_schema:
+ data["raw_schema"] = raw_payload
+
+ return envelope_ok(
+ data,
+ next_actions=[
+ "Use query_graph_data_tool to inspect data that uses this schema.",
+ "Use apply_schema_tool(mode='dry_run') before creating new schema objects.",
+ ],
+ )
+
+
+def _normalize_optional_str(value: str | None) -> str | None:
+ if value is None:
+ return None
+ stripped = str(value).strip()
+ return stripped or None
+
+
+def _validate_filter(
+ filter_kind: str | None,
+ filter_name: str | None,
+) -> dict[str, Any] | None:
+ if filter_kind is None and filter_name is not None:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "filter_name requires filter_kind.",
+ suggestion="Pass filter_kind together with filter_name.",
+ source="inspect_schema_tool",
+ details={"filter_name": filter_name},
+ )
+
+ if filter_kind is not None and filter_kind not in FILTER_KINDS:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ f"Unsupported filter_kind: {filter_kind!r}.",
+ suggestion=(
+ "Use one of: property_key, vertex_label, edge_label, index_label."
+ ),
+ source="inspect_schema_tool",
+ details={"filter_kind": filter_kind},
+ )
+ return None
+
+
+def _safe_get_relations(manager) -> list[str]:
+ try:
+ relations = manager.getRelations()
+ except Exception: # noqa: BLE001 - relations are optional
+ return []
+ return [str(item) for item in relations or []]
+
+
+def _schema_dependency_error(exc: Exception) -> dict[str, Any]:
+ return envelope_err(
+ ErrorType.CONNECTION_FAILED,
+ f"Cannot inspect HugeGraph schema: {exc!s}",
+ suggestion="Verify HugeGraph Server URL, graph, graphspace, and credentials.",
+ retryable=True,
+ source="inspect_schema_tool",
+ details={"error": str(exc)},
+ next_actions=["Retry inspect_graph_tool to confirm server connectivity."],
+ )
+
+
+def _build_summary(
+ raw_schema: dict[str, Any],
+ *,
+ include_index_labels: bool,
+) -> dict[str, Any]:
+ property_keys = [
+ _normalize_schema_item(item) for item in _items(raw_schema, "propertykeys")
+ ]
+ vertex_labels = [
+ _normalize_vertex_label(item) for item in _items(raw_schema, "vertexlabels")
+ ]
+ edge_labels = [
+ _normalize_edge_label(item) for item in _items(raw_schema, "edgelabels")
+ ]
+ index_labels = (
+ [_normalize_schema_item(item) for item in _items(raw_schema, "indexlabels")]
+ if include_index_labels
+ else []
+ )
+ return {
+ "property_key_count": len(property_keys),
+ "vertex_label_count": len(vertex_labels),
+ "edge_label_count": len(edge_labels),
+ "index_label_count": len(_items(raw_schema, "indexlabels")),
+ "property_keys": property_keys,
+ "vertex_labels": vertex_labels,
+ "edge_labels": edge_labels,
+ "index_labels": index_labels,
+ }
+
+
+def _items(raw_schema: dict[str, Any], key: str) -> list[Any]:
+ values = raw_schema.get(key)
+ return values if isinstance(values, list) else []
+
+
+def _filter_schema(
+ raw_schema: dict[str, Any],
+ filter_kind: str | None,
+ filter_name: str | None,
+ summary: dict[str, Any],
+) -> dict[str, Any] | list[Any]:
+ if filter_kind is None:
+ return {
+ "property_keys": summary["property_keys"],
+ "vertex_labels": summary["vertex_labels"],
+ "edge_labels": summary["edge_labels"],
+ "index_labels": summary["index_labels"],
+ }
+
+ key = {
+ "property_key": "propertykeys",
+ "vertex_label": "vertexlabels",
+ "edge_label": "edgelabels",
+ "index_label": "indexlabels",
+ }[filter_kind]
+ normalized = [
+ _normalize_kind_item(filter_kind, item) for item in _items(raw_schema, key)
+ ]
+ if filter_name is None:
+ return normalized
+ for item in normalized:
+ if item.get("name") == filter_name:
+ return item
+ return None
+
+
+def _normalize_kind_item(filter_kind: str, item: Any) -> dict[str, Any]:
+ if filter_kind == "vertex_label":
+ return _normalize_vertex_label(item)
+ if filter_kind == "edge_label":
+ return _normalize_edge_label(item)
+ return _normalize_schema_item(item)
+
+
+def _normalize_vertex_label(item: Any) -> dict[str, Any]:
+ normalized = _normalize_schema_item(item)
+ if isinstance(item, dict):
+ normalized["properties"] = sorted(property_names(item.get("properties")))
+ normalized["primary_keys"] = primary_key_names(item)
+ nullable_keys = item.get("nullable_keys") or item.get("nullableKeys")
+ normalized["nullable_keys"] = _names(nullable_keys)
+ return normalized
+
+
+def _normalize_edge_label(item: Any) -> dict[str, Any]:
+ normalized = _normalize_schema_item(item)
+ if isinstance(item, dict):
+ normalized["source_label"] = edge_schema_endpoint_label(item, "source")
+ normalized["target_label"] = edge_schema_endpoint_label(item, "target")
+ normalized["properties"] = sorted(property_names(item.get("properties")))
+ nullable_keys = item.get("nullable_keys") or item.get("nullableKeys")
+ normalized["nullable_keys"] = _names(nullable_keys)
+ return normalized
+
+
+def _normalize_schema_item(item: Any) -> dict[str, Any]:
+ if isinstance(item, dict):
+ return dict(item)
+ result: dict[str, Any] = {}
+ for name in (
+ "name",
+ "dataType",
+ "cardinality",
+ "id",
+ "baseType",
+ "baseValue",
+ "indexType",
+ "fields",
+ ):
+ if hasattr(item, name):
+ result[name] = getattr(item, name)
+ if not result:
+ result["value"] = str(item)
+ return result
+
+
+def _names(values: Any) -> list[str]:
+ if not isinstance(values, list):
+ return []
+ return sorted(name for value in values if (name := schema_name(value)))
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/live_schema.py b/hugegraph-mcp/hugegraph_mcp/tools/live_schema.py
new file mode 100644
index 00000000..bbae564d
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/live_schema.py
@@ -0,0 +1,39 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Live schema fetch helpers shared by V1 tools."""
+
+import logging
+from typing import Any
+
+from hugegraph_mcp import schema_tools
+
+LOGGER = logging.getLogger("hugegraph_mcp.live_schema")
+
+
+def current_live_schema(live_schema: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Return the provided schema or fetch the current HugeGraph schema."""
+
+ if live_schema is not None:
+ return live_schema
+ return schema_tools.get_live_schema()
+
+
+def fetch_live_schema_or_none() -> dict[str, Any] | None:
+ """Best-effort live schema fetch for write paths that return envelopes."""
+
+ try:
+ return current_live_schema()
+ except Exception as exc:
+ LOGGER.warning("Failed to fetch live schema: %s", exc, exc_info=True)
+ return None
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/manage_graph_data.py b/hugegraph-mcp/hugegraph_mcp/tools/manage_graph_data.py
new file mode 100644
index 00000000..2f48212a
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/manage_graph_data.py
@@ -0,0 +1,411 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""Graph data management orchestration layer.
+
+manage_graph_data() keeps the V1 import/delete safety-chain entry point while
+validation, Gremlin generation, and execution helpers live in focused modules.
+"""
+
+from typing import Any
+
+from hugegraph_mcp import gremlin_tools, schema_tools
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.confirmable_workflow import (
+ confirm_required_error,
+ issue_plan,
+ mark_readonly_preview,
+ plan_hash_error,
+ replayed_plan_error,
+ verify_and_consume_plan,
+)
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+from hugegraph_mcp.guard import Capability, guard
+from hugegraph_mcp.plan_hash import (
+ build_plan_context,
+ compute_payload_digest,
+ compute_plan_hash,
+)
+from hugegraph_mcp.tools import ingest_graph_data
+from hugegraph_mcp.tools.graph_data_execute import (
+ _fetch_live_schema,
+ _mutation_summary,
+ calculate_graph_change_plan_hash,
+ dry_run_graph_change_plan,
+ execute_graph_change_plan,
+)
+from hugegraph_mcp.tools.graph_data_mapping import (
+ GraphChangePlan,
+ _change_plan_from_operations,
+ graph_data_to_change_plan,
+)
+from hugegraph_mcp.tools.graph_data_validate import (
+ _operations,
+ _schema_summary,
+ _validate_mode_operations,
+ validate_graph_change_plan,
+)
+
+# Only export public entry points; import private helpers from graph_data_* modules.
+__all__ = [
+ "GraphChangePlan",
+ "calculate_graph_change_plan_hash",
+ "dry_run_graph_change_plan",
+ "execute_graph_change_plan",
+ "graph_data_to_change_plan",
+ "gremlin_tools",
+ "manage_graph_data",
+ "schema_tools",
+ "validate_graph_change_plan",
+]
+
+
+# ---- Unified entry point ----
+
+
+def manage_graph_data(
+ mode: str,
+ graph_data: dict[str, Any] | None = None,
+ change_plan: dict[str, Any] | list[dict[str, Any]] | None = None,
+ dry_run: bool = True,
+ confirm: bool = False,
+ plan_hash: str | None = None,
+ nonce: str | None = None,
+ expires_at: float | None = None,
+ extra_hash_context: dict[str, Any] | None = None,
+ plan_tool_name: str = "manage_graph_data",
+) -> dict[str, Any]:
+ """统一图数据管理入口。
+
+ 安全链:validate → dry_run → confirm check → plan_hash match → execute
+ 每个环节失败均返回结构化错误,不抛异常。
+ """
+ if mode == "import":
+ if graph_data is None:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "graph_data is required for mode='import'",
+ )
+ if not isinstance(graph_data, dict):
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ "graph_data must be an object for mode='import'.",
+ details={"received_type": type(graph_data).__name__},
+ )
+ elif mode == "delete":
+ if change_plan is None:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ f"change_plan is required for mode='{mode}'",
+ )
+ plan = (
+ change_plan
+ if isinstance(change_plan, dict)
+ else _change_plan_from_operations(change_plan)
+ )
+ else:
+ return envelope_err(
+ ErrorType.VALIDATION_ERROR,
+ f"Unknown mode: {mode!r}. Use 'import' or 'delete'.",
+ details={"mode": mode},
+ )
+
+ if not dry_run and confirm:
+ replay_error = replayed_plan_error(nonce)
+ if replay_error is not None:
+ return replay_error
+
+ # Read the live schema before writing. Do not execute without it because
+ # primary keys, endpoints, and property validity depend on the real schema.
+ live_schema = _fetch_live_schema()
+ if live_schema is None:
+ return envelope_err(
+ ErrorType.CONNECTION_FAILED,
+ "Cannot read live schema from HugeGraph Server. Schema validation is required before graph data changes.",
+ suggestion="Ensure HugeGraph Server is running and accessible, then retry.",
+ retryable=True,
+ )
+
+ if mode == "import" and graph_data is not None:
+ # import additionally validates the original graph_data for rules that
+ # are difficult to express in change_plan: complete vertex keys,
+ # resolvable edge endpoints, and duplicate identities in the payload.
+ payload_validation = ingest_graph_data.validate_graph_payload(
+ graph_data,
+ live_schema=live_schema,
+ )
+ if not payload_validation["valid"]:
+ return envelope_err(
+ ErrorType.SCHEMA_MISMATCH,
+ "Graph data does not match live schema.",
+ details={"errors": payload_validation["errors"]},
+ )
+ # public import scalar source/target values require the live schema to
+ # distinguish a single primary-key value from an explicit ID; outV/inV
+ # always retain ID semantics.
+ plan = graph_data_to_change_plan(graph_data, live_schema=live_schema)
+
+ # The mode/op relationship is the first boundary: import permits only create,
+ # while delete permits only deletion operations, preventing high-risk actions
+ # from being routed through a lower-risk entry point.
+ mode_validation = _validate_mode_operations(mode, plan)
+ if not mode_validation["valid"]:
+ return envelope_err(
+ ErrorType.INVALID_GRAPH_DATA,
+ "Graph change plan contains operations outside the selected mode.",
+ details={"errors": mode_validation["errors"]},
+ )
+
+ dry_run_result = dry_run_graph_change_plan(
+ plan, live_schema, extra_hash_context=extra_hash_context
+ )
+ if not dry_run_result["valid"]:
+ errors = dry_run_result["errors"]
+ error_type = next(
+ (
+ error["error_type"]
+ for error in errors
+ if isinstance(error, dict) and error.get("error_type")
+ ),
+ ErrorType.INVALID_GRAPH_DATA,
+ )
+ return envelope_err(
+ error_type,
+ "Graph change plan is invalid.",
+ details={"errors": errors},
+ warnings=dry_run_result.get("warnings", []),
+ )
+
+ plan_context, _ = _build_manage_graph_data_plan_context(
+ tool_name=plan_tool_name,
+ mode=mode,
+ plan=plan,
+ live_schema=live_schema,
+ nonce=nonce,
+ extra_hash_context=extra_hash_context,
+ )
+ target_bound_hash = compute_plan_hash(plan_context)
+ dry_run_result["plan_hash"] = target_bound_hash
+ dry_run_result["plan_context"] = _plan_context_payload(plan_context)
+ dry_run_result["confirmable"] = True
+
+ if dry_run:
+ warnings = list(dry_run_result.get("warnings", []))
+ next_actions: list[str] = []
+ if MCPConfig.from_env().is_readonly():
+ dry_run_result, readonly_warnings, readonly_next_actions = (
+ mark_readonly_preview(
+ dry_run_result,
+ warning=(
+ "This dry-run was generated while HUGEGRAPH_MCP_READONLY=true. "
+ "Its plan_hash is preview-only; set HUGEGRAPH_MCP_READONLY=false "
+ "and rerun dry_run before confirming writes."
+ ),
+ next_action="Set HUGEGRAPH_MCP_READONLY=false and rerun dry_run before confirm.",
+ )
+ )
+ warnings.extend(readonly_warnings)
+ next_actions.extend(readonly_next_actions)
+ else:
+ issue_error = issue_plan(plan_context, target_bound_hash)
+ if issue_error is not None:
+ return issue_error
+ return envelope_ok(
+ dry_run_result,
+ warnings=warnings,
+ next_actions=next_actions,
+ )
+
+ # Recheck readonly at execution time instead of relying only on write tools
+ # being hidden during server registration; long-running processes and tests
+ # may change configuration or call internal functions directly.
+ violation = guard(Capability.DATA_WRITE)
+ if violation is not None:
+ return violation
+
+ if not confirm:
+ return confirm_required_error(
+ message="Graph data changes require confirm=True after a dry_run.",
+ suggestion="Run dry_run=True, review preview and warnings, then pass confirm=True with the returned plan_hash.",
+ )
+
+ schema_summary = _schema_summary(live_schema)
+ valid, error_type, details = verify_and_consume_plan(
+ submitted_hash=plan_hash,
+ tool_name=plan_tool_name,
+ mode=mode,
+ payload_digest=_manage_graph_data_payload_digest(
+ plan,
+ extra_hash_context=extra_hash_context,
+ ),
+ schema_hash=compute_payload_digest(schema_summary) if schema_summary else None,
+ nonce=nonce,
+ expires_at=expires_at,
+ extra_context={"extra_hash_context": extra_hash_context or {}},
+ )
+ if not valid:
+ return plan_hash_error(
+ error_type=error_type,
+ details=details,
+ mismatch_message="Provided plan_hash does not match the current graph data change plan.",
+ expired_message="Graph data change plan has expired.",
+ suggestion="Run dry_run=True again and use the returned plan_hash.",
+ )
+
+ execute_result = execute_graph_change_plan(plan, live_schema=live_schema)
+ if isinstance(execute_result, dict) and execute_result.get("ok") is False:
+ return envelope_err(
+ execute_result["error"]["type"],
+ execute_result["error"]["message"],
+ suggestion=execute_result["error"].get("suggestion"),
+ # Confirmation has already been consumed and the executor may
+ # have applied an unreported side effect. Require a fresh dry-run
+ # before any retry instead of encouraging blind replay.
+ retryable=False,
+ details=_normalize_execute_result(execute_result, plan),
+ )
+
+ normalized = _normalize_execute_result(execute_result, plan)
+ if normalized.get("success") is False or normalized.get("status") in {
+ "partial",
+ "error",
+ "degraded",
+ }:
+ return envelope_err(
+ ErrorType.FLOW_EXECUTION_FAILED,
+ "Graph change execution did not complete successfully.",
+ retryable=bool(normalized.get("retryable")),
+ details=normalized,
+ warnings=normalized.get("warnings", []),
+ )
+
+ return envelope_ok(normalized)
+
+
+def _build_manage_graph_data_plan_context(
+ *,
+ tool_name: str,
+ mode: str,
+ plan: Any,
+ live_schema: dict[str, Any],
+ nonce: str | None,
+ extra_hash_context: dict[str, Any] | None,
+):
+ schema_summary = _schema_summary(live_schema)
+ return build_plan_context(
+ tool_name=tool_name,
+ mode=mode,
+ payload_digest=_manage_graph_data_payload_digest(
+ plan,
+ extra_hash_context=extra_hash_context,
+ ),
+ schema_hash=compute_payload_digest(schema_summary) if schema_summary else None,
+ nonce=nonce,
+ extra_context={"extra_hash_context": extra_hash_context or {}},
+ )
+
+
+def _manage_graph_data_payload_digest(
+ plan: Any,
+ *,
+ extra_hash_context: dict[str, Any] | None,
+) -> str:
+ payload: dict[str, Any] = {"change_plan": plan}
+ if extra_hash_context is not None:
+ payload["extra_hash_context"] = extra_hash_context
+ return compute_payload_digest(payload)
+
+
+def _plan_context_payload(plan_context) -> dict[str, Any]:
+ return {
+ "nonce": plan_context.nonce,
+ "expires_at": plan_context.expires_at,
+ "graph_url": plan_context.graph_url,
+ "graph_name": plan_context.graph_name,
+ "graphspace": plan_context.graphspace,
+ "principal": plan_context.principal,
+ "readonly": plan_context.readonly,
+ }
+
+
+def _normalize_execute_result(execute_result: Any, plan: Any) -> dict[str, Any]:
+ operations = _operations(plan)
+ planned = _mutation_summary(operations)
+
+ if isinstance(execute_result, dict) and execute_result.get("ok") is False:
+ return {
+ "status": "error",
+ "success": False,
+ "planned": planned,
+ "written": {},
+ "failed_items": [execute_result["error"]],
+ "warnings": execute_result.get("warnings", []),
+ "retryable": False,
+ "compensation_suggestions": [],
+ "results": [],
+ "mutation_summary": planned,
+ }
+
+ if not isinstance(execute_result, dict):
+ return {
+ "status": "degraded",
+ "success": False,
+ "planned": planned,
+ "written": {},
+ "failed_items": [{"result": execute_result}],
+ "warnings": ["Graph change execution returned an unrecognized result."],
+ "retryable": False,
+ "compensation_suggestions": ["Inspect graph state before retrying."],
+ "results": [],
+ "mutation_summary": planned,
+ }
+
+ raw_results = execute_result.get("results")
+ results = raw_results if isinstance(raw_results, list) else []
+ failed_items = execute_result.get("failed_items")
+ if not isinstance(failed_items, list):
+ failed_items = []
+
+ if (
+ execute_result.get("success") is True
+ and len(results) == len(operations)
+ and not failed_items
+ ):
+ status = "success"
+ elif results:
+ status = "partial"
+ elif execute_result.get("success") is False or failed_items:
+ status = "error"
+ else:
+ status = "degraded"
+
+ written = _mutation_summary(
+ [operation for operation, _result in zip(operations, results, strict=False)]
+ )
+ return {
+ "status": status,
+ "success": status == "success",
+ "planned": planned,
+ "written": written,
+ "failed_items": failed_items,
+ "warnings": execute_result.get("warnings", []),
+ "retryable": False,
+ "compensation_suggestions": (
+ ["Inspect graph state before retrying remaining operations."]
+ if status in ("partial", "degraded")
+ else []
+ ),
+ "results": results,
+ "mutation_summary": execute_result.get("mutation_summary", planned),
+ }
diff --git a/hugegraph-mcp/hugegraph_mcp/tools/manage_schema.py b/hugegraph-mcp/hugegraph_mcp/tools/manage_schema.py
new file mode 100644
index 00000000..2e74624d
--- /dev/null
+++ b/hugegraph-mcp/hugegraph_mcp/tools/manage_schema.py
@@ -0,0 +1,1592 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Schema 管理统一入口 — design / validate / dry_run / apply 模式。
+
+v2_core 解锁最窄 schema apply:create_property_key、create_vertex_label、
+create_edge_label。index/rebuild、schema remove/drop、schema append/eliminate
+仍不在 P0a 范围内。
+"""
+
+from copy import deepcopy
+from dataclasses import replace
+from typing import Any
+
+from pyhugegraph.client import PyHugeClient
+
+from hugegraph_mcp import schema_tools
+from hugegraph_mcp.config import MCPConfig
+from hugegraph_mcp.confirmable_workflow import (
+ confirm_required_error,
+ issue_plan,
+ plan_hash_error,
+ replayed_plan_error,
+ verify_and_consume_plan,
+)
+from hugegraph_mcp.envelope import ErrorType, envelope_err, envelope_ok
+from hugegraph_mcp.guard import Capability, guard
+from hugegraph_mcp.hugegraph_client import build_hugegraph_client
+from hugegraph_mcp.plan_hash import (
+ PlanContext,
+ build_plan_context,
+ compute_payload_digest,
+ compute_plan_hash,
+)
+from hugegraph_mcp.tools.live_schema import current_live_schema
+from hugegraph_mcp.tools.schema_utils import normalized_schema_summary
+
+ALLOWED_OPERATION_TYPES = frozenset(
+ {
+ "create_property_key",
+ "create_vertex_label",
+ "create_edge_label",
+ "create_index_label",
+ }
+)
+P0A_APPLY_OPERATION_TYPES = frozenset(
+ {
+ "create_property_key",
+ "create_vertex_label",
+ "create_edge_label",
+ }
+)
+
+REQUIRED_FIELDS = {
+ "create_property_key": ("name", "data_type"),
+ "create_vertex_label": ("name",),
+ "create_edge_label": ("name", "source_label", "target_label"),
+ "create_index_label": ("name", "base_type", "base_label"),
+}
+
+IDENTIFIER_FIELDS = {
+ "create_property_key": ("name",),
+ "create_vertex_label": ("name",),
+ "create_edge_label": ("name", "source_label", "target_label"),
+ "create_index_label": ("name", "base_label"),
+}
+
+UNSUPPORTED_EDGE_LABEL_FIELDS = frozenset(
+ {"parent_label", "parentLabel", "edgelabel_type", "edgeLabelType"}
+)
+
+PROPERTY_KEY_DATA_TYPES = frozenset(
+ {
+ "TEXT",
+ "INT",
+ "INTEGER",
+ "LONG",
+ "DOUBLE",
+ "FLOAT",
+ "BOOLEAN",
+ "BOOL",
+ "DATE",
+ "BYTE",
+ "BLOB",
+ "OBJECT",
+ }
+)
+PROPERTY_KEY_CARDINALITIES = frozenset({"SINGLE", "SET", "LIST"})
+PROPERTY_KEY_AGGREGATE_TYPES = frozenset(
+ {"NONE", "OLD", "SUM", "MIN", "MAX", "SET", "LIST"}
+)
+VERTEX_LABEL_ID_STRATEGIES = frozenset(
+ {"PRIMARY_KEY", "CUSTOMIZE_STRING", "CUSTOMIZE_NUMBER", "AUTOMATIC"}
+)
+EDGE_LABEL_FREQUENCIES = frozenset({"SINGLE", "MULTIPLE"})
+
+PROPERTY_KEY_DATA_TYPE_METHODS = {
+ "TEXT": "asText",
+ "INT": "asInt",
+ "INTEGER": "asInt",
+ "LONG": "asLong",
+ "DOUBLE": "asDouble",
+ "FLOAT": "asFloat",
+ "BOOLEAN": "asBool",
+ "BOOL": "asBool",
+ "DATE": "asDate",
+ "BYTE": "asByte",
+ "BLOB": "asBlob",
+ "OBJECT": "asObject",
+}
+PROPERTY_KEY_CARDINALITY_METHODS = {
+ "SINGLE": "valueSingle",
+ "SET": "valueSet",
+ "LIST": "valueList",
+}
+PROPERTY_KEY_AGGREGATE_METHODS = {
+ "OLD": "calcOld",
+ "SUM": "calcSum",
+ "MIN": "calcMin",
+ "MAX": "calcMax",
+}
+PROPERTY_KEY_DIRECT_AGGREGATE_TYPES = frozenset({"NONE", "SET", "LIST"})
+PROPERTY_KEY_AGGREGATE_CARDINALITIES = {
+ "NONE": frozenset({"SINGLE", "SET", "LIST"}),
+ "OLD": frozenset({"SINGLE"}),
+ "SUM": frozenset({"SINGLE"}),
+ "MIN": frozenset({"SINGLE"}),
+ "MAX": frozenset({"SINGLE"}),
+ "SET": frozenset({"SET"}),
+ "LIST": frozenset({"LIST"}),
+}
+PROPERTY_KEY_DATA_TYPE_CANONICAL = {
+ "INTEGER": "INT",
+ "BOOL": "BOOLEAN",
+}
+VERTEX_LABEL_ID_STRATEGY_METHODS = {
+ "PRIMARY_KEY": "usePrimaryKeyId",
+ "CUSTOMIZE_STRING": "useCustomizeStringId",
+ "CUSTOMIZE_NUMBER": "useCustomizeNumberId",
+ "AUTOMATIC": "useAutomaticId",
+}
+EDGE_LABEL_FREQUENCY_METHODS = {
+ "SINGLE": "singleTime",
+ "MULTIPLE": "multiTimes",
+}
+
+
+ValidationError = dict[str, Any]
+
+
+def _operation_type(operation: dict[str, Any]) -> str:
+ return str(operation.get("type", ""))
+
+
+def _is_delete_operation(op_type: str) -> bool:
+ lowered = op_type.lower()
+ return "delete" in lowered or "drop" in lowered
+
+
+def _validation_error(
+ operation_index: int,
+ operation: Any,
+ reason: str,
+ suggestion: str,
+) -> ValidationError:
+ return {
+ "operation_index": operation_index,
+ "operation": operation,
+ "reason": reason,
+ "suggestion": suggestion,
+ }
+
+
+def _schema_items(live_schema: dict[str, Any], key: str) -> set[str]:
+ schema = live_schema.get("schema", {})
+ return {
+ item.get("name")
+ for item in schema.get(key, [])
+ if isinstance(item, dict) and item.get("name")
+ }
+
+
+def _collect_planned_creates(
+ operations: list[dict[str, Any]],
+) -> tuple[dict[str, set[str]], list[ValidationError]]:
+ planned = {
+ "property_keys": set(),
+ "vertex_labels": set(),
+ "edge_labels": set(),
+ "index_labels": set(),
+ }
+ errors: list[ValidationError] = []
+ create_type_to_key = {
+ "create_property_key": "property_keys",
+ "create_vertex_label": "vertex_labels",
+ "create_edge_label": "edge_labels",
+ "create_index_label": "index_labels",
+ }
+ create_type_to_label = {
+ "create_property_key": "property_key",
+ "create_vertex_label": "vertex_label",
+ "create_edge_label": "edge_label",
+ "create_index_label": "index_label",
+ }
+
+ for idx, operation in enumerate(operations):
+ if not isinstance(operation, dict):
+ continue
+
+ op_type = _operation_type(operation)
+ planned_key = create_type_to_key.get(op_type)
+ if planned_key is None:
+ continue
+
+ name = operation.get("name")
+ if not name:
+ continue
+
+ if name in planned[planned_key]:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"duplicate {op_type} name {name} within the same batch",
+ (
+ f"Define each {create_type_to_label[op_type]} only once "
+ "per schema operation batch."
+ ),
+ )
+ )
+ continue
+
+ planned[planned_key].add(name)
+
+ return planned, errors
+
+
+def _validate_property_references(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ field: str,
+ property_keys: set[str],
+ errors: list[ValidationError],
+) -> None:
+ values = operation.get(field, [])
+ if values in (None, ""):
+ return
+ if not isinstance(values, list):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must be a list",
+ f"Use an array of existing property key names for {field}.",
+ )
+ )
+ return
+
+ invalid_names = _invalid_schema_names(values)
+ if invalid_names:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must contain non-empty string names",
+ f"Use only non-empty schema property key names for {field}.",
+ )
+ )
+ return
+
+ duplicate_names = _duplicate_names(values)
+ if duplicate_names:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} contains duplicate name(s): {', '.join(duplicate_names)}",
+ f"Remove duplicate property key names from {field}.",
+ )
+ )
+ return
+
+ missing_properties = [name for name in values if name not in property_keys]
+ if missing_properties:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} references undefined property key(s): {', '.join(missing_properties)}",
+ "Create these property keys first and rerun validation after they exist in the live schema.",
+ )
+ )
+
+
+def _validate_property_subset_references(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ field: str,
+ property_keys: set[str],
+ errors: list[ValidationError],
+) -> None:
+ values = operation.get(field)
+ if values is None:
+ return
+ if not isinstance(values, list):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must be a list",
+ f"Use an array of existing property key names for {field}.",
+ )
+ )
+ return
+
+ if not values:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must be a non-empty list",
+ f"Use one or more existing property key names for {field}.",
+ )
+ )
+ return
+
+ invalid_names = _invalid_schema_names(values)
+ if invalid_names:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must contain non-empty string names",
+ f"Use only non-empty schema property key names for {field}.",
+ )
+ )
+ return
+
+ duplicate_names = _duplicate_names(values)
+ if duplicate_names:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} contains duplicate name(s): {', '.join(duplicate_names)}",
+ f"Remove duplicate property key names from {field}.",
+ )
+ )
+ return
+
+ missing_properties = [name for name in values if name not in property_keys]
+ if missing_properties:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} references undefined property key(s): {', '.join(missing_properties)}",
+ "Create these property keys first and rerun validation after they exist in the live schema.",
+ )
+ )
+
+ properties = operation.get("properties") or []
+ if not isinstance(properties, list):
+ return
+
+ missing_from_label = [name for name in values if name not in properties]
+ if missing_from_label:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must be included in properties: {', '.join(missing_from_label)}",
+ f"Add each {field} entry to properties before using it in {field}.",
+ )
+ )
+
+
+def _validate_enum_field(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ field: str,
+ allowed_values: frozenset[str],
+ errors: list[ValidationError],
+ required: bool,
+ default: str | None = None,
+) -> str | None:
+ raw_value = operation.get(field)
+ if raw_value in (None, ""):
+ if default is not None:
+ return default
+ if not required:
+ return None
+
+ if not isinstance(raw_value, str):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must be a string, got {type(raw_value).__name__}",
+ f"Use one of: {', '.join(sorted(allowed_values))} for {field}.",
+ )
+ )
+ return None
+
+ normalized = raw_value.upper()
+ if normalized not in allowed_values:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"unsupported {field}: {raw_value!r}",
+ f"Use one of: {', '.join(sorted(allowed_values))} for {field}.",
+ )
+ )
+ return None
+
+ return _canonical_enum_value(field, normalized)
+
+
+def _validate_property_key_aggregate_cardinality(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ cardinality: str | None,
+ aggregate_type: str | None,
+ errors: list[ValidationError],
+) -> None:
+ if aggregate_type is None:
+ return
+ allowed_cardinalities = PROPERTY_KEY_AGGREGATE_CARDINALITIES.get(aggregate_type)
+ if allowed_cardinalities is None or cardinality in allowed_cardinalities:
+ return
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ (
+ f"aggregate_type {aggregate_type!r} is not allowed with "
+ f"cardinality {cardinality!r}"
+ ),
+ (
+ f"Use cardinality in {sorted(allowed_cardinalities)} for "
+ f"aggregate_type {aggregate_type!r}."
+ ),
+ )
+ )
+
+
+def _validate_identifier_field(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ field: str,
+ errors: list[ValidationError],
+) -> bool:
+ value = operation.get(field)
+ if not isinstance(value, str) or not value.strip():
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"{field} must be a non-empty string, got {value!r}",
+ f"Provide {field} as a non-empty string identifier.",
+ )
+ )
+ return False
+ return True
+
+
+def _validate_vertex_primary_keys(
+ *,
+ idx: int,
+ operation: dict[str, Any],
+ id_strategy: str | None,
+ property_keys: set[str],
+ errors: list[ValidationError],
+) -> None:
+ if id_strategy is None:
+ return
+ if id_strategy != "PRIMARY_KEY":
+ return
+
+ primary_keys = operation.get("primary_keys")
+ if not primary_keys:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "primary_keys is required when id_strategy is PRIMARY_KEY",
+ "Add non-empty primary_keys or set id_strategy to AUTOMATIC/CUSTOMIZE_STRING/CUSTOMIZE_NUMBER.",
+ )
+ )
+ return
+
+ if not isinstance(primary_keys, list):
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "primary_keys must be a list",
+ "Use an array of property key names for primary_keys.",
+ )
+ )
+ return
+
+ invalid_names = _invalid_schema_names(primary_keys)
+ if invalid_names:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "primary_keys must contain non-empty string names",
+ "Use only non-empty property key names for primary_keys.",
+ )
+ )
+ return
+
+ duplicate_names = _duplicate_names(primary_keys)
+ if duplicate_names:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ f"primary_keys contains duplicate name(s): {', '.join(duplicate_names)}",
+ "Remove duplicate names from primary_keys.",
+ )
+ )
+ return
+
+ properties = operation.get("properties") or []
+ if not isinstance(properties, list):
+ return
+
+ missing_from_properties = [name for name in primary_keys if name not in properties]
+ if missing_from_properties:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "primary_keys must be included in properties: "
+ + ", ".join(missing_from_properties),
+ "Add each primary key to properties before using it as a primary key.",
+ )
+ )
+
+ missing_property_keys = [name for name in primary_keys if name not in property_keys]
+ if missing_property_keys:
+ errors.append(
+ _validation_error(
+ idx,
+ operation,
+ "primary_keys references undefined property key(s): "
+ + ", ".join(missing_property_keys),
+ "Create these property keys first and rerun validation after they exist in the live schema.",
+ )
+ )
+
+
+def _invalid_schema_names(values: list[Any]) -> list[Any]:
+ return [value for value in values if not isinstance(value, str) or not value]
+
+
+def _duplicate_names(values: list[str]) -> list[str]:
+ seen: set[str] = set()
+ duplicates: list[str] = []
+ for value in values:
+ if value in seen and value not in duplicates:
+ duplicates.append(value)
+ seen.add(value)
+ return duplicates
+
+
+def _validation_warnings(operations: list[dict[str, Any]]) -> list[str]:
+ warnings: list[str] = []
+ for idx, operation in enumerate(operations):
+ if not isinstance(operation, dict):
+ continue
+ id_strategy = str(operation.get("id_strategy", "PRIMARY_KEY")).upper()
+ if (
+ operation.get("type") == "create_vertex_label"
+ and id_strategy != "PRIMARY_KEY"
+ and not operation.get("primary_keys")
... 15144 lines suppressed ...