"""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)