198 lines
7.9 KiB
Python
198 lines
7.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""甄养堂患者订单只读 MCP 服务。
|
||
|
||
该服务只接受由桌面端 MCP 桥接在进程环境中注入的当前会话上下文,工具参数
|
||
不包含 tenant、患者或企微会话标识。所有归属校验都在桌面后台代理完成。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import socket
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
from typing import Any
|
||
|
||
try:
|
||
from mcp.server.fastmcp import FastMCP
|
||
except (ImportError, ModuleNotFoundError):
|
||
# MCP SDK 2.x renamed FastMCP to MCPServer; both expose the tool/run
|
||
# surface used by this stdio-only service.
|
||
from mcp.server.mcpserver import MCPServer as FastMCP
|
||
|
||
|
||
mcp = FastMCP(
|
||
"zyt-order-mcp",
|
||
instructions=(
|
||
"ZYT 患者订单只读查询服务。只能查询当前企微会话绑定患者的订单;"
|
||
"不要猜测、补全或编造订单号和物流状态。实际审核、发货、退款等操作不在此服务中。"
|
||
),
|
||
)
|
||
|
||
|
||
def _context() -> dict[str, str]:
|
||
try:
|
||
value = json.loads(os.environ.get("WECOM_RPA_ORDER_CONTEXT", "{}"))
|
||
except (TypeError, ValueError):
|
||
value = {}
|
||
if not isinstance(value, dict):
|
||
value = {}
|
||
return {
|
||
"external_account_id": str(value.get("external_account_id") or "").strip(),
|
||
"conversation_external_id": str(value.get("conversation_external_id") or "").strip(),
|
||
"person_id": str(value.get("person_id") or "").strip(),
|
||
}
|
||
|
||
|
||
def _base_url() -> str:
|
||
return str(os.environ.get("WECOM_RPA_ORDER_BACKEND_URL") or "").strip().rstrip("/")
|
||
|
||
|
||
def _get(path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
context = _context()
|
||
if not _base_url() or not context["external_account_id"] or not context["conversation_external_id"]:
|
||
return {"ok": False, "code": "patient_context_missing", "message": "当前会话未提供有效患者上下文"}
|
||
query = dict(params or {})
|
||
query.update(context)
|
||
query = {key: value for key, value in query.items() if value not in (None, "")}
|
||
url = f"{_base_url()}{path}"
|
||
encoded = urllib.parse.urlencode(query)
|
||
if encoded:
|
||
url += "?" + encoded
|
||
token = str(os.environ.get("WECOM_RPA_ORDER_DESKTOP_TOKEN") or "").strip()
|
||
if not token:
|
||
return {"ok": False, "code": "desktop_session_missing", "message": "桌面会话已失效,请重新登录"}
|
||
request = urllib.request.Request(
|
||
url,
|
||
headers={"Accept": "application/json", "Authorization": f"Bearer {token}"},
|
||
method="GET",
|
||
)
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=15) as response:
|
||
data = json.loads(response.read().decode("utf-8"))
|
||
except urllib.error.HTTPError as exc:
|
||
try:
|
||
data = json.loads(exc.read().decode("utf-8"))
|
||
except Exception:
|
||
data = {}
|
||
detail = data.get("detail") if isinstance(data, dict) else ""
|
||
detail_code = detail.get("code") if isinstance(detail, dict) else ""
|
||
if isinstance(detail, dict):
|
||
detail = detail.get("message") or detail.get("msg") or ""
|
||
return {
|
||
"ok": False,
|
||
"code": str(detail_code or (data.get("code") if isinstance(data, dict) else "") or f"http_{exc.code}"),
|
||
"message": str(data.get("message") if isinstance(data, dict) else "") or str(detail) or f"订单查询失败(HTTP {exc.code})",
|
||
}
|
||
except (urllib.error.URLError, TimeoutError, socket.timeout, ValueError, TypeError, UnicodeDecodeError) as exc:
|
||
return {"ok": False, "code": "order_backend_unavailable", "message": f"订单后台暂时不可用:{exc}"}
|
||
return data if isinstance(data, dict) else {"ok": False, "code": "invalid_response", "message": "订单后台返回了无效数据"}
|
||
|
||
|
||
def _redact_order_result(data: dict[str, Any]) -> dict[str, Any]:
|
||
"""Remove binding/diagnosis identifiers and any fields the model cannot use."""
|
||
result = dict(data or {})
|
||
result.pop("patient", None)
|
||
result.pop("binding_id", None)
|
||
if isinstance(result.get("order"), dict):
|
||
result["order"] = dict(result["order"])
|
||
result["order"].pop("diagnosis_id", None)
|
||
if isinstance(result.get("items"), list):
|
||
items = []
|
||
for item in result["items"]:
|
||
if isinstance(item, dict):
|
||
safe = dict(item)
|
||
safe.pop("diagnosis_id", None)
|
||
items.append(safe)
|
||
result["items"] = items
|
||
return result
|
||
|
||
|
||
@mcp.tool()
|
||
def get_bound_patient_context() -> dict[str, Any]:
|
||
"""读取当前企微会话是否已有有效患者绑定,不返回患者身份详情。"""
|
||
data = _get("/api/v2/archive/desktop/patient-context")
|
||
if not data.get("ok", True):
|
||
return data
|
||
person = data.get("person") if isinstance(data.get("person"), dict) else {}
|
||
bindings = person.get("patient_bindings") if isinstance(person, dict) else []
|
||
return {
|
||
"ok": True,
|
||
"available": bool(data.get("available")),
|
||
"bound": bool(bindings),
|
||
"binding_count": len(bindings) if isinstance(bindings, list) else 0,
|
||
"requires_person_selection": bool(data.get("requires_person_selection")),
|
||
}
|
||
|
||
|
||
@mcp.tool()
|
||
def query_bound_patient_orders(
|
||
keyword: str = "",
|
||
start_date: str = "",
|
||
end_date: str = "",
|
||
page_no: int = 1,
|
||
page_size: int = 20,
|
||
) -> dict[str, Any]:
|
||
"""查询当前绑定患者的最近订单;keyword 只能是客户提供的订单号或查询关键词。
|
||
|
||
返回 order_count / selection_required / single_order_id / hint:
|
||
selection_required=true 时只能列出各笔的时间和状态让客户确认,不要自行选一笔;
|
||
只有一笔订单时会直接附带 latest_tracking(或 tracking_error 说明为什么查不到)。
|
||
"""
|
||
return _redact_order_result(_get(
|
||
"/api/v2/archive/desktop/patient-orders",
|
||
{
|
||
"keyword": str(keyword or "").strip()[:80],
|
||
"start_date": str(start_date or "").strip()[:20],
|
||
"end_date": str(end_date or "").strip()[:20],
|
||
"page_no": max(1, int(page_no)),
|
||
"page_size": max(1, min(int(page_size), 20)),
|
||
},
|
||
))
|
||
|
||
|
||
@mcp.tool()
|
||
def get_order_detail(order_id: int) -> dict[str, Any]:
|
||
"""读取当前绑定患者指定订单的脱敏详情。"""
|
||
try:
|
||
value = int(order_id)
|
||
except (TypeError, ValueError):
|
||
return {"ok": False, "code": "invalid_order_id", "message": "订单编号不正确"}
|
||
if value <= 0:
|
||
return {"ok": False, "code": "invalid_order_id", "message": "订单编号不正确"}
|
||
return _redact_order_result(_get(f"/api/v2/archive/desktop/patient-orders/{value}"))
|
||
|
||
|
||
@mcp.tool()
|
||
def get_order_tracking(order_id: int) -> dict[str, Any]:
|
||
"""读取当前绑定患者指定订单的脱敏物流状态和轨迹。
|
||
|
||
ok=false 且 code 为 tracking_number_missing / tracking_unavailable 时表示没有真实
|
||
物流结果,只能告诉客户正在核实,不能补一个状态。
|
||
"""
|
||
try:
|
||
value = int(order_id)
|
||
except (TypeError, ValueError):
|
||
return {"ok": False, "code": "invalid_order_id", "message": "订单编号不正确"}
|
||
if value <= 0:
|
||
return {"ok": False, "code": "invalid_order_id", "message": "订单编号不正确"}
|
||
return _redact_order_result(_get(f"/api/v2/archive/desktop/patient-orders/{value}/tracking"))
|
||
|
||
|
||
@mcp.tool()
|
||
def get_order_audit_status(order_id: int) -> dict[str, Any]:
|
||
"""读取当前绑定患者指定订单的处方审核、支付审核和履约状态。"""
|
||
try:
|
||
value = int(order_id)
|
||
except (TypeError, ValueError):
|
||
return {"ok": False, "code": "invalid_order_id", "message": "订单编号不正确"}
|
||
if value <= 0:
|
||
return {"ok": False, "code": "invalid_order_id", "message": "订单编号不正确"}
|
||
return _redact_order_result(_get(f"/api/v2/archive/desktop/patient-orders/{value}/audit-status"))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
mcp.run(transport="stdio")
|