Skip to content

feat(mcp): serve Genkit prompts over MCP - #96

Open
hilariie wants to merge 2 commits into
feat/mcp-server-stdiofrom
feat/mcp-server-prompts
Open

hilariie wants to merge 2 commits into
feat/mcp-server-stdiofrom
feat/mcp-server-prompts

Conversation

@hilariie

Copy link
Copy Markdown
Contributor

Summary

Serves an app's prompts over MCP, the prompts slice of the MCP server. prompts/list reads the app on every request, and prompts/get renders the prompt into the messages a model would get, without calling the model. Adds ai.list_prompts() to core, which returns the action of every registered prompt; each variant is its own prompt, named greet.formal.

ai = Genkit(model='googleai/gemini-flash-latest')
ai.define_prompt(name='greet', input_schema=Person, system='Be brief.', prompt='Hello {{name}}')

server = create_mcp_server(ai, 'bookshop')  # prompts/get greet {"name": "Ada"}
  • Each input field is one argument. MCP arguments are strings, so each is read as its field's type: integer, number, boolean, or JSON for an object or array. Optional, anyOf and $ref fields are read as their one non-null type. A prompt whose input is not an object takes a single input argument, and one with no named fields or with additionalProperties also takes inputJson.
  • The input is checked by the prompt's own schema after its defaults are filled in.
  • Context documents come first. MCP has only user and assistant messages, so system and tool turns are sent as user messages prefixed System instructions: and Tool output:. Inline images and audio are embedded, media at a URL is a resource link, and other parts are sent as JSON.
  • Errors follow the tools rule. An argument that does not parse, or input the prompt's schema rejects, is invalid params naming the failing fields without their values. A PublicError sends its status and message, any other GenkitError only its status, and any other exception nothing.
  • The server now advertises the prompts capability.

Not in this PR: rendering without a configured model (core needs one even though it is never called), marking a defaulted argument as optional, and output instructions in the rendered messages. All three are listed in the README.

Part of #91. Stacked on #93.

Verification

  • mcp_prompts_test.py drives a real client session over the SDK's in-memory transport: listing, variants, typed, optional and nested arguments, defaults from a .prompt file, documents and model turns, media, every error path, and that the model is never called.
  • lookup_test.py covers list_prompts() for variants, an empty app, rendering, and file prompts.

@huangjeff5 huangjeff5 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The MCP prompt rendering flow looks solid overall. Three things before landing: please drop the core list_prompts() from this PR and build on #139 instead, non-object prompt inputs crash in action.run, and _invalid_input_message misses several value-bearing Pydantic error types and caller-key sanitization.

Comment on lines +737 to +738
async def list_prompts(self) -> list[Action[Any, ModelRequest]]:
"""Return the action of every prompt registered on this app, in no particular order.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#139 adds ai.list_prompts() to core and returns Prompt handles instead of raw actions, so whatever you get back can still generate when called, and plugin-API types stay off Genkit. Could you drop this method and rebase onto #139? prompts/list can then read await prompt.describe() (name, description, input schema), and prompts/get can read await prompt.render(input). render() returns GenerateActionOptions, so request_to_messages would read options.messages and options.docs instead of a ModelRequest.

Comment on lines +91 to +94
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Genkit prompts only render mapping or BaseModel inputs: coerce_prompt_template_input, caller_input_keys, and render_dotprompt_to_parts ({**context, **input_}) raise TypeError when action.run(value) receives a scalar or list like 7, turning prompts/get into INTERNAL_ERROR. test_a_scalar_prompt_takes_only_the_input_argument only calls prompt_input() directly, so action.run isn't exercised end-to-end here. Either skip non-object prompts like _export.py does for tools (and drop the scalar input note from README.md), or support non-object inputs in prompt rendering.

Comment on lines +358 to +373
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_invalid_input_message only redacts value_error and assertion_error, so value-bearing Pydantic errors in genkit._core._error._VALUE_BEARING_ERROR_TYPES (such as uuid_parsing, union_tag_invalid, and datetime_object_invalid) still leak into the message, and loc isn't sanitized for extra_forbidden or non-identifier keys. Reusing _served_problem (or sharing a helper from genkit._core._error) keeps prompt input redaction aligned with flows and tools.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants