# Graph tool reference

The tool layer for graph-driven analysis: 72 Graph Engine catalog tools and 3 MCP session-management interfaces, covering data preparation, structural analysis, machine learning, and result presentation, with parameters, outputs, and calling constraints.

## Calling contract

These tools turn analysis questions into graph computations. The agent first establishes the business meaning of nodes, edges, attributes, and weights in the current graph, then selects operations such as queries, paths, communities, centrality, or graph learning. Returned structures and values support interpretation. A task can combine tool categories as evidence emerges; the question and available data determine the calls. Skills organize the workflow, while Graph Engine performs graph computation.

Tools use fixed English names and JSON arguments. This page documents 72 general-purpose tools and separately lists 3 MCP session-management interfaces; use runtime MCP discovery for additional case-specific tools. Parameter names and enums do not change with the UI language. Reporting tools can be disabled by deployment configuration.

| Interface | Request and response |
| --- | --- |
| MCP tool call | tools/call receives params {name, arguments}. An established MCP connection and execution context supply user, session and run identity; response text contains the JSON result. |
| Graph Engine HTTP | POST /sessions/{session_id}/tools/{tool_name} with body {"arguments":{...}}. This service-to-service interface carries service credentials and user/session identity; controlled runs also carry execution generation and operation ID. |
| Graph and dataset versions | graph_version identifies the active session graph; revision identifies a saved construction result. load_constructed_graph brings a saved result into a session; the numbers need not match. |
| Background work | Retain job_id when async=true and inspect get_job_status. Ordinary final output is job.result; large-graph get_job_result returns summary, preview and artifact_id. After a terminal state, still check the business result. |

The separate construction agent has 11 private tool names across its construction stages: inspect_schema, set_workload, evaluate_queries, optimize_graph, connect_columns, generate_entity_table, unfold_multi_category, add_primary_key, remove_primary_key, materialize_join and finish. They run inside isolated construction tasks and are not part of the Graph Engine catalog tools on this page.

The main agent uses the six public construction tools at the end of this page to inspect capabilities, read results, load an active graph, and preview or commit requested edits. Private optimize_graph transforms construction candidates; public preview_graph_optimization/commit_graph_optimization edits saved graphs. They have different execution and validation contexts.

- success=false indicates a tool-level failure; also handle HTTP errors and unmet data, model or version requirements. An empty preview, queued submission or missing model is not a successful analysis.
- Numeric limit is generally capped at 200. Defaults are 10 paths, 20 list items and 5 communities/components. Send only schema-declared parameters. all expands output; still inspect truncated and scope fields.
- Dotted names show nested paths, such as train_config.epochs; actual JSON should use {"train_config":{"epochs":200}}.

- [Graph algorithms and interpretation](/en/graph-algorithms/): Review meanings, preconditions, and worked numerical examples.
- [Graph machine learning](/en/graph-ml/): Explore data structures, training implementation, losses, and inference examples.

The default 72 comprise 60 graph/system tools, 6 public construction tools, 5 graph-learning tools and 1 reporting tool; disabling reports removes one. Runtime skill, user-memory, learned-knowledge and workspace tools are registered separately. This reference is checked against catalogs and implementation, not a claim that every algorithm and parameter combination has been executed.

