---
title: "Defining Function Tools in ADK: Type Hints, Docstrings, and Validation"
date: "2026-11-27T08:24:00+07:00"
description: "How a plain Python function becomes an ADK tool — what the schema generator reads, the required-vs-optional rules, docstring structure as the model's contract, return conventions, and the failure modes that make tools misbehave."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-function-tools-type-hints-docstrings.jpg"
alt: "Python function being wrapped into a labeled toolbox"
tags: ['google-adk', 'function-tools', 'python', 'schema', 'best-practices']
---

A function tool is the smallest complete unit of an ADK agent: a Python function whose signature the framework reads, turns into a JSON schema, and shows to the model. The model never sees your source code — only that schema and the docstring. So the quality of your tool *is* the quality of that generated description.

This tutorial covers exactly what ADK reads, the rules that decide required vs optional, how to write a docstring the model can act on, how return values and context injection work, and the mistakes that produce confident wrong calls.

## What the framework reads

Assign a function to an agent's `tools` list and ADK wraps it in a `FunctionTool`. The schema comes from inspecting:

- **Function name** → tool name (the model matches on it).
- **Docstring** → the tool's *description* — the single most influential string you write.
- **Type hints** → parameter types.
- **Default values** → optionality.
- **Return type** → how the result is packaged.

```python
from google.adk import Agent

def get_weather(city: str, unit: str = 'celsius') -> dict:
    """Retrieve the current weather for a city.

    Args:
        city (str): City name, e.g. 'Bangkok'.
        unit (str): Temperature unit, 'celsius' or 'fahrenheit'. Defaults to 'celsius'.

    Returns:
        dict with 'status' and 'report'.
    """
    ...

agent = Agent(name='helper', model='gemini-3.8-flash', tools=[get_weather])
```

## Required vs optional: the rule people get wrong

- A parameter is **required** if it has a type hint and **no default value**.
- A parameter is **optional** only if it has a **default value**.
- Annotating `Optional[str]` *without* a default leaves it **required** — the annotation alone does not make it optional.

Consequences worth internalising:

```python
def search(term: str, limit: int) -> ...            # both required; model must supply both
def search(term: str, limit: int = 10) -> ...       # limit optional
def search(term: str, limit: int | None = None) -> ...  # optional, nullable semantics

def do_stuff(*args, **kwargs):                      # *args/**kwargs are IGNORED by the schema
    ...                                             # the model cannot pass them — use real params
```

If ADK gets a required argument missing, it returns an error to the model so it can correct the call — which is helpful once and wasteful if it repeats. Getting optionality right the first time removes a whole class of multi-call turns.

**Defaults are not free**: a default the model should *never* silently use (a date, a tenant, an ID) belongs as a required parameter. Use defaults only for genuinely interchangeable values — units, formats, page sizes.

## The docstring is the contract

ADK sends the docstring as the tool's top-level description; it is what the model reasons over when choosing and filling the call.

```python
def issue_refund(order_id: str, reason: str) -> dict:
    """Issue a full refund for an order. Use only after the user has explicitly
    confirmed the refund amount and the order ID.

    Do not call this for partial refunds (use issue_partial_refund) or for
    orders older than 30 days (return an error instead).

    Args:
        order_id (str): Order identifier, format 'A-12345'. Must come from the
            user or from get_orders — never invent one.
        reason (str): Short reason recorded on the refund, e.g. 'item damaged'.

    Returns:
        dict: {'status': 'success'|'error', 'refund_id': str, 'error_message': str}
    """
    ...
```

Notice what's packed in: the **preconditions** (confirm first), the **boundaries** (not partial, not old orders), **argument provenance** ("never invent one"), and the **return shape** including error form. That's the same information a system instruction's decision table provides — see [meta-prompting for tool calling](/blog/system-instruction-meta-prompting-deterministic-tool-calling) — but scoped to one tool.

Practical docstring rules:

