Files
paper-doc/backend/app/mcp/selfcheck.py
T
govin 199e328b48 refactor: call a heading a title, and its use a placement
`template_field_library` and `template_field` were one word apart and meant
opposite kinds of thing — a catalogue of rows versus one row — and neither name
said what a row actually is. Every row of the library is a **heading**: a piece
of text like 「1. Introduction」 with a level and typography, which is what the
reader sees at the top of a paragraph; and every row of the join table is that
heading *placed* in a template, `sort` included.

    template_field_library  -> template_title
    template_field          -> template_title_placement
    field_id (the column)   -> title_id
    TemplateFieldLibrary    -> TemplateTitle
    TemplateField           -> TemplateTitlePlacement

The join table keeps its own name rather than becoming `_link`, because it is
not a bare link: it carries `sort`, the only place display order is stored, and
it deliberately allows the same title twice in one template. `_link` would
describe two foreign keys and hide the column the ordering rule rests on.

Carried through every level, because a half-renamed layer is how the confusing
pair got there in the first place: HTTP paths (`/template-field-library` ->
`/template-titles`), the template payload (`fields`/`field_id` ->
`placements`/`title_id`, and `field_count` -> `placement_count`), the Pydantic
schemas, the CRUD modules, the seed script, the frontend API module and types,
and `docs/OVERVIEW.md`, which now states the naming rules outright.

Two deliberate exceptions:

* `paper_template_filed_sort` is untouched — it is a column of the paper module
  and is spelled as the feature was specified.
* The MCP tools keep their agent-facing names (`field_list`, `field_ids`, and
  the `fields`/`field_id` keys in their responses). Agents already call them by
  those names; the storage names they read underneath have changed.

The migration renames in place (data preserved: 4 templates, 45 titles, 63
placements) and is written to tolerate a database where part of it already ran,
which is not hypothetical — the first attempt renamed the tables and then failed
on the column, because Alembic's MySQL dialect wants an explicit type for
`alter_column` and will not rename a column without one. TiDB carries the
foreign key along with both the renamed table and the renamed column, rehearsed
against the cluster first, and it stays enforced.

Verified: seed re-runs clean, the paper smoke test's 45 checks and the MCP
smoke test's 47 pass, `vue-tsc` and the build are clean, and the UI was driven
in a headless browser through the template list, its preview drawer, the title
library page, the template form (which now posts `placements` with `title_id`)
and the paper document with no console errors.
2026-09-22 16:55:02 +08:00

65 lines
2.4 KiB
Python

"""Self-check: prove the server can start before a client has to find out.
Run with ``python -m app.mcp --check`` (or ``scripts/mcp_server.py --check``).
The failure this exists for is the quiet one. A stdio MCP client spawns the
server, the process starts, the handshake succeeds, and every tool call fails
with a database error the model reads as "the tool is broken". Connecting once
here, on demand, turns that into a message with a host and a port in it.
It is deliberately independent of the transports: it builds the same server
object the transports serve, so the tool count it prints is the tool count a
client will see.
"""
from __future__ import annotations
import sys
import anyio
from mcp.server.mcpserver import MCPServer
from sqlalchemy import func, select
from app.core.config import get_settings
from app.db.session import SessionLocal
from app.mcp.server import SERVER_VERSION
from app.models import Paper, PaperSentence, Template, TemplateTitle
def run_selfcheck(server: MCPServer) -> int:
"""Report the database, the tool surface, and where the tools come from."""
settings = get_settings()
print(f"paper-doc MCP {SERVER_VERSION} (name={server.name})")
print(f"database : {settings.safe_database_url}")
try:
with SessionLocal() as db:
counts = {
"paper": db.scalar(select(func.count(Paper.id))) or 0,
"template": db.scalar(select(func.count(Template.id))) or 0,
"paper_sentence": db.scalar(select(func.count(PaperSentence.id))) or 0,
"template_title": db.scalar(
select(func.count(TemplateTitle.id))
)
or 0,
}
except Exception as error: # noqa: BLE001 - the message is the point
print(f"database : 连接失败 — {error}", file=sys.stderr)
print(
"检查 backend/.env 的 DB_* 配置,或用 proxy_endpoint skill 确认网络可达。",
file=sys.stderr,
)
return 1
print("rows : " + ", ".join(f"{name}={count}" for name, count in counts.items()))
tools = anyio.run(server.list_tools)
groups: dict[str, int] = {}
for tool in tools:
groups[tool.name.split("_", 1)[0]] = groups.get(tool.name.split("_", 1)[0], 0) + 1
print(f"tools : {len(tools)} " + ", ".join(f"{k}={v}" for k, v in sorted(groups.items())))
for tool in tools:
print(f" - {tool.name}")
return 0