|
| 1 | +"""MCP tools backed by ``@mcp_enabled``-decorated functions.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import inspect |
| 6 | +import json |
| 7 | +import typing |
| 8 | +from typing import Any, Callable |
| 9 | + |
| 10 | +from mcp.types import CallToolResult, TextContent, Tool |
| 11 | + |
| 12 | +from dash import get_app |
| 13 | +from dash.mcp._decorator import MCPToolRegistration |
| 14 | +from dash.mcp.primitives.tools.input_schemas import get_input_schema |
| 15 | +from dash.mcp.primitives.tools.input_schemas.schema_callback_type_annotations import ( |
| 16 | + annotation_to_json_schema, |
| 17 | +) |
| 18 | +from dash.mcp.types import MCPInput, is_nullable |
| 19 | + |
| 20 | +from .base import MCPToolProvider |
| 21 | + |
| 22 | + |
| 23 | +def _build_inputs(fn: Callable[..., Any]) -> list[MCPInput]: |
| 24 | + """Build an ``MCPInput`` from each of the function's arguments.""" |
| 25 | + try: |
| 26 | + hints = typing.get_type_hints(fn) |
| 27 | + except Exception: # pylint: disable=broad-exception-caught |
| 28 | + hints = getattr(fn, "__annotations__", {}) |
| 29 | + |
| 30 | + sig = inspect.signature(fn) |
| 31 | + inputs: list[MCPInput] = [] |
| 32 | + |
| 33 | + for name, param in sig.parameters.items(): |
| 34 | + annotation = hints.get(name) |
| 35 | + |
| 36 | + has_default = param.default is not inspect.Parameter.empty |
| 37 | + required = not has_default and ( |
| 38 | + annotation is None or not is_nullable(annotation) |
| 39 | + ) |
| 40 | + |
| 41 | + inputs.append( |
| 42 | + MCPInput( |
| 43 | + name=name, |
| 44 | + id_and_prop="", |
| 45 | + component_id="", |
| 46 | + property="", |
| 47 | + annotation=annotation, |
| 48 | + component_type=None, |
| 49 | + component=None, |
| 50 | + required=required, |
| 51 | + initial_value=param.default if has_default else None, |
| 52 | + upstream_output=None, |
| 53 | + ) |
| 54 | + ) |
| 55 | + return inputs |
| 56 | + |
| 57 | + |
| 58 | +def _build_output_schema(fn: Callable[..., Any]) -> dict[str, Any]: |
| 59 | + """Build a JSON Schema ``outputSchema`` from the return annotation. |
| 60 | +
|
| 61 | + The schema wraps the return type in ``{"result": <type>}`` to match |
| 62 | + the object that ``call_tool`` returns as ``structuredContent``. |
| 63 | + """ |
| 64 | + try: |
| 65 | + hints = typing.get_type_hints(fn) |
| 66 | + except Exception: # pylint: disable=broad-exception-caught |
| 67 | + hints = getattr(fn, "__annotations__", {}) |
| 68 | + |
| 69 | + ret = hints.get("return") |
| 70 | + if ret is None: |
| 71 | + return {} |
| 72 | + |
| 73 | + inner = annotation_to_json_schema(ret) |
| 74 | + if inner is None: |
| 75 | + return {} |
| 76 | + |
| 77 | + return { |
| 78 | + "type": "object", |
| 79 | + "properties": {"result": inner}, |
| 80 | + "required": ["result"], |
| 81 | + } |
| 82 | + |
| 83 | + |
| 84 | +def _build_tool(tool_name: str, reg: MCPToolRegistration) -> Tool: |
| 85 | + fn = reg["fn"] |
| 86 | + inputs = _build_inputs(fn) |
| 87 | + properties = {p["name"]: get_input_schema(p) for p in inputs} |
| 88 | + required = [p["name"] for p in inputs if p["required"]] |
| 89 | + |
| 90 | + input_schema: dict[str, Any] = {"type": "object", "properties": properties} |
| 91 | + if required: |
| 92 | + input_schema["required"] = required |
| 93 | + |
| 94 | + expose_docstring = reg["expose_docstring"] |
| 95 | + if expose_docstring is None: |
| 96 | + expose_docstring = get_app().config.get("mcp_expose_docstrings", False) |
| 97 | + |
| 98 | + description = "MCP tool" |
| 99 | + if expose_docstring: |
| 100 | + docstring = getattr(fn, "__doc__", None) |
| 101 | + if docstring: |
| 102 | + description = docstring.strip() |
| 103 | + |
| 104 | + return Tool( |
| 105 | + name=tool_name, |
| 106 | + description=description, |
| 107 | + inputSchema=input_schema, |
| 108 | + outputSchema=_build_output_schema(fn), |
| 109 | + ) |
| 110 | + |
| 111 | + |
| 112 | +class DecoratedFunctionTools(MCPToolProvider): |
| 113 | + """Exposes ``@mcp_enabled``-decorated functions as MCP tools.""" |
| 114 | + |
| 115 | + @classmethod |
| 116 | + def _registry(cls) -> dict[str, MCPToolRegistration]: |
| 117 | + return get_app().mcp_decorated_functions |
| 118 | + |
| 119 | + @classmethod |
| 120 | + def get_tool_names(cls) -> set[str]: |
| 121 | + return set(cls._registry().keys()) |
| 122 | + |
| 123 | + @classmethod |
| 124 | + def list_tools(cls) -> list[Tool]: |
| 125 | + return [_build_tool(name, reg) for name, reg in cls._registry().items()] |
| 126 | + |
| 127 | + @classmethod |
| 128 | + def call_tool(cls, tool_name: str, arguments: dict[str, Any]) -> CallToolResult: |
| 129 | + reg = cls._registry().get(tool_name) |
| 130 | + if reg is None: |
| 131 | + return CallToolResult( |
| 132 | + content=[TextContent(type="text", text=f"Tool not found: {tool_name}")], |
| 133 | + isError=True, |
| 134 | + ) |
| 135 | + fn = reg["fn"] |
| 136 | + try: |
| 137 | + result = fn(**arguments) |
| 138 | + except Exception as exc: # pylint: disable=broad-exception-caught |
| 139 | + return CallToolResult( |
| 140 | + content=[TextContent(type="text", text=f"{type(exc).__name__}: {exc}")], |
| 141 | + isError=True, |
| 142 | + ) |
| 143 | + |
| 144 | + serialized = json.dumps(result, default=str) |
| 145 | + return CallToolResult( |
| 146 | + content=[TextContent(type="text", text=serialized)], |
| 147 | + structuredContent={"result": result}, |
| 148 | + ) |
0 commit comments