"""Tool registration helpers. One shape, one place -------------------- Every tool in this project returns a JSON string, and that is a decision rather than a default: :func:`mcp_tool` registers with ``structured_output=False`` so a result travels as a text block and nothing else. The alternative — letting the SDK infer a structured output schema from the ``-> str`` annotation — publishes a ``{"result": "..."}`` envelope and sends the same JSON twice, once as ``structuredContent`` and once as text. Half the clients read only one of the two, and the other half reads both and pays for the duplication twice. So a tool is registered by:: @mcp_tool(server, title="列出论文") def paper_list(...) -> str: \"\"\"Short description — this text is what the model reads.\"\"\" The docstring becomes the tool description verbatim, which makes it the most expensive string in the project: it is sent with every request. Keep it to the one or two lines a model needs to choose the tool, and put the reasoning in the module docstring instead, where it costs nothing per request. """ from __future__ import annotations from functools import wraps from collections.abc import Callable from typing import Any, TypeVar from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError from app.core.storage import StorageUnavailable, UnsupportedImage from app.crud.reference import UnknownReference from app.crud.reference_tag import DuplicateTagName, UnknownTag F = TypeVar("F", bound=Callable[..., Any]) #: Refusals the data layer raises on purpose. Each one already carries a #: message written for a reader; the only thing missing is the translation into #: the transport's own error type, which is the whole job of the wrapper below. #: #: A tuple rather than a single class because there is one of these per rule, #: and the tag rules arrived with the tag tools: catching only the reference one #: would have let 「标签不存在:9」 reach the model as an unreadable #: "Error executing tool ...", which is the exact failure this wrapper exists to #: prevent. A new domain refusal belongs in this tuple on the day it is written. #: #: The two storage ones are here for the same reason. A bucket that is not #: configured and a file that is not a picture are both answers rather than #: faults — "缺少 MINIO_ENDPOINT" and "只接受 PNG / JPEG / GIF / WebP" are the #: two things a caller can act on, and neither survives the wrapper as a stack #: trace. DOMAIN_REFUSALS = ( UnknownReference, UnknownTag, DuplicateTagName, StorageUnavailable, UnsupportedImage, ) def mcp_tool( server: MCPServer, *, name: str | None = None, title: str | None = None, ) -> Callable[[F], F]: """Register one tool as unstructured text output.""" def decorator(fn: F) -> F: @wraps(fn) def wrapper(*args: Any, **kwargs: Any) -> Any: # A refusal from the data layer becomes a message the model can read # and retry against. Left unhandled it would reach the client as # "Error executing tool ...", which says nothing about what to fix. try: return fn(*args, **kwargs) except DOMAIN_REFUSALS as error: raise ToolError(str(error)) from error server.add_tool( wrapper, name=name or fn.__name__, title=title, structured_output=False, ) return wrapper # type: ignore[return-value] return decorator __all__ = ["DOMAIN_REFUSALS", "mcp_tool"]