@modelbay/mcp 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,129 @@
1
+ // src/framing.ts
2
+ /**
3
+ * 最小 MCP stdio 帧解析:支持换行分隔的 JSON-RPC(MCP 标准)与 Content-Length 头两种形式。
4
+ * 纯模块:不依赖 @modelbay/core,可被 vpx 子进程直接加载。
5
+ * 所有解析按字节进行,避免 UTF-8 多字节序列被 chunk 切断。
6
+ */
7
+ const LF = 10;
8
+ const CR = 13;
9
+ const HEADER_MARK = new TextEncoder().encode("content-length:");
10
+ const HEADER_END = new Uint8Array([
11
+ CR,
12
+ LF,
13
+ CR,
14
+ LF
15
+ ]);
16
+ const encoder = new TextEncoder();
17
+ const decoder = new TextDecoder();
18
+ function indexOfByte(buf, byte, from = 0) {
19
+ for (let i = from; i < buf.length; i += 1) if (buf[i] === byte) return i;
20
+ return -1;
21
+ }
22
+ function indexOfSequence(buf, seq) {
23
+ outer: for (let i = 0; i <= buf.length - seq.length; i += 1) {
24
+ for (let j = 0; j < seq.length; j += 1) if (buf[i + j] !== seq[j]) continue outer;
25
+ return i;
26
+ }
27
+ return -1;
28
+ }
29
+ function startsWithIgnoreCase(buf, lowerPrefix) {
30
+ if (buf.length < lowerPrefix.length) return false;
31
+ for (let i = 0; i < lowerPrefix.length; i += 1) {
32
+ const byte = buf[i] ?? 0;
33
+ if ((byte >= 65 && byte <= 90 ? byte + 32 : byte) !== lowerPrefix[i]) return false;
34
+ }
35
+ return true;
36
+ }
37
+ function decode(bytes) {
38
+ return decoder.decode(bytes);
39
+ }
40
+ /** 从 Content-Length 头块里取长度;非法返回 null。 */
41
+ function parseContentLength(headerBytes) {
42
+ const lines = decode(headerBytes).split("\r\n");
43
+ for (const line of lines) {
44
+ const colon = line.indexOf(":");
45
+ if (colon < 0) continue;
46
+ if (line.slice(0, colon).trim().toLowerCase() !== "content-length") continue;
47
+ const value = Number(line.slice(colon + 1).trim());
48
+ if (Number.isInteger(value) && value >= 0) return value;
49
+ }
50
+ return null;
51
+ }
52
+ function safeParse(text) {
53
+ try {
54
+ return {
55
+ ok: true,
56
+ value: JSON.parse(text)
57
+ };
58
+ } catch {
59
+ return { ok: false };
60
+ }
61
+ }
62
+ var FramedReader = class {
63
+ buf = /* @__PURE__ */ new Uint8Array(0);
64
+ push(chunk) {
65
+ const bytes = typeof chunk === "string" ? encoder.encode(chunk) : chunk;
66
+ if (bytes.length === 0) return [];
67
+ const merged = new Uint8Array(this.buf.length + bytes.length);
68
+ merged.set(this.buf);
69
+ merged.set(bytes, this.buf.length);
70
+ this.buf = merged;
71
+ return this.drain();
72
+ }
73
+ consume(count) {
74
+ this.buf = this.buf.slice(count);
75
+ }
76
+ drain() {
77
+ const out = [];
78
+ while (this.buf.length > 0) {
79
+ if (startsWithIgnoreCase(this.buf, HEADER_MARK)) {
80
+ const headerEnd = indexOfSequence(this.buf, HEADER_END);
81
+ if (headerEnd < 0) break;
82
+ const length = parseContentLength(this.buf.slice(0, headerEnd));
83
+ if (length === null) {
84
+ this.consume(headerEnd + HEADER_END.length);
85
+ continue;
86
+ }
87
+ const bodyStart = headerEnd + HEADER_END.length;
88
+ const bodyEnd = bodyStart + length;
89
+ if (this.buf.length < bodyEnd) break;
90
+ const body = this.buf.slice(bodyStart, bodyEnd);
91
+ this.consume(bodyEnd);
92
+ const parsed = safeParse(decode(body));
93
+ if (parsed.ok) out.push({
94
+ message: parsed.value,
95
+ framing: "content-length"
96
+ });
97
+ continue;
98
+ }
99
+ const nl = indexOfByte(this.buf, LF);
100
+ if (nl < 0) break;
101
+ const line = this.buf.slice(0, nl);
102
+ this.consume(nl + 1);
103
+ const text = decode(line).trim();
104
+ if (!text) continue;
105
+ const parsed = safeParse(text);
106
+ if (parsed.ok) out.push({
107
+ message: parsed.value,
108
+ framing: "line"
109
+ });
110
+ }
111
+ return out;
112
+ }
113
+ };
114
+ /** 按请求所用的帧格式编码响应(stdio 协议,日志一律走 stderr)。 */
115
+ function encodeMessage(value, framing) {
116
+ const body = encoder.encode(JSON.stringify(value));
117
+ if (framing === "line") {
118
+ const out = new Uint8Array(body.length + 1);
119
+ out.set(body);
120
+ out[body.length] = LF;
121
+ return out;
122
+ }
123
+ const header = encoder.encode(`Content-Length: ${body.length}\r\n\r\n`);
124
+ const out = new Uint8Array(header.length + body.length);
125
+ out.set(header);
126
+ out.set(body, header.length);
127
+ return out;
128
+ }
129
+ export { FramedReader, encodeMessage, parseContentLength };
@@ -0,0 +1,16 @@
1
+ import { GeneratedTool, GeneratedToolSet, MCPTool, ToolGroup } from "./types.mjs";
2
+ import { ModelDeclaration, PlatformAdapter, PlatformDescriptor } from "modelbay";
3
+ export interface GenerateOptions {
4
+ /** 平台适配器:提供 models 与 nodeOnly;缺省时用空声明集合(tools/list 仍可用)。 */
5
+ adapter?: PlatformAdapter;
6
+ /** 直接给声明(测试构造伪造声明时用)。优先于 adapter.models。 */
7
+ models?: readonly ModelDeclaration[];
8
+ }
9
+ /** 去掉内部字段,得到 MCP tools/list 的公开工具形状。 */
10
+ export declare function toMCPTool(tool: GeneratedTool): MCPTool;
11
+ /** 按启用的工具组过滤(MCP_TOOL_GROUPS 开关)。 */
12
+ export declare function listTools(set: GeneratedToolSet, groups: readonly ToolGroup[]): MCPTool[];
13
+ /** 生成全量工具(含所有组);实际 tools/list 由 listTools 按组过滤。 */
14
+ export declare function generateTools(target: PlatformDescriptor | string, options?: GenerateOptions): GeneratedToolSet;
15
+ /** 测试/文档用:返回某组启用时的工具名集合。 */
16
+ export declare function toolNames(set: GeneratedToolSet, groups: readonly ToolGroup[]): string[];
@@ -0,0 +1,126 @@
1
+ import { deriveAnnotations, deriveDefaultNote, deriveInputSchema, deriveToolDescription } from "./derive.mjs";
2
+ import { EXTRA_TOOL_NAMES, deriveMeta } from "./tool-meta.mjs";
3
+ import { findPlatform } from "modelbay";
4
+ // src/generate.ts
5
+ /** 去掉内部字段,得到 MCP tools/list 的公开工具形状。 */
6
+ function toMCPTool(tool) {
7
+ const { name, description, inputSchema, outputSchema, annotations } = tool;
8
+ return {
9
+ name,
10
+ description,
11
+ inputSchema,
12
+ ...outputSchema ? { outputSchema } : {},
13
+ annotations
14
+ };
15
+ }
16
+ /** 按启用的工具组过滤(MCP_TOOL_GROUPS 开关)。 */
17
+ function listTools(set, groups) {
18
+ return set.all.filter((tool) => groups.includes(tool.group)).map(toMCPTool);
19
+ }
20
+ /** 生成全量工具(含所有组);实际 tools/list 由 listTools 按组过滤。 */
21
+ function generateTools(target, options = {}) {
22
+ const platform = typeof target === "string" ? findPlatform(target) : target;
23
+ if (!platform?.mcp) throw new Error(`平台「${String(target)}」没有 MCP 工具目录`);
24
+ const models = options.models ?? options.adapter?.models ?? [];
25
+ const nodeOnly = new Set(options.adapter?.nodeOnly ?? []);
26
+ const defaultCapability = models.flatMap((model) => model.capabilities)[0] ?? "text.chat";
27
+ const entries = platform.mcp.tools.map(({ mapArguments, ...rest }) => ({
28
+ ...structuredClone(rest),
29
+ ...mapArguments ? { mapArguments } : {}
30
+ }));
31
+ const all = [];
32
+ for (const entry of entries) all.push(buildTool(entry, platform.primaryChannel, models, defaultCapability, nodeOnly));
33
+ for (const name of EXTRA_TOOL_NAMES) all.push(buildExtraTool(name));
34
+ const routes = /* @__PURE__ */ new Map();
35
+ const byName = /* @__PURE__ */ new Map();
36
+ for (const tool of all) {
37
+ routes.set(tool.name, tool.route);
38
+ byName.set(tool.name, tool);
39
+ }
40
+ return {
41
+ platform: platform.key,
42
+ all,
43
+ routes,
44
+ byName
45
+ };
46
+ }
47
+ function buildTool(entry, channel, models, defaultCapability, nodeOnly) {
48
+ const convention = deriveMeta(entry.name);
49
+ const meta = {
50
+ ...convention,
51
+ nature: entry.nature ?? convention.nature,
52
+ group: entry.group ?? convention.group
53
+ };
54
+ const capability = entry.capability ?? meta.capability ?? defaultCapability;
55
+ const route = buildRoute(meta, entry.native, capability);
56
+ const group = route.kind === "native" && nodeOnly.has(route.op) ? "node" : meta.group;
57
+ const nativeOp = route.kind === "native" ? route.op : void 0;
58
+ const inputSchema = deriveInputSchema(entry, models, capability, channel, nativeOp);
59
+ const annotations = deriveAnnotations(meta.nature);
60
+ const note = deriveDefaultNote(entry, models, capability, channel, nativeOp);
61
+ const description = `${deriveToolDescription(entry.description, models, capability)}${note ? `\n${note}\n` : ""}`;
62
+ return {
63
+ name: entry.name,
64
+ description,
65
+ inputSchema,
66
+ ...entry.outputSchema ? { outputSchema: structuredClone(entry.outputSchema) } : {},
67
+ annotations,
68
+ group,
69
+ route,
70
+ ...entry.mapArguments ? { mapArguments: entry.mapArguments } : {}
71
+ };
72
+ }
73
+ function buildRoute(meta, nativeOp, capability) {
74
+ if (nativeOp) return {
75
+ kind: "native",
76
+ op: nativeOp,
77
+ nature: meta.nature
78
+ };
79
+ if (meta.localHandler) return {
80
+ kind: "local",
81
+ handler: meta.localHandler,
82
+ nature: meta.nature
83
+ };
84
+ return {
85
+ kind: "submit",
86
+ capability,
87
+ nature: meta.nature
88
+ };
89
+ }
90
+ /** 超出基线的新工具:让客户端从声明派生可用模型与生命周期,不硬编码模型清单。 */
91
+ function buildExtraTool(name) {
92
+ return {
93
+ name,
94
+ description: "列出本平台声明的模型 ID、能力与生命周期提示(从 ModelDeclaration 派生),不联网、不计费。",
95
+ inputSchema: {
96
+ type: "object",
97
+ title: "listDeclaredModelsArguments",
98
+ properties: { capability: {
99
+ type: "string",
100
+ description: "按归一化能力筛选(可选)"
101
+ } }
102
+ },
103
+ outputSchema: {
104
+ type: "object",
105
+ properties: { models: {
106
+ type: "array",
107
+ items: {
108
+ type: "object",
109
+ additionalProperties: true
110
+ }
111
+ } }
112
+ },
113
+ annotations: deriveAnnotations("local"),
114
+ group: "core",
115
+ route: {
116
+ kind: "local",
117
+ handler: "models",
118
+ nature: "local"
119
+ }
120
+ };
121
+ }
122
+ /** 测试/文档用:返回某组启用时的工具名集合。 */
123
+ function toolNames(set, groups) {
124
+ return listTools(set, groups).map((tool) => tool.name);
125
+ }
126
+ export { generateTools, listTools, toMCPTool, toolNames };
@@ -0,0 +1,10 @@
1
+ import { CallToolContent, CallToolResult, GROUP_ENV_VAR, GeneratedTool, GeneratedToolSet, JsonRpcError, JsonRpcRequest, JsonRpcResponse, JsonSchema, LocalHandler, MCPTool, MCP_TOOL_GROUPS, ServerHandlers, ServerInfo, TOOL_GROUPS, TOOL_NATURES, ToolAnnotations, ToolGroup, ToolNature, ToolRoute, ToolSpec } from "./types.mjs";
2
+ import { GenerateOptions, generateTools, listTools, toMCPTool, toolNames } from "./generate.mjs";
3
+ import { McpServer, createServer } from "./server.mjs";
4
+ import { RoutingOptions, createHandlers } from "./routing.mjs";
5
+ import { StartOptions, StartedServer, loadAdapter, mcpPlatforms, resolveGroups, resolvePlatform, startServer } from "./launch.mjs";
6
+ import { StdioServerLike, StdioTransportOptions, attachStdioTransport } from "./stdio-transport.mjs";
7
+ import { DecodedMessage, FramedReader, Framing, encodeMessage, parseContentLength } from "./framing.mjs";
8
+ import { ModelParameterPart, deriveAnnotations, deriveInputSchema, deriveModelParameterPart } from "./derive.mjs";
9
+ import { EXTRA_TOOL_NAMES, ToolMeta, deriveMeta, isOptionalGroup } from "./tool-meta.mjs";
10
+ export { type CallToolContent, type CallToolResult, type DecodedMessage, EXTRA_TOOL_NAMES, FramedReader, type Framing, GROUP_ENV_VAR, type GenerateOptions, type GeneratedTool, type GeneratedToolSet, type JsonRpcError, type JsonRpcRequest, type JsonRpcResponse, type JsonSchema, type LocalHandler, type MCPTool, MCP_TOOL_GROUPS, type McpServer, type ModelParameterPart, type RoutingOptions, type ServerHandlers, type ServerInfo, type StartOptions, type StartedServer, type StdioServerLike, type StdioTransportOptions, TOOL_GROUPS, TOOL_NATURES, type ToolAnnotations, type ToolGroup, type ToolMeta, type ToolNature, type ToolRoute, type ToolSpec, attachStdioTransport, createHandlers, createServer, deriveAnnotations, deriveInputSchema, deriveMeta, deriveModelParameterPart, encodeMessage, generateTools, isOptionalGroup, listTools, loadAdapter, mcpPlatforms, parseContentLength, resolveGroups, resolvePlatform, startServer, toMCPTool, toolNames };
package/dist/index.mjs ADDED
@@ -0,0 +1,10 @@
1
+ import { deriveAnnotations, deriveInputSchema, deriveModelParameterPart } from "./derive.mjs";
2
+ import { EXTRA_TOOL_NAMES, deriveMeta, isOptionalGroup } from "./tool-meta.mjs";
3
+ import { generateTools, listTools, toMCPTool, toolNames } from "./generate.mjs";
4
+ import { createServer } from "./server.mjs";
5
+ import { createHandlers } from "./routing.mjs";
6
+ import { FramedReader, encodeMessage, parseContentLength } from "./framing.mjs";
7
+ import { attachStdioTransport } from "./stdio-transport.mjs";
8
+ import { GROUP_ENV_VAR, MCP_TOOL_GROUPS, TOOL_GROUPS, TOOL_NATURES } from "./types.mjs";
9
+ import { loadAdapter, mcpPlatforms, resolveGroups, resolvePlatform, startServer } from "./launch.mjs";
10
+ export { EXTRA_TOOL_NAMES, FramedReader, GROUP_ENV_VAR, MCP_TOOL_GROUPS, TOOL_GROUPS, TOOL_NATURES, attachStdioTransport, createHandlers, createServer, deriveAnnotations, deriveInputSchema, deriveMeta, deriveModelParameterPart, encodeMessage, generateTools, isOptionalGroup, listTools, loadAdapter, mcpPlatforms, parseContentLength, resolveGroups, resolvePlatform, startServer, toMCPTool, toolNames };
package/dist/jobs.mjs ADDED
@@ -0,0 +1,118 @@
1
+ import { extensionFor, mimeFromName } from "./assets.mjs";
2
+ import { ProviderError } from "modelbay";
3
+ import { mkdir, stat, writeFile } from "node:fs/promises";
4
+ import { basename, join, resolve } from "node:path";
5
+ var JobRegistry = class {
6
+ jobs = /* @__PURE__ */ new Map();
7
+ remember(id, tool, outDir) {
8
+ const record = {
9
+ id,
10
+ tool,
11
+ ...outDir ? { outDir } : {},
12
+ state: "running",
13
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
14
+ };
15
+ this.jobs.set(id, record);
16
+ return record;
17
+ }
18
+ get(id) {
19
+ return this.jobs.get(id);
20
+ }
21
+ list(limit) {
22
+ return [...this.jobs.values()].reverse().slice(0, limit).map(({ delivered: _delivered, ...rest }) => rest);
23
+ }
24
+ };
25
+ /** 取 `out_dir` / `output_directory`(两种写法都认)。 */
26
+ function outputDirectory(args) {
27
+ const value = args.out_dir ?? args.output_directory;
28
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
29
+ }
30
+ /** 取 `wait` 秒数,限制在 0–90。 */
31
+ function waitSeconds(args) {
32
+ const value = Number(args.wait ?? 0);
33
+ if (!Number.isFinite(value) || value <= 0) return 0;
34
+ return Math.min(value, 90);
35
+ }
36
+ function sleep(ms, signal) {
37
+ return new Promise((done, fail) => {
38
+ const onAbort = () => {
39
+ clearTimeout(timer);
40
+ fail(new ProviderError("cancelled", "已取消"));
41
+ };
42
+ const timer = setTimeout(() => {
43
+ signal.removeEventListener("abort", onAbort);
44
+ done();
45
+ }, ms);
46
+ signal.addEventListener("abort", onAbort, { once: true });
47
+ });
48
+ }
49
+ /** 轮询到结束或 `wait` 秒用完;`wait` 为 0 时只查一次。 */
50
+ async function pollUntil(adapter, id, context, wait) {
51
+ if (!adapter.poll) throw new ProviderError("invalid_input", "该平台适配器不支持查询任务进度");
52
+ const deadline = Date.now() + wait * 1e3;
53
+ for (;;) {
54
+ const result = await adapter.poll(id, context);
55
+ if (result.state !== "pending") return result;
56
+ const remaining = deadline - Date.now();
57
+ if (remaining <= 0) return result;
58
+ await sleep(Math.min(result.pollAfterMs ?? 5e3, remaining), context.signal);
59
+ }
60
+ }
61
+ /** 提交后若是异步任务且给了 `wait`,接着轮询。 */
62
+ async function settle(adapter, submitted, context, wait) {
63
+ if (submitted.state !== "pending" || wait <= 0) return submitted;
64
+ const result = await pollUntil(adapter, submitted.remoteId, context, wait);
65
+ return result.state === "pending" ? submitted : result;
66
+ }
67
+ let sequence = 0;
68
+ /**
69
+ * 落盘文件名总带时间戳、进程内序号和输出序号:适配器给的名字(如 `bailian.png`)只当前缀,
70
+ * 同一次多张输出、多次调用都不会互相覆盖。
71
+ */
72
+ function fileName(tool, index, output) {
73
+ const named = output.name ? /^(.+?)(\.[a-z0-9]+)$/i.exec(basename(output.name)) : null;
74
+ const prefix = (named?.[1] ?? tool).replace(/[^\w.-]+/g, "_");
75
+ const ext = named?.[2] || extensionFor(output.mime) || (output.url ? extensionFor(mimeFromName(output.url) ?? "") : "") || ".bin";
76
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\..*$/, "");
77
+ sequence += 1;
78
+ return `${prefix}-${stamp}-${sequence}-${index}${ext}`;
79
+ }
80
+ /**
81
+ * 把文件结果写到 `outDir`:字节直接写,URL 先下载。写好的条目带 `path`,不再带字节。
82
+ * 没给 `outDir` 时原样返回(字节由路由层转成 MCP 内容块,URL 原样给出)。
83
+ */
84
+ async function deliver(outputs, outDir, tool, context) {
85
+ if (!outDir) return [...outputs];
86
+ const dir = resolve(outDir);
87
+ await mkdir(dir, { recursive: true });
88
+ return Promise.all(outputs.map(async (output, index) => {
89
+ if (output.type !== "file") return output;
90
+ let data = output.data;
91
+ if (!data && output.url) {
92
+ const response = await context.fetch(output.url, { signal: context.signal });
93
+ if (!response.ok) throw new ProviderError("unavailable", `结果下载失败:HTTP ${response.status}`);
94
+ data = new Uint8Array(await response.arrayBuffer());
95
+ }
96
+ if (!data) return output;
97
+ const path = join(dir, fileName(tool, index, output));
98
+ await writeFile(path, data);
99
+ const { data: _bytes, ...rest } = output;
100
+ return {
101
+ ...rest,
102
+ path,
103
+ bytes: data.byteLength
104
+ };
105
+ }));
106
+ }
107
+ /** 缓存结果里每个落盘文件都还在、大小与写入时一致。 */
108
+ async function deliveredIntact(payload) {
109
+ const outputs = Array.isArray(payload.outputs) ? payload.outputs : [];
110
+ for (const output of outputs) {
111
+ const { path, bytes } = output ?? {};
112
+ if (typeof path !== "string") continue;
113
+ const info = await stat(path).catch(() => void 0);
114
+ if (!info?.isFile() || info.size !== bytes) return false;
115
+ }
116
+ return true;
117
+ }
118
+ export { JobRegistry, deliver, deliveredIntact, outputDirectory, pollUntil, settle, waitSeconds };
@@ -0,0 +1,25 @@
1
+ import { GeneratedToolSet, ToolGroup } from "./types.mjs";
2
+ import { PlatformAdapter, PlatformDescriptor } from "modelbay";
3
+ import { Readable, Writable } from "node:stream";
4
+ /** 有 MCP 工具目录的平台。 */
5
+ export declare function mcpPlatforms(): PlatformDescriptor[];
6
+ /** 按平台键查有 MCP 工具目录的平台;找不到时抛出带可选清单的错误。 */
7
+ export declare function resolvePlatform(key: string): PlatformDescriptor;
8
+ /**
9
+ * 创建平台的适配器(注入 Node 专属能力),取服务主渠道的那一个。
10
+ * 失败时返回 undefined:tools/list 照常可用,tools/call 返回「适配器未就绪」。
11
+ */
12
+ export declare function loadAdapter(platform: PlatformDescriptor): Promise<PlatformAdapter | undefined>;
13
+ export declare function resolveGroups(env: Record<string, string | undefined>): ToolGroup[];
14
+ export interface StartOptions {
15
+ env?: Record<string, string | undefined>;
16
+ input?: Readable;
17
+ output?: Writable;
18
+ onError?: (error: unknown) => void;
19
+ }
20
+ export interface StartedServer {
21
+ detach: () => void;
22
+ set: GeneratedToolSet;
23
+ groups: ToolGroup[];
24
+ }
25
+ export declare function startServer(key: string, options?: StartOptions): Promise<StartedServer>;
@@ -0,0 +1,83 @@
1
+ import { generateTools, listTools } from "./generate.mjs";
2
+ import { createServer } from "./server.mjs";
3
+ import { createMcpAssetSource } from "./assets.mjs";
4
+ import { createHandlers } from "./routing.mjs";
5
+ import { attachStdioTransport } from "./stdio-transport.mjs";
6
+ import { GROUP_ENV_VAR, MCP_TOOL_GROUPS, TOOL_GROUPS } from "./types.mjs";
7
+ import { PLATFORMS, createAdapterContext, findPlatform, readSecrets } from "modelbay";
8
+ import { readFileSync } from "node:fs";
9
+ import { createNodeAdapters } from "modelbay/node";
10
+ // src/launch.ts
11
+ /**
12
+ * 启动逻辑:从注册表找到平台、读取密钥、创建注入了 Node 扩展的适配器、生成工具、启动 stdio server。
13
+ */
14
+ /** 版本号以 package.json 为准(源码和 dist 都在包目录下一层),发版时不用改代码。 */
15
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
16
+ /** 有 MCP 工具目录的平台。 */
17
+ function mcpPlatforms() {
18
+ return PLATFORMS.filter((platform) => platform.mcp);
19
+ }
20
+ /** 按平台键查有 MCP 工具目录的平台;找不到时抛出带可选清单的错误。 */
21
+ function resolvePlatform(key) {
22
+ const platform = findPlatform(key);
23
+ if (platform?.mcp) return platform;
24
+ const keys = mcpPlatforms().map((item) => item.key);
25
+ throw new Error(`未知的 MCP 平台「${key}」,可选:${keys.join("、")}`);
26
+ }
27
+ /**
28
+ * 创建平台的适配器(注入 Node 专属能力),取服务主渠道的那一个。
29
+ * 失败时返回 undefined:tools/list 照常可用,tools/call 返回「适配器未就绪」。
30
+ */
31
+ async function loadAdapter(platform) {
32
+ try {
33
+ const adapters = await createNodeAdapters(platform);
34
+ return adapters.find((adapter) => adapter.channels.includes(platform.primaryChannel)) ?? adapters[0];
35
+ } catch (error) {
36
+ process.stderr.write(`[modelbay-mcp ${platform.key}] 平台适配器暂不可用:${error instanceof Error ? error.message : String(error)}\n`);
37
+ return;
38
+ }
39
+ }
40
+ function resolveGroups(env) {
41
+ const raw = env[GROUP_ENV_VAR];
42
+ if (!raw) return [...MCP_TOOL_GROUPS.default];
43
+ const groups = raw.split(",").map((value) => value.trim()).filter((value) => TOOL_GROUPS.includes(value));
44
+ return groups.length > 0 ? groups : [...MCP_TOOL_GROUPS.default];
45
+ }
46
+ async function startServer(key, options = {}) {
47
+ const platform = resolvePlatform(key);
48
+ const name = `modelbay-mcp ${platform.key}`;
49
+ const env = options.env ?? process.env;
50
+ const input = options.input ?? process.stdin;
51
+ const output = options.output ?? process.stdout;
52
+ const adapter = await loadAdapter(platform);
53
+ const secrets = readSecrets(platform.secrets, env);
54
+ const context = createAdapterContext({
55
+ secrets,
56
+ assets: createMcpAssetSource(),
57
+ log: (message, data) => {
58
+ process.stderr.write(`[${name}] ${message} ${JSON.stringify(data ?? {})}\n`);
59
+ }
60
+ });
61
+ const groups = resolveGroups(env);
62
+ const set = generateTools(platform, adapter ? { adapter } : {});
63
+ const handlers = createHandlers({
64
+ set,
65
+ adapter,
66
+ context,
67
+ groups,
68
+ secrets: platform.secrets,
69
+ primaryChannel: platform.primaryChannel,
70
+ serverInfo: {
71
+ name: `modelbay-mcp-${platform.key}`,
72
+ version: VERSION
73
+ }
74
+ });
75
+ const server = createServer(handlers);
76
+ process.stderr.write(`[${name}] ready: ${listTools(set, groups).length}/${set.all.length} tools, groups=${groups.join(",")}, adapter=${adapter?.id ?? "none"}\n`);
77
+ return {
78
+ detach: attachStdioTransport(server, input, output, { onError: options.onError ?? ((error) => process.stderr.write(`[${name}] ${String(error)}\n`)) }),
79
+ set,
80
+ groups
81
+ };
82
+ }
83
+ export { VERSION, loadAdapter, mcpPlatforms, resolveGroups, resolvePlatform, startServer };
@@ -0,0 +1,14 @@
1
+ import { GeneratedToolSet, ServerHandlers, ServerInfo, ToolGroup } from "./types.mjs";
2
+ import { AdapterContext, PlatformAdapter, PlatformSecrets } from "modelbay";
3
+ export interface RoutingOptions {
4
+ set: GeneratedToolSet;
5
+ adapter?: PlatformAdapter;
6
+ context: AdapterContext;
7
+ groups: readonly ToolGroup[];
8
+ /** 平台的密钥要求;缺必填密钥时 tools/call 返回清晰错误。 */
9
+ secrets: PlatformSecrets;
10
+ serverInfo: ServerInfo;
11
+ /** 未传 model 时在哪个渠道里选默认模型;缺省取适配器的第一个渠道。 */
12
+ primaryChannel?: string;
13
+ }
14
+ export declare function createHandlers(options: RoutingOptions): ServerHandlers;