Skip to content

feat(mcp): add GraphRAG recall tool - #455

Open
yuangu-chengzi wants to merge 9 commits into
apache:mainfrom
yuangu-chengzi:feat/graph-rag-mcp-tool
Open

yuangu-chengzi wants to merge 9 commits into
apache:mainfrom
yuangu-chengzi:feat/graph-rag-mcp-tool

Conversation

@yuangu-chengzi

@yuangu-chengzi yuangu-chengzi commented Dec 4, 2026 •

Copy link
Copy Markdown

Summary

Adds a core MCP tool that exposes HugeGraph-AI GraphRAG recall through the existing hugegraph-mcp server.

graph_rag_query_tool wraps POST /rag/graph via hugegraph_ai_client, validates its parameters before the AI call, and returns the upstream graph_recall payload in the standard MCP envelope.

Motivation

Closes #225. The MCP server already exposes HugeGraph schema and structured query tools, and it already has an AI client (/text2gremlin, /graph-extract, etc.). GraphRAG recall was the missing AI-facing read path.

Changes

  • Add hugegraph_mcp/tools/graph_rag_query.py.
  • Register graph_rag_query_tool in the core toolset in server.py.
  • Add unit tests for success, optional parameters, validation failures, upstream errors, and malformed responses.
  • Update the public tool tables and the core-tool count in the English/Chinese READMEs, integration docs, releasing docs, and distribution smoke test.
  • Add the new tool to the core tool-contract test.
  • Send the MCP target's graph/graphspace as client_config with each /rag/graph request, validate those fields against the AI service's configured target before executing the recall, and propagate the validated connection as a request-scoped graph_client_config through the flow so later nodes do not re-read huge_settings.
  • Pass the validated connection into SemanticIdQuery, which uses it for both its PyHugeClient and the graph_vids index name/directory.
  • Return a graph_target attestation from /rag/graph; MCP fails closed if the attestation is missing (for example, an older AI service) or does not match its configured target.
  • Fix the default GraphRAG execution path: OperatorList.example_index_query now passes the configured vector-index class and embedding to GremlinExampleIndexQuery, instead of passing the embedding as the vector-index argument.
  • Make GraphQueryNode.operator_schedule catch generated-Gremlin failures and still run the subgraph fallback instead of returning early.
  • Stop using max_graph_items as the aggregate recall cap; the post-materialization guard uses HUGEGRAPH_MCP_MAX_RESULT_ITEMS, because max_graph_items limits each matched vertex's neighbour query while topk_return_results bounds the recall.
  • Preserve an explicit zero vector_dis_threshold in the RAG flows instead of replacing it with the configured default.
  • Move the read-only-principal note after the graphspace-validation paragraph in the English README and add the same warning to the Chinese README.

Tests

  • pytest hugegraph-mcp/tests/test_graph_rag_query.py -q — 30 passed.
  • Added MCP tests for graph binding, target attestation (missing/mismatched), aggregate recall larger than max_graph_items, and the configured result-item guard.
  • Added AI-side tests for matching/mismatching client_config, request-scoped connection propagation into the recall flow, the graph_target response, zero distance thresholds, and the example-index wiring.
  • Added GraphQueryNode.node_init coverage proving a request-scoped connection is used instead of global settings, a generation-failure fallback test, and an integration-style test that drives the real OperatorList path to Gremlin execution.
  • ruff format --check and ruff check pass on both packages.
  • Full MCP registration/contract tests and the HugeGraph-AI LLM suite run in CI; the fastmcp and AI service dependencies are unavailable in this Windows environment.

