Skip to content
Blog

Dependency Injection in ADK: Supplying Services and Adapters to Agents

A practical guide to wiring services, model adapters, and tool dependencies into Google ADK — from constructor injection and the App class to scoped per-request services.

Published on • November 25, 2026

AI Assistant

ADK agents are ordinary Python objects, which means they get dependency injection the ordinary way: you build them with the things they need. What makes ADK specific is which seams exist — the App container, the Runner’s service slots, InvocationContext, and plain constructor arguments — and knowing which one to use for which kind of dependency.

The rule of thumb: lifecycle dependencies go in App or Runner, per-invocation dependencies arrive via context, and pure logic dependencies are constructor arguments.

Why injection matters more here than usual

An agent system accumulates a surprising number of long-lived collaborators: session storage, artifact storage, vector search, HTTP clients, credential providers, feature flag clients. Passing them ad hoc means every agent module grows a global _client — which is exactly the pattern that makes testing painful and multi-tenant isolation hard.

ADK gives you four real seams. Let’s take them in order of scope.

Seam 1: constructor injection for tools and sub-agents

The simplest and most Pythonic seam. A tool is a function, but a tool class is a BaseTool, and it can hold collaborators.

from google.adk.tools import FunctionTool

class BillingClient:
    def __init__(self, base_url: str, timeout: float = 5.0):
        self.base_url, self.timeout = base_url, timeout

    def lookup_invoice(self, invoice_id: str) -> dict:
        ...

def make_billing_tool(client: BillingClient) -> FunctionTool:
    def lookup_invoice(invoice_id: str) -> dict:
        """Look up an invoice by its identifier."""
        return client.lookup_invoice(invoice_id)
    return FunctionTool(func=lookup_invoice)

billing_tool = make_billing_tool(BillingClient(base_url="https://billing.internal"))

This pattern — a factory that closes over the dependency — keeps the tool function signature clean (the model only ever sees invoice_id) while the real client lives in a closure. It is also trivially fakeable in tests:

fake_tool = make_billing_tool(FakeBillingClient(invoices={"INV-1": {...}}))

Prefer this over module-level singletons every time. Module globals are ambient dependencies, and ambient dependencies are what break multi-tenant isolation.

Seam 2: the App container for application-scoped resources

The App class (ADK Python v1.14.0+) is explicitly designed as the centralized configuration point. Its stated purposes include avoiding the need to “pass configuration down through every agent,” plus startup/shutdown lifecycle hooks for resources like connection pools.

from google.adk.agents.llm_agent import Agent
from google.adk.apps import App

root_agent = Agent(
    model="gemini-flash-latest",
    name="greeter_agent",
    instruction="Reply with Hello, World!",
)

app = App(
    name="agents",
    root_agent=root_agent,
    # plugins, context_cache_config, events_compaction_config, resumability_config
)

App also defines an explicit state scope with an app:* prefix, so application-level state has a declared lifetime separate from conversation state. That’s the correct home for “the feature-flag client everyone shares” — one instance, one lifecycle, one place to look.

Run it by handing app to the runner:

from google.adk.runners import InMemoryRunner

runner = InMemoryRunner(app=app)

Seam 3: Runner service slots for framework services

The services ADK itself consumes — session, artifact, memory — are constructor dependencies of Runner, not of your agents:

from google.adk.runners import Runner
from google.adk.sessions import DatabaseSessionService
from google.adk.artifacts import InMemoryArtifactService

runner = Runner(
    app_name="my_app",
    agent=my_root_agent,
    session_service=DatabaseSessionService(...),
    artifact_service=InMemoryArtifactService(),
)

This is where multi-tenant systems do their real work: swapping InMemorySessionService for a database-backed one is a single injection point, not a refactor. Same for pointing ArtifactService at a tenant-namespaced bucket.

Treat these as process-lifetime dependencies. Build them once at startup, share them, and let the framework manage their use across invocations.

Seam 4: context objects for per-invocation dependencies

Not everything is process-scoped. The current user’s credentials, the function_call_id of the in-flight tool call, the session’s state — these exist only for one invocation.

ADK models this with a family of context types rather than one god object:

  • InvocationContext — the full view: session, agent, invocation_id, user_content, and references to all configured services. Received as ctx inside _run_async_impl / _run_live_impl.
  • ReadonlyContext — a restricted, read-only view. Used where mutation is disallowed, e.g. instruction providers. Its state is a mappingproxy.
  • Context (formerly CallbackContext/ToolContext, now unified) — mutable state, artifact load/save, user_content. Used in agent lifecycle and model callbacks.
  • Context in tools — adds request_credential, request_confirmation, search_memory, list_artifacts, and the function_call_id property. Tool-only members raise ValueError unless a tool call is actually in progress.
from google.adk.tools import ToolContext

def search_orders(query: str, tool_context: ToolContext) -> dict:
    # Per-invocation dependency: this session's state, this call's ID
    tenant = tool_context.state.get("app:tenant")
    call_id = tool_context.function_call_id
    return {"tenant": tenant, "call": call_id, "results": []}

Note the discipline: InvocationContext is for the agent’s core logic; everything narrower should take the narrowest context that works. A tool asking for InvocationContext is asking for more authority than it needs.

Choosing the right seam

DependencyLifetimeSeam
HTTP client, DB pool, flag clientprocessApp or your own composition root
Session / artifact / memory storageprocessRunner constructor
Tenant config, feature flagsappApp + app:* state
Current session’s stateinvocationContext.state
Credentials for a tool calltool callToolContext.request_credential
Pure business logicnoneplain constructor arg

Anti-patterns to avoid

Global mutable clients. db = create_client() at import time. It breaks parallel tests, leaks across tenants, and can’t be faked. Wrap it in a factory and inject.

Reading secrets from InvocationContext.state. State is persisted with the session and can be replayed, inspected, and logged. Secrets belong in a secret manager, referenced by ID; ToolContext can request credentials at call time instead.

Injecting the whole context into a pure function. If a function takes ToolContext but only uses it to read one string, pass the string. Narrow signatures are testable signatures.

Building the container inside a tool. Creating a new DB client per tool call defeats pooling and makes failures invisible. Compose once, inject everywhere.

Testing the injected graph

The payoff for doing this properly is that the whole agent becomes constructible with fakes:

def test_billing_tool_uses_client(monkeypatch):
    fake = FakeBillingClient(invoices={"INV-1": {"total": 42}})
    tool = make_billing_tool(fake)

    result = tool.func(invoice_id="INV-1")

    assert result["total"] == 42
    assert fake.calls == ["INV-1"]

For agent-level tests, build a real Runner with an InMemorySessionService and a fake model adapter. Because storage was injected rather than imported, the test never touches the network or a shared database.

Where to go next

Injection is the plumbing that makes the rest of the system testable. From here, look at the InvocationContext lifecycle and thread-safety rules for what arrives through the context seam, multi-tenant scoping for what belongs behind the injection points, and exception handling and fallback strategies for what happens when an injected dependency fails at runtime.

References