Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/genkit/src/genkit/_ai/_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,32 @@ async def menu_price(dish: str) -> float:
return None
return Tool.from_action(action)

async def list_tools(self) -> list[Tool]:
"""Return every tool registered on this app, sorted by name.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we drop the "sorted by name" guarantee (and test_list_tools_is_sorted_by_name)? Go sorts because its registry is a map and iterates in random order; ours is a dict, so registration order is already stable and matches the order the app defined its tools. Once it's documented, the order is API we can't change later. I'd return registration order and leave ordering unspecified in the docstring, and do the same for list_prompts() in #96 so the two match.


Each is the same handle ``lookup_tool`` returns. Every plugin is initialized

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: Line 714 says "Each is the same handle lookup_tool returns", but for a plain Action(kind=ActionKind.TOOL, ...), Tool.from_action builds a fresh _ActionTool wrapper on each call ((await ai.list_tools())[0] == await ai.lookup_tool(name) is False).

I noticed #93 already updates this line to "Each is the kind of handle lookup_tool returns" — worth pulling that wording tweak back into #92 so #92's docstring is accurate on its own.

first, so tools a plugin registers in ``init()`` are included, and a plugin
whose ``init()`` fails makes this raise. Tools a plugin only lists in
``list_actions()`` are registered, and so included, once something has
looked them up. Tools a dynamic action provider serves are not registered
on the app and are left out; pass ``'<provider>:tool/*'`` in ``tools=[...]``
to use those.

Example:
```python
@ai.tool()
async def menu_price(dish: str) -> float:
return 14.5


[tool.name for tool in await ai.list_tools()]
# => ['menu_price']
```
"""
await self._registry.initialize_all_plugins()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

list_tools() delegates to self._registry.initialize_all_plugins(), where _ensure_plugin_initialized (_registry.py:573-593) awaits the shared run_init() task directly without asyncio.shield and never evicts failed or cancelled tasks from _plugin_init_tasks[loop].