Examples calling Graph Engine or MCP directly use internal service interfaces and still require the service key plus workspace / session context. Internal X-User-ID must match user_id returned by GET /api/workspace; it is the fixed workspace owner, not a browser-selectable login identity. Browser calls to Backend public /api/* endpoints do not require this header.

## Data ingestion, datasets and versions

Distinguish the input format and storage location first. Edge lists, triples, and uploaded files can populate the session graph; registry datasets and constructed datasets have separate loading interfaces. Loading, clearing, undirecting, and switching versions change the graph used by later analysis, so verify get_graph_info and graph_version afterward.

### Load graph · load_graph

Load a weighted or unweighted edge list into the active session. Each line is src dst [weight]; replace the graph or append ordinary graph data.

- `edge_text` (string, required): Edge-list text with source, target and an optional numeric weight on each line.
- `append` (boolean): false replaces the active graph; true appends ordinary graph data. Append is unsupported when either side is a constructed property graph. Default: false

Returns: Returns load status, graph_version and graph counts. Use get_graph_info for the structural summary.

- Replacement and append change the active graph. Constructed property graphs do not support append; UNSUPPORTED_PROPERTY_GRAPH_APPEND preserves the existing graph.

### Load graph from upload · load_graph_from_upload

Read a registered graph upload and detect NPZ, PT or graph_data.v1 JSON. Multi-graph PT files are automatically routed to classification-dataset loading.

- `filename` (string, required): Filename of an upload already registered in this session.
- `append` (boolean): false replaces the active graph; true appends ordinary graph data. Append is unsupported when either side is a constructed property graph. Default: false
- `directed` (boolean): Direction parameter for detected text formats, default true; inspect the loaded structural graph for its actual direction. Default: true

Returns: Direct loads return format, status and graph version. Background loads return async, job_id and status; get_job_status exposes the completed result under job.result.

- For .sql, .csv and .txt, MCP returns CONSTRUCTION_REQUIRED and directs construction through the dataset panel. Other engine file paths can detect edge lists, triples or prose; that does not replace the dataset-construction entry point.
- Prose, multi-graph datasets and some Nebula imports become background work; queued does not mean the graph is already loaded.

### Load graph from text · load_graph_from_text

Extract entities and relations from inline text or an uploaded file through an asynchronous text-to-graph job. extraction_goal can narrow the entities and relations to extract.

- `text` (string): Inline text to extract from; provide either text or filename.
- `filename` (string): Uploaded text filename, read directly by the tool; provide either filename or text.
- `directed` (boolean): Whether to create a directed graph. Default: true
- `append` (boolean): false replaces the active graph; true appends ordinary graph data. Append is unsupported when either side is a constructed property graph. Default: false
- `extraction_goal` (string): Scope for extraction, such as keeping only companies, people and employment relations.

Returns: Returns async=true, job_id and queued status. The final job result contains extraction and graph-loading information.

- This entry point performs text-relation extraction. Skill-based dataset construction is handled by a separate construction agent with query validation and representation evolution.

### Load graph from triples · load_graph_from_triples

Convert explicit source–relation–target triples into a graph, with optional confidence, evidence text and source chunk IDs.

- `triples` (array, required): Array of triples. Each requires source, relation and target, and may include confidence, evidence and chunk_id.
- `directed` (boolean): Whether to create a directed graph. Default: true
- `append` (boolean): false replaces the active graph; true appends ordinary graph data. Append is unsupported when either side is a constructed property graph. Default: false

Returns: Returns load status, graph version and counts. Relations and supplied evidence metadata are included in graph creation.

- relation is stored as edge_type, evidence as edge_text, and confidence as edge_feat. Triple count need not equal final edge-entry count.

### Clear graph · clear_graph

Clear the session's active graph and update its graph-version state.



Returns: Returns success, graph_version and the cleared graph state.



### To undirected · to_undirected

Convert the active graph to an undirected graph and publish the converted version.



Returns: Returns conversion status, graph version, node and edge counts, and direction information.

- Changing direction affects path, in/out-degree and edge-count semantics; inspect get_graph_info after conversion.

### List datasets · list_datasets

List datasets accessible to the current user and session for loading or selecting constructed graphs.



Returns: Returns datasets with identifiers, versions and storage information. Construction datasets are filtered by access scope.



### Load dataset · load_dataset

Load a saved dataset version into the active graph. version=latest selects the latest saved version.

- `dataset_id` (string, required): An accessible dataset ID obtained from the dataset list or session data state.
- `version` (string): A saved dataset-version identifier; latest selects the most recent version. Default: "latest"

Returns: Returns dataset_id, dataset_version, graph version and counts. Use load_constructed_graph for construction datasets.

- Use load_constructed_graph for construction datasets. Ordinary loading can return USE_CONSTRUCTED_GRAPH_LOADER to direct you to the correct session-binding update.

### Save as dataset · save_as_dataset

Save the active graph as a reusable dataset and update the session's dataset binding.

- `name` (string, required): Name for the new dataset.
- `description` (string): Purpose or context saved in the dataset metadata.

Returns: Returns dataset metadata, including identifier, name, versions and user or global scope.



### Undo graph · undo_graph

Restore a previous available graph state to undo an earlier graph change.



Returns: Returns restoration status and the active graph_version, or an explanation when no prior state is available.



### List graph versions · list_graph_versions

List graph versions available in the session for switching between full graphs, subgraphs and earlier states.



Returns: Each entry includes graph_version, description, creation time, node and edge counts, and a current flag.



### Load graph version · load_graph_version

Switch the session to a version returned by list_graph_versions.

- `graph_version` (integer, required): Target graph-version number returned by list_graph_versions.

Returns: Returns switch status, the active graph_version, and node and edge counts.



### Discard graph version · discard_graph_version

Delete a session graph version, switching to an available fallback before deleting the active version. Used for version cleanup and removal of temporary derived graphs.

- `graph_version` (integer, required): Actual graph-version number to delete.
- `fallback_graph_version` (integer): Loaded historical version to activate before deleting the active version. If omitted or unavailable, an earlier usable version is tried; deletion fails if none exists.

Returns: Returns discarded_graph_version, the active graph_version and graph counts. Fails when the version or a usable fallback does not exist.

- Marked internal in the catalog, but still discoverable through the native MCP toolkit. It deletes history; use load_graph_version for ordinary switching.

## Partitioned large graphs and artifacts

Prepare a partitioned version, wait for publication, inspect capabilities and submit computation. Summaries and previews remain bounded; downloadable artifacts contain full or bounded materialized output. Ordinary active graphs and partitioned representations are not interchangeable.

### Prepare large-graph snapshot · prepare_large_graph

Stream a registered edge-list or triples file into a versioned partitioned snapshot through a persistent background job.

- `filename` (string, required): Upload filename already registered in the current session; content must match input_format.
- `graph_id` (string): Logical graph ID, defaulting to the current session_id when omitted.
- `graph_version` (integer): Optional new version of at least 1; cannot overwrite an occupied version. Omission lets the service allocate a version and validate binding with ordinary-graph versions.
- `input_format` (string): edgelist for edge lists or triples for relation triples; default edgelist. Options: edgelist, triples Default: "edgelist"
- `delimiter` (string): auto detection, whitespace, comma, tab or a single-character delimiter. Default: "auto"
- `directed` (boolean): Whether to use directed semantics; default true. Default: true
- `partitions` (integer): Partition count, 1–128; omission uses service configuration and available resources.
- `workers` (integer): Requested worker count, at least 1; partitions, CPU count and resource admission constrain actual concurrency.
- `quality_policy` (object): Explicit node normalization, edge identity, weight-conflict, self-loop and invalid-record policy. Omitting the object can differ from passing an empty object; see notes.
- `quality_policy.node_normalization` (string): exact preserves names; nfkc_casefold applies Unicode NFKC normalization and case folding. Options: nfkc_casefold, exact
- `quality_policy.edge_key` (string): endpoints identifies logical edges by endpoints; endpoints_relation preserves parallel relation types, which current classical algorithms reject. Options: endpoints, endpoints_relation Default: "endpoints"
- `quality_policy.weight_conflict` (string): Use first/last/max/min weight for duplicate logical edges, or reject. Options: first, last, max, min, reject
- `quality_policy.self_loops` (string): Allow, skip or reject self-loops. Options: allow, skip, reject
- `quality_policy.invalid_records` (string): Skip or reject invalid records. Options: skip, reject

Returns: Submission returns async=true, job_id, graph_id and graph_version. Completed output includes quality summaries, counts, representation=partitioned_snapshot and current_graph_replaced=false.

- No full GraphData or NetworkX graph is constructed first; a running large-graph worker and sufficient resources are required. Omitting quality_policy uses exact node spelling and last duplicate weight for edgelist, but nfkc_casefold and maximum weight for triples. An empty policy object uses the policy-class defaults and is not equivalent to omission.

### Run large-graph algorithm · run_large_graph_algorithm

Submit an algorithm against a published partitioned snapshot. Check runtime capabilities; matching names do not establish equivalence to ordinary-graph algorithms.

- `graph_id` (string): Logical graph ID, defaulting to the current session_id when omitted.
- `graph_version` (integer, required): Published partitioned-snapshot version, at least 1. Preparation can reserve a new version but cannot overwrite an occupied version.
- `algorithm` (string, required): Select a large-graph operation; put submethods and metrics in parameters and inspect capabilities for semantics and resource constraints first. Options: degree, in_degree, out_degree, degree_centrality, shortest_path, all_shortest_paths, maximum_flow, minimum_cut, global_minimum_cut, minimum_spanning_tree, community_detection, node_centrality, graph_connectivity, find_cycles, maximum_cycle, topological_sort, degree_analysis, subgraph_extraction, link_prediction_score, path_analysis, clique_analysis, reachability, global_metrics, graph_structure_analysis, connectivity_analysis, tree_dag_analysis, matching_coloring_analysis, distance_measures
- `parameters` (object): Algorithm-specific endpoints, method/metric, preview and resource options. Send dotted parameters as nested JSON. Observe the conditional requirements below rather than mixing selectors across algorithms.
- `workers` (integer): Requested worker count, at least 1; partitions, CPU count and resource admission constrain actual concurrency.
- `parameters.source` (string): Source node, paired with target or flow/cut sink.
- `parameters.target` (string): Target node; shortest_path accepts all to generate a source-distance artifact.
- `parameters.sink` (string): Sink for maximum_flow/minimum_cut.
- `parameters.algorithm` (string): Path submode default/yen_k_shortest, or one of the community names; all community names currently map to weighted synchronous label propagation. Options: default, yen_k_shortest, louvain, greedy_modularity, label_propagation, label_propagation_asyn, leiden, girvan_newman, asyn_fluidc
- `parameters.centrality_type` (string): Centrality metric; some methods use sampling or labeled approximations. Inspect capabilities first. Options: degree, betweenness, closeness, pagerank, eigenvector, harmonic, katz, load, voterank, percolation Default: "degree"
- `parameters.method` (string): Submethod belonging to the top-level algorithm; do not mix families. Options: ego_graph, k_core, k_truss, k_corona, node_subset, jaccard, adamic_adar, resource_allocation, preferential_attachment, all_simple_paths, has_path, average_shortest_path_length, find_cliques, clique_number, number_of_cliques, transitive_closure, descendants, ancestors, is_tree, is_forest, is_directed_acyclic_graph, bfs_tree, dfs_tree, lexicographical_topological_sort, all_topological_sorts, is_at_free, check_planarity, is_tournament, score_sequence, is_bipartite, weisfeiler_lehman_graph_hash, node_connectivity, edge_connectivity, minimum_node_cut, minimum_edge_cut, articulation_points, bridges, local_bridges, biconnected_component_edges, bridge_components, condensation, maximum_spanning_tree, random_spanning_tree, lowest_common_ancestor, immediate_dominators, dominance_frontiers, dag_longest_path, dag_longest_path_length, antichains, is_aperiodic, colliders, v_structures, max_weight_matching, min_weight_matching, maximal_matching, min_edge_cover, is_matching, greedy_color, equitable_color
- `parameters.metric` (string): Metric selector for global_metrics/distance_measures. Options: density, diameter, radius, transitivity, average_clustering, degree_assortativity, center, periphery, eccentricity, wiener_index, global_efficiency, local_efficiency, average_neighbor_degree, average_degree_connectivity, rich_club_coefficient, reciprocity, flow_hierarchy, barycenter, estrada_index, girth
- `parameters.node` (string): Required node for ego_graph and descendants/ancestors; optional selected node for number_of_cliques.
- `parameters.nodes` (array): Node names for node_subset; runtime default maximum 10,000, possibly tightened by deployment.
- `parameters.focus_nodes` (array): Node names whose community membership is requested from this run, at most 200.
- `parameters.k` (integer): Yen path count 1–200 (default 3), or ego radius and core/truss/corona threshold (default 2).
- `parameters.cutoff` (integer): all_simple_paths maximum edge count, 1–10,000; default 5. Default: 5
- `parameters.limit` (integer | string): Preview count 1–200; all still maps to the hard cap of 200. Consult artifacts and their scope for complete output.
- `parameters.top_k` (integer | string): Top degree/link-prediction items, 1–200; all remains 200. Omission defaults to 20/10 respectively.
- `parameters.max_cycles` (integer): Maximum cycle candidates, 1–100,000; default 10,000. Default: 10000
- `parameters.optimize_by` (string): Select the best searched cycle by length or total weight. Options: length, weight Default: "length"
- `parameters.treat_as_undirected` (boolean): Whether global_minimum_cut projects directed input to an undirected graph. Default: true
- `parameters.max_iterations` (integer): Iteration limit, schema range 1–2,000; communities allow at most 500, default 5. Default: 5
- `parameters.sample_sources` (integer): Sample sources for Brandes-type centrality, at most 10,000. Below the node count, output is approximate; allow_expensive does not bypass the deployment cap.
- `parameters.damping` (number): PageRank damping, finite and strictly between 0 and 1. Default: 0.85
- `parameters.alpha` (number): Finite Katz attenuation, default 0.1. Default: 0.1
- `parameters.beta` (number): Finite Katz exogenous bias, default 1. Default: 1
- `parameters.tolerance` (number): Finite positive convergence tolerance for iterative centralities. Default: 0.000001
- `parameters.use_weight` (boolean): Use weights for shortest_path. all_shortest_paths always uses weights; other algorithms ignore this parameter. Default: true
- `parameters.create_version` (boolean): Subgraph extraction publishes a partitioned version by default; explicitly use new_graph_version afterward. It does not replace the ordinary active graph. false produces only an artifact. Default: true
- `parameters.allow_expensive` (boolean): Allow some quadratic/exponential admission thresholds, without removing hard memory or sampling limits. Default: false
- `parameters.strict_semantics` (boolean): Reject approximate semantic mappings; does not fall back to full NetworkX computation. Default: false

Returns: Returns an asynchronous job handle. Read summary, preview and artifact_id with get_job_result after completion. Capabilities and output identify exact, approximate, bounded or mixed semantics; full materializable output is stored as artifacts.

- Paths require source/target, flow/cuts source/sink, method families method, and metric families metric. LCA additionally needs node1/node2, dominators source, and equitable coloring num_colors. The parameter object allows extension fields, but runtime validates them per algorithm and explicitly rejects unsupported modes or insufficient resources.

### List large-graph versions · list_large_graph_versions

List partitioned versions of a logical graph in the current user/session scope.

- `graph_id` (string): Logical graph ID, defaulting to the current session_id when omitted.

Returns: Returns success, graph_id and versions, including preparation/publication status and quality summaries.

- Algorithms require a published version. This list differs from ordinary active-graph history returned by list_graph_versions; matching numbers alone do not establish a shared source.

### Get large-graph artifact · get_large_graph_artifact

Read artifact metadata and an optional bounded preview without loading full partition results into model context.

- `artifact_id` (string, required): Artifact ID returned by a job, owned by the current user and session.
- `include_preview` (boolean): Include a bounded result preview, default true; never loads the full partition files. Default: true

Returns: Returns success, artifact and download_url_template. artifact includes the file count, bounded path/download-index preview and full index range.

- The {partition} in download_url_template is the download index in a flat output-file list, not necessarily the input partition number. Download each file through Backend at /api/sessions/{session_id}/large-graph/artifacts/{artifact_id}/partitions/{partition}; workspace, session, and file-scope checks remain, without browser sign-in.

### Get large-graph capabilities · get_large_graph_capabilities

Read operations, submodes, semantics and resource constraints supported by the current large-graph engine.



Returns: Returns success and capabilities, including engine version, exact/approximate/bounded semantics, complexity, parallel strategy and result types.

- The catalog describes implementation contracts and prerequisites, not successful execution of every method on the current data. Community names currently map to weighted synchronous label propagation, and some centralities use sampling or approximations. For strict comparisons, set strict_semantics and inspect actual output.

## Graph inspection and entity search

Start with get_graph_info to establish size and direction, then inspect structures using exact names or IDs. Natural-language retrieval narrows candidates; the top score does not automatically confirm identity. Parallel relationships can share endpoints, so use the saved attributed graph and relationship IDs for a complete relationship audit.

### Get graph info · get_graph_info

Inspect the active graph's size, direction, structural representation, attributes and learning readiness before analysis.



Returns: Returns a graph summary, node and edge previews, num_edge_entries, num_unique_edges, semantic_type, storage_type, and label, feature and GraphML-readiness information.

- num_edge_entries counts stored entries, while num_unique_edges counts deduplicated logical edges. Interpret undirected bidirectional storage according to its graph semantics.

### Get node info · get_node_info

Inspect local structure and attributes using an exact node name or string ID.

- `node_name` (string, required): Exact node name or a node ID represented as a string.

Returns: Returns degree, in-degree, out-degree, neighbors, predecessors, incident edges, labels and types, plus text when present. Lists are bounded previews.

- Use search_node for descriptive queries, then call this tool with an exact name.

### Get edge info · get_edge_info

Inspect directed relationships and attributes between exact endpoints. Parallel relationships can produce multiple records.

- `src_name` (string, required): Exact name of the relationship's source node.
- `dst_name` (string, required): Exact name of the relationship's target node.

Returns: Returns existence, weights, relationship names, labels and types, with preview and truncation information for multiple relationships.

- Distinguish parallel relationships using returned relationship IDs; an endpoint pair does not imply a single relationship.

### Check edge exists · check_edge_exists

Check whether an edge exists from an exact source to an exact target before further analysis.

- `src_name` (string, required): Exact name of the relationship's source node.
- `dst_name` (string, required): Exact name of the relationship's target node.

Returns: Returns status fields including exists and directed.



### Get neighbors · get_neighbors

Query one-hop neighbors through a unified interface: GraphData locally, or native traversal with Nebula primary storage.

- `node_name` (string, required): Exact node name or a node ID represented as a string.
- `direction` (string): out follows outgoing edges, in follows incoming edges, and both traverses both directions; support depends on the tool and storage backend. Options: out, in, both Default: "out"
- `limit` (integer): One-hop neighbor limit, restricted to 1–200 by the server; all is not accepted. Default: 20

Returns: Returns neighbors for the requested direction and traversal metadata, bounded by limit.

- Nebula handles direction in the native query; the result covers only one hop.

### Search node · search_node

Find nodes by name, text, type, label and degree constraints, resolving natural-language descriptions to exact names usable by other tools.

- `query` (string, required): Natural-language description, name or text passage to search for.
- `top_k` (integer): Candidate node count, defaulting to 8 and restricted to 1–50. Default: 8
- `filters` (object): Node constraints: node_type, label, and min/max bounds on total, in- or out-degree.
- `sort` (object): Sort object: field may be score, node_id, degree, num_neighbors, in_degree, out_degree, or total_degree; order is asc or desc.
- `rerank` (boolean): Reranking flag reported in the retrieval response; no separate reranking model is currently invoked. Default: true

Returns: Returns best, candidates, ambiguous, semantic_enabled and retrieval_mode. Candidates contain exact node_name values and matching evidence.

- Resolve candidates when ambiguous=true. Without an embedding provider, exact names and valid node IDs can still match; other text queries receive no lexical-similarity score, so structural filters and sorting primarily determine candidates. Inspect semantic_enabled and retrieval_mode.
- Entity semantic search depends on Graph Engine’s own embedding configuration. EMBEDDING_PROVIDER explicitly selects sentence-transformers, openai or lexical. Automatic selection first tries local Sentence Transformers, requiring its dependency and model weights, then OpenAI when OPENAI_API_KEY is set, and otherwise lexical hashing. The current OpenAI branch calls the fixed api.openai.com/v1/embeddings endpoint; Agent Runtime chat-model or EMBEDDING_BASE_URL settings do not override it. Lexical mode does not provide semantic ranking for entities. Index-encoding failures also disable semantic search; inspect semantic_enabled and retrieval errors. Explicit openai selection requires OPENAI_API_KEY; failure to initialize a forced provider does not run the automatic selection sequence. Initial entity indexing encodes node and edge documents for the entire graph, so remote reachability, latency and quota also affect availability.

### Search edge · search_edge

Find relationships by description, edge text, attributes or endpoint descriptions, optionally constraining both endpoints.

- `query` (string): Natural-language description, name or text passage to search for.
- `src_query` (string): Constrain the source node by name or natural-language description.
- `dst_query` (string): Constrain the target node by name or natural-language description.
- `top_k` (integer): Candidate relationship count, defaulting to 8 and restricted to 1–50. Default: 8
- `filters` (object): Relationship constraints: edge_type, label, min_weight and max_weight.
- `sort` (object): Sort object: field is score, edge_idx or weight; order is asc or desc.
- `rerank` (boolean): Reranking flag reported in the retrieval response; no separate reranking model is currently invoked. Default: true

Returns: Returns best, candidates, ambiguous and retrieval mode; candidates include exact endpoints and relationship information.

- Provide at least one of query, src_query or dst_query. Resolve relationship or endpoint candidates when ambiguous=true.
- Exact endpoints resolve only the last relationship, not every parallel relationship. Use actual edge_id values in the saved attributed graph to inspect individual relationships.
- Semantic queries use the same Graph Engine embedding provider as search_node. Without an available provider, rely on exact resolution, structural filters and sorting; rerank does not invoke a separate reranking model.

## Paths and reachability

Specify whether shortest means fewest hops or minimum total weight. all_shortest_paths enumerates tied optima; yen_k_shortest returns cost-ranked alternative simple paths. Reachability also depends on direction and remote query scope, so inspect scope fields before interpreting an absent path.

### Shortest path · shortest_path

Compute a minimum-cost or minimum-hop path. default returns one shortest path; yen_k_shortest returns the first k simple paths ordered by cost. target=all summarizes single-source reachability.

- `source` (string, required): Exact source-node name.
- `target` (string, required): Target node; the special value all returns distance statistics and nearest-path previews for all reachable nodes.
- `use_weight` (boolean): true treats edge weights as distances or costs; false minimizes hop count. Default: true
- `algorithm` (string): default returns one shortest path; yen_k_shortest returns the first k distinct simple paths. Options: default, yen_k_shortest Default: "default"
- `k` (integer): Used only by yen_k_shortest: number of candidate simple paths, defaulting to 3 and at least 1. Default: 3
- `direction` (string): Applies only with Nebula primary storage and use_weight=false; local shortest paths follow the active graph's direction. Options: out, in, both Default: "out"
- `max_steps` (integer): Maximum hops for a native Nebula query or bounded materialization, restricted to 1–20 by the server. Default: 10

Returns: A single-path result contains found, path, hop_count, total_length, edges and weighted. K-path mode returns paths; all-target mode returns reachable_count, distance statistics and nearest_paths.

- Weights represent distance or cost here. For multigraphs, a private calculation view uses the minimum weight per endpoint pair without deleting stored relationships.

### All shortest paths · all_shortest_paths

Enumerate equal-cost shortest paths between two nodes to check whether the optimal route is unique.

- `source` (string, required): Exact source-node name.
- `target` (string, required): Exact target-node name.
- `direction` (string): out follows outgoing edges, in follows incoming edges, and both traverses both directions; support depends on the tool and storage backend. Options: out, in, both Default: "out"
- `max_steps` (integer): Maximum hops for a native Nebula query or bounded materialization, restricted to 1–20 by the server. Default: 10
- `max_nodes` (integer): Node cap for bounded Nebula subgraph materialization.
- `max_edges` (integer): Edge cap for bounded Nebula subgraph materialization.

Returns: Returns length, paths, count_returned and truncated, showing up to 10 paths by default. paths is empty when no path exists.

- This tool returns equal-cost optimal paths; yen_k_shortest can include more expensive alternatives. The public schema has no limit parameter and defaults to 10 results.

### Path analysis · path_analysis

Check reachability, enumerate simple paths, or calculate average shortest-path length using method.

- `method` (string, required): all_simple_paths enumerates simple paths; has_path checks reachability; average_shortest_path_length calculates average weighted shortest distance. Options: all_simple_paths, has_path, average_shortest_path_length
- `source` (string): Required for all_simple_paths and has_path; unnecessary for average shortest-path mode.
- `target` (string): Required for all_simple_paths and has_path; unnecessary for average shortest-path mode.
- `cutoff` (integer): Maximum number of edges in all_simple_paths; defaults to 5 and is treated as at least 1. Default: 5
- `direction` (string): out follows outgoing edges, in follows incoming edges, and both traverses both directions; support depends on the tool and storage backend. Options: out, in, both Default: "out"
- `max_steps` (integer): Maximum hops for a native Nebula query or bounded materialization, restricted to 1–20 by the server. Default: 10
- `max_nodes` (integer): Node cap for bounded Nebula subgraph materialization.
- `max_edges` (integer): Edge cap for bounded Nebula subgraph materialization.
- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 10

Returns: Depending on the mode, returns has_path, paths/count/truncated, or an average-distance result. Bounded Nebula analysis includes scope metadata.

- Average shortest paths use weights. Directed input must be strongly connected or the call fails; disconnected undirected input uses its largest component. The result does not establish reachability across other components.

### Reachability · reachability

Find reachable descendants or ancestors of a node, or generate a preview of the transitive closure.

- `method` (string, required): transitive_closure generates closure edges; descendants finds reachable descendants; ancestors finds reachable ancestors. Options: transitive_closure, descendants, ancestors
- `node` (string): Required for descendants and ancestors; unnecessary for transitive_closure.
- `max_steps` (integer): Maximum hops for a native Nebula query or bounded materialization, restricted to 1–20 by the server. Default: 10
- `max_nodes` (integer): Node cap for bounded Nebula subgraph materialization.
- `max_edges` (integer): Edge cap for bounded Nebula subgraph materialization.
- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 20

Returns: Returns node or closure-edge previews, counts and truncation flags. Incomplete closure enumeration reports num_edges_at_least.

- Nebula queries are bounded by max_steps, max_nodes and max_edges. Absence within that scope does not prove unreachability across the entire graph.

## Flow, cuts and spanning trees

Flow interprets weights as capacities, cuts measure the capacity removed to separate a network, and spanning trees minimize the cost of connecting nodes. These objectives differ. Flow sums parallel capacities; spanning-tree computation uses its defined projection without mutating source relationships.

### Maximum flow · maximum_flow

Interpret edge weights as capacities and compute the maximum total flow from source to sink.

- `source` (string, required): Exact source-node name.
- `sink` (string, required): Exact sink-node name.

Returns: Returns max_flow_value, total_nonzero_edges, top_flow_edges and truncated.

- weight acts as capacity, with parallel capacities summed. Cost weights do not automatically represent throughput capacity.

### Minimum cut · minimum_cut

Find a minimum-capacity cut separating a source and sink to identify network bottlenecks.

- `source` (string, required): Exact source-node name.
- `sink` (string, required): Exact sink-node name.

Returns: Returns min_cut_value, partition sizes, and previews of the smaller partition and cut edges.

- Source–sink cuts use capacity semantics; parallel relationships are summed by capacity in the calculation view.

### Global minimum cut · global_minimum_cut

Find a global minimum cut in an undirected weighted graph without specifying endpoints. Directed input can be treated as undirected.

- `treat_as_undirected` (boolean): Allow directed input to be treated as undirected and weighted. Directed global minimum cut is unsupported when false. Default: true
- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 20

Returns: Returns min_cut_value, algorithm, partition sizes, cut-edge previews and disconnected. Disconnected graphs have a cut value of 0.

- Directed input is rejected when treat_as_undirected=false. Use minimum_cut for a source–sink problem that retains direction.

### Minimum spanning tree · minimum_spanning_tree

Find a minimum-weight connecting structure on an undirected calculation view. Disconnected input produces a minimum spanning forest summary.



Returns: Connected input returns total_weight, num_edges and mst_edges_preview. Disconnected input returns num_components and forest_summary.

- Uses an undirected view, selecting minimum-weight relationships per pair for property multigraphs. A forest summary is not a complete edge list.

## Connectivity, cycles, topology and cliques

Components describe connectivity, cycles reveal circular dependencies, and topological ordering requires a DAG. Clique analysis distinguishes an inclusion-maximal clique from a largest maximum clique. Cycle and clique enumeration can be expensive; a display limit is not proof of exhaustive search.

### Graph connectivity · graph_connectivity

Analyze strong and weak connectivity in directed graphs, or connected components in undirected graphs.

- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 5

Returns: Returns connectivity flags, component counts, sizes and node previews. Defaults to 5 components with 10 preview nodes each.



### Find cycles · find_cycles

Enumerate simple cycles to inspect feedback loops, cyclic dependencies and closed structures.

- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 20

Returns: Returns cycles, truncated and total_cycles_at_least. With truncation, the count is a confirmed lower bound.

- Simple cycles can grow exponentially in number. limit=all removes the preview enumeration bound; when truncated=true, returned count is not the total cycle count.

### Maximum cycle · maximum_cycle

Search a bounded enumeration of simple cycles for the longest or highest-weight cycle, reporting whether the search was exhaustive.

- `optimize_by` (string): length prioritizes the cycle with most nodes; weight prioritizes the greatest total edge weight. Options: length, weight Default: "length"
- `max_cycles` (integer): Maximum simple cycles examined, defaulting to 10000 and restricted to 1–100000 by the server. Default: 10000

Returns: Returns cycle, cycle_length, cycle_weight, edges, cycles_examined, search_exhausted and truncated.

- Longest simple cycle is a costly combinatorial problem. search_exhausted=false guarantees only the best examined candidate; multigraphs are unsupported.

### Topological sort · topological_sort

Generate a topological order satisfying dependency precedence in a directed acyclic graph.

- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 20

Returns: Returns a topological-order preview, total node count and truncated. Cyclic input cannot produce a valid topological order.

- Topological order may be non-unique; a preview is a prefix of one valid order, not a complete execution plan.

### Clique analysis · clique_analysis

On an undirected view, enumerate maximal cliques, find the maximum clique size, or count maximal-clique participation per node.

- `method` (string, required): find_cliques enumerates maximal cliques; clique_number finds the maximum size; number_of_cliques counts maximal-clique participation. Options: find_cliques, clique_number, number_of_cliques
- `node` (string): Used only by number_of_cliques; omit for a preview of counts across nodes.
- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 20

Returns: find_cliques returns clique previews and a count lower bound; clique_number returns the maximum size; number_of_cliques returns participation counts.

- A maximal clique cannot be enlarged; a maximum clique has the greatest size among all cliques. Enumeration can be exponential, and multigraphs are unsupported.

### Graph structure and traversal · graph_structure_analysis

Check tree, forest, DAG, bipartite, planar and tournament structure, or return traversal trees, topological orders and WL hashes.

- `method` (string, required): Select a supported method; prerequisites and additional required parameters depend on the method. Options: is_tree, is_forest, is_directed_acyclic_graph, bfs_tree, dfs_tree, lexicographical_topological_sort, all_topological_sorts, is_at_free, check_planarity, is_tournament, score_sequence, is_bipartite, weisfeiler_lehman_graph_hash
- `source` (string): Actual source-node name required for BFS/DFS traversal.
- `depth_limit` (integer): Maximum BFS/DFS traversal depth, an integer of at least 0.
- `iterations` (integer): Weisfeiler–Lehman hash iterations, at least 1; default 3. Default: 3
- `limit` (integer | string): List previews default to 20; positive integer limits are capped at 200. all can expand ordinary lists, but topological-order, antichain and collider/v-structure enumeration retains a hard cap of 200. Default: 20

Returns: Returns method-specific value, is_planar, hash, score_sequence, order/orders or traversal-tree edges_preview, with applicable totals and truncation. Does not change the active graph.

- Tree/forest, AT-free, bipartite and planarity checks use an undirected view. BFS/DFS require source; topological ordering requires a DAG. score_sequence checks tournament-score-sequence conditions, not whether the input itself is a tournament. Equal WL hashes do not prove isomorphism.
- The ordinary-graph entry rejects multigraphs with UNSUPPORTED_MULTIGRAPH_OPERATION; the corresponding large-graph operation has separate capability constraints.

### Connectivity, cuts and bridges · connectivity_analysis

Compute node/edge connectivity, minimum node/edge cuts, articulation points, bridges, local bridges, biconnected/bridge components and SCC condensation.

- `method` (string, required): Select a supported method; prerequisites and additional required parameters depend on the method. Options: node_connectivity, edge_connectivity, minimum_node_cut, minimum_edge_cut, articulation_points, bridges, local_bridges, biconnected_component_edges, bridge_components, condensation
- `source` (string): Source for local node/edge connectivity or cuts; provide with target, or omit both for the global operation.
- `target` (string): Actual target-node name, supplied together with source for local connectivity and cuts.
- `limit` (integer | string): List previews default to 20; positive integer limits are capped at 200. all can expand ordinary lists, but topological-order, antichain and collider/v-structure enumeration retains a hard cap of 200. Default: 20

Returns: Returns method-specific value, nodes, items, components or condensation nodes/edges; size/count and truncated describe totals and list scope.

- Provide source and target together for local connectivity/cuts. Connectivity, cuts, articulation, bridge and biconnected methods use an undirected view; condensation requires a directed graph. Global node/edge cuts require nonempty connected input and differ from capacity-weighted minimum_cut.
- The ordinary-graph entry rejects multigraphs with UNSUPPORTED_MULTIGRAPH_OPERATION; the corresponding large-graph operation has separate capability constraints.

### Trees, DAGs and dominators · tree_dag_analysis

Query maximum/random spanning trees, lowest common ancestors, dominators, DAG longest paths, antichains, aperiodicity and collider structures.

- `method` (string, required): Select a supported method; prerequisites and additional required parameters depend on the method. Options: maximum_spanning_tree, random_spanning_tree, lowest_common_ancestor, immediate_dominators, dominance_frontiers, dag_longest_path, dag_longest_path_length, antichains, is_aperiodic, colliders, v_structures
- `source` (string): Actual source-node name required for immediate_dominators/dominance_frontiers.
- `node1` (string): First node name for lowest-common-ancestor queries.
- `node2` (string): Second node name for lowest-common-ancestor queries.
- `seed` (integer): Random-spanning-tree seed, default 42. Default: 42
- `limit` (integer | string): List previews default to 20; positive integer limits are capped at 200. all can expand ordinary lists, but topological-order, antichain and collider/v-structure enumeration retains a hard cap of 200. Default: 20

Returns: Returns method-specific edges/total_weight, ancestor, items, path, value, antichains or structures. Collider results include count_is_exact; count=null means no exact total was obtained.

- Spanning trees use a connected undirected view. LCA needs node1/node2; dominators need source. DAG longest paths use weight, and DAG-specific methods require a DAG. is_aperiodic requires a nonempty strongly connected directed graph; v_structures excludes connected predecessor pairs.
- The ordinary-graph entry rejects multigraphs with UNSUPPORTED_MULTIGRAPH_OPERATION; the corresponding large-graph operation has separate capability constraints.

### Matching, edge covers and coloring · matching_coloring_analysis

Compute weighted/maximal matchings, minimum edge covers and coloring on an undirected view, or validate an edge set as a matching.

- `method` (string, required): Select a supported method; prerequisites and additional required parameters depend on the method. Options: max_weight_matching, min_weight_matching, maximal_matching, min_edge_cover, is_matching, greedy_color, equitable_color
- `edges` (array): Edges to validate with is_matching, as pairs or {from,to} objects containing actual node names.
- `maxcardinality` (boolean): For maximum-weight matching, prioritize maximum cardinality before weight; default false. Default: false
- `strategy` (string): NetworkX greedy_color strategy name, default largest_first. Default: "largest_first"
- `num_colors` (integer): Required color count for equitable_color; must exceed the graph maximum degree at runtime.
- `limit` (integer | string): List previews default to 20; positive integer limits are capped at 200. all can expand ordinary lists, but topological-order, antichain and collider/v-structure enumeration retains a hard cap of 200. Default: 20

Returns: Returns matching or edges with size/total_weight, value for matching validation, or coloring and num_colors. Lists can be truncated.

- A maximal matching cannot accept another edge but need not have maximum cardinality. Minimum edge cover rejects isolates; equitable_color requires num_colors above the maximum degree. Greedy coloring depends on strategy and does not guarantee a minimum color count.
- The ordinary-graph entry rejects multigraphs with UNSUPPORTED_MULTIGRAPH_OPERATION; the corresponding large-graph operation has separate capability constraints.

### Extended distance and structural measures · distance_measures

Compute center, periphery, eccentricity, Wiener index, efficiency, neighbor degree, rich-club coefficient, reciprocity, flow hierarchy, barycenter, Estrada index or girth.

- `metric` (string, required): Select a metric and check its direction, weight and component scope. Options: center, periphery, eccentricity, wiener_index, global_efficiency, local_efficiency, average_neighbor_degree, average_degree_connectivity, rich_club_coefficient, reciprocity, flow_hierarchy, barycenter, estrada_index, girth
- `limit` (integer | string): List previews default to 20; positive integer limits are capped at 200. all can expand ordinary lists, but topological-order, antichain and collider/v-structure enumeration retains a hard cap of 200. Default: 20

Returns: Scalars return value, node sets return nodes/count, and mappings return values/count with applicable truncated. Acyclic girth returns value=null and acyclic=true.

- Center, periphery, eccentricity, Wiener index and barycenter use the largest undirected component; barycenter is weighted and the other four are unweighted. Efficiency uses an unweighted undirected view; rich-club coefficients use normalized=false. flow_hierarchy requires a directed graph and uses weights.
- The ordinary-graph entry rejects multigraphs with UNSUPPORTED_MULTIGRAPH_OPERATION; the corresponding large-graph operation has separate capability constraints.

## Centrality and global statistics

Centralities explain node importance; global metrics describe graph structure. Degree, betweenness, PageRank, and closeness use different definitions, so their scores are not directly comparable. Direction, parallel relationships, and zero or negative weights affect method availability; consult the algorithms guide.

### Node centrality · node_centrality

Rank node importance using degree, shortest-path mediation, random walks, eigenvectors, propagation or voting.

- `centrality_type` (string): Choose degree, betweenness, closeness, PageRank, eigenvector, harmonic, Katz, load, VoteRank or percolation centrality. Options: degree, betweenness, closeness, pagerank, eigenvector, harmonic, katz, load, voterank, percolation Default: "degree"
- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 20

Returns: Returns centrality_type, total_nodes, value_stats, top_nodes, bottom_nodes and truncated.

- On multigraphs, PageRank/eigenvector/Katz sum parallel weights; betweenness/closeness/harmonic/load use minimum distances. voterank/percolation do not support multigraphs.
- Distance weights on property/multigraphs must be nonnegative; betweenness and load require strictly positive weights. Iterative centralities can fail on numerical or convergence conditions.

### Degree analysis · degree_analysis

Analyze in-degree, out-degree or total-degree distributions to identify hubs, sparsely connected nodes and isolates.

- `node` (string): With Nebula primary storage, query one node's degree without materializing the full graph; the local path performs graph-level degree analysis.
- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 20

Returns: Returns degree statistics, distributions and high/low-degree node previews. With node specified on Nebula, returns that node's degree directly.



### Global metrics · global_metrics

Calculate global density, diameter, radius, transitivity, average clustering or degree assortativity.

- `metric` (string, required): Choose density, diameter, radius, transitivity, average clustering or degree assortativity. Options: density, diameter, radius, transitivity, average_clustering, degree_assortativity

Returns: Returns metric, value and defined. Diameter/radius use unweighted distances in the largest undirected component. Nonfinite values become value=null and defined=false; undefined assortativity also includes a reason code and explanation.

- density retains the original direction semantics; diameter/radius use the largest undirected component. Multigraph support is explicit only for density, diameter and radius.

## Communities, subgraphs and structural prediction

Community detection partitions nodes, subgraph extraction selects structure, and structural link prediction scores absent edges. Community IDs label a partition from one computation. subgraph_extraction creates an active version by default; explicitly set create_version=false for inspection only.

### Community detection · community_detection

Identify densely connected node groups on an undirected calculation view and inspect community sizes and modularity.

- `algorithm` (string): Choose Louvain, greedy modularity, synchronous/asynchronous label propagation, Leiden, Girvan–Newman or fluid communities. Options: louvain, greedy_modularity, label_propagation, leiden, girvan_newman, asyn_fluidc, label_propagation_asyn Default: "louvain"
- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 5
- `focus_nodes` (array): Up to 200 actual node names whose memberships are returned from this partition; unknown names appear in missing_focus_nodes.
- `max_iterations` (integer): Range 1–500, default 5; used only by large-graph weighted synchronous label propagation, not ordinary NetworkX community algorithms. Default: 5

Returns: Returns the algorithm, community count, modularity, sizes and node previews, with communities_truncated.

- Leiden falls back to Louvain if dependencies are unavailable or execution fails. Girvan–Newman uses the first split; asyn_fluidc processes only the largest component of disconnected input.
- Multigraphs support only louvain and greedy_modularity using an undirected sum-of-parallel-weights view. Nodes within each community remain a preview.

### Subgraph extraction · subgraph_extraction

Extract an ego neighborhood, core, truss, corona or node-induced subgraph, either as a preview or as a new active graph version.

- `method` (string, required): ego_graph extracts a k-hop neighborhood; k_core requires internal degree at least k; k_truss requires at least k−2 triangles per edge; k_corona selects nodes with exactly k neighbors in the core; node_subset induces a graph on named nodes. Options: ego_graph, k_core, k_truss, k_corona, node_subset
- `node` (string): Center node for ego_graph; unnecessary for other modes.
- `k` (integer): Radius for ego_graph, or threshold for k_core/k_truss/k_corona; k_truss requires k≥2. Default: 2
- `nodes` (array): Exact node names for node_subset.
- `create_version` (boolean): true creates and activates a subgraph version; false returns a preview without changing the active graph. Default: true
- `description` (string): Description for the new subgraph version, saved only with create_version=true.
- `direction` (string): Traversal direction for Nebula ego_graph; local extraction follows the relevant graph algorithm's semantics. Options: out, in, both Default: "out"
- `max_nodes` (integer): Node cap for bounded Nebula subgraph materialization.
- `max_edges` (integer): Edge cap for bounded Nebula subgraph materialization.
- `limit` (integer | string): Preview limit, with numeric values capped at 200. all requests full results and can greatly increase output or enumeration cost. Default: 20

Returns: Returns subgraph counts and node/edge previews. create_version=true also returns a new graph version and activates it.

- create_version defaults to true. Pass false for inspection only; after activation, subsequent tools use the subgraph.
- Multigraphs explicitly support ego_graph and node_subset; core, truss and corona modes are not supported on multigraphs.

### Link prediction score · link_prediction_score

Score potential edges without training using neighborhood similarity and degree. Evaluate one node pair or rank non-edges across the graph.

- `method` (string, required): jaccard divides common neighbors by the neighbor union; adamic_adar weights common neighbors by inverse log degree; resource_allocation uses inverse degree; preferential_attachment multiplies node degrees. Options: jaccard, adamic_adar, resource_allocation, preferential_attachment
- `source` (string): Provide with target to score one pair; omit both to rank non-edge candidates.
- `target` (string): Use together with source to identify the other endpoint of the pair.
- `top_k` (integer): Number of ranked non-edge results, defaulting to 10 and restricted to 1–20. Default: 10

Returns: Returns a score for the specified pair or the top_k potential relationships ranked by score.

- Uses undirected neighborhoods. Global scoring still scans non-edges; top_k bounds retained results, not candidate computation. Multigraphs are unsupported.

## Document indexing and context retrieval

Document and graph-entity indexes are managed separately. upload_document chunks text and persists an index; retrieve_context returns relevant passages to contextualize analysis. Passage relevance does not establish a graph relationship or automatically add nodes and edges.

### Upload document · upload_document

Index inline document content or a session upload for later retrieval of supporting context.

- `filename` (string): Session upload filename; with inline content, it can serve as a source identifier.
- `content` (string): Inline document text; when omitted, read the session upload identified by filename.

Returns: Returns indexing information such as document ID, chunk count and retrieval mode.

- The document index belongs to the current session. Changing embedding dimensionality may require reindexing existing documents.

### Retrieve context · retrieve_context

Retrieve relevant passages from the session's document index to support graph-analysis explanations.

- `query` (string, required): Natural-language description, name or text passage to search for.
- `top_k` (integer): Number of candidate or relevant results to return. Default: 5

Returns: Returns relevant passages, document and chunk IDs, scores and retrieval mode.



## Visualization and analysis reports

Obtain actual analysis results before rendering a view or report. Visualization selects and presents structure; reporting organizes supplied results rather than rerunning every analysis. Distinguish displayed nodes, community previews, and highlights from the algorithm’s computation scope.

### Visualize subgraph · visualize_subgraph

Create an interactive node-and-edge view of the graph or a node subset, with optional communities and node, path or subgraph highlights.

- `node_names` (array): Node names to visualize; omit or leave empty to create a view from the full graph.
- `include_community` (boolean): Whether to include community information in the view. Default: true
- `max_nodes` (integer): Display node limit, catalog default 800; oversized inputs use deterministic overview selection. The engine fallback is configurable with VISUALIZE_MAX_NODES. Default: 800
- `highlights` (object): Highlight object with nodes, paths and subgraphs. Node groups use ids, paths use node_sequence, and subgraphs use nodes; each can include color and label.

Returns: Returns nodes, edges and optional community/highlight data. Bounded views include fields such as truncated; the active graph is unchanged.

- The overview combines highlights, node types, community representatives, high-degree nodes and connecting paths. VISUALIZE_MAX_EDGES defaults to 2,000. Inspect truncated, total_nodes/total_edges and overview.required_nodes_truncated; excessive highlights can also be truncated. Obtain graph metrics from analysis tools.

### Create analysis report · create_analysis_report

Organize existing analysis results into a report specification with summaries, charts, tables and rule-based narrative insights.

- `report_intent` (string, required): Report purpose: overview, analysis, diagnosis, comparison or custom. Options: overview, analysis, diagnosis, comparison, custom Default: "analysis"
- `analysis_goal` (string, required): The user's analysis objective or the agent's faithful summary of it.
- `title` (string): Report title.
- `source_results` (object, required): Actual analysis results keyed by tool name, such as get_graph_info, degree_analysis or node_centrality.
- `options` (object): Report display options: top_k limits chart/table items, include_narrative enables narrative insights, and max_sections limits sections.
- `options.top_k` (integer): Maximum items displayed in charts and tables. Default: 10
- `options.include_narrative` (boolean): Generate rule-based narrative insights from the results. Default: true
- `options.max_sections` (integer): Maximum number of report sections. Default: 6

Returns: Returns report structure and display data. Statistics must come from source_results, the graph, or data explicitly supplied by the user.

- Controlled by MCP_ENABLE_REPORTING_TOOLS and enabled by default; 0, false, no or off disables agent registration.
- Returns an analysis_report.v2 structure for display; it does not automatically write Markdown/PDF or Derived files. For a download, create content under the Runtime Ephemeral workspace and use workspace_publish(path=..., name=...), with the correct extension in name.

## Graph machine learning

Before training, verify the task, features, labels, and splits. Single-graph node classification and link prediction use different bindings from multi-graph classification. Obtain model IDs from completed training jobs. The tools below define invocation contracts; the learning guide explains losses, training loops, and inference structures.

### Load graph classification dataset · load_graph_classification_dataset

Load an uploaded HIV or PCBA multi-graph PT file and bind it for graph-classification training and inference.

- `filename` (string, required): Filename of an upload already registered in this session.
- `dataset_profile` (string): auto detects the dataset contract; hiv and pcba explicitly select supported multi-graph classification formats. Options: auto, hiv, pcba Default: "auto"

Returns: Returns dataset identity, profile, graph count, labels and split information. MCP loading runs as a background job.

- Uses fixed dataset contracts, splits and metrics. Loading one constituent graph as the active graph does not replace the multi-graph training dataset.

### Load graph classification graph · load_graph_classification_graph

Select one graph from a bound classification dataset and load it as the active single graph for analysis and visualization.

- `graph_index` (integer, required): Zero-based graph index in the classification dataset, from 0 to num_graphs−1.
- `dataset_id` (string): Optionally select a bound classification dataset; otherwise use the session's default binding.

Returns: Returns graph_version, graph counts, split, graph_label, previews and analysis readiness.



### Visualize model architecture · visualize_model_architecture

Read trained-model metadata to produce a layer summary and Mermaid architecture diagram.

- `model_id` (string, required): ID of a trained model accessible in the current session.

Returns: Returns an architecture diagram, layer summary and key hyperparameters.



### Train · train

Train a node-classification, link-prediction, graph-classification or pretraining model, with separate data, training and algorithm configurations.

- `task` (string, required): Select node classification, link prediction, graph classification or pretraining. Options: node_classification, link_prediction, graph_classification, pretrain
- `model` (string): Backbone name: APPNP / GCN / GAT / GATV2 / GEN / GIN / SAGE / TRANSFORMER. Required for all three supervised tasks and GNN pretraining, but not Node2Vec.
- `method` (string): Required for pretrain: node2vec, contrastive_learning, graph_contrastive_learning, mask_autoencoding or graph_mask_autoencoding. The latter four share GNN edge reconstruction.
- `graph_version` (integer): Checks the active single-graph version; it does not load history automatically. Omission uses the active graph. Graph classification rejects this field.
- `upstream_model_id` (string): Upstream trained-model ID; required when using embedding features.
- `data` (object): Training-data object: feature source, target node/edge subsets, and a graph-classification dataset ID.
- `train_config` (object): Training settings such as epochs, learning rate, splits, random seed and early stopping.
- `algo_config` (object): Architecture and device settings. Node2Vec pretraining also accepts random-walk and negative-sampling settings.
- `data.feature_source` (string): graph uses node_feat or fallback structural features; embedding reads upstream embedding.npy by node name and requires upstream_model_id. Graph classification accepts only graph. Options: graph, embedding Default: "graph"
- `data.target_nodes` (array): Limit the supervised candidate scope for node classification using actual names; labels and train/validation masks or splits still apply. This is not solely the training set.
- `data.target_edges` (array): Positive-edge subset for link prediction; each entry must be an array of two node names.
- `data.dataset_id` (string): Graph-classification dataset ID; omit to use the dataset already loaded in the session.
- `train_config.split` (object): Train/validation ratios for single-graph tasks. Graph classification uses fixed dataset splits and rejects custom split settings.
- `train_config.split.train` (number): Training-set fraction, defaulting to 0.8. Default: 0.8
- `train_config.split.val` (number): Validation-set fraction, defaulting to 0.2. Default: 0.2
- `train_config.split.test` (number): Legacy ratio field; current training does not use this custom test split.
- `train_config.epochs` (integer): Number of training epochs. Default: 200
- `train_config.lr` (number): Optimizer learning rate. Default: 0.05
- `train_config.weight_decay` (number): Optimizer weight-decay coefficient. Default: 0
- `train_config.seed` (integer): Training random seed. Default: 42
- `train_config.early_stop_patience` (integer): Supervised epochs without sufficient improvement before early stopping; 0 disables it, negative values are invalid. Pretraining ignores early-stopping options. Default: 0
- `train_config.early_stop_min_delta` (number): Minimum metric increase required to count as an improvement. Default: 0
- `train_config.batch_size` (integer): Graphs per mini-batch for graph classification; ignored by single-graph tasks. Default: 64
- `train_config.num_workers` (integer): Number of graph-classification DataLoader workers, defaulting to 0. Default: 0
- `algo_config.device` (string): auto selects an available device; cpu or cuda explicitly selects the computation device. Options: auto, cpu, cuda Default: "auto"
- `algo_config.hidden_dim` (integer): GNN hidden-representation dimension. Default: 64
- `algo_config.node_embedding_dim` (integer): Categorical-node embedding dimension for graph classification. Default: 64
- `algo_config.embedding_dim` (integer): Output node-vector dimension. The catalog annotates 64; when actually omitted, GNN training follows hidden_dim and Node2Vec uses 128. Set explicitly to avoid ambiguity. Default: 64
- `algo_config.num_layers` (integer): Number of GNN layers, at least 2. Default: 2
- `algo_config.dropout` (number): Dropout probability during training. Default: 0.2
- `algo_config.gat_heads` (integer): Attention heads for GAT, GATV2 and TRANSFORMER, default 2 with concat=False. Default: 2
- `algo_config.use_residual_connection` (boolean): Enable layer residual connections, using linear projection when dimensions differ. Default: false
- `algo_config.use_normalization` (boolean): Enable normalization in each GNN layer. Default: false
- `algo_config.norm_pos` (string): pre normalizes before convolution; post normalizes after convolution or the residual operation. Options: pre, post Default: "post"
- `algo_config.norm_type` (string): Select RMSNorm, LayerNorm or BatchNorm. Options: rms_norm, layer_norm, batch_norm Default: "layer_norm"
- `algo_config.walk_length` (integer): Node2Vec random-walk length. Default: 20
- `algo_config.context_size` (integer): Node2Vec context-window size. Default: 10
- `algo_config.walks_per_node` (integer): Number of Node2Vec random walks per node. Default: 10
- `algo_config.num_negative_samples` (integer): Number of negative samples for Node2Vec. Default: 1
- `algo_config.batch_size` (integer): Batch size of the Node2Vec loader. Default: 128
- `algo_config.p` (number): Node2Vec return-bias parameter p. Default: 1
- `algo_config.q` (number): Node2Vec in/out exploration-bias parameter q. Default: 1
- `algo_config.appnp_k` (integer): APPNP propagation iterations, at least 1; default 10. Default: 10
- `algo_config.appnp_alpha` (number): APPNP teleport probability to the initial predictions, 0 < alpha ≤ 1; default 0.1. Default: 0.1

Returns: MCP returns a job handle. The completed result contains model identity, training status and metrics or errors; artifacts are associated with their session and training-data identity.

- Load a dataset before graph classification and use its fixed split/metric. feature_source=embedding requires upstream_model_id; inspect readiness before training.
- Dotted parameter names show nested paths; send actual requests as data, train_config and algo_config objects. MCP supplies the internal background-job marker for training.
- The MCP layer can return a background handle; GraphMCPTools in the native runtime monitors the job and delivers its final result to the main agent.
- Single graphs without node_feat use normalized in-degree, out-degree, total-degree and constant features; business fields are not automatically encoded. GNN pretraining has no separate masking/augmentation implementation or early stopping. Node2Vec runs on CPU, defaults to 128 embedding dimensions and ignores weight_decay and early stopping.

### Infer · infer

Run inference with a saved model. Model metadata determines the task; query selects nodes, pairs, candidate targets or graph indices.

- `model_id` (string, required): ID of a trained model accessible in the current session.
- `graph_version` (integer): Graph version for inference. A mismatch with the model's graph version is rejected by default unless explicitly permitted.
- `query` (object): nodes selects nodes, edges contains name pairs, source_node/candidate_nodes ranks candidates, graph_indices selects graphs and split selects a partition. Omission gives node-classification evaluation/samples, nonedge candidates for link prediction, test graphs for graph classification, or the first saved embeddings for pretraining.
- `infer_config` (object): Inference device, threshold, batch size, pagination and task-specific output settings.
- `query.nodes` (array): Exact node names for node classification or embedding lookup.
- `query.split` (string): Select nodes or graphs using the train, val or test split. Options: train, val, test
- `query.graph_indices` (array): Array of zero-based graph indices in the classification dataset.
- `query.edges` (array): Link-prediction pairs such as [["A","B"],["A","C"]]; source/target objects are not accepted.
- `query.source_node` (string): Source node for source-based link prediction.
- `query.candidate_nodes` (array): Candidate target-node names for the source node.
- `query.topk` (integer): Number of highest-scoring candidates to retain. Default: 10
- `infer_config.return_prob` (boolean): Whether prediction results include probabilities. Default: true
- `infer_config.batch_size` (integer): Mini-batch size for graph-classification inference. Default: 128
- `infer_config.device` (string): Device selection for graph-classification inference: auto/cpu/cuda. Node classification and link prediction currently select automatically; pretraining only reads saved vectors. Options: auto, cpu, cuda Default: "auto"
- `infer_config.threshold` (number): Binary graph-classification threshold, from 0 to 1. Default: 0.5
- `infer_config.top_k_tasks` (integer): Number of highest-probability tasks returned for each PCBA graph. Default: 5
- `infer_config.return_all_task_probs` (boolean): Return all 128 PCBA probabilities, predictions and ground-truth labels. Default: false
- `infer_config.allow_version_mismatch` (boolean): Explicitly permit different training and inference graph versions; disabled by default. Default: false
- `infer_config.sample_size` (integer): Number of random node-classification prediction samples when query is empty. Default: 20
- `infer_config.sample_seed` (integer): Random seed used to sample prediction examples. Default: 42
- `infer_config.result_limit` (integer): Prediction-detail page limit; aggregate evaluation metrics are not restricted to that page. Default: 20
- `infer_config.result_offset` (integer): Zero-based pagination offset for prediction details. Default: 0
- `infer_config.topk` (integer): Number of highest-scoring candidates to retain. Default: 20
- `infer_config.max_candidate_pairs` (integer): Maximum retained and scored nonedge candidates for empty-query link prediction, default 200,000. Generation can still traverse all node pairs; provide explicit candidates on large graphs. Default: 200000
- `infer_config.limit` (integer): Result limit for pretraining/embedding inference when nodes is omitted. Default: 200

Returns: Supervised tasks return predictions and applicable evaluation; pagination does not narrow the evaluated set. Pretraining returns an embeddings array of node and embedding entries. PCBA displays only a few high-probability tasks by default.

- edges must be a list of two-element arrays. Prediction pagination does not mean evaluation covers only that page; PCBA returns a few high-probability tasks by default.
- Pretraining inference queries embedding.npy saved during training rather than running a GNN on a new graph. Link prediction uses a symmetric inner-product decoder; candidates can include existing edges, so inspect exists_in_graph. Node-classification query.split reads original graph masks, not unsaved random training splits.

## Background jobs and graph storage

Use job_id to inspect submitted work and progress cursors to read incremental logs; completed results come from job.result. Nebula-specific tools support storage and native-query diagnostics. Prefer unified tools for ordinary graph analysis and inspect materialization scope and query limits.

### Get job status · get_job_status

Read a background job owned by the current user and session, with cursor-based training or construction progress.

- `job_id` (string, required): Actual job ID returned by a background submission, owned by the current user and session.
- `after_seq` (integer): Read persisted progress events after this sequence number; start at 0 for the first page.
- `progress_limit` (integer): Maximum progress events per read, from 1–1000; the server uses 200 when omitted.

Returns: Returns success, job and progress_updates. Ordinary jobs contain status, progress, detail and final result; large-graph jobs contain persisted stage, summary and artifact_id fields. Use get_job_result for the large-graph result summary.

- For ordinary jobs, after_seq replays progress by cursor; omission drains pending updates. Large-graph progress_updates is empty. Read ordinary completed output from job.result or get_job_result, and large-graph output with get_job_result. Check terminal status and business success in either case.

### Cancel job · cancel_job

Request cancellation of a background job and its associated children in controlled execution.

- `job_id` (string, required): Actual job ID returned by a background submission, owned by the current user and session.

Returns: Returns success and job_id indicating acceptance of the cancellation request. Confirm a terminal state with get_job_status; request acceptance alone does not prove computation has exited.

- Cancellation intent and execution exit are confirmed separately. Queued jobs do not start computation; running jobs require worker exit and resource cleanup.

### Nebula status · nebula_status

Inspect NebulaGraph configuration, connectivity and the current graph's storage or synchronization status.



Returns: Returns Nebula availability, connection and graph-storage status.



### Nebula sync graph · nebula_sync_graph

Synchronize the session graph to NebulaGraph for database queries and subsequent use.



Returns: Synchronization can return a background job_id. Read the final synchronization result and graph-version information through job status.

- Requires an available Nebula service. Agents normally query nodes and paths through the unified get_node_info, get_neighbors and shortest_path tools.

### Nebula get node info · nebula_get_node_info

Read node information directly from NebulaGraph, using the primary-storage or synchronized-graph path for the session.

- `node_name` (string, required): Exact node name in the current graph.

Returns: Returns Nebula node, attribute and connection information, or a storage error when the graph is unavailable or unsynchronized.

- This is a backend-specific entry point. Use get_node_info to let the engine select a path for the active storage backend.

### Nebula get neighbors · nebula_get_neighbors

Query one-hop neighbors in a specified direction directly in NebulaGraph for database traversal and storage diagnostics.

- `node_name` (string, required): Exact node name in the current graph.
- `direction` (string): out follows outgoing edges, in follows incoming edges, and both traverses both directions. Options: out, in, both Default: "out"
- `limit` (integer): Neighbor limit, restricted by the server to 1–200 and defaulting to 20. Default: 20

Returns: Returns Nebula neighbors and traversal information, with the result count bounded by limit.

- The unified get_neighbors can also route to Nebula primary storage. Calling both is unnecessary when they answer the same query.

### Nebula shortest path · nebula_shortest_path

Use native Nebula queries to find a shortest path within a direction and hop bound, where shortest means fewest hops.

- `source` (string, required): Exact source-node name.
- `target` (string, required): Exact target-node name.
- `direction` (string): out follows outgoing edges, in follows incoming edges, and both traverses both directions. Options: out, in, both Default: "out"
- `max_steps` (integer): Maximum hops for native path queries, restricted by the server to 1–20 and defaulting to 10. Default: 10

Returns: Returns bounded path-query results, node sequences and traversal information. No path within the bound does not establish global unreachability.

- Has no use_weight parameter and does not minimize weighted cost. Use shortest_path for the unified interface; native Nebula traversal corresponds to use_weight=false.

### Get job result · get_job_result

Read ordinary or large-graph job status and output; large-graph output remains summaries, previews and artifact references.

- `job_id` (string, required): Actual submitted job ID belonging to the current user and session.

Returns: Returns outer success and result. Ordinary terminal result contains job_id, status, result and error; large-graph result includes status, graph_id, graph_version, summary, preview, artifact_id and error.

- success=true for queued/running means successful lookup only. Confirm status=done, then inspect the inner business result; failed/cancelled returns success=false. Unknown or inaccessible jobs return no result.

## Constructed graphs and optimization

These public tools manage saved construction results separately from the subagent’s private transformations. Read the complete graph and revision, preview requested edits, and commit those operations after confirmation. Explicitly load the new saved version before subsequent session analysis uses it.

### Get graph construction capabilities · get_graph_construction_capabilities

Inspect construction-algorithm availability for SQL, CSV and TXT, and the optimization rules supported for saved graphs.



Returns: Returns source-type capabilities and optimization rules. Unregistered algorithms report algorithm_unavailable.

- Initial source construction is started from the dataset panel. Report unavailable algorithms as such; a text-extraction result is not a skill-construction result.

### Get graph construction status · get_graph_construction_status

Inspect a saved dataset's construction state, revision and size to determine whether its graph can be reused.

- `dataset_id` (string, required): An accessible dataset ID obtained from the dataset list or session data state.

Returns: Returns status, revision, source_type and counts. Only ready indicates an available saved graph.



### Get constructed graph · get_constructed_graph

Read the saved property graph and revision of a construction dataset to inspect real IDs and plan changes.

- `dataset_id` (string, required): An accessible dataset ID obtained from the dataset list or session data state.

Returns: graph contains directed, nodes(id,type,properties) and edges(id,source,target,type,properties), alongside revision information.

- Read the graph before referring to element IDs. revision belongs to the saved dataset and differs from the session graph_version namespace.

### Load constructed graph · load_constructed_graph

Load a dataset's saved constructed graph into the current session for analysis, visualization and learning tools.

- `dataset_id` (string, required): An accessible dataset ID obtained from the dataset list or session data state.

Returns: Returns load status, session graph version and dataset binding. Replaces the active graph without rerunning construction.

- After loading, inspect analysis semantics and features with get_graph_info, and display the result with visualize_subgraph.

### Preview graph optimization · preview_graph_optimization

Preview a batch of saved-graph edits against a known revision, inspecting element, attribute and size changes without writing the dataset.

- `dataset_id` (string, required): An accessible dataset ID obtained from the dataset list or session data state.
- `base_revision` (integer, required): Revision obtained when reading or previewing the saved graph; must be at least 1.
- `operations` (array, required): Non-empty array of ordered operations. Each requires op: collapse_node, node_property_to_edge, extract_property_node, delete, reverse_edges or rename_type.
- `operations[].op` (string, required): Operation type, determining the required IDs, property names and type names. Options: collapse_node, node_property_to_edge, extract_property_node, delete, reverse_edges, rename_type
- `operations[].node_id` (string): Actual node ID for collapse_node or node_property_to_edge.
- `operations[].node_ids` (array): Actual node IDs for extract_property_node.
- `operations[].edge_ids` (array): Actual relationship IDs for property relocation or direction reversal.
- `operations[].ids` (array): Node or edge IDs for delete, with the kind selected by target.
- `operations[].property` (string): Property name; setting it for delete removes the property instead of the entire element.
- `operations[].target_property` (string): Name for a property moved onto relationships; omit to use the rule's default name.
- `operations[].remove_from_node` (boolean): Whether to remove the relocated property from the original node; specify the intended behavior explicitly.
- `operations[].node_type` (string): Node type for extracted attribute nodes.
- `operations[].edge_type` (string): Edge type for new or converted relationships.
- `operations[].target` (string): Select node or edge for delete and rename_type. Options: node, edge
- `operations[].cascade` (boolean): Whether node deletion also removes incident relationships; select explicitly after reviewing the preview.
- `operations[].old_type` (string): Existing type name matched by rename_type.
- `operations[].new_type` (string): New type name saved by rename_type.

Returns: Returns a preview graph and diff for reviewing affected nodes, relationships and properties. Saved state and revision are unchanged.

- operations[].op is required in every item; other fields depend on the operation. Use get_constructed_graph first to obtain real node, relationship and property names.

### Commit graph optimization · commit_graph_optimization

Persist the same batch of graph edits that was previewed and confirmed by the user, creating a new dataset revision.

- `dataset_id` (string, required): An accessible dataset ID obtained from the dataset list or session data state.
- `base_revision` (integer, required): Revision obtained when reading or previewing the saved graph; must be at least 1.
- `operations` (array, required): Non-empty array of ordered operations. Each requires op: collapse_node, node_property_to_edge, extract_property_node, delete, reverse_edges or rename_type.
- `operations[].op` (string, required): Operation type, determining the required IDs, property names and type names. Options: collapse_node, node_property_to_edge, extract_property_node, delete, reverse_edges, rename_type
- `operations[].node_id` (string): Actual node ID for collapse_node or node_property_to_edge.
- `operations[].node_ids` (array): Actual node IDs for extract_property_node.
- `operations[].edge_ids` (array): Actual relationship IDs for property relocation or direction reversal.
- `operations[].ids` (array): Node or edge IDs for delete, with the kind selected by target.
- `operations[].property` (string): Property name; setting it for delete removes the property instead of the entire element.
- `operations[].target_property` (string): Name for a property moved onto relationships; omit to use the rule's default name.
- `operations[].remove_from_node` (boolean): Whether to remove the relocated property from the original node; specify the intended behavior explicitly.
- `operations[].node_type` (string): Node type for extracted attribute nodes.
- `operations[].edge_type` (string): Edge type for new or converted relationships.
- `operations[].target` (string): Select node or edge for delete and rename_type. Options: node, edge
- `operations[].cascade` (boolean): Whether node deletion also removes incident relationships; select explicitly after reviewing the preview.
- `operations[].old_type` (string): Existing type name matched by rename_type.
- `operations[].new_type` (string): New type name saved by rename_type.

Returns: Returns commit status and a new revision. On a revision conflict, read and preview again; then use load_constructed_graph to update the active session.

- Keep base_revision and operations identical to the preview and obtain user confirmation. Set remove_from_node and cascade explicitly to express the intended behavior.

## MCP session-management interfaces

These 3 interfaces are registered separately by the MCP server and are not part of the 72-tool catalog. Native GraphMCPTools does not filter them, so discovery can obtain their schemas. They operate on explicit MCP connection bindings; native runs normally identify business sessions through headers, with lifecycle managed by the host service.

| Interface | Parameters | Behavior and result |
| --- | --- | --- |
| register_session | agent_session_id: string, required; user_id: string\|null, optional, default empty string. ctx is injected by MCP. | Bind the MCP connection to a business session and request session creation in Graph Engine, returning registration/creation status. Use IDs from the actual host session; native header-scoped runs normally do not need a model-created binding. |
| delete_graph_session | No public parameters; ctx is injected by MCP. | Remove the current MCP connection binding and delete its Graph Engine session. With no explicit binding, returns success=true without implying that a header-identified session was deleted. Used for session teardown. |
| set_session_config | llm_model: string\|null; the field must be supplied, but null is allowed. ctx is injected by MCP. | Set the LLM model used by extraction and related operations for an explicitly bound MCP session. A non-empty value triggers an update; null does not. Unregistered connections return session_not_registered; header identity is not the same as a registered binding. |

## Example: path analysis and a graph view

Run this Python example in a server environment with access to Graph Engine HTTP. First create a demo session in the workspace and ensure its graph session is registered, then set GRAPH_ENGINE_URL, IGRAPH_SESSION_ID, IGRAPH_USER_ID and IGRAPH_CONTROL_SERVICE_KEY. The example load_graph replaces that session’s active graph; the later subgraph call uses create_version=false.

Weights in this example represent distance or cost. The graph has 4 nodes and 5 directed edges. A→B→C→D costs 4, while A→C→D and A→B→D each cost 6.

```python
import json
import os
import time
from urllib.request import Request, urlopen

base = os.environ["GRAPH_ENGINE_URL"].rstrip("/")
session_id = os.environ["IGRAPH_SESSION_ID"]
headers = {
    "Content-Type": "application/json",
    "X-User-ID": os.environ["IGRAPH_USER_ID"],
    "X-Session-ID": session_id,
    "X-iGraph-Service-Key": os.environ["IGRAPH_CONTROL_SERVICE_KEY"],
}

def invoke(name, arguments):
    body = json.dumps({"arguments": arguments}).encode("utf-8")
    request = Request(
        f"{base}/sessions/{session_id}/tools/{name}",
        data=body, headers=headers, method="POST",
    )
    with urlopen(request, timeout=900) as response:
        result = json.load(response)
    if result.get("success") is False:
        raise RuntimeError(result)
    return result

def call(name, arguments):
    result = invoke(name, arguments)
    while result.get("async") and result.get("job_id"):
        job_id = result["job_id"]
        while True:
            status = invoke("get_job_status", {"job_id": job_id})
            job = status["job"]
            if job["status"] == "done":
                result = job["result"]
                break
            if job["status"] in {"failed", "cancelled"}:
                raise RuntimeError(job)
            time.sleep(1)
    return result

call("load_graph", {
    "edge_text": "A B 2\nA C 5\nB C 1\nB D 4\nC D 1",
    "append": False,
})
info = call("get_graph_info", {})
path = call("shortest_path", {
    "source": "A", "target": "D", "use_weight": True,
})
assert path["path"] == ["A", "B", "C", "D"]
assert path["total_length"] == 4

preview = call("subgraph_extraction", {
    "method": "node_subset", "nodes": ["A", "B", "C"],
    "create_version": False,
})
view = call("visualize_subgraph", {
    "max_nodes": 50,
    "highlights": {"paths": [{
        "node_sequence": path["path"],
        "label": "Minimum-cost path", "color": "#356ae6",
    }]},
})
print(json.dumps({"path": path, "preview": preview, "view": view}, indent=2))
```

| Call | Verifiable result |
| --- | --- |
| shortest_path · use_weight=true | path=[A,B,C,D], hop_count=3, total_length=4. |
| shortest_path · use_weight=false | Minimum of 2 hops; a tied result may be A→B→D or A→C→D. |
| subgraph_extraction · create_version=false | Previews the graph induced by A, B and C; D remains in the active graph. |
| visualize_subgraph · highlights.paths | Highlights A→B→C→D in the active-graph view, without recomputing the path from a truncated view. |

To compare alternative routes, set shortest_path algorithm to yen_k_shortest and k to 3. To inspect only equal-cost optimal routes, use all_shortest_paths. Enable create_version explicitly when saving a subgraph and retain the returned graph_version.
