diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..70f2809 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,22 @@ +# Build context hygiene. The first entry is the one that matters: `.venv/` is +# ~200MB of host-specific wheels that would be copied into the layer and then +# shadowed by the image's own site-packages. +.venv/ +__pycache__/ +**/__pycache__/ +*.py[cod] +.ruff_cache/ +.mypy_cache/ +.pytest_cache/ + +# Never in the image. The container is configured by the Deployment's env and +# Secret; a baked-in .env would be a database password inside a layer, in a +# registry, forever. .env.example is documentation and does no harm, but it is +# also not read at runtime, so it stays out too. +.env +.env.* + +# Local scaffolding. +.idea/ +.vscode/ +*.md diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..e97fe4b --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,57 @@ +# paper-doc backend image — the REST API and the MCP server, one build. +# +# Both entry points live in the same package and share the same domain layer, so +# they share an image: the Deployment picks which one to run with its own +# command. Building two images would mean two dependency resolutions that can +# drift apart, for a difference of one argv. +# +# The base image comes from a mirror rather than docker.io, which this network +# cannot reach; the pip index is the Tsinghua mirror for the same reason. +FROM docker.m.daocloud.io/library/python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple + +WORKDIR /app + +# The unprivileged uid is created before the code is copied, so the copies can +# be owned by it in one pass. +RUN useradd --no-create-home --shell /usr/sbin/nologin --uid 10001 appuser + +# Requirements first, and alone: the dependency layer is the slow one and the +# application code changes far more often than it does. +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY --chown=10001:10001 app ./app +COPY --chown=10001:10001 scripts ./scripts +# Not used by the MCP server, but the API Deployment runs `alembic upgrade head` +# as an init container against the same image, and shipping the migrations +# beside the models they describe is the only way to keep them in step. +COPY --chown=10001:10001 alembic ./alembic +COPY --chown=10001:10001 alembic.ini ./ + +# COPY carries the source file's mode across, and this working tree keeps its +# files at 0600 — so without this the container starts, reads nothing, and exits +# with "can't open file ... Permission denied". Read and traverse for everyone, +# which is all any of it needs: the image writes nothing. +RUN chmod -R a+rX /app + +USER 10001 + +EXPOSE 8931 + +# Defaults for the container, not the deployment: a Deployment that means to +# run stdio overrides these, and one that forgets to set MCP_HTTP_TOKEN gets a +# server that is only reachable from inside the cluster. +ENV MCP_TRANSPORT=http \ + MCP_HOST=0.0.0.0 \ + MCP_PORT=8931 \ + MCP_PATH=/mcp + +# No HEALTHCHECK: the Deployment probes /healthz and /readyz directly, and a +# Docker healthcheck would be a second, differently-tuned copy of that. +CMD ["python", "scripts/mcp_server.py"] diff --git a/backend/app/mcp/server.py b/backend/app/mcp/server.py index b1b490d..947a85b 100644 --- a/backend/app/mcp/server.py +++ b/backend/app/mcp/server.py @@ -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", +] diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..dc3331d --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,142 @@ +# 部署到 k3s + +paper-doc 的 MCP 服务跑在 k3s 里,命名空间 **`paper-doc`**,客户端通过 +`http://192.168.1.88:30931/mcp` 连接。 + +> **为什么不是 `paper_doc`**:Kubernetes 的命名空间名必须是 RFC 1123 label, +> 下划线不在允许的字符集里(`[a-z0-9]([-a-z0-9]*[a-z0-9])?`),API Server 会直接拒绝。 +> 所以命名空间用连字符 `paper-doc`;数据库名和表名仍然是 `paper_doc`,两者不冲突。 + +## 部署了什么 + +| 资源 | 名字 | 说明 | +|---|---|---| +| Namespace | `paper-doc` | `deploy/k8s/00-namespace.yaml` | +| Deployment | `paper-doc-mcp` | 1 副本,跑 MCP 服务的 http 传输 | +| Service | `paper-doc-mcp` | NodePort **30931** → 容器 8931 | +| ConfigMap | `paper-doc-config` | 非敏感环境变量(数据库地址、监听配置) | +| Secret | `paper-doc-secrets` | `DB_USER` / `DB_PASSWORD` / `MCP_HTTP_TOKEN` | +| Secret | `aliyun-acr` | 镜像仓库拉取凭证(从 `default` 复制) | + +镜像:`registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v2` + +**数据库**:TiDB 已经在这个集群里,Deployment 用集群内的 Service +`tidb-tidb.tidb:4000`,而不是宿主机用的 NodePort `192.168.1.88:32738`。 +两者是同一份数据;集群内用 Service 的好处是节点地址变了也不用改配置。 + +## 访问地址 + +| 从哪里连 | 地址 | +|---|---| +| 宿主机 / 局域网 | `http://192.168.1.88:30931/mcp` | +| 集群内 Pod | `http://paper-doc-mcp.paper-doc.svc.cluster.local:8931/mcp` | +| 健康检查(免鉴权) | `http://192.168.1.88:30931/healthz`、`/readyz` | + +除 `/healthz` 和 `/readyz` 外,所有请求都要带 +`Authorization: Bearer `,否则返回 `401`。 +Token 在 Secret 里,取法: + +```bash +export KUBECONFIG=$HOME/.kube/config +kubectl -n paper-doc get secret paper-doc-secrets \ + -o jsonpath='{.data.MCP_HTTP_TOKEN}' | base64 -d; echo +``` + +## 日常操作 + +先记住这一句,否则 `kubectl` 会去读 root-only 的 +`/etc/rancher/k3s/k3s.yaml` 并报 permission denied: + +```bash +export KUBECONFIG=$HOME/.kube/config +``` + +```bash +# 状态 +kubectl -n paper-doc get deploy,svc,pods +kubectl -n paper-doc logs deploy/paper-doc-mcp --tail=50 + +# 重新构建并推送镜像(需要一个 tag,见下面「两个坑」) +deploy/build-mcp-image.sh v3 + +# 发布新版本 +kubectl -n paper-doc set image deployment/paper-doc-mcp \ + mcp=registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:v3 +kubectl -n paper-doc rollout status deployment/paper-doc-mcp + +# 回滚 +kubectl -n paper-doc rollout undo deployment/paper-doc-mcp + +# 改配置 / 换 token +kubectl -n paper-doc edit configmap paper-doc-config +kubectl -n paper-doc create secret generic paper-doc-secrets \ + --from-literal=DB_USER='Govin' \ + --from-literal=DB_PASSWORD='' \ + --from-literal=MCP_HTTP_TOKEN="$(openssl rand -hex 32)" \ + --dry-run=client -o yaml | kubectl apply -f - +kubectl -n paper-doc rollout restart deployment/paper-doc-mcp +``` + +**验证部署**——不是看 Pod 是不是 Running,而是真的用 MCP 客户端跑一遍: + +```bash +cd backend +.venv/bin/python scripts/smoke_mcp.py \ + --url http://192.168.1.88:30931/mcp --token "$(cat /tmp/paper-mcp-token)" +# 47 项检查全过 = 集群里这套东西真的能写论文 +``` + +## 构建:为什么是 DinD Pod + +这台宿主机上没有容器运行时——k3s 用的是 containerd,节点上的 `ctr` / `crictl` +都是 k3s 的软链,谁都不能从 Dockerfile 构建。所以构建放在集群里一个临时的 +docker-in-docker Pod 里做,源码通过 hostPath 挂进去(`/workspace`), +这样构建上下文就是当前工作区,未提交的改动也在里面。 + +`deploy/build-mcp-image.sh` 把这一整套包好了:起 Pod → 登录 → 构建 → 推送 → 删 Pod +(`trap` 保证失败也会删)。**仓库凭证是从集群里已有的 `aliyun-acr-secret` 读出来的**, +所以脚本里没有任何密码,也不会进 shell history。 + +## 两个坑(都踩过了,别再踩) + +**1. 镜像 tag 复用会发布不出新代码。** +Deployment 的 `imagePullPolicy: IfNotPresent`,节点按 tag 缓存镜像。 +用同样的 `:v1` 重新构建推送后,Pod 重启拿到的还是旧镜像—— +现象是新 Pod 起来了、但行为跟没改一样。**每次构建换一个 tag**(v2、v3…), +或者临时把 `imagePullPolicy` 改成 `Always`(代价是每次启动都要连仓库)。 + +**2. 源码权限 0600 会让容器读不到代码。** +工作区的文件是 `rw-------`,`COPY` 会把权限一起带进镜像, +于是非 root(uid 10001)的容器启动即 +`can't open file '/app/scripts/mcp_server.py': [Errno 13] Permission denied`, +然后 CrashLoopBackOff。Dockerfile 里 `RUN chmod -R a+rX /app` 解决—— +镜像里的东西只需要可读,不需要任何人可写。 + +## 探针:为什么是两个 + +| 探针 | 路径 | 语义 | +|---|---|---| +| liveness | `/healthz` | 进程还活着吗——不碰数据库,所以数据库抖一下不会变成反复重启 | +| readiness | `/readyz` | 现在能服务吗——执行 `SELECT 1`,TiDB 不通就把 Pod 摘出 Service,通了自动加回来 | + +失败 readiness 只是把 Pod 从负载均衡里摘掉,失败 liveness 会杀掉进程。 +数据库短暂不可用只应该是前者,所以这个分工是刻意的。 + +## 还没有部署的 + +- **REST API**:同一个镜像,换 command 即可(`uvicorn app.main:app --host 0.0.0.0 --port 8000`), + 再加一个 init 容器跑 `alembic upgrade head`。配置模板写在 + `deploy/k8s/10-paper-doc-mcp.yaml` 末尾的注释里,解开注释即可。 +- **前端 SPA**:需要额外构建(pnpm build)+ nginx 镜像,目前没做。 + +## 文件清单 + +``` +deploy/ +├── build-mcp-image.sh # DinD 构建并推送镜像 +├── README.md # 本文件 +└── k8s/ + ├── 00-namespace.yaml + ├── 10-paper-doc-mcp.yaml # ConfigMap + Deployment + Service(含 API 的注释模板) + └── secret.example.yaml # Secret 模板,真值不入库 +``` diff --git a/deploy/build-mcp-image.sh b/deploy/build-mcp-image.sh new file mode 100755 index 0000000..4258e89 --- /dev/null +++ b/deploy/build-mcp-image.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +# Build the paper-doc image and push it to the registry the cluster pulls from. +# +# Why a pod builds it +# ------------------- +# There is no container runtime on this host: k3s runs containerd, and the +# binaries on the node are the k3s ones (`ctr`, `crictl`), neither of which +# builds from a Dockerfile. So the build runs where a builder already exists — +# a privileged docker-in-docker pod inside the cluster — and the source reaches +# it through a hostPath mount rather than `kubectl cp`, which keeps the build +# context exactly the working tree you are looking at, uncommitted edits +# included. +# +# The credentials are read out of the cluster's own pull secret rather than +# taken as arguments, so this script has none in it and nothing is pasted into a +# shell history. +# +# Usage (from anywhere): +# +# deploy/build-mcp-image.sh # tag :v1 +# deploy/build-mcp-image.sh v2 # tag :v2 +# IMAGE=... deploy/build-mcp-image.sh # a different repository entirely +# +# Prerequisite: `export KUBECONFIG=$HOME/.kube/config` (the k3s binary defaults +# to /etc/rancher/k3s/k3s.yaml, which is root-only on this host). +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TAG="${1:-v1}" +IMAGE="${IMAGE:-registry.cn-hangzhou.aliyuncs.com/mcp_skill/paper-doc-mcp:${TAG}}" + +BUILD_NAMESPACE="${BUILD_NAMESPACE:-default}" +BUILD_POD="${BUILD_POD:-dind-build-paper-doc}" +REGISTRY_HOST="${IMAGE%%/*}" +# The old build pod is what proved this image is already on the node; the same +# one is used here so a rebuild does not have to reach docker.io, which this +# network cannot. +BUILDER_IMAGE="${BUILDER_IMAGE:-docker:27-dind}" + +export KUBECONFIG="${KUBECONFIG:-$HOME/.kube/config}" + +log() { printf '\n=== %s\n' "$*"; } + +cleanup() { + log "removing the build pod" + kubectl -n "$BUILD_NAMESPACE" delete pod "$BUILD_POD" --ignore-not-found --wait=false >/dev/null 2>&1 || true +} +trap cleanup EXIT + +log "build context: $REPO_ROOT/backend" +log "image: $IMAGE" + +kubectl -n "$BUILD_NAMESPACE" delete pod "$BUILD_POD" --ignore-not-found >/dev/null 2>&1 || true + +log "starting the docker-in-docker builder" +# `DOCKER_TLS_CERTDIR=""` keeps the daemon on tcp://localhost:2375 inside the +# pod, so `docker` in the same container needs no certificate dance. The pod is +# privileged because that is what a docker daemon needs; it lives for the length +# of one build and is deleted by the trap. +cat </dev/null 2>&1; then + break + fi + sleep 2 +done +kubectl -n "$BUILD_NAMESPACE" exec "$BUILD_POD" -- docker info --format 'daemon ok: {{.ServerVersion}}' + +log "logging in to $REGISTRY_HOST" +# Read out of the pull secret the cluster already uses: the push credential and +# the pull credential are the same account, and a second copy of it in a script +# is a second place it can go stale. +kubectl -n default get secret aliyun-acr-secret -o jsonpath='{.data.\.dockerconfigjson}' \ + | base64 -d \ + | python3 -c ' +import json, sys +auth = next(iter(json.load(sys.stdin)["auths"].values())) +print(auth["username"], auth["password"]) +' \ + | kubectl -n "$BUILD_NAMESPACE" exec -i "$BUILD_POD" -- sh -c \ + 'read -r user pass; printf "%s" "$pass" | docker login -u "$user" --password-stdin "$0"' "$REGISTRY_HOST" + +log "building" +# --network=host: the build needs the same mirror access the node has for pip, +# and the pod's own network namespace would otherwise be a second, untested path +# to the internet. +kubectl -n "$BUILD_NAMESPACE" exec "$BUILD_POD" -- \ + docker build --network=host --tag "$IMAGE" /workspace/backend + +log "pushing" +kubectl -n "$BUILD_NAMESPACE" exec "$BUILD_POD" -- docker push "$IMAGE" + +log "done: $IMAGE" +cat <' \ +# --from-literal=MCP_HTTP_TOKEN="$(openssl rand -hex 32)" +# +# Rotating the token is then one `kubectl create secret ... --dry-run=client -o +# yaml | kubectl apply -f -` plus a rollout restart, and no image rebuild. +# +# The registry pull secret is separate and not described here: it is +# `aliyun-acr`, copied into this namespace from `default`, and it holds the +# container registry's credentials rather than the application's. +apiVersion: v1 +kind: Secret +metadata: + name: paper-doc-secrets + namespace: paper-doc +type: Opaque +stringData: + DB_USER: Govin + DB_PASSWORD: change-me + MCP_HTTP_TOKEN: change-me diff --git a/docs/MCP.md b/docs/MCP.md index 5261786..7924a00 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -11,6 +11,8 @@ - 工具数量:**29 个**,按 `paper_` / `paragraph_` / `sentence_` / `template_` / `field_` 五组前缀 - 协议: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` + (打包、发布、回滚见 [deploy/README.md](../deploy/README.md)) --- @@ -48,7 +50,32 @@ tools : 29 field=5, paper=9, paragraph=5, sentence=5, template=5 从任何工作目录都能跑(脚本自己锚定 `sys.path`),所以客户端不需要配 `cwd`。 -### 1.3 streamable-http(推荐给远程/常驻) +### 1.3 连已经在跑的那一个(k3s 里) + +不用自己起进程——服务已经部署好了: + +``` +http://192.168.1.88:30931/mcp # 局域网 / 宿主机 +http://paper-doc-mcp.paper-doc.svc.cluster.local:8931/mcp # 集群内 Pod +``` + +除 `/healthz`、`/readyz` 外都要带 `Authorization: Bearer `。 +取口令: + +```bash +export KUBECONFIG=$HOME/.kube/config +kubectl -n paper-doc get secret paper-doc-secrets -o jsonpath='{.data.MCP_HTTP_TOKEN}' | base64 -d; echo +``` + +自检与验证: + +```bash +curl -s http://192.168.1.88:30931/readyz +cd backend && .venv/bin/python scripts/smoke_mcp.py \ + --url http://192.168.1.88:30931/mcp --token '<口令>' # 47 项检查 +``` + +### 1.4 streamable-http(自己起一个) ```bash cd /data/project/paper/backend @@ -63,7 +90,7 @@ cd /data/project/paper/backend 也可以用环境变量代替参数:`MCP_TRANSPORT` / `MCP_HOST` / `MCP_PORT` / `MCP_PATH` / `MCP_HTTP_TOKEN`。 -### 1.4 跑冒烟测试 +### 1.5 跑冒烟测试 ```bash cd /data/project/paper/backend @@ -185,15 +212,21 @@ enabled = true > 参考:[Codex MCP Servers 文档](https://mintlify.wiki/openai/codex/configuration/mcp-servers) -### 2.4 远程(Windows 上的 Claude Code / Codex 连这台服务器) +### 2.4 远程(Windows 上的 Claude Code / Codex) -三种做法,任选: +服务已经部署在 k3s 里,直接连它就行,客户端填: -1. **HTTP + 口令**(最省事):服务器上跑 HTTP 模式,客户端填 - `http://192.168.1.88:8931/mcp` + `Authorization: Bearer ...`。 -2. **SSH 包一层 stdio**:客户端 `command = "ssh"`,让远端执行 `mcp_server.py`, - 协议走 SSH 的 stdin/stdout(见 ssh_intranet_skill 的 SSH_ASKPASS 写法)。 -3. **Tailscale + HTTP**:走 `100.64.0.1` 内网地址,仍然建议带口令。 +``` +URL: http://192.168.1.88:30931/mcp +Header: Authorization: Bearer +``` + +走 Tailscale 的机器把地址换成 `http://100.64.0.1:30931/mcp`(NodePort 在节点上监听, +两个地址都通)。 + +不想暴露端口的话,还有一条 SSH 包 stdio 的路子:客户端 `command = "ssh"`, +让远端执行 `mcp_server.py`,协议走 SSH 的 stdin/stdout +(见 ssh_intranet_skill 的 SSH_ASKPASS 写法)。 --- @@ -472,4 +505,6 @@ MCP 独有:`paper_outline`(写前看骨架)、`paper_write` / `paper_write | HTTP 返回 421 | 绑定了非 127.0.0.1 但没走本次启动的 DNS-rebinding 关闭逻辑——确认用的是本项目入口,别包了一层反向代理改 Host | | DSH 里工具不出现 | 检查 cordis.patch.yml 的条目是否写在 `insert:` 里;`failOnStartupError: false` 会把启动期连接失败吞掉,看 dsh-web 日志确认 | | 工具调用超时 | DSH/Codex 侧加大 `toolCallTimeoutMs` / `tool_timeout_sec`;`paper_write_text` 写整篇会慢一些 | +| k3s 里连不上 | `kubectl -n paper-doc get pods` 看是否 Ready;`/readyz` 返回 503 说明 TiDB 不通(`kubectl -n paper-doc logs deploy/paper-doc-mcp`) | +| 改了代码但行为没变 | 镜像 tag 没换:`imagePullPolicy: IfNotPresent` 会继续用节点上缓存的同名镜像,换个 tag 重新构建 | | 日志里出现非 JSON 的 stdout 输出 | 不要在这个进程里 `print`——stdio 传输下会污染协议流(本项目的诊断都走 stderr) | diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md index 8355782..01c1f00 100644 --- a/docs/OVERVIEW.md +++ b/docs/OVERVIEW.md @@ -332,7 +332,7 @@ connects to (behind a bearer token). The package is split so that only ``` app/mcp/ -├── server.py transports, CLI, and the instructions sent at initialize +├── server.py transports, CLI, health probes, the instructions sent at initialize ├── support.py sessions, JSON shaping, heading resolution, the one text splitter ├── specs.py the shapes a model may send (a paragraph, a sentence, a citation) ├── selfcheck.py --check: connect once and print the tool surface @@ -340,6 +340,12 @@ app/mcp/ by register_all(), each tool three lines around an app.crud call ``` +`/healthz` and `/readyz` exist for Kubernetes and are the only unauthenticated +routes. They answer different questions on purpose: liveness touches nothing, so +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 with `structured_output=False`**: inferred from a `-> str` annotation, the SDK publishes a `{"result": …}` envelope and sends the JSON twice, once as @@ -499,8 +505,13 @@ paper-doc/ │ │ └── views/ # route-level components (papers/, templates/) │ ├── package.json │ └── vite.config.ts +├── deploy/ # packaging and the k3s manifests +│ ├── build-mcp-image.sh # build + push the image from a DinD pod +│ ├── k8s/ # namespace, ConfigMap, Deployment, Service +│ └── README.md └── docs/ # project documentation - └── OVERVIEW.md + ├── OVERVIEW.md + └── MCP.md # the MCP manual: tools, workflows, client configs ``` ## Getting Started @@ -584,3 +595,18 @@ cd backend .venv/bin/python scripts/mcp_server.py --check .venv/bin/python scripts/smoke_mcp.py ``` + +**Deployment** + +The MCP server runs in k3s in the `paper-doc` namespace and is reached at +`http://192.168.1.88:30931/mcp`, behind a bearer token. 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, with the working tree mounted in +through a hostPath so the build context is what you are actually looking at. +The database is the in-cluster TiDB Service (`tidb-tidb.tidb:4000`), not the +NodePort the host uses. `deploy/README.md` has the commands, the two traps +worth knowing (a reused image tag silently keeps the cached image; `COPY` +carries the working tree's `0600` file mode into the image and a non-root +container then cannot read its own code), and how to add the REST API to the +same namespace.