Skip to content
Visual explainer 3h to learn 5 steps

Write typed read-only function tools for an ADK agent

Define a typed, read-only ticket-status tool with a clear docstring, structured input and output, and predictable errors over local records.

By Invicly Tech, , in Google ADK with Python for AI Agents. About 12 minutes to read.

Topic 7 of 29

In short

A function tool is an ordinary Python function that an ADK agent may ask to run. ADK reads the function name, type hints, default values and docstring to build the schema the model sees, so those parts are the tool's real interface. A good support tool is read-only, takes a small typed input, returns a dictionary with a clear status and reports problems as data instead of crashing the run.

Think of it like this: A function tool is like a form at a service desk: the labels tell the visitor what to fill in, and the clerk always hands back a stamped slip, even when the answer is no.

Explained simply

A language model can only produce text. To check a real ticket, it needs your code to do the work. In ADK you give the agent a list of tools, and the simplest tool is a normal Python function. The model reads a short description of each tool and, when it decides one would help, it asks ADK to run it with some arguments.

ADK builds that description from your function. The function name becomes the tool name, the docstring becomes the description, and the type hints and defaults become the list of parameters. So a clear name, a clear docstring and exact types are not decoration. They are how the model learns what your tool does.

Your function returns a dictionary, for example status ok plus the ticket status. ADK sends that dictionary back to the model, and the model writes the reply for the user. If you return something that is not a dictionary, ADK wraps it under a key called result, which is less clear.

In this course every tool is read-only. It looks things up in local, made-up ticket records and never changes anything. That keeps mistakes cheap while you learn how the model chooses tools and arguments.

Press Play on a diagram to walk through it one step at a time.

FlowFrom Python function to tool result
  1. 1
    Define

    Typed parameters, docstring, dict return

  2. 2
    Register

    Put the function in the agent's tools list

  3. 3
    Schema

    ADK builds name, description and parameters

  4. 4
    Model call

    The model asks for the tool with arguments

  5. 5
    Run

    ADK calls your function and injects ToolContext

  6. 6
    Result

    The dict goes back to the model as a function response

CompareWeak tool versus strong tool
Weak
  • Untyped or catch-all parameters
  • Docstring missing or vague
  • Returns a free-text string
  • Raises on a missing ticket
Strong
  • Typed args, defaults only where optional
  • Docstring says when to use it and what each arg means
  • Returns a dict with a status field
  • Returns error_code NOT_FOUND as data
CycleOne tool turn inside an agent run
  1. 1
    Model reads tool list
  2. 2
    Model emits a function call
  3. 3
    ADK runs your function
  4. 4
    Function response event saved
  5. 5
    Model reads the result and replies or calls again
  6. Back to step 1

In depth

How ADK turns a function into a schema

When you add a function to an agent's tools list, ADK wraps it in a FunctionTool. It inspects the signature: each parameter's name and type becomes a field in the schema, the docstring becomes the description, and parameters with a default value are marked optional. A parameter typed Optional[str] with no default is still required, so write Optional[str] = None when you really mean optional. Pydantic models also work as parameter types; ADK converts the model's arguments into an instance before your code runs. ADK ignores catch-all star-args and keyword star-args parameters when it builds the schema, so the model never sees them. Keep the parameter list short and simple: strings, integers, booleans, enums written as Literal, and small lists. Each extra parameter is another thing the model can get wrong.

  • No default means required
  • Docstring means description
  • Literal["open", "closed"] limits allowed values
  • Pydantic BaseModel parameters are validated and converted

Writing a docstring the model can use

The model chooses tools by reading their descriptions, so write the docstring as a short instruction. Say what the tool does, when to use it and when not to, and the exact format of each argument. For example: Look up the status of one support ticket owned by the signed-in user. Use this when the user gives a ticket ID. Do not use it to search documentation. Then an Args section that says ticket_id is in the form T-1234. Mention what comes back, including the error codes, so the model can explain them. Avoid internal jargon and database names the model cannot act on. If two tools sound alike, make the difference explicit in both docstrings; overlapping descriptions are a common reason a model picks the wrong tool.

Structured results and errors as data

A predictable result shape makes the agent predictable. Return the same keys every time: a status field with a small set of values, the data on success, and an error_code plus a short safe message on failure. Use fixed error codes such as INVALID_ARGUMENT, NOT_FOUND and UPSTREAM_TIMEOUT. The model can then say the ticket ID looks wrong or the system is slow, try later, and your tests can assert exact values. Raise exceptions only for bugs you want to see in logs, not for normal outcomes such as a missing ticket. Never put stack traces, SQL or internal hostnames in the result, because the model may repeat them to the user.

MapOne result shape for every outcome
Tool result dict
  • status ok
    • ticket_id
    • ticket_status
    • updated_at
  • status error
    • error_code
    • message (safe, short)
  • error codes
    • INVALID_ARGUMENT
    • NOT_FOUND
    • UPSTREAM_TIMEOUT

ToolContext: state and identity without asking the model

Some information should never come from the model, above all who the user is. Add a parameter annotated with ToolContext and ADK fills it in at call time; ADK recognises it by its type, and it does not appear in the schema. tool_context.user_id is the user ID the runner was started with, which your server takes from the signed-in session. tool_context.state reads and writes session state, for example a preferred language. Use it for read-only lookups here. The same object also offers artifacts and memory, which belong to later topics.

  • tool_context.user_id: who is asking
  • tool_context.state: session state, including temp: keys
  • Never add a user_id parameter the model can fill in

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Type parameters and return values~35m
  2. 2
    Write a docstring the model can use~35m
  3. 3
    Return structured results~35m
  4. 4
    Report errors as data~35m
  5. 5
    Read from local synthetic tickets~35m

