image_task: 改成异步任务形态(op=create/get),对齐 video_task 契约
上游智谱 images 是同步接口,异步语义由服务自维护的进程内任务表模拟: create 登记 task_id 后把同步调用丢后台执行、立即返回;get 只读本地表。 已完成任务保留 1h、容量上限 1000;容器重启任务丢失,仅限单实例部署。
This commit is contained in:
+68
-19
@@ -1,6 +1,6 @@
|
||||
# MCP Image Task
|
||||
|
||||
一个基于 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 的图片生成服务,对接智谱 BigModel 的 `CogView` 系列模型。每次调用通过 HTTP header 传入智谱 API 的 Bearer Token。只有一个工具 `image_task`,用 `op` 区分动作(图片生成为同步接口,当前仅支持 `op=create`)。
|
||||
一个基于 [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)
|
||||
@@ -28,7 +28,7 @@ docker compose up -d --build mcp_image_task
|
||||
```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}
|
||||
# {"status":"ok","service":"image_task","sessions":0,"tasks":0}
|
||||
```
|
||||
|
||||
### MCP 客户端配置
|
||||
@@ -62,18 +62,22 @@ docker exec mcp_image_task node -e "fetch('http://localhost:3000/health').then(r
|
||||
|
||||
## 工具:image_task
|
||||
|
||||
调用智谱图片生成接口,返回图片 URL。生成为**同步**接口,`op=create` 直接出结果,无需轮询。
|
||||
管理图片生成异步任务。典型流程:`op=create` 拿 `task_id`,然后不断 `op=get` 直到 `task_status` 为 `SUCCESS` 或 `FAIL`。
|
||||
|
||||
| op | 作用 | 同步/异步 |
|
||||
| op | 作用 | 说明 |
|
||||
|---|---|---|
|
||||
| `create` | 按 prompt 生成图片,返回图片 URL | 同步(直接返回结果) |
|
||||
| `create` | 提交图片生成任务,**立即**返回 `task_id`,生成在后台执行 | 需要 `prompt` |
|
||||
| `get` | 查询任务状态;`SUCCESS` 时返回图片 URL | 需要 `task_id` |
|
||||
|
||||
> 上游智谱 images 接口是同步阻塞的;这里的异步是对外的统一形态(对齐 `video_task`),服务内部把同步调用丢到后台跑并回写任务表。
|
||||
|
||||
### 参数(AI 可见)
|
||||
|
||||
| 名称 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `op` | `"create"` | ✅ | 要执行的操作(当前仅 `create`) |
|
||||
| `prompt` | string | ✅ | 图片生成提示词,描述想要的画面内容(仅 op=create 使用) |
|
||||
| `op` | `"create"` \| `"get"` | ✅ | 要执行的操作 |
|
||||
| `prompt` | string | op=create 时 ✅ | 图片生成提示词,描述想要的画面内容 |
|
||||
| `task_id` | string | op=get 时 ✅ | `op=create` 返回的任务 ID |
|
||||
|
||||
> 图片尺寸不再透传,走上游默认;尺寸档位与成本/成功率挂钩,AI 传错值经常直接报错。
|
||||
|
||||
@@ -93,20 +97,33 @@ docker exec mcp_image_task node -e "fetch('http://localhost:3000/health').then(r
|
||||
|
||||
### 返回
|
||||
|
||||
工具成功时返回若干 `text` 块,第一块是摘要,后续每块各包含一张图片的 URL(方便 LLM 直接贴图或下载):
|
||||
`op=create` 成功时立即返回 `task_id`(生成已转入后台):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"content": [
|
||||
{ "type": "text", "text": "Model: CogView-3-Flash\nPrompt: ...\nImage 1: https://maas-watermark-prod-new.cn-wlcb.ufileos.com/..." },
|
||||
{ "type": "text", "text": "Model: CogView-3-Flash\ntask_id: <uuid>\ntask_status: PROCESSING\n\nImage generation is running in background. Call this tool again with op=\"get\" and task_id=\"<uuid>\" to fetch the result." }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`op=get` 按任务状态返回:
|
||||
|
||||
- `PROCESSING`:提示几秒后再查;
|
||||
- `SUCCESS`:若干 `text` 块,第一块是摘要,后续每块各包含一张图片的 URL(方便 LLM 直接贴图或下载):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"content": [
|
||||
{ "type": "text", "text": "task_id: <uuid>\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/..." }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
URL 由智谱签名下发,**带有效期**(通常 24h),如需长期保存请在收到后及时转存到自己的存储。
|
||||
- `FAIL`:`isError: true`,正文含 `task_status: FAIL` 与错误信息(上游 4xx/5xx、无 URL 返回等都会归档到这里)。
|
||||
|
||||
失败时返回 `isError: true` 的错误描述。
|
||||
URL 由智谱签名下发,**带有效期**(通常 24h),如需长期保存请在收到后及时转存到自己的存储。
|
||||
|
||||
---
|
||||
|
||||
@@ -127,8 +144,10 @@ Token 仅在每次 tool call 时从 header 读取,不写入任何存储、不
|
||||
| 场景 | HTTP 状态 | 表现 |
|
||||
|---|---|---|
|
||||
| initialize 时缺 token | `401` | JSON-RPC `error.message` 提示补充 header |
|
||||
| 智谱 API 4xx/5xx | `200`(MCP 工具返回) | `isError: true`,正文含智谱返回的状态码和 body |
|
||||
| 网络失败 | `200`(MCP 工具返回) | `isError: true`,正文含 `fetch` 错误信息 |
|
||||
| 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` 错误信息 |
|
||||
|
||||
---
|
||||
|
||||
@@ -174,7 +193,7 @@ curl -s -X POST http://localhost:8082/mcp \
|
||||
-H "Mcp-Session-Id: $SESSION" \
|
||||
-d '{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}'
|
||||
|
||||
# 4. 调 image_task(op=create)
|
||||
# 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" \
|
||||
@@ -192,6 +211,25 @@ curl -s -X POST http://localhost:8082/mcp \
|
||||
}
|
||||
}
|
||||
}'
|
||||
|
||||
# 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 即可。
|
||||
@@ -212,11 +250,16 @@ image_task/
|
||||
|
||||
### 关键设计
|
||||
|
||||
- **单工具 + `op` 分发**:`image_task(op=create)`,与 `video_task` 的服务形态保持一致;生成为同步接口,所以 `op` 只有 `create` 一个取值
|
||||
- **单工具 + `op` 分发**:`image_task(op=create|get)`,与 `video_task` 的服务形态完全一致,agent 侧一套轮询逻辑通吃图片/视频
|
||||
- **同步上游 → 异步契约**:智谱 images 接口只支持同步,所以服务自维护一张任务表来模拟异步:
|
||||
- `create` 本地生成 `task_id`(`randomUUID`),登记 `PROCESSING`,把同步调用丢后台(fire-and-forget),立即返回
|
||||
- 后台完成时回写 `SUCCESS`(含 URLs)或 `FAIL`(含错误)
|
||||
- `get` 只读本地表,不碰上游
|
||||
- 表为进程内存 Map:已完成任务保留 1 小时(TTL)、容量上限 1000,每次 `create` 顺带淘汰;**容器重启后任务丢失**,`get` 会报 unknown task_id;**不适用于多副本部署**(表不互通)
|
||||
- token/model 在 `create` 那一刻从请求 header 捕获进闭包,后台完成前不再读取,保持「每请求读 header」的无状态设计
|
||||
- **每 session 一个 transport + server**:通过 `Mcp-Session-Id` 复用,避免每请求重建
|
||||
- **Token 闭包注入**:在 Express 入口处从 header 提取 token,闭包传给 tool 回调;不依赖 SDK 内部字段
|
||||
- **模型参数不入 schema**:model 只从 HTTP header 读取(`X-Image-Task-Model` / `X-Mcp-Model` / `X-Model`),AI 不可见
|
||||
- **URL 提取**:`response.data[].url` 为准,若返回 `b64_json` 也会一并返回
|
||||
- **URL 提取**:`response.data[].url` 为准,若返回 `b64_json` 也会一并归档进任务表
|
||||
|
||||
### 默认模型
|
||||
|
||||
@@ -237,8 +280,14 @@ A: 这是设计意图。模型选择属于路由策略,不让 AI 决策。调
|
||||
**Q: 换模型需要重连 MCP session 吗?**
|
||||
A: 不需要。Model header 在每次 `tools/call` 都从当前请求读取,不需要重建 session。
|
||||
|
||||
**Q: 为什么 op 只有 create?**
|
||||
A: 图片生成是同步接口,`op=create` 直接返回结果,不存在需要轮询的异步任务。保留 `op` 参数是为了与 `video_task` 等异步任务型服务形态一致;将来若上游出现异步接口再加 `get`。
|
||||
**Q: 上游是同步接口,为什么对外做成异步?**
|
||||
A: 为了和 `video_task` 保持同一套任务型契约,agent 侧只需维护一种「create 后轮询 get」的调用模式。同步调用被放到后台执行,对 AI 而言表现为标准异步任务。
|
||||
|
||||
**Q: create 之后服务容器重启了,get 会怎样?**
|
||||
A: 任务表在进程内存里,重启即丢失,`get` 会返回 unknown task_id 的 `isError`。需要重新 `create`。图片生成只跑几秒,受影响窗口很小;若将来要上多副本或需要可靠恢复,再把表换成持久化存储。
|
||||
|
||||
**Q: 为什么 get 不需要等上游?**
|
||||
A: `get` 只读本地任务表,上游调用只发生在 `create` 的后台一次,不会因轮询而重复计费/重复生图。
|
||||
|
||||
**Q: 为什么 Model 优先级不是「工具参数 > header」?**
|
||||
A: 因为我们故意不在 schema 暴露 model 参数,AI 根本不会传 model,所以「工具参数 > header」这条分支实际上不存在。
|
||||
|
||||
@@ -116,56 +116,161 @@ function extractUrls(data) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// ===== op=create:提交图片生成(同步,直接返回图片 URL)=====
|
||||
// ===== 自维护任务表(异步语义全靠这层模拟) =====
|
||||
// 上游智谱 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;
|
||||
|
||||
try {
|
||||
const data = await callZhipuImagesGenerations({
|
||||
token,
|
||||
model,
|
||||
prompt: args.prompt,
|
||||
});
|
||||
const urls = extractUrls(data);
|
||||
if (urls.length === 0) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Returned no image URL. Raw response: ${JSON.stringify(data)}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const summary = urls
|
||||
.map((u, i) => `Image ${i + 1}: ${u}`)
|
||||
.join("\n");
|
||||
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 {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Model: ${model}\nPrompt: ${args.prompt}\n${summary}`,
|
||||
},
|
||||
...urls.map((u) => ({ type: "text", text: u })),
|
||||
],
|
||||
isError: true,
|
||||
content: [{ type: "text", text: 'op=get requires "task_id".' }],
|
||||
};
|
||||
} catch (e) {
|
||||
}
|
||||
|
||||
const task = tasks.get(args.task_id);
|
||||
if (!task) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Failed to generate image: ${e.message}${
|
||||
e.detail ? `\nDetails: ${JSON.stringify(e.detail)}` : ""
|
||||
}`,
|
||||
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() {
|
||||
@@ -183,21 +288,28 @@ function buildServer() {
|
||||
|
||||
server.tool(
|
||||
"image_task",
|
||||
`Manages image generation. Generation is synchronous: op=create returns the image URLs directly.
|
||||
`Manages asynchronous image generation tasks.
|
||||
|
||||
op=create Generate an image from a prompt. Requires prompt.`,
|
||||
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"])
|
||||
.describe(
|
||||
'Operation to perform. Only "create" is supported (generation is synchronous, so there is no task to poll).'
|
||||
),
|
||||
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. Used with op=create."
|
||||
"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
|
||||
@@ -220,13 +332,15 @@ op=create Generate an image from a prompt. Requires prompt.`,
|
||||
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).`,
|
||||
text: `Unknown op "${args.op}" (available: create, get).`,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -259,7 +373,12 @@ async function startHttp({ port, host }) {
|
||||
};
|
||||
|
||||
app.get("/health", (_req, res) => {
|
||||
res.json({ status: "ok", service: "image_task", sessions: sessions.size });
|
||||
res.json({
|
||||
status: "ok",
|
||||
service: "image_task",
|
||||
sessions: sessions.size,
|
||||
tasks: tasks.size,
|
||||
});
|
||||
});
|
||||
|
||||
async function handleSessionRequest(req, res) {
|
||||
|
||||
Reference in New Issue
Block a user