backend: give the reference library the MCP tools it was missing, and fix the one that broke
The reference library landed with a full REST API and no MCP surface at all: an agent could cite `reference_id: 42` — the citation is validated now — but could not look up what 42 was, create it, or find out whether the library already had it. That is the citation half of "generate the paper, then write it in" missing, and it is the half an agent is worst at doing by hand. Twelve tools, mirroring the REST surface plus one addition each way: - `reference_*` — search, read, create, update, delete, plus `reference_import`, which takes a whole pasted bibliography in one call and reports what it skipped (an existing DOI or an identical title) and what it could not read, one bad entry at a time rather than losing the other nineteen; and `reference_citations`, which answers "what is this cited for" before a rename or a delete. `reference_list`'s keyword search across title, container, DOI and author names is the de-duplication path that `reference_import` uses. - `reference_tag_*` — the five CRUD tools. Deleting a tag drops the labelling and leaves the literature, which is the opposite of what the field library needs and the same choice the REST route makes. Two things had to be fixed to get here, both found by testing rather than reading: `template_list` was crashing. The rename that turned a heading into a title and its use into a placement changed `TemplateListItem.field_count` to `placement_count` and left the tool reading the old attribute, so the call died with `Error executing tool template_list` — unreadable, and live in the cluster. The suite passed 47 checks while this was broken because it never called `template_list`: the uncovered tools were exactly the read-only ones, so the write paths were all green and the browse path was not. The suite now covers all 41 tools — 76 checks — and step 5 asserts the shape each read tool returns, not merely that it returned. `DOMAIN_REFUSALS` in the tool registry held one class, `UnknownReference`. The tag rules arrived with the tag tools and raise two more, so 「标签不存在:9」 and 「标签「必读」已存在」 would have reached a model as `Error executing tool …`. The tuple is now the list of every refusal a tool is expected to translate, and a new one belongs in it on the day it is written. `reference_update` takes its changes as one nested object rather than 38 keyword parameters: a nested model keeps `model_fields_set`, so an omitted field stays absent while an explicit null clears the column. Flattened, the two are indistinguishable — every omitted field arrives as None — which is the same problem `paper_update` solves by rebuilding its payload from what it was given. Verified against the deployed service, not a local process: 76 checks pass over the NodePort, then the same 76 over stdio and against a local HTTP server, and the REST suite still passes its 55. The image is rebuilt as v4 and the Deployment follows it, because `imagePullPolicy: IfNotPresent` means re-pushing a tag the node already holds changes nothing.
This commit is contained in:
@@ -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",
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user