From 1b3887ea9af42f25318487d55a7b646ceab75f19 Mon Sep 17 00:00:00 2001 From: Jacob Cable Date: Tue, 20 Oct 2026 14:55:28 +0100 Subject: [PATCH 1/2] feat(py): list an app's tools with ai.list_tools() ai.registry is private since genkit-ai/genkit#6690, and Genkit can look up one tool by name but cannot enumerate them. Anything that serves an app's tools to something else, such as an MCP server, has no public way to find them. list_tools() returns one Tool handle per registered tool, the same handle lookup_tool() returns. It promises no order: plugin tools are registered when plugins start, not where the app defines them. It starts every plugin first, since Python starts plugins lazily and a plugin may register tools in init(). A plugin whose init() fails makes it raise, as registry listing already does, rather than return a list that looks complete but is missing that plugin's tools. Tools a plugin only advertises in list_actions() and builds in resolve() are listed once something has looked them up. Building them eagerly would call every plugin's list_actions(), which for some plugins is a network call. Tools a dynamic action provider serves are left out: they are not defined on the app, and listing them would reach the provider's transport. Both match Go's genkit.ListTools, which lists registered tools only. The GenkitLike protocol middleware sees is unchanged. Upstream-PR: https://github.com/genkit-ai/genkit/pull/6881 --- packages/genkit/src/genkit/_ai/_aio.py | 25 +++ .../genkit/tests/genkit/veneer/lookup_test.py | 162 +++++++++++++++++- 2 files changed, 186 insertions(+), 1 deletion(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index cd8d47ec7..6a1c79a8d 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -708,6 +708,31 @@ 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, in no particular order. + + Each is the same handle ``lookup_tool`` returns. Every plugin is started + first, so tools a plugin registers in ``init()`` are included, and a plugin + whose ``init()`` fails makes this raise. Tools a plugin only advertises and + builds on first lookup are included once something has looked them up. + Tools a dynamic action provider serves are not defined on the app and are + left out; select those as ``:tool/*``. + + 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() + actions = await self._registry.resolve_actions_by_kind(ActionKind.TOOL) + return [Tool.from_action(action) for action in actions.values()] + 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) diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index c702c8590..370297c67 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -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.""" import re from collections.abc import Awaitable, Callable @@ -164,6 +164,166 @@ 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')] + + 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 all(isinstance(tool, Tool) for tool in tools.values()) + assert tools['menu_price'].definition() == menu_price.definition() + assert await tools['menu_price']('ramen') == 14.5 + + +@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() + assert await ai.list_tools() == [] + + @ai.tool() + async def menu_price(dish: str) -> float: + return 14.5 + + assert [tool.name for tool in await ai.list_tools()] == ['menu_price'] + + +@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.') + + 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): + """Advertises `shelf/count` and builds 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]: + 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 build 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 defined on the app, so listing never reaches the provider.""" + 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 + + 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() From 2dfcd299bde82e652b7d1fb64a1af063a6ae3d60 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:36:32 +0100 Subject: [PATCH 2/2] fix(py): sort ai.list_tools() by name and tighten its tests Upstream-PR: https://github.com/genkit-ai/genkit/pull/6881 --- packages/genkit/src/genkit/_ai/_aio.py | 15 ++++---- .../genkit/tests/genkit/veneer/lookup_test.py | 37 ++++++++++++++++--- 2 files changed, 39 insertions(+), 13 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 6a1c79a8d..3bf49f721 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -709,14 +709,15 @@ async def menu_price(dish: str) -> float: return Tool.from_action(action) async def list_tools(self) -> list[Tool]: - """Return every tool registered on this app, in no particular order. + """Return every tool registered on this app, sorted by name. - Each is the same handle ``lookup_tool`` returns. Every plugin is started + Each is the same handle ``lookup_tool`` returns. Every plugin is initialized first, so tools a plugin registers in ``init()`` are included, and a plugin - whose ``init()`` fails makes this raise. Tools a plugin only advertises and - builds on first lookup are included once something has looked them up. - Tools a dynamic action provider serves are not defined on the app and are - left out; select those as ``:tool/*``. + 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 ``':tool/*'`` in ``tools=[...]`` + to use those. Example: ```python @@ -731,7 +732,7 @@ async def menu_price(dish: str) -> float: """ await self._registry.initialize_all_plugins() actions = await self._registry.resolve_actions_by_kind(ActionKind.TOOL) - return [Tool.from_action(action) for action in actions.values()] + 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.""" diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index 370297c67..9f11f671c 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -200,11 +200,26 @@ async def opening_hours() -> str: tools = {tool.name: tool for tool in await ai.list_tools()} assert sorted(tools) == ['menu_price', 'opening_hours'] - assert all(isinstance(tool, Tool) for tool in tools.values()) - assert tools['menu_price'].definition() == menu_price.definition() + 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.""" @@ -215,7 +230,6 @@ async def test_list_tools_on_an_app_without_tools_is_empty() -> None: 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() - assert await ai.list_tools() == [] @ai.tool() async def menu_price(dish: str) -> float: @@ -223,6 +237,12 @@ async def menu_price(dish: str) -> float: 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: @@ -270,7 +290,7 @@ async def menu_price(dish: str) -> float: class AdvertisingToolPlugin(Plugin): - """Advertises `shelf/count` and builds it only when resolved.""" + """Lists `shelf/count` in `list_actions()`; the registry gets it only when resolved.""" name = 'shelf' @@ -295,7 +315,7 @@ async def count(sku: str) -> int: @pytest.mark.asyncio async def test_list_tools_includes_an_advertised_plugin_tool_only_once_looked_up() -> None: - """Listing does not build tools a plugin only advertises; a lookup registers them.""" + """Listing does not resolve tools a plugin only advertises; a lookup registers them.""" ai = Genkit(plugins=[AdvertisingToolPlugin()]) assert await ai.list_tools() == [] @@ -305,7 +325,7 @@ async def test_list_tools_includes_an_advertised_plugin_tool_only_once_looked_up @pytest.mark.asyncio async def test_list_tools_leaves_out_dynamic_action_provider_tools() -> None: - """A provider's tools are not defined on the app, so listing never reaches the provider.""" + """A provider's tools are not registered on the app, so listing never reaches the provider, even after a lookup.""" ai = Genkit() listed = 0 @@ -323,6 +343,11 @@ async def remote_search(query: str) -> str: 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."""