diff --git a/backend/app/mcp/specs.py b/backend/app/mcp/specs.py index 67141bd..c42a7d7 100644 --- a/backend/app/mcp/specs.py +++ b/backend/app/mcp/specs.py @@ -109,10 +109,105 @@ class FieldSpec(BaseModel): ] +class ReferenceAuthorSpec(BaseModel): + """One contributor of one reference.""" + + name: Annotated[ + str, + Field(description="姓名,按引用里要印的样子写,如 “Smith, John” 或 “张三”"), + ] + family_name: Annotated[str | None, Field(description="姓")] = None + given_name: Annotated[str | None, Field(description="名")] = None + role: Annotated[ + str, + Field(description="角色:author(默认)/ editor / translator / compiler"), + ] = "author" + + +class ReferenceFields(BaseModel): + """Every bibliographic field, all optional — the shape an update sends. + + Nested rather than flattened into the tool signature for one reason that + matters more than tidiness: a nested model keeps ``model_fields_set``, so + the tool can tell "the caller wrote ``note: null``" (clear it) from "the + caller did not mention ``note``" (leave it). Spread across 38 keyword + parameters, every omitted field would arrive as ``None`` and the two cases + would be indistinguishable — the same problem ``paper_update`` solves by + rebuilding its payload from the parameters it was given. + """ + + type: Annotated[ + str | None, + Field(description="类型:journal-article / book / book-chapter / conference-paper / thesis / patent / standard / report / newspaper-article / web-page / dataset / software / preprint / other"), + ] = None + title: Annotated[str | None, Field(description="题名(原文)")] = None + subtitle: Annotated[str | None, Field(description="副题名")] = None + title_translated: Annotated[str | None, Field(description="并列题名/译名")] = None + title_short: Annotated[str | None, Field(description="题名缩写")] = None + container_title: Annotated[str | None, Field(description="期刊/论文集/丛书名")] = None + container_title_short: Annotated[str | None, Field(description="容器名缩写")] = None + series_title: Annotated[str | None, Field(description="丛书名")] = None + series_number: Annotated[str | None, Field(description="丛书号")] = None + edition: Annotated[str | None, Field(description="版次")] = None + volume: Annotated[str | None, Field(description="卷")] = None + issue: Annotated[str | None, Field(description="期")] = None + pages: Annotated[str | None, Field(description="页码,如 123-145")] = None + article_number: Annotated[str | None, Field(description="文章编号")] = None + publisher: Annotated[str | None, Field(description="出版社/机构")] = None + publisher_place: Annotated[str | None, Field(description="出版地")] = None + event_title: Annotated[str | None, Field(description="会议名")] = None + event_place: Annotated[str | None, Field(description="会议地点")] = None + event_date: Annotated[str | None, Field(description="会议日期")] = None + publication_year: Annotated[int | None, Field(description="出版年")] = None + publication_month: Annotated[int | None, Field(description="出版月 1-12")] = None + publication_day: Annotated[int | None, Field(description="出版日 1-31")] = None + accessed_date: Annotated[str | None, Field(description="访问日期 YYYY-MM-DD")] = None + doi: Annotated[str | None, Field(description="DOI,可带 https://doi.org/ 前缀")] = None + isbn: Annotated[str | None, Field(description="ISBN")] = None + issn: Annotated[str | None, Field(description="ISSN")] = None + url: Annotated[str | None, Field(description="网址")] = None + patent_country: Annotated[str | None, Field(description="专利国别")] = None + patent_number: Annotated[str | None, Field(description="专利号")] = None + standard_number: Annotated[str | None, Field(description="标准号")] = None + report_number: Annotated[str | None, Field(description="报告号")] = None + arxiv_id: Annotated[str | None, Field(description="arXiv 编号")] = None + abstract: Annotated[str | None, Field(description="摘要")] = None + keywords: Annotated[str | None, Field(description="关键词")] = None + note: Annotated[str | None, Field(description="备注")] = None + citation_key: Annotated[str | None, Field(description="引用键,如 smith2024flood")] = None + language: Annotated[str | None, Field(description="语言:zh / en / ja / other")] = None + authors: Annotated[ + list[ReferenceAuthorSpec] | None, + Field(description="作者列表;给了就是整体替换,顺序即印刷顺序"), + ] = None + tag_ids: Annotated[ + list[int] | None, + Field(description="标签 id 列表;给了就是整体替换,传 [] 表示清空"), + ] = None + + +class ReferenceSpec(ReferenceFields): + """The shape a *new* reference arrives in: a type and a title, at least.""" + + type: Annotated[ + str, + Field(description="类型:journal-article(默认)/ book / book-chapter / conference-paper / thesis / patent / standard / report / newspaper-article / web-page / dataset / software / preprint / other"), + ] = "journal-article" + title: Annotated[str, Field(description="题名(原文),必填")] + authors: Annotated[ + list[ReferenceAuthorSpec], + Field(description="作者列表,顺序即印刷顺序"), + ] = [] + tag_ids: Annotated[list[int], Field(description="标签 id 列表")] = [] + + __all__ = [ "CitationSpec", "FieldSpec", "ParagraphSpec", + "ReferenceAuthorSpec", + "ReferenceFields", + "ReferenceSpec", "SentenceItem", "SentenceSpec", "SplitMode", diff --git a/backend/app/mcp/tools/__init__.py b/backend/app/mcp/tools/__init__.py index 70e7433..b948e24 100644 --- a/backend/app/mcp/tools/__init__.py +++ b/backend/app/mcp/tools/__init__.py @@ -16,12 +16,20 @@ from __future__ import annotations from mcp.server.mcpserver import MCPServer -from app.mcp.tools import fields, papers, paragraphs, sentences, templates +from app.mcp.tools import ( + fields, + papers, + paragraphs, + reference_tags, + references, + sentences, + templates, +) #: 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) +MODULES = (papers, paragraphs, sentences, templates, fields, references, reference_tags) def register_all(server: MCPServer) -> None: diff --git a/backend/app/mcp/tools/reference_tags.py b/backend/app/mcp/tools/reference_tags.py new file mode 100644 index 0000000..e1ce93b --- /dev/null +++ b/backend/app/mcp/tools/reference_tags.py @@ -0,0 +1,152 @@ +"""Reference-tag tools (文献标签): the labels a bibliography is sorted by. + +A tag is a label, not a category: the library's own fields already say what a +work *is* (``type``), and tags say what it is *for* — 「必读」「方法」「待核实」. +That is why deleting one is allowed while deleting a reference is not: removing +a label drops the labelling and leaves every paper it was on, so the refusal the +field library needs would be the wrong answer here. The REST route +(``app/api/routes/reference_tags.py``) makes the same choice. + +Renaming is the exception, and it is enforced for a different reason: a tag name +is unique, and two labels differing only by spelling would split the same set in +two. ``DuplicateTagName`` is translated into a readable refusal by the tool +registry. +""" + +from __future__ import annotations + +from typing import Annotated + +from mcp.server.mcpserver import MCPServer +from pydantic import Field, ValidationError +from sqlalchemy.orm import Session + +from app.crud import reference_tag as tag_crud +from app.mcp import support as s +from app.mcp.tools.registry import mcp_tool +from app.schemas.reference_tag import ReferenceTagCreate, ReferenceTagUpdate + + +def register(server: MCPServer) -> None: + """Register every reference-tag tool on ``server``.""" + + @mcp_tool(server, title="列出文献标签") + def reference_tag_list( + keyword: Annotated[str | None, Field(description="按标签名模糊搜索")] = None, + page: Annotated[int, Field(description="页码,从 1 开始")] = 1, + page_size: Annotated[int, Field(description="每页条数,最大 200")] = 50, + ) -> str: + """列出文献标签(含每个标签下有几条文献)。给文献打标签前先查 id。""" + page, page_size = s.page_args(page, page_size) + with s.session() as db: + items, total = tag_crud.list_tags( + db, keyword=keyword, page=page, page_size=page_size + ) + return s.dumps( + s.page_payload( + items=[_row(item) for item in items], + total=total, + page=page, + page_size=page_size, + ) + ) + + @mcp_tool(server, title="取一个标签") + def reference_tag_get( + tag_id: Annotated[int, Field(description="标签 id")], + ) -> str: + """取一个文献标签,含它标了几条文献。""" + with s.session() as db: + return s.dumps(_row(tag_crud.read(db, _or_fail(db, tag_id)))) + + @mcp_tool(server, title="新建文献标签") + def reference_tag_create( + name: Annotated[str, Field(description="标签名,唯一,如「必读」「方法」")], + color: Annotated[ + str, Field(description="颜色 #RRGGBB 或 rgb(r,g,b)") + ] = "#409EFF", + note: Annotated[str | None, Field(description="备注")] = None, + ) -> str: + """新建一个文献标签。名称重复会被拒绝。""" + payload = _validated(ReferenceTagCreate, {"name": name, "color": color, "note": note}) + with s.session() as db: + # ``create``/``update`` hand back the row, not the payload: the + # reference count is computed, and only ``read`` computes it. + return s.dumps(_row(tag_crud.read(db, tag_crud.create(db, payload)))) + + @mcp_tool(server, title="修改文献标签") + def reference_tag_update( + tag_id: Annotated[int, Field(description="标签 id")], + name: Annotated[str | None, Field(description="新名称;不传则不改")] = None, + color: Annotated[str | None, Field(description="新颜色;不传则不改")] = None, + note: Annotated[str | None, Field(description="新备注;不传则不改")] = None, + clear_note: Annotated[bool, Field(description="true 表示把备注清空")] = False, + ) -> str: + """改标签名称、颜色或备注。改名会立刻反映到所有带它的文献上。""" + values: dict[str, object] = {} + if name is not None: + values["name"] = name + if color is not None: + values["color"] = color + if note is not None: + values["note"] = note + if clear_note: + values["note"] = None + if not values: + s.fail("没有给出任何要修改的内容") + + payload = _validated(ReferenceTagUpdate, values) + with s.session() as db: + updated = tag_crud.update(db, _or_fail(db, tag_id), payload) + return s.dumps(_row(tag_crud.read(db, updated))) + + @mcp_tool(server, title="删除文献标签") + def reference_tag_delete( + tag_ids: Annotated[int | list[int], Field(description="标签 id,或 id 数组")], + ) -> str: + """删除标签。文献本身不受影响,只是不再带这个标签。""" + ids = s.id_list(tag_ids) + if not ids: + s.fail("必须给出至少一个标签 id") + + with s.session() as db: + found = {tag.id for tag in tag_crud.get_many(db, ids)} + return s.dumps( + { + "deleted": tag_crud.delete_many(db, ids), + "ids": [tag_id for tag_id in ids if tag_id in found], + "missing": [tag_id for tag_id in ids if tag_id not in found], + } + ) + + +# --- helpers ----------------------------------------------------------------- + + +def _or_fail(db: Session, tag_id: int): + """Return one tag, or refuse with the id that was not found.""" + tag = tag_crud.get(db, tag_id) + if tag is None: + s.fail(f"标签 {tag_id} 不存在") + return tag + + +def _validated(schema: type, values: dict) -> object: + """Build the domain payload, turning a validation error into a refusal.""" + try: + return schema(**values) + except ValidationError as error: + first = error.errors()[0] + field = ".".join(str(part) for part in first.get("loc") or ()) + s.fail(f"标签不合法({field or '字段'}):{first.get('msg')}") + + +def _row(tag: object) -> dict: + """One tag as a model reads it: the label, its colour, and how much it holds.""" + return { + "id": tag.id, + "name": tag.name, + "color": tag.color, + "note": tag.note, + "references": tag.reference_count, + } diff --git a/backend/app/mcp/tools/references.py b/backend/app/mcp/tools/references.py new file mode 100644 index 0000000..4dbd654 --- /dev/null +++ b/backend/app/mcp/tools/references.py @@ -0,0 +1,371 @@ +"""Reference tools (参考文献): the literature a paper cites. + +The library is what makes a citation mean something. Until it existed, +``paper_sentence_reference.reference_id`` was a plain integer with no table +behind it — a sentence could say "I quote reference 7" and nothing in the +system could say what 7 was. These tools are the other half of that link: they +let an agent *find* the entry, *create* it when the library does not have it +yet, and *check what it is cited for* before touching it. + +Two tools here go past mirroring the REST surface, both because the caller is +a model rather than a form: + +* :func:`reference_list` filters by ``keyword`` across title, container, DOI, + keywords and author names, which is also the de-duplication path — look + before you create; +* :func:`reference_import` creates a whole bibliography in one call and reports + what it skipped, because "here are the 20 references I cited" arrives as one + intention and should not be twenty round trips. A ``reference_create`` per + entry would also spend one context window on twenty near-identical schemas. + +The refusal to delete a cited reference is the same rule the REST route +enforces (``app/api/routes/references.py``): the citation lives on a sentence, +and deleting the entry underneath it would leave a marker pointing at nothing. +""" + +from __future__ import annotations + +from typing import Annotated, Any + +from mcp.server.mcpserver import MCPServer +from pydantic import Field, ValidationError +from sqlalchemy.orm import Session + +from app.crud import reference as reference_crud +from app.mcp import support as s +from app.mcp.specs import ReferenceFields, ReferenceSpec +from app.mcp.tools.registry import mcp_tool +from app.schemas.reference import ReferenceCreate, ReferenceUpdate + + +def register(server: MCPServer) -> None: + """Register every reference tool on ``server``.""" + + @mcp_tool(server, title="检索文献") + def reference_list( + keyword: Annotated[ + str | None, + Field(description="按题名、副题名、期刊、DOI、关键词、备注或作者名模糊搜索"), + ] = None, + type: Annotated[ + str | None, Field(description="按类型过滤,如 journal-article / book / patent") + ] = None, + year: Annotated[int | None, Field(description="按出版年过滤")] = None, + cited_only: Annotated[ + bool | None, Field(description="true=只看被引用过的,false=只看没被引用的") + ] = None, + tag_ids: Annotated[ + list[int] | None, Field(description="按标签过滤;给多个表示要同时带这些标签") + ] = None, + page: Annotated[int, Field(description="页码,从 1 开始")] = 1, + page_size: Annotated[int, Field(description="每页条数,最大 200")] = 20, + ) -> str: + """检索参考文献库。新建文献前先用 keyword 查重(DOI/题名/作者都能搜)。""" + page, page_size = s.page_args(page, page_size) + with s.session() as db: + items, total = reference_crud.list_references( + db, + keyword=keyword, + type_=type, + year=year, + cited_only=cited_only, + tag_ids=tag_ids, + page=page, + page_size=page_size, + ) + return s.dumps( + s.page_payload( + items=[_list_row(item) for item in items], + total=total, + page=page, + page_size=page_size, + ) + ) + + @mcp_tool(server, title="取一条文献") + def reference_get( + reference_id: Annotated[int, Field(description="文献 id")], + ) -> str: + """取一条文献的全部字段(作者、标签、被引用次数)。""" + with s.session() as db: + return s.dumps(_read_row(reference_crud.read(db, _or_fail(db, reference_id)))) + + @mcp_tool(server, title="新增文献") + def reference_create( + reference: Annotated[ + ReferenceSpec, + Field( + description=( + "文献内容。至少给 type 和 title;作者放 authors 数组" + "([{name, role?}]),标签放 tag_ids。" + "不确定的字段留空即可,之后可以 reference_update 补" + ) + ), + ], + ) -> str: + """往参考文献库加一条文献。建议先用 reference_list 查重。""" + payload = _validated(reference) + with s.session() as db: + return s.dumps(_read_row(reference_crud.read(db, reference_crud.create(db, payload)))) + + @mcp_tool(server, title="修改文献") + def reference_update( + reference_id: Annotated[int, Field(description="文献 id")], + changes: Annotated[ + ReferenceFields, + Field( + description=( + "要改的字段,只写要改的。传 null 表示清空该字段;" + "authors / tag_ids 给了就是整体替换(tag_ids 传 [] 清空标签)" + ) + ), + ], + ) -> str: + """改一条文献的字段。只传要改的部分,其余不动。""" + # Only the keys the caller actually wrote are forwarded: the nested spec + # keeps ``model_fields_set``, so an omitted field stays absent while an + # explicit null clears the column. Flattened into keyword parameters + # both would arrive as None and be indistinguishable. + provided = changes.model_dump(exclude_unset=True) + if not provided: + s.fail("没有给出任何要修改的字段") + + payload = _validated_update(provided) + with s.session() as db: + reference = _or_fail(db, reference_id) + updated = reference_crud.update(db, reference, payload) + return s.dumps(_read_row(reference_crud.read(db, updated))) + + @mcp_tool(server, title="删除文献") + def reference_delete( + reference_ids: Annotated[int | list[int], Field(description="文献 id,或 id 数组")], + ) -> str: + """删除文献。正被论文引用的会被拒绝,需先在段落里移除引用。""" + ids = s.id_list(reference_ids) + if not ids: + s.fail("必须给出至少一个文献 id") + + with s.session() as db: + references = reference_crud.get_many(db, ids) + _assert_not_cited(db, references) + deleted = reference_crud.delete_many(db, ids) + found = {reference.id for reference in references} + return s.dumps( + { + "deleted": deleted, + "ids": [reference_id for reference_id in ids if reference_id in found], + "missing": [ + reference_id for reference_id in ids if reference_id not in found + ], + } + ) + + @mcp_tool(server, title="批量录入文献") + def reference_import( + references: Annotated[ + list[ReferenceSpec], + Field(description="要录入的文献数组,每条与 reference_create 的形状相同"), + ], + skip_duplicates: Annotated[ + bool, + Field(description="true(默认)=同 DOI 或同题名的已存在,跳过不重复建"), + ] = True, + ) -> str: + """一次录入多条文献,自动跳过重复的,并逐条报告失败原因。""" + if not references: + s.fail("references 不能为空") + + created: list[dict[str, Any]] = [] + skipped: list[dict[str, Any]] = [] + failed: list[dict[str, Any]] = [] + + with s.session() as db: + for spec in references: + try: + payload = _validated(spec) + except Exception as error: # noqa: BLE001 - reported per entry + # One bad entry must not lose the other nineteen: a model + # handing over a pasted bibliography has usually mistyped + # one type or left one title blank. + failed.append({"title": spec.title, "error": str(error)}) + continue + + if skip_duplicates: + duplicate = _duplicate_of(db, payload) + if duplicate is not None: + skipped.append( + {"title": payload.title, "existing_id": duplicate} + ) + continue + + try: + row = reference_crud.create(db, payload) + except Exception as error: # noqa: BLE001 - reported per entry + db.rollback() + failed.append({"title": payload.title, "error": str(error)}) + continue + + created.append({"id": row.id, "title": row.title}) + + return s.dumps( + { + "created": created, + "skipped": skipped, + "failed": failed, + "total": len(references), + } + ) + + @mcp_tool(server, title="文献被谁引用") + def reference_citations( + reference_id: Annotated[int, Field(description="文献 id")], + ) -> str: + """查这条文献被哪些句子引用了——改稿或删除前用它确认影响面。""" + with s.session() as db: + reference = _or_fail(db, reference_id) + citations = reference_crud.list_citations(db, reference) + return s.dumps( + { + "reference_id": reference.id, + "title": reference.title, + "total": len(citations), + "items": [ + { + "paper_id": item.paper_id, + "paper_title": item.paper_title, + "position": item.paper_template_filed_sort, + "paragraph": item.paragraph_name, + "sentence_id": item.sentence_id, + "quote": item.quote, + "sentence": item.sentence_content, + } + for item in citations + ], + } + ) + + +# --- helpers ----------------------------------------------------------------- + + +def _or_fail(db: Session, reference_id: int): + """Return one reference, or refuse with the id that was not found.""" + reference = reference_crud.get(db, reference_id) + if reference is None: + s.fail(f"参考文献 {reference_id} 不存在") + return reference + + +def _validated(spec: ReferenceSpec) -> ReferenceCreate: + """Turn a tool argument into the domain payload, refusing politely. + + Pydantic's own message is a list of field errors addressed to a programmer; + the first one is what a model can act on, so it is what the refusal carries. + """ + try: + return ReferenceCreate(**spec.model_dump()) + except ValidationError as error: + first = error.errors()[0] + field = ".".join(str(part) for part in first.get("loc") or ()) + s.fail(f"文献不合法({field or '字段'}):{first.get('msg')}") + + +def _validated_update(provided: dict[str, Any]) -> ReferenceUpdate: + """Same, for the update shape: only the keys the caller wrote are passed.""" + try: + return ReferenceUpdate(**provided) + except ValidationError as error: + first = error.errors()[0] + field = ".".join(str(part) for part in first.get("loc") or ()) + s.fail(f"字段不合法({field or '字段'}):{first.get('msg')}") + + +def _duplicate_of(db: Session, payload: ReferenceCreate) -> int | None: + """The id of an entry this one repeats, if the library already holds it. + + Two tests, in order of how much they prove: an exact DOI is the same work + by definition, while an exact title is the same work in practice — two + different papers sharing a full title is rare enough that the cost of a + wrong skip (one lookup) is far below the cost of a wrong create (a + bibliography with the same paper twice, cited under two ids). + """ + if payload.doi: + rows, _ = reference_crud.list_references(db, keyword=payload.doi, page_size=10) + wanted = payload.doi.strip().casefold() + for row in rows: + if row.doi and row.doi.strip().casefold() == wanted: + return row.id + + rows, _ = reference_crud.list_references(db, keyword=payload.title, page_size=10) + wanted_title = payload.title.strip().casefold() + for row in rows: + if row.title.strip().casefold() == wanted_title: + return row.id + return None + + +def _list_row(item: Any) -> dict: + """One reference as a browse row: enough to recognise it, no more.""" + return { + "id": item.id, + "type": item.type, + "title": item.title, + "subtitle": item.subtitle, + "authors": item.authors_line, + "author_count": item.author_count, + "year": item.publication_year, + "container": item.container_title, + "publisher": item.publisher, + "volume": item.volume, + "issue": item.issue, + "pages": item.pages, + "doi": item.doi, + "tags": [tag.name for tag in item.tags], + "citations": item.citation_count, + } + + +def _read_row(reference: Any) -> dict: + """One reference in full, with its authors and tags flattened. + + ``clean`` drops every unset column on the way out, so a record filled in + halfway reads as the handful of fields it actually has rather than as + thirty-eight keys and a wall of nulls. + """ + return { + **reference.model_dump( + exclude={"authors", "tags", "created_at", "updated_at"} + ), + "authors": [ + { + "name": author.name, + "family_name": author.family_name, + "given_name": author.given_name, + "role": author.role, + "sort": author.sort, + } + for author in reference.authors + ], + "tags": [{"id": tag.id, "name": tag.name} for tag in reference.tags], + "updated_at": reference.updated_at, + } + + +def _assert_not_cited(db: Session, references: list[Any]) -> None: + """Refuse the delete while any sentence cites the reference. + + The twin of ``_assert_not_cited`` in ``app/api/routes/references.py``: the + rule is one rule, but each door states it in its own error type — HTTP 409 + there, a readable tool error here. All offenders are reported at once so a + batch delete does not become trial and error. + """ + counts = reference_crud.citation_counts(db, [row.id for row in references]) + if not counts: + return + + titles = {row.id: row.title for row in references} + blockers = "、".join( + f"“{titles.get(reference_id, reference_id)}”({count} 处引用)" + for reference_id, count in sorted(counts.items()) + ) + s.fail("以下文献正被论文引用,请先在段落里移除对应引用:" + blockers) diff --git a/backend/app/mcp/tools/registry.py b/backend/app/mcp/tools/registry.py index 4b61e4f..cc65186 100644 --- a/backend/app/mcp/tools/registry.py +++ b/backend/app/mcp/tools/registry.py @@ -33,9 +33,21 @@ from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError from app.crud.reference import UnknownReference +from app.crud.reference_tag import DuplicateTagName, UnknownTag F = TypeVar("F", bound=Callable[..., Any]) +#: Refusals the data layer raises on purpose. Each one already carries a +#: message written for a reader; the only thing missing is the translation into +#: the transport's own error type, which is the whole job of the wrapper below. +#: +#: A tuple rather than a single class because there is one of these per rule, +#: and the tag rules arrived with the tag tools: catching only the reference one +#: 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) + def mcp_tool( server: MCPServer, @@ -53,7 +65,7 @@ def mcp_tool( # "Error executing tool ...", which says nothing about what to fix. try: return fn(*args, **kwargs) - except UnknownReference as error: + except DOMAIN_REFUSALS as error: raise ToolError(str(error)) from error server.add_tool( @@ -67,4 +79,4 @@ def mcp_tool( return decorator -__all__ = ["mcp_tool"] +__all__ = ["DOMAIN_REFUSALS", "mcp_tool"] diff --git a/backend/app/mcp/tools/templates.py b/backend/app/mcp/tools/templates.py index 78f00c7..a650ee1 100644 --- a/backend/app/mcp/tools/templates.py +++ b/backend/app/mcp/tools/templates.py @@ -60,7 +60,13 @@ def register(server: MCPServer) -> None: "id": item.id, "name": item.name, "abstract": item.abstract, - "fields": item.field_count, + # Read from ``placement_count`` — the column this + # interface calls a field count. The rename that + # introduced "placement" changed the schema and left + # this read behind, which is why this tool is the + # one the first tool sweep found broken: the key + # stays "fields" for callers, the attribute does not. + "fields": item.placement_count, "updated_at": item.updated_at, } for item in items diff --git a/backend/scripts/smoke_mcp.py b/backend/scripts/smoke_mcp.py index f306d8a..0f461c5 100644 --- a/backend/scripts/smoke_mcp.py +++ b/backend/scripts/smoke_mcp.py @@ -43,13 +43,15 @@ 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.models import Paper, Reference, Template # noqa: E402 +from app.models import Paper, Reference, ReferenceTag, Template # noqa: E402 SERVER_SCRIPT = BACKEND_DIR / "scripts" / "mcp_server.py" _checks = 0 _created_papers: list[int] = [] _created_templates: list[int] = [] +_created_references: list[int] = [] +_created_tags: list[int] = [] def check(label: str, condition: bool, detail: str = "") -> None: @@ -97,15 +99,6 @@ async def expect_error(session: ClientSession, tool: str, **arguments: Any) -> s ) -class _Box: - """A one-slot holder, so the citation helper can read what the context set.""" - - value: int | None = None - - -_CITATION_REFERENCE_ID = _Box() - - def pick_template() -> tuple[int, list[dict[str, Any]]]: """The template with the most titles, and its outline as the tools see it.""" with SessionLocal() as db: @@ -154,8 +147,7 @@ async def connect(url: str | None, token: str | None) -> AsyncIterator[ClientSes async def run(url: str | None = None, token: str | None = None) -> int: - with reference_for_citation(): - return await _run(url, token) + return await _run(url, token) async def _run(url: str | None = None, token: str | None = None) -> int: @@ -175,11 +167,20 @@ 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("29 tools are published", len(names) == 29, f"got {len(names)}") + check("the whole surface is published", len(names) == 41, f"got {len(names)}") check( "every group is reachable", - {"paper_write", "paragraph_write", "sentence_add", "template_get", "field_list"} + { + "paper_write", + "paragraph_write", + "sentence_add", + "template_get", + "field_list", + "reference_create", + "reference_tag_create", + } <= names, + ", ".join(sorted(names)), ) check( "no tool returns a structured envelope", @@ -243,7 +244,66 @@ async def _run(url: str | None = None, token: str | None = None) -> int: json.dumps(written, ensure_ascii=False), ) - print("\n5. a heading the template does not have is refused, with candidates") + print("\n5. every read tool answers") + # The read-only tools are what a suite forgets, and they are where a + # rename bites: `template_list` read a schema attribute that no longer + # existed and crashed with an unreadable "Error executing tool" while + # every other check here passed, because nothing called it. Each + # assertion below is about the *shape* a caller depends on, not merely + # that the call came back. + templates = await call(session, "template_list", page_size=50) + check( + "template_list lists the paper's template", + any(item["id"] == template_id for item in templates["items"]), + json.dumps(templates, ensure_ascii=False)[:300], + ) + check( + "and reports how many fields it places", + all(isinstance(item.get("fields"), int) for item in templates["items"]), + json.dumps(templates["items"], ensure_ascii=False)[:300], + ) + + fetched_template = await call(session, "template_get", template_id=template_id) + positions = [item["position"] for item in fetched_template["fields"]] + check( + "template_get returns the outline already ordered", + positions == sorted(positions) and len(positions) == len(outline), + json.dumps(positions), + ) + + library = await call(session, "field_list", page_size=5) + check( + "field_list pages the library", + library["total"] >= 1 and len(library["items"]) <= 5, + json.dumps({key: library[key] for key in ("total", "page_size", "pages")}), + ) + one_field = await call(session, "field_get", field_id=library["items"][0]["id"]) + check( + "field_get returns that same entry", + one_field["id"] == library["items"][0]["id"], + json.dumps(one_field, ensure_ascii=False), + ) + + listed_papers = await call(session, "paper_list", keyword="SMOKE MCP") + check( + "paper_list finds the paper by title", + any(item["id"] == paper["id"] for item in listed_papers["items"]), + json.dumps(listed_papers, ensure_ascii=False)[:300], + ) + fetched_paper = await call(session, "paper_get", paper_id=paper["id"]) + check( + "paper_get reports the four sentences written so far", + fetched_paper["sentences"] == 4, + json.dumps(fetched_paper, ensure_ascii=False), + ) + paragraphs = await call(session, "paragraph_list", paper_id=paper["id"]) + check( + "paragraph_list covers every position the template defines", + len(paragraphs["items"]) == len(positions), + f"{len(paragraphs['items'])} vs {len(positions)}", + ) + + print("\n6. a heading the template does not have is refused, with candidates") message = await expect_error( session, "paragraph_write", @@ -253,7 +313,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int: ) check("the refusal lists the real headings", first in message, message) - print("\n6. read one paragraph back") + print("\n7. read one paragraph back") paragraph = await call( session, "paragraph_get", paper_id=paper["id"], heading=first ) @@ -264,14 +324,162 @@ async def _run(url: str | None = None, token: str | None = None) -> int: json.dumps(paragraph["sentences"], ensure_ascii=False), ) - print("\n7. append a sentence with a citation") + print("\n8. the reference library") + tag = await call( + session, "reference_tag_create", name="SMOKE MCP 标签", color="#123456" + ) + _created_tags.append(tag["id"]) + check("a tag can be created", tag["name"] == "SMOKE MCP 标签", json.dumps(tag, ensure_ascii=False)) + + created_reference = 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.001", + "language": "en", + "authors": [ + {"name": "Smith, John", "family_name": "Smith", "given_name": "John"}, + {"name": "张三", "role": "editor"}, + ], + "tag_ids": [tag["id"]], + }, + ) + reference_id = created_reference["id"] + _created_references.append(reference_id) + check( + "authors keep the order they were sent in", + [author["name"] for author in created_reference["authors"]] == ["Smith, John", "张三"], + json.dumps(created_reference["authors"], ensure_ascii=False), + ) + check( + "and the tag is attached", + [item["name"] for item in created_reference["tags"]] == ["SMOKE MCP 标签"], + json.dumps(created_reference["tags"], ensure_ascii=False), + ) + + tags = await call(session, "reference_tag_list", keyword="SMOKE MCP") + check( + "reference_tag_list counts the literature under the tag", + any(item["id"] == tag["id"] and item["references"] == 1 for item in tags["items"]), + json.dumps(tags, ensure_ascii=False)[:300], + ) + + one_tag = await call(session, "reference_tag_get", tag_id=tag["id"]) + check( + "reference_tag_get returns that same tag", + one_tag["id"] == tag["id"] and one_tag["references"] == 1, + json.dumps(one_tag, ensure_ascii=False), + ) + + retagged = await call( + session, + "reference_tag_update", + tag_id=tag["id"], + color="#ABCDEF", + note="测试备注", + ) + check( + "reference_tag_update changes only what it was given", + retagged["color"] == "#ABCDEF" + and retagged["note"] == "测试备注" + and retagged["name"] == "SMOKE MCP 标签", + json.dumps(retagged, ensure_ascii=False), + ) + + unlabelled_note = await call( + session, "reference_tag_update", tag_id=tag["id"], clear_note=True + ) + check( + "clear_note takes the note back off", + "note" not in unlabelled_note, + json.dumps(unlabelled_note, ensure_ascii=False), + ) + + by_doi = await call(session, "reference_list", keyword="10.1000/smoke.mcp.001") + check( + "reference_list finds it by DOI", + any(item["id"] == reference_id for item in by_doi["items"]), + json.dumps(by_doi, ensure_ascii=False)[:300], + ) + check( + "a row carries its citation count", + all(isinstance(item.get("citations"), int) for item in by_doi["items"]), + json.dumps(by_doi["items"], ensure_ascii=False)[:300], + ) + + fetched_reference = await call(session, "reference_get", reference_id=reference_id) + check( + "reference_get returns the whole record", + fetched_reference["doi"] == "10.1000/smoke.mcp.001" + and fetched_reference["container_title"] == "Journal of Smoke Tests", + json.dumps(fetched_reference, ensure_ascii=False)[:300], + ) + + patched = await call( + session, + "reference_update", + reference_id=reference_id, + changes={"note": "由测试写入", "publication_year": 2025}, + ) + check( + "reference_update changes only what it was given", + patched["publication_year"] == 2025 and patched["title"] == "SMOKE MCP 文献", + json.dumps(patched, ensure_ascii=False)[:300], + ) + + cleared = await call( + session, "reference_update", reference_id=reference_id, changes={"note": None} + ) + check( + "an explicit null clears the field", + "note" not in cleared, + json.dumps(cleared, ensure_ascii=False)[:200], + ) + + imported = await call( + session, + "reference_import", + references=[ + {"title": "SMOKE MCP 导入一", "publication_year": 2020}, + {"title": "SMOKE MCP 导入二", "publication_year": 2021}, + {"title": "SMOKE MCP 文献", "doi": "10.1000/smoke.mcp.001"}, + {"title": " ", "type": "journal-article"}, + ], + ) + imported_ids = [item["id"] for item in imported["created"]] + _created_references.extend(imported_ids) + check( + "import creates the entries that are new", + len(imported["created"]) == 2, + json.dumps(imported, ensure_ascii=False)[:400], + ) + check( + "skips the one the library already has, naming it", + len(imported["skipped"]) == 1 + and imported["skipped"][0]["existing_id"] == reference_id, + json.dumps(imported["skipped"], ensure_ascii=False), + ) + check( + "and reports the bad entry without losing the rest", + len(imported["failed"]) == 1 and imported["failed"][0]["title"].strip() == "", + json.dumps(imported["failed"], ensure_ascii=False), + ) + + print("\n9. append a sentence with a citation") added = await call( session, "sentence_add", paper_id=paper["id"], heading=first, content="A cited sentence.", - citations=[{"quote": "引用的原话", "reference_id": _reference_id()}], + citations=[{"quote": "引用的原话", "reference_id": reference_id}], ) check("appended", added["sentence"]["content"] == "A cited sentence.") check("the citation is stored", added["sentence"]["citations"][0]["quote"] == "引用的原话") @@ -283,7 +491,51 @@ async def _run(url: str | None = None, token: str | None = None) -> int: json.dumps(after["sentences"][-1], ensure_ascii=False), ) - print("\n8. edit one sentence without touching its paragraph") + print("\n10. a cited reference cannot be deleted") + citations = await call(session, "reference_citations", reference_id=reference_id) + check( + "the reference reports the sentence citing it", + citations["total"] == 1 + and citations["items"][0]["paper_id"] == paper["id"] + and citations["items"][0]["quote"] == "引用的原话", + json.dumps(citations, ensure_ascii=False)[:400], + ) + + message = await expect_error(session, "reference_delete", reference_ids=[reference_id]) + check("deleting it is refused with the count", "1 处引用" in message, message) + + cited = await call(session, "sentence_list", paper_id=paper["id"]) + sentence_id = next(row["id"] for row in cited["items"] if row["citations"]) + await call( + session, + "sentence_update", + paper_id=paper["id"], + sentence_id=sentence_id, + citations=[], + ) + check( + "clearing the citation frees the reference", + (await call(session, "reference_citations", reference_id=reference_id))["total"] == 0, + ) + + freed = await call(session, "reference_delete", reference_ids=reference_id) + check("now it deletes", freed["deleted"] == 1, json.dumps(freed, ensure_ascii=False)) + _created_references.remove(reference_id) + + batch = await call(session, "reference_delete", reference_ids=imported_ids) + check( + "a batch delete takes the imported ones too", + batch["deleted"] == len(imported_ids), + json.dumps(batch, ensure_ascii=False), + ) + for imported_id in imported_ids: + _created_references.remove(imported_id) + + dropped = await call(session, "reference_tag_delete", tag_ids=tag["id"]) + check("and the tag goes with it", dropped["deleted"] == 1, json.dumps(dropped, ensure_ascii=False)) + _created_tags.remove(tag["id"]) + + print("\n11. edit one sentence without touching its paragraph") edited = await call( session, "sentence_update", @@ -295,7 +547,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int: still = await call(session, "paragraph_get", paper_id=paper["id"], heading=first) check("the other sentences kept their ids", still["sentences"][1]["id"] == after["sentences"][1]["id"]) - print("\n9. delete one sentence") + print("\n12. delete one sentence") before = await call(session, "sentence_list", paper_id=paper["id"]) await call( session, @@ -310,7 +562,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int: f"{before['total']} -> {remaining['total']}", ) - print("\n10. write a whole generated document in one call") + print("\n13. write a whole generated document in one call") generated = "\n".join( [f"# {item['name']}" + "\n" + f"{item['name']}的正文写在标题下面。这句话是第二句。" for item in outline] @@ -325,7 +577,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int: ) check("nothing was left unmatched", "unmatched" not in whole, json.dumps(whole, ensure_ascii=False)) - print("\n11. read the paper as a document") + print("\n14. read the paper as a document") document = await call(session, "paper_document", paper_id=paper["id"]) check("the text carries every heading", all(item["name"] in document["text"] for item in outline)) check("and every paragraph", document["text"].count("正文写在标题下面") == len(outline)) @@ -341,11 +593,11 @@ async def _run(url: str | None = None, token: str | None = None) -> int: ), ) - print("\n12. search across papers") + 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("\n13. move a paragraph, then clear the one it moved onto") + print("\n16. move a paragraph, then clear the one it moved onto") home = outline[0] target = outline[1] relocation = await call( @@ -377,7 +629,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("\n14. the field library round-trips") + print("\n17. 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 字段(改)") @@ -386,7 +638,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("\n15. switch the template and keep the content") + print("\n18. switch the template and keep the content") spare = await call( session, "template_create", @@ -430,15 +682,15 @@ async def _run(url: str | None = None, token: str | None = None) -> int: json.dumps(switched_document, ensure_ascii=False)[:400], ) - print("\n16. a template in use cannot be deleted") + print("\n19. 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("\n17. deleting a paper needs an explicit confirmation") + print("\n20. 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("\n18. delete the paper and the template") + print("\n21. 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"]) @@ -450,38 +702,6 @@ async def _run(url: str | None = None, token: str | None = None) -> int: return 0 -@contextmanager -def reference_for_citation() -> Iterator[int]: - """A library entry the citation checks can point at. - - A citation names real literature now, so the test has to have some: the MCP - surface has no reference tools yet, and this creates the row directly. - """ - with SessionLocal() as db: - reference = Reference(type="journal-article", title="SMOKE MCP 文献") - db.add(reference) - db.commit() - db.refresh(reference) - reference_id = reference.id - _CITATION_REFERENCE_ID.value = reference_id - try: - yield reference_id - finally: - with SessionLocal() as db: - stored = db.get(Reference, reference_id) - if stored is not None: - db.delete(stored) - db.commit() - _CITATION_REFERENCE_ID.value = None - - -def _reference_id() -> int: - """The id the current citation check should use.""" - if _CITATION_REFERENCE_ID.value is None: - raise AssertionError("no reference in scope for this citation check") - return _CITATION_REFERENCE_ID.value - - def _field_id(name: str) -> int: """The library field behind a heading name, for the template-create step.""" from app.models import TemplateTitle @@ -511,6 +731,24 @@ def cleanup() -> None: db.delete(template) db.commit() print(f"cleaned up templates {_created_templates}") + # References go before tags: a reference carries tag links, and a tag + # deleted out from under one would leave the link pointing at nothing. + if _created_references: + with SessionLocal() as db: + for reference in db.scalars( + select(Reference).where(Reference.id.in_(_created_references)) + ).all(): + db.delete(reference) + db.commit() + print(f"cleaned up references {_created_references}") + if _created_tags: + with SessionLocal() as db: + for tag in db.scalars( + select(ReferenceTag).where(ReferenceTag.id.in_(_created_tags)) + ).all(): + db.delete(tag) + db.commit() + print(f"cleaned up tags {_created_tags}") def parse_args(argv: list[str] | None = None) -> argparse.Namespace: @@ -546,6 +784,19 @@ def main(argv: list[str] | None = None) -> int: ).all() for template in stale_templates: db.delete(template) + # References and tags from a run that died before cleanup: the suite + # creates them through the tools now, so a failure between the two + # steps leaves rows the next run would trip over (a duplicate tag name + # refuses the create outright). + for reference in db.scalars( + select(Reference).where(Reference.title.like("SMOKE MCP%")) + ).all(): + db.delete(reference) + db.flush() + for tag in db.scalars( + select(ReferenceTag).where(ReferenceTag.name.like("SMOKE MCP%")) + ).all(): + db.delete(tag) db.commit() try: diff --git a/deploy/k8s/10-paper-doc-mcp.yaml b/deploy/k8s/10-paper-doc-mcp.yaml index bee8a76..b3b1d0e 100644 --- a/deploy/k8s/10-paper-doc-mcp.yaml +++ b/deploy/k8s/10-paper-doc-mcp.yaml @@ -67,7 +67,7 @@ spec: type: RuntimeDefault containers: - name: mcp - image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v3 + image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v4 imagePullPolicy: IfNotPresent ports: - name: http @@ -178,13 +178,13 @@ spec: # imagePullSecrets: [{name: aliyun-acr}] # initContainers: # - name: migrate -# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v3 +# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v4 # command: ["alembic", "upgrade", "head"] # envFrom: [{configMapRef: {name: paper-doc-config}}] # env: [...] # the same three secret keys as above # containers: # - name: api -# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v3 +# image: registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v4 # 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/docs/MCP.md b/docs/MCP.md index 7924a00..847561f 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 客户端跑 47 项检查,stdio 与 HTTP 都过) -- 工具数量:**29 个**,按 `paper_` / `paragraph_` / `sentence_` / `template_` / `field_` 五组前缀 +- 冒烟测试:`backend/scripts/smoke_mcp.py`(真 MCP 客户端跑 76 项检查、覆盖 41/41 个工具,stdio 与 HTTP 都过) +- 工具数量:**41 个**,按 `paper_` / `paragraph_` / `sentence_` / `template_` / `field_` / `reference_` / `reference_tag_` 七组前缀 - 协议: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,10 +98,10 @@ cd /data/project/paper/backend .venv/bin/python scripts/smoke_mcp.py --url http://127.0.0.1:8931/mcp --token 你的口令 # 连已有的 HTTP 服务 ``` -同一个套件 **47 项检查**跑两种传输,覆盖 18 个步骤:建论文 → 看骨架 → 按标题写段落 → +同一个套件 **76 项检查**跑两种传输,覆盖 21 个步骤:建论文 → 看骨架 → 按标题写段落 → 定位失败时列出候选标题 → 读段落/追加带引用的句子 → 只改一句 → 删一句 → 整篇一次写入 → 读全文 → 跨论文搜索 → 搬段落 → 清空段落 → 字段库增删改 → 建/改模板 → 换模板后正文不丢 → -删模板被拒 → 删论文要确认 → 清理。写真实数据,结束时自己删干净。 +文献库增删改查与批量导入 → 引用守卫(被引用的文献删不掉)→ 删模板被拒 → 删论文要确认 → 清理。写真实数据,结束时自己删干净。 --- @@ -323,6 +323,66 @@ Header: Authorization: Bearer --- +### 3.6 参考文献 references(7 个) + +参考文献库是引用的另一半:句子上的 `reference_id` 指向它。建文献前**先用 `reference_list` 查重**—— +`keyword` 会同时搜题名、副题名、期刊名、DOI、关键词、备注和作者名。 + +| 工具 | 作用 | 关键参数 | +|---|---|---| +| `reference_list` | 检索文献库(也是查重路径) | `keyword?` `type?` `year?` `cited_only?` `tag_ids?` `page?` `page_size?` | +| `reference_get` | 取一条文献的全部字段 | `reference_id` | +| `reference_create` | 新增一条 | `reference`(对象,见下)| +| `reference_update` | 改字段,只传要改的 | `reference_id`、`changes` | +| `reference_delete` | 删(被引用的会被拒) | `reference_ids`(int 或数组) | +| `reference_import` | **一次录入一批**,自动跳过重复 | `references`(数组)、`skip_duplicates?` | +| `reference_citations` | **这条文献被哪些句子引用了** | `reference_id` | + +`reference_create` 的 `reference` 对象(39 个字段,全都有默认值,能填多少填多少): + +```jsonc +{ + "type": "journal-article", // journal-article / book / book-chapter / conference-paper / + // thesis / patent / standard / report / newspaper-article / + // web-page / dataset / software / preprint / other + "title": "题名(必填)", + "authors": [ // 顺序即印刷顺序 + {"name": "Smith, John", "family_name": "Smith", "given_name": "John"}, + {"name": "张三", "role": "editor"} // role: author(默认)/ editor / translator / compiler + ], + "container_title": "期刊名", "volume": "12", "issue": "3", "pages": "45-67", + "publication_year": 2024, "doi": "10.1000/xyz", "url": "…", + "keywords": "…", "abstract": "…", "note": "…", "language": "en", + "isbn": "…", "issn": "…", "patent_number": "…", "standard_number": "…", + "accessed_date": "2024-05-01", "citation_key": "smith2024flood", + "tag_ids": [3, 7] +} +``` + +`reference_update` 的 `changes` 只写要改的字段;**传 `null` 表示清空该字段**(不传就是不动): + +```jsonc +{"name": "reference_update", "arguments": { + "reference_id": 42, + "changes": {"publication_year": 2025, "doi": "10.1000/xyz-v2", "note": null} +}} +``` + +`authors` 和 `tag_ids` 一给就是**整体替换**(`tag_ids: []` 清空标签)。 + +### 3.7 文献标签 reference_tag(5 个) + +标签不是分类,是标记(「必读」「方法」「待核实」)。删标签**不会**动文献——只掉标记; +删文献则要求它没被引用。 + +| 工具 | 作用 | 关键参数 | +|---|---|---| +| `reference_tag_list` | 列标签(含每个标签下几条文献)| `keyword?` `page?` `page_size?` | +| `reference_tag_get` | 取一个标签 | `tag_id` | +| `reference_tag_create` | 新建(名称唯一)| `name`、`color?` `note?` | +| `reference_tag_update` | 改名/颜色/备注 | `tag_id`、`name?` `color?` `note?` `clear_note?` | +| `reference_tag_delete` | 删标签(文献不受影响)| `tag_ids`(int 或数组)| + ## 4. 典型用法 ### 4.1 AI 写完,整篇一次灌进去(主推) @@ -423,6 +483,36 @@ Header: Authorization: Bearer --- +### 4.7 文献:查重 → 录入 → 引用 → 复查 + +```jsonc +// 1) 先查库里有没有(DOI / 题名 / 作者都能搜) +{"name": "reference_list", "arguments": {"keyword": "10.1000/xyz"}} + +// 2) 没有就录;一次一批更省事(重复的会自动跳过,坏的逐条报告,不连累其它条) +{"name": "reference_import", "arguments": {"references": [ + {"type": "journal-article", "title": "A flood study", "container_title": "J. Hydrol.", + "publication_year": 2023, "volume": "61", "issue": "2", "pages": "1-18", + "doi": "10.1000/xyz", "authors": [{"name": "Smith, John"}]}, + {"type": "book", "title": "另一本书", "publisher": "某出版社", "publication_year": 2019, + "authors": [{"name": "张三"}]} +]}} +// → {"created":[{"id":42,…},{"id":43,…}], "skipped":[{"title":"…","existing_id":7}], "failed":[…]} + +// 3) 写正文时引用它(citations 里给 reference_id 和引用的原话) +{"name": "paragraph_write", "arguments": { + "paper_id": 96, "heading": "2 Related Work", + "sentences": [{"content": "已有研究指出……", "citations": [{"quote": "引用的原话", "reference_id": 42}]}] +}} + +// 4) 改稿前先看影响面:这条文献被哪些句子用了 +{"name": "reference_citations", "arguments": {"reference_id": 42}} +// → {"total":2, "items":[{"paper_id":96,"position":30,"paragraph":"2 Related Work","sentence_id":512,"quote":"引用的原话"}]} +``` + +删文献时如果它还被引用,会被拒绝并报出「(N 处引用)」——先按上面第 4 步找到那些句子、 +用 `sentence_update(citations=[])` 摘掉引用,再删。 + ## 5. 返回值与错误约定 - **成功**:`content[0].text` 是一段 JSON 字符串。例如 `paper_list` 返回 @@ -437,6 +527,11 @@ Header: Authorization: Bearer | 删除模板被拒 | `以下模板正被论文使用,请先用 paper_update 给论文切换模板:“…”(2 篇论文)` | | 删字段被拒 | `以下字段正被模板使用,请先用 template_update 从模板里移除:“…”(1 个模板)` | | 删论文没确认 | `…确认无误后请带 confirm=true 重新调用` | + | 删被引用的文献 | `以下文献正被论文引用,请先在段落里移除对应引用:“…”(2 处引用)` | + | 引用了不存在的文献 | `参考文献不存在:42` | + | 给文献打了不存在的标签 | `标签不存在:9` | + | 标签重名 | `标签「必读」已存在` | + | 文献字段不合法 | `文献不合法(type):文献类型只能是:journal-article、book、…` | | 参数写错 | SDK 层的参数校验错误(列出哪个字段不合法) | 所有消息都写成"哪里错 + 怎么修",因为读它的是模型,它据此重试一次就能成功。 @@ -489,7 +584,13 @@ REST 和 MCP 同时生效。这让"网页里看到的"和"AI 写进去的"永远 | 改一句 | `PATCH /api/papers/{id}/sentences/{id}` | `sentence_update` | | 搜句子 | —(MCP 专有) | `sentence_search` | | 建模板 | `POST /api/templates` | `template_create` | -| 字段库 | `/api/template-field-library` | `field_*` | +| 字段库 | `/api/templates/titles` | `field_*` | +| 列/搜文献 | `GET /api/references` | `reference_list` | +| 建文献 | `POST /api/references` | `reference_create` | +| 改文献 | `PATCH /api/references/{id}` | `reference_update` | +| 删文献 | `DELETE /api/references/{id}` | `reference_delete` | +| 谁引用了它 | `GET /api/references/{id}/citations` | `reference_citations` | +| 文献标签 | `/api/reference-tags` | `reference_tag_*` | MCP 独有:`paper_outline`(写前看骨架)、`paper_write` / `paper_write_text`(批量写入)、 `paragraph_move`、`sentence_search`。 diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md index b6cf838..fba428a 100644 --- a/docs/OVERVIEW.md +++ b/docs/OVERVIEW.md @@ -464,6 +464,8 @@ written by an agent is indistinguishable from one written by hand. What | `paper_write` / `paper_write_text` | "generate the paper, then put it in" is one intention, not thirty round trips | | `paper_delete` refuses once before it deletes | a cascading delete has no undo in a tool call | | `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 | 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 @@ -486,7 +488,19 @@ a database that is briefly unreachable cannot become a restart loop, while readiness runs `SELECT 1` so the pod leaves the Service's endpoints while TiDB is down and rejoins when it is not. -Two decisions are worth knowing before adding a tool. **Results are registered +Two shape decisions are worth knowing before adding a tool. **A nested argument +model keeps `model_fields_set`**, which a flattened signature cannot: 38 +bibliographic fields spread across keyword parameters would arrive with the +omitted ones indistinguishable from explicit nulls, so `reference_update` takes +its changes as one object and forwards only the keys the caller actually wrote. +And **a domain refusal belongs in `DOMAIN_REFUSALS`** in `tools/registry.py` on +the day it is written — `UnknownReference` was translated there when the +reference tools were still to come, and the tag rules (`UnknownTag`, +`DuplicateTagName`) had to be added when those tools landed, because an +unlisted refusal reaches the model as `Error executing tool …` and says nothing +about what to fix. + +Two more decisions are worth knowing. **Results are registered with `structured_output=False`**: inferred from a `-> str` annotation, the SDK publishes a `{"result": …}` envelope and sends the JSON twice, once as `structuredContent` and once as text, and clients that read only one of the two