Skip to content

feat(plugins): 支持配置 MCP 运行参数 - #2368

Merged
deepcoldy merged 5 commits into
deepcoldy:masterfrom
yousay123:feat/plugin-runtime-options-20261026
Oct 27, 2026
Merged

deepcoldy merged 5 commits into
deepcoldy:masterfrom
yousay123:feat/plugin-runtime-options-20261026

Conversation

@yousay123

Copy link
Copy Markdown
Contributor

改动内容

  • 增加按 Bot、按插件配置的 pluginRuntime,支持宿主侧 stdio 环境变量与单次工具调用超时。
  • 增加机器级 mcpGatewayMaxToolTimeoutMs 上限,默认 10 分钟,并保留 Node 定时器绝对安全边界。
  • 会话只把已启用插件的运行参数写入 0600 快照;Codex Gateway 外层等待时间与机器上限保持一致。
  • 补充配置解析、会话快照、Gateway 调用和安装配置测试及使用文档。

为什么改

不同插件的进程环境和执行时长并不相同。此前这些参数缺少会话级、宿主侧的统一配置入口,长任务还可能先被 CLI 外层默认超时中断。现在可以在不把密钥注入模型 CLI 的前提下按插件配置,并由机器级上限统一约束。

影响范围

  • 影响插件 MCP Gateway、Bot 配置解析、会话运行快照和 Codex Gateway 配置生成。
  • Gateway 层能力与单模型或多模型编排无关;环境变量只适用于本地 stdio 插件进程。
  • 未配置时保持 SDK 默认调用超时;机器级上限缺省为 10 分钟。
  • 不涉及业务数据查询、授权写操作、发布或合并。

验证

  • bun run build:通过。
  • bunx vitest run test/global-config.test.ts test/bot-registry-grant.test.ts test/plugin-mcp-gateway-installer.test.ts test/plugin-cli-generation.test.ts:109 项通过。
  • bunx vitest run test/plugin-mcp-gateway.test.ts -t "tool timeout":1 项通过,32 项跳过。
  • 本机重启 3 个 daemon;冷启动会话快照确认插件超时为 600000ms,Codex 外层配置为 600s。
  • 全量测试在本机受既有隔离状态与长时序用例影响,未作为本次通过依据。

@deepcoldy

Copy link
Copy Markdown
Owner

你好,这个 PR 的自动评审群已建,麻烦点击链接加入群聊、查看评审意见并跟进后续修改:
https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=726r3e33-3111-4cc7-840b-da7b22d27c0d

另外你暂时不在自动拉群名单里,也可以把 GitHub 账号和飞书信息补进名单文档,补好后后续评审会自动拉你进群:https://bytedance.larkoffice.com/wiki/WJ1nwWbtxi89erkNGNbcgkt9nUe

(本条为自动流程发出的提示消息)

@deepcoldy

Copy link
Copy Markdown
Owner

自动评审初步意见(最终以维护者审阅为准)。

整体方向、边界(env 经 sanitizePerBotEnv 过滤保留键、只进 0600 快照与 stdio 插件子进程;超机器上限在 refreshSessionMcpRuntimeManifest fail-closed throw;Codex 外层用 Math.ceil 保证不小于内层)都没有问题,我也用真实慢工具插件实测了端到端行为:配置 toolTimeoutMs: 500 时,一个 sleep 3s 的工具调用在 505ms 被以 MCP -32001 中止,env 也确实进入了插件子进程。上游 Codex 兼容性也核实过(tool_timeout_sec 在 rust-v0.40.0 引入;更老版本 serde 未开 deny_unknown_fields 会忽略未知键,不会导致 config.toml 解析失败)。

