fufu-report-rules 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. fufu_report_rules-1.0.0/PKG-INFO +55 -0
  2. fufu_report_rules-1.0.0/README.md +45 -0
  3. fufu_report_rules-1.0.0/pyproject.toml +22 -0
  4. fufu_report_rules-1.0.0/setup.cfg +4 -0
  5. fufu_report_rules-1.0.0/src/fufu_report_rules/__init__.py +2 -0
  6. fufu_report_rules-1.0.0/src/fufu_report_rules/judge.py +54 -0
  7. fufu_report_rules-1.0.0/src/fufu_report_rules/server.py +160 -0
  8. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/MANIFEST.json +39 -0
  9. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/core/__init__.py +7 -0
  10. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/core/data_guard.py +1233 -0
  11. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/core/medical_grader.py +1080 -0
  12. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/core/population_profile.py +252 -0
  13. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/core/reference_thresholds.csv +287 -0
  14. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/core/reference_thresholds_elderly.csv +53 -0
  15. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/core/reference_thresholds_pregnancy.csv +41 -0
  16. fufu_report_rules-1.0.0/src/fufu_report_rules/vendor/core/threshold_judge.py +2500 -0
  17. fufu_report_rules-1.0.0/src/fufu_report_rules.egg-info/PKG-INFO +55 -0
  18. fufu_report_rules-1.0.0/src/fufu_report_rules.egg-info/SOURCES.txt +20 -0
  19. fufu_report_rules-1.0.0/src/fufu_report_rules.egg-info/dependency_links.txt +1 -0
  20. fufu_report_rules-1.0.0/src/fufu_report_rules.egg-info/entry_points.txt +2 -0
  21. fufu_report_rules-1.0.0/src/fufu_report_rules.egg-info/requires.txt +1 -0
  22. fufu_report_rules-1.0.0/src/fufu_report_rules.egg-info/top_level.txt +1 -0
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: fufu-report-rules
3
+ Version: 1.0.0
4
+ Summary: Read-only MCP connector: threshold lookup and abnormal-flag judgment for health-check indicators (runs locally, no patient data leaves your machine)
5
+ Author: 南京扶扶网络科技有限公司
6
+ License-Expression: LicenseRef-Proprietary
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: mcp<2,>=1.2.0
10
+
11
+ # fufu-report-rules
12
+
13
+ 体检指标参考区间与阈值判定的**只读 MCP 连接器**(WorkBuddy 连接器市场)。
14
+
15
+ - 需求:`docs/01-需求/20261124-REQ-只读MCP连接器立项-v1.0.md`
16
+ - 验证报告:`docs/03-测试/连接器上架前置验证报告_20261124.md`
17
+
18
+ ## 结构
19
+
20
+ ```
21
+ mcp_rule_lookup/
22
+ ├── connector-meta.json # 连接器元信息(source: fufu-report-rules)
23
+ ├── mcp.json # stdio,uvx 拉起
24
+ ├── icon.svg / README.md
25
+ ├── skills/rule-lookup/SKILL.md
26
+ ├── tools/export_snapshot.py # 快照导出(唯一真源=模块 core/)
27
+ └── src/fufu_report_rules/
28
+ ├── server.py # FastMCP stdio:lookup_indicator / get_threshold / judge_indicator
29
+ ├── judge.py # shim:vendor 装载 + 预置 _DB_ROWS(REQ 硬约束)
30
+ └── vendor/core/ # 模块 core 判定子树字节级快照 + MANIFEST.json(SHA256)
31
+ ```
32
+
33
+ ## 快照纪律
34
+
35
+ - **模块 core 是唯一真源**:改了 `core/threshold_judge.py` 或阈值 CSV 后必须重跑
36
+ `py -3 mcp_rule_lookup/tools/export_snapshot.py`,然后 `--check` 校验。
37
+ - `vendor/core/__init__.py` 是生成态最小 glue(唯一例外于字节一致断言)。
38
+ - `vendor/core/MANIFEST.json` 记录每文件 SHA256;`tests/test_connector_shim.py` 会断言
39
+ 快照与模块 core 一致,漂移即报警。
40
+
41
+ ## 本地试跑
42
+
43
+ ```bash
44
+ cd mcp_rule_lookup
45
+ py -3 -m pip install -e .
46
+ py -3 -m fufu_report_rules.server # stdio 起服务(或命令 fufu-report-rules)
47
+ ```
48
+
49
+ ## 已知边界
50
+
51
+ - vendor 快照**不含** `core/ports/**`:`data_guard` 的脏数据回写路径(连接器工具不触达)
52
+ 如被误调用会 ImportError,工具层包装为明确报错。
53
+ - 判定入口依赖 `judge.py` 预置 `tj._DB_ROWS=[]`——这是与 core 内部命名的受控耦合,
54
+ 行为测试锁定,勿删。
55
+ - v1 不支持儿童/青少年人群。
@@ -0,0 +1,45 @@
1
+ # fufu-report-rules
2
+
3
+ 体检指标参考区间与阈值判定的**只读 MCP 连接器**(WorkBuddy 连接器市场)。
4
+
5
+ - 需求:`docs/01-需求/20261124-REQ-只读MCP连接器立项-v1.0.md`
6
+ - 验证报告:`docs/03-测试/连接器上架前置验证报告_20261124.md`
7
+
8
+ ## 结构
9
+
10
+ ```
11
+ mcp_rule_lookup/
12
+ ├── connector-meta.json # 连接器元信息(source: fufu-report-rules)
13
+ ├── mcp.json # stdio,uvx 拉起
14
+ ├── icon.svg / README.md
15
+ ├── skills/rule-lookup/SKILL.md
16
+ ├── tools/export_snapshot.py # 快照导出(唯一真源=模块 core/)
17
+ └── src/fufu_report_rules/
18
+ ├── server.py # FastMCP stdio:lookup_indicator / get_threshold / judge_indicator
19
+ ├── judge.py # shim:vendor 装载 + 预置 _DB_ROWS(REQ 硬约束)
20
+ └── vendor/core/ # 模块 core 判定子树字节级快照 + MANIFEST.json(SHA256)
21
+ ```
22
+
23
+ ## 快照纪律
24
+
25
+ - **模块 core 是唯一真源**:改了 `core/threshold_judge.py` 或阈值 CSV 后必须重跑
26
+ `py -3 mcp_rule_lookup/tools/export_snapshot.py`,然后 `--check` 校验。
27
+ - `vendor/core/__init__.py` 是生成态最小 glue(唯一例外于字节一致断言)。
28
+ - `vendor/core/MANIFEST.json` 记录每文件 SHA256;`tests/test_connector_shim.py` 会断言
29
+ 快照与模块 core 一致,漂移即报警。
30
+
31
+ ## 本地试跑
32
+
33
+ ```bash
34
+ cd mcp_rule_lookup
35
+ py -3 -m pip install -e .
36
+ py -3 -m fufu_report_rules.server # stdio 起服务(或命令 fufu-report-rules)
37
+ ```
38
+
39
+ ## 已知边界
40
+
41
+ - vendor 快照**不含** `core/ports/**`:`data_guard` 的脏数据回写路径(连接器工具不触达)
42
+ 如被误调用会 ImportError,工具层包装为明确报错。
43
+ - 判定入口依赖 `judge.py` 预置 `tj._DB_ROWS=[]`——这是与 core 内部命名的受控耦合,
44
+ 行为测试锁定,勿删。
45
+ - v1 不支持儿童/青少年人群。
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fufu-report-rules"
7
+ version = "1.0.0"
8
+ description = "Read-only MCP connector: threshold lookup and abnormal-flag judgment for health-check indicators (runs locally, no patient data leaves your machine)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "LicenseRef-Proprietary"
12
+ authors = [{ name = "南京扶扶网络科技有限公司" }]
13
+ dependencies = ["mcp>=1.2.0,<2"]
14
+
15
+ [project.scripts]
16
+ fufu-report-rules = "fufu_report_rules.server:main"
17
+
18
+ [tool.setuptools.packages.find]
19
+ where = ["src"]
20
+
21
+ [tool.setuptools.package-data]
22
+ "fufu_report_rules" = ["vendor/core/*.csv", "vendor/core/*.py", "vendor/MANIFEST.json"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ # -*- coding: utf-8 -*-
2
+ """fufu-report-rules:只读 MCP 连接器包(REQ: docs/01-需求/20261124-REQ-只读MCP连接器立项-v1.0.md)"""
@@ -0,0 +1,54 @@
1
+ # -*- coding: utf-8 -*-
2
+ """judge shim:vendor 快照装载 + REQ 硬约束预置。
3
+
4
+ ⚠️ 本文件是连接器与 core 内部命名的唯一跨层耦合点,受 tests/test_connector_shim.py
5
+ 行为测试锁定。预置逻辑(`tj._DB_ROWS = []` / `tj._DB_ROWS_LOADED = True`)删掉任意一行,
6
+ 测试都会报警——它们防止判定入口无条件触发 load_db_thresholds()(拉起 sqlalchemy/app.*,
7
+ 见 docs/03-测试/连接器上架前置验证报告_20261124.md 阶段 2b 实证)。
8
+ """
9
+ import os
10
+ import sys
11
+
12
+ # vendor/ 置顶:保证 `import core.*` 解析到快照,而不是别的同名包
13
+ _VENDOR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vendor")
14
+ if _VENDOR not in sys.path:
15
+ sys.path.insert(0, _VENDOR)
16
+
17
+ import core.threshold_judge as tj # noqa: E402 (vendor 快照,非宿主 core)
18
+ from core.population_profile import PopulationProfile # noqa: E402,F401
19
+
20
+ # ---- REQ 硬约束(勿删,见 tests/test_connector_shim.py::test_preseed_is_load_bearing)----
21
+ tj._DB_ROWS = []
22
+ tj._DB_ROWS_LOADED = True
23
+
24
+ # 本快照未包含 core/ports:万一工具层误触脏数据回写路径,给出明确报错而非 sqlalchemy 堆栈
25
+ _HAS_PORTS = "core.ports.database" in sys.modules
26
+
27
+ # v1 支持的人群类别(child/adolescent 无对应 CSV,明确拒绝而非静默降级到成人库)
28
+ SUPPORTED_CATEGORIES = ("adult", "pregnant", "elderly", "elderly_75plus")
29
+
30
+
31
+ def build_profile(category: str = "adult", age=None, gender: str = "",
32
+ trimester=None, disease_history=None):
33
+ """工具参数 → PopulationProfile(非法组合显式报错)"""
34
+ if category not in SUPPORTED_CATEGORIES:
35
+ raise ValueError(
36
+ f"不支持的人群类别: {category!r}(v1 支持: {', '.join(SUPPORTED_CATEGORIES)};"
37
+ "儿童/青少年区间库未建立,请勿用成人库代替)")
38
+ if category == "pregnant" and trimester not in (None, 1, 2, 3):
39
+ raise ValueError(f"trimester 取值 1/2/3 或 None,收到: {trimester!r}")
40
+ return PopulationProfile(
41
+ category=category,
42
+ trimester=trimester if category == "pregnant" else None,
43
+ age=age,
44
+ gender=gender or "",
45
+ disease_history=list(disease_history or []),
46
+ )
47
+
48
+
49
+ def clean_rule(rule: dict) -> dict:
50
+ """规则行 → 对外只读 JSON(去掉内部标记键)"""
51
+ out = {k: v for k, v in rule.items() if not k.startswith("_")}
52
+ for k in ("alias", "hospital_alias", "normal_values"):
53
+ out[k] = list(out.get(k) or [])
54
+ return out
@@ -0,0 +1,160 @@
1
+ # -*- coding: utf-8 -*-
2
+ """fufu-report-rules MCP server(stdio,只读 3 工具)
3
+
4
+ 工具:
5
+ lookup_indicator 规则/编码检索(keyword/alias/性别,含 item_code + LOINC + ref_source)
6
+ get_threshold 阈值查询(按人群/性别给出该指标的生效规则,不判定)
7
+ judge_indicator 单项判定(数值或定性值 → 异常方向 + 阈值依据)
8
+
9
+ 合规:输出为参考区间阈值判定,不构成医学诊断(R-001)。
10
+ """
11
+ import json
12
+
13
+ from mcp.server.fastmcp import FastMCP
14
+
15
+ from fufu_report_rules.judge import (
16
+ SUPPORTED_CATEGORIES,
17
+ _HAS_PORTS,
18
+ build_profile,
19
+ clean_rule,
20
+ tj,
21
+ )
22
+
23
+ mcp = FastMCP(
24
+ "fufu-report-rules",
25
+ instructions=(
26
+ "体检指标参考区间与阈值判定的只读查询。所有结果来自本地规则库快照"
27
+ "(286 条通用规则 + 孕期/老年人人群库),仅作阈值判定参考,不构成医学诊断。"
28
+ ),
29
+ )
30
+
31
+
32
+ def _rows_for(profile):
33
+ """统一走预置后的组合入口(DB 路径已被 judge shim 预置短路)"""
34
+ return tj.get_thresholds_for_population(profile)
35
+
36
+
37
+ @mcp.tool()
38
+ def lookup_indicator(keyword: str, gender: str = "", limit: int = 10) -> str:
39
+ """按关键词/别名检索规则库条目(含项目编码 item_code 与 LOINC 编码、依据来源 ref_source)。
40
+
41
+ Args:
42
+ keyword: 指标关键词或英文缩写(如「空腹血糖」「FPG」「血肌酐」;中文按包含匹配,纯 ASCII 缩写按独立词匹配)
43
+ gender: 可选筛选,「男」/「女」/留空(默认全部)
44
+ limit: 最多返回条数(默认 10,上限 30)
45
+ """
46
+ limit = max(1, min(int(limit), 30))
47
+ rows = tj.get_thresholds_for_population(None)
48
+ kw = (keyword or "").strip()
49
+ if not kw:
50
+ return json.dumps({"error": "keyword 不能为空"}, ensure_ascii=False)
51
+
52
+ is_ascii = all(ord(c) < 128 for c in kw)
53
+ hits = []
54
+ for r in rows:
55
+ texts = [r.get("keyword", "")] + list(r.get("alias") or [])
56
+ hit = any(
57
+ (tj._ascii_token_in(kw, t) if is_ascii else kw in t)
58
+ for t in texts if t
59
+ )
60
+ if not hit:
61
+ continue
62
+ if gender and r.get("gender") not in ("通用", gender):
63
+ continue
64
+ hits.append(clean_rule(r))
65
+ if len(hits) >= limit:
66
+ break
67
+ return json.dumps({
68
+ "keyword": kw,
69
+ "total_rules": len(rows),
70
+ "matched": len(hits),
71
+ "results": hits,
72
+ "note": "条目为规则库快照,ref_source 注明依据来源;不构成医学诊断",
73
+ }, ensure_ascii=False)
74
+
75
+
76
+ @mcp.tool()
77
+ def get_threshold(item_name: str, category: str = "adult", gender: str = "",
78
+ age: int = None, trimester: int = None,
79
+ disease_history: list = None) -> str:
80
+ """查询某指标在指定人群下的生效阈值规则(只查询,不判定)。
81
+
82
+ Args:
83
+ item_name: 指标名或别名(如「空腹血糖」「FPG」)
84
+ category: 人群类别,adult/pregnant/elderly/elderly_75plus(v1 不支持儿童/青少年)
85
+ gender: 「男」/「女」,影响性别特异规则的选择
86
+ age: 年龄(可选,供老年人档说明)
87
+ trimester: 孕期 1/2/3(仅 category=pregnant 时有效)
88
+ disease_history: 既往病史列表(可选,仅作档案信息)
89
+ """
90
+ try:
91
+ profile = build_profile(category, age, gender, trimester, disease_history)
92
+ except ValueError as e:
93
+ return json.dumps({"error": str(e)}, ensure_ascii=False)
94
+ rows = _rows_for(profile)
95
+ best = tj.select_best_rule(rows, item_name, gender=gender or "")
96
+ if best is None:
97
+ return json.dumps({
98
+ "item_name": item_name, "category": category,
99
+ "found": False,
100
+ "note": "规则库未收录该指标(或该人群/性别组合无规则);不构成医学诊断",
101
+ }, ensure_ascii=False)
102
+ return json.dumps({
103
+ "item_name": item_name, "category": category, "found": True,
104
+ "rule": clean_rule(best),
105
+ "population_note": (
106
+ "妊娠期专属规则" if category == "pregnant"
107
+ else "≥80 岁放宽规则" if category == "elderly_75plus"
108
+ else "65-79 岁规则" if category == "elderly"
109
+ else "成人通用规则"),
110
+ "note": "依据 ref_source 可溯源;不构成医学诊断",
111
+ }, ensure_ascii=False)
112
+
113
+
114
+ @mcp.tool()
115
+ def judge_indicator(item_name: str, value, category: str = "adult",
116
+ gender: str = "", age: int = None, trimester: int = None,
117
+ disease_history: list = None) -> str:
118
+ """单项判定:给出指标名和检测值,返回异常方向(正常/偏高/偏低/临界/暂无参考区间)与阈值依据。
119
+
120
+ Args:
121
+ item_name: 指标名或别名
122
+ value: 检测值——数值(如 6.8)或定性文本(如「(-)」「阳性」「+3」)
123
+ category/gender/age/trimester/disease_history: 同 get_threshold
124
+ """
125
+ try:
126
+ profile = build_profile(category, age, gender, trimester, disease_history)
127
+ except ValueError as e:
128
+ return json.dumps({"error": str(e)}, ensure_ascii=False)
129
+ rows = _rows_for(profile)
130
+ best = tj.select_best_rule(rows, item_name, gender=gender or "")
131
+ if best is None:
132
+ return json.dumps({
133
+ "item_name": item_name, "value": value,
134
+ "tag": "暂无规则",
135
+ "note": "规则库未收录该指标(或该人群/性别组合无规则);不构成医学诊断",
136
+ }, ensure_ascii=False)
137
+
138
+ v = str(value).strip()
139
+ is_numeric = v.replace(".", "", 1).replace("-", "", 1).isdigit()
140
+ if is_numeric:
141
+ tag, remark = tj.evaluate_numeric(float(v), best, item_name)
142
+ else:
143
+ tag, remark = tj.evaluate_enum(v, best, item_name)
144
+ return json.dumps({
145
+ "item_name": item_name, "value": value,
146
+ "tag": tag, "remark": remark,
147
+ "rule": clean_rule(best),
148
+ "category": category,
149
+ "note": "阈值为规则库快照判定,仅供筛查参考,不构成医学诊断(R-001)",
150
+ }, ensure_ascii=False)
151
+
152
+
153
+ def main():
154
+ if _HAS_PORTS:
155
+ raise RuntimeError("vendor 快照不应包含 core.ports,请重跑 export_snapshot.py")
156
+ mcp.run(transport="stdio")
157
+
158
+
159
+ if __name__ == "__main__":
160
+ main()
@@ -0,0 +1,39 @@
1
+ {
2
+ "generated_at": "2026-11-24T15:47:49",
3
+ "source_of_truth": "模块项目 core/(封印基准,sha256 登记 config/core_sealed.json)",
4
+ "entry": "core/threshold_judge.py",
5
+ "excluded": [
6
+ "core/ports/**(宿主端口层,连接器工具不触达)"
7
+ ],
8
+ "note": "__init__.py 为生成态最小 glue(见文件头注释),不在字节一致断言范围",
9
+ "files": {
10
+ "data_guard.py": {
11
+ "sha256": "99ce8bf8c6db738c22dbfb00c68d8191d4cb35890496e73f899bba81da760e36",
12
+ "source": "core/data_guard.py"
13
+ },
14
+ "medical_grader.py": {
15
+ "sha256": "99686999db5634368b04aa93fc4a888af72e307ad1cd6b3b41724a04b634b08a",
16
+ "source": "core/medical_grader.py"
17
+ },
18
+ "population_profile.py": {
19
+ "sha256": "57d3f1e4682ff938dee64744c42a95343e24e9c4504f369446700138c561df0f",
20
+ "source": "core/population_profile.py"
21
+ },
22
+ "threshold_judge.py": {
23
+ "sha256": "1cda637885aeef9606a60996853890d703eb97b580d114c34f10368edc9a50a1",
24
+ "source": "core/threshold_judge.py"
25
+ },
26
+ "reference_thresholds.csv": {
27
+ "sha256": "c692a2adeb012d74c8ae4b15fd1416f57c9e201ca195141a3d4a851df86b9324",
28
+ "source": "core/reference_thresholds.csv"
29
+ },
30
+ "reference_thresholds_elderly.csv": {
31
+ "sha256": "29f8d8282c6150387f55530478139b3a6c05e7dc0ef5ade4a899d41cd14091e7",
32
+ "source": "core/reference_thresholds_elderly.csv"
33
+ },
34
+ "reference_thresholds_pregnancy.csv": {
35
+ "sha256": "ba81326477f0c58b448d3009ced5c963eb8c3d12c8f74075fd23781f24f6de1c",
36
+ "source": "core/reference_thresholds_pregnancy.csv"
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,7 @@
1
+ # -*- coding: utf-8 -*-
2
+ """[生成态] 连接器快照最小 glue —— 由 export_snapshot.py 生成,勿手改。
3
+
4
+ 与模块 core/__init__.py **有意不同**:模块版在包级拉起 router/rule_*/fusion_engine
5
+ 重链,连接器快照只需要 threshold_judge 判定子树,最小化 import 面。
6
+ 字节一致断言只覆盖其余文件(见 tests/test_connector_shim.py)。
7
+ """