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
2 changes: 2 additions & 0 deletions packages/genkit-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/*'])
Expand Down
3 changes: 1 addition & 2 deletions packages/genkit-mcp/src/genkit_mcp/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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."""
Expand Down
42 changes: 13 additions & 29 deletions packages/genkit-mcp/src/genkit_mcp/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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
9 changes: 8 additions & 1 deletion packages/genkit-mcp/tests/fake_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'}),
Expand Down
39 changes: 32 additions & 7 deletions packages/genkit-mcp/tests/mcp_client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down
80 changes: 75 additions & 5 deletions packages/genkit-mcp/tests/mcp_tools_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand All @@ -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


Expand Down Expand Up @@ -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'})]

Expand All @@ -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),
Expand All @@ -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]
Expand All @@ -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
Expand Down
Loading