|
| 1 | +"""Elicitation utilities for MCP servers.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import types |
| 6 | +from typing import Generic, Literal, TypeVar, Union, get_args, get_origin |
| 7 | + |
| 8 | +from pydantic import BaseModel |
| 9 | +from pydantic.fields import FieldInfo |
| 10 | + |
| 11 | +from mcp.server.session import ServerSession |
| 12 | +from mcp.types import RequestId |
| 13 | + |
| 14 | +ElicitSchemaModelT = TypeVar("ElicitSchemaModelT", bound=BaseModel) |
| 15 | + |
| 16 | + |
| 17 | +class AcceptedElicitation(BaseModel, Generic[ElicitSchemaModelT]): |
| 18 | + """Result when user accepts the elicitation.""" |
| 19 | + |
| 20 | + action: Literal["accept"] = "accept" |
| 21 | + data: ElicitSchemaModelT |
| 22 | + |
| 23 | + |
| 24 | +class DeclinedElicitation(BaseModel): |
| 25 | + """Result when user declines the elicitation.""" |
| 26 | + |
| 27 | + action: Literal["decline"] = "decline" |
| 28 | + |
| 29 | + |
| 30 | +class CancelledElicitation(BaseModel): |
| 31 | + """Result when user cancels the elicitation.""" |
| 32 | + |
| 33 | + action: Literal["cancel"] = "cancel" |
| 34 | + |
| 35 | + |
| 36 | +ElicitationResult = AcceptedElicitation[ElicitSchemaModelT] | DeclinedElicitation | CancelledElicitation |
| 37 | + |
| 38 | + |
| 39 | +# Primitive types allowed in elicitation schemas |
| 40 | +_ELICITATION_PRIMITIVE_TYPES = (str, int, float, bool) |
| 41 | + |
| 42 | + |
| 43 | +def _validate_elicitation_schema(schema: type[BaseModel]) -> None: |
| 44 | + """Validate that a Pydantic model only contains primitive field types.""" |
| 45 | + for field_name, field_info in schema.model_fields.items(): |
| 46 | + if not _is_primitive_field(field_info): |
| 47 | + raise TypeError( |
| 48 | + f"Elicitation schema field '{field_name}' must be a primitive type " |
| 49 | + f"{_ELICITATION_PRIMITIVE_TYPES} or Optional of these types. " |
| 50 | + f"Complex types like lists, dicts, or nested models are not allowed." |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +def _is_primitive_field(field_info: FieldInfo) -> bool: |
| 55 | + """Check if a field is a primitive type allowed in elicitation schemas.""" |
| 56 | + annotation = field_info.annotation |
| 57 | + |
| 58 | + # Handle None type |
| 59 | + if annotation is types.NoneType: |
| 60 | + return True |
| 61 | + |
| 62 | + # Handle basic primitive types |
| 63 | + if annotation in _ELICITATION_PRIMITIVE_TYPES: |
| 64 | + return True |
| 65 | + |
| 66 | + # Handle Union types |
| 67 | + origin = get_origin(annotation) |
| 68 | + if origin is Union or origin is types.UnionType: |
| 69 | + args = get_args(annotation) |
| 70 | + # All args must be primitive types or None |
| 71 | + return all(arg is types.NoneType or arg in _ELICITATION_PRIMITIVE_TYPES for arg in args) |
| 72 | + |
| 73 | + return False |
| 74 | + |
| 75 | + |
| 76 | +async def elicit_with_validation( |
| 77 | + session: ServerSession, |
| 78 | + message: str, |
| 79 | + schema: type[ElicitSchemaModelT], |
| 80 | + related_request_id: RequestId | None = None, |
| 81 | +) -> ElicitationResult[ElicitSchemaModelT]: |
| 82 | + """Elicit information from the client/user with schema validation. |
| 83 | +
|
| 84 | + This method can be used to interactively ask for additional information from the |
| 85 | + client within a tool's execution. The client might display the message to the |
| 86 | + user and collect a response according to the provided schema. Or in case a |
| 87 | + client is an agent, it might decide how to handle the elicitation -- either by asking |
| 88 | + the user or automatically generating a response. |
| 89 | + """ |
| 90 | + # Validate that schema only contains primitive types and fail loudly if not |
| 91 | + _validate_elicitation_schema(schema) |
| 92 | + |
| 93 | + json_schema = schema.model_json_schema() |
| 94 | + |
| 95 | + result = await session.elicit( |
| 96 | + message=message, |
| 97 | + requestedSchema=json_schema, |
| 98 | + related_request_id=related_request_id, |
| 99 | + ) |
| 100 | + |
| 101 | + if result.action == "accept" and result.content: |
| 102 | + # Validate and parse the content using the schema |
| 103 | + validated_data = schema.model_validate(result.content) |
| 104 | + return AcceptedElicitation(data=validated_data) |
| 105 | + elif result.action == "decline": |
| 106 | + return DeclinedElicitation() |
| 107 | + elif result.action == "cancel": |
| 108 | + return CancelledElicitation() |
| 109 | + else: |
| 110 | + # This should never happen, but handle it just in case |
| 111 | + raise ValueError(f"Unexpected elicitation action: {result.action}") |
0 commit comments