|
| 1 | +from collections.abc import Callable |
| 2 | +from dataclasses import dataclass |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +import mcp.types |
| 6 | +import nexusrpc |
| 7 | +import pydantic |
| 8 | + |
| 9 | +from .service import MCPService |
| 10 | + |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class Tool: |
| 14 | + func: Callable[..., Any] |
| 15 | + defn: nexusrpc.Operation[Any, Any] |
| 16 | + |
| 17 | + def to_mcp_tool(self, service: nexusrpc.ServiceDefinition) -> mcp.types.Tool: |
| 18 | + return mcp.types.Tool( |
| 19 | + name=f"{service.name}.{self.defn.name}", |
| 20 | + description=(self.func.__doc__.strip() if self.func.__doc__ is not None else None), |
| 21 | + inputSchema=( |
| 22 | + self.defn.input_type.model_json_schema() |
| 23 | + if self.defn.input_type is not None and issubclass(self.defn.input_type, pydantic.BaseModel) |
| 24 | + else {} |
| 25 | + ), |
| 26 | + ) |
| 27 | + |
| 28 | + |
| 29 | +@dataclass |
| 30 | +class ToolService: |
| 31 | + defn: nexusrpc.ServiceDefinition |
| 32 | + tools: list[Tool] |
| 33 | + |
| 34 | + |
| 35 | +@nexusrpc.handler.service_handler(service=MCPService) |
| 36 | +class MCPServiceHandler: |
| 37 | + tool_services: list[ToolService] |
| 38 | + |
| 39 | + def __init__(self) -> None: |
| 40 | + self.tool_services = [] |
| 41 | + |
| 42 | + def tool_service(self, cls: type) -> type: |
| 43 | + service_defn = nexusrpc.get_service_definition(cls) |
| 44 | + if service_defn is None: |
| 45 | + raise ValueError(f"Class {cls.__name__} is not a Nexus Service") |
| 46 | + |
| 47 | + tools: list[Tool] = [] |
| 48 | + for op in service_defn.operations.values(): |
| 49 | + attr_name = op.method_name or op.name |
| 50 | + attr = getattr(cls, attr_name) |
| 51 | + if not callable(attr): |
| 52 | + raise ValueError(f"Attribute {attr_name} is not callable") |
| 53 | + if not getattr(attr, "__nexus_mcp_tool__", True): |
| 54 | + continue |
| 55 | + tools.append(Tool(attr, op)) |
| 56 | + |
| 57 | + self.tool_services.append(ToolService(tools=tools, defn=service_defn)) |
| 58 | + return cls |
| 59 | + |
| 60 | + @nexusrpc.handler.sync_operation |
| 61 | + async def list_tools(self, _ctx: nexusrpc.handler.StartOperationContext, _input: None) -> list[mcp.types.Tool]: |
| 62 | + return [tool.to_mcp_tool(service.defn) for service in self.tool_services for tool in service.tools] |
| 63 | + |
| 64 | + |
| 65 | +ExcludedCallable = Callable[..., Any] |
| 66 | + |
| 67 | + |
| 68 | +def exclude(fn: ExcludedCallable) -> ExcludedCallable: |
| 69 | + """ |
| 70 | + Decorate a function to exclude it from the MCP inventory. |
| 71 | + """ |
| 72 | + setattr(fn, "__nexus_mcp_tool__", False) |
| 73 | + return fn |
0 commit comments