agnes-image-mcp-node 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +116 -3
- package/bin/cli.js +90 -0
- package/package.json +35 -5
- package/src/client.js +221 -0
- package/src/config.js +53 -0
- package/src/index.js +201 -0
- package/src/logs.js +83 -0
package/README.md
CHANGED
|
@@ -1,3 +1,116 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# agnes-image-mcp-node
|
|
2
|
+
|
|
3
|
+
Agnes Image 2.5 Flash 生图 MCP 服务(Node 独立版)。
|
|
4
|
+
**只做生图**,3 个工具,不含活动规则逻辑。支持 stdio(npx 默认)与 Streamable HTTP 两种传输。
|
|
5
|
+
|
|
6
|
+
## npx 接入(推荐)
|
|
7
|
+
|
|
8
|
+
无需 clone / install,MCP 客户端直接拉起。WorkBuddy 写在 `~/.workbuddy/mcp.json`:
|
|
9
|
+
|
|
10
|
+
```json
|
|
11
|
+
{
|
|
12
|
+
"mcpServers": {
|
|
13
|
+
"agnes-image": {
|
|
14
|
+
"command": "npx",
|
|
15
|
+
"args": ["-y", "agnes-image-mcp-node"],
|
|
16
|
+
"env": {
|
|
17
|
+
"AGNES_IMAGE_API_KEY": "你的 Agnes API Key",
|
|
18
|
+
"AGNES_IMAGE_MODEL": "agnes-image-2.5-flash"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`AGNES_IMAGE_MODEL` 可不填,默认即 `agnes-image-2.5-flash`;显式写出便于日后切换模型。
|
|
26
|
+
stdio 模式下 stdout 只跑 JSON-RPC,所有日志走 stderr,不会污染协议。
|
|
27
|
+
|
|
28
|
+
命令行参数:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npx -y agnes-image-mcp-node # 默认 stdio
|
|
32
|
+
npx -y agnes-image-mcp-node --http # Streamable HTTP: /mcp
|
|
33
|
+
npx -y agnes-image-mcp-node --http --port 8323 # 指定端口
|
|
34
|
+
npx -y agnes-image-mcp-node --output-dir ./images # 指定图片落盘目录
|
|
35
|
+
npx -y agnes-image-mcp-node --model agnes-image-2.5-flash
|
|
36
|
+
npx -y agnes-image-mcp-node --help # 查看全部参数
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## 关键协议适配
|
|
40
|
+
|
|
41
|
+
Agnes 的 `POST /v1/images/generations` **不是标准 OpenAI 图像协议**:
|
|
42
|
+
|
|
43
|
+
1. `response_format` 必须在 `extra_body`,放顶层会被忽略/报错
|
|
44
|
+
2. 图生图/多图合成的 `image` 数组也在 `extra_body`,且**不需要** `tags: ["img2img"]`
|
|
45
|
+
3. 精确 `WxH` 尺寸不传 `ratio`(避免语义冲突)
|
|
46
|
+
|
|
47
|
+
## 本地启动
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm install
|
|
51
|
+
cp .env.example .env # 填入 AGNES_IMAGE_API_KEY
|
|
52
|
+
npm start # HTTP: http://127.0.0.1:8321/mcp
|
|
53
|
+
npm run start:stdio # stdio(与 npx 默认模式一致)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
配置集中在 `src/config.js`(环境变量 + `.env`,key 缺失启动即报错)。
|
|
57
|
+
优先级:命令行参数 > MCP 客户端注入的 env > 调用方工作目录 `.env` > 包内 `.env`。
|
|
58
|
+
|
|
59
|
+
| 变量 | 必填 | 默认 |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| `AGNES_IMAGE_API_KEY` | 是 | 也接受 `AI_IMAGE_KEY` |
|
|
62
|
+
| `AGNES_BASE_URL` | 否 | `https://apihub.agnes-ai.com/v1` |
|
|
63
|
+
| `AGNES_IMAGE_MODEL` | 否 | `agnes-image-2.5-flash` |
|
|
64
|
+
| `AGNES_IMAGE_TIMEOUT_SECONDS` | 否 | `180` |
|
|
65
|
+
| `AGNES_IMAGE_OUTPUT_DIR` | 否 | `./agnes-images`(调用方工作目录,npx 下不会落进 npm 缓存) |
|
|
66
|
+
| `PORT` / `HOST` | 否 | `8321` / `127.0.0.1`(仅 HTTP 模式) |
|
|
67
|
+
| `LOG_LEVEL` | 否 | `info` |
|
|
68
|
+
|
|
69
|
+
健康检查(仅 HTTP 模式):`GET /healthz`(含 model / endpoint / api_key_configured / uptime)。
|
|
70
|
+
|
|
71
|
+
## 工具(3 个)
|
|
72
|
+
|
|
73
|
+
| 工具 | 说明 |
|
|
74
|
+
|---|---|
|
|
75
|
+
| `generate_image(prompt, size?, ratio?, response_format?)` | 文生图,落盘返回绝对路径 |
|
|
76
|
+
| `edit_image(prompt, images[], size?, ratio?, response_format?)` | 图生图/多图合成,images 为公网 URL 或 `data:` URI |
|
|
77
|
+
| `get_image_specs()` | size 档位、ratio 及实际像素表 |
|
|
78
|
+
|
|
79
|
+
默认:`size="2K"`、`ratio="1:1"`、`response_format="url"`。
|
|
80
|
+
size 档位 1K/2K/3K/4K 或精确 `1024x768`;ratio 支持 8 种。
|
|
81
|
+
|
|
82
|
+
**图片一律落盘并返回绝对路径**——下游(如 `market-mcp-node` 的 `apply_image_results`)拿到 `path` 后会自动托管成可访问 URL。
|
|
83
|
+
|
|
84
|
+
返回标准 `CallToolResult`:`content[0].text` 完整 JSON + `structuredContent` 结构化对象,读任一即可。
|
|
85
|
+
|
|
86
|
+
## 日志
|
|
87
|
+
|
|
88
|
+
**只输出到进程 stderr,不落盘、不轮转、不清理**——日志由运行环境(终端 / systemd / 容器日志驱动)统一收集。
|
|
89
|
+
|
|
90
|
+
行格式:`时间戳 LEVEL [requestId] 消息 {"event":...,"tool":...,"ms":...,"ok":...}`
|
|
91
|
+
|
|
92
|
+
- requestId 贯穿单次 MCP 调用,`grep <requestId>` 可串出完整链路
|
|
93
|
+
- 尾部结构化字段便于日志系统检索(`tool_error` / `tool_end` / `http_error` 等)
|
|
94
|
+
- 级别由 `LOG_LEVEL` 控制(debug/info/warn/error,默认 info)
|
|
95
|
+
- 参数只记摘要(图片数、尺寸等),不记完整 prompt 或敏感内容
|
|
96
|
+
|
|
97
|
+
## 测试
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
npm test # 8 passed(mock HTTP,不消耗额度)
|
|
101
|
+
npm run compare # 跨实现对拍(两边默认都是 8321,需错开端口)
|
|
102
|
+
# PY_MCP=http://127.0.0.1:8321/mcp/ NODE_MCP=http://127.0.0.1:8323/mcp node tests/compare.mjs
|
|
103
|
+
npm run smoke # 端到端冒烟(需先启动 HTTP 模式)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
真实生图已验证:1K/1:1 约 23 秒,返回本地路径 + `source_url`,落盘正常。
|
|
107
|
+
|
|
108
|
+
## 发布 / 安装
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
npm pack --dry-run # 检查 tarball 只含 bin/、src/、README.md
|
|
112
|
+
npm login
|
|
113
|
+
npm publish # publishConfig.access=public
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
用户侧:`npx -y agnes-image-mcp-node --help`;本地安装:`npm i -g agnes-image-mcp-node`。
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** npx / 命令行入口:默认 stdio,--http 切回 Streamable HTTP。 */
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
const args = process.argv.slice(2);
|
|
9
|
+
const VALUE_FLAGS = ['--host', '--port', '--output-dir', '--model'];
|
|
10
|
+
const BOOL_FLAGS = ['--http', '--stdio', '--help', '-h', '--version', '-v'];
|
|
11
|
+
|
|
12
|
+
function die(msg) {
|
|
13
|
+
process.stderr.write(`${msg}\n`);
|
|
14
|
+
process.exit(1);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
18
|
+
process.stdout.write(`agnes-image-mcp-node — Agnes 生图 MCP(3 个工具)
|
|
19
|
+
|
|
20
|
+
用法:
|
|
21
|
+
npx -y agnes-image-mcp-node [选项] # 默认 stdio(MCP 客户端直接拉起)
|
|
22
|
+
npx -y agnes-image-mcp-node --http # Streamable HTTP: /mcp,默认 127.0.0.1:8321
|
|
23
|
+
|
|
24
|
+
选项:
|
|
25
|
+
--stdio 使用 stdio(默认)
|
|
26
|
+
--http 使用 Streamable HTTP
|
|
27
|
+
--host <addr> HTTP 监听地址(默认 127.0.0.1)
|
|
28
|
+
--port <number> HTTP 监听端口(默认 8321)
|
|
29
|
+
--output-dir <dir> 图片落盘目录(默认当前工作目录 ./agnes-images)
|
|
30
|
+
--model <name> 生图模型(默认 agnes-image-2.5-flash)
|
|
31
|
+
-v, --version 打印版本
|
|
32
|
+
-h, --help 打印帮助
|
|
33
|
+
|
|
34
|
+
命令行参数会覆盖同名环境变量;未显式传入时从 env / .env 读取:
|
|
35
|
+
AGNES_IMAGE_API_KEY 必填,也接受 AI_IMAGE_KEY
|
|
36
|
+
AGNES_IMAGE_MODEL 默认 agnes-image-2.5-flash
|
|
37
|
+
AGNES_IMAGE_OUTPUT_DIR 图片落盘目录
|
|
38
|
+
AGNES_IMAGE_TIMEOUT_SECONDS 请求超时秒数(默认 180)
|
|
39
|
+
AGNES_BASE_URL API 根地址
|
|
40
|
+
HOST / PORT / LOG_LEVEL HTTP 地址 / 端口 / 日志级别
|
|
41
|
+
`);
|
|
42
|
+
process.exit(0);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
46
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'));
|
|
47
|
+
process.stdout.write(`${pkg.version}\n`);
|
|
48
|
+
process.exit(0);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const values = {};
|
|
52
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
53
|
+
const arg = args[i];
|
|
54
|
+
if (VALUE_FLAGS.includes(arg)) {
|
|
55
|
+
const value = args[i + 1];
|
|
56
|
+
if (!value || VALUE_FLAGS.includes(value) || BOOL_FLAGS.includes(value)) die(`${arg} 缺少取值`);
|
|
57
|
+
values[arg] = value;
|
|
58
|
+
i += 1;
|
|
59
|
+
} else if (!BOOL_FLAGS.includes(arg)) {
|
|
60
|
+
die(`未知参数:${arg}(用 --help 查看用法)`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (args.includes('--http') && args.includes('--stdio')) die('--http 与 --stdio 不能同时使用');
|
|
64
|
+
|
|
65
|
+
function takeValue(flag) {
|
|
66
|
+
return values[flag];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const host = takeValue('--host');
|
|
70
|
+
const port = takeValue('--port');
|
|
71
|
+
const outputDir = takeValue('--output-dir');
|
|
72
|
+
const model = takeValue('--model');
|
|
73
|
+
|
|
74
|
+
if (port !== undefined && !/^\d+$/.test(port)) die('--port 必须是正整数');
|
|
75
|
+
if (host) process.env.HOST = host;
|
|
76
|
+
if (port !== undefined) process.env.PORT = port;
|
|
77
|
+
if (outputDir) process.env.AGNES_IMAGE_OUTPUT_DIR = path.resolve(outputDir);
|
|
78
|
+
if (model) process.env.AGNES_IMAGE_MODEL = model;
|
|
79
|
+
|
|
80
|
+
// 动态导入:确保 --help / --version 不需要 API key(config.js 会在导入时校验)
|
|
81
|
+
try {
|
|
82
|
+
const { startStdio, startHttp } = await import('../src/index.js');
|
|
83
|
+
if (args.includes('--http')) {
|
|
84
|
+
await startHttp();
|
|
85
|
+
} else {
|
|
86
|
+
await startStdio();
|
|
87
|
+
}
|
|
88
|
+
} catch (exc) {
|
|
89
|
+
die(`启动失败:${exc?.message || exc}`);
|
|
90
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "agnes-image-mcp-node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
1
|
+
{
|
|
2
|
+
"name": "agnes-image-mcp-node",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Agnes Image 生图 MCP 服务(Node 独立版)",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"bin": {
|
|
7
|
+
"agnes-image-mcp-node": "bin/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public"
|
|
16
|
+
},
|
|
17
|
+
"directories": {
|
|
18
|
+
"test": "tests"
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"start": "node bin/cli.js --http",
|
|
22
|
+
"start:stdio": "node bin/cli.js",
|
|
23
|
+
"test": "node --test tests/*.test.js",
|
|
24
|
+
"compare": "node tests/compare.mjs",
|
|
25
|
+
"smoke": "node tests/smoke.mjs"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
29
|
+
"dotenv": "^18.0.10",
|
|
30
|
+
"zod": "^4.6.7"
|
|
31
|
+
},
|
|
32
|
+
"type": "module",
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=20"
|
|
35
|
+
}
|
|
6
36
|
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agnes Image 2.5 Flash 客户端。
|
|
3
|
+
*
|
|
4
|
+
* 这个 API 不是标准 OpenAI 图像协议,两个关键差异:
|
|
5
|
+
* 1. `response_format` 必须放在 `extra_body`,放顶层会被忽略/报错;
|
|
6
|
+
* 2. 图生图/多图合成的 `image` 数组也放在 `extra_body`,且不需要 `tags: ["img2img"]`。
|
|
7
|
+
*
|
|
8
|
+
* 支持文生图、图生图、多图合成;输出 url 或 b64_json,统一落成本地文件返回路径。
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
export const VALID_SIZES = new Set(['1K', '2K', '3K', '4K']);
|
|
14
|
+
export const VALID_RATIOS = new Set([
|
|
15
|
+
'1:1', '3:4', '4:3', '16:9', '9:16', '2:3', '3:2', '21:9',
|
|
16
|
+
]);
|
|
17
|
+
export const VALID_FORMATS = new Set(['url', 'b64_json']);
|
|
18
|
+
|
|
19
|
+
// 档位 + 比例 → 实际像素
|
|
20
|
+
export const SIZE_PIXELS = {
|
|
21
|
+
'1K': {
|
|
22
|
+
'1:1': [1024, 1024], '3:4': [864, 1152], '4:3': [1152, 864],
|
|
23
|
+
'16:9': [1312, 736], '9:16': [736, 1312], '2:3': [832, 1248],
|
|
24
|
+
'3:2': [1248, 832], '21:9': [1568, 672],
|
|
25
|
+
},
|
|
26
|
+
'2K': {
|
|
27
|
+
'1:1': [2048, 2048], '3:4': [1728, 2304], '4:3': [2304, 1728],
|
|
28
|
+
'16:9': [2624, 1472], '9:16': [1472, 2624], '2:3': [1664, 2496],
|
|
29
|
+
'3:2': [2496, 1664], '21:9': [3136, 1344],
|
|
30
|
+
},
|
|
31
|
+
'3K': {
|
|
32
|
+
'1:1': [3072, 3072], '3:4': [2592, 3456], '4:3': [3456, 2592],
|
|
33
|
+
'16:9': [3936, 2208], '9:16': [2208, 3936], '2:3': [2496, 3744],
|
|
34
|
+
'3:2': [3744, 2496], '21:9': [4704, 2016],
|
|
35
|
+
},
|
|
36
|
+
'4K': {
|
|
37
|
+
'1:1': [4096, 4096], '3:4': [3456, 4608], '4:3': [4608, 3456],
|
|
38
|
+
'16:9': [5248, 2944], '9:16': [2944, 5248], '2:3': [3328, 4992],
|
|
39
|
+
'3:2': [4992, 3328], '21:9': [6272, 2688],
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export class AgnesImageError extends Error {
|
|
44
|
+
constructor(code, message) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.name = 'AgnesImageError';
|
|
47
|
+
this.code = code;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 列表格式:['a', 'b'],用于错误文案 */
|
|
52
|
+
function pyList(values) {
|
|
53
|
+
return '[' + values.map((v) => `'${v}'`).join(', ') + ']';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function validate(prompt, size, ratio, responseFormat) {
|
|
57
|
+
if (!prompt || !String(prompt).trim()) {
|
|
58
|
+
throw new AgnesImageError('INVALID_PROMPT', 'prompt 不能为空');
|
|
59
|
+
}
|
|
60
|
+
if (!VALID_SIZES.has(size) && !/^\d+x\d+$/.test(size)) {
|
|
61
|
+
throw new AgnesImageError('INVALID_SIZE', `size 必须是 ${pyList([...VALID_SIZES].sort())} 之一或 WxH 格式`);
|
|
62
|
+
}
|
|
63
|
+
if (!VALID_RATIOS.has(ratio)) {
|
|
64
|
+
throw new AgnesImageError('INVALID_RATIO', `ratio 必须是 ${pyList([...VALID_RATIOS].sort())} 之一`);
|
|
65
|
+
}
|
|
66
|
+
if (!VALID_FORMATS.has(responseFormat)) {
|
|
67
|
+
throw new AgnesImageError('INVALID_FORMAT', 'response_format 只能是 url 或 b64_json');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 构造请求体 */
|
|
72
|
+
export function buildPayload(settings, { prompt, size, ratio, responseFormat, images }) {
|
|
73
|
+
const imageList = images || [];
|
|
74
|
+
const extraBody = { response_format: responseFormat };
|
|
75
|
+
if (imageList.length) extraBody.image = imageList;
|
|
76
|
+
const payload = {
|
|
77
|
+
model: settings.model,
|
|
78
|
+
prompt: String(prompt).trim(),
|
|
79
|
+
size,
|
|
80
|
+
extra_body: extraBody,
|
|
81
|
+
};
|
|
82
|
+
// 档位式 size 才配 ratio;精确 WxH 不传,避免语义冲突
|
|
83
|
+
if (VALID_SIZES.has(size)) payload.ratio = ratio;
|
|
84
|
+
if (responseFormat === 'b64_json') payload.return_base64 = true;
|
|
85
|
+
return payload;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 默认 HTTP 实现(可注入替换以测试) */
|
|
89
|
+
async function defaultFetch(url, options) {
|
|
90
|
+
return fetch(url, options);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function guessExtension(bytes, sourceUrl) {
|
|
94
|
+
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return '.png';
|
|
95
|
+
if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) return '.jpg';
|
|
96
|
+
if (bytes.length >= 12 && String.fromCharCode(...bytes.slice(0, 4)) === 'RIFF'
|
|
97
|
+
&& String.fromCharCode(...bytes.slice(8, 12)) === 'WEBP') return '.webp';
|
|
98
|
+
if (sourceUrl) {
|
|
99
|
+
const suffix = path.extname(sourceUrl.split('?')[0]).toLowerCase();
|
|
100
|
+
if (['.png', '.jpg', '.jpeg', '.webp'].includes(suffix)) {
|
|
101
|
+
return suffix === '.jpeg' ? '.jpg' : suffix;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return '.png';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function resolveDimensions(size, ratio) {
|
|
108
|
+
const table = SIZE_PIXELS[size];
|
|
109
|
+
if (table) return table[ratio] || [null, null];
|
|
110
|
+
const m = /^(\d+)x(\d+)$/.exec(size);
|
|
111
|
+
return m ? [Number(m[1]), Number(m[2])] : [null, null];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function save(bytes, settings, extension) {
|
|
115
|
+
const now = new Date();
|
|
116
|
+
const day = `${now.getUTCFullYear()}${String(now.getUTCMonth() + 1).padStart(2, '0')}${String(now.getUTCDate()).padStart(2, '0')}`;
|
|
117
|
+
const directory = path.join(settings.outputDir, day);
|
|
118
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
119
|
+
// 毫秒 + 纳秒余量,保证单调唯一
|
|
120
|
+
const ns = BigInt(Date.now()) * 1000000n + BigInt(process.hrtime.bigint() % 1000000n);
|
|
121
|
+
const target = path.join(directory, `agnes_${ns}${extension}`);
|
|
122
|
+
const temp = `${target}.tmp`;
|
|
123
|
+
try {
|
|
124
|
+
fs.writeFileSync(temp, bytes);
|
|
125
|
+
fs.renameSync(temp, target);
|
|
126
|
+
} finally {
|
|
127
|
+
if (fs.existsSync(temp)) fs.unlinkSync(temp);
|
|
128
|
+
}
|
|
129
|
+
return target;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 文生图 / 图生图 / 多图合成,返回落地后的本地文件信息。
|
|
134
|
+
* @param {object} opts - 可注入 fetchImpl 用于测试
|
|
135
|
+
*/
|
|
136
|
+
export async function generateImage(settings, {
|
|
137
|
+
prompt,
|
|
138
|
+
size = '2K',
|
|
139
|
+
ratio = '1:1',
|
|
140
|
+
responseFormat = 'url',
|
|
141
|
+
images = [],
|
|
142
|
+
fetchImpl = defaultFetch,
|
|
143
|
+
} = {}) {
|
|
144
|
+
validate(prompt, size, ratio, responseFormat);
|
|
145
|
+
const payload = buildPayload(settings, { prompt, size, ratio, responseFormat, images });
|
|
146
|
+
|
|
147
|
+
let response;
|
|
148
|
+
try {
|
|
149
|
+
response = await fetchImpl(settings.endpoint, {
|
|
150
|
+
method: 'POST',
|
|
151
|
+
headers: {
|
|
152
|
+
Authorization: `Bearer ${settings.apiKey}`,
|
|
153
|
+
'Content-Type': 'application/json',
|
|
154
|
+
},
|
|
155
|
+
body: JSON.stringify(payload),
|
|
156
|
+
signal: AbortSignal.timeout(settings.timeoutMs),
|
|
157
|
+
});
|
|
158
|
+
} catch (exc) {
|
|
159
|
+
throw new AgnesImageError('NETWORK_ERROR', `无法连接 Agnes:${exc.message}`);
|
|
160
|
+
}
|
|
161
|
+
if (!response.ok) {
|
|
162
|
+
let detail = '';
|
|
163
|
+
try { detail = (await response.text()).slice(0, 500); } catch { /* ignore */ }
|
|
164
|
+
throw new AgnesImageError(`HTTP_${response.status}`, `Agnes 返回 ${response.status}: ${detail}`);
|
|
165
|
+
}
|
|
166
|
+
let raw;
|
|
167
|
+
try { raw = await response.json(); } catch {
|
|
168
|
+
throw new AgnesImageError('BAD_RESPONSE', '响应不是合法 JSON');
|
|
169
|
+
}
|
|
170
|
+
const data = raw?.data;
|
|
171
|
+
if (!Array.isArray(data) || !data.length || typeof data[0] !== 'object') {
|
|
172
|
+
throw new AgnesImageError('BAD_RESPONSE', '响应缺少 data[0]');
|
|
173
|
+
}
|
|
174
|
+
const item = data[0];
|
|
175
|
+
|
|
176
|
+
let imageBytes;
|
|
177
|
+
let sourceUrl = null;
|
|
178
|
+
if (responseFormat === 'b64_json') {
|
|
179
|
+
const encoded = item.b64_json || item.url;
|
|
180
|
+
if (typeof encoded !== 'string' || !encoded) {
|
|
181
|
+
throw new AgnesImageError('BAD_RESPONSE', '响应缺少 b64_json');
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
imageBytes = Buffer.from(encoded, 'base64');
|
|
185
|
+
} catch (exc) {
|
|
186
|
+
throw new AgnesImageError('BAD_BASE64', `Base64 解码失败:${exc.message}`);
|
|
187
|
+
}
|
|
188
|
+
} else {
|
|
189
|
+
sourceUrl = item.url;
|
|
190
|
+
if (typeof sourceUrl !== 'string' || !/^https?:\/\//.test(sourceUrl)) {
|
|
191
|
+
throw new AgnesImageError('BAD_RESPONSE', '响应缺少可用的 url');
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
const dl = await fetchImpl(sourceUrl, { headers: { 'User-Agent': 'agnes-image-mcp/0.1' } });
|
|
195
|
+
if (!dl.ok) throw new Error(`HTTP ${dl.status}`);
|
|
196
|
+
imageBytes = Buffer.from(await dl.arrayBuffer());
|
|
197
|
+
} catch (exc) {
|
|
198
|
+
throw new AgnesImageError('DOWNLOAD_FAILED', `图片下载失败:${exc.message}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (!imageBytes || !imageBytes.length) {
|
|
202
|
+
throw new AgnesImageError('EMPTY_IMAGE', '图片内容为空');
|
|
203
|
+
}
|
|
204
|
+
const extension = guessExtension(imageBytes, sourceUrl);
|
|
205
|
+
const filePath = save(imageBytes, settings, extension);
|
|
206
|
+
const [width, height] = resolveDimensions(size, ratio);
|
|
207
|
+
return {
|
|
208
|
+
path: filePath,
|
|
209
|
+
source_url: sourceUrl,
|
|
210
|
+
width,
|
|
211
|
+
height,
|
|
212
|
+
size,
|
|
213
|
+
ratio,
|
|
214
|
+
revised_prompt: typeof item.revised_prompt === 'string' ? item.revised_prompt : null,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export default {
|
|
219
|
+
generateImage, buildPayload, validate, guessExtension, resolveDimensions,
|
|
220
|
+
VALID_SIZES, VALID_RATIOS, VALID_FORMATS, SIZE_PIXELS, AgnesImageError,
|
|
221
|
+
};
|
package/src/config.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** 集中配置:从 .env / 环境变量读取,带校验。key 缺失启动即报错。 */
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import dotenv from 'dotenv';
|
|
6
|
+
|
|
7
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
const ROOT = path.resolve(__dirname, '..');
|
|
9
|
+
|
|
10
|
+
const envPath = path.join(ROOT, '.env');
|
|
11
|
+
if (fs.existsSync(envPath)) dotenv.config({ path: envPath, override: false });
|
|
12
|
+
// npx 场景包在 npm 缓存中,包内没有 .env:再从调用方工作目录兜底读取。
|
|
13
|
+
// override:false 保证 MCP 客户端注入的 env > cwd .env > 包内 .env。
|
|
14
|
+
const cwdEnvPath = path.join(process.cwd(), '.env');
|
|
15
|
+
if (cwdEnvPath !== envPath && fs.existsSync(cwdEnvPath)) {
|
|
16
|
+
dotenv.config({ path: cwdEnvPath, override: false });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const DEFAULT_BASE_URL = 'https://apihub.agnes-ai.com/v1';
|
|
20
|
+
const DEFAULT_MODEL = 'agnes-image-2.5-flash';
|
|
21
|
+
// 图片是交付物,不能落到 npx 缓存目录;默认放在调用方工作目录
|
|
22
|
+
const DEFAULT_OUTPUT_DIR = path.join(process.cwd(), 'agnes-images');
|
|
23
|
+
|
|
24
|
+
function intEnv(name, fallback) {
|
|
25
|
+
const raw = String(process.env[name] || '').trim();
|
|
26
|
+
if (!raw) return fallback;
|
|
27
|
+
const value = Number(raw);
|
|
28
|
+
return Number.isInteger(value) && value > 0 ? value : fallback;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// key 必填:兼容 market-agent 的 AI_IMAGE_KEY
|
|
32
|
+
const apiKey = String(process.env.AGNES_IMAGE_API_KEY || process.env.AI_IMAGE_KEY || '').trim();
|
|
33
|
+
if (!apiKey) {
|
|
34
|
+
throw new Error('缺少 Agnes API key:请设置 AGNES_IMAGE_API_KEY(或 AI_IMAGE_KEY)');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const baseUrl = String(process.env.AGNES_BASE_URL || DEFAULT_BASE_URL).trim() || DEFAULT_BASE_URL;
|
|
38
|
+
const outputDir = path.resolve(String(process.env.AGNES_IMAGE_OUTPUT_DIR || '').trim() || DEFAULT_OUTPUT_DIR);
|
|
39
|
+
|
|
40
|
+
export const config = Object.freeze({
|
|
41
|
+
root: ROOT,
|
|
42
|
+
baseUrl,
|
|
43
|
+
endpoint: `${baseUrl.replace(/\/$/, '')}/images/generations`,
|
|
44
|
+
model: String(process.env.AGNES_IMAGE_MODEL || DEFAULT_MODEL).trim() || DEFAULT_MODEL,
|
|
45
|
+
apiKey,
|
|
46
|
+
timeoutMs: intEnv('AGNES_IMAGE_TIMEOUT_SECONDS', 180) * 1000,
|
|
47
|
+
outputDir,
|
|
48
|
+
host: process.env.HOST || '127.0.0.1',
|
|
49
|
+
port: Number(process.env.PORT || 8321),
|
|
50
|
+
logLevel: String(process.env.LOG_LEVEL || 'info').toLowerCase(),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
export default config;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agnes 生图 MCP 服务(Node 独立版)
|
|
3
|
+
* 3 个工具:generate_image / edit_image / get_image_specs
|
|
4
|
+
* 只做生图,不含活动规则逻辑。
|
|
5
|
+
*/
|
|
6
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
7
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
8
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
9
|
+
import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
|
|
13
|
+
import config from './config.js';
|
|
14
|
+
import { info, warn, error, runWithRequestId, newRequestId, logged } from './logs.js';
|
|
15
|
+
import {
|
|
16
|
+
generateImage, AgnesImageError, VALID_SIZES, VALID_RATIOS, VALID_FORMATS, SIZE_PIXELS,
|
|
17
|
+
} from './client.js';
|
|
18
|
+
|
|
19
|
+
const STARTED_AT = Date.now();
|
|
20
|
+
|
|
21
|
+
const MCP_INSTRUCTIONS = [
|
|
22
|
+
'本服务提供 Agnes Image 2.5 Flash 生图能力:文生图、图生图、多图合成。',
|
|
23
|
+
'文生图用 generate_image;带参考图转换风格或合成用 edit_image;生成前可用 get_image_specs 查档位与比例。',
|
|
24
|
+
'size 用 1K/2K/3K/4K 档位配 ratio;也兼容 1024x768 精确写法(此时不需要 ratio)。',
|
|
25
|
+
'图片一律落盘到本地并返回绝对路径 source_url 供追溯;把 path 交给下游服务(如 market-agent 的 apply_image_results)即可回填活动配置。',
|
|
26
|
+
'所有工具返回标准 CallToolResult:content[0].text 为完整 JSON,structuredContent 为结构化对象,读任一即可。',
|
|
27
|
+
].join('\n');
|
|
28
|
+
|
|
29
|
+
/** 把 generateImage 结果/异常转成工具返回体 */
|
|
30
|
+
async function runGeneration(args) {
|
|
31
|
+
try {
|
|
32
|
+
const result = await generateImage(config, {
|
|
33
|
+
prompt: args.prompt,
|
|
34
|
+
size: args.size ?? '2K',
|
|
35
|
+
ratio: args.ratio ?? '1:1',
|
|
36
|
+
responseFormat: args.response_format ?? 'url',
|
|
37
|
+
images: args.images ?? [],
|
|
38
|
+
});
|
|
39
|
+
return {
|
|
40
|
+
ok: true,
|
|
41
|
+
path: result.path,
|
|
42
|
+
width: result.width,
|
|
43
|
+
height: result.height,
|
|
44
|
+
size: result.size,
|
|
45
|
+
ratio: result.ratio,
|
|
46
|
+
source_url: result.source_url,
|
|
47
|
+
revised_prompt: result.revised_prompt,
|
|
48
|
+
};
|
|
49
|
+
} catch (exc) {
|
|
50
|
+
if (exc instanceof AgnesImageError) {
|
|
51
|
+
return { ok: false, code: exc.code, error: exc.message };
|
|
52
|
+
}
|
|
53
|
+
return { ok: false, code: exc?.name || 'Error', error: exc?.message || String(exc) };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createServer() {
|
|
58
|
+
const server = new McpServer({
|
|
59
|
+
name: 'agnes-image',
|
|
60
|
+
title: 'Agnes 生图 MCP',
|
|
61
|
+
description: 'Agnes Image 2.5 Flash 生图:文生图、图生图、多图合成。图片落盘返回绝对路径。',
|
|
62
|
+
version: '0.1.0',
|
|
63
|
+
instructions: MCP_INSTRUCTIONS,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// 标准 CallToolResult 包装:content[0].text + structuredContent 双输出
|
|
67
|
+
const reg = (name, description, inputSchema, fn) => {
|
|
68
|
+
const handler = logged(name, fn);
|
|
69
|
+
return server.registerTool(name, { description, inputSchema }, async (args) => {
|
|
70
|
+
const data = await handler(args);
|
|
71
|
+
const isObject = data && typeof data === 'object' && !Array.isArray(data);
|
|
72
|
+
const text = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
|
|
73
|
+
return {
|
|
74
|
+
content: [{ type: 'text', text }],
|
|
75
|
+
...(isObject ? { structuredContent: data } : {}),
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
reg('generate_image',
|
|
81
|
+
'文生图:按提示词生成图片,保存到本地并返回绝对路径。size 用 1K/2K/3K/4K 档位配 ratio;response_format 选 url 或 b64_json。',
|
|
82
|
+
{
|
|
83
|
+
prompt: z.string(),
|
|
84
|
+
size: z.string().optional().default('2K'),
|
|
85
|
+
ratio: z.string().optional().default('1:1'),
|
|
86
|
+
response_format: z.string().optional().default('url'),
|
|
87
|
+
},
|
|
88
|
+
runGeneration);
|
|
89
|
+
|
|
90
|
+
reg('edit_image',
|
|
91
|
+
'图生图 / 多图合成:传入提示词和 1 张以上参考图(公网 URL 或 data URI Base64),按提示词转换风格或合成新图,保存到本地并返回绝对路径。',
|
|
92
|
+
{
|
|
93
|
+
prompt: z.string(),
|
|
94
|
+
images: z.array(z.string()),
|
|
95
|
+
size: z.string().optional().default('2K'),
|
|
96
|
+
ratio: z.string().optional().default('1:1'),
|
|
97
|
+
response_format: z.string().optional().default('url'),
|
|
98
|
+
},
|
|
99
|
+
(args) => {
|
|
100
|
+
if (!args.images || !args.images.length) {
|
|
101
|
+
return { ok: false, code: 'NO_IMAGES', error: '至少需要一张参考图' };
|
|
102
|
+
}
|
|
103
|
+
return runGeneration(args);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
reg('get_image_specs',
|
|
107
|
+
'查询 Agnes 生图支持的 size 档位、ratio 宽高比,以及每个组合的实际像素尺寸。生成前可调用此工具选择合适的档位与比例。',
|
|
108
|
+
{},
|
|
109
|
+
() => ({
|
|
110
|
+
ok: true,
|
|
111
|
+
model: config.model,
|
|
112
|
+
sizes: [...VALID_SIZES].sort(),
|
|
113
|
+
ratios: [...VALID_RATIOS].sort(),
|
|
114
|
+
response_formats: [...VALID_FORMATS].sort(),
|
|
115
|
+
pixels: SIZE_PIXELS,
|
|
116
|
+
output_dir: config.outputDir,
|
|
117
|
+
}));
|
|
118
|
+
|
|
119
|
+
return server;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function createApp() {
|
|
123
|
+
const app = createMcpExpressApp({ host: config.host });
|
|
124
|
+
const server = createServer();
|
|
125
|
+
|
|
126
|
+
app.post('/mcp', async (req, res) => {
|
|
127
|
+
const requestId = newRequestId();
|
|
128
|
+
await runWithRequestId(requestId, async () => {
|
|
129
|
+
const start = Date.now();
|
|
130
|
+
info('MCP 请求进入', {
|
|
131
|
+
event: 'http_request', method: req.body?.method,
|
|
132
|
+
tool: req.body?.method === 'tools/call' ? req.body?.params?.name : undefined,
|
|
133
|
+
});
|
|
134
|
+
try {
|
|
135
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
136
|
+
res.on('close', () => transport.close());
|
|
137
|
+
await server.connect(transport);
|
|
138
|
+
await transport.handleRequest(req, res, req.body);
|
|
139
|
+
info(`MCP 请求完成(${Date.now() - start}ms)`, { event: 'http_end', ms: Date.now() - start });
|
|
140
|
+
} catch (exc) {
|
|
141
|
+
error(`MCP 请求处理失败:${exc?.message || exc}`, {
|
|
142
|
+
event: 'http_error', ms: Date.now() - start, error_message: exc?.message,
|
|
143
|
+
});
|
|
144
|
+
if (!res.headersSent) {
|
|
145
|
+
res.status(500).json({
|
|
146
|
+
jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error', data: { requestId } }, id: null,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
app.get('/healthz', (_req, res) => res.json({
|
|
154
|
+
ok: true,
|
|
155
|
+
service: 'agnes-image-mcp-node',
|
|
156
|
+
model: config.model,
|
|
157
|
+
endpoint: config.endpoint,
|
|
158
|
+
api_key_configured: Boolean(config.apiKey),
|
|
159
|
+
tools: 3,
|
|
160
|
+
uptime_seconds: Math.floor((Date.now() - STARTED_AT) / 1000),
|
|
161
|
+
}));
|
|
162
|
+
return app;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
process.on('uncaughtException', (exc) => {
|
|
166
|
+
error(`未捕获异常:${exc?.stack || exc?.message || exc}`, { event: 'uncaught_exception' });
|
|
167
|
+
});
|
|
168
|
+
process.on('unhandledRejection', (reason) => {
|
|
169
|
+
error(`未处理的 Promise 拒绝:${reason?.stack || reason?.message || reason}`, { event: 'unhandled_rejection' });
|
|
170
|
+
});
|
|
171
|
+
for (const sig of ['SIGTERM', 'SIGINT']) {
|
|
172
|
+
process.on(sig, () => { info(`收到 ${sig},退出`); process.exit(0); });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** stdio:npx / 桌面客户端的默认模式。日志走 stderr,stdout 只跑 JSON-RPC */
|
|
176
|
+
export async function startStdio() {
|
|
177
|
+
const server = createServer();
|
|
178
|
+
await server.connect(new StdioServerTransport());
|
|
179
|
+
info('agnes-image-mcp-node 已启动(stdio,3 个工具)', { event: 'stdio_start' });
|
|
180
|
+
return server;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** HTTP:保留原有 Streamable HTTP 模式(--http) */
|
|
184
|
+
export async function startHttp() {
|
|
185
|
+
const app = createApp();
|
|
186
|
+
return new Promise((resolve, reject) => {
|
|
187
|
+
const httpServer = app.listen(config.port, config.host, () => {
|
|
188
|
+
info(`agnes-image-mcp-node 已启动:http://${config.host}:${config.port}/mcp(3 个工具)`,
|
|
189
|
+
{ event: 'http_start' });
|
|
190
|
+
resolve(httpServer);
|
|
191
|
+
});
|
|
192
|
+
httpServer.once('error', reject);
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
197
|
+
startHttp().catch((exc) => {
|
|
198
|
+
error(`HTTP 启动失败:${exc?.message || exc}`, { event: 'http_start_error' });
|
|
199
|
+
process.exit(1);
|
|
200
|
+
});
|
|
201
|
+
}
|
package/src/logs.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 纯进程日志:只写 stderr,不落盘、不轮转。
|
|
3
|
+
* 日志由运行进程的环境(终端 / systemd / 容器)统一收集。
|
|
4
|
+
*
|
|
5
|
+
* 行格式:
|
|
6
|
+
* <ts> <LEVEL> [<requestId>] <msg> {"event":...,"tool":...,"ms":...,"ok":...}
|
|
7
|
+
* 前半人类可读,尾部结构化字段便于日志系统检索。
|
|
8
|
+
*
|
|
9
|
+
* 每次 MCP 调用通过 AsyncLocalStorage 贯穿 requestId,
|
|
10
|
+
* 一次调用的多条日志可用 grep requestId 串起来。
|
|
11
|
+
*/
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
14
|
+
import config from './config.js';
|
|
15
|
+
|
|
16
|
+
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
17
|
+
const MIN_LEVEL = LEVELS[config.logLevel] ?? LEVELS.info;
|
|
18
|
+
|
|
19
|
+
// requestId 贯穿异步调用链
|
|
20
|
+
const requestStore = new AsyncLocalStorage();
|
|
21
|
+
export function runWithRequestId(requestId, fn) {
|
|
22
|
+
return requestStore.run(requestId, fn);
|
|
23
|
+
}
|
|
24
|
+
export function currentRequestId() {
|
|
25
|
+
return requestStore.getStore() || '-';
|
|
26
|
+
}
|
|
27
|
+
export function newRequestId() {
|
|
28
|
+
return crypto.randomBytes(6).toString('hex');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function emit(level, msg, fields = {}) {
|
|
32
|
+
if (LEVELS[level] < MIN_LEVEL) return;
|
|
33
|
+
const ts = new Date().toISOString();
|
|
34
|
+
const rid = currentRequestId();
|
|
35
|
+
const extra = Object.keys(fields).length ? ' ' + JSON.stringify(fields) : '';
|
|
36
|
+
process.stderr.write(`${ts} ${level.toUpperCase().padEnd(5)} [${rid}] ${msg}${extra}\n`);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function debug(msg, fields) { emit('debug', msg, fields); }
|
|
40
|
+
export function info(msg, fields) { emit('info', msg, fields); }
|
|
41
|
+
export function warn(msg, fields) { emit('warn', msg, fields); }
|
|
42
|
+
export function error(msg, fields) { emit('error', msg, fields); }
|
|
43
|
+
|
|
44
|
+
/** 工具包装:requestId + 结构化审计 + 异常兜底 + 统一 ok 字段 */
|
|
45
|
+
export function logged(name, fn) {
|
|
46
|
+
return async (args) => {
|
|
47
|
+
const start = performance.now();
|
|
48
|
+
debug(`工具调用:${name}`, { event: 'tool_start', tool: name, args_summary: summarizeArgs(args) });
|
|
49
|
+
try {
|
|
50
|
+
const result = await fn(args);
|
|
51
|
+
const ms = Math.round(performance.now() - start);
|
|
52
|
+
info(`工具完成:${name}(${ms}ms)`, {
|
|
53
|
+
event: 'tool_end', tool: name, ms, ok: result?.ok !== false,
|
|
54
|
+
});
|
|
55
|
+
if (result && typeof result === 'object' && !Array.isArray(result)) {
|
|
56
|
+
if (!('ok' in result)) result.ok = true;
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
} catch (exc) {
|
|
61
|
+
const ms = Math.round(performance.now() - start);
|
|
62
|
+
error(`工具失败:${name} - ${exc?.message || exc}`, {
|
|
63
|
+
event: 'tool_error', tool: name, ms,
|
|
64
|
+
error_code: exc?.code || exc?.name || 'Error',
|
|
65
|
+
error_message: exc?.message || String(exc),
|
|
66
|
+
});
|
|
67
|
+
return { ok: false, code: exc?.code || exc?.name || 'Error', error: exc?.message || String(exc) };
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function summarizeArgs(args) {
|
|
73
|
+
if (!args || typeof args !== 'object') return {};
|
|
74
|
+
const out = {};
|
|
75
|
+
if (Array.isArray(args.images)) out.images_count = args.images.length;
|
|
76
|
+
if (typeof args.prompt === 'string') out.prompt_len = args.prompt.length;
|
|
77
|
+
if (typeof args.size === 'string') out.size = args.size;
|
|
78
|
+
if (typeof args.ratio === 'string') out.ratio = args.ratio;
|
|
79
|
+
if (typeof args.response_format === 'string') out.response_format = args.response_format;
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export default { runWithRequestId, currentRequestId, newRequestId, debug, info, warn, error, logged };
|