From 2f878e69dbf682b59909cb106d54713ad47faec9 Mon Sep 17 00:00:00 2001 From: Hilary Date: Tue, 10 Nov 2026 14:26:59 +0100 Subject: [PATCH 1/2] feat(py): list an app's prompts with ai.list_prompts() --- packages/genkit/src/genkit/_ai/_aio.py | 22 ++++++++ .../genkit/tests/genkit/veneer/lookup_test.py | 56 +++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 4c6a51be..b540d611 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -734,6 +734,28 @@ async def menu_price(dish: str) -> float: actions = await self._registry.resolve_actions_by_kind(ActionKind.TOOL) return [Tool.from_action(actions[name]) for name in sorted(actions)] + async def list_prompts(self) -> list[Action[Any, ModelRequest]]: + """Return the action of every prompt registered on this app, in no particular order. + + Running one renders the prompt into the request a model would get, + without calling the model, though the app still needs a model to render + against. Each is listed under its registered name, so a variant reads + ``'greet.formal'``, and ``ai.prompt(action.name)`` gives the handle that + generates. Every plugin is started first, and a plugin whose ``init()`` + fails makes this raise. + + Example: + ```python + ai.define_prompt(name='greet', prompt='Hello {{name}}') + + [action.name for action in await ai.list_prompts()] + # => ['greet'] + ``` + """ + await self._registry.initialize_all_plugins() + actions = await self._registry.resolve_actions_by_kind(ActionKind.PROMPT) + return [cast(Action[Any, ModelRequest], 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 9f11f671..6567b8a1 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -7,6 +7,7 @@ import re from collections.abc import Awaitable, Callable +from pathlib import Path import pytest @@ -349,6 +350,61 @@ async def remote_search(query: str) -> str: assert await ai.list_tools() == [] +@pytest.mark.asyncio +async def test_list_prompts_lists_each_prompt_and_variant_by_registered_name() -> None: + """A variant is its own prompt, listed as `name.variant`, with the description it was defined with.""" + ai = Genkit() + ai.define_prompt(name='greet', description='Say hello.', prompt='Hello {{name}}') + ai.define_prompt(name='greet', variant='formal', prompt='Good day {{name}}') + + prompts = {action.name: action for action in await ai.list_prompts()} + + assert sorted(prompts) == ['greet', 'greet.formal'] + assert prompts['greet'].description == 'Say hello.' + + +@pytest.mark.asyncio +async def test_list_prompts_on_an_app_without_prompts_is_empty() -> None: + """An app that defines no prompts lists none.""" + assert await Genkit().list_prompts() == [] + + +@pytest.mark.asyncio +async def test_a_listed_prompt_renders_the_request_without_calling_the_model() -> None: + """Running a listed prompt gives the messages the model would get, and the model never runs.""" + ai = Genkit(model='test/never') + calls = 0 + + async def never(request: ModelRequest, ctx: ModelContext) -> ModelResponse: + nonlocal calls + calls += 1 + return _answer('unreachable') + + ai.define_model(name='test/never', fn=never) + ai.define_prompt(name='greet', system='Be brief.', prompt='Hello {{name}}') + + [action] = await ai.list_prompts() + request = (await action.run({'name': 'Ada'})).response + + assert [(message.role, message.text) for message in request.messages] == [ + (Role.SYSTEM, 'Be brief.'), + (Role.USER, 'Hello Ada'), + ] + assert calls == 0 + + +@pytest.mark.asyncio +async def test_list_prompts_includes_file_prompts_with_their_input_schema(tmp_path: Path) -> None: + """A `.prompt` file is listed under its file name, its frontmatter schema already loaded.""" + (tmp_path / 'greet.prompt').write_text('---\ninput:\n schema:\n name: string\n---\nHello {{name}}\n') + ai = Genkit(prompt_dir=tmp_path) + + [action] = await ai.list_prompts() + + assert action.name == 'greet' + assert (action.input_schema or {}).get('properties') == {'name': {'type': 'string'}} + + 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 0c6f398a59fd748b7f6b0b5971e655fcc1b42219 Mon Sep 17 00:00:00 2001 From: Hilary Date: Wed, 11 Nov 2026 14:07:56 +0100 Subject: [PATCH 2/2] feat(py/plugins/mcp): serve Genkit prompts over MCP --- packages/genkit-mcp/README.md | 47 +- .../genkit-mcp/src/genkit_mcp/__init__.py | 2 +- .../genkit-mcp/src/genkit_mcp/_prompts.py | 335 +++++++++++++ packages/genkit-mcp/src/genkit_mcp/_server.py | 124 ++++- packages/genkit-mcp/tests/mcp_prompts_test.py | 469 ++++++++++++++++++ packages/genkit-mcp/tests/mcp_server_test.py | 6 +- 6 files changed, 968 insertions(+), 15 deletions(-) create mode 100644 packages/genkit-mcp/src/genkit_mcp/_prompts.py create mode 100644 packages/genkit-mcp/tests/mcp_prompts_test.py diff --git a/packages/genkit-mcp/README.md b/packages/genkit-mcp/README.md index 43ea33bc..057cee9d 100644 --- a/packages/genkit-mcp/README.md +++ b/packages/genkit-mcp/README.md @@ -165,8 +165,8 @@ them, so the next `generate` lists every server again. ## Serving your app as an MCP server -`create_mcp_server` wraps a `Genkit` instance and registers nothing, so the tools it serves are the -ones the app already has: +`create_mcp_server` wraps a `Genkit` instance and registers nothing, so the tools and prompts it +serves are the ones the app already has: ```python import asyncio @@ -218,6 +218,44 @@ call. A result that cannot be encoded as UTF-8 answers with `Tool '' faile fails to start fails the listing, and the client is told only that the server could not list its tools. +### Prompts + +The app's prompts are read with `ai.list_prompts()` on every `prompts/list`, and each variant is its +own prompt, named `greet.formal`. `prompts/get` renders the prompt into the messages a model would +get, without calling the model: + +```python +ai = Genkit(model='googleai/gemini-flash-latest') + + +class Person(BaseModel): + name: str + + +ai.define_prompt(name='greet', input_schema=Person, system='Be brief.', prompt='Hello {{name}}') +``` + +Each named input field is one argument. MCP arguments are always strings, so each is read as the +type its field's schema names: a number, a boolean, or JSON for an object or an array. An optional +field is read as its type without the null, and a field that may be one of several types is left +as text. A prompt whose input is not an object takes it as a single `input` argument, and one that +accepts fields its schema does not name, including a prompt with no input schema, takes them +together as an `inputJson` JSON object. The input is then checked against the prompt's schema, with +the prompt's defaults filled in first. + +A failure is worded as a tool's is. An argument that does not parse as its type, or input the +prompt's schema rejects, answers with invalid params naming the failing field, without the value +sent. A schema given as JSON, as a `.prompt` file's is, quotes the value in its error, so its +rejection names only the prompt. A `PublicError` sends +its status and message. Any other `GenkitError` answers with an internal error saying `Prompt +'' failed to render: `, and any other exception with just `Prompt '' failed to +render`. + +Context documents come first, as user messages. MCP has only user and assistant messages, so a +system turn is sent as a user message beginning `System instructions:` and a tool turn as one +beginning `Tool output:`. Inline images and audio are embedded, media that lives at a URL is sent +as a resource link, and a part MCP has no content for, such as a tool request, is sent as its JSON. + ### stdio `await server.start()` serves on this process's stdin and stdout until stdin closes. They are the @@ -247,3 +285,8 @@ check of the result. Nothing sends `notifications/tools/list_changed`; the list request instead. A client's `notifications/cancelled` cancels the tool call. Progress, sampling and elicitation are not supported. A plugin-namespaced tool name carries a `/`, which the MCP SDK warns about. stdio reads and writes UTF-8 whatever the locale, but is untested on Windows. + +A prompt renders only when the app has a model configured, even though `prompts/get` never calls it; +without one, it answers with `Prompt '' failed to render: INVALID_ARGUMENT`. An argument that has a default is still advertised as +required when the schema requires it. A prompt's output instructions are not part of the rendered +messages, since Genkit adds them when it generates. diff --git a/packages/genkit-mcp/src/genkit_mcp/__init__.py b/packages/genkit-mcp/src/genkit_mcp/__init__.py index 539bdc77..e5af6dd0 100644 --- a/packages/genkit-mcp/src/genkit_mcp/__init__.py +++ b/packages/genkit-mcp/src/genkit_mcp/__init__.py @@ -17,7 +17,7 @@ """Model Context Protocol for Genkit. Exposes the tools of one or more stdio MCP servers as Genkit ``tool`` actions, -and serves a Genkit app's own tools to MCP clients. +and serves a Genkit app's own tools and prompts to MCP clients. """ from genkit_mcp._client import McpClient, define_mcp_client diff --git a/packages/genkit-mcp/src/genkit_mcp/_prompts.py b/packages/genkit-mcp/src/genkit_mcp/_prompts.py new file mode 100644 index 00000000..afb38962 --- /dev/null +++ b/packages/genkit-mcp/src/genkit_mcp/_prompts.py @@ -0,0 +1,335 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# SPDX-License-Identifier: Apache-2.0 + +"""Translation of Genkit prompts and their rendered requests into MCP shapes.""" + +import json +import math +import re +from typing import Any + +from mcp.types import ( + AudioContent, + BlobResourceContents, + ContentBlock, + EmbeddedResource, + ImageContent, + Prompt, + PromptArgument, + PromptMessage, + ResourceLink, + TextContent, +) +from pydantic import AnyUrl + +from genkit import Message, Part, Role +from genkit.model import ModelRequest +from genkit.plugin_api import Action + +_DATA_URL = re.compile(r'^data:(?P[^;,]+)(?:;[^;,]*)*;base64,(?P.*)$', re.DOTALL) + +_INTEGER = re.compile(r'-?(?:0|[1-9][0-9]*)') + +_MAX_REF_DEPTH = 32 +"""How many ``$ref`` hops are followed before a schema is taken as it stands.""" + +SCALAR_ARGUMENT = 'input' +"""The one argument a prompt whose input is not an object takes.""" + +JSON_ARGUMENT = 'inputJson' +"""The argument that carries input fields a prompt's schema does not name, as a JSON object.""" + +_PREFIXES: dict[str, str] = {Role.SYSTEM: 'System instructions:\n', Role.TOOL: 'Tool output:\n'} +"""How a turn MCP has no role for is marked when it is sent as a user turn.""" + + +class PromptArgumentError(ValueError): + """An MCP argument that cannot be read as what the prompt's schema expects.""" + + +def prompt_to_mcp(action: Action) -> Prompt: + """Describe one Genkit prompt action as an MCP prompt. + + Each named input field becomes one argument. A prompt whose input is not an + object takes it as ``input``, and one that accepts fields its schema does not + name also takes them together as ``inputJson``. + + Args: + action: A registered ``prompt`` action. + + Returns: + The MCP prompt description. + """ + schema = dict(action.input_schema or {}) + return Prompt(name=action.name, description=action.description, arguments=_arguments(schema)) + + +def prompt_input(schema: dict[str, Any], arguments: dict[str, str]) -> object: + """Read MCP's string arguments as the input the prompt's schema describes. + + Args: + schema: The prompt's input JSON schema. + arguments: What the client sent, every value a string. + + Returns: + The prompt input, or ``None`` when no arguments were sent. + + Raises: + PromptArgumentError: An argument does not parse as its field's type. + """ + if not arguments: + return None + root = schema + schema = _resolve(schema, root) + if not _is_object(schema): + if set(arguments) != {SCALAR_ARGUMENT}: + raise PromptArgumentError(f'this prompt takes a single {SCALAR_ARGUMENT!r} argument') + return _convert(schema, arguments[SCALAR_ARGUMENT], SCALAR_ARGUMENT) + + properties = _as_object(schema.get('properties')) + takes_json = _takes_json_input(schema, properties) + value: dict[str, Any] = {} + if takes_json and JSON_ARGUMENT in arguments: + fields = _convert({**schema, 'type': 'object'}, arguments[JSON_ARGUMENT], JSON_ARGUMENT) + value.update(_as_object(fields)) + for name, text in arguments.items(): + if takes_json and name == JSON_ARGUMENT: + continue + value[name] = _convert(_field_schema(schema, properties, name, root), text, name) + return value + + +def request_to_messages(request: ModelRequest, prompt_name: str) -> list[PromptMessage]: + """Convert a rendered prompt into MCP prompt messages. + + Context documents come first, as user turns. MCP has only user and + assistant turns, so system and tool turns are sent as user turns with their + text marked. + + Args: + request: What running the prompt action rendered. + prompt_name: Name of the prompt, used to mint a URI for binary content + that has no URI of its own. + + Returns: + One MCP message per content part. + """ + messages: list[PromptMessage] = [] + index = 0 + for number, doc in enumerate(request.docs or [], start=1): + header = f'Context document {number}:' + if doc.metadata: + header += f'\nMetadata: {json.dumps(doc.metadata)}' + messages.append(PromptMessage(role='user', content=TextContent(type='text', text=header))) + for part in doc.content: + messages.append(PromptMessage(role='user', content=_part_to_block(part, prompt_name, index))) + index += 1 + for message in request.messages: + for part in message.content: + messages.append(_part_to_message(message, part, prompt_name, index)) + index += 1 + return messages + + +def _arguments(schema: dict[str, Any]) -> list[PromptArgument]: + """List the arguments a prompt with this input schema takes, sorted by name.""" + schema = _resolve(schema, schema) + if not _is_object(schema): + description = schema.get('description') + return [ + PromptArgument( + name=SCALAR_ARGUMENT, + description=description if isinstance(description, str) else None, + required=True, + ) + ] + properties = _as_object(schema.get('properties')) + raw_required = schema.get('required') + required = {name for name in raw_required if isinstance(name, str)} if isinstance(raw_required, list) else set() + arguments: list[PromptArgument] = [] + for name, field in properties.items(): + description = _as_object(field).get('description') + arguments.append( + PromptArgument( + name=name, + description=description if isinstance(description, str) else None, + required=name in required, + ) + ) + if _takes_json_input(schema, properties): + arguments.append( + PromptArgument(name=JSON_ARGUMENT, description='JSON object of prompt input fields', required=False) + ) + return sorted(arguments, key=lambda argument: argument.name) + + +def _is_object(schema: dict[str, Any]) -> bool: + """Whether the input is an object, which a schema with no type or union is taken to be.""" + kind = schema.get('type') + if kind is None: + return not schema.get('anyOf') and not schema.get('oneOf') + return kind == 'object' + + +def _resolve(schema: dict[str, Any], root: dict[str, Any]) -> dict[str, Any]: + """Reduce a schema to the one type an argument is read as, where it has one. + + A ``$ref`` into the root's ``$defs`` is followed, and a ``null`` alternative + is dropped, since an optional field's argument is only sent with a value. A + schema left with several types is returned as it is, and its argument is + read as text. + """ + for _ in range(_MAX_REF_DEPTH): + ref = schema.get('$ref') + if not isinstance(ref, str) or not ref.startswith('#/$defs/'): + break + target = _as_object(_as_object(root.get('$defs')).get(ref.removeprefix('#/$defs/'))) + schema = {**{key: value for key, value in schema.items() if key != '$ref'}, **target} + kind = schema.get('type') + if isinstance(kind, list): + types = [item for item in kind if item != 'null'] + return {**schema, 'type': types[0]} if len(types) == 1 else schema + for union in ('anyOf', 'oneOf'): + branches = schema.get(union) + if not isinstance(branches, list): + continue + typed = [_resolve(_as_object(branch), root) for branch in branches] + present = [branch for branch in typed if branch.get('type') != 'null'] + if len(present) == 1: + rest = {key: value for key, value in schema.items() if key != union} + return {**rest, **present[0]} + return schema + + +def _takes_json_input(schema: dict[str, Any], properties: dict[str, Any]) -> bool: + """Whether the prompt accepts fields it does not name, so ``inputJson`` is offered. + + A prompt with no named fields is taken to accept any, unless its schema + says otherwise. + """ + additional = schema.get('additionalProperties') + if additional is False or JSON_ARGUMENT in properties: + return False + return not properties or additional is not None + + +def _field_schema( + schema: dict[str, Any], properties: dict[str, Any], name: str, root: dict[str, Any] +) -> dict[str, Any]: + """The schema of one input field, falling back to what unnamed fields must match.""" + field = properties[name] if name in properties else schema.get('additionalProperties') + return _resolve(_as_object(field), root) + + +def _convert(schema: dict[str, Any], text: str, name: str) -> object: + """Parse one string argument as the type its schema names; text stays text.""" + kind = schema.get('type') + if kind == 'integer': + return _integer(text, name) + if kind == 'number': + return _number(text, name) + if kind == 'boolean': + if text.lower() in ('true', 'false'): + return text.lower() == 'true' + raise PromptArgumentError(f'argument {name!r} must be true or false') + if kind in ('object', 'array'): + try: + value = json.loads(text) + except json.JSONDecodeError as error: + raise PromptArgumentError(f'argument {name!r} must be JSON: {error.msg}') from None + expected = dict if kind == 'object' else list + if not isinstance(value, expected): + raise PromptArgumentError(f'argument {name!r} must be a JSON {kind}') + return value + return text + + +def _integer(text: str, name: str) -> int: + """Parse a whole number, allowing the JSON spelling of one such as ``3.0``.""" + if _INTEGER.fullmatch(text): + return int(text) + value = _number(text, name) + if value != int(value): + raise PromptArgumentError(f'argument {name!r} must be a whole number') + return int(value) + + +def _number(text: str, name: str) -> float: + """Parse a finite number.""" + try: + value = float(text) + except ValueError: + raise PromptArgumentError(f'argument {name!r} must be a number') from None + if not math.isfinite(value): + raise PromptArgumentError(f'argument {name!r} must be a finite number') + return value + + +def _part_to_message(message: Message, part: Part, prompt_name: str, index: int) -> PromptMessage: + """Convert one part of a rendered turn into an MCP message.""" + content = _part_to_block(part, prompt_name, index) + prefix = _PREFIXES.get(message.role) + if prefix is not None and isinstance(content, TextContent): + content = TextContent(type='text', text=prefix + content.text) + return PromptMessage(role='assistant' if message.role == Role.MODEL else 'user', content=content) + + +def _part_to_block(part: Part, prompt_name: str, index: int) -> ContentBlock: + """Convert one Genkit content part into an MCP content block. + + A part MCP has no block for is sent as its JSON. A part's metadata is not + sent, since MCP content has nowhere to carry it. + """ + if part.text is not None: + return TextContent(type='text', text=part.text) + if part.media is not None: + return _media_block(part.media.url, part.media.content_type, prompt_name, index) + if part.resource is not None: + return _link(str(part.resource.uri), None) + if part.data is not None or 'data' in part.model_fields_set: + return TextContent(type='text', text=json.dumps(part.data)) + return TextContent(type='text', text=json.dumps(part.model_dump(by_alias=True, exclude_none=True))) + + +def _media_block(url: str, content_type: str | None, prompt_name: str, index: int) -> ContentBlock: + """Embed base64 inline media, and link to media that lives elsewhere.""" + match = _DATA_URL.match(url) + if match is None: + return _link(url, content_type) + mime_type = content_type or match.group('mime') + data = match.group('data') + if mime_type.startswith('image/'): + return ImageContent(type='image', mimeType=mime_type, data=data) + if mime_type.startswith('audio/'): + return AudioContent(type='audio', mimeType=mime_type, data=data) + return EmbeddedResource( + type='resource', + resource=BlobResourceContents( + uri=AnyUrl(f'genkit://prompt/{prompt_name}/content/{index}'), + mimeType=mime_type, + blob=data, + ), + ) + + +def _link(url: str, mime_type: str | None) -> ContentBlock: + """Link to content by URL, or send the URL as text when it is not absolute.""" + try: + uri = AnyUrl(url) + except ValueError: + return TextContent(type='text', text=url) + return ResourceLink(type='resource_link', uri=uri, name=url, mimeType=mime_type) + + +def _as_object(value: object) -> dict[str, Any]: + """Read a schema value that should be a nested object, or nothing.""" + if not isinstance(value, dict): + return {} + return {str(key): item for key, item in value.items()} diff --git a/packages/genkit-mcp/src/genkit_mcp/_server.py b/packages/genkit-mcp/src/genkit_mcp/_server.py index c0242d11..3f4578ca 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_server.py +++ b/packages/genkit-mcp/src/genkit_mcp/_server.py @@ -18,12 +18,31 @@ from mcp.server.lowlevel import Server from mcp.server.stdio import stdio_server from mcp.shared.exceptions import McpError -from mcp.types import INTERNAL_ERROR, CallToolResult, ErrorData, Tool as McpTool -from pydantic import TypeAdapter - -from genkit import Genkit, GenkitError, Interrupt, MultipartToolResponse, PublicError, Tool, get_logger +from mcp.types import ( + INTERNAL_ERROR, + INVALID_PARAMS, + CallToolResult, + ErrorData, + GetPromptResult, + Prompt, + Tool as McpTool, +) +from pydantic import TypeAdapter, ValidationError + +from genkit import ( + ErrorReason, + Genkit, + GenkitError, + Interrupt, + MultipartToolResponse, + PublicError, + Tool, + get_logger, +) +from genkit.plugin_api import Action from genkit.web import error_body, error_status from genkit_mcp._export import error_result, multipart_to_call_result, tool_to_mcp +from genkit_mcp._prompts import PromptArgumentError, prompt_input, prompt_to_mcp, request_to_messages logger = get_logger(__name__) @@ -34,12 +53,17 @@ _LISTING_FAILED = 'The server could not list its tools' +_PROMPT_LISTING_FAILED = 'The server could not list its prompts' + +_CUSTOM_ERROR_TYPES = frozenset({'value_error', 'assertion_error'}) +"""Pydantic error types whose message is a custom validator's own text.""" + class McpServer: - """Serves a Genkit app's tools to MCP clients. + """Serves a Genkit app's tools and prompts to MCP clients. - Tools are read from the app on every ``tools/list``, so a tool defined - after the server was built is still served. Tools a dynamic action + Tools and prompts are read from the app on every list request, so one + defined after the server was built is still served. Tools a dynamic action provider serves are not. Attributes: @@ -59,7 +83,7 @@ def __init__( """Build a server over a Genkit app. Args: - ai: The app whose tools are served. + ai: The app whose tools and prompts are served. name: Name the server advertises. version: Version the server advertises. instructions: How a client should use this server. @@ -75,6 +99,8 @@ def __init__( self._server: Server[Any, Any] = Server(name, version=version, instructions=instructions) self._server.list_tools()(self._list_tools) self._server.call_tool()(self._call_tool) + self._server.list_prompts()(self._list_prompts) + self._server.get_prompt()(self._get_prompt) @property def name(self) -> str: @@ -182,6 +208,47 @@ async def _answer(self, name: str, arguments: dict[str, Any]) -> CallToolResult: logger.exception('an MCP tool call failed', tool=name) return error_result(_client_message(name, error)) + async def _list_prompts(self) -> list[Prompt]: + """Describe every prompt this server offers, read fresh from the app.""" + try: + return [prompt_to_mcp(action) for action in await self._ai.list_prompts()] + except Exception as error: + logger.exception("could not list the app's prompts for MCP") + raise McpError(ErrorData(code=INTERNAL_ERROR, message=_PROMPT_LISTING_FAILED)) from error + + async def _get_prompt(self, name: str, arguments: dict[str, str] | None) -> GetPromptResult: + """Render one prompt with the client's arguments, without calling a model. + + An error the client caused is reported as invalid params, and any other + as an internal error, logged here where its traceback is still useful. A + result that cannot be encoded fails here rather than in the transport, + where it would end the session. + """ + try: + action = await self._find_prompt(name) + if action is None: + raise McpError(ErrorData(code=INVALID_PARAMS, message=f'Prompt {name!r} is not registered')) + value = prompt_input(dict(action.input_schema or {}), arguments or {}) + request = (await action.run(value)).response + result = GetPromptResult(description=action.description, messages=request_to_messages(request, name)) + result.model_dump_json(by_alias=True, exclude_none=True) + return result + except McpError: + raise + except PromptArgumentError as error: + raise McpError(ErrorData(code=INVALID_PARAMS, message=str(error))) from None + except Exception as error: + if error_status(error) >= 500: + logger.exception('an MCP prompt failed to render', prompt=name) + raise _prompt_error(name, error) from None + + async def _find_prompt(self, name: str) -> Action | None: + """Find a prompt by the name it was listed under.""" + for action in await self._ai.list_prompts(): + if action.name == name: + return action + return None + def _request_context(self) -> dict[str, Any] | None: """Pass the request's MCP ``_meta`` in the shape the client's handler reads.""" try: @@ -211,7 +278,7 @@ def create_mcp_server( """Build a server over a Genkit app, registering nothing. Args: - ai: The app whose tools are served. + ai: The app whose tools and prompts are served. name: Name the server advertises. version: Version the server advertises. instructions: How a client should use this server. @@ -267,6 +334,45 @@ def _as_json(value: object) -> Any: # noqa: ANN401 - whatever JSON the value du return _JSON.dump_python(value, mode='json', by_alias=True) +def _prompt_error(prompt_name: str, error: Exception) -> McpError: + """Say why a prompt failed to render, by the rule ``_client_message`` follows for tools. + + Input the prompt's schema rejects is the client's, so it is invalid params + naming the failing fields, without the values sent. A ``PublicError`` sends + its status and message, and anything else only its status, as an internal + error. + """ + if isinstance(error, GenkitError) and error.reason == ErrorReason.INVALID_INPUT: + return McpError(ErrorData(code=INVALID_PARAMS, message=_invalid_input_message(prompt_name, error))) + status = error_status(error) + if isinstance(error, PublicError) or status < 500: + body = error_body(error) + message = f'{body["status"]}: {body["message"]}' + elif isinstance(error, GenkitError): + message = f'Prompt {prompt_name!r} failed to render: {error.status}' + else: + message = f'Prompt {prompt_name!r} failed to render' + return McpError(ErrorData(code=INVALID_PARAMS if status < 500 else INTERNAL_ERROR, message=message)) + + +def _invalid_input_message(prompt_name: str, error: GenkitError) -> str: + """Name each field the prompt's model rejected and why, in Pydantic's fixed wording. + + A schema given as JSON is checked by text that quotes the value, so its + failure is reported without the field. + """ + message = f'Invalid input for prompt {prompt_name!r}' + cause = error.__cause__ + if not isinstance(cause, ValidationError): + return message + problems = [ + f'{".".join(str(part) for part in problem["loc"]) or "input"}: ' + f'{"Value error" if problem["type"] in _CUSTOM_ERROR_TYPES else problem["msg"]}' + for problem in cause.errors(include_url=False, include_input=False) + ] + return f'{message}: {"; ".join(problems)}' if problems else message + + def _client_message(tool_name: str, error: Exception) -> str: """Say why a tool failed without passing on text the app never chose to show. diff --git a/packages/genkit-mcp/tests/mcp_prompts_test.py b/packages/genkit-mcp/tests/mcp_prompts_test.py new file mode 100644 index 00000000..bf1a9f7a --- /dev/null +++ b/packages/genkit-mcp/tests/mcp_prompts_test.py @@ -0,0 +1,469 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# SPDX-License-Identifier: Apache-2.0 + +"""Tests serving Genkit prompts to an in-memory MCP client.""" + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import date +from pathlib import Path +from typing import Any + +import pytest +from genkit_mcp._prompts import PromptArgumentError, prompt_input, request_to_messages +from genkit_mcp._server import McpServer, create_mcp_server +from mcp import ClientSession +from mcp.shared.exceptions import McpError +from mcp.shared.memory import create_connected_server_and_client_session +from mcp.types import INTERNAL_ERROR, INVALID_PARAMS, ImageContent, PromptMessage, ResourceLink, TextContent +from pydantic import BaseModel, Field + +from genkit import ( + Document, + FinishReason, + Genkit, + GenkitError, + Media, + Message, + ModelResponse, + Part, + PublicError, + Role, +) +from genkit.model import ModelContext, ModelRequest + +PIXEL = 'iVBORw0KGgo=' + + +class Person(BaseModel): + """Input of a prompt whose fields are all text.""" + + name: str + + +class Order(BaseModel): + """Input of a prompt whose fields MCP sends as strings but are not text.""" + + count: int + vip: bool + items: list[str] + + +@asynccontextmanager +async def connected(server: McpServer) -> AsyncIterator[ClientSession]: + """Drive a server over the SDK's in-memory transport.""" + async with create_connected_server_and_client_session(server._server, raise_exceptions=True) as session: + yield session + + +def app(prompt_dir: Path | None = None) -> tuple[Genkit, list[ModelRequest]]: + """An app with a default model that records every call it gets.""" + ai = Genkit(model='test/recorder', prompt_dir=prompt_dir) + calls: list[ModelRequest] = [] + + async def recorder(request: ModelRequest, ctx: ModelContext) -> ModelResponse: + calls.append(request) + return ModelResponse( + finish_reason=FinishReason.STOP, + message=Message(role=Role.MODEL, content=[Part.from_text('unused')]), + ) + + ai.define_model(name='test/recorder', fn=recorder) + return ai, calls + + +def texts(messages: list[PromptMessage]) -> list[tuple[str, str]]: + """Read each message as its role and text, failing on any other content.""" + out: list[tuple[str, str]] = [] + for message in messages: + assert isinstance(message.content, TextContent) + out.append((message.role, message.content.text)) + return out + + +async def get_error(session: ClientSession, name: str, arguments: dict[str, str] | None = None) -> McpError: + """Ask for a prompt that must fail, and return the error the client got.""" + with pytest.raises(McpError) as caught: + await session.get_prompt(name, arguments) + return caught.value + + +@pytest.mark.asyncio +async def test_a_prompt_defined_after_the_server_is_listed_with_its_arguments() -> None: + """Listing reads the app per request, and each input field becomes one argument.""" + ai, _ = app() + server = create_mcp_server(ai, 'bookshop') + ai.define_prompt(name='order', description='Place an order.', input_schema=Order, prompt='{{count}}') + + async with connected(server) as session: + [prompt] = (await session.list_prompts()).prompts + + assert prompt.name == 'order' + assert prompt.description == 'Place an order.' + assert [(argument.name, argument.required) for argument in prompt.arguments or []] == [ + ('count', True), + ('items', True), + ('vip', True), + ] + + +@pytest.mark.asyncio +async def test_getting_a_prompt_renders_it_without_calling_the_model() -> None: + """A system turn goes out as a marked user message, and the model never runs.""" + ai, calls = app() + ai.define_prompt( + name='greet', description='Say hello.', input_schema=Person, system='Be brief.', prompt='Hello {{name}}' + ) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.get_prompt('greet', {'name': 'Ada'}) + + assert result.description == 'Say hello.' + assert texts(result.messages) == [('user', 'System instructions:\nBe brief.'), ('user', 'Hello Ada')] + assert calls == [] + + +@pytest.mark.asyncio +async def test_a_variant_is_its_own_prompt() -> None: + ai, _ = app() + ai.define_prompt(name='greet', input_schema=Person, prompt='Hello {{name}}') + ai.define_prompt(name='greet', variant='formal', input_schema=Person, prompt='Good day, {{name}}') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + listed = sorted(prompt.name for prompt in (await session.list_prompts()).prompts) + result = await session.get_prompt('greet.formal', {'name': 'Ada'}) + + assert listed == ['greet', 'greet.formal'] + assert texts(result.messages) == [('user', 'Good day, Ada')] + + +@pytest.mark.asyncio +async def test_string_arguments_are_read_as_the_types_the_schema_names() -> None: + """A `false` that stayed a string would be truthy and print VIP.""" + ai, _ = app() + ai.define_prompt( + name='order', + input_schema=Order, + prompt='{{#if vip}}VIP {{/if}}{{count}} of {{#each items}}{{this}};{{/each}}', + ) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.get_prompt('order', {'count': '3', 'vip': 'false', 'items': '["tea", "cake"]'}) + + assert texts(result.messages) == [('user', '3 of tea;cake;')] + + +@pytest.mark.asyncio +async def test_an_argument_that_does_not_parse_is_invalid_params() -> None: + ai, _ = app() + ai.define_prompt(name='order', input_schema=Order, prompt='{{count}}') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'order', {'count': 'many', 'vip': 'true', 'items': '[]'}) + + assert error.error.code == INVALID_PARAMS + assert "'count'" in error.error.message + + +@pytest.mark.asyncio +async def test_a_missing_required_argument_is_invalid_params() -> None: + """The prompt's own schema check catches it, after its defaults are filled in, and names the field.""" + ai, _ = app() + ai.define_prompt(name='greet', input_schema=Person, prompt='Hello {{name}}') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'greet', {}) + + assert error.error.code == INVALID_PARAMS + assert error.error.message == "Invalid input for prompt 'greet': name: Field required" + + +@pytest.mark.asyncio +async def test_a_default_fills_an_argument_the_client_leaves_out(tmp_path: Path) -> None: + (tmp_path / 'greet.prompt').write_text( + '---\ninput:\n schema:\n name: string\n default:\n name: friend\n---\nHello {{name}}\n' + ) + ai, _ = app(prompt_dir=tmp_path) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.get_prompt('greet') + + assert texts(result.messages) == [('user', 'Hello friend')] + + +@pytest.mark.asyncio +async def test_an_unknown_prompt_is_invalid_params() -> None: + ai, _ = app() + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'missing') + + assert error.error.code == INVALID_PARAMS + assert error.error.message == "Prompt 'missing' is not registered" + + +@pytest.mark.asyncio +async def test_a_prompt_without_an_input_schema_takes_its_fields_as_json() -> None: + ai, _ = app() + ai.define_prompt(name='greet', prompt='Hello {{name}}') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + [prompt] = (await session.list_prompts()).prompts + result = await session.get_prompt('greet', {'inputJson': '{"name": "Ada"}'}) + + assert [(argument.name, argument.required) for argument in prompt.arguments or []] == [('inputJson', False)] + assert texts(result.messages) == [('user', 'Hello Ada')] + + +@pytest.mark.asyncio +async def test_an_app_without_a_model_cannot_render() -> None: + """The cause is in the server's log; the client gets only the status.""" + ai = Genkit() + ai.define_prompt(name='greet', input_schema=Person, prompt='Hello {{name}}') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'greet', {'name': 'Ada'}) + + assert error.error.code == INTERNAL_ERROR + assert error.error.message == "Prompt 'greet' failed to render: INVALID_ARGUMENT" + + +@pytest.mark.asyncio +async def test_a_render_that_raises_keeps_its_text_off_the_wire(monkeypatch: pytest.MonkeyPatch) -> None: + """Any error that is not a GenkitError can carry a URL or a credential.""" + ai, _ = app() + ai.define_prompt(name='greet', input_schema=Person, prompt='Hello {{name}}') + [action] = await ai.list_prompts() + + async def explode(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + raise RuntimeError('https://user:secret@example.com') + + monkeypatch.setattr(action, 'run', explode) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'greet', {'name': 'Ada'}) + + assert error.error.code == INTERNAL_ERROR + assert error.error.message == "Prompt 'greet' failed to render" + + +@pytest.mark.asyncio +async def test_documents_come_first_and_model_turns_are_assistant_messages() -> None: + ai, _ = app() + ai.define_prompt( + name='recall', + docs=[Document.from_text('Ada likes tea.', metadata={'source': 'notes'})], + messages=[Message(role=Role.MODEL, content=[Part.from_text('What would you like?')])], + prompt='Something to drink.', + ) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.get_prompt('recall') + + assert texts(result.messages) == [ + ('user', 'Context document 1:\nMetadata: {"source": "notes"}'), + ('user', 'Ada likes tea.'), + ('assistant', 'What would you like?'), + ('user', 'Something to drink.'), + ] + + +@pytest.mark.asyncio +async def test_inline_media_is_embedded_and_remote_media_is_linked() -> None: + ai, _ = app() + ai.define_prompt( + name='look', + prompt=[ + Part(media=Media(url=f'data:image/png;base64,{PIXEL}', content_type='image/png')), + Part(media=Media(url='https://example.com/cat.png', content_type='image/png')), + ], + ) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.get_prompt('look') + + inline, remote = (message.content for message in result.messages) + assert isinstance(inline, ImageContent) + assert (inline.mimeType, inline.data) == ('image/png', PIXEL) + assert isinstance(remote, ResourceLink) + assert str(remote.uri) == 'https://example.com/cat.png' + + +class Address(BaseModel): + city: str + + +class Delivery(BaseModel): + """Input whose fields pydantic describes with a union and a reference.""" + + count: int | None = None + address: Address + + +@pytest.mark.asyncio +async def test_optional_and_nested_fields_are_read_as_their_types() -> None: + """Pydantic writes `int | None` as anyOf and a nested model as a `$ref`.""" + ai, _ = app() + ai.define_prompt(name='deliver', input_schema=Delivery, prompt='{{count}} to {{address.city}}') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.get_prompt('deliver', {'count': '3', 'address': '{"city": "Paris"}'}) + + assert texts(result.messages) == [('user', '3 to Paris')] + + +@pytest.mark.asyncio +async def test_an_optional_field_of_a_file_prompt_is_read_as_its_type(tmp_path: Path) -> None: + """Picoschema writes an optional field as a type list that includes null.""" + (tmp_path / 'order.prompt').write_text( + '---\ninput:\n schema:\n count?: integer\n vip?: boolean\n---\n{{#if vip}}VIP {{/if}}{{count}}\n' + ) + ai, _ = app(prompt_dir=tmp_path) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + result = await session.get_prompt('order', {'count': '3', 'vip': 'false'}) + + assert texts(result.messages) == [('user', '3')] + + +@pytest.mark.asyncio +async def test_a_failure_after_rendering_keeps_its_text_off_the_wire() -> None: + """Mapping runs after the prompt renders, and its errors are internal ones too.""" + ai, _ = app() + ai.define_prompt( + name='recall', + docs=[Document.from_text('Ada likes tea.', metadata={'when': date(2020, 1, 1)})], + prompt='Something to drink.', + ) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'recall') + + assert error.error.code == INTERNAL_ERROR + assert error.error.message == "Prompt 'recall' failed to render" + + +@pytest.mark.asyncio +async def test_a_genkit_error_while_rendering_sends_only_its_status(monkeypatch: pytest.MonkeyPatch) -> None: + """A provider's error text can name a project or a URL.""" + ai, _ = app() + ai.define_prompt(name='greet', input_schema=Person, prompt='Hello {{name}}') + [action] = await ai.list_prompts() + + async def unavailable(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + raise GenkitError(status='UNAVAILABLE', message='try later') + + monkeypatch.setattr(action, 'run', unavailable) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'greet', {'name': 'Ada'}) + + assert error.error.code == INTERNAL_ERROR + assert error.error.message == "Prompt 'greet' failed to render: UNAVAILABLE" + + +@pytest.mark.asyncio +async def test_a_public_error_while_rendering_sends_its_status_and_message(monkeypatch: pytest.MonkeyPatch) -> None: + ai, _ = app() + ai.define_prompt(name='greet', input_schema=Person, prompt='Hello {{name}}') + [action] = await ai.list_prompts() + + async def busy(*args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + raise PublicError(status='UNAVAILABLE', message='try later') + + monkeypatch.setattr(action, 'run', busy) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'greet', {'name': 'Ada'}) + + assert error.error.code == INTERNAL_ERROR + assert error.error.message == 'UNAVAILABLE: try later' + + +@pytest.mark.asyncio +async def test_input_a_file_prompt_rejects_names_only_the_prompt(tmp_path: Path) -> None: + """A JSON schema's check quotes the value it rejects, so none of its text is sent.""" + (tmp_path / 'greet.prompt').write_text('---\ninput:\n schema:\n name: string\n---\nHello {{name}}\n') + ai, _ = app(prompt_dir=tmp_path) + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'greet', {'inputJson': '{}'}) + + assert error.error.code == INVALID_PARAMS + assert error.error.message == "Invalid input for prompt 'greet'" + + +class Stock(BaseModel): + """Input with a constraint Pydantic checks after the argument is read.""" + + count: int = Field(gt=0) + + +@pytest.mark.asyncio +async def test_rejected_input_names_the_field_without_the_value_sent() -> None: + ai, _ = app() + ai.define_prompt(name='restock', input_schema=Stock, prompt='{{count}}') + + async with connected(create_mcp_server(ai, 'bookshop')) as session: + error = await get_error(session, 'restock', {'count': '-41'}) + + assert error.error.code == INVALID_PARAMS + assert error.error.message == "Invalid input for prompt 'restock': count: Input should be greater than 0" + + +def test_a_field_that_may_be_several_types_stays_text() -> None: + schema = {'type': 'object', 'properties': {'n': {'anyOf': [{'type': 'string'}, {'type': 'integer'}]}}} + assert prompt_input(schema, {'n': '3'}) == {'n': '3'} + + +def test_a_scalar_union_takes_the_input_argument() -> None: + assert prompt_input({'anyOf': [{'type': 'integer'}, {'type': 'null'}]}, {'input': '7'}) == 7 + + +def test_inline_media_with_parameters_is_embedded() -> None: + request = ModelRequest( + messages=[ + Message(role=Role.USER, content=[Part(media=Media(url=f'data:image/png;name=dot.png;base64,{PIXEL}'))]) + ] + ) + [message] = request_to_messages(request, 'look') + assert isinstance(message.content, ImageContent) + assert message.content.data == PIXEL + + +def test_a_whole_number_may_be_spelled_as_json_writes_it() -> None: + assert prompt_input({'properties': {'n': {'type': 'integer'}}}, {'n': '3.0'}) == {'n': 3} + + +@pytest.mark.parametrize( + ('field', 'text'), + [ + ({'type': 'integer'}, '3.5'), + ({'type': 'number'}, 'inf'), + ({'type': 'boolean'}, 'yes'), + ({'type': 'object'}, '[1]'), + ({'type': 'array'}, '{"a": 1}'), + ({'type': 'array'}, '[1'), + ], +) +def test_an_argument_that_is_not_its_fields_type_is_refused(field: dict[str, Any], text: str) -> None: + with pytest.raises(PromptArgumentError, match="'n'"): + prompt_input({'properties': {'n': field}}, {'n': text}) + + +def test_a_scalar_prompt_takes_only_the_input_argument() -> None: + assert prompt_input({'type': 'integer'}, {'input': '7'}) == 7 + with pytest.raises(PromptArgumentError): + prompt_input({'type': 'integer'}, {'n': '7'}) + + +def test_a_field_the_schema_does_not_name_is_read_by_what_unnamed_fields_must_be() -> None: + schema = {'type': 'object', 'properties': {}, 'additionalProperties': {'type': 'integer'}} + assert prompt_input(schema, {'inputJson': '{"a": "text"}', 'b': '2'}) == {'a': 'text', 'b': 2} diff --git a/packages/genkit-mcp/tests/mcp_server_test.py b/packages/genkit-mcp/tests/mcp_server_test.py index 473dd241..80b70c11 100644 --- a/packages/genkit-mcp/tests/mcp_server_test.py +++ b/packages/genkit-mcp/tests/mcp_server_test.py @@ -110,8 +110,8 @@ async def test_the_server_advertises_its_name_and_version() -> None: @pytest.mark.asyncio -async def test_capabilities_offer_tools_and_nothing_else() -> None: - """Prompts and resources are not served, so they are not advertised.""" +async def test_capabilities_offer_tools_and_prompts_and_nothing_else() -> None: + """Resources are not served, so they are not advertised.""" ai = app() server = create_mcp_server(ai, 'bookshop') @@ -119,7 +119,7 @@ async def test_capabilities_offer_tools_and_nothing_else() -> None: result = await session.initialize() assert result.capabilities.tools is not None - assert result.capabilities.prompts is None + assert result.capabilities.prompts is not None assert result.capabilities.resources is None