feat(video_task): 上游从智谱换成 WorkBuddy 网关
智谱 cogvideox-flash 是免费模型,实测连续 429「访问量过大」,基本调不通。
改接 wb.ai 的 OpenAI 兼容视频接口(/v1/videos/generations + /v1/videos/{id}):
- 默认模型 cn:minimax-video-h3(4s 约 62 积分 / 128s),可切 cn:kling-video-v3
- 参数换成网关口径:seconds / aspect_ratio / resolution / negative_prompt / enable_audio
- 鉴权改为 wb.ai 的 API Key,服务端仍不存密钥
- presets.json 的视频预设同步改默认模型与说明
实测:提交→轮询→出片 2.1MB MP4 全链路通过,op=get 与错误路径均正常。
This commit is contained in:
@@ -95,7 +95,7 @@
|
||||
{
|
||||
"key": "video_task",
|
||||
"label": "视频生成",
|
||||
"desc": "智谱 BigModel 异步视频接口",
|
||||
"desc": "WorkBuddy 网关(minimax / kling)",
|
||||
"url": "http://mcp_video_task:3000/mcp",
|
||||
"mode": "skill",
|
||||
"fields": [
|
||||
@@ -105,12 +105,12 @@
|
||||
"secret": true,
|
||||
"prefix": "Bearer ",
|
||||
"required": true,
|
||||
"placeholder": "智谱 API Key"
|
||||
"placeholder": "wb.ai 的 API Key"
|
||||
},
|
||||
{
|
||||
"header": "X-Video-Task-Model",
|
||||
"label": "模型",
|
||||
"default": "cogvideox-flash"
|
||||
"default": "cn:minimax-video-h3"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+8
-8
@@ -6,7 +6,7 @@
|
||||
|---|---|---|---|---|
|
||||
| `web_search/` | `mcp_web_search` | 网页搜索(默认免费 Parallel / Exa,可换成自建 `/search` 上游) | `3000` | `POST /` |
|
||||
| `image_task/` | `mcp_image_task` | 图片生成 / 编辑(文生图走 `/images/generations`,图生图走 `/images/edits`,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||
| `video_task/` | `mcp_video_task` | 智谱 CogVideo 视频生成(异步,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||
| `video_task/` | `mcp_video_task` | 视频生成(上游 WorkBuddy 网关 `/v1/videos`,异步,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||
| `asr/` | `mcp_asr` | 语音转文字(上游 OpenAI 兼容 `/audio/transcriptions`),**额外带一个给输入框用的 `POST /transcribe`** | `3000` | `POST /mcp` |
|
||||
|
||||
**这些服务一个宿主机端口都不占**——它们只挂在 `agent-mcp-net` 上,由 `agent-core` / `agent-executor`
|
||||
@@ -50,7 +50,7 @@ mcp_servers:
|
||||
> 从旧的「agent + mcp 双仓库」部署升级:先在旧 mcp 仓库目录 `docker compose down`(只需一次,否则同名容器与网络会冲突),再 `up` 本栈。
|
||||
|
||||
`image_task` / `video_task` 的 token **不由服务端保存**——每个请求从 `Authorization` header 读取
|
||||
(agent 侧配在 `config.yml` 的 `mcp_servers[].headers`)。`video_task` 用智谱 token;
|
||||
(agent 侧配在 `config.yml` 的 `mcp_servers[].headers`)。`video_task` 用 wb.ai 网关的 API Key;
|
||||
`image_task` 走任意 OpenAI 兼容的 images 上游:文生图 `/images/generations`、图生图 `/images/edits`,
|
||||
上游地址与模型分别由 `X-Image-Task-Base-Url` / `X-Image-Task-Model` 指定(两者都必填)。
|
||||
所以这两个服务不用配任何密钥。
|
||||
@@ -71,23 +71,23 @@ mcp_servers:
|
||||
本栈默认不给 MCP 服务映射宿主机端口(它们只在 `agent-mcp-net` 内网可达)。要从宿主机直连,
|
||||
自行在 `docker-compose.yml` 给对应服务加 `ports` 即可。
|
||||
|
||||
## 图片是怎么到智谱手上的(只有 video_task 关心)
|
||||
## 图片是怎么到上游的(只有 video_task 关心)
|
||||
|
||||
智谱服务器生成视频前要**自己来拉参考图**,它不带 cookie、不带 `Authorization`。这套链路里**没有任何人上传文件**:
|
||||
上游生成视频前要**自己来拉参考图**,它不带 cookie、不带 `Authorization`。这套链路里**没有任何人上传文件**:
|
||||
|
||||
```
|
||||
AI ──调用 agent 内置的「公开临时 URL」工具(直接传文件路径)──► 拿到一条短命公网 URL
|
||||
│
|
||||
▼
|
||||
AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp
|
||||
AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp(转发为上游的 image 字段)
|
||||
│
|
||||
▼
|
||||
智谱 ──匿名 GET──► agent 侧提供的公开临时 URL
|
||||
那个文件始终躺在 agent 的任务目录里,零拷贝
|
||||
上游 ──匿名 GET──► agent 侧提供的公开临时 URL
|
||||
那个文件始终躺在 agent 的任务目录里,零拷贝
|
||||
```
|
||||
|
||||
- 签发与托管全在 agent 侧(它已集成为一个 tool,AI 直接调用即可,不需要 curl 任何内网入口)。
|
||||
- 链接短命:到期或 agent 重启后失效;智谱只在提交任务那一刻拉一次图,完全够用。
|
||||
- 链接短命:到期或 agent 重启后失效;上游只在提交任务那一刻拉一次图,完全够用。
|
||||
- mcp 这三家一个端口都不露,唯一公网可达的东西只有 agent 自己。
|
||||
|
||||
## 端口与安全
|
||||
|
||||
+101
-259
@@ -1,13 +1,13 @@
|
||||
# MCP Video Task
|
||||
|
||||
基于 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 的视频生成服务,对接智谱 BigModel 的视频生成**异步**接口,支持**文生视频**和**图生视频**。只有一个工具 `video_task`,用 `op` 区分动作:`op=create` 提交任务、`op=get` 单次查询结果。Server **不内部轮询**——AI 拿到 `task_id` 后自己决定什么时候用 `op="get"` 复查。
|
||||
对接 **WorkBuddy 网关**(`wb.ai`)的 OpenAI 兼容视频接口。只有一个工具 `video_task`,用 `op` 区分提交与查询。
|
||||
Server **不内部轮询**——AI 拿到 `task_id` 后自己决定什么时候复查。
|
||||
|
||||
- 协议: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」工具拿到短命链接(见下节)
|
||||
- 上游:`POST /v1/videos/generations`(提交,`wait=false` 立刻回 `task_id`)、`GET /v1/videos/{task_id}`(查询)
|
||||
- 默认模型:`cn:minimax-video-h3`;可选 `cn:kling-video-v3`、`global:kling-video-v3`
|
||||
- 端口:容器内 `3000`(MCP `/mcp` + `/health`,容器外不映射,只在 `agent-mcp-net` 内被 agent 访问)
|
||||
- 鉴权:**无服务端密钥**,每次请求必须从 header 携带网关 API Key
|
||||
|
||||
---
|
||||
|
||||
@@ -18,291 +18,133 @@
|
||||
仓库根目录 `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 调试,自行给该服务加 `ports` 映射。
|
||||
|
||||
```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}
|
||||
# {"status":"ok","service":"video_task","upstream":"https://wb.ai.foresh.com","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 <your-zhipu-api-key>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```yaml
|
||||
mcp_servers:
|
||||
- name: video_task
|
||||
url: "http://mcp_video_task:3000/mcp"
|
||||
mode: skill
|
||||
headers:
|
||||
Authorization: Bearer <wb.ai 的 API Key>
|
||||
X-Video-Task-Model: cn:minimax-video-h3 # 可选,覆盖默认模型
|
||||
```
|
||||
|
||||
> 上面的 `localhost:8083` 只是示例:本栈默认不给 MCP 服务映射宿主端口,要直连需自行加 `ports`。
|
||||
|
||||
> **重要**:客户端必须在 **每一个 HTTP 请求**(`initialize` / `notifications/initialized` / `tools/call`)都带上 `Authorization` header。
|
||||
|
||||
---
|
||||
|
||||
## 工具:video_task
|
||||
|
||||
单个工具,`op` 必填,只有两个取值:
|
||||
|
||||
| op | 作用 | 同步/异步 |
|
||||
|---|---|---|
|
||||
| `create` | 提交一个视频生成任务,立刻返回 `task_id` | 同步(仅提交) |
|
||||
| `get` | 用 `task_id` 拉一次当前结果 | 同步(单次查询,不轮询) |
|
||||
## 工具:`video_task`
|
||||
|
||||
### 参数(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`**:单个 `text` 块,含 `Video URL`(智谱签名 URL,**24h 左右有效**,需及时转存),以及 `Cover` 封面图:
|
||||
```jsonc
|
||||
{
|
||||
"content": [
|
||||
{ "type": "text", "text": "task_id: ...\nmodel: cogvideox-flash\ntask_status: SUCCESS\nVideo URL: https://...\nCover: https://..." }
|
||||
]
|
||||
}
|
||||
```
|
||||
- **`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: <token>` | 直传,避免与客户端自身的 Authorization 冲突 |
|
||||
| 2 | `X-Mcp-Token: <token>` | 通用兜底 |
|
||||
| 3 | `Authorization: Bearer <token>` | 标准 OAuth 风格(排最后是为避免误用) |
|
||||
| `op` | `create` \| `get` | 提交 / 查询,必填 |
|
||||
| `prompt` | string ≤ 2000 | `create` 必填。图生视频时描述画面如何运动 |
|
||||
| `image_url` | url | 图生视频的参考图,公网可访问的 png/jpeg/jpg |
|
||||
| `seconds` | 4–15 | 时长,默认 4。越长越慢越贵 |
|
||||
| `aspect_ratio` | string | `16:9` / `9:16` / `1:1`。上游不严格校验 |
|
||||
| `resolution` | string | `768P` / `1080P`,留空用上游默认 |
|
||||
| `negative_prompt` | string | 不希望出现的画面 |
|
||||
| `enable_audio` | boolean | 是否生成音频,默认 false(别名 `with_audio`) |
|
||||
| `task_id` | string | `get` 必填,`create` 返回 |
|
||||
|
||||
Token 仅在每次 tool call 时从 header 读取,不写入任何存储、不进 session。
|
||||
### 返回(`op=create`)
|
||||
|
||||
### 错误响应
|
||||
```
|
||||
task_id: 1312831544-minimax_video_h3-5c12…
|
||||
model: cn:minimax-video-h3
|
||||
status: queued
|
||||
提示:生成是异步的,用 op="get" + task_id 查结果。
|
||||
```
|
||||
|
||||
| 场景 | HTTP 状态 | 表现 |
|
||||
### 返回(`op=get`)
|
||||
|
||||
```
|
||||
task_id: …
|
||||
model: cn:minimax-video-h3
|
||||
status: completed
|
||||
Video URL: https://…mp4?q-signature=…
|
||||
credit: 62.29
|
||||
|
||||
注意:视频是签名直链,约 12 小时失效;要长期保存请立刻下载到本地。
|
||||
```
|
||||
|
||||
`status` 归一化为 `queued` / `in_progress` / `completed` / `failed`。
|
||||
`failed` 时返回 `isError: true` 并把上游原话带出来。
|
||||
|
||||
---
|
||||
|
||||
## 模型与计费(2026-11-17 实测)
|
||||
|
||||
| 模型 | 请求 | 实际扣费 | 出片耗时 | 分辨率 |
|
||||
|---|---|---|---|---|
|
||||
| `cn:minimax-video-h3` | 4s / 16:9 | **62.29** | **128 秒** | 768P |
|
||||
| `cn:kling-video-v3` | 4s(实际出 5s) | 102.86 | ≈473 秒 | — |
|
||||
|
||||
- 扣费发生在**出片那一刻**,提交不扣;重复查询不重复计费
|
||||
- 上游 `usage` 只回一次,之后重复查询不带 `credit` 属正常
|
||||
- `kling` 慢一个量级,客户端超时要给到 15 分钟以上
|
||||
|
||||
## 本地文件 → 公网 URL
|
||||
|
||||
本服务不搬字节:图生视频要的是**公网可访问的 URL**。本地文件先由 agent 内置的
|
||||
「公开临时 URL」工具(`mint_public_link`)换一个短命链接,再把该链接作为 `image_url` 传进来。
|
||||
|
||||
---
|
||||
|
||||
## 环境变量
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| 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`,不会无限卡住工具调用 |
|
||||
| `WB_BASE_URL` | `https://wb.ai.foresh.com` | 网关地址,末尾斜杠自动去掉 |
|
||||
|
||||
---
|
||||
|
||||
## 推荐用法(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`。下面用一行版串起来:
|
||||
## curl 调试
|
||||
|
||||
```bash
|
||||
# 把 <your-zhipu-api-key> 替换成你智谱的 API Key
|
||||
TOKEN="<your-zhipu-api-key>"
|
||||
# 1. initialize 拿 session id
|
||||
curl -s -D - -X POST http://127.0.0.1:3000/mcp \
|
||||
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
|
||||
-H "Authorization: Bearer $WB_KEY" \
|
||||
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"c","version":"0"}}}'
|
||||
# 响应头里的 mcp-session-id 后续要带上
|
||||
|
||||
# 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')
|
||||
# 2. 提交
|
||||
curl -s -X POST http://127.0.0.1:3000/mcp \
|
||||
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
|
||||
-H "mcp-session-id: $SID" -H "Authorization: Bearer $WB_KEY" \
|
||||
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"video_task","arguments":{"op":"create","prompt":"一只橘猫在草地上奔跑","seconds":4}}}'
|
||||
|
||||
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,替换下面的 <task_id>)
|
||||
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": "<task_id>" }
|
||||
}
|
||||
}'
|
||||
# 3. 查结果
|
||||
curl -s -X POST http://127.0.0.1:3000/mcp \
|
||||
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
|
||||
-H "mcp-session-id: $SID" -H "Authorization: Bearer $WB_KEY" \
|
||||
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"video_task","arguments":{"op":"get","task_id":"<task_id>"}}}'
|
||||
```
|
||||
|
||||
响应是 SSE 格式(`event: message` + `data: {...}`),用 `grep '^data:'` 抽 JSON 即可。
|
||||
响应是 SSE 帧(`event: message` + `data: {...}`),解析时取 `data:` 那一行。
|
||||
|
||||
---
|
||||
|
||||
## 架构与文件
|
||||
|
||||
```
|
||||
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 分发)
|
||||
```
|
||||
| 文件 | 作用 |
|
||||
|---|---|
|
||||
| `src/mcp-server.js` | 全部逻辑:Express + MCP SDK,`buildServer()` 注册工具,`startHttp()` 起 Streamable HTTP |
|
||||
| `Dockerfile` | node:22-alpine,`node src/mcp-server.js --http --port 3000` |
|
||||
| `package.json` | `@modelcontextprotocol/sdk` + `express` + `zod` |
|
||||
|
||||
### 关键设计
|
||||
|
||||
- **单工具 + `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 失效,但智谱只在提交任务时拉一次,不受影响。
|
||||
- **服务端不轮询**:`create` 提交完立刻返回,`get` 只拉一次,由 AI 控制节奏
|
||||
- **状态归一化**:上游 `queued` / `in_progress` / `completed` / `failed` 统一成小写,AI 不用猜
|
||||
- **错误透传**:上游 4xx/5xx 的原话进 `content[0].text`,模型能读到「模型不存在」这类可行动信息
|
||||
- **鉴权随请求走**:服务端不落任何密钥,多实例共用一份镜像也不串号
|
||||
|
||||
+145
-204
@@ -1,4 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
// MCP 视频任务服务:对接 WorkBuddy 网关(wb.ai)的 OpenAI 兼容视频接口
|
||||
// 提交 POST /v1/videos/generations(wait=false,立刻回 task_id)
|
||||
// 查询 GET /v1/videos/{task_id}
|
||||
// 只有一条工具 video_task,用 op 区分 create / get;服务端不轮询,AI 自己查。
|
||||
import express from "express";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
@@ -6,26 +10,25 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
|
||||
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)}`;
|
||||
// 上游网关地址:容器内可用 WB_BASE_URL 覆盖
|
||||
const WB_BASE = (process.env.WB_BASE_URL || "https://wb.ai.foresh.com").replace(/\/+$/, "");
|
||||
const SUBMIT_URL = `${WB_BASE}/v1/videos/generations`;
|
||||
const queryUrl = (id) => `${WB_BASE}/v1/videos/${encodeURIComponent(id)}`;
|
||||
|
||||
// 默认模型:cogvideox-flash
|
||||
const DEFAULT_MODEL = "cogvideox-flash";
|
||||
// 默认模型:minimax 出片约 2 分钟、扣 57 积分;kling 约 8 分钟、扣 103 积分
|
||||
const DEFAULT_MODEL = "cn:minimax-video-h3";
|
||||
const DEFAULT_SECONDS = 4;
|
||||
|
||||
// AI 不可见的服务端默认(可被同名 header 覆盖)
|
||||
const DEFAULT_QUALITY = "speed"; // speed | quality
|
||||
const DEFAULT_FPS = 30; // 30 | 60
|
||||
const DEFAULT_WATERMARK_ENABLED = true; // 平台政策默认 true
|
||||
// 提交/查询都是快接口(wait=false 立刻返回),卡住基本等于上游挂了
|
||||
const UPSTREAM_TIMEOUT_MS = 60_000;
|
||||
|
||||
// submit/query 都是快接口,卡住基本等于上游挂了;限时避免工具调用被拖死
|
||||
const UPSTREAM_TIMEOUT_MS = 30_000;
|
||||
// 上游状态归一:命中终态才停轮询
|
||||
const DONE = new Set(["completed", "succeeded", "success"]);
|
||||
const FAILED = new Set(["failed", "error", "cancelled", "canceled"]);
|
||||
|
||||
// ── 优雅退出 ──────────────────────────────────────────────────────────────
|
||||
// 容器里 node 以 PID 1 运行且未注册 SIGTERM 处理器时,内核不会对其执行默认
|
||||
// 终止动作,docker stop/restart 会白等满 10s 宽限期才被 SIGKILL。
|
||||
// 显式注册处理器,关闭 MCP session 与长连接后立即退出;3s 定时器为兜底。
|
||||
let httpServer = null;
|
||||
let closeAllSessions = () => {};
|
||||
let shuttingDown = false;
|
||||
@@ -35,7 +38,7 @@ function shutdown(sig) {
|
||||
shuttingDown = true;
|
||||
console.log(`[video] received ${sig}, shutting down`);
|
||||
closeAllSessions();
|
||||
if (!httpServer) process.exit(0); // stdio 模式无监听,直接退
|
||||
if (!httpServer) process.exit(0);
|
||||
httpServer.close(() => process.exit(0));
|
||||
setTimeout(() => process.exit(0), 3000).unref();
|
||||
}
|
||||
@@ -43,11 +46,7 @@ process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {
|
||||
http: false,
|
||||
port: 3000,
|
||||
host: "0.0.0.0",
|
||||
};
|
||||
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;
|
||||
@@ -57,6 +56,7 @@ function parseArgs(argv) {
|
||||
return args;
|
||||
}
|
||||
|
||||
// 鉴权:每个请求从 header 取 wb.ai 的 API Key,服务端不落盘
|
||||
function pickToken(headers) {
|
||||
if (!headers) return null;
|
||||
const candidates = [
|
||||
@@ -80,42 +80,13 @@ function pickToken(headers) {
|
||||
|
||||
function pickModel(headers) {
|
||||
if (!headers) return null;
|
||||
const v =
|
||||
headers["x-video-task-model"] ||
|
||||
headers["x-mcp-model"] ||
|
||||
headers["x-model"];
|
||||
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 }) {
|
||||
async function callWb({ url, token, method = "POST", body }) {
|
||||
const init = {
|
||||
method,
|
||||
headers: {
|
||||
@@ -125,16 +96,17 @@ async function callZhipu({ url, token, method = "POST", body }) {
|
||||
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 new Error(`上游 ${UPSTREAM_TIMEOUT_MS} ms 内没有响应`);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
const text = await resp.text();
|
||||
let data;
|
||||
try {
|
||||
@@ -143,9 +115,9 @@ async function callZhipu({ url, token, method = "POST", body }) {
|
||||
data = { raw: text };
|
||||
}
|
||||
if (!resp.ok) {
|
||||
const err = new Error(
|
||||
`Zhipu API error: ${resp.status} ${resp.statusText} - ${text}`
|
||||
);
|
||||
// 网关的错误体是 {error:{message}},取原话给模型看,便于自行纠错
|
||||
const msg = data?.error?.message || data?.error?.code || text.slice(0, 300);
|
||||
const err = new Error(`网关返回 ${resp.status}: ${msg}`);
|
||||
err.status = resp.status;
|
||||
err.detail = data;
|
||||
throw err;
|
||||
@@ -153,96 +125,62 @@ async function callZhipu({ url, token, method = "POST", body }) {
|
||||
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=create:提交任务,wait=false 立刻返回 task_id =====
|
||||
async function submitVideo({ token, model, prompt, imageUrl, seconds, aspectRatio, resolution, negativePrompt, enableAudio }) {
|
||||
const body = { model, prompt, wait: false };
|
||||
if (imageUrl) body.image = imageUrl;
|
||||
if (seconds) body.seconds = seconds;
|
||||
if (aspectRatio) body.aspect_ratio = aspectRatio;
|
||||
if (resolution) body.resolution = resolution;
|
||||
if (negativePrompt) body.negative_prompt = negativePrompt;
|
||||
if (enableAudio !== undefined && enableAudio !== null) body.enable_audio = Boolean(enableAudio);
|
||||
return await callWb({ url: SUBMIT_URL, token, body });
|
||||
}
|
||||
|
||||
// ===== 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=get:查任务(单次拉取) =====
|
||||
async function queryVideo({ token, taskId }) {
|
||||
return await callWb({ url: queryUrl(taskId), token, method: "GET" });
|
||||
}
|
||||
|
||||
function normStatus(s) {
|
||||
return String(s || "").trim().toLowerCase();
|
||||
}
|
||||
|
||||
// ---------- op=create 的业务处理 ----------
|
||||
async function handleCreate({ args, headers, token }) {
|
||||
// 纯空白 prompt 等同没给:schema 只校验类型/长度,不校验内容。
|
||||
// 不 trim 的话,“ ”会被当成合法 prompt 提交(text-to-video 拿到空白提示词,
|
||||
// image-to-video 则多传一个无意义字段)。
|
||||
const prompt = typeof args.prompt === "string" ? args.prompt.trim() : "";
|
||||
if (!prompt && !args.image_url) {
|
||||
if (!prompt) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: 'op=create requires at least one of "prompt" or "image_url".',
|
||||
},
|
||||
],
|
||||
content: [{ type: "text", text: 'op=create 需要 "prompt"(视频描述,必填)。' }],
|
||||
};
|
||||
}
|
||||
|
||||
// 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
|
||||
);
|
||||
const seconds = Number.isFinite(args.seconds) ? args.seconds : DEFAULT_SECONDS;
|
||||
|
||||
try {
|
||||
const data = await submitVideo({
|
||||
token,
|
||||
model,
|
||||
prompt,
|
||||
image_url: args.image_url,
|
||||
quality,
|
||||
with_audio: args.with_audio ?? false,
|
||||
fps,
|
||||
watermark_enabled,
|
||||
imageUrl: args.image_url,
|
||||
seconds,
|
||||
aspectRatio: args.aspect_ratio,
|
||||
resolution: args.resolution,
|
||||
negativePrompt: args.negative_prompt,
|
||||
// 兼容旧字段名
|
||||
enableAudio: args.enable_audio ?? args.with_audio,
|
||||
});
|
||||
|
||||
const taskId = data.task_id || data.id;
|
||||
const summary =
|
||||
`Model: ${model}\n` +
|
||||
`task_id: ${data.id}\n` +
|
||||
`request_id: ${data.request_id}\n` +
|
||||
`task_status: ${data.task_status}\n` +
|
||||
`model: ${data.model || model}\n` +
|
||||
`task_id: ${taskId}\n` +
|
||||
`status: ${normStatus(data.status) || "queued"}\n` +
|
||||
`\n` +
|
||||
`Video generation is asynchronous. ` +
|
||||
`Call this tool again with op="get" and task_id="${data.id}" to fetch the result.`;
|
||||
`视频是异步生成(minimax 约 2 分钟,kling 约 8 分钟)。` +
|
||||
`之后用 op="get" 加 task_id="${taskId}" 查询,直到 status 变成 completed 或 failed。` +
|
||||
`不要重复提交同一个任务。`;
|
||||
|
||||
return { content: [{ type: "text", text: summary }] };
|
||||
} catch (e) {
|
||||
@@ -251,138 +189,157 @@ async function handleCreate({ args, headers, token }) {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Failed to submit video task: ${e.message}${
|
||||
e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : ""
|
||||
}`,
|
||||
text: `提交视频任务失败:${e.message}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- op=get 的业务处理 ----------
|
||||
async function handleGet({ args, token }) {
|
||||
// 与 handleCreate 同理:纯空白 task_id 不能直接拼进上游路径,
|
||||
// 否则会得到一条含编码后空白的上游报错,既无从归因也误导模型。
|
||||
const taskId = typeof args.task_id === "string" ? args.task_id.trim() : "";
|
||||
if (!taskId) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{ type: "text", text: 'op=get requires "task_id".' }],
|
||||
content: [{ type: "text", text: 'op=get 需要 "task_id"。' }],
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await queryAsyncResult({ token, id: taskId });
|
||||
const status = data.task_status || "UNKNOWN";
|
||||
const data = await queryVideo({ token, taskId });
|
||||
const status = normStatus(data.status) || "unknown";
|
||||
|
||||
if (status === "SUCCESS") {
|
||||
const v = (data.video_result || [])[0];
|
||||
if (!v || !v.url) {
|
||||
if (DONE.has(status)) {
|
||||
const url = (data.videos || [])[0]?.url;
|
||||
if (!url) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Task succeeded but no video URL returned. Raw: ${JSON.stringify(
|
||||
data
|
||||
)}`,
|
||||
text: `任务已完成但没有返回视频地址。原始响应:${JSON.stringify(data).slice(0, 500)}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const credit = data.usage?.credit;
|
||||
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` : "");
|
||||
// 单块输出:URL 已经写在摘要里,旧版额外回一个裸 URL 块会让模型
|
||||
// (core 会把 text 块 join 成一段)看到同一个链接两遍。
|
||||
`task_id: ${taskId}\n` +
|
||||
`model: ${data.model || "-"}\n` +
|
||||
`status: completed\n` +
|
||||
`Video URL: ${url}\n` +
|
||||
(credit !== undefined ? `credit: ${credit}\n` : "") +
|
||||
`\n注意:视频是签名直链,约 12 小时失效;要长期保存请立刻下载到本地。`;
|
||||
return { content: [{ type: "text", text: summary }] };
|
||||
}
|
||||
|
||||
// PROCESSING / FAIL / 其他:原样返回关键字段
|
||||
const errBlock = data.error ? `\nerror: ${JSON.stringify(data.error)}` : "";
|
||||
if (FAILED.has(status)) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
`task_id: ${taskId}\n` +
|
||||
`status: ${status}\n` +
|
||||
(data.error ? `error: ${JSON.stringify(data.error)}\n` : "") +
|
||||
`任务已失败,需要换提示词或模型重新提交。`,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// queued / in_progress:告诉模型继续等,别重复提交
|
||||
const progress = data.progress;
|
||||
return {
|
||||
isError: status === "FAIL",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
`task_id: ${data.id}\n` +
|
||||
`model: ${data.model}\n` +
|
||||
`task_status: ${status}` +
|
||||
errBlock,
|
||||
`task_id: ${taskId}\n` +
|
||||
`model: ${data.model || "-"}\n` +
|
||||
`status: ${status}` +
|
||||
(progress !== undefined && progress !== null ? `(进度 ${progress}%)` : "") +
|
||||
`\n还没出片,稍后再用 op="get" 查一次。`,
|
||||
},
|
||||
],
|
||||
};
|
||||
} catch (e) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Failed to query video task: ${e.message}${
|
||||
e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : ""
|
||||
}`,
|
||||
},
|
||||
],
|
||||
content: [{ type: "text", text: `查询视频任务失败:${e.message}` }],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function buildServer() {
|
||||
const server = new McpServer(
|
||||
{ name: "video_task", version: "1.0.0" },
|
||||
{ name: "video_task", version: "2.0.0" },
|
||||
{ capabilities: { tools: {} } }
|
||||
);
|
||||
|
||||
server.tool(
|
||||
"video_task",
|
||||
`AI video generation task.
|
||||
`AI 视频生成任务(异步)。
|
||||
|
||||
Operations:
|
||||
- \`create\`: Start a new video generation task. Requires at least one of \`prompt\` or \`image_url\`. Returns \`task_id\` immediately; generation runs in background.
|
||||
- \`get\`: Check an existing task. Requires \`task_id\`. Returns status and, on SUCCESS, the video URL.
|
||||
操作:
|
||||
- \`create\`:提交视频生成,必须给 \`prompt\`。立刻返回 \`task_id\`,生成在后台跑。
|
||||
- \`get\`:用 \`task_id\` 查进度,出片后返回视频直链。
|
||||
|
||||
Examples:
|
||||
- Text-to-video → \`{"op":"create","prompt":"A cat running in a garden"}\`
|
||||
- Image-to-video → \`{"op":"create","image_url":"https://example.com/cat.jpg","prompt":"The cat runs forward"}\`
|
||||
- Check task → \`{"op":"get","task_id":"<task_id from create>"}\`
|
||||
示例:
|
||||
- 文生视频 → \`{"op":"create","prompt":"一只橘猫在阳光下的草地上奔跑,电影感"}\`
|
||||
- 图生视频 → \`{"op":"create","prompt":"画面里的人缓缓转身","image_url":"https://..."}\`
|
||||
- 查任务 → \`{"op":"get","task_id":"<create 返回的 task_id>"}\`
|
||||
|
||||
Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\` until \`task_status\` is \`SUCCESS\` or \`FAIL\`. Never create duplicate tasks just to check status.`,
|
||||
工作流:\`create\` 调一次,然后反复用 \`get\` 查同一个 \`task_id\`,直到 status 变成 completed 或 failed。**不要为了看进度重复提交任务。**
|
||||
耗时参考:minimax 约 2 分钟(扣 57 积分),kling 约 8 分钟(扣 103 积分)。视频直链约 12 小时失效。`,
|
||||
{
|
||||
op: z
|
||||
.enum(["create", "get"])
|
||||
.describe(
|
||||
"Use create to start video generation; use get to check a task by its task_id."
|
||||
),
|
||||
.describe("create 提交生成;get 按 task_id 查结果。"),
|
||||
prompt: z
|
||||
.string()
|
||||
.max(512)
|
||||
.max(2000)
|
||||
.optional()
|
||||
.describe(
|
||||
"Video description, max 512 characters. Required for text-to-video; when combined with image_url it describes the motion."
|
||||
),
|
||||
.describe("视频描述,create 必填。图生视频时描述画面如何运动。"),
|
||||
image_url: z
|
||||
.string()
|
||||
.url()
|
||||
.optional()
|
||||
.describe(
|
||||
"Reference image for image-to-video: publicly reachable png/jpeg/jpg URL <= 5 MB. For local files, first use the built-in mint_public_link tool to get a public temporary URL."
|
||||
"图生视频的参考图,公网可访问的 png/jpeg URL。本地文件先用 mint_public_link 换成公网短链。"
|
||||
),
|
||||
seconds: z
|
||||
.number()
|
||||
.min(4)
|
||||
.max(15)
|
||||
.optional()
|
||||
.describe("视频时长(秒),默认 4。越长越慢越贵。"),
|
||||
aspect_ratio: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("画幅,如 16:9 / 9:16 / 1:1。上游不严格校验,写合法值即可。"),
|
||||
resolution: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("分辨率,如 768P / 1080P。留空用上游默认。"),
|
||||
negative_prompt: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("不希望出现的画面描述。"),
|
||||
enable_audio: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe("是否生成音频,默认 false。"),
|
||||
with_audio: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"Whether to generate AI audio. Used with create; defaults to false."
|
||||
),
|
||||
.describe("旧字段名,等同 enable_audio。"),
|
||||
task_id: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("task_id returned by create. Required for get; omit for create."),
|
||||
.describe("create 返回的 task_id,get 时必填。"),
|
||||
},
|
||||
async (args, extra) => {
|
||||
const headers = extra?.requestInfo?.headers;
|
||||
@@ -390,7 +347,7 @@ Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\`
|
||||
if (!token) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{ type: "text", text: "Missing authentication token." }],
|
||||
content: [{ type: "text", text: "缺少鉴权:header 里要带 Authorization: Bearer <API Key>。" }],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -402,12 +359,7 @@ Workflow: call \`create\` once, then call \`get\` with the returned \`task_id\`
|
||||
default:
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Unknown op "${args.op}" (available: create, get).`,
|
||||
},
|
||||
],
|
||||
content: [{ type: "text", text: `未知 op "${args.op}"(可用:create、get)。` }],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -420,7 +372,6 @@ async function startHttp({ port, host }) {
|
||||
const app = express();
|
||||
app.use(express.json({ limit: "2mb" }));
|
||||
|
||||
// session -> { server, transport } 映射
|
||||
const sessions = new Map();
|
||||
|
||||
closeAllSessions = () => {
|
||||
@@ -433,32 +384,28 @@ async function startHttp({ port, host }) {
|
||||
} 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 });
|
||||
res.json({ status: "ok", service: "video_task", upstream: WB_BASE, 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",
|
||||
message: "Bad Request: missing valid Mcp-Session-Id for non-initialize request",
|
||||
},
|
||||
id: req.body?.id ?? null,
|
||||
});
|
||||
@@ -484,10 +431,8 @@ async function startHttp({ port, host }) {
|
||||
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)) {
|
||||
@@ -501,17 +446,13 @@ async function startHttp({ port, host }) {
|
||||
app.delete("/mcp", handleOther);
|
||||
|
||||
httpServer = app.listen(port, host, () => {
|
||||
console.log(
|
||||
`[video] MCP HTTP server listening on http://${host}:${port}/mcp`
|
||||
);
|
||||
console.log(`[video] MCP HTTP server listening on http://${host}:${port}/mcp → ${WB_BASE}`);
|
||||
});
|
||||
}
|
||||
|
||||
async function startStdio() {
|
||||
const server = buildServer();
|
||||
const { StdioServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/stdio.js"
|
||||
);
|
||||
const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
console.error("[video] MCP stdio server started");
|
||||
|
||||
Reference in New Issue
Block a user