From d33a6f7a6722ba59677b5667a9c86f8b6168682b Mon Sep 17 00:00:00 2001 From: Hilary Chukwuma Date: Wed, 11 Nov 2026 15:09:21 +0100 Subject: [PATCH] fix(mcp): carry each MCP tool's output schema, title and annotations Port of genkit-ai/genkit#6903, adapted to this repo's Tool API. mcp_tool_to_action now sets the server's outputSchema as the tool's model_output_schema, so :tool/* selectors send it to the model as get_active_tools() handles already did. mcp_tools_to_handles only existed to add that schema, so it is removed. metadata['mcp'] also keeps the tool's title and annotations, leaving out what the server did not send. Upstream-Commit: genkit-ai/genkit@6606da92a49719c23eea6a7e01cca98e7d6575de Upstream-PR: https://github.com/genkit-ai/genkit/pull/6903 --- packages/genkit-mcp/README.md | 2 + packages/genkit-mcp/src/genkit_mcp/_client.py | 3 +- packages/genkit-mcp/src/genkit_mcp/_tools.py | 42 +++------- packages/genkit-mcp/tests/fake_server.py | 9 ++- packages/genkit-mcp/tests/mcp_client_test.py | 39 +++++++-- packages/genkit-mcp/tests/mcp_tools_test.py | 80 +++++++++++++++++-- 6 files changed, 131 insertions(+), 44 deletions(-) diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index edad9de81..13ad52ffe 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -32,6 +32,8 @@ async def main() -> None: tools = await client.get_active_tools() for tool in tools: print(tool.name, tool.description) + # The server's display title and behaviour hints, when it sent them. + print(tool.metadata['mcp']) # Every tool of this server, or just one. result = await ai.generate(prompt='Echo "hello".', tools=['everything:tool/*']) diff --git a/packages/genkit-mcp/src/genkit_mcp/_client.py b/packages/genkit-mcp/src/genkit_mcp/_client.py index f57a9dcc5..86045cfc6 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_client.py +++ b/packages/genkit-mcp/src/genkit_mcp/_client.py @@ -37,7 +37,6 @@ from genkit_mcp._tools import ( mcp_tool_name, mcp_tools_to_actions, - mcp_tools_to_handles, validate_provider_name, validate_tool_prefix, ) @@ -169,7 +168,7 @@ async def get_active_tools(self) -> list[Tool]: JSON-RPC error code it answers the listing with. """ tools = await self._on_connection(McpConnection.list_tools) - return mcp_tools_to_handles(tools, self._name, self._call_tool) + return mcp_tools_to_actions(tools, self._name, self._call_tool) async def _list_actions(self) -> list[Action[Any, Any]]: """List the server's tools as unregistered actions, for a provider to hand out.""" diff --git a/packages/genkit-mcp/src/genkit_mcp/_tools.py b/packages/genkit-mcp/src/genkit_mcp/_tools.py index 257de3188..2b14f1180 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_tools.py +++ b/packages/genkit-mcp/src/genkit_mcp/_tools.py @@ -197,7 +197,11 @@ def mcp_tool_to_action( The returned action carries its own name under the ``name`` metadata key, which is what a dynamic action provider matches a wildcard selector against, - and the server's own tool name under ``metadata['mcp']['tool']``. + the server's own tool name under ``metadata['mcp']['tool']``, its display + title and behaviour hints under ``metadata['mcp']['title']`` and + ``metadata['mcp']['annotations']``, and the server's output schema, if + any, as its ``model_output_schema``. A title or hint the server left out is + left out of the metadata too. Args: tool: Tool as listed by the server. @@ -241,7 +245,14 @@ async def handler(input: dict[str, Any], ctx: ToolContext) -> MultipartToolRespo input_schema=tool.inputSchema, ) action.metadata['name'] = action.name - action.metadata['mcp'] = {'prefix': prefix, 'tool': tool.name, '_meta': mcp_meta} + action.model_output_schema = dict(tool.outputSchema) if tool.outputSchema is not None else None + mcp: dict[str, object] = {'prefix': prefix, 'tool': tool.name, '_meta': mcp_meta} + if tool.title is not None: + mcp['title'] = tool.title + annotations = tool.annotations.model_dump(exclude_none=True) if tool.annotations is not None else {} + if annotations: + mcp['annotations'] = annotations + action.metadata['mcp'] = mcp return action @@ -277,30 +288,3 @@ def mcp_tools_to_actions( for tool in tools if len(server_tools_by_name[mcp_tool_name(prefix, tool.name)]) == 1 ] - - -def mcp_tools_to_handles( - tools: Sequence[McpTool], - prefix: str, - call: McpToolCall, -) -> list[Tool]: - """Build one Genkit tool handle per tool in a server listing. - - A handle is what ``generate`` accepts in ``tools``, and what a caller can - invoke directly. Its ``model_output_schema`` is the one the server declared. - - Args: - tools: Tools as listed by the server. - prefix: Namespace for the Genkit tool names. - call: Coroutine function invoking a tool on the live session. - - Returns: - Handles in listing order, leaving out the tools - :func:`mcp_tools_to_actions` leaves out. - """ - by_name = {mcp_tool_name(prefix, tool.name): tool for tool in tools} - handles = mcp_tools_to_actions(tools, prefix, call) - for handle in handles: - output_schema = by_name[handle.name].outputSchema - handle.model_output_schema = dict(output_schema) if output_schema is not None else None - return handles diff --git a/packages/genkit-mcp/tests/fake_server.py b/packages/genkit-mcp/tests/fake_server.py index 24b9de335..7c6ceda15 100644 --- a/packages/genkit-mcp/tests/fake_server.py +++ b/packages/genkit-mcp/tests/fake_server.py @@ -37,12 +37,19 @@ ServerResult, TextContent, Tool, + ToolAnnotations, ) app = Server('fake-server') TOOLS = [ - Tool(name='echo', description='Echo input.', inputSchema={'type': 'object'}), + Tool( + name='echo', + title='Echo', + description='Echo input.', + inputSchema={'type': 'object'}, + annotations=ToolAnnotations.model_validate({'readOnlyHint': True, 'costHint': 'free'}), + ), Tool(name='second', description='Another tool.', inputSchema={'type': 'object'}), Tool(name='wait', description='Wait before replying.', inputSchema={'type': 'object'}), Tool(name='list_requests', description='Count tools/list requests.', inputSchema={'type': 'object'}), diff --git a/packages/genkit-mcp/tests/mcp_client_test.py b/packages/genkit-mcp/tests/mcp_client_test.py index c75c00fad..de0c59d5e 100644 --- a/packages/genkit-mcp/tests/mcp_client_test.py +++ b/packages/genkit-mcp/tests/mcp_client_test.py @@ -53,6 +53,12 @@ 'bad_output', ] +BAD_OUTPUT_SCHEMA = { + 'type': 'object', + 'properties': {'value': {'type': 'integer'}}, + 'required': ['value'], +} + # A listing must not expire by the clock in these tests: every re-list they # assert is one the client asked for. LONG_TTL_MILLIS = 600_000 @@ -190,6 +196,9 @@ async def test_generate_calls_a_tool_and_receives_its_result(tmp_path: Path) -> assert pm.request_count == 2 assert pm.last_request is not None assert sorted(tool.name for tool in pm.last_request.tools or []) == sorted(f'fake_{tool}' for tool in ALL_TOOLS) + sent = {tool.name: tool.output_schema for tool in pm.last_request.tools or []} + assert sent['fake_echo'] is None + assert sent['fake_bad_output'] == BAD_OUTPUT_SCHEMA tool_message = pm.last_request.messages[-1] assert tool_message.role == Role.TOOL assert tool_message.content[0].tool_response is not None @@ -219,15 +228,12 @@ async def test_generate_accepts_the_listed_tools(tmp_path: Path) -> None: tool_message = pm.last_request.messages[-1] assert tool_message.content[0].tool_response is not None assert tool_message.content[0].tool_response.output == 'hello' - sent = next(tool for tool in pm.last_request.tools or [] if tool.name == 'fake_bad_output') + sent = {tool.name: tool.output_schema for tool in pm.last_request.tools or []} + assert sent['fake_echo'] is None + assert sent['fake_bad_output'] == BAD_OUTPUT_SCHEMA assert tools[0].definition().output_schema is None assert tools[-1].name == 'fake_bad_output' - assert tools[-1].definition().output_schema == { - 'type': 'object', - 'properties': {'value': {'type': 'integer'}}, - 'required': ['value'], - } - assert sent.output_schema == tools[-1].definition().output_schema + assert tools[-1].definition().output_schema == BAD_OUTPUT_SCHEMA @pytest.mark.asyncio @@ -830,6 +836,25 @@ async def test_an_unregistered_client_lists_and_runs_its_tools(tmp_path: Path) - assert server_processes(tmp_path) == [] +@pytest.mark.asyncio +async def test_a_tool_keeps_the_title_and_annotations_the_server_listed(tmp_path: Path) -> None: + """A selected tool and a listed handle both carry the server's title and hints.""" + ai = Genkit() + client = define_mcp_client(ai, 'fake', **server(tmp_path)) + try: + selected = await ai.lookup_tool('fake:tool/fake_echo') + listed = (await client.get_active_tools())[0] + finally: + await client.close() + + assert selected is not None + for tool in (selected, listed): + mcp = tool.metadata['mcp'] + assert isinstance(mcp, dict) + assert mcp['title'] == 'Echo' + assert mcp['annotations'] == {'readOnlyHint': True, 'costHint': 'free'} + + @pytest.mark.asyncio async def test_an_unregistered_client_restarts_and_closes_without_a_provider(tmp_path: Path) -> None: """Restart and close do not need a provider, and close is still final.""" diff --git a/packages/genkit-mcp/tests/mcp_tools_test.py b/packages/genkit-mcp/tests/mcp_tools_test.py index 2b6c08726..1b8c6f3a8 100644 --- a/packages/genkit-mcp/tests/mcp_tools_test.py +++ b/packages/genkit-mcp/tests/mcp_tools_test.py @@ -25,7 +25,6 @@ mcp_tool_name, mcp_tool_to_action, mcp_tools_to_actions, - mcp_tools_to_handles, validate_provider_name, validate_tool_prefix, ) @@ -39,11 +38,13 @@ TextContent, TextResourceContents, Tool, + ToolAnnotations, ) from pydantic import AnyUrl from structlog.testing import capture_logs from genkit import MultipartToolResponse, Part +from genkit._ai._generate import to_tool_definition # noqa: TID251 from genkit.plugin_api import Action @@ -372,6 +373,75 @@ def test_mcp_tool_to_action_warns_about_a_name_longer_than_a_model_accepts() -> assert logs[0]['tool'] == f'catalog_{tool_name}' +def test_mcp_tool_to_action_keeps_the_server_title_and_annotations() -> None: + """Hints the server sent are kept as given, including ones the SDK has no field for.""" + tool = Tool( + name='delete_record', + title='Delete record', + inputSchema={'type': 'object'}, + annotations=ToolAnnotations.model_validate({ + 'title': 'Delete a record', + 'destructiveHint': True, + 'openWorldHint': False, + 'costHint': 'high', + }), + ) + + action = mcp_tool_to_action(tool, 'catalog', no_content) + + mcp = action.metadata['mcp'] + assert isinstance(mcp, dict) + assert mcp['title'] == 'Delete record' + assert mcp['annotations'] == { + 'title': 'Delete a record', + 'destructiveHint': True, + 'openWorldHint': False, + 'costHint': 'high', + } + + +@pytest.mark.parametrize('annotations', [None, ToolAnnotations()]) +def test_mcp_tool_to_action_leaves_out_a_title_and_hints_the_server_did_not_send( + annotations: ToolAnnotations | None, +) -> None: + """No title and no hints means no ``title`` or ``annotations`` key, rather than a None.""" + tool = Tool(name='lookup', inputSchema={'type': 'object'}, annotations=annotations) + + mcp = mcp_tool_to_action(tool, 'catalog', no_content).metadata['mcp'] + + assert isinstance(mcp, dict) + assert 'title' not in mcp + assert 'annotations' not in mcp + + +@pytest.mark.parametrize( + ('title', 'annotations', 'kept'), + [('Look up', None, {'title'}), (None, ToolAnnotations(readOnlyHint=True), {'annotations'})], +) +def test_mcp_tool_to_action_keeps_a_title_or_hints_on_their_own( + title: str | None, + annotations: ToolAnnotations | None, + kept: set[str], +) -> None: + """A title without hints, or hints without a title, is kept on its own.""" + tool = Tool(name='lookup', title=title, inputSchema={'type': 'object'}, annotations=annotations) + + mcp = mcp_tool_to_action(tool, 'catalog', no_content).metadata['mcp'] + + assert isinstance(mcp, dict) + assert {'title', 'annotations'} & mcp.keys() == kept + + +@pytest.mark.parametrize('output_schema', [{'type': 'object', 'properties': {'hits': {'type': 'integer'}}}, None]) +def test_mcp_tool_to_action_sends_the_server_output_schema_to_the_model(output_schema: dict[str, Any] | None) -> None: + """The model is told what the server said the tool returns, not the multipart envelope.""" + action = mcp_tool_to_action( + Tool(name='lookup', inputSchema={'type': 'object'}, outputSchema=output_schema), 'catalog', no_content + ) + + assert to_tool_definition(action).output_schema == output_schema + + def test_mcp_tools_to_actions_maps_a_listing_in_order() -> None: tools = [Tool(name='lookup', inputSchema={'type': 'object'}), Tool(name='look.up', inputSchema={'type': 'object'})] @@ -382,8 +452,8 @@ def test_mcp_tools_to_actions_maps_a_listing_in_order() -> None: @pytest.mark.asyncio -async def test_mcp_tools_to_handles_wraps_each_action_with_the_server_output_schema() -> None: - """A handle carries the Genkit name, the server's output schema, and runs the tool.""" +async def test_mcp_tools_to_actions_carry_the_server_output_schema() -> None: + """An action carries the Genkit name, the server's output schema, and runs the tool.""" output_schema: dict[str, Any] = {'type': 'object', 'properties': {'hits': {'type': 'integer'}}} tools = [ Tool(name='lookup', inputSchema={'type': 'object'}, outputSchema=output_schema), @@ -393,7 +463,7 @@ async def test_mcp_tools_to_handles_wraps_each_action_with_the_server_output_sch async def call(name: str, arguments: dict[str, Any], meta: dict[str, Any] | None) -> CallToolResult: return CallToolResult(content=[text(name)]) - handles = mcp_tools_to_handles(tools, 'catalog', call) + handles = mcp_tools_to_actions(tools, 'catalog', call) assert [handle.name for handle in handles] == ['catalog_lookup', 'catalog_look_up'] assert [handle.definition().output_schema for handle in handles] == [output_schema, None] @@ -413,7 +483,7 @@ def test_mcp_tool_handle_exposes_output_schema_on_definition() -> None: Tool(name='ping', inputSchema={'type': 'object'}), ] - handles = mcp_tools_to_handles(tools, 'lab', no_content) + handles = mcp_tools_to_actions(tools, 'lab', no_content) assert handles[0].definition().output_schema == output_schema assert handles[1].definition().output_schema is None