---
title: "GraphQL API Integration as Dynamic ADK Tools"
date: "2026-11-28T11:15:00+07:00"
description: "Turn a GraphQL API into typed ADK tools: introspect the schema at build time, expose named operations with variables, batch requests, and shape responses for the model."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/graphql-api-dynamic-adk-tools.jpg"
alt: "Abstract network of connected nodes representing a GraphQL schema on a dark gradient"
tags: ['google-adk', 'adk-tools', 'graphql', 'api-integration', 'httpx']
---

Exposing a GraphQL API to an agent as a single `graphql(query: str)` tool is the fastest way to build a toy and the slowest way to build a production agent: the model must invent a query string against a schema it has never seen, and you inherit every depth, cost, and injection risk the endpoint exposes. The better shape is a small set of named, typed operations — generated from the schema itself — that the model picks from like any other function tool.

This tutorial covers reading a GraphQL schema with introspection, compiling it into ADK function tools with typed variables, batching calls safely, and returning payloads the model can actually use.

## The three ways to expose GraphQL

| Approach | Model experience | Safety | Cost |
|---|---|---|---|
| One `graphql(query)` tool | Must free-type a query string | Worst — full query surface, no allow-list | Cheap to build, expensive to run |
| Named operations as generated tools | Picks a tool, fills typed args | Good — only registered operations execute | Build-time introspection |
| REST/OpenAPI wrapper or MCP server | Same as above, outside the agent | Good, plus server-side policy | Highest upfront effort |

For agent use, named operations win: the schema becomes tool descriptions, variables become parameters, and unknown mutations simply do not exist as far as the model is concerned.

## Introspect the schema at build time

GraphQL exposes its own type system through the `__schema` field on the query root — types, fields, arguments, descriptions, and enum values. That is exactly the material ADK needs for a tool declaration, so run introspection in a build step (or against staging, since many production endpoints disable introspection to shrink their attack surface). The registry it emits is a build artifact, checked into the repo like an OpenAPI file — regenerating it is a code change, reviewed like any other:

```python
import httpx

INTROSPECTION = """
query Introspect {
  __schema { queryType { fields { name description
    args { name type { kind name ofType { kind name } } } } } }
}"""

async def build_registry(endpoint: str) -> dict:
    async with httpx.AsyncClient(timeout=10) as client:
        resp = await client.post(endpoint, json={"query": INTROSPECTION})
        resp.raise_for_status()
    fields = resp.json()["data"]["__schema"]["queryType"]["fields"]
    return {f["name"]: {"description": f.get("description") or "", "args": f["args"]}
            for f in fields}
```

## Compile operations into ADK tools

Each tool wraps *one named operation* with *variables*, never with a query string interpolated by the model:

```python
GET_ORDER = """query GetOrder($id: ID!) {
  order(id: $id) { id state total items { sku qty } }
}"""

async def get_order(id: str) -> dict:
    """Fetch a single order by its ID.

    Args:
        id (str): Order identifier, e.g. 'A-12345'.
    """
    payload = await graphql_call(GET_ORDER, {"id": id})
    if payload.get("errors"):
        return {"status": "error", "error_message": payload["errors"][0]["message"][:300]}
    order = payload["data"]["order"]
    return {"status": "success", "id": order["id"], "state": order["state"],
            "total": order["total"],
            "summary": f"Order {order['id']} is {order['state']}, total {order['total']}."}

agent = Agent(name="commerce", model="gemini-3.8-flash", tools=[get_order, search_products])
```

The wrapper is thin on purpose: fixed document, typed variables, shaped result. You can generate these functions from the introspection registry at import time instead of hand-writing them — but a *generated* function must declare real parameters. ADK ignores `*args`/`**kwargs` when it builds the schema, so a `**kwargs`-only wrapper reaches the model with no arguments at all, and nested inputs are better expressed as Pydantic models ([covered separately](/blog/pydantic-base-models-tool-arguments)). The docstring stays the model's only description of what the operation does.

## Never interpolate: variables only

GraphQL variable values are sent in a separate `variables` map and type-checked by the server — that is the equivalent of parameter binding for GraphQL. String-splicing a search term into the document (`products(query: "${q}")`) reintroduces the exact class of injection SQL parameterisation removed. A registry of named operations also doubles as operation safe-listing: whatever the model sends, only pre-approved documents reach the wire.

```python
async def graphql_call(query: str, variables: dict) -> dict:
    async with httpx.AsyncClient(timeout=10) as client:
        resp = await client.post(
            ENDPOINT,
            json={"query": query, "variables": variables},
            headers={"Authorization": f"Bearer {get_token()}"},
        )
        resp.raise_for_status()
        return resp.json()
```

Cap the timeout, and treat a GraphQL `200` response carrying an `errors` array as a failure — GraphQL reports execution errors in the body, not the status line.

## Batch without turning one call into fifty

Three legitimate batching strategies, in increasing order of control:

1. **Aliases in one document.** `a1: order(id:$i1) a2: order(id:$i2)` returns several results in a single round trip — great for "check these five IDs" follow-ups.
2. **Async fan-out with a concurrency bound.** Independent queries can run together; bound them so a model that asks for 50 lookups does not open 50 sockets:

```python
import asyncio

async def fan_out(ids: list[str]) -> list[dict]:
    sem = asyncio.Semaphore(5)
    async def one(oid: str) -> dict:
        async with sem:
            return await get_order(id=oid)
    return await asyncio.gather(*(one(i) for i in ids[:20]))
```

3. **Batch arrays** (`[{query, variables}, ...]`) where the endpoint supports them — verify before relying on it; batching support is server-specific.

Aggregate before returning: twenty full order objects is a context-flood; a compact table of `{id, state, total}` plus a `truncated` flag is not. That boundary is [pagination and batch processing](/blog/pagination-batch-processing-tools) territory.

## Shape the result for the model

GraphQL payloads are deep and verbose — `__typename` everywhere, nullable wrappers, nested connections. The model wants a shallow dict with a status and a sentence:

```python
return {
    "status": "success",
    "items": [{"id": o["id"], "state": o["state"], "total": o["total"]} for o in orders],
    "count": len(orders),
    "summary": f"Found {len(orders)} orders; states: {sorted({o['state'] for o in orders})}.",
}
```

Drop keys the model never references, flatten one level, and put anything large behind a `get_detail(id)` follow-up tool. Rationale and token economics are in [tool output formatting](/blog/tool-output-formatting-markdown-vs-json).

## Takeaways

- Do not expose a raw `graphql(query)` tool — compile named operations into individual tools whose docstrings come from schema descriptions.
- Introspect once at build time (`__schema`), store the registry as a reviewed artifact, and regenerate when the API changes.
- Send values through the `variables` map only; the operation allow-list is your injection defence.
- Batch with aliases or a semaphore-bounded `asyncio.gather`, aggregate the results, and cap what enters the context.
- Read GraphQL `errors` out of a `200` body, bound every request with a timeout, and surface failures as `status: error` with a readable `error_message`.

## Further reading

- [Pagination and batch processing patterns for high-volume tools](/blog/pagination-batch-processing-tools)
- [Tool output formatting: Markdown vs structured dictionaries](/blog/tool-output-formatting-markdown-vs-json)
- [Defining function tools in ADK](/blog/adk-function-tools-type-hints-docstrings)
- [Pydantic BaseModels as tool arguments](/blog/pydantic-base-models-tool-arguments)
- [GraphQL introspection](https://graphql.org/learn/introspection/)
- [ADK custom tools](https://adk.dev/tools-custom/)