两点测试相关的建议:

  1. Gateway 超时执行链没有行为测试。 目前只测了纯函数 pluginMcpToolTimeoutOptions,而 snapshot → snapshotGatewayDescriptors → GatewayConnection.toolTimeoutMs → callTool(requestOptions) 这条链上我做了三发删除式变异(拔掉 callTool 的第三个参数、拔掉 requestOptions 里的展开、拔掉 descriptor 映射),现有测试全部存活。也就是未来任何重构把配置超时接断,CI 都会绿,功能静默失效。仓库已有现成 harness(installFixturePlugin + InMemoryTransport),建议加一个 sleep 工具的 fixture,断言配置小超时后 callTool reject 且耗时落在配置值附近(默认不传超时的路径也顺带保留)。

  2. test/bot-registry-grant.test.ts 里 tooLong 这条用例没有测到它想测的分支。 键名 'tooLong' 含大写字母,在插件 id 正则 /^[a-z0-9][a-z0-9._-]{0,63}$/ 处整条就被过滤了,所以 toolTimeoutMs: 2_147_483_648 根本没有走到绝对值上限校验——我把解析处的 <= ABSOLUTE_MAX_MCP_GATEWAY_TOOL_TIMEOUT_MS 删掉后这条测试依然全绿。改成合法 id(如 'toolong')才能真正覆盖该校验。

可选的小项(不阻塞):

  • 读快照侧 readSessionMcpRuntimeManifest 的 toolTimeoutMs 校验没有负例(host 自有 0600 文件,属纵深防御,主流程也写不进超限值)。
  • 插件 id 校验在 bot-registry.ts 内联了一份比 isValidPluginId(src/core/plugins/ids.ts)略宽的正则(允许数字开头),建议直接复用共享谓词,避免后续规则漂移。
  • streamable-http 插件配置的 env 会被静默忽略(文档已说明仅 stdio 生效),如能在解析时给一条 diagnostic 更易排查。
  • resolvePluginGenerationBot 的返回类型 Pick<...> 未包含新增的 'pluginRuntime',运行时依赖 loadBotConfigs() 返回的全量对象带上;回退路径(bots.json 不可读)没有该字段属安全降级,但类型签名建议同步补上。

本地验证:bunx tsc --noEmit、bun run build 通过;5 个改动测试文件 vitest 141/142(唯一失败项在基线提交 b17e043 上同样复现,为本机 vitest 环境的既有 socket flake,bun 引擎下 33/33 通过),bun 引擎 5 文件全绿;CI 首跑 9/9 通过。

@deepcoldy

Copy link
Copy Markdown
Owner

维护者复审完成,以下是合并后的修改清单(首审评论以本条为准;最终仍以维护者审阅为准)。需要改 2 个 P2 + 决定 1 个跨 CLI 项,P3 可选。

必改

1. 给超时执行链补行为测试(P2)

目前只测了纯函数,「快照 toolTimeoutMs → descriptor → GatewayConnection → callTool 传给 MCP SDK」整条链没有任何行为测试:我们做了 6 发删除式/退化变异,现有测试全部存活,意味着以后重构把配置超时接断 CI 不会红。复审时已写好 3 个行为测试(真实 stdio 插件 + InMemoryTransport):

  • per-plugin 超时能中止长调用(断言 <2s 返回,而不是跑满 3s);
  • progress 通知不能延长总时长(验证 maxTotalTimeout 真的生效——这条对应 PR 描述里"配了 progress 也不能超过总时长"的承诺);
  • env 只进入配置它的那个插件子进程(对照插件拿不到)。

打上后 6 发变异在 Node(vitest) 与 bun 两个引擎下全部变红,原有用例保持绿。可直接采用下面的 patch(fixture 加 slow/progress 两个模式):

suggested-tests.patch
diff --git a/test/fixtures/plugin-mcp-server.mjs b/test/fixtures/plugin-mcp-server.mjs
index caa9e69e1e..1c22db7e34 100644
--- a/test/fixtures/plugin-mcp-server.mjs
+++ b/test/fixtures/plugin-mcp-server.mjs
@@ -43,7 +43,20 @@ server.setRequestHandler(ListToolsRequestSchema, request => {
       };
 });
 
