backend: let a model put a figure in the paper, and set a formula's alignment

Two things the editor gained and MCP could not do, both because the tool layer
had been told about the domain's columns by hand.

**A figure.** Bytes go to MinIO and the sentence keeps a Markdown address, so a
picture is ordinary text — which means the writing tools already carry it, and
the only half a model cannot do is the upload: it has bytes and no way to send
multipart. `image_upload` takes base64 and answers with the URL, the Markdown
and the *sentence object* the editor produces when a picture is dropped in, so a
figure is written by putting that object into `sentences` unchanged. It does not
fetch a URL the caller names: a service inside the cluster that will GET any
address it is handed is an SSRF primitive aimed at everything beside it.

The width argument is the reader's rule or it is refused. `{width=70%}` is
parsed by `frontend/src/utils/rich.ts`, and a value it cannot read is not an
error there — the picture just prints at its natural size. A size that silently
does not apply is worse than a refusal, so the syntax and the range (pixels
1–4000, per cent 1–100) are mirrored in `app/mcp/tools/images.py`, with the
usual comment naming the other side.

`paragraph_text` also had to learn what a figure is: a sentence holding nothing
but an image is a 插图 — the view prints it on its own line with the brackets'
text as its caption — and the text a tool hands back broke lines around a
display formula but not around a picture. Same rule as `figureOf`, same pair of
implementations, same warning about changing both.

**A formula's alignment.** `paper_sentence.formula_align` reached the editor and
the REST API and stopped there: `SentenceSpec` had no such field, so a model that
sent one got a successful call and a centred formula. The column is now declared,
carried through every write path and reported by every read path.

That is the second column lost the same way, so the fix is structural rather
than another two edits. `SENTENCE_FIELDS` is read from
`app.schemas.paper.SentenceInput` instead of written out, the payload is built
by one `sentence_payload()`, and the three append paths spread
`SentenceCreate(**item.model_dump())` rather than copying fields. One edit
remains — declaring the field in `specs.py` — and smoke_mcp.py's first step
compares the two field sets, so forgetting it now fails the suite instead of
losing the field. `sort` is declared too, which it never was: a model that sent
one had it dropped in silence.

smoke_mcp.py: 99 checks to 119. The figure step uploads a real 1x1 GIF (the same
bytes twice, and the key is the same object), writes the returned sentence as it
came back, checks the paragraph prints it alone on its line and that an image
inside a sentence does not break the line, and takes the four refusals — not a
picture, an unparseable size, an out-of-range one, not base64. The alignment step
writes a right-aligned formula, moves the sentence to left on its own, and takes
the paragraph to another position to prove the setting travels with it.

