ht32-code-mcp 0.1.1__tar.gz → 0.1.3__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.
- ht32_code_mcp-0.1.3/DEPLOY.md +300 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/PKG-INFO +1 -1
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/ht32-code-mcp-update.md +37 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/pyproject.toml +1 -1
- ht32_code_mcp-0.1.3/src/ht32_code_mcp/exporter.py +277 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/src/ht32_code_mcp/server.py +124 -7
- ht32_code_mcp-0.1.3/src/ht32_code_mcp/usage.py +138 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/tests/test_tools.py +190 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/uv.lock +1 -1
- ht32_code_mcp-0.1.1/src/ht32_code_mcp/exporter.py +0 -128
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/.gitignore +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/.gitkeep +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/README.md +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/e2e_scenario_a.py +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/e2e_scenario_b.py +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/smoke_stdio.py +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/src/ht32_code_mcp/__init__.py +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/src/ht32_code_mcp/__main__.py +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/src/ht32_code_mcp/index.py +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/src/ht32_code_mcp/knowledge.py +0 -0
- {ht32_code_mcp-0.1.1 → ht32_code_mcp-0.1.3}/tests/conftest.py +0 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
# MCP Server 部署指南(ht32-code)
|
|
2
|
+
|
|
3
|
+
HT32 Code MCP Server 的部署、配置与排错。代码在 `.work/mcp-server/`,已发布到 PyPI(`ht32-code-mcp`)。
|
|
4
|
+
|
|
5
|
+
## 部署信息
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
MCP Server 地址(Streamable HTTP): https://mcp.s621.work/ht32-code
|
|
9
|
+
PyPI 包: https://pypi.org/project/ht32-code-mcp/(uvx ht32-code-mcp 即可运行)
|
|
10
|
+
Bundle 下载地址: https://mcp.s621.work/ht32-bundles/<token>.zip
|
|
11
|
+
本地 Gitea: http://100.66.1.6:3000/S621/ht32-code.git
|
|
12
|
+
MCP Server 代码: .work/mcp-server/
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## 部署链路
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
PyPI 发布包 → 1Panel 原生 MCP 管理(类型 uvx,启动命令 uvx ht32-code-mcp,输出类型 streamableHttp)
|
|
19
|
+
→ supergateway 包装 stdio 为 Streamable HTTP(stateful)
|
|
20
|
+
→ OpenResty 暴露公网
|
|
21
|
+
├─ /ht32-code/* → MCP 协议端点(反向代理到容器)
|
|
22
|
+
└─ /ht32-bundles/* → bundle zip 静态目录(P1-3)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
代码默认走 `stdio`(`MCP_TRANSPORT` 未设置时),supergateway 负责 stdio→Streamable HTTP 转换。
|
|
26
|
+
与 ht32-wiki 同构:SSE 无心跳会被 OpenResty 空闲切断,故走 streamableHttp stateful。
|
|
27
|
+
|
|
28
|
+
## 关键配置
|
|
29
|
+
|
|
30
|
+
1Panel MCP 表单:
|
|
31
|
+
|
|
32
|
+
- 类型:`uvx`
|
|
33
|
+
- 启动命令:`uvx ht32-code-mcp`(**必须带 uvx 前缀**,容器里没装裸命令)
|
|
34
|
+
- 输出类型:`streamableHttp`
|
|
35
|
+
- 流式传输路径:`/ht32-code`(切输出类型后是**新字段**,默认空,必须手填;必填校验)
|
|
36
|
+
- 协议版本:`2025-06-18`(1Panel 预填默认值,勿动;仅用于 supergateway 对下游 stdio 的 auto-init)
|
|
37
|
+
- 镜像:`supercorp/supergateway:next-uvx`(**必须覆盖默认的 `:uvx`**——见下方踩坑)
|
|
38
|
+
- 参数:`--stateful --sessionTimeout 3600000`
|
|
39
|
+
- 环境变量:`CODE_ROOT=/app/code`
|
|
40
|
+
- 挂载:`/opt/ht32-code:/app/code`(**不用加 `:ro`**——`index/code_index.json`
|
|
41
|
+
已 gitignore 且容器内可能需重建,只读会阻断;容器路径不能有前导空格,否则 `invalid mount path`)
|
|
42
|
+
|
|
43
|
+
### 镜像 tag 踩坑(2026-09-20)
|
|
44
|
+
|
|
45
|
+
默认镜像 `supercorp/supergateway:uvx` 构建时解析到旧版
|
|
46
|
+
`@modelcontextprotocol/sdk`(LATEST_PROTOCOL_VERSION=2025-06-18),新版客户端
|
|
47
|
+
(Trae 发 `2025-11-25`)initialize 直接被拒:`Bad Request: Unsupported protocol
|
|
48
|
+
version`。根因是 supergateway 3.4.3 对 SDK 声明的是浮动依赖 `^1.18.2`,镜像构建
|
|
49
|
+
日期决定行为;`next-uvx`(4.0.0-rc.4)将 SDK **精确锁定 1.30.0**,无此问题。
|
|
50
|
+
|
|
51
|
+
## 云端 zip 下载通道(P1-3,0.1.2+)
|
|
52
|
+
|
|
53
|
+
`export_project_bundle` 有两种交付形态,**由服务端环境变量决定,调用方无需判断**:
|
|
54
|
+
|
|
55
|
+
| 模式 | 触发条件 | 行为 |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| 云端 zip | `BUNDLE_DIR` 与 `BUNDLE_BASE_URL` **同时非空** | 打包到 `BUNDLE_DIR`,返回 `<BUNDLE_BASE_URL>/<token>.zip` + SHA256 + 过期时间 |
|
|
58
|
+
| 本地目录 | 二者任一为空(默认) | 物化到 `out_dir`(须为空目录/不存在) |
|
|
59
|
+
|
|
60
|
+
### 环境变量
|
|
61
|
+
|
|
62
|
+
| 变量 | 默认 | 说明 |
|
|
63
|
+
|------|------|------|
|
|
64
|
+
| `BUNDLE_DIR` | 空(= 关闭云端模式) | 容器内 bundle 输出目录,须可写 |
|
|
65
|
+
| `BUNDLE_BASE_URL` | 空(= 关闭云端模式) | 公网下载前缀,如 `https://mcp.s621.work/ht32-bundles` |
|
|
66
|
+
| `BUNDLE_TTL_SECONDS` | `3600` | zip 有效期;每次 export 前顺带清理过期 zip |
|
|
67
|
+
|
|
68
|
+
非数字的 `BUNDLE_TTL_SECONDS` 会静默回退默认值,不报错。
|
|
69
|
+
|
|
70
|
+
### 实现要点
|
|
71
|
+
|
|
72
|
+
- **token**:`secrets.token_urlsafe(24)`(192 bit 熵),文件名即 token;不可枚举、不可猜测
|
|
73
|
+
- **物化在系统临时目录**(`tempfile.mkdtemp`)而非 bundle 目录——bundle 目录里只出现
|
|
74
|
+
最终 zip,中途失败的半成品不会暴露成可下载文件
|
|
75
|
+
- **清理**:`sweep_expired()` 在每次 export 时按 mtime 删除超期 `*.zip`;
|
|
76
|
+
进程崩溃遗留的临时目录不影响交付(不在 bundle 目录内)
|
|
77
|
+
- **TTL 到点不主动删**:靠下次 export 的 sweep 或 P1-2 定时脚本清理;过期后
|
|
78
|
+
重新调用工具即可拿新 URL
|
|
79
|
+
|
|
80
|
+
### 服务器侧落地(3 步)
|
|
81
|
+
|
|
82
|
+
本部署的 OpenResty 是**容器化**的(容器名 `1Panel-openresty-ih7J`),
|
|
83
|
+
已挂载 `WEBSITE_DIR=/opt/1panel/www` → 容器内 `/www`。
|
|
84
|
+
因此 bundle 目录直接落在网站根目录树下,**OpenResty 的 volumes 一行都不用改**——
|
|
85
|
+
两个容器通过宿主机上的同一目录交换文件:
|
|
86
|
+
|
|
87
|
+
```
|
|
88
|
+
宿主机 /opt/1panel/www/sites/mcp.s621.work/index/ht32-bundles/ (站点 root 目录下 + /ht32-bundles)
|
|
89
|
+
├─ code-mcp 容器看到 /app/bundles
|
|
90
|
+
└─ OpenResty 容器看到 /www/sites/mcp.s621.work/index/ht32-bundles
|
|
91
|
+
公网 URL https://mcp.s621.work/ht32-bundles/<token>.zip
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
站点「网站目录」显示 root = `/opt/1panel/www/sites/mcp.s621.work/index`,
|
|
95
|
+
bundle 放其下子目录即被当作静态文件直接访问。
|
|
96
|
+
|
|
97
|
+
**第 1 步:宿主机建 bundle 目录**
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
mkdir -p /opt/1panel/www/sites/mcp.s621.work/index/ht32-bundles
|
|
101
|
+
chmod 755 /opt/1panel/www/sites/mcp.s621.work/index/ht32-bundles
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**第 2 步:1Panel 给 code-mcp 容器补挂载与环境变量**
|
|
105
|
+
|
|
106
|
+
| 配置项 | 值 |
|
|
107
|
+
|--------|-----|
|
|
108
|
+
| 挂载 | `/opt/1panel/www/sites/mcp.s621.work/index/ht32-bundles:/app/bundles`(**不要加 `:ro`,需可写**) |
|
|
109
|
+
| 环境变量 | `BUNDLE_DIR=/app/bundles` |
|
|
110
|
+
| 环境变量 | `BUNDLE_BASE_URL=https://mcp.s621.work/ht32-bundles` |
|
|
111
|
+
| 环境变量 | `BUNDLE_TTL_SECONDS=3600`(可选,默认即 3600) |
|
|
112
|
+
|
|
113
|
+
完整配置(含现有项):
|
|
114
|
+
|
|
115
|
+
```
|
|
116
|
+
类型: uvx
|
|
117
|
+
启动命令: uvx ht32-code-mcp
|
|
118
|
+
输出类型: streamableHttp
|
|
119
|
+
流式传输路径:/ht32-code
|
|
120
|
+
协议版本: 2025-06-18
|
|
121
|
+
镜像: supercorp/supergateway:next-uvx
|
|
122
|
+
参数: --stateful --sessionTimeout 3600000
|
|
123
|
+
环境变量: CODE_ROOT=/app/code
|
|
124
|
+
BUNDLE_DIR=/app/bundles
|
|
125
|
+
BUNDLE_BASE_URL=https://mcp.s621.work/ht32-bundles
|
|
126
|
+
挂载: /opt/ht32-code:/app/code
|
|
127
|
+
/opt/1panel/www/sites/mcp.s621.work/index/ht32-bundles:/app/bundles ← 宿主机路径,非容器内路径
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
**第 3 步:OpenResty 无需任何配置**
|
|
131
|
+
|
|
132
|
+
站点 root = `/opt/1panel/www/sites/mcp.s621.work/index`,映射到容器内
|
|
133
|
+
`/www/sites/mcp.s621.work/index`。bundle 目录落在这个 root 之下子目录,
|
|
134
|
+
静态文件天然可访问,**不用建反向代理、不用手写 location、不用改 compose**。
|
|
135
|
+
|
|
136
|
+
> **不要为 bundles 建反向代理条目**:1Panel 反代 UI 表达不了静态 location
|
|
137
|
+
> (后端代理地址必填,而静态目录没有后端)。若建了且后端留空,1Panel 生成的
|
|
138
|
+
> location 会抢走 `/ht32-bundles/` 却不知从哪读文件 → 404。已有此类条目请删除。
|
|
139
|
+
|
|
140
|
+
> **静态 location 无需 `proxy_*` 指令**:文件由 nginx 读盘直接返回,不用
|
|
141
|
+
> `proxy_pass`,也不用 `proxy_read_timeout`——这与 code 的代理 location 形态不同属正常。
|
|
142
|
+
|
|
143
|
+
> **权限**:1Panel 站点要求 `index` 目录下所有文件/目录属主与属组为 `1000`(见
|
|
144
|
+
> 「网站目录」页提示,PHP 容器环境)。nginx worker 需可读该目录;zip 文件 644 /
|
|
145
|
+
> 目录 755 正常可读。若验证时拿 403,先查属主属组与 SELinux 上下文。
|
|
146
|
+
|
|
147
|
+
重载(改了容器挂载或环境变量时需重建 code-mcp;仅改文件无需重载 nginx):
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
docker exec 1Panel-openresty-ih7J nginx -t
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### 验证生效
|
|
154
|
+
|
|
155
|
+
1. 调 `get_code_version`,应出现:
|
|
156
|
+
|
|
157
|
+
```
|
|
158
|
+
云端 zip 下载:启用(TTL 3600s,https://mcp.s621.work/ht32-bundles)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
仍显示「未配置」→ 环境变量没注入成功(查变量名 / 容器是否重建)。
|
|
162
|
+
|
|
163
|
+
2. 调 `export_project_bundle(chip="HT32F52352")`,应返回:
|
|
164
|
+
|
|
165
|
+
```
|
|
166
|
+
下载 URL:https://mcp.s621.work/ht32-bundles/<token>.zip
|
|
167
|
+
有效期:3600 秒(至 ...)
|
|
168
|
+
大小:1.53 MB(455 文件)
|
|
169
|
+
SHA256:...
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
3. 浏览器/curl 拉该 URL:应得约 1.5 MB zip;`sha256sum` 与报告一致;
|
|
173
|
+
解压后 455 文件、`project/MDK_ARMv5/ht32f5-template.uvprojx` 在,UV4 编译 0E0W。
|
|
174
|
+
|
|
175
|
+
4. 确认 `ls /opt/1panel/www/sites/mcp.s621.work/index/ht32-bundles` 只有 `*.zip`(无残留临时目录)。
|
|
176
|
+
|
|
177
|
+
## 反馈与用量日志(P1-5,0.1.3+)
|
|
178
|
+
|
|
179
|
+
两条通道写入同一目录、按 UTC 日期分文件(JSON Lines):
|
|
180
|
+
|
|
181
|
+
| 通道 | 触发 | 记录内容 |
|
|
182
|
+
|------|------|----------|
|
|
183
|
+
| `usage_YYYY-MM-DD.jsonl` | **服务端自动**(middleware 拦截所有工具调用) | 工具名、参数原文(剔除 `limit`/`max_length`/`out_dir`)、耗时、成败、错误、客户端 session |
|
|
184
|
+
| `feedback_YYYY-MM-DD.jsonl` | **Agent 主动**(`submit_feedback` 工具) | 语义性问题:答错 / 知识库缺口 / 模板缺陷,含 `issue_type`、`model_id`、`tools_called` |
|
|
185
|
+
|
|
186
|
+
自动通道保证调用事实完整(不依赖 Agent 配合);反馈通道补 middleware
|
|
187
|
+
判断不了的语义问题。`issue_type` 枚举:`wrong_api` / `missing_info` /
|
|
188
|
+
`wrong_path` / `export_defect` / `unclear` / `other`。
|
|
189
|
+
|
|
190
|
+
### 环境变量
|
|
191
|
+
|
|
192
|
+
| 变量 | 默认 | 说明 |
|
|
193
|
+
|------|------|------|
|
|
194
|
+
| `CODE_LOG_DIR` | 空(= **整体关闭**,本地开发默认不落盘) | 日志写入目录,须可写 |
|
|
195
|
+
|
|
196
|
+
> **隐私**:参数按原文记录,`query`/`question` 可能含用户项目信息。
|
|
197
|
+
> 该目录只应挂在受控服务器上,**不要提交进仓库**(定时脚本是
|
|
198
|
+
> `git reset --hard` 镜像模式,写进仓库也会被覆盖丢失)。
|
|
199
|
+
|
|
200
|
+
### 服务器侧落地(2 步)
|
|
201
|
+
|
|
202
|
+
**第 1 步:宿主机建日志目录**
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
mkdir -p /opt/ht32-code-logs
|
|
206
|
+
chmod 755 /opt/ht32-code-logs
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
**第 2 步:1Panel 给 code-mcp 容器补挂载与环境变量**
|
|
210
|
+
|
|
211
|
+
| 配置项 | 值 |
|
|
212
|
+
|--------|-----|
|
|
213
|
+
| 挂载 | `/opt/ht32-code-logs:/app/logs`(**不要加 `:ro`,需可写**) |
|
|
214
|
+
| 环境变量 | `CODE_LOG_DIR=/app/logs` |
|
|
215
|
+
|
|
216
|
+
完整配置(含现有项):
|
|
217
|
+
|
|
218
|
+
```
|
|
219
|
+
类型: uvx
|
|
220
|
+
启动命令: uvx ht32-code-mcp
|
|
221
|
+
输出类型: streamableHttp
|
|
222
|
+
流式传输路径:/ht32-code
|
|
223
|
+
协议版本: 2025-06-18
|
|
224
|
+
镜像: supercorp/supergateway:next-uvx
|
|
225
|
+
参数: --stateful --sessionTimeout 3600000
|
|
226
|
+
环境变量: CODE_ROOT=/app/code
|
|
227
|
+
BUNDLE_DIR=/app/bundles
|
|
228
|
+
BUNDLE_BASE_URL=https://mcp.s621.work/ht32-bundles
|
|
229
|
+
CODE_LOG_DIR=/app/logs
|
|
230
|
+
挂载: /opt/ht32-code:/app/code
|
|
231
|
+
/opt/1panel/www/sites/mcp.s621.work/index/ht32-bundles:/app/bundles
|
|
232
|
+
/opt/ht32-code-logs:/app/logs
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### 验证生效
|
|
236
|
+
|
|
237
|
+
1. 调 `get_code_version`,应出现 `用量日志:启用(/app/logs)`。
|
|
238
|
+
仍显示「未配置」→ 环境变量没注入(查变量名 / 容器是否重建)。
|
|
239
|
+
|
|
240
|
+
2. 随便调几个工具,然后看日志:
|
|
241
|
+
|
|
242
|
+
```bash
|
|
243
|
+
tail -3 /opt/ht32-code-logs/usage_$(date -u +%Y-%m-%d).jsonl
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
3. 按日期分析需求分布(示例:统计被请求的芯片型号,指导 P2-1 排优先级):
|
|
247
|
+
|
|
248
|
+
```bash
|
|
249
|
+
grep -h export_project_bundle /opt/ht32-code-logs/usage_*.jsonl \
|
|
250
|
+
| python3 -c "
|
|
251
|
+
import sys, json, collections
|
|
252
|
+
c = collections.Counter()
|
|
253
|
+
for l in sys.stdin:
|
|
254
|
+
c.update([json.loads(l)['args'].get('chip', '?')])
|
|
255
|
+
for k, v in c.most_common():
|
|
256
|
+
print(f'{v:5d} {k}')
|
|
257
|
+
"
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
4. 清理策略由定时同步脚本第 7 步负责(`LOG_KEEP_DAYS=30`,与同步日志同口径)。
|
|
261
|
+
|
|
262
|
+
## PyPI 包发布流程
|
|
263
|
+
|
|
264
|
+
```bash
|
|
265
|
+
# token 在 ht32-code 根目录 .env 的 UV_PUBLISH_TOKEN
|
|
266
|
+
uv lock && uv build && uv publish
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
发布后同步 `VERSION` 文件末行:`MCP Server: <版本>(deployed, PyPI, <日期>)`。
|
|
270
|
+
|
|
271
|
+
## 踩过的坑
|
|
272
|
+
|
|
273
|
+
### 1. 云端跑的是 PyPI 包,不是 /opt 仓库(P0-1)
|
|
274
|
+
|
|
275
|
+
- **症状**:改了仓库代码、云端 MCP 行为不变
|
|
276
|
+
- **根因**:`uvx ht32-code-mcp` 从 PyPI 拉包,`/opt/ht32-code` 只是被检索的数据源
|
|
277
|
+
- **修复**:改代码必须**发版 + 重建容器**,改仓库文件本身不生效
|
|
278
|
+
|
|
279
|
+
### 2. 索引只读挂载
|
|
280
|
+
|
|
281
|
+
- **症状**:容器启动报索引无法写入/重建失败
|
|
282
|
+
- **根因**:`/opt/ht32-code:/app/code:ro` 时 `index/code_index.json` 不可写
|
|
283
|
+
- **修复**:挂载去掉 `:ro`
|
|
284
|
+
|
|
285
|
+
### 3. 镜像 tag 导致协议版本被拒
|
|
286
|
+
|
|
287
|
+
见上方「镜像 tag 踩坑」。
|
|
288
|
+
|
|
289
|
+
## 当前部署状态
|
|
290
|
+
|
|
291
|
+
| # | 任务 | 说明 | 状态 |
|
|
292
|
+
|---|------|------|------|
|
|
293
|
+
| 3.1 | 7 个 MCP 工具实现 | `.work/mcp-server/src/ht32_code_mcp/`(FastMCP) | ✅ |
|
|
294
|
+
| 3.2 | 工具级测试 | `pytest` 36 用例全绿 | ✅ |
|
|
295
|
+
| 3.3 | PyPI 发布(hatchling) | `ht32-code-mcp` 0.1.2(2026-09-21,含 bundle 通道) | ✅ |
|
|
296
|
+
| 3.4 | 云端 git clone + 挂载 | `/opt/ht32-code:/app/code` | ✅ |
|
|
297
|
+
| 3.5 | 1Panel 部署(uvx + supergateway → streamableHttp stateful,镜像 next-uvx) | `https://mcp.s621.work/ht32-code` | ✅ |
|
|
298
|
+
| 3.6 | OpenResty 超时修复(`proxy_read_timeout 3600s`) | 修复 60s 空闲断连;2026-09-21 复核两端空闲 100s 后调用仍 200,未被 1Panel 回退 | ✅ |
|
|
299
|
+
| 3.7 | 云端 zip 下载通道(P1-3) | 服务器侧已上线:下载 1608157 字节 / SHA256 一致 / 解压 455 文件 / UV4 0E0W | ✅ |
|
|
300
|
+
| 3.8 | 定时同步脚本含 bundle 清理(P1-2) | `ht32-code-mcp-update.md` 第 6 步 `find … -mmin +60 -delete` | ✅ |
|
|
@@ -26,6 +26,16 @@
|
|
|
26
26
|
|
|
27
27
|
# 日志:按天归档 /opt/ht32-code-sync/ht32-code-sync-YYYYMMDD.log,自动清理 30 天前的旧日志
|
|
28
28
|
|
|
29
|
+
# - 顺带清理 bundle 下载目录的过期 zip(P1-3)
|
|
30
|
+
|
|
31
|
+
# (server 每次 export 前也会 sweep 一次,此处为兜底:
|
|
32
|
+
|
|
33
|
+
# 若一段时间无人调用 export,TTL 过期的 zip 不会被那次 sweep 清掉)
|
|
34
|
+
|
|
35
|
+
# - 顺带清理超期的用量日志 / 反馈 JSONL(P1-5)
|
|
36
|
+
|
|
37
|
+
# (保留 LOG_KEEP_DAYS 天,与同步日志同口径)
|
|
38
|
+
|
|
29
39
|
# ============================================================
|
|
30
40
|
|
|
31
41
|
set -e
|
|
@@ -37,6 +47,15 @@ LOG_FILE="$LOG_DIR/ht32-code-sync-$(date '+%Y%m%d').log"
|
|
|
37
47
|
LOG_KEEP_DAYS=30
|
|
38
48
|
INDEX_FILE="$CODE_DIR/.work/mcp-server/index/code_index.json"
|
|
39
49
|
|
|
50
|
+
# bundle 目录(站点 root 下子目录,OpenResty 直接静态提供)与保留时长
|
|
51
|
+
|
|
52
|
+
BUNDLE_DIR="/opt/1panel/www/sites/mcp.s621.work/index/ht32-bundles"
|
|
53
|
+
BUNDLE_TTL_MIN=60
|
|
54
|
+
|
|
55
|
+
# 用量日志 / 反馈目录(1Panel 挂载到容器 /app/logs)
|
|
56
|
+
|
|
57
|
+
CODE_LOG_DIR="/opt/ht32-code-logs"
|
|
58
|
+
|
|
40
59
|
# 日志目录(不存在则创建)
|
|
41
60
|
|
|
42
61
|
mkdir -p "$LOG_DIR"
|
|
@@ -101,4 +120,22 @@ fi
|
|
|
101
120
|
|
|
102
121
|
find "$LOG_DIR" -name "ht32-code-sync-*.log" -mtime +$LOG_KEEP_DAYS -delete 2>/dev/null || true
|
|
103
122
|
|
|
123
|
+
# 6. 清理 bundle 目录中超过 TTL 的 zip(兜底,与 BUNDLE_TTL_SECONDS 保持一致)
|
|
124
|
+
|
|
125
|
+
if [ -d "$BUNDLE_DIR" ]; then
|
|
126
|
+
SWEPT=$(find "$BUNDLE_DIR" -maxdepth 1 -name "*.zip" -mmin +$BUNDLE_TTL_MIN -print -delete 2>/dev/null | wc -l)
|
|
127
|
+
log "bundle 清理:删除 $SWEPT 个过期 zip"
|
|
128
|
+
else
|
|
129
|
+
log "bundle 目录不存在,跳过清理:$BUNDLE_DIR"
|
|
130
|
+
fi
|
|
131
|
+
|
|
132
|
+
# 7. 清理超期的用量日志 / 反馈(同样保留 LOG_KEEP_DAYS 天)
|
|
133
|
+
|
|
134
|
+
if [ -d "$CODE_LOG_DIR" ]; then
|
|
135
|
+
OLD_LOGS=$(find "$CODE_LOG_DIR" -maxdepth 1 \( -name "usage_*.jsonl" -o -name "feedback_*.jsonl" \) -mtime +$LOG_KEEP_DAYS -print -delete 2>/dev/null | wc -l)
|
|
136
|
+
log "用量日志清理:删除 $OLD_LOGS 个过期文件"
|
|
137
|
+
else
|
|
138
|
+
log "用量日志目录不存在,跳过清理:$CODE_LOG_DIR"
|
|
139
|
+
fi
|
|
140
|
+
|
|
104
141
|
log "本次同步完成"
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""export_project_bundle:从模板组装自包含可编译 Keil 工程(本地目录 / 云端 zip)。
|
|
2
|
+
|
|
3
|
+
模板自带全量官方库树(library/),因此导出只需复制模板 + 按 devices.json
|
|
4
|
+
参数化 uvprojx(Device / C 宏 / 汇编宏 / system / startup 文件指向)。
|
|
5
|
+
|
|
6
|
+
两种交付形态:
|
|
7
|
+
- 本地目录模式:物化到 out_dir(本地 stdio 调试用)。
|
|
8
|
+
- 云端 zip 模式:物化到临时目录 → 打包成 <token>.zip 放进 bundle 目录 →
|
|
9
|
+
由 nginx 静态目录按随机 token + TTL 提供下载(服务器与用户电脑解耦)。
|
|
10
|
+
|
|
11
|
+
参数化依据:raw/templates/ht32f5-keil/devices.json(device/cdef/adef/sys/startup)。
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import dataclasses
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
import secrets
|
|
20
|
+
import shutil
|
|
21
|
+
import tempfile
|
|
22
|
+
import time
|
|
23
|
+
import zipfile
|
|
24
|
+
from datetime import datetime
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
# 模板中默认型号(HT32F52352)的 system / startup 文件名主干,导出时按目标型号替换
|
|
28
|
+
_TEMPLATE_SYS_STEM = "system_ht32f5xxxx_01"
|
|
29
|
+
_TEMPLATE_STARTUP_STEM = "startup_ht32f5xxxx_01"
|
|
30
|
+
|
|
31
|
+
# 云端 zip 产物默认有效期(秒)
|
|
32
|
+
DEFAULT_BUNDLE_TTL = 3600
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ExportError(Exception):
|
|
36
|
+
"""导出失败(型号未知 / 源文件缺失 / 目标目录非空等)。"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclasses.dataclass
|
|
40
|
+
class Materialized:
|
|
41
|
+
"""一次物化的结果(本地/云端共用)。"""
|
|
42
|
+
|
|
43
|
+
device: str
|
|
44
|
+
entry: dict
|
|
45
|
+
sys_c: Path
|
|
46
|
+
sys_h: Path
|
|
47
|
+
startup: Path
|
|
48
|
+
files: int
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclasses.dataclass
|
|
52
|
+
class Bundle:
|
|
53
|
+
"""云端 zip 产物信息。"""
|
|
54
|
+
|
|
55
|
+
token: str
|
|
56
|
+
path: Path
|
|
57
|
+
size: int
|
|
58
|
+
sha256: str
|
|
59
|
+
expires_at: float
|
|
60
|
+
materialized: Materialized
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _read_text(path: Path) -> str:
|
|
64
|
+
return path.read_text(encoding="utf-8", errors="replace")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _sha256(path: Path) -> str:
|
|
68
|
+
h = hashlib.sha256()
|
|
69
|
+
with open(path, "rb") as f:
|
|
70
|
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
71
|
+
h.update(chunk)
|
|
72
|
+
return h.hexdigest()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _fmt_time(ts: float) -> str:
|
|
76
|
+
return datetime.fromtimestamp(ts).astimezone().strftime("%Y-%m-%d %H:%M:%S %z")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _rmtree(path: Path) -> None:
|
|
80
|
+
"""删除目录树;Windows 上句柄释放有延迟,失败重试几次后再放弃。
|
|
81
|
+
|
|
82
|
+
放弃也无害:临时目录在系统 temp 下,容器重启即清空。
|
|
83
|
+
"""
|
|
84
|
+
for attempt in range(3):
|
|
85
|
+
if not path.exists():
|
|
86
|
+
return
|
|
87
|
+
try:
|
|
88
|
+
shutil.rmtree(path)
|
|
89
|
+
return
|
|
90
|
+
except OSError:
|
|
91
|
+
if attempt == 2:
|
|
92
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
93
|
+
else:
|
|
94
|
+
time.sleep(0.2 * (attempt + 1))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def sweep_expired(bundle_dir: Path, ttl_seconds: int) -> int:
|
|
98
|
+
"""清理过期 zip 产物,返回清理条数。
|
|
99
|
+
|
|
100
|
+
惰性清理:每次打包前扫一遍即可,无需常驻定时任务。
|
|
101
|
+
"""
|
|
102
|
+
if not bundle_dir.is_dir():
|
|
103
|
+
return 0
|
|
104
|
+
now = time.time()
|
|
105
|
+
swept = 0
|
|
106
|
+
for p in bundle_dir.glob("*.zip"):
|
|
107
|
+
try:
|
|
108
|
+
if now - p.stat().st_mtime > ttl_seconds:
|
|
109
|
+
p.unlink()
|
|
110
|
+
swept += 1
|
|
111
|
+
except OSError:
|
|
112
|
+
continue # 并发/权限竞争时跳过,不影响本次打包
|
|
113
|
+
return swept
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class ProjectExporter:
|
|
117
|
+
def __init__(self, code_root: Path) -> None:
|
|
118
|
+
self.root = Path(code_root)
|
|
119
|
+
self.template_dir = self.root / "raw" / "templates" / "ht32f5-keil"
|
|
120
|
+
# 模板自带全量官方库树,system/startup 在此校验
|
|
121
|
+
self.lib_device = (self.template_dir / "library" / "Device"
|
|
122
|
+
/ "Holtek" / "HT32F5xxxx" / "Source")
|
|
123
|
+
|
|
124
|
+
# ------------------------------------------------------- 本地目录模式
|
|
125
|
+
def export(self, chip: str, out_dir: str) -> str:
|
|
126
|
+
out = Path(out_dir).expanduser().resolve()
|
|
127
|
+
if out.exists() and any(out.iterdir()):
|
|
128
|
+
raise ExportError(f"目标目录非空,拒绝覆盖:{out}(请指定新目录或先清空)")
|
|
129
|
+
m = self._materialize(chip, out)
|
|
130
|
+
return dir_report(out, m)
|
|
131
|
+
|
|
132
|
+
# ------------------------------------------------------- 云端 zip 模式
|
|
133
|
+
def export_zip(self, chip: str, bundle_dir: str, ttl_seconds: int) -> Bundle:
|
|
134
|
+
bdir = Path(bundle_dir).expanduser().resolve()
|
|
135
|
+
bdir.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
sweep_expired(bdir, ttl_seconds)
|
|
137
|
+
|
|
138
|
+
token = secrets.token_urlsafe(24)
|
|
139
|
+
# 物化在系统临时目录:bundle 目录只暴露最终 zip,不半成品公开
|
|
140
|
+
tmp = Path(tempfile.mkdtemp(prefix="ht32-bundle-"))
|
|
141
|
+
try:
|
|
142
|
+
m = self._materialize(chip, tmp)
|
|
143
|
+
zip_path = bdir / f"{token}.zip"
|
|
144
|
+
_zip_tree(tmp, zip_path)
|
|
145
|
+
finally:
|
|
146
|
+
_rmtree(tmp)
|
|
147
|
+
return Bundle(token=token, path=zip_path, size=zip_path.stat().st_size,
|
|
148
|
+
sha256=_sha256(zip_path),
|
|
149
|
+
expires_at=time.time() + ttl_seconds, materialized=m)
|
|
150
|
+
|
|
151
|
+
# ------------------------------------------------------------ 物化
|
|
152
|
+
def _materialize(self, chip: str, out: Path) -> Materialized:
|
|
153
|
+
if not self.template_dir.is_dir():
|
|
154
|
+
raise ExportError(f"模板目录不存在:{self.template_dir}")
|
|
155
|
+
device, entry = self._resolve_device(chip)
|
|
156
|
+
|
|
157
|
+
# 预检模板内目标型号所需源文件(先验证后落盘,失败不产生半成品)
|
|
158
|
+
sys_c = self.lib_device / entry["sys"]
|
|
159
|
+
sys_h = sys_c.parent.parent / "Include" / (sys_c.stem + ".h")
|
|
160
|
+
startup = self.lib_device / "ARM" / entry["startup"]
|
|
161
|
+
missing = [str(p) for p in (sys_c, sys_h, startup) if not p.is_file()]
|
|
162
|
+
if missing:
|
|
163
|
+
raise ExportError("模板 library/ 缺少所需源文件:\n- " + "\n- ".join(missing))
|
|
164
|
+
|
|
165
|
+
# 复制模板树(含全量官方库,导出即自包含)
|
|
166
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
shutil.copytree(self.template_dir, out, dirs_exist_ok=True)
|
|
168
|
+
|
|
169
|
+
# 参数化 uvprojx:Device / C 宏 / 汇编宏 / system / startup 指向
|
|
170
|
+
uvprojx = out / "project" / "MDK_ARMv5" / "ht32f5-template.uvprojx"
|
|
171
|
+
text = _read_text(uvprojx)
|
|
172
|
+
text = re.sub(r"(<Device>)[^<]*(</Device>)", rf"\g<1>{device}\g<2>", text, count=1)
|
|
173
|
+
text = _replace_define(text, "USE_HT32_DRIVER", entry["cdef"])
|
|
174
|
+
text = _replace_define(text, "USE_HT32_CHIP", entry["adef"])
|
|
175
|
+
text = text.replace(_TEMPLATE_SYS_STEM, sys_c.stem)
|
|
176
|
+
text = text.replace(_TEMPLATE_STARTUP_STEM, startup.stem)
|
|
177
|
+
with open(uvprojx, "w", encoding="utf-8", newline="") as f:
|
|
178
|
+
f.write(text)
|
|
179
|
+
|
|
180
|
+
files = sum(1 for p in out.rglob("*") if p.is_file())
|
|
181
|
+
return Materialized(device=device, entry=entry, sys_c=sys_c, sys_h=sys_h,
|
|
182
|
+
startup=startup, files=files)
|
|
183
|
+
|
|
184
|
+
# ------------------------------------------------------------ 辅助
|
|
185
|
+
def _resolve_device(self, chip: str) -> tuple[str, dict]:
|
|
186
|
+
dj = self.template_dir / "devices.json"
|
|
187
|
+
if not dj.is_file():
|
|
188
|
+
raise ExportError(f"模板型号参数表缺失:{dj}")
|
|
189
|
+
meta = json.loads(dj.read_text(encoding="utf-8"))
|
|
190
|
+
want = chip.strip().upper()
|
|
191
|
+
for d in meta.get("devices", []):
|
|
192
|
+
if d.get("device", "").upper() == want:
|
|
193
|
+
return d["device"], d # 重名取首条(官方板级变体)
|
|
194
|
+
# 宽松匹配:型号主体包含(HT32F52352 含于 HT32F52352_SK 场景已由上面精确处理)
|
|
195
|
+
for d in meta.get("devices", []):
|
|
196
|
+
if want in d.get("device", "").upper():
|
|
197
|
+
return d["device"], d
|
|
198
|
+
names = [d.get("device", "") for d in meta.get("devices", [])][:20]
|
|
199
|
+
raise ExportError(
|
|
200
|
+
f"型号 '{chip}' 不在模板参数表(共 {meta.get('count', '?')} 个型号)。\n"
|
|
201
|
+
f"可用型号(前 20):{', '.join(names)}…\n"
|
|
202
|
+
"完整清单:get_file('raw/templates/ht32f5-keil/devices.json') 或 get_project_manifest()"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _zip_tree(src: Path, zip_path: Path) -> None:
|
|
207
|
+
"""把 src 下整棵树打成 zip(文件相对 src 定位,故解压即得工程根结构)。"""
|
|
208
|
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
|
|
209
|
+
for p in sorted(src.rglob("*")):
|
|
210
|
+
if p.is_file():
|
|
211
|
+
zf.write(p, p.relative_to(src).as_posix())
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _spec_lines(m: Materialized) -> list[str]:
|
|
215
|
+
"""两种模式共用的工程参数说明行。"""
|
|
216
|
+
return [
|
|
217
|
+
f"目标芯片:{m.device}",
|
|
218
|
+
"工程文件:project/MDK_ARMv5/ht32f5-template.uvprojx(已按型号参数化)",
|
|
219
|
+
f"C 宏(Cads):{m.entry['cdef']}",
|
|
220
|
+
f"汇编宏(Aads):{m.entry['adef']}",
|
|
221
|
+
f"system:library/Device/Holtek/HT32F5xxxx/Source/{m.sys_c.name}"
|
|
222
|
+
f"(+ Include/{m.sys_h.name})",
|
|
223
|
+
f"startup:library/Device/Holtek/HT32F5xxxx/Source/ARM/{m.startup.name}",
|
|
224
|
+
"libcfg:library/HT32F5xxxx_Driver/inc/(ht32f5xxxx_lib.h 按 C 宏自动引入)",
|
|
225
|
+
]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
_FOLLOWUP = [
|
|
229
|
+
"1. Keil MDK 打开 project/MDK_ARMv5/ht32f5-template.uvprojx"
|
|
230
|
+
"(需 Holtek HT32_DFP pack ≥1.0.67)",
|
|
231
|
+
"2. 如需精确 IROM/IRAM 内存布局,在 Options → Device 重新选择该型号由 DFP 刷新",
|
|
232
|
+
"3. 基线编译验证(UV4 命令行复核 0 Error 0 Warning)",
|
|
233
|
+
]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def dir_report(out: Path, m: Materialized) -> str:
|
|
237
|
+
lines = [
|
|
238
|
+
f"自包含 Keil 工程已导出:{out}",
|
|
239
|
+
*_spec_lines(m),
|
|
240
|
+
f"文件总数:{m.files}",
|
|
241
|
+
"",
|
|
242
|
+
"目录结构:",
|
|
243
|
+
" component/ 共享组件层(基础模板为空,按项目增补)",
|
|
244
|
+
" library/ CMSIS / Device / Driver / USBD(全量官方库,模板自带)",
|
|
245
|
+
" utilities/ ht32_board 板级支持",
|
|
246
|
+
" project/ MDK_ARMv5(Keil 工程文件)+ Src_USER(用户文件)",
|
|
247
|
+
"",
|
|
248
|
+
"后续步骤:",
|
|
249
|
+
*_FOLLOWUP,
|
|
250
|
+
]
|
|
251
|
+
return "\n".join(lines)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def bundle_report(b: Bundle, base_url: str, ttl_seconds: int) -> str:
|
|
255
|
+
url = f"{base_url.rstrip('/')}/{b.path.name}"
|
|
256
|
+
lines = [
|
|
257
|
+
"自包含 Keil 工程已打包(云端 zip 下载):",
|
|
258
|
+
f"下载 URL:{url}",
|
|
259
|
+
f"有效期:{ttl_seconds} 秒(至 {_fmt_time(b.expires_at)})",
|
|
260
|
+
f"大小:{b.size / 1048576:.2f} MB({b.materialized.files} 文件)",
|
|
261
|
+
f"SHA256:{b.sha256}",
|
|
262
|
+
*_spec_lines(b.materialized),
|
|
263
|
+
"",
|
|
264
|
+
"下载解压:zip 内文件直接位于根(project/ library/ utilities/ component/),"
|
|
265
|
+
"解压到目标工程目录即可;过期后重新调用本工具获取新 URL。",
|
|
266
|
+
"后续步骤:",
|
|
267
|
+
*_FOLLOWUP,
|
|
268
|
+
]
|
|
269
|
+
return "\n".join(lines)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _replace_define(text: str, anchor: str, new_value: str) -> str:
|
|
273
|
+
"""替换 uvprojx 中包含 anchor 的 <Define> 行内容(Cads/Aads 各一条)。"""
|
|
274
|
+
pattern = re.compile(r"(<Define>)[^<]*" + re.escape(anchor) + r"[^<]*(</Define>)")
|
|
275
|
+
if not pattern.search(text):
|
|
276
|
+
raise ExportError(f"uvprojx 中未找到含 {anchor} 的 <Define>,模板结构可能已变化")
|
|
277
|
+
return pattern.sub(rf"\g<1>{new_value}\g<2>", text, count=1)
|