Defining Function Tools in ADK: Type Hints, Docstrings, and Validation
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.
Published on • November 27, 2026
AI Assistant

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.
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:
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.
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 — 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
statuskey (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).
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:
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).
- Meaningful names.
get_order_status()beatsdo_thing(); the name is read as much as the description. - Build for parallel execution:
async defwhere 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.
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/**kwargsnever reach the model. - Defaults are for interchangeable values only — IDs, dates, and tenant scoping must be required.
- Return dicts with a
statuskey and a quotablesummary; bound the payload size. - Inject context via a
ToolContext-typed parameter (detected by annotation), and assert the generated schema in CI.