- **First line: what it does and when to use it.** The model chooses between tools mostly on this.
- **Name the near-miss tools explicitly** so the model can discriminate between overlapping functions.
- **State constraints on values**: formats, ranges, allowed enums.
- **Document the error contract**: what a failure returns, and what the model should do about it.
- Keep it stable — docstrings are part of your prompt surface, and they change your cache prefix.

## Return values: speak the model's language

- Return a **dict** — that's the preferred shape. Non-dict returns get wrapped in `{'result': ...}`.
- Include a **`status` key** (`success` / `error` / `pending`) so the model can branch.
- Return **descriptive text, not codes**: `{'error_message': 'Order A-1 is older than 30 days'}` beats `{'code': 4031}`.
- Keep payloads **bounded** — one tool returning 40 KB of JSON sets your cost floor for every subsequent turn (see [token budgeting](/blog/token-budgeting-cache-aware-prompting)).

```python
def get_order(order_id: str) -> dict:
    """Fetch a single order by ID.

    Args:
        order_id (str): Order identifier, format 'A-12345'.
    """
    order = orders.lookup(order_id)
    if order is None:
        return {'status': 'error', 'error_message': f'No order {order_id} exists.'}
    return {
        'status': 'success',
        'id': order.id,
        'state': order.state,
        'total': order.total,
        'summary': f'Order {order.id} is {order.state}, total {order.total}.',
    }
```

That `summary` line is deliberate: it gives the model a sentence it can quote directly, so the final answer doesn't require a second pass over a raw structure.

## Context injection

A parameter typed `ToolContext` is injected by the framework and hidden from the model — this is how a tool reaches session state, actions, and artifacts:

```python
from google.adk.tools import ToolContext

def record_preference(topic: str, value: str, ctx: ToolContext) -> dict:
    """Remember a user preference for later turns.

    Args:
        topic (str): Preference topic, e.g. 'language'.
        value (str): Preferred value.
    """
    ctx.state[f'pref_{topic}'] = value
    return {'status': 'success', 'saved': topic}
```

Detection is by **type annotation**, not name — `ctx`, `tool_context`, `c` all work. Between tools, pass data with the `temp:` state prefix: `ctx.state['temp:last_id']`, available for the current invocation only.

## Design and testing checklist

- **Fewer parameters is better.** Every parameter is another chance for a wrong call.
- **Simple types over classes** where a class doesn't buy validation; use a Pydantic model when it does ([covered next](/blog/pydantic-base-models-tool-arguments)).
- **Meaningful names.** `get_order_status()` beats `do_thing()`; the name is read as much as the description.
- **Build for parallel execution**: `async def` where the work is I/O-bound.
- **Assert the generated schema in a test.** Parse the tool declaration and check names, required lists, and enum values — schema regressions are invisible until a user hits them.

```python
def test_tool_schema():
    tool = FunctionTool(func=get_order)
    decl = tool.get_declaration()
    assert 'order_id' in decl.parameters['required']
```

## Takeaways

- The model sees only the schema and docstring — write them as a contract: purpose, preconditions, argument provenance, return shape.
- Required = type hint without a default; `Optional[...]` alone does not make it optional; `*args/**kwargs` never reach the model.
- Defaults are for interchangeable values only — IDs, dates, and tenant scoping must be required.
- Return dicts with a `status` key and a quotable `summary`; bound the payload size.
- Inject context via a `ToolContext`-typed parameter (detected by annotation), and assert the generated schema in CI.

## Further reading

- [Pydantic BaseModels as tool arguments](/blog/pydantic-base-models-tool-arguments)
- [Synchronous vs asynchronous tool implementations](/blog/sync-vs-async-tools-adk)
- [Tool errors and recoverable exceptions](/blog/adk-tool-errors-recoverable-exceptions)
- [The anatomy of agents, runners, sessions, events, and tools](/blog/adk-anatomy-agents-runners-sessions-events-tools)