Notes

  • Requires HUGEGRAPH_MCP_ALLOW_AI=true and a reachable HugeGraph-AI service.
  • graph_rag_query_tool is fail-closed behind HUGEGRAPH_MCP_AI_GRAPH_READONLY=true: the operator must assert that HugeGraph-AI uses a read-only HugeGraph principal, because /rag/graph executes model-generated Gremlin inside the AI service.
  • Size parameters reject values above MAX_LIMIT=500 and are capped by HUGEGRAPH_MCP_MAX_RESULT_ITEMS; graph_recall passes through _gremlin_output_guard_error.
  • vector_dis_threshold accepts any finite non-negative value (including backend-specific values above 1), and zero is forwarded unchanged.
  • Graph binding validates the configured graph and graphspace; it does not prove both sides use the same physical server, which remains a deployment check documented in both READMEs.
  • No new dependencies; no HugeGraph write path from MCP itself.
  • The full-answer /rag endpoint is intentionally out of scope; it can be added in a follow-up.
  • The contributor has submitted the ICLA to secretary@apache.org; this PR is ready for review.

🤖 Generated with Claude Code

@yuangu-chengzi
yuangu-chengzi force-pushed the feat/graph-rag-mcp-tool branch from 1c23465 to 33ce6a8 Compare December 4, 2026 05:17
Add graph_rag_query_tool to the core MCP toolset. It wraps the HugeGraph-AI /rag/graph endpoint through hugegraph_ai_client, validates parameters before the AI call, and returns graph_recall in the standard envelope.

Update the core tool count and public tool tables, and cover success, optional parameters, validation, upstream errors, and malformed responses with unit tests.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi
yuangu-chengzi force-pushed the feat/graph-rag-mcp-tool branch from 33ce6a8 to d42e761 Compare December 4, 2026 05:34
@yuangu-chengzi
yuangu-chengzi marked this pull request as ready for review December 4, 2026 05:35

@imbajin imbajin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Score: 5.5/10 · Confidence: high

Blocking: yes

Summary

The READ tool can execute generated graph mutations with writable backend credentials, and its distance validation rejects supported thresholds.

Evidence

Traced /rag/graph into GraphQueryNode's direct Gremlin execution and checked the vector-store distance comparison and upstream request model.

Validation notes

Source review only; no live graph mutation or vector-store integration test was run. Mutation depends on backend credentials and generated output.

}
if gremlin_prompt is not None:
payload["gremlin_prompt"] = gremlin_prompt

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Enforce a read-only boundary for generated Gremlin

With the default gremlin_tmpl_num=1, /rag/graph reaches GraphQueryNode._gremlin_generate_query, which submits the model-generated Gremlin directly using the AI service's graph credentials. The caller can also supply gremlin_prompt. If those credentials allow writes and the model generates a mutation, this READ tool can modify the graph even when MCP is read-only, bypassing write confirmation. Please enforce a read-only graph principal or an equivalent server-side execution boundary before exposing this route. This is based on source tracing; I did not run a live mutation.

if isinstance(gremlin_tmpl_num, bool) or not isinstance(gremlin_tmpl_num, int):
return _validation_error("gremlin_tmpl_num must be an integer.", "gremlin_tmpl_num")

if (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Match the backend's distance threshold range

The upstream request accepts distance thresholds above 1, and the Qdrant store compares 1 - similarity against this threshold (cosine distance can reach 2); FAISS also uses raw distances. A valid value such as 1.5 is therefore rejected here before reaching the backend, preventing callers from using supported retrieval settings. Please validate according to the backend's distance semantics rather than imposing a universal upper bound of 1. The upstream graph flow also replaces a supplied zero with its default, so that boundary needs an integration check.

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: graph_rag_query_tool exposes /rag/graph as a READ tool, but its size parameters and response skip the package's result guards. The generated-Gremlin and distance-threshold comments already on this head still apply.

("topk_per_keyword", topk_per_keyword, 1),
)
for name, value, minimum in integer_fields:
if isinstance(value, bool) or not isinstance(value, int) or value < minimum:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: max_graph_items, topk_return_results and topk_per_keyword have no upper bound, and the returned graph_recall skips the HUGEGRAPH_MCP_MAX_RESULT_ITEMS and HUGEGRAPH_MCP_MAX_RESULT_BYTES guards, so a caller can pull an unbounded subgraph through a READ tool. Cap these fields as query_graph_data does with MAX_LIMIT and cfg.max_result_items, and reject an oversized graph_recall through _gremlin_output_guard_error.

