Skip to content

Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.

feat: add optional Tencent Cloud MCP Initializr under tools/tcmcp (#14)

cocofhu766189d78bb3
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 607f30c1..2811e3df 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -14,6 +14,7 @@ on:
permissions:
contents: write
id-token: write
+ packages: write
concurrency:
group: release-${{ github.ref }}
@@ -55,6 +56,19 @@ jobs:
echo "name=${package_name}" >> "$GITHUB_OUTPUT"
echo "version=${package_version}" >> "$GITHUB_OUTPUT"
echo "tag=${release_tag}" >> "$GITHUB_OUTPUT"
+ owner="$(printf '%s' "${GITHUB_REPOSITORY_OWNER}" | tr '[:upper:]' '[:lower:]')"
+ image="ghcr.io/${owner}/loopforge-tcmcp"
+ sha="$(git rev-parse --short HEAD)"
+ tags="${image}:${package_version}"$'\n'"${image}:sha-${sha}"
+ if [[ "${package_version}" != *-* ]]; then
+ tags+=$'\n'"${image}:${package_version%.*}"
+ tags+=$'\n'"${image}:latest"
+ fi
+ {
+ echo "image_tags<<EOF"
+ printf '%s\n' "$tags"
+ echo "EOF"
+ } >> "$GITHUB_OUTPUT"
- name: Install validation dependencies
run: python3 -m pip install pyyaml==6.0.3
@@ -68,6 +82,23 @@ jobs:
bash scripts/smoke-curl-install.sh
bash scripts/scan-secrets.sh
+ - name: Log in to GHCR
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Build and push tcmcp image
+ uses: docker/build-push-action@v6
+ with:
+ context: tools/tcmcp
+ push: true
+ tags: ${{ steps.package.outputs.image_tags }}
+
- name: Build GitHub Release assets
run: bash scripts/build-release-archive.sh
diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml
index 5dee4f0f..4b563172 100644
--- a/.github/workflows/validate.yml
+++ b/.github/workflows/validate.yml
@@ -28,6 +28,26 @@ jobs:
- run: bash scripts/smoke-install.sh
- run: bash scripts/smoke-npm.sh
+ tcmcp:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/[email protected]
+ - uses: actions/[email protected]
+ with:
+ python-version: "3.11"
+ - uses: actions/[email protected]
+ with:
+ node-version: "22"
+ - name: Test tcmcp
+ working-directory: tools/tcmcp
+ run: |
+ python3 -m venv .venv
+ .venv/bin/pip install -e '.[dev]'
+ .venv/bin/python -m pytest
+ - name: Build frontend
+ working-directory: tools/tcmcp/web
+ run: npm ci && npm run build
+
secrets:
runs-on: ubuntu-latest
steps:
diff --git a/.gitignore b/.gitignore
index 00c94492..cbfe0d86 100644
--- a/.gitignore
+++ b/.gitignore
@@ -26,3 +26,6 @@ build/
dist/
*.egg-info/
*.tgz
+node_modules/
+tools/tcmcp/.venv/
+tools/tcmcp/web/dist/
diff --git a/AGENTS.md b/AGENTS.md
index 4de7985b..d61dc783 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,6 +5,7 @@
- Treat the repository as two editions: Classic (`.codebuddy/.codex/.cursor/.claude`) and Portable (`skills/`). Do not mix their runtime assets.
- Treat `.codebuddy` as the Classic reference behavior. `.cursor` and `.claude` are generated Classic host bundles; do not edit them directly.
- Treat `skills/devflow/` and `skills/devflow-clarify-requirements/` as the canonical Portable workflow.
+- Treat `tools/tcmcp/` as an independent optional tool (Python 3.11+). Do not mix it into Classic or Portable edition runtime files.
- Keep logical roles in `skills/devflow/agents/manifest.json`, artifacts in `skills/devflow/templates/manifest.json`, rules in `skills/devflow/rules/manifest.json`, and host capabilities in each `skills/devflow/adapters/<host>/manifest.json`.
- After changing Classic behavior or host adaptation, run `python3 scripts/build-classic-hosts.py --write`.
- A Classic change is not automatically a Portable change. Share explicit behavior contracts and tests, not runtime files.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c3f7c612..6256ba86 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
English | [简体中文](CHANGELOG.zh-CN.md)
+## Unreleased
+
+- Added `tools/tcmcp`, a Tencent Cloud read-only MCP Initializr that is documented and run separately from `loopforge install`. LoopForge version tags also publish `ghcr.io/tencent/loopforge-tcmcp`.
+
## 0.2.0
- Added an opt-in local observability dashboard for Classic DevFlow runs on CodeBuddy, Cursor, and Claude Code.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 9991fecb..77a1e3d3 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -2,6 +2,10 @@
[English](CHANGELOG.md) | 简体中文
+## Unreleased
+
+- 新增 `tools/tcmcp`:腾讯云只读 MCP Initializr,与 `loopforge install` 分开文档化与运行。LoopForge 版本 tag 同时发布 `ghcr.io/tencent/loopforge-tcmcp`。
+
## 0.2.0
- 为 CodeBuddy、Cursor 和 Claude Code 的 Classic DevFlow 流程新增可选的本地可观测性看板。
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 400685b1..ce58b6cd 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -7,7 +7,7 @@ Thanks for contributing to LoopForge.
## Development workflow
1. Start changes from a feature branch.
-2. Keep templates generic; do not introduce organisation-, repository-, or cloud-specific information.
+2. Keep Classic/Portable workflow templates generic; do not introduce organisation-, repository-, or cloud-specific information there. Product tools under `tools/` (such as `tools/tcmcp`) may target a public cloud product, but must not include private domains, real resource IDs, or credentials.
3. Do not commit credentials, local permission configurations, or production data.
4. First indicate whether a change belongs to Classic, Portable, or shared behaviour contracts. Portable only modifies `skills/`; Classic `.cursor/.claude` files are not edited directly — run `build-classic-hosts.py --write`.
5. When modifying shared workflow contracts, describe the impact on both editions separately; do not copy runtime files between them.
@@ -18,6 +18,6 @@ Thanks for contributing to LoopForge.
- Describe the problem the change solves and the applicable runtime.
- List behaviour changes, compatibility impact, and verification results.
- When adding third-party content, include source, licence, and modification notes.
-- Do not put internal deployment or operational capabilities into core templates; use a separate private extension.
+- Do not put internal deployment or operational capabilities into Classic/Portable templates; keep unpublished ops in a private extension. Optional public tools belong in `tools/`, not in host workflow packs.
Commit messages should follow Conventional Commits, e.g. `feat: add workflow checkpoint validation`.
diff --git a/CONTRIBUTING.zh-CN.md b/CONTRIBUTING.zh-CN.md
index 5a861093..79c2ab58 100644
--- a/CONTRIBUTING.zh-CN.md
+++ b/CONTRIBUTING.zh-CN.md
@@ -7,7 +7,7 @@
## 开发流程
1. 从功能分支开始修改。
-2. 保持模板通用,不引入特定组织、仓库或云资源信息。
+2. Classic/Portable 工作流模板保持通用,不要在其中写入特定组织、仓库或云资源信息。`tools/` 下的产品工具(如 `tools/tcmcp`)可以面向公有云产品,但不得包含内网域名、真实资源 ID 或凭据。
3. 不提交任何凭据、本地权限配置或生产数据。
4. 先标明改动属于 Classic、Portable 或共享行为合同。Portable 只修改 `skills/`;Classic 的 `.cursor/.claude` 不直接修改,运行 `build-classic-hosts.py --write`。
5. 修改共享工作流契约时分别说明两个 edition 的影响;不要在二者之间复制运行文件。
@@ -18,6 +18,6 @@
- 说明改动解决的问题和适用运行时。
- 列出行为变化、兼容性影响和验证结果。
- 新增第三方内容时补充来源、许可证和修改说明。
-- 不要把内部部署或运维能力放进核心模板;使用单独的私有扩展。
+- 不要把内部部署或运维能力放进 Classic/Portable 模板;未开源的运维能力使用单独的私有扩展。面向公开用户的可选工具放在 `tools/`,不要打进宿主工作流包。
提交信息建议遵循 Conventional Commits,例如 `feat: add workflow checkpoint validation`。
diff --git a/README.md b/README.md
index 36d22ead..7e77971d 100644
--- a/README.md
+++ b/README.md
@@ -245,6 +245,16 @@ If you have cloned this repository, install the LoopForge CLI from the current s
pipx install .
```
+## Optional tools
+
+`tools/tcmcp` is a Tencent Cloud read-only MCP Initializr (Redis, CDB, TDSQL-C, TKE, CLS, COS). It is not part of `loopforge install` or the npm CLI package. From a clone:
+
+```bash
+cd tools/tcmcp
+```
+
+Then follow [`tools/tcmcp/README.md`](tools/tcmcp/README.md). Cloud API keys are not written into generated zips or the container image; they stay on the machine that lists resources or installs the MCP client. LoopForge `vX.Y.Z` releases publish `ghcr.io/tencent/loopforge-tcmcp:<version>`.
+
## Permissions and security
Some Classic host configurations enable automatic execution or high-permission agent modes. Use LoopForge only in trusted projects. Before installation, inspect planned files with `loopforge plan codebuddy`, `loopforge plan codex`, `loopforge plan cursor`, or `loopforge plan claude`. Do not put credentials, private endpoints, or production operations configuration in workflow templates.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 4cb5a028..5a6f79b5 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -244,6 +244,16 @@ loopforge skills uninstall claude
pipx install .
```
+## 可选工具
+
+`tools/tcmcp` 是腾讯云只读 MCP Initializr(Redis、CDB、TDSQL-C、TKE、CLS、COS)。它不包含在 `loopforge install` 或 npm CLI 包中。克隆仓库后:
+
+```bash
+cd tools/tcmcp
+```
+
+再按 [`tools/tcmcp/README.md`](tools/tcmcp/README.md) 启动。云 API 密钥不会写入生成的 zip 或容器镜像,只留在拉取资源或安装 MCP 客户端的本机。LoopForge 打 `vX.Y.Z` tag 发版时会发布 `ghcr.io/tencent/loopforge-tcmcp:<version>`。
+
## 权限与安全
部分宿主的 Classic 配置会启用自动执行或高权限 Agent 模式。请只在可信项目中使用;安装前可以通过 `loopforge plan codebuddy`、`loopforge plan codex`、`loopforge plan cursor` 或 `loopforge plan claude` 检查将写入的文件。不要把凭据、私有地址或生产运维配置写入工作流模板。
diff --git a/docs/architecture.md b/docs/architecture.md
index 00fb2d78..e985ee7d 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -31,7 +31,11 @@ Portable 安装到目标项目时才生成 `.cursor/.claude/.agents/.codebuddy`
是 Classic;`loopforge install <host>` 安装完整宿主包,Portable 通过
`loopforge skills install <host>` 安装。安装器不改变两套工作流的内部状态机。
-## 私有扩展
+## 可选工具与私有扩展
-CI/CD、工单、企业代码托管、知识库、聊天通知和云运维应保存在部署方的
-私有仓库,通过本地配置或受控安装叠加,不应反向提交到公共核心。
+`tools/` 存放不进入 Classic/Portable 安装包和 `loopforge-cli` npm 包的配套工具。
+当前 `tools/tcmcp` 是腾讯云只读 MCP Initializr,由克隆仓库或 GHCR 镜像单独运行。
+
+CI/CD、工单、企业代码托管、知识库、聊天通知,以及未开源的云运维能力,应保存在部署方的
+私有仓库,通过本地配置或受控安装叠加。不要把 CAM 策略、内网域名或运维 MCP 写进
+Classic/Portable 工作流模板。
diff --git a/scripts/validate.sh b/scripts/validate.sh
index ec4535e9..9c28a1bb 100755
--- a/scripts/validate.sh
+++ b/scripts/validate.sh
@@ -21,16 +21,45 @@ if rg --hidden -n -i \
echo "Credential-like content found." >&2
exit 1
fi
+if rg --hidden -n -i \
+ -e 'woa\.com' \
+ -e '(^|[^[:alnum:]])oa\.com' \
+ -e 'git\.woa' \
+ -e 'iwiki' \
+ -e 'tapd' \
+ -e 'internal\.tencentcloudapi' \
+ -e 'cls\.internal\.tencentcloudapi\.com' \
+ -e 'AKID[A-Za-z0-9]{16,}' \
+ -g '!.git/**' \
+ -g '!.venv/**' \
+ -g '!node_modules/**' \
+ "$ROOT_DIR/tools/tcmcp"; then
+ echo "Internal or credential-like content found under tools/tcmcp." >&2
+ exit 1
+fi
+
+FIND_PRUNE=(
+ -not -path '*/.git/*'
+ -not -path '*/node_modules/*'
+ -not -path '*/.venv/*'
+ -not -path '*/web/dist/*'
+)
echo "[2/6] Checking shell syntax"
while IFS= read -r -d '' file; do bash -n "$file"; done \
- < <(find "$ROOT_DIR" -type f -name '*.sh' -not -path '*/.git/*' -print0)
+ < <(find "$ROOT_DIR" -type f -name '*.sh' "${FIND_PRUNE[@]}" -print0)
echo "[3/6] Checking JavaScript and Python syntax"
while IFS= read -r -d '' file; do node --check "$file" >/dev/null; done \
- < <(find "$ROOT_DIR" -type f \( -name '*.js' -o -name '*.cjs' -o -name '*.mjs' \) -not -path '*/.git/*' -print0)
+ < <(find "$ROOT_DIR" -type f \( -name '*.js' -o -name '*.cjs' -o -name '*.mjs' \) "${FIND_PRUNE[@]}" -print0)
+
+PY_FIND=( "${FIND_PRUNE[@]}" )
+python_minor="$(python3 -c 'import sys; print(sys.version_info.minor)')"
+if (( python_minor < 10 )); then
+ PY_FIND+=( -not -path '*/tools/tcmcp/*' )
+fi
while IFS= read -r -d '' file; do python3 -m py_compile "$file"; done \
- < <(find "$ROOT_DIR" -type f -name '*.py' -not -path '*/.git/*' -print0)
+ < <(find "$ROOT_DIR" -type f -name '*.py' "${PY_FIND[@]}" -print0)
echo "[4/6] Checking JSON, YAML, Markdown links, and Skill metadata"
python3 - "$ROOT_DIR" <<'PY'
@@ -46,17 +75,24 @@ sys.path.insert(0, str(root / "src"))
from devflow_cli import __version__
from devflow_cli.editions import DEFAULT_EDITION, EDITION_SPECS, HOSTS, source_for
+SKIP_PARTS = {".git", "node_modules", ".venv", "dist"}
+
+def skip(path: pathlib.Path) -> bool:
+ return bool(SKIP_PARTS.intersection(path.parts))
+
for path in root.rglob("*.json"):
- if ".git" not in path.parts:
- json.loads(path.read_text(encoding="utf-8"))
+ if skip(path):
+ continue
+ json.loads(path.read_text(encoding="utf-8"))
for pattern in ("*.yaml", "*.yml"):
for path in root.rglob(pattern):
- if ".git" not in path.parts:
- yaml.safe_load(path.read_text(encoding="utf-8"))
+ if skip(path):
+ continue
+ yaml.safe_load(path.read_text(encoding="utf-8"))
missing = []
for path in root.rglob("*.md"):
- if ".git" in path.parts:
+ if skip(path):
continue
for target in re.findall(r"\[[^]]*\]\(([^)]+)\)", path.read_text(encoding="utf-8")):
target = target.split("#", 1)[0]
@@ -136,7 +172,9 @@ for path in README.md LICENSE SECURITY.md CONTRIBUTING.md THIRD_PARTY_NOTICES.md
scripts/scan-secrets.sh scripts/smoke-install.sh scripts/smoke-npm.sh \
scripts/smoke-curl-install.sh scripts/build-release-archive.sh \
scripts/build-classic-hosts.py \
- src/devflow_cli/cli.py src/devflow_cli/core.py; do
+ src/devflow_cli/cli.py src/devflow_cli/core.py \
+ tools/tcmcp/README.md tools/tcmcp/README.zh-CN.md \
+ tools/tcmcp/pyproject.toml tools/tcmcp/app/main.py tools/tcmcp/Dockerfile; do
test -f "$ROOT_DIR/$path"
done
diff --git a/tools/tcmcp/.dockerignore b/tools/tcmcp/.dockerignore
new file mode 100644
index 00000000..ec01f917
--- /dev/null
+++ b/tools/tcmcp/.dockerignore
@@ -0,0 +1,13 @@
+.git
+.venv
+venv
+__pycache__
+*.pyc
+.pytest_cache
+*.egg-info
+web/node_modules
+web/dist
+.env
+conf/
+config.yaml
+.DS_Store
diff --git a/tools/tcmcp/.gitignore b/tools/tcmcp/.gitignore
new file mode 100644
index 00000000..6419ebbe
--- /dev/null
+++ b/tools/tcmcp/.gitignore
@@ -0,0 +1,14 @@
+__pycache__/
+*.pyc
+.venv/
+venv/
+dist/
+*.egg-info/
+.pytest_cache/
+web/node_modules/
+web/dist/
+.DS_Store
+conf/
+config.yaml
+.env
+.cursor/
diff --git a/tools/tcmcp/Dockerfile b/tools/tcmcp/Dockerfile
new file mode 100644
index 00000000..e33eb423
--- /dev/null
+++ b/tools/tcmcp/Dockerfile
@@ -0,0 +1,25 @@
+FROM node:20-slim AS web
+
+WORKDIR /web
+COPY web/package.json web/package-lock.json ./
+RUN npm ci
+COPY web/ ./
+RUN npm run build
+
+
+FROM python:3.11-slim
+
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ TCMCP_HOST=0.0.0.0 \
+ TCMCP_PORT=8088
+
+WORKDIR /app
+COPY pyproject.toml README.md ./
+COPY app ./app
+RUN python -m pip install --no-cache-dir .
+
+COPY --from=web /web/dist ./web/dist
+
+EXPOSE 8088
+CMD ["python", "-m", "app.main"]
diff --git a/tools/tcmcp/README.md b/tools/tcmcp/README.md
new file mode 100644
index 00000000..a9f42927
--- /dev/null
+++ b/tools/tcmcp/README.md
@@ -0,0 +1,132 @@
+# Tencent Cloud MCP Initializr
+
+English | [简体中文](README.zh-CN.md)
+
+MIT. Copyright (C) 2026 Tencent. This directory is an optional LoopForge tool; the repository root [`LICENSE`](../../LICENSE) applies.
+
+A [start.spring.io](https://start.spring.io/)-style service: pick Tencent Cloud products and **real resources**, then download a scoped Python MCP project.
+
+Resource IDs go into the generated `config.yaml`. Tool arguments use alias enums (`prod` / `api` / `cache`). The Schema Inspector `tools/list` preview matches the tools registered in the zip, so the model is not flooded with unused tools.
+
+Supported products: Redis, CDB, TDSQL-C, TKE (TKEX), CLS, COS. The first release is read-only. COS lists buckets and objects and reads object metadata; it does not download object bodies.
+
+This tool is not installed by `loopforge install`. Run it from this directory or pull the published image.
+
+## Run locally
+
+Requires Python 3.11+ and Node.js 20+ (for the frontend build).
+
+```bash
+cd tools/tcmcp
+python3 -m venv .venv && source .venv/bin/activate
+pip install -e '.[dev]'
+cd web && npm install && npm run build && cd ..
+python -m app.main
+```
+
+Open http://127.0.0.1:8088 . The server listens on localhost by default. CORS allows the Vite dev origin `http://127.0.0.1:5173`; set `TCMCP_CORS_ORIGINS` (comma-separated) for extra origins. For split development:
+
+```bash
+python -m app.main # API :8088
+cd web && npm run dev # UI :5173, proxies /api
+```
+
+## Docker
+
+LoopForge `vX.Y.Z` releases also publish this image to GHCR (same version as the CLI):
+
+```bash
+docker pull ghcr.io/tencent/loopforge-tcmcp:0.2.0
+docker run --rm -p 127.0.0.1:8088:8088 ghcr.io/tencent/loopforge-tcmcp:0.2.0
+```
+
+Build from this directory (Node builds the UI; Python serves the API and `web/dist`):
+
+```bash
+docker build -t tcmcp .
+docker run --rm -p 127.0.0.1:8088:8088 tcmcp
+```
+
+The container listens on `0.0.0.0:8088`. Map the port with `-p`. Use `-e TCMCP_PORT=9000` to change the port, and `-e TCMCP_CORS_ORIGINS=https://your-host` for extra CORS origins.
+
+The service generates zips and one-click install links. Cloud API keys are used only for that listing request; they are not written to disk or the image. Install packages contain selected resource IDs and are kept for 24 hours. Keys are entered on the user machine and written only to the local client config.
+When exposing this beyond localhost, put TLS and authentication in front of it.
+
+## Workflow
+
+1. Enter the project name, target alias, region, and a cloud API key used only for this request (**not written into the zip**).
+2. Select products, list resources, select instances / log topics, and optionally rename aliases.
+3. Inspect each tool JSON Schema and enum; disable unused tools.
+4. Generate an install command for Cursor / CodeBuddy / Codex / WorkBuddy and paste it into a terminal.
+5. Enter SecretId / SecretKey in the terminal (input is shown as typed). The script downloads the project, creates a venv, installs dependencies, checks MCP, and merges client config.
+6. Refresh MCP or restart the client; confirm any trust prompt. The page can still download a ZIP or copy a Docker deploy command.
+
+## curl one-click install
+
+Each selection gets an install ID valid for 24 hours. The page prints a full command:
+
+```bash
+curl -fsSL 'http://127.0.0.1:8088/codebuddy?project=<install-id>' | bash
+curl -fsSL 'http://127.0.0.1:8088/cursor?project=<install-id>' | bash
+curl -fsSL 'http://127.0.0.1:8088/codex?project=<install-id>' | bash
+curl -fsSL 'http://127.0.0.1:8088/workbuddy?project=<install-id>' | bash
+```
+
+Short entry points prompt for the install ID:
+
+```bash
+curl -fsSL http://127.0.0.1:8088/codebuddy | bash
+```
+
+macOS / Linux only. Requires Bash, Python 3.11+ (venv / pip), and network access to a Python package index.
+Native Windows is not supported; WSL installs only change WSL user config.
+No sudo. Projects land in `~/.local/share/tcmcp/install-*/<project-name>`. Client config is written only after dependencies install.
+
+| Client | Default user config |
+| --- | --- |
+| Cursor | `~/.cursor/mcp.json` |
+| CodeBuddy | `~/.codebuddy/mcp.json` |
+| Codex | `${CODEX_HOME:-~/.codex}/config.toml` |
+| WorkBuddy | `~/.workbuddy/mcp.json` |
+
+The server name is `tcmcp-<project-name>`. Reinstalling replaces that server and leaves other MCP entries alone.
+Each install writes a sibling pre-install snapshot `*.bak-<random-id>` (including an empty snapshot when no config existed). Config and snapshots are `0600`.
+The terminal prints a `rollback.sh` command. Rollback keeps `*.before-rollback-<random-id>` before restoring.
+If the client config changed after install, the script refuses to overwrite and asks for a manual merge. JSON allows comments and trailing commas and is written back as standard JSON; Codex TOML keeps other settings and comments.
+Old install directories are kept until you delete them. Unreadable existing config stops the install.
+
+Override with environment variables (`export` before the pipe):
+
+- `TCMCP_PYTHON`: Python 3.11+ executable.
+- `TCMCP_INSTALL_ID`: install ID for the short entry (required without a TTY).
+- `TENCENT_SECRET_ID` / `TENCENT_SECRET_KEY`: non-interactive keys; written only to local client config, not uploaded to the generator.
+- `TCMCP_INSTALL_DIR`: local install directory.
+- `TCMCP_CLIENT_CONFIG`: client config path when it is not the default.
+
+Server settings:
+
+- `TCMCP_PUBLIC_URL`: public URL such as `https://mcp.example.com` so install scripts can download packages behind a reverse proxy.
+- `TCMCP_INSTALL_STORE`: package directory (default: `tcmcp-installations` under the system temp dir). Share it across workers; mount a volume if containers must keep old links.
+- At most 200 valid packages, 10 MiB each. Expired packages are removed when creating a new one.
+
+Share install links only with people you trust. Use HTTPS for any non-local deploy, and proxy the four script entry points plus `/api/installations`.
+If the gateway requires auth, the terminal must be able to authenticate; a browser session is not sent to curl or the Python downloader.
+
+Config formats: [Cursor MCP](https://prod.cursor.com/docs/mcp), [CodeBuddy](https://www.codebuddy.cn/docs/cli/codebuddy-dir), [Codex MCP](https://developers.openai.com/codex/mcp), [WorkBuddy MCP](https://staging.codebuddy.cn/docs/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/MCP-Guide).
+
+## Generated project
+
+```bash
+export TENCENT_SECRET_ID=AKID...
+export TENCENT_SECRET_KEY=...
+pip install -e .
+python -m tcmcp_server --config ./config.yaml
+```
+
+Copy the `mcp.json` snippet into Cursor. The generated zip includes a CAM policy draft at `deploy/cam-policy.json` (replace `$uin` with the account UIN). That file is not in this source tree.
+
+## Tests
+
+```bash
+pytest
+```
diff --git a/tools/tcmcp/README.zh-CN.md b/tools/tcmcp/README.zh-CN.md
new file mode 100644
index 00000000..62cf4f49
--- /dev/null
+++ b/tools/tcmcp/README.zh-CN.md
@@ -0,0 +1,135 @@
+# 腾讯云 MCP Initializr
+
+[English](README.md) | 简体中文
+
+MIT。Copyright (C) 2026 Tencent。本目录是 LoopForge 的可选工具,适用仓库根目录 [`LICENSE`](../../LICENSE)。
+
+类似 [start.spring.io](https://start.spring.io/):在页面上勾选腾讯云产品与**真实资源**,下载一个精简的 Python MCP 项目。
+
+资源 ID 写入生成项目的 `config.yaml`,工具入参只有别名 enum(`prod` / `api` / `cache`)。右侧 Schema Inspector 预览的 `tools/list` 与 zip 里注册的工具同源,避免一次挂上过多工具让模型幻觉。
+
+支持的产品:Redis、CDB、TDSQL-C、TKE(TKEX)、CLS、COS。一期只走只读 API;COS 仅列桶、列对象和查询对象元数据,不下载对象内容。
+
+`loopforge install` **不会**安装本工具。在本目录运行,或拉取已发布镜像。
+
+## 本地运行
+
+需要 Python 3.11+,以及用于前端构建的 Node.js 20+。
+
+```bash
+cd tools/tcmcp
+python3 -m venv .venv && source .venv/bin/activate
+pip install -e '.[dev]'
+cd web && npm install && npm run build && cd ..
+python -m app.main
+```
+
+打开 http://127.0.0.1:8088 。默认只监听本机。跨域只放行 Vite 开发源 `http://127.0.0.1:5173`;需要额外源时设 `TCMCP_CORS_ORIGINS`(逗号分隔)。开发时也可以分开跑:
+
+```bash
+python -m app.main # API :8088
+cd web && npm run dev # UI :5173,代理 /api
+```
+
+## Docker
+
+LoopForge 打 `vX.Y.Z` tag 发版时,会把本镜像推到 GHCR(版本号与 CLI 相同):
+
+```bash
+docker pull ghcr.io/tencent/loopforge-tcmcp:0.2.0
+docker run --rm -p 127.0.0.1:8088:8088 ghcr.io/tencent/loopforge-tcmcp:0.2.0
+```
+
+在本目录本地构建(Node 打前端,Python 跑 API 并托管 `web/dist`):
+
+```bash
+docker build -t tcmcp .
+docker run --rm -p 127.0.0.1:8088:8088 tcmcp
+```
+
+容器内监听 `0.0.0.0:8088`,用 `-p` 决定对外暴露到哪。改端口用 `-e TCMCP_PORT=9000`,
+需要额外跨域来源用 `-e TCMCP_CORS_ORIGINS=https://your-host`。
+
+这个服务生成 zip 和一键安装链接,云 API 密钥仅在单次资源查询请求里透传,不落盘也不写进镜像。
+一键安装包包含所选资源信息,服务端临时保留 24 小时;密钥在用户终端输入,仅写入用户本机客户端配置。
+放到本机以外时,前面要加带 TLS 和认证的网关。
+
+## 工作流
+
+1. 填项目名、target 别名、地域,以及仅用于当次请求的云 API 密钥(**不写入 zip**)。
+2. 勾选产品,拉取资源,勾选实例 / 日志主题,可改别名。
+3. 右侧查看每个工具的 JSON Schema 与 enum;可关掉单个工具。
+4. 点击「生成安装命令」,选择 Cursor / CodeBuddy / Codex / WorkBuddy,将命令粘贴到终端运行。
+5. 在终端输入 SecretId / SecretKey(输入内容正常显示),自动下载项目、创建虚拟环境、安装依赖、检查 MCP 并合并客户端配置。
+6. 在客户端刷新 MCP 或重启;如出现信任提示,在客户端确认。安装页仍可下载 ZIP 或复制 Docker 部署命令。
+
+## curl 一键安装
+
+在页面选择资源后,每份配置生成独立安装 ID,有效期 24 小时。页面直接提供完整命令:
+
+```bash
+curl -fsSL 'http://127.0.0.1:8088/codebuddy?project=<安装ID>' | bash
+curl -fsSL 'http://127.0.0.1:8088/cursor?project=<安装ID>' | bash
+curl -fsSL 'http://127.0.0.1:8088/codex?project=<安装ID>' | bash
+curl -fsSL 'http://127.0.0.1:8088/workbuddy?project=<安装ID>' | bash
+```
+
+也可以使用短入口,脚本会通过终端提示输入页面给出的安装 ID:
+
+```bash
+curl -fsSL http://127.0.0.1:8088/codebuddy | bash
+```
+
+支持 macOS / Linux,需 Bash、Python 3.11+(含 venv / pip)及访问 Python 包索引的网络。
+原生 Windows 暂不支持;WSL 安装只修改 WSL 用户配置。
+不需要 sudo。项目装到 `~/.local/share/tcmcp/install-*/<项目名>`,依赖安装完成后才写入客户端。
+
+| 客户端 | 默认用户级配置 |
+| --- | --- |
+| Cursor | `~/.cursor/mcp.json` |
+| CodeBuddy | `~/.codebuddy/mcp.json` |
+| Codex | `${CODEX_HOME:-~/.codex}/config.toml` |
+| WorkBuddy | `~/.workbuddy/mcp.json` |
+
+服务名为 `tcmcp-<项目名>`。重复安装替换同名服务,保留其他 MCP 和客户端设置。
+每次安装都会生成相邻的安装前快照 `*.bak-<随机ID>`,即使此前没有配置文件也会生成空配置快照;配置和快照权限为 `0600`。
+安装完成后终端会打印该版本的 `rollback.sh` 命令。执行回滚时,原配置恢复前还会保留一份 `*.before-rollback-<随机ID>`。
+如果安装后客户端配置又被修改,脚本会拒绝自动覆盖,提示人工合并。JSON 配置支持注释和尾逗号,写回标准 JSON;Codex TOML 保留其他设置与注释。
+旧安装目录保留,方便恢复备份后继续运行;确认新版本可用后可手动清理旧目录。
+已有配置无法解析时停止,不覆盖原文件。
+
+可通过环境变量覆盖行为(先 `export`,再执行管道命令):
+
+- `TCMCP_PYTHON`:Python 3.11+ 可执行文件路径。
+- `TCMCP_INSTALL_ID`:短入口使用的安装 ID,无终端环境必须提供。
+- `TENCENT_SECRET_ID` / `TENCENT_SECRET_KEY`:免交互输入密钥;仅写入本机配置,不上传到生成服务。
+- `TCMCP_INSTALL_DIR`:本机安装目录。
+- `TCMCP_CLIENT_CONFIG`:指定客户端配置路径,适用于非默认安装位置。
+
+服务端设置:
+
+- `TCMCP_PUBLIC_URL`:外部访问地址,例如 `https://mcp.example.com`,反向代理后建议配置,脚本以此下载安装包。
+- `TCMCP_INSTALL_STORE`:安装包目录,默认系统临时目录下的 `tcmcp-installations`。多 worker / 多实例需共享此目录;容器重建后仍需使用旧链接时挂载持久卷。
+- 最多保留 200 份有效安装包,单包最大 10 MiB;创建新包时清理过期包,过期链接不能下载。无后续请求时可由系统定期清理过期临时文件。
+
+安装链接可下载所选资源配置,请只分享给可信人员。对外部署请使用 HTTPS,网关同时转发四个脚本入口和 `/api/installations`。
+如网关要求认证,应确保终端也能完成认证;浏览器登录态不会自动传给 curl 或 Python 下载器。
+
+配置格式依据:[Cursor MCP](https://prod.cursor.com/docs/mcp)、[CodeBuddy 目录说明](https://www.codebuddy.cn/docs/cli/codebuddy-dir)、[Codex MCP](https://developers.openai.com/codex/mcp)、[WorkBuddy MCP](https://staging.codebuddy.cn/docs/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/MCP-Guide)。
+
+## 生成项目
+
+```bash
+export TENCENT_SECRET_ID=AKID...
+export TENCENT_SECRET_KEY=...
+pip install -e .
+python -m tcmcp_server --config ./config.yaml
+```
+
+把 `mcp.json` 片段拷到 Cursor。生成的 zip 内有 CAM 草稿 `deploy/cam-policy.json`(把 `$uin` 换成主账号 UIN)。该文件不在本源码树中。
+
+## 测试
+
+```bash
+pytest
+```
diff --git a/tools/tcmcp/app/__init__.py b/tools/tcmcp/app/__init__.py
new file mode 100644
index 00000000..c42eec95
--- /dev/null
+++ b/tools/tcmcp/app/__init__.py
@@ -0,0 +1,3 @@
+"""Tencent Cloud MCP Initializr."""
+
+__version__ = "0.1.0"
diff --git a/tools/tcmcp/app/cam.py b/tools/tcmcp/app/cam.py
new file mode 100644
index 00000000..e1ab8e80
--- /dev/null
+++ b/tools/tcmcp/app/cam.py
@@ -0,0 +1,186 @@
+"""Draft a resource-scoped CAM policy for the selected cloud objects."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from app.models import Selection
+
+
+def cam_policy(selection: Selection) -> dict[str, Any]:
+ region = selection.project.region or "ap-guangzhou"
+ statements: list[dict[str, Any]] = []
+ products = set(selection.products)
+
+ if "tdsqlc" in products:
+ resources = [
+ f"qcs::cynosdb:{r.region or region}:uin/$uin:instance/{r.cluster_id}"
+ for r in selection.resources.tdsqlc
+ ]
+ if resources:
+ statements.append(
+ {
+ "_comment": "cynosdb 资源六段式填集群 ID,资源类型名是 instance。",
+ "effect": "allow",
+ "action": [
+ "cynosdb:DescribeClusterDatabases",
+ "cynosdb:SearchClusterTables",
+ "cynosdb:DescribeClusterDetail",
+ "cynosdb:DescribeInstances",
+ "cynosdb:DescribeInstanceSlowQueries",
+ "cynosdb:DescribeInstanceErrorLogs",
+ ],
+ "resource": resources,
+ }
+ )
+ inst = [
+ f"qcs::dbbrain:{r.region or region}:uin/$uin:instanceId/{r.instance_id}"
+ for r in selection.resources.tdsqlc
+ ]
+ statements.append(
+ {
+ "_comment": "DBBrain 资源级接口,填实例 ID。",
+ "effect": "allow",
+ "action": [
+ "dbbrain:DescribeMySqlProcessList",
+ "dbbrain:DescribeSlowLogTopSqls",
+ "dbbrain:DescribeSlowLogTimeSeriesStats",
+ "dbbrain:DescribeUserSqlAdvice",
+ "dbbrain:DescribeHealthScoreTimeSeries",
+ ],
+ "resource": inst,
+ }
+ )
+ statements.append(
+ {
+ "_comment": "DBBrain 操作级接口,resource 只能是 *。",
+ "effect": "allow",
+ "action": [
+ "dbbrain:DescribeDiagDBInstances",
+ "dbbrain:DescribeDBDiagEvents",
+ "dbbrain:DescribeDBDiagEvent",
+ "dbbrain:DescribeHealthScore",
+ "dbbrain:DescribeTopSpaceTables",
+ ],
+ "resource": ["*"],
+ }
+ )
+
+ if "cdb" in products:
+ resources = [
+ f"qcs::cdb:{r.region or region}:uin/$uin:instanceId/{r.id}"
+ for r in selection.resources.cdb
+ ]
+ if resources:
+ statements.append(
+ {
+ "effect": "allow",
+ "action": [
+ "cdb:DescribeDBInstances",
+ "cdb:DescribeDatabases",
+ "cdb:DescribeSlowLogs",
+ "cdb:DescribeErrorLog",
+ ],
+ "resource": resources,
+ }
+ )
+ statements.append(
+ {
+ "effect": "allow",
+ "action": [
+ "dbbrain:DescribeMySqlProcessList",
+ "dbbrain:DescribeSlowLogTopSqls",
+ "dbbrain:DescribeUserSqlAdvice",
+ "dbbrain:DescribeHealthScoreTimeSeries",
+ "dbbrain:DescribeDBDiagEvents",
+ "dbbrain:DescribeDBDiagEvent",
+ "dbbrain:DescribeHealthScore",
+ ],
+ "resource": ["*"],
+ }
+ )
+
+ if "redis" in products:
+ resources = [
+ f"qcs::redis:{r.region or region}:uin/$uin:instance/{r.id}"
+ for r in selection.resources.redis
+ ]
+ if resources:
+ statements.append(
+ {
+ "effect": "allow",
+ "action": [
+ "redis:DescribeInstances",
+ "redis:DescribeSlowLog",
+ "redis:DescribeInstanceParams",
+ ],
+ "resource": resources,
+ }
+ )
+
+ if "tke" in products:
+ resources = [
+ f"qcs::tke:{r.region or region}:uin/$uin:cluster/{r.id}"
+ for r in selection.resources.tke
+ ]
+ if resources:
+ statements.append(
+ {
+ "effect": "allow",
+ "action": [
+ "tke:DescribeClusters",
+ "tke:DescribeClusterStatus",
+ "tke:DescribeClusterInstances",
+ "tke:DescribeClusterNodePools",
+ "tke:DescribeClusterNodePoolDetail",
+ "tke:DescribeNodePools",
+ "tke:DescribeAddon",
+ "tke:DescribeClusterEndpointStatus",
+ "tke:DescribeLogSwitches",
+ "tke:ForwardApplicationRequestV3",
+ ],
+ "resource": resources,
+ }
+ )
+
+ if "cls" in products:
+ topic_ids: list[str] = []
+ for logset in selection.resources.cls:
+ topic_ids.extend(t.id for t in logset.topics)
+ resources = [f"qcs::cls:{region}:uin/$uin:topic/{tid}" for tid in topic_ids]
+ if resources:
+ statements.append(
+ {
+ "effect": "allow",
+ "action": [
+ "cls:SearchLog",
+ "cls:DescribeTopics",
+ "cls:DescribeIndex",
+ "cls:DescribeLogHistogram",
+ ],
+ "resource": resources,
+ }
+ )
+
+ if "cos" in products:
+ resources: list[str] = []
+ for bucket in selection.resources.cos:
+ appid = bucket.id.rsplit("-", 1)[-1]
+ resources.append(
+ f"qcs::cos:{bucket.region or region}:uid/{appid}:{bucket.id}/*"
+ )
+ if resources:
+ statements.append(
+ {
+ "_comment": "COS 桶名须包含 APPID;只授权列对象、检查桶和读取对象元数据。",
+ "effect": "allow",
+ "action": [
+ "cos:HeadBucket",
+ "cos:GetBucket",
+ "cos:HeadObject",
+ ],
+ "resource": resources,
+ }
+ )
+
+ return {"version": "2.0", "statement": statements}
diff --git a/tools/tcmcp/app/catalog.py b/tools/tcmcp/app/catalog.py
new file mode 100644
index 00000000..140e1aa1
--- /dev/null
+++ b/tools/tcmcp/app/catalog.py
@@ -0,0 +1,678 @@
+"""Product → tool catalog. Single source of truth for UI, preview, and zip."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Literal
+
+from app.regions import public_regions
+
+ParamType = Literal["string", "integer", "array"]
+EnumFrom = Literal[
+ "targets",
+ "topics",
+ "redis",
+ "cdb",
+ "tdsqlc",
+ "tke",
+ "cos",
+]
+
+
+@dataclass(frozen=True)
+class Param:
+ name: str
+ type: ParamType
+ description: str
+ required: bool = False
+ enum: tuple[str, ...] | None = None
+ enum_from: EnumFrom | None = None
+ default: Any = None
+ items_type: str | None = None
+
+
+@dataclass(frozen=True)
+class ToolSpec:
+ name: str
+ product: str
+ description: str
+ params: tuple[Param, ...] = ()
+ requires_resources: tuple[str, ...] = ()
+ requires_products: tuple[str, ...] = ()
+ read_only: bool = True
+
+
+@dataclass(frozen=True)
+class ProductSpec:
+ id: str
+ name: str
+ description: str
+ color: str
+
+
+PRODUCTS: tuple[ProductSpec, ...] = (
+ ProductSpec("redis", "Redis", "实例详情、慢日志与参数(云 API 只读)", "#e85d4c"),
+ ProductSpec("cdb", "CDB", "云数据库 MySQL 元数据、慢 SQL 与 DBBrain", "#3d8bfd"),
+ ProductSpec("tdsqlc", "TDSQL-C", "CynosDB 集群拓扑、库表与 DBBrain(Product=cynosdb)", "#2ec27e"),
+ ProductSpec("tke", "TKE", "集群、节点、Pod 日志、组件与日志开关(对应 TKEX / TKE)", "#c084fc"),
+ ProductSpec("cls", "CLS", "日志检索、索引字段与直方图", "#f5a524"),
+ ProductSpec("cos", "COS", "存储桶、对象列表与对象元数据(只读,不下载对象内容)", "#00a4ff"),
+)
+
+TARGET = Param(
+ "target",
+ "string",
+ "目标环境别名(config 里的 targets 键)",
+ required=True,
+ enum_from="targets",
+)
+
+RFC_START = Param("startTime", "string", "开始时间,RFC3339,例如 2026-08-04T15:00:00+08:00")
+RFC_END = Param("endTime", "string", "结束时间,RFC3339。省略则为当前时间")
+LIMIT = Param("limit", "integer", "返回条数;超上限直接报错,不会静默截断")
+
+
+def _dbbrain(prefix: str, catalog_product: str, engine: str, instance_enum: EnumFrom) -> tuple[ToolSpec, ...]:
+ inst = Param(
+ "instance",
+ "string",
+ "已绑定实例的别名(实例 ID 在 config,不由模型填写)",
+ required=True,
+ enum_from=instance_enum,
+ )
+ engine_note = (
+ "DBBrain 的 Product 已写死为 "
+ f"{engine},不作为工具入参。"
+ )
+ return (
+ ToolSpec(
+ f"{prefix}dbbrain_health_score",
+ catalog_product,
+ f"实例健康得分与扣分项。{engine_note}",
+ (TARGET, inst, RFC_START, RFC_END),
+ requires_resources=(instance_enum,),
+ ),
+ ToolSpec(
+ f"{prefix}dbbrain_diag_events",
+ catalog_product,
+ f"诊断事件历史(死锁、全表扫描、慢 SQL 等)。只保留最近 30 天。{engine_note}",
+ (
+ TARGET,
+ inst,
+ RFC_START,
+ RFC_END,
+ Param("limit", "integer", "返回条数,默认 20,上限 50"),
+ Param(
+ "severities",
+ "array",
+ "风险等级:1 致命、2 严重、3 告警、4 提示、5 健康",
+ items_type="integer",
+ ),
+ ),
+ requires_resources=(instance_enum,),
+ ),
+ ToolSpec(
+ f"{prefix}dbbrain_diag_event_detail",
+ catalog_product,
+ "单个诊断事件详情:问题、严重程度与处理建议。eventId 来自 diag_events。",
+ (
+ TARGET,
+ inst,
+ Param("eventId", "integer", "事件 ID", required=True),
+ ),
+ requires_resources=(instance_enum,),
+ ),
+ ToolSpec(
+ f"{prefix}dbbrain_process_list",
+ catalog_product,
+ "当前会话与正在执行的 SQL,用于锁等待和长事务。",
+ (
+ TARGET,
+ inst,
+ Param("db", "string", "按库名过滤"),
+ Param("user", "string", "按账号过滤"),
+ Param("host", "string", "按来源主机过滤"),
+ Param("minSeconds", "integer", "只看执行超过该秒数的会话"),
+ Param("limit", "integer", "返回条数,默认 100,上限 100"),
+ ),
+ requires_resources=(instance_enum,),
+ ),
+ ToolSpec(
+ f"{prefix}dbbrain_slow_top_sqls",
+ catalog_product,
+ "按 SQL 模板聚合的慢查询排行。时间窗不得超过 7 天。",
+ (
+ TARGET,
+ inst,
+ Param("startTime", "string", "开始时间,RFC3339。间隔不得超过 7 天", required=True),
+ Param("endTime", "string", "结束时间,RFC3339", required=True),
+ Param("limit", "integer", "返回条数,默认 20,上限 100"),
+ Param(
+ "sortBy",
+ "string",
+ "排序字段,默认 QueryTime",
+ enum=("QueryTime", "ExecTimes", "RowsSent", "LockTime", "RowsExamined"),
+ default="QueryTime",
+ ),
+ ),
+ requires_resources=(instance_enum,),
+ ),
+ ToolSpec(
+ f"{prefix}dbbrain_sql_advice",
+ catalog_product,
+ "对一条 SQL 给出索引建议与预估收益。不会执行 SQL。",
+ (
+ TARGET,
+ inst,
+ Param("sql", "string", "要分析的 SQL", required=True),
+ Param("schema", "string", "库名"),
+ ),
+ requires_resources=(instance_enum,),
+ ),
+ )
+
+
+TOOLS: tuple[ToolSpec, ...] = (
+ ToolSpec(
+ "ping",
+ "common",
+ "连通性自检。返回服务版本、已配置的产品与资源别名,不访问任何后端。",
+ (TARGET,),
+ requires_resources=(),
+ ),
+ # --- Redis ---
+ ToolSpec(
+ "redis_instance_detail",
+ "redis",
+ "已绑定 Redis 实例的规格、状态、网络与版本(DescribeInstances,按 InstanceId 过滤)。",
+ (
+ TARGET,
+ Param("instance", "string", "实例别名", required=True, enum_from="redis"),
+ ),
+ requires_resources=("redis",),
+ ),
+ ToolSpec(
+ "redis_slow_logs",
+ "redis",
+ "Redis 慢日志明细(DescribeSlowLog)。实例 ID 来自 config。",
+ (
+ TARGET,
+ Param("instance", "string", "实例别名", required=True, enum_from="redis"),
+ RFC_START,
+ RFC_END,
+ LIMIT,
+ ),
+ requires_resources=("redis",),
+ ),
+ ToolSpec(
+ "redis_params",
+ "redis",
+ "实例当前参数列表(DescribeInstanceParams)。",
+ (
+ TARGET,
+ Param("instance", "string", "实例别名", required=True, enum_from="redis"),
+ ),
+ requires_resources=("redis",),
+ ),
+ # --- CDB ---
+ ToolSpec(
+ "cdb_instance_detail",
+ "cdb",
+ "CDB 实例规格、状态、内网地址与版本。实例 ID 来自 config。",
+ (
+ TARGET,
+ Param("instance", "string", "实例别名", required=True, enum_from="cdb"),
+ ),
+ requires_resources=("cdb",),
+ ),
+ ToolSpec(
+ "cdb_list_databases",
+ "cdb",
+ "列出 CDB 实例上的数据库名(DescribeDatabases)。",
+ (
+ TARGET,
+ Param("instance", "string", "实例别名", required=True, enum_from="cdb"),
+ ),
+ requires_resources=("cdb",),
+ ),
+ ToolSpec(
+ "cdb_slow_queries",
+ "cdb",
+ "CDB 慢查询明细(DescribeSlowLogs)。",
+ (
+ TARGET,
+ Param("instance", "string", "实例别名", required=True, enum_from="cdb"),
+ RFC_START,
+ RFC_END,
+ LIMIT,
+ ),
+ requires_resources=("cdb",),
+ ),
+ ToolSpec(
+ "cdb_error_logs",
+ "cdb",
+ "CDB 错误日志(DescribeErrorLog)。",
+ (
+ TARGET,
+ Param("instance", "string", "实例别名", required=True, enum_from="cdb"),
+ RFC_START,
+ RFC_END,
+ LIMIT,
+ ),
+ requires_resources=("cdb",),
+ ),
+ *_dbbrain("cdb_", "cdb", "mysql", "cdb"),
+ # --- TDSQL-C ---
+ ToolSpec(
+ "db_cluster_detail",
+ "tdsqlc",
+ "TDSQL-C 集群拓扑与规格:版本、状态、存储、内网地址及实例角色。集群 ID 来自 config。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tdsqlc"),
+ ),
+ requires_resources=("tdsqlc",),
+ ),
+ ToolSpec(
+ "db_list_databases",
+ "tdsqlc",
+ "列出 TDSQL-C 集群下的数据库名(DescribeClusterDatabases)。走云 API。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tdsqlc"),
+ ),
+ requires_resources=("tdsqlc",),
+ ),
+ ToolSpec(
+ "db_search_tables",
+ "tdsqlc",
+ "按库名和表名模糊搜索表(SearchClusterTables)。不含列定义。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tdsqlc"),
+ Param("database", "string", "库名,省略则搜索全部库"),
+ Param("table", "string", "表名关键字"),
+ Param(
+ "tableType",
+ "string",
+ "表类型,默认 all",
+ enum=("all", "base_table", "view"),
+ default="all",
+ ),
+ ),
+ requires_resources=("tdsqlc",),
+ ),
+ ToolSpec(
+ "tdsqlc_slow_queries",
+ "tdsqlc",
+ "慢 SQL 原始明细(DescribeInstanceSlowQueries)。实例 ID 来自 config。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tdsqlc"),
+ RFC_START,
+ RFC_END,
+ LIMIT,
+ Param("sqlText", "string", "按 SQL 文本过滤"),
+ ),
+ requires_resources=("tdsqlc",),
+ ),
+ ToolSpec(
+ "tdsqlc_error_logs",
+ "tdsqlc",
+ "实例错误日志(DescribeInstanceErrorLogs)。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tdsqlc"),
+ RFC_START,
+ RFC_END,
+ LIMIT,
+ ),
+ requires_resources=("tdsqlc",),
+ ),
+ ToolSpec(
+ "dbbrain_top_space_tables",
+ "tdsqlc",
+ "占用空间最大的表。DBBrain Product 已写死为 cynosdb。",
+ (
+ TARGET,
+ Param("instance", "string", "集群/实例别名", required=True, enum_from="tdsqlc"),
+ Param("limit", "integer", "返回条数,默认 20,上限 100"),
+ Param(
+ "sortBy",
+ "string",
+ "排序字段",
+ enum=("TotalLength", "DataLength", "IndexLength", "DataFree", "FragRatio", "TableRows"),
+ default="TotalLength",
+ ),
+ ),
+ requires_resources=("tdsqlc",),
+ ),
+ ToolSpec(
+ "dbbrain_slow_log_time_series",
+ "tdsqlc",
+ "慢日志数量随时间的分布(间隔不得超过 7 天)。Product=cynosdb。",
+ (
+ TARGET,
+ Param("instance", "string", "集群/实例别名", required=True, enum_from="tdsqlc"),
+ Param("startTime", "string", "开始时间,RFC3339", required=True),
+ Param("endTime", "string", "结束时间,RFC3339", required=True),
+ ),
+ requires_resources=("tdsqlc",),
+ ),
+ *_dbbrain("", "tdsqlc", "cynosdb", "tdsqlc"),
+ # --- TKE ---
+ ToolSpec(
+ "tke_cluster_detail",
+ "tke",
+ "已绑定 TKE 集群的状态、版本、网络与节点概况。集群 ID 来自 config。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_cluster_status",
+ "tke",
+ "集群运行状态与节点健康汇总(DescribeClusterStatus)。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_list_nodes",
+ "tke",
+ "列出集群节点:IP、状态、节点池、是否封锁(DescribeClusterInstances)。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ Param("nodePoolId", "string", "按节点池 ID 过滤,可空"),
+ Param("offset", "integer", "分页偏移,默认 0"),
+ LIMIT,
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_list_node_pools",
+ "tke",
+ "列出集群节点池,含原生 / 普通 / 超级 / 第三方(DescribeNodePools + DescribeClusterNodePools)。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_node_pool_detail",
+ "tke",
+ "单个节点池详情。普通池走 DescribeClusterNodePoolDetail,原生池走 DescribeNodePools。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ Param("nodePoolId", "string", "节点池 ID,例如 np-xxxx", required=True),
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_list_addons",
+ "tke",
+ "列出集群已安装组件及版本、状态(DescribeAddon)。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ Param("addon", "string", "组件名;不填则返回全部"),
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_endpoint_status",
+ "tke",
+ "集群 apiserver 内网/外网访问端口是否已开通(DescribeClusterEndpointStatus)。不返回 kubeconfig。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_log_switches",
+ "tke",
+ "集群审计 / 事件 / 日志采集开关(DescribeLogSwitches)。和 CLS 的 k8s_audit / k8s_events 配套。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_list_pods",
+ "tke",
+ "列出集群 Pod(ForwardApplicationRequestV3 GET /api/v1/pods)。用来找 pod 名再查日志。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ Param("namespace", "string", "命名空间;不填则全集群"),
+ Param("labelSelector", "string", "标签选择器,例如 app=api"),
+ LIMIT,
+ ),
+ requires_resources=("tke",),
+ ),
+ ToolSpec(
+ "tke_pod_logs",
+ "tke",
+ "读取某个 Pod 当前容器的最近日志(k8s pods/log,实时,不是 CLS)。",
+ (
+ TARGET,
+ Param("cluster", "string", "集群别名", required=True, enum_from="tke"),
+ Param("pod", "string", "Pod 名", required=True),
+ Param("namespace", "string", "命名空间,默认 default"),
+ Param("container", "string", "多容器时指定容器名"),
+ Param("tailLines", "integer", "最近多少行,默认 200,上限 500"),
+ Param("previous", "string", "true 则读上一次崩溃容器的日志", enum=("true", "false"), default="false"),
+ ),
+ requires_resources=("tke",),
+ ),
+ # --- CLS ---
+ ToolSpec(
+ "cls_search_log",
+ "cls",
+ "检索 CLS 日志(SearchLog),CQL 语法。topic 用别名,不是 UUID。",
+ (
+ TARGET,
+ Param("query", "string", "CQL 检索语句;查全部用 *", required=True),
+ Param("topic", "string", "日志主题别名", required=True, enum_from="topics"),
+ RFC_START,
+ RFC_END,
+ Param("limit", "integer", "返回条数,默认 100,上限 1000"),
+ Param("sort", "string", "按时间排序", enum=("asc", "desc"), default="desc"),
+ ),
+ requires_resources=("cls",),
+ ),
+ ToolSpec(
+ "cls_list_topics",
+ "cls",
+ "列出该环境已绑定的日志主题别名与配置中的 UUID 对应关系。",
+ (TARGET,),
+ requires_resources=("cls",),
+ ),
+ ToolSpec(
+ "cls_index_fields",
+ "cls",
+ "列出某个日志主题已建索引的字段及类型。写检索语句前先看这个。",
+ (
+ TARGET,
+ Param("topic", "string", "日志主题别名", required=True, enum_from="topics"),
+ ),
+ requires_resources=("cls",),
+ ),
+ ToolSpec(
+ "cls_histogram",
+ "cls",
+ "按时间分桶统计命中条数(DescribeLogHistogram)。先看分布再下钻。",
+ (
+ TARGET,
+ Param("query", "string", "CQL 检索语句;查全部用 *", required=True),
+ Param("topic", "string", "日志主题别名", required=True, enum_from="topics"),
+ RFC_START,
+ RFC_END,
+ Param("interval", "string", "分桶间隔,例如 30s / 5m / 1h", default="5m"),
+ ),
+ requires_resources=("cls",),
+ ),
+ ToolSpec(
+ "container_logs",
+ "cls",
+ "按容器维度检索已采集进 CLS 的历史 stdout。要看当前 Pod 实时日志用 tke_pod_logs。需要同时启用 TKE。",
+ (
+ TARGET,
+ Param("workload", "string", "workload / 容器名"),
+ Param("pod", "string", "精确到某个 pod 名"),
+ Param("query", "string", "附加 CQL 条件,例如 level:error"),
+ RFC_START,
+ RFC_END,
+ LIMIT,
+ ),
+ requires_resources=("cls",),
+ requires_products=("tke",),
+ ),
+ ToolSpec(
+ "k8s_events",
+ "cls",
+ "检索已绑定的 k8s 事件主题(别名 events,若未绑定则不可用)。",
+ (
+ TARGET,
+ Param("query", "string", "附加 CQL 条件"),
+ RFC_START,
+ RFC_END,
+ LIMIT,
+ ),
+ requires_resources=("cls",),
+ requires_products=("tke",),
+ ),
+ ToolSpec(
+ "k8s_audit",
+ "cls",
+ "检索 kube-apiserver 审计日志(别名 audit,若未绑定则不可用)。",
+ (
+ TARGET,
+ Param("query", "string", "例如 verb:update AND objectRef.resource:deployments"),
+ RFC_START,
+ RFC_END,
+ LIMIT,
+ ),
+ requires_resources=("cls",),
+ requires_products=("tke",),
+ ),
+ # --- COS ---
+ ToolSpec(
+ "cos_bucket_detail",
+ "cos",
+ "检查已绑定 COS 存储桶是否存在且当前身份是否有访问权限(HeadBucket)。",
+ (
+ TARGET,
+ Param("bucket", "string", "存储桶别名", required=True, enum_from="cos"),
+ ),
+ requires_resources=("cos",),
+ ),
+ ToolSpec(
+ "cos_list_objects",
+ "cos",
+ "列出 COS 存储桶中的对象和公共前缀(GetBucket/ListObjects),不读取对象内容。",
+ (
+ TARGET,
+ Param("bucket", "string", "存储桶别名", required=True, enum_from="cos"),
+ Param("prefix", "string", "只返回以该字符串开头的对象键"),
+ Param("delimiter", "string", "目录分隔符,通常为 /"),
+ Param("marker", "string", "分页起点;使用上次返回的 nextMarker"),
+ Param("limit", "integer", "返回对象和公共前缀的总上限,默认 100,上限 1000"),
+ ),
+ requires_resources=("cos",),
+ ),
+ ToolSpec(
+ "cos_object_metadata",
+ "cos",
+ "查询 COS 对象的响应头与自定义元数据(HeadObject),不下载对象内容。",
+ (
+ TARGET,
+ Param("bucket", "string", "存储桶别名", required=True, enum_from="cos"),
+ Param("key", "string", "对象键,例如 logs/2026-09-14.json", required=True),
+ Param("versionId", "string", "可选的对象版本 ID"),
+ ),
+ requires_resources=("cos",),
+ ),
+)
+
+
+PRODUCT_BY_ID = {p.id: p for p in PRODUCTS}
+TOOL_BY_NAME = {t.name: t for t in TOOLS}
+
+TOOL_WARN_THRESHOLD = 15
+
+
+def tools_for_products(products: list[str]) -> list[ToolSpec]:
+ enabled = set(products)
+ out: list[ToolSpec] = []
+ for tool in TOOLS:
+ if tool.product == "common":
+ out.append(tool)
+ continue
+ if tool.product not in enabled:
+ continue
+ if tool.requires_products and not set(tool.requires_products) <= enabled:
+ continue
+ out.append(tool)
+ return out
+
+
+def metadata() -> dict[str, Any]:
+ by_product: dict[str, list[dict[str, Any]]] = {p.id: [] for p in PRODUCTS}
+ by_product["common"] = []
+ for tool in TOOLS:
+ by_product.setdefault(tool.product, []).append(_tool_public(tool))
+ return {
+ "name": "Tencent Cloud MCP Initializr",
+ "version": "0.1.0",
+ "toolWarnThreshold": TOOL_WARN_THRESHOLD,
+ "defaults": {
+ "name": "demo",
+ "target": "prod",
+ "region": "ap-guangzhou",
+ },
+ "products": [
+ {
+ "id": p.id,
+ "name": p.name,
+ "description": p.description,
+ "color": p.color,
+ "tools": by_product.get(p.id, []),
+ }
+ for p in PRODUCTS
+ ],
+ "commonTools": by_product["common"],
+ "regions": public_regions(),
+ }
+
+
+def _tool_public(tool: ToolSpec) -> dict[str, Any]:
+ return {
+ "name": tool.name,
+ "description": tool.description,
+ "product": tool.product,
+ "requiresResources": list(tool.requires_resources),
+ "requiresProducts": list(tool.requires_products),
+ "readOnly": tool.read_only,
+ "params": [
+ {
+ "name": p.name,
+ "type": p.type,
+ "description": p.description,
+ "required": p.required,
+ "enum": list(p.enum) if p.enum else None,
+ "enumFrom": p.enum_from,
+ "default": p.default,
+ }
+ for p in tool.params
+ ],
+ }
diff --git a/tools/tcmcp/app/cloud/__init__.py b/tools/tcmcp/app/cloud/__init__.py
new file mode 100644
index 00000000..6d1f8a97
--- /dev/null
+++ b/tools/tcmcp/app/cloud/__init__.py
@@ -0,0 +1,5 @@
+"""Read-only Tencent Cloud resource listing. Credentials are per-request only."""
+
+from app.cloud.listing import list_resources
+
+__all__ = ["list_resources"]
diff --git a/tools/tcmcp/app/cloud/listing.py b/tools/tcmcp/app/cloud/listing.py
new file mode 100644
index 00000000..bfdc26bd
--- /dev/null
+++ b/tools/tcmcp/app/cloud/listing.py
@@ -0,0 +1,297 @@
+"""Describe* wrappers. Secrets never leave the request scope."""
+
+from __future__ import annotations
+
+from typing import Any, Callable
+
+from app.models import (
+ CloudCreds,
+ ListedLogset,
+ ListedResource,
+ ListedTopic,
+ ResourceCatalog,
+)
+
+
+def _client(product: str, secret_id: str, secret_key: str, region: str):
+ from tencentcloud.common import credential
+ from tencentcloud.common.profile.client_profile import ClientProfile
+ from tencentcloud.common.profile.http_profile import HttpProfile
+
+ cred = credential.Credential(secret_id, secret_key)
+ http = HttpProfile(endpoint=f"{product}.tencentcloudapi.com")
+ profile = ClientProfile(httpProfile=http)
+ if product == "redis":
+ from tencentcloud.redis.v20180412.redis_client import RedisClient
+
+ return RedisClient(cred, region, profile)
+ if product == "cdb":
+ from tencentcloud.cdb.v20170320.cdb_client import CdbClient
+
+ return CdbClient(cred, region, profile)
+ if product == "cynosdb":
+ from tencentcloud.cynosdb.v20190107.cynosdb_client import CynosdbClient
+
+ return CynosdbClient(cred, region, profile)
+ if product == "tke":
+ from tencentcloud.tke.v20180525.tke_client import TkeClient
+
+ return TkeClient(cred, region, profile)
+ if product == "cls":
+ from tencentcloud.cls.v20201016.cls_client import ClsClient
+
+ return ClsClient(cred, region, profile)
+ raise ValueError(f"unknown product {product}")
+
+
+def _safe(label: str, errors: dict[str, str], fn: Callable[[], Any]) -> Any:
+ try:
+ return fn()
+ except Exception as exc: # noqa: BLE001 — surface any SDK/auth error to the UI
+ errors[label] = str(exc)
+ return None
+
+
+def _cos_client(secret_id: str, secret_key: str, region: str):
+ from qcloud_cos import CosConfig, CosS3Client
+
+ config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Scheme="https")
+ return CosS3Client(config)
+
+
+def list_redis(creds: CloudCreds) -> list[ListedResource]:
+ from tencentcloud.redis.v20180412 import models
+
+ client = _client("redis", creds.secret_id, creds.secret_key, creds.region)
+ req = models.DescribeInstancesRequest()
+ req.Limit = 100
+ if creds.project_id is not None:
+ req.ProjectIds = [creds.project_id]
+ resp = client.DescribeInstances(req)
+ out: list[ListedResource] = []
+ for inst in resp.InstanceSet or []:
+ pid = int(inst.ProjectId) if getattr(inst, "ProjectId", None) is not None else None
+ out.append(
+ ListedResource(
+ id=inst.InstanceId or "",
+ name=inst.InstanceName or inst.InstanceId or "",
+ region=getattr(inst, "Region", None) or creds.region,
+ projectId=pid,
+ extra={"status": inst.Status, "size": inst.Size, "engine": inst.Type},
+ )
+ )
+ return out
+
+
+def list_cdb(creds: CloudCreds) -> list[ListedResource]:
+ from tencentcloud.cdb.v20170320 import models
+
+ client = _client("cdb", creds.secret_id, creds.secret_key, creds.region)
+ req = models.DescribeDBInstancesRequest()
+ req.Limit = 100
+ if creds.project_id is not None:
+ req.ProjectId = creds.project_id
+ resp = client.DescribeDBInstances(req)
+ out: list[ListedResource] = []
+ for inst in resp.Items or []:
+ out.append(
+ ListedResource(
+ id=inst.InstanceId or "",
+ name=inst.InstanceName or inst.InstanceId or "",
+ region=inst.Region or creds.region,
+ projectId=int(inst.ProjectId) if inst.ProjectId is not None else None,
+ extra={
+ "status": inst.Status,
+ "engine": inst.EngineVersion,
+ "vip": inst.Vip,
+ "instanceType": inst.InstanceType,
+ },
+ )
+ )
+ return out
+
+
+def list_tdsqlc(creds: CloudCreds) -> list[ListedResource]:
+ from tencentcloud.cynosdb.v20190107 import models
+
+ client = _client("cynosdb", creds.secret_id, creds.secret_key, creds.region)
+ req = models.DescribeClustersRequest()
+ req.Limit = 100
+ if creds.project_id is not None:
+ filt = models.QueryFilter()
+ filt.Names = ["ProjectId"]
+ filt.Values = [str(creds.project_id)]
+ filt.ExactMatch = True
+ req.Filters = [filt]
+ resp = client.DescribeClusters(req)
+ out: list[ListedResource] = []
+ for cluster in resp.ClusterSet or []:
+ instance_id = ""
+ members = getattr(cluster, "InstanceSet", None) or []
+ for member in members:
+ role = (getattr(member, "InstanceRole", None) or "").lower()
+ if role in ("master", "rw", "primary"):
+ instance_id = member.InstanceId or ""
+ break
+ if not instance_id and members:
+ instance_id = members[0].InstanceId or ""
+ if not instance_id:
+ instance_id = _first_cynos_instance(client, cluster.ClusterId)
+ out.append(
+ ListedResource(
+ id=cluster.ClusterId or "",
+ name=cluster.ClusterName or cluster.ClusterId or "",
+ region=getattr(cluster, "Region", None) or creds.region,
+ projectId=int(cluster.ProjectId) if getattr(cluster, "ProjectId", None) is not None else None,
+ extra={
+ "status": cluster.Status,
+ "instanceId": instance_id,
+ "dbVersion": getattr(cluster, "DbVersion", None),
+ "vip": getattr(cluster, "Vip", None),
+ },
+ )
+ )
+ return out
+
+
+def _first_cynos_instance(client, cluster_id: str) -> str:
+ from tencentcloud.cynosdb.v20190107 import models
+
+ req = models.DescribeInstancesRequest()
+ filt = models.QueryFilter()
+ filt.Names = ["ClusterId"]
+ filt.Values = [cluster_id]
+ filt.ExactMatch = True
+ req.Filters = [filt]
+ req.Limit = 20
+ resp = client.DescribeInstances(req)
+ items = resp.InstanceSet or []
+ for inst in items:
+ role = (getattr(inst, "InstanceRole", None) or "").lower()
+ if role in ("master", "rw", "primary"):
+ return inst.InstanceId or ""
+ return items[0].InstanceId if items else ""
+
+
+def list_tke(creds: CloudCreds) -> list[ListedResource]:
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client("tke", creds.secret_id, creds.secret_key, creds.region)
+ req = models.DescribeClustersRequest()
+ req.Limit = 100
+ if creds.project_id is not None:
+ filt = models.Filter()
+ filt.Name = "ProjectId"
+ filt.Values = [str(creds.project_id)]
+ req.Filters = [filt]
+ resp = client.DescribeClusters(req)
+ out: list[ListedResource] = []
+ for cluster in resp.Clusters or []:
+ pid = None
+ if getattr(cluster, "ProjectId", None) not in (None, ""):
+ try:
+ pid = int(cluster.ProjectId)
+ except (TypeError, ValueError):
+ pid = None
+ out.append(
+ ListedResource(
+ id=cluster.ClusterId or "",
+ name=cluster.ClusterName or cluster.ClusterId or "",
+ region=creds.region,
+ projectId=pid,
+ extra={
+ "status": cluster.ClusterStatus,
+ "version": cluster.ClusterVersion,
+ "type": cluster.ClusterType,
+ },
+ )
+ )
+ return out
+
+
+def list_cls(creds: CloudCreds) -> list[ListedLogset]:
+ from tencentcloud.cls.v20201016 import models
+
+ client = _client("cls", creds.secret_id, creds.secret_key, creds.region)
+ req = models.DescribeLogsetsRequest()
+ req.Offset = 0
+ req.Limit = 100
+ resp = client.DescribeLogsets(req)
+ out: list[ListedLogset] = []
+ for logset in resp.Logsets or []:
+ topics: list[ListedTopic] = []
+ t_req = models.DescribeTopicsRequest()
+ filt = models.Filter()
+ filt.Key = "logsetId"
+ filt.Values = [logset.LogsetId]
+ t_req.Filters = [filt]
+ t_req.Offset = 0
+ t_req.Limit = 100
+ t_resp = client.DescribeTopics(t_req)
+ for topic in t_resp.Topics or []:
+ topics.append(
+ ListedTopic(
+ id=topic.TopicId or "",
+ name=topic.TopicName or topic.TopicId or "",
+ logsetId=logset.LogsetId or "",
+ )
+ )
+ out.append(
+ ListedLogset(
+ id=logset.LogsetId or "",
+ name=logset.LogsetName or logset.LogsetId or "",
+ region=creds.region,
+ topics=topics,
+ )
+ )
+ return out
+
+
+def list_cos(creds: CloudCreds) -> list[ListedResource]:
+ """List COS buckets in the requested region via GET Service."""
+ client = _cos_client(creds.secret_id, creds.secret_key, creds.region)
+ response = client.list_buckets(Region=creds.region)
+ bucket_rows = (response.get("Buckets") or {}).get("Bucket") or []
+ if isinstance(bucket_rows, dict):
+ bucket_rows = [bucket_rows]
+
+ out: list[ListedResource] = []
+ for bucket in bucket_rows:
+ name = str(bucket.get("Name") or "")
+ region = str(bucket.get("Location") or creds.region)
+ if region != creds.region:
+ continue
+ out.append(
+ ListedResource(
+ id=name,
+ name=name,
+ region=region,
+ extra={"creationDate": bucket.get("CreationDate")},
+ )
+ )
+ return out
+
+
+LISTERS = {
+ "redis": list_redis,
+ "cdb": list_cdb,
+ "tdsqlc": list_tdsqlc,
+ "tke": list_tke,
+ "cls": list_cls,
+ "cos": list_cos,
+}
+
+
+def list_resources(creds: CloudCreds) -> ResourceCatalog:
+ products = creds.products or list(LISTERS)
+ errors: dict[str, str] = {}
+ data: dict[str, Any] = {"errors": errors}
+ for product in products:
+ lister = LISTERS.get(product)
+ if not lister:
+ errors[product] = f"unknown product {product}"
+ continue
+ result = _safe(product, errors, lambda lister=lister: lister(creds))
+ if result is not None:
+ data[product] = result
+ return ResourceCatalog.model_validate(data)
diff --git a/tools/tcmcp/app/generate.py b/tools/tcmcp/app/generate.py
new file mode 100644
index 00000000..a2fa7e49
--- /dev/null
+++ b/tools/tcmcp/app/generate.py
@@ -0,0 +1,351 @@
+"""Render a scoped Python MCP project into a zip."""
+
+from __future__ import annotations
+
+import io
+import json
+import re
+import zipfile
+from pathlib import Path
+
+import yaml
+
+from app.cam import cam_policy
+from app.models import Selection
+from app.preview import materialize
+
+ROOT = Path(__file__).resolve().parent
+RUNTIME = ROOT / "mcp_runtime"
+
+
+def _slug(name: str) -> str:
+ s = re.sub(r"[^a-zA-Z0-9._-]+", "-", name.strip()).strip("-._")
+ return s or "tcmcp-project"
+
+
+def config_dict(selection: Selection) -> dict:
+ target = selection.project.target or "prod"
+ region = selection.project.region or "ap-guangzhou"
+ t: dict = {"description": selection.project.description}
+ if selection.resources.redis:
+ t["redis"] = [
+ {"alias": r.alias, "id": r.id, "name": r.name, "region": r.region or region}
+ for r in selection.resources.redis
+ ]
+ if selection.resources.cdb:
+ t["cdb"] = [
+ {"alias": r.alias, "id": r.id, "name": r.name, "region": r.region or region}
+ for r in selection.resources.cdb
+ ]
+ if selection.resources.tdsqlc:
+ t["tdsqlc"] = [
+ {
+ "alias": r.alias,
+ "clusterId": r.cluster_id,
+ "instanceId": r.instance_id,
+ "name": r.name,
+ "region": r.region or region,
+ "product": "cynosdb",
+ }
+ for r in selection.resources.tdsqlc
+ ]
+ if selection.resources.tke:
+ t["tke"] = [
+ {"alias": r.alias, "id": r.id, "name": r.name, "region": r.region or region}
+ for r in selection.resources.tke
+ ]
+ if selection.resources.cls:
+ t["cls"] = []
+ for logset in selection.resources.cls:
+ t["cls"].append(
+ {
+ "logsetId": logset.logset_id,
+ "logsetName": logset.logset_name,
+ "region": logset.region or region,
+ "topics": [
+ {"alias": topic.alias, "id": topic.id, "name": topic.name}
+ for topic in logset.topics
+ ],
+ }
+ )
+ if selection.resources.cos:
+ t["cos"] = [
+ {"alias": r.alias, "id": r.id, "name": r.name, "region": r.region or region}
+ for r in selection.resources.cos
+ ]
+ return {
+ "server": {
+ "listen": "127.0.0.1:8099",
+ "endpointPath": "/mcp",
+ },
+ "project": {
+ "name": selection.project.name,
+ "description": selection.project.description,
+ "target": target,
+ },
+ "products": list(selection.products),
+ "disabledTools": list(selection.disabled_tools),
+ "limits": {"maxRows": 200, "maxBytes": 262144, "queryTimeout": "30s"},
+ "auth": {"tokens": ["${TCMCP_AUTH_TOKEN}"]},
+ "tencent": {
+ "secretId": "${TENCENT_SECRET_ID}",
+ "secretKey": "${TENCENT_SECRET_KEY}",
+ "region": region,
+ },
+ "targets": {target: t},
+ }
+
+
+def rewrite_app_imports(src: str) -> str:
+ return src.replace("from app.", "from tcmcp_server.").replace("import app.", "import tcmcp_server.")
+
+
+def build_files(selection: Selection) -> dict[str, bytes]:
+ preview = materialize(selection)
+ registered = set(preview["registered"])
+ products = set(selection.products)
+ slug = _slug(selection.project.name)
+ cfg = config_dict(selection)
+ files: dict[str, bytes] = {}
+
+ files[f"{slug}/config.yaml"] = yaml.safe_dump(cfg, allow_unicode=True, sort_keys=False).encode()
+ files[f"{slug}/config.example.yaml"] = files[f"{slug}/config.yaml"]
+ files[f"{slug}/deploy/cam-policy.json"] = json.dumps(
+ cam_policy(selection), indent=2, ensure_ascii=False
+ ).encode()
+ files[f"{slug}/pyproject.toml"] = _pyproject(selection).encode()
+ files[f"{slug}/README.md"] = _readme(selection, preview).encode()
+ files[f"{slug}/mcp.json"] = _mcp_json(selection).encode()
+ files[f"{slug}/run.sh"] = _run_script().encode()
+ files[f"{slug}/Dockerfile"] = _dockerfile().encode()
+ files[f"{slug}/.dockerignore"] = _dockerignore().encode()
+
+ # Shared catalog / models / preview — same source the Initializr uses.
+ for name in ("catalog.py", "models.py", "preview.py", "regions.py"):
+ text = rewrite_app_imports((ROOT / name).read_text())
+ files[f"{slug}/src/tcmcp_server/{name}"] = text.encode()
+
+ handler_keep = {"__init__.py", "dispatch.py", "ping.py"}
+ if "redis" in products:
+ handler_keep.add("redis.py")
+ if "cdb" in products:
+ handler_keep.update({"cdb.py", "dbbrain.py"})
+ if "tdsqlc" in products:
+ handler_keep.update({"tdsqlc.py", "dbbrain.py"})
+ if "tke" in products:
+ handler_keep.add("tke.py")
+ if "cls" in products:
+ handler_keep.add("cls.py")
+ if "cos" in products:
+ handler_keep.add("cos.py")
+
+ for path in RUNTIME.rglob("*"):
+ if not path.is_file():
+ continue
+ if "__pycache__" in path.parts or path.suffix == ".pyc":
+ continue
+ rel = path.relative_to(RUNTIME)
+ if rel.parts[0] == "handlers" and rel.name not in handler_keep:
+ continue
+ dest = f"{slug}/src/tcmcp_server/{rel.as_posix()}"
+ files[dest] = path.read_bytes()
+
+ files[f"{slug}/src/tcmcp_server/generated.json"] = json.dumps(
+ {"registered": sorted(registered), "products": list(selection.products)},
+ indent=2,
+ ).encode()
+ return files
+
+
+def build_zip(selection: Selection) -> bytes:
+ files = build_files(selection)
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ for name, data in sorted(files.items()):
+ zf.writestr(name, data)
+ return buf.getvalue()
+
+
+def _pyproject(selection: Selection) -> str:
+ name = _slug(selection.project.name)
+ dependencies = [
+ "mcp>=1.12.0,<2",
+ "pyyaml>=6.0.2",
+ "pydantic>=2.10.0",
+ "tencentcloud-sdk-python>=3.0.1400",
+ ]
+ if "cos" in selection.products:
+ dependencies.append("cos-python-sdk-v5>=1.9.38")
+ dependency_lines = "\n".join(f' "{dependency}",' for dependency in dependencies)
+ return f"""[project]
+name = "{name}"
+version = "0.1.0"
+description = {json.dumps(selection.project.description, ensure_ascii=False)}
+requires-python = ">=3.11"
+dependencies = [
+{dependency_lines}
+]
+
+[project.scripts]
+{json.dumps(name)} = "tcmcp_server.server:main"
+
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools.packages.find]
+where = ["src"]
+"""
+
+
+def _mcp_json(selection: Selection) -> str:
+ name = _slug(selection.project.name)
+ body = {
+ "mcpServers": {
+ name: {
+ "command": "/bin/bash",
+ "args": [f"/absolute/path/to/{name}/run.sh"],
+ "env": {
+ "TENCENT_SECRET_ID": "",
+ "TENCENT_SECRET_KEY": "",
+ },
+ }
+ }
+ }
+ return json.dumps(body, indent=2)
+
+
+def _run_script() -> str:
+ return """#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PYTHON="${TCMCP_PYTHON:-python3}"
+VENV="${TCMCP_VENV:-$ROOT/.venv}"
+MARKER="$VENV/.tcmcp-installed"
+
+if ! command -v "$PYTHON" >/dev/null 2>&1; then
+ echo "tcmcp: Python 3.11+ is required; set TCMCP_PYTHON if it is installed elsewhere." >&2
+ exit 127
+fi
+
+if ! "$PYTHON" -c 'import sys; raise SystemExit(sys.version_info < (3, 11))'; then
+ echo "tcmcp: Python 3.11+ is required." >&2
+ exit 1
+fi
+
+if [[ ! -x "$VENV/bin/python" ]]; then
+ echo "tcmcp: creating virtual environment at $VENV" >&2
+ "$PYTHON" -m venv "$VENV"
+fi
+
+if [[ ! -f "$MARKER" || "$ROOT/pyproject.toml" -nt "$MARKER" ]]; then
+ echo "tcmcp: installing dependencies (first start may take a moment)" >&2
+ "$VENV/bin/python" -m pip install -e "$ROOT" >&2
+ touch "$MARKER"
+fi
+
+exec "$VENV/bin/python" -m tcmcp_server --config "$ROOT/config.yaml" "$@"
+"""
+
+
+def _dockerfile() -> str:
+ return """FROM python:3.11-slim
+
+ENV PYTHONDONTWRITEBYTECODE=1 \\
+ PYTHONUNBUFFERED=1
+
+WORKDIR /app
+COPY pyproject.toml ./
+COPY src ./src
+RUN python -m pip install --no-cache-dir .
+
+COPY config.yaml ./config.yaml
+EXPOSE 8099
+
+CMD ["python", "-m", "tcmcp_server", "--config", "/app/config.yaml", "--transport", "http", "--listen", "0.0.0.0:8099"]
+"""
+
+
+def _dockerignore() -> str:
+ return """.venv
+__pycache__
+*.pyc
+.git
+.env
+"""
+
+
+def _readme(selection: Selection, preview: dict) -> str:
+ tools = "\n".join(f"- `{n}`" for n in preview["registered"])
+ products = ", ".join(selection.products) or "(none)"
+ return f"""# {selection.project.name}
+
+由 Tencent Cloud MCP Initializr 生成的只读运维 MCP。
+
+- 产品: {products}
+- 环境别名: `{selection.project.target}`
+
+资源 ID 写在 `config.yaml`,工具入参只有别名 enum,避免模型猜 UUID。
+
+## 已注册工具
+
+{tools or "(未绑定资源,没有可注册工具)"}
+
+## 运行
+
+`run.sh` 会检查 Python 3.11+,首次启动自动创建 `.venv` 并安装依赖。
+默认 stdio(Cursor / Claude Code);HTTP 用启动参数切换。
+
+```bash
+export TENCENT_SECRET_ID=AKID...
+export TENCENT_SECRET_KEY=...
+bash ./run.sh
+bash ./run.sh --transport http
+```
+
+### Cursor 本机接入
+
+配置见 `mcp.json`。把 `/absolute/path/to/{_slug(selection.project.name)}` 改成解压后的绝对路径,
+并在 Cursor 配置的 `env` 中填写密钥。第一次连接会自动完成环境安装。
+
+### Docker Server
+
+HTTP 模式强制 Bearer 鉴权。没有 `TCMCP_AUTH_TOKEN` 时进程不会启动。
+密钥和鉴权 token 都用环境变量注入,不要写进镜像。
+
+```bash
+export TCMCP_AUTH_TOKEN=$(python -c 'import secrets; print(secrets.token_urlsafe(32))')
+docker build -t {_slug(selection.project.name)} .
+docker run --rm -p 127.0.0.1:8099:8099 \\
+ -e TENCENT_SECRET_ID \\
+ -e TENCENT_SECRET_KEY \\
+ -e TCMCP_AUTH_TOKEN \\
+ {_slug(selection.project.name)}
+curl -fsS http://127.0.0.1:8099/healthz
+```
+
+Cursor 连这个 HTTP Server:
+
+```json
+{{
+ "mcpServers": {{
+ "{_slug(selection.project.name)}-http": {{
+ "url": "http://127.0.0.1:8099/mcp",
+ "headers": {{
+ "Authorization": "Bearer 你的TCMCP_AUTH_TOKEN"
+ }}
+ }}
+ }}
+}}
+```
+
+`/healthz` 不鉴权。`/mcp` 必须带 `Authorization: Bearer <token>`。
+生产环境仍应放在 TLS 网关后面;token 当作共享密钥轮换。
+
+密钥用 `${{TENCENT_SECRET_ID}}` 占位,不要把真实密钥写进仓库。
+
+CAM 草稿见 `deploy/cam-policy.json`,把 `$uin` 换成主账号 UIN。
+
+一期只有只读能力,没有 `sql_query` / `redis-cli`,COS 也不会下载对象内容。
+"""
diff --git a/tools/tcmcp/app/install.py b/tools/tcmcp/app/install.py
new file mode 100644
index 00000000..7f87eae5
--- /dev/null
+++ b/tools/tcmcp/app/install.py
@@ -0,0 +1,117 @@
+"""Short-lived, per-selection installation packages and curl entrypoints."""
+
+from __future__ import annotations
+
+import base64
+import fcntl
+import json
+import os
+from pathlib import Path
+import re
+import secrets
+import shlex
+import tempfile
+import time
+
+from fastapi import APIRouter, HTTPException, Request
+from fastapi.responses import Response
+
+from app.generate import build_zip
+from app.models import Selection
+
+router = APIRouter()
+CLIENTS = ("cursor", "codebuddy", "codex", "workbuddy")
+TTL = 24 * 60 * 60
+MAX_PACKAGES = 200
+TOKEN = re.compile(r"^[a-f0-9]{32}$")
+NO_CACHE = {"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"}
+
+
+def store_dir() -> Path:
+ path = Path(os.environ.get("TCMCP_INSTALL_STORE", str(Path(tempfile.gettempdir()) / "tcmcp-installations")))
+ path.mkdir(parents=True, exist_ok=True, mode=0o700)
+ return path
+
+
+def package_path(token: str) -> Path:
+ if not TOKEN.fullmatch(token):
+ raise HTTPException(404, "安装 ID 无效,请在页面重新生成")
+ path = store_dir() / f"{token}.zip"
+ try:
+ expired = time.time() - path.stat().st_mtime >= TTL
+ except FileNotFoundError:
+ raise HTTPException(404, "安装链接不存在或已过期,请在页面重新生成")
+ if expired:
+ path.unlink(missing_ok=True)
+ raise HTTPException(410, "安装链接已过期,请在页面重新生成")
+ return path
+
+
[email protected]("/api/installations")
+def create_installation(selection: Selection):
+ if not selection.products:
+ raise HTTPException(400, "至少选择一个产品")
+ data = build_zip(selection)
+ if len(data) > 10 * 1024 * 1024:
+ raise HTTPException(413, "项目过大,请减少资源数量")
+ directory = store_dir()
+ with (directory / ".lock").open("a") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ now = time.time()
+ for path in directory.glob("*.zip"):
+ if now - path.stat().st_mtime >= TTL:
+ path.unlink(missing_ok=True)
+ if len(list(directory.glob("*.zip"))) >= MAX_PACKAGES:
+ raise HTTPException(503, "安装包存储已满,请稍后重试或联系管理员")
+ token = secrets.token_hex(16)
+ path = directory / f"{token}.zip"
+ with path.open("xb") as output:
+ os.chmod(path, 0o600)
+ output.write(data)
+ return Response(
+ json.dumps({"id": token, "expiresAt": int(now + TTL),
+ "paths": {client: f"/{client}?project={token}" for client in CLIENTS}}),
+ media_type="application/json", headers=NO_CACHE,
+ )
+
+
[email protected]("/api/installations/{token}/starter.zip")
+def installation_zip(token: str):
+ return Response(package_path(token).read_bytes(), media_type="application/zip", headers=NO_CACHE)
+
+
+def render_script(client: str, base_url: str, token: str = "") -> str:
+ settings = base64.b64encode(json.dumps({"client": client, "base_url": base_url, "project": token}).encode()).decode()
+ source = Path(__file__).with_name("installer.py").read_text()
+ # The function is invoked only after its closing brace arrives: a truncated curl
+ # response cannot start installing part of a shell script.
+ return f'''#!/usr/bin/env bash
+set -euo pipefail
+tcmcp_install() {{
+ umask 077
+ local tcmcp_python="${{TCMCP_PYTHON:-python3}}"
+ command -v "$tcmcp_python" >/dev/null 2>&1 || {{ echo '需要 Python 3.11+,可通过 TCMCP_PYTHON 指定路径。' >&2; return 1; }}
+ "$tcmcp_python" -c 'import sys; raise SystemExit(sys.version_info < (3, 11))' || {{ echo '需要 Python 3.11+。' >&2; return 1; }}
+ tcmcp_tmp="$(mktemp -d)"
+ trap 'if [[ -n "${{tcmcp_tmp:-}}" ]]; then rm -rf -- "$tcmcp_tmp"; fi' EXIT
+ cat > "$tcmcp_tmp/installer.py" <<'TCMCP_INSTALLER_PY'
+{source}
+TCMCP_INSTALLER_PY
+ "$tcmcp_python" "$tcmcp_tmp/installer.py" {shlex.quote(settings)}
+ rm -rf -- "$tcmcp_tmp"
+ trap - EXIT
+}}
+tcmcp_install
+'''
+
+
[email protected]("/codebuddy")
[email protected]("/workbuddy")
+def installer(request: Request, project: str = ""):
+ if project:
+ package_path(project)
+ client = request.url.path.rsplit("/", 1)[-1]
+ base_url = os.environ.get("TCMCP_PUBLIC_URL", str(request.base_url)).rstrip("/")
+ return Response(render_script(client, base_url, project), media_type="text/x-shellscript", headers=NO_CACHE)
diff --git a/tools/tcmcp/app/installer.py b/tools/tcmcp/app/installer.py
new file mode 100644
index 00000000..065c4b5f
--- /dev/null
+++ b/tools/tcmcp/app/installer.py
@@ -0,0 +1,274 @@
+"""Standalone installer shipped to the user's machine; bootstrap uses stdlib only."""
+
+from __future__ import annotations
+
+import base64
+import fcntl
+import hashlib
+import io
+import json
+import os
+from pathlib import Path, PurePosixPath
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import urllib.error
+import urllib.request
+import uuid
+import zipfile
+
+
+def prompt(label: str, variable: str) -> str:
+ value = os.environ.get(variable, "").strip()
+ if value:
+ return value
+ try:
+ with open("/dev/tty", "w") as tty:
+ tty.write(label)
+ tty.flush()
+ with open("/dev/tty", "r") as input_tty:
+ value = input_tty.readline().strip()
+ except OSError:
+ raise ValueError(f"没有交互终端,请先 export {variable} 再运行安装命令") from None
+ if not value:
+ raise ValueError(f"{variable} 不能为空")
+ return value
+
+
+def extract_package(data: bytes, destination: Path) -> Path:
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ members = archive.infolist()
+ roots = set()
+ total = 0
+ for member in members:
+ path = PurePosixPath(member.filename)
+ if (path.is_absolute() or ".." in path.parts or "\\" in member.filename
+ or not path.parts or (member.external_attr >> 16) & 0o170000 == 0o120000):
+ raise ValueError("安装包含不安全的路径")
+ roots.add(path.parts[0])
+ total += member.file_size
+ if len(roots) != 1 or total > 100 * 1024 * 1024:
+ raise ValueError("安装包目录或大小无效")
+ root = destination / roots.pop()
+ archive.extractall(destination)
+ for name in ("pyproject.toml", "config.yaml", "run.sh"):
+ if not (root / name).is_file():
+ raise ValueError(f"安装包缺少 {name}")
+ return root
+
+
+def config_path(client: str) -> Path:
+ override = os.environ.get("TCMCP_CLIENT_CONFIG")
+ if override:
+ return Path(override).expanduser().resolve()
+ if client == "codex":
+ return Path(os.environ.get("CODEX_HOME", str(Path.home() / ".codex"))).expanduser() / "config.toml"
+ if client not in ("cursor", "codebuddy", "workbuddy"):
+ raise ValueError("不支持的客户端")
+ return Path.home() / f".{client}" / "mcp.json"
+
+
+def merge_config(client: str, previous: str, name: str, entry: dict) -> str:
+ if client == "codex":
+ import tomlkit
+
+ document = tomlkit.parse(previous)
+ servers = document.setdefault("mcp_servers", tomlkit.table())
+ if not isinstance(servers, dict):
+ raise ValueError("mcp_servers 必须是一个表")
+ servers[name] = entry
+ return tomlkit.dumps(document)
+ import json5
+
+ document = json5.loads(previous) if previous.strip() else {}
+ if not isinstance(document, dict) or not isinstance(document.get("mcpServers", {}), dict):
+ raise ValueError("MCP 配置及 mcpServers 必须是 JSON 对象")
+ document.setdefault("mcpServers", {})[name] = {"type": "stdio", **entry}
+ return json.dumps(document, indent=2, ensure_ascii=False) + "\n"
+
+
+def empty_config(client: str) -> bytes:
+ return b"" if client == "codex" else b'{\n "mcpServers": {}\n}\n'
+
+
+def write_rollback_artifacts(
+ root: Path,
+ client: str,
+ path: Path,
+ backup: Path,
+ before_existed: bool,
+ updated: bytes,
+) -> Path:
+ helper = root / ".tcmcp-installer.py"
+ helper.write_text(Path(__file__).read_text(), encoding="utf-8")
+ os.chmod(helper, 0o600)
+ metadata = root / ".tcmcp-rollback.json"
+ metadata.write_text(
+ json.dumps(
+ {
+ "client": client,
+ "config": str(path),
+ "backup": str(backup),
+ "beforeExisted": before_existed,
+ "installedSha256": hashlib.sha256(updated).hexdigest(),
+ },
+ indent=2,
+ ensure_ascii=False,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ os.chmod(metadata, 0o600)
+ script = root / "rollback.sh"
+ script.write_text(
+ """#!/usr/bin/env bash
+set -euo pipefail
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+exec "$ROOT/.venv/bin/python" "$ROOT/.tcmcp-installer.py" --rollback "$ROOT/.tcmcp-rollback.json"
+""",
+ encoding="utf-8",
+ )
+ os.chmod(script, 0o700)
+ return script
+
+
+def atomic_write(path: Path, data: bytes) -> None:
+ descriptor, temporary = tempfile.mkstemp(prefix=".tcmcp-rollback-", dir=path.parent)
+ try:
+ with os.fdopen(descriptor, "wb") as output:
+ output.write(data)
+ output.flush()
+ os.fsync(output.fileno())
+ os.replace(temporary, path)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+
+
+def rollback(metadata_path: Path) -> None:
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ path = Path(metadata["config"])
+ backup = Path(metadata["backup"])
+ with path.with_name(path.name + ".tcmcp.lock").open("a") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ if not path.is_file():
+ raise ValueError(f"客户端配置不存在:{path}")
+ current = path.read_bytes()
+ if hashlib.sha256(current).hexdigest() != metadata["installedSha256"]:
+ raise ValueError(f"客户端配置在安装后已发生变化,未自动回滚:{path}")
+ recovery = path.with_name(f"{path.name}.before-rollback-{uuid.uuid4().hex}")
+ if metadata["beforeExisted"]:
+ if not backup.is_file():
+ raise ValueError(f"找不到安装前备份:{backup}")
+ with recovery.open("xb") as output:
+ os.chmod(recovery, 0o600)
+ output.write(current)
+ atomic_write(path, backup.read_bytes())
+ os.chmod(path, 0o600)
+ print(f"已恢复安装前配置:{path}")
+ else:
+ os.replace(path, recovery)
+ print(f"安装前没有客户端配置,已移走安装生成的配置:{recovery}")
+ recovery = None
+ if recovery:
+ print(f"回滚前配置副本:{recovery}")
+
+
+def configure(client: str, root: Path) -> Path:
+ if not root.is_dir():
+ raise ValueError(f"安装目录不存在:{root}")
+ path = config_path(client).resolve()
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ entry = {
+ "command": str(root / ".venv" / "bin" / "python"),
+ "args": ["-m", "tcmcp_server", "--config", str(root / "config.yaml"), "--transport", "stdio"],
+ "env": {key: os.environ[key] for key in ("TENCENT_SECRET_ID", "TENCENT_SECRET_KEY")},
+ }
+ # Lock cooperating installers and detect edits by the client before replacing.
+ with path.with_name(path.name + ".tcmcp.lock").open("a") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ previous = path.read_bytes() if path.exists() else None
+ try:
+ updated = merge_config(client, (previous or b"").decode("utf-8"), f"tcmcp-{root.name}", entry)
+ except Exception:
+ raise ValueError(f"无法解析已有配置 {path},原文件未修改,请修复后重试") from None
+ backup = path.with_name(f"{path.name}.bak-{uuid.uuid4().hex}")
+ with backup.open("xb") as output:
+ os.chmod(backup, 0o600)
+ output.write(previous if previous is not None else empty_config(client))
+ descriptor, temporary = tempfile.mkstemp(prefix=".tcmcp-", dir=path.parent)
+ try:
+ with os.fdopen(descriptor, "w", encoding="utf-8") as output:
+ output.write(updated)
+ output.flush()
+ os.fsync(output.fileno())
+ current = path.read_bytes() if path.exists() else None
+ if current != previous:
+ raise ValueError("客户端配置在安装过程中发生变化,请重新运行安装命令")
+ rollback_script = write_rollback_artifacts(
+ root, client, path, backup, previous is not None, updated.encode("utf-8")
+ )
+ os.replace(temporary, path)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
+ print(f"安装前配置快照:{backup}")
+ print(f"已配置 {client}:{path}")
+ print(f"回滚命令:bash {shlex.quote(str(rollback_script))}")
+ return path
+
+
+def install(settings: dict) -> None:
+ token = settings["project"] or prompt("页面生成的安装 ID:", "TCMCP_INSTALL_ID")
+ if not re.fullmatch(r"[a-f0-9]{32}", token):
+ raise ValueError("安装 ID 无效,请复制页面生成的命令")
+ url = f"{settings['base_url']}/api/installations/{token}/starter.zip"
+ print("正在下载所选 MCP 项目…", flush=True)
+ try:
+ with urllib.request.urlopen(url, timeout=60) as response:
+ data = response.read(10 * 1024 * 1024 + 1)
+ except urllib.error.HTTPError as exc:
+ raise ValueError(f"安装包下载失败(HTTP {exc.code}),请在页面重新生成命令") from None
+ if len(data) > 10 * 1024 * 1024:
+ raise ValueError("安装包过大")
+ credentials = {
+ "TENCENT_SECRET_ID": prompt("腾讯云 SecretId:", "TENCENT_SECRET_ID"),
+ "TENCENT_SECRET_KEY": prompt("腾讯云 SecretKey:", "TENCENT_SECRET_KEY"),
+ }
+ base = Path(os.environ.get("TCMCP_INSTALL_DIR", str(Path.home() / ".local" / "share" / "tcmcp"))).expanduser().resolve()
+ base.mkdir(parents=True, exist_ok=True, mode=0o700)
+ release = Path(tempfile.mkdtemp(prefix="install-", dir=base))
+ configured = False
+ try:
+ root = extract_package(data, release)
+ python = root / ".venv" / "bin" / "python"
+ print(f"正在安装依赖:{root}", flush=True)
+ subprocess.run([sys.executable, "-m", "venv", str(root / ".venv")], check=True)
+ subprocess.run([str(python), "-m", "pip", "install", str(root), "tomlkit>=0.13,<1", "json5>=0.10,<1"], check=True)
+ # Preflight imports/config without making cloud calls or leaving a server running.
+ subprocess.run([str(python), "-c", "from tcmcp_server.server import build_mcp; import sys; build_mcp(sys.argv[1])", str(root / "config.yaml")], check=True, env={**os.environ, **credentials})
+ subprocess.run([str(python), str(Path(__file__).resolve()), "--configure", settings["client"], str(root)], check=True, env={**os.environ, **credentials})
+ configured = True
+ finally:
+ if not configured:
+ shutil.rmtree(release)
+ print(f"安装完成。请在 {settings['client']} 刷新 MCP 或重启客户端;如提示信任,请在客户端确认。")
+
+
+def main() -> None:
+ os.umask(0o077)
+ if sys.argv[1] == "--configure":
+ configure(sys.argv[2], Path(sys.argv[3]))
+ elif sys.argv[1] == "--rollback":
+ rollback(Path(sys.argv[2]))
+ else:
+ install(json.loads(base64.b64decode(sys.argv[1])))
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except (ValueError, OSError, subprocess.CalledProcessError, zipfile.BadZipFile) as exc:
+ print(f"tcmcp 安装失败:{exc}", file=sys.stderr)
+ sys.exit(1)
diff --git a/tools/tcmcp/app/main.py b/tools/tcmcp/app/main.py
new file mode 100644
index 00000000..933fc25b
--- /dev/null
+++ b/tools/tcmcp/app/main.py
@@ -0,0 +1,96 @@
+"""Initializr HTTP API + static UI."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+from fastapi import FastAPI, HTTPException
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import Response
+from fastapi.staticfiles import StaticFiles
+
+from app.catalog import metadata
+from app.cloud import list_resources
+from app.generate import _slug, build_zip
+from app.install import router as install_router
+from app.models import CloudCreds, Selection
+from app.preview import materialize
+
+WEB_DIST = Path(__file__).resolve().parent.parent / "web" / "dist"
+
+# Same-origin 8088 does not need CORS. Vite :5173 is the only default cross-origin.
+_DEFAULT_CORS = (
+ "http://127.0.0.1:5173",
+ "http://localhost:5173",
+ "http://127.0.0.1:8088",
+ "http://localhost:8088",
+)
+
+
+def _cors_origins() -> list[str]:
+ raw = os.environ.get("TCMCP_CORS_ORIGINS", "").strip()
+ if raw:
+ return [item.strip() for item in raw.split(",") if item.strip()]
+ return list(_DEFAULT_CORS)
+
+
+app = FastAPI(title="Tencent Cloud MCP Initializr", version="0.1.0")
+app.include_router(install_router)
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=_cors_origins(),
+ allow_methods=["GET", "POST", "OPTIONS"],
+ allow_headers=["Content-Type"],
+)
+
+
[email protected]("/api/metadata")
+def api_metadata():
+ return metadata()
+
+
[email protected]("/api/resources")
+def api_resources(creds: CloudCreds):
+ if not creds.secret_id or not creds.secret_key:
+ raise HTTPException(400, "secretId / secretKey 必填")
+ return list_resources(creds)
+
+
[email protected]("/api/preview-schema")
+def api_preview(selection: Selection):
+ return materialize(selection)
+
+
[email protected]("/api/starter.zip")
+def api_starter(selection: Selection):
+ if not selection.products:
+ raise HTTPException(400, "至少选择一个产品")
+ data = build_zip(selection)
+ filename = f"{_slug(selection.project.name)}.zip"
+ return Response(
+ content=data,
+ media_type="application/zip",
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
+ )
+
+
[email protected]("/api/healthz")
+def healthz():
+ return {"ok": True}
+
+
+if WEB_DIST.is_dir():
+ app.mount("/", StaticFiles(directory=WEB_DIST, html=True), name="web")
+
+
+def main() -> None:
+ import uvicorn
+
+ host = os.environ.get("TCMCP_HOST", "127.0.0.1")
+ port = int(os.environ.get("TCMCP_PORT", "8088"))
+ uvicorn.run("app.main:app", host=host, port=port, reload=False)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/tcmcp/app/mcp_runtime/__init__.py b/tools/tcmcp/app/mcp_runtime/__init__.py
new file mode 100644
index 00000000..95cc450f
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/__init__.py
@@ -0,0 +1 @@
+"""Generated Tencent Cloud ops MCP server."""
diff --git a/tools/tcmcp/app/mcp_runtime/__main__.py b/tools/tcmcp/app/mcp_runtime/__main__.py
new file mode 100644
index 00000000..d723d32c
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/__main__.py
@@ -0,0 +1,4 @@
+from tcmcp_server.server import main
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/tcmcp/app/mcp_runtime/config.py b/tools/tcmcp/app/mcp_runtime/config.py
new file mode 100644
index 00000000..92836cb8
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/config.py
@@ -0,0 +1,113 @@
+"""Load config.yaml and expose it as a Selection for preview.materialize."""
+
+from __future__ import annotations
+
+import os
+import re
+from pathlib import Path
+
+import yaml
+
+from tcmcp_server.models import (
+ BoundResources,
+ CLSResource,
+ CLSTopic,
+ ProjectSpec,
+ ResourceItem,
+ Selection,
+ TDSQLCResource,
+)
+
+_ENV = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
+
+
+def expand_env(text: str) -> str:
+ def repl(match: re.Match[str]) -> str:
+ return os.environ.get(match.group(1), "")
+
+ return _ENV.sub(repl, text)
+
+
+def load(path: str | Path) -> tuple[dict, Selection]:
+ raw = Path(path).read_text()
+ data = yaml.safe_load(expand_env(raw)) or {}
+ return data, selection_from_config(data)
+
+
+def selection_from_config(data: dict) -> Selection:
+ project_raw = data.get("project") or {}
+ tencent = data.get("tencent") or {}
+ target_name = project_raw.get("target") or "prod"
+ targets = data.get("targets") or {}
+ t = targets.get(target_name) or {}
+
+ redis = [
+ ResourceItem(id=x["id"], alias=x["alias"], name=x.get("name", ""), region=x.get("region", ""))
+ for x in t.get("redis") or []
+ ]
+ cdb = [
+ ResourceItem(id=x["id"], alias=x["alias"], name=x.get("name", ""), region=x.get("region", ""))
+ for x in t.get("cdb") or []
+ ]
+ tdsqlc = [
+ TDSQLCResource(
+ clusterId=x["clusterId"],
+ instanceId=x["instanceId"],
+ alias=x["alias"],
+ name=x.get("name", ""),
+ region=x.get("region", ""),
+ )
+ for x in t.get("tdsqlc") or []
+ ]
+ tke = [
+ ResourceItem(id=x["id"], alias=x["alias"], name=x.get("name", ""), region=x.get("region", ""))
+ for x in t.get("tke") or []
+ ]
+ cos = [
+ ResourceItem(id=x["id"], alias=x["alias"], name=x.get("name", ""), region=x.get("region", ""))
+ for x in t.get("cos") or []
+ ]
+ cls: list[CLSResource] = []
+ for logset in t.get("cls") or []:
+ cls.append(
+ CLSResource(
+ logsetId=logset["logsetId"],
+ logsetName=logset.get("logsetName", ""),
+ region=logset.get("region", ""),
+ topics=[
+ CLSTopic(id=tp["id"], alias=tp["alias"], name=tp.get("name", ""))
+ for tp in logset.get("topics") or []
+ ],
+ )
+ )
+
+ project = ProjectSpec(
+ name=project_raw.get("name") or "demo",
+ description=project_raw.get("description") or "",
+ target=target_name,
+ transport=(data.get("server") or {}).get("transport") or "stdio",
+ region=tencent.get("region") or "ap-guangzhou",
+ )
+ return Selection(
+ project=project,
+ products=list(data.get("products") or []),
+ disabled_tools=list(data.get("disabledTools") or []),
+ resources=BoundResources(redis=redis, cdb=cdb, tdsqlc=tdsqlc, tke=tke, cls=cls, cos=cos),
+ )
+
+
+def secret_pair(data: dict) -> tuple[str, str, str]:
+ tencent = data.get("tencent") or {}
+ return (
+ tencent.get("secretId") or "",
+ tencent.get("secretKey") or "",
+ tencent.get("region") or "ap-guangzhou",
+ )
+
+
+def resolve_alias(items: list, alias: str, id_attr: str = "id"):
+ for item in items:
+ if getattr(item, "alias", None) == alias:
+ return item
+ names = [getattr(i, "alias", "") for i in items]
+ raise ValueError(f"未知别名 {alias!r},可用: {names}")
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/__init__.py b/tools/tcmcp/app/mcp_runtime/handlers/__init__.py
new file mode 100644
index 00000000..ef46e913
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/__init__.py
@@ -0,0 +1 @@
+"""Tool handlers registered by product."""
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/cdb.py b/tools/tcmcp/app/mcp_runtime/handlers/cdb.py
new file mode 100644
index 00000000..43299c03
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/cdb.py
@@ -0,0 +1,111 @@
+from __future__ import annotations
+
+from tcmcp_server.config import resolve_alias, secret_pair
+from tcmcp_server.handlers.dispatch import register as _register
+from tcmcp_server.sdk import cloud_client, fail, ok
+
+
+def _inst(selection, alias: str):
+ return resolve_alias(selection.resources.cdb, alias)
+
+
+def handle_detail(args, data, selection):
+ item = _inst(selection, args.get("instance", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cdb.v20170320 import models
+
+ client = cloud_client("cdb", sid, skey, item.region or region)
+ req = models.DescribeDBInstancesRequest()
+ req.InstanceIds = [item.id]
+ resp = client.DescribeDBInstances(req)
+ items = resp.Items or []
+ if not items:
+ return fail(f"找不到实例 {item.id}")
+ inst = items[0]
+ return ok(
+ {
+ "instanceId": inst.InstanceId,
+ "name": inst.InstanceName,
+ "status": inst.Status,
+ "engine": inst.EngineVersion,
+ "vip": inst.Vip,
+ "vport": inst.Vport,
+ "memory": inst.Memory,
+ "volume": inst.Volume,
+ }
+ )
+
+
+def handle_databases(args, data, selection):
+ item = _inst(selection, args.get("instance", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cdb.v20170320 import models
+
+ client = cloud_client("cdb", sid, skey, item.region or region)
+ req = models.DescribeDatabasesRequest()
+ req.InstanceId = item.id
+ resp = client.DescribeDatabases(req)
+ items = [d.DatabaseName if hasattr(d, "DatabaseName") else str(d) for d in (resp.Items or [])]
+ return ok({"items": items, "count": len(items)})
+
+
+def handle_slow(args, data, selection):
+ item = _inst(selection, args.get("instance", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cdb.v20170320 import models
+
+ client = cloud_client("cdb", sid, skey, item.region or region)
+ req = models.DescribeSlowLogsRequest()
+ req.InstanceId = item.id
+ if args.get("startTime"):
+ req.StartTime = args["startTime"]
+ if args.get("endTime"):
+ req.EndTime = args["endTime"]
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ resp = client.DescribeSlowLogs(req)
+ rows = []
+ for log in resp.Items or []:
+ rows.append(
+ {
+ "sql": getattr(log, "SqlText", None),
+ "queryTime": getattr(log, "QueryTime", None),
+ "database": getattr(log, "Database", None),
+ "user": getattr(log, "UserHost", None),
+ "timestamp": getattr(log, "Timestamp", None),
+ }
+ )
+ return ok({"items": rows, "count": len(rows), "total": resp.TotalCount})
+
+
+def handle_errors(args, data, selection):
+ item = _inst(selection, args.get("instance", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cdb.v20170320 import models
+
+ client = cloud_client("cdb", sid, skey, item.region or region)
+ req = models.DescribeErrorLogDataRequest()
+ req.InstanceId = item.id
+ if args.get("startTime"):
+ req.StartTime = args["startTime"]
+ if args.get("endTime"):
+ req.EndTime = args["endTime"]
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ resp = client.DescribeErrorLogData(req)
+ rows = []
+ for log in resp.Items or []:
+ rows.append(
+ {
+ "timestamp": getattr(log, "Timestamp", None),
+ "content": getattr(log, "Content", None),
+ }
+ )
+ return ok({"items": rows, "count": len(rows), "total": getattr(resp, "TotalCount", len(rows))})
+
+
+def register() -> None:
+ _register("cdb_instance_detail", handle_detail)
+ _register("cdb_list_databases", handle_databases)
+ _register("cdb_slow_queries", handle_slow)
+ _register("cdb_error_logs", handle_errors)
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/cls.py b/tools/tcmcp/app/mcp_runtime/handlers/cls.py
new file mode 100644
index 00000000..d411e7ea
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/cls.py
@@ -0,0 +1,143 @@
+from __future__ import annotations
+
+from tcmcp_server.config import secret_pair
+from tcmcp_server.handlers.dispatch import register as _register
+from tcmcp_server.sdk import cloud_client, fail, ok
+
+
+def _topics(selection) -> list:
+ out = []
+ for logset in selection.resources.cls:
+ for topic in logset.topics:
+ out.append((topic, logset))
+ return out
+
+
+def _topic(selection, alias: str):
+ for topic, logset in _topics(selection):
+ if topic.alias == alias:
+ return topic, logset
+ names = [t.alias for t, _ in _topics(selection)]
+ raise ValueError(f"未知 topic 别名 {alias!r},可用: {names}")
+
+
+def handle_list_topics(args, data, selection):
+ items = [
+ {"alias": t.alias, "id": t.id, "name": t.name, "logsetId": ls.logset_id}
+ for t, ls in _topics(selection)
+ ]
+ return ok({"items": items, "count": len(items)})
+
+
+def handle_search(args, data, selection):
+ topic, logset = _topic(selection, args.get("topic", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cls.v20201016 import models
+
+ client = cloud_client("cls", sid, skey, logset.region or region)
+ req = models.SearchLogRequest()
+ req.TopicId = topic.id
+ req.Query = args.get("query") or "*"
+ req.From = _ms(args.get("startTime"), hours=1)
+ req.To = _ms(args.get("endTime"), hours=0)
+ req.Limit = int(args.get("limit") or 100)
+ if req.Limit > 1000:
+ return fail("limit 上限 1000", "缩小 limit 后重试")
+ req.Sort = args.get("sort") or "desc"
+ resp = client.SearchLog(req)
+ results = []
+ for item in resp.Results or []:
+ results.append(
+ {
+ "time": getattr(item, "Time", None),
+ "source": getattr(item, "Source", None),
+ "logJson": getattr(item, "LogJson", None),
+ }
+ )
+ return ok({"items": results, "count": len(results), "topic": topic.alias})
+
+
+def handle_index(args, data, selection):
+ topic, logset = _topic(selection, args.get("topic", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cls.v20201016 import models
+
+ client = cloud_client("cls", sid, skey, logset.region or region)
+ req = models.DescribeIndexRequest()
+ req.TopicId = topic.id
+ resp = client.DescribeIndex(req)
+ rule = resp.Rule
+ fields = []
+ if rule and rule.KeyValue and rule.KeyValue.KeyValues:
+ for kv in rule.KeyValue.KeyValues:
+ fields.append({"key": kv.Key, "type": getattr(kv.Value, "Type", None)})
+ return ok({"topic": topic.alias, "fields": fields, "count": len(fields)})
+
+
+def handle_histogram(args, data, selection):
+ topic, logset = _topic(selection, args.get("topic", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cls.v20201016 import models
+
+ client = cloud_client("cls", sid, skey, logset.region or region)
+ req = models.DescribeLogHistogramRequest()
+ req.TopicId = topic.id
+ req.Query = args.get("query") or "*"
+ req.From = _ms(args.get("startTime"), hours=1)
+ req.To = _ms(args.get("endTime"), hours=0)
+ if args.get("interval"):
+ req.Interval = args["interval"]
+ resp = client.DescribeLogHistogram(req)
+ buckets = []
+ for b in resp.HistogramInfos or []:
+ buckets.append({"time": b.BTime, "count": b.Count})
+ return ok({"topic": topic.alias, "items": buckets, "count": len(buckets)})
+
+
+def _container_query(args, extra: str) -> str:
+ parts = [p for p in (extra, args.get("query")) if p]
+ if args.get("workload"):
+ parts.append(f'container:{args["workload"]}')
+ if args.get("pod"):
+ parts.append(f'pod:{args["pod"]}')
+ return " AND ".join(parts) if parts else "*"
+
+
+def handle_container(args, data, selection):
+ args = dict(args)
+ aliases = [t.alias for t, _ in _topics(selection)]
+ args["topic"] = "api" if "api" in aliases else aliases[0]
+ args["query"] = _container_query(args, "")
+ return handle_search(args, data, selection)
+
+
+def handle_events(args, data, selection):
+ args = dict(args)
+ args["topic"] = "events"
+ return handle_search(args, data, selection)
+
+
+def handle_audit(args, data, selection):
+ args = dict(args)
+ args["topic"] = "audit"
+ return handle_search(args, data, selection)
+
+
+def _ms(rfc: str | None, hours: int) -> int:
+ from datetime import datetime, timedelta, timezone
+
+ if rfc:
+ dt = datetime.fromisoformat(rfc.replace("Z", "+00:00"))
+ else:
+ dt = datetime.now(timezone.utc) - timedelta(hours=hours)
+ return int(dt.timestamp() * 1000)
+
+
+def register() -> None:
+ _register("cls_search_log", handle_search)
+ _register("cls_list_topics", handle_list_topics)
+ _register("cls_index_fields", handle_index)
+ _register("cls_histogram", handle_histogram)
+ _register("container_logs", handle_container)
+ _register("k8s_events", handle_events)
+ _register("k8s_audit", handle_audit)
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/cos.py b/tools/tcmcp/app/mcp_runtime/handlers/cos.py
new file mode 100644
index 00000000..85f79107
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/cos.py
@@ -0,0 +1,92 @@
+from __future__ import annotations
+
+from tcmcp_server.config import resolve_alias, secret_pair
+from tcmcp_server.handlers.dispatch import register as _register
+from tcmcp_server.sdk import cos_client, fail, ok
+
+
+def _bucket(selection, alias: str):
+ return resolve_alias(selection.resources.cos, alias)
+
+
+def _client(data: dict, bucket):
+ sid, skey, default_region = secret_pair(data)
+ return cos_client(sid, skey, bucket.region or default_region)
+
+
+def _list(value) -> list:
+ if not value:
+ return []
+ return value if isinstance(value, list) else [value]
+
+
+def handle_bucket_detail(args, data, selection):
+ bucket = _bucket(selection, args.get("bucket", ""))
+ response = _client(data, bucket).head_bucket(Bucket=bucket.id)
+ return ok(
+ {
+ "alias": bucket.alias,
+ "name": bucket.id,
+ "region": bucket.region,
+ "headers": dict(response or {}),
+ }
+ )
+
+
+def handle_list_objects(args, data, selection):
+ bucket = _bucket(selection, args.get("bucket", ""))
+ limit = int(args.get("limit") or 100)
+ if limit < 1 or limit > 1000:
+ return fail("limit 必须在 1 到 1000 之间", "调整 limit 后重试")
+
+ request = {"Bucket": bucket.id, "MaxKeys": limit}
+ for arg, sdk_name in (("prefix", "Prefix"), ("delimiter", "Delimiter"), ("marker", "Marker")):
+ if args.get(arg):
+ request[sdk_name] = args[arg]
+ response = _client(data, bucket).list_objects(**request)
+
+ items = []
+ for item in _list(response.get("Contents")):
+ items.append(
+ {
+ "key": item.get("Key"),
+ "size": item.get("Size"),
+ "etag": item.get("ETag"),
+ "lastModified": item.get("LastModified"),
+ "storageClass": item.get("StorageClass"),
+ }
+ )
+ prefixes = [item.get("Prefix") for item in _list(response.get("CommonPrefixes")) if item.get("Prefix")]
+ return ok(
+ {
+ "bucket": bucket.alias,
+ "prefix": response.get("Prefix", args.get("prefix") or ""),
+ "items": items,
+ "commonPrefixes": prefixes,
+ "count": len(items),
+ "isTruncated": str(response.get("IsTruncated", "false")).lower() == "true",
+ "nextMarker": response.get("NextMarker") or "",
+ }
+ )
+
+
+def handle_object_metadata(args, data, selection):
+ bucket = _bucket(selection, args.get("bucket", ""))
+ key = args.get("key") or ""
+ request = {"Bucket": bucket.id, "Key": key}
+ if args.get("versionId"):
+ request["versionId"] = args["versionId"]
+ response = _client(data, bucket).head_object(**request)
+ return ok(
+ {
+ "bucket": bucket.alias,
+ "key": key,
+ "metadata": dict(response or {}),
+ }
+ )
+
+
+def register() -> None:
+ _register("cos_bucket_detail", handle_bucket_detail)
+ _register("cos_list_objects", handle_list_objects)
+ _register("cos_object_metadata", handle_object_metadata)
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/dbbrain.py b/tools/tcmcp/app/mcp_runtime/handlers/dbbrain.py
new file mode 100644
index 00000000..b7c53312
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/dbbrain.py
@@ -0,0 +1,252 @@
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from tcmcp_server.config import resolve_alias, secret_pair
+from tcmcp_server.handlers.dispatch import register as _register
+from tcmcp_server.sdk import cloud_client, fail, ok
+
+
+def _instance_id(selection, alias: str, kind: str) -> tuple[str, str]:
+ if kind == "cdb":
+ item = resolve_alias(selection.resources.cdb, alias)
+ return item.id, item.region
+ item = resolve_alias(selection.resources.tdsqlc, alias)
+ return item.instance_id, item.region
+
+
+def _fmt(rfc: str | None) -> str | None:
+ if not rfc:
+ return None
+ dt = datetime.fromisoformat(rfc.replace("Z", "+00:00"))
+ return dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+
+
+def _client(data, region: str):
+ sid, skey, fallback = secret_pair(data)
+ return cloud_client("dbbrain", sid, skey, region or fallback)
+
+
+def handle_health(args, data, selection, *, product: str, kind: str):
+ instance_id, region = _instance_id(selection, args.get("instance", ""), kind)
+ from tencentcloud.dbbrain.v20210527 import models
+
+ client = _client(data, region)
+ start, end = _fmt(args.get("startTime")), _fmt(args.get("endTime"))
+ if start and end:
+ req = models.DescribeHealthScoreTimeSeriesRequest()
+ req.InstanceId = instance_id
+ req.Product = product
+ req.StartTime = start
+ req.EndTime = end
+ resp = client.DescribeHealthScoreTimeSeries(req)
+ return ok({"series": [x.__dict__ for x in (resp.Data or [])]})
+ req = models.DescribeHealthScoreRequest()
+ req.InstanceId = instance_id
+ req.Product = product
+ resp = client.DescribeHealthScore(req)
+ d = resp.Data
+ return ok({"score": getattr(d, "HealthScore", None), "level": getattr(d, "HealthLevel", None)})
+
+
+def handle_events(args, data, selection, *, product: str, kind: str):
+ instance_id, region = _instance_id(selection, args.get("instance", ""), kind)
+ from tencentcloud.dbbrain.v20210527 import models
+
+ client = _client(data, region)
+ req = models.DescribeDBDiagEventsRequest()
+ req.InstanceIds = [instance_id]
+ req.Product = product
+ if args.get("startTime"):
+ req.StartTime = _fmt(args["startTime"])
+ if args.get("endTime"):
+ req.EndTime = _fmt(args["endTime"])
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ resp = client.DescribeDBDiagEvents(req)
+ items = []
+ for ev in resp.Items or []:
+ items.append(
+ {
+ "eventId": ev.EventId,
+ "diagType": ev.DiagType,
+ "severity": ev.Severity,
+ "startTime": ev.StartTime,
+ "outline": ev.Outline,
+ }
+ )
+ return ok({"items": items, "count": len(items), "total": resp.TotalCount})
+
+
+def handle_event_detail(args, data, selection, *, product: str, kind: str):
+ instance_id, region = _instance_id(selection, args.get("instance", ""), kind)
+ from tencentcloud.dbbrain.v20210527 import models
+
+ client = _client(data, region)
+ req = models.DescribeDBDiagEventRequest()
+ req.InstanceId = instance_id
+ req.EventId = int(args["eventId"])
+ req.Product = product
+ resp = client.DescribeDBDiagEvent(req)
+ return ok(
+ {
+ "diagItem": resp.DiagItem,
+ "diagType": resp.DiagType,
+ "explanation": resp.Explanation,
+ "outline": resp.Outline,
+ "problem": resp.Problem,
+ "severity": resp.Severity,
+ "suggestions": resp.Suggestions,
+ }
+ )
+
+
+def handle_process(args, data, selection, *, product: str, kind: str):
+ instance_id, region = _instance_id(selection, args.get("instance", ""), kind)
+ from tencentcloud.dbbrain.v20210527 import models
+
+ client = _client(data, region)
+ req = models.DescribeMySqlProcessListRequest()
+ req.InstanceId = instance_id
+ req.Product = product
+ if args.get("db"):
+ req.DB = args["db"]
+ if args.get("user"):
+ req.User = args["user"]
+ if args.get("host"):
+ req.Host = args["host"]
+ if args.get("minSeconds"):
+ req.Time = int(args["minSeconds"])
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ resp = client.DescribeMySqlProcessList(req)
+ items = []
+ for p in resp.ProcessList or []:
+ items.append(
+ {
+ "id": p.ID,
+ "user": p.User,
+ "host": p.Host,
+ "db": p.DB,
+ "command": p.Command,
+ "time": p.Time,
+ "state": p.State,
+ "info": p.Info,
+ }
+ )
+ return ok({"items": items, "count": len(items)})
+
+
+def handle_top_sqls(args, data, selection, *, product: str, kind: str):
+ instance_id, region = _instance_id(selection, args.get("instance", ""), kind)
+ if not args.get("startTime") or not args.get("endTime"):
+ return fail("startTime 与 endTime 必填,间隔不得超过 7 天")
+ from tencentcloud.dbbrain.v20210527 import models
+
+ client = _client(data, region)
+ req = models.DescribeSlowLogTopSqlsRequest()
+ req.InstanceId = instance_id
+ req.Product = product
+ req.StartTime = _fmt(args["startTime"])
+ req.EndTime = _fmt(args["endTime"])
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ if args.get("sortBy"):
+ req.SortBy = args["sortBy"]
+ resp = client.DescribeSlowLogTopSqls(req)
+ items = []
+ for s in resp.Rows or []:
+ items.append(
+ {
+ "sqlTemplate": s.SqlTemplate,
+ "queryTime": s.QueryTime,
+ "execTimes": s.ExecTimes,
+ "schema": s.Schema,
+ }
+ )
+ return ok({"items": items, "count": len(items), "total": resp.TotalCount})
+
+
+def handle_advice(args, data, selection, *, product: str, kind: str):
+ instance_id, region = _instance_id(selection, args.get("instance", ""), kind)
+ from tencentcloud.dbbrain.v20210527 import models
+
+ client = _client(data, region)
+ req = models.DescribeUserSqlAdviceRequest()
+ req.InstanceId = instance_id
+ req.Product = product
+ req.SqlText = args["sql"]
+ if args.get("schema"):
+ req.Schema = args["schema"]
+ resp = client.DescribeUserSqlAdvice(req)
+ return ok({"advice": resp.Advices, "comments": resp.Comments, "tables": resp.Tables})
+
+
+def handle_space(args, data, selection, *, product: str, kind: str):
+ instance_id, region = _instance_id(selection, args.get("instance", ""), kind)
+ from tencentcloud.dbbrain.v20210527 import models
+
+ client = _client(data, region)
+ req = models.DescribeTopSpaceTablesRequest()
+ req.InstanceId = instance_id
+ req.Product = product
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ if args.get("sortBy"):
+ req.SortBy = args["sortBy"]
+ resp = client.DescribeTopSpaceTables(req)
+ items = []
+ for t in resp.TopSpaceTables or []:
+ items.append(
+ {
+ "tableName": t.TableName,
+ "tableSchema": t.TableSchema,
+ "dataLength": t.DataLength,
+ "indexLength": t.IndexLength,
+ "dataFree": t.DataFree,
+ "totalLength": t.TotalLength,
+ }
+ )
+ return ok({"items": items, "count": len(items)})
+
+
+def handle_series(args, data, selection, *, product: str, kind: str):
+ instance_id, region = _instance_id(selection, args.get("instance", ""), kind)
+ from tencentcloud.dbbrain.v20210527 import models
+
+ client = _client(data, region)
+ req = models.DescribeSlowLogTimeSeriesStatsRequest()
+ req.InstanceId = instance_id
+ req.Product = product
+ req.StartTime = _fmt(args["startTime"])
+ req.EndTime = _fmt(args["endTime"])
+ resp = client.DescribeSlowLogTimeSeriesStats(req)
+ return ok(
+ {
+ "period": resp.Period,
+ "timeSeries": [x.__dict__ for x in (resp.TimeSeries or [])],
+ }
+ )
+
+
+def _bind(name: str, fn, product: str, kind: str):
+ _register(name, lambda args, data, selection, fn=fn, product=product, kind=kind: fn(args, data, selection, product=product, kind=kind))
+
+
+def register(products: list[str]) -> None:
+ if "tdsqlc" in products:
+ _bind("dbbrain_health_score", handle_health, "cynosdb", "tdsqlc")
+ _bind("dbbrain_diag_events", handle_events, "cynosdb", "tdsqlc")
+ _bind("dbbrain_diag_event_detail", handle_event_detail, "cynosdb", "tdsqlc")
+ _bind("dbbrain_process_list", handle_process, "cynosdb", "tdsqlc")
+ _bind("dbbrain_slow_top_sqls", handle_top_sqls, "cynosdb", "tdsqlc")
+ _bind("dbbrain_sql_advice", handle_advice, "cynosdb", "tdsqlc")
+ _bind("dbbrain_top_space_tables", handle_space, "cynosdb", "tdsqlc")
+ _bind("dbbrain_slow_log_time_series", handle_series, "cynosdb", "tdsqlc")
+ if "cdb" in products:
+ _bind("cdb_dbbrain_health_score", handle_health, "mysql", "cdb")
+ _bind("cdb_dbbrain_diag_events", handle_events, "mysql", "cdb")
+ _bind("cdb_dbbrain_diag_event_detail", handle_event_detail, "mysql", "cdb")
+ _bind("cdb_dbbrain_process_list", handle_process, "mysql", "cdb")
+ _bind("cdb_dbbrain_slow_top_sqls", handle_top_sqls, "mysql", "cdb")
+ _bind("cdb_dbbrain_sql_advice", handle_advice, "mysql", "cdb")
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/dispatch.py b/tools/tcmcp/app/mcp_runtime/handlers/dispatch.py
new file mode 100644
index 00000000..99f2a943
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/dispatch.py
@@ -0,0 +1,52 @@
+from __future__ import annotations
+
+from typing import Any, Callable
+
+Handler = Callable[[dict, dict, Any], Any]
+
+REGISTRY: dict[str, Handler] = {}
+
+
+def register(name: str, fn: Handler) -> None:
+ REGISTRY[name] = fn
+
+
+def call(name: str, args: dict, data: dict, selection) -> Any:
+ fn = REGISTRY.get(name)
+ if fn is None:
+ raise ValueError(f"未注册的工具 {name}")
+ return fn(args, data, selection)
+
+
+def load_handlers(products: list[str]) -> None:
+ from tcmcp_server.handlers import ping
+
+ register("ping", ping.handle_ping)
+ if "redis" in products:
+ from tcmcp_server.handlers import redis as redis_h
+
+ redis_h.register()
+ if "cdb" in products:
+ from tcmcp_server.handlers import cdb as cdb_h
+
+ cdb_h.register()
+ if "tdsqlc" in products:
+ from tcmcp_server.handlers import tdsqlc as tdsqlc_h
+
+ tdsqlc_h.register()
+ if "tke" in products:
+ from tcmcp_server.handlers import tke as tke_h
+
+ tke_h.register()
+ if "cls" in products:
+ from tcmcp_server.handlers import cls as cls_h
+
+ cls_h.register()
+ if "cos" in products:
+ from tcmcp_server.handlers import cos as cos_h
+
+ cos_h.register()
+ if "cdb" in products or "tdsqlc" in products:
+ from tcmcp_server.handlers import dbbrain as dbbrain_h
+
+ dbbrain_h.register(products)
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/ping.py b/tools/tcmcp/app/mcp_runtime/handlers/ping.py
new file mode 100644
index 00000000..857529cd
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/ping.py
@@ -0,0 +1,22 @@
+from __future__ import annotations
+
+from tcmcp_server.preview import aliases_for, materialize
+
+
+def handle_ping(args: dict, data: dict, selection) -> dict:
+ preview = materialize(selection)
+ target = args.get("target") or selection.project.target
+ return {
+ "ok": True,
+ "service": selection.project.name,
+ "target": target,
+ "products": selection.products,
+ "tools": preview["registered"],
+ "resources": {
+ "redis": aliases_for(selection.resources, "redis"),
+ "cdb": aliases_for(selection.resources, "cdb"),
+ "tdsqlc": aliases_for(selection.resources, "tdsqlc"),
+ "tke": aliases_for(selection.resources, "tke"),
+ "topics": aliases_for(selection.resources, "topics"),
+ },
+ }
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/redis.py b/tools/tcmcp/app/mcp_runtime/handlers/redis.py
new file mode 100644
index 00000000..684f0679
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/redis.py
@@ -0,0 +1,87 @@
+from __future__ import annotations
+
+from tcmcp_server.config import resolve_alias, secret_pair
+from tcmcp_server.handlers.dispatch import register as _register
+from tcmcp_server.sdk import cloud_client, fail, ok
+
+
+def _inst(selection, alias: str):
+ return resolve_alias(selection.resources.redis, alias)
+
+
+def handle_detail(args, data, selection):
+ item = _inst(selection, args.get("instance", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.redis.v20180412 import models
+
+ client = cloud_client("redis", sid, skey, item.region or region)
+ req = models.DescribeInstancesRequest()
+ req.InstanceId = item.id
+ resp = client.DescribeInstances(req)
+ items = resp.InstanceSet or []
+ if not items:
+ return fail(f"找不到实例 {item.id}")
+ inst = items[0]
+ return ok(
+ {
+ "instanceId": inst.InstanceId,
+ "name": inst.InstanceName,
+ "status": inst.Status,
+ "size": inst.Size,
+ "type": inst.Type,
+ "vip": getattr(inst, "WanIp", None) or getattr(inst, "Vip", None),
+ }
+ )
+
+
+def handle_slow(args, data, selection):
+ item = _inst(selection, args.get("instance", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.redis.v20180412 import models
+
+ client = cloud_client("redis", sid, skey, item.region or region)
+ req = models.DescribeSlowLogRequest()
+ req.InstanceId = item.id
+ if args.get("startTime"):
+ req.BeginTime = args["startTime"]
+ if args.get("endTime"):
+ req.EndTime = args["endTime"]
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ resp = client.DescribeSlowLog(req)
+ rows = []
+ for log in resp.InstanceSlowlogDetail or []:
+ rows.append(
+ {
+ "command": getattr(log, "Command", None),
+ "duration": getattr(log, "Duration", None),
+ "executeTime": getattr(log, "ExecuteTime", None),
+ "client": getattr(log, "Client", None),
+ }
+ )
+ return ok({"items": rows, "count": len(rows), "total": resp.TotalCount})
+
+
+def handle_params(args, data, selection):
+ item = _inst(selection, args.get("instance", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.redis.v20180412 import models
+
+ client = cloud_client("redis", sid, skey, item.region or region)
+ req = models.DescribeInstanceParamsRequest()
+ req.InstanceId = item.id
+ resp = client.DescribeInstanceParams(req)
+ items = []
+ for group in resp.InstanceEnumParam or []:
+ items.append({"name": group.ParamName, "value": group.CurrentValue, "kind": "enum"})
+ for group in resp.InstanceIntegerParam or []:
+ items.append({"name": group.ParamName, "value": group.CurrentValue, "kind": "int"})
+ for group in resp.InstanceTextParam or []:
+ items.append({"name": group.ParamName, "value": group.CurrentValue, "kind": "text"})
+ return ok({"items": items, "count": len(items)})
+
+
+def register() -> None:
+ _register("redis_instance_detail", handle_detail)
+ _register("redis_slow_logs", handle_slow)
+ _register("redis_params", handle_params)
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/tdsqlc.py b/tools/tcmcp/app/mcp_runtime/handlers/tdsqlc.py
new file mode 100644
index 00000000..8c04caf2
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/tdsqlc.py
@@ -0,0 +1,140 @@
+from __future__ import annotations
+
+from tcmcp_server.config import resolve_alias, secret_pair
+from tcmcp_server.handlers.dispatch import register as _register
+from tcmcp_server.sdk import cloud_client, fail, ok
+
+
+def _cluster(selection, alias: str):
+ return resolve_alias(selection.resources.tdsqlc, alias)
+
+
+def handle_detail(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cynosdb.v20190107 import models
+
+ client = cloud_client("cynosdb", sid, skey, item.region or region)
+ req = models.DescribeClusterDetailRequest()
+ req.ClusterId = item.cluster_id
+ resp = client.DescribeClusterDetail(req)
+ d = resp.Detail
+ return ok(
+ {
+ "clusterId": d.ClusterId,
+ "name": d.ClusterName,
+ "status": d.Status,
+ "dbVersion": d.DbVersion,
+ "vip": d.Vip,
+ "vport": d.Vport,
+ "configuredInstanceId": item.instance_id,
+ "instanceNum": d.ServerlessInstanceNum or d.InstanceNum,
+ }
+ )
+
+
+def handle_databases(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cynosdb.v20190107 import models
+
+ client = cloud_client("cynosdb", sid, skey, item.region or region)
+ req = models.DescribeClusterDatabasesRequest()
+ req.ClusterId = item.cluster_id
+ req.Limit = 100
+ resp = client.DescribeClusterDatabases(req)
+ items = [str(d) for d in (resp.Databases or [])]
+ return ok({"items": items, "count": len(items), "total": resp.TotalCount})
+
+
+def handle_tables(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cynosdb.v20190107 import models
+
+ client = cloud_client("cynosdb", sid, skey, item.region or region)
+ req = models.SearchClusterTablesRequest()
+ req.ClusterId = item.cluster_id
+ if args.get("database"):
+ req.Database = args["database"]
+ if args.get("table"):
+ req.Table = args["table"]
+ if args.get("tableType"):
+ req.TableType = args["tableType"]
+ resp = client.SearchClusterTables(req)
+ items = []
+ for t in resp.Tables or []:
+ items.append(
+ {
+ "database": getattr(t, "Database", None),
+ "table": getattr(t, "Table", None),
+ "tableType": getattr(t, "TableType", None),
+ }
+ )
+ return ok({"items": items, "count": len(items)})
+
+
+def handle_slow(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cynosdb.v20190107 import models
+
+ client = cloud_client("cynosdb", sid, skey, item.region or region)
+ req = models.DescribeInstanceSlowQueriesRequest()
+ req.InstanceId = item.instance_id
+ if args.get("startTime"):
+ req.StartTime = args["startTime"]
+ if args.get("endTime"):
+ req.EndTime = args["endTime"]
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ if args.get("sqlText"):
+ req.Query = args["sqlText"]
+ resp = client.DescribeInstanceSlowQueries(req)
+ rows = []
+ for q in resp.SlowQueries or []:
+ rows.append(
+ {
+ "sql": getattr(q, "QuerySql", None) or getattr(q, "SqlText", None),
+ "queryTime": getattr(q, "QueryTime", None),
+ "user": getattr(q, "User", None),
+ "host": getattr(q, "UserHost", None),
+ "database": getattr(q, "Database", None),
+ "timestamp": getattr(q, "Timestamp", None),
+ }
+ )
+ return ok({"items": rows, "count": len(rows), "total": getattr(resp, "TotalCount", len(rows))})
+
+
+def handle_errors(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ sid, skey, region = secret_pair(data)
+ from tencentcloud.cynosdb.v20190107 import models
+
+ client = cloud_client("cynosdb", sid, skey, item.region or region)
+ req = models.DescribeInstanceErrorLogsRequest()
+ req.InstanceId = item.instance_id
+ if args.get("startTime"):
+ req.StartTime = args["startTime"]
+ if args.get("endTime"):
+ req.EndTime = args["endTime"]
+ if args.get("limit"):
+ req.Limit = int(args["limit"])
+ resp = client.DescribeInstanceErrorLogs(req)
+ rows = []
+ for log in resp.ErrorLogs or []:
+ rows.append(
+ {
+ "timestamp": getattr(log, "Timestamp", None),
+ "content": getattr(log, "Content", None),
+ }
+ )
+ return ok({"items": rows, "count": len(rows), "total": getattr(resp, "TotalCount", len(rows))})
+
+
+def register() -> None:
+ _register("db_cluster_detail", handle_detail)
+ _register("db_list_databases", handle_databases)
+ _register("db_search_tables", handle_tables)
+ _register("tdsqlc_slow_queries", handle_slow)
+ _register("tdsqlc_error_logs", handle_errors)
diff --git a/tools/tcmcp/app/mcp_runtime/handlers/tke.py b/tools/tcmcp/app/mcp_runtime/handlers/tke.py
new file mode 100644
index 00000000..7d7091bb
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/handlers/tke.py
@@ -0,0 +1,437 @@
+from __future__ import annotations
+
+import json
+from urllib.parse import quote, urlencode
+
+from tcmcp_server.config import resolve_alias, secret_pair
+from tcmcp_server.handlers.dispatch import register as _register
+from tcmcp_server.sdk import cloud_client, fail, ok
+
+
+def _cluster(selection, alias: str):
+ return resolve_alias(selection.resources.tke, alias)
+
+
+def _client(data, selection, item):
+ sid, skey, region = secret_pair(data)
+ return cloud_client("tke", sid, skey, item.region or region)
+
+
+def _client2022(data, selection, item):
+ sid, skey, region = secret_pair(data)
+ return cloud_client("tke2022", sid, skey, item.region or region)
+
+
+def _regular_pool_row(p) -> dict:
+ summary = getattr(p, "NodeCountSummary", None)
+ manual = getattr(summary, "ManuallyAdded", None) if summary else None
+ auto = getattr(summary, "AutoscalingAdded", None) if summary else None
+ return {
+ "nodePoolId": p.NodePoolId,
+ "name": p.Name,
+ "type": "Regular",
+ "lifeState": p.LifeState,
+ "autoscaling": bool(getattr(p, "AutoscalingGroupId", None)),
+ "desired": getattr(p, "DesiredNodesNum", None),
+ "min": getattr(p, "MinNodesNum", None),
+ "max": getattr(p, "MaxNodesNum", None),
+ "os": getattr(p, "NodePoolOs", None),
+ "autoscalingGroupId": getattr(p, "AutoscalingGroupId", None),
+ "autoscalingGroupStatus": getattr(p, "AutoscalingGroupStatus", None),
+ "manuallyAdded": getattr(manual, "Total", None) if manual else None,
+ "autoscalingAdded": getattr(auto, "Total", None) if auto else None,
+ }
+
+
+def _native_scaling(native) -> dict:
+ scaling = getattr(native, "Scaling", None) if native else None
+ return {
+ "desired": getattr(native, "Replicas", None) if native else None,
+ "ready": getattr(native, "ReadyReplicas", None) if native else None,
+ "min": getattr(scaling, "MinReplicas", None) if scaling else None,
+ "max": getattr(scaling, "MaxReplicas", None) if scaling else None,
+ "autoscaling": bool(getattr(native, "EnableAutoscaling", None)) if native else False,
+ "instanceTypes": list(getattr(native, "InstanceTypes", None) or []) if native else [],
+ "machineType": getattr(native, "MachineType", None) if native else None,
+ "chargeType": getattr(native, "InstanceChargeType", None) if native else None,
+ }
+
+
+def _v2022_pool_row(p) -> dict:
+ extra = _native_scaling(getattr(p, "Native", None))
+ return {
+ "nodePoolId": p.NodePoolId,
+ "name": p.Name,
+ "type": p.Type,
+ "lifeState": p.LifeState,
+ "createdAt": getattr(p, "CreatedAt", None),
+ "deletionProtection": bool(getattr(p, "DeletionProtection", None)),
+ "unschedulable": bool(getattr(p, "Unschedulable", None)),
+ "autoscaling": extra["autoscaling"],
+ "desired": extra["desired"],
+ "ready": extra["ready"],
+ "min": extra["min"],
+ "max": extra["max"],
+ "instanceTypes": extra["instanceTypes"],
+ "machineType": extra["machineType"],
+ "chargeType": extra["chargeType"],
+ }
+
+
+def handle_detail(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client(data, selection, item)
+ req = models.DescribeClustersRequest()
+ req.ClusterIds = [item.id]
+ resp = client.DescribeClusters(req)
+ items = resp.Clusters or []
+ if not items:
+ return fail(f"找不到集群 {item.id}")
+ c = items[0]
+ return ok(
+ {
+ "clusterId": c.ClusterId,
+ "name": c.ClusterName,
+ "status": c.ClusterStatus,
+ "version": c.ClusterVersion,
+ "type": c.ClusterType,
+ "description": c.ClusterDescription,
+ }
+ )
+
+
+def handle_status(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client(data, selection, item)
+ req = models.DescribeClusterStatusRequest()
+ req.ClusterIds = [item.id]
+ resp = client.DescribeClusterStatus(req)
+ rows = resp.ClusterStatusSet or []
+ if not rows:
+ return fail(f"找不到集群状态 {item.id}")
+ s = rows[0]
+ return ok(
+ {
+ "clusterId": s.ClusterId,
+ "clusterState": s.ClusterState,
+ "instanceState": s.ClusterInstanceState,
+ "monitor": bool(s.ClusterBMonitor),
+ "runningNodes": s.ClusterRunningNodeNum,
+ "failedNodes": s.ClusterFailedNodeNum,
+ "initNodes": s.ClusterInitNodeNum,
+ "deletionProtection": bool(s.ClusterDeletionProtection),
+ "auditEnabled": bool(getattr(s, "ClusterAuditEnabled", None)),
+ }
+ )
+
+
+def handle_nodes(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client(data, selection, item)
+ req = models.DescribeClusterInstancesRequest()
+ req.ClusterId = item.id
+ req.Offset = int(args.get("offset") or 0)
+ req.Limit = min(int(args.get("limit") or 100), 100)
+ pool = (args.get("nodePoolId") or "").strip()
+ if pool:
+ filt = models.Filter()
+ filt.Name = "nodepool-id"
+ filt.Values = [pool]
+ req.Filters = [filt]
+ resp = client.DescribeClusterInstances(req)
+ items = []
+ for n in resp.InstanceSet or []:
+ items.append(
+ {
+ "instanceId": n.InstanceId,
+ "role": n.InstanceRole,
+ "state": n.InstanceState,
+ "lanIp": getattr(n, "LanIP", None),
+ "nodePoolId": getattr(n, "NodePoolId", None),
+ "drainStatus": getattr(n, "DrainStatus", None),
+ "failedReason": getattr(n, "FailedReason", None),
+ }
+ )
+ return ok({"items": items, "count": len(items), "total": resp.TotalCount})
+
+
+def handle_pools(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ by_id: dict[str, dict] = {}
+ errors: list[str] = []
+
+ try:
+ from tencentcloud.tke.v20220501 import models as m2022
+
+ client = _client2022(data, selection, item)
+ req = m2022.DescribeNodePoolsRequest()
+ req.ClusterId = item.id
+ req.Limit = 100
+ resp = client.DescribeNodePools(req)
+ for p in resp.NodePools or []:
+ if p.NodePoolId:
+ by_id[p.NodePoolId] = _v2022_pool_row(p)
+ except Exception as exc: # noqa: BLE001
+ errors.append(f"DescribeNodePools: {exc}")
+
+ try:
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client(data, selection, item)
+ req = models.DescribeClusterNodePoolsRequest()
+ req.ClusterId = item.id
+ resp = client.DescribeClusterNodePools(req)
+ for p in resp.NodePoolSet or []:
+ if p.NodePoolId and p.NodePoolId not in by_id:
+ by_id[p.NodePoolId] = _regular_pool_row(p)
+ except Exception as exc: # noqa: BLE001
+ errors.append(f"DescribeClusterNodePools: {exc}")
+
+ payload: dict = {"items": list(by_id.values()), "count": len(by_id)}
+ if not by_id and errors:
+ return fail(
+ "列出节点池失败: " + "; ".join(errors),
+ "确认 CAM 有 tke:DescribeNodePools 和 tke:DescribeClusterNodePools",
+ )
+ if errors:
+ payload["warnings"] = errors
+ return ok(payload)
+
+
+def handle_pool_detail(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ pool_id = (args.get("nodePoolId") or "").strip()
+ if not pool_id:
+ return fail("nodePoolId 必填")
+
+ try:
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client(data, selection, item)
+ req = models.DescribeClusterNodePoolDetailRequest()
+ req.ClusterId = item.id
+ req.NodePoolId = pool_id
+ resp = client.DescribeClusterNodePoolDetail(req)
+ if resp.NodePool:
+ return ok(_regular_pool_row(resp.NodePool))
+ except Exception:
+ pass
+
+ try:
+ from tencentcloud.tke.v20220501 import models as m2022
+
+ client = _client2022(data, selection, item)
+ req = m2022.DescribeNodePoolsRequest()
+ req.ClusterId = item.id
+ filt = m2022.Filter()
+ filt.Name = "NodePoolsId"
+ filt.Values = [pool_id]
+ req.Filters = [filt]
+ resp = client.DescribeNodePools(req)
+ pools = [p for p in (resp.NodePools or []) if p.NodePoolId == pool_id]
+ if pools:
+ return ok(_v2022_pool_row(pools[0]))
+ except Exception as cop_exc: # noqa: BLE001
+ return fail(f"读取节点池失败: {exc}", "确认 CAM 有 tke:DescribeNodePools")
+
+ return fail(f"找不到节点池 {pool_id}")
+
+
+def handle_addons(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client(data, selection, item)
+ req = models.DescribeAddonRequest()
+ req.ClusterId = item.id
+ if args.get("addon"):
+ req.AddonName = args["addon"]
+ resp = client.DescribeAddon(req)
+ items = []
+ for a in resp.Addons or []:
+ items.append(
+ {
+ "name": a.AddonName,
+ "version": a.AddonVersion,
+ "latest": getattr(a, "LatestVersion", None),
+ "phase": a.Phase,
+ "reason": getattr(a, "Reason", None),
+ }
+ )
+ return ok({"items": items, "count": len(items)})
+
+
+def handle_endpoint(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client(data, selection, item)
+
+ def _status(extranet: bool) -> str:
+ req = models.DescribeClusterEndpointStatusRequest()
+ req.ClusterId = item.id
+ req.IsExtranet = extranet
+ return client.DescribeClusterEndpointStatus(req).Status or "Unknown"
+
+ intranet = _status(False)
+ internet = _status(True)
+ return ok(
+ {
+ "intranet": intranet,
+ "internet": internet,
+ "intranetReady": str(intranet).lower() == "created",
+ "internetReady": str(internet).lower() == "created",
+ }
+ )
+
+
+def _switch_info(info):
+ if not info:
+ return None
+ return {
+ "enabled": getattr(info, "Enable", None),
+ "logsetId": getattr(info, "LogsetId", None),
+ "topicId": getattr(info, "TopicId", None),
+ "status": getattr(info, "Status", None),
+ }
+
+
+def handle_log_switches(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ from tencentcloud.tke.v20180525 import models
+
+ client = _client(data, selection, item)
+ req = models.DescribeLogSwitchesRequest()
+ req.ClusterIds = [item.id]
+ resp = client.DescribeLogSwitches(req)
+ rows = resp.SwitchSet or []
+ if not rows:
+ return ok({"clusterId": item.id, "audit": None, "event": None, "log": None})
+ sw = rows[0]
+ return ok(
+ {
+ "clusterId": sw.ClusterId or item.id,
+ "audit": _switch_info(sw.Audit),
+ "event": _switch_info(sw.Event),
+ "log": _switch_info(sw.Log),
+ "masterLog": _switch_info(getattr(sw, "MasterLog", None)),
+ }
+ )
+
+
+def _k8s_get(client, cluster_id: str, path: str) -> str:
+ payload = client.call_json(
+ "ForwardApplicationRequestV3",
+ {"ClusterName": cluster_id, "Method": "GET", "Path": path},
+ )
+ resp = payload.get("Response") or payload
+ err = resp.get("Error")
+ if err:
+ raise ValueError(err.get("Message") or str(err))
+ return resp.get("ResponseBody") or ""
+
+
+def _pod_row(pod: dict) -> dict:
+ meta = pod.get("metadata") or {}
+ spec = pod.get("spec") or {}
+ status = pod.get("status") or {}
+ containers = []
+ restarts = 0
+ ready = 0
+ total = 0
+ for cs in status.get("containerStatuses") or []:
+ total += 1
+ if cs.get("ready"):
+ ready += 1
+ restarts += int(cs.get("restartCount") or 0)
+ containers.append(cs.get("name"))
+ if not containers:
+ containers = [c.get("name") for c in (spec.get("containers") or []) if c.get("name")]
+ total = len(containers)
+ return {
+ "name": meta.get("name"),
+ "namespace": meta.get("namespace"),
+ "phase": status.get("phase"),
+ "node": spec.get("nodeName"),
+ "ready": f"{ready}/{total}" if total else status.get("phase"),
+ "restarts": restarts,
+ "containers": containers,
+ }
+
+
+def handle_list_pods(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ client = _client(data, selection, item)
+ ns = (args.get("namespace") or "").strip()
+ path = f"/api/v1/namespaces/{quote(ns, safe='')}/pods" if ns else "/api/v1/pods"
+ query: dict[str, str] = {}
+ if args.get("labelSelector"):
+ query["labelSelector"] = args["labelSelector"]
+ limit = int(args.get("limit") or 100)
+ if limit > 200:
+ return fail("limit 上限 200", "缩小 limit 后重试")
+ query["limit"] = str(limit)
+ path = f"{path}?{urlencode(query)}"
+ try:
+ raw = _k8s_get(client, item.id, path)
+ body = json.loads(raw) if raw else {}
+ except Exception as e:
+ return fail(f"列出 Pod 失败: {e}", "确认 CAM 有 tke:ForwardApplicationRequestV3,且集群 apiserver 可访问")
+ items = [_pod_row(p) for p in (body.get("items") or [])]
+ return ok({"items": items, "count": len(items)})
+
+
+def handle_pod_logs(args, data, selection):
+ item = _cluster(selection, args.get("cluster", ""))
+ pod = (args.get("pod") or "").strip()
+ if not pod:
+ return fail("pod 必填")
+ ns = (args.get("namespace") or "default").strip() or "default"
+ tail = min(int(args.get("tailLines") or 200), 500)
+ query = {"timestamps": "true", "tailLines": str(tail)}
+ if args.get("container"):
+ query["container"] = args["container"]
+ if str(args.get("previous") or "").lower() == "true":
+ query["previous"] = "true"
+ path = f"/api/v1/namespaces/{quote(ns, safe='')}/pods/{quote(pod, safe='')}/log?{urlencode(query)}"
+ client = _client(data, selection, item)
+ try:
+ text = _k8s_get(client, item.id, path)
+ except Exception as e:
+ return fail(
+ f"读取 Pod 日志失败: {e}",
+ "先用 tke_list_pods 确认 namespace / pod / container;多容器必须传 container",
+ )
+ truncated = False
+ if len(text) > 200_000:
+ text = text[-200_000:]
+ truncated = True
+ return ok(
+ {
+ "pod": pod,
+ "namespace": ns,
+ "container": args.get("container") or "",
+ "tailLines": tail,
+ "truncated": truncated,
+ "log": text,
+ }
+ )
+
+
+def register() -> None:
+ _register("tke_cluster_detail", handle_detail)
+ _register("tke_cluster_status", handle_status)
+ _register("tke_list_nodes", handle_nodes)
+ _register("tke_list_node_pools", handle_pools)
+ _register("tke_node_pool_detail", handle_pool_detail)
+ _register("tke_list_addons", handle_addons)
+ _register("tke_endpoint_status", handle_endpoint)
+ _register("tke_log_switches", handle_log_switches)
+ _register("tke_list_pods", handle_list_pods)
+ _register("tke_pod_logs", handle_pod_logs)
diff --git a/tools/tcmcp/app/mcp_runtime/http_auth.py b/tools/tcmcp/app/mcp_runtime/http_auth.py
new file mode 100644
index 00000000..894c15f3
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/http_auth.py
@@ -0,0 +1,79 @@
+"""Bearer token gate for Streamable HTTP / Docker."""
+
+from __future__ import annotations
+
+import hmac
+import os
+from collections.abc import Iterable
+
+from starlette.responses import JSONResponse
+
+PUBLIC_PATHS = frozenset({"/healthz", "/health"})
+
+
+def resolve_http_tokens(*groups: Iterable[str] | str | None) -> list[str]:
+ out: list[str] = []
+ seen: set[str] = set()
+ for group in groups:
+ if group is None:
+ continue
+ values = [group] if isinstance(group, str) else list(group)
+ for raw in values:
+ for part in str(raw).split(","):
+ token = part.strip()
+ if token and token not in seen:
+ seen.add(token)
+ out.append(token)
+ extra = os.environ.get("TCMCP_AUTH_TOKENS") or os.environ.get("TCMCP_AUTH_TOKEN") or ""
+ for part in extra.split(","):
+ token = part.strip()
+ if token and token not in seen:
+ seen.add(token)
+ out.append(token)
+ return out
+
+
+def _authorized(header: bytes, tokens: list[str]) -> bool:
+ text = header.decode("latin-1", errors="replace").strip()
+ if not text.lower().startswith("bearer "):
+ return False
+ given = text[7:].strip()
+ if not given:
+ return False
+ return any(hmac.compare_digest(given, token) for token in tokens)
+
+
+class BearerTokenASGI:
+ """Reject HTTP requests that do not present a configured Bearer token."""
+
+ def __init__(self, app, tokens: list[str]):
+ self.app = app
+ self.tokens = tokens
+
+ async def __call__(self, scope, receive, send):
+ if scope["type"] != "http":
+ await self.app(scope, receive, send)
+ return
+ path = scope.get("path") or ""
+ if path.rstrip("/") in PUBLIC_PATHS or path in PUBLIC_PATHS:
+ await self.app(scope, receive, send)
+ return
+ headers = dict(scope.get("headers") or [])
+ if _authorized(headers.get(b"authorization", b""), self.tokens):
+ await self.app(scope, receive, send)
+ return
+ response = JSONResponse(
+ {"error": "unauthorized", "hint": "Authorization: Bearer <TCMCP_AUTH_TOKEN>"},
+ status_code=401,
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ await response(scope, receive, send)
+
+
+def protect_http_app(mcp, tokens: list[str]) -> None:
+ inner = mcp.streamable_http_app
+
+ def wrapped():
+ return BearerTokenASGI(inner(), tokens)
+
+ mcp.streamable_http_app = wrapped # type: ignore[method-assign]
diff --git a/tools/tcmcp/app/mcp_runtime/listen.py b/tools/tcmcp/app/mcp_runtime/listen.py
new file mode 100644
index 00000000..9a3cf70b
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/listen.py
@@ -0,0 +1,26 @@
+"""Parse config.yaml server.listen into a bind address."""
+
+from __future__ import annotations
+
+DEFAULT_LISTEN = "127.0.0.1:8099"
+
+
+def parse_listen(listen: str | None) -> tuple[str, int]:
+ """Bind localhost unless the config names another host."""
+ raw = (listen or "").strip() or DEFAULT_LISTEN
+ if raw.startswith(":"):
+ host, port = "127.0.0.1", raw[1:]
+ elif ":" in raw:
+ host, _, port = raw.rpartition(":")
+ host = host or "127.0.0.1"
+ else:
+ host, port = "127.0.0.1", raw
+ return host, int(port or 8099)
+
+
+def resolve_transport(*candidates: str | None) -> str:
+ """First of CLI / env / leftover config; default stdio."""
+ for value in candidates:
+ if value in ("stdio", "http"):
+ return value
+ return "stdio"
diff --git a/tools/tcmcp/app/mcp_runtime/sdk.py b/tools/tcmcp/app/mcp_runtime/sdk.py
new file mode 100644
index 00000000..47a90628
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/sdk.py
@@ -0,0 +1,69 @@
+"""Thin Tencent Cloud client factory for generated tools."""
+
+from __future__ import annotations
+
+import warnings
+from functools import lru_cache
+
+# tencentcloud-sdk-python typos "fileds" when the API returns extra JSON keys.
+warnings.filterwarnings("ignore", message=r".*fileds are useless\.")
+
+
+@lru_cache(maxsize=32)
+def cloud_client(product: str, secret_id: str, secret_key: str, region: str):
+ from tencentcloud.common import credential
+ from tencentcloud.common.profile.client_profile import ClientProfile
+ from tencentcloud.common.profile.http_profile import HttpProfile
+
+ cred = credential.Credential(secret_id, secret_key)
+ endpoint = "tke.tencentcloudapi.com" if product.startswith("tke") else f"{product}.tencentcloudapi.com"
+ http = HttpProfile(endpoint=endpoint)
+ profile = ClientProfile(httpProfile=http)
+ if product == "redis":
+ from tencentcloud.redis.v20180412.redis_client import RedisClient
+
+ return RedisClient(cred, region, profile)
+ if product == "cdb":
+ from tencentcloud.cdb.v20170320.cdb_client import CdbClient
+
+ return CdbClient(cred, region, profile)
+ if product == "cynosdb":
+ from tencentcloud.cynosdb.v20190107.cynosdb_client import CynosdbClient
+
+ return CynosdbClient(cred, region, profile)
+ if product == "tke":
+ from tencentcloud.tke.v20180525.tke_client import TkeClient
+
+ return TkeClient(cred, region, profile)
+ if product == "tke2022":
+ from tencentcloud.tke.v20220501.tke_client import TkeClient as TkeClient2022
+
+ return TkeClient2022(cred, region, profile)
+ if product == "cls":
+ from tencentcloud.cls.v20201016.cls_client import ClsClient
+
+ return ClsClient(cred, region, profile)
+ if product == "dbbrain":
+ from tencentcloud.dbbrain.v20210527.dbbrain_client import DbbrainClient
+
+ return DbbrainClient(cred, region, profile)
+ raise ValueError(f"unknown product {product}")
+
+
+@lru_cache(maxsize=32)
+def cos_client(secret_id: str, secret_key: str, region: str):
+ from qcloud_cos import CosConfig, CosS3Client
+
+ config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Scheme="https")
+ return CosS3Client(config)
+
+
+def ok(payload) -> dict:
+ return payload if isinstance(payload, dict) else {"result": payload}
+
+
+def fail(message: str, hint: str = "") -> dict:
+ out = {"error": message}
+ if hint:
+ out["hint"] = hint
+ return out
diff --git a/tools/tcmcp/app/mcp_runtime/server.py b/tools/tcmcp/app/mcp_runtime/server.py
new file mode 100644
index 00000000..5c0d9b12
--- /dev/null
+++ b/tools/tcmcp/app/mcp_runtime/server.py
@@ -0,0 +1,127 @@
+"""MCP server: list_tools comes from preview.materialize (same as the Initializr)."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+
+from mcp.server.fastmcp import FastMCP
+from mcp.types import TextContent, Tool
+
+from starlette.requests import Request
+from starlette.responses import JSONResponse
+
+from tcmcp_server.config import load
+from tcmcp_server.handlers.dispatch import call, load_handlers
+from tcmcp_server.http_auth import protect_http_app, resolve_http_tokens
+from tcmcp_server.listen import parse_listen, resolve_transport
+from tcmcp_server.preview import materialize
+
+_STATE: dict = {}
+
+
+def _preview():
+ return materialize(_STATE["selection"])
+
+
+class ScopedMCP(FastMCP):
+ """list_tools is the materialized catalog, not inferred function signatures."""
+
+ async def list_tools(self) -> list[Tool]:
+ tools: list[Tool] = []
+ for item in _preview()["tools"]:
+ tools.append(
+ Tool(
+ name=item["name"],
+ description=item["description"],
+ inputSchema=item["inputSchema"],
+ annotations={"readOnlyHint": item["annotations"]["readOnlyHint"]},
+ )
+ )
+ return tools
+
+ async def call_tool(self, name: str, arguments: dict):
+ registered = {t["name"] for t in _preview()["tools"]}
+ if name not in registered:
+ payload = {"error": f"工具未注册: {name}"}
+ else:
+ try:
+ payload = call(name, arguments or {}, _STATE["data"], _STATE["selection"])
+ except Exception as exc: # noqa: BLE001
+ payload = {"error": str(exc)}
+ text = json.dumps(payload, ensure_ascii=False, default=str)
+ return [TextContent(type="text", text=text)]
+
+
+def build_mcp(config_path: str, listen_override: str | None = None) -> FastMCP:
+ data, selection = load(config_path)
+ _STATE["data"] = data
+ _STATE["selection"] = selection
+ load_handlers(selection.products)
+ preview = _preview()
+ host, port = parse_listen(listen_override or (data.get("server") or {}).get("listen"))
+ endpoint = (data.get("server") or {}).get("endpointPath") or "/mcp"
+ mcp = ScopedMCP(
+ selection.project.name or "tcmcp",
+ instructions=preview["instructions"],
+ host=host,
+ port=port,
+ streamable_http_path=endpoint,
+ )
+
+ @mcp.custom_route("/healthz", methods=["GET"])
+ async def healthz(_request: Request) -> JSONResponse:
+ return JSONResponse({"ok": True})
+
+ return mcp
+
+
+def main(argv: list[str] | None = None) -> None:
+ parser = argparse.ArgumentParser(description="Tencent Cloud ops MCP")
+ parser.add_argument("-config", "--config", default=os.environ.get("TCMCP_CONFIG", "config.yaml"))
+ parser.add_argument(
+ "-t",
+ "--transport",
+ choices=("stdio", "http"),
+ default=None,
+ help="stdio (default) or streamable HTTP. Overrides TCMCP_TRANSPORT.",
+ )
+ parser.add_argument(
+ "--listen",
+ default=None,
+ help="HTTP bind address, for example 0.0.0.0:8099. Overrides TCMCP_LISTEN and config.",
+ )
+ parser.add_argument(
+ "--auth-token",
+ default=None,
+ help="Bearer token for HTTP mode. Overrides / adds to TCMCP_AUTH_TOKEN.",
+ )
+ args = parser.parse_args(argv)
+ path = Path(args.config)
+ if not path.exists():
+ raise SystemExit(f"config not found: {path}")
+ data, selection = load(path)
+ mcp = build_mcp(str(path), args.listen or os.environ.get("TCMCP_LISTEN"))
+ transport = resolve_transport(
+ args.transport,
+ os.environ.get("TCMCP_TRANSPORT"),
+ (data.get("server") or {}).get("transport"),
+ selection.project.transport,
+ )
+ if transport == "http":
+ tokens = resolve_http_tokens(args.auth_token, (data.get("auth") or {}).get("tokens") or [])
+ if not tokens:
+ raise SystemExit(
+ "HTTP mode requires TCMCP_AUTH_TOKEN (or --auth-token). "
+ "Do not start a Docker / HTTP server without a Bearer token."
+ )
+ protect_http_app(mcp, tokens)
+ mcp.run(transport="streamable-http")
+ else:
+ mcp.run(transport="stdio")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/tcmcp/app/models.py b/tools/tcmcp/app/models.py
new file mode 100644
index 00000000..fa3896b2
--- /dev/null
+++ b/tools/tcmcp/app/models.py
@@ -0,0 +1,111 @@
+"""Shared request/response models for the Initializr API."""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+
+class ProjectSpec(BaseModel):
+ name: str = "demo"
+ description: str = "Tencent Cloud ops MCP"
+ target: str = "prod"
+ transport: Literal["stdio", "http"] = "stdio"
+ region: str = "ap-guangzhou"
+
+
+class ResourceItem(BaseModel):
+ id: str
+ alias: str
+ name: str = ""
+ region: str = ""
+ extra: dict[str, Any] = Field(default_factory=dict)
+
+
+class CLSTopic(BaseModel):
+ id: str
+ alias: str
+ name: str = ""
+
+
+class CLSResource(BaseModel):
+ logset_id: str = Field(alias="logsetId")
+ logset_name: str = Field(default="", alias="logsetName")
+ region: str = ""
+ topics: list[CLSTopic] = Field(default_factory=list)
+
+ model_config = {"populate_by_name": True}
+
+
+class TDSQLCResource(BaseModel):
+ cluster_id: str = Field(alias="clusterId")
+ instance_id: str = Field(alias="instanceId")
+ alias: str
+ name: str = ""
+ region: str = ""
+
+ model_config = {"populate_by_name": True}
+
+
+class BoundResources(BaseModel):
+ redis: list[ResourceItem] = Field(default_factory=list)
+ cdb: list[ResourceItem] = Field(default_factory=list)
+ tdsqlc: list[TDSQLCResource] = Field(default_factory=list)
+ tke: list[ResourceItem] = Field(default_factory=list)
+ cls: list[CLSResource] = Field(default_factory=list)
+ cos: list[ResourceItem] = Field(default_factory=list)
+
+
+class Selection(BaseModel):
+ """Current UI selection — used by preview-schema and starter.zip."""
+
+ project: ProjectSpec = Field(default_factory=ProjectSpec)
+ products: list[str] = Field(default_factory=list)
+ disabled_tools: list[str] = Field(default_factory=list)
+ resources: BoundResources = Field(default_factory=BoundResources)
+
+
+class CloudCreds(BaseModel):
+ secret_id: str = Field(alias="secretId")
+ secret_key: str = Field(alias="secretKey")
+ region: str = "ap-guangzhou"
+ project_id: int | None = Field(default=None, alias="projectId")
+ products: list[str] = Field(default_factory=list)
+
+ model_config = {"populate_by_name": True}
+
+
+class ListedResource(BaseModel):
+ id: str
+ name: str
+ region: str = ""
+ project_id: int | None = Field(default=None, alias="projectId")
+ extra: dict[str, Any] = Field(default_factory=dict)
+
+ model_config = {"populate_by_name": True}
+
+
+class ListedTopic(BaseModel):
+ id: str
+ name: str
+ logset_id: str = Field(alias="logsetId")
+
+ model_config = {"populate_by_name": True}
+
+
+class ListedLogset(BaseModel):
+ id: str
+ name: str
+ region: str = ""
+ topics: list[ListedTopic] = Field(default_factory=list)
+
+
+class ResourceCatalog(BaseModel):
+ redis: list[ListedResource] = Field(default_factory=list)
+ cdb: list[ListedResource] = Field(default_factory=list)
+ tdsqlc: list[ListedResource] = Field(default_factory=list)
+ tke: list[ListedResource] = Field(default_factory=list)
+ cls: list[ListedLogset] = Field(default_factory=list)
+ cos: list[ListedResource] = Field(default_factory=list)
+ errors: dict[str, str] = Field(default_factory=dict)
diff --git a/tools/tcmcp/app/preview.py b/tools/tcmcp/app/preview.py
new file mode 100644
index 00000000..8f30ae5f
--- /dev/null
+++ b/tools/tcmcp/app/preview.py
@@ -0,0 +1,175 @@
+"""Materialize MCP tools/list from a Selection. Used by UI and the generated server."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from app.catalog import TOOL_WARN_THRESHOLD, ToolSpec, tools_for_products
+from app.models import BoundResources, Selection
+
+
+def aliases_for(resources: BoundResources, kind: str) -> list[str]:
+ if kind == "redis":
+ return [r.alias for r in resources.redis if r.alias]
+ if kind == "cdb":
+ return [r.alias for r in resources.cdb if r.alias]
+ if kind == "tdsqlc":
+ return [r.alias for r in resources.tdsqlc if r.alias]
+ if kind == "tke":
+ return [r.alias for r in resources.tke if r.alias]
+ if kind == "cos":
+ return [r.alias for r in resources.cos if r.alias]
+ if kind in ("cls", "topics"):
+ out: list[str] = []
+ for logset in resources.cls:
+ for topic in logset.topics:
+ if topic.alias:
+ out.append(topic.alias)
+ return out
+ return []
+
+
+def has_resources(resources: BoundResources, kind: str) -> bool:
+ return bool(aliases_for(resources, kind))
+
+
+def tool_ready(tool: ToolSpec, products: list[str], resources: BoundResources) -> tuple[bool, str]:
+ if tool.requires_products:
+ missing = [p for p in tool.requires_products if p not in products]
+ if missing:
+ return False, f"需要同时启用产品: {', '.join(missing)}"
+ for kind in tool.requires_resources:
+ if not has_resources(resources, kind):
+ return False, f"缺少已绑定的 {kind} 资源,生成时不会注册"
+ if tool.name in ("k8s_events", "k8s_audit"):
+ topics = aliases_for(resources, "topics")
+ need = "events" if tool.name == "k8s_events" else "audit"
+ if need not in topics:
+ return False, f"需要绑定别名为 {need} 的 CLS 主题"
+ return True, ""
+
+
+def input_schema(tool: ToolSpec, selection: Selection) -> dict[str, Any]:
+ props: dict[str, Any] = {}
+ required: list[str] = []
+ target_name = selection.project.target or "prod"
+ for param in tool.params:
+ schema: dict[str, Any] = {"type": param.type, "description": param.description}
+ if param.type == "array":
+ schema["items"] = {"type": param.items_type or "string"}
+ values: list[str] | None = None
+ if param.enum:
+ values = list(param.enum)
+ elif param.enum_from == "targets":
+ values = [target_name]
+ elif param.enum_from:
+ values = aliases_for(selection.resources, param.enum_from)
+ if values:
+ schema["enum"] = values
+ if param.default is not None:
+ schema["default"] = param.default
+ props[param.name] = schema
+ if param.required:
+ required.append(param.name)
+ out: dict[str, Any] = {"type": "object", "properties": props}
+ if required:
+ out["required"] = required
+ return out
+
+
+def materialize(selection: Selection) -> dict[str, Any]:
+ """Return tools/list-shaped payload plus grouping metadata for the UI."""
+ products = list(dict.fromkeys(selection.products))
+ disabled = set(selection.disabled_tools)
+ candidates = tools_for_products(products)
+ tools: list[dict[str, Any]] = []
+ skipped: list[dict[str, Any]] = []
+ registered: list[str] = []
+
+ for spec in candidates:
+ ready, reason = tool_ready(spec, products, selection.resources)
+ enabled = spec.name not in disabled
+ item = {
+ "name": spec.name,
+ "description": spec.description,
+ "product": spec.product,
+ "inputSchema": input_schema(spec, selection),
+ "annotations": {"readOnlyHint": spec.read_only},
+ "enabled": enabled,
+ "ready": ready,
+ "skipReason": "" if ready else reason,
+ }
+ if enabled and ready:
+ tools.append(item)
+ registered.append(spec.name)
+ else:
+ skipped.append(item)
+
+ grouped: dict[str, list[dict[str, Any]]] = {}
+ for item in tools + skipped:
+ grouped.setdefault(item["product"], []).append(item)
+
+ instructions = _instructions(products, registered)
+ return {
+ "instructions": instructions,
+ "tools": tools,
+ "skipped": skipped,
+ "grouped": grouped,
+ "registered": registered,
+ "counts": {
+ "products": len(products),
+ "resources": _resource_count(selection.resources),
+ "tools": len(tools),
+ "threshold": TOOL_WARN_THRESHOLD,
+ },
+ "warn": len(tools) > TOOL_WARN_THRESHOLD,
+ "warnMessage": (
+ f"将生成 {len(tools)} 个工具,超过 {TOOL_WARN_THRESHOLD} 容易让模型幻觉。"
+ "建议少选产品或在右侧关掉不常用工具。"
+ if len(tools) > TOOL_WARN_THRESHOLD
+ else ""
+ ),
+ }
+
+
+def _resource_count(resources: BoundResources) -> int:
+ n = (
+ len(resources.redis)
+ + len(resources.cdb)
+ + len(resources.tdsqlc)
+ + len(resources.tke)
+ + len(resources.cos)
+ )
+ for logset in resources.cls:
+ n += len(logset.topics)
+ return n
+
+
+def _instructions(products: list[str], tools: list[str]) -> str:
+ lines = [
+ "腾讯云运维 MCP(只读云 API)。资源 ID 已绑定在 config,工具入参只用别名。",
+ "时间参数用 RFC3339。limit 超上限会报错,不会静默截断。",
+ ]
+ if "tdsqlc" in products:
+ lines.append(
+ "TDSQL-C:库表用 db_*;慢 SQL 用 tdsqlc_slow_queries 看明细、"
+ "dbbrain_slow_top_sqls 看模板聚合。DBBrain Product 已固定为 cynosdb。"
+ )
+ if "cdb" in products:
+ lines.append("CDB:cdb_* 工具,DBBrain Product 已固定为 mysql。")
+ if "cls" in products:
+ lines.append("日志:cls_search_log / cls_histogram;topic 必须用已绑定别名。")
+ if "tke" in products:
+ lines.append(
+ "TKE:tke_list_pods + tke_pod_logs 看当前 Pod 日志;"
+ "tke_list_nodes / tke_list_addons 看节点和组件。"
+ )
+ if "tke" in products and "cls" in products:
+ lines.append("容器日志与 k8s 事件走 CLS 历史数据,不是实时 tail。")
+ if "redis" in products:
+ lines.append("Redis 只读云 API,不是 redis-cli 数据面。")
+ if "cos" in products:
+ lines.append("COS 只返回桶、对象列表和对象元数据,不下载对象内容。")
+ if tools:
+ lines.append("已注册工具: " + ", ".join(tools))
+ return "\n".join(lines)
diff --git a/tools/tcmcp/app/regions.py b/tools/tcmcp/app/regions.py
new file mode 100644
index 00000000..1e55c28d
--- /dev/null
+++ b/tools/tcmcp/app/regions.py
@@ -0,0 +1,27 @@
+"""Tencent Cloud regions shown in the Initializr picker."""
+
+from __future__ import annotations
+
+REGIONS: tuple[tuple[str, str], ...] = (
+ ("ap-guangzhou", "广州"),
+ ("ap-shanghai", "上海"),
+ ("ap-nanjing", "南京"),
+ ("ap-beijing", "北京"),
+ ("ap-chengdu", "成都"),
+ ("ap-chongqing", "重庆"),
+ ("ap-hongkong", "中国香港"),
+ ("ap-singapore", "新加坡"),
+ ("ap-tokyo", "东京"),
+ ("ap-seoul", "首尔"),
+ ("ap-bangkok", "曼谷"),
+ ("ap-jakarta", "雅加达"),
+ ("ap-mumbai", "孟买"),
+ ("na-ashburn", "弗吉尼亚"),
+ ("na-siliconvalley", "硅谷"),
+ ("eu-frankfurt", "法兰克福"),
+ ("sa-saopaulo", "圣保罗"),
+)
+
+
+def public_regions() -> list[dict[str, str]]:
+ return [{"id": rid, "name": name} for rid, name in REGIONS]
diff --git a/tools/tcmcp/pyproject.toml b/tools/tcmcp/pyproject.toml
new file mode 100644
index 00000000..7c4a22ce
--- /dev/null
+++ b/tools/tcmcp/pyproject.toml
@@ -0,0 +1,38 @@
+[project]
+name = "tcmcp"
+version = "0.1.0"
+description = "Tencent Cloud MCP Initializr — generate a scoped ops MCP project"
+readme = "README.md"
+requires-python = ">=3.11"
+dependencies = [
+ "fastapi>=0.115.0",
+ "uvicorn[standard]>=0.32.0",
+ "pydantic>=2.10.0",
+ "jinja2>=3.1.4",
+ "pyyaml>=6.0.2",
+ "tencentcloud-sdk-python>=3.0.1400",
+ "cos-python-sdk-v5>=1.9.38",
+]
+
+[project.optional-dependencies]
+dev = [
+ "pytest>=8.3.0",
+ "httpx>=0.28.0",
+ "mcp>=1.12.0,<2",
+ "tomlkit>=0.13,<1",
+ "json5>=0.10,<1",
+]
+
+[project.scripts]
+tcmcp = "app.main:main"
+
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools.packages.find]
+include = ["app*"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+pythonpath = ["."]
diff --git a/tools/tcmcp/start.sh b/tools/tcmcp/start.sh
new file mode 100755
index 00000000..4a318bce
--- /dev/null
+++ b/tools/tcmcp/start.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")"
+if [[ ! -d .venv ]]; then
+ python3 -m venv .venv
+ .venv/bin/pip install -e '.[dev]'
+fi
+if [[ ! -d web/dist ]]; then
+ (cd web && npm install && npm run build)
+fi
+exec .venv/bin/python -m app.main
diff --git a/tools/tcmcp/tests/test_api.py b/tools/tcmcp/tests/test_api.py
new file mode 100644
index 00000000..ab19a57c
--- /dev/null
+++ b/tools/tcmcp/tests/test_api.py
@@ -0,0 +1,64 @@
+from pathlib import Path
+
+import pytest
+from fastapi.testclient import TestClient
+
+from app.main import app
+
+client = TestClient(app)
+WEB_DIST = Path(__file__).resolve().parents[1] / "web" / "dist"
+
+
+def test_metadata_and_preview_and_zip():
+ meta = client.get("/api/metadata")
+ assert meta.status_code == 200
+ assert [p["id"] for p in meta.json()["products"]] == ["redis", "cdb", "tdsqlc", "tke", "cls", "cos"]
+ assert any(r["id"] == "ap-guangzhou" for r in meta.json()["regions"])
+
+ body = {
+ "project": {"name": "demo", "target": "prod", "transport": "stdio", "region": "ap-guangzhou"},
+ "products": ["cls"],
+ "disabled_tools": [],
+ "resources": {
+ "cls": [
+ {
+ "logsetId": "ls",
+ "topics": [
+ {"id": "t-api", "alias": "api"},
+ {"id": "t-audit", "alias": "audit"},
+ ],
+ }
+ ]
+ },
+ }
+ preview = client.post("/api/preview-schema", json=body)
+ assert preview.status_code == 200
+ data = preview.json()
+ assert "cls_search_log" in data["registered"]
+ assert "redis_instance_detail" not in data["registered"]
+ topic_enum = next(t for t in data["tools"] if t["name"] == "cls_search_log")["inputSchema"]["properties"]["topic"]["enum"]
+ assert topic_enum == ["api", "audit"]
+
+ z = client.post("/api/starter.zip", json=body)
+ assert z.status_code == 200
+ assert z.headers["content-type"].startswith("application/zip")
+ assert z.content[:2] == b"PK"
+
+
+def test_cors_allows_vite_origin():
+ res = client.get("/api/healthz", headers={"Origin": "http://127.0.0.1:5173"})
+ assert res.status_code == 200
+ assert res.headers.get("access-control-allow-origin") == "http://127.0.0.1:5173"
+
+
+def test_cors_rejects_foreign_origin():
+ res = client.get("/api/healthz", headers={"Origin": "https://evil.example"})
+ assert res.status_code == 200
+ assert res.headers.get("access-control-allow-origin") != "https://evil.example"
+
+
[email protected](not (WEB_DIST / "index.html").exists(), reason="web/dist not built")
+def test_ui_index_served():
+ page = client.get("/")
+ assert page.status_code == 200
+ assert "Tencent Cloud MCP Initializr" in page.text
diff --git a/tools/tcmcp/tests/test_cam.py b/tools/tcmcp/tests/test_cam.py
new file mode 100644
index 00000000..d7244104
--- /dev/null
+++ b/tools/tcmcp/tests/test_cam.py
@@ -0,0 +1,41 @@
+from app.cam import cam_policy
+from app.models import BoundResources, ProjectSpec, ResourceItem, Selection
+
+
+def test_tke_cam_covers_native_pools_and_forward():
+ sel = Selection(
+ project=ProjectSpec(name="demo", region="ap-nanjing"),
+ products=["tke"],
+ resources=BoundResources(
+ tke=[ResourceItem(id="cls-xxxxxxxx", alias="demo-tke", name="x", region="ap-nanjing")]
+ ),
+ )
+ actions = {a for stmt in cam_policy(sel)["statement"] for a in stmt["action"]}
+ assert "tke:DescribeNodePools" in actions
+ assert "tke:DescribeClusterNodePools" in actions
+ assert "tke:ForwardApplicationRequestV3" in actions
+
+
+def test_cos_cam_is_scoped_to_selected_bucket():
+ sel = Selection(
+ project=ProjectSpec(name="demo", region="ap-guangzhou"),
+ products=["cos"],
+ resources=BoundResources(
+ cos=[
+ ResourceItem(
+ id="assets-1250000000",
+ alias="assets",
+ region="ap-guangzhou",
+ )
+ ]
+ ),
+ )
+ policy = cam_policy(sel)
+ assert policy["statement"] == [
+ {
+ "_comment": "COS 桶名须包含 APPID;只授权列对象、检查桶和读取对象元数据。",
+ "effect": "allow",
+ "action": ["cos:HeadBucket", "cos:GetBucket", "cos:HeadObject"],
+ "resource": ["qcs::cos:ap-guangzhou:uid/1250000000:assets-1250000000/*"],
+ }
+ ]
diff --git a/tools/tcmcp/tests/test_catalog.py b/tools/tcmcp/tests/test_catalog.py
new file mode 100644
index 00000000..7e3b83fc
--- /dev/null
+++ b/tools/tcmcp/tests/test_catalog.py
@@ -0,0 +1,61 @@
+from app.catalog import PRODUCTS, TOOLS, metadata, tools_for_products
+
+
+def test_metadata_lists_six_products():
+ meta = metadata()
+ ids = [p["id"] for p in meta["products"]]
+ assert ids == ["redis", "cdb", "tdsqlc", "tke", "cls", "cos"]
+ assert meta["toolWarnThreshold"] == 15
+ ids_region = [r["id"] for r in meta["regions"]]
+ assert "ap-guangzhou" in ids_region
+ assert "ap-shanghai" in ids_region
+
+
+def test_cls_wrappers_need_tke():
+ names = {t.name for t in tools_for_products(["cls"])}
+ assert "cls_search_log" in names
+ assert "container_logs" not in names
+ both = {t.name for t in tools_for_products(["cls", "tke"])}
+ assert "container_logs" in both
+ assert "k8s_events" in both
+
+
+def test_dbbrain_product_split():
+ cdb = {t.name for t in tools_for_products(["cdb"])}
+ cyn = {t.name for t in tools_for_products(["tdsqlc"])}
+ assert "cdb_dbbrain_health_score" in cdb
+ assert "dbbrain_health_score" in cyn
+ assert "dbbrain_health_score" not in cdb
+
+
+def test_every_tool_has_product():
+ ids = {p.id for p in PRODUCTS} | {"common"}
+ assert all(t.product in ids for t in TOOLS)
+
+
+def test_tke_has_cluster_and_node_tools():
+ names = {t.name for t in tools_for_products(["tke"])}
+ assert names >= {
+ "ping",
+ "tke_cluster_detail",
+ "tke_cluster_status",
+ "tke_list_nodes",
+ "tke_list_node_pools",
+ "tke_node_pool_detail",
+ "tke_list_addons",
+ "tke_endpoint_status",
+ "tke_log_switches",
+ "tke_list_pods",
+ "tke_pod_logs",
+ }
+
+
+def test_cos_has_read_only_bucket_and_object_tools():
+ names = {t.name for t in tools_for_products(["cos"])}
+ assert names == {
+ "ping",
+ "cos_bucket_detail",
+ "cos_list_objects",
+ "cos_object_metadata",
+ }
+ assert all(t.read_only for t in tools_for_products(["cos"]))
diff --git a/tools/tcmcp/tests/test_cloud.py b/tools/tcmcp/tests/test_cloud.py
new file mode 100644
index 00000000..a10079fd
--- /dev/null
+++ b/tools/tcmcp/tests/test_cloud.py
@@ -0,0 +1,65 @@
+from app.cloud.listing import list_resources
+from app.models import CloudCreds, ListedLogset, ListedResource, ListedTopic, ResourceCatalog
+
+
+def test_list_resources_uses_injected_listers(monkeypatch):
+ import app.cloud.listing as mod
+
+ def fake_redis(creds):
+ return [ListedResource(id="crs-1", name="cache")]
+
+ def fake_cls(creds):
+ return [
+ ListedLogset(
+ id="ls-1",
+ name="app",
+ topics=[ListedTopic(id="t1", name="api", logsetId="ls-1")],
+ )
+ ]
+
+ monkeypatch.setattr(mod, "LISTERS", {"redis": fake_redis, "cls": fake_cls})
+ cat = list_resources(
+ CloudCreds(secretId="id", secretKey="key", region="ap-guangzhou", products=["redis", "cls"])
+ )
+ assert isinstance(cat, ResourceCatalog)
+ assert cat.redis[0].id == "crs-1"
+ assert cat.cls[0].topics[0].id == "t1"
+ assert not cat.errors
+
+
+def test_lister_error_is_captured(monkeypatch):
+ import app.cloud.listing as mod
+
+ def boom(creds):
+ raise RuntimeError("AuthFailure")
+
+ monkeypatch.setattr(mod, "LISTERS", {"redis": boom})
+ cat = list_resources(CloudCreds(secretId="id", secretKey="key", products=["redis"]))
+ assert "AuthFailure" in cat.errors["redis"]
+
+
+def test_list_cos_filters_requested_region(monkeypatch):
+ import app.cloud.listing as mod
+
+ class FakeClient:
+ def list_buckets(self, **kwargs):
+ assert kwargs == {"Region": "ap-guangzhou"}
+ return {
+ "Buckets": {
+ "Bucket": [
+ {
+ "Name": "assets-1250000000",
+ "Location": "ap-guangzhou",
+ "CreationDate": "2026-09-14T00:00:00Z",
+ },
+ {"Name": "backup-1250000000", "Location": "ap-shanghai"},
+ ]
+ }
+ }
+
+ monkeypatch.setattr(mod, "_cos_client", lambda *args: FakeClient())
+ rows = mod.list_cos(
+ CloudCreds(secretId="id", secretKey="key", region="ap-guangzhou", products=["cos"])
+ )
+ assert [row.id for row in rows] == ["assets-1250000000"]
+ assert rows[0].extra["creationDate"] == "2026-09-14T00:00:00Z"
diff --git a/tools/tcmcp/tests/test_cos_handler.py b/tools/tcmcp/tests/test_cos_handler.py
new file mode 100644
index 00000000..28d4dd61
--- /dev/null
+++ b/tools/tcmcp/tests/test_cos_handler.py
@@ -0,0 +1,89 @@
+import sys
+import zipfile
+from io import BytesIO
+from pathlib import Path
+
+from app.generate import build_zip
+from app.models import BoundResources, ProjectSpec, ResourceItem, Selection
+
+
+def test_generated_cos_handler_lists_objects_and_metadata(tmp_path: Path, monkeypatch):
+ selection = Selection(
+ project=ProjectSpec(name="cos-ops", target="prod", region="ap-guangzhou"),
+ products=["cos"],
+ resources=BoundResources(
+ cos=[
+ ResourceItem(
+ id="assets-1250000000",
+ alias="assets",
+ region="ap-guangzhou",
+ )
+ ]
+ ),
+ )
+ with zipfile.ZipFile(BytesIO(build_zip(selection))) as zf:
+ zf.extractall(tmp_path)
+
+ src = str(tmp_path / "cos-ops" / "src")
+ sys.path.insert(0, src)
+ for key in list(sys.modules):
+ if key == "tcmcp_server" or key.startswith("tcmcp_server."):
+ del sys.modules[key]
+
+ class FakeClient:
+ def list_objects(self, **kwargs):
+ assert kwargs == {
+ "Bucket": "assets-1250000000",
+ "MaxKeys": 20,
+ "Prefix": "logs/",
+ "Delimiter": "/",
+ }
+ return {
+ "Prefix": "logs/",
+ "Contents": [
+ {
+ "Key": "logs/app.json",
+ "Size": "42",
+ "ETag": '"abc"',
+ "LastModified": "2026-09-14T00:00:00Z",
+ "StorageClass": "STANDARD",
+ }
+ ],
+ "CommonPrefixes": {"Prefix": "logs/archive/"},
+ "IsTruncated": "true",
+ "NextMarker": "logs/app.json",
+ }
+
+ def head_object(self, **kwargs):
+ assert kwargs == {
+ "Bucket": "assets-1250000000",
+ "Key": "logs/app.json",
+ "versionId": "v1",
+ }
+ return {"Content-Length": "42", "ETag": '"abc"'}
+
+ try:
+ from tcmcp_server.config import load
+ from tcmcp_server.handlers import cos
+
+ monkeypatch.setattr(cos, "cos_client", lambda *args: FakeClient())
+ data, generated_selection = load(tmp_path / "cos-ops" / "config.yaml")
+ listed = cos.handle_list_objects(
+ {"bucket": "assets", "prefix": "logs/", "delimiter": "/", "limit": 20},
+ data,
+ generated_selection,
+ )
+ assert listed["items"][0]["key"] == "logs/app.json"
+ assert listed["commonPrefixes"] == ["logs/archive/"]
+ assert listed["isTruncated"] is True
+ metadata = cos.handle_object_metadata(
+ {"bucket": "assets", "key": "logs/app.json", "versionId": "v1"},
+ data,
+ generated_selection,
+ )
+ assert metadata["metadata"]["Content-Length"] == "42"
+ finally:
+ sys.path.remove(src)
+ for key in list(sys.modules):
+ if key == "tcmcp_server" or key.startswith("tcmcp_server."):
+ del sys.modules[key]
diff --git a/tools/tcmcp/tests/test_frontend_contract.py b/tools/tcmcp/tests/test_frontend_contract.py
new file mode 100644
index 00000000..3fe5fa52
--- /dev/null
+++ b/tools/tcmcp/tests/test_frontend_contract.py
@@ -0,0 +1,28 @@
+from pathlib import Path
+
+WEB = Path(__file__).resolve().parents[1] / "web" / "src"
+
+
+def test_wizard_and_schema_inspector_exist():
+ app = (WEB / "App.tsx").read_text()
+ inspector = (WEB / "components" / "SchemaInspector.tsx").read_text()
+ assert "项目与产品" in app
+ assert "云资源绑定" in app
+ assert "绑定 Redis" in app
+ assert "MCP Schema" in app
+ assert "previewSchema" in app
+ assert "disabled_tools" in app
+ assert 'label="传输"' not in app
+ assert "setTransport" not in app
+ assert "安装与部署" in app
+ assert "Docker Server" in app
+ assert "TCMCP_AUTH_TOKEN" in app
+ assert "复制启动命令" in app
+ assert "复制 HTTP 配置" in app
+ assert "复制配置" in app
+ assert "mcpConfigCopy" in app
+ assert "点复制会带上刚才填写的密钥" in app
+ assert "按产品" in inspector
+ assert "扁平列表" in inspector
+ assert "查看原始 JSON" in inspector
+ assert "enum" in inspector
diff --git a/tools/tcmcp/tests/test_generate.py b/tools/tcmcp/tests/test_generate.py
new file mode 100644
index 00000000..f05f2f3a
--- /dev/null
+++ b/tools/tcmcp/tests/test_generate.py
@@ -0,0 +1,147 @@
+import json
+import zipfile
+from io import BytesIO
+from pathlib import Path
+
+import yaml
+
+from app.generate import build_files, build_zip
+from app.models import BoundResources, CLSResource, CLSTopic, ProjectSpec, ResourceItem, Selection
+from app.preview import materialize
+
+
+def _selection() -> Selection:
+ return Selection(
+ project=ProjectSpec(name="skill-ops", target="prod", transport="stdio"),
+ products=["cls"],
+ resources=BoundResources(
+ cls=[
+ CLSResource(
+ logsetId="logset-1",
+ topics=[
+ CLSTopic(id="aaaa", alias="api", name="api"),
+ CLSTopic(id="bbbb", alias="audit", name="audit"),
+ ],
+ )
+ ]
+ ),
+ )
+
+
+def test_zip_omits_other_product_handlers():
+ files = build_files(_selection())
+ names = list(files)
+ assert any(n.endswith("src/tcmcp_server/handlers/cls.py") for n in names)
+ assert not any(n.endswith("src/tcmcp_server/handlers/redis.py") for n in names)
+ assert not any(n.endswith("src/tcmcp_server/handlers/tdsqlc.py") for n in names)
+ assert not any(n.endswith("src/tcmcp_server/handlers/dbbrain.py") for n in names)
+ assert "cos-python-sdk-v5" not in files["skill-ops/pyproject.toml"].decode()
+
+
+def test_config_only_has_selected_topics():
+ files = build_files(_selection())
+ cfg = yaml.safe_load(files["skill-ops/config.yaml"])
+ topics = cfg["targets"]["prod"]["cls"][0]["topics"]
+ assert {t["alias"] for t in topics} == {"api", "audit"}
+ assert "redis" not in cfg["targets"]["prod"]
+ assert cfg["tencent"]["secretId"] == "${TENCENT_SECRET_ID}"
+ assert cfg["server"]["listen"] == "127.0.0.1:8099"
+ assert "transport" not in cfg["server"]
+ assert cfg["auth"]["tokens"] == ["${TCMCP_AUTH_TOKEN}"]
+ mcp_json = json.loads(files["skill-ops/mcp.json"])
+ server = next(iter(mcp_json["mcpServers"].values()))
+ assert server["command"] == "/bin/bash"
+ assert server["args"] == ["/absolute/path/to/skill-ops/run.sh"]
+
+
+def test_bootstrap_script_installs_without_polluting_stdout():
+ files = build_files(_selection())
+ script = files["skill-ops/run.sh"].decode()
+ assert "python3" in script
+ assert "sys.version_info < (3, 11)" in script
+ assert 'python" -m venv' not in script
+ assert '"$PYTHON" -m venv "$VENV"' in script
+ assert 'pip install -e "$ROOT" >&2' in script
+ assert 'exec "$VENV/bin/python" -m tcmcp_server' in script
+
+
+def test_docker_server_uses_http_and_runtime_secrets():
+ files = build_files(_selection())
+ dockerfile = files["skill-ops/Dockerfile"].decode()
+ assert "TENCENT_SECRET" not in dockerfile
+ assert '"--transport", "http"' in dockerfile
+ assert '"--listen", "0.0.0.0:8099"' in dockerfile
+ assert "EXPOSE 8099" in dockerfile
+ assert "skill-ops/.dockerignore" in files
+ assert "skill-ops/src/tcmcp_server/http_auth.py" in files
+ assert "TCMCP_AUTH_TOKEN" not in dockerfile
+
+
+def test_preview_matches_generated_json():
+ sel = _selection()
+ preview = materialize(sel)
+ files = build_files(sel)
+ gen = json.loads(files["skill-ops/src/tcmcp_server/generated.json"])
+ assert set(gen["registered"]) == set(preview["registered"])
+ assert gen["products"] == ["cls"]
+
+
+def test_zip_roundtrip_materialize(tmp_path: Path):
+ sel = _selection()
+ preview = materialize(sel)
+ raw = build_zip(sel)
+ with zipfile.ZipFile(BytesIO(raw)) as zf:
+ zf.extractall(tmp_path)
+ cfg = yaml.safe_load((tmp_path / "skill-ops" / "config.yaml").read_text())
+ from app.models import Selection as S
+ from app.preview import materialize as mat
+
+ again = mat(
+ S.model_validate(
+ {
+ "project": {
+ **cfg["project"],
+ "region": cfg["tencent"]["region"],
+ },
+ "products": cfg["products"],
+ "disabled_tools": cfg["disabledTools"],
+ "resources": {"cls": cfg["targets"]["prod"]["cls"]},
+ }
+ )
+ )
+ assert again["registered"] == preview["registered"]
+ search = next(t for t in again["tools"] if t["name"] == "cls_search_log")
+ assert search["inputSchema"]["properties"]["topic"]["enum"] == ["api", "audit"]
+ assert (tmp_path / "skill-ops" / "deploy" / "cam-policy.json").exists()
+ copied = (tmp_path / "skill-ops" / "src" / "tcmcp_server" / "preview.py").read_text()
+ assert "from tcmcp_server." in copied
+ assert "from app." not in copied
+
+
+def test_cos_selection_generates_handler_config_and_dependency():
+ sel = Selection(
+ project=ProjectSpec(name="cos-ops", target="prod", region="ap-guangzhou"),
+ products=["cos"],
+ resources=BoundResources(
+ cos=[
+ ResourceItem(
+ id="assets-1250000000",
+ alias="assets",
+ name="assets-1250000000",
+ region="ap-guangzhou",
+ )
+ ]
+ ),
+ )
+ files = build_files(sel)
+ cfg = yaml.safe_load(files["cos-ops/config.yaml"])
+ assert cfg["targets"]["prod"]["cos"] == [
+ {
+ "alias": "assets",
+ "id": "assets-1250000000",
+ "name": "assets-1250000000",
+ "region": "ap-guangzhou",
+ }
+ ]
+ assert "cos-ops/src/tcmcp_server/handlers/cos.py" in files
+ assert "cos-python-sdk-v5" in files["cos-ops/pyproject.toml"].decode()
diff --git a/tools/tcmcp/tests/test_generated_list_tools.py b/tools/tcmcp/tests/test_generated_list_tools.py
new file mode 100644
index 00000000..9914140f
--- /dev/null
+++ b/tools/tcmcp/tests/test_generated_list_tools.py
@@ -0,0 +1,54 @@
+import asyncio
+import sys
+import zipfile
+from io import BytesIO
+from pathlib import Path
+
+from app.generate import build_zip
+from app.models import BoundResources, CLSResource, CLSTopic, ProjectSpec, Selection
+from app.preview import materialize
+
+
+def test_generated_list_tools_matches_preview(tmp_path: Path):
+ sel = Selection(
+ project=ProjectSpec(name="skill-ops", target="prod"),
+ products=["cls"],
+ resources=BoundResources(
+ cls=[
+ CLSResource(
+ logsetId="logset-1",
+ topics=[
+ CLSTopic(id="aaaa", alias="api", name="api"),
+ CLSTopic(id="bbbb", alias="audit", name="audit"),
+ ],
+ )
+ ]
+ ),
+ )
+ preview = materialize(sel)
+ with zipfile.ZipFile(BytesIO(build_zip(sel))) as zf:
+ zf.extractall(tmp_path)
+
+ src = str(tmp_path / "skill-ops" / "src")
+ sys.path.insert(0, src)
+ for key in list(sys.modules):
+ if key == "tcmcp_server" or key.startswith("tcmcp_server."):
+ del sys.modules[key]
+ try:
+ from tcmcp_server.server import build_mcp
+
+ mcp = build_mcp(str(tmp_path / "skill-ops" / "config.yaml"))
+ tools = asyncio.run(mcp.list_tools())
+ assert [t.name for t in tools] == preview["registered"]
+ by_name = {t.name: t for t in tools}
+ for item in preview["tools"]:
+ got = by_name[item["name"]].inputSchema
+ assert got.get("required") == item["inputSchema"].get("required")
+ for key, prop in item["inputSchema"]["properties"].items():
+ if "enum" in prop:
+ assert got["properties"][key]["enum"] == prop["enum"]
+ finally:
+ sys.path.remove(src)
+ for key in list(sys.modules):
+ if key == "tcmcp_server" or key.startswith("tcmcp_server."):
+ del sys.modules[key]
diff --git a/tools/tcmcp/tests/test_http_auth.py b/tools/tcmcp/tests/test_http_auth.py
new file mode 100644
index 00000000..046dc2a9
--- /dev/null
+++ b/tools/tcmcp/tests/test_http_auth.py
@@ -0,0 +1,24 @@
+import hmac
+
+from app.mcp_runtime.http_auth import _authorized, resolve_http_tokens
+
+
+def test_resolve_http_tokens_dedupes_and_skips_empty(monkeypatch):
+ monkeypatch.delenv("TCMCP_AUTH_TOKEN", raising=False)
+ monkeypatch.delenv("TCMCP_AUTH_TOKENS", raising=False)
+ assert resolve_http_tokens("", ["", " "], " alpha ", "alpha,beta") == ["alpha", "beta"]
+
+
+def test_resolve_http_tokens_reads_env(monkeypatch):
+ monkeypatch.setenv("TCMCP_AUTH_TOKEN", "from-env")
+ monkeypatch.delenv("TCMCP_AUTH_TOKENS", raising=False)
+ assert resolve_http_tokens([]) == ["from-env"]
+
+
+def test_authorized_bearer_compare():
+ tokens = ["secret-token"]
+ assert _authorized(b"Bearer secret-token", tokens)
+ assert _authorized(b"bearer secret-token", tokens)
+ assert not _authorized(b"Bearer wrong", tokens)
+ assert not _authorized(b"secret-token", tokens)
+ assert hmac.compare_digest("secret-token", tokens[0])
diff --git a/tools/tcmcp/tests/test_install.py b/tools/tcmcp/tests/test_install.py
new file mode 100644
index 00000000..5a1847cc
--- /dev/null
+++ b/tools/tcmcp/tests/test_install.py
@@ -0,0 +1,207 @@
+import io
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+import tomllib
+import zipfile
+
+from fastapi.testclient import TestClient
+import pytest
+
+from app import install as api
+from app import installer
+from app.generate import build_zip
+from app.main import app
+from app.models import ProjectSpec, Selection
+
+
+def client(tmp_path, monkeypatch):
+ monkeypatch.setenv("TCMCP_INSTALL_STORE", str(tmp_path / "packages"))
+ return TestClient(app)
+
+
+def test_installation_scoped_expiring_package(client):
+ one = client.post("/api/installations", json={"project": {"name": "one"}, "products": ["cls"], "secretKey": "DO-NOT-STORE"})
+ two = client.post("/api/installations", json={"project": {"name": "two"}, "products": ["redis"]})
+ assert one.status_code == two.status_code == 200
+ token = one.json()["id"]
+ assert token != two.json()["id"]
+ assert one.headers["cache-control"] == "no-store"
+ package = client.get(f"/api/installations/{token}/starter.zip")
+ with zipfile.ZipFile(io.BytesIO(package.content)) as z:
+ assert all(name.startswith("one/") for name in z.namelist())
+ assert all(b"DO-NOT-STORE" not in z.read(name) for name in z.namelist())
+ for name, path in one.json()["paths"].items():
+ response = client.get(path)
+ assert response.status_code == 200
+ assert response.text.startswith("#!/usr/bin/env bash")
+ assert "text/x-shellscript" in response.headers["content-type"]
+ assert response.headers["cache-control"] == "no-store"
+ subprocess.run(["bash", "-n"], input=response.text, text=True, check=True)
+ assert client.get(f"/{name}").status_code == 200
+ expired = api.package_path(token)
+ os.utime(expired, (time.time() - api.TTL - 1,) * 2)
+ assert client.get(f"/codebuddy?project={token}").status_code == 410
+ assert client.get(f"/api/installations/{token}/starter.zip").status_code == 404
+
+
+def test_invalid_empty_and_full_store(client, monkeypatch):
+ assert client.post("/api/installations", json={}).status_code == 400
+ assert client.get("/cursor?project=../../etc/passwd").status_code == 404
+ assert client.get(f"/codex?project={'a' * 32}").status_code == 404
+ monkeypatch.setattr(api, "MAX_PACKAGES", 1)
+ assert client.post("/api/installations", json={"products": ["cls"]}).status_code == 200
+ assert client.post("/api/installations", json={"products": ["cls"]}).status_code == 503
+
+
[email protected]("agent", api.CLIENTS)
+def test_config_merge_backup_and_reinstall(tmp_path, monkeypatch, agent):
+ path = tmp_path / ("config.toml" if agent == "codex" else "mcp.json")
+ original = '# user comment\nmodel = "keep"\n[mcp_servers.other]\ncommand = "keep"\n' if agent == "codex" else '{// user comment\n"theme":"keep","mcpServers":{"other":{"command":"keep"}},}'
+ path.write_text(original)
+ monkeypatch.setenv("TCMCP_CLIENT_CONFIG", str(path))
+ monkeypatch.setenv("TENCENT_SECRET_ID", "test-id")
+ monkeypatch.setenv("TENCENT_SECRET_KEY", 'key-"-\\-测试')
+ root = tmp_path / "path with spaces" / "demo.name"
+ root.mkdir(parents=True)
+ for _ in range(2):
+ installer.configure(agent, root)
+ data = tomllib.loads(path.read_text()) if agent == "codex" else json.loads(path.read_text())
+ servers = data["mcp_servers" if agent == "codex" else "mcpServers"]
+ assert len(servers) == 2
+ assert servers["other"] == {"command": "keep"}
+ entry = servers["tcmcp-demo.name"]
+ assert entry["args"][3] == str(root / "config.yaml")
+ assert entry["env"]["TENCENT_SECRET_KEY"] == 'key-"-\\-测试'
+ assert entry["command"] == str(root / ".venv/bin/python")
+ assert data["model" if agent == "codex" else "theme"] == "keep"
+ assert len(list(tmp_path.glob(f"{path.name}.bak-*"))) == 2
+ assert any(p.read_text() == original for p in tmp_path.glob(f"{path.name}.bak-*"))
+ assert path.stat().st_mode & 0o777 == 0o600
+ if agent == "codex":
+ assert "# user comment" in path.read_text()
+ assert (root / "rollback.sh").stat().st_mode & 0o777 == 0o700
+
+
[email protected]("agent", api.CLIENTS)
+def test_rollback_restores_existing_config(tmp_path, monkeypatch, agent):
+ path = tmp_path / ("config.toml" if agent == "codex" else "mcp.json")
+ original = b'[mcp_servers.other]\ncommand = "keep"\n' if agent == "codex" else b'{"mcpServers":{"other":{"command":"keep"}}}\n'
+ path.write_bytes(original)
+ root = tmp_path / "project" / agent
+ root.mkdir(parents=True)
+ (root / ".venv/bin").mkdir(parents=True)
+ (root / ".venv/bin/python").symlink_to(sys.executable)
+ monkeypatch.setenv("TCMCP_CLIENT_CONFIG", str(path))
+ monkeypatch.setenv("TENCENT_SECRET_ID", "fake")
+ monkeypatch.setenv("TENCENT_SECRET_KEY", "fake")
+ installer.configure(agent, root)
+ subprocess.run(["bash", str(root / "rollback.sh")], check=True)
+ assert path.read_bytes() == original
+ assert list(tmp_path.glob(f"{path.name}.bak-*"))
+ assert list(tmp_path.glob(f"{path.name}.before-rollback-*"))
+
+
+def test_first_install_has_snapshot_and_rollback(tmp_path, monkeypatch):
+ path = tmp_path / "cursor" / "mcp.json"
+ root = tmp_path / "project"
+ root.mkdir()
+ (root / ".venv/bin").mkdir(parents=True)
+ (root / ".venv/bin/python").symlink_to(sys.executable)
+ monkeypatch.setenv("TCMCP_CLIENT_CONFIG", str(path))
+ monkeypatch.setenv("TENCENT_SECRET_ID", "fake")
+ monkeypatch.setenv("TENCENT_SECRET_KEY", "fake")
+ installer.configure("cursor", root)
+ backups = list(path.parent.glob("mcp.json.bak-*"))
+ assert len(backups) == 1
+ assert json.loads(backups[0].read_text()) == {"mcpServers": {}}
+ subprocess.run(["bash", str(root / "rollback.sh")], check=True)
+ assert not path.exists()
+ assert len(list(path.parent.glob("mcp.json.before-rollback-*"))) == 1
+
+
+def test_rollback_refuses_changed_config(tmp_path, monkeypatch):
+ path = tmp_path / "mcp.json"
+ path.write_text('{"mcpServers": {}}')
+ root = tmp_path / "project"
+ root.mkdir()
+ (root / ".venv/bin").mkdir(parents=True)
+ (root / ".venv/bin/python").symlink_to(sys.executable)
+ monkeypatch.setenv("TCMCP_CLIENT_CONFIG", str(path))
+ monkeypatch.setenv("TENCENT_SECRET_ID", "fake")
+ monkeypatch.setenv("TENCENT_SECRET_KEY", "fake")
+ installer.configure("cursor", root)
+ path.write_text('{"mcpServers": {"later": {"command": "keep"}}}')
+ result = subprocess.run(["bash", str(root / "rollback.sh")], text=True, capture_output=True)
+ assert result.returncode != 0
+ assert "安装后已发生变化" in result.stderr
+ assert "later" in path.read_text()
+
+
[email protected]("agent,invalid", [("cursor", '{"secret":"dont-log",'), ("cursor", '{"mcpServers": []}'), ("codex", '[mcp_servers\n'), ("codex", 'mcp_servers = []')])
+def test_invalid_config_untouched(tmp_path, monkeypatch, agent, invalid):
+ path = tmp_path / "config"
+ path.write_text(invalid)
+ monkeypatch.setenv("TCMCP_CLIENT_CONFIG", str(path))
+ monkeypatch.setenv("TENCENT_SECRET_ID", "fake")
+ monkeypatch.setenv("TENCENT_SECRET_KEY", "fake")
+ with pytest.raises(ValueError, match="原文件未修改") as exc:
+ root = tmp_path / "demo"
+ root.mkdir()
+ installer.configure(agent, root)
+ assert "dont-log" not in str(exc.value)
+ assert path.read_text() == invalid
+ assert not list(tmp_path.glob("*.bak-*"))
+
+
+def test_default_paths_and_codex_home(monkeypatch, tmp_path):
+ monkeypatch.delenv("TCMCP_CLIENT_CONFIG", raising=False)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ for agent in ("cursor", "codebuddy", "workbuddy"):
+ assert installer.config_path(agent) == tmp_path / f".{agent}/mcp.json"
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "custom-codex"))
+ assert installer.config_path("codex") == tmp_path / "custom-codex/config.toml"
+
+
+def test_extract_rejects_traversal(tmp_path):
+ stream = io.BytesIO()
+ with zipfile.ZipFile(stream, "w") as z:
+ z.writestr("../escaped", "bad")
+ with pytest.raises(ValueError, match="不安全"):
+ installer.extract_package(stream.getvalue(), tmp_path)
+ assert not (tmp_path.parent / "escaped").exists()
+
+
+def test_generated_metadata_is_valid_and_safe(tmp_path):
+ selection = Selection(project=ProjectSpec(name="..", description='quote\' and " and\n换行'), products=["cls"])
+ root = installer.extract_package(build_zip(selection), tmp_path)
+ assert root.name == "tcmcp-project"
+ assert tomllib.loads((root / "pyproject.toml").read_text())["project"]["description"] == selection.project.description
+
+
+def test_install_failure_leaves_client_untouched(tmp_path, monkeypatch):
+ monkeypatch.setenv("TCMCP_INSTALL_DIR", str(tmp_path / "installs"))
+ monkeypatch.setenv("TENCENT_SECRET_ID", "fake")
+ monkeypatch.setenv("TENCENT_SECRET_KEY", "fake")
+ data = build_zip(Selection(products=["cls"]))
+ monkeypatch.setattr(installer.urllib.request, "urlopen", lambda *a, **kw: io.BytesIO(data))
+ def fail(*args, **kwargs):
+ raise subprocess.CalledProcessError(1, ["venv"])
+ monkeypatch.setattr(installer.subprocess, "run", fail)
+ with pytest.raises(subprocess.CalledProcessError):
+ installer.install({"project": "a" * 32, "client": "cursor", "base_url": "http://testserver"})
+ assert list((tmp_path / "installs").iterdir()) == []
+
+
+def test_piped_script_no_tty_reports_missing_id(tmp_path):
+ script = api.render_script("codebuddy", "http://testserver")
+ env = {**os.environ, "TCMCP_PYTHON": sys.executable}
+ env.pop("TCMCP_INSTALL_ID", None)
+ result = subprocess.run(["bash"], input=script, text=True, capture_output=True, env=env, start_new_session=True)
+ assert result.returncode != 0
+ assert "export TCMCP_INSTALL_ID" in result.stderr
+ assert "unbound variable" not in result.stderr
diff --git a/tools/tcmcp/tests/test_listen.py b/tools/tcmcp/tests/test_listen.py
new file mode 100644
index 00000000..d989768c
--- /dev/null
+++ b/tools/tcmcp/tests/test_listen.py
@@ -0,0 +1,18 @@
+from app.mcp_runtime.listen import parse_listen, resolve_transport
+
+
+def test_parse_listen_defaults_to_localhost():
+ assert parse_listen(None) == ("127.0.0.1", 8099)
+ assert parse_listen("") == ("127.0.0.1", 8099)
+ assert parse_listen(":8099") == ("127.0.0.1", 8099)
+ assert parse_listen("8099") == ("127.0.0.1", 8099)
+ assert parse_listen("127.0.0.1:9000") == ("127.0.0.1", 9000)
+ assert parse_listen("0.0.0.0:8099") == ("0.0.0.0", 8099)
+
+
+def test_resolve_transport_cli_wins():
+ assert resolve_transport() == "stdio"
+ assert resolve_transport("http", "stdio", "stdio") == "http"
+ assert resolve_transport(None, "http") == "http"
+ assert resolve_transport(None, None, "stdio") == "stdio"
+ assert resolve_transport("bogus", "http") == "http"
diff --git a/tools/tcmcp/tests/test_preview.py b/tools/tcmcp/tests/test_preview.py
new file mode 100644
index 00000000..c5dd7147
--- /dev/null
+++ b/tools/tcmcp/tests/test_preview.py
@@ -0,0 +1,103 @@
+from app.models import BoundResources, CLSResource, CLSTopic, ProjectSpec, Selection
+from app.preview import materialize
+
+
+def _cls_selection(topics: list[tuple[str, str]], products=None, disabled=None) -> Selection:
+ return Selection(
+ project=ProjectSpec(name="demo", target="prod"),
+ products=products or ["cls"],
+ disabled_tools=disabled or [],
+ resources=BoundResources(
+ cls=[
+ CLSResource(
+ logsetId="logset-1",
+ logsetName="app",
+ topics=[CLSTopic(id=tid, alias=alias, name=alias) for alias, tid in topics],
+ )
+ ]
+ ),
+ )
+
+
+def test_cls_only_registers_log_tools_with_topic_enum():
+ preview = materialize(_cls_selection([("api", "topic-api"), ("audit", "topic-audit")]))
+ names = preview["registered"]
+ assert "ping" in names
+ assert "cls_search_log" in names
+ assert "redis_instance_detail" not in names
+ assert "dbbrain_health_score" not in names
+ search = next(t for t in preview["tools"] if t["name"] == "cls_search_log")
+ assert search["inputSchema"]["properties"]["topic"]["enum"] == ["api", "audit"]
+ assert search["inputSchema"]["properties"]["target"]["enum"] == ["prod"]
+
+
+def test_k8s_audit_requires_audit_alias():
+ preview = materialize(_cls_selection([("api", "topic-api")], products=["cls", "tke"]))
+ skipped = {t["name"]: t for t in preview["skipped"]}
+ assert "k8s_audit" in skipped
+ assert "audit" in skipped["k8s_audit"]["skipReason"]
+
+
+def test_disable_tool_drops_from_registered():
+ preview = materialize(
+ _cls_selection([("api", "t1")], disabled=["cls_histogram"]),
+ )
+ assert "cls_histogram" not in preview["registered"]
+ assert "cls_search_log" in preview["registered"]
+
+
+def test_warn_when_too_many_tools():
+ from app.models import ResourceItem, TDSQLCResource
+
+ sel = Selection(
+ project=ProjectSpec(name="big"),
+ products=["redis", "cdb", "tdsqlc", "tke", "cls"],
+ resources=BoundResources(
+ redis=[ResourceItem(id="crs-1", alias="cache")],
+ cdb=[ResourceItem(id="cdb-1", alias="mysql")],
+ tdsqlc=[TDSQLCResource(clusterId="c1", instanceId="i1", alias="primary")],
+ tke=[ResourceItem(id="cls-xx", alias="k8s")],
+ cls=[
+ CLSResource(
+ logsetId="ls",
+ topics=[
+ CLSTopic(id="1", alias="api"),
+ CLSTopic(id="2", alias="events"),
+ CLSTopic(id="3", alias="audit"),
+ ],
+ )
+ ],
+ ),
+ )
+ preview = materialize(sel)
+ assert preview["warn"] is True
+ assert preview["counts"]["tools"] > 15
+
+
+def test_cos_tools_use_bound_bucket_aliases():
+ from app.models import ResourceItem
+
+ sel = Selection(
+ project=ProjectSpec(name="cos-ops", target="prod"),
+ products=["cos"],
+ resources=BoundResources(
+ cos=[
+ ResourceItem(
+ id="assets-1250000000",
+ alias="assets",
+ name="assets-1250000000",
+ region="ap-guangzhou",
+ )
+ ]
+ ),
+ )
+ preview = materialize(sel)
+ assert set(preview["registered"]) == {
+ "ping",
+ "cos_bucket_detail",
+ "cos_list_objects",
+ "cos_object_metadata",
+ }
+ tool = next(t for t in preview["tools"] if t["name"] == "cos_list_objects")
+ assert tool["inputSchema"]["properties"]["bucket"]["enum"] == ["assets"]
+ assert preview["counts"]["resources"] == 1
diff --git a/tools/tcmcp/web/index.html b/tools/tcmcp/web/index.html
new file mode 100644
index 00000000..a11ed6d4
--- /dev/null
+++ b/tools/tcmcp/web/index.html
@@ -0,0 +1,18 @@
+<!doctype html>
+<html lang="zh-CN">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Tencent Cloud MCP Initializr</title>
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link
+ href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Noto+Sans+SC:wght@400;500;600&family=Outfit:wght@400;500;600;700&display=swap"
+ rel="stylesheet"
+ />
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+ </body>
+</html>
diff --git a/tools/tcmcp/web/package-lock.json b/tools/tcmcp/web/package-lock.json
new file mode 100644
index 00000000..850bbfe4
--- /dev/null
+++ b/tools/tcmcp/web/package-lock.json
@@ -0,0 +1,1841 @@
+{
+ "name": "tcmcp-web",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "tcmcp-web",
+ "version": "0.1.0",
+ "dependencies": {
+ "react": "^19.1.0",
+ "react-dom": "^19.1.0"
+ },
+ "devDependencies": {
+ "@types/react": "^19.1.0",
+ "@types/react-dom": "^19.1.0",
+ "@vitejs/plugin-react": "^4.5.0",
+ "typescript": "^5.8.0",
+ "vite": "^6.3.0"
+ }
+ },
+ "node_modules/@babel/code-frame": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "js-tokens": "^4.0.0",
+ "picocolors": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/compat-data": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/core": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
+ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-compilation-targets": "^7.29.7",
+ "@babel/helper-module-transforms": "^7.29.7",
+ "@babel/helpers": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7",
+ "@jridgewell/remapping": "^2.3.5",
+ "convert-source-map": "^2.0.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.2",
+ "json5": "^2.2.3",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/babel"
+ }
+ },
+ "node_modules/@babel/generator": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz",
+ "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.8",
+ "@babel/types": "^7.29.8",
+ "@jridgewell/gen-mapping": "^0.3.12",
+ "@jridgewell/trace-mapping": "^0.3.28",
+ "jsesc": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-compilation-targets": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
+ "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/compat-data": "^7.29.7",
+ "@babel/helper-validator-option": "^7.29.7",
+ "browserslist": "^4.24.0",
+ "lru-cache": "^5.1.1",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-globals": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-imports": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-transforms": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
+ "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-module-imports": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "@babel/traverse": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0"
+ }
+ },
+ "node_modules/@babel/helper-plugin-utils": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz",
+ "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-option": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helpers": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
+ "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",
+ "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.8"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-self": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz",
+ "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-source": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz",
+ "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/template": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/traverse": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz",
+ "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.8",
+ "@babel/helper-globals": "^7.29.7",
+ "@babel/parser": "^7.29.8",
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.8",
+ "debug": "^4.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.8",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
+ "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/remapping": {
+ "version": "2.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.0-beta.27",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
+ "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.63.1.tgz",
+ "integrity": "sha512-UZ8sUxPTiHWYX9QNdJedb1kDZSpS1t/VPWBWGSgqHNi9w3Cu6IXvu2mzbhiTiPvtrqgTQJ+zqiAq2iPIPilpaQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.63.1.tgz",
+ "integrity": "sha512-cQ4nFQABN5cDvDpbvJ7bMStCpnaVxynZrRMfUJYgxcIk9Sh54FIO1vtfkg0B69REjER77ioZ/ov+eAApx/KmLQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.63.1.tgz",
+ "integrity": "sha512-FQNqd1lRy/0QhDk3xeRIkSBiCpXCiDnZO3YLVdcDKN1UBiKToNftCzcXYNLshmPDUMlu2TdeS8tGcsU6f3YF1Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.63.1.tgz",
+ "integrity": "sha512-pvD16V939D3CloK0+qikpGaxiPrDUXTe7Y5cWOMkMSy7m1cawa8EGy/kXYi/G/cKAC4HDAbSnzCIk1WmsoOKXg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.63.1.tgz",
+ "integrity": "sha512-pcFGeL2345VwdTnJhA6zLbew+YgWB0qBG2+dMtXjCicf6+rm6kO6cOoh5VnTe0ZMrMRgRyuHmCJxZWrIdzYuOw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.63.1.tgz",
+ "integrity": "sha512-mRJlqSRulVzcKq/LKA6ICSIc3K/l4fzlVn/gePn2nXIHy8seRi5z/eeRE0d/XMBxcMldiXtQTSpRj0tkkC3g8Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.63.1.tgz",
+ "integrity": "sha512-YDUNvVM85TI3g/1OpnqKP1h4NeW/j64DfWMf+G3M809xNk1bJSnpFp4sh83NpmVE5DXnkh8ULor4LTVZKoYLHw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.63.1.tgz",
+ "integrity": "sha512-7Mcn71p9ZuQFAj+h+dhQXy/yeLePRS2yKRnmW1DijA9thKO5qap0GNOIQK4yQ6iP3SU0Mrb/yWo8h8vgRba8lw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.63.1.tgz",
+ "integrity": "sha512-4YiLQTX6U4CSl0L9cluep9A9W6UmTfqBDc2/CH6wlu54pl4E7Jn3cOD8oxzvBDEGk/JMKgJ47C8g+radF7mwvg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.63.1.tgz",
+ "integrity": "sha512-2ra8F7w8OquwZN9z2/fKFnli69wa8PLwaVzRMIPGb13ByMJwC28Fbp8YcVGoUhlYMTt7j5j9bNgpysrN2UM+vw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.63.1.tgz",
+ "integrity": "sha512-Sy20ncyhjmBP0Ml+UvQbimjlk6VFgjW5uNP+qqwHB00mTE8Bl2C1TuHTlRwK2YoXeZbee5lP2XevBWVkAQAtSQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.63.1.tgz",
+ "integrity": "sha512-noITLp8oNjYliPnGWmLyelIHwULGqbHloQHGw1rtxbWhTuWooRpnZarZQJ1y9EUC4szuCusCc+HEpUtxpIwYvA==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.63.1.tgz",
+ "integrity": "sha512-hlxxXd+F1mWiAcaFR7Sv9ZQT6m6UfI8+Vy/kFJzztq2pDMU/0wZ9sish0iszNZvsQDo8Gc0i5yuFEOz5dDf6fA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.63.1.tgz",
+ "integrity": "sha512-EF7OpqQTQ/BvGqLzUi4rEHuagCV9MugAUXSHemwPW5vxZ75RR+jxO/2j95Ph2dalMpFHSVECjRoioHZgA9zOYA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.63.1.tgz",
+ "integrity": "sha512-wQO3JesW9PRkwlabQ27y7sPfVOOTLRG73I4F2UYHG5PXun3J9U3y+b7ezVKSYbsvSKGQ1k1cq8Qlun4C9kLt3w==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.63.1.tgz",
+ "integrity": "sha512-ouAGwhO6wHRXdnOVCOsB0tRFkA7nhNB2Nwax6oECXN0YiN8EYUTBAOudADOB1PI+yDL61TeNx/u7MVCzksNbkQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.63.1.tgz",
+ "integrity": "sha512-q2R38Sn+1J8RxhfJ+T54wSWmyKXWec+9jgDfqO2AtArEqHO5R2aeayp5H5OYLr5UYDVGsVaZPEFUooMhYCdz5A==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.63.1.tgz",
+ "integrity": "sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.63.1.tgz",
+ "integrity": "sha512-4h6XqthmB4Hspji84wvgk+ElodTsGj+dbZqHJHHtKxj4mYq0ANSEEPX9ys3moJueqsRjwpaJYH7874Itwnj2ow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.63.1.tgz",
+ "integrity": "sha512-dlfCOa87o1VAYegLQ9EKilx2JCeRofiyPGhTCmqnuXZ6bMPiycO1rq1+sKoulAp7pGLIsTIw+1x5R+zgh5LhhA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.63.1.tgz",
+ "integrity": "sha512-cjkLbOlfcm3QGhMM1J5zaZjsw1GggbN6rw9UTSSRrPrR1KkcXnN7Uq9rPw34xImQ9VOY9GN+6u2Zj80B9ptkcw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.63.1.tgz",
+ "integrity": "sha512-Li1KdUnWGE4N3e1F/B4RTB1ms+nG4WBgjByO46pkeBVX/2UBsY53xf5vK9WygVmnH3RwncIST7lkSdLSY6P9lg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.63.1.tgz",
+ "integrity": "sha512-t4ZYOSoLTgwhuFMrmTMLx/+i1DQVK7HYqMc6kY46EApwi8X0nIVphzdNoThU3xt6n+N5urG1/gxBdCaKDLavfg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.63.1.tgz",
+ "integrity": "sha512-RgroPfMmKlD1RzSDxvwgcPiy2HNQKoYV7OmwIXDsk73uKW5t6B/V8KIy27SMv/FNXFo/oSBtWc9J0X7t91ezZg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.63.1.tgz",
+ "integrity": "sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@types/babel__core": {
+ "version": "7.20.5",
+ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
+ "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.20.7",
+ "@babel/types": "^7.20.7",
+ "@types/babel__generator": "*",
+ "@types/babel__template": "*",
+ "@types/babel__traverse": "*"
+ }
+ },
+ "node_modules/@types/babel__generator": {
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",
+ "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.0.0"
+ }
+ },
+ "node_modules/@types/babel__template": {
+ "version": "7.4.4",
+ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
+ "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.1.0",
+ "@babel/types": "^7.0.0"
+ }
+ },
+ "node_modules/@types/babel__traverse": {
+ "version": "7.28.0",
+ "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
+ "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.28.2"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/react": {
+ "version": "19.2.18",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz",
+ "integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "csstype": "^3.2.2"
+ }
+ },
+ "node_modules/@types/react-dom": {
+ "version": "19.2.5",
+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.5.tgz",
+ "integrity": "sha512-fMPwH9v7r/pp43yUd2/Mbiex5KouJwwR3dzHkhLREUC6764VyDsqxhAxv6OFEYR1RhjOyD1naqba8ECDBe7ZQg==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "^19.2.0"
+ }
+ },
+ "node_modules/@vitejs/plugin-react": {
+ "version": "4.7.0",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
+ "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/core": "^7.28.0",
+ "@babel/plugin-transform-react-jsx-self": "^7.27.1",
+ "@babel/plugin-transform-react-jsx-source": "^7.27.1",
+ "@rolldown/pluginutils": "1.0.0-beta.27",
+ "@types/babel__core": "^7.20.5",
+ "react-refresh": "^0.17.0"
+ },
+ "engines": {
+ "node": "^14.18.0 || >=16.0.0"
+ },
+ "peerDependencies": {
+ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
+ }
+ },
+ "node_modules/baseline-browser-mapping": {
+ "version": "2.11.20",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.20.tgz",
+ "integrity": "sha512-H0ulySigv6icDJ1F7SjtdCD6PrhTpdYCmP0CactWy1+ekh0AFd0o1Wn5T8b+hnTmdBx19u9yhL6wvCylXMY7zw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "baseline-browser-mapping": "dist/cli.cjs"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/browserslist": {
+ "version": "4.28.8",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.8.tgz",
+ "integrity": "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "baseline-browser-mapping": "^2.11.12",
+ "caniuse-lite": "^1.0.30001809",
+ "electron-to-chromium": "^1.5.402",
+ "node-releases": "^2.0.53",
+ "update-browserslist-db": "^1.3.0"
+ },
+ "bin": {
+ "browserslist": "cli.js"
+ },
+ "engines": {
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001810",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz",
+ "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "CC-BY-4.0"
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/electron-to-chromium": {
+ "version": "1.5.417",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.417.tgz",
+ "integrity": "sha512-4T+DTDWuMPM4aHlHwWdAVCVWwp7LDilnhzkj+c/Lbj91XSQrLuOmZSLtS9Q4iIqjlPUbPOnC624zDVVHCHaolQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/esbuild": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.12",
+ "@esbuild/android-arm": "0.25.12",
+ "@esbuild/android-arm64": "0.25.12",
+ "@esbuild/android-x64": "0.25.12",
+ "@esbuild/darwin-arm64": "0.25.12",
+ "@esbuild/darwin-x64": "0.25.12",
+ "@esbuild/freebsd-arm64": "0.25.12",
+ "@esbuild/freebsd-x64": "0.25.12",
+ "@esbuild/linux-arm": "0.25.12",
+ "@esbuild/linux-arm64": "0.25.12",
+ "@esbuild/linux-ia32": "0.25.12",
+ "@esbuild/linux-loong64": "0.25.12",
+ "@esbuild/linux-mips64el": "0.25.12",
+ "@esbuild/linux-ppc64": "0.25.12",
+ "@esbuild/linux-riscv64": "0.25.12",
+ "@esbuild/linux-s390x": "0.25.12",
+ "@esbuild/linux-x64": "0.25.12",
+ "@esbuild/netbsd-arm64": "0.25.12",
+ "@esbuild/netbsd-x64": "0.25.12",
+ "@esbuild/openbsd-arm64": "0.25.12",
+ "@esbuild/openbsd-x64": "0.25.12",
+ "@esbuild/openharmony-arm64": "0.25.12",
+ "@esbuild/sunos-x64": "0.25.12",
+ "@esbuild/win32-arm64": "0.25.12",
+ "@esbuild/win32-ia32": "0.25.12",
+ "@esbuild/win32-x64": "0.25.12"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/gensync": {
+ "version": "1.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/jsesc": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "jsesc": "bin/jsesc"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/json5": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "json5": "lib/cli.js"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "yallist": "^3.0.2"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.18",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
+ "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/node-releases": {
+ "version": "2.0.54",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.54.tgz",
+ "integrity": "sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.26",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
+ "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.17",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/react": {
+ "version": "19.2.8",
+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
+ "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "19.2.8",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
+ "integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
+ "license": "MIT",
+ "dependencies": {
+ "scheduler": "^0.27.0"
+ },
+ "peerDependencies": {
+ "react": "^19.2.8"
+ }
+ },
+ "node_modules/react-refresh": {
+ "version": "0.17.0",
+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
+ "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/rollup": {
+ "version": "4.63.1",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz",
+ "integrity": "sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.9"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",
+ "@rollup/rollup-android-arm-eabi": "4.63.1",
+ "@rollup/rollup-android-arm64": "4.63.1",
+ "@rollup/rollup-darwin-arm64": "4.63.1",
+ "@rollup/rollup-darwin-x64": "4.63.1",
+ "@rollup/rollup-freebsd-arm64": "4.63.1",
+ "@rollup/rollup-freebsd-x64": "4.63.1",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.63.1",
+ "@rollup/rollup-linux-arm-musleabihf": "4.63.1",
+ "@rollup/rollup-linux-arm64-gnu": "4.63.1",
+ "@rollup/rollup-linux-arm64-musl": "4.63.1",
+ "@rollup/rollup-linux-loong64-gnu": "4.63.1",
+ "@rollup/rollup-linux-loong64-musl": "4.63.1",
+ "@rollup/rollup-linux-ppc64-gnu": "4.63.1",
+ "@rollup/rollup-linux-ppc64-musl": "4.63.1",
+ "@rollup/rollup-linux-riscv64-gnu": "4.63.1",
+ "@rollup/rollup-linux-riscv64-musl": "4.63.1",
+ "@rollup/rollup-linux-s390x-gnu": "4.63.1",
+ "@rollup/rollup-linux-x64-gnu": "4.63.1",
+ "@rollup/rollup-linux-x64-musl": "4.63.1",
+ "@rollup/rollup-openbsd-x64": "4.63.1",
+ "@rollup/rollup-openharmony-arm64": "4.63.1",
+ "@rollup/rollup-win32-arm64-msvc": "4.63.1",
+ "@rollup/rollup-win32-ia32-msvc": "4.63.1",
+ "@rollup/rollup-win32-x64-gnu": "4.63.1",
+ "@rollup/rollup-win32-x64-msvc": "4.63.1",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/scheduler": {
+ "version": "0.27.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
+ "license": "MIT"
+ },
+ "node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/update-browserslist-db": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.2.tgz",
+ "integrity": "sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "escalade": "^3.2.0",
+ "picocolors": "^1.1.1"
+ },
+ "bin": {
+ "update-browserslist-db": "cli.js"
+ },
+ "peerDependencies": {
+ "browserslist": ">= 4.21.0"
+ }
+ },
+ "node_modules/vite": {
+ "version": "6.4.3",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
+ "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.25.0",
+ "fdir": "^6.4.4",
+ "picomatch": "^4.0.2",
+ "postcss": "^8.5.3",
+ "rollup": "^4.34.9",
+ "tinyglobby": "^0.2.13"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
+ "jiti": ">=1.21.0",
+ "less": "*",
+ "lightningcss": "^1.21.0",
+ "sass": "*",
+ "sass-embedded": "*",
+ "stylus": "*",
+ "sugarss": "*",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/yallist": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
+ "dev": true,
+ "license": "ISC"
+ }
+ }
+}
diff --git a/tools/tcmcp/web/package.json b/tools/tcmcp/web/package.json
new file mode 100644
index 00000000..93eff9c8
--- /dev/null
+++ b/tools/tcmcp/web/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "tcmcp-web",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "tsc --noEmit && vite build",
+ "preview": "vite preview"
+ },
+ "dependencies": {
+ "react": "^19.1.0",
+ "react-dom": "^19.1.0"
+ },
+ "devDependencies": {
+ "@types/react": "^19.1.0",
+ "@types/react-dom": "^19.1.0",
+ "@vitejs/plugin-react": "^4.5.0",
+ "typescript": "^5.8.0",
+ "vite": "^6.3.0"
+ }
+}
diff --git a/tools/tcmcp/web/src/App.tsx b/tools/tcmcp/web/src/App.tsx
new file mode 100644
index 00000000..9fcc3d1d
--- /dev/null
+++ b/tools/tcmcp/web/src/App.tsx
@@ -0,0 +1,818 @@
+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { createInstallation, downloadZip, fetchMetadata, fetchResources, previewSchema, type AgentClient, type Installation } from "./api";
+import { ProductCard } from "./components/ProductCard";
+import { ResourcePanel } from "./components/ResourcePanel";
+import { SchemaInspector } from "./components/SchemaInspector";
+import { resolveRegions } from "./regions";
+import { uniqueAlias } from "./slug";
+import type {
+ BoundResources,
+ Metadata,
+ Preview,
+ ResourceCatalog,
+ ResourceItem,
+ Selection,
+} from "./types";
+
+const emptyResources = (): BoundResources => ({
+ redis: [],
+ cdb: [],
+ tdsqlc: [],
+ tke: [],
+ cls: [],
+ cos: [],
+});
+
+const emptyCatalog = (): ResourceCatalog => ({
+ redis: [],
+ cdb: [],
+ tdsqlc: [],
+ tke: [],
+ cls: [],
+ cos: [],
+ errors: {},
+});
+
+const PRODUCT_ORDER = ["redis", "cdb", "tdsqlc", "tke", "cls", "cos"] as const;
+
+const PRODUCT_STEP: Record<string, { title: string; short: string }> = {
+ redis: { title: "绑定 Redis", short: "Redis" },
+ cdb: { title: "绑定 CDB", short: "CDB" },
+ tdsqlc: { title: "绑定 TDSQL-C", short: "TDSQL-C" },
+ tke: { title: "绑定 TKE", short: "TKE" },
+ cls: { title: "绑定 CLS", short: "CLS" },
+ cos: { title: "绑定 COS", short: "COS" },
+};
+
+type WizardStep = { id: string; title: string; short: string; product?: string };
+
+function buildSteps(selected: string[]): WizardStep[] {
+ const resourceSteps = PRODUCT_ORDER.filter((id) => selected.includes(id)).map((id) => ({
+ id: `res-${id}`,
+ product: id,
+ ...PRODUCT_STEP[id],
+ }));
+ return [
+ { id: "welcome", title: "开始", short: "指引" },
+ { id: "project", title: "项目配置", short: "项目" },
+ { id: "products", title: "项目与产品", short: "产品" },
+ ...resourceSteps,
+ { id: "schema", title: "MCP Schema", short: "预览" },
+ { id: "install", title: "安装与部署", short: "安装" },
+ ];
+}
+
+export function App() {
+ const [step, setStep] = useState(0);
+ const [meta, setMeta] = useState<Metadata | null>(null);
+ const [name, setName] = useState("demo");
+ const [description, setDescription] = useState("Tencent Cloud ops MCP");
+ const [target, setTarget] = useState("prod");
+ const [secretId, setSecretId] = useState("");
+ const [secretKey, setSecretKey] = useState("");
+ const [projectId, setProjectId] = useState("");
+ const [products, setProducts] = useState<string[]>([]);
+ const [disabled, setDisabled] = useState<string[]>([]);
+ const [resources, setResources] = useState<BoundResources>(emptyResources);
+ const [catalog, setCatalog] = useState<ResourceCatalog>(emptyCatalog);
+ const [productRegions, setProductRegions] = useState<Record<string, string>>({});
+ const [pulledRegions, setPulledRegions] = useState<Record<string, string[]>>({});
+ const [loadingProduct, setLoadingProduct] = useState<string | null>(null);
+ const [productErrors, setProductErrors] = useState<Record<string, string>>({});
+ const [error, setError] = useState("");
+ const [preview, setPreview] = useState<Preview | null>(null);
+ const [mode, setMode] = useState<"grouped" | "flat">("grouped");
+ const [genError, setGenError] = useState("");
+ const [generating, setGenerating] = useState(false);
+ const [downloaded, setDownloaded] = useState(false);
+ const [installation, setInstallation] = useState<Installation | null>(null);
+ const [agentClient, setAgentClient] = useState<AgentClient>("codebuddy");
+ const [copiedInstall, setCopiedInstall] = useState(false);
+ const [installCopyError, setInstallCopyError] = useState("");
+ const [copied, setCopied] = useState(false);
+ const [copiedDocker, setCopiedDocker] = useState(false);
+ const [copiedHttp, setCopiedHttp] = useState(false);
+ const [authToken] = useState(() => newAuthToken());
+
+ const region = useMemo(() => fallbackRegion(resources, productRegions), [resources, productRegions]);
+
+ const selection: Selection = useMemo(
+ () => ({
+ project: { name, description, target, region },
+ products,
+ disabled_tools: disabled,
+ resources,
+ }),
+ [name, description, target, region, products, disabled, resources],
+ );
+ const latestSelection = useRef(selection);
+ latestSelection.current = selection;
+
+ useEffect(() => {
+ fetchMetadata().then(setMeta).catch((e) => setError(String(e)));
+ }, []);
+
+ useEffect(() => {
+ setInstallation(null);
+ setDownloaded(false);
+ setCopiedInstall(false);
+ }, [selection]);
+
+ useEffect(() => {
+ const handle = setTimeout(() => {
+ previewSchema(selection).then(setPreview).catch(() => setPreview(null));
+ }, 200);
+ return () => clearTimeout(handle);
+ }, [selection]);
+
+ function toggleProduct(id: string) {
+ setProducts((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
+ }
+
+ function toggleTool(toolName: string) {
+ setDisabled((prev) => (prev.includes(toolName) ? prev.filter((x) => x !== toolName) : [...prev, toolName]));
+ }
+
+ function setProductRegion(product: string, rid: string) {
+ setProductRegions((prev) => ({ ...prev, [product]: rid }));
+ }
+
+ async function onFetchProduct(product: string, fetchRegion: string) {
+ if (!fetchRegion) {
+ setProductErrors((prev) => ({ ...prev, [product]: "先选一个地域再拉取。" }));
+ return;
+ }
+ setProductErrors((prev) => ({ ...prev, [product]: "" }));
+ setLoadingProduct(product);
+ try {
+ const pid = projectId.trim() ? Number(projectId) : null;
+ const data = await fetchResources({
+ secretId,
+ secretKey,
+ region: fetchRegion,
+ projectId: Number.isFinite(pid as number) ? pid : null,
+ products: [product],
+ });
+ setCatalog((prev) => mergeCatalog(prev, data, product, fetchRegion));
+ setPulledRegions((prev) => {
+ const cur = prev[product] || [];
+ return { ...prev, [product]: cur.includes(fetchRegion) ? cur : [...cur, fetchRegion] };
+ });
+ if (data.errors[product]) {
+ setProductErrors((prev) => ({ ...prev, [product]: `${fetchRegion}: ${data.errors[product]}` }));
+ }
+ } catch (e) {
+ setProductErrors((prev) => ({ ...prev, [product]: `${fetchRegion}: ${e}` }));
+ } finally {
+ setLoadingProduct(null);
+ }
+ }
+
+ function onAddSimple(
+ kind: "redis" | "cdb" | "tke" | "cos",
+ items: { id: string; name: string; region: string; extra?: Record<string, unknown> }[],
+ ) {
+ setResources((prev) => {
+ const used = aliasesOf(prev);
+ const list = [...prev[kind]];
+ for (const item of items) {
+ if (list.some((x) => x.id === item.id)) continue;
+ const next: ResourceItem = {
+ id: item.id,
+ alias: uniqueAlias(item.name || item.id, used),
+ name: item.name,
+ region: item.region,
+ extra: item.extra,
+ };
+ list.push(next);
+ }
+ return { ...prev, [kind]: list };
+ });
+ }
+
+ function onRemoveSimple(kind: "redis" | "cdb" | "tke" | "cos", id: string) {
+ setResources((prev) => ({ ...prev, [kind]: prev[kind].filter((x) => x.id !== id) }));
+ }
+
+ function onAddTdsqlc(items: { clusterId: string; instanceId: string; name: string; region: string }[]) {
+ setResources((prev) => {
+ const used = aliasesOf(prev);
+ const list = [...prev.tdsqlc];
+ for (const item of items) {
+ if (list.some((x) => x.clusterId === item.clusterId)) continue;
+ list.push({
+ clusterId: item.clusterId,
+ instanceId: item.instanceId,
+ alias: uniqueAlias(item.name || item.clusterId, used),
+ name: item.name,
+ region: item.region,
+ });
+ }
+ return { ...prev, tdsqlc: list };
+ });
+ }
+
+ function onRemoveTdsqlc(clusterId: string) {
+ setResources((prev) => ({ ...prev, tdsqlc: prev.tdsqlc.filter((x) => x.clusterId !== clusterId) }));
+ }
+
+ function onAddTopics(
+ items: { logsetId: string; logsetName: string; topicId: string; topicName: string; region: string }[],
+ ) {
+ setResources((prev) => {
+ const used = aliasesOf(prev);
+ const cls = prev.cls.map((ls) => ({ ...ls, topics: [...ls.topics] }));
+ for (const item of items) {
+ let logset = cls.find((x) => x.logsetId === item.logsetId);
+ if (!logset) {
+ logset = { logsetId: item.logsetId, logsetName: item.logsetName, region: item.region, topics: [] };
+ cls.push(logset);
+ }
+ if (logset.topics.some((t) => t.id === item.topicId)) continue;
+ logset.topics.push({
+ id: item.topicId,
+ alias: uniqueAlias(item.topicName || item.topicId, used),
+ name: item.topicName,
+ });
+ }
+ return { ...prev, cls };
+ });
+ }
+
+ function onRemoveTopic(logsetId: string, topicId: string) {
+ setResources((prev) => ({
+ ...prev,
+ cls: prev.cls
+ .map((ls) =>
+ ls.logsetId === logsetId ? { ...ls, topics: ls.topics.filter((t) => t.id !== topicId) } : ls,
+ )
+ .filter((ls) => ls.topics.length > 0),
+ }));
+ }
+
+ function onAlias(kind: string, id: string, alias: string, logsetId?: string) {
+ setResources((prev) => {
+ if (kind === "redis" || kind === "cdb" || kind === "tke" || kind === "cos") {
+ return { ...prev, [kind]: prev[kind].map((r) => (r.id === id ? { ...r, alias } : r)) };
+ }
+ if (kind === "tdsqlc") {
+ return { ...prev, tdsqlc: prev.tdsqlc.map((r) => (r.clusterId === id ? { ...r, alias } : r)) };
+ }
+ return {
+ ...prev,
+ cls: prev.cls.map((ls) =>
+ ls.logsetId === logsetId
+ ? { ...ls, topics: ls.topics.map((t) => (t.id === id ? { ...t, alias } : t)) }
+ : ls,
+ ),
+ };
+ });
+ }
+
+ async function onGenerate(advance: boolean) {
+ setGenError("");
+ setDownloaded(false);
+ setCopied(false);
+ setGenerating(true);
+ try {
+ const result = await createInstallation(selection);
+ if (latestSelection.current !== selection) {
+ setGenError("选择已变化,请重新生成安装命令。");
+ return;
+ }
+ setInstallation(result);
+ setCopiedInstall(false);
+ setDownloaded(true);
+ if (advance) setStep((currentStep) => currentStep + 1);
+ } catch (e) {
+ setGenError(String(e));
+ } finally {
+ setGenerating(false);
+ }
+ }
+
+ const counts = preview?.counts;
+ const installCommand = installation
+ ? `curl -fsSL '${new URL(installation.paths[agentClient], window.location.origin).href.replace(/'/g, "%27")}' | bash`
+ : "";
+
+ async function copyInstallCommand() {
+ setInstallCopyError("");
+ try {
+ await copyText(installCommand);
+ setCopiedInstall(true);
+ } catch {
+ setInstallCopyError("复制失败,请手动选择下方命令复制。");
+ }
+ }
+
+ async function downloadProject() {
+ setGenError("");
+ try {
+ await downloadZip(selection);
+ } catch (e) {
+ setGenError(String(e));
+ }
+ }
+ const slug = projectSlug(name);
+ const mcpConfigPreview = mcpSnippet(slug, "填写 SecretId", "填写 SecretKey");
+ const mcpConfigCopy = mcpSnippet(slug, secretId.trim() || "填写 SecretId", secretKey.trim() || "填写 SecretKey");
+ const dockerCommandsPreview = dockerRunSnippet(slug);
+ const dockerCommandsCopy = dockerRunSnippet(slug, {
+ secretId: secretId.trim(),
+ secretKey: secretKey.trim(),
+ authToken,
+ });
+ const httpMcpPreview = httpMcpSnippet(slug, "填写 TCMCP_AUTH_TOKEN");
+ const httpMcpCopy = httpMcpSnippet(slug, authToken);
+
+ async function copyMcpConfig() {
+ try {
+ await copyText(mcpConfigCopy);
+ setCopied(true);
+ } catch {
+ setCopied(false);
+ }
+ }
+
+ async function copyDockerCommands() {
+ try {
+ await copyText(`${dockerCommandsCopy}\n\n${httpMcpCopy}`);
+ setCopiedDocker(true);
+ } catch {
+ setCopiedDocker(false);
+ }
+ }
+
+ async function copyHttpMcp() {
+ try {
+ await copyText(httpMcpCopy);
+ setCopiedHttp(true);
+ } catch {
+ setCopiedHttp(false);
+ }
+ }
+
+ const productToolCount = (id: string) =>
+ (preview?.grouped[id] ?? []).filter((t) => t.ready && t.enabled).length;
+
+ const steps = useMemo(() => buildSteps(products), [products]);
+ const current = steps[Math.min(step, steps.length - 1)] ?? steps[0];
+ const resourceProduct = current.product;
+ const schemaIndex = steps.findIndex((s) => s.id === "schema");
+ const canNext =
+ current.id === "welcome"
+ ? true
+ : current.id === "project"
+ ? Boolean(name.trim() && target.trim())
+ : current.id === "products"
+ ? products.length > 0
+ : true;
+
+ useEffect(() => {
+ if (step >= steps.length) {
+ setStep(steps.length - 1);
+ return;
+ }
+ if (current.id.startsWith("res-") && current.product && !products.includes(current.product)) {
+ const idx = steps.findIndex((s) => s.id === "products");
+ setStep(idx >= 0 ? idx : 0);
+ }
+ }, [current.id, current.product, products, step, steps]);
+
+ function next() {
+ if (!canNext) return;
+ setStep((s) => Math.min(s + 1, steps.length - 1));
+ }
+ function back() {
+ setStep((s) => Math.max(s - 1, 0));
+ }
+
+ return (
+ <div className="app">
+ <header className="topbar">
+ <div className="brand">
+ <span className="logo" aria-hidden>
+ <span />
+ </span>
+ <div>
+ <h1>Tencent Cloud MCP Initializr</h1>
+ <span>安装向导 · 按产品与资源生成 MCP 项目</span>
+ </div>
+ </div>
+ <div className="status">
+ <span className="stat">
+ <em>{counts?.products ?? products.length}</em> products
+ </span>
+ <span className="stat">
+ <em>{counts?.resources ?? 0}</em> resources
+ </span>
+ <span className={`stat${preview?.warn ? " warn" : ""}`}>
+ <em>{counts?.tools ?? 0}</em>
+ {preview ? `/${preview.tools.length + preview.skipped.length}` : ""} tools
+ </span>
+ </div>
+ </header>
+
+ <ol className="stepper" aria-label="安装步骤">
+ {steps.map((s, i) => (
+ <li key={s.id} className={i === step ? "on" : i < step ? "done" : ""}>
+ <button
+ type="button"
+ onClick={() => (i <= step || (downloaded && s.id === "install")) && setStep(i)}
+ disabled={i > step && !(downloaded && s.id === "install")}
+ >
+ <span className="num">{i < step ? "✓" : i + 1}</span>
+ <span className="lab">{s.short}</span>
+ </button>
+ </li>
+ ))}
+ </ol>
+
+ {preview?.warn && step >= schemaIndex ? <div className="warn-banner">{preview.warnMessage}</div> : null}
+
+ <main className="wizard">
+ <div className={`sheet${["schema", "install"].includes(current.id) || current.id.startsWith("res-") ? " wide" : ""}`}>
+ {error ? <div className="err">{error}</div> : null}
+ {current.id === "welcome" ? (
+ <section className="intro">
+ <p className="eyebrow">安装向导</p>
+ <h2>一步一个产品,生成精简的运维 MCP</h2>
+ <p className="lead">
+ 只把你勾选的产品和云资源打进项目。资源 ID 写在配置里,模型只能看到别名,避免工具太多产生幻觉。
+ </p>
+ <ul className="guide">
+ <li>
+ <strong>1. 项目配置</strong>
+ <span>名称和环境别名</span>
+ </li>
+ <li>
+ <strong>2. 项目与产品</strong>
+ <span>选择 Redis / CDB / TDSQL-C / TKE / CLS</span>
+ </li>
+ <li>
+ <strong>3. 云资源绑定</strong>
+ <span>每个产品单独一步:拉取后点击资源即可绑定</span>
+ </li>
+ <li>
+ <strong>4. MCP Schema</strong>
+ <span>预览工具,生成一键安装命令</span>
+ </li>
+ </ul>
+ </section>
+ ) : null}
+
+ {current.id === "project" ? (
+ <section>
+ <h2>项目配置</h2>
+ <p className="hint">这些信息会出现在生成项目的 README 和 mcp.json 里。</p>
+ <div className="grid-2">
+ <Field label="项目名">
+ <input value={name} onChange={(e) => setName(e.target.value)} />
+ </Field>
+ <Field label="环境别名 target">
+ <input className="mono" value={target} onChange={(e) => setTarget(e.target.value)} />
+ </Field>
+ </div>
+ <Field label="说明">
+ <input value={description} onChange={(e) => setDescription(e.target.value)} />
+ </Field>
+ <div className="callout">
+ 下一步会填写云 API 密钥。密钥只用于当次拉取资源,<strong>不会写入 zip、也不会落盘</strong>。
+ </div>
+ <div className="grid-2">
+ <Field label="SecretId">
+ <input value={secretId} onChange={(e) => setSecretId(e.target.value)} autoComplete="off" spellCheck={false} />
+ </Field>
+ <Field label="SecretKey">
+ <input type="password" value={secretKey} onChange={(e) => setSecretKey(e.target.value)} autoComplete="off" />
+ </Field>
+ </div>
+ <Field label="云项目 ProjectId(可选过滤)">
+ <input value={projectId} onChange={(e) => setProjectId(e.target.value)} placeholder="留空则不过滤" />
+ </Field>
+ </section>
+ ) : null}
+
+ {current.id === "products" ? (
+ <section>
+ <h2>项目与产品</h2>
+ <p className="hint">只勾选这个 MCP 真正需要的产品。选得越少,模型越不容易用错工具。工具会在下一步绑定资源后才写入 zip,现在看到「待绑定」是正常的。</p>
+ <div className="product-grid">
+ {(meta?.products ?? []).map((p) => (
+ <ProductCard
+ key={p.id}
+ product={p}
+ on={products.includes(p.id)}
+ toolCount={productToolCount(p.id)}
+ onToggle={() => toggleProduct(p.id)}
+ />
+ ))}
+ </div>
+ {!products.length ? <p className="field-err">至少选择一个产品才能继续。</p> : null}
+ </section>
+ ) : null}
+
+ {resourceProduct ? (
+ <section>
+ <h2>{current.title}</h2>
+ <p className="hint">选一个地域拉取,点击左侧资源即可绑定;换一个地域再拉、再点。右侧是已经绑定的全部资源。</p>
+ {!secretId || !secretKey ? (
+ <div className="callout">还没填 SecretId / SecretKey。请回到「项目配置」补上,否则无法拉取。</div>
+ ) : null}
+ <ResourcePanel
+ products={[resourceProduct]}
+ productMeta={meta?.products ?? []}
+ regions={resolveRegions(meta?.regions)}
+ productRegions={productRegions}
+ pulledRegions={pulledRegions}
+ catalog={catalog}
+ bound={resources}
+ loadingProduct={loadingProduct}
+ productErrors={productErrors}
+ onRegion={setProductRegion}
+ onFetchProduct={onFetchProduct}
+ onAddSimple={onAddSimple}
+ onRemoveSimple={onRemoveSimple}
+ onAddTdsqlc={onAddTdsqlc}
+ onRemoveTdsqlc={onRemoveTdsqlc}
+ onAddTopics={onAddTopics}
+ onRemoveTopic={onRemoveTopic}
+ onAlias={onAlias}
+ />
+ </section>
+ ) : null}
+
+ {current.id === "schema" ? (
+ <section>
+ <h2>MCP Schema</h2>
+ <p className="hint">这里就是生成后模型看到的 tools/list。关掉不需要的工具,enum 来自你绑定的别名。</p>
+ <SchemaInspector preview={preview} mode={mode} onMode={setMode} onToggleTool={toggleTool} />
+ </section>
+ ) : null}
+
+ {current.id === "install" && downloaded ? (
+ <section>
+ <p className="eyebrow">生成成功</p>
+ <h2>安装与部署</h2>
+ <p className="hint">选择你的客户端,复制命令到终端运行,即可自动下载项目、安装依赖并配置 MCP。</p>
+
+ {installation ? (
+ <div className="download-help one-click-install">
+ <div className="download-help-head">
+ <div>
+ <strong>一键安装到本机</strong>
+ <p>支持 macOS / Linux,需要 Python 3.11+。保留其他 MCP 服务,生成配置快照和一键回滚脚本。</p>
+ </div>
+ <button className="btn primary" type="button" onClick={copyInstallCommand}>
+ {copiedInstall ? "已复制" : "复制安装命令"}
+ </button>
+ </div>
+ <Field label="Agent 客户端">
+ <select value={agentClient} onChange={(e) => { setAgentClient(e.target.value as AgentClient); setCopiedInstall(false); }}>
+ <option value="cursor">Cursor</option>
+ <option value="codebuddy">CodeBuddy</option>
+ <option value="codex">Codex</option>
+ <option value="workbuddy">WorkBuddy</option>
+ </select>
+ </Field>
+ <pre>{installCommand}</pre>
+ {installCopyError ? <p className="field-err">{installCopyError}</p> : null}
+ <p>运行时在终端输入 SecretId / SecretKey,输入和粘贴内容会正常显示。密钥仅保存在本机客户端配置中。安装后刷新 MCP 或重启客户端。</p>
+ <p>安装 ID:<code>{installation.id}</code> · 有效期至 {new Date(installation.expiresAt * 1000).toLocaleString()}。链接包含所选资源,请仅分享给可信人员。</p>
+ <button className="btn" type="button" onClick={downloadProject}>下载 ZIP(手动安装 / Docker)</button>
+ </div>
+ ) : null}
+
+ <details>
+ <summary>手动安装与 Docker 部署</summary>
+ <div className="install-grid">
+ <div className="download-help">
+ <div className="download-help-head">
+ <div>
+ <strong>方式一:接入 Cursor</strong>
+ <p>启动器会检查 Python 3.11+,首次连接自动创建环境和安装依赖。点复制会带上刚才填写的密钥。</p>
+ </div>
+ <button className="btn" type="button" onClick={copyMcpConfig}>
+ {copied ? "已复制" : "复制配置"}
+ </button>
+ </div>
+ <ol>
+ <li>解压 zip,并把下方路径改成解压目录的绝对路径。</li>
+ <li>将配置加入 <code>~/.cursor/mcp.json</code> 或项目的 <code>.cursor/mcp.json</code>。</li>
+ <li>粘贴后把路径改成实际目录,刷新 MCP。密钥已写入复制内容,无需再填。</li>
+ </ol>
+ <pre>{mcpConfigPreview}</pre>
+ </div>
+
+ <div className="deploy-help">
+ <div className="download-help-head">
+ <div>
+ <strong>方式二:Docker Server</strong>
+ <p>
+ HTTP 强制 Bearer 鉴权。没有 <code>TCMCP_AUTH_TOKEN</code> 容器起不来。
+ 下面 token 是本次生成的,复制命令会带上密钥和 token。
+ </p>
+ </div>
+ <button className="btn" type="button" onClick={copyDockerCommands}>
+ {copiedDocker ? "已复制" : "复制启动命令"}
+ </button>
+ </div>
+ <ol>
+ <li>解压后在项目目录构建镜像。</li>
+ <li>用环境变量注入云 API 密钥和 <code>TCMCP_AUTH_TOKEN</code>。</li>
+ <li>Cursor 用下方 HTTP 配置连接 <code>http://127.0.0.1:8099/mcp</code>。</li>
+ </ol>
+ <pre>{dockerCommandsPreview}</pre>
+ <div className="download-help-head" style={{ marginTop: 12 }}>
+ <p>Cursor 连 Docker HTTP(鉴权头)</p>
+ <button className="btn" type="button" onClick={copyHttpMcp}>
+ {copiedHttp ? "已复制" : "复制 HTTP 配置"}
+ </button>
+ </div>
+ <pre>{httpMcpPreview}</pre>
+ <p>
+ <code>/healthz</code> 不鉴权;<code>/mcp</code> 必须
+ <code> Authorization: Bearer &lt;token&gt;</code>。
+ 生产环境放在 TLS 网关后面,并轮换 token。
+ </p>
+ </div>
+ </div>
+ <p className="secret-note">密钥只通过环境变量注入,不要写进 config.yaml、Dockerfile 或提交到 Git。</p>
+ </details>
+ </section>
+ ) : null}
+
+ <footer className="wizard-foot">
+ <button className="btn" type="button" onClick={back} disabled={step === 0}>
+ 上一步
+ </button>
+ <div className="foot-right">
+ {current.id === "schema" ? (
+ <>
+ <span className="ready-count">{preview?.registered.length ?? 0} 个工具将安装到客户端</span>
+ <button
+ className="btn primary"
+ type="button"
+ disabled={!products.length || generating}
+ onClick={() => onGenerate(true)}
+ >
+ {generating ? "生成中…" : "生成安装命令"}
+ </button>
+ </>
+ ) : current.id === "install" ? (
+ <button className="btn primary" type="button" disabled={generating} onClick={() => onGenerate(false)}>
+ {generating ? "生成中…" : "重新生成安装命令"}
+ </button>
+ ) : (
+ <button className="btn primary" type="button" disabled={!canNext} onClick={next}>
+ {current.id === "welcome" ? "开始配置" : "下一步"}
+ </button>
+ )}
+ {genError ? <div className="err">{genError}</div> : null}
+ </div>
+ </footer>
+ </div>
+ </main>
+ </div>
+ );
+}
+
+function mergeCatalog(
+ prev: ResourceCatalog,
+ incoming: ResourceCatalog,
+ product: string,
+ region: string,
+): ResourceCatalog {
+ const next: ResourceCatalog = { ...prev, errors: { ...prev.errors, ...incoming.errors } };
+ if (product === "cls") {
+ const keep = prev.cls.filter((ls) => (ls.region || "") !== region);
+ next.cls = [...keep, ...incoming.cls.map((ls) => ({ ...ls, region: ls.region || region }))];
+ return next;
+ }
+ const key = product as "redis" | "cdb" | "tdsqlc" | "tke" | "cos";
+ const keep = (prev[key] ?? []).filter((item) => (item.region || "") !== region);
+ next[key] = [...keep, ...(incoming[key] ?? []).map((item) => ({ ...item, region: item.region || region }))];
+ return next;
+}
+
+function fallbackRegion(res: BoundResources, productRegions: Record<string, string>): string {
+ for (const list of [res.redis, res.cdb, res.tke, res.cos]) {
+ for (const item of list) if (item.region) return item.region;
+ }
+ for (const item of res.tdsqlc) if (item.region) return item.region;
+ for (const ls of res.cls) if (ls.region) return ls.region;
+ for (const id of Object.values(productRegions)) {
+ if (id) return id;
+ }
+ return "ap-guangzhou";
+}
+
+function aliasesOf(res: BoundResources): Set<string> {
+ const used = new Set<string>();
+ for (const r of res.redis) used.add(r.alias);
+ for (const r of res.cdb) used.add(r.alias);
+ for (const r of res.tdsqlc) used.add(r.alias);
+ for (const r of res.tke) used.add(r.alias);
+ for (const r of res.cos) used.add(r.alias);
+ for (const ls of res.cls) for (const t of ls.topics) used.add(t.alias);
+ return used;
+}
+
+function projectSlug(value: string): string {
+ return value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^[-._]+|[-._]+$/g, "") || "tcmcp-project";
+}
+
+function mcpSnippet(slug: string, secretId: string, secretKey: string): string {
+ return JSON.stringify(
+ {
+ mcpServers: {
+ [slug]: {
+ command: "/bin/bash",
+ args: [`/absolute/path/to/${slug}/run.sh`],
+ env: {
+ TENCENT_SECRET_ID: secretId,
+ TENCENT_SECRET_KEY: secretKey,
+ },
+ },
+ },
+ },
+ null,
+ 2,
+ );
+}
+
+function httpMcpSnippet(slug: string, token: string): string {
+ return JSON.stringify(
+ {
+ mcpServers: {
+ [`${slug}-http`]: {
+ url: "http://127.0.0.1:8099/mcp",
+ headers: { Authorization: `Bearer ${token}` },
+ },
+ },
+ },
+ null,
+ 2,
+ );
+}
+
+function dockerRunSnippet(
+ slug: string,
+ filled?: { secretId: string; secretKey: string; authToken: string },
+): string {
+ const sid = filled?.secretId ? `'${filled.secretId}'` : "";
+ const skey = filled?.secretKey ? `'${filled.secretKey}'` : "";
+ const token = filled?.authToken ? `'${filled.authToken}'` : "";
+ const env = filled
+ ? `-e TENCENT_SECRET_ID=${sid} \\
+ -e TENCENT_SECRET_KEY=${skey} \\
+ -e TCMCP_AUTH_TOKEN=${token} \\`
+ : `-e TENCENT_SECRET_ID \\
+ -e TENCENT_SECRET_KEY \\
+ -e TCMCP_AUTH_TOKEN \\`;
+ return `cd /absolute/path/to/${slug}
+docker build -t ${slug} .
+docker run --rm -p 127.0.0.1:8099:8099 \\
+ ${env}
+ ${slug}`;
+}
+
+async function copyText(text: string): Promise<void> {
+ if (navigator.clipboard?.writeText && window.isSecureContext) {
+ await navigator.clipboard.writeText(text);
+ return;
+ }
+
+ const textarea = document.createElement("textarea");
+ textarea.value = text;
+ textarea.setAttribute("readonly", "");
+ textarea.style.position = "fixed";
+ textarea.style.left = "-9999px";
+ textarea.style.top = "0";
+ document.body.appendChild(textarea);
+ try {
+ textarea.focus();
+ textarea.select();
+ textarea.setSelectionRange(0, text.length);
+ const copied = document.execCommand("copy");
+ if (!copied) throw new Error("copy failed");
+ } finally {
+ document.body.removeChild(textarea);
+ }
+}
+
+function newAuthToken(): string {
+ const bytes = new Uint8Array(24);
+ crypto.getRandomValues(bytes);
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+function Field({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <label className="field-block">
+ <span>{label}</span>
+ {children}
+ </label>
+ );
+}
diff --git a/tools/tcmcp/web/src/api.ts b/tools/tcmcp/web/src/api.ts
new file mode 100644
index 00000000..4e7ee2c5
--- /dev/null
+++ b/tools/tcmcp/web/src/api.ts
@@ -0,0 +1,62 @@
+import type { Metadata, Preview, ResourceCatalog, Selection } from "./types";
+
+export type AgentClient = "cursor" | "codebuddy" | "codex" | "workbuddy";
+export type Installation = { id: string; expiresAt: number; paths: Record<AgentClient, string> };
+
+export async function createInstallation(selection: Selection): Promise<Installation> {
+ const res = await fetch("/api/installations", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(selection),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json();
+}
+
+export async function fetchMetadata(): Promise<Metadata> {
+ const res = await fetch("/api/metadata");
+ if (!res.ok) throw new Error(await res.text());
+ return res.json();
+}
+
+export async function fetchResources(body: {
+ secretId: string;
+ secretKey: string;
+ region: string;
+ projectId?: number | null;
+ products: string[];
+}): Promise<ResourceCatalog> {
+ const res = await fetch("/api/resources", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json();
+}
+
+export async function previewSchema(selection: Selection): Promise<Preview> {
+ const res = await fetch("/api/preview-schema", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(selection),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json();
+}
+
+export async function downloadZip(selection: Selection): Promise<void> {
+ const res = await fetch("/api/starter.zip", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(selection),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ const blob = await res.blob();
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${selection.project.name || "tcmcp"}.zip`;
+ a.click();
+ URL.revokeObjectURL(url);
+}
diff --git a/tools/tcmcp/web/src/components/ProductCard.tsx b/tools/tcmcp/web/src/components/ProductCard.tsx
new file mode 100644
index 00000000..847c9741
--- /dev/null
+++ b/tools/tcmcp/web/src/components/ProductCard.tsx
@@ -0,0 +1,53 @@
+import type { ProductMeta } from "../types";
+
+const ICONS: Record<string, string> = {
+ redis: "R",
+ cdb: "C",
+ tdsqlc: "T",
+ tke: "K",
+ cls: "L",
+};
+
+export function ProductCard({
+ product,
+ on,
+ toolCount,
+ onToggle,
+}: {
+ product: ProductMeta;
+ on: boolean;
+ toolCount: number;
+ onToggle: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ className={`product-card${on ? " on" : ""}`}
+ style={{ ["--dot" as string]: product.color }}
+ onClick={onToggle}
+ aria-pressed={on}
+ >
+ <span className="product-mark">{ICONS[product.id] ?? product.name[0]}</span>
+ <span className="product-copy">
+ <span className="product-title">
+ <strong>{product.name}</strong>
+ <span className={`count-pill${on ? " on" : ""}`}>
+ {on
+ ? toolCount > 0
+ ? `${toolCount}/${product.tools.length} 已就绪`
+ : `${product.tools.length} tools · 待绑定`
+ : `${product.tools.length} tools`}
+ </span>
+ </span>
+ <span className="product-desc">{product.description}</span>
+ </span>
+ <span className={`check${on ? " on" : ""}`} aria-hidden>
+ {on ? (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
+ <path d="M2.2 6.2 4.8 8.8 9.8 3.2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ ) : null}
+ </span>
+ </button>
+ );
+}
diff --git a/tools/tcmcp/web/src/components/ResourcePanel.tsx b/tools/tcmcp/web/src/components/ResourcePanel.tsx
new file mode 100644
index 00000000..77639f64
--- /dev/null
+++ b/tools/tcmcp/web/src/components/ResourcePanel.tsx
@@ -0,0 +1,581 @@
+import { useMemo, useState } from "react";
+import type { BoundResources, ListedLogset, ListedResource, ProductMeta, ResourceCatalog } from "../types";
+
+const TITLES: Record<string, string> = {
+ redis: "Redis",
+ cdb: "CDB",
+ tdsqlc: "TDSQL-C",
+ tke: "TKE",
+ cls: "CLS",
+ cos: "COS",
+};
+
+const COLORS: Record<string, string> = {
+ redis: "#ff6b57",
+ cdb: "#4c8dff",
+ tdsqlc: "#3dd68c",
+ tke: "#c084fc",
+ cls: "#f5b942",
+ cos: "#00a4ff",
+};
+
+type SimpleKind = "redis" | "cdb" | "tke" | "cos";
+
+function AliasInput({
+ value,
+ onChange,
+}: {
+ value: string;
+ onChange: (v: string) => void;
+}) {
+ return (
+ <input
+ className="alias"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ aria-label="资源别名"
+ />
+ );
+}
+
+function regionLabel(regions: { id: string; name: string }[], id: string) {
+ return regions.find((r) => r.id === id)?.name || id;
+}
+
+function match(q: string, ...parts: string[]) {
+ const needle = q.trim().toLowerCase();
+ if (!needle) return true;
+ return parts.some((p) => p.toLowerCase().includes(needle));
+}
+
+export function ResourcePanel({
+ products,
+ productMeta,
+ regions,
+ productRegions,
+ pulledRegions,
+ catalog,
+ bound,
+ loadingProduct,
+ productErrors,
+ onRegion,
+ onFetchProduct,
+ onAddSimple,
+ onRemoveSimple,
+ onAddTdsqlc,
+ onRemoveTdsqlc,
+ onAddTopics,
+ onRemoveTopic,
+ onAlias,
+}: {
+ products: string[];
+ productMeta: ProductMeta[];
+ regions: { id: string; name: string }[];
+ productRegions: Record<string, string>;
+ pulledRegions: Record<string, string[]>;
+ catalog: ResourceCatalog;
+ bound: BoundResources;
+ loadingProduct: string | null;
+ productErrors: Record<string, string>;
+ onRegion: (product: string, region: string) => void;
+ onFetchProduct: (product: string, region: string) => void;
+ onAddSimple: (
+ kind: SimpleKind,
+ items: { id: string; name: string; region: string; extra?: Record<string, unknown> }[],
+ ) => void;
+ onRemoveSimple: (kind: SimpleKind, id: string) => void;
+ onAddTdsqlc: (items: { clusterId: string; instanceId: string; name: string; region: string }[]) => void;
+ onRemoveTdsqlc: (clusterId: string) => void;
+ onAddTopics: (
+ items: { logsetId: string; logsetName: string; topicId: string; topicName: string; region: string }[],
+ ) => void;
+ onRemoveTopic: (logsetId: string, topicId: string) => void;
+ onAlias: (kind: string, id: string, alias: string, extra?: string) => void;
+}) {
+ const names = useMemo(() => {
+ const m: Record<string, string> = {};
+ for (const p of productMeta) m[p.id] = p.name;
+ return m;
+ }, [productMeta]);
+
+ if (!products.length) {
+ return (
+ <div className="empty-card">
+ <p className="empty">先回到上一步勾选产品。</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="product-fetch-list">
+ {products.map((id) => (
+ <ProductFetchCard
+ key={id}
+ product={id}
+ title={names[id] || TITLES[id] || id}
+ color={productMeta.find((p) => p.id === id)?.color || COLORS[id] || "#888"}
+ regions={regions}
+ region={productRegions[id] || "ap-guangzhou"}
+ pulled={pulledRegions[id] || []}
+ catalog={catalog}
+ bound={bound}
+ loading={loadingProduct === id}
+ error={productErrors[id] || ""}
+ onRegion={(r) => onRegion(id, r)}
+ onFetch={(r) => onFetchProduct(id, r)}
+ onAddSimple={onAddSimple}
+ onRemoveSimple={onRemoveSimple}
+ onAddTdsqlc={onAddTdsqlc}
+ onRemoveTdsqlc={onRemoveTdsqlc}
+ onAddTopics={onAddTopics}
+ onRemoveTopic={onRemoveTopic}
+ onAlias={onAlias}
+ />
+ ))}
+ </div>
+ );
+}
+
+function ProductFetchCard({
+ product,
+ title,
+ color,
+ regions,
+ region,
+ pulled,
+ catalog,
+ bound,
+ loading,
+ error,
+ onRegion,
+ onFetch,
+ onAddSimple,
+ onRemoveSimple,
+ onAddTdsqlc,
+ onRemoveTdsqlc,
+ onAddTopics,
+ onRemoveTopic,
+ onAlias,
+}: {
+ product: string;
+ title: string;
+ color: string;
+ regions: { id: string; name: string }[];
+ region: string;
+ pulled: string[];
+ catalog: ResourceCatalog;
+ bound: BoundResources;
+ loading: boolean;
+ error: string;
+ onRegion: (region: string) => void;
+ onFetch: (region: string) => void;
+ onAddSimple: (
+ kind: SimpleKind,
+ items: { id: string; name: string; region: string; extra?: Record<string, unknown> }[],
+ ) => void;
+ onRemoveSimple: (kind: SimpleKind, id: string) => void;
+ onAddTdsqlc: (items: { clusterId: string; instanceId: string; name: string; region: string }[]) => void;
+ onRemoveTdsqlc: (clusterId: string) => void;
+ onAddTopics: (
+ items: { logsetId: string; logsetName: string; topicId: string; topicName: string; region: string }[],
+ ) => void;
+ onRemoveTopic: (logsetId: string, topicId: string) => void;
+ onAlias: (kind: string, id: string, alias: string, extra?: string) => void;
+}) {
+ const [q, setQ] = useState("");
+ const boundCount = countBound(product, bound);
+ const fetched = pulled.includes(region);
+ const regionName = regionLabel(regions, region);
+ const known = regions.some((r) => r.id === region);
+
+ function addSimpleResource(item: ListedResource) {
+ if (product !== "redis" && product !== "cdb" && product !== "tke" && product !== "cos") return;
+ onAddSimple(product, [{ id: item.id, name: item.name, region: item.region || region, extra: item.extra }]);
+ }
+
+ function addTdsqlcResource(item: ListedResource) {
+ onAddTdsqlc([
+ {
+ clusterId: item.id,
+ instanceId: String(item.extra?.instanceId || ""),
+ name: item.name,
+ region: item.region || region,
+ },
+ ]);
+ }
+
+ function addClsTopic(ls: ListedLogset, tp: ListedLogset["topics"][number]) {
+ if (product === "cls") {
+ onAddTopics([
+ {
+ logsetId: ls.id,
+ logsetName: ls.name,
+ topicId: tp.id,
+ topicName: tp.name,
+ region: ls.region || region,
+ },
+ ]);
+ }
+ }
+
+ return (
+ <section className="fetch-card">
+ <header className="fetch-card-head">
+ <span className="dot" style={{ background: color }} />
+ <h3>{title}</h3>
+ <span className="count-pill">{boundCount} 已绑定</span>
+ </header>
+ <div className="fetch-toolbar">
+ <select
+ className="region-select"
+ value={region}
+ onChange={(e) => {
+ onRegion(e.target.value);
+ }}
+ >
+ {!known && region ? <option value={region}>{region}</option> : null}
+ {regions.map((r) => (
+ <option key={r.id} value={r.id}>
+ {r.name} · {r.id}
+ </option>
+ ))}
+ </select>
+ <button className="btn" type="button" onClick={() => onFetch(region)} disabled={loading || !region}>
+ {loading ? "拉取中…" : `拉取 ${regionName}`}
+ </button>
+ <input className="search-mini" placeholder="筛选名称 / ID" value={q} onChange={(e) => setQ(e.target.value)} />
+ </div>
+ {pulled.length ? (
+ <div className="region-chips">
+ <span className="region-chips-empty">已拉取</span>
+ {pulled.map((id) => (
+ <button
+ key={id}
+ className={`region-chip-btn${id === region ? " on" : ""}`}
+ type="button"
+ onClick={() => onRegion(id)}
+ >
+ {regionLabel(regions, id)}
+ </button>
+ ))}
+ </div>
+ ) : null}
+ {error ? <div className="err">{error}</div> : null}
+ <div className="transfer">
+ <div className="transfer-pane">
+ <h4>待选 · {regionName}</h4>
+ <div className="transfer-list">
+ {product === "cls" ? (
+ <CLSPool
+ items={catalog.cls.filter((ls) => (ls.region || "") === region)}
+ bound={bound}
+ q={q}
+ fetched={fetched}
+ onAdd={addClsTopic}
+ />
+ ) : product === "tdsqlc" ? (
+ <TDSQLCPool
+ items={catalog.tdsqlc.filter((r) => (r.region || "") === region)}
+ bound={bound}
+ q={q}
+ fetched={fetched}
+ onAdd={addTdsqlcResource}
+ />
+ ) : (
+ <SimplePool
+ kind={product as SimpleKind}
+ items={(catalog[product as SimpleKind] ?? []).filter((r) => (r.region || "") === region)}
+ bound={bound}
+ q={q}
+ fetched={fetched}
+ onAdd={addSimpleResource}
+ />
+ )}
+ </div>
+ </div>
+ <div className="transfer-mid">
+ <span className="transfer-arrow" aria-hidden>
+ →
+ </span>
+ </div>
+ <div className="transfer-pane">
+ <h4>已绑定</h4>
+ <div className="transfer-list">
+ {product === "cls" ? (
+ <CLSBound bound={bound} onAlias={onAlias} onRemove={onRemoveTopic} />
+ ) : product === "tdsqlc" ? (
+ <TDSQLCBound bound={bound} onAlias={onAlias} onRemove={onRemoveTdsqlc} />
+ ) : (
+ <SimpleBound kind={product as SimpleKind} bound={bound} onAlias={onAlias} onRemove={onRemoveSimple} />
+ )}
+ </div>
+ </div>
+ </div>
+ </section>
+ );
+}
+
+function PickRow({
+ onAdd,
+ name,
+ region,
+ meta,
+}: {
+ onAdd: () => void;
+ name: string;
+ region?: string;
+ meta: string;
+}) {
+ return (
+ <button className="res-item pick" type="button" onClick={onAdd}>
+ <span className="add-mark" aria-hidden>
+ +
+ </span>
+ <div>
+ <div className="name">
+ {name}
+ {region ? <span className="region-chip">{region}</span> : null}
+ </div>
+ <div className="meta">{meta}</div>
+ </div>
+ </button>
+ );
+}
+
+function SimplePool({
+ kind,
+ items,
+ bound,
+ q,
+ fetched,
+ onAdd,
+}: {
+ kind: SimpleKind;
+ items: ListedResource[];
+ bound: BoundResources;
+ q: string;
+ fetched: boolean;
+ onAdd: (item: ListedResource) => void;
+}) {
+ const boundIds = new Set(bound[kind].map((x) => x.id));
+ const rows = items.filter((r) => !boundIds.has(r.id) && match(q, r.name, r.id, r.region || ""));
+ if (!fetched) return <p className="empty">选好地域后点拉取,只拉这一类产品。</p>;
+ if (!rows.length) return <p className="empty">{q ? "没有匹配的资源" : "这个地域没有可添加的实例"}</p>;
+ return (
+ <>
+ {rows.map((r) => (
+ <PickRow
+ key={`${r.region}:${r.id}`}
+ onAdd={() => onAdd(r)}
+ name={r.name}
+ region={r.region}
+ meta={r.id}
+ />
+ ))}
+ </>
+ );
+}
+
+function SimpleBound({
+ kind,
+ bound,
+ onAlias,
+ onRemove,
+}: {
+ kind: SimpleKind;
+ bound: BoundResources;
+ onAlias: (kind: string, id: string, alias: string) => void;
+ onRemove: (kind: SimpleKind, id: string) => void;
+}) {
+ const rows = bound[kind];
+ if (!rows.length) return <p className="empty">点击左侧资源后会出现在这里。</p>;
+ return (
+ <>
+ {rows.map((r) => (
+ <div className="res-item bound" key={r.id}>
+ <div>
+ <div className="name">
+ {r.name}
+ {r.region ? <span className="region-chip">{r.region}</span> : null}
+ </div>
+ <div className="meta">{r.id}</div>
+ </div>
+ <AliasInput value={r.alias} onChange={(v) => onAlias(kind, r.id, v)} />
+ <button className="btn ghost" type="button" onClick={() => onRemove(kind, r.id)}>
+ 移除
+ </button>
+ </div>
+ ))}
+ </>
+ );
+}
+
+function TDSQLCPool({
+ items,
+ bound,
+ q,
+ fetched,
+ onAdd,
+}: {
+ items: ListedResource[];
+ bound: BoundResources;
+ q: string;
+ fetched: boolean;
+ onAdd: (item: ListedResource) => void;
+}) {
+ const boundIds = new Set(bound.tdsqlc.map((x) => x.clusterId));
+ const rows = items.filter(
+ (r) => !boundIds.has(r.id) && match(q, r.name, r.id, String(r.extra?.instanceId || ""), r.region || ""),
+ );
+ if (!fetched) return <p className="empty">选好地域后点拉取,只拉 TDSQL-C 集群。</p>;
+ if (!rows.length) return <p className="empty">{q ? "没有匹配的资源" : "这个地域没有可添加的集群"}</p>;
+ return (
+ <>
+ {rows.map((r) => {
+ const instanceId = String(r.extra?.instanceId || "");
+ return (
+ <PickRow
+ key={`${r.region}:${r.id}`}
+ onAdd={() => onAdd(r)}
+ name={r.name}
+ region={r.region}
+ meta={instanceId ? `${r.id} · ${instanceId}` : r.id}
+ />
+ );
+ })}
+ </>
+ );
+}
+
+function TDSQLCBound({
+ bound,
+ onAlias,
+ onRemove,
+}: {
+ bound: BoundResources;
+ onAlias: (kind: string, id: string, alias: string) => void;
+ onRemove: (clusterId: string) => void;
+}) {
+ if (!bound.tdsqlc.length) return <p className="empty">点击左侧资源后会出现在这里。</p>;
+ return (
+ <>
+ {bound.tdsqlc.map((r) => (
+ <div className="res-item bound" key={r.clusterId}>
+ <div>
+ <div className="name">
+ {r.name}
+ {r.region ? <span className="region-chip">{r.region}</span> : null}
+ </div>
+ <div className="meta">
+ {r.clusterId}
+ {r.instanceId ? ` · ${r.instanceId}` : ""}
+ </div>
+ </div>
+ <AliasInput value={r.alias} onChange={(v) => onAlias("tdsqlc", r.clusterId, v)} />
+ <button className="btn ghost" type="button" onClick={() => onRemove(r.clusterId)}>
+ 移除
+ </button>
+ </div>
+ ))}
+ </>
+ );
+}
+
+function CLSPool({
+ items,
+ bound,
+ q,
+ fetched,
+ onAdd,
+}: {
+ items: ListedLogset[];
+ bound: BoundResources;
+ q: string;
+ fetched: boolean;
+ onAdd: (logset: ListedLogset, topic: ListedLogset["topics"][number]) => void;
+}) {
+ if (!fetched) return <p className="empty">选好地域后点拉取,只拉该地域的日志集和主题。</p>;
+ const visible = items
+ .map((ls) => ({
+ ...ls,
+ topics: ls.topics.filter((tp) => {
+ const already = bound.cls.find((x) => x.logsetId === ls.id)?.topics.some((t) => t.id === tp.id);
+ if (already) return false;
+ return match(q, ls.name, ls.id, tp.name, tp.id, ls.region || "");
+ }),
+ }))
+ .filter((ls) => ls.topics.length);
+ if (!visible.length) return <p className="empty">{q ? "没有匹配的主题" : "这个地域没有可添加的日志主题"}</p>;
+ return (
+ <>
+ {visible.map((ls) => (
+ <div key={`${ls.region}:${ls.id}`} className="logset">
+ <div className="logset-head">
+ <span>
+ {ls.name}
+ {ls.region ? <span className="region-chip">{ls.region}</span> : null}
+ </span>
+ <code>{ls.id}</code>
+ </div>
+ {ls.topics.map((tp) => (
+ <PickRow
+ key={tp.id}
+ onAdd={() => onAdd(ls, tp)}
+ name={tp.name}
+ meta={tp.id}
+ />
+ ))}
+ </div>
+ ))}
+ </>
+ );
+}
+
+function CLSBound({
+ bound,
+ onAlias,
+ onRemove,
+}: {
+ bound: BoundResources;
+ onAlias: (kind: string, id: string, alias: string, extra?: string) => void;
+ onRemove: (logsetId: string, topicId: string) => void;
+}) {
+ if (!bound.cls.length) return <p className="empty">点击左侧主题后会出现在这里。</p>;
+ return (
+ <>
+ {bound.cls.map((ls) => (
+ <div key={ls.logsetId} className="logset">
+ <div className="logset-head">
+ <span>
+ {ls.logsetName}
+ {ls.region ? <span className="region-chip">{ls.region}</span> : null}
+ </span>
+ <code>{ls.logsetId}</code>
+ </div>
+ {ls.topics.map((tp) => (
+ <div className="res-item bound" key={tp.id}>
+ <div>
+ <div className="name">{tp.name}</div>
+ <div className="meta">{tp.id}</div>
+ </div>
+ <AliasInput value={tp.alias} onChange={(v) => onAlias("cls", tp.id, v, ls.logsetId)} />
+ <button className="btn ghost" type="button" onClick={() => onRemove(ls.logsetId, tp.id)}>
+ 移除
+ </button>
+ </div>
+ ))}
+ </div>
+ ))}
+ </>
+ );
+}
+
+function countBound(product: string, bound: BoundResources): number {
+ if (product === "redis") return bound.redis.length;
+ if (product === "cdb") return bound.cdb.length;
+ if (product === "tdsqlc") return bound.tdsqlc.length;
+ if (product === "tke") return bound.tke.length;
+ if (product === "cls") return bound.cls.reduce((n, ls) => n + ls.topics.length, 0);
+ if (product === "cos") return bound.cos.length;
+ return 0;
+}
diff --git a/tools/tcmcp/web/src/components/SchemaInspector.tsx b/tools/tcmcp/web/src/components/SchemaInspector.tsx
new file mode 100644
index 00000000..55ec8ea6
--- /dev/null
+++ b/tools/tcmcp/web/src/components/SchemaInspector.tsx
@@ -0,0 +1,174 @@
+import { useMemo, useState } from "react";
+import type { Preview, SchemaTool } from "../types";
+
+const LABELS: Record<string, string> = {
+ common: "Common",
+ redis: "Redis",
+ cdb: "CDB",
+ tdsqlc: "TDSQL-C",
+ tke: "TKE",
+ cls: "CLS",
+};
+
+const COLORS: Record<string, string> = {
+ common: "#8b98a5",
+ redis: "#ff6b57",
+ cdb: "#4c8dff",
+ tdsqlc: "#3dd68c",
+ tke: "#c084fc",
+ cls: "#f5b942",
+};
+
+export function SchemaInspector({
+ preview,
+ mode,
+ onMode,
+ onToggleTool,
+}: {
+ preview: Preview | null;
+ mode: "grouped" | "flat";
+ onMode: (m: "grouped" | "flat") => void;
+ onToggleTool: (name: string) => void;
+}) {
+ const [q, setQ] = useState("");
+ const [open, setOpen] = useState<Record<string, boolean>>({});
+
+ const items = useMemo(() => {
+ if (!preview) return [];
+ const all = [...preview.tools, ...preview.skipped];
+ const needle = q.trim().toLowerCase();
+ if (!needle) return all;
+ return all.filter(
+ (t) => t.name.toLowerCase().includes(needle) || t.description.toLowerCase().includes(needle),
+ );
+ }, [preview, q]);
+
+ if (!preview || (!preview.tools.length && !preview.skipped.length)) {
+ return (
+ <div className="empty-card schema-empty">
+ <div className="empty-icon">{"{}"}</div>
+ <p className="empty">勾选左侧产品后,这里显示模型将看到的 tools/list。</p>
+ </div>
+ );
+ }
+
+ const groups = new Map<string, SchemaTool[]>();
+ for (const t of items) {
+ const list = groups.get(t.product) ?? [];
+ list.push(t);
+ groups.set(t.product, list);
+ }
+
+ return (
+ <>
+ <div className="inspector-toolbar">
+ <div className="tabs" role="tablist">
+ <button className={`tab${mode === "grouped" ? " on" : ""}`} onClick={() => onMode("grouped")}>
+ 按产品
+ </button>
+ <button className={`tab${mode === "flat" ? " on" : ""}`} onClick={() => onMode("flat")}>
+ 扁平列表
+ </button>
+ </div>
+ <input
+ className="search"
+ placeholder="搜索工具名或描述"
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ />
+ </div>
+ {mode === "flat"
+ ? items.map((t) => (
+ <ToolCard
+ key={t.name}
+ tool={t}
+ expanded={!!open[t.name]}
+ onExpand={() => setOpen((s) => ({ ...s, [t.name]: !s[t.name] }))}
+ onToggle={() => onToggleTool(t.name)}
+ />
+ ))
+ : [...groups.entries()].map(([product, tools]) => {
+ const ready = tools.filter((t) => t.ready && t.enabled).length;
+ return (
+ <div className="group" key={product}>
+ <div className="group-head">
+ <span className="dot" style={{ background: COLORS[product] || "#888" }} />
+ <strong>{LABELS[product] ?? product}</strong>
+ <span className="count-pill">{ready} ready</span>
+ </div>
+ {tools.map((t) => (
+ <ToolCard
+ key={t.name}
+ tool={t}
+ expanded={!!open[t.name]}
+ onExpand={() => setOpen((s) => ({ ...s, [t.name]: !s[t.name] }))}
+ onToggle={() => onToggleTool(t.name)}
+ />
+ ))}
+ </div>
+ );
+ })}
+ </>
+ );
+}
+
+function ToolCard({
+ tool,
+ expanded,
+ onExpand,
+ onToggle,
+}: {
+ tool: SchemaTool;
+ expanded: boolean;
+ onExpand: () => void;
+ onToggle: () => void;
+}) {
+ const dim = !tool.ready || !tool.enabled;
+ const required = new Set(tool.inputSchema.required ?? []);
+ const props = tool.inputSchema.properties ?? {};
+ return (
+ <div className={`tool-card${dim ? " dim" : ""}${expanded ? " open" : ""}`}>
+ <div className="tool-top">
+ <label className="switch" title={tool.enabled ? "从生成结果中移除" : "重新加入"}>
+ <input type="checkbox" checked={tool.enabled} onChange={onToggle} />
+ <span />
+ </label>
+ <button type="button" className="tool-name" onClick={onExpand}>
+ <code>{tool.name}</code>
+ <span className="chevron">{expanded ? "−" : "+"}</span>
+ </button>
+ {tool.annotations.readOnlyHint ? <span className="badge ok">read-only</span> : null}
+ {!tool.ready ? <span className="badge">skipped</span> : null}
+ </div>
+ <p className="tool-desc">{tool.description}</p>
+ {!tool.ready && tool.skipReason ? <div className="skip">{tool.skipReason}</div> : null}
+ {expanded ? (
+ <div className="fields">
+ {Object.entries(props).map(([name, prop]) => (
+ <div className="field" key={name}>
+ <div className="field-k">
+ <span className="k">{name}</span>
+ <span className="type">{prop.type}</span>
+ {required.has(name) ? <span className="req">required</span> : null}
+ </div>
+ {prop.description ? <div className="d">{prop.description}</div> : null}
+ {prop.enum?.length ? (
+ <div className="chips">
+ {prop.enum.map((v) => (
+ <span className="chip" key={v}>
+ {v}
+ </span>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ))}
+ <details>
+ <summary>查看原始 JSON</summary>
+ <pre className="raw">{JSON.stringify(tool.inputSchema, null, 2)}</pre>
+ </details>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/tools/tcmcp/web/src/main.tsx b/tools/tcmcp/web/src/main.tsx
new file mode 100644
index 00000000..98911296
--- /dev/null
+++ b/tools/tcmcp/web/src/main.tsx
@@ -0,0 +1,10 @@
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import { App } from "./App";
+import "./styles.css";
+
+createRoot(document.getElementById("root")!).render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+);
diff --git a/tools/tcmcp/web/src/regions.ts b/tools/tcmcp/web/src/regions.ts
new file mode 100644
index 00000000..f7d57d52
--- /dev/null
+++ b/tools/tcmcp/web/src/regions.ts
@@ -0,0 +1,23 @@
+export const PUBLIC_REGIONS: { id: string; name: string }[] = [
+ { id: "ap-guangzhou", name: "广州" },
+ { id: "ap-shanghai", name: "上海" },
+ { id: "ap-nanjing", name: "南京" },
+ { id: "ap-beijing", name: "北京" },
+ { id: "ap-chengdu", name: "成都" },
+ { id: "ap-chongqing", name: "重庆" },
+ { id: "ap-hongkong", name: "中国香港" },
+ { id: "ap-singapore", name: "新加坡" },
+ { id: "ap-tokyo", name: "东京" },
+ { id: "ap-seoul", name: "首尔" },
+ { id: "ap-bangkok", name: "曼谷" },
+ { id: "ap-jakarta", name: "雅加达" },
+ { id: "ap-mumbai", name: "孟买" },
+ { id: "na-ashburn", name: "弗吉尼亚" },
+ { id: "na-siliconvalley", name: "硅谷" },
+ { id: "eu-frankfurt", name: "法兰克福" },
+ { id: "sa-saopaulo", name: "圣保罗" },
+];
+
+export function resolveRegions(remote?: { id: string; name: string }[]): { id: string; name: string }[] {
+ return remote?.length ? remote : PUBLIC_REGIONS;
+}
diff --git a/tools/tcmcp/web/src/slug.ts b/tools/tcmcp/web/src/slug.ts
new file mode 100644
index 00000000..06c51c20
--- /dev/null
+++ b/tools/tcmcp/web/src/slug.ts
@@ -0,0 +1,19 @@
+export function slugify(raw: string): string {
+ const s = raw
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+ return s.slice(0, 32) || "res";
+}
+
+export function uniqueAlias(base: string, used: Set<string>): string {
+ let alias = slugify(base);
+ let i = 2;
+ while (used.has(alias)) {
+ alias = `${slugify(base)}-${i}`;
+ i += 1;
+ }
+ used.add(alias);
+ return alias;
+}
diff --git a/tools/tcmcp/web/src/styles.css b/tools/tcmcp/web/src/styles.css
new file mode 100644
index 00000000..c1dec596
--- /dev/null
+++ b/tools/tcmcp/web/src/styles.css
@@ -0,0 +1,479 @@
+:root {
+ --bg: #f4f6f8;
+ --bg-elev: #ffffff;
+ --bg-card: #ffffff;
+ --line: #e6e8ee;
+ --line-strong: #d4d8e0;
+ --text: #15181e;
+ --muted: #5c6573;
+ --faint: #8b93a1;
+ --accent: #2f6fed;
+ --accent-soft: #e8f0ff;
+ --warn: #b45309;
+ --warn-bg: #fff7ed;
+ --danger: #c2410c;
+ --ok: #0f9f6e;
+ --ok-soft: #e6f7f0;
+ --mono: "IBM Plex Mono", ui-monospace, Menlo, monospace;
+ --sans: "Outfit", "Noto Sans SC", system-ui, sans-serif;
+ --shadow: 0 16px 40px rgba(22, 28, 40, 0.08);
+ --radius: 16px;
+}
+
+* { box-sizing: border-box; }
+html, body, #root { height: 100%; margin: 0; }
+body {
+ background:
+ radial-gradient(900px 420px at 10% -8%, #e8f0ff 0%, transparent 55%),
+ radial-gradient(700px 360px at 100% 0%, #e9f8f1 0%, transparent 50%),
+ var(--bg);
+ color: var(--text);
+ font-family: var(--sans);
+ font-size: 15px;
+ line-height: 1.55;
+ -webkit-font-smoothing: antialiased;
+}
+
+.sr { position: absolute; opacity: 0; pointer-events: none; width: 0; height: 0; }
+
+.app { display: flex; flex-direction: column; min-height: 100%; }
+
+.topbar {
+ display: flex; align-items: center; justify-content: space-between;
+ padding: 18px 32px 14px; max-width: 1080px; margin: 0 auto; width: 100%;
+}
+.brand { display: flex; align-items: center; gap: 12px; }
+.logo {
+ width: 36px; height: 36px; border-radius: 10px;
+ background: linear-gradient(160deg, #4c84f5 0%, #2f6fed 60%, #12b981 140%);
+ box-shadow: 0 8px 18px rgba(47, 111, 237, 0.25);
+ position: relative;
+}
+.logo span {
+ position: absolute; inset: 9px;
+ border: 1.6px solid rgba(255,255,255,0.95);
+ border-radius: 5px; border-right-color: transparent;
+ transform: rotate(45deg);
+}
+.brand h1 { margin: 0; font-size: 18px; font-weight: 650; letter-spacing: -0.03em; }
+.brand span { color: var(--muted); font-size: 13px; }
+
+.status { display: flex; gap: 8px; }
+.stat {
+ display: flex; align-items: baseline; gap: 6px;
+ padding: 5px 10px; border-radius: 999px;
+ background: #fff; border: 1px solid var(--line);
+ color: var(--muted); font-size: 12px;
+}
+.stat em { font-style: normal; color: var(--text); font-weight: 650; font-variant-numeric: tabular-nums; }
+.stat.warn { background: var(--warn-bg); border-color: #f3d5a8; color: var(--warn); }
+
+.stepper {
+ list-style: none; display: flex; flex-wrap: wrap; gap: 4px 0; padding: 0 24px 8px;
+ max-width: 1080px; margin: 0 auto 8px; width: 100%;
+}
+.stepper li { flex: 1 1 72px; min-width: 72px; position: relative; }
+.stepper li:not(:last-child)::after {
+ content: ""; position: absolute; left: calc(50% + 22px); right: calc(-50% + 22px);
+ top: 15px; height: 2px; background: var(--line); z-index: 0;
+}
+.stepper li.done:not(:last-child)::after { background: var(--ok); }
+.stepper button {
+ position: relative; z-index: 1; width: 100%;
+ display: flex; flex-direction: column; align-items: center; gap: 6px;
+ background: none; border: 0; cursor: pointer; color: var(--faint); font: inherit;
+}
+.stepper button:disabled { cursor: default; }
+.stepper .num {
+ width: 32px; height: 32px; border-radius: 999px;
+ display: grid; place-items: center;
+ background: #fff; border: 1.5px solid var(--line-strong);
+ font-size: 13px; font-weight: 650;
+}
+.stepper .lab { font-size: 12px; font-weight: 550; }
+.stepper li.on .num {
+ background: var(--accent); border-color: var(--accent); color: #fff;
+ box-shadow: 0 6px 14px rgba(47, 111, 237, 0.28);
+}
+.stepper li.on .lab, .stepper li.on button { color: var(--text); }
+.stepper li.done .num { background: var(--ok-soft); border-color: #9ad9bf; color: var(--ok); }
+.stepper li.done .lab { color: var(--ok); }
+
+.warn-banner {
+ max-width: 880px; margin: 0 auto 8px; width: calc(100% - 48px);
+ background: var(--warn-bg); color: var(--warn);
+ border: 1px solid #f3d5a8; border-radius: 12px;
+ padding: 10px 14px; font-size: 13px;
+}
+
+.wizard {
+ flex: 1; display: flex; justify-content: center;
+ padding: 8px 24px 40px;
+}
+.sheet {
+ width: min(760px, 100%);
+ background: var(--bg-card);
+ border: 1px solid var(--line);
+ border-radius: 20px;
+ box-shadow: var(--shadow);
+ padding: 28px 32px 20px;
+ display: flex; flex-direction: column; min-height: 520px;
+}
+.sheet.wide { width: min(1080px, 100%); }
+.sheet h2 { margin: 0 0 6px; font-size: 26px; letter-spacing: -0.03em; font-weight: 650; }
+.hint { margin: 0 0 22px; color: var(--muted); }
+
+.eyebrow { margin: 0 0 8px; color: var(--accent); font-size: 12px; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; }
+.lead { color: var(--muted); font-size: 16px; margin: 0 0 24px; max-width: 38em; }
+.guide { list-style: none; padding: 0; margin: 0; display: grid; gap: 10px; }
+.guide li {
+ display: grid; grid-template-columns: 140px 1fr; gap: 12px; align-items: baseline;
+ padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; background: #fafbfc;
+}
+.guide strong { font-size: 14px; }
+.guide span { color: var(--muted); font-size: 13.5px; }
+
+.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 16px; }
+.field-block { display: block; margin-bottom: 14px; }
+.field-block > span { display: block; font-size: 13px; color: var(--muted); margin-bottom: 6px; font-weight: 550; }
+.field-err { color: var(--danger); font-size: 13px; margin-top: 8px; }
+
+input, select {
+ width: 100%; background: #fff; color: var(--text);
+ border: 1px solid var(--line-strong); border-radius: 10px;
+ padding: 10px 12px; font: inherit; transition: border-color .15s, box-shadow .15s;
+}
+input.mono { font-family: var(--mono); font-size: 13.5px; }
+input:focus, select:focus {
+ outline: none; border-color: var(--accent);
+ box-shadow: 0 0 0 3px rgba(47, 111, 237, 0.16);
+}
+
+.callout {
+ background: #f4f8ff; border: 1px solid #d7e4ff; color: #27406b;
+ border-radius: 12px; padding: 12px 14px; font-size: 13.5px; margin: 4px 0 16px;
+}
+
+.product-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+
+.product-card {
+ width: 100%; display: grid; grid-template-columns: 40px 1fr 22px;
+ gap: 12px; align-items: center; text-align: left;
+ background: #fff; border: 1px solid var(--line);
+ border-radius: 14px; padding: 13px 14px;
+ color: inherit; cursor: pointer; transition: border-color .15s, box-shadow .15s, transform .15s;
+}
+.product-card:hover { border-color: #c5cdd8; transform: translateY(-1px); }
+.product-card.on {
+ border-color: color-mix(in srgb, var(--dot) 45%, #d0d5dd);
+ background: color-mix(in srgb, var(--dot) 8%, #fff);
+ box-shadow: 0 8px 20px color-mix(in srgb, var(--dot) 12%, transparent);
+}
+.product-mark {
+ width: 40px; height: 40px; border-radius: 11px;
+ display: grid; place-items: center;
+ font-family: var(--mono); font-weight: 500; font-size: 15px; color: #fff;
+ background: var(--dot);
+}
+.product-copy { min-width: 0; }
+.product-title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.product-title strong { font-size: 15px; font-weight: 650; }
+.product-desc { display: block; color: var(--muted); font-size: 12.5px; margin-top: 3px; line-height: 1.4; }
+.check {
+ width: 20px; height: 20px; border-radius: 999px;
+ border: 1.5px solid var(--line-strong);
+ display: grid; place-items: center; color: #fff;
+}
+.check.on { background: var(--ok); border-color: var(--ok); }
+
+.count-pill {
+ font-size: 11px; color: var(--muted);
+ background: #f3f5f8; border: 1px solid var(--line);
+ border-radius: 999px; padding: 1px 8px; white-space: nowrap;
+}
+.count-pill.on { color: var(--text); background: #fff; }
+
+.btn {
+ appearance: none; border: 1px solid var(--line-strong);
+ background: #fff; color: var(--text);
+ border-radius: 10px; padding: 10px 16px; cursor: pointer;
+ font: inherit; font-weight: 600; transition: .15s ease;
+}
+.btn:hover:not(:disabled) { border-color: #9aa3b2; }
+.btn:disabled { opacity: 0.4; cursor: not-allowed; }
+.btn.primary {
+ background: var(--accent); border-color: var(--accent); color: #fff;
+ box-shadow: 0 8px 18px rgba(47, 111, 237, 0.22);
+}
+.btn.primary:hover:not(:disabled) { filter: brightness(1.05); color: #fff; }
+.err { color: var(--danger); font-size: 13px; margin-top: 8px; }
+
+.fetch-tip { color: var(--muted); font-size: 13.5px; margin: -8px 0 16px; }
+.product-fetch-list { display: flex; flex-direction: column; gap: 14px; }
+.fetch-card {
+ border: 1px solid var(--line); border-radius: 16px;
+ background: #fafbfc; padding: 14px 14px 12px;
+}
+.fetch-card-head { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
+.fetch-card-head h3 { margin: 0; font-size: 16px; font-weight: 650; }
+.fetch-toolbar {
+ display: grid; grid-template-columns: minmax(200px, 1.3fr) auto minmax(140px, 1fr);
+ gap: 8px; align-items: center; margin-bottom: 10px;
+}
+.region-chips {
+ display: flex; flex-wrap: wrap; gap: 6px; align-items: center;
+ min-height: 28px; margin: -2px 0 10px;
+}
+.region-chips-empty { font-size: 12.5px; color: var(--faint); }
+.region-chip-btn {
+ display: inline-flex; align-items: center; gap: 6px;
+ border: 1px solid #d7e4ff; background: #e8f0ff; color: #1e4bb8;
+ border-radius: 999px; padding: 3px 9px 3px 10px;
+ font: inherit; font-size: 12px; font-weight: 600; cursor: pointer;
+}
+.region-chip-btn.on { border-color: var(--accent); background: #dce8ff; }
+.region-chip-btn span { font-size: 14px; line-height: 1; color: #5c7cc4; }
+.region-select, .search-mini {
+ margin: 0; background: #fff;
+}
+.transfer {
+ display: grid;
+ grid-template-columns: 1fr 72px 1fr;
+ gap: 10px;
+ align-items: stretch;
+ min-height: 240px;
+}
+.transfer-pane {
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: #fff;
+ display: flex;
+ flex-direction: column;
+ min-height: 220px;
+ max-height: 380px;
+ overflow: hidden;
+}
+.transfer-pane h4 {
+ margin: 0;
+ padding: 10px 12px;
+ font-size: 12px;
+ font-weight: 650;
+ color: var(--muted);
+ border-bottom: 1px solid var(--line);
+ background: #fafbfc;
+}
+.transfer-list {
+ flex: 1;
+ overflow: auto;
+ padding: 8px;
+}
+.transfer-mid {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+}
+.transfer-arrow {
+ width: 34px; height: 34px; border-radius: 50%;
+ display: grid; place-items: center;
+ color: var(--accent); background: var(--accent-soft);
+ border: 1px solid #d7e4ff; font-size: 20px; font-weight: 700;
+}
+.btn.ghost {
+ padding: 6px 10px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--muted);
+}
+.region-chip {
+ display: inline-block; margin-left: 8px;
+ font-family: var(--mono); font-size: 11px; font-weight: 500;
+ color: #1e4bb8; background: #e8f0ff;
+ border-radius: 999px; padding: 1px 7px; vertical-align: 1px;
+}
+
+.empty-card {
+ border: 1px dashed var(--line-strong); border-radius: 14px;
+ padding: 28px 18px; text-align: center; background: #fafbfc;
+}
+.empty-icon {
+ width: 44px; height: 44px; margin: 0 auto 10px;
+ border-radius: 12px; display: grid; place-items: center;
+ background: var(--accent-soft); color: var(--accent);
+ font-family: var(--mono); font-size: 18px;
+}
+.empty { color: var(--muted); font-size: 13.5px; margin: 0; line-height: 1.55; }
+.schema-empty { margin-top: 8px; }
+
+.res-group { margin-bottom: 18px; }
+.res-group h4 {
+ margin: 0 0 10px; font-size: 13px; font-weight: 650;
+ display: flex; align-items: center; gap: 8px;
+}
+.dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
+
+.res-item {
+ position: relative;
+ display: grid; grid-template-columns: 18px 1fr 118px;
+ gap: 10px; align-items: center;
+ padding: 10px 12px; border: 1px solid var(--line);
+ border-radius: 12px; margin-bottom: 7px;
+ background: #fff; cursor: pointer;
+}
+.res-item.pick { grid-template-columns: 18px 1fr; }
+.res-item.pick {
+ width: 100%; color: inherit; font: inherit; text-align: left;
+}
+.res-item.bound { grid-template-columns: 1fr 110px auto; cursor: default; }
+.res-item:hover { border-color: #c9cfd8; }
+.res-item.pick:hover {
+ border-color: #b7ccf7; background: #f5f8ff;
+}
+.res-item .meta { font-size: 11.5px; color: var(--faint); font-family: var(--mono); margin-top: 2px; word-break: break-all; }
+.res-item .name { font-weight: 600; font-size: 14px; }
+.add-mark {
+ width: 18px; height: 18px; border-radius: 50%;
+ display: grid; place-items: center; align-self: start; margin-top: 1px;
+ border: 1px solid var(--line-strong); color: var(--muted);
+ background: #fff; font-size: 14px; line-height: 1; font-weight: 700;
+}
+.res-item.pick:hover .add-mark {
+ color: #fff; background: var(--accent); border-color: var(--accent);
+}
+.alias { width: 118px; font-family: var(--mono); font-size: 12px; padding: 6px 8px; }
+.alias-ph { font-size: 11px; color: var(--faint); text-align: right; }
+
+.logset { margin-bottom: 12px; }
+.logset-head {
+ display: flex; justify-content: space-between; gap: 8px;
+ font-size: 12.5px; color: var(--muted); margin: 4px 2px 8px;
+}
+.logset-head code { font-family: var(--mono); font-size: 11px; color: var(--faint); }
+
+.inspector-toolbar { display: flex; justify-content: space-between; gap: 12px; margin-bottom: 14px; align-items: center; }
+.tabs {
+ display: inline-flex; padding: 3px; gap: 2px;
+ background: #f3f5f8; border: 1px solid var(--line); border-radius: 10px;
+}
+.tab {
+ border: 0; background: transparent; color: var(--muted);
+ border-radius: 8px; padding: 6px 12px; cursor: pointer;
+ font: inherit; font-size: 13px; font-weight: 600;
+}
+.tab.on { color: var(--text); background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }
+.search { margin: 0; max-width: 280px; }
+
+.group { margin-bottom: 16px; }
+.group-head { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
+
+.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
+.chip {
+ font-family: var(--mono); font-size: 11px;
+ background: var(--accent-soft); border: 1px solid #d7e4ff;
+ color: #1e4bb8; border-radius: 999px; padding: 2px 9px;
+}
+
+.tool-card {
+ border: 1px solid var(--line); border-radius: 12px;
+ padding: 12px 14px; margin-bottom: 8px; background: #fff;
+}
+.tool-card.open { border-color: #b7ccf7; }
+.tool-card.dim { opacity: 0.5; }
+.tool-top { display: flex; align-items: center; gap: 10px; }
+.tool-name {
+ flex: 1; display: flex; align-items: center; justify-content: space-between;
+ background: none; border: 0; color: inherit; padding: 0; cursor: pointer; min-width: 0;
+}
+.tool-name code { font-family: var(--mono); font-size: 13.5px; color: #1e4bb8; font-weight: 550; }
+.chevron { color: var(--faint); font-size: 16px; margin-left: 8px; }
+.badge {
+ font-size: 10px; text-transform: uppercase; letter-spacing: 0.06em;
+ border: 1px solid var(--line); border-radius: 999px; padding: 2px 7px; color: var(--muted);
+}
+.badge.ok { color: var(--ok); border-color: #9ad9bf; background: var(--ok-soft); }
+.tool-desc { margin: 8px 0 0 38px; color: var(--muted); font-size: 13px; }
+.skip { color: var(--warn); font-size: 12.5px; margin: 8px 0 0 38px; }
+
+.switch { position: relative; width: 32px; height: 18px; flex-shrink: 0; }
+.switch input { appearance: none; width: 32px; height: 18px; margin: 0; cursor: pointer; }
+.switch span {
+ position: absolute; inset: 0; border-radius: 999px; background: #d5dae2; transition: .15s;
+}
+.switch span::after {
+ content: ""; position: absolute; top: 2px; left: 2px;
+ width: 14px; height: 14px; border-radius: 50%; background: #fff;
+ box-shadow: 0 1px 3px rgba(0,0,0,0.15); transition: .15s;
+}
+.switch input:checked + span { background: var(--ok); }
+.switch input:checked + span::after { transform: translateX(14px); }
+
+.fields { margin: 12px 0 0 38px; }
+.field { padding: 10px 0; border-top: 1px solid var(--line); }
+.field-k { display: flex; align-items: center; gap: 8px; }
+.field .k { font-family: var(--mono); font-size: 13px; color: #1e4bb8; }
+.field .type { font-family: var(--mono); font-size: 11px; color: var(--faint); }
+.req {
+ color: var(--danger); font-size: 10px; letter-spacing: 0.04em; text-transform: uppercase;
+ border: 1px solid #f4c4b0; border-radius: 999px; padding: 0 6px; background: #fff4ef;
+}
+.field .d { color: var(--muted); font-size: 12.5px; margin-top: 4px; }
+.raw {
+ margin-top: 8px; background: #f6f7f9; border-radius: 10px; padding: 12px;
+ font-family: var(--mono); font-size: 11.5px; overflow: auto; max-height: 220px;
+ color: #333; border: 1px solid var(--line);
+}
+details summary { cursor: pointer; color: var(--muted); font-size: 13px; margin-top: 8px; }
+
+.download-help {
+ padding: 18px;
+ border: 1px solid #9ad9bf; border-radius: 14px; background: var(--ok-soft);
+}
+.download-help-head {
+ display: flex; align-items: flex-start; justify-content: space-between; gap: 16px;
+}
+.download-help-head strong { font-size: 16px; }
+.download-help-head p { margin: 3px 0 0; color: var(--muted); font-size: 13px; }
+.download-help ol { margin: 14px 0; padding-left: 22px; color: #285747; font-size: 13.5px; }
+.download-help pre {
+ margin: 0; padding: 14px; overflow: auto;
+ border: 1px solid #c7d9d2; border-radius: 10px; background: #fff;
+ color: var(--text); font: 12.5px/1.55 var(--mono); white-space: pre;
+}
+.download-help code { font-family: var(--mono); font-size: 0.92em; }
+.install-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; align-items: start; }
+.one-click-install { margin-bottom: 24px; }
+.deploy-help {
+ padding: 18px; border: 1px solid #d7e4ff; border-radius: 14px; background: #f4f8ff;
+}
+.deploy-help > strong { font-size: 16px; }
+.deploy-help p { color: var(--muted); font-size: 13px; }
+.deploy-help p:first-of-type { margin: 3px 0 14px; }
+.deploy-help p:last-child { margin: 10px 0 0; }
+.deploy-help code { font-family: var(--mono); font-size: 0.92em; }
+.deploy-help pre {
+ margin: 0; padding: 14px; overflow: auto;
+ border: 1px solid #d7e4ff; border-radius: 10px; background: #fff;
+ color: var(--text); font: 12.5px/1.55 var(--mono); white-space: pre;
+}
+.secret-note { margin: 12px 0 0; color: var(--danger); font-size: 12.5px; }
+
+.wizard-foot {
+ margin-top: auto; padding-top: 18px;
+ display: flex; justify-content: space-between; align-items: center; gap: 16px;
+ border-top: 1px solid var(--line);
+}
+.foot-right { display: flex; align-items: center; gap: 12px; }
+.ready-count { color: var(--muted); font-size: 13px; }
+
+@media (max-width: 800px) {
+ .grid-2, .product-grid { grid-template-columns: 1fr; }
+ .guide li { grid-template-columns: 1fr; gap: 4px; }
+ .inspector-toolbar { flex-direction: column; align-items: stretch; }
+ .install-grid { grid-template-columns: 1fr; }
+ .download-help-head { flex-direction: column; }
+ .search { max-width: none; }
+ .sheet { padding: 20px 16px 16px; }
+ .fetch-toolbar { grid-template-columns: 1fr; }
+ .transfer { grid-template-columns: 1fr; }
+ .transfer-mid { flex-direction: row; padding: 4px 0; }
+}
diff --git a/tools/tcmcp/web/src/types.ts b/tools/tcmcp/web/src/types.ts
new file mode 100644
index 00000000..f6cccc30
--- /dev/null
+++ b/tools/tcmcp/web/src/types.ts
@@ -0,0 +1,126 @@
+export type ProductId = "redis" | "cdb" | "tdsqlc" | "tke" | "cls" | "cos";
+
+export interface ProductMeta {
+ id: ProductId;
+ name: string;
+ description: string;
+ color: string;
+ tools: { name: string; description: string }[];
+}
+
+export interface Metadata {
+ name: string;
+ version: string;
+ toolWarnThreshold: number;
+ defaults: { name: string; target: string; region: string };
+ products: ProductMeta[];
+ regions: { id: string; name: string }[];
+}
+
+export interface ResourceItem {
+ id: string;
+ alias: string;
+ name: string;
+ region?: string;
+ extra?: Record<string, unknown>;
+}
+
+export interface CLSTopic {
+ id: string;
+ alias: string;
+ name: string;
+}
+
+export interface CLSResource {
+ logsetId: string;
+ logsetName: string;
+ region?: string;
+ topics: CLSTopic[];
+}
+
+export interface TDSQLCResource {
+ clusterId: string;
+ instanceId: string;
+ alias: string;
+ name: string;
+ region?: string;
+}
+
+export interface BoundResources {
+ redis: ResourceItem[];
+ cdb: ResourceItem[];
+ tdsqlc: TDSQLCResource[];
+ tke: ResourceItem[];
+ cls: CLSResource[];
+ cos: ResourceItem[];
+}
+
+export interface Selection {
+ project: {
+ name: string;
+ description: string;
+ target: string;
+ region: string;
+ };
+ products: string[];
+ disabled_tools: string[];
+ resources: BoundResources;
+}
+
+export interface SchemaTool {
+ name: string;
+ description: string;
+ product: string;
+ inputSchema: {
+ type: string;
+ properties?: Record<string, SchemaProp>;
+ required?: string[];
+ };
+ annotations: { readOnlyHint: boolean };
+ enabled: boolean;
+ ready: boolean;
+ skipReason: string;
+}
+
+export interface SchemaProp {
+ type: string;
+ description?: string;
+ enum?: string[];
+ default?: unknown;
+ items?: { type: string };
+}
+
+export interface Preview {
+ instructions: string;
+ tools: SchemaTool[];
+ skipped: SchemaTool[];
+ grouped: Record<string, SchemaTool[]>;
+ registered: string[];
+ counts: { products: number; resources: number; tools: number; threshold: number };
+ warn: boolean;
+ warnMessage: string;
+}
+
+export interface ListedResource {
+ id: string;
+ name: string;
+ region?: string;
+ extra?: Record<string, unknown>;
+}
+
+export interface ListedLogset {
+ id: string;
+ name: string;
+ region?: string;
+ topics: { id: string; name: string; logsetId: string }[];
+}
+
+export interface ResourceCatalog {
+ redis: ListedResource[];
+ cdb: ListedResource[];
+ tdsqlc: ListedResource[];
+ tke: ListedResource[];
+ cls: ListedLogset[];
+ cos: ListedResource[];
+ errors: Record<string, string>;
+}
diff --git a/tools/tcmcp/web/src/vite-env.d.ts b/tools/tcmcp/web/src/vite-env.d.ts
new file mode 100644
index 00000000..11f02fe2
--- /dev/null
+++ b/tools/tcmcp/web/src/vite-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" />
diff --git a/tools/tcmcp/web/tsconfig.json b/tools/tcmcp/web/tsconfig.json
new file mode 100644
index 00000000..14e5242f
--- /dev/null
+++ b/tools/tcmcp/web/tsconfig.json
@@ -0,0 +1,19 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "useDefineForClassFields": true,
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "isolatedModules": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true
+ },
+ "include": ["src"]
+}
diff --git a/tools/tcmcp/web/vite.config.ts b/tools/tcmcp/web/vite.config.ts
new file mode 100644
index 00000000..0a5d2955
--- /dev/null
+++ b/tools/tcmcp/web/vite.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from "vite";
+import react from "@vitejs/plugin-react";
+
+export default defineConfig({
+ plugins: [react()],
+ server: {
+ port: 5173,
+ proxy: {
+ "/api": "http://127.0.0.1:8088",
+ "/cursor": "http://127.0.0.1:8088",
+ "/codebuddy": "http://127.0.0.1:8088",
+ "/codex": "http://127.0.0.1:8088",
+ "/workbuddy": "http://127.0.0.1:8088",
+ },
+ },
+});