diff --git a/mcp/README.md b/mcp/README.md new file mode 100644 index 0000000..5ae0b85 --- /dev/null +++ b/mcp/README.md @@ -0,0 +1,90 @@ +# MCP 服务集合 + +三个 MCP(Model Context Protocol)服务,各占一个目录,由仓库根 `docker-compose.yml` 统一编排: + +| 目录 | 容器名 | 作用 | 容器内端口 | MCP 端点 | +|---|---|---|---|---| +| `web_search/` | `mcp_web_search` | 免费网页搜索(Parallel / Exa,无需 key) | `3000` | `POST /` | +| `image_task/` | `mcp_image_task` | 智谱 CogView 图片生成(单工具 op=create) | `3000` | `POST /mcp` | +| `video_task/` | `mcp_video_task` | 智谱 CogVideo 视频生成(异步,单工具 op=create/get) | `3000` | `POST /mcp` | + +**这些服务一个宿主机端口都不占**——它们只挂在 `agent-mcp-net` 上,由 `agent-core` / `agent-executor` +按容器名访问。所以整台服务器对外只需要开 agent-core 那一个端口(`AGENT_PORT`,默认 8090)。 +(要从宿主机 curl 调试时,把根 `docker-compose.yml` 里对应服务注释掉的 `ports` 两行打开。) + +## 部署 + +它们和 `agent-core` / `agent-executor` / `wxbot` 同属一个 compose 项目,无需单独启动,也没有先后顺序: + +```bash +cd /root/workspace/tools/agent +docker compose up -d --build +``` + +`config.yml` 里的地址与容器名一一对应: + +```yaml +mcp_servers: + - name: web_search + url: "http://mcp_web_search:3000/" + - name: image_task + url: "http://mcp_image_task:3000/mcp" + - name: video_task + url: "http://mcp_video_task:3000/mcp" +``` + +服务没起来时,core 只在启动日志里告警,不影响 Web 主流程,但对应工具不会下发给模型。 + +> 从旧的「agent + mcp 双仓库」部署升级:先在旧 mcp 仓库目录 `docker compose down`(只需一次,否则同名容器与网络会冲突),再 `up` 本栈。 + +`image_task` / `video_task` 需要智谱 token,但 token **不由服务端保存**——每个请求从 header 读取 +(agent 侧配在 `config.yml` 的 `mcp_servers[].headers`,`init.sh` 会用 `BIGMODEL_KEY` 自动写入)。 +所以这里不用配任何密钥。 + +### 调试端口 + +写在仓库顶层 `.env` 里即可(不写就用默认值;开了端口记得调试完注释回去): + +| 变量 | 默认 | 说明 | +|---|---|---| +| `WEB_SEARCH_PORT` | `8081` | 只在临时打开 web_search 调试端口时用 | +| `IMAGE_TASK_PORT` | `8082` | 只在临时打开 image_task 调试端口时用 | +| `VIDEO_TASK_PORT` | `8083` | 只在临时打开 video_task 调试端口(MCP 口,仅本机短时调试)时用 | + +## 图片是怎么到智谱手上的(只有 video_task 关心) + +智谱服务器生成视频前要**自己来拉参考图**,它不带 cookie、不带 `Authorization`。这套链路里**没有任何人上传文件**: + +``` +AI ──调用 agent 内置的「公开临时 URL」工具(直接传文件路径)──► 拿到一条短命公网 URL + │ + ▼ +AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp + │ + ▼ +智谱 ──匿名 GET──► agent 侧提供的公开临时 URL + 那个文件始终躺在 agent 的任务目录里,零拷贝 +``` + +- 签发与托管全在 agent 侧(它已集成为一个 tool,AI 直接调用即可,不需要 curl 任何内网入口)。 +- 链接短命:到期或 agent 重启后失效;智谱只在提交任务那一刻拉一次图,完全够用。 +- mcp 这三家一个端口都不露,唯一公网可达的东西只有 agent 自己。 + +## 端口与安全 + +| 服务 | 公网暴露 | 说明 | +|---|---|---| +| `mcp_web_search` | 无 | 服务端无鉴权,**永远不要映射出去**(会被白嫖搜索额度);agent 走内网访问 | +| `mcp_image_task` | 无 | token 由调用方自带,暴露后可被拿去消耗你的智谱额度 | +| `mcp_video_task` | 无 | 它需要的公开临时 URL 由 agent 侧集成的工具提供,自己不占端口 | + +## 单独调试 + +```bash +cd /root/workspace/tools/agent +docker compose up -d --build mcp_web_search +# 不占端口的健康检查 +docker exec mcp_web_search node -e "fetch('http://localhost:3000/health').then(r=>r.text()).then(console.log)" +``` + +各目录下的 `README.md` 有该服务的工具说明、header 覆盖项与 curl 调试脚本。 diff --git a/mcp/image_task/.dockerignore b/mcp/image_task/.dockerignore new file mode 100644 index 0000000..b0e3907 --- /dev/null +++ b/mcp/image_task/.dockerignore @@ -0,0 +1,3 @@ +node_modules +npm-debug.log +.DS_Store diff --git a/mcp/image_task/Dockerfile b/mcp/image_task/Dockerfile new file mode 100644 index 0000000..324ba3c --- /dev/null +++ b/mcp/image_task/Dockerfile @@ -0,0 +1,19 @@ +FROM node:22-slim + +WORKDIR /app + +# 国内构建慢:npm 默认源在国外(web_search 零依赖不需要,这个要)。 +# 想换回官方:docker compose build --build-arg NPM_REGISTRY=https://registry.npmjs.org/ mcp_image_task +ARG NPM_REGISTRY=https://mirrors.cloud.tencent.com/npm/ + +# 复制 package.json 并安装依赖 +COPY package.json ./ +RUN npm config set registry "$NPM_REGISTRY" && npm install --omit=dev + +# 复制源码 +COPY . . + +EXPOSE 3000 + +# 启用 HTTP/SSE 模式,监听 3000 端口 +CMD ["node", "src/mcp-server.js", "--http", "--port", "3000", "--host", "0.0.0.0"] diff --git a/mcp/image_task/README.md b/mcp/image_task/README.md new file mode 100644 index 0000000..9b127d0 --- /dev/null +++ b/mcp/image_task/README.md @@ -0,0 +1,306 @@ +# MCP Image Task + +一个基于 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 的图片生成服务,对接智谱 BigModel 的 `CogView` 系列模型。每次调用通过 HTTP header 传入智谱 API 的 Bearer Token。只有一个工具 `image_task`,用 `op` 区分动作(`create` / `get`),对外提供与 `video_task` 一致的**异步任务**契约;上游为同步接口,异步语义由服务自维护的任务表模拟(见「架构与文件」)。 + +- 协议:MCP **Streamable HTTP**(单端点 `/mcp`,支持 SSE 流) +- 上游:[智谱 BigModel Images Generations API](https://open.bigmodel.cn/dev/api#images) +- 默认模型:`CogView-3-Flash` +- 端口:`3000` +- 鉴权:**无服务端密钥**,每次请求必须从 header 携带智谱 token + +--- + +## 快速开始 + +### 启动(docker-compose) + +仓库根目录 `docker-compose.yml` 已包含本服务: + +```bash +cd /root/workspace/tools/agent +docker compose up -d --build mcp_image_task +``` + +服务容器名 `mcp_image_task`,容器内端口 3000,**默认不占宿主端口**:agent 走 `agent-mcp-net` +按容器名访问(`http://mcp_image_task:3000/mcp`)。需要从宿主机 curl 调试时,去仓库根 +`docker-compose.yml` 把 `mcp_image_task` 注释掉的 `ports` 两行打开(默认写的是 8082),调试完记得注释回去。 + +```bash +# 不占端口的健康检查 +docker exec mcp_image_task node -e "fetch('http://localhost:3000/health').then(r=>r.text()).then(console.log)" +# {"status":"ok","service":"image_task","sessions":0,"tasks":0} +``` + +### MCP 客户端配置 + +#### Claude Desktop / Cursor 等支持 `headers` 配置的客户端 + +```jsonc +// Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json +// Cursor: ~/.cursor/mcp.json +{ + "mcpServers": { + "image_task": { + "url": "http://localhost:8082/mcp", + "headers": { + "Authorization": "Bearer " + } + } + } +} +``` + +> 上面 `url` 里的端口 `8082` 需要先把 compose 里注释的 `ports` 打开(默认不占宿主端口)。 + +> **重要**:客户端必须在 **每一个 HTTP 请求**(`initialize` / `notifications/initialized` / `tools/call`)都带上 `Authorization` header。配置在 `headers` 里、由客户端自动重发即可。直连模式下 token 不在 session 间共享。 + +#### 不支持 `headers` 字段的客户端 + +如果客户端只支持 `command`/`args` 启动方式,可改用 stdio 模式(需自行包一层把 token 注入环境变量,再让工具回调从环境变量读——当前实现 HTTP 模式下不依赖环境变量,需自行扩展)。 + +--- + +## 工具:image_task + +管理图片生成异步任务。典型流程:`op=create` 拿 `task_id`,然后不断 `op=get` 直到 `task_status` 为 `SUCCESS` 或 `FAIL`。 + +| op | 作用 | 说明 | +|---|---|---| +| `create` | 提交图片生成任务,**立即**返回 `task_id`,生成在后台执行 | 需要 `prompt` | +| `get` | 查询任务状态;`SUCCESS` 时返回图片 URL | 需要 `task_id` | + +> 上游智谱 images 接口是同步阻塞的;这里的异步是对外的统一形态(对齐 `video_task`),服务内部把同步调用丢到后台跑并回写任务表。 + +### 参数(AI 可见) + +| 名称 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `op` | `"create"` \| `"get"` | ✅ | 要执行的操作 | +| `prompt` | string | op=create 时 ✅ | 图片生成提示词,描述想要的画面内容 | +| `task_id` | string | op=get 时 ✅ | `op=create` 返回的任务 ID | + +> 图片尺寸不再透传,走上游默认;尺寸档位与成本/成功率挂钩,AI 传错值经常直接报错。 + +### Model 控制(不在工具参数中暴露) + +模型名由调用方在 **tools/call 这一次的 HTTP header** 中传递,**AI 看不到也填不了**,避免其误传。识别顺序(首个非空值生效): + +| 优先级 | Header | +|---|---| +| 1 | `X-Image-Task-Model` | +| 2 | `X-Mcp-Model` | +| 3 | `X-Model` | + +如果都没传,走代码内常量 `DEFAULT_MODEL = "CogView-3-Flash"`。 + +**为什么不放进工具参数?** 调用方一般是 AI 助手(Claude / Cursor 等),它不需要也没能力选择用哪个模型;模型选择属于部署/路由策略,由请求的发起方在 HTTP header 里注入更可控。 + +### 返回 + +`op=create` 成功时立即返回 `task_id`(生成已转入后台): + +```jsonc +{ + "content": [ + { "type": "text", "text": "Model: CogView-3-Flash\ntask_id: \ntask_status: PROCESSING\n\nImage generation is running in background. Call this tool again with op=\"get\" and task_id=\"\" to fetch the result." } + ] +} +``` + +`op=get` 按任务状态返回: + +- `PROCESSING`:提示几秒后再查; +- `SUCCESS`:若干 `text` 块,第一块是摘要,后续每块各包含一张图片的 URL(方便 LLM 直接贴图或下载): + +```jsonc +{ + "content": [ + { "type": "text", "text": "task_id: \nmodel: CogView-3-Flash\ntask_status: SUCCESS\nImage 1: https://maas-watermark-prod-new.cn-wlcb.ufileos.com/..." }, + { "type": "text", "text": "https://maas-watermark-prod-new.cn-wlcb.ufileos.com/..." } + ] +} +``` + +- `FAIL`:`isError: true`,正文含 `task_status: FAIL` 与错误信息(上游 4xx/5xx、无 URL 返回等都会归档到这里)。 + +URL 由智谱签名下发,**带有效期**(通常 24h),如需长期保存请在收到后及时转存到自己的存储。 + +--- + +## 鉴权细节 + +每个 HTTP 请求必须携带智谱 API Token,server 从以下 header 字段按顺序识别,**首个非空值生效**: + +| 优先级 | Header | 说明 | +|---|---|---| +| 1 | `X-Image-Task-Token: ` | 直传,避免与客户端自身的 Authorization 冲突 | +| 2 | `X-Mcp-Token: ` | 通用兜底 | +| 3 | `Authorization: Bearer ` | 标准 OAuth 风格(排最后是为避免误用) | + +Token 仅在每次 tool call 时从 header 读取,不写入任何存储、不进 session。 + +### 错误响应 + +| 场景 | HTTP 状态 | 表现 | +|---|---|---| +| initialize 时缺 token | `401` | JSON-RPC `error.message` 提示补充 header | +| op=create 缺 prompt / op=get 缺 task_id | `200`(MCP 工具返回) | `isError: true`,参数提示 | +| op=get 查不到任务(ID 错/已过期/服务重启过) | `200`(MCP 工具返回) | `isError: true`,提示 unknown task_id | +| 智谱 API 4xx/5xx | `200`(MCP 工具返回) | 在 `op=get` 中以 `isError: true` + `task_status: FAIL` 呈现,正文含智谱返回的状态码和 body | +| 网络失败 | `200`(MCP 工具返回) | 同上,`task_status: FAIL`,正文含 `fetch` 错误信息 | +| 上游挂住不回(超时 >120s) | `200`(MCP 工具返回) | 同上,`task_status: FAIL`,正文提示 timed out;不会出现永久 PROCESSING 的僵尸任务 | + +--- + +## 用 curl 手工调试 + +MCP Streamable HTTP 不是普通 REST,**必须按顺序**:`initialize` → `notifications/initialized` → `tools/call`。下面用一行版串起来: + +```bash +# 把 替换成你智谱的 API Key +TOKEN="" + +# 1. initialize 拿 sessionId +SESSION=$(curl -s -D - -X POST http://localhost:8082/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -d '{ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2024-11-05", + "capabilities": {}, + "clientInfo": { "name": "curl", "version": "1.0" } + } + }' | grep -i '^mcp-session-id:' | awk '{print $2}' | tr -d '\r\n') + +echo "Session: $SESSION" + +# 2. notifications/initialized +curl -s -X POST http://localhost:8082/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Mcp-Session-Id: $SESSION" \ + -d '{"jsonrpc": "2.0", "method": "notifications/initialized"}' + +# 3. 列出工具(可选验证) +curl -s -X POST http://localhost:8082/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Mcp-Session-Id: $SESSION" \ + -d '{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}' + +# 4. 调 image_task(op=create,立即返回 task_id) +curl -s -X POST http://localhost:8082/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Mcp-Session-Id: $SESSION" \ + -d '{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "image_task", + "arguments": { + "op": "create", + "prompt": "一只可爱的小猫咪,坐在阳光明媚的窗台上,背景是蓝天白云" + } + } + }' + +# 5. 拿上一步返回的 task_id 轮询结果(直到 SUCCESS / FAIL) +curl -s -X POST http://localhost:8082/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Mcp-Session-Id: $SESSION" \ + -d '{ + "jsonrpc": "2.0", + "id": 4, + "method": "tools/call", + "params": { + "name": "image_task", + "arguments": { + "op": "get", + "task_id": "<上一步返回的 task_id>" + } + } + }' +``` + +响应是 SSE 格式(`event: message` + `data: {...}`),用 `grep '^data:'` 抽 JSON 即可。 + +--- + +## 架构与文件 + +``` +image_task/ +├── Dockerfile # node:22-slim,安装依赖后启动 MCP HTTP server +├── .dockerignore # 排除 node_modules +├── package.json # @modelcontextprotocol/sdk + express + zod +├── README.md # 本文件 +└── src/ + └── mcp-server.js # 单文件实现:HTTP server + MCP transport + 单工具(op 分发) +``` + +### 关键设计 + +- **单工具 + `op` 分发**:`image_task(op=create|get)`,与 `video_task` 的服务形态完全一致,agent 侧一套轮询逻辑通吃图片/视频 +- **同步上游 → 异步契约**:智谱 images 接口只支持同步,所以服务自维护一张任务表来模拟异步: + - `create` 本地生成 `task_id`(`randomUUID`),登记 `PROCESSING`,把同步调用丢后台(fire-and-forget),立即返回 + - 后台完成时回写 `SUCCESS`(含 URLs)或 `FAIL`(含错误);上游同步调用带 120s 超时(`AbortSignal.timeout`),超时记 `FAIL`,杜绝僵尸 `PROCESSING` + - `get` 只读本地表,不碰上游 + - 表为进程内存 Map:已完成任务保留 1 小时(TTL)、容量上限 1000,每次 `create` 顺带淘汰;**容器重启后任务丢失**,`get` 会报 unknown task_id;**不适用于多副本部署**(表不互通) + - token/model 在 `create` 那一刻从请求 header 捕获进闭包,后台完成前不再读取,保持「每请求读 header」的无状态设计 +- **每 session 一个 transport + server**:通过 `Mcp-Session-Id` 复用,避免每请求重建 +- **模型参数不入 schema**:model 只从 HTTP header 读取(`X-Image-Task-Model` / `X-Mcp-Model` / `X-Model`),AI 不可见 +- **URL 提取**:`response.data[].url` 为准,若返回 `b64_json` 也会一并归档进任务表 + +### 默认模型 + +```js +// src/mcp-server.js +const DEFAULT_MODEL = "CogView-3-Flash"; +``` + +修改后 `docker compose up -d --build mcp_image_task` 即可生效。 + +--- + +## 常见问题 + +**Q: AI 不知道有哪些 model 可选,怎么办?** +A: 这是设计意图。模型选择属于路由策略,不让 AI 决策。调用方在 HTTP header `X-Image-Task-Model` 里注入即可。 + +**Q: 换模型需要重连 MCP session 吗?** +A: 不需要。Model header 在每次 `tools/call` 都从当前请求读取,不需要重建 session。 + +**Q: 上游是同步接口,为什么对外做成异步?** +A: 为了和 `video_task` 保持同一套任务型契约,agent 侧只需维护一种「create 后轮询 get」的调用模式。同步调用被放到后台执行,对 AI 而言表现为标准异步任务。 + +**Q: 任务一直 PROCESSING 会不会没完没了?** +A: 不会。上游同步调用封顶 120s(`AbortSignal.timeout`),超时直接记 `FAIL`,`get` 会拿到明确的 timed out 错误;不存在僵尸任务。 + +**Q: create 之后服务容器重启了,get 会怎样?** +A: 任务表在进程内存里,重启即丢失,`get` 会返回 unknown task_id 的 `isError`。需要重新 `create`。图片生成只跑几秒,受影响窗口很小;若将来要上多副本或需要可靠恢复,再把表换成持久化存储。 + +**Q: 为什么 get 不需要等上游?** +A: `get` 只读本地任务表,上游调用只发生在 `create` 的后台一次,不会因轮询而重复计费/重复生图。 + +**Q: 为什么 Model 优先级不是「工具参数 > header」?** +A: 因为我们故意不在 schema 暴露 model 参数,AI 根本不会传 model,所以「工具参数 > header」这条分支实际上不存在。 + +**Q: Token 会不会泄露到日志?** +A: 当前实现只在 session 内存里持有,不会写入 stdout/stderr。Container 日志只打印 session id。 + +**Q: 收到 `Missing valid Mcp-Session-Id` 错误?** +A: 漏发了 `Mcp-Session-Id` header,或调 `tools/call` 前没先 `initialize`。 + +**Q: URL 多久过期?** +A: 智谱签发 URL 默认 24h 左右,详见响应里的 `Expires` 参数。需要长期使用请自行转存到 OSS/S3。 diff --git a/mcp/image_task/package.json b/mcp/image_task/package.json new file mode 100644 index 0000000..f172c50 --- /dev/null +++ b/mcp/image_task/package.json @@ -0,0 +1,14 @@ +{ + "name": "mcp_image_task", + "version": "1.0.0", + "description": "MCP server for image generation via Zhipu BigModel CogView (single tool image_task with op=create)", + "type": "module", + "main": "src/mcp-server.js", + "scripts": { + "start": "node src/mcp-server.js --http --port 3000 --host 0.0.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.0.4", + "express": "^4.21.0" + } +} diff --git a/mcp/image_task/src/mcp-server.js b/mcp/image_task/src/mcp-server.js new file mode 100644 index 0000000..1b85e10 --- /dev/null +++ b/mcp/image_task/src/mcp-server.js @@ -0,0 +1,486 @@ +#!/usr/bin/env node +import express from "express"; +import { randomUUID } from "node:crypto"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; + +const ZHIPU_API_URL = + "https://open.bigmodel.cn/api/paas/v4/images/generations"; +const DEFAULT_MODEL = "CogView-3-Flash"; + +// 上游同步调用耗时上限(出图几十秒量级,留足余量)。 +// 超时后任务记为 FAIL,避免上游挂而不回时永远卡在 PROCESSING。 +const UPSTREAM_TIMEOUT_MS = 180_000; + +// ── 优雅退出 ────────────────────────────────────────────────────────────── +// 容器里 node 以 PID 1 运行且未注册 SIGTERM 处理器时,内核不会对其执行默认 +// 终止动作,docker stop/restart 会白等满 10s 宽限期才被 SIGKILL。 +// 显式注册处理器,关闭 MCP session 与长连接后立即退出;3s 定时器为兜底。 +let httpServer = null; +let closeAllSessions = () => {}; +let shuttingDown = false; + +function shutdown(sig) { + if (shuttingDown) return; + shuttingDown = true; + console.log(`[image] received ${sig}, shutting down`); + closeAllSessions(); + if (!httpServer) process.exit(0); // stdio 模式无监听,直接退 + httpServer.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 3000).unref(); +} +process.on("SIGTERM", () => shutdown("SIGTERM")); +process.on("SIGINT", () => shutdown("SIGINT")); + +function parseArgs(argv) { + const args = { + http: false, + port: 3000, + host: "0.0.0.0", + }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--http") args.http = true; + else if (a === "--port") args.port = parseInt(argv[++i], 10); + else if (a === "--host") args.host = argv[++i]; + } + return args; +} + +function pickToken(headers) { + if (!headers) return null; + const candidates = [ + headers["x-image-task-token"], + headers["x-mcp-token"], + headers["authorization"], + ]; + for (const v of candidates) { + if (!v) continue; + const s = String(v).trim(); + if (!s) continue; + if (/^Bearer\s+/i.test(s)) { + const t = s.replace(/^Bearer\s+/i, "").trim(); + if (t) return t; + } else { + return s; + } + } + return null; +} + +function pickModel(headers) { + if (!headers) return null; + const v = + headers["x-image-task-model"] || + headers["x-mcp-model"] || + headers["x-model"]; + if (!v) return null; + const s = String(v).trim(); + return s || null; +} + +async function callZhipuImagesGenerations({ token, model, prompt }) { + const body = { model, prompt }; + let resp; + try { + resp = await fetch(ZHIPU_API_URL, { + method: "POST", + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), + }); + } catch (e) { + // AbortSignal.timeout 中止时抛 TimeoutError/AbortError, + // 转成普通错误后由 runImageTask 回写 FAIL + if (e?.name === "TimeoutError" || e?.name === "AbortError") { + throw new Error(`Upstream request timed out after ${UPSTREAM_TIMEOUT_MS} ms`); + } + throw e; + } + const text = await resp.text(); + let data; + try { + data = JSON.parse(text); + } catch { + data = { raw: text }; + } + if (!resp.ok) { + const err = new Error( + `Zhipu API error: ${resp.status} ${resp.statusText} - ${text}` + ); + err.status = resp.status; + err.detail = data; + throw err; + } + return data; +} + +function extractUrls(data) { + if (!data) return []; + if (Array.isArray(data.data)) { + return data.data + .map((it) => it && (it.url || it.b64_json)) + .filter(Boolean); + } + if (typeof data.url === "string") return [data.url]; + return []; +} + +// ===== 自维护任务表(异步语义全靠这层模拟) ===== +// 上游智谱 images 接口是同步阻塞的,但对外要和 video_task 一样提供 +// create(立即返回 task_id)+ get(轮询结果)的异步契约: +// create 登记 PROCESSING 后把同步调用丢到后台跑,get 从表里读最新状态。 +// +// 已知取舍: +// - 表在进程内存里:容器重启/重建后任务丢失,get 会报 unknown task_id; +// 图片生成只跑几秒,窗口很小,不值得为此引入持久化。 +// - 只适用于单实例部署:多副本时 create 和 get 可能打到不同进程,表不互通。 +const TASK_TTL_MS = 60 * 60 * 1000; // 已完成(SUCCESS/FAIL)任务保留 1 小时 +const MAX_TASKS = 1000; // 表容量上限,超出从最老的已完成任务开始淘汰 + +// task_id -> { status, model, prompt, createdAt, urls?, error? } +const tasks = new Map(); + +function pruneTasks() { + const now = Date.now(); + for (const [id, t] of tasks) { + if (t.status !== "PROCESSING" && now - t.createdAt > TASK_TTL_MS) { + tasks.delete(id); + } + } + if (tasks.size > MAX_TASKS) { + // Map 按插入序迭代;PROCESSING 永不主动淘汰 + for (const [id, t] of tasks) { + if (tasks.size <= MAX_TASKS) break; + if (t.status !== "PROCESSING") tasks.delete(id); + } + } +} + +// 后台跑同步上游调用,结果回写任务表(fire-and-forget,不 await) +function runImageTask({ task, token, model, prompt }) { + callZhipuImagesGenerations({ token, model, prompt }) + .then((data) => { + const urls = extractUrls(data); + if (urls.length === 0) { + task.status = "FAIL"; + task.error = `Zhipu returned no image URL. Raw response: ${JSON.stringify(data)}`; + } else { + task.status = "SUCCESS"; + task.urls = urls; + } + }) + .catch((e) => { + task.status = "FAIL"; + task.error = `${e.message}${ + e.detail ? ` Details: ${JSON.stringify(e.detail)}` : "" + }`; + }); +} + +// ===== op=create:提交图片生成(立即返回 task_id,后台执行)===== +async function handleCreate({ args, headers, token }) { + if (!args.prompt) { + return { + isError: true, + content: [{ type: "text", text: 'op=create requires "prompt".' }], + }; + } + + // model 完全由 HTTP header 控制(X-Image-Task-Model / X-Mcp-Model / X-Model), + // 不存进 session,每次从本次请求的 header 读取,未设置则用默认 CogView-3-Flash。 + // AI 看不到 model 参数(schema 中已删除),避免其误传。 + const model = pickModel(headers) || DEFAULT_MODEL; + + pruneTasks(); + const taskId = randomUUID(); + const task = { + status: "PROCESSING", + model, + prompt: args.prompt, + createdAt: Date.now(), + }; + tasks.set(taskId, task); + + // token/model 在此刻从本次请求 header 捕获进闭包,后台完成前无需再取 + runImageTask({ task, token, model, prompt: args.prompt }); + + const summary = + `Model: ${model}\n` + + `task_id: ${taskId}\n` + + `task_status: PROCESSING\n` + + `\n` + + `Image generation is running in background. ` + + `Call this tool again with op="get" and task_id="${taskId}" to fetch the result.`; + + return { content: [{ type: "text", text: summary }] }; +} + +// ===== op=get:查询任务状态(只读本地表,不碰上游)===== +async function handleGet({ args }) { + if (!args.task_id) { + return { + isError: true, + content: [{ type: "text", text: 'op=get requires "task_id".' }], + }; + } + + const task = tasks.get(args.task_id); + if (!task) { + return { + isError: true, + content: [ + { + type: "text", + text: + `Unknown task_id "${args.task_id}". ` + + `Finished tasks are kept for 1 hour and are lost on service restart.`, + }, + ], + }; + } + + if (task.status === "PROCESSING") { + return { + content: [ + { + type: "text", + text: + `task_id: ${args.task_id}\n` + + `model: ${task.model}\n` + + `task_status: PROCESSING\n` + + `\n` + + `Call op="get" again in a few seconds.`, + }, + ], + }; + } + + if (task.status === "FAIL") { + return { + isError: true, + content: [ + { + type: "text", + text: `task_id: ${args.task_id}\ntask_status: FAIL\nerror: ${task.error}`, + }, + ], + }; + } + + // SUCCESS:输出格式与原同步版 create 一致(摘要块 + 每张图一个 URL 块) + const lines = task.urls.map((u, i) => `Image ${i + 1}: ${u}`).join("\n"); + const summary = + `task_id: ${args.task_id}\n` + + `model: ${task.model}\n` + + `task_status: SUCCESS\n` + + `${lines}`; + return { + content: [ + { type: "text", text: summary }, + ...task.urls.map((u) => ({ type: "text", text: u })), + ], + }; +} + +function buildServer() { + const server = new McpServer( + { + name: "image_task", + version: "1.0.0", + }, + { + capabilities: { + tools: {}, + }, + } + ); + + server.tool( + "image_task", + `Manages asynchronous image generation tasks. + +op=create Submit a new task. Returns a task_id immediately; generation runs in background. + Requires prompt. +op=get Fetch the status of a previously submitted task. Requires task_id. + On SUCCESS, returns the image URLs. + +Typical flow: call op=create, then call op=get with the returned task_id until task_status is SUCCESS or FAIL.`, + { + op: z.enum(["create", "get"]).describe("Operation to perform."), + prompt: z + .string() + .min(1) + .optional() + .describe( + "Image generation prompt; describe the desired scene in detail. Required when op=create." + ), + task_id: z + .string() + .min(1) + .optional() + .describe("task_id returned by op=create. Required when op=get."), + }, + async (args, extra) => { + // SDK 在 tool callback 的 extra.requestInfo.headers 里会透传当前 HTTP 请求的 headers + // (参见 webStandardStreamableHttp.js: buildRequestInfo 段) + const headers = extra?.requestInfo?.headers; + const token = pickToken(headers); + if (!token) { + return { + isError: true, + content: [ + { + type: "text", + text: + "Missing authentication token.", + }, + ], + }; + } + + switch (args.op) { + case "create": + return await handleCreate({ args, headers, token }); + case "get": + return await handleGet({ args }); + default: + return { + isError: true, + content: [ + { + type: "text", + text: `Unknown op "${args.op}" (available: create, get).`, + }, + ], + }; + } + } + ); + + return server; +} + +async function startHttp({ port, host }) { + const app = express(); + app.use(express.json({ limit: "2mb" })); + + // session -> { server, transport } 映射 + const sessions = new Map(); + + closeAllSessions = () => { + for (const { server, transport } of sessions.values()) { + try { + transport.close(); + } catch {} + try { + server.close(); + } catch {} + } + sessions.clear(); + // 掰掉未关闭的 SSE / keep-alive 连接,否则 httpServer.close() 回调不会触发 + httpServer?.closeAllConnections?.(); + }; + + app.get("/health", (_req, res) => { + res.json({ + status: "ok", + service: "image_task", + sessions: sessions.size, + tasks: tasks.size, + }); + }); + + async function handleSessionRequest(req, res) { + const sessionId = req.headers["mcp-session-id"]; + + // 已有 session:复用 transport + if (sessionId && sessions.has(sessionId)) { + const { transport } = sessions.get(sessionId); + await transport.handleRequest(req, res, req.body); + return; + } + + // 新 session:必须是 initialize 请求 + if (!isInitializeRequest(req.body)) { + res.status(400).json({ + jsonrpc: "2.0", + error: { + code: -32000, + message: "Bad Request: missing valid Mcp-Session-Id for non-initialize request", + }, + id: req.body?.id ?? null, + }); + return; + } + + const newId = randomUUID(); + const server = buildServer(); + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => newId, + onsessioninitialized: (id) => { + sessions.set(id, { server, transport }); + }, + }); + + transport.onclose = () => { + if (transport.sessionId) { + sessions.delete(transport.sessionId); + } + }; + + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + } + + // POST /mcp: 主入口 + app.post("/mcp", handleSessionRequest); + + // GET /mcp & DELETE /mcp: 用于 SSE 流 / 会话关闭 + const handleOther = async (req, res) => { + const sessionId = req.headers["mcp-session-id"]; + if (!sessionId || !sessions.has(sessionId)) { + res.status(400).send("Invalid or missing session ID"); + return; + } + const { transport } = sessions.get(sessionId); + await transport.handleRequest(req, res); + }; + app.get("/mcp", handleOther); + app.delete("/mcp", handleOther); + + httpServer = app.listen(port, host, () => { + console.log( + `[image] MCP HTTP server listening on http://${host}:${port}/mcp` + ); + }); +} + +async function startStdio() { + // 保留 stdio 启动方式,便于本地直接调试 + const server = buildServer(); + const { StdioServerTransport } = await import( + "@modelcontextprotocol/sdk/server/stdio.js" + ); + const transport = new StdioServerTransport(); + await server.connect(transport); + console.error("[image] MCP stdio server started"); +} + +const args = parseArgs(process.argv.slice(2)); +if (args.http) { + startHttp({ port: args.port, host: args.host }).catch((e) => { + console.error("[image] failed to start http server:", e); + process.exit(1); + }); +} else { + startStdio().catch((e) => { + console.error("[image] failed to start stdio server:", e); + process.exit(1); + }); +} diff --git a/mcp/video_task/.dockerignore b/mcp/video_task/.dockerignore new file mode 100644 index 0000000..2f6141d --- /dev/null +++ b/mcp/video_task/.dockerignore @@ -0,0 +1,3 @@ +node_modules +npm-debug.log +.DS_Store \ No newline at end of file diff --git a/mcp/video_task/Dockerfile b/mcp/video_task/Dockerfile new file mode 100644 index 0000000..b15f6ad --- /dev/null +++ b/mcp/video_task/Dockerfile @@ -0,0 +1,19 @@ +FROM node:22-slim + +WORKDIR /app + +# 国内构建慢:npm 默认源在国外。想换回官方: +# docker compose build --build-arg NPM_REGISTRY=https://registry.npmjs.org/ mcp_video_task +ARG NPM_REGISTRY=https://mirrors.cloud.tencent.com/npm/ + +# 复制 package.json 并安装依赖 +COPY package.json ./ +RUN npm config set registry "$NPM_REGISTRY" && npm install --omit=dev + +# 复制源码 +COPY . . + +EXPOSE 3000 + +# HTTP 模式:只提供 MCP(/mcp)与 /health;容器外不映射,只在 agent-mcp-net 内被 agent 访问。 +CMD ["node", "src/mcp-server.js", "--http", "--port", "3000", "--host", "0.0.0.0"] diff --git a/mcp/video_task/README.md b/mcp/video_task/README.md new file mode 100644 index 0000000..781db42 --- /dev/null +++ b/mcp/video_task/README.md @@ -0,0 +1,310 @@ +# MCP Video Task + +基于 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 的视频生成服务,对接智谱 BigModel 的视频生成**异步**接口,支持**文生视频**和**图生视频**。只有一个工具 `video_task`,用 `op` 区分动作:`op=create` 提交任务、`op=get` 单次查询结果。Server **不内部轮询**——AI 拿到 `task_id` 后自己决定什么时候用 `op="get"` 复查。 + +- 协议:MCP **Streamable HTTP**(单端点 `/mcp`,支持 SSE 流) +- 上游:[智谱 BigModel 视频生成(异步)](https://docs.bigmodel.cn/api-reference/模型-api/视频生成异步) + [查询异步结果](https://docs.bigmodel.cn/api-reference/模型-api/查询异步结果) +- 默认模型:`cogvideox-flash` +- 端口:容器内 `3000`(MCP `/mcp` + `/health`,**容器外不映射**,只在 `agent-mcp-net` 内被 agent 访问) +- 鉴权:**无服务端密钥**,每次请求必须从 header 携带智谱 token +- 本地文件需要公网 URL 时:不传字节,AI 直接调用 agent 内置的「公开临时 URL」工具拿到短命链接(见下节) + +--- + +## 快速开始 + +### 启动(docker-compose) + +仓库根目录 `docker-compose.yml` 已包含本服务: + +```bash +cd /root/workspace/tools/agent +docker compose up -d --build mcp_video_task +``` + +服务容器名 `mcp_video_task`,**默认不占宿主机端口**:由 agent 走 `agent-mcp-net` 按容器名访问 +(`http://mcp_video_task:3000/mcp`)。需要从宿主机 curl 调试时,去仓库根 `docker-compose.yml` +把 `mcp_video_task` 注释掉的 `ports` 两行打开(映的是 MCP 端口 3000,仅本机短时调试用)。 + +```bash +# 容器内健康检查(无需占端口) +docker exec mcp_video_task node -e "fetch('http://localhost:3000/health').then(r=>r.text()).then(console.log)" +# {"status":"ok","service":"video_task","sessions":0} +``` + +> 下文 curl 示例里的 `localhost:8083` 均指“临时打开了调试端口”的情形。 + +### MCP 客户端配置 + +#### Claude Desktop / Cursor 等支持 `headers` 配置的客户端 + +```jsonc +// Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json +// Cursor: ~/.cursor/mcp.json +{ + "mcpServers": { + "video_task": { + "url": "http://localhost:8083/mcp", + "headers": { + "Authorization": "Bearer " + } + } + } +} +``` + +> 上面 `url` 里的端口 `8083` 需要先把 compose 里注释的 `ports` 打开(默认不占宿主端口)。 + +> **重要**:客户端必须在 **每一个 HTTP 请求**(`initialize` / `notifications/initialized` / `tools/call`)都带上 `Authorization` header。 + +--- + +## 工具:video_task + +单个工具,`op` 必填,只有两个取值: + +| op | 作用 | 同步/异步 | +|---|---|---| +| `create` | 提交一个视频生成任务,立刻返回 `task_id` | 同步(仅提交) | +| `get` | 用 `task_id` 拉一次当前结果 | 同步(单次查询,不轮询) | + +### 参数(AI 可见) + +| 名称 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `op` | `"create"` \| `"get"` | ✅ | 要执行的操作 | +| `prompt` | string | op=create 时与 `image_url` 二选一 | 视频文本描述,最大 512 字符;与 `image_url` 同传时作为运动/动作描述 | +| `image_url` | string (URL) | ❌ | 参考图 URL(**单张**,不支持数组 / 多张 / 首尾帧)。图片 ≤ 5MB,格式 png/jpeg/jpg。本地文件请先用 agent 内置的公开临时 URL 工具换成公网链接(上一节) | +| `with_audio` | boolean | ❌ | 是否生成 AI 音效,默认 `false`(仅 op=create 使用) | +| `task_id` | string | op=get 时必填 | `op=create` 返回的 `id` | + +### 服务端 Header 覆盖项(AI 看不到) + +| Header | 类型 | 默认 | 说明 | +|---|---|---|---| +| `X-Video-Task-Model` / `X-Mcp-Model` / `X-Model` | string | `cogvideox-flash` | 覆盖模型 | +| `X-Video-Task-Quality` | string | `speed` | `speed`(速度优先)或 `quality`(质量优先) | +| `X-Video-Task-Fps` | int | `30` | `30` 或 `60` | +| `X-Video-Task-Watermark` | bool | `true` | 是否添加 AI 水印;关闭需先在智谱后台签署免责声明 | + +模型名串识别顺序(首个非空值生效):`X-Video-Task-Model` → `X-Mcp-Model` → `X-Model` → 默认。 + +### 返回(op=create) + +立刻返回智谱提交结果: + +```jsonc +{ + "content": [ + { "type": "text", "text": "Model: cogvideox-flash\ntask_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\nrequest_id: yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy\ntask_status: PROCESSING\n\nVideo generation is asynchronous. Call this tool again with op=\"get\" and task_id=\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\" to fetch the result." } + ] +} +``` + +`task_status` 通常为 `PROCESSING`,极少数情况下可能直接 `SUCCESS`(极快完成的短任务)。 + +### 返回(op=get) + +- **`SUCCESS`**:返回 `Video URL`(智谱签名 URL,**24h 左右有效**,需及时转存),外加一张 `Cover` 封面图: + ```jsonc + { + "content": [ + { "type": "text", "text": "task_id: ...\nmodel: cogvideox-flash\ntask_status: SUCCESS\nVideo URL: https://...\nCover: https://..." }, + { "type": "text", "text": "https://...video url..." } + ] + } + ``` +- **`PROCESSING`**:`isError: false`,正文给出当前状态,建议稍候再查。 +- **`FAIL`**:`isError: true`,正文含 `task_status` 和智谱返回的 `error` 详情。 + +--- + +## 本地文件 → 公网 URL(本服务不搬字节) + +`image_url` 必须是一个**公网可达**的 URL(智谱服务器会自己去拉)。图片在本地盘上时,本服务不负责上传: +agent 侧已集成为一个 **tool**,AI 直接传文件路径就能拿到一条公开临时 URL,拿来填 `image_url` 即可, +不需要 curl 任何地址、不需要任何配置。 + +- 文件始终躺在 agent 的任务目录里,零拷贝;链接短命、到期或 agent 重启后失效。 +- 智谱只在提交任务那一刻拉一次图,短命链接完全够用。 + +--- + +## 鉴权细节 + +每个 HTTP 请求必须携带智谱 API Token,server 从以下 header 字段按顺序识别,**首个非空值生效**: + +| 优先级 | Header | 说明 | +|---|---|---| +| 1 | `X-Video-Task-Token: ` | 直传,避免与客户端自身的 Authorization 冲突 | +| 2 | `X-Mcp-Token: ` | 通用兜底 | +| 3 | `Authorization: Bearer ` | 标准 OAuth 风格(排最后是为避免误用) | + +Token 仅在每次 tool call 时从 header 读取,不写入任何存储、不进 session。 + +### 错误响应 + +| 场景 | HTTP 状态 | 表现 | +|---|---|---| +| initialize 时缺 token | `401` | JSON-RPC `error.message` 提示补充 header | +| 智谱 API 4xx/5xx | `200`(MCP 工具返回) | `isError: true`,正文含智谱返回的状态码和 body | +| 网络失败 | `200`(MCP 工具返回) | `isError: true`,正文含 `fetch` 错误信息 | +| 上游挂住不回(超时 >30s) | `200`(MCP 工具返回) | `isError: true`,正文提示 timed out;`fetch` 带 `AbortSignal.timeout`,不会无限卡住工具调用 | + +--- + +## 推荐用法(AI 视角) + +``` +1. 如果手头是【本地文件】:先调用 agent 内置的「公开临时 URL」工具拿到一条公网链接(上一节),再进第 2 步 +2. 调用 video_task({ op: "create", prompt, image_url?, with_audio? }) +3. 拿到 task_id → 等待若干秒(建议 2~5 秒) +4. 调用 video_task({ op: "get", task_id }) + - 若 PROCESSING → 等一会再调 + - 若 SUCCESS → 拿到 video URL,贴给用户 / 下载 / 二次编辑 + - 若 FAIL → 展示错误信息,结束 +``` + +> `image_url` 必须是公网可达 URL;本地文件走 agent 内置工具,本服务不参与上传。 + +--- + +## 用 curl 手工调试 + +MCP Streamable HTTP 不是普通 REST,**必须按顺序**:`initialize` → `notifications/initialized` → `tools/call`。下面用一行版串起来: + +```bash +# 把 替换成你智谱的 API Key +TOKEN="" + +# 1. initialize 拿 sessionId +SESSION=$(curl -s -D - -X POST http://localhost:8083/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -d '{ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2024-11-05", + "capabilities": {}, + "clientInfo": { "name": "curl", "version": "1.0" } + } + }' | grep -i '^mcp-session-id:' | awk '{print $2}' | tr -d '\r\n') + +echo "Session: $SESSION" + +# 2. notifications/initialized +curl -s -X POST http://localhost:8083/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Mcp-Session-Id: $SESSION" \ + -d '{"jsonrpc": "2.0", "method": "notifications/initialized"}' + +# 3. 列出工具(可选验证) +curl -s -X POST http://localhost:8083/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Mcp-Session-Id: $SESSION" \ + -d '{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}' + +# 4. 提交文生视频任务(op=create) +curl -s -X POST http://localhost:8083/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Mcp-Session-Id: $SESSION" \ + -d '{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "video_task", + "arguments": { + "op": "create", + "prompt": "A cat is playing with a ball.", + "with_audio": true + } + } + }' + +# 5. 查结果(op=get,替换下面的 ) +curl -s -X POST http://localhost:8083/mcp \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Mcp-Session-Id: $SESSION" \ + -d '{ + "jsonrpc": "2.0", + "id": 4, + "method": "tools/call", + "params": { + "name": "video_task", + "arguments": { "op": "get", "task_id": "" } + } + }' +``` + +响应是 SSE 格式(`event: message` + `data: {...}`),用 `grep '^data:'` 抽 JSON 即可。 + +## 架构与文件 + +``` +video_task/ +├── Dockerfile # node:22-slim,安装依赖后启动 MCP HTTP server +├── .dockerignore # 排除 node_modules +package.json # @modelcontextprotocol/sdk + express +├── README.md # 本文件 +└── src/ + └── mcp-server.js # 单文件实现:HTTP server + MCP transport + 单工具(op 分发) +``` + +### 关键设计 + +- **单工具 + `op` 分发**:`video_task(op=create|get)` 替代原来的 `video_gen` + `query_video` 双工具,AI 面对的工具面更小,参数按 op 在 handler 侧校验 +- **每 session 一个 transport + server**:通过 `Mcp-Session-Id` 复用,避免每请求重建 +- **Token 闭包注入**:在 Express 入口处从 header 提取 token,闭包传给 tool 回调;不依赖 SDK 内部字段 +- **AI 可见 vs AI 不可见**: + - AI 只看到 `op / prompt / image_url / with_audio / task_id` + - `model / quality / fps / watermark_enabled` 全部由 HTTP header 注入,避免 AI 误传或被诱导调高价档 +- **异步语义暴露给 AI**:服务端不做轮询,`op=create` 只提交、`op=get` 只查一次。AI 自主决定节奏 +- **服务端自动 `request_id`**:每次提交服务端生成一个 UUID 作为智谱 `request_id`,便于日志关联,但不暴露给 AI +- **不搬字节**:本地文件 -> 公网 URL 完全由 agent 侧集成的「公开临时 URL」工具完成,本服务不参与;所以本体不加任何写入口、不落盘、不需要额外端口 +- **链接短命**:公开临时 URL 到期或 agent 重启后失效;智谱只需在提交任务那一刻拉一次图 + +### 默认模型 + +```js +// src/mcp-server.js +const DEFAULT_MODEL = "cogvideox-flash"; +``` + +修改后 `docker compose up -d --build mcp_video_task` 即可生效。 + +--- + +## 常见问题 + +**Q: AI 拿到 task_id 后立刻 op=get 一直 PROCESSING,怎么办?** +A: AI 自己 sleep 几秒再调(建议 2~5 秒间隔)。这是设计取舍:把节奏控制权交给 AI 模型,而不是服务端硬编码超时。 + +**Q: 视频 URL 多久过期?** +A: 智谱签发 URL 默认 24h 左右。需要在收到后及时转存到自己的 OSS/S3。 + +**Q: 为什么 quality / fps 不让 AI 直接传?** +A: 这些是技术档位,与成本/单价挂钩。让 AI 自主挑 `quality=quality + fps=60` 会爆账号预算。改成 header 由部署方注入更可控。 + +**Q: 报错 `Missing valid Mcp-Session-Id`?** +A: 漏发了 `Mcp-Session-Id` header,或调 `tools/call` 前没先 `initialize`。 + +**Q: 同一 task_id 能并发查吗?** +A: 可以。`/async-result/{id}` 是幂等的读接口,并发无副作用。 + +**Q: 换模型需要重连 MCP session 吗?** +A: 不需要。Model header 在每次 `tools/call` 都从当前请求读取。 + +**Q: 上传的图片多久过期?** +A: 本服务不存图,不存在“上传的图片”:要用的图在 agent 的任务目录里,AI 用 agent 内置的公开临时 URL 工具现取一条短命链接给智谱拉。链接过期或 agent 重启后该 URL 失效,但智谱只在提交任务时拉一次,不受影响。 diff --git a/mcp/video_task/package.json b/mcp/video_task/package.json new file mode 100644 index 0000000..dcc7e0a --- /dev/null +++ b/mcp/video_task/package.json @@ -0,0 +1,14 @@ +{ + "name": "mcp_video_task", + "version": "1.0.0", + "description": "MCP server for async video generation tasks via Zhipu BigModel cogvideox-flash (single tool video_task with op=create/get)", + "type": "module", + "main": "src/mcp-server.js", + "scripts": { + "start": "node src/mcp-server.js --http --port 3000 --host 0.0.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.0.4", + "express": "^4.21.0" + } +} \ No newline at end of file diff --git a/mcp/video_task/src/mcp-server.js b/mcp/video_task/src/mcp-server.js new file mode 100644 index 0000000..92a9467 --- /dev/null +++ b/mcp/video_task/src/mcp-server.js @@ -0,0 +1,521 @@ +#!/usr/bin/env node +import express from "express"; +import { randomUUID } from "node:crypto"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; + +const ZHIPU_SUBMIT_URL = + "https://open.bigmodel.cn/api/paas/v4/videos/generations"; +const ZHIPU_QUERY_URL = (id) => + `https://open.bigmodel.cn/api/paas/v4/async-result/${encodeURIComponent(id)}`; + +// 默认模型:cogvideox-flash +const DEFAULT_MODEL = "cogvideox-flash"; + +// AI 不可见的服务端默认(可被同名 header 覆盖) +const DEFAULT_QUALITY = "speed"; // speed | quality +const DEFAULT_FPS = 30; // 30 | 60 +const DEFAULT_WATERMARK_ENABLED = true; // 平台政策默认 true + +// submit/query 都是快接口,卡住基本等于上游挂了;限时避免工具调用被拖死 +const UPSTREAM_TIMEOUT_MS = 30_000; + +// ── 优雅退出 ────────────────────────────────────────────────────────────── +// 容器里 node 以 PID 1 运行且未注册 SIGTERM 处理器时,内核不会对其执行默认 +// 终止动作,docker stop/restart 会白等满 10s 宽限期才被 SIGKILL。 +// 显式注册处理器,关闭 MCP session 与长连接后立即退出;3s 定时器为兜底。 +let httpServer = null; +let closeAllSessions = () => {}; +let shuttingDown = false; + +function shutdown(sig) { + if (shuttingDown) return; + shuttingDown = true; + console.log(`[video] received ${sig}, shutting down`); + closeAllSessions(); + if (!httpServer) process.exit(0); // stdio 模式无监听,直接退 + httpServer.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 3000).unref(); +} +process.on("SIGTERM", () => shutdown("SIGTERM")); +process.on("SIGINT", () => shutdown("SIGINT")); + +function parseArgs(argv) { + const args = { + http: false, + port: 3000, + host: "0.0.0.0", + }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--http") args.http = true; + else if (a === "--port") args.port = parseInt(argv[++i], 10); + else if (a === "--host") args.host = argv[++i]; + } + return args; +} + +function pickToken(headers) { + if (!headers) return null; + const candidates = [ + headers["x-video-task-token"], + headers["x-mcp-token"], + headers["authorization"], + ]; + for (const v of candidates) { + if (!v) continue; + const s = String(v).trim(); + if (!s) continue; + if (/^Bearer\s+/i.test(s)) { + const t = s.replace(/^Bearer\s+/i, "").trim(); + if (t) return t; + } else { + return s; + } + } + return null; +} + +function pickModel(headers) { + if (!headers) return null; + const v = + headers["x-video-task-model"] || + headers["x-mcp-model"] || + headers["x-model"]; + if (!v) return null; + const s = String(v).trim(); + return s || null; +} + +function pickHeaderString(headers, name, fallback) { + if (!headers) return fallback; + const v = headers[name]; + if (v === undefined || v === null) return fallback; + const s = String(v).trim(); + return s ? s : fallback; +} + +function pickHeaderInt(headers, name, fallback) { + if (!headers) return fallback; + const v = headers[name]; + if (v === undefined || v === null) return fallback; + const n = parseInt(String(v).trim(), 10); + return Number.isFinite(n) ? n : fallback; +} + +function pickHeaderBool(headers, name, fallback) { + if (!headers) return fallback; + const v = headers[name]; + if (v === undefined || v === null) return fallback; + const s = String(v).trim().toLowerCase(); + if (s === "true" || s === "1" || s === "yes") return true; + if (s === "false" || s === "0" || s === "no") return false; + return fallback; +} + +async function callZhipu({ url, token, method = "POST", body }) { + const init = { + method, + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }, + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), + }; + if (body !== undefined) init.body = JSON.stringify(body); + let resp; + try { + resp = await fetch(url, init); + } catch (e) { + // AbortSignal.timeout 中止时抛 TimeoutError/AbortError,转成明确的超时错误 + if (e?.name === "TimeoutError" || e?.name === "AbortError") { + throw new Error(`Upstream request timed out after ${UPSTREAM_TIMEOUT_MS} ms`); + } + throw e; + } + const text = await resp.text(); + let data; + try { + data = JSON.parse(text); + } catch { + data = { raw: text }; + } + if (!resp.ok) { + const err = new Error( + `Zhipu API error: ${resp.status} ${resp.statusText} - ${text}` + ); + err.status = resp.status; + err.detail = data; + throw err; + } + return data; +} + +// ===== op=create:提交视频生成(同步只提交,立刻返回)===== +async function submitVideo({ + token, + model, + prompt, + image_url, + quality, + with_audio, + fps, + watermark_enabled, +}) { + // 平台要求 image_url 和 prompt 至少传一个(handler 侧已校验) + const body = { + model, + quality, + with_audio: Boolean(with_audio), + watermark_enabled: Boolean(watermark_enabled), + fps, + // 由服务端生成唯一 request_id,便于日志关联;不暴露给 AI + request_id: randomUUID(), + }; + if (prompt) body.prompt = prompt; + if (image_url) body.image_url = image_url; + + return await callZhipu({ url: ZHIPU_SUBMIT_URL, token, body }); + // { model, id, request_id, task_status } +} + +// ===== op=get:查询异步结果(单次拉取,不内部轮询)===== +async function queryAsyncResult({ token, id }) { + return await callZhipu({ + url: ZHIPU_QUERY_URL(id), + token, + method: "GET", + }); + // { id, request_id, model, task_status, video_result?, ... } +} + +// ---------- op=create 的业务处理 ---------- +async function handleCreate({ args, headers, token }) { + if (!args.prompt && !args.image_url) { + return { + isError: true, + content: [ + { + type: "text", + text: 'op=create requires at least one of "prompt" or "image_url".', + }, + ], + }; + } + + // AI 不可见:全部走 header + const model = pickModel(headers) || DEFAULT_MODEL; + const quality = pickHeaderString( + headers, + "x-video-task-quality", + DEFAULT_QUALITY + ); + const fps = pickHeaderInt(headers, "x-video-task-fps", DEFAULT_FPS); + const watermark_enabled = pickHeaderBool( + headers, + "x-video-task-watermark", + DEFAULT_WATERMARK_ENABLED + ); + + try { + const data = await submitVideo({ + token, + model, + prompt: args.prompt, + image_url: args.image_url, + quality, + with_audio: args.with_audio ?? false, + fps, + watermark_enabled, + }); + + const summary = + `Model: ${model}\n` + + `task_id: ${data.id}\n` + + `request_id: ${data.request_id}\n` + + `task_status: ${data.task_status}\n` + + `\n` + + `Video generation is asynchronous. ` + + `Call this tool again with op="get" and task_id="${data.id}" to fetch the result.`; + + return { content: [{ type: "text", text: summary }] }; + } catch (e) { + return { + isError: true, + content: [ + { + type: "text", + text: `Failed to submit video task: ${e.message}${ + e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : "" + }`, + }, + ], + }; + } +} + +// ---------- op=get 的业务处理 ---------- +async function handleGet({ args, token }) { + if (!args.task_id) { + return { + isError: true, + content: [{ type: "text", text: 'op=get requires "task_id".' }], + }; + } + + try { + const data = await queryAsyncResult({ token, id: args.task_id }); + const status = data.task_status || "UNKNOWN"; + + if (status === "SUCCESS") { + const v = (data.video_result || [])[0]; + if (!v || !v.url) { + return { + isError: true, + content: [ + { + type: "text", + text: `Task succeeded but no video URL returned. Raw: ${JSON.stringify( + data + )}`, + }, + ], + }; + } + const summary = + `task_id: ${data.id}\n` + + `model: ${data.model}\n` + + `task_status: SUCCESS\n` + + `Video URL: ${v.url}\n` + + (v.cover_image_url ? `Cover: ${v.cover_image_url}\n` : ""); + return { + content: [ + { type: "text", text: summary }, + { type: "text", text: v.url }, + ], + }; + } + + // PROCESSING / FAIL / 其他:原样返回关键字段 + const errBlock = data.error ? `\nerror: ${JSON.stringify(data.error)}` : ""; + return { + isError: status === "FAIL", + content: [ + { + type: "text", + text: + `task_id: ${data.id}\n` + + `model: ${data.model}\n` + + `task_status: ${status}` + + errBlock, + }, + ], + }; + } catch (e) { + return { + isError: true, + content: [ + { + type: "text", + text: `Failed to query video task: ${e.message}${ + e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : "" + }`, + }, + ], + }; + } +} + +function buildServer() { + const server = new McpServer( + { name: "video_task", version: "1.0.0" }, + { capabilities: { tools: {} } } + ); + + server.tool( + "video_task", + `Manages asynchronous video generation tasks. + +op=create Submit a new task. Returns a task_id immediately; generation runs asynchronously. + Requires at least one of prompt or image_url. + - text-to-video: pass prompt only. + - image-to-video: also pass image_url. +op=get Fetch the status of a previously submitted task. Requires task_id. + On SUCCESS, returns the video URL. + +Typical flow: call op=create, then call op=get with the returned task_id until task_status is SUCCESS or FAIL.`, + { + op: z.enum(["create", "get"]).describe("Operation to perform."), + prompt: z + .string() + .max(512) + .optional() + .describe( + "Video text description (max 512 chars). Used with op=create. When combined with image_url it serves as the motion/action description." + ), + image_url: z + .string() + .url() + .optional() + .describe( + "Reference image for image-to-video. Used with op=create. Must be a publicly reachable URL to a png/jpeg/jpg <= 5MB (for local files, first use the agent's built-in tool to mint a public temporary URL)." + ), + with_audio: z + .boolean() + .optional() + .describe( + "Whether to generate AI audio. Used with op=create. Default false." + ), + task_id: z + .string() + .min(1) + .optional() + .describe("task_id returned by op=create. Required when op=get."), + }, + async (args, extra) => { + const headers = extra?.requestInfo?.headers; + const token = pickToken(headers); + if (!token) { + return { + isError: true, + content: [{ type: "text", text: "Missing authentication token." }], + }; + } + + switch (args.op) { + case "create": + return await handleCreate({ args, headers, token }); + case "get": + return await handleGet({ args, token }); + default: + return { + isError: true, + content: [ + { + type: "text", + text: `Unknown op "${args.op}" (available: create, get).`, + }, + ], + }; + } + } + ); + + return server; +} + +async function startHttp({ port, host }) { + const app = express(); + app.use(express.json({ limit: "2mb" })); + + // session -> { server, transport } 映射 + const sessions = new Map(); + + closeAllSessions = () => { + for (const { server, transport } of sessions.values()) { + try { + transport.close(); + } catch {} + try { + server.close(); + } catch {} + } + sessions.clear(); + // 掰掉未关闭的 SSE / keep-alive 连接,否则 httpServer.close() 回调不会触发 + httpServer?.closeAllConnections?.(); + }; + + app.get("/health", (_req, res) => { + res.json({ status: "ok", service: "video_task", sessions: sessions.size }); + }); + + async function handleSessionRequest(req, res) { + const sessionId = req.headers["mcp-session-id"]; + + // 已有 session:复用 transport + if (sessionId && sessions.has(sessionId)) { + const { transport } = sessions.get(sessionId); + await transport.handleRequest(req, res, req.body); + return; + } + + // 新 session:必须是 initialize 请求 + if (!isInitializeRequest(req.body)) { + res.status(400).json({ + jsonrpc: "2.0", + error: { + code: -32000, + message: + "Bad Request: missing valid Mcp-Session-Id for non-initialize request", + }, + id: req.body?.id ?? null, + }); + return; + } + + const newId = randomUUID(); + const server = buildServer(); + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => newId, + onsessioninitialized: (id) => { + sessions.set(id, { server, transport }); + }, + }); + + transport.onclose = () => { + if (transport.sessionId) { + sessions.delete(transport.sessionId); + } + }; + + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + } + + // POST /mcp: 主入口 + app.post("/mcp", handleSessionRequest); + + // GET /mcp & DELETE /mcp: 用于 SSE 流 / 会话关闭 + const handleOther = async (req, res) => { + const sessionId = req.headers["mcp-session-id"]; + if (!sessionId || !sessions.has(sessionId)) { + res.status(400).send("Invalid or missing session ID"); + return; + } + const { transport } = sessions.get(sessionId); + await transport.handleRequest(req, res); + }; + app.get("/mcp", handleOther); + app.delete("/mcp", handleOther); + + httpServer = app.listen(port, host, () => { + console.log( + `[video] MCP HTTP server listening on http://${host}:${port}/mcp` + ); + }); +} + +async function startStdio() { + const server = buildServer(); + const { StdioServerTransport } = await import( + "@modelcontextprotocol/sdk/server/stdio.js" + ); + const transport = new StdioServerTransport(); + await server.connect(transport); + console.error("[video] MCP stdio server started"); +} + +const args = parseArgs(process.argv.slice(2)); +if (args.http) { + startHttp({ port: args.port, host: args.host }).catch((e) => { + console.error("[video] failed to start http server:", e); + process.exit(1); + }); +} else { + startStdio().catch((e) => { + console.error("[video] failed to start stdio server:", e); + process.exit(1); + }); +} diff --git a/mcp/web_search/Dockerfile b/mcp/web_search/Dockerfile new file mode 100644 index 0000000..6b655d4 --- /dev/null +++ b/mcp/web_search/Dockerfile @@ -0,0 +1,11 @@ +FROM node:22-slim + +WORKDIR /app + +# 零运行时依赖:直接拷贝本地重构的源码,无需 npm install +COPY package.json server.js mcp.js core.js ./ + +EXPOSE 3000 + +# HTTP/SSE 模式监听 3000 端口(stdio 模式见 package.json 的 start:stdio) +CMD ["node", "server.js", "--http", "--port", "3000", "--host", "0.0.0.0"] diff --git a/mcp/web_search/README.md b/mcp/web_search/README.md new file mode 100644 index 0000000..8e5f60a --- /dev/null +++ b/mcp/web_search/README.md @@ -0,0 +1,51 @@ +# web_search + +免费网页搜索 MCP server 的本地重构版(上游开源实现:[@sheep233_/dsh-web-search-free](https://github.com/sheep-programmer/dsh-web-search-free),MIT)。 + +零运行时依赖,只用 Node 内置 `fetch`(Node ≥ 18),**无需 npm install,直接 `node server.js` 启动**。 + +## 结构 + +| 文件 | 职责 | +| --- | --- | +| `core.js` | 搜索后端:Parallel(默认)/ Exa(备用)免费 MCP 端点封装 + 响应解析 | +| `mcp.js` | MCP 协议层:`web_search` 工具定义 + JSON-RPC 分发 | +| `server.js` | 入口:CLI 参数 + stdio / HTTP/SSE 双传输 | + +## 本地启动 + +```bash +# HTTP/SSE 模式(默认 127.0.0.1:3100) +node server.js --http --port 3100 + +# stdio 模式(Claude Code / Codex 直接拉起时用) +node server.js +``` + +MCP 端点: + +- `POST /` — Streamable HTTP(也接受 `Accept: text/event-stream`) +- `GET /sse` + `POST /messages` — 老式 SSE 传输 +- `GET /health` — 健康检查 + +环境变量(均可选): + +- `EXA_API_KEY` — 提升 Exa 匿名限额 +- `SEARCH_TIMEOUT_MS` — 上游搜索超时,默认 30000 + +## Docker + +`docker-compose.yml` 中的 `mcp_web_search` 服务直接构建本目录,Dockerfile 已改为拷贝源码启动(不再有 `npm install -g`)。 + +容器内监听 3000,**默认不占宿主端口**:agent 走 `agent-mcp-net` 按容器名访问 +(`http://mcp_web_search:3000/`)。需要从宿主机 curl 调试时,把仓库根 `docker-compose.yml` 里 +`mcp_web_search` 注释掉的 `ports` 两行打开(默认写的是 8081),调试完记得注释回去。 + +```bash +docker compose build mcp_web_search && docker compose up -d mcp_web_search +# 不占端口的健康检查 +docker exec mcp_web_search node -e "fetch('http://localhost:3000/health').then(r=>r.text()).then(console.log)" +# {"name":"web_search","version":"...","transport":"http/sse","port":3000} +``` + +该服务**无服务端鉴权**(上游是免费端点),**永远不要**对外映射端口——会被白嫆搜索额度。 diff --git a/mcp/web_search/core.js b/mcp/web_search/core.js new file mode 100644 index 0000000..91774c6 --- /dev/null +++ b/mcp/web_search/core.js @@ -0,0 +1,150 @@ +/** + * 零依赖搜索核心:Parallel(默认,匿名免 key)与 Exa(备用)两个免费后端的统一封装。 + * + * 只用 Node 内置 fetch,不依赖任何 npm 包。两个后端都是公开的免费 MCP 端点, + * 本模块以 JSON-RPC `tools/call` 的方式直接调用它们,并归一化成统一的结果结构: + * `{ url, title?, snippet?, publishedAt? }[]`。 + * + * 上游实现参考:@sheep233_/dsh-web-search-free(github.com/sheep-programmer/dsh-web-search-free)。 + */ + +/** Parallel Web Search 免费 MCP 端点(匿名可用,OpenCode 默认后端之一)。 */ +export const PARALLEL_MCP_URL = 'https://search.parallel.ai/mcp'; +/** Exa 免费 MCP 端点(匿名可用;EXA_API_KEY 可提升限额)。 */ +export const EXA_MCP_URL = 'https://mcp.exa.ai/mcp'; + +const USER_AGENT = 'web_search/1.0.0'; +/** 单次上游搜索请求的超时,避免远端挂起拖死 MCP 请求。 */ +const REQUEST_TIMEOUT_MS = Number(process.env.SEARCH_TIMEOUT_MS ?? 30_000); + +/** + * 向免费 MCP 端点发一次 `tools/call`,返回工具结果里的 text 载荷。 + * 响应可能是裸 JSON,也可能是 SSE(`data: {...}`)分帧,两种都兼容。 + */ +async function callMcpTool(endpoint, toolName, toolArgs, signal) { + const response = await fetch(endpoint, { + method: 'POST', + redirect: 'error', + headers: { + 'content-type': 'application/json', + 'accept': 'application/json, text/event-stream', + 'user-agent': USER_AGENT, + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: toolName, arguments: toolArgs }, + }), + ...(signal !== undefined ? { signal } : {}), + }); + if (!response.ok) { + throw new Error(`${toolName} API error (HTTP ${response.status})`); + } + const text = extractToolText(await response.text()); + if (text === undefined) { + throw new Error(`${toolName} returned no tool result`); + } + return text; +} + +/** 从裸 JSON 或 SSE 文本中提取 MCP `tools/call` 的 result.content[].text。 */ +export function extractToolText(body) { + const parsePayload = (raw) => { + try { + const data = JSON.parse(raw); + const item = data.result?.content?.find((c) => c.type === 'text' && typeof c.text === 'string'); + return item?.text || undefined; + } catch { + return undefined; // 不是 JSON 载荷,交给 SSE 行解析 + } + }; + + const trimmed = body.trim(); + if (trimmed.length > 0) { + const direct = parsePayload(trimmed); + if (direct !== undefined) return direct; + } + for (const line of body.split('\n')) { + if (!line.startsWith('data: ')) continue; + const data = parsePayload(line.slice(6)); + if (data !== undefined) return data; + } + return undefined; +} + +/** Parallel 响应解析:text 是内嵌 JSON `{ results: [...] }`。 */ +export function mapParallelResponse(text) { + let payload; + try { + payload = JSON.parse(text); + } catch (error) { + throw new Error(`Parallel search returned an unprocessable payload: ${String(error)}`); + } + const sources = []; + for (const item of payload.results ?? []) { + if (!item.url) continue; + sources.push({ + url: item.url, + ...(item.title ? { title: item.title } : {}), + ...(item.excerpts?.length > 0 ? { snippet: item.excerpts.join(' ') } : {}), + ...(item.publish_date ? { publishedAt: item.publish_date } : {}), + }); + } + return sources; +} + +/** + * Exa 响应解析:text 是纯文本块,每条结果以 `Title: ` 开头: + * ``` + * Title: <标题> + * URL: <链接> + * Published: <日期 | N/A> + * Author: <作者 | N/A> + * Highlights: + * <正文摘要> + * ``` + */ +export function parseExaText(text) { + const blocks = text.split(/(?=^Title: )/m).filter((block) => block.trim().length > 0); + const sources = []; + for (const block of blocks) { + const url = block.match(/^URL: (\S+)$/m)?.[1]; + if (url === undefined) continue; + const title = block.match(/^Title: (.+)$/m)?.[1]?.trim(); + const published = block.match(/^Published: (.+)$/m)?.[1]?.trim(); + const highlights = block.split(/^Highlights:\s*$/m)[1]?.trim(); + sources.push({ + url, + ...(title ? { title } : {}), + ...(highlights ? { snippet: highlights.slice(0, 500) } : {}), + ...(published && published !== 'N/A' ? { publishedAt: published } : {}), + }); + } + return sources; +} + +/** Parallel 搜索(默认免费后端)。 */ +export async function parallelSearch(query, maxResults) { + const text = await callMcpTool(PARALLEL_MCP_URL, 'web_search', { + objective: query, + search_queries: [query], + }, AbortSignal.timeout(REQUEST_TIMEOUT_MS)); + const sources = mapParallelResponse(text); + return maxResults !== undefined ? sources.slice(0, maxResults) : sources; +} + +/** Exa 搜索(备用免费后端;apiKey 可选,用于提升匿名限额)。 */ +export async function exaSearch(query, maxResults, apiKey) { + const endpoint = apiKey + ? `${EXA_MCP_URL}?exaApiKey=${encodeURIComponent(apiKey)}` + : EXA_MCP_URL; + const text = await callMcpTool(endpoint, 'web_search_exa', { + query, + type: 'auto', + numResults: maxResults ?? 8, + livecrawl: 'fallback', + }, AbortSignal.timeout(REQUEST_TIMEOUT_MS)); + const sources = parseExaText(text); + return maxResults !== undefined ? sources.slice(0, maxResults) : sources; +} diff --git a/mcp/web_search/mcp.js b/mcp/web_search/mcp.js new file mode 100644 index 0000000..274d0ae --- /dev/null +++ b/mcp/web_search/mcp.js @@ -0,0 +1,95 @@ +/** + * MCP(Model Context Protocol)协议层:工具清单 + JSON-RPC 分发。 + * + * 与传输无关(stdio / HTTP 都在 server.js 里),只负责把一条 JSON-RPC + * 消息变成 JSON-RPC 响应。支持的 method 与上游 dsh-web-search-free 一致: + * initialize / tools/list / tools/call / ping。 + */ +import { parallelSearch, exaSearch } from './core.js'; + +export const SERVER_NAME = 'web_search'; +export const VERSION = '1.0.0'; +const DEFAULT_PROTOCOL = '2025-03-26'; + +/** 暴露给 MCP 客户端的工具清单。 */ +const TOOLS = [ + { + name: 'web_search', + description: 'Free web search tool. Uses Parallel by default or Exa as fallback. Returns an array of results with title, url, snippet, and publishedAt.', + inputSchema: { + type: 'object', + properties: { + query: { type: 'string', description: 'Search query text' }, + provider: { type: 'string', enum: ['parallel', 'exa'], description: "Backend provider: 'parallel' (default) or 'exa' (fallback)" }, + numResults: { type: 'integer', minimum: 1, default: 8, description: 'Maximum number of results to return (default 8)' }, + }, + required: ['query'], + }, + }, +]; + +/** 执行一次 tools/call;失败时抛 { code, message } 表示工具级错误。 */ +async function callTool(name, args) { + if (name !== 'web_search') throw { code: -32602, message: `unknown tool: ${name}` }; + + const params = args ?? {}; + const query = typeof params.query === 'string' && params.query.trim().length > 0 + ? params.query.trim() + : null; + if (query === null) throw { code: -32602, message: 'query is required' }; + + const provider = params.provider === 'exa' ? 'exa' : 'parallel'; + const numResults = typeof params.numResults === 'number' && Number.isFinite(params.numResults) + ? Math.max(1, Math.floor(params.numResults)) + : 8; + + const sources = provider === 'exa' + ? await exaSearch(query, numResults, process.env.EXA_API_KEY) + : await parallelSearch(query, numResults); + + return { content: [{ type: 'text', text: JSON.stringify(sources, null, 2) }] }; +} + +/** 处理一条请求消息,返回 result;失败时抛 { code, message }。 */ +async function handleRequest(message) { + switch (message.method) { + case 'initialize': + return { + protocolVersion: message.params?.protocolVersion ?? DEFAULT_PROTOCOL, + capabilities: { tools: {} }, + serverInfo: { name: SERVER_NAME, version: VERSION }, + }; + case 'tools/list': + return { tools: TOOLS }; + case 'tools/call': + return callTool(message.params?.name, message.params?.arguments); + case 'ping': + return {}; + default: + throw { code: -32601, message: `method not found: ${String(message.method)}` }; + } +} + +/** + * 解析并执行一条 JSON 消息。 + * @returns 响应信封对象;notification(无 id)返回 null;非法 JSON 返回 undefined。 + */ +export async function dispatch(raw) { + let message; + try { + message = JSON.parse(raw); + } catch { + return undefined; + } + if (message.id === undefined) return null; // 通知不响应 + try { + return { jsonrpc: '2.0', id: message.id, result: await handleRequest(message) }; + } catch (error) { + const e = error; + return { + jsonrpc: '2.0', + id: message.id, + error: { code: typeof e.code === 'number' ? e.code : -32603, message: String(e.message ?? error) }, + }; + } +} diff --git a/mcp/web_search/package.json b/mcp/web_search/package.json new file mode 100644 index 0000000..956422f --- /dev/null +++ b/mcp/web_search/package.json @@ -0,0 +1,19 @@ +{ + "name": "web_search", + "version": "1.0.0", + "private": true, + "description": "Free web search tool. Uses Parallel by default or Exa as fallback.", + "license": "MIT", + "type": "module", + "main": "server.js", + "bin": { + "web_search": "server.js" + }, + "engines": { + "node": ">=18" + }, + "scripts": { + "start": "node server.js --http --port 3000 --host 0.0.0.0", + "start:stdio": "node server.js" + } +} diff --git a/mcp/web_search/server.js b/mcp/web_search/server.js new file mode 100644 index 0000000..7bab7ed --- /dev/null +++ b/mcp/web_search/server.js @@ -0,0 +1,158 @@ +#!/usr/bin/env node +/** + * MCP server 入口 —— 免费网页搜索(Parallel 默认 / Exa 备用,匿名免 key)。 + * + * 本地重构版(上游:@sheep233_/dsh-web-search-free),零运行时依赖,直接 node 启动。 + * + * ## 双传输 + * - **stdio**(默认):`node server.js` + * - `claude mcp add web_search -- node <路径>/server.js` + * - **HTTP/SSE**(监听端口):`node server.js --http --port 3000 --host 0.0.0.0` + * - 兼容 Streamable HTTP(`POST /`)与老式 SSE(`GET /sse` + `POST /messages`) + * - `GET /` 或 `GET /health` 返回服务信息,可做健康检查 + * + * 环境变量:EXA_API_KEY(可选,提升 Exa 匿名限额);SEARCH_TIMEOUT_MS(可选,上游超时)。 + */ +import { createInterface } from 'node:readline'; +import { createServer } from 'node:http'; +import { randomUUID } from 'node:crypto'; +import { SERVER_NAME, VERSION, dispatch } from './mcp.js'; + +// ── 优雅退出 ──────────────────────────────────────────────────────────────── +// 容器里 node 以 PID 1 运行且未注册 SIGTERM 处理器时,内核不会对其执行默认 +// 终止动作,docker stop/restart 会白等满 10s 宽限期才被 SIGKILL。 +// 显式注册处理器立即关服务;3s 兜底定时器防止长连接卡住 close 回调。 +let httpServer = null; +let forceCloseConnections = () => {}; +let shuttingDown = false; + +function shutdown(sig) { + if (shuttingDown) return; + shuttingDown = true; + process.stdout.write(`[web_search] 收到 ${sig},停止服务\n`); + forceCloseConnections(); + if (httpServer === null) process.exit(0); // stdio 模式无监听,直接退 + httpServer.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 3000).unref(); +} +process.on('SIGTERM', () => shutdown('SIGTERM')); +process.on('SIGINT', () => shutdown('SIGINT')); + +// ── stdio 传输(默认)─────────────────────────────────────────────────────── +function runStdio() { + const rl = createInterface({ input: process.stdin, crlfDelay: Infinity }); + rl.on('line', (line) => { + const trimmed = line.trim(); + if (trimmed.length === 0) return; + void dispatch(trimmed).then((response) => { + if (response != null) { + process.stdout.write(`${JSON.stringify(response)}\n`); + } + }); + }); +} + +// ── HTTP/SSE 传输(--http [--port ] [--host ])────────────────────── +function runHttp(host, port) { + /** sessionId → 老式 SSE 响应流(GET /sse 建立的连接)。 */ + const sseChannels = new Map(); + + const server = createServer((req, res) => { + const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`); + + // 健康检查 / 服务信息 + if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/health')) { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ name: SERVER_NAME, version: VERSION, transport: 'http/sse', port })); + return; + } + + // 老式 SSE 通道:GET /sse(MCP-Session-Id 关联后续 POST /messages) + if (req.method === 'GET' && url.pathname === '/sse') { + const sessionId = req.headers['mcp-session-id'] ?? randomUUID(); + res.writeHead(200, { + 'content-type': 'text/event-stream', + 'cache-control': 'no-cache', + 'connection': 'keep-alive', + 'mcp-session-id': sessionId, + }); + res.write(`event: endpoint\ndata: /messages?session_id=${sessionId}\n\n`); + sseChannels.set(sessionId, res); + req.on('close', () => { sseChannels.delete(sessionId); }); + return; + } + + // 消息端点:POST /(Streamable HTTP)与 POST /messages(老式 SSE) + if (req.method === 'POST' && (url.pathname === '/' || url.pathname === '/messages')) { + const sessionId = req.headers['mcp-session-id'] ?? url.searchParams.get('session_id') ?? undefined; + let body = ''; + req.on('data', (chunk) => { body += chunk.toString(); }); + req.on('end', () => { + void dispatch(body).then((response) => { + if (response === null) { // 通知 + res.writeHead(202).end(); + return; + } + const payload = JSON.stringify(response); + // 老式 SSE:结果推回通道连接 + if (url.pathname === '/messages' && sessionId !== undefined && sseChannels.has(sessionId)) { + sseChannels.get(sessionId).write(`data: ${payload}\n\n`); + res.writeHead(202, { 'mcp-session-id': sessionId }).end(); + return; + } + // Streamable HTTP:按 Accept 返回 SSE 帧或裸 JSON + if (String(req.headers.accept ?? '').includes('text/event-stream')) { + res.writeHead(200, { + 'content-type': 'text/event-stream', + 'cache-control': 'no-cache', + ...(sessionId !== undefined ? { 'mcp-session-id': sessionId } : {}), + }); + res.end(`data: ${payload}\n\n`); + return; + } + res.writeHead(200, { + 'content-type': 'application/json', + ...(sessionId !== undefined ? { 'mcp-session-id': sessionId } : {}), + }); + res.end(payload); + }); + }); + return; + } + + res.writeHead(404, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ + error: 'not found', + hint: 'MCP endpoints: POST / (streamable http), GET /sse + POST /messages (legacy sse), GET / (info)', + })); + }); + + httpServer = server; + forceCloseConnections = () => { + // 掐掉老式 SSE 长连接与 keep-alive 连接,否则 server.close() 回调不会触发 + for (const res of sseChannels.values()) res.destroy(); + sseChannels.clear(); + server.closeAllConnections?.(); + }; + + server.listen(port, host, () => { + process.stdout.write(`[web_search] HTTP/SSE listening on http://${host}:${port} (MCP: POST /, GET /sse + POST /messages)\n`); + }); +} + +// ── 入口:参数解析 ────────────────────────────────────────────────────────── +const args = process.argv.slice(2); +const httpMode = args.includes('--http') + || (args.includes('--transport') && args[args.indexOf('--transport') + 1] === 'http'); + +const readFlag = (name, fallback) => { + const index = args.indexOf(name); + return index >= 0 && args[index + 1] !== undefined ? args[index + 1] : fallback; +}; + +if (httpMode) { + const port = Number(readFlag('--port', 3100)); + runHttp(readFlag('--host', '127.0.0.1'), Number.isFinite(port) ? port : 3100); +} else { + runStdio(); +}