@ai-zen/agents-sdk 1.2.0-alpha.2 → 2.0.0-alpha.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.
- package/CHANGELOG.md +77 -0
- package/README.md +397 -113
- package/README.zh.md +314 -112
- package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
- package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
- package/dist/agent-plugins/AutoMigratePlugin.d.ts +56 -6
- package/dist/agent-plugins/AutoMigratePlugin.js +64 -15
- package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +12 -9
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +6 -7
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +32 -24
- package/dist/agent-plugins/ContextGuardPlugin.js +37 -22
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +38 -46
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +37 -50
- package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +15 -1
- package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -1
- package/dist/config/ConfigManager.d.ts +13 -5
- package/dist/config/ConfigManager.js +58 -39
- package/dist/config/constants.d.ts +1 -1
- package/dist/config/constants.js +2 -2
- package/dist/config/factory-skills.js +2 -2
- package/dist/config/normalize.d.ts +93 -0
- package/dist/config/normalize.js +158 -0
- package/dist/crud/AgentRepository.d.ts +3 -1
- package/dist/crud/AgentRepository.js +4 -2
- package/dist/index.d.ts +22 -9
- package/dist/index.js +16 -6
- package/dist/runtime/AgentRuntime.d.ts +293 -0
- package/dist/runtime/AgentRuntime.js +457 -0
- package/dist/runtime/HandoffGuardPlugin.d.ts +85 -16
- package/dist/runtime/HandoffGuardPlugin.js +140 -19
- package/dist/runtime/HandoffService.d.ts +255 -91
- package/dist/runtime/HandoffService.js +392 -177
- package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
- package/dist/runtime/RuntimePeerSessions.js +50 -0
- package/dist/runtime/Scopes.d.ts +123 -0
- package/dist/runtime/Scopes.js +169 -0
- package/dist/runtime/SdkAgent.d.ts +21 -11
- package/dist/runtime/SdkAgent.js +24 -8
- package/dist/runtime/completeOnce.d.ts +3 -3
- package/dist/runtime/completeOnce.js +3 -3
- package/dist/runtime/createAgent.d.ts +29 -7
- package/dist/runtime/createAgent.js +57 -12
- package/dist/runtime/createModel.d.ts +4 -4
- package/dist/runtime/createModel.js +6 -6
- package/dist/runtime/lastPromptTokens.d.ts +18 -0
- package/dist/runtime/lastPromptTokens.js +26 -0
- package/dist/runtime/resolveModel.d.ts +9 -9
- package/dist/runtime/resolveModel.js +8 -8
- package/dist/scope/Scope.d.ts +42 -14
- package/dist/scope/Scope.js +55 -16
- package/dist/scope/ScopePlugin.d.ts +2 -8
- package/dist/scope/disclosure.d.ts +1 -1
- package/dist/scope/disclosure.js +1 -1
- package/dist/scope/plugins/allInOne.d.ts +13 -1
- package/dist/scope/plugins/allInOne.js +9 -5
- package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
- package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
- package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
- package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
- package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
- package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
- package/dist/scope/plugins/builtin/ExecTool.js +10 -199
- package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
- package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
- package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
- package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
- package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
- package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
- package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
- package/dist/scope/plugins/builtin/SleepTool.js +2 -3
- package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
- package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
- package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
- package/dist/scope/plugins/builtin/WriteTool.js +8 -1
- package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
- package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
- package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
- package/dist/scope/plugins/builtin/commandOutput.js +55 -0
- package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
- package/dist/scope/plugins/builtin/commandRun.js +169 -0
- package/dist/scope/plugins/builtin/discover.d.ts +1 -3
- package/dist/scope/plugins/builtin/discover.js +1 -3
- package/dist/scope/plugins/builtin/index.d.ts +5 -7
- package/dist/scope/plugins/builtin/index.js +7 -7
- package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
- package/dist/scope/plugins/builtin/outputGuard.js +1 -5
- package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +61 -9
- package/dist/scope/plugins/mcp/McpConnectionManager.js +174 -72
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +37 -4
- package/dist/scope/plugins/mcp/McpScopePlugin.js +100 -9
- package/dist/scope/plugins/mcp/discover.d.ts +9 -2
- package/dist/scope/plugins/mcp/discover.js +12 -14
- package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
- package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
- package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
- package/dist/scope/plugins/mcp/mcpTools.js +220 -39
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +25 -0
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +32 -0
- package/dist/scope/plugins/peers/peerSessionTools.d.ts +173 -0
- package/dist/scope/plugins/peers/peerSessionTools.js +292 -0
- package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
- package/dist/scope/plugins/skills/discover.d.ts +15 -8
- package/dist/scope/plugins/skills/discover.js +15 -26
- package/dist/scope/plugins/skills/skillTools.d.ts +9 -8
- package/dist/scope/plugins/skills/skillTools.js +21 -13
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
- package/dist/scope/plugins/subagents/discover.d.ts +7 -1
- package/dist/scope/plugins/subagents/discover.js +7 -3
- package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
- package/dist/scope/plugins/subagents/subAgentTools.js +14 -1
- package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
- package/dist/scope/plugins/usertools/discover.d.ts +7 -8
- package/dist/scope/plugins/usertools/discover.js +17 -27
- package/dist/shared/EntityRepository.d.ts +22 -5
- package/dist/shared/EntityRepository.js +45 -29
- package/dist/shared/content-blocks.d.ts +9 -3
- package/dist/shared/content-blocks.js +12 -19
- package/dist/shared/errors.d.ts +8 -3
- package/dist/shared/errors.js +9 -4
- package/dist/shared/logger.d.ts +21 -10
- package/dist/shared/logger.js +9 -15
- package/dist/types/index.d.ts +38 -13
- package/package.json +2 -2
- package/dist/config/migrate.d.ts +0 -115
- package/dist/config/migrate.js +0 -200
- package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
- package/dist/scope/plugins/builtin/test-helpers.js +0 -4
|
@@ -11,11 +11,7 @@ export const DEFAULT_MAX_TOOL_OUTPUT = 32_768;
|
|
|
11
11
|
/**
|
|
12
12
|
* 标准输出保护骨架。
|
|
13
13
|
*
|
|
14
|
-
* 各工具在 call()
|
|
15
|
-
* 1) isOverLimit —— 是否超过上限(工具自读 config 判定,未被超限即原样返回 content);
|
|
16
|
-
* 2) dump —— 超限时落盘哪些文件(可省略 = 只警告不落盘);
|
|
17
|
-
* 3) buildWarning —— 超限时返回给模型的内容。
|
|
18
|
-
*
|
|
14
|
+
* 各工具在 call() 出口调用,三个回调的含义见 {@link OutputGuardOptions}。
|
|
19
15
|
* 骨架职责:判定 → 未超限原样返回 / 超限时创建独立目录并写文件 → 交给 buildWarning。
|
|
20
16
|
*
|
|
21
17
|
* 落盘目录:<os.tmpdir()>/ai-zen/tool-output/<tool>-<时间戳>-<随机串>/,
|
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
2
2
|
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
3
|
+
import type { Agent } from "@ai-zen/agents-core";
|
|
4
|
+
import { type LogSink } from "../../../shared/logger.js";
|
|
3
5
|
import type { McpServerConfig, McpServerManifest, McpConnectionState } from "../../../types/index.js";
|
|
6
|
+
import { type McpTaskNoticePort } from "./mcpTaskNotice.js";
|
|
4
7
|
export interface McpConnectOptions {
|
|
5
8
|
/** 空闲超时(毫秒),默认 stdio: 30min, http/sse: 5min */
|
|
6
9
|
idleTimeoutMs?: number;
|
|
7
10
|
/** 建连超时(毫秒),默认 60s;超时即断开并抛错,避免工具永久挂起 */
|
|
8
11
|
connectTimeoutMs?: number;
|
|
9
|
-
/** 失败时自动重连 */
|
|
10
|
-
autoReconnect?: boolean;
|
|
11
|
-
/** 最大重试次数,默认 3 */
|
|
12
|
-
maxRetries?: number;
|
|
13
|
-
/** 判断是否为配置错误(不重试),默认全部重试 */
|
|
14
|
-
isConfigError?: (err: unknown) => boolean;
|
|
15
12
|
}
|
|
16
13
|
export declare class McpConnectionManager {
|
|
17
14
|
private servers;
|
|
@@ -19,28 +16,83 @@ export declare class McpConnectionManager {
|
|
|
19
16
|
private _transportFactory?;
|
|
20
17
|
/** 可替换的 Client 工厂,用于测试注入 */
|
|
21
18
|
private _clientFactory?;
|
|
19
|
+
/** 日志口(构造时定下缺省:不注入就什么都不写) */
|
|
20
|
+
private readonly logger;
|
|
21
|
+
/** 任务通知的投递口(宿主实现);不注入就没有人接得住任务状态 */
|
|
22
|
+
private readonly _taskNotice?;
|
|
23
|
+
/**
|
|
24
|
+
* 任务 id → 发起它的那段会话。
|
|
25
|
+
*
|
|
26
|
+
* 这份对应关系只活在这里:进程没了就没了 —— 任务本身在服务器那边,谈不上恢复;重启之后
|
|
27
|
+
* 服务器再推来的状态也没有会话可投,丢掉就是。
|
|
28
|
+
*/
|
|
29
|
+
private readonly taskSessions;
|
|
30
|
+
/**
|
|
31
|
+
* 比「记下这个任务是谁发起的」更早到的终态。
|
|
32
|
+
*
|
|
33
|
+
* 任务建出来之后服务器就跑,状态可能在我们拿到句柄、把对应关系记下来之前先到(同一个连接上
|
|
34
|
+
* 两条消息的先后不保证)。先搁在这里,记下那一刻立刻补投;搁不下的(没有谁来认领的终态)
|
|
35
|
+
* 直接丢掉。
|
|
36
|
+
*/
|
|
37
|
+
private readonly earlyStatuses;
|
|
22
38
|
/**
|
|
23
39
|
* @param transportFactory 可选的自定义 transport 工厂(用于测试注入)
|
|
24
40
|
* @param clientFactory 可选的自定义 Client 工厂(用于测试注入)
|
|
41
|
+
* @param logger 日志口(可选):建连失败、清单没拉到、断线、关不掉从这里报;缺省不记
|
|
42
|
+
* @param taskNotice 任务通知的投递口(可选):不给就没有地方投,任务状态只当没收到
|
|
25
43
|
*/
|
|
26
|
-
constructor(transportFactory?: (config: McpServerConfig) => Transport, clientFactory?: () => Client);
|
|
44
|
+
constructor(transportFactory?: (config: McpServerConfig) => Transport, clientFactory?: () => Client, logger?: LogSink, taskNotice?: McpTaskNoticePort);
|
|
27
45
|
getState(name: string): McpConnectionState;
|
|
28
46
|
getManifest(name: string): McpServerManifest | undefined;
|
|
29
47
|
getClient(name: string): Client | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* 这个工具声明的任务档位。
|
|
50
|
+
*
|
|
51
|
+
* 清单里没有它、或者它没写这一格,就是 `forbidden`(规范的缺省);清单是从 `tools/list`
|
|
52
|
+
* 拿到的,所以问它和问服务器是同一件事,不必再发一次请求。
|
|
53
|
+
*/
|
|
54
|
+
taskSupportOf(name: string, tool: string): "forbidden" | "optional" | "required";
|
|
55
|
+
/**
|
|
56
|
+
* 记住一个任务是谁发起的:状态通知到了要投进那段会话的 inbox。
|
|
57
|
+
*
|
|
58
|
+
* 会话 id 只有投递口答得出来(发起调用的是执行体,它属于哪一段会话是运行时的事)。答不出来
|
|
59
|
+
* 就什么都不记 —— 那种调用(被派出去的 subagent、一次性执行体)发起的任务没有会话可以回报。
|
|
60
|
+
*/
|
|
61
|
+
rememberTask(name: string, taskId: string, agent: Agent): void;
|
|
30
62
|
connect(name: string, config: McpServerConfig, options?: McpConnectOptions): Promise<McpServerManifest>;
|
|
31
63
|
/** 给建连套上超时:超时即取消连接并清掉半成品状态 */
|
|
32
64
|
private withConnectTimeout;
|
|
33
|
-
private connectWithRetry;
|
|
34
65
|
private doConnect;
|
|
35
|
-
/**
|
|
66
|
+
/** 关闭连接资源(断开/取消路径共用):关不掉要留一行,不能装成关掉了 */
|
|
36
67
|
private closeQuietly;
|
|
37
68
|
/** 运行期断线:标记 disconnected 并记日志(已在连接状态才处理,避免重复日志) */
|
|
38
69
|
private markDisconnected;
|
|
70
|
+
/**
|
|
71
|
+
* 一条任务状态通知该干什么。
|
|
72
|
+
*
|
|
73
|
+
* 只有终态才投:`working` / `input_required` 不是「有事要人动手」,每一条都投就是刷屏;
|
|
74
|
+
* 终态那一条是要人(执行体)去拉结果的信号,投进发起这次调用的那段会话。
|
|
75
|
+
*
|
|
76
|
+
* 对应关系用过就删:这里记的是「哪个任务还欠谁一条回报」,终态之后就没了。
|
|
77
|
+
*/
|
|
78
|
+
private onTaskStatus;
|
|
79
|
+
/** 把先到的终态搁一下(上限只防未认领的那些无限长) */
|
|
80
|
+
private rememberEarlyStatus;
|
|
81
|
+
/** 把一条终态投进那段会话 */
|
|
82
|
+
private report;
|
|
83
|
+
/** 丢掉一台服务器上所有任务的对应关系(断开与断线共用) */
|
|
84
|
+
private forgetTasks;
|
|
39
85
|
/**
|
|
40
86
|
* 根据配置创建对应的 Transport 实例。
|
|
41
87
|
* 如果设置了自定义工厂(测试用),则使用自定义工厂。
|
|
42
88
|
*/
|
|
43
89
|
private createTransport;
|
|
90
|
+
/**
|
|
91
|
+
* 断开**单个** server(不影响别的 server)。
|
|
92
|
+
*
|
|
93
|
+
* 状态与清单一起失效:断开之后 `getState()` 回到 `disconnected`、`getManifest()` 为空,
|
|
94
|
+
* 下一次 `connect()` 会按新的定义重新建链(懒连)。
|
|
95
|
+
*/
|
|
44
96
|
disconnect(name: string): Promise<void>;
|
|
45
97
|
disconnectAll(): Promise<void>;
|
|
46
98
|
touch(name: string): void;
|
|
@@ -2,37 +2,73 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
|
2
2
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
3
3
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
4
4
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
|
-
import {
|
|
5
|
+
import { TaskStatusNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
6
|
+
import { SILENT_LOG } from "../../../shared/logger.js";
|
|
7
|
+
import { isTerminalTaskStatus } from "./mcpTaskNotice.js";
|
|
6
8
|
/**
|
|
7
9
|
* 建连超时缺省值(毫秒)。
|
|
8
10
|
*
|
|
9
11
|
* 没有上限时,配置错误的 SSE / HTTP 端点会让 `load_mcp` 永久挂起(SSE 在服务端不发
|
|
10
|
-
* 响应头时尤其如此,fetch 只对建链有兜底,对"连上了但永不回话"
|
|
12
|
+
* 响应头时尤其如此,fetch 只对建链有兜底,对"连上了但永不回话"没有)。
|
|
11
13
|
*/
|
|
12
14
|
const DEFAULT_CONNECT_TIMEOUT_MS = 60_000;
|
|
15
|
+
/**
|
|
16
|
+
* 客户端在能力协商里声明的能力。
|
|
17
|
+
*
|
|
18
|
+
* `tasks` 这一格是任务增强的前提:服务器按它判断对面接不接得住任务。里面只声明真的会用的那
|
|
19
|
+
* 一项 —— `cancel` 是因为工具面有取消那一条(`tasks/cancel`);`list` 不用,就不声明。
|
|
20
|
+
*/
|
|
21
|
+
const CLIENT_CAPABILITIES = { tasks: { cancel: {} } };
|
|
22
|
+
/**
|
|
23
|
+
* 任务 id 在管理器里的键:任务 id 只在它自己那台服务器上唯一,两台服务器各自发的同号任务
|
|
24
|
+
* 是两件事。
|
|
25
|
+
*/
|
|
26
|
+
function taskKey(server, taskId) {
|
|
27
|
+
return `${server}\u0000${taskId}`;
|
|
28
|
+
}
|
|
29
|
+
/** 先到的终态最多搁这么多条:超过就丢最早的那一条(只影响没有谁来认领的那些) */
|
|
30
|
+
const EARLY_STATUS_LIMIT = 64;
|
|
13
31
|
const DEFAULT_IDLE_TIMEOUT = {
|
|
14
32
|
stdio: 30 * 60 * 1000,
|
|
15
33
|
http: 5 * 60 * 1000,
|
|
16
34
|
sse: 5 * 60 * 1000,
|
|
17
35
|
};
|
|
18
|
-
/** 指数退避: 1s → 2s → 4s → 8s → 16s → 30s(封顶) */
|
|
19
|
-
function backoff(attempt) {
|
|
20
|
-
const ms = Math.min(1000 * Math.pow(2, attempt), 30_000);
|
|
21
|
-
return ms;
|
|
22
|
-
}
|
|
23
36
|
export class McpConnectionManager {
|
|
24
37
|
servers = new Map();
|
|
25
38
|
/** 可替换的 transport 工厂,用于测试注入 */
|
|
26
39
|
_transportFactory;
|
|
27
40
|
/** 可替换的 Client 工厂,用于测试注入 */
|
|
28
41
|
_clientFactory;
|
|
42
|
+
/** 日志口(构造时定下缺省:不注入就什么都不写) */
|
|
43
|
+
logger;
|
|
44
|
+
/** 任务通知的投递口(宿主实现);不注入就没有人接得住任务状态 */
|
|
45
|
+
_taskNotice;
|
|
46
|
+
/**
|
|
47
|
+
* 任务 id → 发起它的那段会话。
|
|
48
|
+
*
|
|
49
|
+
* 这份对应关系只活在这里:进程没了就没了 —— 任务本身在服务器那边,谈不上恢复;重启之后
|
|
50
|
+
* 服务器再推来的状态也没有会话可投,丢掉就是。
|
|
51
|
+
*/
|
|
52
|
+
taskSessions = new Map();
|
|
53
|
+
/**
|
|
54
|
+
* 比「记下这个任务是谁发起的」更早到的终态。
|
|
55
|
+
*
|
|
56
|
+
* 任务建出来之后服务器就跑,状态可能在我们拿到句柄、把对应关系记下来之前先到(同一个连接上
|
|
57
|
+
* 两条消息的先后不保证)。先搁在这里,记下那一刻立刻补投;搁不下的(没有谁来认领的终态)
|
|
58
|
+
* 直接丢掉。
|
|
59
|
+
*/
|
|
60
|
+
earlyStatuses = new Map();
|
|
29
61
|
/**
|
|
30
62
|
* @param transportFactory 可选的自定义 transport 工厂(用于测试注入)
|
|
31
63
|
* @param clientFactory 可选的自定义 Client 工厂(用于测试注入)
|
|
64
|
+
* @param logger 日志口(可选):建连失败、清单没拉到、断线、关不掉从这里报;缺省不记
|
|
65
|
+
* @param taskNotice 任务通知的投递口(可选):不给就没有地方投,任务状态只当没收到
|
|
32
66
|
*/
|
|
33
|
-
constructor(transportFactory, clientFactory) {
|
|
67
|
+
constructor(transportFactory, clientFactory, logger = SILENT_LOG, taskNotice) {
|
|
34
68
|
this._transportFactory = transportFactory;
|
|
35
69
|
this._clientFactory = clientFactory;
|
|
70
|
+
this.logger = logger;
|
|
71
|
+
this._taskNotice = taskNotice;
|
|
36
72
|
}
|
|
37
73
|
// ---- 对外查询 ----
|
|
38
74
|
getState(name) {
|
|
@@ -44,6 +80,38 @@ export class McpConnectionManager {
|
|
|
44
80
|
getClient(name) {
|
|
45
81
|
return this.servers.get(name)?.client;
|
|
46
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* 这个工具声明的任务档位。
|
|
85
|
+
*
|
|
86
|
+
* 清单里没有它、或者它没写这一格,就是 `forbidden`(规范的缺省);清单是从 `tools/list`
|
|
87
|
+
* 拿到的,所以问它和问服务器是同一件事,不必再发一次请求。
|
|
88
|
+
*/
|
|
89
|
+
taskSupportOf(name, tool) {
|
|
90
|
+
const tools = this.servers.get(name)?.manifest?.tools ?? [];
|
|
91
|
+
return tools.find((item) => item.name === tool)?.execution?.taskSupport ?? "forbidden";
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 记住一个任务是谁发起的:状态通知到了要投进那段会话的 inbox。
|
|
95
|
+
*
|
|
96
|
+
* 会话 id 只有投递口答得出来(发起调用的是执行体,它属于哪一段会话是运行时的事)。答不出来
|
|
97
|
+
* 就什么都不记 —— 那种调用(被派出去的 subagent、一次性执行体)发起的任务没有会话可以回报。
|
|
98
|
+
*/
|
|
99
|
+
rememberTask(name, taskId, agent) {
|
|
100
|
+
const sessionId = this._taskNotice?.sessionOf(agent);
|
|
101
|
+
if (sessionId === undefined) {
|
|
102
|
+
this.logger.info(`[McpConnectionManager] task "${taskId}" of "${name}" has no session to report to`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const key = taskKey(name, taskId);
|
|
106
|
+
// 再快也快不过它:终态已经先到了的话,记下的这一刻就把它投出去
|
|
107
|
+
const early = this.earlyStatuses.get(key);
|
|
108
|
+
if (early !== undefined) {
|
|
109
|
+
this.earlyStatuses.delete(key);
|
|
110
|
+
this.report(name, early, sessionId);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
this.taskSessions.set(key, sessionId);
|
|
114
|
+
}
|
|
47
115
|
// ---- 连接 ----
|
|
48
116
|
async connect(name, config, options = {}) {
|
|
49
117
|
const existing = this.servers.get(name);
|
|
@@ -56,7 +124,7 @@ export class McpConnectionManager {
|
|
|
56
124
|
return this.servers.get(name)?.manifest ?? this.throwNotConnected(name);
|
|
57
125
|
}
|
|
58
126
|
const timeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT[config.transport] ?? 5 * 60 * 1000;
|
|
59
|
-
const pendingPromise = this.
|
|
127
|
+
const pendingPromise = this.doConnect(name, config);
|
|
60
128
|
this.servers.set(name, {
|
|
61
129
|
state: "connecting",
|
|
62
130
|
pendingPromise,
|
|
@@ -103,8 +171,11 @@ export class McpConnectionManager {
|
|
|
103
171
|
}
|
|
104
172
|
catch (err) {
|
|
105
173
|
if (String(err?.message ?? "").includes("timed out")) {
|
|
106
|
-
//
|
|
107
|
-
|
|
174
|
+
// 取消挂着的建连,并清掉它可能建好的资源。清理自己再失败也要留一行:
|
|
175
|
+
// 主错误下面照抛,但「建到一半的东西没清掉」是另一件事
|
|
176
|
+
await this.disconnect(name).catch((cleanupError) => {
|
|
177
|
+
this.logger.warn(`[McpConnectionManager] 连接超时后清理 "${name}" 失败:${String(cleanupError)}`);
|
|
178
|
+
});
|
|
108
179
|
}
|
|
109
180
|
throw err;
|
|
110
181
|
}
|
|
@@ -113,53 +184,19 @@ export class McpConnectionManager {
|
|
|
113
184
|
clearTimeout(timer);
|
|
114
185
|
}
|
|
115
186
|
}
|
|
116
|
-
async connectWithRetry(name, config, options, attempt) {
|
|
117
|
-
try {
|
|
118
|
-
await this.doConnect(name, config);
|
|
119
|
-
}
|
|
120
|
-
catch (err) {
|
|
121
|
-
const entry = this.servers.get(name);
|
|
122
|
-
if (entry?.cancelled)
|
|
123
|
-
throw err;
|
|
124
|
-
if (options.isConfigError?.(err))
|
|
125
|
-
throw err;
|
|
126
|
-
if (!options.autoReconnect)
|
|
127
|
-
throw err;
|
|
128
|
-
const maxRetries = options.maxRetries ?? 3;
|
|
129
|
-
if (attempt >= maxRetries)
|
|
130
|
-
throw err;
|
|
131
|
-
const delay = backoff(attempt);
|
|
132
|
-
await new Promise((resolve, reject) => {
|
|
133
|
-
const current = this.servers.get(name);
|
|
134
|
-
if (current)
|
|
135
|
-
current.cancelRetryWait = reject;
|
|
136
|
-
const timer = setTimeout(() => {
|
|
137
|
-
const current2 = this.servers.get(name);
|
|
138
|
-
if (current2)
|
|
139
|
-
current2.cancelRetryWait = undefined;
|
|
140
|
-
if (current2?.cancelled) {
|
|
141
|
-
reject(new Error(`Connection to "${name}" was cancelled`));
|
|
142
|
-
}
|
|
143
|
-
else {
|
|
144
|
-
resolve();
|
|
145
|
-
}
|
|
146
|
-
}, delay);
|
|
147
|
-
const current3 = this.servers.get(name);
|
|
148
|
-
if (current3)
|
|
149
|
-
current3.retryTimer = timer;
|
|
150
|
-
});
|
|
151
|
-
const recheck = this.servers.get(name);
|
|
152
|
-
if (recheck?.cancelled)
|
|
153
|
-
throw new Error(`Connection to "${name}" was cancelled`);
|
|
154
|
-
return this.connectWithRetry(name, config, options, attempt + 1);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
187
|
async doConnect(name, config) {
|
|
158
188
|
const transport = this.createTransport(config);
|
|
159
189
|
const client = this._clientFactory
|
|
160
190
|
? this._clientFactory()
|
|
161
|
-
: new Client({ name: "ai-zen-agents", version: "0.1.0" }, {
|
|
191
|
+
: new Client({ name: "ai-zen-agents", version: "0.1.0" }, {
|
|
192
|
+
capabilities: CLIENT_CAPABILITIES,
|
|
193
|
+
});
|
|
162
194
|
await client.connect(transport);
|
|
195
|
+
// 任务状态是服务器推来的(`notifications/tasks/status`):建好连就把这一条接上,之后由
|
|
196
|
+
// `onTaskStatus` 决定投不投。一个 client 一条,重复建连时旧 client 已经关了,不会叠。
|
|
197
|
+
client.setNotificationHandler(TaskStatusNotificationSchema, (notification) => {
|
|
198
|
+
this.onTaskStatus(name, notification.params);
|
|
199
|
+
});
|
|
163
200
|
// 根据 Server 声明的 capabilities 按需调用,避免调用未声明的方法
|
|
164
201
|
const serverCaps = client.getServerCapabilities();
|
|
165
202
|
const manifest = {
|
|
@@ -174,10 +211,12 @@ export class McpConnectionManager {
|
|
|
174
211
|
name: t.name,
|
|
175
212
|
description: t.description ?? "",
|
|
176
213
|
inputSchema: t.inputSchema,
|
|
214
|
+
// 任务档位带着走:`call_mcp_tool` 要不要带任务参数,判据就是这一格
|
|
215
|
+
...(t.execution ? { execution: { taskSupport: t.execution.taskSupport } } : {}),
|
|
177
216
|
}));
|
|
178
217
|
}
|
|
179
218
|
catch (err) {
|
|
180
|
-
|
|
219
|
+
this.logger.error(`[McpConnectionManager] Failed to list tools for "${name}": ${err?.message ?? err}`);
|
|
181
220
|
}
|
|
182
221
|
}
|
|
183
222
|
if (serverCaps?.resources) {
|
|
@@ -191,7 +230,7 @@ export class McpConnectionManager {
|
|
|
191
230
|
}));
|
|
192
231
|
}
|
|
193
232
|
catch (err) {
|
|
194
|
-
|
|
233
|
+
this.logger.error(`[McpConnectionManager] Failed to list resources for "${name}": ${err?.message ?? err}`);
|
|
195
234
|
}
|
|
196
235
|
}
|
|
197
236
|
if (serverCaps?.prompts) {
|
|
@@ -203,7 +242,7 @@ export class McpConnectionManager {
|
|
|
203
242
|
}));
|
|
204
243
|
}
|
|
205
244
|
catch (err) {
|
|
206
|
-
|
|
245
|
+
this.logger.error(`[McpConnectionManager] Failed to list prompts for "${name}": ${err?.message ?? err}`);
|
|
207
246
|
}
|
|
208
247
|
}
|
|
209
248
|
const entry = this.servers.get(name) ?? { state: "connecting" };
|
|
@@ -213,7 +252,7 @@ export class McpConnectionManager {
|
|
|
213
252
|
await this.closeQuietly(client, transport);
|
|
214
253
|
throw new Error(`Connection to "${name}" was cancelled`);
|
|
215
254
|
}
|
|
216
|
-
// 断线检测:运行期 transport 关掉时把状态标回 disconnected,避免 load_mcp
|
|
255
|
+
// 断线检测:运行期 transport 关掉时把状态标回 disconnected,避免 `load_mcp`
|
|
217
256
|
// 一直展示过期清单(不做自动重连:重连策略属于上层)。
|
|
218
257
|
const prevOnClose = transport.onclose;
|
|
219
258
|
transport.onclose = () => {
|
|
@@ -223,7 +262,7 @@ export class McpConnectionManager {
|
|
|
223
262
|
const prevOnError = transport.onerror;
|
|
224
263
|
transport.onerror = (error) => {
|
|
225
264
|
prevOnError?.(error);
|
|
226
|
-
|
|
265
|
+
this.logger.error(`[McpConnectionManager] Transport error for "${name}": ${error?.message ?? error}`);
|
|
227
266
|
};
|
|
228
267
|
this.servers.set(name, {
|
|
229
268
|
...entry,
|
|
@@ -234,26 +273,91 @@ export class McpConnectionManager {
|
|
|
234
273
|
cancelled: false,
|
|
235
274
|
});
|
|
236
275
|
}
|
|
237
|
-
/**
|
|
276
|
+
/** 关闭连接资源(断开/取消路径共用):关不掉要留一行,不能装成关掉了 */
|
|
238
277
|
async closeQuietly(client, transport) {
|
|
239
278
|
try {
|
|
240
279
|
await client?.close();
|
|
241
280
|
}
|
|
242
|
-
catch {
|
|
281
|
+
catch (error) {
|
|
282
|
+
this.logger.warn(`[McpConnectionManager] 关闭 MCP client 失败:${String(error)}`);
|
|
283
|
+
}
|
|
243
284
|
try {
|
|
244
285
|
await transport?.close();
|
|
245
286
|
}
|
|
246
|
-
catch {
|
|
287
|
+
catch (error) {
|
|
288
|
+
this.logger.warn(`[McpConnectionManager] 关闭 MCP transport 失败:${String(error)}`);
|
|
289
|
+
}
|
|
247
290
|
}
|
|
248
291
|
/** 运行期断线:标记 disconnected 并记日志(已在连接状态才处理,避免重复日志) */
|
|
249
292
|
markDisconnected(name) {
|
|
250
293
|
const entry = this.servers.get(name);
|
|
251
294
|
if (!entry || entry.state !== "connected")
|
|
252
295
|
return;
|
|
253
|
-
|
|
296
|
+
this.logger.error(`[McpConnectionManager] MCP server "${name}" disconnected`);
|
|
254
297
|
this.clearTimeout(name);
|
|
298
|
+
// 连不上了就再也收不到这台服务器的状态通知:那些对应关系没有用处了,一并丢掉
|
|
299
|
+
this.forgetTasks(name);
|
|
255
300
|
this.servers.set(name, { state: "disconnected" });
|
|
256
301
|
}
|
|
302
|
+
/**
|
|
303
|
+
* 一条任务状态通知该干什么。
|
|
304
|
+
*
|
|
305
|
+
* 只有终态才投:`working` / `input_required` 不是「有事要人动手」,每一条都投就是刷屏;
|
|
306
|
+
* 终态那一条是要人(执行体)去拉结果的信号,投进发起这次调用的那段会话。
|
|
307
|
+
*
|
|
308
|
+
* 对应关系用过就删:这里记的是「哪个任务还欠谁一条回报」,终态之后就没了。
|
|
309
|
+
*/
|
|
310
|
+
onTaskStatus(name, task) {
|
|
311
|
+
if (!isTerminalTaskStatus(task.status))
|
|
312
|
+
return;
|
|
313
|
+
const key = taskKey(name, task.taskId);
|
|
314
|
+
const sessionId = this.taskSessions.get(key);
|
|
315
|
+
if (sessionId === undefined) {
|
|
316
|
+
this.rememberEarlyStatus(key, task);
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
this.taskSessions.delete(key);
|
|
320
|
+
this.report(name, task, sessionId);
|
|
321
|
+
}
|
|
322
|
+
/** 把先到的终态搁一下(上限只防未认领的那些无限长) */
|
|
323
|
+
rememberEarlyStatus(key, task) {
|
|
324
|
+
if (this.earlyStatuses.size >= EARLY_STATUS_LIMIT) {
|
|
325
|
+
const oldest = this.earlyStatuses.keys().next().value;
|
|
326
|
+
if (oldest !== undefined)
|
|
327
|
+
this.earlyStatuses.delete(oldest);
|
|
328
|
+
}
|
|
329
|
+
this.earlyStatuses.set(key, task);
|
|
330
|
+
}
|
|
331
|
+
/** 把一条终态投进那段会话 */
|
|
332
|
+
report(name, task, sessionId) {
|
|
333
|
+
const port = this._taskNotice;
|
|
334
|
+
if (port === undefined || !isTerminalTaskStatus(task.status))
|
|
335
|
+
return;
|
|
336
|
+
// 通知处理是服务器那一侧推过来的,没有人接得住异常:投不出去(那段已经不在)由端口自己
|
|
337
|
+
// 记一句并返回 false,真报错也只落到日志里
|
|
338
|
+
void port
|
|
339
|
+
.deliver(sessionId, {
|
|
340
|
+
server: name,
|
|
341
|
+
taskId: task.taskId,
|
|
342
|
+
status: task.status,
|
|
343
|
+
...(task.statusMessage === undefined ? {} : { statusMessage: task.statusMessage }),
|
|
344
|
+
})
|
|
345
|
+
.catch((error) => {
|
|
346
|
+
this.logger.warn(`[McpConnectionManager] 投递任务通知失败 "${name}/${task.taskId}":${String(error)}`);
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/** 丢掉一台服务器上所有任务的对应关系(断开与断线共用) */
|
|
350
|
+
forgetTasks(name) {
|
|
351
|
+
const prefix = `${name}\u0000`;
|
|
352
|
+
for (const key of [...this.taskSessions.keys()]) {
|
|
353
|
+
if (key.startsWith(prefix))
|
|
354
|
+
this.taskSessions.delete(key);
|
|
355
|
+
}
|
|
356
|
+
for (const key of [...this.earlyStatuses.keys()]) {
|
|
357
|
+
if (key.startsWith(prefix))
|
|
358
|
+
this.earlyStatuses.delete(key);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
257
361
|
/**
|
|
258
362
|
* 根据配置创建对应的 Transport 实例。
|
|
259
363
|
* 如果设置了自定义工厂(测试用),则使用自定义工厂。
|
|
@@ -293,20 +397,20 @@ export class McpConnectionManager {
|
|
|
293
397
|
throw new Error(`Unsupported MCP transport type: ${config.transport}`);
|
|
294
398
|
}
|
|
295
399
|
// ---- 断开 ----
|
|
400
|
+
/**
|
|
401
|
+
* 断开**单个** server(不影响别的 server)。
|
|
402
|
+
*
|
|
403
|
+
* 状态与清单一起失效:断开之后 `getState()` 回到 `disconnected`、`getManifest()` 为空,
|
|
404
|
+
* 下一次 `connect()` 会按新的定义重新建链(懒连)。
|
|
405
|
+
*/
|
|
296
406
|
async disconnect(name) {
|
|
297
407
|
const entry = this.servers.get(name);
|
|
298
408
|
if (!entry || entry.state === "disconnected")
|
|
299
409
|
return;
|
|
300
410
|
entry.cancelled = true;
|
|
301
|
-
if (entry.cancelRetryWait) {
|
|
302
|
-
entry.cancelRetryWait(new Error(`Connection to "${name}" was cancelled`));
|
|
303
|
-
entry.cancelRetryWait = undefined;
|
|
304
|
-
}
|
|
305
|
-
if (entry.retryTimer) {
|
|
306
|
-
clearTimeout(entry.retryTimer);
|
|
307
|
-
entry.retryTimer = undefined;
|
|
308
|
-
}
|
|
309
411
|
this.clearTimeout(name);
|
|
412
|
+
// 连接没了就收不到状态通知了:这台服务器上还没到终态的任务不再欠谁一条回报
|
|
413
|
+
this.forgetTasks(name);
|
|
310
414
|
// 断开失败也清理状态。注意保留 `cancelled`:建连中的 await 回来后要据此放弃写入。
|
|
311
415
|
await this.closeQuietly(entry.client, entry.transport);
|
|
312
416
|
this.servers.set(name, {
|
|
@@ -317,8 +421,6 @@ export class McpConnectionManager {
|
|
|
317
421
|
manifest: undefined,
|
|
318
422
|
pendingPromise: undefined,
|
|
319
423
|
timeoutTimer: undefined,
|
|
320
|
-
retryTimer: undefined,
|
|
321
|
-
cancelRetryWait: undefined,
|
|
322
424
|
});
|
|
323
425
|
}
|
|
324
426
|
async disconnectAll() {
|
|
@@ -1,29 +1,62 @@
|
|
|
1
1
|
import type { Tool } from "@ai-zen/agents-core";
|
|
2
|
+
import type { McpTaskNoticePort } from "./mcpTaskNotice.js";
|
|
3
|
+
import type { McpServerConfig } from "../../../types/index.js";
|
|
4
|
+
import type { LogSink } from "../../../shared/logger.js";
|
|
2
5
|
import type { Scope, FilterOutput } from "../../Scope.js";
|
|
3
6
|
import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
|
|
4
7
|
/**
|
|
5
8
|
* MCP 插件 —— 发现 mcp.json + 自持连接管理器 + 装配渐进式披露元工具。
|
|
6
9
|
*
|
|
7
10
|
* 渐进式披露:
|
|
8
|
-
* - `load_mcp`
|
|
9
|
-
* - `call_mcp_tool`
|
|
10
|
-
* - `read_mcp_resource`
|
|
11
|
-
*
|
|
11
|
+
* - `load_mcp` 枚举所有允许的 server(含 include_manifest 开关)
|
|
12
|
+
* - `call_mcp_tool` 调用已连接 server 的工具(可带任务参数)
|
|
13
|
+
* - `read_mcp_resource` 读取已连接 server 的资源
|
|
14
|
+
* - `get_mcp_task_result` 按任务 id 取回一个任务的结果
|
|
15
|
+
* - `cancel_mcp_task` 取消一个任务
|
|
16
|
+
* 五个元工具名恒上报 `tools` 维度;`mcpManager` 由本插件私有持有,
|
|
12
17
|
* 有配置路径时在构造时创建,`dispose()` 时统一断开。
|
|
18
|
+
*
|
|
19
|
+
* 每次 `discover()` 除了重读 mcp 文件,还会把连接与发现结果对账一次(见 `reconcileConnections`)。
|
|
13
20
|
*/
|
|
14
21
|
export declare class McpScopePlugin implements ScopePlugin {
|
|
15
22
|
static readonly ID = "mcp";
|
|
16
23
|
readonly id = "mcp";
|
|
17
24
|
private readonly paths;
|
|
18
25
|
private readonly mcpManager;
|
|
26
|
+
/** 日志口(可选):连接管理器与 `load_mcp` 那两句都走它;不注入就不记 */
|
|
27
|
+
private readonly logger?;
|
|
19
28
|
private servers;
|
|
29
|
+
/**
|
|
30
|
+
* @param options.taskNotice 任务通知的投递口(可选):不给就是任务状态没有人接,其余照常
|
|
31
|
+
*/
|
|
20
32
|
constructor(options?: {
|
|
21
33
|
paths?: string[];
|
|
34
|
+
logger?: LogSink;
|
|
35
|
+
taskNotice?: McpTaskNoticePort;
|
|
22
36
|
});
|
|
23
37
|
discover(scope: Scope): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* 让连接跟着发现结果对账。
|
|
40
|
+
*
|
|
41
|
+
* 连接是按**定义**建立的:声明改了而连接不动,等于「配置改了但实际没生效」。所以
|
|
42
|
+
* - 这次发现里消失的 server → 断开它的连接(连同缓存的状态 / 清单一起失效);
|
|
43
|
+
* - 定义变了的 server → 断开旧连接,下一次调用时按新定义懒连;
|
|
44
|
+
* - 新增的 server → 不主动连(保持懒连接:没人调用就不起进程 / 不建链);
|
|
45
|
+
* - 定义没变的 → 一个字节都不动(连接与清单原样留着)。
|
|
46
|
+
*
|
|
47
|
+
* 于是「改了 mcp 配置」只需刷一次 Scope,不必重建它。
|
|
48
|
+
*/
|
|
49
|
+
private reconcileConnections;
|
|
24
50
|
/** 是否配置了 MCP(供外部代码判定,如 UnknownToolHintPlugin) */
|
|
25
51
|
hasConfig(): boolean;
|
|
26
52
|
candidates(): ScopeCandidates;
|
|
27
53
|
instantiate(scope: Scope, filtered: FilterOutput): Tool[];
|
|
28
54
|
dispose(): Promise<void>;
|
|
29
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* 对账结论:这些 server 的连接必须断掉。
|
|
58
|
+
*
|
|
59
|
+
* 两类:已经不在这次发现里的(配置里删了 / 被禁用),以及定义变了的(连接不能再按旧定义用)。
|
|
60
|
+
* 新增的不在结论里 —— 新增不主动连,保持懒连接。
|
|
61
|
+
*/
|
|
62
|
+
export declare function staleMcpConnections(previous: readonly McpServerConfig[], discovered: readonly McpServerConfig[]): string[];
|