Skip to content

feat: @client_tool decorator for client tools - #936

Merged
PaulAsjes merged 8 commits into
mainfrom
feat/client-tool-decorator
Nov 18, 2026
Merged

PaulAsjes merged 8 commits into
mainfrom
feat/client-tool-decorator

Conversation

@PaulAsjes

@PaulAsjes PaulAsjes commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Client tools can now be defined as ordinary Python functions. @client_tool reads the function's name, docstring and type hints into a tool, and the same function runs when the agent calls it. This is in the style of the OpenAI Agents SDK's @function_tool. tools.create() and tools.update() also take the decorated function directly, so it needs no build() step. Chained builders keep build(). Nothing existing changes: passing a request model works as before, and the decorator produces the same ClientTool builder as Tool.client().

@client_tool(expects_response=True)
def add_to_cart(sku: str, quantity: int = 1, size: Optional[Literal["S", "M", "L"]] = None) -> dict:
    """Add a product to the shopper's cart.

    Args:
        sku: The product SKU, e.g. TSH-0042
        quantity: How many to add
        size: Clothing size, only for apparel
    """

client.conversational_ai.tools.create(request=add_to_cart)
client_tools.register_tools(add_to_cart)
Details
  • Type mapping:
    • str, int, float and bool map to the matching schema types.
    • Literal of strings becomes choices.
    • List[T] becomes an array, and TypedDict becomes an object.
    • A param with a default or an Optional type is optional.
    • For a TypedDict field, NotRequired makes it optional and Required makes it required.
  • Descriptions:
    • Param descriptions come from a Google-style Args: section or reST :param x: lines.
    • TypedDict field descriptions come from its Attributes: section.
    • Annotated[T, Param(...)] sets a description, a dynamic variable or a constant instead.
    • Anything else is set on fn.tool.
  • Unsupported types raise a TypeError naming the param. That covers dict, unions other than Optional, non-string Literals, missing hints, a missing docstring, and *args or positional-only params.
  • The tool is validated when the function is defined, so a mistake raises ToolValidationError at import, not at build().
  • The handler only passes params the function declares. ClientTools mixes tool_call_id into the params dict, so other keys are dropped unless the function takes **kwargs.
  • NotRequired is read from the annotation itself. TypedDict.__required_keys__ is wrong under from __future__ import annotations.
  • ClientTools.register_tools(*fns) duck-types the functions it's given, so conversation.py has no runtime import of agent_tools.
  • tools.create() and tools.update() accept a decorated function.
    • ConversationalAiClient and its tools client get hand-maintained subclasses in conversational_ai_custom.py (now in .fernignore), wired in through client.py the same way as music_custom.py.
    • create() and update() accept ToolRequestModel | ClientToolFunction.
    • Chained builders deliberately aren't accepted. build() followed by the generated create() is the step every SDK can share, and Go, Rust and Java couldn't take a builder without changing every generated signature.
    • Passing a builder raises a TypeError that says to call build(), rather than failing during serialization.
  • Schema drift check. tools.check_client_tools(agent_id, *fns, strict=False) lists the agent's tools (paginated, used_by_agent_id) and compares each function with the client tool of the same name. It compares only what changes the calls the function receives: param names, types, enum choices and required, recursively through objects and arrays. Descriptions, value sources and server-filled defaults ("", false) are ignored. Each difference is a ToolSchemaDriftWarning and a returned ToolSchemaDrift; strict=True raises ToolSchemaDriftError. The README now pushes the schema at deploy time and calls the check at startup, because the schema is shared by every running client, older versions included.
  • This is client tools only. Webhook tools run on the user's server and need a URL, a location for each param, secrets and response assignments, none of which a signature can express. System tools have no function at all.

Testing

  • 16 new tests in tests/agent_tools/test_client_tool_decorator.py. One checks that the decorator gives byte-identical JSON to the same tool written with the builder. Others cover nesting, docstring formats, errors, handlers, register_tools with sync and async functions, sync and async tools.create() / tools.update() sending the same body for a function or a model, and the TypeError for a chained builder.
  • 6 tests in tests/agent_tools/test_client_tool_drift.py cover the drift check against mocked server responses with server-filled defaults: a match, each kind of difference, nesting, pagination, strict=True and async.
  • tests/agent_tools and tests/test_client_tools.py pass on Python 3.13 (104 tests, with the client tests); tests/agent_tools passes on 3.8 (87). mypy and ruff are clean.
  • The rest of the suite: the only failures are live API tests that need a key, plus 2 in test_convai_disconnect.py that fail on main as well.
  • Not run: a live tools.create, check_client_tools against the real API, or a conversation.