Key points

  • Putting a plain function in an agent's tools list is enough: ADK wraps it in a FunctionTool for you.
  • The docstring becomes the tool description the model reads, so write it for the model, not only for people.
  • A parameter is optional only when it has a default value; Optional[str] on its own still makes it required.
  • Return a dictionary; anything else is wrapped under a result key. Include a status field such as ok or error.
  • Add a ToolContext parameter to read session state or the user ID; ADK injects it and hides it from the model.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from google.adk.tools import ToolContext

TICKETS = {"T-1001": {"owner": "user-a", "status": "open"}}

def get_ticket_status(ticket_id: str, tool_context: ToolContext) -> dict:
    """Look up the status of one support ticket owned by the current user.

    Args:
        ticket_id: Ticket ID in the form T-1234.
    """
    ticket = TICKETS.get(ticket_id.strip().upper())
    if ticket is None or ticket["owner"] != tool_context.user_id:
        return {"status": "error", "error_code": "NOT_FOUND"}
    return {"status": "ok", "ticket_id": ticket_id, "ticket_status": ticket["status"]}

A typed, read-only tool over synthetic records. Someone else's ticket looks the same as a missing one.

A ticket-status tool with fixed error codes

The tool normalises the ID, checks the format, then looks up synthetic records. A ticket owned by another user returns NOT_FOUND, so the tool does not reveal that the ID exists. Register it with Agent(name="support", model="gemini-flash-latest", tools=[get_ticket_status]).

python
import re
from google.adk.tools import ToolContext

TICKETS = {"T-1001": {"owner": "user-a", "status": "open"}}
TICKET_ID = re.compile(r"^T-\d{4}$")

def get_ticket_status(ticket_id: str, tool_context: ToolContext) -> dict:
    """Get the status of one ticket owned by the signed-in user. ticket_id looks like T-1234."""
    ticket_id = ticket_id.strip().upper()
    if not TICKET_ID.match(ticket_id):
        return {"status": "error", "error_code": "INVALID_ARGUMENT"}
    ticket = TICKETS.get(ticket_id)
    if ticket is None or ticket["owner"] != tool_context.user_id:
        return {"status": "error", "error_code": "NOT_FOUND"}
    return {"status": "ok", "ticket_id": ticket_id, "ticket_status": ticket["status"]}

Optional filters done right

A second tool lists the user's tickets. status_filter is optional because it has a default of None, and Literal limits it to two values. The model sees a required-free schema with an enum, and limit is capped in code no matter what the model sends.

python
from typing import Literal, Optional
from google.adk.tools import ToolContext

def list_my_tickets(
    tool_context: ToolContext,
    status_filter: Optional[Literal["open", "closed"]] = None,
    limit: int = 5,
) -> dict:
    """List the signed-in user's tickets, newest first. Optionally filter by status."""
    mine = [t for t in TICKETS.values() if t["owner"] == tool_context.user_id]
    if status_filter:
        mine = [t for t in mine if t["status"] == status_filter]
    return {"status": "ok", "tickets": mine[: max(1, min(limit, 20))]}

Quick reference

  • A plain function in tools=[...] is wrapped as a FunctionTool automatically.
  • Docstring = tool description sent to the model. Write when to use it and the argument format.
  • A parameter is optional only with a default value, for example note: Optional[str] = None.
  • Return a dict with a status field; non-dict returns are wrapped under result.
  • Add tool_context: ToolContext to read user_id and state; it is hidden from the model.
  • Use fixed error codes: INVALID_ARGUMENT, NOT_FOUND, UPSTREAM_TIMEOUT.
  • Keep course tools read-only and backed by synthetic records.

Common mistakes

  • Writing the docstring for humans only, so the model cannot tell when to call the tool or what format the ID takes.
  • Raising an exception for an expected case such as an unknown ticket, which ends the turn instead of letting the model answer politely.
  • Accepting a user_id argument from the model. The user's identity must come from ToolContext, which the server fills from authentication.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which part of your function becomes the tool description the model reads?

Question 2

2def find(query: str, region: Optional[str]): How does the model see region?

Question 3

3A user asks about a ticket that belongs to someone else. What should the tool return?

Question 4

4Where should a tool get the current user's identity?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a read-only tool get_product_plan(plan: str) that returns the monthly price of the Basic or Pro plan from a dict, with error_code NOT_FOUND for anything else.

  2. Exercise 2medium

    Add get_ticket_status to an agent, run adk web with a mock or real model, ask about T-1001 as user-a and as user-b, and record the function call and function response events for each.

  3. Exercise 3hard

    Replace the ticket_id string with a Pydantic model TicketQuery that has ticket_id (pattern T- plus 4 digits) and include_history: bool = False, and explain what the model now sees.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need to use the FunctionTool class myself?
Usually not. Passing the function in the tools list is enough. Create a FunctionTool yourself only when you need its extra options, such as require_confirmation.
Can a tool be async?
Yes. Define it with async def and await your I/O. ADK can then run several tool calls from one model turn at the same time.
How long should a docstring be?
Usually two to six lines: what it does, when to use it, the argument formats and the possible error codes. Long essays cost tokens on every model call.

Go deeper

ShareXLinkedInWhatsApp