If a caller cancels ai.list_tools() while plugin.init() is in flight (for example asyncio.wait_for, or an MCP client in #93 sending notifications/cancelled on the first tools/list), the shared Task is cancelled and stays cached in _plugin_init_tasks[loop] forever while _all_plugins_initialized[loop] stays unset. Every subsequent uncancelled await ai.list_tools() immediately raises CancelledError (which in #93 suppresses the JSON-RPC response and hangs every later tools/list and tools/call until timeout). Likewise, a single transient Exception from plugin.init() stays cached forever and skips init() on later plugins without retrying on the next list_tools().

I suggest matching DynamicActionProvider._get_or_fetch (_dap.py:88-114) in _ensure_plugin_initialized: await via asyncio.shield(task) and evict loop_tasks[plugin_name] in a done-callback when task.cancelled() or task.exception() is not None (keeping completed tasks cached so init() still runs once on success).

actions = await self._registry.resolve_actions_by_kind(ActionKind.TOOL)
return [Tool.from_action(actions[name]) for name in sorted(actions)]

def lookup_value(self, *, kind: str, name: str) -> object | None:
"""Return the value defined under ``kind`` and ``name``, or None."""
return self._registry.lookup_value(kind, name)
Expand Down
187 changes: 186 additions & 1 deletion packages/genkit/tests/genkit/veneer/lookup_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Copyright 2026 Google LLC
# SPDX-License-Identifier: Apache-2.0

"""What app code and middleware get back from lookup_model, lookup_tool, lookup_value, and define_value."""
"""What app code and middleware get back from lookup_model, lookup_tool, list_tools, lookup_value, and define_value."""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

lookup_test.py:6 includes middleware in "What app code and middleware get back from lookup_model, lookup_tool, list_tools, lookup_value, and define_value", and at runtime ctx.ai on MiddlewareContext is the app's Genkit, but GenkitLike (_protocols.py:107-125) still only declares lookup_model, lookup_tool, and lookup_value.

A middleware hook calling await ctx.ai.list_tools() (e.g. to inspect or attach app tools in wrap_generate) works at runtime, yet fails pyright, pyrefly, and ty (Cannot access attribute "list_tools" for class "GenkitLike").

I suggest adding async def list_tools(self) -> list[Tool]: ... to GenkitLike (plus updating MiddlewareContext's docstring in _middleware.py:282-284) and adding a middleware test alongside test_middleware_ctx_ai_lookup_model_finds_app_model.


import re
from collections.abc import Awaitable, Callable
Expand Down Expand Up @@ -164,6 +164,191 @@ async def table_status(table_id: str) -> str:
assert Tool.from_action(found) is found


class ToolPlugin(Plugin):
"""Registers `catalog/stock` from init, the way a plugin ships tools."""

name = 'catalog'

async def init(self) -> list[Action]:
async def stock(sku: str) -> int:
return 3

return [Tool(stock, name='catalog/stock')]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Every list_tools fixture in this file (@ai.tool(), define_interrupt, ToolPlugin, AdvertisingToolPlugin) already registers a Tool instance, whereas genkit.plugin_api exports Action and ActionKind rather than Tool.

If Tool.from_action(...) at _aio.py:735 were removed, all 29 tests in lookup_test.py would still pass, and nothing here exercises passing await ai.list_tools() into ai.generate(tools=...).

I suggest adding a test where a plugin returns a plain Action(kind=ActionKind.TOOL, ...) from init() and passes tools=await ai.list_tools() into ai.generate(...) (similar to test_lookup_tool_wraps_plain_tool_action_via_from_action above).


async def resolve(self, action_type: ActionKind, name: str) -> Action | None:
return None

async def list_actions(self) -> list[Action]:
return []


@pytest.mark.asyncio
async def test_list_tools_returns_every_defined_tool_as_a_callable_tool() -> None:
"""`ai.list_tools()` gives one Tool per defined tool, each describing and running like the decorated one."""
ai = Genkit()

@ai.tool()
async def menu_price(dish: str) -> float:
"""Price of a dish in dollars."""
return 14.5

@ai.tool()
async def opening_hours() -> str:
"""When the restaurant is open."""
return '9-5'

tools = {tool.name: tool for tool in await ai.list_tools()}

assert sorted(tools) == ['menu_price', 'opening_hours']
assert tools['menu_price'] is menu_price
assert await tools['menu_price']('ramen') == 14.5


@pytest.mark.asyncio
async def test_list_tools_is_sorted_by_name() -> None:
"""Tools come back by name, not in the order they were defined."""
ai = Genkit()

@ai.tool()
async def opening_hours() -> str:
return '9-5'

@ai.tool()
async def menu_price(dish: str) -> float:
return 14.5

assert [tool.name for tool in await ai.list_tools()] == ['menu_price', 'opening_hours']


@pytest.mark.asyncio
async def test_list_tools_on_an_app_without_tools_is_empty() -> None:
"""An app that defines no tools lists none."""
assert await Genkit().list_tools() == []


@pytest.mark.asyncio
async def test_list_tools_reads_the_app_again_on_every_call() -> None:
"""A tool defined after one listing is in the next one."""
ai = Genkit()

@ai.tool()
async def menu_price(dish: str) -> float:
return 14.5

assert [tool.name for tool in await ai.list_tools()] == ['menu_price']

@ai.tool()
async def opening_hours() -> str:
return '9-5'

assert [tool.name for tool in await ai.list_tools()] == ['menu_price', 'opening_hours']


@pytest.mark.asyncio
async def test_list_tools_includes_interrupts() -> None:
"""An interrupt is a tool, so `list_tools` lists it, as `lookup_tool` finds it."""
ai = Genkit()
ai.define_interrupt('confirm_order', description='Ask the diner to confirm.')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

test_list_tools_includes_interrupts pins that ai.define_interrupt(...) comes back in ai.list_tools(), while define_interrupt (_ai/_tools.py:450) stamps no distinguishing metadata on the registered Tool (tool.metadata is identical to @ai.tool() async def f(x: Any) -> Any).

In #93, create_mcp_server reads await ai.list_tools() and ends up advertising confirm_order in MCP tools/list even though every MCP call to a define_interrupt tool is guaranteed to fail ("paused for input from the user, which this server cannot ask for"), unlike scalar-input tools which #93 skips from tools/list so clients aren't offered uncallable tools.

Maybe we can keep define_interrupt in ai.list_tools() (so ai.generate(tools=await ai.list_tools()) still includes human-in-the-loop checkpoints) and stamp tool.metadata['tool'] = {'restartable': False} in define_interrupt (since restarting one just interrupts again) so #93 can skip always-interrupting tools in tools/list?


assert [tool.name for tool in await ai.list_tools()] == ['confirm_order']


@pytest.mark.asyncio
async def test_list_tools_includes_tools_a_plugin_registers_at_init() -> None:
"""A plugin's tools are listed before anything has used the plugin."""
ai = Genkit(plugins=[ToolPlugin()])

assert [tool.name for tool in await ai.list_tools()] == ['catalog/stock']


class FailingPlugin(Plugin):
"""Fails to start, as a plugin with a bad API key does."""

name = 'failing'

async def init(self) -> list[Action]:
raise RuntimeError('no API key')

async def resolve(self, action_type: ActionKind, name: str) -> Action | None:
return None

async def list_actions(self) -> list[Action]:
return []


@pytest.mark.asyncio
async def test_list_tools_raises_when_a_plugin_fails_to_start() -> None:
"""A listing that silently dropped a plugin's tools would look complete, so a failed start raises."""
ai = Genkit(plugins=[FailingPlugin()])

@ai.tool()
async def menu_price(dish: str) -> float:
return 14.5

with pytest.raises(RuntimeError, match='no API key'):
await ai.list_tools()


class AdvertisingToolPlugin(Plugin):
"""Lists `shelf/count` in `list_actions()`; the registry gets it only when resolved."""

name = 'shelf'

async def init(self) -> list[Action]:
return []

async def resolve(self, action_type: ActionKind, name: str) -> Action | None:
if action_type != ActionKind.TOOL or name != 'count':
return None
return _shelf_count()

async def list_actions(self) -> list[Action]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: Unlike test_list_tools_leaves_out_dynamic_action_provider_tools below (which asserts listed == 0), AdvertisingToolPlugin.list_actions() doesn't track whether it was called.

Because Registry.list_actions() doesn't write advertised plugin rows into _entries, test_list_tools_includes_an_advertised_plugin_tool_only_once_looked_up would still pass even if ai.list_tools() accidentally called plugin.list_actions() and triggered provider network calls.

Maybe we can add a calls counter on AdvertisingToolPlugin.list_actions() and assert calls == 0 after await ai.list_tools()?

return [_shelf_count()]


def _shelf_count() -> Tool:
async def count(sku: str) -> int:
return 7

return Tool(count, name='shelf/count')


@pytest.mark.asyncio
async def test_list_tools_includes_an_advertised_plugin_tool_only_once_looked_up() -> None:
"""Listing does not resolve tools a plugin only advertises; a lookup registers them."""
ai = Genkit(plugins=[AdvertisingToolPlugin()])

assert await ai.list_tools() == []
assert await ai.lookup_tool('shelf/count') is not None
assert [tool.name for tool in await ai.list_tools()] == ['shelf/count']


@pytest.mark.asyncio
async def test_list_tools_leaves_out_dynamic_action_provider_tools() -> None:
"""A provider's tools are not registered on the app, so listing never reaches the provider, even after a lookup."""
ai = Genkit()
listed = 0

async def provide() -> dict[str, list[Action]]:
nonlocal listed
listed += 1

async def remote_search(query: str) -> str:
return query

return {'tool': [Tool(remote_search, name='remote_search')]}

ai.define_dynamic_action_provider('remote', provide)

assert await ai.list_tools() == []
assert listed == 0

found = await ai.lookup_tool('remote:tool/remote_search')
assert found is not None
assert await found('ramen') == 'ramen'
assert await ai.list_tools() == []


def test_define_value_then_lookup_value_returns_it() -> None:
"""A value stored with `ai.define_value(...)` comes back from `ai.lookup_value(...)` for the same kind and name."""
ai = Genkit()
Expand Down
Loading