Cap graph_rag_query_tool size parameters with MAX_LIMIT and HUGEGRAPH_MCP_MAX_RESULT_ITEMS, route graph_recall through the post-materialization output guard, and accept finite non-negative distance thresholds beyond 1.

Add a fail-closed HUGEGRAPH_MCP_AI_GRAPH_READONLY assertion so GraphRAG execution is disabled unless the operator declares that HugeGraph-AI uses a read-only HugeGraph principal.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Thanks for the review. I pushed a follow-up commit.

  • Size guards: max_graph_items, topk_return_results, and topk_per_keyword now reject values above MAX_LIMIT=500 and are capped by HUGEGRAPH_MCP_MAX_RESULT_ITEMS. The returned graph_recall now goes through _gremlin_output_guard_error (item and byte guards).
  • Distance threshold: vector_dis_threshold now accepts any finite non-negative value; the universal 0..1 upper bound is removed so backend-specific values such as 1.5 pass through.
  • Generated-Gremlin boundary: MCP cannot verify the AI service's graph credentials from this side. I added a fail-closed HUGEGRAPH_MCP_AI_GRAPH_READONLY assertion: graph_rag_query_tool returns FEATURE_DISABLED unless the operator explicitly declares that HugeGraph-AI uses a read-only HugeGraph principal. The README states it must never be set for writable credentials. If you want a stronger server-side boundary, I can open a paired hugegraph-llm change to validate generated Gremlin before execution; please advise whether that should be part of this PR or a follow-up.

@yuangu-chengzi

Copy link
Copy Markdown
Author

I opened the paired server-side boundary: #456.

It adds GRAPH_GREMLIN_READ_ONLY (default true) and rejects non-read-only Gremlin before GraphQueryNode or run_gremlin_query executes it. GraphQueryNode falls back to the safe subgraph query; run_gremlin_query raises a clear error. The MCP-side HUGEGRAPH_MCP_AI_GRAPH_READONLY assertion in this PR remains as defense-in-depth.

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: the new output guard checks the recall item count against max_graph_items, a per-vertex traversal limit, so valid recalls within topk_return_results fail with VALIDATION_ERROR. The README placement of the read-only principal note is a minor doc fix.

data,
result_count,
0.0,
max_items=bounded_max_graph_items,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: upstream max_graph_items limits each matched vertex's neighbour query while topk_return_results caps graph_result, so max_graph_items=10 with the default topk_return_results=20 rejects a valid 15-path recall. Drop max_items so the guard uses HUGEGRAPH_MCP_MAX_RESULT_ITEMS, and update test_graph_rag_query_rejects_oversized_recall to match.

Comment thread hugegraph-mcp/README.md Outdated
ignored and is not a way to override the AI target.
For the default MCP target `DEFAULT/hugegraph`, set AI `GRAPH_NAME=hugegraph`.

GraphRAG execution calls model-generated Gremlin inside the AI service, so it is disabled unless you configure the AI service with a HugeGraph principal that has read-only permissions and then set `HUGEGRAPH_MCP_AI_GRAPH_READONLY=true`. Never set this assertion when the AI service uses writable credentials.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: this paragraph splits the graphspace target-validation text from its paragraph, so lines 254-256 render as part of the GraphRAG note, and README.zh-CN.md has no matching warning against writable credentials. Move the note below line 256 and add the same paragraph to the Chinese AI 服务配置 section.

@imbajin imbajin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Score: 6.0/10 · Confidence: high

Blocking: yes

Summary

