Repository navigation
feat(mcp): add GraphRAG recall tool - #455
yuangu-chengzi wants to merge 9 commits into
Conversation
1c23465 to
33ce6a8
Compare
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>
33ce6a8 to
d42e761
Compare
imbajin
left a comment
There was a problem hiding this comment.
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 | ||
|
|
There was a problem hiding this comment.
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 ( |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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>
|
Thanks for the review. I pushed a follow-up commit.
|
|
I opened the paired server-side boundary: #456. It adds |
bitflicker64
left a comment
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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>
|
Thanks for the detailed review. Pushed a follow-up that addresses each blocking point:
Local checks: |
|
Pushed the follow-up for the latest review (head |
imbajin
left a comment
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
… 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>
|
Addressed the two new blocking findings in the latest head (
Local: Could a maintainer approve the new |
… 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>
|
One more push for the default-path finding (head
The new |
bitflicker64
left a comment
There was a problem hiding this comment.
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) |
|
|
||
| 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 |
There was a problem hiding this comment.
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>
|
Addressed both new findings in head
The new |
bitflicker64
left a comment
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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": |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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>
|
Addressed the latest review in head
The new |
… 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>
|
Small follow-up on |
bitflicker64
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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": { |
There was a problem hiding this comment.
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.
Summary
Adds a core MCP tool that exposes HugeGraph-AI GraphRAG recall through the existing
hugegraph-mcpserver.graph_rag_query_toolwrapsPOST /rag/graphviahugegraph_ai_client, validates its parameters before the AI call, and returns the upstreamgraph_recallpayload 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
hugegraph_mcp/tools/graph_rag_query.py.graph_rag_query_toolin thecoretoolset inserver.py.graph/graphspaceasclient_configwith each/rag/graphrequest, validate those fields against the AI service's configured target before executing the recall, and propagate the validated connection as a request-scopedgraph_client_configthrough the flow so later nodes do not re-readhuge_settings.SemanticIdQuery, which uses it for both itsPyHugeClientand thegraph_vidsindex name/directory.graph_targetattestation from/rag/graph; MCP fails closed if the attestation is missing (for example, an older AI service) or does not match its configured target.OperatorList.example_index_querynow passes the configured vector-index class and embedding toGremlinExampleIndexQuery, instead of passing the embedding as the vector-index argument.GraphQueryNode.operator_schedulecatch generated-Gremlin failures and still run the subgraph fallback instead of returning early.max_graph_itemsas the aggregate recall cap; the post-materialization guard usesHUGEGRAPH_MCP_MAX_RESULT_ITEMS, becausemax_graph_itemslimits each matched vertex's neighbour query whiletopk_return_resultsbounds the recall.vector_dis_thresholdin the RAG flows instead of replacing it with the configured default.Tests
pytest hugegraph-mcp/tests/test_graph_rag_query.py -q— 30 passed.max_graph_items, and the configured result-item guard.client_config, request-scoped connection propagation into the recall flow, thegraph_targetresponse, zero distance thresholds, and the example-index wiring.GraphQueryNode.node_initcoverage proving a request-scoped connection is used instead of global settings, a generation-failure fallback test, and an integration-style test that drives the realOperatorListpath to Gremlin execution.ruff format --checkandruff checkpass on both packages.fastmcpand AI service dependencies are unavailable in this Windows environment.Notes
HUGEGRAPH_MCP_ALLOW_AI=trueand a reachable HugeGraph-AI service.graph_rag_query_toolis fail-closed behindHUGEGRAPH_MCP_AI_GRAPH_READONLY=true: the operator must assert that HugeGraph-AI uses a read-only HugeGraph principal, because/rag/graphexecutes model-generated Gremlin inside the AI service.MAX_LIMIT=500and are capped byHUGEGRAPH_MCP_MAX_RESULT_ITEMS;graph_recallpasses through_gremlin_output_guard_error.vector_dis_thresholdaccepts any finite non-negative value (including backend-specific values above 1), and zero is forwarded unchanged./ragendpoint is intentionally out of scope; it can be added in a follow-up.🤖 Generated with Claude Code