> [!WARNING]
>
> **Preview**
>
>
> This feature is
>
> subject to the "Pre-GA Offerings Terms" in the General Service Terms section of the
> [Service Specific
> Terms](https://docs.cloud.google.com/terms/service-terms#1), and the
> [Additional Terms for Generative AI
> Preview Products](https://cloud.google.com/trustedtester/aitos).
>
> Pre-GA features are available "as is" and might have limited support.
>
> For more information, see the
> [launch stage descriptions](https://cloud.google.com/products/#product-launch-stages).


> [!WARNING]
> **PostgreSQL interface note:** The examples in this topic are intended for GoogleSQL-dialect databases. This feature doesn't support PostgreSQL interface.

<br />

This tutorial describes how to set up and use QueryData in Spanner Graph using the Google Cloud console and integrate it with your application. You learn how to set up the `FinGraph` property graph, build a Graph Query Language (GQL) context set file using the context engineering agent, create a context set in Spanner Studio, test QueryData by calling the [QueryData method in the Conversational Analytics API](https://docs.cloud.google.com/gemini/data-agents/conversational-analytics-api/data-agent-authored-context-databases.md.txt) with `graph_ids` configured, and use a custom HTTP tool in [MCP Toolbox](https://github.com/googleapis/mcp-toolbox) to connect an agent application to QueryData.

For more information, see [QueryData overview](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/data-agent-overview.md.txt).

## Objectives

- Create the `FinGraph` property graph schema and populate it with sample graph data.
- Build a context set file for `FinGraph` using the context engineering agent.
- Create a context set and upload the context set file in Spanner Studio.
- Test QueryData and generate GQL queries by calling the `QueryData` REST API with `graph_ids` specified in `spanner_reference`.
- Integrate QueryData with your application using a custom [HTTP tool](https://mcp-toolbox.dev/integrations/http/) in MCP Toolbox that calls the `QueryData` REST API.
- Ground LLM responses in your graph data using query templates, query facets, and `GRAPH_TABLE` value search queries.

## Costs

In this document, you use the following billable components of Google Cloud:

- [Spanner](https://docs.cloud.google.com/spanner/pricing)
- [Gemini for Google Cloud API](https://docs.cloud.google.com/gemini/pricing)

To generate a cost estimate based on your projected usage, use the [pricing calculator](https://cloud.google.com/products/calculator).

New Google Cloud users might be eligible for a [free trial](https://docs.cloud.google.com/free).

To avoid continued billing, delete the resources you created when you finish the tasks in this document. For more information, see [Clean up](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/integrate-applications-data-agent.md.txt#clean-up).

## Before you begin

Complete the following prerequisites before creating a context set:

### Enable required services

Enable the following services for your project:

- [Data Analytics API with Gemini](https://console.cloud.google.com/apis/library/geminidataanalytics.googleapis.com)
- [Gemini for Google Cloud API](https://console.cloud.google.com/apis/library/cloudaicompanion.googleapis.com)
- [Knowledge Catalog API](https://console.cloud.google.com/apis/library/dataplex.googleapis.com)

### Prepare a Spanner instance

- Make sure that a Spanner instance is available. For more information, see [Create an instance](https://docs.cloud.google.com/spanner/docs/create-manage-instances.md.txt).
- Ensure that you create a database in your instance where you will create the tables. For more information, see [Create a database on the
  Spanner instance](https://docs.cloud.google.com/spanner/docs/create-manage-databases#create-database).

### Required roles and permissions

- Add an IAM user or service account to the instance. For more information, see [Apply IAM roles](https://docs.cloud.google.com/spanner/docs/grant-permissions.md.txt).
- Grant the `roles/spanner.databaseReader`, `roles/serviceusage.serviceUsageConsumer`, and `roles/geminidataanalytics.queryDataUser` roles to the IAM user at the project level. For more information, see [Add IAM policy binding for a project](https://docs.cloud.google.com/sdk/gcloud/reference/projects/add-iam-policy-binding).
- To create, upload, and manage context sets, grant the Dataplex Catalog Editor (`roles/dataplex.catalogEditor`) or Dataplex Catalog Admin (`roles/dataplex.catalogAdmin`) role to the IAM user at the project level. For more information, see [Context sets permissions](https://docs.cloud.google.com/knowledge-catalog/docs/iam-permissions.md.txt#context-set-permissions).
- [Grant roles and permissions](https://docs.cloud.google.com/spanner/docs/grant-permissions.md.txt#project-level_permissions) to the IAM user at the project-level for the required databases.

> [!WARNING]
> **Warning:** All context sets associated with a database are viewable to all users with any read access to that database. In cases where users have narrower access to the database, such as Spanner fine-grained access control, users can potentially discover other fields and tables from the context set.

## Create the `FinGraph` schema and insert graph data

This tutorial uses the `FinGraph` financial property graph dataset, which models `Person` and `Account` nodes connected by `Owns` (`PersonOwnAccount`) and `Transfers` (`AccountTransferAccount`) edges.

To create the `FinGraph` schema and populate the graph data in your Spanner database, complete the following steps from the Spanner Graph setup guide:

1. Follow [Create a graph database using a schema](https://docs.cloud.google.com/spanner/docs/graph/set-up.md.txt#create-database) to create the `Person`, `Account`, `PersonOwnAccount`, and `AccountTransferAccount` tables and the `FinGraph` property graph definition.
2. Follow [Insert graph data](https://docs.cloud.google.com/spanner/docs/graph/set-up.md.txt#insert-graph-data) to insert the sample people (`Alex`, `Dana`, and `Lee`), accounts (`7`, `16`, and `20`), account ownership edges, and money transfer edges into `FinGraph`.

## Create a context set

Create an empty context set named `fingraph-assistant`. Later in this tutorial, you upload a context set file to it.

1. In the Google Cloud console, go to the Spanner page.

   [Go to Spanner](https://console.cloud.google.com/spanner)
2. Select your instance from the list, and then select the database containing `FinGraph`.

3. In the navigation menu, click **Spanner Studio**.

4. In the **Explorer** pane, next to **Context sets** , click **View actions**.

5. Click **Create context set**.

6. In the **Context set name** field, enter `fingraph-assistant`.

7. Click **Create**.

## Test QueryData without context

In this section, you call the `QueryData` REST API to generate GQL queries for natural language questions without a context set. Without context, QueryData can answer questions that map directly to the `FinGraph` schema, but it can't interpret custom business terminology such as `high-risk transfers` or resolve value formatting differences such as `Czech Republic` versus `Czech_Republic`.

> [!IMPORTANT]
> **Important:** In Preview, the **Help me code** panel (**Generate SQL** ) in Spanner Studio doesn't support QueryData for Spanner Graph and doesn't generate GQL queries. Don't use Spanner Studio to test QueryData for Spanner Graph. Instead, call the `QueryData` REST API as described in this section.

> [!NOTE]
> **Note:** Generative AI models are nondeterministic, meaning the same prompt might yield different responses across separate calls. The generated GQL queries in this tutorial are examples.

1. In your terminal, set the following environment variables:

   ```
   export PROJECT_ID="PROJECT_ID"
   export INSTANCE_ID="INSTANCE_ID"
   export DATABASE_ID="DATABASE_ID"
   ```

   Replace the following:
   - `PROJECT_ID`: your Google Cloud project ID.
   - `INSTANCE_ID`: your Spanner instance ID.
   - `DATABASE_ID`: the ID of the database that contains `FinGraph`.
2. Create a helper script named `query_data.sh` that sends a question to the `QueryData` REST API with `graph_ids` set to `FinGraph`. If the `CONTEXT_SET_ID` environment variable is set, the script also sends your context set ID:

   ```bash
   cat > query_data.sh <<'EOF'
   #!/bin/bash
   # Usage: ./query_data.sh "NATURAL_LANGUAGE_QUESTION"
   if [[ -n "${CONTEXT_SET_ID}" ]]; then
     AGENT_CONTEXT=", \"agent_context_reference\": {\"context_set_id\": \"${CONTEXT_SET_ID}\"}"
   fi
   curl -sS -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json" \
     -H "x-goog-user-project: ${PROJECT_ID}" \
     "https://geminidataanalytics.googleapis.com/v1beta/projects/${PROJECT_ID}/locations/global:queryData" \
     -d @- <<JSON
   {
     "prompt": "$1",
     "context": {
       "datasource_references": {
         "spanner_reference": {
           "database_reference": {
             "engine": "GOOGLE_SQL",
             "project_id": "${PROJECT_ID}",
             "instance_id": "${INSTANCE_ID}",
             "database_id": "${DATABASE_ID}",
             "graph_ids": ["FinGraph"]
           }${AGENT_CONTEXT}
         }
       }
     },
     "generation_options": {
       "generate_query_result": true,
       "generate_natural_language_answer": true,
       "generate_explanation": true
     }
   }
   JSON
   EOF
   chmod +x query_data.sh
   ```

   The script inserts your question into the request body as is, so don't use double quotation marks (`"`) in the question.
3. Ask a question that maps directly to the `FinGraph` schema:

   ```
   ./query_data.sh "Find everyone that Dana transferred money to, along with the account IDs and transfer amounts."
   ```

   In the response, review the `generatedQuery` and `queryResult` fields. For this unambiguous question, QueryData generates a GQL query similar to the following:

   ```sql
   GRAPH FinGraph
   MATCH
     (p:Person {name: 'Dana'})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account),
     (recipient:Person)-[:Owns]->(dst)
   RETURN
     recipient.name AS recipient_name,
     dst.id AS recipient_account_id,
     t.amount AS transfer_amount;
   ```

   This returns results similar to the following:

       +---+---+---+
       | recipient_name | recipient_account_id | transfer_amount |
       +---+---+---+
       | Alex           | 7                    | 500             |
       | Lee            | 16                   | 200             |
       +---+---+---+

4. Ask a question that includes the business term `high-risk transfers`:

   ```
   ./query_data.sh "Find all high-risk transfers initiated by Alex"
   ```

   Because the `FinGraph` schema doesn't define what constitutes a `high-risk transfer` (which in your business logic means a transfer of `200` or more to a blocked account where `is_blocked = true`), QueryData either doesn't apply the blocked-account and amount threshold filters or applies its own interpretation of the term. For example, QueryData might invent an amount threshold that returns no rows, or it might ignore the term and generate a query similar to the following:

   ```sql
   -- Returning transfers initiated by Alex because 'high-risk' is not defined in the schema.
   GRAPH FinGraph
   MATCH
     (p:Person {name: 'Alex'})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account)
   RETURN
     src.id AS source_account_id,
     dst.id AS destination_account_id,
     t.amount AS transfer_amount,
     t.order_number;
   ```

   This returns both of Alex's transfers, including the `100` transfer that doesn't meet the threshold:

       +---+---+---+---+
       | source_account_id | destination_account_id | transfer_amount | order_number    |
       +---+---+---+---+
       | 7                 | 16                     | 300             | 304330008004315 |
       | 7                 | 16                     | 100             | 304120005529714 |
       +---+---+---+---+

5. Ask a question that refers to a country:

   ```
   ./query_data.sh "Find accounts owned by people from Czech Republic"
   ```

   Without context or value linking, QueryData generates a GQL query that filters for `'Czech Republic'` with a space. Because the `Person.country` property in `FinGraph` stores the value as `'Czech_Republic'` with an underscore, the query returns no rows:

   ```sql
   GRAPH FinGraph
   MATCH
     (p:Person {country: 'Czech Republic'})-[:Owns]->(a:Account)
   RETURN
     p.name AS owner_name,
     a.id AS account_id,
     a.nick_name;
   ```

## Generate context for the context set

In this section, you prepare your local environment and use the context engineering agent to create a context set file (`context_set.json`) for the `FinGraph` property graph in your Spanner database.

### Set up your environment

To set up your environment for the context engineering agent, perform the following steps:

1. Install the Antigravity CLI. For more information, see [Get Started with Antigravity CLI](https://antigravity.google/docs/cli/getting-started/).
2. [Install the Google Cloud CLI](https://docs.cloud.google.com/sdk/docs/install).
3. [Set up Application Default Credentials (ADC)](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt). Run the following command in your terminal to authenticate:

   ```bash
   gcloud auth application-default login
   ```
4. [Install the context engineering agent](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/build-context-sets.md.txt#install-agent).

5. In your terminal, start the Antigravity CLI:

   ```bash
   agy
   ```
6. Set up the database connection for your Spanner database. Enter a prompt that explicitly specifies that you are generating context for the property graphs in your Spanner database, and includes the `FinGraph` property graph name so that the agent triggers the GQL-specific context engineering workflow:

       Help me set up the database connection for the FinGraph property graph in my Spanner database.

   Follow the instructions provided by the agent to create `autoctx/tools.yaml` and `autoctx/state.md`. Then open `autoctx/state.md` and verify that the `## Active Database` section contains the line `- **Graph Ids**: ["FinGraph"]`. The context engineering agent reads the property graph names from this line when it generates evaluation configurations. For more information about `tools.yaml`, see [MCP Toolbox documentation](https://mcp-toolbox.dev/documentation/configuration/).

   > [!NOTE]
   > **Note:** If this connection isn't established, the extension returns error messages such as `Error Discovering tools from mcp_toolbox`, and context generation fails to work.

7. To reload the configuration after `autoctx/tools.yaml` is created, run the following command in the Antigravity CLI:

   ```bash
   /mcp
   ```
8. Select `toolbox`, and then select `Restart`.

9. Verify that the MCP Toolbox and the context engineering agent plugin are connected and ready to use:

   ```bash
   /mcp
   ```

### Generate GQL template context

To address the issue where QueryData didn't recognize the business term `high-risk transfers`, define `high-risk transfers` in the context set file as transfers of `200` or more sent to a blocked account (`dst.is_blocked = true`).

To generate the GQL template context, perform the following steps:

1. Enter the following prompt into the agent harness, specifying that `FinGraph` is a property graph in your Spanner database:

   ```bash
   For the FinGraph property graph in my Spanner database, generate a GQL template for the question: "Find all high-risk transfers initiated by Alex" with the following GQL query:
   GRAPH FinGraph
   MATCH
     (p:Person {name: 'Alex'})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account {is_blocked: true})
   WHERE
     t.amount >= 200
   RETURN
     dst.id AS destination_account_id,
     t.amount AS transfer_amount
   ORDER BY
     t.amount DESC;
   ```
2. The agent converts your input into a parameterized GQL template that generalizes across person names. For more information, see [Context sets overview](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/context-sets-overview.md.txt).

3. Review the generated GQL query template, and then prompt the agent with `Save it to context_set.json`. The agent creates `context_set.json` in your directory with the following content:

   ```json
   {
     "templates": [
       {
         "nl_query": "Find all high-risk transfers initiated by Alex",
         "sql": "GRAPH FinGraph MATCH (p:Person {name: 'Alex'})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account {is_blocked: true}) WHERE t.amount >= 200 RETURN dst.id AS destination_account_id, t.amount AS transfer_amount ORDER BY t.amount DESC;",
         "intent": "Find all high-risk transfers initiated by Alex",
         "manifest": "Find all high-risk transfers initiated by a given person",
         "parameterized": {
           "parameterized_sql": "GRAPH FinGraph MATCH (p:Person {name: ?})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account {is_blocked: true}) WHERE t.amount >= 200 RETURN dst.id AS destination_account_id, t.amount AS transfer_amount ORDER BY t.amount DESC;",
           "parameterized_intent": "Find all high-risk transfers initiated by ?"
         }
       }
     ]
   }
   ```

### Generate facet and value search context

In this section, you add a GQL facet and two `GRAPH_TABLE` value search queries to `context_set.json`. The template that you added in the previous section answers questions that have the same structure as "Find all high-risk transfers initiated by Alex." The facet captures the blocked-account pattern so that QueryData can also apply it to questions that don't match the template, such as "Find all money transfers involving a blocked account." The value searches let QueryData map value phrases such as `Czech Republic` to the stored value `Czech_Republic` on `Person.country`, and match account nicknames on `Account.nick_name` regardless of case.

1. Enter the following prompt into the agent harness, specifying that `FinGraph` is a property graph in your Spanner database:

       For the FinGraph property graph in my Spanner database, generate a GQL facet with the GQL clause "MATCH (account:Account)-[transfer:Transfers]-(:Account {is_blocked: true})" for intent "transfers involving a blocked account". Then generate two GRAPH_TABLE value searches on FinGraph: one on Person.country that ignores case and treats underscores as spaces, with concept type "Person country", and one on Account.nick_name that ignores case, with concept type "Account nickname". Validate the value search queries against the database, and then append the facet and value searches to context_set.json.

2. Review the updated `context_set.json` file, which now contains the GQL template, the GQL facet, and the value search definitions:

   ```json
   {
     "templates": [
       {
         "nl_query": "Find all high-risk transfers initiated by Alex",
         "sql": "GRAPH FinGraph MATCH (p:Person {name: 'Alex'})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account {is_blocked: true}) WHERE t.amount >= 200 RETURN dst.id AS destination_account_id, t.amount AS transfer_amount ORDER BY t.amount DESC;",
         "intent": "Find all high-risk transfers initiated by Alex",
         "manifest": "Find all high-risk transfers initiated by a given person",
         "parameterized": {
           "parameterized_sql": "GRAPH FinGraph MATCH (p:Person {name: ?})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account {is_blocked: true}) WHERE t.amount >= 200 RETURN dst.id AS destination_account_id, t.amount AS transfer_amount ORDER BY t.amount DESC;",
           "parameterized_intent": "Find all high-risk transfers initiated by ?"
         }
       }
     ],
     "facets": [
       {
         "sql_snippet": "MATCH (account:Account)-[transfer:Transfers]-(:Account {is_blocked: true})",
         "intent": "transfers involving a blocked account",
         "manifest": "transfers involving a blocked account",
         "parameterized": {
           "parameterized_sql_snippet": "MATCH (account:Account)-[transfer:Transfers]-(:Account {is_blocked: true})",
           "parameterized_intent": "transfers involving a blocked account"
         }
       }
     ],
     "value_searches": [
       {
         "query": "SELECT value, columns, concept_type, distance, context FROM GRAPH_TABLE(FinGraph MATCH (p:Person) WHERE LOWER(REPLACE(p.country, '_', ' ')) = LOWER(REPLACE($value, '_', ' ')) RETURN DISTINCT p.country AS value, 'FinGraph.Person.country' AS columns, 'Person country' AS concept_type, 0 AS distance, JSON '{}' AS context)",
         "concept_type": "Person country",
         "description": "Match for country names on Person nodes in FinGraph that ignores case and treats underscores as spaces"
       },
       {
         "query": "SELECT value, columns, concept_type, distance, context FROM GRAPH_TABLE(FinGraph MATCH (a:Account) WHERE LOWER(a.nick_name) = LOWER($value) RETURN DISTINCT a.nick_name AS value, 'FinGraph.Account.nick_name' AS columns, 'Account nickname' AS concept_type, 0 AS distance, JSON '{}' AS context)",
         "concept_type": "Account nickname",
         "description": "Case-insensitive match for account nicknames on Account nodes in FinGraph"
       }
     ]
   }
   ```

   Each value search uses the `GRAPH_TABLE` operator to match a node label in `FinGraph` and returns the stored property value, the property location (`FinGraph.Person.country`), the concept type, a distance of `0` for a match, and an empty JSON context. For more information, see [Value search queries](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/context-sets-overview.md.txt#value-search-queries).

## Upload the context set file to QueryData

In this section, you upload the `context_set.json` file to your `fingraph-assistant` context set in Spanner Studio.

1. In the Google Cloud console, go to the Spanner page.

   [Go to Spanner](https://console.cloud.google.com/spanner)
2. Select your instance from the list, and then select your Spanner database.

3. In the navigation menu, click **Spanner Studio**.

4. In the **Explorer** pane, next to your `fingraph-assistant` context set, click **View actions**.

5. Click **Edit context set**.

6. Optional: Edit **Context set description**.

7. Click **Browse** in the **Upload context set file** section, and select the `context_set.json` file you generated.

8. Click **Save**.

## Generate GQL queries using QueryData

In this section, you call the `QueryData` REST API with your `fingraph-assistant` context set to verify that QueryData accurately translates business terms such as `high-risk transfers` and resolves `Czech Republic` to `Czech_Republic` in GQL queries.

> [!NOTE]
> **Note:** Generative AI models are nondeterministic, meaning the same prompt might yield different responses across separate calls.

1. Find the context set ID for `fingraph-assistant`. For instructions, see [Find the context set ID](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/inspect-data-agent.md.txt#find-context-id).
2. Set the `CONTEXT_SET_ID` environment variable so that `query_data.sh` sends your context set:

   ```
   export CONTEXT_SET_ID="CONTEXT_SET_ID"
   ```

   Replace `CONTEXT_SET_ID` with the complete context set ID, such as `projects/my-project/locations/us-central1/contextSets/fingraph-assistant`.
3. Ask the high-risk transfers question again:

   ```
   ./query_data.sh "Find all high-risk transfers initiated by Alex"
   ```

   The generated GQL query now applies the blocked destination account filter (`is_blocked: true`) and amount threshold (`t.amount >= 200`):

   ```sql
   GRAPH FinGraph
   MATCH
     (p:Person {name: 'Alex'})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account {is_blocked: true})
   WHERE
     t.amount >= 200
   RETURN
     dst.id AS destination_account_id,
     t.amount AS transfer_amount
   ORDER BY
     t.amount DESC;
   ```

   This excludes Alex's transfer of `100` to blocked account `16` and returns results similar to the following:

       +---+---+
       | destination_account_id | transfer_amount |
       +---+---+
       | 16                     | 300             |
       +---+---+

4. Ask a similar question for `Dana`:

   ```
   ./query_data.sh "What are the high-risk transfers initiated by Dana?"
   ```

   Because the GQL template in `context_set.json` is parameterized (`{name: ?}`), QueryData applies the same `high-risk transfers` definition to `Dana`:

   ```sql
   GRAPH FinGraph
   MATCH
     (p:Person {name: 'Dana'})-[:Owns]->(src:Account)-[t:Transfers]->(dst:Account {is_blocked: true})
   WHERE
     t.amount >= 200
   RETURN
     dst.id AS destination_account_id,
     t.amount AS transfer_amount
   ORDER BY
     t.amount DESC;
   ```

   This excludes Dana's transfer of `500` to unblocked account `7` and returns results similar to the following:

       +---+---+
       | destination_account_id | transfer_amount |
       +---+---+
       | 16                     | 200             |
       +---+---+

5. Ask the country question again:

   ```
   ./query_data.sh "Find accounts owned by people from Czech Republic"
   ```

   QueryData runs the `Person country` value search, links `Czech Republic` to the stored value `Czech_Republic`, and generates a query similar to the following:

   ```sql
   GRAPH FinGraph
   MATCH
     (p:Person {country: 'Czech_Republic'})-[:Owns]->(a:Account)
   RETURN
     p.name AS owner_name,
     a.id AS account_id,
     a.nick_name;
   ```

   This returns results similar to the following:

       +---+---+---+
       | owner_name | account_id | nick_name      |
       +---+---+---+
       | Dana       | 20         | Rainy Day Fund |
       +---+---+---+

6. Ask a question that uses the blocked-account facet:

   ```
   ./query_data.sh "Find all money transfers involving a blocked account."
   ```

   QueryData uses the facet to match transfers in either direction that involve blocked account `16`, and returns four transfers.

## Integrate QueryData with your application

In this section, you create a conversational data agent application for `FinGraph` using the [Agent Development Kit (ADK)](https://github.com/google/adk-python), MCP Toolbox, and your `fingraph-assistant` context set. To enable GQL query generation for Spanner Graph, you define a custom [HTTP tool](https://mcp-toolbox.dev/integrations/http/) in your `tools.yaml` file that calls the `QueryData` REST API with `graph_ids` set in `spanner_reference.database_reference`.

> [!NOTE]
> **Note:** The prebuilt MCP Toolbox QueryData tool doesn't accept `graph_ids`, so this tutorial defines an HTTP tool that calls the QueryData endpoint directly.

1. Download [MCP Toolbox](https://mcp-toolbox.dev/documentation/introduction/) version 1.4.0 or later. MCP Toolbox exposes the `QueryData` REST API as an MCP tool for applications to connect with.
2. Set up [Application Default Credentials (ADC)](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt):

   ```bash
   gcloud auth application-default login
   ```
3. Create a `tools.yaml` configuration file that defines an HTTP source for the Conversational Analytics API and an HTTP tool that calls the `QueryData` method. Make sure to specify `graph_ids` (set to `["FinGraph"]`) under `spanner_reference.database_reference` in the request body:

   ```yaml
   kind: source
   name: gda-rest-source
   type: http
   baseUrl: https://geminidataanalytics.googleapis.com
   timeout: 120s
   headers:
     Authorization: Bearer ${GDA_ACCESS_TOKEN}
     Content-Type: application/json
     x-goog-user-project: ${PROJECT_ID}
   ---
   kind: tool
   name: fingraph_query_data_tool
   type: http
   source: gda-rest-source
   method: POST
   path: /v1beta/projects/${PROJECT_ID}/locations/global:queryData
   description: Use this tool to send natural language questions about the FinGraph property graph to the QueryData API and receive GQL queries, query results, natural language answers, and explanations.
   requestBody: |
     {
       "parent": "projects/${PROJECT_ID}/locations/global",
       "prompt": {{json .query}},
       "context": {
         "datasource_references": {
           "spanner_reference": {
             "database_reference": {
               "engine": "GOOGLE_SQL",
               "project_id": "${PROJECT_ID}",
               "instance_id": "${INSTANCE_ID}",
               "database_id": "${DATABASE_ID}",
               "graph_ids": ["FinGraph"]
             },
             "agent_context_reference": {
               "context_set_id": "${CONTEXT_SET_ID}"
             }
           }
         }
       },
       "generation_options": {
         "generate_query_result": true,
         "generate_natural_language_answer": true,
         "generate_explanation": true,
         "generate_disambiguation_question": true
       }
     }
   bodyParams:
     - name: query
       type: string
       description: A natural language question about the FinGraph property graph.
   ```

   MCP Toolbox replaces the `${...}` references with the values of the corresponding environment variables when it loads `tools.yaml`, and replaces `{{json .query}}` with the question that the agent sends to the tool, encoded as a JSON string.
4. In the terminal where you run MCP Toolbox, set the environment variables that `tools.yaml` references:

   ```
   export PROJECT_ID="PROJECT_ID"
   export INSTANCE_ID="INSTANCE_ID"
   export DATABASE_ID="DATABASE_ID"
   export CONTEXT_SET_ID="CONTEXT_SET_ID"
   export GDA_ACCESS_TOKEN="$(gcloud auth application-default print-access-token)"
   ```

   Replace the following:
   - `PROJECT_ID`: your Google Cloud project ID.
   - `INSTANCE_ID`: the ID of your Spanner instance.
   - `DATABASE_ID`: the ID of the Spanner database that contains `FinGraph`.
   - `CONTEXT_SET_ID`: the complete context set ID of `fingraph-assistant`.

   > [!NOTE]
   > **Note:** The access token in `GDA_ACCESS_TOKEN` expires after about one hour. When it expires, regenerate the token and restart MCP Toolbox. For production applications, use a service account and a server-side token refresh mechanism instead of a static token.

5. Run the MCP Toolbox server with the `tools.yaml` file:

   ```console
   ./toolbox --config "tools.yaml"
   ```

   > [!NOTE]
   > **Note:** Don't close the terminal window where the MCP Toolbox server is running.

6. Create an ADK application that invokes the `fingraph_query_data_tool` tool using the MCP Toolbox Python SDK:

   1. Create and change to a directory for the application, such as `fingraph-assistant-app`:

      ```console
      mkdir fingraph-assistant-app
      cd fingraph-assistant-app
      ```
   2. Create a virtual environment and install the required packages:

      ```console
      python3 -m venv .venv
      source .venv/bin/activate
      pip install toolbox-core
      pip install google-genai
      pip install google-adk
      ```
   3. Create an ADK agent:

      ```console
      adk create my_agent
      ```
   4. Select the `gemini-2.5-flash` model, select **Google AI** , and enter your Gemini API key. For more information, see [Using Gemini API keys](https://ai.google.dev/gemini-api/docs/api-key).

   5. Replace the contents of `my_agent/agent.py` with the following Financial Graph Assistant sample application code:

      ```python
      from typing import cast

      from google.adk.agents.llm_agent import Agent
      from google.adk.agents.llm_agent import ToolUnion

      from toolbox_core import ToolboxSyncClient

      TOOLBOX_URL = "http://127.0.0.1:5000"

      INSTRUCTION = """
      # ROLE
      You are a factual financial graph data assistant for FinGraph. Your goal is to help users analyze account ownership, money transfers, and risk patterns by providing accurate information with a helpful, professional tone.
      - Always call the Query Data Tool first to answer questions about the graph data, including questions with domain-specific terms (such as "high-risk"), because the tool resolves domain definitions against the database context. Ask the user to clarify only if the tool returns a disambiguation question or fails to generate a valid query.

      # OPERATIONAL CONSTRAINTS
      - TOOL LIMITATION: You only have access to the Query Data Tool. Do not claim to have capabilities beyond what this tool provides.
      - TRANSPARENCY POLICY: Maintain a seamless user experience. Never mention that you are using a tool, querying a database, or generating GQL. Frame all responses as your own direct assistance.
      - SCOPE MANAGEMENT: If a user asks for something beyond your capabilities, politely state that you cannot perform that specific task and guide the user toward what you can help with.

      # COMMUNICATION STYLE
      - Be concise and scannable when listing answers.
      - Maintain a helpful, professional persona.

      =====

      # QUERY DATA TOOL

      Inputs:
      1. query: A natural language formulation of a graph database query.

      Outputs: (all optional)
      1. disambiguationQuestion: Clarification questions or comments where the tool needs the user's input.
      2. generatedQuery: The generated GQL query for the user query.
      3. intentExplanation: An explanation for why the tool produced `generatedQuery`.
      4. queryResult: The result of executing `generatedQuery`.
      5. naturalLanguageAnswer: The natural language answer that summarizes the `query` and `queryResult`.

      Usage guidance:
      1. If `disambiguationQuestion` is produced, solicit the needed inputs from the user and try the tool with a new `query` that includes the clarification.
      2. If `naturalLanguageAnswer` is produced, use `intentExplanation` and `generatedQuery` to see if you need to clarify any assumptions for the user.
      3. If the tool output indicates failure or empty results, explain that clearly using the provided reasoning.
      """

      client = ToolboxSyncClient(TOOLBOX_URL)

      mcp_tool = client.load_tool("fingraph_query_data_tool")

      root_agent = Agent(
          model="gemini-2.5-flash",
          name="root_agent",
          instruction=INSTRUCTION,
          tools=cast(list[ToolUnion], [mcp_tool]),
      )
      ```
7. Start the ADK web server at `http://127.0.0.1:8000`:

   ```console
   adk web --port 8000
   ```
8. Enter a multi-hop graph question in the ADK web UI:

       Who did Dana transfer money to, and what were the amounts?

   The agent calls the `fingraph_query_data_tool` tool, which sends the question to the `QueryData` REST API with `graph_ids` set to `FinGraph`. QueryData runs the generated GQL query, and the agent returns a response similar to the following:

       Dana transferred money from account 20 to the following recipients:

       * Alex (account 7): 500
       * Lee (account 16): 200

9. Enter a question that uses the `high-risk transfers` GQL template you added to the context set:

       What are the high-risk transfers initiated by Alex?

   Based on the GQL template in `fingraph-assistant`, QueryData identifies transfers of at least `200` to a blocked account, and the agent returns a response similar to the following:

       Here is the high-risk transfer initiated by Alex (transfers of 200 or more to a blocked account):

       * Blocked destination account 16: amount 300

## Iterate agent performance

The ADK web UI lets you inspect the request and response payloads from the `fingraph_query_data_tool` tool. In the **Event** tab in the navigation pane, expand `functionResponse` to inspect the generated `FinGraph` GQL query (`generatedQuery`), `queryResult`, `intentExplanation`, `disambiguationQuestion`, and `naturalLanguageAnswer`. The `QueryData` REST API returns these field names in camelCase.

### Refine response accuracy

You can continuously refine the accuracy of responses from QueryData by adding GQL templates, facets, and value searches. Use the [context engineering agent](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/build-context-sets.md.txt) to generate and evaluate updated context for the `FinGraph` property graph in your Spanner database, and then upload the updated context set file in Spanner Studio. For more information, see [Manage context sets in Spanner Studio](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/manage-data-agents.md.txt).

### Multiple agents

In your development environment, you can perform A/B testing on multiple Spanner Graph context sets by defining multiple HTTP tools in your `tools.yaml` file (such as `fingraph_query_data_tool_v1` and `fingraph_query_data_tool_v2`). Each tool's request body sets `graph_ids` to `["FinGraph"]` and a different `context_set_id`.

## Clean up

To avoid continued billing, delete the resources you created when you finish this tutorial.

### Delete the context set

Before you delete the Spanner database or instance, delete the `fingraph-assistant` context set:

1. In the Google Cloud console, go to the Spanner page.

   [Go to Spanner](https://console.cloud.google.com/spanner)
2. Select your instance from the list, and then select your Spanner database.

3. In the navigation menu, click **Spanner Studio**.

4. In the **Explorer** pane, next to `fingraph-assistant`, click **View actions**.

5. Click **Delete context set** , enter `fingraph-assistant` in the confirmation field, and click **Confirm**.

### Delete the database and instance

To delete the `FinGraph` property graph, Spanner database, and Spanner instance, follow the steps in [Set up and query Spanner Graph: Clean up](https://docs.cloud.google.com/spanner/docs/graph/set-up.md.txt#clean-up).

## What's next

- Learn more about [context sets for Spanner Graph](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/context-sets-overview.md.txt).
- Learn how to [build context sets using the context engineering agent](https://docs.cloud.google.com/gemini/data-agents/querydata/spanner-graph/build-context-sets.md.txt).
- Learn how to [define authored context for database data sources](https://docs.cloud.google.com/gemini/data-agents/conversational-analytics-api/data-agent-authored-context-databases.md.txt).