@migor/agentia 0.7.0 → 0.7.2
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/CHANGELOG.md +198 -1
- package/README.md +1 -1
- package/dist/AGENTS.md +160 -16
- package/dist/container/container.d.ts +8 -1
- package/dist/container/container.js +8 -1
- package/dist/container/container.js.map +1 -1
- package/dist/core/run.d.ts +5 -1
- package/dist/core/timeout.d.ts +8 -0
- package/dist/core/timeout.js +14 -3
- package/dist/core/timeout.js.map +1 -1
- package/dist/core/tool.d.ts +64 -0
- package/dist/engine/budget.d.ts +17 -4
- package/dist/engine/budget.js +3 -3
- package/dist/engine/budget.js.map +1 -1
- package/dist/engine/loop.d.ts +7 -0
- package/dist/engine/loop.js +102 -6
- package/dist/engine/loop.js.map +1 -1
- package/dist/engine/spec.d.ts +18 -2
- package/dist/engine/spec.js.map +1 -1
- package/dist/engine/tracer.d.ts +11 -0
- package/dist/engine/tracer.js +25 -12
- package/dist/engine/tracer.js.map +1 -1
- package/dist/engine/turn.d.ts +25 -3
- package/dist/engine/turn.js +63 -4
- package/dist/engine/turn.js.map +1 -1
- package/dist/engine/types.d.ts +28 -1
- package/dist/engine/types.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/integrations/anthropic.d.ts +5 -0
- package/dist/integrations/anthropic.js +57 -4
- package/dist/integrations/anthropic.js.map +1 -1
- package/dist/integrations/mcp-http.d.ts +43 -0
- package/dist/integrations/mcp-http.js +250 -0
- package/dist/integrations/mcp-http.js.map +1 -0
- package/dist/integrations/mcp-stdio.d.ts +46 -0
- package/dist/integrations/mcp-stdio.js +230 -0
- package/dist/integrations/mcp-stdio.js.map +1 -0
- package/dist/integrations/mcp.d.ts +46 -73
- package/dist/integrations/mcp.js +24 -421
- package/dist/integrations/mcp.js.map +1 -1
- package/dist/integrations/metrics-otlp.d.ts +42 -0
- package/dist/integrations/metrics-otlp.js +178 -0
- package/dist/integrations/metrics-otlp.js.map +1 -0
- package/dist/integrations/metrics-render.d.ts +2 -0
- package/dist/integrations/metrics-render.js +145 -0
- package/dist/integrations/metrics-render.js.map +1 -0
- package/dist/integrations/metrics-state.d.ts +191 -0
- package/dist/integrations/metrics-state.js +363 -0
- package/dist/integrations/metrics-state.js.map +1 -0
- package/dist/integrations/metrics.d.ts +3 -86
- package/dist/integrations/metrics.js +28 -650
- package/dist/integrations/metrics.js.map +1 -1
- package/dist/integrations/openai.js +25 -3
- package/dist/integrations/openai.js.map +1 -1
- package/dist/integrations/otlp.js +15 -6
- package/dist/integrations/otlp.js.map +1 -1
- package/dist/runtime/run.d.ts +6 -0
- package/dist/runtime/run.js +23 -0
- package/dist/runtime/run.js.map +1 -1
- package/dist/store/fsStore.d.ts +3 -2
- package/dist/store/fsStore.js +20 -6
- package/dist/store/fsStore.js.map +1 -1
- package/dist/store/sqliteStore.js +7 -5
- package/dist/store/sqliteStore.js.map +1 -1
- package/dist/store/store.d.ts +17 -1
- package/dist/store/store.js +3 -2
- package/dist/store/store.js.map +1 -1
- package/dist/toolkit/asset.d.ts +3 -2
- package/dist/toolkit/asset.js +11 -2
- package/dist/toolkit/asset.js.map +1 -1
- package/dist/toolkit/module.d.ts +3 -2
- package/dist/toolkit/module.js +3 -0
- package/dist/toolkit/module.js.map +1 -1
- package/dist/toolkit/skill.js +46 -8
- package/dist/toolkit/skill.js.map +1 -1
- package/dist/toolkit/subagent.js +26 -1
- package/dist/toolkit/subagent.js.map +1 -1
- package/dist/toolkit/tool.d.ts +6 -0
- package/dist/toolkit/tool.js +1 -0
- package/dist/toolkit/tool.js.map +1 -1
- package/dist/transport/async.d.ts +81 -1
- package/dist/transport/async.js +323 -11
- package/dist/transport/async.js.map +1 -1
- package/dist/transport/http.d.ts +5 -0
- package/dist/transport/http.js +74 -2
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/scheduler.js +33 -2
- package/dist/transport/scheduler.js.map +1 -1
- package/package.json +9 -5
|
@@ -6,9 +6,11 @@ import type { AgentTool } from '../core/tool.js';
|
|
|
6
6
|
* `McpClientLike` 的客户端都能接(同 `RedisLike` 的 duck-typing)。本文件只依赖 core,
|
|
7
7
|
* 符合分层约定(`integrations` → `core`)。
|
|
8
8
|
*
|
|
9
|
-
* **连接器**(2026-09-18
|
|
9
|
+
* **连接器**(2026-09-18 起**内置**,见文末「连接器」一节与 spec §10 同日条):
|
|
10
10
|
* `createStdioMcpConnector` / `createStreamableHttpMcpConnector`。二者只用标准库
|
|
11
11
|
* (`node:child_process` + 全局 `fetch`),**不新增任何第三方依赖**。
|
|
12
|
+
* 2026-09-20 起两个连接器各居其文件(`mcp-stdio.ts` / `mcp-http.ts`,纯结构拆分、
|
|
13
|
+
* 零行为变化),本文件保留桥 + 共享 helper 并 re-export —— 公共面不变。
|
|
12
14
|
*
|
|
13
15
|
* 用法(接入点是 `AppOptions.tools` 这条**裸工具缝**):
|
|
14
16
|
* ```ts
|
|
@@ -40,7 +42,15 @@ export interface McpToolInfo {
|
|
|
40
42
|
*/
|
|
41
43
|
export interface McpClientLike {
|
|
42
44
|
listTools(): Promise<McpToolInfo[]>;
|
|
43
|
-
|
|
45
|
+
/**
|
|
46
|
+
* `opts.abandoned`:裁判(引擎 `toolTimeoutMs` / 桥兜底超时)**放弃等待**的通知信号。
|
|
47
|
+
* 放弃 ≠ 取消 —— 但连接器应借此清掉这次调用的簿记(stdio 的 pending 条目、
|
|
48
|
+
* HTTP 的在飞 fetch),否则「server 活着但不回包」时每超时一次就泄漏一条。
|
|
49
|
+
* 只实现两个参数的旧客户端依然兼容(可选参数,鸭子类型)。
|
|
50
|
+
*/
|
|
51
|
+
callTool(name: string, args: Record<string, unknown>, opts?: {
|
|
52
|
+
abandoned?: AbortSignal;
|
|
53
|
+
}): Promise<unknown>;
|
|
44
54
|
}
|
|
45
55
|
export interface McpToolsOptions {
|
|
46
56
|
/**
|
|
@@ -106,80 +116,43 @@ export interface McpConnector extends McpClientLike {
|
|
|
106
116
|
*/
|
|
107
117
|
close(): Promise<void>;
|
|
108
118
|
}
|
|
109
|
-
/** `close()` 里 SIGTERM → SIGKILL 的宽限期(毫秒) */
|
|
110
|
-
export declare const MCP_CLOSE_GRACE_MS = 2000;
|
|
111
|
-
export interface StdioMcpConnectorOptions {
|
|
112
|
-
/** 追加 / 覆盖的环境变量(缺省继承 `process.env`) */
|
|
113
|
-
env?: Record<string, string>;
|
|
114
|
-
/** 子进程工作目录 */
|
|
115
|
-
cwd?: string;
|
|
116
|
-
/** 子进程 stderr 去向:`'inherit'`(缺省,server 日志直通终端)| `'ignore'` */
|
|
117
|
-
stderr?: 'inherit' | 'ignore';
|
|
118
|
-
/** 见 {@link DEFAULT_CLIENT_INFO} */
|
|
119
|
-
clientInfo?: {
|
|
120
|
-
name: string;
|
|
121
|
-
version: string;
|
|
122
|
-
};
|
|
123
|
-
/** 请求的协议版本,缺省 `'2024-11-05'` */
|
|
124
|
-
protocolVersion?: string;
|
|
125
|
-
/**
|
|
126
|
-
* 装配期超时(毫秒)—— 只作用于**握手 + `tools/list`**,缺省
|
|
127
|
-
* {@link MCP_DEFAULT_TIMEOUT_MS};非正数 = 不限。语义见 {@link Guard}。
|
|
128
|
-
*
|
|
129
|
-
* 超时同样只是一类账(`code='timeout'`):**不终止子进程**,与仓库其余「等待的终点」
|
|
130
|
-
* 一致(超时 = 放弃等待)。
|
|
131
|
-
*/
|
|
132
|
-
timeoutMs?: number;
|
|
133
|
-
}
|
|
134
119
|
/**
|
|
135
|
-
*
|
|
136
|
-
* (`initialize` → `notifications/initialized` → `tools/list` / `tools/call`)。
|
|
120
|
+
* 缺省 `clientInfo`(`initialize` 握手要发,协议要求该字段存在)。
|
|
137
121
|
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
* 三处非显然的坑,这里都兜住了(此前 `scripts/e2e-mcp.ts` 内联的那 94 行踩过):
|
|
142
|
-
* 1. spawn **失败**(命令不存在 → `ENOENT`)是异步的 `'error'` 事件,不是抛出 ——
|
|
143
|
-
* 没有监听器就是未捕获异常、直接把宿主进程带崩,所以必须接住并拒绝在途请求;
|
|
144
|
-
* 2. 分帧:一条报文可能跨多个 chunk,必须自己攒 buffer 按 `\n` 切;
|
|
145
|
-
* 3. **协议层 `isError: true` 必须转成抛错** —— 否则模型收到一条「成功」的结果,
|
|
146
|
-
* trace 也把它记成成功的调用(`McpClientLike` 的约定,见其注释)。
|
|
122
|
+
* **刻意不写框架自身版本**:`integrations` 层不 import 公共面(`AGENTIA_VERSION` 在
|
|
123
|
+
* `src/index.ts`),且 `scripts/release-surface.mjs` 的发版面按**精确版本串**计数 ——
|
|
124
|
+
* 这里多一处版本字面量会让它的 count 断言失配。需要真实版本请自行传 `clientInfo`。
|
|
147
125
|
*/
|
|
148
|
-
export declare
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
name: string;
|
|
155
|
-
version: string;
|
|
156
|
-
};
|
|
157
|
-
/** 请求的协议版本,缺省 `'2024-11-05'`;协商结果以 server 回的为准 */
|
|
158
|
-
protocolVersion?: string;
|
|
159
|
-
/** 装配期超时(毫秒)—— 只作用于**握手 + `tools/list`**,语义同 {@link StdioMcpConnectorOptions.timeoutMs} */
|
|
160
|
-
timeoutMs?: number;
|
|
161
|
-
/**
|
|
162
|
-
* 会话过期时被调一次(见 `rpc` 的 404 自愈)。**给可观测用**:默认自愈是静默的,
|
|
163
|
-
* 而「静默恢复」和「静默失效」在监控上看不出区别 —— 要计数 / 告警 / 打日志就挂这个钩子。
|
|
164
|
-
*/
|
|
165
|
-
onSessionExpired?: () => void;
|
|
166
|
-
/** 注入 `fetch`(测试用;缺省全局 `fetch`,与 `createOpenAIClient` 同款) */
|
|
167
|
-
fetchImpl?: typeof fetch;
|
|
168
|
-
}
|
|
126
|
+
export declare const DEFAULT_CLIENT_INFO: {
|
|
127
|
+
name: string;
|
|
128
|
+
version: string;
|
|
129
|
+
};
|
|
130
|
+
/** `initialize` 缺省请求的协议版本(e2e 已验证的版本;要对齐新版 server 请显式传) */
|
|
131
|
+
export declare const DEFAULT_PROTOCOL_VERSION = "2024-11-05";
|
|
169
132
|
/**
|
|
170
|
-
*
|
|
171
|
-
* Streamable HTTP 传输)。
|
|
133
|
+
* 装配期超时的落点:**握手 + `tools/list`**。
|
|
172
134
|
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
* (后续响应不带该头时**不覆盖**);`close()` 尽力 `DELETE` 终止会话;
|
|
177
|
-
* **会话过期自愈**:带会话 id 收到 `404` ⇒ 视为「会话已终止、该请求未被 server 执行」
|
|
178
|
-
* ⇒ 丢会话 → 重新握手 → 把这一次**重试一次**(只一次,不再循环)。自愈是静默的,
|
|
179
|
-
* 所以给了 `onSessionExpired` 钩子给你计数 / 告警 —— 否则它和「静默失效」没区别。
|
|
180
|
-
* - 协议版本:请求头 `MCP-Protocol-Version` 带**协商到的**版本(2025-06-18 起要求,
|
|
181
|
-
* 老 server 忽略未知头);
|
|
182
|
-
* - HTTP 层失败**挂数值 `status`** ⇒ `engine/errors.ts::classifyError` 自动分流
|
|
183
|
-
* (429 → `rate_limit` 可重试 / ≥500 → `server` 可重试 / 其余 4xx → `api` 不可重试)。
|
|
135
|
+
* 为什么不给 `callTool` 也套一个:一次调用只有一个裁判(见 `McpToolsOptions.timeoutMs`)。
|
|
136
|
+
* 走 `mcpTools` 时 `callTool` 由引擎 / 桥判定;而握手与 `tools/list` 发生在**装配期**,
|
|
137
|
+
* 没有任何别的裁判 —— server 卡住会让 `createApp` 永久挂起,必须在这里兜住。
|
|
184
138
|
*/
|
|
185
|
-
export
|
|
139
|
+
export type Guard = <T>(p: Promise<T>, label: string) => Promise<T>;
|
|
140
|
+
/** 把可能很大的值截成可读片段(错误消息要能进日志,不能是一兆的 JSON) */
|
|
141
|
+
export declare function brief(value: unknown, max?: number): string;
|
|
142
|
+
/** JSON-RPC 错误对象 → `Error`(`code` 进文案:`classifyError` 只认数值 `status`,这里不冒充它) */
|
|
143
|
+
export declare function jsonRpcError(err: unknown): Error;
|
|
144
|
+
/** server 混进 stdout / SSE 的非 JSON 行 */
|
|
145
|
+
export declare function isJsonRpcResponse(msg: unknown): msg is {
|
|
146
|
+
id: number;
|
|
147
|
+
result?: unknown;
|
|
148
|
+
error?: unknown;
|
|
149
|
+
};
|
|
150
|
+
/** 从一条已解析的报文里取结果;带 `error` 则抛 */
|
|
151
|
+
export declare function unwrap(msg: {
|
|
152
|
+
result?: unknown;
|
|
153
|
+
error?: unknown;
|
|
154
|
+
}, method: string): unknown;
|
|
155
|
+
export { createStdioMcpConnector, MCP_CLOSE_GRACE_MS } from './mcp-stdio.js';
|
|
156
|
+
export type { StdioMcpConnectorOptions } from './mcp-stdio.js';
|
|
157
|
+
export { createStreamableHttpMcpConnector } from './mcp-http.js';
|
|
158
|
+
export type { StreamableHttpMcpConnectorOptions } from './mcp-http.js';
|
package/dist/integrations/mcp.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
2
1
|
import { TIMED_OUT, TimeoutError, withTimeout } from '../core/timeout.js';
|
|
2
|
+
import { combineSignals, releaseCombinedSignal } from '../core/abort.js';
|
|
3
3
|
/** 缺省超时:MCP server 可能去连外部系统,60s 是「明显卡死」与「慢但正常」的分界 */
|
|
4
4
|
export const MCP_DEFAULT_TIMEOUT_MS = 60_000;
|
|
5
5
|
/**
|
|
@@ -113,16 +113,26 @@ export async function mcpTools(client, opts = {}) {
|
|
|
113
113
|
// 与「一次调用只有一个裁判」相反:说了不限就该不限。
|
|
114
114
|
const engineBudget = ctx?.toolTimeoutMs;
|
|
115
115
|
if (engineBudget != null) {
|
|
116
|
-
|
|
116
|
+
// 引擎是裁判:它的 toolTimeoutMs 到点会 fire ctx.abandoned —— 连接器据此
|
|
117
|
+
// 清掉这次调用的簿记(stdio 的 pending 条目),不留下等不到回收的残骸。
|
|
118
|
+
return client.callTool(original, args, ctx?.abandoned !== undefined ? { abandoned: ctx.abandoned } : undefined);
|
|
119
|
+
}
|
|
120
|
+
// 桥兜底裁判(脱离引擎单用 / 引擎没设超时):到点除了放弃等待,还要通知连接器
|
|
121
|
+
// 清理簿记 —— 与引擎路径共用同一个 `abandoned` 缝(`core/abort.ts` 合成)。
|
|
122
|
+
const ac = new AbortController();
|
|
123
|
+
const abandoned = ctx?.abandoned !== undefined ? combineSignals(ctx.abandoned, ac.signal) : ac.signal;
|
|
124
|
+
try {
|
|
125
|
+
return await withDeadline(client.callTool(original, args, { abandoned }), timeoutMs, original);
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
ac.abort(); // 无论成败都摘掉:成功时条目已被响应清掉,超时/出错时靠这次 abort 清
|
|
129
|
+
releaseCombinedSignal(abandoned); // 摘除挂在 ctx.abandoned 上的监听器
|
|
117
130
|
}
|
|
118
|
-
return withDeadline(client.callTool(original, args), timeoutMs, original);
|
|
119
131
|
},
|
|
120
132
|
});
|
|
121
133
|
}
|
|
122
134
|
return tools;
|
|
123
135
|
}
|
|
124
|
-
/** `close()` 里 SIGTERM → SIGKILL 的宽限期(毫秒) */
|
|
125
|
-
export const MCP_CLOSE_GRACE_MS = 2_000;
|
|
126
136
|
/**
|
|
127
137
|
* 缺省 `clientInfo`(`initialize` 握手要发,协议要求该字段存在)。
|
|
128
138
|
*
|
|
@@ -130,14 +140,14 @@ export const MCP_CLOSE_GRACE_MS = 2_000;
|
|
|
130
140
|
* `src/index.ts`),且 `scripts/release-surface.mjs` 的发版面按**精确版本串**计数 ——
|
|
131
141
|
* 这里多一处版本字面量会让它的 count 断言失配。需要真实版本请自行传 `clientInfo`。
|
|
132
142
|
*/
|
|
133
|
-
const DEFAULT_CLIENT_INFO = {
|
|
143
|
+
export const DEFAULT_CLIENT_INFO = {
|
|
134
144
|
name: 'agentia',
|
|
135
145
|
version: '0.0.0',
|
|
136
146
|
};
|
|
137
147
|
/** `initialize` 缺省请求的协议版本(e2e 已验证的版本;要对齐新版 server 请显式传) */
|
|
138
|
-
const DEFAULT_PROTOCOL_VERSION = '2024-11-05';
|
|
148
|
+
export const DEFAULT_PROTOCOL_VERSION = '2024-11-05';
|
|
139
149
|
/** 把可能很大的值截成可读片段(错误消息要能进日志,不能是一兆的 JSON) */
|
|
140
|
-
function brief(value, max = 200) {
|
|
150
|
+
export function brief(value, max = 200) {
|
|
141
151
|
let s;
|
|
142
152
|
try {
|
|
143
153
|
s = typeof value === 'string' ? value : JSON.stringify(value);
|
|
@@ -150,7 +160,7 @@ function brief(value, max = 200) {
|
|
|
150
160
|
return s.length > max ? `${s.slice(0, max)}…` : s;
|
|
151
161
|
}
|
|
152
162
|
/** JSON-RPC 错误对象 → `Error`(`code` 进文案:`classifyError` 只认数值 `status`,这里不冒充它) */
|
|
153
|
-
function jsonRpcError(err) {
|
|
163
|
+
export function jsonRpcError(err) {
|
|
154
164
|
if (typeof err === 'object' && err !== null) {
|
|
155
165
|
const { code, message } = err;
|
|
156
166
|
return new Error(`MCP error ${String(code)}: ${String(message)}`);
|
|
@@ -158,425 +168,18 @@ function jsonRpcError(err) {
|
|
|
158
168
|
return new Error(`MCP error: ${brief(err)}`);
|
|
159
169
|
}
|
|
160
170
|
/** server 混进 stdout / SSE 的非 JSON 行 */
|
|
161
|
-
function isJsonRpcResponse(msg) {
|
|
171
|
+
export function isJsonRpcResponse(msg) {
|
|
162
172
|
return (typeof msg === 'object' && msg !== null && typeof msg.id === 'number');
|
|
163
173
|
}
|
|
164
174
|
/** 从一条已解析的报文里取结果;带 `error` 则抛 */
|
|
165
|
-
function unwrap(msg, method) {
|
|
175
|
+
export function unwrap(msg, method) {
|
|
166
176
|
if (msg.error !== undefined)
|
|
167
177
|
throw jsonRpcError(msg.error);
|
|
168
178
|
if (!('result' in msg))
|
|
169
179
|
throw new Error(`MCP ${method}:响应里既没有 result 也没有 error`);
|
|
170
180
|
return msg.result;
|
|
171
181
|
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
*
|
|
176
|
-
* 进程与握手都是**惰性**的 —— 构造不产生副作用,第一次 `listTools` / `callTool` 才 spawn;
|
|
177
|
-
* 握手只做一次(并发调用共享同一次握手)。
|
|
178
|
-
*
|
|
179
|
-
* 三处非显然的坑,这里都兜住了(此前 `scripts/e2e-mcp.ts` 内联的那 94 行踩过):
|
|
180
|
-
* 1. spawn **失败**(命令不存在 → `ENOENT`)是异步的 `'error'` 事件,不是抛出 ——
|
|
181
|
-
* 没有监听器就是未捕获异常、直接把宿主进程带崩,所以必须接住并拒绝在途请求;
|
|
182
|
-
* 2. 分帧:一条报文可能跨多个 chunk,必须自己攒 buffer 按 `\n` 切;
|
|
183
|
-
* 3. **协议层 `isError: true` 必须转成抛错** —— 否则模型收到一条「成功」的结果,
|
|
184
|
-
* trace 也把它记成成功的调用(`McpClientLike` 的约定,见其注释)。
|
|
185
|
-
*/
|
|
186
|
-
export function createStdioMcpConnector(cmd, opts = {}) {
|
|
187
|
-
const bin = cmd[0];
|
|
188
|
-
if (typeof bin !== 'string' || bin === '') {
|
|
189
|
-
throw new Error('createStdioMcpConnector:cmd 不能为空(需要可执行文件 + 参数)');
|
|
190
|
-
}
|
|
191
|
-
const rest = cmd.slice(1);
|
|
192
|
-
const timeoutMs = opts.timeoutMs ?? MCP_DEFAULT_TIMEOUT_MS;
|
|
193
|
-
const clientInfo = opts.clientInfo ?? DEFAULT_CLIENT_INFO;
|
|
194
|
-
const protocolVersion = opts.protocolVersion ?? DEFAULT_PROTOCOL_VERSION;
|
|
195
|
-
let proc = null;
|
|
196
|
-
let fatal = null;
|
|
197
|
-
let closed = false;
|
|
198
|
-
let exited = false;
|
|
199
|
-
let buf = '';
|
|
200
|
-
let nextId = 1;
|
|
201
|
-
let ready = null;
|
|
202
|
-
let resolveExit = null;
|
|
203
|
-
const exitPromise = new Promise((r) => {
|
|
204
|
-
resolveExit = r;
|
|
205
|
-
});
|
|
206
|
-
const pending = new Map();
|
|
207
|
-
const markExited = () => {
|
|
208
|
-
exited = true;
|
|
209
|
-
resolveExit?.();
|
|
210
|
-
};
|
|
211
|
-
/** 进程已死 / 已 close 时一次性拒绝全部在途请求 —— 不留永久挂起的 promise */
|
|
212
|
-
const fail = (err) => {
|
|
213
|
-
fatal = err;
|
|
214
|
-
for (const p of pending.values())
|
|
215
|
-
p.reject(err);
|
|
216
|
-
pending.clear();
|
|
217
|
-
};
|
|
218
|
-
const guard = (p, label) => withDeadline(p, timeoutMs, label);
|
|
219
|
-
const ensureProc = () => {
|
|
220
|
-
if (closed)
|
|
221
|
-
throw new Error('MCP 连接器已 close —— 请重新创建一个');
|
|
222
|
-
if (fatal)
|
|
223
|
-
throw fatal;
|
|
224
|
-
if (proc)
|
|
225
|
-
return proc;
|
|
226
|
-
const spawnOpts = {
|
|
227
|
-
stdio: ['pipe', 'pipe', opts.stderr ?? 'inherit'],
|
|
228
|
-
// exactOptionalPropertyTypes:可选字段不能赋 undefined,只能条件展开
|
|
229
|
-
...(opts.env ? { env: { ...process.env, ...opts.env } } : {}),
|
|
230
|
-
...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
|
|
231
|
-
};
|
|
232
|
-
const p = spawn(bin, rest, spawnOpts);
|
|
233
|
-
proc = p;
|
|
234
|
-
p.on('error', (err) => {
|
|
235
|
-
// 见函数头第 1 条:这个监听器不是可选的
|
|
236
|
-
fail(err instanceof Error ? err : new Error(String(err)));
|
|
237
|
-
markExited();
|
|
238
|
-
});
|
|
239
|
-
p.on('exit', (code, signal) => {
|
|
240
|
-
if (!closed) {
|
|
241
|
-
fail(new Error(`MCP server 进程已退出(code=${code ?? 'null'} signal=${signal ?? 'null'})`));
|
|
242
|
-
}
|
|
243
|
-
markExited();
|
|
244
|
-
});
|
|
245
|
-
// 'exit' 在 spawn 失败时可能不触发,'close' 一定会 —— close() 靠它才不会白等
|
|
246
|
-
p.on('close', markExited);
|
|
247
|
-
// 进程已死时写 stdin 会异步报 EPIPE;真实原因由上面的 'error' / 'exit' 给出
|
|
248
|
-
p.stdin?.on('error', () => {
|
|
249
|
-
/* 吞掉:EPIPE 是「进程没了」的次生现象,不是根因 */
|
|
250
|
-
});
|
|
251
|
-
p.stdout?.setEncoding('utf8');
|
|
252
|
-
p.stdout?.on('data', (chunk) => {
|
|
253
|
-
buf += chunk;
|
|
254
|
-
for (;;) {
|
|
255
|
-
const nl = buf.indexOf('\n');
|
|
256
|
-
if (nl < 0)
|
|
257
|
-
break;
|
|
258
|
-
const line = buf.slice(0, nl);
|
|
259
|
-
buf = buf.slice(nl + 1);
|
|
260
|
-
if (line.trim() === '')
|
|
261
|
-
continue;
|
|
262
|
-
let msg;
|
|
263
|
-
try {
|
|
264
|
-
msg = JSON.parse(line);
|
|
265
|
-
}
|
|
266
|
-
catch {
|
|
267
|
-
continue; // MCP 规定 stdout 只走协议,但 server 混日志进来是常事
|
|
268
|
-
}
|
|
269
|
-
if (!isJsonRpcResponse(msg))
|
|
270
|
-
continue; // 通知(无 id)不配对
|
|
271
|
-
const waiter = pending.get(msg.id);
|
|
272
|
-
if (!waiter)
|
|
273
|
-
continue;
|
|
274
|
-
pending.delete(msg.id);
|
|
275
|
-
try {
|
|
276
|
-
waiter.resolve(unwrap(msg, 'response'));
|
|
277
|
-
}
|
|
278
|
-
catch (e) {
|
|
279
|
-
waiter.reject(e instanceof Error ? e : new Error(String(e)));
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
});
|
|
283
|
-
return p;
|
|
284
|
-
};
|
|
285
|
-
const write = (payload) => {
|
|
286
|
-
const p = ensureProc();
|
|
287
|
-
p.stdin?.write(`${JSON.stringify(payload)}\n`);
|
|
288
|
-
};
|
|
289
|
-
const send = (method, params) => {
|
|
290
|
-
if (closed)
|
|
291
|
-
return Promise.reject(new Error('MCP 连接器已 close —— 请重新创建一个'));
|
|
292
|
-
if (fatal)
|
|
293
|
-
return Promise.reject(fatal);
|
|
294
|
-
const id = nextId++;
|
|
295
|
-
return new Promise((resolve, reject) => {
|
|
296
|
-
try {
|
|
297
|
-
ensureProc();
|
|
298
|
-
}
|
|
299
|
-
catch (e) {
|
|
300
|
-
reject(e instanceof Error ? e : new Error(String(e)));
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
pending.set(id, { resolve, reject });
|
|
304
|
-
write({ jsonrpc: '2.0', id, method, params });
|
|
305
|
-
});
|
|
306
|
-
};
|
|
307
|
-
/** 握手只做一次;失败是**粘性**的(连接器已不可用 → 重建,而不是半初始化态) */
|
|
308
|
-
const ensureReady = () => {
|
|
309
|
-
if (ready)
|
|
310
|
-
return ready;
|
|
311
|
-
ready = (async () => {
|
|
312
|
-
const init = await guard(send('initialize', { protocolVersion, capabilities: {}, clientInfo }), 'initialize');
|
|
313
|
-
// 协商结果以 server 回的那个为准(协议允许 server 降级或选自己的版本)
|
|
314
|
-
void init;
|
|
315
|
-
write({ jsonrpc: '2.0', method: 'notifications/initialized', params: {} });
|
|
316
|
-
})();
|
|
317
|
-
return ready;
|
|
318
|
-
};
|
|
319
|
-
const request = async (method, params) => {
|
|
320
|
-
await ensureReady();
|
|
321
|
-
return send(method, params);
|
|
322
|
-
};
|
|
323
|
-
const listTools = async () => {
|
|
324
|
-
const r = await guard(request('tools/list', {}), 'tools/list');
|
|
325
|
-
if (typeof r !== 'object' || r === null) {
|
|
326
|
-
throw new Error(`MCP tools/list 返回了非对象:${brief(r)}`);
|
|
327
|
-
}
|
|
328
|
-
const listed = r.tools;
|
|
329
|
-
if (listed === undefined)
|
|
330
|
-
return [];
|
|
331
|
-
if (!Array.isArray(listed)) {
|
|
332
|
-
// 响亮失败:把协议不符吞成空菜单,用户看到的是「一个工具都没有」而不是「server 坏了」
|
|
333
|
-
throw new Error(`MCP tools/list 的 tools 不是数组:${brief(listed)}`);
|
|
334
|
-
}
|
|
335
|
-
return listed;
|
|
336
|
-
};
|
|
337
|
-
const callTool = async (name, args) => {
|
|
338
|
-
const r = await request('tools/call', { name, arguments: args });
|
|
339
|
-
// 承重:协议层 isError 只有连接器看得见(见函数头第 3 条)
|
|
340
|
-
if (typeof r === 'object' && r !== null && r.isError) {
|
|
341
|
-
throw new Error(`MCP 工具 ${name} 返回 isError: ${brief(r.content)}`);
|
|
342
|
-
}
|
|
343
|
-
return r;
|
|
344
|
-
};
|
|
345
|
-
return {
|
|
346
|
-
listTools,
|
|
347
|
-
callTool,
|
|
348
|
-
async close() {
|
|
349
|
-
if (closed)
|
|
350
|
-
return;
|
|
351
|
-
closed = true;
|
|
352
|
-
fail(new Error('MCP 连接器已 close —— 请重新创建一个'));
|
|
353
|
-
const p = proc;
|
|
354
|
-
proc = null;
|
|
355
|
-
if (!p)
|
|
356
|
-
return;
|
|
357
|
-
p.kill('SIGTERM');
|
|
358
|
-
if (exited)
|
|
359
|
-
return;
|
|
360
|
-
const killTimer = setTimeout(() => {
|
|
361
|
-
try {
|
|
362
|
-
p.kill('SIGKILL');
|
|
363
|
-
}
|
|
364
|
-
catch {
|
|
365
|
-
/* 已经死了 */
|
|
366
|
-
}
|
|
367
|
-
// ⚠️ 这里**不** resolve:SIGKILL 不可被捕获,'exit'/'close' 必达 —— 继续等真的退出。
|
|
368
|
-
// 到点即返回是 2026-09-18 之前的行为:调用方以为进程没了,实际还留着一个孤儿。
|
|
369
|
-
}, MCP_CLOSE_GRACE_MS);
|
|
370
|
-
try {
|
|
371
|
-
await exitPromise;
|
|
372
|
-
}
|
|
373
|
-
finally {
|
|
374
|
-
clearTimeout(killTimer);
|
|
375
|
-
}
|
|
376
|
-
},
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* **StreamableHTTP 连接器**:一个 endpoint,POST JSON-RPC(MCP 2025-03-26 起的
|
|
381
|
-
* Streamable HTTP 传输)。
|
|
382
|
-
*
|
|
383
|
-
* - 两种响应形态**都要接**:`application/json`(整条报文)与 `text/event-stream`
|
|
384
|
-
* (报文按 SSE 帧下发,server 应在发完响应后关流);
|
|
385
|
-
* - 会话:`initialize` 响应里的 `Mcp-Session-Id` 会被记住并在后续请求上回带
|
|
386
|
-
* (后续响应不带该头时**不覆盖**);`close()` 尽力 `DELETE` 终止会话;
|
|
387
|
-
* **会话过期自愈**:带会话 id 收到 `404` ⇒ 视为「会话已终止、该请求未被 server 执行」
|
|
388
|
-
* ⇒ 丢会话 → 重新握手 → 把这一次**重试一次**(只一次,不再循环)。自愈是静默的,
|
|
389
|
-
* 所以给了 `onSessionExpired` 钩子给你计数 / 告警 —— 否则它和「静默失效」没区别。
|
|
390
|
-
* - 协议版本:请求头 `MCP-Protocol-Version` 带**协商到的**版本(2025-06-18 起要求,
|
|
391
|
-
* 老 server 忽略未知头);
|
|
392
|
-
* - HTTP 层失败**挂数值 `status`** ⇒ `engine/errors.ts::classifyError` 自动分流
|
|
393
|
-
* (429 → `rate_limit` 可重试 / ≥500 → `server` 可重试 / 其余 4xx → `api` 不可重试)。
|
|
394
|
-
*/
|
|
395
|
-
export function createStreamableHttpMcpConnector(url, opts = {}) {
|
|
396
|
-
if (typeof url !== 'string' || url === '') {
|
|
397
|
-
throw new Error('createStreamableHttpMcpConnector:url 不能为空');
|
|
398
|
-
}
|
|
399
|
-
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
400
|
-
const timeoutMs = opts.timeoutMs ?? MCP_DEFAULT_TIMEOUT_MS;
|
|
401
|
-
const clientInfo = opts.clientInfo ?? DEFAULT_CLIENT_INFO;
|
|
402
|
-
const requestedVersion = opts.protocolVersion ?? DEFAULT_PROTOCOL_VERSION;
|
|
403
|
-
const baseHeaders = {
|
|
404
|
-
'content-type': 'application/json',
|
|
405
|
-
// MCP 规定客户端必须同时接受两种响应形态(否则 server 无法按规范回 SSE)
|
|
406
|
-
accept: 'application/json, text/event-stream',
|
|
407
|
-
...opts.headers,
|
|
408
|
-
};
|
|
409
|
-
let sessionId = null;
|
|
410
|
-
let negotiated = requestedVersion;
|
|
411
|
-
let closed = false;
|
|
412
|
-
let ready = null;
|
|
413
|
-
let nextId = 1;
|
|
414
|
-
const guard = (p, label) => withDeadline(p, timeoutMs, label);
|
|
415
|
-
/** HTTP 层失败:带上数值 `status`,让 `classifyError` 能按状态分流 */
|
|
416
|
-
const httpError = (status, method, body) => {
|
|
417
|
-
const e = new Error(`MCP ${method} HTTP ${status}${body ? `:${body}` : ''}`);
|
|
418
|
-
e.status = status;
|
|
419
|
-
return e;
|
|
420
|
-
};
|
|
421
|
-
const readText = async (res) => {
|
|
422
|
-
try {
|
|
423
|
-
return await res.text();
|
|
424
|
-
}
|
|
425
|
-
catch {
|
|
426
|
-
return '';
|
|
427
|
-
}
|
|
428
|
-
};
|
|
429
|
-
const post = async (payload, o = {}) => {
|
|
430
|
-
if (closed)
|
|
431
|
-
throw new Error('MCP 连接器已 close —— 请重新创建一个');
|
|
432
|
-
const headers = { ...baseHeaders };
|
|
433
|
-
if (sessionId !== null)
|
|
434
|
-
headers['mcp-session-id'] = sessionId;
|
|
435
|
-
if (o.withVersion)
|
|
436
|
-
headers['mcp-protocol-version'] = negotiated;
|
|
437
|
-
const res = await fetchImpl(url, { method: 'POST', headers, body: JSON.stringify(payload) });
|
|
438
|
-
// 会话 id 只在 initialize 响应里出现;后续响应不带时**不能**把它清成 null
|
|
439
|
-
const sid = res.headers.get('mcp-session-id');
|
|
440
|
-
if (sid !== null && sid !== '')
|
|
441
|
-
sessionId = sid;
|
|
442
|
-
return res;
|
|
443
|
-
};
|
|
444
|
-
/** 非 SSE 报文(单条 JSON-RPC)→ 取 result;SSE 里可能有别的通知帧,只取与 `id` 配对的 */
|
|
445
|
-
const pickResult = (msg, id, method) => {
|
|
446
|
-
if (!isJsonRpcResponse(msg)) {
|
|
447
|
-
throw new Error(`MCP ${method}:响应里没有 id 为 ${id} 的 JSON-RPC 报文`);
|
|
448
|
-
}
|
|
449
|
-
return unwrap(msg, method);
|
|
450
|
-
};
|
|
451
|
-
/**
|
|
452
|
-
* 从响应取结果。SSE 分支一次性读完整个 body 再解析 —— StreamableHTTP 约定 server 发完
|
|
453
|
-
* 响应即关流,读全比手写增量解析器稳(`text/event-stream` 里 `data:` 行按规范可跨多行拼接)。
|
|
454
|
-
*/
|
|
455
|
-
const readResult = async (res, id, method) => {
|
|
456
|
-
const ct = (res.headers.get('content-type') ?? '').toLowerCase();
|
|
457
|
-
const text = await readText(res);
|
|
458
|
-
if (ct.includes('text/event-stream')) {
|
|
459
|
-
for (const frame of text.split(/\r?\n\r?\n/)) {
|
|
460
|
-
const data = frame
|
|
461
|
-
.split(/\r?\n/)
|
|
462
|
-
.filter((l) => l.startsWith('data:'))
|
|
463
|
-
.map((l) => l.slice(5).trim())
|
|
464
|
-
.join('');
|
|
465
|
-
if (data === '')
|
|
466
|
-
continue;
|
|
467
|
-
let msg;
|
|
468
|
-
try {
|
|
469
|
-
msg = JSON.parse(data);
|
|
470
|
-
}
|
|
471
|
-
catch {
|
|
472
|
-
continue;
|
|
473
|
-
}
|
|
474
|
-
if (isJsonRpcResponse(msg) && msg.id === id)
|
|
475
|
-
return unwrap(msg, method);
|
|
476
|
-
}
|
|
477
|
-
throw new Error(`MCP ${method}:SSE 响应里没有 id 为 ${id} 的报文`);
|
|
478
|
-
}
|
|
479
|
-
if (text.trim() === '') {
|
|
480
|
-
throw new Error(`MCP ${method}:响应体为空(期望 id 为 ${id} 的 JSON-RPC 报文)`);
|
|
481
|
-
}
|
|
482
|
-
let msg;
|
|
483
|
-
try {
|
|
484
|
-
msg = JSON.parse(text);
|
|
485
|
-
}
|
|
486
|
-
catch {
|
|
487
|
-
throw new Error(`MCP ${method}:响应不是合法 JSON:${brief(text)}`);
|
|
488
|
-
}
|
|
489
|
-
return pickResult(msg, id, method);
|
|
490
|
-
};
|
|
491
|
-
/**
|
|
492
|
-
* 一次 JSON-RPC 往返,带**会话过期自愈**(2026-09-18;MCP Streamable HTTP 的规范语义)。
|
|
493
|
-
*
|
|
494
|
-
* 带会话 id 收到 `404` 的含义是「这个会话我不认识」⇒ **该请求没有被执行** ——
|
|
495
|
-
* 所以丢掉会话、重新握手、把这一次**重试一次**是安全的(不会重复执行副作用)。
|
|
496
|
-
* 规范也是这么要求的:客户端**必须**新建会话(不带会话 id 重新 `initialize`)。
|
|
497
|
-
*
|
|
498
|
-
* **只重试一次**:第二次再 404 说明对面不是「会话过期」而是别的问题,直接抛(不循环)。
|
|
499
|
-
* 自愈本身是静默的,但可通过 `onSessionExpired` 观测 —— 否则它和「静默失效」没区别。
|
|
500
|
-
*/
|
|
501
|
-
const rpc = async (method, params, withVersion, allowReinit = true) => {
|
|
502
|
-
const id = nextId++;
|
|
503
|
-
const res = await post({ jsonrpc: '2.0', id, method, params }, { withVersion });
|
|
504
|
-
if (res.status === 404 && sessionId !== null && allowReinit) {
|
|
505
|
-
await readText(res); // 排空,别把连接晾着
|
|
506
|
-
opts.onSessionExpired?.();
|
|
507
|
-
sessionId = null;
|
|
508
|
-
ready = null; // 下一次 ensureReady 会新建会话
|
|
509
|
-
await ensureReady();
|
|
510
|
-
return rpc(method, params, withVersion, false);
|
|
511
|
-
}
|
|
512
|
-
if (!res.ok)
|
|
513
|
-
throw httpError(res.status, method, await readText(res));
|
|
514
|
-
return guard(readResult(res, id, method), method);
|
|
515
|
-
};
|
|
516
|
-
const ensureReady = () => {
|
|
517
|
-
if (ready)
|
|
518
|
-
return ready;
|
|
519
|
-
ready = (async () => {
|
|
520
|
-
const init = await guard(rpc('initialize', { protocolVersion: requestedVersion, capabilities: {}, clientInfo }, false), 'initialize');
|
|
521
|
-
if (typeof init === 'object' && init !== null) {
|
|
522
|
-
const v = init.protocolVersion;
|
|
523
|
-
if (typeof v === 'string' && v !== '')
|
|
524
|
-
negotiated = v;
|
|
525
|
-
}
|
|
526
|
-
const res = await guard(post({ jsonrpc: '2.0', method: 'notifications/initialized', params: {} }, { withVersion: true }), 'notifications/initialized');
|
|
527
|
-
if (!res.ok) {
|
|
528
|
-
throw httpError(res.status, 'notifications/initialized', await readText(res));
|
|
529
|
-
}
|
|
530
|
-
await readText(res); // 排空:202 + 空体是合法应答,但别把连接晾着
|
|
531
|
-
})();
|
|
532
|
-
return ready;
|
|
533
|
-
};
|
|
534
|
-
const listTools = async () => {
|
|
535
|
-
await ensureReady();
|
|
536
|
-
const r = await guard(rpc('tools/list', {}, true), 'tools/list');
|
|
537
|
-
if (typeof r !== 'object' || r === null) {
|
|
538
|
-
throw new Error(`MCP tools/list 返回了非对象:${brief(r)}`);
|
|
539
|
-
}
|
|
540
|
-
const listed = r.tools;
|
|
541
|
-
if (listed === undefined)
|
|
542
|
-
return [];
|
|
543
|
-
if (!Array.isArray(listed)) {
|
|
544
|
-
throw new Error(`MCP tools/list 的 tools 不是数组:${brief(listed)}`);
|
|
545
|
-
}
|
|
546
|
-
return listed;
|
|
547
|
-
};
|
|
548
|
-
const callTool = async (name, args) => {
|
|
549
|
-
await ensureReady();
|
|
550
|
-
const r = await rpc('tools/call', { name, arguments: args }, true);
|
|
551
|
-
// 承重同 stdio:协议层 isError 只有连接器看得见
|
|
552
|
-
if (typeof r === 'object' && r !== null && r.isError) {
|
|
553
|
-
throw new Error(`MCP 工具 ${name} 返回 isError: ${brief(r.content)}`);
|
|
554
|
-
}
|
|
555
|
-
return r;
|
|
556
|
-
};
|
|
557
|
-
return {
|
|
558
|
-
listTools,
|
|
559
|
-
callTool,
|
|
560
|
-
async close() {
|
|
561
|
-
if (closed)
|
|
562
|
-
return;
|
|
563
|
-
closed = true;
|
|
564
|
-
const sid = sessionId;
|
|
565
|
-
sessionId = null;
|
|
566
|
-
if (sid === null)
|
|
567
|
-
return;
|
|
568
|
-
try {
|
|
569
|
-
// 尽力终止会话(MCP 约定的显式关闭);server 不认这个方法也不该让 close() 抛
|
|
570
|
-
const res = await fetchImpl(url, {
|
|
571
|
-
method: 'DELETE',
|
|
572
|
-
headers: { ...baseHeaders, 'mcp-session-id': sid, 'mcp-protocol-version': negotiated },
|
|
573
|
-
});
|
|
574
|
-
await readText(res);
|
|
575
|
-
}
|
|
576
|
-
catch {
|
|
577
|
-
/* 关闭是尽力而为 */
|
|
578
|
-
}
|
|
579
|
-
},
|
|
580
|
-
};
|
|
581
|
-
}
|
|
182
|
+
// 两个内置连接器(2026-09-20 起各居其文件;公共面不变,index.ts 仍从这里取)
|
|
183
|
+
export { createStdioMcpConnector, MCP_CLOSE_GRACE_MS } from './mcp-stdio.js';
|
|
184
|
+
export { createStreamableHttpMcpConnector } from './mcp-http.js';
|
|
582
185
|
//# sourceMappingURL=mcp.js.map
|