"""MCP Python SDK 2.1.1 教学 Server：工具、资源、提示；没有真实订单或付款。
只面向本地单用户演示。真实远程服务必须接入认证，不能共享下面的固定主体。
"""
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
from tool_contracts import DEMO_USER, ToolFailure, dispatch

mcp = MCPServer(name="shop-support")


def call_business(name: str, order_id: str) -> dict:
    try:
        # 主体不出现在模型参数中；本例绑定固定教学用户。
        return dispatch(name, {"order_id": order_id}, DEMO_USER)
    except ToolFailure as error:
        # 已知业务错误转成 SDK 工具错误，保留 is_error 语义。
        raise ToolError(str(error)) from None


@mcp.tool(description="读取获准教学订单的签收天数及质量核实状态，不修改数据。",
          annotations=ToolAnnotations(read_only_hint=True, idempotent_hint=True))
def get_order(order_id: str) -> dict:
    """按订单号查询；格式与归属由业务函数校验。"""
    return call_business("get_order", order_id)


@mcp.tool(description="读取获准订单适用的教学政策，不审批或提交退款。",
          annotations=ToolAnnotations(read_only_hint=True, idempotent_hint=True))
def get_refund_policy(order_id: str) -> dict:
    """查询当前例子适用的政策，实际应用需按时间和商品范围选择。"""
    return call_business("get_refund_policy", order_id)


@mcp.resource("policy://refund")
def refund_policy() -> str:
    """固定教学资源；URI 定位内容，不是访问授权。"""
    return "P7-v2：签收三十天内，经核实的质量问题退货，由商家承担运费。"


@mcp.prompt()
def explain_refund(order_id: str) -> str:
    """生成解释模板，不查询订单、不产生批准或执行动作。"""
    from tool_contracts import validate_order_args
    validate_order_args({"order_id": order_id})
    return f"请查询获准订单 {order_id} 与适用政策，区分已核实事实和缺失条件，只解释不提交。"


if __name__ == "__main__":
    # stdout 专供协议帧使用；不要在业务函数中 print 调试内容。
    mcp.run(transport="stdio")
