diff --git a/backend/app/mcp/specs.py b/backend/app/mcp/specs.py index 31943bf..cb870fd 100644 --- a/backend/app/mcp/specs.py +++ b/backend/app/mcp/specs.py @@ -27,6 +27,15 @@ from pydantic import BaseModel, Field #: of an explicit list. See :func:`app.mcp.support.split_text`. SplitMode = Literal["line", "sentence", "paragraph"] +#: Where a display formula sits on its line. Spelled out here rather than as a +#: plain ``str`` so the JSON Schema a client receives carries the three values: +#: a model that reads "formula_align: string" invents ``middle``. +#: +#: This is the same set as :data:`app.models.paper_sentence.FORMULA_ALIGNMENTS`, +#: which the payload validator enforces; a value outside it is refused by the +#: same message the REST API gives. +FormulaAlign = Literal["center", "left", "right"] + class CitationSpec(BaseModel): """One citation of one sentence.""" @@ -42,9 +51,22 @@ class CitationSpec(BaseModel): class SentenceSpec(BaseModel): - """One sentence, optionally carrying citations.""" + """One sentence, optionally carrying citations. + + The fields here are the sentence's own columns, and they are meant to stay + that way: :data:`app.mcp.support.SENTENCE_FIELDS` is read from + :class:`~app.schemas.paper.SentenceInput` at import, and ``smoke_mcp.py`` + asserts that this model declares every one of them. A column added to the + domain therefore fails the suite until it is declared here, instead of being + dropped from every write in silence — which is what happened to + ``line_break_before`` and then to ``formula_align``. + """ content: Annotated[str, Field(description="句子正文;空白会被折叠成一行")] + sort: Annotated[ + int | None, + Field(description="段内排序值;不传则按写入顺序接在段尾"), + ] = None line_break_before: Annotated[ bool, Field( @@ -55,6 +77,15 @@ class SentenceSpec(BaseModel): ) ), ] = False + formula_align: Annotated[ + FormulaAlign, + Field( + description=( + "display 公式在这一行怎么排:center(默认)/ left / right。" + "只对含 $$…$$ 的句子有意义,句号后的编号始终靠右" + ) + ), + ] = "center" citations: Annotated[ list[CitationSpec], Field(description="这一段引用了哪些文献"), @@ -78,6 +109,10 @@ class TextSpec(BaseModel): ) ), ] = False + formula_align: Annotated[ + FormulaAlign, + Field(description="这块切出来的公式怎么排:center(默认)/ left / right"), + ] = "center" citations: Annotated[ list[CitationSpec], Field(description="整段共用的引用"), diff --git a/backend/app/mcp/support.py b/backend/app/mcp/support.py index 33115ec..f96b660 100644 --- a/backend/app/mcp/support.py +++ b/backend/app/mcp/support.py @@ -260,6 +260,9 @@ def sentence_row(sentence: Any, *, separator: str | None = None) -> dict: # 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, + # Only meaningful for a sentence holding a display formula, and reported + # anyway: a row that hides it looks like a row where it is not set. + "formula_align": sentence.formula_align, "citations": [citation_row(item) for item in sentence.citations], } if separator is not None: @@ -283,17 +286,46 @@ 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``, +#: This is the same rule as ``hasDisplayMath`` in ``frontend/src/utils/rich.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]+?\\\]") +#: One image, as a sentence writes it: ``![图注](地址)`` with pandoc's optional +#: ``{width=…}``. The counterpart of the image alternative in ``RICH_PATTERN`` +#: (same file as above), and the same warning applies: the two are one rule. +_IMAGE = re.compile(r"!\[(?P[^\]]*)\]\([^()\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 _figure_caption(content: str) -> str | None: + """The 图注 of a figure sentence — a sentence that is nothing but one image. + + The paper view's ``figureOf``: a sentence holding only a picture is a 插图, + printed on a line of its own with the brackets' text underneath as its + caption; a picture inside a sentence that says something stays in the line. + Anything else — two images, or an image with words around it — is not a + figure, and returns ``None``. + """ + match = _IMAGE.search(content) + if match is None: + return None + if content[: match.start()].strip() or content[match.end() :].strip(): + return None + return match.group("alt") + + +def _is_block(sentence: Any) -> bool: + """Whether this sentence takes a line of its own, whether or not it asked. + + Two kinds do, and both are rules the paper view already applies: a display + formula, and a figure. Nothing else is inferred — an ordinary sentence that + merely follows a full stop runs on, which is what a paragraph is. + """ + return bool(_DISPLAY_MATH.search(sentence.content)) or _figure_caption( + sentence.content + ) is not None def paragraph_text( @@ -308,14 +340,20 @@ 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 + A line break is printed where the model asked for one, and on both sides of + a block — a display formula, or a sentence that is one figure — because the + paper view sets those on a line of their own. 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 figure prints as the Markdown it is stored as — ``![图注](地址)`` on its + own line — rather than as its caption alone. The text form cannot draw the + picture, and the address is what says *which* picture: a model that reads a + paragraph back sees the same string the writer put there, and can paste it + somewhere else unchanged. + 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 @@ -325,7 +363,7 @@ def paragraph_text( parts: list[str] = [] previous_block = False for sentence in paragraph.sentences: - block = _is_display(sentence) + block = _is_block(sentence) if parts and (sentence.line_break_before or block or previous_block): parts.append("\n") else: @@ -619,6 +657,50 @@ def _is_latin_break(text: str, index: int) -> bool: return True +#: Every field a sentence payload carries, read from the payload schema itself +#: rather than listed by hand here. +#: +#: The hand-written list was wrong twice. A column added to the domain — +#: ``line_break_before``, and then ``formula_align`` — reached the REST API, the +#: editor and the paper view, and was silently dropped by every MCP write path +#: that had spelled the fields out: the call succeeded and the field was simply +#: gone. Reading the names from :class:`~app.schemas.paper.SentenceInput` means a +#: new column flows through :func:`sentence_payload` and through the tools that +#: spread it, and the only edit left is declaring it in +#: :class:`~app.mcp.specs.SentenceSpec` — which ``smoke_mcp.py`` checks for, so +#: forgetting *that* fails the suite instead of losing the field. +SENTENCE_FIELDS: tuple[str, ...] = tuple(SentenceInput.model_fields) + + +def sentence_payload(values: Mapping[str, Any], **overrides: Any) -> SentenceInput: + """One sentence payload, built from whatever the caller sent. + + Fields the caller did not mention keep the schema's own defaults, and keys + this layer does not know are dropped rather than handed to a validator that + would refuse them: a model that copies a row out of ``paragraph_get`` and + edits it sends back ``id``, ``position`` and ``separator_before`` as well, + and read-modify-write is a reasonable way to work. + """ + known = {name: values[name] for name in SENTENCE_FIELDS if name in values} + known.update(overrides) + return SentenceInput(**known) + + +def sentence_values(row: Any) -> dict[str, Any]: + """One *stored* sentence as payload fields again — for a move or a copy. + + ``sort`` is deliberately absent, and the caller decides about it: a sentence + moved onto another paragraph must not carry its old number there, or the two + paragraphs interleave by sort instead of the moved block landing after the + target's own sentences. + """ + return { + name: getattr(row, name) + for name in SENTENCE_FIELDS + if name not in {"sort", "citations"} and hasattr(row, name) + } + + def sentence_inputs(items: Sequence[Any], *, default_split: str = "line") -> list[SentenceInput]: """Normalise what a model sent into the project's own sentence payload. @@ -660,13 +742,7 @@ def sentence_inputs(items: Sequence[Any], *, default_split: str = "line") -> lis line_break = bool(item.get("line_break_before", False)) if item.get("content") is not None: - out.append( - SentenceInput( - content=str(item["content"]), - line_break_before=line_break, - citations=citations, - ) - ) + out.append(sentence_payload(item, citations=citations)) continue if item.get("text") is not None: @@ -679,8 +755,12 @@ def sentence_inputs(items: Sequence[Any], *, default_split: str = "line") -> lis # would turn a paragraph the writer wrapped across three lines # into three lines of the paper. out.append( - SentenceInput( + sentence_payload( + item, content=piece, + # A block has no ``sort`` of its own: the pieces are one + # after another, and the CRUD layer numbers them. + sort=None, line_break_before=line_break and offset == 0, citations=citations, ) @@ -728,6 +808,7 @@ def paragraph_inputs(spec: Any) -> list[SentenceInput]: __all__ = [ "MAX_PAGE_SIZE", + "SENTENCE_FIELDS", "SPLIT_MODES", "clean", "citation_row", @@ -747,7 +828,9 @@ __all__ = [ "resolve_position", "sentence_inputs", "sentence_or_fail", + "sentence_payload", "sentence_row", + "sentence_values", "session", "split_text", "template_or_fail", diff --git a/backend/app/mcp/tools/__init__.py b/backend/app/mcp/tools/__init__.py index b948e24..7f3d714 100644 --- a/backend/app/mcp/tools/__init__.py +++ b/backend/app/mcp/tools/__init__.py @@ -1,4 +1,4 @@ -"""Tool registry: the five groups, registered in one call. +"""Tool registry: the groups, registered in one call. The groups mirror the domain rather than the HTTP routes — papers and paragraphs and sentences are the same tables the REST API serves, but a model @@ -7,9 +7,10 @@ and the split between :mod:`~app.mcp.tools.papers` and :mod:`~app.mcp.tools.paragraphs` follows those jobs. Prefixes are load-bearing: every tool name starts with its group -(``paper_``, ``paragraph_``, ``sentence_``, ``template_``, ``field_``), because -that prefix is what a model uses to pick a tool out of a list of twenty-nine -without reading all twenty-nine descriptions. +(``paper_``, ``paragraph_``, ``sentence_``, ``template_``, ``field_``, +``reference_``, ``reference_tag_``, ``image_``), because that prefix is what a +model uses to pick a tool out of a list of forty without reading all forty +descriptions. """ from __future__ import annotations @@ -18,6 +19,7 @@ from mcp.server.mcpserver import MCPServer from app.mcp.tools import ( fields, + images, papers, paragraphs, reference_tags, @@ -28,8 +30,18 @@ from app.mcp.tools import ( #: Registration order is also the order a client lists the tools in, which is #: the order a paper is actually written in: find it, shape it, write it, then -#: the things it is written against. -MODULES = (papers, paragraphs, sentences, templates, fields, references, reference_tags) +#: the things it is written against — and last the figure, which is written by +#: putting a sentence somewhere. +MODULES = ( + papers, + paragraphs, + sentences, + templates, + fields, + references, + reference_tags, + images, +) def register_all(server: MCPServer) -> None: diff --git a/backend/app/mcp/tools/images.py b/backend/app/mcp/tools/images.py new file mode 100644 index 0000000..e9c2322 --- /dev/null +++ b/backend/app/mcp/tools/images.py @@ -0,0 +1,191 @@ +"""Image tools (插图): put a figure in the bucket, and hand back the sentence. + +A picture is not text, so it does not live in the database: the sentence keeps a +Markdown address and the bytes live in MinIO (see :mod:`app.core.storage`). That +is what keeps a sentence one editable string, and it is also why there is no +``image_create`` that attaches a picture to a paragraph — writing a figure *is* +writing a sentence whose content happens to be ``![图注](/api/images/…)``. + +One tool, and one field of a sentence, is therefore the whole feature from a +model's side. ``image_upload`` exists for the half a model cannot do itself: it +has bytes (a screenshot the user pasted, a figure it generated) and no way to +send a multipart request. Everything after that is ordinary text. + +The base64 argument is a deliberate cost. A tool argument is context tokens, and +base64 is a third larger than the bytes it carries — but the alternative is a +second ingestion path (an HTTP fetch of a URL the caller names), and a service +inside the cluster that will fetch any address it is handed is an SSRF primitive +aimed at everything beside it. A model with a picture and no base64 can post it +to ``POST /api/images`` and use the Markdown that comes back; the two produce the +same sentence, byte for byte, because both go through +:func:`app.core.storage.markdown_for`. +""" + +from __future__ import annotations + +import base64 +import binascii +import re +from typing import Annotated + +from mcp.server.mcpserver import MCPServer +from pydantic import Field + +from app.core.config import get_settings +from app.core.storage import get_store, image_url, markdown_for +from app.mcp import support as s +from app.mcp.tools.registry import mcp_tool + + +def register(server: MCPServer) -> None: + """Register every image tool on ``server``.""" + + @mcp_tool(server, title="上传插图") + def image_upload( + data_base64: Annotated[ + str, + Field( + description=( + "图片内容的 base64。可以直接给 data:image/png;base64,… 这种完整形式。" + "PNG / JPEG / GIF / WebP,最大 20 MB" + ) + ), + ], + caption: Annotated[ + str | None, + Field(description="图注;不给就用 filename 的主干,都没有则留空"), + ] = None, + filename: Annotated[ + str | None, + Field(description="文件名,只用于取图注初值;存储的键由内容决定,与它无关"), + ] = None, + width: Annotated[ + str | None, + Field( + description=( + "可选宽度:70%(占栏宽)或 400px。不传则按原尺寸,最大不超过栏宽" + ) + ), + ] = None, + ) -> str: + """上传一张图片,返回可直接写进句子的 Markdown 与那个句子对象。""" + data = _decode(data_base64) + settings = get_settings() + if len(data) > settings.max_image_bytes: + s.fail( + f"图片太大了({len(data) / (1024 * 1024):.1f} MB)," + f"上限是 {settings.max_image_bytes // (1024 * 1024)} MB。先压缩或裁剪一下再传。" + ) + + # The store sniffs the format out of the bytes and refuses anything that + # is not a picture: an SVG is stored XSS when it is served from this + # origin, and the caller's content type or filename is only a claim. + key, content_type, digest = get_store().save(data) + + markdown = _embed(key, caption=caption or _stem(filename), width=width) + return s.dumps( + { + "key": key, + "url": image_url(key), + "markdown": markdown, + "content_type": content_type, + "size": len(data), + "sha256": digest, + # The sentence, not just the Markdown: this is what the editor + # produces when a picture is dropped into it — the figure on a + # line of its own — so a model writes a figure by putting this + # object into `sentences` and changing nothing about it. + "sentence": { + "content": markdown, + "line_break_before": True, + "formula_align": "center", + }, + } + ) + + +# --- helpers ----------------------------------------------------------------- + +#: How a size may be written, and what it may be. Both halves mirror +#: ``WIDTH_PATTERN`` and ``parseImageWidth`` in ``frontend/src/utils/rich.ts``, +#: which is what actually reads the attribute when the paper is printed: the +#: syntax is ``{width=70%}`` or ``{width=400px}``, digits with at most one unit, +#: pixels up to :data:`MAX_PIXELS` and percentages up to 100. +#: +#: Written twice because one side is TypeScript and one is Python, and checked +#: here rather than passed through, because the reader's answer to a value it +#: cannot parse is to print the picture at its natural size — a size that +#: silently does not apply is worse than a refusal that says so. +_WIDTH_ATTRIBUTE = re.compile(r"^\s*(?:w|width)\s*=\s*(\d{1,4})\s*(%|px)?\s*$", re.IGNORECASE) +_WIDTH_BARE = re.compile(r"^\s*(\d{1,4})\s*(%|px)?\s*$") +_MAX_PIXELS = 4000 +_MAX_PERCENT = 100 + + +def _decode(value: str) -> bytes: + """The bytes behind a base64 argument, refusing anything that is not one. + + A ``data:`` prefix is stripped rather than refused: it is what a browser + writes when a picture is copied as a data URL, and it is what a model + produces when it repeats what it was given. + """ + text = value.strip() + if text.startswith("data:"): + _, _, text = text.partition(",") + # Whitespace is folded out because base64 arrives wrapped in as many ways as + # there are tools that produced it. + text = "".join(text.split()) + if not text: + s.fail("data_base64 是空的,没有图片内容") + try: + return base64.b64decode(text, validate=True) + except (binascii.Error, ValueError): + s.fail("data_base64 不是合法的 base64;请给图片字节的 base64,不要给文件路径或 URL") + + +def _stem(filename: str | None) -> str: + """The caption a filename suggests, the way the upload endpoint reads it.""" + if not filename: + return "" + name = filename.replace("\\", "/").rsplit("/", 1)[-1] + return name.rsplit(".", 1)[0] if "." in name else name + + +def _embed(key: str, *, caption: str, width: str | None) -> str: + """The Markdown a sentence carries: the address, plus an optional width. + + ``markdown_for`` writes the ``![图注](地址)`` half — the same function the + upload endpoint answers with — and this adds the size, which the endpoint + does not take because a browser appends it in the editor. + """ + markdown = markdown_for(key, caption) + attribute = _width_attribute(width) + return f"{markdown}{attribute}" if attribute else markdown + + +def _width_attribute(width: str | None) -> str: + """``{width=70%}`` from what the caller wrote, or a refusal saying why not. + + Tolerant about how it is written — ``70%``, ``70 %``, ``{width=70%}`` and + ``w=400px`` all mean the same thing, which is what a model repeats back from + a sentence it read — and strict about what it means. + """ + if width is None or not str(width).strip(): + return "" + + written = str(width).strip().strip("{}").strip() + match = _WIDTH_ATTRIBUTE.match(written) or _WIDTH_BARE.match(written) + if match is None: + s.fail( + f"width 只能是百分比或像素,例如 70% 或 400px,收到的是“{width}”。" + "不写则按原尺寸显示(最多不超过栏宽)" + ) + + digits, unit = int(match.group(1)), (match.group(2) or "px").lower() + limit = _MAX_PERCENT if unit == "%" else _MAX_PIXELS + if not 1 <= digits <= limit: + s.fail(f"width 的 {unit} 值要在 1 到 {limit} 之间,收到的是“{width}”") + return f"{{width={digits}{unit}}}" + + +__all__ = ["register"] diff --git a/backend/app/mcp/tools/papers.py b/backend/app/mcp/tools/papers.py index 21e2531..8790157 100644 --- a/backend/app/mcp/tools/papers.py +++ b/backend/app/mcp/tools/papers.py @@ -342,12 +342,12 @@ def register(server: MCPServer) -> None: paper_crud.append_sentence( db, paper, + # Spread, not copied field by field: a sentence + # column added to the domain then reaches this path + # by itself, instead of being dropped in silence. SentenceCreate( + **item.model_dump(), paper_template_filed_sort=position, - content=item.content, - line_break_before=item.line_break_before, - citations=item.citations, - sort=item.sort, ), ) else: diff --git a/backend/app/mcp/tools/paragraphs.py b/backend/app/mcp/tools/paragraphs.py index 6476e30..26a08f3 100644 --- a/backend/app/mcp/tools/paragraphs.py +++ b/backend/app/mcp/tools/paragraphs.py @@ -204,19 +204,13 @@ def register(server: MCPServer) -> None: if not rows: s.fail(f"第 {source} 段没有内容可以搬") + # Moved, not rewritten. Every column of the sentence travels — + # where a line started, how a formula was aligned, what it cited — + # because all of it is part of what was there; and ``sort`` is the + # one field deliberately left behind (see + # :func:`app.mcp.support.sentence_values`). inputs = [ - 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), - ) + SentenceInput(**s.sentence_values(row), citations=list(row.citations)) for row in rows ] paper_crud.replace_paragraph( @@ -266,6 +260,11 @@ def _write( at a time — the same call ``POST /papers/{id}/sentences`` makes — rather than read-modify-write, so two sentences appended in one request cannot overwrite each other's ``sort``. + + The payload is spread rather than copied field by field, so a column added + to a sentence reaches this path without anyone remembering to add it here — + which is how ``line_break_before`` and ``formula_align`` each went missing + once. """ if mode == "append": for item in inputs: @@ -273,11 +272,7 @@ def _write( db, paper, SentenceCreate( - paper_template_filed_sort=field_sort, - content=item.content, - line_break_before=item.line_break_before, - citations=item.citations, - sort=item.sort, + **item.model_dump(), paper_template_filed_sort=field_sort ), ) else: diff --git a/backend/app/mcp/tools/registry.py b/backend/app/mcp/tools/registry.py index cc65186..2f25ddb 100644 --- a/backend/app/mcp/tools/registry.py +++ b/backend/app/mcp/tools/registry.py @@ -32,6 +32,7 @@ from typing import Any, TypeVar from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError +from app.core.storage import StorageUnavailable, UnsupportedImage from app.crud.reference import UnknownReference from app.crud.reference_tag import DuplicateTagName, UnknownTag @@ -46,7 +47,19 @@ F = TypeVar("F", bound=Callable[..., Any]) #: would have let 「标签不存在:9」 reach the model as an unreadable #: "Error executing tool ...", which is the exact failure this wrapper exists to #: prevent. A new domain refusal belongs in this tuple on the day it is written. -DOMAIN_REFUSALS = (UnknownReference, UnknownTag, DuplicateTagName) +#: +#: The two storage ones are here for the same reason. A bucket that is not +#: configured and a file that is not a picture are both answers rather than +#: faults — "缺少 MINIO_ENDPOINT" and "只接受 PNG / JPEG / GIF / WebP" are the +#: two things a caller can act on, and neither survives the wrapper as a stack +#: trace. +DOMAIN_REFUSALS = ( + UnknownReference, + UnknownTag, + DuplicateTagName, + StorageUnavailable, + UnsupportedImage, +) def mcp_tool( diff --git a/backend/app/mcp/tools/sentences.py b/backend/app/mcp/tools/sentences.py index 2b72d93..ea5b7e1 100644 --- a/backend/app/mcp/tools/sentences.py +++ b/backend/app/mcp/tools/sentences.py @@ -20,7 +20,7 @@ from pydantic import Field from app.crud import paper as paper_crud from app.mcp import support as s -from app.mcp.specs import CitationSpec +from app.mcp.specs import CitationSpec, FormulaAlign from app.mcp.tools.registry import mcp_tool from app.models import Paper from app.schemas.paper import CitationInput, SentenceCreate, SentenceUpdate @@ -94,6 +94,10 @@ def register(server: MCPServer) -> None: ) ), ] = False, + formula_align: Annotated[ + FormulaAlign, + Field(description="display 公式怎么排:center(默认)/ left / right"), + ] = "center", sort: Annotated[ int | None, Field(description="段内位置;不传则排在段尾") ] = None, @@ -109,6 +113,7 @@ def register(server: MCPServer) -> None: paper_template_filed_sort=field_sort, content=content, line_break_before=line_break_before, + formula_align=formula_align, citations=_citations(citations or []), sort=sort, ), @@ -137,17 +142,22 @@ def register(server: MCPServer) -> None: bool | None, Field(description="这一句是否另起一行;不传则不动,false 表示取消换行"), ] = None, + formula_align: Annotated[ + FormulaAlign | None, + Field(description="display 公式怎么排;不传则不动"), + ] = None, citations: Annotated[ list[CitationSpec] | None, Field(description="引用整组替换;传 [] 表示清空引用"), ] = None, ) -> str: - """修改一句话的正文、所属段落、排序、换行或引用(引用是整体替换)。""" + """修改一句话的正文、所属段落、排序、换行、公式对齐或引用(引用是整体替换)。""" if ( content is None and position is None and sort is None and line_break_before is None + and formula_align is None and citations is None ): s.fail("没有给出任何要修改的内容") @@ -164,6 +174,7 @@ def register(server: MCPServer) -> None: paper_template_filed_sort=position, sort=sort, line_break_before=line_break_before, + formula_align=formula_align, citations=None if citations is None else _citations(citations), ), ) diff --git a/backend/scripts/smoke_mcp.py b/backend/scripts/smoke_mcp.py index 6d35fa3..3b9d5ac 100644 --- a/backend/scripts/smoke_mcp.py +++ b/backend/scripts/smoke_mcp.py @@ -23,8 +23,10 @@ Exits non-zero on the first failed expectation and cleans up after itself. from __future__ import annotations import argparse +import base64 import json import os +import re import sys from collections.abc import AsyncIterator, Iterator from contextlib import asynccontextmanager, contextmanager @@ -43,10 +45,21 @@ from mcp.client.stdio import StdioServerParameters, stdio_client # noqa: E402 from sqlalchemy import or_, select # noqa: E402 from app.db.session import SessionLocal # noqa: E402 +from app.mcp.specs import SentenceSpec # noqa: E402 from app.models import Paper, Reference, ReferenceTag, Template # noqa: E402 +from app.schemas.paper import SentenceInput # noqa: E402 SERVER_SCRIPT = BACKEND_DIR / "scripts" / "mcp_server.py" +#: A 1x1 GIF, and something that is definitely not a picture. Both are inline +#: rather than files on disk: the suite has to run from a checkout with nothing +#: beside it, and a fixture that cannot go missing cannot fail for the wrong +#: reason. +GIF_1PX_BASE64 = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" +NOT_A_PICTURE_BASE64 = base64.b64encode( + b'' +).decode() + _checks = 0 _created_papers: list[int] = [] _created_templates: list[int] = [] @@ -169,7 +182,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int: print("\n1. tool discovery") listed = await session.list_tools() names = {tool.name for tool in listed.tools} - check("the whole surface is published", len(names) == 41, f"got {len(names)}") + check("the whole surface is published", len(names) == 42, f"got {len(names)}") check( "every group is reachable", { @@ -180,10 +193,33 @@ async def _run(url: str | None = None, token: str | None = None) -> int: "field_list", "reference_create", "reference_tag_create", + "image_upload", } <= names, ", ".join(sorted(names)), ) + # The prefix is how a model finds a tool in a list of forty: a tool whose + # name does not start with its group's prefix is a tool nothing reaches + # for, and the mistake is invisible in every other check. + check( + "every tool name starts with its group's prefix", + all( + name.startswith( + ( + "paper_", + "paragraph_", + "sentence_", + "template_", + "field_", + "reference_", + "reference_tag_", + "image_", + ) + ) + for name in names + ), + ", ".join(sorted(names)), + ) check( "no tool returns a structured envelope", all(tool.output_schema is None for tool in listed.tools), @@ -193,6 +229,24 @@ async def _run(url: str | None = None, token: str | None = None) -> int: "paper_write describes its paragraph array", "paragraphs" in write_tool.input_schema["properties"], ) + # A sentence column that this surface does not declare is a column no + # model can set — which is exactly how `line_break_before` and then + # `formula_align` were lost: the write succeeded and the field was + # silently gone. Declaring every field is one line; forgetting one fails + # here. + missing = set(SentenceInput.model_fields) - set(SentenceSpec.model_fields) + check( + "the sentence schema declares every writable field of a sentence", + not missing, + f"missing from SentenceSpec: {sorted(missing)}", + ) + add_tool = next(tool for tool in listed.tools if tool.name == "sentence_add") + align = add_tool.input_schema["properties"]["formula_align"] + check( + "and a formula's alignment is an enum, so a model cannot invent one", + align.get("enum") == ["center", "left", "right"], + json.dumps(align, ensure_ascii=False), + ) print("\n2. create a paper on that template") paper = await call( @@ -864,7 +918,213 @@ async def _run(url: str | None = None, token: str | None = None) -> int: repr(as_text["text"][-300:]), ) - print("\n18. move a paragraph, then clear the one it moved onto") + print("\n18. a figure goes in, and prints on a line of its own") + # The bytes go to the object store and the sentence keeps the address, + # so this is the one place the suite needs MinIO as well as the database. + # The 1x1 GIF is the smallest real picture there is, which is all that is + # needed to prove the bytes arrive and the address comes back. + figure = await call( + session, + "image_upload", + data_base64=f"data:image/gif;base64,{GIF_1PX_BASE64}", + caption="图 1 试验装置示意图", + width="70%", + ) + check( + "the key is the shape the store writes, named after the bytes", + re.fullmatch(r"\d{4}/\d{2}/[0-9a-f]{16}\.gif", figure["key"]) is not None, + figure["key"], + ) + check( + "the URL is same-origin under the API prefix", + figure["url"] == f"/api/images/{figure['key']}", + figure["url"], + ) + check( + "the markdown is the sentence's content, caption and size included", + figure["markdown"] + == f"![图 1 试验装置示意图](/api/images/{figure['key']}){{width=70%}}", + figure["markdown"], + ) + check( + "and the sentence that shows it is ready to write as it stands", + figure["sentence"] + == { + "content": figure["markdown"], + "line_break_before": True, + "formula_align": "center", + }, + json.dumps(figure["sentence"], ensure_ascii=False), + ) + + same = await call( + session, "image_upload", data_base64=GIF_1PX_BASE64, filename="另一张.png" + ) + check( + "the same picture again is the same object, not a second copy", + same["key"] == figure["key"], + f"{same['key']} vs {figure['key']}", + ) + check( + "and the caption defaults to the filename's stem", + same["markdown"] == f"![另一张](/api/images/{figure['key']})", + same["markdown"], + ) + + # The returned sentence object is written as it came back, unchanged: + # that is the whole contract of the tool. + await call( + session, + "sentence_add", + paper_id=paper["id"], + heading=outline[3]["name"], + **figure["sentence"], + ) + with_figure = await call( + session, "paragraph_get", paper_id=paper["id"], heading=outline[3]["name"] + ) + check( + "the figure is stored as the sentence it was handed", + with_figure["sentences"][-1]["content"] == figure["markdown"] + and with_figure["sentences"][-1]["line_break_before"] is True, + json.dumps(with_figure["sentences"][-1], ensure_ascii=False), + ) + check( + "and the paragraph prints it alone on its own line", + with_figure["text"].endswith("\n" + figure["markdown"]), + repr(with_figure["text"][-200:]), + ) + + inline_url = same["url"] + inline = f"试验装置如 ![示意图]({inline_url}) 所示。" + await call( + session, + "sentence_add", + paper_id=paper["id"], + heading=outline[3]["name"], + content=inline, + ) + with_inline = await call( + session, "paragraph_get", paper_id=paper["id"], heading=outline[3]["name"] + ) + check( + "an image inside a sentence stays on the line with the words", + f"\n{inline}" in with_inline["text"] + and f"![示意图]({inline_url})\n" not in with_inline["text"], + repr(with_inline["text"][-260:]), + ) + + message = await expect_error( + session, + "image_upload", + data_base64=NOT_A_PICTURE_BASE64, + filename="图.svg", + ) + check( + "a file that is not a picture is refused, naming the formats", + "PNG" in message and "SVG" in message, + message, + ) + tolerant = await call( + session, + "image_upload", + data_base64=GIF_1PX_BASE64, + caption="写法宽容", + width="{w = 400 px}", + ) + check( + "how the size is written is forgiving, what it means is not", + tolerant["markdown"] == f"![写法宽容](/api/images/{tolerant['key']}){{width=400px}}", + tolerant["markdown"], + ) + message = await expect_error( + session, "image_upload", data_base64=GIF_1PX_BASE64, width="70em" + ) + check( + "a size the reader cannot parse is refused rather than quietly ignored", + "70%" in message, + message, + ) + message = await expect_error( + session, "image_upload", data_base64=GIF_1PX_BASE64, width="150%" + ) + check( + "and so is one that parses but the page would drop on the floor", + "1 到 100" in message, + message, + ) + message = await expect_error( + session, "image_upload", data_base64="这不是 base64" + ) + check( + "and a value that is not base64 says what to send instead", + "base64" in message, + message, + ) + + print("\n19. a formula says how it is set on its line") + derivation = outline[2] + await call( + session, + "paper_write", + paper_id=paper["id"], + paragraphs=[ + { + "heading": derivation["name"], + "sentences": [ + "推导如下。", + { + "content": "$$ a^2 + b^2 = c^2 $$", + "line_break_before": True, + "formula_align": "right", + }, + ], + } + ], + ) + aligned = await call( + session, "paragraph_get", paper_id=paper["id"], heading=derivation["name"] + ) + check( + "the alignment is stored on the sentence that carries the formula", + [row["formula_align"] for row in aligned["sentences"]] + == ["center", "right"], + json.dumps(aligned["sentences"], ensure_ascii=False), + ) + turned = await call( + session, + "sentence_update", + paper_id=paper["id"], + sentence_id=aligned["sentences"][-1]["id"], + formula_align="left", + ) + check( + "and it can be changed without touching the formula", + turned["sentence"]["formula_align"] == "left" + and turned["sentence"]["content"] == "$$ a^2 + b^2 = c^2 $$", + json.dumps(turned["sentence"], ensure_ascii=False), + ) + await call( + session, + "paragraph_move", + paper_id=paper["id"], + heading=derivation["name"], + target_heading=outline[3]["name"], + ) + carried = await call( + session, "paragraph_get", paper_id=paper["id"], heading=outline[3]["name"] + ) + check( + "and it travels with the sentence when the paragraph moves", + any( + row["content"] == "$$ a^2 + b^2 = c^2 $$" + and row["formula_align"] == "left" + for row in carried["sentences"] + ), + json.dumps(carried["sentences"], ensure_ascii=False), + ) + + print("\n20. move a paragraph, then clear the one it moved onto") home = outline[0] target = outline[1] relocation = await call( @@ -896,7 +1156,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("\n19. the field library round-trips") + print("\n21. 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 字段(改)") @@ -905,7 +1165,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("\n20. switch the template and keep the content") + print("\n22. switch the template and keep the content") spare = await call( session, "template_create", @@ -949,15 +1209,15 @@ async def _run(url: str | None = None, token: str | None = None) -> int: json.dumps(switched_document, ensure_ascii=False)[:400], ) - print("\n21. a template in use cannot be deleted") + print("\n23. 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("\n22. deleting a paper needs an explicit confirmation") + print("\n24. 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("\n23. delete the paper and the template") + print("\n25. 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 5e66900..6edcdee 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -14,20 +14,26 @@ paper-doc 的 MCP 服务跑在 k3s 里,命名空间 **`paper-doc`**,客户 | Namespace | `paper-doc` | `deploy/k8s/00-namespace.yaml` | | Deployment | `paper-doc-mcp` | 1 副本,跑 MCP 服务的 http 传输 | | Service | `paper-doc-mcp` | NodePort **30931** → 容器 8931 | -| ConfigMap | `paper-doc-config` | 非敏感环境变量(数据库地址、监听配置) | -| Secret | `paper-doc-secrets` | `DB_USER` / `DB_PASSWORD` / `MCP_HTTP_TOKEN` | +| ConfigMap | `paper-doc-config` | 非敏感环境变量(数据库地址、监听配置、MinIO 端点与桶名) | +| Secret | `paper-doc-secrets` | `DB_USER` / `DB_PASSWORD` / `MCP_HTTP_TOKEN` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` | | Secret | `aliyun-acr` | 镜像仓库拉取凭证(从 `default` 复制) | -镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v5` -(`sha256:1e17a72ca611a498d93fc960a7fe1eba5ed5803376794efa66f1967830d51c5d`; +镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v6` +(`sha256:c89c0ba250c872dec45e6e5ce056dcf1f73c5415f55aa8b05216ce785ae28732`; `kubectl -n paper-doc get pods -o jsonpath='{.items[0].status.containerStatuses[0].imageID}'` 对得上,才说明跑的就是 ACR 上那一版。历史:v1 首发布 → v2 重命名表 → v3 参考文献库 → -v4 补参考文献 MCP 工具 → **v5 换行与参考文献表**。) +v4 补参考文献 MCP 工具 → v5 换行与参考文献表 → **v6 插图与公式对齐**。) **数据库**:TiDB 已经在这个集群里,Deployment 用集群内的 Service `tidb-tidb.tidb:4000`,而不是宿主机用的 NodePort `192.168.1.88:32738`。 两者是同一份数据;集群内用 Service 的好处是节点地址变了也不用改配置。 +**对象存储**:论文里的插图放在 MinIO(命名空间 `minio`,同一个集群)。 +集群内用它自己的 Service `http://minio.minio.svc.cluster.local:9000`, +宿主机上开发才用 NodePort `http://192.168.1.88:30090`;两边是同一个桶 `paper-images`, +桶会在第一次上传时自动创建。少给凭证不会让服务起不来:`image_upload` 会回一句 +「图片存储还没有配置好(缺少 MINIO_…)」,写作类工具照常可用。 + ## 访问地址 | 从哪里连 | 地址 | diff --git a/deploy/k8s/10-paper-doc-mcp.yaml b/deploy/k8s/10-paper-doc-mcp.yaml index 9093cd8..2954196 100644 --- a/deploy/k8s/10-paper-doc-mcp.yaml +++ b/deploy/k8s/10-paper-doc-mcp.yaml @@ -22,6 +22,14 @@ data: DB_NAME: paper_doc APP_NAME: paper-doc API DEBUG: "false" + # Object storage for the images a paper embeds (MinIO, in its own namespace). + # The in-cluster Service, not the host's NodePort 30090: same bucket, and the + # address survives the node changing. The credentials live in the Secret — + # without them `image_upload` answers 「图片存储还没有配置好」 and names the + # variables, while every writing tool keeps working. + MINIO_ENDPOINT: http://minio.minio.svc.cluster.local:9000 + MINIO_BUCKET: paper-images + MINIO_REGION: us-east-1 # The container's own defaults, restated here because the Deployment is where # a reader looks for them. MCP_TRANSPORT: http @@ -67,7 +75,7 @@ spec: type: RuntimeDefault containers: - name: mcp - image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v5 + image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v6 imagePullPolicy: IfNotPresent ports: - name: http @@ -94,6 +102,19 @@ spec: secretKeyRef: name: paper-doc-secrets key: MCP_HTTP_TOKEN + # The object store's credentials. A key scoped to this one bucket is + # enough: the bucket is created on the first upload, so nothing has + # to be provisioned by hand before the first figure goes in. + - name: MINIO_ACCESS_KEY + valueFrom: + secretKeyRef: + name: paper-doc-secrets + key: MINIO_ACCESS_KEY + - name: MINIO_SECRET_KEY + valueFrom: + secretKeyRef: + name: paper-doc-secrets + key: MINIO_SECRET_KEY # Readiness asks the database; liveness does not. A TiDB blip should # take the pod out of the Service's endpoints and put it back when the # blip ends — not restart a process that is working correctly. @@ -178,13 +199,14 @@ spec: # imagePullSecrets: [{name: aliyun-acr}] # initContainers: # - name: migrate -# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v5 +# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v6 # command: ["alembic", "upgrade", "head"] # envFrom: [{configMapRef: {name: paper-doc-config}}] -# env: [...] # the same three secret keys as above +# env: [...] # the same secret keys as above; the MinIO +# # pair is what lets the API serve the figures # containers: # - name: api -# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v5 +# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v6 # command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] # ports: [{name: http, containerPort: 8000}] # envFrom: [{configMapRef: {name: paper-doc-config}}] diff --git a/deploy/k8s/secret.example.yaml b/deploy/k8s/secret.example.yaml index 7a6ab71..552a51b 100644 --- a/deploy/k8s/secret.example.yaml +++ b/deploy/k8s/secret.example.yaml @@ -5,11 +5,18 @@ # kubectl -n paper-doc create secret generic paper-doc-secrets \ # --from-literal=DB_USER='Govin' \ # --from-literal=DB_PASSWORD='' \ -# --from-literal=MCP_HTTP_TOKEN="$(openssl rand -hex 32)" +# --from-literal=MCP_HTTP_TOKEN="$(openssl rand -hex 32)" \ +# --from-literal=MINIO_ACCESS_KEY='' \ +# --from-literal=MINIO_SECRET_KEY='' # # Rotating the token is then one `kubectl create secret ... --dry-run=client -o # yaml | kubectl apply -f -` plus a rollout restart, and no image rebuild. # +# The MinIO pair is what `image_upload` / `POST /api/images` needs; a key scoped +# to the one bucket is enough, and the bucket is created on the first upload. +# Without the pair every writing tool still works and the image ones answer with +# the names of the variables that are missing. +# # The registry pull secret is separate and not described here: it is # `aliyun-acr`, copied into this namespace from `default`, and it holds the # container registry's credentials rather than the application's. @@ -23,3 +30,5 @@ stringData: DB_USER: Govin DB_PASSWORD: change-me MCP_HTTP_TOKEN: change-me + MINIO_ACCESS_KEY: change-me + MINIO_SECRET_KEY: change-me diff --git a/docs/MCP.md b/docs/MCP.md index 30456cc..cc85003 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -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 | 工具 | 作用 | 关键参数 | |---|---|---| | `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 三条规则: 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 | `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) |