From 9f2bbe50eb81d9b32da8c517955db376f831065f Mon Sep 17 00:00:00 2001 From: govin Date: Wed, 23 Sep 2026 11:49:39 +0800 Subject: [PATCH] =?UTF-8?q?backend:=20let=20a=20model=20ask=20for=20a=20li?= =?UTF-8?q?ne=20break,=20and=20read=20the=20=E5=8F=82=E8=80=83=E6=96=87?= =?UTF-8?q?=E7=8C=AE=20list=20back?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The paper model gained two things while the MCP layer was not looking, and both were invisible from a tool call. `paper_sentence.line_break_before` — the flag a paragraph needs so a formula, a list of items or an author line can start a line of its own — was not in `SentenceSpec`, and `sentence_inputs` dropped it on the floor: a model could write the field, watch the call succeed, and get prose back. It is now part of every write path (`paragraph_write`, `paper_write`, `sentence_add`, `sentence_update`) and of every read path (`sentence_row` reports it, so a model can see the lines before moving one). Two bugs fell out of doing it properly: * `paragraph_move` rebuilt its sentences without the flag, so moving a paragraph that carried a formula turned it into prose. It also passed the *source* sorts through, which interleaved the moved sentences with the target's own — the merged paragraph read in an order neither writer wrote. Both are fixed; the tool now appends, as its own description promised. * `document_text` printed a formula run into the sentence before it. The paper view renders `$$…$$` as a block, so the seam rules are now the same in both places, with a comment on each side naming the other. `PaperDocumentRead.references` and `reference_style` — the per-work 参考文献 list the backend now assembles and formats — were reachable over REST but not over MCP: `paper_document(format="json")` returned citations and nothing to point them at, even though docs/MCP.md already described the list. The json form now carries the entries (index, reference_id, text, missing, citations) and the style name, so a model quotes the bibliography instead of assembling a second one out of the same fields. smoke_mcp.py grows from 76 checks to 99 over two new steps — the line-break step pins the display-formula rule, the marker toggle and the moving case; the bibliography step cites one work from two sentences and checks that the text, the entry and both markers agree on one number. --- backend/app/mcp/specs.py | 19 ++ backend/app/mcp/support.py | 63 ++++++- backend/app/mcp/tools/papers.py | 26 ++- backend/app/mcp/tools/paragraphs.py | 24 ++- backend/app/mcp/tools/sentences.py | 25 ++- backend/scripts/smoke_mcp.py | 281 +++++++++++++++++++++++++++- deploy/README.md | 6 +- deploy/build-mcp-image.sh | 6 +- deploy/k8s/10-paper-doc-mcp.yaml | 6 +- docs/MCP.md | 58 +++++- docs/OVERVIEW.md | 3 +- 11 files changed, 483 insertions(+), 34 deletions(-) diff --git a/backend/app/mcp/specs.py b/backend/app/mcp/specs.py index c42a7d7..31943bf 100644 --- a/backend/app/mcp/specs.py +++ b/backend/app/mcp/specs.py @@ -45,6 +45,16 @@ class SentenceSpec(BaseModel): """One sentence, optionally carrying citations.""" content: Annotated[str, Field(description="句子正文;空白会被折叠成一行")] + line_break_before: Annotated[ + bool, + Field( + description=( + "这一句前面另起一行(默认 false)。正文被句子拼成一段,所以公式、" + "分条列举、作者行这类不是散文的行要在这里开口;break 会顶掉句间的空格," + "不会多印一个空格。display 公式($$…$$ 或 \\[…\\])本来就独占一行,不必设这个" + ) + ), + ] = False citations: Annotated[ list[CitationSpec], Field(description="这一段引用了哪些文献"), @@ -59,6 +69,15 @@ class TextSpec(BaseModel): SplitMode, Field(description="切句方式:line 一行一句(默认)/ sentence 按句号切 / paragraph 整段一句"), ] = "line" + line_break_before: Annotated[ + bool, + Field( + description=( + "这一整块从新的一行开始(默认 false);只作用于切出来的第一句," + "因为切出来的其余几句是接着它的,不是各自另起一行" + ) + ), + ] = False citations: Annotated[ list[CitationSpec], Field(description="整段共用的引用"), diff --git a/backend/app/mcp/support.py b/backend/app/mcp/support.py index 5861026..33115ec 100644 --- a/backend/app/mcp/support.py +++ b/backend/app/mcp/support.py @@ -256,6 +256,10 @@ def sentence_row(sentence: Any, *, separator: str | None = None) -> dict: "position": sentence.paper_template_filed_sort, "sort": sentence.sort, "content": sentence.content, + # Reported so a writer can see where the lines fall before deciding to + # move one: a paragraph read back without this flag looks like prose + # that happens to have no spaces in it. + "line_break_before": sentence.line_break_before, "citations": [citation_row(item) for item in sentence.citations], } if separator is not None: @@ -277,6 +281,21 @@ def paragraph_row(paragraph: ParagraphRead, *, preview: int = 80) -> dict: } +#: A formula the paper view sets on a line of its own: ``$$…$$`` or ``\[…\]``. +#: +#: This is the same rule as ``hasDisplayMath`` in ``frontend/src/utils/math.ts``, +#: written twice because the view is TypeScript and this is Python. The two must +#: agree, or a tool result and the page a writer is looking at would disagree +#: about where the lines are — which is the one thing this module exists to +#: prevent. Change one, change the other. +_DISPLAY_MATH = re.compile(r"\$\$[\s\S]+?\$\$|\\\[[\s\S]+?\\\]") + + +def _is_display(sentence: Any) -> bool: + """Whether this sentence is a display formula — a block, not a run of text.""" + return bool(_DISPLAY_MATH.search(sentence.content)) + + def paragraph_text( paragraph: ParagraphRead, *, @@ -289,6 +308,14 @@ def paragraph_text( belongs at each seam, so a tool result and the paper view agree on where the spaces go. Nothing here adds spacing of its own. + A line break is printed where the model asked for one, and around a display + formula — the paper view renders ``$$…$$`` as a block, so the lines on + either side of it are line boundaries there too. A break *replaces* the + separator rather than joining it: the new line already separates the two + sentences, and a space as well would indent the line below by one blank. + The first sentence of a paragraph is never preceded by a break, because + there is nothing above it to break from. + A marker's number comes from ``index_by_citation`` — the citation's *work* number as the whole document assigned it, not its position in this sentence — so what is printed in the text matches the 参考文献 list it points at. Read @@ -296,8 +323,15 @@ def paragraph_text( falls back to the citation's place in the sentence. """ parts: list[str] = [] + previous_block = False for sentence in paragraph.sentences: - parts.append(sentence.separator_before + sentence.content) + block = _is_display(sentence) + if parts and (sentence.line_break_before or block or previous_block): + parts.append("\n") + else: + parts.append(sentence.separator_before) + parts.append(sentence.content) + previous_block = block if citations and sentence.citations: numbers = [ str( @@ -592,6 +626,8 @@ def sentence_inputs(items: Sequence[Any], *, default_split: str = "line") -> lis * ``"A sentence."`` — the common case; * ``{"content": "...", "citations": [{"quote": "...", "reference_id": 3}]}``; + * ``{"content": "$$ y = ax + b $$", "line_break_before": true}`` — a block + that starts a line of its own; * ``{"text": "one\\ntwo", "split": "line"}`` — a block to be cut. Every path ends in :class:`~app.schemas.paper.SentenceInput`, so the @@ -621,15 +657,34 @@ def sentence_inputs(items: Sequence[Any], *, default_split: str = "line") -> lis ) for citation in (item.get("citations") or []) ] + line_break = bool(item.get("line_break_before", False)) if item.get("content") is not None: - out.append(SentenceInput(content=str(item["content"]), citations=citations)) + out.append( + SentenceInput( + content=str(item["content"]), + line_break_before=line_break, + citations=citations, + ) + ) continue if item.get("text") is not None: mode = item.get("split") or default_split - for piece in split_text(str(item["text"]), mode): - out.append(SentenceInput(content=piece, citations=citations)) + pieces = split_text(str(item["text"]), mode) + for offset, piece in enumerate(pieces): + # A break asked for on a *block* belongs to its first sentence: + # "this block starts a new line". The pieces after it are + # separated by whatever the split found, and flagging them too + # would turn a paragraph the writer wrapped across three lines + # into three lines of the paper. + out.append( + SentenceInput( + content=piece, + line_break_before=line_break and offset == 0, + citations=citations, + ) + ) continue fail("句子对象需要有 content 或 text 字段") diff --git a/backend/app/mcp/tools/papers.py b/backend/app/mcp/tools/papers.py index b61edad..21e2531 100644 --- a/backend/app/mcp/tools/papers.py +++ b/backend/app/mcp/tools/papers.py @@ -248,7 +248,7 @@ def register(server: MCPServer) -> None: bool, Field(description="是否带上引用标记与参考文献列表") ] = True, ) -> str: - """读整篇论文:按模板顺序输出全文(含引用编号和参考文献)。""" + """读整篇论文:按模板顺序输出全文(含引用编号、参考文献表与换行)。""" with s.session() as db: paper = s.paper_or_fail(db, paper_id) document = paper_crud.build_document(db, paper) @@ -270,6 +270,8 @@ def register(server: MCPServer) -> None: for paragraph in document.paragraphs if include_empty or paragraph.sentences ] + # One row per *place* in the text, each carrying the number of + # the work it cites — the number the marker in the text shows. payload["citations"] = [ { "index": item.index, @@ -279,6 +281,24 @@ def register(server: MCPServer) -> None: } for item in document.citations ] + # The 参考文献 list as it prints: one entry per work, already + # formatted by the server, so a model quotes the bibliography + # rather than assembling a second one out of the same fields. + # It is reported even when it is empty, because "this paper + # cites nothing yet" is an answer. + payload["references"] = [ + { + "index": entry.index, + "reference_id": entry.reference_id, + "text": entry.text, + "missing": entry.missing, + # The ids of the places that cite it; the rows + # themselves are in citations above. + "citations": [row.id for row in entry.citations], + } + for entry in document.references + ] + payload["reference_style"] = document.reference_style if document.warnings: payload["warnings"] = document.warnings return s.dumps(payload) @@ -291,7 +311,8 @@ def register(server: MCPServer) -> None: Field( description=( "要写的段落数组。每段用 heading(如 “1. Introduction”)或 position 指定," - "正文放 sentences(字符串数组或带 citations 的对象数组)," + "正文放 sentences(字符串数组或带 citations 的对象数组," + "要另起一行的公式或条目加 line_break_before: true)," "或放 text + split 让服务端切句" ) ), @@ -324,6 +345,7 @@ def register(server: MCPServer) -> None: SentenceCreate( paper_template_filed_sort=position, content=item.content, + line_break_before=item.line_break_before, citations=item.citations, sort=item.sort, ), diff --git a/backend/app/mcp/tools/paragraphs.py b/backend/app/mcp/tools/paragraphs.py index 2524252..6476e30 100644 --- a/backend/app/mcp/tools/paragraphs.py +++ b/backend/app/mcp/tools/paragraphs.py @@ -74,7 +74,7 @@ def register(server: MCPServer) -> None: str | None, Field(description="段落标题,如 “2. Methods”") ] = None, ) -> str: - """读一个段落:拼好的正文、逐句内容与 id、引用、段间分隔符。""" + """读一个段落:拼好的正文、逐句内容与 id、引用、段间分隔符与换行。""" with s.session() as db: paper = s.paper_or_fail(db, paper_id) field_sort = s.resolve_position(paper, position=position, heading=heading) @@ -109,7 +109,13 @@ def register(server: MCPServer) -> None: ] = None, sentences: Annotated[ list[SentenceItem] | None, - Field(description="句子数组:字符串、{content, citations} 或 {text, split}"), + Field( + description=( + "句子数组:字符串、{content, citations} 或 {text, split}。" + "要某一句另起一行(公式、分条列举、作者行),用对象形式加上 " + "line_break_before: true" + ) + ), ] = None, text: Annotated[ str | None, Field(description="整段文本;与 sentences 二选一") @@ -199,7 +205,18 @@ def register(server: MCPServer) -> None: s.fail(f"第 {source} 段没有内容可以搬") inputs = [ - SentenceInput(content=row.content, sort=row.sort, citations=list(row.citations)) + SentenceInput( + content=row.content, + # ``sort`` is deliberately left unset so that + # :func:`app.crud.paper.replace_paragraph` numbers the block + # from the *target's* current maximum. Carrying the old + # numbers over instead would interleave the two paragraphs — + # the moved sentence with ``sort=1`` would sort against the + # target's own sentence with ``sort=1`` — and the merge would + # read in an order neither writer wrote. + line_break_before=row.line_break_before, + citations=list(row.citations), + ) for row in rows ] paper_crud.replace_paragraph( @@ -258,6 +275,7 @@ def _write( SentenceCreate( paper_template_filed_sort=field_sort, content=item.content, + line_break_before=item.line_break_before, citations=item.citations, sort=item.sort, ), diff --git a/backend/app/mcp/tools/sentences.py b/backend/app/mcp/tools/sentences.py index 16ebffb..2b72d93 100644 --- a/backend/app/mcp/tools/sentences.py +++ b/backend/app/mcp/tools/sentences.py @@ -85,6 +85,15 @@ def register(server: MCPServer) -> None: citations: Annotated[ list[CitationSpec] | None, Field(description="这句引用了哪些文献") ] = None, + line_break_before: Annotated[ + bool, + Field( + description=( + "这一句前面另起一行(默认 false):公式、分条列举、作者行用得上。" + "break 会顶掉句间的空格" + ) + ), + ] = False, sort: Annotated[ int | None, Field(description="段内位置;不传则排在段尾") ] = None, @@ -99,6 +108,7 @@ def register(server: MCPServer) -> None: SentenceCreate( paper_template_filed_sort=field_sort, content=content, + line_break_before=line_break_before, citations=_citations(citations or []), sort=sort, ), @@ -123,13 +133,23 @@ def register(server: MCPServer) -> None: sort: Annotated[ int | None, Field(description="段内排序值;不传则不动") ] = None, + line_break_before: Annotated[ + bool | None, + Field(description="这一句是否另起一行;不传则不动,false 表示取消换行"), + ] = None, citations: Annotated[ list[CitationSpec] | None, Field(description="引用整组替换;传 [] 表示清空引用"), ] = None, ) -> str: - """修改一句话的正文、所属段落、排序或引用(引用是整体替换)。""" - if content is None and position is None and sort is None and citations is None: + """修改一句话的正文、所属段落、排序、换行或引用(引用是整体替换)。""" + if ( + content is None + and position is None + and sort is None + and line_break_before is None + and citations is None + ): s.fail("没有给出任何要修改的内容") with s.session() as db: @@ -143,6 +163,7 @@ def register(server: MCPServer) -> None: content=content, paper_template_filed_sort=position, sort=sort, + line_break_before=line_break_before, citations=None if citations is None else _citations(citations), ), ) diff --git a/backend/scripts/smoke_mcp.py b/backend/scripts/smoke_mcp.py index 0f461c5..6d35fa3 100644 --- a/backend/scripts/smoke_mcp.py +++ b/backend/scripts/smoke_mcp.py @@ -152,7 +152,9 @@ async def run(url: str | None = None, token: str | None = None) -> int: async def _run(url: str | None = None, token: str | None = None) -> int: template_id, outline = pick_template() - check("a template with fields exists", len(outline) >= 3, f"got {len(outline)}") + # Four headings, because the line-break and bibliography steps below move one + # paragraph onto a fourth; with fewer, they would have nowhere to write. + check("a template with four fields exists", len(outline) >= 4, f"got {len(outline)}") first = outline[0]["name"] second = outline[1]["name"] @@ -592,12 +594,277 @@ async def _run(url: str | None = None, token: str | None = None) -> int: for row in paragraph["sentences"] ), ) + check( + "it names the citation style the entries are printed in", + structured["reference_style"] == "springer", + str(structured.get("reference_style")), + ) + # Step 13 rewrote every paragraph, so the citation step 9 wrote is gone + # and this paper cites nothing: the 参考文献 list is reported as empty + # rather than left out, because "this cites nothing yet" is an answer. + check( + "and reports the 参考文献 list as empty when nothing is cited", + structured["references"] == [], + json.dumps(structured["references"], ensure_ascii=False), + ) print("\n15. search across papers") found = await call(session, "sentence_search", keyword="正文写在标题下面", paper_id=paper["id"]) check("the search finds what was written", found["total"] >= 1, str(found["total"])) - print("\n16. move a paragraph, then clear the one it moved onto") + print("\n16. the writer asks for a line break") + # A paragraph is its sentences run together, so a formula, a list of + # items or an author line has to say where the lines are. A *display* + # formula does not have to: the paper view sets one on a line of its own + # by definition, and the text a tool hands back has to agree with the + # page the writer is looking at, or the two disagree about the lines. + prose = outline[2] + await call( + session, + "paper_write", + paper_id=paper["id"], + paragraphs=[ + { + "heading": prose["name"], + "sentences": [ + "本段说明公式的来历。", + {"content": "$$ E = mc^2 $$"}, + {"content": "其中 c 为光速。", "line_break_before": True}, + ], + } + ], + ) + written = await call( + session, "paragraph_get", paper_id=paper["id"], heading=prose["name"] + ) + check( + "the flag is stored per sentence", + [row["line_break_before"] for row in written["sentences"]] + == [False, False, True], + json.dumps(written["sentences"], ensure_ascii=False), + ) + check( + "a formula takes its own line unasked, and a flagged sentence too", + written["text"] == "本段说明公式的来历。\n$$ E = mc^2 $$\n其中 c 为光速。", + repr(written["text"]), + ) + check( + "and the flag replaces the separator rather than joining it", + "\n " not in written["text"], + repr(written["text"]), + ) + + whole = await call(session, "paper_document", paper_id=paper["id"]) + check( + "the whole document prints it the same way", + "本段说明公式的来历。\n$$ E = mc^2 $$\n其中 c 为光速。" in whole["text"], + repr(whole["text"][-260:]), + ) + + added = await call( + session, + "sentence_add", + paper_id=paper["id"], + heading=prose["name"], + content="另一条列举。", + line_break_before=True, + ) + check( + "sentence_add can ask for one as well", + added["sentence"]["line_break_before"] is True, + json.dumps(added["sentence"], ensure_ascii=False), + ) + + # Toggled on the sentence that follows the prose, not the one that + # follows the formula: the formula is a block, so the sentence after it + # starts a line whatever its flag says, and a check written on that one + # would pass for the wrong reason. + joined = added["sentence"]["id"] + off = await call( + session, + "sentence_update", + paper_id=paper["id"], + sentence_id=joined, + line_break_before=False, + ) + check( + "the break can be taken off again", + off["sentence"]["line_break_before"] is False, + json.dumps(off, ensure_ascii=False), + ) + rejoined = await call( + session, "paragraph_get", paper_id=paper["id"], heading=prose["name"] + ) + check( + "and the two sentences run on as one line", + "\n另一条列举。" not in rejoined["text"] + and "其中 c 为光速。另一条列举。" in rejoined["text"], + repr(rejoined["text"]), + ) + check( + "while the line after the formula stays broken, flag or no flag", + "\n其中 c 为光速。" in rejoined["text"], + repr(rejoined["text"]), + ) + await call( + session, + "sentence_update", + paper_id=paper["id"], + sentence_id=joined, + line_break_before=True, + ) + relined = await call( + session, "paragraph_get", paper_id=paper["id"], heading=prose["name"] + ) + check( + "asking for it again puts the line back", + "\n另一条列举。" in relined["text"], + repr(relined["text"]), + ) + + moved_texts = [row["content"] for row in written["sentences"]] + [ + added["sentence"]["content"] + ] + await call( + session, + "paragraph_move", + paper_id=paper["id"], + heading=prose["name"], + target_heading=outline[3]["name"], + ) + landed = await call( + session, "paragraph_get", paper_id=paper["id"], heading=outline[3]["name"] + ) + # Matched by content rather than by id: a move rewrites the rows, so the + # ids the source paragraph had do not survive it. Citations are rebuilt + # the same way, which is why they come back attached to the new rows. + flag_of = {row["content"]: row["line_break_before"] for row in landed["sentences"]} + check( + "a paragraph carries its line breaks when it moves", + [flag_of.get(text) for text in moved_texts] == [False, False, True, True], + f"moved={moved_texts} reads back as " + f"{[flag_of.get(text) for text in moved_texts]} out of " + f"{json.dumps(landed['sentences'], ensure_ascii=False)}", + ) + check( + "and it lands after the target's own sentences, as the tool says", + [row["content"] for row in landed["sentences"]][-len(moved_texts):] + == moved_texts, + json.dumps([row["content"] for row in landed["sentences"]], ensure_ascii=False), + ) + + print("\n17. the 参考文献 list is printed, not assembled by the client") + # Step 10 deleted the reference this run made, so the bibliography step + # brings its own work to cite. It is cited twice on purpose: one work, + # one entry, one number in both places is the rule being checked. + bibliography = await call( + session, + "reference_create", + reference={ + "type": "journal-article", + "title": "SMOKE MCP 参考文献表", + "container_title": "Journal of Smoke Tests", + "publication_year": 2024, + "volume": "12", + "issue": "3", + "pages": "45-67", + "doi": "10.1000/smoke.mcp.002", + "authors": [ + {"name": "Smith, John", "family_name": "Smith", "given_name": "John"} + ], + }, + ) + cited_reference = bibliography["id"] + _created_references.append(cited_reference) + + first = await call( + session, + "sentence_add", + paper_id=paper["id"], + heading=outline[3]["name"], + content="A cited sentence.", + citations=[{"quote": "引用的原话", "reference_id": cited_reference}], + ) + await call( + session, + "sentence_add", + paper_id=paper["id"], + heading=outline[3]["name"], + content="A second sentence, same work.", + line_break_before=True, + citations=[{"quote": "再次引用", "reference_id": cited_reference}], + ) + + document = await call( + session, "paper_document", paper_id=paper["id"], format="json" + ) + check( + "the style the entries are written in is named", + document["reference_style"] == "springer", + str(document.get("reference_style")), + ) + check( + "one row per place in the text", + len(document["citations"]) == 2, + json.dumps(document["citations"], ensure_ascii=False), + ) + check( + "but one entry for the work, however often it is cited", + len(document["references"]) == 1, + json.dumps(document["references"], ensure_ascii=False), + ) + entry = document["references"][0] + check( + "the entry is a bibliography line rather than the quoted words", + entry["text"].startswith("Smith, J.: SMOKE MCP 参考文献表") + and "Journal of Smoke Tests 12(3), 45–67 (2024)" in entry["text"] + and entry["text"].endswith("https://doi.org/10.1000/smoke.mcp.002"), + entry["text"], + ) + check( + "a complete entry is reported as complete", + entry["missing"] == [], + str(entry["missing"]), + ) + check( + "both places wear the one number the entry has", + {row["index"] for row in document["citations"]} == {entry["index"]}, + json.dumps(document["citations"], ensure_ascii=False), + ) + check( + "and the entry names both of them", + len(entry["citations"]) == 2 + and first["sentence"]["id"] + in {row["sentence_id"] for row in document["citations"]}, + json.dumps(entry, ensure_ascii=False), + ) + + as_text = await call(session, "paper_document", paper_id=paper["id"]) + check( + "the text form carries the 参考文献 block with that entry", + f"参考文献\n[{entry['index']}] {entry['text']}" in as_text["text"], + repr(as_text["text"][-300:]), + ) + check( + "and marks both places with that same number", + f"A cited sentence.[{entry['index']}]" in as_text["text"] + and f"A second sentence, same work.[{entry['index']}]" in as_text["text"], + repr(as_text["text"][-700:]), + ) + check( + "and the bibliography lists the work exactly once", + len( + [ + line + for line in as_text["text"].splitlines() + if line.startswith(f"[{entry['index']}] ") + ] + ) + == 1, + repr(as_text["text"][-300:]), + ) + + print("\n18. move a paragraph, then clear the one it moved onto") home = outline[0] target = outline[1] relocation = await call( @@ -629,7 +896,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int: after_clear = await call(session, "paragraph_get", paper_id=paper["id"], position=target["position"]) check("and the paragraph is empty", after_clear["sentences"] == [], json.dumps(after_clear, ensure_ascii=False)) - print("\n17. the field library round-trips") + print("\n19. the field library round-trips") field = await call(session, "field_create", name="SMOKE MCP 字段", level=2, font_size=9.5) check("created with its typography", field["level"] == 2 and field["font_size"] == 9.5, json.dumps(field, ensure_ascii=False)) renamed = await call(session, "field_update", field_id=field["id"], name="SMOKE MCP 字段(改)") @@ -638,7 +905,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int: check("deleted while no template places it", dropped["deleted"] == 1, json.dumps(dropped, ensure_ascii=False)) check("and it is reported as found, not missing", dropped["missing"] == [], json.dumps(dropped, ensure_ascii=False)) - print("\n18. switch the template and keep the content") + print("\n20. switch the template and keep the content") spare = await call( session, "template_create", @@ -682,15 +949,15 @@ async def _run(url: str | None = None, token: str | None = None) -> int: json.dumps(switched_document, ensure_ascii=False)[:400], ) - print("\n19. a template in use cannot be deleted") + print("\n21. a template in use cannot be deleted") message = await expect_error(session, "template_delete", template_ids=spare["id"]) check("the refusal names the blocker", "SMOKE MCP 模板" in message, message) - print("\n20. deleting a paper needs an explicit confirmation") + print("\n22. deleting a paper needs an explicit confirmation") message = await expect_error(session, "paper_delete", paper_ids=paper["id"]) check("the refusal explains itself", "confirm=true" in message, message) - print("\n21. delete the paper and the template") + print("\n23. delete the paper and the template") deleted = await call(session, "paper_delete", paper_ids=paper["id"], confirm=True) check("deleted", deleted["deleted"] == 1, json.dumps(deleted, ensure_ascii=False)) _created_papers.remove(paper["id"]) diff --git a/deploy/README.md b/deploy/README.md index dc3331d..5e66900 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -18,7 +18,11 @@ paper-doc 的 MCP 服务跑在 k3s 里,命名空间 **`paper-doc`**,客户 | Secret | `paper-doc-secrets` | `DB_USER` / `DB_PASSWORD` / `MCP_HTTP_TOKEN` | | Secret | `aliyun-acr` | 镜像仓库拉取凭证(从 `default` 复制) | -镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v2` +镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v5` +(`sha256:1e17a72ca611a498d93fc960a7fe1eba5ed5803376794efa66f1967830d51c5d`; +`kubectl -n paper-doc get pods -o jsonpath='{.items[0].status.containerStatuses[0].imageID}'` +对得上,才说明跑的就是 ACR 上那一版。历史:v1 首发布 → v2 重命名表 → v3 参考文献库 → +v4 补参考文献 MCP 工具 → **v5 换行与参考文献表**。) **数据库**:TiDB 已经在这个集群里,Deployment 用集群内的 Service `tidb-tidb.tidb:4000`,而不是宿主机用的 NodePort `192.168.1.88:32738`。 diff --git a/deploy/build-mcp-image.sh b/deploy/build-mcp-image.sh index 4258e89..99d810a 100755 --- a/deploy/build-mcp-image.sh +++ b/deploy/build-mcp-image.sh @@ -128,6 +128,8 @@ log "done: $IMAGE" cat <=2.2,<3` 协商) - 传输:`stdio`(本地拉起)与 `streamable-http`(远程连接,支持 Bearer 口令),另兼容旧 `sse` @@ -98,10 +98,12 @@ cd /data/project/paper/backend .venv/bin/python scripts/smoke_mcp.py --url http://127.0.0.1:8931/mcp --token 你的口令 # 连已有的 HTTP 服务 ``` -同一个套件 **76 项检查**跑两种传输,覆盖 21 个步骤:建论文 → 看骨架 → 按标题写段落 → +同一个套件 **99 项检查**跑两种传输,覆盖 23 个步骤:建论文 → 看骨架 → 按标题写段落 → 定位失败时列出候选标题 → 读段落/追加带引用的句子 → 只改一句 → 删一句 → 整篇一次写入 → -读全文 → 跨论文搜索 → 搬段落 → 清空段落 → 字段库增删改 → 建/改模板 → 换模板后正文不丢 → -文献库增删改查与批量导入 → 引用守卫(被引用的文献删不掉)→ 删模板被拒 → 删论文要确认 → 清理。写真实数据,结束时自己删干净。 +读全文 → 跨论文搜索 → **另起一行**(公式独行、标记开关、搬段落时跟着走)→ **参考文献表** +(一处引用一行、一部文献一条、正文编号与表号同号)→ 搬段落 → 清空段落 → 字段库增删改 → +建/改模板 → 换模板后正文不丢 → 文献库增删改查与批量导入 → 引用守卫(被引用的文献删不掉)→ +删模板被拒 → 删论文要确认 → 清理。写真实数据,结束时自己删干净。 --- @@ -270,10 +272,10 @@ Header: Authorization: Bearer | 工具 | 作用 | 关键参数 | |---|---|---| | `paragraph_list` | 段落骨架 + 预览 | `paper_id`、`include_empty?` `preview?` | -| `paragraph_get` | 读一段:拼好的正文、逐句 id/内容/引用/分隔符 | `paper_id`、`position?` `heading?` | +| `paragraph_get` | 读一段:拼好的正文、逐句 id/内容/引用/分隔符与换行 | `paper_id`、`position?` `heading?` | | `paragraph_write` | 写一段(覆盖或追加) | `paper_id`、`position?` `heading?`、`sentences?` `text?` `split?` `citations?` `mode?` | | `paragraph_delete` | 清空该段全部句子(段落仍在) | `paper_id`、`position?` `heading?` | -| `paragraph_move` | 整段搬到另一个位置(接在目标段之后) | `paper_id`、`position?` `heading?`、`target_position?` `target_heading?` | +| `paragraph_move` | 整段搬到另一个位置(**接在目标段已有内容之后**,换行与引用一起搬过去) | `paper_id`、`position?` `heading?`、`target_position?` `target_heading?` | 定位规则:`position` 直接采用(包括模板没定义的位置,会以"未设定"渲染); `heading` 按模板解析,忽略编号、空格和大小写,所以下面三种写法等价: @@ -292,11 +294,38 @@ Header: Authorization: Bearer | 工具 | 作用 | 关键参数 | |---|---|---| | `sentence_list` | 列句子(可只列某段) | `paper_id`、`position?` `heading?` `include_empty?` | -| `sentence_add` | 段尾追加一句(可带引用) | `paper_id`、`content`、`position?` `heading?` `citations?` `sort?` | -| `sentence_update` | 改正文 / 改所属段 / 改排序 / 整组换引用 | `paper_id`、`sentence_id`、`content?` `position?` `sort?` `citations?` | +| `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_delete` | 删一句(连引用) | `paper_id`、`sentence_id` | | `sentence_search` | **跨论文搜句子**(保持术语一致) | `keyword`、`paper_id?` `limit?` | +#### 另起一行:公式、分条列举、作者行 + +一段是**它的句子连排**出来的,所以"不是散文的行"要自己开口。方式是在句子对象上加 +`line_break_before: true`,写进去、读回来、搬走都带着: + +```jsonc +{"heading": "3. Methods", "sentences": [ + "本段说明公式的来历。", + {"content": "$$ E = mc^2 $$"}, // 不用标,见下 + {"content": "其中 $c$ 为光速。", "line_break_before": true}, + {"content": "(1)第一项;", "line_break_before": true} +]} +``` + +三条规则: + +1. **换行顶掉分隔符,不是叠加。** 新行本身已经把两句分开了,再加一个空格会让下一行空一格。 +2. **display 公式(`$$…$$` 或 `\[…\]`)自己独占一行,不必标。** 论文页面就是这么排的, + `paper_document` 的 `text` 也这么排——两处必须一致,所以模型不要去猜"这里要不要加标记"。 + 行内公式(`$…$`)不算,它本来就在句子里。 +3. **"请读一遍这一段"时看得到换行。** `paragraph_get` / `paper_document` 返回的 `text` 里换行就是真的换行符; + `sentence_list` 每句还带 `line_break_before` 字段,所以搬句子之前能看出哪几句是另起的行。 + +`text` + `split` 那种整块写法也可以带 `line_break_before`,但它只作用于**切出来的第一句**—— +"这一块从新的一行开始"。块里其余几句是接着它的,不是各自另起一行;否则一个换行写了三行的段落 +就会被切成三行。 + ### 3.4 模板 templates(5 个) 模板就是结构:论文的标题是**每次渲染现读模板**得到的,所以改模板会影响所有用它的论文, @@ -418,6 +447,10 @@ Header: Authorization: Bearer > `sentence` 会避开小数点(`3.14`)和 `et al.` / `i.e.` 这类缩写,但它仍然是"猜"。 > 想完全不猜,就直接给 `sentences` 数组。 +`paper_write_text` 的正文是一整块字符串,**表达不了"这一句另起一行"**(也只有第一行能带)。 +display 公式不用担心——它本来就独占一行;但分条列举、作者行这类要另起的行, +请改用 `paper_write` 给 `sentences` 数组并加 `line_break_before: true`(见 §3.3)。 + 标题识别两种形态:Markdown 标题行(`# 0 Abstract`),或**与模板完全同名的独立一行** (把 `paper_outline` 的标题原样抄下来最稳)。前面没有标题的内容会被丢弃; 一个都没匹配上则整次调用报错,不会写半截。 @@ -565,6 +598,13 @@ REST 和 MCP 同时生效。这让"网页里看到的"和"AI 写进去的"永远 写入路径不切任何文本"(见 `docs/OVERVIEW.md`)。只有 `text` + `split` 这条路会切, 默认还是 `line`。已存文本永远不会被重新切分。 +**换行是"要求"出来的,不是猜出来的。** `line_break_before` 只在被明确写出来时才设: +`text` 里换了一行不等于要另起一行(模型把一段话折成三行是常事),所以工具不从这里推断。 +唯一的例外是 display 公式——页面渲染和 `paper_document` 的 `text` 都让它独占一行, +这条规则在 `frontend/src/utils/math.ts` 和 `app/mcp/support.py` 里各写了一遍 +(一个 TypeScript、一个 Python),**改一处必须改另一处**,否则网页和工具结果就会在 +"哪一行是哪一行"上不一致。冒烟测试里有一项专门盯着它。 + **删除要二次确认。** `paper_delete` 第一次调用必定被拒并说明后果, 因为一次误删会连带整篇的句子和引用,而这在 MCP 里没有回收站。 diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md index 434562e..3005ead 100644 --- a/docs/OVERVIEW.md +++ b/docs/OVERVIEW.md @@ -516,7 +516,7 @@ written by an agent is indistinguishable from one written by hand. What | Addition | Why the REST shape is wrong for a model | |---|---| -| 29 tools with `paper_` / `paragraph_` / `sentence_` / `template_` / `field_` prefixes | a model picks a tool out of a list by its name, not by reading 29 descriptions | +| 41 tools with `paper_` / `paragraph_` / `sentence_` / `template_` / `field_` / `reference_` / `reference_tag_` prefixes | a model picks a tool out of a list by its name, not by reading 41 descriptions | | JSON strings, `None`-free, no pagination envelope on reads | a tool result is paid for in context tokens | | `paragraph_write` addressed by **heading** as well as position | nobody writing "1. Introduction" knows the template places it at `sort = 20` | | `paper_write` / `paper_write_text` | "generate the paper, then put it in" is one intention, not thirty round trips | @@ -524,6 +524,7 @@ written by an agent is indistinguishable from one written by hand. What | `sentence_search` across papers | the job is consistency — one paper says 洪水损失, the next must not say GUL | | `reference_*` and `reference_tag_*` | the reference library is what makes a citation mean something; an agent that can cite id 42 but cannot look up what 42 *is* is writing blind | | `reference_import` | "here are the twenty references I cited" is one intention, and twenty round trips would spend twenty schemas on it | +| `line_break_before` on a sentence, and the display-formula rule in `document_text` | a paragraph is its sentences run together, so a formula, a list or an author line needs a way to say where the line starts — and the text an agent reads back has to break lines where the paper view breaks them, or the two disagree about what the manuscript looks like | Two transports are served from one build: `stdio`, which is what a client spawns, and `streamable-http`, which is what a client on another machine