🤖 Generated with Claude Code

The decorator reads a function's name, docstring and type hints into a
ClientTool builder (on fn.tool) and validates it when defined. The same
function is the handler: ClientTools.register_tools() registers it and
passes only the params it declares, dropping tool_call_id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PaulAsjes
PaulAsjes marked this pull request as ready for review November 17, 2026 12:47
@cursor

cursor Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

PR Summary

Medium Risk
Touches conversational AI tool create/update and runtime registration; schema drift is opt-in, but mismatched deploy vs client code can break live agents.

Overview
Adds @client_tool so client tools can be defined as normal Python functions: signatures, docstrings, and Annotated[..., Param(...)] become the server schema, and the same function runs when the agent calls it.

tools.create() / tools.update() on the custom conversational AI client accept the decorated function directly (no separate build()). ClientTools.register_tools() wires those functions into conversations. tools.check_client_tools() compares local functions to the agent’s server tools at startup (warnings or strict errors) to catch schema drift before calls fail mid-session.

README documents deploy-time schema push vs runtime registration and shared-schema versioning guidance.

Reviewed by Cursor Bugbot for commit cda16ce. Bugbot is set up for automated code reviews on this repo. Configure here.

ConversationalAiClient and its tools client get hand-maintained
subclasses (conversational_ai_custom.py, like music_custom.py) whose
create() and update() build the request from a Tool or a decorated
function. Passing a ToolRequestModel works as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

PaulAsjes and others added 2 commits November 17, 2026 14:01
Chained builders keep build(), the step every SDK shares. Passing one
directly now raises a TypeError that says to call build().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Match typing and typing_extensions special forms, so typing.Literal maps to choices on Python 3.8 and 3.9.
- Don't apply docstring text to from_variable or constant params; a description makes the value LLM-filled.
- Keep a Param description inside Optional[Annotated[...]] instead of overwriting it with the docstring.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread README.md Resolved

@kraenhansen kraenhansen left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Safe to merge, but also, I'm a bit concerned this will cause confusion as the schema is stored serverside for future conversations with the agent, which might be shared with other (older) versions of this code causing a data-race between schemas. This feature is ideal for ephemeral (or like here, created just in time for the conversation) agents - persisted agents, not so much IMO and I think that should be front and center.

PaulAsjes and others added 2 commits November 18, 2026 12:01
… shared

The example created the tool right before each conversation, so every run made a new
tool and the last client to start won. Split it into a deploy step and a runtime step,
and say plainly that the schema is shared by every running client, including older ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PaulAsjes

PaulAsjes commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

Good point, thanks. It applies to any client tool, but the decorator makes the schema look like local code, and the README example made it worse by creating the tool right before each conversation. Addressed in cf94b29:

  • The README now splits pushing the schema (once, at deploy time, tools.create or tools.update) from runtime, where the app only calls register_tools.
  • A The schema is shared note explains that every running client, older versions included, gets the same schema, and that renames, removals, type changes and newly required params should ship under a new tool name.

The docs get the same split and warning. I'd rather frame it as treating the schema as an API contract than limit the decorator to temporary agents, which would mean creating new agents and tools each run.

🤖 Addressed by Claude Code

…he agent's tools

Run at startup, it reports each function the agent has no tool for, and each param whose
name, type, choices or required status differs from the tool on the server, as a
ToolSchemaDriftWarning (or a ToolSchemaDriftError with strict=True). Descriptions, value
sources and server-filled defaults are ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit dc15176. Configure here.

Comment thread src/elevenlabs/agent_tools/drift.py Resolved
The API can store a type as a list such as ["integer", "null"], or leave it out of an object or array schema. Normalize both sides with _kind_of so these don't report false mismatches or skip nested checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PaulAsjes
PaulAsjes merged commit 4c1a8ec into main Nov 18, 2026
6 checks passed
@PaulAsjes
PaulAsjes deleted the feat/client-tool-decorator branch November 18, 2026 11:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants