deploy: run the MCP server in k3s under the paper-doc namespace

The server has to be reachable by the Harness, Claude Code and Codex, and all
three of those are clients of an address rather than of a source tree — a
stdio child process only serves whichever machine spawned it. So it is packaged
and deployed: namespace `paper-doc`, one Deployment, one NodePort Service at
`http://192.168.1.88:30931/mcp` behind a bearer token, talking to the
in-cluster TiDB Service rather than the node's NodePort.

The namespace is `paper-doc` and not `paper_doc`, which is not a preference:
a namespace name is an RFC 1123 label, underscores are outside that alphabet,
and the API server rejects it outright. The database keeps its underscore.

Two routes were added to the server for the deployment, and they are the only
unauthenticated ones. `/healthz` answers "is this process alive" without
touching anything, `/readyz` answers "can it serve" by running `SELECT 1`. The
split is the point: a failing readiness probe takes the pod out of the
Service's endpoints and puts it back when TiDB returns, while a failing
liveness probe kills a process that was working correctly.

There is no container runtime on this host — k3s runs containerd and neither
`ctr` nor `crictl` builds from a Dockerfile — so `deploy/build-mcp-image.sh`
builds inside a throwaway privileged docker-in-docker pod, mounting the working
tree through a hostPath so the build context is the tree you are looking at,
uncommitted edits included. It reads the registry credentials out of the
cluster's own pull secret, so no password is in the script or in a shell
history. One Dockerfile serves both entry points, because the API and the MCP
server share the domain layer and differ by one argv.

Verified against the deployed Service, not against a local process: 47 MCP
checks pass over the NodePort, and the Node MCP SDK — the one the Harness's
mcp-client plugin uses — lists all 29 tools and calls them. The same 47 pass in
stdio and against a local HTTP server, and the REST suite still passes its 45.
This commit is contained in:
2026-09-21 00:08:17 +08:00
parent 5a6461eeec
commit 7e7820f823
10 changed files with 735 additions and 14 deletions
+74 -3
View File
@@ -31,16 +31,30 @@ import os
import sys
from typing import Any
import anyio.to_thread
from mcp.server.mcpserver import MCPServer
from mcp.server.transport_security import TransportSecuritySettings
from sqlalchemy import text
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from app.core.config import get_settings
from app.mcp.tools import register_all
#: The name a client sees at ``initialize``, and the prefix of nothing else —
#: tool names carry their own group prefix (``paper_``, ``paragraph_`` …), so
#: they read the same whatever server they arrive from.
SERVER_NAME = "paper-doc"
#: Version reported at ``initialize``. Bumped when the tool surface changes in
#: a way a client could notice, since it is the only version a client sees.
SERVER_VERSION = "1.0.0"
#: Paths served without the bearer token. A Kubernetes probe cannot carry one —
#: it can be given headers, but a liveness check that fails because a secret was
#: rotated is a liveness check that restarts a healthy pod.
PUBLIC_PATHS = frozenset({"/healthz", "/readyz"})
INSTRUCTIONS = """\
paper-doc 论文写作服务:管理论文(paper)、段落(paragraph)、句子(sentence)、
模板(template)和字段库(field)。工具名前缀对应这五类。
@@ -64,7 +78,7 @@ paper-doc 论文写作服务:管理论文(paper)、段落(paragraph)
def build_server() -> MCPServer:
"""Assemble the server with every paper-doc tool registered."""
server = MCPServer(
name="paper-doc",
name=SERVER_NAME,
title="paper-doc 论文写作",
version=SERVER_VERSION,
instructions=INSTRUCTIONS,
@@ -73,9 +87,54 @@ def build_server() -> MCPServer:
log_level="WARNING",
)
register_all(server)
_register_health_routes(server)
return server
def _register_health_routes(server: MCPServer) -> None:
"""Serve the two probes a Kubernetes deployment needs, and nothing else.
They are split because they answer different questions and only one of them
should be allowed to kill a pod:
* ``/healthz`` — is this process alive? It touches nothing, so a database
that is briefly unreachable cannot turn into a restart loop that makes the
outage longer than it was.
* ``/readyz`` — can this process serve a request? It runs ``SELECT 1``, so
the pod leaves the Service's endpoints while TiDB is down and comes back
on its own when it is not. Failing readiness drops a pod out of rotation;
failing liveness kills it, and only the first is the right answer here.
The database call runs in a worker thread: the handler is on the event loop
that also carries in-flight MCP responses, and a probe must not stall them.
"""
@server.custom_route("/healthz", methods=["GET"], include_in_schema=False)
async def healthz(request: Request) -> Response:
return JSONResponse(
{"status": "ok", "server": SERVER_NAME, "version": SERVER_VERSION}
)
@server.custom_route("/readyz", methods=["GET"], include_in_schema=False)
async def readyz(request: Request) -> Response:
try:
await anyio.to_thread.run_sync(_ping_database)
except Exception as error: # noqa: BLE001 - the message is the probe output
return JSONResponse(
{"status": "unready", "error": f"{type(error).__name__}: {error}"},
status_code=503,
)
return JSONResponse({"status": "ready"})
def _ping_database() -> None:
"""One round trip to TiDB, on its own short-lived connection."""
from app.db.session import SessionLocal
with SessionLocal() as db:
db.execute(text("select 1"))
# --- HTTP transports ---------------------------------------------------------
@@ -88,6 +147,10 @@ class BearerTokenMiddleware:
configured the check is skipped entirely — which is the right default for
``stdio`` and for a loopback bind, and the reason
:func:`_serve_http` warns when a non-loopback host is used without one.
``/healthz`` and ``/readyz`` are exempt (see :data:`PUBLIC_PATHS`): a probe
that fails because a rotated secret was not yet rolled out would restart a
pod that is serving fine.
"""
def __init__(self, app: Any, token: str) -> None:
@@ -95,7 +158,7 @@ class BearerTokenMiddleware:
self.token = token
async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
if scope["type"] == "http":
if scope["type"] == "http" and scope.get("path") not in PUBLIC_PATHS:
headers = {
key.lower(): value for key, value in (scope.get("headers") or [])
}
@@ -244,4 +307,12 @@ def main(argv: list[str] | None = None) -> int:
return 0
__all__ = ["BearerTokenMiddleware", "INSTRUCTIONS", "SERVER_VERSION", "build_server", "main"]
__all__ = [
"BearerTokenMiddleware",
"INSTRUCTIONS",
"PUBLIC_PATHS",
"SERVER_NAME",
"SERVER_VERSION",
"build_server",
"main",
]