alphapulse-quantify-mcp 0.0.0-stage → 0.1.0
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.
- package/README.md +55 -2
- package/cordis.patch.yml +22 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +18 -0
- package/icon.svg +7 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +21 -4
- package/server/launch.js +50 -0
- package/server/quant_mcp.py +585 -0
package/README.md
CHANGED
|
@@ -1,3 +1,56 @@
|
|
|
1
|
-
#
|
|
1
|
+
# alphapulse-quantify-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
把 Alphapulse Quantify 量化研究工作区(aquant)的**只读**查询能力,作为
|
|
4
|
+
[DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) MCP 插件接入 agent。
|
|
5
|
+
|
|
6
|
+
安装后得到 16 个工具,前缀 `mcp__quantify__`,全部无副作用:不写库、不下单、不发消息。
|
|
7
|
+
|
|
8
|
+
## 工具
|
|
9
|
+
|
|
10
|
+
| 类别 | 工具 |
|
|
11
|
+
|---|---|
|
|
12
|
+
| 策略 | `strategy_list` `signal_preview` `alpha1_status` |
|
|
13
|
+
| 模拟盘 | `paper_status` |
|
|
14
|
+
| 数据 | `bars` `adj_factors` `daily_basic` `universe` `trade_calendar` `index_daily` `data_health` |
|
|
15
|
+
| 回测/运维 | `backtest_runs` `ops_status` `ops_history` `notify_recent` `notify_incidents` |
|
|
16
|
+
|
|
17
|
+
## 安装
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
# 在本机 DSH profile 里安装(或让 agent 调 plugin_manager install_bundle)
|
|
21
|
+
dsh # 打开 Plugins → Add plugin,选择 npm 包名 alphapulse-quantify-mcp
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
装好后插件页出现「量化研究台」,启用即注册工具。
|
|
25
|
+
|
|
26
|
+
## 前置条件
|
|
27
|
+
|
|
28
|
+
1. **aquant 检出 + 虚拟环境**:`QUANTIFY_AQUANT_ROOT` 指向 aquant 仓库,且
|
|
29
|
+
`$QUANTIFY_AQUANT_ROOT/.venv/bin/python` 能 `import aquant`(含 pandas/pymongo)。
|
|
30
|
+
2. 本机配置了 aquant 的只读 Mongo 身份(`~/.quantaxis/setting/config.ini`)。
|
|
31
|
+
3. `paper_status` 需要 aquant 的 Supabase 只读凭据;没有时只有该工具失败,其余照常。
|
|
32
|
+
|
|
33
|
+
环境变量(都在 `cordis.patch.yml` 的 `env` 里改):
|
|
34
|
+
|
|
35
|
+
| 变量 | 作用 |
|
|
36
|
+
|---|---|
|
|
37
|
+
| `QUANTIFY_AQUANT_ROOT` | aquant 仓库路径,用于定位 venv 并作为 `aq` 的 cwd |
|
|
38
|
+
| `QUANTIFY_PYTHON` | 直接指定 Python 解释器,优先级最高 |
|
|
39
|
+
| `QUANTIFY_QUANTDATA_ROOT` | 回测产物目录,默认 `$QUANTIFY_AQUANT_ROOT/../QuantData` |
|
|
40
|
+
|
|
41
|
+
## 边界
|
|
42
|
+
|
|
43
|
+
- 只读:没有写入、下单、推送类工具。
|
|
44
|
+
- `signal_preview` 依赖各策略的输入产物:`xingmai3` 可直接算;`alpha1`/`alpha2ml` 需要冻结产物;
|
|
45
|
+
`polaris1`/`xingmai2` 需要盘中快照;`alpha3` 仅人工观察。
|
|
46
|
+
- 行情来自 `QUANTIFY_AQUANT_ROOT` 所连的 Mongo(可能是研究副本,未必是最新交易日);
|
|
47
|
+
`paper_status` 读生产账本,两者日期可能不一致,以 `data_health` 为准。
|
|
48
|
+
- MCP 客户端没有逐工具审批,因此本包只暴露只读工具。
|
|
49
|
+
|
|
50
|
+
## 开发
|
|
51
|
+
|
|
52
|
+
```
|
|
53
|
+
server/quant_mcp.py # 零第三方依赖的 stdio MCP server(JSON-RPC 手写)
|
|
54
|
+
server/launch.js # 定位 python 并转发 stdio
|
|
55
|
+
cordis.patch.yml # 插入 @deepseek-ai/dsh-mcp-client,transport: stdio
|
|
56
|
+
```
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# 把 Alphapulse Quantify 的只读 MCP 服务接入 agent。
|
|
2
|
+
#
|
|
3
|
+
# 子进程的 cwd 是当前 profile 目录(DSH 实测),所以 args 用 profile 相对路径指向包内启动器;
|
|
4
|
+
# launch.js 再用 __dirname 定位包内 quant_mcp.py,跟 cwd 无关。
|
|
5
|
+
#
|
|
6
|
+
# QUANTIFY_AQUANT_ROOT 改成你自己的 aquant 检出目录;也可用 QUANTIFY_PYTHON 直接指定解释器。
|
|
7
|
+
- insert:
|
|
8
|
+
- id: quantify-mcp
|
|
9
|
+
name: '@deepseek-ai/dsh-mcp-client'
|
|
10
|
+
config:
|
|
11
|
+
serverName: quantify
|
|
12
|
+
transport: stdio
|
|
13
|
+
command: node
|
|
14
|
+
args:
|
|
15
|
+
- node_modules/alphapulse-quantify-mcp/server/launch.js
|
|
16
|
+
env:
|
|
17
|
+
QUANTIFY_AQUANT_ROOT: /Users/yueyue/Finance/Quantify/aquant
|
|
18
|
+
TZ: Asia/Shanghai
|
|
19
|
+
PYTHONUNBUFFERED: '1'
|
|
20
|
+
toolCallTimeoutMs: 600000
|
|
21
|
+
startupTimeoutMs: 30000
|
|
22
|
+
failOnStartupError: true
|
package/docs/DETAIL.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+