Deployed as v6, and the pod now carries MINIO_ENDPOINT (the in-cluster Service)
plus the two credential keys from the Secret; without them the image tool answers
with the missing variable names and every writing tool still works.
This commit is contained in:
2026-09-24 10:54:27 +08:00
parent eb0f12b8cf
commit ebaf9e558b
13 changed files with 816 additions and 79 deletions
+115 -15
View File
@@ -7,8 +7,8 @@
用 `paragraph_write` / `sentence_update` 微调 → `paper_document` 读回来检查。
- 代码:`backend/app/mcp/`(工具实现)、`backend/scripts/mcp_server.py`(入口)
- 冒烟测试:`backend/scripts/smoke_mcp.py`(真 MCP 客户端跑 99 项检查、覆盖 41/41 个工具,stdio 与 HTTP 都过)
- 工具数量:**41 个**,按 `paper_` / `paragraph_` / `sentence_` / `template_` / `field_` / `reference_` / `reference_tag_` 七组前缀
- 冒烟测试:`backend/scripts/smoke_mcp.py`(真 MCP 客户端跑 119 项检查、覆盖 42/42 个工具,stdio 与 HTTP 都过)
- 工具数量:**42 个**,按 `paper_` / `paragraph_` / `sentence_` / `template_` / `field_` / `reference_` / `reference_tag_` / `image_` 八组前缀
- 协议:MCP 2024-11-05 ~ 2025-11-25(官方 Python SDK `mcp>=2.2,<3` 协商)
- 传输:`stdio`(本地拉起)与 `streamable-http`(远程连接,支持 Bearer 口令),另兼容旧 `sse`
- **已经部署在 k3s 里**:命名空间 `paper-doc`,端点 `http://192.168.1.88:30931/mcp`
@@ -98,12 +98,14 @@ cd /data/project/paper/backend
.venv/bin/python scripts/smoke_mcp.py --url http://127.0.0.1:8931/mcp --token 你的口令 # 连已有的 HTTP 服务
```
同一个套件 **99 项检查**跑两种传输,覆盖 23 个步骤:建论文 → 看骨架 → 按标题写段落 →
同一个套件 **119 项检查**跑两种传输,覆盖 25 个步骤:建论文 → 看骨架 → 按标题写段落 →
定位失败时列出候选标题 → 读段落/追加带引用的句子 → 只改一句 → 删一句 → 整篇一次写入 →
读全文 → 跨论文搜索 → **另起一行**(公式独行、标记开关、搬段落时跟着走)→ **参考文献表**
(一处引用一行、一部文献一条、正文编号与表号同号)→ 搬段落 → 清空段落 → 字段库增删改 →
建/改模板 → 换模板后正文不丢 → 文献库增删改查与批量导入 → 引用守卫(被引用的文献删不掉)→
删模板被拒 → 删论文要确认 → 清理。写真实数据,结束时自己删干净。
(一处引用一行、一部文献一条、正文编号与表号同号)→ **插图**(传图、同一张图只存一份、
独占一行、行内图不断行、格式/尺寸/非 base64 的拒绝)→ **公式对齐**(写入、单独改、跟着搬)→
搬段落 → 清空段落 → 字段库增删改 → 建/改模板 → 换模板后正文不丢 → 文献库增删改查与批量导入 →
引用守卫(被引用的文献删不掉)→ 删模板被拒 → 删论文要确认 → 清理。写真实数据(插图那步还需要
MinIO 可用),结束时自己删干净。
---
@@ -294,11 +296,15 @@ Header: Authorization: Bearer <MCP_HTTP_TOKEN>
| 工具 | 作用 | 关键参数 |
|---|---|---|
| `sentence_list` | 列句子(可只列某段) | `paper_id`、`position?` `heading?` `include_empty?` |
| `sentence_add` | 段尾追加一句(可带引用) | `paper_id`、`content`、`position?` `heading?` `citations?` `line_break_before?` `sort?` |
| `sentence_update` | 改正文 / 改所属段 / 改排序 / 改换行 / 整组换引用 | `paper_id`、`sentence_id`、`content?` `position?` `sort?` `line_break_before?` `citations?` |
| `sentence_add` | 段尾追加一句(可带引用) | `paper_id`、`content`、`position?` `heading?` `citations?` `line_break_before?` `formula_align?` `sort?` |
| `sentence_update` | 改正文 / 改所属段 / 改排序 / 改换行 / 改公式对齐 / 整组换引用 | `paper_id`、`sentence_id`、`content?` `position?` `sort?` `line_break_before?` `formula_align?` `citations?` |
| `sentence_delete` | 删一句(连引用) | `paper_id`、`sentence_id` |
| `sentence_search` | **跨论文搜句子**(保持术语一致) | `keyword`、`paper_id?` `limit?` |
一句能带的字段就是这一组(`content`、`sort`、`line_break_before`、`formula_align`、`citations`,
外加写插图用的图片 Markdown)。**MCP 的工具 schema 必须声明全部字段**,`smoke_mcp.py` 第一步就查这件事——
少一个字段意味着模型能写、工具会静默丢掉,写作调用"成功"而内容不对。
#### 另起一行:公式、分条列举、作者行
一段是**它的句子连排**出来的,所以"不是散文的行"要自己开口。方式是在句子对象上加
@@ -316,16 +322,29 @@ Header: Authorization: Bearer <MCP_HTTP_TOKEN>
三条规则:
1. **换行顶掉分隔符,不是叠加。** 新行本身已经把两句分开了,再加一个空格会让下一行空一格。
2. **display 公式(`$$…$$` 或 `\[…\]`)自己独占一行,不必标。** 论文页面就是这么排的,
`paper_document` 的 `text` 也这么排——两处必须一致,所以模型不要去猜"这里要不要加标记"。
行内公式(`$…$`)不算,它本来就在句子里。
2. **独占一行的东西不必标。** display 公式(`$$…$$` 或 `\[…\]`)和"整句只有一张图"的插图
都自己占一行——论文页面就是这么排的,`paper_document` 的 `text` 也这么排,两处必须一致,
所以模型不要去猜"这里要不要加标记"。行内公式(`$…$`)和夹在句子中间的图不算。
3. **"请读一遍这一段"时看得到换行。** `paragraph_get` / `paper_document` 返回的 `text` 里换行就是真的换行符;
`sentence_list` 每句还带 `line_break_before` 字段,所以搬句子之前能看出哪几句是另起的行。
`sentence_list` 每句还带 `line_break_before` 与 `formula_align` 字段,所以搬句子之前能看出
哪几句是另起的行、公式是怎么摆的。
`text` + `split` 那种整块写法也可以带 `line_break_before`,但它只作用于**切出来的第一句**——
"这一块从新的一行开始"。块里其余几句是接着它的,不是各自另起一行;否则一个换行写了三行的段落
就会被切成三行。
#### 公式怎么摆:center / left / right
含 display 公式的句子还带 `formula_align`,默认 `center`,可给 `left` 或 `right`:
```jsonc
{"content": "$$ \\Delta I = f(\\tau) $$", "line_break_before": true, "formula_align": "left"}
```
它是**每一句公式自己的排版**,不是标题(字段库)的设置:一段里合法的组合就是"先居中一个公式、
后面接一个右对齐的续行"。句号后的编号(`\tag{1}`)始终靠右,三种对齐都一样。
只对含 display 公式的句子有意义——纯文本句子给了它也不会变样,但它照样会被原样存下来。
### 3.4 模板 templates(5 个)
模板就是结构:论文的标题是**每次渲染现读模板**得到的,所以改模板会影响所有用它的论文,
@@ -417,6 +436,45 @@ Header: Authorization: Bearer <MCP_HTTP_TOKEN>
| `reference_tag_update` | 改名/颜色/备注 | `tag_id`、`name?` `color?` `note?` `clear_note?` |
| `reference_tag_delete` | 删标签(文献不受影响)| `tag_ids`(int 或数组)|
### 3.8 插图 images(1 个)
图片不进数据库:**字节放 MinIO,句子只留地址**,写成 Markdown。
| 工具 | 作用 | 关键参数 |
|---|---|---|
| `image_upload` | 传一张图,返回可写进句子的 Markdown 与那个句子对象 | `data_base64`、`caption?` `filename?` `width?` |
```jsonc
{"name": "image_upload", "arguments": {
"data_base64": "iVBORw0KGgo…", // 也可以直接给 data:image/png;base64,…
"caption": "图 3 惯性—冲量相空间", // 不给就用 filename 的主干
"width": "70%" // 或 400px;不传按原尺寸(不超过栏宽)
}}
// → {"key": "2026/09/9f8c1a4b7e2d0c33.png",
// "url": "/api/images/2026/09/9f8c1a4b7e2d0c33.png",
// "markdown": "![图 3 惯性—冲量相空间](/api/images/2026/09/9f8c1a4b7e2d0c33.png){width=70%}",
// "sentence": {"content": "![图 3 …](…){width=70%}", "line_break_before": true, "formula_align": "center"}}
```
拿回来的 `sentence` **原样**放进 `paper_write` / `paragraph_write` / `sentence_add` 的 `sentences` 里就是一张插图,
不需要再拼字符串——`content` 与网页端"插入图片"写出来的是同一个(都走 `markdown_for`)。
三条规则:
1. **键就是内容的摘要。** 同一张图传两次是**同一个对象**(不是两份),地址永远指不到别的图上,
所以 `url` 可以带一年不变的缓存头。文件名、`Content-Type` 都只是说法,格式按字节判断。
2. **只收 PNG / JPEG / GIF / WebP,SVG 明确不收**(从本站点提供上传的 SVG 等于存储型 XSS)。
超过 20 MB 会被拒,并告诉你先压缩。
3. **句子只有一张图 = 插图**(独占一行、居中、方括号里的字当图注);图夹在一句话中间就是行内小图。
`paragraph_get` / `paper_document` 的 `text` 按同一条规则断行,图以它存储的 Markdown 原样印在自己的行上——
文本画不出图片,而地址是"哪一张图"的唯一答案,读回来还能原样搬走。
`width` 写法宽容(`70%`、`70 %`、`{width=70%}`、`w=400px` 都收),含义严格:像素 1–4000、百分比 1–100,
超出会被拒绝而不是默默忽略——网页端读不懂的尺寸会退回原尺寸,那等于写了个不生效的值。
存储没配好(缺 `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY`)时,这个工具报 503 语义的说明,
**写作路径照常**:论文、段落、句子、模板、文献都不碰对象存储。
## 4. 典型用法
### 4.1 AI 写完,整篇一次灌进去(主推)
@@ -551,6 +609,36 @@ display 公式不用担心——它本来就独占一行;但分条列举、作
删文献时如果它还被引用,会被拒绝并报出「(N 处引用)」——先按上面第 4 步找到那些句子、
用 `sentence_update(citations=[])` 摘掉引用,再删。
### 4.8 插图:把一张图放进论文
```jsonc
// 1) 传图(给字节的 base64;模型手里是文件路径时先读出字节)
{"name": "image_upload", "arguments": {
"data_base64": "iVBORw0KGgo…", "caption": "图 3 惯性—冲量相空间", "width": "70%"
}}
// → {"key": "…", "url": "/api/images/2026/09/….png",
// "sentence": {"content": "![图 3 …](…){width=70%}", "line_break_before": true, "formula_align": "center"}}
// 2) 原样写进去(也可以塞进 paper_write 的 paragraphs[].sentences 里)
{"name": "sentence_add", "arguments": {
"paper_id": 96, "heading": "4.4 技术惯性量化",
"content": "![图 3 惯性—冲量相空间](/api/images/2026/09/….png){width=70%}",
"line_break_before": true
}}
// 3) 读回来确认它在自己的一行上
{"name": "paragraph_get", "arguments": {"paper_id": 96, "heading": "4.4 技术惯性量化"}}
```
要点:
- **同一张图传两次是同一个对象**:键是内容的 SHA-256,所以重复上传不会堆出副本,也不会换地址。
- **图注写在方括号里**,网页端显示为图下那行字;`width` 不给就按原尺寸(最多不超过栏宽)。
- 想让图**跟着一句话走**(行内小图,而不是独占一行的插图),把它拼进那句话里就行:
`"回归结果见 ![小图](/api/images/…) 的右panel。"`。
- MCP 只做上传这一半。图是**通过 API(`/api/images/…`)读**的:句子存的是同源相对路径,
局域网和以后的公网地址都能用,桶也不必公开。
## 5. 返回值与错误约定
- **成功**:`content[0].text` 是一段 JSON 字符串。例如 `paper_list` 返回
@@ -600,10 +688,18 @@ REST 和 MCP 同时生效。这让"网页里看到的"和"AI 写进去的"永远
**换行是"要求"出来的,不是猜出来的。** `line_break_before` 只在被明确写出来时才设:
`text` 里换了一行不等于要另起一行(模型把一段话折成三行是常事),所以工具不从这里推断。
唯一的例外是 display 公式——页面渲染和 `paper_document` 的 `text` 都让它独占一行,
这条规则在 `frontend/src/utils/math.ts` 和 `app/mcp/support.py` 里各写了一遍
唯一的例外是 display 公式和"整句只有一张图"的插图——页面渲染和 `paper_document` 的 `text`
都让它们独占一行。这两条规则在 `frontend/src/utils/rich.ts` 和 `app/mcp/support.py` 里各写了一遍
(一个 TypeScript、一个 Python),**改一处必须改另一处**,否则网页和工具结果就会在
"哪一行是哪一行"上不一致。冒烟测试里有一项专门盯着它。
"哪一行是哪一行"上不一致。冒烟测试里各有一项盯着它们。
**句子的字段从 payload schema 里读出来,不手抄。** `app/mcp/support.py` 的
`SENTENCE_FIELDS` 直接取自 `app.schemas.paper.SentenceInput`,写入路径用
`SentenceCreate(**item.model_dump())` 整体展开。这条改动是有代价换来的:`line_break_before`
和 `formula_align` 两次都是"后端加了列、网页能用、REST 能存,MCP 静默丢掉"——
调用成功、字段不见,是最难查的一类错。现在只剩一处需要人工同步:在
`app/mcp/specs.py` 里声明字段,而 `smoke_mcp.py` 的第一步会比对
`SentenceInput` 与 `SentenceSpec` 的字段集合,漏了就红。
**删除要二次确认。** `paper_delete` 第一次调用必定被拒并说明后果,
因为一次误删会连带整篇的句子和引用,而这在 MCP 里没有回收站。
@@ -636,6 +732,8 @@ REST 和 MCP 同时生效。这让"网页里看到的"和"AI 写进去的"永远
| 删文献 | `DELETE /api/references/{id}` | `reference_delete` |
| 谁引用了它 | `GET /api/references/{id}/citations` | `reference_citations` |
| 文献标签 | `/api/reference-tags` | `reference_tag_*` |
| 传图 | `POST /api/images`(multipart)| `image_upload`(base64)|
| 看图 | `GET /api/images/{key}` | —(句子里的地址由页面/浏览器直接取)|
MCP 独有:`paper_outline`(写前看骨架)、`paper_write` / `paper_write_text`(批量写入)、
`paragraph_move`、`sentence_search`。
@@ -653,4 +751,6 @@ MCP 独有:`paper_outline`(写前看骨架)、`paper_write` / `paper_write
| 工具调用超时 | DSH/Codex 侧加大 `toolCallTimeoutMs` / `tool_timeout_sec`;`paper_write_text` 写整篇会慢一些 |
| k3s 里连不上 | `kubectl -n paper-doc get pods` 看是否 Ready;`/readyz` 返回 503 说明 TiDB 不通(`kubectl -n paper-doc logs deploy/paper-doc-mcp`) |
| 改了代码但行为没变 | 镜像 tag 没换:`imagePullPolicy: IfNotPresent` 会继续用节点上缓存的同名镜像,换个 tag 重新构建 |
| `image_upload` 报"图片存储还没有配置好" | 缺 `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY`。本机看 `backend/.env`;集群里看 `paper-doc-config`(端点是 `http://minio.minio.svc.cluster.local:9000`,不是宿主机的 `:30090`)与 `paper-doc-secrets` |
| `image_upload` 报"连不上对象存储" | MinIO 不通或凭证不对:`kubectl -n minio get pods`,再用同一组凭证 `mc`/`aws s3` 试一次 `PutObject` |
| 日志里出现非 JSON 的 stdout 输出 | 不要在这个进程里 `print`——stdio 传输下会污染协议流(本项目的诊断都走 stderr) |