-server.setRequestHandler(CallToolRequestSchema, request => {
+server.setRequestHandler(CallToolRequestSchema, async request => {
+  if (serverName === 'slow') await new Promise(r => setTimeout(r, 3000));
+  if (serverName === 'progress') {
+    // Emits progress every 100ms for ~1.9s. Each notification resets the SDK
+    // request timeout, so only maxTotalTimeout can end this call early.
+    const token = request.params?._meta?.progressToken;
+    const startedAt = Date.now();
+    for (let tick = 1; Date.now() - startedAt < 1_900; tick += 1) {
+      await new Promise(r => setTimeout(r, 100));
+      if (token !== undefined) {
+        await server.notification({ method: 'notifications/progress', params: { progressToken: token, progress: tick } });
+      }
+    }
+  }
   if (serverName === 'link-ref') {
     const authorizationUrl = 'https://auth.example.test/authorize'
       + '?code=code-value&token=token-value&signature=sig-value&state=state-value'
diff --git a/test/plugin-mcp-gateway.test.ts b/test/plugin-mcp-gateway.test.ts
index f25a4b4bab..63a59b16a0 100644
--- a/test/plugin-mcp-gateway.test.ts
+++ b/test/plugin-mcp-gateway.test.ts
@@ -53,6 +53,91 @@ describe('plugin MCP Gateway', () => {
     rmSync(home, { recursive: true, force: true });
   });
 
+  it('aborts a downstream tool call at the configured per-plugin timeout', async () => {
+    installFixturePlugin('plugin-slow', 'slow');
+    const dataDir = join(home, '.botmux', 'data');
+    refreshSessionMcpRuntimeManifest({
+      sessionId: 'slow-session',
+      pluginIds: ['plugin-slow'],
+      pluginRuntime: { 'plugin-slow': { toolTimeoutMs: 500 } },
+      dataDir,
+    });
+    const gateway = new PluginMcpGateway(
+      undefined,
+      { ...process.env, SESSION_DATA_DIR: dataDir, BOTMUX_SESSION_ID: 'slow-session' },
+    );
+    const client = new Client({ name: 'gateway-slow-test', version: '1.0.0' });
+    const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+    await Promise.all([gateway.connect(serverTransport), client.connect(clientTransport)]);
+    try {
+      expect((await client.listTools()).tools.map(tool => tool.name)).toContain('echo');
+      const started = Date.now();
+      await expect(client.callTool({ name: 'echo', arguments: {} })).rejects.toThrow();
+      expect(Date.now() - started).toBeLessThan(2_000);
+    } finally {
+      await client.close().catch(() => undefined);
+      await gateway.close();
+    }
+  });
+
+  it('injects per-plugin runtime env into that plugin process only', async () => {
+    installFixturePlugin('plugin-a', 'alpha');
+    installFixturePlugin('plugin-b', 'beta');
+    const dataDir = join(home, '.botmux', 'data');
+    refreshSessionMcpRuntimeManifest({
+      sessionId: 'runtime-env-session',
+      pluginIds: ['plugin-a', 'plugin-b'],
+      pluginRuntime: { 'plugin-a': { env: { PRIVATE_MCP_TOKEN: 'runtime-token' } } },
+      dataDir,
+    });
+    const gateway = new PluginMcpGateway(
+      undefined,
+      { ...process.env, SESSION_DATA_DIR: dataDir, BOTMUX_SESSION_ID: 'runtime-env-session' },
+    );
+    const client = new Client({ name: 'gateway-runtime-env-test', version: '1.0.0' });
+    const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+    await Promise.all([gateway.connect(serverTransport), client.connect(clientTransport)]);
+    try {
+      const withEnv = await client.callTool({ name: 'plugin-a__echo', arguments: {} });
+      expect((withEnv.content[0] as { text: string }).text).toContain('token=runtime-token');
+      const withoutEnv = await client.callTool({ name: 'plugin-b__echo', arguments: {} });
+      expect((withoutEnv.content[0] as { text: string }).text).toMatch(/token=$/);
+    } finally {
+      await client.close().catch(() => undefined);
+      await gateway.close();
+    }
+  });
+
+  it('does not let progress notifications extend a plugin call past its total timeout', async () => {
+    installFixturePlugin('plugin-progress', 'progress');
+    const dataDir = join(home, '.botmux', 'data');
+    refreshSessionMcpRuntimeManifest({
+      sessionId: 'progress-session',
+      pluginIds: ['plugin-progress'],
+      pluginRuntime: { 'plugin-progress': { toolTimeoutMs: 500 } },
+      dataDir,
+    });
+    const gateway = new PluginMcpGateway(
+      undefined,
+      { ...process.env, SESSION_DATA_DIR: dataDir, BOTMUX_SESSION_ID: 'progress-session' },
+    );
+    const client = new Client({ name: 'gateway-progress-test', version: '1.0.0' });
+    const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+    await Promise.all([gateway.connect(serverTransport), client.connect(clientTransport)]);
+    try {
+      const started = Date.now();
+      await expect(client.callTool(
+        { name: 'echo', arguments: {}, _meta: { progressToken: 'progress-token' } },
+        undefined,
+        { timeout: 10_000 },
+      )).rejects.toThrow();
+      expect(Date.now() - started).toBeLessThan(1_500);
+    } finally {
+      await client.close().catch(() => undefined);
+      await gateway.close();
+    }
+  });
+
   it('applies a configured downstream tool timeout without changing the default', () => {
     expect(pluginMcpToolTimeoutOptions(120_000)).toEqual({
       timeout: 120_000,

2. 修掉 test/bot-registry-grant.test.ts 的假覆盖(P2)

用例里键名 'tooLong' 含大写字母,在插件 id 正则处整条被过滤,2_147_483_648 根本没走到绝对值上限分支——删掉 <= ABSOLUTE_MAX_MCP_GATEWAY_TOOL_TIMEOUT_MS 校验该用例仍绿。请改成合法 id(如 'toolong');另外再补一条非整数(如 1.5)被丢弃的用例,否则 Number.isInteger 这一条件也没有覆盖。

需要你决定的一项(跨 CLI)

Claude Code 方向没有对应的外层上限。 Codex 侧写了 tool_timeout_sec,但 gatewayJsonValue(src/core/plugins/mcp/gateway-installer.ts)写 claude-json 时没有 per-server timeout。我们核实了本机 Claude Code 2.1.310:stdio MCP 的看门狗默认 30 分钟空闲中止(CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT ?? 1800000),且 per-server timeout(ms)会同时抬高空闲阈值与总上界;实测 claude mcp get botmux 能正确显示 Timeout: 900000ms。机器上限默认 600000ms 时今天不出事,但合法配置上界是 2^31-1,一旦运维把 mcpGatewayMaxToolTimeoutMs 抬到 30 分钟以上,不发 progress 的长插件调用会先被 Claude 在外层掐断,而内层还在正常跑。

建议与 Codex 对称,一行修复(effectiveMcpGatewayMaxToolTimeoutMs 该文件已 import):

function gatewayJsonValue(entry: GatewayEntry): Record<string, unknown> {
  return {
    type: 'stdio',
    command: entry.command,
    args: entry.args,
    timeout: effectiveMcpGatewayMaxToolTimeoutMs(entry.maxToolTimeoutMs),
    env: { /* 保持现状 */ },
  };
}

并在 installer 的 claude-json 用例里断言 timeout: 600000。如果不打算修,请至少在 docs/plugin-mcp-runtime.md 写明 Claude Code 30 分钟空闲上界这一约束。

可选(P3,不阻塞)

  • 解析期对非法插件 id / 越界 toolTimeoutMs 是静默 filter 丢弃、零 warning(同段代码隔壁字段是会 warn 的);运维手写 999999999999 会不报错地退回 SDK 默认 60s,建议加一条 logger.warn。
  • plugin_mcp_tool_timeout_exceeds_max:... 会原样进会话启动失败卡片,建议像 worker.skill_delivery_failed 一样给一条 i18n 文案,点名 pluginRuntime.toolTimeoutMs 与 mcpGatewayMaxToolTimeoutMs 两个配置项。
  • resolvePluginGenerationBot(src/worker.ts)的返回 Pick<...> 仍未包含 'pluginRuntime'(现在能编过仅因该字段可选);bots.json 读失败的回退路径会静默产出无超时的快照,建议把 Pick 补全。
  • bot-registry.ts 内联的 id 正则比 src/core/plugins/ids.ts 的 isValidPluginId 略宽(允许数字开头,这类 id 不可能对应真实插件),建议直接复用共享谓词。

正面结论:env 边界(只进 stdio 插件子进程、不进模型 CLI)、超限 fail-closed、Codex 侧 ceil 外层≥内层、老版本 codex 对未知 TOML 键的兼容性,以及真机 500ms 超时中止长调用,我们都已独立验证通过。请在当前最新 master 基础上修改后推送,我们会在新 head 上重审,新 head 的 CI 需首跑全绿。

@yousay123

Copy link
Copy Markdown
Contributor Author

本轮已按 review 意见补充验证覆盖,增量如下:

  • 新增从插件配置快照、runtime descriptor、Gateway 到 callTool 的端到端超时测试,验证超时会在真实执行链生效。
  • 补充未配置超时时保持默认行为的覆盖。
  • 将超长插件 ID 用例中的无效标识修正为合法的 toolong,确保测试命中长度边界而非字符格式校验。

验证:

  • env -u BOTMUX_MCP_GATEWAY_REQUIRED -u BOTMUX_MCP_GATEWAY_SOCKET bunx [email protected] x vitest run test/bot-registry-grant.test.ts test/global-config.test.ts test/plugin-cli-generation.test.ts test/plugin-mcp-gateway-installer.test.ts test/plugin-mcp-gateway.test.ts:5 个文件,144 个测试通过。
  • bunx [email protected] run build:通过。

已核验 HEAD:bfd540f9b2fa7449af58cd8319960b15e828ffbf。当前 CI 中 build 及三个 bun binary 检查已通过,其余测试仍在运行。

@yousay123

yousay123 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor Author

本轮已按维护者复审意见完成必改项与跨 CLI 超时对齐,并同步最新 master(561fae3f4549370d7894257099f5bbed0d381a18)。

解决的问题与增量:

  • 新增真实 stdio 插件的 progress 行为测试,验证持续进度通知不能延长 maxTotalTimeout 的绝对总时长。
  • 新增双插件对照测试,验证 runtime env 只注入配置它的插件进程,不会泄漏到其他插件。
  • 为 toolTimeoutMs: 1.5 增加非法非整数覆盖;原超上限用例继续使用合法插件 ID toolong,确保命中数值边界。
  • Claude Code 的 MCP JSON 增加 per-server timeout,取配置后的有效机器上限;测试断言默认写入 600000ms,与 Codex 外层保护对齐。

实际验证:

  • env -u BOTMUX_MCP_GATEWAY_REQUIRED -u BOTMUX_MCP_GATEWAY_SOCKET bunx [email protected] x vitest run test/bot-registry-grant.test.ts test/global-config.test.ts test/plugin-cli-generation.test.ts test/plugin-mcp-gateway-installer.test.ts test/plugin-mcp-gateway.test.ts:5 个文件,146 个测试通过。
  • env -u BOTMUX_MCP_GATEWAY_REQUIRED -u BOTMUX_MCP_GATEWAY_SOCKET bunx [email protected] x vitest run test/plugin-mcp-gateway.test.ts:1 个文件,37 个测试通过(补强耗时下界后复跑)。
  • bunx [email protected] run build:通过。

已核验本地与远端分支 HEAD 一致:efe70f4cf7c718438c0be92f3f88f1d649179835。PR 当前可合并;新 head 的 CI 已触发,当前状态为 pending:run 40437975797。

@deepcoldy

Copy link
Copy Markdown
Owner

你好,这个 PR 的自动评审群已建,麻烦点击链接加入群聊、查看评审意见并跟进后续修改:
https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=285paf23-25b9-46fd-ae5e-ffdb8523b706

另外你暂时不在自动拉群名单里,也可以把 GitHub 账号和飞书信息补进名单文档,补好后后续评审会自动拉你进群:https://bytedance.larkoffice.com/wiki/WJ1nwWbtxi89erkNGNbcgkt9nUe

(本条为自动流程发出的提示消息)

@deepcoldy
deepcoldy merged commit 0e95838 into deepcoldy:master Oct 27, 2026
9 checks passed
@deepcoldy

Copy link
Copy Markdown
Owner

已合并,感谢贡献!

两轮评审提出的超时执行链行为测试、toolong/非整数用例、Claude 侧网关条目对齐 timeout 都已在最终 head 落实并通过验证。

未尽的非阻塞打磨项已汇总到 follow-up issue:#2423(机器级配置到两个 CLI 条目的端到端用例、非法配置解析告警、超限错误文案、resolvePluginGenerationBot 返回类型补全、复用统一的插件 id 校验谓词),欢迎继续认领。

欢迎后续再提 PR。

@github-actions

Copy link
Copy Markdown

🚀 Released in v3.54.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants