cli.py
11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""运维命令行。
gl-mcp-admin db init 建表(幂等)
gl-mcp-admin db check 检查数据库连通性
gl-mcp-admin services list 列出自动发现到的服务及装配状态
gl-mcp-admin probe <service> 穷举签名模式探测上游,定位联调问题
gl-mcp-admin audit stats 命令行看调用统计
"""
from __future__ import annotations
import argparse
import asyncio
import sys
from datetime import datetime, timedelta
from gl_mcp_server.core.config.settings import get_app_settings
from gl_mcp_server.core.logging_setup import setup_logging
def _bootstrap() -> object:
"""CLI 通用初始化:加载配置 + 初始化日志。每个子命令执行前都会调用一次。"""
settings = get_app_settings()
setup_logging(
app_env=settings.app_env,
component="admin",
level=settings.log_level,
json_output=False, # CLI 永远输出人类可读格式
)
return settings
# --------------------------------------------------------------------------- db
async def _db_init() -> int:
"""`gl-mcp-admin db init`:建表/升级表结构。返回进程退出码。"""
settings = get_app_settings()
db = settings.database
from gl_mcp_server.core.db.engine import check_connection, dispose_engine, is_configured
from gl_mcp_server.core.db.migrations import apply_migrations
if not is_configured(db):
print("✗ 数据库未配置:请在 config/.env.<APP_ENV> 里填 DB_HOST / DB_NAME / DB_USER / DB_PASSWORD")
return 1
ok, detail = await check_connection(db)
if not ok:
print(f"✗ 连不上数据库 {db.host}:{db.port}/{db.name} —— {detail}")
return 1
applied = await apply_migrations(db)
if applied:
print(f"✓ 已应用 {len(applied)} 个迁移: {', '.join(applied)}")
else:
print("✓ 表结构已是最新,无需变更")
await dispose_engine()
return 0
async def _db_check() -> int:
"""`gl-mcp-admin db check`:只探活,不做任何写操作。返回进程退出码。"""
settings = get_app_settings()
db = settings.database
from gl_mcp_server.core.db.engine import check_connection, dispose_engine
ok, detail = await check_connection(db)
print(f"{'✓' if ok else '✗'} {db.host}:{db.port}/{db.name} —— {detail}")
await dispose_engine()
return 0 if ok else 1
# --------------------------------------------------------------------- services
def _services_list() -> int:
"""`gl-mcp-admin services list`:列出自动发现到的服务及各自装配状态。
装配失败的服务不会中断整个命令,只会在对应条目下打印错误原因
(对应 registry 模块「尽力而为」的装配语义)。返回进程退出码。
"""
settings = get_app_settings()
from gl_mcp_server.core.mcp.host import build_instances
instances = build_instances(settings)
if not instances:
print("没有发现任何服务。请检查 src/gl_mcp_server/services/<name>/manifest.py")
return 1
print(f"APP_ENV={settings.app_env},发现 {len(instances)} 个服务:\n")
for inst in instances:
mark = "✓" if inst.ok else "✗"
print(f"{mark} {inst.key} ({inst.manifest.display_name})")
if inst.settings:
print(f" 上游 {inst.settings.backend.base_url}")
print(f" 签名 {inst.settings.sign_mode}")
print(f" 行上限 {inst.settings.max_rows}")
if inst.error:
print(f" 错误 {inst.error}")
if inst.ok:
tools = asyncio.run(inst.mcp.list_tools())
print(f" 工具 {', '.join(t.name for t in tools) or '(无)'}")
print()
return 0 if all(i.ok for i in instances) else 1
# ------------------------------------------------------------------------ probe
async def _probe(service_key: str, timeout: float) -> int:
"""穷举签名模式打真实上游,定位「缺少必要参数」到底卡在哪。
背景:接口规范 1.2 节正文说 appKey/sign/timestamp 走 HTTP 请求头,
签名步骤却说「收集所有请求参数(query string 中的 key-value 对)」,
而文档的 curl 示例两者都不是。端到端联调恒定返回 400「缺少必要参数」,
连故意用错误的 sign 也是同样的响应 —— 说明可能压根没走到签名校验。
这个命令把所有组合跑一遍,把每种的完整请求和响应打出来。
"""
import httpx
from gl_mcp_server.core.http.signing import VALID_SIGN_MODES, SigningStrategy
from gl_mcp_server.core.registry import get_manifest
manifest = get_manifest(service_key)
if manifest is None:
print(f"✗ 未知的服务: {service_key}")
return 1
try:
settings = manifest.load_settings()
except Exception as exc: # noqa: BLE001
print(f"✗ 加载 {service_key} 配置失败: {exc}")
return 1
# 探测用的最小请求:上架接口所有参数可选,最适合当探针
probe_path = "/mcp/shelf/list"
probe_body = {"storeName": "探测请求"}
print(f"探测目标: {settings.backend.base_url}{probe_path}")
print(f"appKey: {settings.backend.app_key}")
print(f"参数: {probe_body}\n")
results: list[tuple[str, str]] = []
async with httpx.AsyncClient(base_url=settings.backend.base_url, timeout=timeout) as client:
for mode in VALID_SIGN_MODES:
signer = SigningStrategy(settings.backend.app_key, settings.backend.secret, mode)
signed = signer.sign(probe_body)
label = f"sign_mode={mode}"
try:
resp = await client.post(
probe_path,
json=signed.json_body,
params=signed.query_params,
headers=signed.headers,
)
except Exception as exc: # noqa: BLE001
print(f"[{label}] 请求失败: {type(exc).__name__}: {exc}\n")
results.append((label, f"EXC {type(exc).__name__}"))
continue
body = resp.text[:400].replace("\n", " ")
print(f"[{label}]")
print(f" body = {signed.json_body}")
print(f" query = {signed.query_params}")
print(f" sign = {signed.headers['sign']}")
print(f" -> HTTP {resp.status_code} ({resp.headers.get('content-type', '?')})")
print(f" -> {body}\n")
results.append((label, f"HTTP {resp.status_code}"))
# 对照组:故意用错的 sign。如果它和「正确」签名的响应一模一样,
# 说明请求压根没走到签名校验那一步,问题在更前置的拦截器上。
print("[对照组] 故意使用错误的 sign")
try:
resp = await client.post(
probe_path,
json=probe_body,
headers={
"appKey": settings.backend.app_key,
"sign": "0" * 40,
"timestamp": "1725264000000",
"Content-Type": "application/json; charset=utf-8",
},
)
print(f" -> HTTP {resp.status_code}: {resp.text[:400]}\n")
results.append(("错误签名对照组", f"HTTP {resp.status_code}"))
except Exception as exc: # noqa: BLE001
print(f" 请求失败: {exc}\n")
print("=" * 64)
print("汇总:")
for label, outcome in results:
print(f" {label:<28} {outcome}")
distinct = {outcome for _, outcome in results}
print()
if len(distinct) == 1:
print("所有模式(含故意用错签名的对照组)返回完全一致 —— 请求没有走到签名校验,")
print("问题在更前置的拦截器/网关上。需要向大数据团队要一个确认能跑通的完整 curl 示例。")
else:
print("不同模式返回不同 —— 说明签名确实参与了校验。挑返回 200 的那个模式,")
print(f"写进 config/.env.<APP_ENV> 的 {settings.env_prefix}_SIGN_MODE 即可。")
return 0
# ------------------------------------------------------------------------ audit
async def _audit_stats(days: int) -> int:
"""`gl-mcp-admin audit stats --days N`:命令行查看最近 N 天的调用统计。返回进程退出码。"""
settings = get_app_settings()
from gl_mcp_server.core.audit.repository import AuditRepository, LogFilter
from gl_mcp_server.core.db.engine import dispose_engine, is_configured
if not is_configured(settings.database):
print("✗ 数据库未配置")
return 1
repo = AuditRepository(settings.database)
flt = LogFilter(date_from=datetime.now() - timedelta(days=days))
try:
stats = await repo.stats(flt)
except Exception as exc: # noqa: BLE001
print(f"✗ 查询失败: {exc}")
return 1
finally:
await dispose_engine()
print(f"最近 {days} 天的调用统计:\n")
print(f" 总调用 {stats['total']}")
rate = stats["success_rate"]
print(f" 成功率 {f'{rate:.1%}' if rate is not None else '—'}")
print(f" 平均耗时 {stats['avg_ms']} ms")
print(f" P95 耗时 {stats['p95_ms']} ms")
print(f" 最慢 {stats['max_ms']} ms")
if stats["top_tools"]:
print("\n 调用最多的工具:")
for row in stats["top_tools"]:
print(f" {row['tool']:<28} {row['total']:>6} 次(失败 {row['errors']})")
if stats["top_callers"]:
print("\n 调用最多的来源:")
for row in stats["top_callers"]:
print(f" {row['caller']!s:<28} {row['total']:>6} 次")
return 0
# ------------------------------------------------------------------------- main
def build_parser() -> argparse.ArgumentParser:
"""构造 `gl-mcp-admin` 的命令行参数解析器(db / services / probe / audit 四组子命令)。"""
parser = argparse.ArgumentParser(prog="gl-mcp-admin", description="MCP Hive 运维工具")
sub = parser.add_subparsers(dest="command", required=True)
db = sub.add_parser("db", help="数据库")
db_sub = db.add_subparsers(dest="db_command", required=True)
db_sub.add_parser("init", help="建表(幂等)")
db_sub.add_parser("check", help="检查连通性")
services = sub.add_parser("services", help="服务")
services_sub = services.add_subparsers(dest="services_command", required=True)
services_sub.add_parser("list", help="列出发现到的服务")
probe = sub.add_parser("probe", help="穷举签名模式探测上游")
probe.add_argument("service", help="服务 key,如 used_car")
probe.add_argument("--timeout", type=float, default=15.0)
audit = sub.add_parser("audit", help="审计")
audit_sub = audit.add_subparsers(dest="audit_command", required=True)
stats = audit_sub.add_parser("stats", help="调用统计")
stats.add_argument("--days", type=int, default=7)
return parser
def main(argv: list[str] | None = None) -> int:
"""`gl-mcp-admin` 命令行入口。argv 为 None 时使用 sys.argv,显式传入主要方便单测。"""
args = build_parser().parse_args(argv)
_bootstrap()
if args.command == "db":
return asyncio.run(_db_init() if args.db_command == "init" else _db_check())
if args.command == "services":
return _services_list()
if args.command == "probe":
return asyncio.run(_probe(args.service, args.timeout))
if args.command == "audit":
return asyncio.run(_audit_stats(args.days))
return 1
if __name__ == "__main__":
sys.exit(main())