Graph recall can silently query a different graph than the MCP target. Existing issues remain: the aggregate guard may reject valid recalls, a zero distance threshold is replaced by the upstream default, and the Chinese documentation lacks the writable-credential warning.

Evidence

Traced the MCP request and envelope, AI endpoint and graph configuration, per-vertex traversal limit, and threshold defaulting in source.

Validation notes

Source review only; no live multi-graph, retrieval, or security integration test was run. The read-only principal is an operator assertion.

if gremlin_prompt is not None:
payload["gremlin_prompt"] = gremlin_prompt

ai_result = post("/rag/graph", json=payload)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Bind recall to the configured graph

If MCP targets graph A but the AI service is configured for graph B, this request returns B's data while the MCP envelope identifies A. /rag/graph ignores client_config and uses the AI service's own graph settings, so the read-only assertion does not prevent cross-graph reads. Please validate the expected graph and graphspace on the AI side as part of executing the recall, and fail closed on mismatch. This is based on source tracing; I did not run a live multi-graph test.

… guard

- Send graph/graphspace client_config with /rag/graph, validate it on the AI
  side, and reject mismatches before executing the recall.
- Treat unset/DEFAULT graphspaces as equivalent during target validation.
- Stop capping the aggregate GraphRAG recall by max_graph_items; use the
  configured result-item limit.
- Preserve an explicit zero vector_dis_threshold in the RAG flows.
- Document the read-only principal requirement in both READMEs.
- Add MCP and AI-side tests for graph binding, zero thresholds, and aggregate
  recall limits.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

yuangu-chengzi commented Dec 5, 2026 •

Copy link
Copy Markdown
Author

Thanks for the detailed review. Pushed a follow-up that addresses each blocking point:

  • Bind recall to the configured graph: graph_rag_query_tool now sends client_config: {graph, gs} with every /rag/graph request. On the AI side, /rag/graph validates those fields against GRAPH_NAME/GRAPH_SPACE and returns 400 on a mismatch before calling the recall flow. Unset/null/empty/DEFAULT graphspaces are treated as equivalent for this validation. Added MCP and AI contract tests for matching and mismatching targets.
  • Aggregate result guard: dropped max_items=max_graph_items from _gremlin_output_guard_error; the aggregate recall is now bounded by HUGEGRAPH_MCP_MAX_RESULT_ITEMS (via cfg.max_result_items), while max_graph_items keeps its per-vertex traversal meaning. Added a regression test where a 15-path recall passes with max_graph_items=10, topk_return_results=20, plus an oversized-recall test using the configured item limit.
  • Zero distance threshold: the RAG flows now use vector_dis_threshold if vector_dis_threshold is not None else default, so an explicit 0.0 is preserved. Added a flow test.
  • README: moved the read-only-principal paragraph after the graphspace-validation paragraph and added the same warning under AI 服务配置 in README.zh-CN.md. Both READMEs now also state that the AI service rejects a target mismatch.

Local checks: pytest hugegraph-mcp/tests/test_graph_rag_query.py -q — 28 passed; ruff format --check and ruff check pass on both packages. The new AI-side tests run in CI because this Windows checkout lacks the full FastAPI/LLM dependency set.

@yuangu-chengzi

Copy link
Copy Markdown
Author

Pushed the follow-up for the latest review (head 9eda390). The new HugeGraph AI CI run is action_required; could a maintainer approve the workflow when convenient? Thanks!

@imbajin imbajin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Score: 5.0/10 · Confidence: high

Blocking: yes

Summary

The default GraphRAG path fails before recall, and graph binding can still be violated during concurrent configuration updates or when the AI service is older.

Evidence

Traced the default through GraphQueryNode, OperatorList and GremlinExampleIndexQuery, and traced target validation and later global reads. The old endpoint ignores client_config.

Validation notes

Source review only; no live AI service, mixed-version deployment or concurrent graph update was tested.

topk_return_results: int = 20,
vector_dis_threshold: float = 0.9,
topk_per_keyword: int = 1,
gremlin_tmpl_num: int = 1,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Fix the default GraphRAG execution path

With the default gremlin_tmpl_num=1, GraphQueryNode calls OperatorList(None, None).example_index_query(), which passes None as the vector_index to GremlinExampleIndexQuery; its constructor then calls vector_index.exist(...). The outer node handler catches that error and returns before the subgraph fallback, so the default request cannot retrieve graph results through this path. Please wire the vector index and embedding correctly and cover the real GraphRAG flow, not only a mocked AI response. This is based on source tracing; I did not run an end-to-end service.

status_code=status.HTTP_400_BAD_REQUEST,
detail="Query must not be empty.",
)
_request_graph_connection(req)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Keep the validated target through recall

This validates the current global graph settings, but discards the returned connection; the recall flow and graph nodes read huge_settings again. If a graph configuration update runs between the check and node initialization, a request validated for graph A can execute against graph B and return it under A's MCP target. Please propagate an immutable validated connection through the entire recall or synchronize updates with execution. The race follows from source inspection; I did not reproduce it with concurrent services.

yuangu-chengzi and others added 2 commits December 5, 2026 22:52
… guard

- Send graph/graphspace client_config with /rag/graph, validate it on the AI
  side, snapshot the validated connection through the recall flow, and return a
  graph_target attestation; MCP rejects missing or mismatched attestations.
- Use the requested vector-index class when building the Text2Gremlin example
  index, fixing the default GraphRAG execution path.
- Stop capping the aggregate GraphRAG recall by max_graph_items; use the
  configured result-item limit.
- Preserve an explicit zero vector_dis_threshold in the RAG flows.
- Document the read-only principal requirement in both READMEs.
- Add MCP and AI-side tests for graph binding/attestation, the example-index
  wiring, request-scoped connections, zero thresholds, and aggregate recall
  limits.

Co-Authored-By: Claude Code <noreply@anthropic.com>
… guard

- Send graph/graphspace client_config with /rag/graph, validate it on the AI
  side, snapshot the validated connection through the recall flow, and return a
  graph_target attestation; MCP rejects missing or mismatched attestations.
- Use the requested vector-index class when building the Text2Gremlin example
  index, fixing the default GraphRAG execution path.
- Stop capping the aggregate GraphRAG recall by max_graph_items; use the
  configured result-item limit.
- Preserve an explicit zero vector_dis_threshold in the RAG flows.
- Document the read-only principal requirement in both READMEs.
- Add MCP and AI-side tests for graph binding/attestation, the example-index
  wiring, request-scoped connections, zero thresholds, and aggregate recall
  limits.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Addressed the two new blocking findings in the latest head (80f25d8):

  • Default GraphRAG path: OperatorList.example_index_query was passing self.embedding as the vector_index argument, so the default gremlin_tmpl_num=1 path reached GremlinExampleIndexQuery with None and raised before execution. It now resolves get_vector_index_class(index_settings.cur_vector_index) and passes the embedding separately. Added a unit test that asserts the vector-index class receives exist()/from_name() and the operator keeps the configured embedding.
  • Validated target through recall: /rag/graph now takes the validated connection, captured atomically under runtime_config_lock, and passes it as graph_client_config through GraphRAGRecall → RAGGraphOnlyFlow.prepare → WkFlowInput. SchemaNode, SemanticIdQueryNode (graph name), GraphQueryNode (PyHugeClient construction), and the get_vertex_only detail lookup use that snapshot instead of re-reading huge_settings. Added a flow test and a GraphQueryNode.node_init test proving the request-scoped connection wins.
  • Older AI / attestation: /rag/graph now returns a graph_target attestation alongside graph_recall; MCP rejects a missing attestation (FLOW_EXECUTION_FAILED) or a mismatched one (VALIDATION_ERROR). This makes an older AI that ignores client_config fail closed instead of silently reading the wrong graph.

