Skip to content
Blog

GraphQL API Integration as Dynamic ADK Tools

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.

Published on • November 28, 2026

AI Assistant

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

ApproachModel experienceSafetyCost
One graphql(query) toolMust free-type a query stringWorst — full query surface, no allow-listCheap to build, expensive to run
Named operations as generated toolsPicks a tool, fills typed argsGood — only registered operations executeBuild-time introspection
REST/OpenAPI wrapper or MCP serverSame as above, outside the agentGood, plus server-side policyHighest 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:

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:

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). 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.

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:
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]))
  1. 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 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:

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.

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