video_gen: 丢掉上传/落盘整套,本地图片改由 agent 内网现签公网链接
- 删除 POST /upload、GET /uploads/*、multer、上传目录与 TTL 清理、公网只读监听(PUBLIC_PORT/3001) - 删除 UPLOAD_BASE_URL / PUBLIC_BASE_URL / UPLOAD_DIR,改为单一个 PUBLIC_LINK_URL: 工具描述里给的命令变成 curl -s "<PUBLIC_LINK_URL>?path=<绝对路径>",stdout 即现成 URL - package.json: 去掉 multer 依赖;Dockerfile: EXPOSE 3000,去掉 3001 与上传说明 - docker-compose.yml: 去掉 ./uploads 挂载与相关 env,只留 PUBLIC_LINK_URL - .gitignore: 去掉 uploads/ - 文档: 根 README 与 video_gen README 改写「图片怎么到智谱手上」(零拷贝 + 签名链接)
This commit is contained in:
+1
-3
@@ -1,5 +1,3 @@
|
||||
node_modules/
|
||||
# video_gen 的上传目录(compose bind 到宿主机,运行时产物,不进库)
|
||||
uploads/
|
||||
# 编排变量(PUBLIC_BASE_URL 等),含部署相关的地址,不进库
|
||||
# 编排变量(PUBLIC_LINK_URL 等),含部署相关的地址,不进库
|
||||
.env
|
||||
|
||||
+23
-26
@@ -6,10 +6,11 @@
|
||||
|---|---|---|---|---|
|
||||
| `web_search/` | `mcp_web_search` | 免费网页搜索(Parallel / Exa,无需 key) | `3000` | `POST /` |
|
||||
| `image_gen/` | `mcp_image_gen` | 智谱 CogView 图片生成 | `3000` | `POST /mcp` |
|
||||
| `video_gen/` | `mcp_video_gen` | 智谱 CogVideo 视频生成(异步)+ 图片上传 | `3000` 全量 / `3001` 只读 | `POST /mcp` |
|
||||
| `video_gen/` | `mcp_video_gen` | 智谱 CogVideo 视频生成(异步) | `3000` | `POST /mcp` |
|
||||
|
||||
**这些服务默认不占宿主机端口**——它们只挂在 `my-app-network` 上,由 `agent-core` / `agent-executor`
|
||||
**这些服务一个宿主机端口都不占**——它们只挂在 `my-app-network` 上,由 `agent-core` / `agent-executor`
|
||||
按容器名访问。所以整台服务器对外只需要开 agent-core 那一个端口(`AGENT_PORT`,默认 8090)。
|
||||
(要从宿主机 curl 调试时,把 `docker-compose.yml` 里对应服务注释掉的 `ports` 两行打开。)
|
||||
|
||||
## 部署(无 nginx-proxy)
|
||||
|
||||
@@ -35,33 +36,32 @@ cd /root/workspace/tools/mcp && docker compose up -d --build
|
||||
|
||||
| 变量 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `PUBLIC_BASE_URL` | `http://localhost:8090/mcp-uploads` | **必须改**。video_gen `/upload` 返回给智谱的 URL 前缀,指向 agent-core 的只读中转;无域名时填 `http://<服务器IP>:<AGENT_PORT>/mcp-uploads` |
|
||||
| `PUBLIC_LINK_URL` | `http://agent-core:8081/public-link` | video_gen 用:告诉 AI「本地图片怎么换成公网 URL」的 agent 内网签发入口 |
|
||||
| `WEB_SEARCH_PORT` | `8081` | 只在临时打开 web_search 调试端口时用 |
|
||||
| `IMAGE_GEN_PORT` | `8082` | 只在临时打开 image_gen 调试端口时用 |
|
||||
| `VIDEO_GEN_PORT` | `8083` | 只在临时打开 video_gen 调试端口(只读监听)时用 |
|
||||
| `VIDEO_GEN_PORT` | `8083` | 只在临时打开 video_gen 调试端口(MCP 口,仅本机短时调试)时用 |
|
||||
|
||||
## 图片是怎么到智谱手上的(video_gen 特有)
|
||||
## 图片是怎么到智谱手上的(只有 video_gen 关心)
|
||||
|
||||
只有 `video_gen` 需要一个"公网可达的地址",因为智谱服务器生成视频前要**自己来拉这张参考图**,
|
||||
它不带 cookie、不带 `Authorization`。链路是:
|
||||
智谱服务器生成视频前要**自己来拉参考图**,它不带 cookie、不带 `Authorization`。这套链路里**没有任何人上传文件**:
|
||||
|
||||
```
|
||||
AI(agent-executor 内执行 curl)
|
||||
│ POST /upload(走 docker 内网,不经过公网)
|
||||
▼
|
||||
mcp_video_gen:3000 ──存储──► ./uploads/<randomUUID>.png
|
||||
│ 返回 url = PUBLIC_BASE_URL + /uploads/<name>
|
||||
▼
|
||||
视频任务提交给智谱,image_url 就是上面那个 url
|
||||
│
|
||||
▼
|
||||
智谱 ──匿名 GET──► http://<服务器IP>:8090/mcp-uploads/uploads/<name>
|
||||
│ agent-core 只转发 GET/HEAD
|
||||
▼
|
||||
mcp_video_gen:3001(只读监听,那边没有任何写路由)
|
||||
AI(agent 的 executor 沙箱里)
|
||||
│ curl -s "http://agent-core:8081/public-link?path=/workspace/tasks/<会话>/foo.png"
|
||||
▼
|
||||
agent-core :8081(内网、不映射宿主机 -> 无需凭据)
|
||||
│ 现签一条签名下载链接(HMAC,含会话/路径/过期时间)
|
||||
▼
|
||||
AI 把拿到的 URL 当 image_url 交给 video_gen:3000/mcp
|
||||
│
|
||||
▼
|
||||
智谱 ──匿名 GET──► http://<服务器IP>:8090/api/sessions/<会话>/files/download-name/…&t=…
|
||||
那个文件始终躺在 agent 的任务目录里,零拷贝
|
||||
```
|
||||
|
||||
所以:**写路径(`POST /upload`)永远不出公网**,公网只暴露一个只读、不可枚举、24h 过期的下载路径。
|
||||
- 链接:不可猜(HMAC)、会过期(默认 30 分钟)、绑会话、agent 重启即全部失效。
|
||||
- 前提:agent 侧 `config.yml` 配了 `public_link.base_url`(就是那个对外地址),否则签发端口不启动。
|
||||
- 唯一公网可达的东西是 agent 的 8090,以及那条**签名**下载路径;mcp 这三家一个端口都不露。
|
||||
|
||||
## 端口与安全
|
||||
|
||||
@@ -69,16 +69,13 @@ mcp_video_gen:3000 ──存储──► ./uploads/<randomUUID>.png
|
||||
|---|---|---|
|
||||
| `mcp_web_search` | 无 | 服务端无鉴权,**永远不要映射出去**(会被白嫖搜索额度);agent 走内网访问 |
|
||||
| `mcp_image_gen` | 无 | token 由调用方自带,暴露后可被拿去消耗你的智谱额度 |
|
||||
| `mcp_video_gen` | 无 | 只读路径已经由 agent-core 的 `/mcp-uploads` 代拉,无需自己占端口 |
|
||||
|
||||
需要从宿主机直接 curl 调试时,去 `docker-compose.yml` 把对应服务注释掉的 `ports` 两行打开
|
||||
(video_gen 那个映的是只读监听 3001,不会暴露 `POST /upload`),调试完记得再注释回去。
|
||||
`video_gen` 的用户上传文件落在宿主 `./uploads/`(已 gitignore,24h 自动清理)。
|
||||
| `mcp_video_gen` | 无 | 它需要的公网下载路径由 agent 的签名链接提供,自己不占端口 |
|
||||
|
||||
## 单独调试
|
||||
|
||||
```bash
|
||||
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)"
|
||||
```
|
||||
|
||||
|
||||
+6
-14
@@ -26,22 +26,14 @@ services:
|
||||
build: ./video_gen
|
||||
container_name: mcp_video_gen
|
||||
restart: unless-stopped
|
||||
# 调试用(默认关;这里映的是只读监听 3001,不会暴露 POST /upload):
|
||||
# 调试用(默认关;这里映的是 MCP 端口,会暴露 /mcp,仅本机短时调试用):
|
||||
# ports:
|
||||
# - "${VIDEO_GEN_PORT:-8083}:3001"
|
||||
# - "${VIDEO_GEN_PORT:-8083}:3000"
|
||||
environment:
|
||||
# AI 往哪上传(拼进 video_gen 工具的 curl 模板):走 docker 内网即可,不需要公网。
|
||||
- UPLOAD_BASE_URL=http://mcp_video_gen:3000
|
||||
# 智谱从哪下载(拼进 /upload 返回的 url 字段):必须【公网可达】。
|
||||
# 无域名时填 http://<服务器IP>:<AGENT_PORT>/mcp-uploads(agent-core 的只读中转,默认端口 8090)。
|
||||
# 填错的现象:图传上去了,但智谱取不到图、图生视频失败;启动日志会打印实际生效的地址便于核对。
|
||||
- PUBLIC_BASE_URL=${PUBLIC_BASE_URL:-http://localhost:8090/mcp-uploads}
|
||||
# 公网只读监听(容器内):agent 的 MCP_UPLOADS_URL 指向它;也只被上面那个调试端口映射。
|
||||
- PUBLIC_PORT=3001
|
||||
# 上传落宿主 ./uploads(重启不让已发出的 URL 失效),TTL 清理照旧
|
||||
- UPLOAD_DIR=/uploads
|
||||
volumes:
|
||||
- ./uploads:/uploads
|
||||
# 本地图片 -> 公网 URL:agent-core 的【内网】签发入口(agent 侧 public_link 功能),
|
||||
# agent-core:8081 就是它那个不映射宿主机的签发端口(env PUBLIC_LINK_PORT,默认 8081)。
|
||||
# 本服务不搬字节:只把这条命令拼进工具描述,AI 自己在沙箱里 curl,拿回一条短命链接。
|
||||
- PUBLIC_LINK_URL=${PUBLIC_LINK_URL:-http://agent-core:8081/public-link}
|
||||
networks:
|
||||
- my-app-network
|
||||
|
||||
|
||||
@@ -9,9 +9,8 @@ RUN npm install --omit=dev
|
||||
# 复制源码
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3000 3001
|
||||
EXPOSE 3000
|
||||
|
||||
# 启用 HTTP/SSE 模式:
|
||||
# 3000 = MCP(/mcp) + POST /upload + GET /uploads/*,容器外不映射(只在 docker 网络内可达)
|
||||
# 3001 = 公网只读的 GET /uploads/*,由 compose 映射到宿主机给智谱下载(PUBLIC_PORT 开启)
|
||||
# HTTP 模式:只提供 MCP(/mcp)与 /health;容器外不映射,只在 my-app-network 内被 agent 访问。
|
||||
# 本地图片需要公网 URL 时,AI 去 curl agent 的内网签发入口(env PUBLIC_LINK_URL),本服务不搬字节。
|
||||
CMD ["node", "src/mcp-server.js", "--http", "--port", "3000", "--host", "0.0.0.0"]
|
||||
+21
-124
@@ -5,9 +5,9 @@
|
||||
- 协议:MCP **Streamable HTTP**(单端点 `/mcp`,支持 SSE 流)
|
||||
- 上游:[智谱 BigModel 视频生成(异步)](https://docs.bigmodel.cn/api-reference/模型-api/视频生成异步) + [查询异步结果](https://docs.bigmodel.cn/api-reference/模型-api/查询异步结果)
|
||||
- 默认模型:`cogvideox-flash`
|
||||
- 端口:容器内 `3000`(`/mcp` + `POST /upload` + `GET /uploads/*`,**容器外不映射**)、容器内 `3001`(公网只读的 `GET /uploads/*`)
|
||||
- 端口:容器内 `3000`(MCP `/mcp` + `/health`,**容器外不映射**,只在 `my-app-network` 内被 agent 访问)
|
||||
- 鉴权:**无服务端密钥**,每次请求必须从 header 携带智谱 token
|
||||
- 附带 `/upload`:供 AI 上传本地图片换取 URL(写路径只在 docker 内网可达;落宿主 `./uploads/`,按 TTL 自动清理)
|
||||
- 本地文件需要公网 URL 时:不传字节,让 AI 去 agent 的内网签发入口现签一条短命链接(见下节)
|
||||
|
||||
---
|
||||
|
||||
@@ -24,7 +24,7 @@ docker compose up -d --build mcp_video_gen
|
||||
|
||||
服务容器名 `mcp_video_gen`,**默认不占宿主机端口**:由 agent 走 `my-app-network` 按容器名访问
|
||||
(`http://mcp_video_gen:3000/mcp`)。需要从宿主机 curl 调试时,去仓库根 `docker-compose.yml`
|
||||
把 `mcp_video_gen` 注释掉的 `ports` 两行打开(映的是只读监听 3001)。
|
||||
把 `mcp_video_gen` 注释掉的 `ports` 两行打开(映的是 MCP 端口 3000,仅本机短时调试用)。
|
||||
|
||||
```bash
|
||||
# 容器内健康检查(无需占端口)
|
||||
@@ -68,113 +68,23 @@ docker exec mcp_video_gen node -e "fetch('http://localhost:3000/health').then(r=
|
||||
|
||||
---
|
||||
|
||||
## 上传图片:POST /upload
|
||||
|
||||
供 AI 上传本地图片、拿到 URL 后喂给 `video_gen.image_url`。**不走 MCP、不走鉴权**,但**写路径只在内网**(容器内 3000,容器外不映射),
|
||||
所以公网上没有任何写入入口。唯一公网可达的是**只读**的下载路径,而且由 agent-core 代拉:
|
||||
## 本地文件 → 公网 URL(本服务不搬字节)
|
||||
|
||||
```
|
||||
AI(agent-executor 内 curl)
|
||||
│ POST http://mcp_video_gen:3000/upload ← docker 内网,不经公网
|
||||
▼
|
||||
./uploads/<randomUUID>.png 返回 url = PUBLIC_BASE_URL + /uploads/<name>
|
||||
│
|
||||
▼
|
||||
智谱服务器 ──匿名 GET──► http://<服务器IP>:<AGENT_PORT>/mcp-uploads/uploads/<name>
|
||||
│ agent-core 只转发 GET/HEAD
|
||||
▼
|
||||
mcp_video_gen:3001(只读监听,那边没有 /upload)
|
||||
```
|
||||
|
||||
### 配置(两个地址刻意分开)
|
||||
|
||||
| 变量 | 作用 | 该填什么 |
|
||||
|---|---|---|
|
||||
| `UPLOAD_BASE_URL` | 拼进 tool description 里那条 curl,告诉 AI 往哪上传 | 内网地址 `http://mcp_video_gen:3000`(compose 已配好) |
|
||||
| `PUBLIC_BASE_URL` | 拼进 `/upload` 返回的 `url` 字段,给**智谱**下载用 | **必须外部可达**:`http://<服务器IP>:<AGENT_PORT>/mcp-uploads` |
|
||||
| `PUBLIC_PORT` | 只读监听的容器内端口(agent 的 `MCP_UPLOADS_URL` 指向它) | compose 里是 `3001`;留 `0` 则不开双监听 |
|
||||
|
||||
`UPLOAD_BASE_URL` 未设时会退回 `PUBLIC_BASE_URL`,两个都没设则都是 `http://localhost:<port>`(本机调试)。
|
||||
启动日志会打印两个实际生效的地址,配错了一看就知道。
|
||||
|
||||
其它环境变量:
|
||||
|
||||
| 变量 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `UPLOAD_DIR` | `/tmp/video_gen_uploads` | 磁盘存储目录;compose 里指向宿主挂载的 `/uploads` |
|
||||
| `UPLOAD_TTL_HOURS` | `24` | 超过该小时数的文件会在启动时和每小时被自动删除 |
|
||||
|
||||
### 接口
|
||||
|
||||
```
|
||||
POST /upload (只在容器内 3000,内网可达)
|
||||
Content-Type: multipart/form-data
|
||||
|
||||
file: <二进制图片文件>
|
||||
```
|
||||
|
||||
### 限制
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 最大体积 | 8MB(智谱 `image_url` 上限5MB,留余量) |
|
||||
| 白名单 content-type | `image/png`、`image/jpeg`、`image/jpg` |
|
||||
| 存储位置 | 宿主 `./uploads/`(compose 挂到容器 `/uploads`,`UPLOAD_DIR` 可覆盖) |
|
||||
| 持久化 | 落盘,重启不失效;但按 TTL 到期自动删,**不要依赖长期 URL** |
|
||||
| 过期清理 | 启动时 + 每小时一次删除 `>UPLOAD_TTL_HOURS` 的文件,默认 24h |
|
||||
| 鉴权 | 无(靠“不映射到宿主机”隔离;AI 走内网访问) |
|
||||
|
||||
### 返回
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"url": "http://<服务器IP>:8090/mcp-uploads/uploads/abc123.png",
|
||||
"filename": "abc123.png",
|
||||
"size": 12345,
|
||||
"content_type": "image/png",
|
||||
"original_name": "my-cat.png"
|
||||
}
|
||||
```
|
||||
|
||||
返回的 `url` 可直接作为 `video_gen.image_url` 使用(前缀 = `PUBLIC_BASE_URL`)。
|
||||
|
||||
### 端口与路由
|
||||
|
||||
| 容器内端口 | 路由 | 容器外 |
|
||||
|---|---|---|
|
||||
| `3000` | `/mcp` + `POST /upload` + `GET /uploads/*` | 不映射,只在 `my-app-network` 内可达 |
|
||||
| `3001`(`PUBLIC_PORT`) | 只有 `GET /uploads/*` + `/health` | 也不映射;由 agent-core 的 `MCP_UPLOADS_URL` 指向它代拉 |
|
||||
|
||||
只读监听的意义:公网那条入站链路(智谱拉图)接的是它,所以即使 agent 侧中转有 bug 把写方法转过来,
|
||||
这边也没路由可打(纵深防御)。
|
||||
|
||||
### curl 示例
|
||||
|
||||
默认不占宿主端口。推荐用 `docker exec` 在容器内测(不破坏安全边界):
|
||||
`image_url` 必须是一个**公网可达**的 URL(智谱服务器会自己去拉)。图片在本地盘上时,本服务不负责上传,
|
||||
而是让 AI 去 agent 那边现签一条短命的公网链接(实现见 agent 仓库 `app/server/routes/public-link.js`):
|
||||
|
||||
```bash
|
||||
# 上传(走全量监听的 3000):把 /etc/hostname 当假图片,只为看返回结构
|
||||
docker exec mcp_video_gen node -e "
|
||||
const fs=require('fs');
|
||||
const fd=new FormData();
|
||||
fd.append('file',new File([fs.readFileSync('/etc/hostname')],'t.png',{type:'image/png'}));
|
||||
fetch('http://localhost:3000/upload',{method:'POST',body:fd}).then(r=>r.json()).then(j=>console.log(j));
|
||||
"
|
||||
|
||||
# 只读监听取文件(把 <name> 换成上一步返回的 filename)
|
||||
docker exec mcp_video_gen node -e "fetch('http://localhost:3001/uploads/<name>').then(r=>console.log(r.status,r.headers.get('content-type')))"
|
||||
|
||||
# 只读监听上试写:应当 404(那边没有 /upload)
|
||||
docker exec mcp_video_gen node -e "fetch('http://localhost:3001/upload',{method:'POST'}).then(r=>console.log(r.status))"
|
||||
# AI 在 agent 的 executor 沙箱里执行;路径就是它平时看到的那个绝对路径
|
||||
curl -s "http://agent-core:8081/public-link?path=/workspace/tasks/<会话>/foo.png"
|
||||
# stdout 就是现成 URL(纯文本,不需要解析 JSON):
|
||||
# http://<服务器IP>:8090/api/sessions/<会话>/files/download-name/foo.png?path=foo.png&expires=…&t=…
|
||||
```
|
||||
|
||||
要从宿主机 curl 调试,临时把 compose 里注释的 `ports` 打开(打开的是只读侧 `8083:3001`;
|
||||
想试上传就临时改成 `8083:3000`,测完记得改回来):
|
||||
|
||||
```bash
|
||||
curl -sI http://localhost:8083/uploads/<name> # 只读侧取图:200
|
||||
curl -s http://localhost:8083/upload # 只读侧写:404(本来就没这个路由)
|
||||
```
|
||||
- 那条链接是 agent 的**签名下载链接**:不可猜(HMAC)、会过期(默认 30 分钟)、绑会话、agent 重启即全部失效。
|
||||
- `8081` 是 agent 侧的**内网**签发端口(`PUBLIC_LINK_PORT`),**不映射到宿主机**,所以接它不需要任何凭据;
|
||||
地址由 env `PUBLIC_LINK_URL` 告诉本服务(compose 已默认指向 `http://agent-core:8081/public-link`)。
|
||||
- `PUBLIC_LINK_URL` 没配时,工具描述里不会出现这条命令,而是提示“请运维配置”。
|
||||
|
||||
---
|
||||
|
||||
@@ -187,7 +97,7 @@ curl -s http://localhost:8083/upload # 只读侧写:404(本来
|
||||
| 名称 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `prompt` | string | ✅ | 视频文本描述,最大 512 字符 |
|
||||
| `image_url` | string (URL) | ❌ | 参考图 URL(**单张**,不支持数组 / 多张 / 首尾帧)。图片 ≤ 5MB,格式 png/jpeg/jpg。本地文件请走 `/upload` |
|
||||
| `image_url` | string (URL) | ❌ | 参考图 URL(**单张**,不支持数组 / 多张 / 首尾帧)。图片 ≤ 5MB,格式 png/jpeg/jpg。本地文件请先用上一节的命令换一条公网链接 |
|
||||
| `size` | string | ❌ | 视频尺寸,例如 `1920x1080`、`1080x1920`、`1024x1024`、`1280x960` 等 |
|
||||
| `with_audio` | boolean | ❌ | 是否生成 AI 音效,默认 `false` |
|
||||
|
||||
@@ -269,7 +179,7 @@ Token 仅在每次 tool call 时从 header 读取,不写入任何存储、不
|
||||
## 推荐用法(AI 视角)
|
||||
|
||||
```
|
||||
1. 如果手头是【本地文件】:先调 POST {UPLOAD_BASE_URL}/upload 拿到 url,再进第 2 步
|
||||
1. 如果手头是【本地文件】:先 `curl -s "http://agent-core:8081/public-link?path=<绝对路径>"` 拿到一条公网链接(上一节),再进第 2 步
|
||||
2. 调用 video_gen({ prompt, image_url?, size?, with_audio? })
|
||||
3. 拿到 task_id → 等待若干秒(建议 2~5 秒)
|
||||
4. 调用 query_video({ task_id })
|
||||
@@ -363,19 +273,6 @@ curl -s -X POST http://localhost:8083/mcp \
|
||||
|
||||
响应是 SSE 格式(`event: message` + `data: {...}`),用 `grep '^data:'` 抽 JSON 即可。
|
||||
|
||||
### 单独调试 `/upload`
|
||||
|
||||
```bash
|
||||
# 上传(需先在 compose 里临时把 ports 打开成 8083:3000;默认不映射)
|
||||
curl -F "file=@/tmp/cat.png" http://localhost:8083/upload
|
||||
# {"url":"http://<服务器IP>:8090/mcp-uploads/uploads/xxx.png", ...} ← 返回的是公网地址(PUBLIC_BASE_URL)
|
||||
|
||||
# 直接从只读监听取文件(compose 默认那行就是 8083:3001)
|
||||
curl -o cat.png http://localhost:8083/uploads/xxx.png
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 架构与文件
|
||||
|
||||
```
|
||||
@@ -397,8 +294,8 @@ package.json # @modelcontextprotocol/sdk + express + multer
|
||||
- `model / quality / fps / watermark_enabled` 全部由 HTTP header 注入,避免 AI 误传或被诱导调高价档
|
||||
- **异步语义暴露给 AI**:服务端不做轮询,`video_gen` 只提交、`query_video` 只查一次。AI 自主决定节奏
|
||||
- **服务端自动 `request_id`**:每次提交服务端生成一个 UUID 作为智谱 `request_id`,便于日志关联,但不暴露给 AI
|
||||
- **上传接口与 MCP 走同一进程**:额外 `POST /upload` + `GET /uploads/*` 不走 MCP、不鉴权;写路径只在容器内 3000(不外映射),公网只暴露只读监听 3001。写入时的 `UPLOAD_BASE_URL` 与返回给智谱的 `PUBLIC_BASE_URL` **分开配置**(前者内网、后者公网),AI 看到的 tool description 启动时拼接进真实地址,避免 AI 自由发挥
|
||||
- **上传过期清理**:启动时 + 每小时一次删除 `mtime > UPLOAD_TTL_HOURS` 的文件,避免磁盘被不消费的上传堆满;清理 timer 用 `unref()` 不阻塞进程退出
|
||||
- **不搬字节**:本地文件 -> 公网 URL 完全由 agent 侧完成(`GET /public-link` 现签一条签名下载链接),本服务只把命令拼进工具描述;那只所以能不给本体加任何写入口、不落盘、不需要额外端口
|
||||
- **链接短命**:签名链接默认 30 分钟过期、绑会话、agent 重启即全失效;`PUBLIC_LINK_URL` 未配时工具描述退化为“请运维配置”
|
||||
|
||||
### 默认模型
|
||||
|
||||
@@ -435,7 +332,7 @@ A: 可以。`/async-result/{id}` 是幂等的读接口,并发无副作用。
|
||||
A: 不需要。Model header 在每次 `tools/call` 都从当前请求读取。
|
||||
|
||||
**Q: 上传的图片多久过期?**
|
||||
A: 落宿主 `./uploads/`(重启不失效),但按 `UPLOAD_TTL_HOURS`(默认 24h)自动删除,所以拿到 `url` 后尽快喂给 `video_gen.image_url`。过期后 URL 变 404。
|
||||
A: 本服务不存图,不存在“上传的图片”:要用的图在 agent 的任务目录里,AI 现签一条签名链接给智谱拉。链接按 agent 的 `public_link.ttl_ms`(默认 30 分钟)过期,过期后 URL 变 403。
|
||||
|
||||
**Q: `PUBLIC_BASE_URL` 不设会怎样?**
|
||||
A: compose 给个默认值 `http://localhost:8090/mcp-uploads`(代码 fallback 是 `http://localhost:<port>`)。本机调试无所谓,但智谱服务器拉不到图——图生视频会失败。无域名部署时要显式设成 `http://<服务器IP>:<AGENT_PORT>/mcp-uploads`,并确认 agent-core 那边配了 `MCP_UPLOADS_URL`(否则中转路由不存在)。启动日志会打印两个实际生效的地址,一眼就能看出配对没。
|
||||
**Q: `PUBLIC_LINK_URL` 不配会怎样?**
|
||||
A: 工具描述里不会出现“怎么把本地文件变成公网 URL”的命令,而是提示让运维配置,AI 就只能用已经是公网 URL 的图片(比如 image_gen 刚生成的图)。配的时候注意:它指向的是 agent 侧的**内网**签发端口(`http://agent-core:8081/public-link`),不是 agent 对外的 8090。
|
||||
@@ -9,7 +9,6 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.0.4",
|
||||
"express": "^4.21.0",
|
||||
"multer": "^1.4.5-lts.1"
|
||||
"express": "^4.21.0"
|
||||
}
|
||||
}
|
||||
+25
-201
@@ -1,8 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
import express from "express";
|
||||
import multer from "multer";
|
||||
import path from "node:path";
|
||||
import fs from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
@@ -22,88 +19,13 @@ const DEFAULT_QUALITY = "speed"; // speed | quality
|
||||
const DEFAULT_FPS = 30; // 30 | 60
|
||||
const DEFAULT_WATERMARK_ENABLED = true; // 平台政策默认 true
|
||||
|
||||
// ===== 上传文件相关 =====
|
||||
// 两个地址刻意分开——无域名/无反代部署的关键:
|
||||
// uploadBaseUrl —— 拼进 tool description 里那条 curl,告诉 AI 该往哪里 POST。这跳由 AI 在
|
||||
// agent-executor 里执行,走 docker 内网即可,不需要公网。
|
||||
// publicBaseUrl —— 拼进 /upload 返回的 url 字段。这跳是【智谱服务器】去 GET,必须公网可达。
|
||||
// 都不配时两者退化为 http://localhost:<port>(本机调试)。
|
||||
function normalizeBaseUrl(s) {
|
||||
return String(s || "").trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function resolveUploadBaseUrl({ port }) {
|
||||
return (
|
||||
normalizeBaseUrl(process.env.UPLOAD_BASE_URL) ||
|
||||
normalizeBaseUrl(process.env.PUBLIC_BASE_URL) ||
|
||||
`http://localhost:${port}`
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePublicBaseUrl({ port }) {
|
||||
return (
|
||||
normalizeBaseUrl(process.env.PUBLIC_BASE_URL) ||
|
||||
`http://localhost:${port}`
|
||||
);
|
||||
}
|
||||
|
||||
// 公网只读监听端口(容器内):>0 时额外起一个只挂 GET /uploads/* 的监听,专门给智谱下载。
|
||||
// 0/未设 = 不开(单监听模式,本机开发默认);等于主端口时也跳过。
|
||||
// 主端口(--port,容器内 3000)挂着 /mcp 与 POST /upload,容器外不映射,只在 docker 网络内可达。
|
||||
const PUBLIC_PORT = parseInt(process.env.PUBLIC_PORT || "0", 10) || 0;
|
||||
|
||||
// 上传文件存储目录:compose 里 bind 到宿主 ./uploads(重启不让已发出的 URL 失效);本机裸跑默认 /tmp。
|
||||
const UPLOAD_DIR = process.env.UPLOAD_DIR || "/tmp/video_gen_uploads";
|
||||
const UPLOAD_PATH_PREFIX = "/uploads"; // 对外的 URL 路径前缀
|
||||
const UPLOAD_MAX_BYTES = 8 * 1024 * 1024; // 8MB(智谱 image_url 上限 5MB,留余量)
|
||||
const UPLOAD_ALLOWED_MIME = new Set([
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
]);
|
||||
|
||||
// 过期清理:UPLOAD_TTL_HOURS 小时之前的文件会被定时删除
|
||||
const UPLOAD_TTL_HOURS = (() => {
|
||||
const n = parseInt(process.env.UPLOAD_TTL_HOURS || "24", 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : 24;
|
||||
})();
|
||||
const UPLOAD_TTL_MS = UPLOAD_TTL_HOURS * 60 * 60 * 1000;
|
||||
const UPLOAD_CLEANUP_INTERVAL_MS = 60 * 60 * 1000; // 每小时一次
|
||||
|
||||
// 清理 UPLOAD_DIR 下 mtime 早于 TTL 的文件。返回 {kept, removed, errors}
|
||||
async function cleanupUploads({ now = Date.now(), dir = UPLOAD_DIR } = {}) {
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.promises.readdir(dir);
|
||||
} catch (e) {
|
||||
if (e && e.code === "ENOENT") return { kept: 0, removed: 0, errors: 0 };
|
||||
console.error(`[video_gen] cleanup: readdir failed: ${e.message}`);
|
||||
return { kept: 0, removed: 0, errors: 1 };
|
||||
}
|
||||
|
||||
let kept = 0;
|
||||
let removed = 0;
|
||||
let errors = 0;
|
||||
await Promise.all(
|
||||
entries.map(async (name) => {
|
||||
const full = path.join(dir, name);
|
||||
try {
|
||||
const st = await fs.promises.stat(full);
|
||||
if (!st.isFile()) return;
|
||||
if (now - st.mtimeMs >= UPLOAD_TTL_MS) {
|
||||
await fs.promises.unlink(full);
|
||||
removed++;
|
||||
} else {
|
||||
kept++;
|
||||
}
|
||||
} catch (e) {
|
||||
if (e && e.code === "ENOENT") return;
|
||||
errors++;
|
||||
console.error(`[video_gen] cleanup: ${name}: ${e.message}`);
|
||||
}
|
||||
})
|
||||
);
|
||||
return { kept, removed, errors };
|
||||
// ===== 本地图片怎么拿到公网 URL =====
|
||||
// 本服务不搬字节:本地文件 -> 公网 URL 这件事由 agent(agent-core)侧完成:
|
||||
// agent-core 在【内网】端口上提供签发入口(GET /public-link?path=<绝对路径>),
|
||||
// 沙箱里的 AI 命令 curl 它,换回一条短命的签名下载链接(复用登录下载那套:不可猜/会过期/绑会话)。
|
||||
// 这里只把那条命令拼进 tool description 告诉 AI;agent 侧的具体实现见其 routes/public-link.js。
|
||||
function resolvePublicLinkUrl() {
|
||||
return String(process.env.PUBLIC_LINK_URL || "").trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
@@ -251,7 +173,7 @@ async function queryAsyncResult({ token, id }) {
|
||||
return data; // { id, request_id, model, task_status, video_result?, ... }
|
||||
}
|
||||
|
||||
function buildServer({ publicBaseUrl, uploadBaseUrl }) {
|
||||
function buildServer({ publicLinkUrl }) {
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: "video_gen",
|
||||
@@ -264,7 +186,15 @@ function buildServer({ publicBaseUrl, uploadBaseUrl }) {
|
||||
}
|
||||
);
|
||||
|
||||
const uploadUrl = `${uploadBaseUrl}/upload`;
|
||||
// 本地文件 -> 公网 URL 的那条命令。由 agent-core 的内网签发入口提供(见 resolvePublicLinkUrl 注释):
|
||||
// 它返回 text/plain,stdout 就是现成 URL,所以 AI 不需要解析 JSON。
|
||||
const localFileHint = publicLinkUrl
|
||||
? `If you need to use a LOCAL image file as image_url, first mint a temporary public URL for it by running this exact command in the shell (replace the path with the file's absolute path):
|
||||
|
||||
curl -s "${publicLinkUrl}?path=/workspace/tasks/<your-session>/your-image.png"
|
||||
|
||||
The command prints ONE URL as plain text — pass that URL directly as the image_url argument below. The link is short-lived (minutes), so mint it right before calling this tool.`
|
||||
: `If you need to use a LOCAL image file as image_url but no public-link minting endpoint is configured, ask the operator to configure it (env PUBLIC_LINK_URL). You cannot upload files from here.`;
|
||||
|
||||
// ---------- 工具 1:video_gen ----------
|
||||
server.tool(
|
||||
@@ -273,13 +203,9 @@ function buildServer({ publicBaseUrl, uploadBaseUrl }) {
|
||||
Returns the task_id immediately; poll the result later with query_video.
|
||||
prompt is required. Must add image_url for image-to-video.
|
||||
|
||||
If you need to use a LOCAL image file as image_url, upload it FIRST with this exact command (replace the path):
|
||||
${localFileHint}
|
||||
|
||||
curl -F "file=@/path/to/your/image.png" ${uploadUrl}
|
||||
|
||||
The response JSON has a "url" field — pass that URL directly as the image_url argument below.
|
||||
Supported formats: png, jpeg, jpg. Max 5MB per image.
|
||||
Uploaded files are kept on the server temporarily and auto-deleted after a TTL — do not rely on long-term URLs.`,
|
||||
Supported formats: png, jpeg, jpg. Max 5MB per image, and the URL must be reachable from the public internet (the upstream fetches it itself).`,
|
||||
{
|
||||
prompt: z
|
||||
.string()
|
||||
@@ -291,7 +217,7 @@ Uploaded files are kept on the server temporarily and auto-deleted after a TTL
|
||||
.url()
|
||||
.optional()
|
||||
.describe(
|
||||
"Reference image URL string for image-to-video. Image <= 5MB, .png/.jpeg/.jpg. Use the /upload endpoint to get a URL from a local file."
|
||||
"Reference image URL string for image-to-video. Image <= 5MB, .png/.jpeg/.jpg. For a local file, first mint a temporary public URL with the shell command shown in this tool's description."
|
||||
),
|
||||
size: z
|
||||
.string()
|
||||
@@ -471,83 +397,8 @@ async function startHttp({ port, host }) {
|
||||
const app = express();
|
||||
app.use(express.json({ limit: "2mb" }));
|
||||
|
||||
const publicBaseUrl = resolvePublicBaseUrl({ port });
|
||||
const uploadBaseUrl = resolveUploadBaseUrl({ port });
|
||||
console.log(`[video_gen] UPLOAD_BASE_URL = ${uploadBaseUrl} (AI 往哪上传,走内网)`);
|
||||
console.log(`[video_gen] PUBLIC_BASE_URL = ${publicBaseUrl} (返回给智谱的下载地址,须公网可达)`);
|
||||
|
||||
// ===== /upload:接收图片,返回 URL(不走 MCP)=====
|
||||
// 磁盘存储:保证 UPLOAD_DIR 存在(compose 里挂到宿主 ./uploads,重启不失效)
|
||||
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
|
||||
|
||||
// 过期清理:启动时跑一次,之后每小时一次
|
||||
cleanupUploads()
|
||||
.then((r) =>
|
||||
console.log(
|
||||
`[video_gen] startup cleanup: kept=${r.kept} removed=${r.removed} errors=${r.errors} ttl=${UPLOAD_TTL_HOURS}h`
|
||||
)
|
||||
)
|
||||
.catch((e) => console.error(`[video_gen] startup cleanup failed: ${e.message}`));
|
||||
const cleanupTimer = setInterval(() => {
|
||||
cleanupUploads()
|
||||
.then((r) => {
|
||||
if (r.removed > 0 || r.errors > 0) {
|
||||
console.log(
|
||||
`[video_gen] periodic cleanup: kept=${r.kept} removed=${r.removed} errors=${r.errors}`
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((e) => console.error(`[video_gen] periodic cleanup failed: ${e.message}`));
|
||||
}, UPLOAD_CLEANUP_INTERVAL_MS);
|
||||
cleanupTimer.unref(); // 不阻止进程退出
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (_req, _file, cb) => cb(null, UPLOAD_DIR),
|
||||
filename: (_req, file, cb) => {
|
||||
const ext = (path.extname(file.originalname) || ".bin").toLowerCase();
|
||||
cb(null, `${randomUUID()}${ext}`);
|
||||
},
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
limits: { fileSize: UPLOAD_MAX_BYTES, files: 1 },
|
||||
fileFilter: (_req, file, cb) => {
|
||||
if (UPLOAD_ALLOWED_MIME.has(file.mimetype)) return cb(null, true);
|
||||
cb(new Error(`Unsupported content-type: ${file.mimetype}. Allowed: ${[...UPLOAD_ALLOWED_MIME].join(", ")}`));
|
||||
},
|
||||
});
|
||||
|
||||
app.post("/upload", (req, res) => {
|
||||
upload.single("file")(req, res, (err) => {
|
||||
if (err) {
|
||||
const status = err.code === "LIMIT_FILE_SIZE" ? 413 : 400;
|
||||
return res.status(status).json({
|
||||
error: err.message || "upload failed",
|
||||
});
|
||||
}
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: "Missing form field 'file'" });
|
||||
}
|
||||
const url = `${publicBaseUrl}${UPLOAD_PATH_PREFIX}/${req.file.filename}`;
|
||||
return res.json({
|
||||
url,
|
||||
filename: req.file.filename,
|
||||
size: req.file.size,
|
||||
content_type: req.file.mimetype,
|
||||
original_name: req.file.originalname,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 静态下载:只要文件存在于 UPLOAD_DIR 就吐出去(不鉴权、不持久化)
|
||||
app.use(
|
||||
UPLOAD_PATH_PREFIX,
|
||||
express.static(UPLOAD_DIR, {
|
||||
fallthrough: false,
|
||||
maxAge: 0,
|
||||
})
|
||||
);
|
||||
const publicLinkUrl = resolvePublicLinkUrl();
|
||||
console.log(`[video_gen] PUBLIC_LINK_URL = ${publicLinkUrl || "(未配置 -> 工具描述里不会出现本地文件取公网 URL 的命令)"}`);
|
||||
|
||||
// session -> { server, transport } 映射
|
||||
const sessions = new Map();
|
||||
@@ -580,7 +431,7 @@ async function startHttp({ port, host }) {
|
||||
}
|
||||
|
||||
const newId = randomUUID();
|
||||
const server = buildServer({ publicBaseUrl, uploadBaseUrl });
|
||||
const server = buildServer({ publicLinkUrl });
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: () => newId,
|
||||
onsessioninitialized: (id) => {
|
||||
@@ -619,38 +470,11 @@ async function startHttp({ port, host }) {
|
||||
`[video_gen] MCP HTTP server listening on http://${host}:${port}/mcp`
|
||||
);
|
||||
});
|
||||
|
||||
// ===== 公网只读监听(只给智谱下载用)=====
|
||||
// 只挂 GET /uploads/* 与 /health:没有 /mcp、没有 POST /upload —— 写入口物理上不在这个端口上,
|
||||
// 不靠 token,而是压根没监听。这一侧必须【匿名】可达(智谱拉图不带任何 header/凭据)。
|
||||
if (PUBLIC_PORT && PUBLIC_PORT !== port) {
|
||||
const publicApp = express();
|
||||
publicApp.get("/health", (_req, res) => {
|
||||
res.json({ status: "ok", service: "video_gen", scope: "public-read" });
|
||||
});
|
||||
publicApp.use(
|
||||
UPLOAD_PATH_PREFIX,
|
||||
express.static(UPLOAD_DIR, {
|
||||
fallthrough: false,
|
||||
maxAge: 0,
|
||||
index: false,
|
||||
})
|
||||
);
|
||||
publicApp.use((_req, res) => {
|
||||
res.status(404).json({ error: "not found", scope: "public-read" });
|
||||
});
|
||||
publicApp.listen(PUBLIC_PORT, host, () => {
|
||||
console.log(
|
||||
`[video_gen] public read-only server listening on http://${host}:${PUBLIC_PORT}${UPLOAD_PATH_PREFIX}/*`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function startStdio() {
|
||||
// stdio 模式下上传接口不可用,用 placeholder 避免 description 里出现奇怪的占位
|
||||
const local = "http://localhost:3000";
|
||||
const server = buildServer({ publicBaseUrl: local, uploadBaseUrl: local });
|
||||
// stdio 模式:拿不到 agent 的内网签发入口也没关系,description 里会退化为“请运维配 PUBLIC_LINK_URL”
|
||||
const server = buildServer({ publicLinkUrl: resolvePublicLinkUrl() });
|
||||
const { StdioServerTransport } = await import(
|
||||
"@modelcontextprotocol/sdk/server/stdio.js"
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user