Repository navigation
Conversation
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: genkit-ai/genkit#6881
huangjeff5
left a comment
There was a problem hiding this comment.
Shape of await ai.list_tools() -> list[Tool] looks clean. Left a few comments before this base PR merges — mainly around shielding/evicting failed Plugin.init() tasks in _ensure_plugin_initialized (which affects #93 when a tools/list call is cancelled or hits a transient startup error), exposing list_tools on GenkitLike, and marking define_interrupt metadata so #93 doesn't advertise uncallable interrupt checkpoints over MCP.
| # => ['menu_price'] | ||
| ``` | ||
| """ | ||
| await self._registry.initialize_all_plugins() |
There was a problem hiding this comment.
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).
| # 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.""" |
There was a problem hiding this comment.
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.
| 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.') |
There was a problem hiding this comment.
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?
| async def stock(sku: str) -> int: | ||
| return 3 | ||
|
|
||
| return [Tool(stock, name='catalog/stock')] |
There was a problem hiding this comment.
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).
| return None | ||
| return _shelf_count() | ||
|
|
||
| async def list_actions(self) -> list[Action]: |
There was a problem hiding this comment.
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()?
| async def list_tools(self) -> list[Tool]: | ||
| """Return every tool registered on this app, sorted by name. | ||
|
|
||
| Each is the same handle ``lookup_tool`` returns. Every plugin is initialized |
There was a problem hiding this comment.
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.
| return Tool.from_action(action) | ||
|
|
||
| async def list_tools(self) -> list[Tool]: | ||
| """Return every tool registered on this app, sorted by name. |
There was a problem hiding this comment.
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.
The registry is a dict, so registration order is already stable. Leave ordering unspecified rather than make sorted-by-name part of the API, matching the ask on list_tools() in #92.
ai.list_tools()returns every tool registered on the app, sorted by name, so code that serves an app's tools to something else (an MCP server'stools/list) can find them without reaching into the private registry.Changes
Genkit.list_tools() -> list[Tool]. Each entry is the same handleai.lookup_tool()returns, so it goes straight intogenerate(tools=[...]).init()are listed. A plugin whoseinit()fails makes it raise, as the Dev UI listing already does, rather than return a list that looks complete.list_actions()show up once something has looked them up; resolving them up front would call every plugin'slist_actions(), which is a network call for several providers.'<provider>:tool/*'intools=[...].Breaking changes
None.
Part of #91.