|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any, Dict, List, Type, Union, get_args, get_origin |
| 4 | + |
| 5 | +from pydantic import BaseModel, Field, create_model, field_validator |
| 6 | + |
| 7 | + |
| 8 | +class ArgsBaseModel(BaseModel): |
| 9 | + """Base class for tool argument models with strict object schema.""" |
| 10 | + |
| 11 | + model_config = { |
| 12 | + "extra": "forbid", |
| 13 | + "json_schema_extra": {"additionalProperties": False}, |
| 14 | + } |
| 15 | + |
| 16 | + |
| 17 | +_MODEL_CACHE: Dict[type[BaseModel], type[BaseModel]] = {} |
| 18 | + |
| 19 | + |
| 20 | +def _convert_annotation( |
| 21 | + annotation: Any, |
| 22 | + field_name: str, |
| 23 | + validators: Dict[str, classmethod], |
| 24 | +) -> Any: |
| 25 | + origin = get_origin(annotation) |
| 26 | + if origin is None: |
| 27 | + if isinstance(annotation, type) and issubclass(annotation, BaseModel): |
| 28 | + return get_args_model(annotation) |
| 29 | + if annotation is int: |
| 30 | + # Replace ints with floats and create validator to coerce to int |
| 31 | + @field_validator(field_name, mode="before") |
| 32 | + def _coerce(cls, v): |
| 33 | + return None if v is None else int(v) |
| 34 | + |
| 35 | + validators[f"coerce_{field_name}"] = _coerce |
| 36 | + return float |
| 37 | + return annotation |
| 38 | + if origin in (list, List): |
| 39 | + inner = _convert_annotation(get_args(annotation)[0], field_name, validators) |
| 40 | + return List[inner] |
| 41 | + if origin is Union: |
| 42 | + converted = [ |
| 43 | + _convert_annotation(arg, field_name, validators) for arg in get_args(annotation) |
| 44 | + ] |
| 45 | + return Union[tuple(converted)] |
| 46 | + return annotation |
| 47 | + |
| 48 | + |
| 49 | +def get_args_model(model_cls: Type[BaseModel]) -> Type[BaseModel]: |
| 50 | + """Create an Args model for the given request model.""" |
| 51 | + if model_cls in _MODEL_CACHE: |
| 52 | + return _MODEL_CACHE[model_cls] |
| 53 | + |
| 54 | + fields: Dict[str, tuple[Any, Any]] = {} |
| 55 | + validators: Dict[str, classmethod] = {} |
| 56 | + |
| 57 | + for name, field in model_cls.model_fields.items(): |
| 58 | + ann = _convert_annotation(field.annotation, name, validators) |
| 59 | + default = field.default if not field.is_required() else ... |
| 60 | + ge = le = None |
| 61 | + for meta in getattr(field, "metadata", []): |
| 62 | + if hasattr(meta, "ge"): |
| 63 | + ge = meta.ge |
| 64 | + if hasattr(meta, "le"): |
| 65 | + le = meta.le |
| 66 | + fields[name] = ( |
| 67 | + ann, |
| 68 | + Field( |
| 69 | + default, |
| 70 | + description=getattr(field, "description", None), |
| 71 | + ge=ge, |
| 72 | + le=le, |
| 73 | + ), |
| 74 | + ) |
| 75 | + |
| 76 | + ArgsModel = create_model( |
| 77 | + f"{model_cls.__name__}Args", |
| 78 | + __base__=ArgsBaseModel, |
| 79 | + __validators__=validators, |
| 80 | + **fields, |
| 81 | + ) |
| 82 | + |
| 83 | + _MODEL_CACHE[model_cls] = ArgsModel |
| 84 | + return ArgsModel |
| 85 | + |
| 86 | + |
| 87 | +from typing import Callable |
| 88 | + |
| 89 | + |
| 90 | +def tool_with_args( |
| 91 | + mcp, |
| 92 | + request_model: Type[BaseModel] | None = None, |
| 93 | + **decorator_kwargs: Any, |
| 94 | +) -> Callable: |
| 95 | + """Decorator to wrap MCP tools with generated Args models.""" |
| 96 | + |
| 97 | + def decorator(func: Callable) -> Callable: |
| 98 | + if request_model is None: |
| 99 | + ArgsModel = ArgsBaseModel |
| 100 | + |
| 101 | + async def inner(args: ArgsModel): |
| 102 | + return await func() |
| 103 | + else: |
| 104 | + ArgsModel = get_args_model(request_model) |
| 105 | + |
| 106 | + async def inner(args: ArgsModel): |
| 107 | + model = request_model(**args.model_dump()) |
| 108 | + return await func(model) |
| 109 | + |
| 110 | + inner.__name__ = func.__name__ |
| 111 | + inner.__doc__ = func.__doc__ |
| 112 | + inner.__annotations__ = { |
| 113 | + "args": ArgsModel, |
| 114 | + "return": func.__annotations__.get("return", Any), |
| 115 | + } |
| 116 | + return mcp.tool(**decorator_kwargs)(inner) |
| 117 | + |
| 118 | + return decorator |
0 commit comments