Local: pytest hugegraph-mcp/tests/test_graph_rag_query.py -q — 30 passed; ruff format --check / ruff check pass on both packages. The new AI-side flow/node tests run in CI.

Could a maintainer approve the new HugeGraph AI CI run when convenient? Thanks!

… guard

- Send graph/graphspace client_config with /rag/graph, validate it on the AI
  side, snapshot the validated connection through the recall flow, and return a
  graph_target attestation; MCP rejects missing or mismatched attestations.
- Use the requested vector-index class when building the Text2Gremlin example
  index, fixing the default GraphRAG execution path.
- Stop capping the aggregate GraphRAG recall by max_graph_items; use the
  configured result-item limit.
- Preserve an explicit zero vector_dis_threshold in the RAG flows.
- Document the read-only principal requirement in both READMEs.
- Add MCP and AI-side tests for graph binding/attestation, the example-index
  wiring, request-scoped connections, zero thresholds, and aggregate recall
  limits.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

One more push for the default-path finding (head 2d1b7ef):

  • GraphQueryNode.operator_schedule now catches a failure in _gremlin_generate_query and still runs _subgraph_query, so a broken index/LLM path falls back instead of returning early.
  • Added an integration-style test that drives the real OperatorList path (fake vector index/embedding/LLM) and asserts _gremlin_generate_query reaches exec("g.V().limit(1)").
  • Added a test that a generation exception still invokes the subgraph fallback.

The new HugeGraph AI CI run needs approval again — thanks for bearing with the iterations.

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: test_graph_rag_default_path.py sets graph_gremlin_read_only, which exists only in #456, so the llm CI job fails at this head. SemanticIdQuery still reads huge_settings, so the vid lookup can run against a different graph than the one /rag/graph validated.



def test_default_gremlin_generation_path_reaches_execution(monkeypatch):
monkeypatch.setattr(huge_settings, "graph_gremlin_read_only", True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: HugeGraphConfig has no graph_gremlin_read_only on this branch (it comes from #456), so this setattr raises AttributeError and fails the llm CI job. Drop this line here, or add it in #456 once that field exists.


graph_name = huge_settings.graph_name
graph_connection = getattr(self.wk_input, "graph_client_config", None)
graph_name = (graph_connection.get("graph") if graph_connection else None) or huge_settings.graph_name

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: graph_name from the request connection only feeds the null check; SemanticIdQuery.__init__ still builds its client and graph_vids index from huge_settings, so a /config/graph update mid-request returns another graph's match_vids under the attested target. Pass the validated connection into SemanticIdQuery and use it for both the client and the index name.

… guard

- Send graph/graphspace client_config with /rag/graph, validate it on the AI
  side, snapshot the validated connection through the recall flow, and return a
  graph_target attestation; MCP rejects missing or mismatched attestations.
- Pass the validated connection into SemanticIdQuery so its client and
  graph_vids index use the same target as the recall.
- Use the requested vector-index class when building the Text2Gremlin example
  index, fixing the default GraphRAG execution path.
- Stop capping the aggregate GraphRAG recall by max_graph_items; use the
  configured result-item limit, and preserve an explicit zero threshold.
- Document the read-only principal requirement in both READMEs.
- Add MCP and AI-side tests for graph binding/attestation, the example-index
  wiring, request-scoped connections, zero thresholds, and aggregate recalls.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Addressed both new findings in head 81def81:

  • Removed graph_gremlin_read_only from test_graph_rag_default_path.py; that field belongs to feat(llm): enforce read-only Gremlin before execution #456, and this branch's test now only exercises the index/LLM path it actually owns.
  • SemanticIdQuery now accepts the validated graph_client_config and uses it for both its PyHugeClient and the graph_vids index name/directory. SemanticIdQueryNode passes the request snapshot through. Added a test asserting the client and index use the snapshot graph.
  • ruff format/check pass on both packages; MCP tests 30 passed.

The new HugeGraph AI CI run is action_required; could a maintainer approve it? Thanks!

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: graph_rag_query_tool bounds three size fields but forwards any gremlin_tmpl_num, which HugeGraph-AI uses as top_k for its FAISS example search. The earlier graph-binding, default-path, size-guard and SemanticIdQuery comments are addressed at this head.

return _validation_error(f"{name} exceeds maximum {MAX_LIMIT}.", name)

# HugeGraph-AI treats gremlin_tmpl_num <= 0 as "no template".
if isinstance(gremlin_tmpl_num, bool) or not isinstance(gremlin_tmpl_num, int):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: gremlin_tmpl_num has no upper bound, and HugeGraph-AI passes it as top_k to the FAISS gremlin_examples search, so a value such as 10**9 makes one recall allocate tens of GB in the AI service. Reject values above MAX_LIMIT as the other size fields do.

@imbajin imbajin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Score: 6.0/10 · Confidence: high

Blocking: yes

Summary

Graphspace binding can reuse another target's vertex index; valid requests can also fail or do unnecessary index work. The existing unbounded template-count issue remains.

Evidence

Traced snapshot validation, semantic index lookup and build, and example-index constructor and search.

Validation notes

Source review only; no live multi-graphspace, legacy-server or embedding-backend test.

if request_field not in client_config.model_fields_set:
continue
requested_value = getattr(client_config, request_field)
if request_field == "gs":

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Preserve the configured graphspace after validation

The equivalence check accepts a request with gs=DEFAULT when the configured graphspace is unset, but this assignment replaces the captured value with DEFAULT. PyHugeClient treats an explicit graphspace as graphspace-capable and skips version detection, so an existing /rag/graph caller using DEFAULT against a supported 1.5–1.6 server can start using unsupported /graphspaces/DEFAULT paths. Please retain the configured value after validation. This is source-traced; I did not run a legacy server.

pwd = huge_settings.graph_pwd
graphspace = huge_settings.graph_space
self.index_dir = str(os.path.join(resource_path, graph_name, "graph_vids"))
self.vector_index = vector_index.from_name(embedding.get_embedding_dim(), graph_name, "graph_vids")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Scope the vertex index to the validated graph target

The snapshot includes graphspace and server, but this lookup and the existing index builder key graph_vids only by graph name. After switching between two graphspaces with the same graph name, fuzzy lookup can reuse the first target's IDs and return them in match_vids while attesting the second target. Please isolate index creation and lookup by target and handle existing ambiguous indexes. This follows from source tracing; I did not run a multi-graphspace deployment.

from hugegraph_llm.utils.vector_index_utils import get_vector_index_class

vector_index = get_vector_index_class(index_settings.cur_vector_index)
self.operators.append(GremlinExampleIndexQuery(vector_index, self.embedding, num_examples))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Skip index initialization when no examples are requested

For gremlin_tmpl_num=0, this still constructs GremlinExampleIndexQuery, whose constructor loads or builds the index and may call the embedding service for the bundled examples before its zero-example check. On a fresh or unavailable backend, a request that asks for no examples can incur that work or fall back without generating Gremlin. Please bypass initialization when the count is zero. This is source-traced; no live embedding backend was tested.

… guard

- Send graph/graphspace client_config with /rag/graph, validate it on the AI
  side, snapshot the validated connection through the recall flow, and return a
  graph_target attestation; MCP rejects missing or mismatched attestations.
- Preserve the configured graphspace spelling (None stays None) so legacy
  servers do not switch to graphspace-capable paths.
- Scope the SemanticIdQuery graph_vids index by graphspace/server while keeping
  the legacy key for the default target; pass the validated connection through.
- Bound gremlin_tmpl_num and skip example-index initialization when it is zero.
- Use the requested vector-index class in the Text2Gremlin example index.
- Stop capping aggregate recall by max_graph_items; preserve zero thresholds.
- Add tests for binding/attestation, index scoping, zero-example index init,
  template bounds, and graphspace preservation.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Addressed the latest review in head a4ce9b9:

  • gremlin_tmpl_num is now bounded by MAX_LIMIT=500 before it reaches the AI service.
  • _request_graph_connection keeps the configured graphspace spelling; a request gs=DEFAULT against an unset configured graphspace no longer rewrites it to DEFAULT. Added an assertion for the returned graph_target.
  • SemanticIdQuery now scopes its graph_vids index by graphspace/server (graph_<hash>), while keeping the legacy graph_name key for the default target so existing indexes still work.
  • OperatorList.example_index_query(0) bypasses index construction entirely. Added a test.
  • MCP tests: 31 passed; ruff format/check pass on both packages.

The new HugeGraph AI CI run is action_required; could a maintainer approve it?

… guard

- Send graph/graphspace client_config with /rag/graph, validate it on the AI
  side, snapshot the validated connection through the recall flow, and return a
  graph_target attestation; MCP rejects missing or mismatched attestations.
- Preserve the configured graphspace spelling (None stays None) so legacy
  servers do not switch to graphspace-capable paths.
- Scope the SemanticIdQuery graph_vids index by graphspace/server while keeping
  the legacy key for the default target; pass the validated connection through.
- Bound gremlin_tmpl_num and skip example-index initialization when it is zero.
- Use the requested vector-index class in the Text2Gremlin example index.
- Stop capping aggregate recall by max_graph_items; preserve zero thresholds.
- Add tests for binding/attestation, index scoping, zero-example index init,
  template bounds, and graphspace preservation.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@yuangu-chengzi

Copy link
Copy Markdown
Author

Small follow-up on SemanticIdQuery._index_key: cast graphspace/URL to str before normalization so the existing mocked unit tests and legacy values are handled safely. Head is now b52214b; the run needs approval once more.

@bitflicker64 bitflicker64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: yes. Summary: SemanticIdQuery reads the graph_vids index from a graphspace-scoped key that the index builder never writes, so fuzzy vertex matching breaks for every deployment with a non-DEFAULT GRAPH_SPACE. The gremlin_tmpl_num bound, configured-graphspace and zero-example comments are addressed at this head.

user = huge_settings.graph_user
pwd = huge_settings.graph_pwd
graphspace = huge_settings.graph_space
index_key = self._index_key(graph_name, graphspace, url)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: with a non-DEFAULT GRAPH_SPACE, lookup reads <graph>_<hash>/graph_vids, but BuildSemanticIndex, get_graph_index_info and clean_all_graph_index still use graph_name, so _fuzzy_match_vids returns nothing in every GraphRAG flow. Share one key helper with those three paths and fall back to the existing graph_name index so built indexes keep working.

@imbajin imbajin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Score: 5.5/10 · Confidence: high

Blocking: yes

Summary

Recall can return data from a different graph server with identical graph and space names. Existing index issues also break non-default-space fuzzy lookup and allow reuse of a previous server's IDs.

Evidence

The request and response attestation check graph and graphspace only; the semantic lookup key differs from the builder for non-default spaces and remains the bare graph name for the current default-space server.

Validation notes

Source review only; no live multi-server, vector-index, or end-to-end GraphRAG test.

# HugeGraph-AI validates these against its own configured target and
# fails closed on a mismatch, so a recall cannot silently read a
# different graph than the MCP target.
"client_config": {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Validate the graph server identity as well

The request and attestation only compare graph and graphspace. If MCP and the AI service point to different HugeGraph servers that have the same graph and space names, validation succeeds and the tool returns the AI server's data under the MCP target. The README calls out this deployment check, but the tool cannot detect a misconfiguration. Please validate a trusted server identity or explicit expected AI-side endpoint mapping before recall, accounting for network aliases. This is source-traced; I did not test a live two-server deployment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

support MCP for GraphRAG server

3 participants