|
|
@@ -0,0 +1 @@
|
|
|
1
|
+

|
package/docs/preview.svg
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="300" viewBox="0 0 640 300">
|
|
2
|
+
<rect width="640" height="300" rx="20" fill="#f3f5f9"/>
|
|
3
|
+
<rect x="48" y="72" width="176" height="156" rx="20" fill="#ffffff" stroke="#b7c3d2" stroke-width="2"/>
|
|
4
|
+
<path d="M78 105h104a10 10 0 0 1 10 10v20a10 10 0 0 1-10 10h-72l-16 12v-12H78a10 10 0 0 1-10-10v-20a10 10 0 0 1 10-10Z" fill="#e4edf8"/>
|
|
5
|
+
<path d="M104 167h78a10 10 0 0 1 10 10v19a10 10 0 0 1-10 10h-78a10 10 0 0 1-10-10v-19a10 10 0 0 1 10-10Z" fill="#247bbf"/>
|
|
6
|
+
<path d="M260 126h116m-10-10 10 10-10 10" fill="none" stroke="#247bbf" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
|
|
7
|
+
<path d="M376 174H260m10-10-10 10 10 10" fill="none" stroke="#7b8b9f" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
|
|
8
|
+
<rect x="412" y="72" width="180" height="156" rx="20" fill="#ffffff" stroke="#b7c3d2" stroke-width="2"/>
|
|
9
|
+
<path d="M444 196h116" fill="none" stroke="#9cacc0" stroke-width="3" stroke-linecap="round"/>
|
|
10
|
+
<g fill="#247bbf">
|
|
11
|
+
<rect x="448" y="164" width="18" height="32" rx="5"/>
|
|
12
|
+
<rect x="478" y="140" width="18" height="56" rx="5"/>
|
|
13
|
+
<rect x="508" y="120" width="18" height="76" rx="5"/>
|
|
14
|
+
<rect x="538" y="98" width="18" height="98" rx="5"/>
|
|
15
|
+
</g>
|
|
16
|
+
<path d="M448 148 486 128 516 112 552 92" fill="none" stroke="#3f9b6d" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
|
|
17
|
+
<circle cx="552" cy="92" r="5" fill="#3f9b6d"/>
|
|
18
|
+
</svg>
|
package/icon.svg
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
|
|
2
|
+
<g fill="#247bbf">
|
|
3
|
+
<rect x="7" y="19" width="5" height="10" rx="1.5"/>
|
|
4
|
+
<rect x="15.5" y="14.5" width="5" height="14.5" rx="1.5"/>
|
|
5
|
+
<rect x="24" y="9.5" width="5" height="19.5" rx="1.5"/>
|
|
6
|
+
</g>
|
|
7
|
+
</svg>
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Alphapulse research console",
|
|
4
|
+
"description": "Brings the Alphapulse Quantify workspace's read-only aquant tools to the agent: 16 tools for strategy inventory, signal previews, paper-trading status, data freshness, scheduled-job and notification records, Alpha1 research status, backtest artifacts, and daily bars, adjustment factors, valuation snapshots, security eligibility, trading calendar, and index series. Tools appear as mcp__quantify__*. Every tool is side-effect free: no database writes, no orders, and no messages; a signal preview is computed but never published. Market data, valuations, eligibility, and the calendar are read from the research Mongo database through this machine's read-only identity — currently an SSH tunnel to dgx8001-quant, not the Mac mini production database, and that copy does not follow production updates. Paper-trading accounts come from the production Supabase ledger over a read-only connection, so account dates are usually newer than the research bars; check data_health before treating a date as the latest session. Production writes and notifications run on the Mac mini and are not part of this plugin. Turning the plugin off removes every mcp__quantify__* tool.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/locale/zh.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Alphapulse 量化研究台",
|
|
4
|
+
"description": "把 Alphapulse Quantify 工作区的 aquant 只读能力接入 agent:16 个工具覆盖策略清单、信号预览、模拟盘状态、数据健康、定时任务与推送记录、Alpha1 研究状态、回测产物,以及日线、复权因子、估值截面、证券资格、交易日历与指数日线。工具名形如 mcp__quantify__bars。全部工具无副作用:不写库、不下单、不发消息;信号预览只计算、不发布。行情、估值、资格与日历经本机配置的只读 Mongo 身份读取研究库(当前经 SSH 隧道指向 dgx8001-quant,不是 Mac mini 生产库,副本不随生产更新);模拟盘账本经 Supabase 只读连接读取生产账本,因此账户日期通常比研究库行情更新——把某天当作最新交易日之前先用 data_health 确认。生产写入与推送在 Mac mini 上运行,不在本插件内。关闭插件即移除全部 mcp__quantify__* 工具。",
|
|
5
|
+
"detail": "docs/DETAIL.zh.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "alphapulse-quantify-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Alphapulse Quantify: read-only quant-research tools (aquant strategies, paper accounts, market data) for DeepSeek Harness over MCP.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "UNLICENSED",
|
|
7
|
+
"keywords": ["alphapulse", "dsh", "deepseek-harness", "mcp", "quant", "aquant"],
|
|
8
|
+
"engines": { "dsh": ">=0.2.2-rc.3", "node": ">=18" },
|
|
9
|
+
"exports": {
|
|
10
|
+
"./locale/*.json": "./locale/*.json",
|
|
11
|
+
"./icon": "./icon.svg",
|
|
12
|
+
"./server/launch.js": "./server/launch.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"cordis.patch.yml",
|
|
16
|
+
"locale/*.json",
|
|
17
|
+
"docs",
|
|
18
|
+
"icon.svg",
|
|
19
|
+
"server",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
|
|
23
|
+
}
|
package/server/launch.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* MCP stdio 启动器:定位包内的 quant_mcp.py,选一个能 import aquant 的 Python,然后把
|
|
4
|
+
* stdio 原样交给它(DSH 直接和 Python 进程说 JSON-RPC)。
|
|
5
|
+
*
|
|
6
|
+
* Python 解析顺序:
|
|
7
|
+
* 1. QUANTIFY_PYTHON 显式指定解释器
|
|
8
|
+
* 2. $QUANTIFY_AQUANT_ROOT/.venv/bin/python 项目自带虚拟环境(推荐)
|
|
9
|
+
* 3. python3
|
|
10
|
+
*
|
|
11
|
+
* 之所以要这层:mcp-client 用固定 command 拉起子进程,而 npm 包的安装路径因 profile 而异;
|
|
12
|
+
* 用 __dirname 定位包内文件后,路径问题就和 cwd 无关了。
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from 'node:child_process'
|
|
15
|
+
import { existsSync } from 'node:fs'
|
|
16
|
+
import { dirname, join } from 'node:path'
|
|
17
|
+
import { fileURLToPath } from 'node:url'
|
|
18
|
+
|
|
19
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
20
|
+
const server = join(here, 'quant_mcp.py')
|
|
21
|
+
const aquantRoot = process.env.QUANTIFY_AQUANT_ROOT || ''
|
|
22
|
+
|
|
23
|
+
const candidates = [
|
|
24
|
+
process.env.QUANTIFY_PYTHON,
|
|
25
|
+
aquantRoot ? join(aquantRoot, '.venv', 'bin', 'python') : undefined,
|
|
26
|
+
'python3',
|
|
27
|
+
].filter(Boolean)
|
|
28
|
+
|
|
29
|
+
const python = candidates.find((p) => p === 'python3' || existsSync(p))
|
|
30
|
+
|
|
31
|
+
if (!existsSync(server)) {
|
|
32
|
+
console.error(`[quantify-mcp] 找不到服务端脚本:${server}`)
|
|
33
|
+
process.exit(1)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const child = spawn(python, [server, ...process.argv.slice(2)], {
|
|
37
|
+
stdio: 'inherit',
|
|
38
|
+
cwd: aquantRoot && existsSync(aquantRoot) ? aquantRoot : process.cwd(),
|
|
39
|
+
env: process.env,
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
child.on('error', (error) => {
|
|
43
|
+
console.error(`[quantify-mcp] 启动 ${python} 失败:${error.message}`)
|
|
44
|
+
process.exit(1)
|
|
45
|
+
})
|
|
46
|
+
child.on('exit', (code, signal) => process.exit(signal ? 1 : code ?? 0))
|
|
47
|
+
|
|
48
|
+
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) {
|
|
49
|
+
process.on(signal, () => child.kill(signal))
|
|
50
|
+
}
|
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Quantify 只读 MCP server(stdio,零第三方 MCP SDK 依赖)。
|
|
3
|
+
|
|
4
|
+
把本项目 aquant 的只读能力暴露为 MCP 工具,供 DeepSeek Harness 的
|
|
5
|
+
`@deepseek-ai/dsh-mcp-client` 以 `transport: stdio` 接入。
|
|
6
|
+
|
|
7
|
+
设计约束:
|
|
8
|
+
- 只读:命令级工具只调用 `aq` 的查询类子命令;数据级工具只走 DataPortal 的读方法。
|
|
9
|
+
- 不写 stdout 除 JSON-RPC 帧以外的任何内容;诊断信息一律写 stderr。
|
|
10
|
+
- 超时与行数上限是硬约束,避免一次调用把全市场数据塞进上下文。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
import traceback
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Callable
|
|
22
|
+
|
|
23
|
+
AQUANT_ROOT = Path(
|
|
24
|
+
os.environ.get("QUANTIFY_AQUANT_ROOT") or "/Users/yueyue/Finance/Quantify/aquant"
|
|
25
|
+
).expanduser()
|
|
26
|
+
QUANTDATA_ROOT = Path(
|
|
27
|
+
os.environ.get("QUANTIFY_QUANTDATA_ROOT") or str(AQUANT_ROOT.parent / "QuantData")
|
|
28
|
+
).expanduser()
|
|
29
|
+
SERVER_NAME = "quantify"
|
|
30
|
+
SERVER_VERSION = "0.1.0"
|
|
31
|
+
DEFAULT_PROTOCOL = "2025-06-18"
|
|
32
|
+
MAX_CHARS = 180_000
|
|
33
|
+
MAX_ROWS = 2_000
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def log(message: str) -> None:
|
|
37
|
+
print(f"[quant-mcp] {message}", file=sys.stderr, flush=True)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# --------------------------------------------------------------------------- 通用
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _truncate(text: str) -> str:
|
|
44
|
+
if len(text) <= MAX_CHARS:
|
|
45
|
+
return text
|
|
46
|
+
return text[:MAX_CHARS] + f"\n…(已截断,原长度 {len(text)} 字符;请缩小查询范围或降低 limit)"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _json(obj: Any) -> str:
|
|
50
|
+
return _truncate(json.dumps(obj, ensure_ascii=False, default=str, separators=(",", ":")))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def run_aq(args: list[str], timeout: float = 300) -> Any:
|
|
54
|
+
"""在 aquant 仓库内运行只读 `aq` 子命令,返回解析后的 JSON。"""
|
|
55
|
+
proc = subprocess.run(
|
|
56
|
+
[sys.executable, "-m", "aquant.cli", *args],
|
|
57
|
+
cwd=str(AQUANT_ROOT),
|
|
58
|
+
capture_output=True,
|
|
59
|
+
text=True,
|
|
60
|
+
timeout=timeout,
|
|
61
|
+
)
|
|
62
|
+
out = (proc.stdout or "").strip()
|
|
63
|
+
try:
|
|
64
|
+
data = json.loads(out) if out else None
|
|
65
|
+
except json.JSONDecodeError:
|
|
66
|
+
data = None
|
|
67
|
+
if proc.returncode != 0:
|
|
68
|
+
# 部分子命令用非零退出码表达业务结论(如 data check 的“数据陈旧”),JSON 仍有效
|
|
69
|
+
if data is not None:
|
|
70
|
+
if isinstance(data, dict):
|
|
71
|
+
data.setdefault("_exit_code", proc.returncode)
|
|
72
|
+
return data
|
|
73
|
+
detail = (proc.stderr or out or "").strip().splitlines()
|
|
74
|
+
tail = detail[-1] if detail else "无错误输出"
|
|
75
|
+
raise RuntimeError(f"aq {' '.join(args)} 失败(退出码 {proc.returncode}):{tail[:500]}")
|
|
76
|
+
if data is None:
|
|
77
|
+
return {"raw": _truncate(out)} if out else {"ok": True}
|
|
78
|
+
return data
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _frame(df, limit: int = MAX_ROWS) -> dict:
|
|
82
|
+
"""DataFrame → 可序列化记录,带截断标记。"""
|
|
83
|
+
total = int(len(df))
|
|
84
|
+
head = df.head(limit)
|
|
85
|
+
records = head.astype(object).where(head.notna(), None).to_dict("records")
|
|
86
|
+
result: dict[str, Any] = {"rows": records, "returned": len(records), "total": total}
|
|
87
|
+
if total > len(records):
|
|
88
|
+
result["truncated"] = True
|
|
89
|
+
return result
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def portal():
|
|
93
|
+
from aquant.data import DataPortal
|
|
94
|
+
|
|
95
|
+
return DataPortal()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# --------------------------------------------------------------------------- 工具实现
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def strategy_list(_: dict) -> Any:
|
|
102
|
+
return run_aq(["strategy", "list"], timeout=120)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def signal_preview(args: dict) -> Any:
|
|
106
|
+
cmd = ["signal", args["strategy"]]
|
|
107
|
+
if args.get("date"):
|
|
108
|
+
cmd += ["--date", args["date"]]
|
|
109
|
+
return run_aq(cmd, timeout=900)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def paper_status(args: dict) -> Any:
|
|
113
|
+
return run_aq(["paper", "status", args["strategy"]], timeout=180)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def data_health(_: dict) -> Any:
|
|
117
|
+
return run_aq(["data", "check"], timeout=180)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def ops_status(_: dict) -> Any:
|
|
121
|
+
return run_aq(["ops", "status"], timeout=120)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def ops_history(args: dict) -> Any:
|
|
125
|
+
cmd = ["ops", "history", "--limit", str(int(args.get("limit", 20)))]
|
|
126
|
+
if args.get("job"):
|
|
127
|
+
cmd.append(args["job"])
|
|
128
|
+
return run_aq(cmd, timeout=120)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def notify_recent(args: dict) -> Any:
|
|
132
|
+
return run_aq(["notify", "recent", "--limit", str(int(args.get("limit", 20)))], timeout=120)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def notify_incidents(args: dict) -> Any:
|
|
136
|
+
return run_aq(["notify", "incidents", "--limit", str(int(args.get("limit", 20)))], timeout=120)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def alpha1_status(_: dict) -> Any:
|
|
140
|
+
return run_aq(["research", "alpha1", "status"], timeout=120)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def backtest_runs(args: dict) -> Any:
|
|
144
|
+
root = QUANTDATA_ROOT / "runs"
|
|
145
|
+
limit = max(1, min(int(args.get("limit", 20)), 200))
|
|
146
|
+
strategy = args.get("strategy")
|
|
147
|
+
runs = []
|
|
148
|
+
if root.exists():
|
|
149
|
+
bases = [root / strategy] if strategy else [p for p in root.iterdir() if p.is_dir()]
|
|
150
|
+
for base in bases:
|
|
151
|
+
if not base.is_dir():
|
|
152
|
+
continue
|
|
153
|
+
for run in base.iterdir():
|
|
154
|
+
if not run.is_dir():
|
|
155
|
+
continue
|
|
156
|
+
summary = run / "summary.json"
|
|
157
|
+
metrics = run / "metrics.json"
|
|
158
|
+
item: dict[str, Any] = {
|
|
159
|
+
"strategy": base.name,
|
|
160
|
+
"run": run.name,
|
|
161
|
+
"path": str(run),
|
|
162
|
+
"modified": run.stat().st_mtime,
|
|
163
|
+
}
|
|
164
|
+
for name, path in (("summary", summary), ("metrics", metrics)):
|
|
165
|
+
if path.exists():
|
|
166
|
+
text = path.read_text()
|
|
167
|
+
try:
|
|
168
|
+
parsed = json.loads(text)
|
|
169
|
+
item[name] = (
|
|
170
|
+
parsed
|
|
171
|
+
if len(json.dumps(parsed, ensure_ascii=False)) <= 4_000
|
|
172
|
+
else _truncate(text[:4_000])
|
|
173
|
+
)
|
|
174
|
+
except Exception:
|
|
175
|
+
item[name] = _truncate(text[:4_000])
|
|
176
|
+
break
|
|
177
|
+
runs.append(item)
|
|
178
|
+
runs.sort(key=lambda r: r["modified"], reverse=True)
|
|
179
|
+
return {"runs": runs[:limit], "total": len(runs)}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def bars(args: dict) -> Any:
|
|
183
|
+
p = portal()
|
|
184
|
+
df = p.daily_bars(args["ts_codes"], args["start"], args["end"])
|
|
185
|
+
return _frame(df, int(args.get("limit", MAX_ROWS)))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def adj_factors(args: dict) -> Any:
|
|
189
|
+
p = portal()
|
|
190
|
+
df = p.adj_factors(args["ts_codes"], args["start"], args["end"])
|
|
191
|
+
return _frame(df, int(args.get("limit", MAX_ROWS)))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def daily_basic(args: dict) -> Any:
|
|
195
|
+
p = portal()
|
|
196
|
+
fields = args.get("fields") or ["pe_ttm", "pb", "total_mv", "circ_mv", "turnover_rate"]
|
|
197
|
+
df = p.daily_basic(args["day"], fields)
|
|
198
|
+
return _frame(df, int(args.get("limit", MAX_ROWS)))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def universe(args: dict) -> Any:
|
|
202
|
+
p = portal()
|
|
203
|
+
fields = tuple(args.get("fields") or ["tradable", "is_st", "is_suspended"])
|
|
204
|
+
df = p.universe(args["day"], fields)
|
|
205
|
+
return _frame(df, int(args.get("limit", MAX_ROWS)))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def trade_calendar(args: dict) -> Any:
|
|
209
|
+
cal = portal().calendar
|
|
210
|
+
out: dict[str, Any] = {"first": cal.first, "last": cal.last, "count": len(cal.sessions)}
|
|
211
|
+
day = args.get("day")
|
|
212
|
+
if day:
|
|
213
|
+
item: dict[str, Any] = {"day": day, "is_session": cal.is_session(day)}
|
|
214
|
+
try:
|
|
215
|
+
item["previous"] = cal.previous(day)
|
|
216
|
+
except Exception:
|
|
217
|
+
item["previous"] = None
|
|
218
|
+
try:
|
|
219
|
+
item["next"] = cal.next(day)
|
|
220
|
+
except Exception:
|
|
221
|
+
item["next"] = None
|
|
222
|
+
out["day"] = item
|
|
223
|
+
if item.get("next") is None:
|
|
224
|
+
out["note"] = f"日历仅覆盖到 {cal.last},其后交易日未知(本机 calendar-sync 未运行到最后)"
|
|
225
|
+
if args.get("start") and args.get("end"):
|
|
226
|
+
sessions = cal.between(args["start"], args["end"])
|
|
227
|
+
limit = max(1, min(int(args.get("limit", 60)), 500))
|
|
228
|
+
out["sessions"] = sessions[:limit]
|
|
229
|
+
out["session_count"] = len(sessions)
|
|
230
|
+
return out
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def index_daily(args: dict) -> Any:
|
|
234
|
+
p = portal()
|
|
235
|
+
df = p.index_daily(args["ts_code"], args["start"], args["end"])
|
|
236
|
+
return _frame(df, int(args.get("limit", MAX_ROWS)))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
# --------------------------------------------------------------------------- 工具注册表
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _date(desc: str) -> dict:
|
|
243
|
+
return {"type": "string", "description": desc, "pattern": r"^\d{4}-\d{2}-\d{2}$"}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _codes() -> dict:
|
|
247
|
+
return {
|
|
248
|
+
"type": "array",
|
|
249
|
+
"items": {"type": "string"},
|
|
250
|
+
"description": "证券代码,支持 000001.SZ / 600000.SH / 830799.BJ 或 6 位代码",
|
|
251
|
+
"minItems": 1,
|
|
252
|
+
"maxItems": 200,
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
STRATEGY_HINT = "策略 id,例如 alpha1、alpha2ml、alpha3、polaris1、xingmai2、xingmai3"
|
|
257
|
+
|
|
258
|
+
TOOLS: list[dict[str, Any]] = [
|
|
259
|
+
{
|
|
260
|
+
"name": "strategy_list",
|
|
261
|
+
"description": "列出 aquant 已注册策略:id、显示名、版本、模拟盘账户与通知通道。只读。",
|
|
262
|
+
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
|
|
263
|
+
"handler": strategy_list,
|
|
264
|
+
},
|
|
265
|
+
{
|
|
266
|
+
"name": "signal_preview",
|
|
267
|
+
"description": (
|
|
268
|
+
"只计算某策略在某信号日的目标股池(不发布、不下单、不推送)。"
|
|
269
|
+
"返回 signal_date、execution_date 与 targets(ts_code/name/weight)。计算可能需要数十秒。"
|
|
270
|
+
"本机可用性:xingmai3 可直接预览;alpha1/alpha2ml 需要 QuantData/frozen 冻结产物;"
|
|
271
|
+
"polaris1/xingmai2 需要盘中快照;alpha3 只走人工观察流程。"
|
|
272
|
+
),
|
|
273
|
+
"inputSchema": {
|
|
274
|
+
"type": "object",
|
|
275
|
+
"properties": {
|
|
276
|
+
"strategy": {"type": "string", "description": STRATEGY_HINT},
|
|
277
|
+
"date": _date("信号日 YYYY-MM-DD;缺省为最近一个已收盘交易日"),
|
|
278
|
+
},
|
|
279
|
+
"required": ["strategy"],
|
|
280
|
+
"additionalProperties": False,
|
|
281
|
+
},
|
|
282
|
+
"handler": signal_preview,
|
|
283
|
+
},
|
|
284
|
+
{
|
|
285
|
+
"name": "paper_status",
|
|
286
|
+
"description": (
|
|
287
|
+
"读取某策略模拟盘账户状态:资金/净值、持仓、最新目标批次、运行态。只读,不改账户。"
|
|
288
|
+
"账本经 Supabase 只读连接读取,是生产账本,通常比本机 Mongo 行情更新;"
|
|
289
|
+
"不要用它的日期推断本机行情最新交易日(那看 data_health)。"
|
|
290
|
+
),
|
|
291
|
+
"inputSchema": {
|
|
292
|
+
"type": "object",
|
|
293
|
+
"properties": {"strategy": {"type": "string", "description": STRATEGY_HINT}},
|
|
294
|
+
"required": ["strategy"],
|
|
295
|
+
"additionalProperties": False,
|
|
296
|
+
},
|
|
297
|
+
"handler": paper_status,
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
"name": "data_health",
|
|
301
|
+
"description": "数据新鲜度巡检:各集合最新交易日、stale 明细、日历是否覆盖、待核验退市证券。只读,不发告警。",
|
|
302
|
+
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
|
|
303
|
+
"handler": data_health,
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
"name": "ops_status",
|
|
307
|
+
"description": "定时任务状态(本机 launchd 视图):每个 job 的加载状态、计划时刻、最近运行与退出码。只读。",
|
|
308
|
+
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
|
|
309
|
+
"handler": ops_status,
|
|
310
|
+
},
|
|
311
|
+
{
|
|
312
|
+
"name": "ops_history",
|
|
313
|
+
"description": "定时任务运行历史(最近 N 条,可按任务名过滤)。只读。",
|
|
314
|
+
"inputSchema": {
|
|
315
|
+
"type": "object",
|
|
316
|
+
"properties": {
|
|
317
|
+
"job": {"type": "string", "description": "任务名,如 data-update、paper-execute"},
|
|
318
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
|
|
319
|
+
},
|
|
320
|
+
"additionalProperties": False,
|
|
321
|
+
},
|
|
322
|
+
"handler": ops_history,
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
"name": "notify_recent",
|
|
326
|
+
"description": "最近推送记录(outbox)。只读,不发送、不重试。",
|
|
327
|
+
"inputSchema": {
|
|
328
|
+
"type": "object",
|
|
329
|
+
"properties": {"limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}},
|
|
330
|
+
"additionalProperties": False,
|
|
331
|
+
},
|
|
332
|
+
"handler": notify_recent,
|
|
333
|
+
},
|
|
334
|
+
{
|
|
335
|
+
"name": "notify_incidents",
|
|
336
|
+
"description": "待诊断告警队列(只读查看,不运行诊断、不外发)。",
|
|
337
|
+
"inputSchema": {
|
|
338
|
+
"type": "object",
|
|
339
|
+
"properties": {"limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}},
|
|
340
|
+
"additionalProperties": False,
|
|
341
|
+
},
|
|
342
|
+
"handler": notify_incidents,
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
"name": "alpha1_status",
|
|
346
|
+
"description": "Alpha1 研究自动化状态:当前窗口、期次、任务进度与阻塞。只读。",
|
|
347
|
+
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
|
|
348
|
+
"handler": alpha1_status,
|
|
349
|
+
},
|
|
350
|
+
{
|
|
351
|
+
"name": "backtest_runs",
|
|
352
|
+
"description": (
|
|
353
|
+
"列出 QuantData/runs 下的回测产物(策略、run 目录、修改时间,附 summary/metrics 摘要)。"
|
|
354
|
+
"只列出,不运行回测、不发布。"
|
|
355
|
+
),
|
|
356
|
+
"inputSchema": {
|
|
357
|
+
"type": "object",
|
|
358
|
+
"properties": {
|
|
359
|
+
"strategy": {"type": "string", "description": "只列该策略的 run;缺省为全部"},
|
|
360
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200, "default": 20},
|
|
361
|
+
},
|
|
362
|
+
"additionalProperties": False,
|
|
363
|
+
},
|
|
364
|
+
"handler": backtest_runs,
|
|
365
|
+
},
|
|
366
|
+
{
|
|
367
|
+
"name": "bars",
|
|
368
|
+
"description": (
|
|
369
|
+
"读取日线(stock_day 为主,缺日由补充集合补齐;已剔除隔离行)。"
|
|
370
|
+
"字段含 ts_code/code/date/open/high/low/close/vol/amount 等,vol 单位为手。"
|
|
371
|
+
"数据来自研究库(经本机配置的只读 Mongo 身份读取,当前为 dgx8001-quant 的 SSH 隧道),"
|
|
372
|
+
"不是 Mac mini 生产库;最新可用交易日以 data_health 为准。"
|
|
373
|
+
),
|
|
374
|
+
"inputSchema": {
|
|
375
|
+
"type": "object",
|
|
376
|
+
"properties": {
|
|
377
|
+
"ts_codes": _codes(),
|
|
378
|
+
"start": _date("起始交易日(含)"),
|
|
379
|
+
"end": _date("结束交易日(含)"),
|
|
380
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 5000, "default": 2000},
|
|
381
|
+
},
|
|
382
|
+
"required": ["ts_codes", "start", "end"],
|
|
383
|
+
"additionalProperties": False,
|
|
384
|
+
},
|
|
385
|
+
"handler": bars,
|
|
386
|
+
},
|
|
387
|
+
{
|
|
388
|
+
"name": "adj_factors",
|
|
389
|
+
"description": "读取复权因子(已剔除隔离行)。用于把原始价换算为后复权序列。",
|
|
390
|
+
"inputSchema": {
|
|
391
|
+
"type": "object",
|
|
392
|
+
"properties": {
|
|
393
|
+
"ts_codes": _codes(),
|
|
394
|
+
"start": _date("起始交易日(含)"),
|
|
395
|
+
"end": _date("结束交易日(含)"),
|
|
396
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 5000, "default": 2000},
|
|
397
|
+
},
|
|
398
|
+
"required": ["ts_codes", "start", "end"],
|
|
399
|
+
"additionalProperties": False,
|
|
400
|
+
},
|
|
401
|
+
"handler": adj_factors,
|
|
402
|
+
},
|
|
403
|
+
{
|
|
404
|
+
"name": "daily_basic",
|
|
405
|
+
"description": "读取单日估值截面(已剔除隔离行、去重)。常用字段 pe_ttm、pb、total_mv、circ_mv、turnover_rate。",
|
|
406
|
+
"inputSchema": {
|
|
407
|
+
"type": "object",
|
|
408
|
+
"properties": {
|
|
409
|
+
"day": _date("交易日 YYYY-MM-DD"),
|
|
410
|
+
"fields": {
|
|
411
|
+
"type": "array",
|
|
412
|
+
"items": {"type": "string"},
|
|
413
|
+
"description": "需要的字段;缺省 pe_ttm/pb/total_mv/circ_mv/turnover_rate",
|
|
414
|
+
},
|
|
415
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 5000, "default": 2000},
|
|
416
|
+
},
|
|
417
|
+
"required": ["day"],
|
|
418
|
+
"additionalProperties": False,
|
|
419
|
+
},
|
|
420
|
+
"handler": daily_basic,
|
|
421
|
+
},
|
|
422
|
+
{
|
|
423
|
+
"name": "universe",
|
|
424
|
+
"description": "读取单日证券资格截面:tradable、is_st、is_suspended 等(已叠加隔离状态)。",
|
|
425
|
+
"inputSchema": {
|
|
426
|
+
"type": "object",
|
|
427
|
+
"properties": {
|
|
428
|
+
"day": _date("交易日 YYYY-MM-DD"),
|
|
429
|
+
"fields": {
|
|
430
|
+
"type": "array",
|
|
431
|
+
"items": {"type": "string"},
|
|
432
|
+
"description": "需要的字段;缺省 tradable/is_st/is_suspended",
|
|
433
|
+
},
|
|
434
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 5000, "default": 2000},
|
|
435
|
+
},
|
|
436
|
+
"required": ["day"],
|
|
437
|
+
"additionalProperties": False,
|
|
438
|
+
},
|
|
439
|
+
"handler": universe,
|
|
440
|
+
},
|
|
441
|
+
{
|
|
442
|
+
"name": "trade_calendar",
|
|
443
|
+
"description": "交易日历:覆盖范围;给 day 返回是否交易日与前后交易日;给 start/end 返回区间内的交易日列表。",
|
|
444
|
+
"inputSchema": {
|
|
445
|
+
"type": "object",
|
|
446
|
+
"properties": {
|
|
447
|
+
"day": _date("要判断的日期"),
|
|
448
|
+
"start": _date("区间起始日"),
|
|
449
|
+
"end": _date("区间结束日"),
|
|
450
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 500, "default": 60},
|
|
451
|
+
},
|
|
452
|
+
"additionalProperties": False,
|
|
453
|
+
},
|
|
454
|
+
"handler": trade_calendar,
|
|
455
|
+
},
|
|
456
|
+
{
|
|
457
|
+
"name": "index_daily",
|
|
458
|
+
"description": "读取指数日线(trade_date/open/close)。例如 000300.SH、899050.BJ。",
|
|
459
|
+
"inputSchema": {
|
|
460
|
+
"type": "object",
|
|
461
|
+
"properties": {
|
|
462
|
+
"ts_code": {"type": "string", "description": "指数代码,如 000300.SH"},
|
|
463
|
+
"start": _date("起始交易日(含)"),
|
|
464
|
+
"end": _date("结束交易日(含)"),
|
|
465
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 5000, "default": 2000},
|
|
466
|
+
},
|
|
467
|
+
"required": ["ts_code", "start", "end"],
|
|
468
|
+
"additionalProperties": False,
|
|
469
|
+
},
|
|
470
|
+
"handler": index_daily,
|
|
471
|
+
},
|
|
472
|
+
]
|
|
473
|
+
|
|
474
|
+
BY_NAME: dict[str, dict[str, Any]] = {t["name"]: t for t in TOOLS}
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
# --------------------------------------------------------------------------- JSON-RPC
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _reply(msg_id: Any, result: Any) -> None:
|
|
481
|
+
frame = {"jsonrpc": "2.0", "id": msg_id, "result": result}
|
|
482
|
+
sys.stdout.write(json.dumps(frame, ensure_ascii=False) + "\n")
|
|
483
|
+
sys.stdout.flush()
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _error(msg_id: Any, code: int, message: str) -> None:
|
|
487
|
+
frame = {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}}
|
|
488
|
+
sys.stdout.write(json.dumps(frame, ensure_ascii=False) + "\n")
|
|
489
|
+
sys.stdout.flush()
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _call_tool(params: dict) -> dict:
|
|
493
|
+
name = params.get("name")
|
|
494
|
+
tool = BY_NAME.get(name)
|
|
495
|
+
if tool is None:
|
|
496
|
+
return {"content": [{"type": "text", "text": f"未知工具:{name}"}], "isError": True}
|
|
497
|
+
args = params.get("arguments") or {}
|
|
498
|
+
if not isinstance(args, dict):
|
|
499
|
+
return {"content": [{"type": "text", "text": "arguments 必须是对象"}], "isError": True}
|
|
500
|
+
try:
|
|
501
|
+
value = tool["handler"](args)
|
|
502
|
+
return {"content": [{"type": "text", "text": _json(value)}], "isError": False}
|
|
503
|
+
except subprocess.TimeoutExpired:
|
|
504
|
+
return {"content": [{"type": "text", "text": f"{name} 超时:命令未在限制时间内完成"}], "isError": True}
|
|
505
|
+
except Exception as exc: # 业务异常回填给模型,不中断会话
|
|
506
|
+
log(traceback.format_exc())
|
|
507
|
+
return {"content": [{"type": "text", "text": f"{name} 失败:{type(exc).__name__}: {exc}"}], "isError": True}
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def handle(message: dict) -> None:
|
|
511
|
+
method = message.get("method")
|
|
512
|
+
msg_id = message.get("id")
|
|
513
|
+
is_notification = "id" not in message
|
|
514
|
+
params = message.get("params") or {}
|
|
515
|
+
|
|
516
|
+
if method == "initialize":
|
|
517
|
+
requested = params.get("protocolVersion") or DEFAULT_PROTOCOL
|
|
518
|
+
_reply(
|
|
519
|
+
msg_id,
|
|
520
|
+
{
|
|
521
|
+
"protocolVersion": requested,
|
|
522
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
523
|
+
"serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
|
|
524
|
+
"instructions": (
|
|
525
|
+
"Quantify 量化研究工作区的只读工具集:策略与模拟盘查询、数据健康、"
|
|
526
|
+
"定时任务与推送记录、日线/复权/估值/资格/日历/指数查询。"
|
|
527
|
+
"全部工具无副作用;生产系统的写入与推送不在本服务内。"
|
|
528
|
+
),
|
|
529
|
+
},
|
|
530
|
+
)
|
|
531
|
+
return
|
|
532
|
+
|
|
533
|
+
if is_notification:
|
|
534
|
+
return # notifications/initialized、notifications/cancelled 等无需响应
|
|
535
|
+
|
|
536
|
+
if method == "ping":
|
|
537
|
+
_reply(msg_id, {})
|
|
538
|
+
elif method == "tools/list":
|
|
539
|
+
_reply(
|
|
540
|
+
msg_id,
|
|
541
|
+
{
|
|
542
|
+
"tools": [
|
|
543
|
+
{
|
|
544
|
+
"name": t["name"],
|
|
545
|
+
"description": t["description"],
|
|
546
|
+
"inputSchema": t["inputSchema"],
|
|
547
|
+
"annotations": {"readOnlyHint": True, "destructiveHint": False, "openWorldHint": False},
|
|
548
|
+
}
|
|
549
|
+
for t in TOOLS
|
|
550
|
+
]
|
|
551
|
+
},
|
|
552
|
+
)
|
|
553
|
+
elif method == "tools/call":
|
|
554
|
+
_reply(msg_id, _call_tool(params))
|
|
555
|
+
elif method == "resources/list":
|
|
556
|
+
_reply(msg_id, {"resources": []})
|
|
557
|
+
elif method == "prompts/list":
|
|
558
|
+
_reply(msg_id, {"prompts": []})
|
|
559
|
+
else:
|
|
560
|
+
_error(msg_id, -32601, f"method not found: {method}")
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def main() -> int:
|
|
564
|
+
log(f"starting {SERVER_NAME} {SERVER_VERSION} (python {sys.version.split()[0]})")
|
|
565
|
+
for raw in sys.stdin:
|
|
566
|
+
raw = raw.strip()
|
|
567
|
+
if not raw:
|
|
568
|
+
continue
|
|
569
|
+
try:
|
|
570
|
+
message = json.loads(raw)
|
|
571
|
+
except json.JSONDecodeError as exc:
|
|
572
|
+
log(f"bad frame: {exc}")
|
|
573
|
+
_error(None, -32700, "parse error")
|
|
574
|
+
continue
|
|
575
|
+
try:
|
|
576
|
+
handle(message)
|
|
577
|
+
except Exception as exc: # 任何未捕获异常都要回帧,否则客户端会挂起
|
|
578
|
+
log(traceback.format_exc())
|
|
579
|
+
_error(message.get("id"), -32603, f"{type(exc).__name__}: {exc}")
|
|
580
|
+
log("stdin closed, exiting")
|
|
581
|
+
return 0
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
if __name__ == "__main__":
|
|
585
|
+
sys.exit(main())
|