@modelbay/mcp 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/LICENSE +21 -0
- package/README.md +102 -2
- package/dist/arguments.mjs +105 -0
- package/dist/assets.mjs +109 -0
- package/dist/bin/modelbay-mcp.d.mts +1 -0
- package/dist/bin/modelbay-mcp.mjs +11 -0
- package/dist/derive.d.mts +29 -0
- package/dist/derive.mjs +206 -0
- package/dist/framing.d.mts +15 -0
- package/dist/framing.mjs +129 -0
- package/dist/generate.d.mts +16 -0
- package/dist/generate.mjs +126 -0
- package/dist/index.d.mts +10 -0
- package/dist/index.mjs +10 -0
- package/dist/jobs.mjs +118 -0
- package/dist/launch.d.mts +25 -0
- package/dist/launch.mjs +78 -0
- package/dist/routing.d.mts +14 -0
- package/dist/routing.mjs +252 -0
- package/dist/server.d.mts +5 -0
- package/dist/server.mjs +85 -0
- package/dist/stdio-transport.d.mts +10 -0
- package/dist/stdio-transport.mjs +38 -0
- package/dist/tool-meta.d.mts +17 -0
- package/dist/tool-meta.mjs +54 -0
- package/dist/types.d.mts +121 -0
- package/dist/types.mjs +31 -0
- package/package.json +46 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ikuyu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,103 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @modelbay/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MCP tool generator and per-platform stdio servers for [Modelbay](../../README.md). MIT licensed.
|
|
4
|
+
|
|
5
|
+
`@modelbay/mcp` derives MCP tools from `ModelDeclaration` data and `@modelbay/core` schemas, and
|
|
6
|
+
serves them over a minimal stdio JSON-RPC transport. It does **not** depend on
|
|
7
|
+
`@modelcontextprotocol/sdk` or any other new runtime dependency.
|
|
8
|
+
|
|
9
|
+
## Command
|
|
10
|
+
|
|
11
|
+
One command serves every platform that ships MCP tools; the platform is the first argument:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npx -y @modelbay/mcp ark # or: modelbay-mcp ark
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
| Platform | Argument | Required keys (any one row) |
|
|
18
|
+
| --------------- | --------------- | ------------------------------------------------------------ |
|
|
19
|
+
| Volcengine Ark | `ark` | `ARK_API_KEY`, or `ARK_AGENT_PLAN_API_KEY` |
|
|
20
|
+
| MiniMax | `minimax` | `MINIMAX_API_KEY` |
|
|
21
|
+
| Alibaba Bailian | `bailian` | `BAILIAN_API_KEY` (alias `DASHSCOPE_API_KEY`) |
|
|
22
|
+
| Doubao Speech | `doubao-speech` | `DOUBAO_API_KEY`, or `DOUBAO_APP_ID` + `DOUBAO_ACCESS_TOKEN` |
|
|
23
|
+
|
|
24
|
+
The platform list, key names and aliases come from each platform package's `PlatformDescriptor`;
|
|
25
|
+
running `modelbay-mcp` without an argument prints the available platforms. Keys are supplied by the
|
|
26
|
+
host through environment variables and never stored. When a key is missing, `tools/list` still
|
|
27
|
+
works and `tools/call` returns an error naming the missing variables.
|
|
28
|
+
|
|
29
|
+
### Node-only capabilities
|
|
30
|
+
|
|
31
|
+
Some capabilities need Node-only implementations (object-storage uploads, `sharp` mask
|
|
32
|
+
processing). They live in the platform packages' optional subpaths and are loaded and injected
|
|
33
|
+
automatically at launch through `modelbay/node` (each subpath exports `nodeOptions`):
|
|
34
|
+
|
|
35
|
+
| Platform | Subpath | Injected option | Capability |
|
|
36
|
+
| -------- | ------------------------------ | ------------------------------------------------- | ------------------------------------------------- |
|
|
37
|
+
| Ark | `@modelbay/ark/node` | `uploadVideo`, `transcribePlan`, `listPlanModels` | video reference upload, plan ASR, plan model list |
|
|
38
|
+
| Bailian | `@modelbay/bailian/node` | `edit`, `process` | `image.edit`, `image.process` |
|
|
39
|
+
| Doubao | `@modelbay/doubao-speech/node` | `asr`, `interpretation` | streaming ASR, simultaneous interpretation |
|
|
40
|
+
|
|
41
|
+
The optional peer dependencies (`@volcengine/tos-sdk`, `sharp`, `ws`) are imported lazily inside
|
|
42
|
+
those subpaths, so a missing dependency never stops the server from starting — the call that needs
|
|
43
|
+
it fails with an explicit "install X" error instead. When a subpath cannot be loaded at all, the
|
|
44
|
+
adapter is created without that option and the affected capability reports which subpath to inject.
|
|
45
|
+
|
|
46
|
+
Ark's reference-video upload additionally needs the storage configuration, read from the same
|
|
47
|
+
environment: `ARK_REFERENCE_STORAGE` (`tos` / `oss` / `cos` / `s3`), `ARK_REFERENCE_BUCKET`,
|
|
48
|
+
`ARK_REFERENCE_REGION`, and optionally `ARK_REFERENCE_ENDPOINT` and `ARK_REFERENCE_PATH_STYLE`,
|
|
49
|
+
plus the key pair `ARK_TOS_ACCESS_KEY` / `ARK_TOS_SECRET_KEY`. These are optional: without them the
|
|
50
|
+
server still starts and only the video-reference path is unavailable.
|
|
51
|
+
|
|
52
|
+
## Tool groups
|
|
53
|
+
|
|
54
|
+
`MODELBAY_MCP_GROUPS` (comma separated) controls which groups are exposed by `tools/list`:
|
|
55
|
+
|
|
56
|
+
| Group | Default | Contents |
|
|
57
|
+
| ------------ | ------- | ------------------------------------------------------------------------- |
|
|
58
|
+
| `core` | yes | generation, query and local/introspection tools |
|
|
59
|
+
| `realtime` | no | realtime session open/send/receive/close |
|
|
60
|
+
| `management` | no | console, hotword tables, task deletion, raw request |
|
|
61
|
+
| `node` | no | capabilities that require the optional `node:` subpath (e.g. file upload) |
|
|
62
|
+
|
|
63
|
+
Example: `MODELBAY_MCP_GROUPS=core,realtime modelbay-mcp doubao-speech`.
|
|
64
|
+
|
|
65
|
+
## How tools are generated
|
|
66
|
+
|
|
67
|
+
- Each platform package defines its tools in `src/mcp/tools.ts` (`ToolSpec[]`): field shapes,
|
|
68
|
+
platform switches and parameter descriptions, plus routing hints (`capability`, `native`,
|
|
69
|
+
`nature`, `group`, `modelParams`). No model IDs, limits, defaults or lifecycle strings.
|
|
70
|
+
- The **model part** of each `inputSchema` — model IDs, defaults, per-model limits and lifecycle
|
|
71
|
+
notices — is derived at startup from the platform's `ModelDeclaration`s via `@modelbay/core`.
|
|
72
|
+
Editing a declaration changes the generated tools; nothing is hardcoded.
|
|
73
|
+
- `annotations` are derived from the tool's `nature` (`generate` / `query` / `mutate` / `local` /
|
|
74
|
+
`realtime`).
|
|
75
|
+
- Shared capabilities use the same tool name on every platform (`generate_image`,
|
|
76
|
+
`text_to_speech`, `clone_voice`, `design_voice`, `get_job`, ...).
|
|
77
|
+
|
|
78
|
+
Details (in Chinese): [`docs/mcp.md`](../../docs/mcp.md).
|
|
79
|
+
|
|
80
|
+
## JSON-RPC methods
|
|
81
|
+
|
|
82
|
+
`initialize`, `ping`, `tools/list`, `tools/call`; plus `resources/list`,
|
|
83
|
+
`resources/templates/list`, `prompts/list` (empty, protocol completeness). Framing supports both
|
|
84
|
+
newline-delimited JSON (MCP stdio standard) and `Content-Length` headers. Responses use the same
|
|
85
|
+
framing as the request. All logs go to **stderr** so stdout is never polluted.
|
|
86
|
+
|
|
87
|
+
`tools/call` routes to `PlatformAdapter.submit` (normalized capabilities) or
|
|
88
|
+
`PlatformAdapter.native` (single-platform ops); local introspection tools are answered in-process.
|
|
89
|
+
|
|
90
|
+
## Programmatic use
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { generateTools, listTools, createServer, createHandlers, MCP_TOOL_GROUPS } from '@modelbay/mcp'
|
|
94
|
+
|
|
95
|
+
const set = generateTools('ark', { adapter: arkAdapter }) // or pass a PlatformDescriptor
|
|
96
|
+
const tools = listTools(set, MCP_TOOL_GROUPS.all) // every tool, including optional groups
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Testing
|
|
100
|
+
|
|
101
|
+
`vp test run packages/mcp` runs the parity tests against the frozen tool-list snapshots in
|
|
102
|
+
`test/baselines/` (70 tools), a real stdio smoke test (child process + pipes), and unit tests for
|
|
103
|
+
schema derivation, group switches, routing and error paths.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { mimeFromName } from "./assets.mjs";
|
|
2
|
+
import { ProviderError } from "modelbay";
|
|
3
|
+
// src/arguments.ts
|
|
4
|
+
/**
|
|
5
|
+
* MCP 工具参数 → 归一化能力输入的通用映射。
|
|
6
|
+
*
|
|
7
|
+
* 工具目录沿用各平台原 MCP 的字段名(`prompt`、`history`、`max_tokens`、`voice_id`…),
|
|
8
|
+
* 适配器按 `CapabilityInputs` 的归一化字段读取。这里只做「补」:归一化字段没给时,
|
|
9
|
+
* 从同义的 MCP 字段换算出来;原字段保留,适配器里已有的 MCP 专属处理照常生效。
|
|
10
|
+
* 和具体平台、模型有关的字段不在这里处理。
|
|
11
|
+
*/
|
|
12
|
+
const has = (value) => value !== void 0 && value !== null;
|
|
13
|
+
function setIfAbsent(input, key, value) {
|
|
14
|
+
if (!has(input[key]) && has(value)) input[key] = value;
|
|
15
|
+
}
|
|
16
|
+
/** 路径 / URL → AssetRef;种类由参数本身决定。 */
|
|
17
|
+
function asset(value, kind, field) {
|
|
18
|
+
if (typeof value !== "string" || !value.trim()) throw new ProviderError("invalid_input", `${field} 须为本地路径或 URL`);
|
|
19
|
+
const mime = mimeFromName(value);
|
|
20
|
+
return {
|
|
21
|
+
assetId: value,
|
|
22
|
+
kind,
|
|
23
|
+
...mime ? { mime } : {}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function assets(value, kind, field) {
|
|
27
|
+
if (!has(value)) return [];
|
|
28
|
+
return (Array.isArray(value) ? value : [value]).map((item) => asset(item, kind, field));
|
|
29
|
+
}
|
|
30
|
+
function chatMessages(args) {
|
|
31
|
+
const prompt = args.prompt;
|
|
32
|
+
const history = args.history;
|
|
33
|
+
const system = args.system;
|
|
34
|
+
if (!has(prompt) && !has(history)) return void 0;
|
|
35
|
+
if (has(history) && !Array.isArray(history)) throw new ProviderError("invalid_input", "history 须为消息数组");
|
|
36
|
+
const messages = [];
|
|
37
|
+
if (typeof system === "string" && system.trim()) messages.push({
|
|
38
|
+
role: "system",
|
|
39
|
+
content: system
|
|
40
|
+
});
|
|
41
|
+
for (const item of history ?? []) {
|
|
42
|
+
const message = item;
|
|
43
|
+
if (typeof message?.role !== "string" || !has(message.content)) throw new ProviderError("invalid_input", "history 里的每条消息都需要 role 和 content");
|
|
44
|
+
messages.push({
|
|
45
|
+
role: message.role,
|
|
46
|
+
content: message.content
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
const images = assets(args.images, "image", "images");
|
|
50
|
+
if (images.length) messages.push({
|
|
51
|
+
role: "user",
|
|
52
|
+
content: [...typeof prompt === "string" && prompt ? [{
|
|
53
|
+
type: "text",
|
|
54
|
+
text: prompt
|
|
55
|
+
}] : [], ...images.map((image) => ({
|
|
56
|
+
type: "image",
|
|
57
|
+
image
|
|
58
|
+
}))]
|
|
59
|
+
});
|
|
60
|
+
else if (typeof prompt === "string") messages.push({
|
|
61
|
+
role: "user",
|
|
62
|
+
content: prompt
|
|
63
|
+
});
|
|
64
|
+
return messages;
|
|
65
|
+
}
|
|
66
|
+
/** 按能力补齐归一化字段;返回新对象,不改入参。 */
|
|
67
|
+
function normalizeArguments(capability, args) {
|
|
68
|
+
const input = { ...args };
|
|
69
|
+
switch (capability) {
|
|
70
|
+
case "text.chat":
|
|
71
|
+
if (!Array.isArray(input.messages)) {
|
|
72
|
+
if (has(input.images) && !has(input.prompt)) throw new ProviderError("invalid_input", "images 需要同时提供 prompt");
|
|
73
|
+
const messages = chatMessages(input);
|
|
74
|
+
if (messages) input.messages = messages;
|
|
75
|
+
}
|
|
76
|
+
setIfAbsent(input, "maxTokens", input.max_tokens);
|
|
77
|
+
break;
|
|
78
|
+
case "audio.speech":
|
|
79
|
+
setIfAbsent(input, "voice", input.voice_id);
|
|
80
|
+
setIfAbsent(input, "instruction", input.instructions);
|
|
81
|
+
break;
|
|
82
|
+
case "image.generate": {
|
|
83
|
+
setIfAbsent(input, "negativePrompt", input.negative_prompt);
|
|
84
|
+
setIfAbsent(input, "count", input.n);
|
|
85
|
+
const references = assets(input.images, "image", "images");
|
|
86
|
+
if (references.length) setIfAbsent(input, "references", references);
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
case "video.generate": {
|
|
90
|
+
setIfAbsent(input, "aspectRatio", input.ratio ?? input.aspect_ratio);
|
|
91
|
+
if (has(input.first_frame)) setIfAbsent(input, "firstFrame", asset(input.first_frame, "image", "first_frame"));
|
|
92
|
+
if (has(input.last_frame)) setIfAbsent(input, "lastFrame", asset(input.last_frame, "image", "last_frame"));
|
|
93
|
+
const references = [
|
|
94
|
+
...assets(input.reference_images, "image", "reference_images"),
|
|
95
|
+
...assets(input.reference_videos, "video", "reference_videos"),
|
|
96
|
+
...assets(input.reference_audios, "audio", "reference_audios")
|
|
97
|
+
];
|
|
98
|
+
if (references.length) setIfAbsent(input, "references", references);
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
case "audio.transcribe": if (typeof input.audio === "string") input.audio = asset(input.audio, "audio", "audio");
|
|
102
|
+
}
|
|
103
|
+
return input;
|
|
104
|
+
}
|
|
105
|
+
export { normalizeArguments };
|
package/dist/assets.mjs
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { ProviderError } from "modelbay";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { extname, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
// src/assets.ts
|
|
7
|
+
/**
|
|
8
|
+
* MCP 的素材来源:工具参数里的图片 / 音频 / 视频是本地路径、`file://`、`http(s)://` 或 `data:` URL,
|
|
9
|
+
* 适配器按 `AssetRef.assetId` 读取时由这里取字节。没有这层,适配器拿不到任何输入素材。
|
|
10
|
+
*/
|
|
11
|
+
const MIME_BY_EXT = {
|
|
12
|
+
".png": "image/png",
|
|
13
|
+
".jpg": "image/jpeg",
|
|
14
|
+
".jpeg": "image/jpeg",
|
|
15
|
+
".webp": "image/webp",
|
|
16
|
+
".gif": "image/gif",
|
|
17
|
+
".bmp": "image/bmp",
|
|
18
|
+
".tif": "image/tiff",
|
|
19
|
+
".tiff": "image/tiff",
|
|
20
|
+
".heic": "image/heic",
|
|
21
|
+
".heif": "image/heif",
|
|
22
|
+
".mp4": "video/mp4",
|
|
23
|
+
".mov": "video/quicktime",
|
|
24
|
+
".webm": "video/webm",
|
|
25
|
+
".mp3": "audio/mpeg",
|
|
26
|
+
".wav": "audio/wav",
|
|
27
|
+
".m4a": "audio/mp4",
|
|
28
|
+
".aac": "audio/aac",
|
|
29
|
+
".ogg": "audio/ogg",
|
|
30
|
+
".opus": "audio/opus",
|
|
31
|
+
".flac": "audio/flac",
|
|
32
|
+
".pcm": "audio/pcm",
|
|
33
|
+
".amr": "audio/amr"
|
|
34
|
+
};
|
|
35
|
+
const EXT_BY_MIME = Object.fromEntries(Object.entries(MIME_BY_EXT).reverse().map(([ext, mime]) => [mime, ext]));
|
|
36
|
+
/** 按扩展名猜 MIME;猜不出时返回 undefined。 */
|
|
37
|
+
function mimeFromName(name) {
|
|
38
|
+
const path = name.split(/[?#]/)[0] ?? name;
|
|
39
|
+
return MIME_BY_EXT[extname(path).toLowerCase()];
|
|
40
|
+
}
|
|
41
|
+
/** 按 MIME 取常用扩展名(含点);没有时返回空字符串。 */
|
|
42
|
+
function extensionFor(mime) {
|
|
43
|
+
return EXT_BY_MIME[mime.split(";")[0].trim().toLowerCase()] ?? "";
|
|
44
|
+
}
|
|
45
|
+
function decodeDataUrl(ref) {
|
|
46
|
+
const match = /^data:([^;,]*)((?:;[^,]*)?),(.*)$/s.exec(ref);
|
|
47
|
+
if (!match) throw new ProviderError("invalid_input", "data URL 格式不正确");
|
|
48
|
+
const mime = match[1] || "application/octet-stream";
|
|
49
|
+
const body = match[3] ?? "";
|
|
50
|
+
return {
|
|
51
|
+
data: match[2]?.includes(";base64") ? Uint8Array.from(Buffer.from(body, "base64")) : percentDecode(body),
|
|
52
|
+
mime
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** 百分号转义直接解成字节(二进制内容不一定是合法 UTF-8,不能走 decodeURIComponent)。 */
|
|
56
|
+
function percentDecode(body) {
|
|
57
|
+
const bytes = [];
|
|
58
|
+
const encoder = new TextEncoder();
|
|
59
|
+
for (let i = 0; i < body.length;) {
|
|
60
|
+
const hex = body[i] === "%" ? body.slice(i + 1, i + 3) : "";
|
|
61
|
+
if (/^[0-9a-f]{2}$/i.test(hex)) {
|
|
62
|
+
bytes.push(Number.parseInt(hex, 16));
|
|
63
|
+
i += 3;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const char = String.fromCodePoint(body.codePointAt(i));
|
|
67
|
+
bytes.push(...encoder.encode(char));
|
|
68
|
+
i += char.length;
|
|
69
|
+
}
|
|
70
|
+
return Uint8Array.from(bytes);
|
|
71
|
+
}
|
|
72
|
+
function localPath(ref, cwd) {
|
|
73
|
+
if (ref.startsWith("file://")) return fileURLToPath(ref);
|
|
74
|
+
if (ref === "~" || ref.startsWith("~/")) return resolve(homedir(), ref.slice(2));
|
|
75
|
+
return resolve(cwd, ref);
|
|
76
|
+
}
|
|
77
|
+
function createMcpAssetSource(options = {}) {
|
|
78
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
79
|
+
const cwd = options.cwd ?? process.cwd();
|
|
80
|
+
return { async load(ref) {
|
|
81
|
+
const value = ref.trim();
|
|
82
|
+
if (!value) throw new ProviderError("invalid_input", "素材路径为空");
|
|
83
|
+
if (value.startsWith("data:")) return decodeDataUrl(value);
|
|
84
|
+
if (/^https?:\/\//i.test(value)) {
|
|
85
|
+
const response = await fetchImpl(value);
|
|
86
|
+
if (!response.ok) throw new ProviderError("unavailable", `素材下载失败:HTTP ${response.status}(${value})`);
|
|
87
|
+
const header = response.headers.get("content-type")?.split(";")[0]?.trim();
|
|
88
|
+
const mime = header && header !== "application/octet-stream" ? header : mimeFromName(value) ?? "application/octet-stream";
|
|
89
|
+
return {
|
|
90
|
+
data: new Uint8Array(await response.arrayBuffer()),
|
|
91
|
+
mime,
|
|
92
|
+
url: value
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const path = localPath(value, cwd);
|
|
96
|
+
let data;
|
|
97
|
+
try {
|
|
98
|
+
data = new Uint8Array(await readFile(path));
|
|
99
|
+
} catch (error) {
|
|
100
|
+
const code = error.code;
|
|
101
|
+
throw new ProviderError("invalid_input", code === "ENOENT" ? `找不到素材文件:${path}` : `读取素材文件失败:${path}`);
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
data,
|
|
105
|
+
mime: mimeFromName(path) ?? "application/octet-stream"
|
|
106
|
+
};
|
|
107
|
+
} };
|
|
108
|
+
}
|
|
109
|
+
export { createMcpAssetSource, extensionFor, mimeFromName };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { mcpPlatforms, startServer } from "../launch.mjs";
|
|
3
|
+
// src/bin/modelbay-mcp.ts
|
|
4
|
+
/** `modelbay-mcp <platform>`:启动某个平台的 MCP stdio 服务。 */
|
|
5
|
+
const key = process.argv[2];
|
|
6
|
+
if (!key) {
|
|
7
|
+
const keys = mcpPlatforms().map((platform) => platform.key);
|
|
8
|
+
process.stderr.write(`用法:modelbay-mcp <platform>\n可选平台:${keys.join("、")}\n`);
|
|
9
|
+
process.exitCode = 2;
|
|
10
|
+
} else await startServer(key);
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { JsonSchema, ToolAnnotations, ToolNature } from "./types.mjs";
|
|
2
|
+
import { ModelDeclaration, ToolSpec } from "modelbay";
|
|
3
|
+
export declare function deriveAnnotations(nature: ToolNature): ToolAnnotations;
|
|
4
|
+
export interface ModelParameterPart {
|
|
5
|
+
/** 派生后的 model 字段(替换基线里硬编码的默认值)。 */
|
|
6
|
+
modelField: Record<string, unknown>;
|
|
7
|
+
/** 声明 optionsSchema 带来的上下限 / 默认值等属性,只增不覆盖地并入。 */
|
|
8
|
+
optionProperties: Record<string, Record<string, unknown>>;
|
|
9
|
+
/** 随模型变化的参数范围:属性名 → 该属性的约束。 */
|
|
10
|
+
paramProperties: Record<string, Record<string, unknown>>;
|
|
11
|
+
/** 供文档/测试核对的派生明细。 */
|
|
12
|
+
ids: string[];
|
|
13
|
+
notices: string[];
|
|
14
|
+
defaultModel: string | null;
|
|
15
|
+
/** 每个模型一行的上限摘要。 */
|
|
16
|
+
details: string[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 用 core 的 schema 函数从声明派生模型参数部分:
|
|
20
|
+
* - capabilityInputSchema() 给出 model / capability / input 的规范形状(含「渠道:渠道内ID」说明);
|
|
21
|
+
* - declarationJsonSchema() 把每个声明的 optionsSchema(上下限、默认值)合并进来;
|
|
22
|
+
* - selectDefaultModel() 选默认模型(只允许 active),lifecycleNotice() 给生命周期提示;
|
|
23
|
+
* - deriveModelParam() 把 ModelLimits / MediaRequirements 里的上限翻译成参数约束。
|
|
24
|
+
*/
|
|
25
|
+
export declare function deriveModelParameterPart(models: readonly ModelDeclaration[], capability: string, channel?: string,
|
|
26
|
+
/** native 操作的专用模型(声明里用 native 字段标记),优先于能力默认。 */
|
|
27
|
+
nativeOp?: string): ModelParameterPart;
|
|
28
|
+
/** 合并 catalog 的平台特有字段 + 派生的模型参数部分,生成最终 inputSchema。 */
|
|
29
|
+
export declare function deriveInputSchema(entry: ToolSpec, models: readonly ModelDeclaration[], capability: string, channel?: string, nativeOp?: string): JsonSchema;
|
package/dist/derive.mjs
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { capabilityInputSchema, declarationJsonSchema, deriveModelParam, lifecycleNotice, modelLimitsText, selectDefaultModel, selectNativeModel } from "modelbay";
|
|
2
|
+
// src/derive.ts
|
|
3
|
+
/**
|
|
4
|
+
* inputSchema 的「模型参数部分」全部从这里派生:
|
|
5
|
+
* - model 字段的可选 ID、说明、默认值、生命周期提示
|
|
6
|
+
* ← ModelDeclaration + capabilityInputSchema() / selectDefaultModel() / lifecycleNotice()
|
|
7
|
+
* - 默认值只在平台的主渠道里选(方舟 MCP 用按量渠道,不能落到套餐渠道)
|
|
8
|
+
* - 随模型变化的参数范围(时长、分辨率、画幅、张数、种子、语速、字数上限等)
|
|
9
|
+
* ← ModelDeclaration.limits(ModelLimits / MediaRequirements)
|
|
10
|
+
* - 工具说明里的模型清单与各模型的上限
|
|
11
|
+
*
|
|
12
|
+
* 平台特有字段(web_search、out_dir、previous_response_id 等)来自各平台包的 `src/mcp/tools.ts`,
|
|
13
|
+
* 那里是手写的源码,不含任何模型 ID、上下限数值或生命周期字符串。
|
|
14
|
+
* 本文件也不出现这些字面量(AGENTS.md 硬规则)。
|
|
15
|
+
*/
|
|
16
|
+
/** annotations 由能力性质派生,四个 hint 一律齐全(修正基线里缺 destructiveHint 的条目)。 */
|
|
17
|
+
const ANNOTATIONS_BY_NATURE = {
|
|
18
|
+
generate: {
|
|
19
|
+
readOnlyHint: false,
|
|
20
|
+
destructiveHint: false,
|
|
21
|
+
idempotentHint: false,
|
|
22
|
+
openWorldHint: true
|
|
23
|
+
},
|
|
24
|
+
query: {
|
|
25
|
+
readOnlyHint: true,
|
|
26
|
+
destructiveHint: false,
|
|
27
|
+
idempotentHint: true,
|
|
28
|
+
openWorldHint: true
|
|
29
|
+
},
|
|
30
|
+
mutate: {
|
|
31
|
+
readOnlyHint: false,
|
|
32
|
+
destructiveHint: true,
|
|
33
|
+
idempotentHint: false,
|
|
34
|
+
openWorldHint: true
|
|
35
|
+
},
|
|
36
|
+
local: {
|
|
37
|
+
readOnlyHint: true,
|
|
38
|
+
destructiveHint: false,
|
|
39
|
+
idempotentHint: true,
|
|
40
|
+
openWorldHint: false
|
|
41
|
+
},
|
|
42
|
+
realtime: {
|
|
43
|
+
readOnlyHint: false,
|
|
44
|
+
destructiveHint: false,
|
|
45
|
+
idempotentHint: false,
|
|
46
|
+
openWorldHint: true
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
function deriveAnnotations(nature) {
|
|
50
|
+
return { ...ANNOTATIONS_BY_NATURE[nature] };
|
|
51
|
+
}
|
|
52
|
+
/** 从声明收集可选模型 ID:渠道内 ID、规范 ID、官方别名、简称。 */
|
|
53
|
+
function collectModelIds(model) {
|
|
54
|
+
const ids = [];
|
|
55
|
+
const push = (value) => {
|
|
56
|
+
if (value && !ids.includes(value)) ids.push(value);
|
|
57
|
+
};
|
|
58
|
+
push(model.canonicalId);
|
|
59
|
+
for (const channel of model.channels) push(channel.id);
|
|
60
|
+
for (const alias of model.aliases.official ?? []) push(alias);
|
|
61
|
+
for (const alias of model.aliases.short ?? []) push(alias);
|
|
62
|
+
return ids;
|
|
63
|
+
}
|
|
64
|
+
/** 声明里参与这项能力的模型(按声明顺序)。 */
|
|
65
|
+
function modelsForCapability(models, capability) {
|
|
66
|
+
return models.filter((model) => model.capabilities.includes(capability));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* 用 core 的 schema 函数从声明派生模型参数部分:
|
|
70
|
+
* - capabilityInputSchema() 给出 model / capability / input 的规范形状(含「渠道:渠道内ID」说明);
|
|
71
|
+
* - declarationJsonSchema() 把每个声明的 optionsSchema(上下限、默认值)合并进来;
|
|
72
|
+
* - selectDefaultModel() 选默认模型(只允许 active),lifecycleNotice() 给生命周期提示;
|
|
73
|
+
* - deriveModelParam() 把 ModelLimits / MediaRequirements 里的上限翻译成参数约束。
|
|
74
|
+
*/
|
|
75
|
+
function deriveModelParameterPart(models, capability, channel, nativeOp) {
|
|
76
|
+
const cap = capability;
|
|
77
|
+
const baseModel = (capabilityInputSchema(cap).properties ?? {}).model ?? { type: "string" };
|
|
78
|
+
const ids = [];
|
|
79
|
+
const notices = [];
|
|
80
|
+
const details = [];
|
|
81
|
+
const optionProperties = {};
|
|
82
|
+
const scoped = modelsForCapability(models, capability);
|
|
83
|
+
for (const model of scoped) {
|
|
84
|
+
for (const id of collectModelIds(model)) if (!ids.includes(id)) ids.push(id);
|
|
85
|
+
const notice = lifecycleNotice(model);
|
|
86
|
+
if (notice) notices.push(`${model.canonicalId}:${notice}`);
|
|
87
|
+
const limits = modelLimitsText(model);
|
|
88
|
+
if (limits) details.push(`${model.canonicalId}:${limits}`);
|
|
89
|
+
const declarationProperties = declarationJsonSchema(model).properties ?? {};
|
|
90
|
+
for (const [key, value] of Object.entries(declarationProperties)) {
|
|
91
|
+
if ([
|
|
92
|
+
"model",
|
|
93
|
+
"capability",
|
|
94
|
+
"input",
|
|
95
|
+
"extra"
|
|
96
|
+
].includes(key)) continue;
|
|
97
|
+
if (!(key in optionProperties)) optionProperties[key] = value;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const selected = nativeOp ? selectNativeModel(models, nativeOp, channel) ?? selectDefaultModel(models, cap, channel) : selectDefaultModel(models, cap, channel);
|
|
101
|
+
const defaultModel = selected ? `${selected.channel.channel}:${selected.channel.id}` : null;
|
|
102
|
+
const description = [
|
|
103
|
+
baseModel.description,
|
|
104
|
+
ids.length > 0 ? `可选模型 ID:${ids.join("、")}` : void 0,
|
|
105
|
+
...notices
|
|
106
|
+
].filter((part) => Boolean(part)).join("\n");
|
|
107
|
+
return {
|
|
108
|
+
modelField: {
|
|
109
|
+
...baseModel,
|
|
110
|
+
...description ? { description } : {},
|
|
111
|
+
...defaultModel ? { default: defaultModel } : {}
|
|
112
|
+
},
|
|
113
|
+
optionProperties,
|
|
114
|
+
paramProperties: {},
|
|
115
|
+
ids,
|
|
116
|
+
notices,
|
|
117
|
+
defaultModel,
|
|
118
|
+
details
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* 把声明里的上限翻译成工具参数的约束。
|
|
123
|
+
*
|
|
124
|
+
* 数值型(时长、张数、种子、语速、字数上限)在 schema 里给出并集范围,
|
|
125
|
+
* 这样任何模型能接受的值都不会被挡掉;分辨率、画幅、素材要求这类各模型不同的取值
|
|
126
|
+
* 放在工具说明里逐模型列出。
|
|
127
|
+
*/
|
|
128
|
+
function deriveParamProperties(models, capability, modelParams, channel) {
|
|
129
|
+
if (!modelParams) return {};
|
|
130
|
+
const scoped = modelsForCapability(models, capability);
|
|
131
|
+
const selected = selectDefaultModel(models, capability, channel);
|
|
132
|
+
const out = {};
|
|
133
|
+
for (const [property, kind] of Object.entries(modelParams)) {
|
|
134
|
+
const derived = deriveModelParam(scoped, kind, selected?.declaration.canonicalId);
|
|
135
|
+
if (Object.keys(derived.schema).length > 0) out[property] = derived.schema;
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* 生成工具说明里的模型清单:每个模型一行,写它的上限和生命周期提示。
|
|
141
|
+
* 内容全部来自声明,改声明这段文字就跟着变。
|
|
142
|
+
*/
|
|
143
|
+
function deriveModelDetails(models, capability) {
|
|
144
|
+
const scoped = modelsForCapability(models, capability);
|
|
145
|
+
if (!scoped.length) return "";
|
|
146
|
+
return scoped.map((model) => {
|
|
147
|
+
const limits = modelLimitsText(model);
|
|
148
|
+
const notice = lifecycleNotice(model);
|
|
149
|
+
const parts = [
|
|
150
|
+
model.title,
|
|
151
|
+
limits,
|
|
152
|
+
notice
|
|
153
|
+
].filter(Boolean);
|
|
154
|
+
return `- ${model.canonicalId}:${parts.join(";")}`;
|
|
155
|
+
}).join("\n");
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* 工具说明里「model 必须显式传」的提示。
|
|
159
|
+
*
|
|
160
|
+
* 只有当工具的 model 字段既没有目录给的默认值、又没有声明派生的默认模型时才提示;
|
|
161
|
+
* 目录显式写 `default: null` 的工具(如百炼 TTS 按音色反推模型)不需要提示。
|
|
162
|
+
*/
|
|
163
|
+
function deriveDefaultNote(entry, models, capability, channel, nativeOp) {
|
|
164
|
+
const model = (entry.inputSchema.properties ?? {}).model;
|
|
165
|
+
if (!model || "default" in model) return "";
|
|
166
|
+
const part = deriveModelParameterPart(models, capability, channel, nativeOp);
|
|
167
|
+
if (part.defaultModel) return "";
|
|
168
|
+
const notices = part.notices.join(";");
|
|
169
|
+
return notices ? `model 必须显式指定:${notices}` : "model 必须显式指定:声明里没有该能力的默认模型。";
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* 工具的完整说明 = 目录里手写的平台说明 + 运行时派生的模型清单。
|
|
173
|
+
* 模型清单里每个模型一行,带它的上限与生命周期提示。
|
|
174
|
+
*/
|
|
175
|
+
function deriveToolDescription(base, models, capability) {
|
|
176
|
+
const details = deriveModelDetails(models, capability);
|
|
177
|
+
if (!details) return base;
|
|
178
|
+
return `${base}\n可用模型(由声明派生):\n${details}\n`;
|
|
179
|
+
}
|
|
180
|
+
/** 合并 catalog 的平台特有字段 + 派生的模型参数部分,生成最终 inputSchema。 */
|
|
181
|
+
function deriveInputSchema(entry, models, capability, channel, nativeOp) {
|
|
182
|
+
const schema = structuredClone(entry.inputSchema);
|
|
183
|
+
const properties = schema.properties ??= {};
|
|
184
|
+
const part = deriveModelParameterPart(models, capability, channel, nativeOp);
|
|
185
|
+
if ("model" in properties) {
|
|
186
|
+
const baselineModel = properties.model;
|
|
187
|
+
properties.model = {
|
|
188
|
+
...baselineModel,
|
|
189
|
+
...typeof part.modelField.description === "string" ? { description: part.modelField.description } : {},
|
|
190
|
+
..."default" in baselineModel ? {} : part.modelField.default !== void 0 ? { default: part.modelField.default } : {}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
for (const [key, value] of Object.entries(part.optionProperties)) if (!(key in properties)) properties[key] = structuredClone(value);
|
|
194
|
+
for (const [key, value] of Object.entries(deriveParamProperties(models, capability, entry.modelParams, channel))) {
|
|
195
|
+
if (!(key in properties)) {
|
|
196
|
+
properties[key] = structuredClone(value);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
properties[key] = {
|
|
200
|
+
...properties[key],
|
|
201
|
+
...structuredClone(value)
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
return schema;
|
|
205
|
+
}
|
|
206
|
+
export { deriveAnnotations, deriveDefaultNote, deriveInputSchema, deriveModelDetails, deriveModelParameterPart, deriveParamProperties, deriveToolDescription };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type Framing = 'line' | 'content-length';
|
|
2
|
+
export interface DecodedMessage {
|
|
3
|
+
message: unknown;
|
|
4
|
+
framing: Framing;
|
|
5
|
+
}
|
|
6
|
+
/** 从 Content-Length 头块里取长度;非法返回 null。 */
|
|
7
|
+
export declare function parseContentLength(headerBytes: Uint8Array): number | null;
|
|
8
|
+
export declare class FramedReader {
|
|
9
|
+
buf: Uint8Array;
|
|
10
|
+
push(chunk: Uint8Array | string): DecodedMessage[];
|
|
11
|
+
consume(count: number): void;
|
|
12
|
+
drain(): DecodedMessage[];
|
|
13
|
+
}
|
|
14
|
+
/** 按请求所用的帧格式编码响应(stdio 协议,日志一律走 stderr)。 */
|
|
15
|
+
export declare function encodeMessage(value: unknown, framing: Framing): Uint8Array;
|