@wecom/wecom-openclaw-plugin 1.0.12-beta.0 → 1.0.12-beta.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/dist/index.cjs.js +718 -144
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +722 -150
- package/dist/index.esm.js.map +1 -1
- package/dist/src/const.d.ts +0 -2
- package/dist/src/interface.d.ts +0 -13
- package/dist/src/mcp/index.d.ts +6 -0
- package/dist/src/mcp/schema.d.ts +11 -0
- package/dist/src/mcp/tool.d.ts +51 -0
- package/dist/src/mcp/transport.d.ts +59 -0
- package/dist/src/version.d.ts +2 -0
- package/package.json +3 -3
- package/skills/wecom-contact-lookup/SKILL.md +162 -0
- package/skills/wecom-doc-manager/SKILL.md +64 -0
- package/skills/wecom-doc-manager/references/api-create-doc.md +56 -0
- package/skills/wecom-doc-manager/references/api-edit-doc-content.md +68 -0
- package/skills/wecom-doc-manager/references/api-export-document.md +88 -0
- package/skills/wecom-edit-todo/SKILL.md +249 -0
- package/skills/wecom-get-todo-detail/SKILL.md +143 -0
- package/skills/wecom-get-todo-list/SKILL.md +127 -0
- package/skills/wecom-meeting-create/SKILL.md +158 -0
- package/skills/wecom-meeting-create/references/example-full.md +30 -0
- package/skills/wecom-meeting-create/references/example-reminder.md +46 -0
- package/skills/wecom-meeting-create/references/example-security.md +22 -0
- package/skills/wecom-meeting-manage/SKILL.md +136 -0
- package/skills/wecom-meeting-query/SKILL.md +330 -0
- package/skills/wecom-preflight/SKILL.md +141 -0
- package/skills/wecom-schedule/SKILL.md +159 -0
- package/skills/wecom-schedule/references/api-check-availability.md +56 -0
- package/skills/wecom-schedule/references/api-create-schedule.md +38 -0
- package/skills/wecom-schedule/references/api-get-schedule-detail.md +81 -0
- package/skills/wecom-schedule/references/api-update-schedule.md +30 -0
- package/skills/wecom-schedule/references/ref-reminders.md +24 -0
- package/skills/wecom-smartsheet-data/SKILL.md +71 -0
- package/skills/wecom-smartsheet-data/references/api-get-records.md +61 -0
- package/skills/wecom-smartsheet-data/references/cell-value-formats.md +120 -0
- package/skills/wecom-smartsheet-schema/SKILL.md +92 -0
- package/skills/wecom-smartsheet-schema/references/field-types.md +43 -0
- package/dist/src/mcp-config.d.ts +0 -29
- package/skills/wecom-doc/SKILL.md +0 -363
- package/skills/wecom-doc/references/doc-api.md +0 -224
package/dist/index.cjs.js
CHANGED
|
@@ -10,8 +10,8 @@ var fs = require('node:fs/promises');
|
|
|
10
10
|
var path = require('node:path');
|
|
11
11
|
var os = require('node:os');
|
|
12
12
|
var node_url = require('node:url');
|
|
13
|
-
var url = require('url');
|
|
14
13
|
var fileType = require('file-type');
|
|
14
|
+
var node_fs = require('node:fs');
|
|
15
15
|
|
|
16
16
|
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
17
17
|
function _interopNamespaceDefault(e) {
|
|
@@ -416,10 +416,6 @@ const MEDIA_DOCUMENT_PLACEHOLDER = "<media:document>";
|
|
|
416
416
|
const MCP_GET_CONFIG_CMD = "aibot_get_mcp_config";
|
|
417
417
|
/** MCP 配置拉取超时时间(毫秒) */
|
|
418
418
|
const MCP_CONFIG_FETCH_TIMEOUT_MS = 15000;
|
|
419
|
-
const __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)));
|
|
420
|
-
const __dirname$1 = path$1.dirname(__filename$1);
|
|
421
|
-
const PLUGIN_JSON_FILENAME = "openclaw.plugin.json";
|
|
422
|
-
path$1.resolve(path$1.join(__dirname$1, "../", PLUGIN_JSON_FILENAME));
|
|
423
419
|
// ============================================================================
|
|
424
420
|
// 默认值
|
|
425
421
|
// ============================================================================
|
|
@@ -586,7 +582,7 @@ async function sendWeComReply(params) {
|
|
|
586
582
|
}
|
|
587
583
|
// 使用 SDK 的 replyStream 方法发送消息,带超时保护
|
|
588
584
|
await withTimeout(wsClient.replyStream(frame, streamId, text, finish), REPLY_SEND_TIMEOUT_MS, `Reply send timed out (streamId=${streamId})`);
|
|
589
|
-
runtime.log?.(`[plugin -> server] streamId=${streamId}, finish=${finish}
|
|
585
|
+
runtime.log?.(`[plugin -> server] streamId=${streamId}, finish=${finish}`);
|
|
590
586
|
return streamId;
|
|
591
587
|
}
|
|
592
588
|
|
|
@@ -1577,140 +1573,6 @@ async function cleanupAccount(accountId) {
|
|
|
1577
1573
|
}
|
|
1578
1574
|
}
|
|
1579
1575
|
|
|
1580
|
-
/**
|
|
1581
|
-
* MCP 配置拉取与持久化模块
|
|
1582
|
-
*
|
|
1583
|
-
* 负责:
|
|
1584
|
-
* - 通过 WSClient 发送 aibot_get_mcp_config 请求
|
|
1585
|
-
* - 解析服务端响应,提取 MCP 配置(url、type、is_authed)
|
|
1586
|
-
* - 将配置写入 openclaw.plugin.json 的 wecomMcp 字段
|
|
1587
|
-
*/
|
|
1588
|
-
// ============================================================================
|
|
1589
|
-
// MCP 配置拉取
|
|
1590
|
-
// ============================================================================
|
|
1591
|
-
/**
|
|
1592
|
-
* 通过 WSClient 发送 aibot_get_mcp_config 命令,获取 MCP 配置
|
|
1593
|
-
*
|
|
1594
|
-
* @param wsClient - 已认证的 WSClient 实例
|
|
1595
|
-
* @returns MCP 配置(url、type、is_authed)
|
|
1596
|
-
* @throws 响应错误码非 0 或缺少 url 字段时抛出错误
|
|
1597
|
-
*/
|
|
1598
|
-
async function fetchMcpConfig(wsClient) {
|
|
1599
|
-
const biz_type = "doc";
|
|
1600
|
-
const reqId = aibotNodeSdk.generateReqId("mcp_config");
|
|
1601
|
-
// 通过 reply 方法发送自定义命令
|
|
1602
|
-
const response = await withTimeout(wsClient.reply({ headers: { req_id: reqId } }, { biz_type }, MCP_GET_CONFIG_CMD), MCP_CONFIG_FETCH_TIMEOUT_MS, `MCP config fetch timed out after ${MCP_CONFIG_FETCH_TIMEOUT_MS}ms`);
|
|
1603
|
-
// 校验响应错误码
|
|
1604
|
-
if (response.errcode && response.errcode !== 0) {
|
|
1605
|
-
throw new Error(`MCP config request failed: errcode=${response.errcode}, errmsg=${response.errmsg ?? "unknown"}`);
|
|
1606
|
-
}
|
|
1607
|
-
// 提取并校验 body
|
|
1608
|
-
const body = response.body;
|
|
1609
|
-
if (!body?.url) {
|
|
1610
|
-
throw new Error("MCP config response missing required 'url' field");
|
|
1611
|
-
}
|
|
1612
|
-
return {
|
|
1613
|
-
biz_type,
|
|
1614
|
-
url: body.url,
|
|
1615
|
-
type: body.type,
|
|
1616
|
-
is_authed: body.is_authed,
|
|
1617
|
-
};
|
|
1618
|
-
}
|
|
1619
|
-
// ============================================================================
|
|
1620
|
-
// 配置持久化
|
|
1621
|
-
// ============================================================================
|
|
1622
|
-
/**
|
|
1623
|
-
* 将 MCP 配置写入 openclaw.plugin.json 的 mcpConfig 字段
|
|
1624
|
-
*
|
|
1625
|
-
* 使用 OpenClaw SDK 提供的文件锁和原子写入,保证并发安全。
|
|
1626
|
-
* 配置格式: { mcpConfig: { [type]: { type, url } } }
|
|
1627
|
-
* 示例: { "mcpConfig": { "doc": { "type": "streamable-http", "url": "..." } } }
|
|
1628
|
-
*
|
|
1629
|
-
* @param config - MCP 配置
|
|
1630
|
-
* @param runtime - 运行时环境
|
|
1631
|
-
*/
|
|
1632
|
-
async function saveMcpConfigToPluginJson(config, runtime) {
|
|
1633
|
-
// const pluginJsonPath = PLUGIN_JSON_PATH;
|
|
1634
|
-
// 获取绝对路径并写入到配置文件
|
|
1635
|
-
// const absolutePath = path.resolve(pluginJsonPath);
|
|
1636
|
-
const wecomConfigDir = path$1.join(os$1.homedir(), ".openclaw", "wecomConfig");
|
|
1637
|
-
const wecomConfigPath = path$1.join(wecomConfigDir, "config.json");
|
|
1638
|
-
// // 写入 wecom 配置文件
|
|
1639
|
-
// try {
|
|
1640
|
-
// const lockOptions = {
|
|
1641
|
-
// stale: 60_000,
|
|
1642
|
-
// retries: {
|
|
1643
|
-
// retries: 3,
|
|
1644
|
-
// factor: 1.35,
|
|
1645
|
-
// minTimeout: 8,
|
|
1646
|
-
// maxTimeout: 200,
|
|
1647
|
-
// randomize: true,
|
|
1648
|
-
// },
|
|
1649
|
-
// };
|
|
1650
|
-
// await withFileLock(wecomConfigPath, lockOptions, async () => {
|
|
1651
|
-
// const { value: wecomConfig } = await readJsonFileWithFallback<Record<string, unknown>>(
|
|
1652
|
-
// wecomConfigPath,
|
|
1653
|
-
// {},
|
|
1654
|
-
// );
|
|
1655
|
-
// wecomConfig.pluginConfigPath = absolutePath;
|
|
1656
|
-
// await writeJsonFileAtomically(wecomConfigPath, wecomConfig);
|
|
1657
|
-
// runtime.log?.(`[WeCom] Plugin config path saved to ${wecomConfigPath}`);
|
|
1658
|
-
// });
|
|
1659
|
-
// } catch (err) {
|
|
1660
|
-
// runtime.error?.(`[WeCom] Failed to save plugin config path: ${String(err)}`);
|
|
1661
|
-
// }
|
|
1662
|
-
const lockOptions = {
|
|
1663
|
-
stale: 60000, // 60秒锁过期
|
|
1664
|
-
retries: {
|
|
1665
|
-
retries: 6,
|
|
1666
|
-
factor: 1.35,
|
|
1667
|
-
minTimeout: 8,
|
|
1668
|
-
maxTimeout: 1200,
|
|
1669
|
-
randomize: true,
|
|
1670
|
-
},
|
|
1671
|
-
};
|
|
1672
|
-
await pluginSdk.withFileLock(wecomConfigPath, lockOptions, async () => {
|
|
1673
|
-
// 读取现有配置(不存在时使用空对象)
|
|
1674
|
-
const { value: pluginJson } = await pluginSdk.readJsonFileWithFallback(wecomConfigPath, {});
|
|
1675
|
-
// 确保 mcpConfig 字段存在且为对象
|
|
1676
|
-
if (!pluginJson.mcpConfig || typeof pluginJson.mcpConfig !== 'object') {
|
|
1677
|
-
pluginJson.mcpConfig = {};
|
|
1678
|
-
}
|
|
1679
|
-
// 使用 type 作为键存储配置
|
|
1680
|
-
const typeKey = config.biz_type || 'default';
|
|
1681
|
-
pluginJson.mcpConfig[typeKey] = {
|
|
1682
|
-
type: config.type,
|
|
1683
|
-
url: config.url,
|
|
1684
|
-
};
|
|
1685
|
-
// 原子写入
|
|
1686
|
-
await pluginSdk.writeJsonFileAtomically(wecomConfigPath, pluginJson);
|
|
1687
|
-
runtime.log?.(`[WeCom] MCP config saved to ${wecomConfigPath}`);
|
|
1688
|
-
});
|
|
1689
|
-
}
|
|
1690
|
-
// ============================================================================
|
|
1691
|
-
// 组合入口
|
|
1692
|
-
// ============================================================================
|
|
1693
|
-
/**
|
|
1694
|
-
* 拉取 MCP 配置并持久化到 openclaw.plugin.json
|
|
1695
|
-
*
|
|
1696
|
-
* 认证成功后调用。失败仅记录日志,不影响 WebSocket 消息正常收发。
|
|
1697
|
-
*
|
|
1698
|
-
* @param wsClient - 已认证的 WSClient 实例
|
|
1699
|
-
* @param accountId - 账户 ID(用于日志)
|
|
1700
|
-
* @param runtime - 运行时环境(用于日志)
|
|
1701
|
-
*/
|
|
1702
|
-
async function fetchAndSaveMcpConfig(wsClient, accountId, runtime) {
|
|
1703
|
-
try {
|
|
1704
|
-
runtime.log?.(`[${accountId}] Fetching MCP config...`);
|
|
1705
|
-
const config = await fetchMcpConfig(wsClient);
|
|
1706
|
-
runtime.log?.(`[${accountId}] MCP config fetched: url=${config.url}, type=${config.type ?? "N/A"}, is_authed=${config.is_authed ?? "N/A"}`);
|
|
1707
|
-
await saveMcpConfigToPluginJson(config, runtime);
|
|
1708
|
-
}
|
|
1709
|
-
catch (err) {
|
|
1710
|
-
runtime.error?.(`[${accountId}] Failed to fetch/save MCP config: ${String(err)}`);
|
|
1711
|
-
}
|
|
1712
|
-
}
|
|
1713
|
-
|
|
1714
1576
|
/**
|
|
1715
1577
|
* 企业微信 WebSocket 监控器主模块
|
|
1716
1578
|
*
|
|
@@ -1992,7 +1854,7 @@ async function routeAndDispatchMessage(params) {
|
|
|
1992
1854
|
dispatcherOptions: {
|
|
1993
1855
|
deliver: async (payload, info) => {
|
|
1994
1856
|
state.deliverCalled = true;
|
|
1995
|
-
runtime.log?.(`[openclaw -> plugin] kind=${info.kind}, text=${payload.text ?? ''}, mediaUrl=${payload.mediaUrl ?? ''}, mediaUrls=${JSON.stringify(payload.mediaUrls ?? [])}`);
|
|
1857
|
+
// runtime.log?.(`[openclaw -> plugin] kind=${info.kind}, text=${payload.text ?? ''}, mediaUrl=${payload.mediaUrl ?? ''}, mediaUrls=${JSON.stringify(payload.mediaUrls ?? [])}`);
|
|
1996
1858
|
// 累积文本
|
|
1997
1859
|
if (payload.text) {
|
|
1998
1860
|
accumulateText(state, payload.text);
|
|
@@ -2140,7 +2002,7 @@ async function processWeComMessage(params) {
|
|
|
2140
2002
|
}
|
|
2141
2003
|
// Step 7: 构建上下文并路由到核心处理流程(带整体超时保护)
|
|
2142
2004
|
const ctxPayload = buildMessageContext(frame, account, config, text, mediaList, quoteContent);
|
|
2143
|
-
runtime.log?.(`[plugin -> openclaw] body=${text}, mediaPaths=${JSON.stringify(mediaList.map(m => m.path))}${quoteContent ? `, quote=${quoteContent}` : ''}`);
|
|
2005
|
+
// runtime.log?.(`[plugin -> openclaw] body=${text}, mediaPaths=${JSON.stringify(mediaList.map(m => m.path))}${quoteContent ? `, quote=${quoteContent}` : ''}`);
|
|
2144
2006
|
try {
|
|
2145
2007
|
await withTimeout(routeAndDispatchMessage({
|
|
2146
2008
|
ctxPayload,
|
|
@@ -2239,8 +2101,6 @@ async function monitorWeComProvider(options) {
|
|
|
2239
2101
|
wsClient.on("authenticated", () => {
|
|
2240
2102
|
runtime.log?.(`[${account.accountId}] Authentication successful`);
|
|
2241
2103
|
setWeComWebSocket(account.accountId, wsClient);
|
|
2242
|
-
// 认证成功后自动拉取 MCP 配置(异步,失败不影响主流程)
|
|
2243
|
-
fetchAndSaveMcpConfig(wsClient, account.accountId, runtime);
|
|
2244
2104
|
});
|
|
2245
2105
|
// 监听断开事件
|
|
2246
2106
|
wsClient.on("disconnected", (reason) => {
|
|
@@ -2775,6 +2635,713 @@ const wecomPlugin = {
|
|
|
2775
2635
|
},
|
|
2776
2636
|
};
|
|
2777
2637
|
|
|
2638
|
+
/** 从 package.json 中读取版本号,兼容打包产物和直接运行 .ts 两种场景 */
|
|
2639
|
+
const getVersion = () => {
|
|
2640
|
+
try {
|
|
2641
|
+
// ESM 环境使用 import.meta.url,CJS 环境使用全局 __dirname
|
|
2642
|
+
const currentDir = path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href))));
|
|
2643
|
+
// 直接运行 .ts 时在 src/ 下,打包后在 dist/ 下,都向上一级找 package.json
|
|
2644
|
+
const pkgPath = path.resolve(currentDir, "..", "package.json");
|
|
2645
|
+
const pkg = JSON.parse(node_fs.readFileSync(pkgPath, "utf-8"));
|
|
2646
|
+
return pkg.version ?? "";
|
|
2647
|
+
}
|
|
2648
|
+
catch {
|
|
2649
|
+
return "";
|
|
2650
|
+
}
|
|
2651
|
+
};
|
|
2652
|
+
/** 插件版本号,来源于 package.json */
|
|
2653
|
+
const PLUGIN_VERSION = getVersion();
|
|
2654
|
+
|
|
2655
|
+
/**
|
|
2656
|
+
* MCP Streamable HTTP 传输层模块
|
|
2657
|
+
*
|
|
2658
|
+
* 负责:
|
|
2659
|
+
* - MCP JSON-RPC over HTTP 通信(发送请求、解析响应)
|
|
2660
|
+
* - Streamable HTTP session 生命周期管理(initialize 握手 → Mcp-Session-Id 维护 → 失效重建)
|
|
2661
|
+
* - 自动检测无状态 Server:如果 initialize 响应未返回 Mcp-Session-Id,
|
|
2662
|
+
* 则标记为无状态模式,后续请求跳过握手和 session 管理
|
|
2663
|
+
* - SSE 流式响应解析
|
|
2664
|
+
* - MCP 配置运行时缓存(通过 WSClient 拉取 URL 并缓存在内存中)
|
|
2665
|
+
*/
|
|
2666
|
+
// ============================================================================
|
|
2667
|
+
// 内部状态
|
|
2668
|
+
// ============================================================================
|
|
2669
|
+
/** HTTP 请求超时时间(毫秒) */
|
|
2670
|
+
const HTTP_REQUEST_TIMEOUT_MS = 30000;
|
|
2671
|
+
/** 日志前缀 */
|
|
2672
|
+
const LOG_TAG = "[mcp]";
|
|
2673
|
+
/**
|
|
2674
|
+
* MCP JSON-RPC 错误
|
|
2675
|
+
*
|
|
2676
|
+
* 携带服务端返回的 JSON-RPC error.code,
|
|
2677
|
+
* 用于上层按错误码进行差异化处理(如特定错误码触发缓存清理)。
|
|
2678
|
+
*/
|
|
2679
|
+
class McpRpcError extends Error {
|
|
2680
|
+
constructor(code, message, data) {
|
|
2681
|
+
super(message);
|
|
2682
|
+
this.code = code;
|
|
2683
|
+
this.data = data;
|
|
2684
|
+
this.name = "McpRpcError";
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
/**
|
|
2688
|
+
* MCP HTTP 错误
|
|
2689
|
+
*
|
|
2690
|
+
* 携带 HTTP 状态码,用于精确判断 session 失效(404)等场景,
|
|
2691
|
+
* 避免通过字符串匹配 "404" 导致的误判。
|
|
2692
|
+
*/
|
|
2693
|
+
class McpHttpError extends Error {
|
|
2694
|
+
constructor(statusCode, message) {
|
|
2695
|
+
super(message);
|
|
2696
|
+
this.statusCode = statusCode;
|
|
2697
|
+
this.name = "McpHttpError";
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
/**
|
|
2701
|
+
* 需要清理缓存的 JSON-RPC 错误码集合
|
|
2702
|
+
*
|
|
2703
|
+
* 当 MCP Server 返回以下错误码时,说明服务端状态已发生变化(如配置变更、
|
|
2704
|
+
* 服务重启等),需要清理对应 category 的全部缓存,确保下次请求重新
|
|
2705
|
+
* 拉取配置并重建会话。
|
|
2706
|
+
*
|
|
2707
|
+
* - -32001: 服务不可用(Server Unavailable)
|
|
2708
|
+
* - -32002: 配置已变更(Config Changed)
|
|
2709
|
+
* - -32003: 认证失败(Auth Failed)
|
|
2710
|
+
*/
|
|
2711
|
+
const CACHE_CLEAR_ERROR_CODES = new Set([-32001, -32002, -32003]);
|
|
2712
|
+
/** MCP 配置缓存:category → response.body(完整配置) */
|
|
2713
|
+
const mcpConfigCache = new Map();
|
|
2714
|
+
/** Streamable HTTP 会话缓存:category → session */
|
|
2715
|
+
const mcpSessionCache = new Map();
|
|
2716
|
+
/** 已确认为无状态的 MCP Server 品类集合(跳过后续握手) */
|
|
2717
|
+
const statelessCategories = new Set();
|
|
2718
|
+
/** 正在进行中的 initialize 请求(防止并发重复初始化),key 为 category */
|
|
2719
|
+
const inflightInitRequests = new Map();
|
|
2720
|
+
// ============================================================================
|
|
2721
|
+
// MCP 配置拉取与缓存
|
|
2722
|
+
// ============================================================================
|
|
2723
|
+
/**
|
|
2724
|
+
* 通过 WSClient 拉取指定 category 的 MCP 完整配置
|
|
2725
|
+
*
|
|
2726
|
+
* @param category - MCP 品类名称,如 doc、contact
|
|
2727
|
+
* @returns 完整的 response.body 配置对象(至少包含 url 字段)
|
|
2728
|
+
*/
|
|
2729
|
+
async function fetchMcpConfig(category) {
|
|
2730
|
+
const wsClient = getWeComWebSocket(pluginSdk.DEFAULT_ACCOUNT_ID);
|
|
2731
|
+
if (!wsClient) {
|
|
2732
|
+
throw new Error("WSClient 未连接,无法拉取 MCP 配置");
|
|
2733
|
+
}
|
|
2734
|
+
const reqId = aibotNodeSdk.generateReqId("mcp_config");
|
|
2735
|
+
const response = await withTimeout(wsClient.reply({ headers: { req_id: reqId } }, { biz_type: category, plugin_version: PLUGIN_VERSION }, MCP_GET_CONFIG_CMD), MCP_CONFIG_FETCH_TIMEOUT_MS, `MCP config fetch for "${category}" timed out after ${MCP_CONFIG_FETCH_TIMEOUT_MS}ms`);
|
|
2736
|
+
if (response.errcode !== undefined && response.errcode !== 0) {
|
|
2737
|
+
const errMsg = `MCP 配置请求失败: errcode=${response.errcode}, errmsg=${response.errmsg ?? "unknown"}`;
|
|
2738
|
+
console.error(`${LOG_TAG} ${errMsg}`);
|
|
2739
|
+
throw new Error(errMsg);
|
|
2740
|
+
}
|
|
2741
|
+
const body = response.body;
|
|
2742
|
+
if (!body?.url) {
|
|
2743
|
+
throw new Error(`MCP 配置响应缺少 url 字段 (category="${category}")`);
|
|
2744
|
+
}
|
|
2745
|
+
console.log(`${LOG_TAG} 配置拉取成功 (category="${category}")`);
|
|
2746
|
+
return body;
|
|
2747
|
+
}
|
|
2748
|
+
/**
|
|
2749
|
+
* 获取指定品类的 MCP Server URL
|
|
2750
|
+
*
|
|
2751
|
+
* 优先从内存缓存中读取,未命中时通过 WSClient 拉取并缓存。
|
|
2752
|
+
*
|
|
2753
|
+
* @param category - MCP 品类名称
|
|
2754
|
+
* @returns MCP Server URL
|
|
2755
|
+
*/
|
|
2756
|
+
async function getMcpUrl(category) {
|
|
2757
|
+
// 查内存缓存
|
|
2758
|
+
const cached = mcpConfigCache.get(category);
|
|
2759
|
+
if (cached)
|
|
2760
|
+
return cached.url;
|
|
2761
|
+
// 缓存未命中,通过 WSClient 拉取
|
|
2762
|
+
const body = await fetchMcpConfig(category);
|
|
2763
|
+
// 写入缓存
|
|
2764
|
+
mcpConfigCache.set(category, body);
|
|
2765
|
+
console.log(`${LOG_TAG} getMcpUrl ${category}: ${body.url}`);
|
|
2766
|
+
return body.url;
|
|
2767
|
+
}
|
|
2768
|
+
// ============================================================================
|
|
2769
|
+
// HTTP 底层通信
|
|
2770
|
+
// ============================================================================
|
|
2771
|
+
/**
|
|
2772
|
+
* 发送原始 HTTP 请求到 MCP Server(底层方法)
|
|
2773
|
+
*
|
|
2774
|
+
* 自动携带 Mcp-Session-Id 请求头(如果有),
|
|
2775
|
+
* 并从响应头中更新 sessionId。
|
|
2776
|
+
*/
|
|
2777
|
+
async function sendRawJsonRpc(url, session, body) {
|
|
2778
|
+
const controller = new AbortController();
|
|
2779
|
+
const timeoutId = setTimeout(() => controller.abort(), HTTP_REQUEST_TIMEOUT_MS);
|
|
2780
|
+
const headers = {
|
|
2781
|
+
"Content-Type": "application/json",
|
|
2782
|
+
Accept: "application/json, text/event-stream",
|
|
2783
|
+
};
|
|
2784
|
+
// Streamable HTTP:携带会话 ID
|
|
2785
|
+
if (session.sessionId) {
|
|
2786
|
+
headers["Mcp-Session-Id"] = session.sessionId;
|
|
2787
|
+
}
|
|
2788
|
+
let response;
|
|
2789
|
+
try {
|
|
2790
|
+
response = await fetch(url, {
|
|
2791
|
+
method: "POST",
|
|
2792
|
+
headers,
|
|
2793
|
+
body: JSON.stringify(body),
|
|
2794
|
+
signal: controller.signal,
|
|
2795
|
+
});
|
|
2796
|
+
}
|
|
2797
|
+
catch (err) {
|
|
2798
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
2799
|
+
throw new Error(`MCP 请求超时 (${HTTP_REQUEST_TIMEOUT_MS}ms)`);
|
|
2800
|
+
}
|
|
2801
|
+
throw new Error(`MCP 网络请求失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
2802
|
+
}
|
|
2803
|
+
finally {
|
|
2804
|
+
clearTimeout(timeoutId);
|
|
2805
|
+
}
|
|
2806
|
+
// 从响应头提取新的 sessionId(不直接修改入参,由调用方决定如何更新)
|
|
2807
|
+
const newSessionId = response.headers.get("mcp-session-id");
|
|
2808
|
+
if (!response.ok) {
|
|
2809
|
+
throw new McpHttpError(response.status, `MCP HTTP 请求失败: ${response.status} ${response.statusText}`);
|
|
2810
|
+
}
|
|
2811
|
+
// Streamable HTTP:notification 响应可能无响应体(204 或 content-length: 0)
|
|
2812
|
+
const contentLength = response.headers.get("content-length");
|
|
2813
|
+
if (response.status === 204 || contentLength === "0") {
|
|
2814
|
+
return { response, rpcResult: undefined, newSessionId };
|
|
2815
|
+
}
|
|
2816
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
2817
|
+
// 处理 SSE 流式响应
|
|
2818
|
+
if (contentType.includes("text/event-stream")) {
|
|
2819
|
+
return { response, rpcResult: await parseSseResponse(response), newSessionId };
|
|
2820
|
+
}
|
|
2821
|
+
// 普通 JSON 响应 — 先读取文本,防止空内容导致 JSON.parse 报错
|
|
2822
|
+
const text = await response.text();
|
|
2823
|
+
if (!text.trim()) {
|
|
2824
|
+
return { response, rpcResult: undefined, newSessionId };
|
|
2825
|
+
}
|
|
2826
|
+
const rpc = JSON.parse(text);
|
|
2827
|
+
if (rpc.error) {
|
|
2828
|
+
throw new McpRpcError(rpc.error.code, `MCP 调用错误 [${rpc.error.code}]: ${rpc.error.message}`, rpc.error.data);
|
|
2829
|
+
}
|
|
2830
|
+
return { response, rpcResult: rpc.result, newSessionId };
|
|
2831
|
+
}
|
|
2832
|
+
// ============================================================================
|
|
2833
|
+
// Session 管理
|
|
2834
|
+
// ============================================================================
|
|
2835
|
+
/**
|
|
2836
|
+
* 对指定 URL 执行 Streamable HTTP 的 initialize 握手
|
|
2837
|
+
*
|
|
2838
|
+
* 发送 initialize → 接收 serverInfo → 发送 initialized 通知。
|
|
2839
|
+
* 如果服务端未返回 Mcp-Session-Id,则标记为无状态模式,后续请求跳过 session 管理。
|
|
2840
|
+
*/
|
|
2841
|
+
async function initializeSession(url, category) {
|
|
2842
|
+
const session = { sessionId: null, initialized: false, stateless: false };
|
|
2843
|
+
console.log(`${LOG_TAG} 开始 initialize 握手 (category="${category}")`);
|
|
2844
|
+
// 1. 发送 initialize 请求
|
|
2845
|
+
const initBody = {
|
|
2846
|
+
jsonrpc: "2.0",
|
|
2847
|
+
id: aibotNodeSdk.generateReqId("mcp_init"),
|
|
2848
|
+
method: "initialize",
|
|
2849
|
+
params: {
|
|
2850
|
+
protocolVersion: "2025-03-26",
|
|
2851
|
+
capabilities: {},
|
|
2852
|
+
clientInfo: { name: "wecom_mcp", version: "1.0.0" },
|
|
2853
|
+
},
|
|
2854
|
+
};
|
|
2855
|
+
const { newSessionId: initSessionId } = await sendRawJsonRpc(url, session, initBody);
|
|
2856
|
+
// 用返回的 newSessionId 更新 session(不再依赖副作用修改)
|
|
2857
|
+
if (initSessionId) {
|
|
2858
|
+
session.sessionId = initSessionId;
|
|
2859
|
+
}
|
|
2860
|
+
// 检查服务端是否返回了 Mcp-Session-Id
|
|
2861
|
+
// 如果没有返回,说明该 Server 是无状态实现,无需维护 session
|
|
2862
|
+
if (!session.sessionId) {
|
|
2863
|
+
session.stateless = true;
|
|
2864
|
+
session.initialized = true;
|
|
2865
|
+
statelessCategories.add(category);
|
|
2866
|
+
mcpSessionCache.set(category, session);
|
|
2867
|
+
console.log(`${LOG_TAG} 无状态 Server 确认 (category="${category}")`);
|
|
2868
|
+
return session;
|
|
2869
|
+
}
|
|
2870
|
+
// 2. 发送 initialized 通知(JSON-RPC notification 不带 id 字段)
|
|
2871
|
+
const notifyBody = {
|
|
2872
|
+
jsonrpc: "2.0",
|
|
2873
|
+
method: "notifications/initialized",
|
|
2874
|
+
};
|
|
2875
|
+
// initialized 通知不需要等待响应,但 Streamable HTTP 要求通过 POST 发送
|
|
2876
|
+
const { newSessionId: notifySessionId } = await sendRawJsonRpc(url, session, notifyBody);
|
|
2877
|
+
// 如果 initialized 通知的响应也携带了 sessionId,以最新的为准
|
|
2878
|
+
if (notifySessionId) {
|
|
2879
|
+
session.sessionId = notifySessionId;
|
|
2880
|
+
}
|
|
2881
|
+
session.initialized = true;
|
|
2882
|
+
mcpSessionCache.set(category, session);
|
|
2883
|
+
console.log(`${LOG_TAG} 有状态 Session 建立成功 (category="${category}", sessionId="${session.sessionId}")`);
|
|
2884
|
+
return session;
|
|
2885
|
+
}
|
|
2886
|
+
/**
|
|
2887
|
+
* 获取或创建指定 URL 的 MCP 会话
|
|
2888
|
+
*
|
|
2889
|
+
* - 已确认无状态的 category:直接返回空 session,跳过握手
|
|
2890
|
+
* - 已有可用有状态会话:直接返回缓存
|
|
2891
|
+
* - 其他情况:执行 initialize 握手,并发请求会被合并
|
|
2892
|
+
*/
|
|
2893
|
+
async function getOrCreateSession(url, category) {
|
|
2894
|
+
// 已确认为无状态的 Server,直接返回空 session 跳过握手
|
|
2895
|
+
if (statelessCategories.has(category)) {
|
|
2896
|
+
const cached = mcpSessionCache.get(category);
|
|
2897
|
+
if (cached)
|
|
2898
|
+
return cached;
|
|
2899
|
+
// 首次发现被清除(理论上不会走到这里),重新走握手探测
|
|
2900
|
+
}
|
|
2901
|
+
const cached = mcpSessionCache.get(category);
|
|
2902
|
+
if (cached?.initialized)
|
|
2903
|
+
return cached;
|
|
2904
|
+
// 防止并发重复初始化
|
|
2905
|
+
const inflight = inflightInitRequests.get(category);
|
|
2906
|
+
if (inflight)
|
|
2907
|
+
return inflight;
|
|
2908
|
+
const promise = initializeSession(url, category).finally(() => {
|
|
2909
|
+
inflightInitRequests.delete(category);
|
|
2910
|
+
});
|
|
2911
|
+
inflightInitRequests.set(category, promise);
|
|
2912
|
+
return promise;
|
|
2913
|
+
}
|
|
2914
|
+
// ============================================================================
|
|
2915
|
+
// SSE 解析
|
|
2916
|
+
// ============================================================================
|
|
2917
|
+
/**
|
|
2918
|
+
* 解析 SSE 流式响应,提取最终的 JSON-RPC result
|
|
2919
|
+
*
|
|
2920
|
+
* 按照 SSE 规范,同一事件中的多个 `data:` 行会用换行符拼接。
|
|
2921
|
+
* 空行分隔不同事件,取最后一个完整事件的数据。
|
|
2922
|
+
*/
|
|
2923
|
+
async function parseSseResponse(response) {
|
|
2924
|
+
const text = await response.text();
|
|
2925
|
+
const lines = text.split("\n");
|
|
2926
|
+
// 按 SSE 规范解析:空行分隔事件,同一事件内的 data 行用换行拼接
|
|
2927
|
+
let currentDataParts = [];
|
|
2928
|
+
let lastEventData = "";
|
|
2929
|
+
for (const line of lines) {
|
|
2930
|
+
if (line.startsWith("data: ")) {
|
|
2931
|
+
currentDataParts.push(line.slice(6));
|
|
2932
|
+
}
|
|
2933
|
+
else if (line.startsWith("data:")) {
|
|
2934
|
+
// data: 后无空格时,值为空字符串
|
|
2935
|
+
currentDataParts.push(line.slice(5));
|
|
2936
|
+
}
|
|
2937
|
+
else if (line.trim() === "" && currentDataParts.length > 0) {
|
|
2938
|
+
// 空行表示事件结束,拼接所有 data 行
|
|
2939
|
+
lastEventData = currentDataParts.join("\n").trim();
|
|
2940
|
+
currentDataParts = [];
|
|
2941
|
+
}
|
|
2942
|
+
}
|
|
2943
|
+
// 处理最后一个未以空行结尾的事件
|
|
2944
|
+
if (currentDataParts.length > 0) {
|
|
2945
|
+
lastEventData = currentDataParts.join("\n").trim();
|
|
2946
|
+
}
|
|
2947
|
+
if (!lastEventData) {
|
|
2948
|
+
throw new Error("SSE 响应中未包含有效数据");
|
|
2949
|
+
}
|
|
2950
|
+
try {
|
|
2951
|
+
const rpc = JSON.parse(lastEventData);
|
|
2952
|
+
if (rpc.error) {
|
|
2953
|
+
throw new McpRpcError(rpc.error.code, `MCP 调用错误 [${rpc.error.code}]: ${rpc.error.message}`, rpc.error.data);
|
|
2954
|
+
}
|
|
2955
|
+
return rpc.result;
|
|
2956
|
+
}
|
|
2957
|
+
catch (err) {
|
|
2958
|
+
if (err instanceof SyntaxError) {
|
|
2959
|
+
throw new Error(`SSE 响应解析失败: ${lastEventData.slice(0, 200)}`);
|
|
2960
|
+
}
|
|
2961
|
+
throw err;
|
|
2962
|
+
}
|
|
2963
|
+
}
|
|
2964
|
+
// ============================================================================
|
|
2965
|
+
// 公共 API
|
|
2966
|
+
// ============================================================================
|
|
2967
|
+
/**
|
|
2968
|
+
* 清理指定品类的所有 MCP 缓存(配置、会话、无状态标记)
|
|
2969
|
+
*
|
|
2970
|
+
* 当 MCP Server 返回特定错误码时调用,确保下次请求重新拉取配置并重建会话。
|
|
2971
|
+
*
|
|
2972
|
+
* @param category - MCP 品类名称
|
|
2973
|
+
*/
|
|
2974
|
+
function clearCategoryCache(category) {
|
|
2975
|
+
console.log(`${LOG_TAG} 清理缓存 (category="${category}")`);
|
|
2976
|
+
mcpConfigCache.delete(category);
|
|
2977
|
+
mcpSessionCache.delete(category);
|
|
2978
|
+
statelessCategories.delete(category);
|
|
2979
|
+
inflightInitRequests.delete(category);
|
|
2980
|
+
}
|
|
2981
|
+
/**
|
|
2982
|
+
* 发送 JSON-RPC 请求到 MCP Server(Streamable HTTP 协议)
|
|
2983
|
+
*
|
|
2984
|
+
* 自动管理 session 生命周期:
|
|
2985
|
+
* - 无状态 Server:跳过 session 管理,直接发送请求
|
|
2986
|
+
* - 有状态 Server:首次调用先执行 initialize 握手,session 失效(404)时自动重建并重试
|
|
2987
|
+
*
|
|
2988
|
+
* @param category - MCP 品类名称
|
|
2989
|
+
* @param method - JSON-RPC 方法名
|
|
2990
|
+
* @param params - JSON-RPC 参数
|
|
2991
|
+
* @returns JSON-RPC result
|
|
2992
|
+
*/
|
|
2993
|
+
async function sendJsonRpc(category, method, params) {
|
|
2994
|
+
const url = await getMcpUrl(category);
|
|
2995
|
+
const body = {
|
|
2996
|
+
jsonrpc: "2.0",
|
|
2997
|
+
id: aibotNodeSdk.generateReqId("mcp_rpc"),
|
|
2998
|
+
method,
|
|
2999
|
+
...(params !== undefined ? { params } : {}),
|
|
3000
|
+
};
|
|
3001
|
+
let session = await getOrCreateSession(url, category);
|
|
3002
|
+
try {
|
|
3003
|
+
const { rpcResult, newSessionId } = await sendRawJsonRpc(url, session, body);
|
|
3004
|
+
// 用最新的 sessionId 更新 session
|
|
3005
|
+
if (newSessionId) {
|
|
3006
|
+
session.sessionId = newSessionId;
|
|
3007
|
+
}
|
|
3008
|
+
return rpcResult;
|
|
3009
|
+
}
|
|
3010
|
+
catch (err) {
|
|
3011
|
+
// 特定 JSON-RPC 错误码触发缓存清理(统一在传输层处理,上层无需关心)
|
|
3012
|
+
if (err instanceof McpRpcError && CACHE_CLEAR_ERROR_CODES.has(err.code)) {
|
|
3013
|
+
clearCategoryCache(category);
|
|
3014
|
+
}
|
|
3015
|
+
// 无状态 Server 不存在 session 失效问题,直接抛出错误
|
|
3016
|
+
if (session.stateless)
|
|
3017
|
+
throw err;
|
|
3018
|
+
// 有状态 Server:session 失效时服务端返回 404,需要重新初始化并重试一次
|
|
3019
|
+
// 使用 McpHttpError.statusCode 精确匹配,避免字符串匹配 "404" 导致误判
|
|
3020
|
+
if (err instanceof McpHttpError && err.statusCode === 404) {
|
|
3021
|
+
console.log(`${LOG_TAG} Session 失效 (category="${category}"),开始重建...`);
|
|
3022
|
+
mcpSessionCache.delete(category);
|
|
3023
|
+
// 使用 rebuildSession 合并并发的 session 重建请求,避免竞态条件
|
|
3024
|
+
session = await rebuildSession(url, category);
|
|
3025
|
+
const { rpcResult, newSessionId } = await sendRawJsonRpc(url, session, body);
|
|
3026
|
+
if (newSessionId) {
|
|
3027
|
+
session.sessionId = newSessionId;
|
|
3028
|
+
}
|
|
3029
|
+
return rpcResult;
|
|
3030
|
+
}
|
|
3031
|
+
// 其他错误记录日志后抛出
|
|
3032
|
+
console.error(`${LOG_TAG} RPC 请求失败 (category="${category}", method="${method}"): ${err instanceof Error ? err.message : String(err)}`);
|
|
3033
|
+
throw err;
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
/**
|
|
3037
|
+
* 合并并发的 session 重建请求
|
|
3038
|
+
*
|
|
3039
|
+
* 与 getOrCreateSession 类似,使用 inflightInitRequests 防止
|
|
3040
|
+
* 多个并发请求同时遇到 404 时重复执行 initialize 握手。
|
|
3041
|
+
*/
|
|
3042
|
+
async function rebuildSession(url, category) {
|
|
3043
|
+
const inflight = inflightInitRequests.get(category);
|
|
3044
|
+
if (inflight)
|
|
3045
|
+
return inflight;
|
|
3046
|
+
const promise = initializeSession(url, category).finally(() => {
|
|
3047
|
+
inflightInitRequests.delete(category);
|
|
3048
|
+
});
|
|
3049
|
+
inflightInitRequests.set(category, promise);
|
|
3050
|
+
return promise;
|
|
3051
|
+
}
|
|
3052
|
+
|
|
3053
|
+
/**
|
|
3054
|
+
* MCP Schema 清洗模块
|
|
3055
|
+
*
|
|
3056
|
+
* 负责内联 $ref/$defs 引用并移除 Gemini 不支持的 JSON Schema 关键词,
|
|
3057
|
+
* 防止 Gemini 模型解析 function response 时报 400 错误。
|
|
3058
|
+
*/
|
|
3059
|
+
/** Gemini 不支持的 JSON Schema 关键词 */
|
|
3060
|
+
const GEMINI_UNSUPPORTED_KEYWORDS = new Set([
|
|
3061
|
+
"patternProperties", "additionalProperties", "$schema", "$id", "$ref", "$defs",
|
|
3062
|
+
"definitions", "examples", "minLength", "maxLength", "minimum", "maximum",
|
|
3063
|
+
"multipleOf", "pattern", "format", "minItems", "maxItems", "uniqueItems",
|
|
3064
|
+
"minProperties", "maxProperties",
|
|
3065
|
+
]);
|
|
3066
|
+
/**
|
|
3067
|
+
* 清洗 JSON Schema,内联 $ref 引用并移除 Gemini 不支持的关键词,
|
|
3068
|
+
* 防止 Gemini 模型解析 function response 时报 400 错误。
|
|
3069
|
+
*/
|
|
3070
|
+
function cleanSchemaForGemini(schema) {
|
|
3071
|
+
if (!schema || typeof schema !== "object")
|
|
3072
|
+
return schema;
|
|
3073
|
+
if (Array.isArray(schema))
|
|
3074
|
+
return schema.map(cleanSchemaForGemini);
|
|
3075
|
+
const obj = schema;
|
|
3076
|
+
// 收集 $defs/definitions 用于后续 $ref 内联解析
|
|
3077
|
+
const defs = {
|
|
3078
|
+
...(obj.$defs && typeof obj.$defs === "object" ? obj.$defs : {}),
|
|
3079
|
+
...(obj.definitions && typeof obj.definitions === "object" ? obj.definitions : {}),
|
|
3080
|
+
};
|
|
3081
|
+
return cleanWithDefs(obj, defs, new Set());
|
|
3082
|
+
}
|
|
3083
|
+
function cleanWithDefs(schema, defs, refStack) {
|
|
3084
|
+
if (!schema || typeof schema !== "object")
|
|
3085
|
+
return schema;
|
|
3086
|
+
if (Array.isArray(schema))
|
|
3087
|
+
return schema.map((item) => cleanWithDefs(item, defs, refStack));
|
|
3088
|
+
const obj = schema;
|
|
3089
|
+
// 合并当前层级的 $defs/definitions 到 defs 中
|
|
3090
|
+
if (obj.$defs && typeof obj.$defs === "object") {
|
|
3091
|
+
Object.assign(defs, obj.$defs);
|
|
3092
|
+
}
|
|
3093
|
+
if (obj.definitions && typeof obj.definitions === "object") {
|
|
3094
|
+
Object.assign(defs, obj.definitions);
|
|
3095
|
+
}
|
|
3096
|
+
// 处理 $ref 引用:尝试内联解析
|
|
3097
|
+
if (typeof obj.$ref === "string") {
|
|
3098
|
+
const ref = obj.$ref;
|
|
3099
|
+
if (refStack.has(ref))
|
|
3100
|
+
return {}; // 防止循环引用
|
|
3101
|
+
const match = ref.match(/^#\/(?:\$defs|definitions)\/(.+)$/);
|
|
3102
|
+
if (match && match[1] && defs[match[1]]) {
|
|
3103
|
+
const nextStack = new Set(refStack);
|
|
3104
|
+
nextStack.add(ref);
|
|
3105
|
+
return cleanWithDefs(defs[match[1]], defs, nextStack);
|
|
3106
|
+
}
|
|
3107
|
+
return {}; // 无法解析的 $ref,返回空对象
|
|
3108
|
+
}
|
|
3109
|
+
const cleaned = {};
|
|
3110
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
3111
|
+
if (GEMINI_UNSUPPORTED_KEYWORDS.has(key))
|
|
3112
|
+
continue;
|
|
3113
|
+
if (key === "const") {
|
|
3114
|
+
cleaned.enum = [value];
|
|
3115
|
+
continue;
|
|
3116
|
+
}
|
|
3117
|
+
if (key === "properties" && value && typeof value === "object" && !Array.isArray(value)) {
|
|
3118
|
+
cleaned[key] = Object.fromEntries(Object.entries(value).map(([k, v]) => [
|
|
3119
|
+
k, cleanWithDefs(v, defs, refStack),
|
|
3120
|
+
]));
|
|
3121
|
+
}
|
|
3122
|
+
else if (key === "items" && value) {
|
|
3123
|
+
cleaned[key] = Array.isArray(value)
|
|
3124
|
+
? value.map((item) => cleanWithDefs(item, defs, refStack))
|
|
3125
|
+
: cleanWithDefs(value, defs, refStack);
|
|
3126
|
+
}
|
|
3127
|
+
else if ((key === "anyOf" || key === "oneOf" || key === "allOf") && Array.isArray(value)) {
|
|
3128
|
+
// 过滤掉 null 类型的变体
|
|
3129
|
+
const nonNull = value.filter((v) => {
|
|
3130
|
+
if (!v || typeof v !== "object")
|
|
3131
|
+
return true;
|
|
3132
|
+
const r = v;
|
|
3133
|
+
return r.type !== "null";
|
|
3134
|
+
});
|
|
3135
|
+
if (nonNull.length === 1) {
|
|
3136
|
+
// 只剩一个变体时直接内联
|
|
3137
|
+
const single = cleanWithDefs(nonNull[0], defs, refStack);
|
|
3138
|
+
if (single && typeof single === "object" && !Array.isArray(single)) {
|
|
3139
|
+
Object.assign(cleaned, single);
|
|
3140
|
+
}
|
|
3141
|
+
}
|
|
3142
|
+
else {
|
|
3143
|
+
cleaned[key] = nonNull.map((v) => cleanWithDefs(v, defs, refStack));
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
else {
|
|
3147
|
+
cleaned[key] = value;
|
|
3148
|
+
}
|
|
3149
|
+
}
|
|
3150
|
+
return cleaned;
|
|
3151
|
+
}
|
|
3152
|
+
|
|
3153
|
+
/**
|
|
3154
|
+
* wecom_mcp — 模拟 MCP 调用的 Agent Tool
|
|
3155
|
+
*
|
|
3156
|
+
* 通过 MCP Streamable HTTP 传输协议调用企业微信 MCP Server,
|
|
3157
|
+
* 提供 list(列出所有工具)和 call(调用工具)两个操作。
|
|
3158
|
+
*
|
|
3159
|
+
* 在 skills 中的使用方式:
|
|
3160
|
+
* wecom_mcp list <category>
|
|
3161
|
+
* wecom_mcp call <category> <method> '<jsonArgs>'
|
|
3162
|
+
*
|
|
3163
|
+
* 示例:
|
|
3164
|
+
* wecom_mcp list contact
|
|
3165
|
+
* wecom_mcp call contact getContact '{}'
|
|
3166
|
+
*/
|
|
3167
|
+
// ============================================================================
|
|
3168
|
+
// 响应构造辅助
|
|
3169
|
+
// ============================================================================
|
|
3170
|
+
/** 构造统一的文本响应结构 */
|
|
3171
|
+
const textResult = (data) => ({
|
|
3172
|
+
content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
|
|
3173
|
+
});
|
|
3174
|
+
/** 构造错误响应 */
|
|
3175
|
+
const errorResult = (err) => {
|
|
3176
|
+
// 适配企业微信 API 返回的 { errcode, errmsg } 结构
|
|
3177
|
+
if (err && typeof err === "object" && "errcode" in err) {
|
|
3178
|
+
const { errcode, errmsg } = err;
|
|
3179
|
+
return textResult({ error: errmsg ?? `错误码: ${errcode}`, errcode });
|
|
3180
|
+
}
|
|
3181
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
3182
|
+
return textResult({ error: message });
|
|
3183
|
+
};
|
|
3184
|
+
// ============================================================================
|
|
3185
|
+
// list 操作:列出某品类的所有 MCP 工具
|
|
3186
|
+
// ============================================================================
|
|
3187
|
+
const handleList = async (category) => {
|
|
3188
|
+
const result = await sendJsonRpc(category, "tools/list");
|
|
3189
|
+
const tools = result?.tools ?? [];
|
|
3190
|
+
if (tools.length === 0) {
|
|
3191
|
+
return { message: `品类 "${category}" 下暂无可用工具`, tools: [] };
|
|
3192
|
+
}
|
|
3193
|
+
return {
|
|
3194
|
+
category,
|
|
3195
|
+
count: tools.length,
|
|
3196
|
+
tools: tools.map((t) => ({
|
|
3197
|
+
name: t.name,
|
|
3198
|
+
description: t.description ?? "",
|
|
3199
|
+
// 清洗 inputSchema,内联 $ref/$defs 引用并移除 Gemini 不支持的关键词,
|
|
3200
|
+
// 避免 Gemini 模型解析 function response 时报 400 错误
|
|
3201
|
+
inputSchema: t.inputSchema ? cleanSchemaForGemini(t.inputSchema) : undefined,
|
|
3202
|
+
})),
|
|
3203
|
+
};
|
|
3204
|
+
};
|
|
3205
|
+
// ============================================================================
|
|
3206
|
+
// call 操作:调用某品类的某个 MCP 工具
|
|
3207
|
+
// ============================================================================
|
|
3208
|
+
/**
|
|
3209
|
+
* 需要触发缓存清理的业务错误码集合
|
|
3210
|
+
*
|
|
3211
|
+
* 这些错误码出现在 MCP 工具调用返回的 content 文本中(业务层面),
|
|
3212
|
+
* 与 JSON-RPC 层面的错误码不同,需要在此处额外检测。
|
|
3213
|
+
*
|
|
3214
|
+
* - 850002: 机器人未被授权使用对应能力,需清理缓存以便下次重新拉取配置
|
|
3215
|
+
*/
|
|
3216
|
+
const BIZ_CACHE_CLEAR_ERROR_CODES = new Set([850002]);
|
|
3217
|
+
/**
|
|
3218
|
+
* 检查 tools/call 的返回结果中是否包含需要清理缓存的业务错误码
|
|
3219
|
+
*
|
|
3220
|
+
* MCP Server 可能在正常的 JSON-RPC 响应中返回业务层错误,
|
|
3221
|
+
* 这些错误被包裹在 result.content[].text 中,需要解析后判断。
|
|
3222
|
+
*/
|
|
3223
|
+
const checkBizErrorAndClearCache = (result, category) => {
|
|
3224
|
+
if (!result || typeof result !== "object")
|
|
3225
|
+
return;
|
|
3226
|
+
const { content } = result;
|
|
3227
|
+
if (!Array.isArray(content))
|
|
3228
|
+
return;
|
|
3229
|
+
for (const item of content) {
|
|
3230
|
+
if (item.type !== "text" || !item.text)
|
|
3231
|
+
continue;
|
|
3232
|
+
try {
|
|
3233
|
+
const parsed = JSON.parse(item.text);
|
|
3234
|
+
if (typeof parsed.errcode === "number" && BIZ_CACHE_CLEAR_ERROR_CODES.has(parsed.errcode)) {
|
|
3235
|
+
console.log(`[mcp] 检测到业务错误码 ${parsed.errcode} (category="${category}"),清理缓存`);
|
|
3236
|
+
clearCategoryCache(category);
|
|
3237
|
+
return;
|
|
3238
|
+
}
|
|
3239
|
+
}
|
|
3240
|
+
catch {
|
|
3241
|
+
// text 不是 JSON 格式,跳过
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
};
|
|
3245
|
+
const handleCall = async (category, method, args) => {
|
|
3246
|
+
const result = await sendJsonRpc(category, "tools/call", {
|
|
3247
|
+
name: method,
|
|
3248
|
+
arguments: args,
|
|
3249
|
+
});
|
|
3250
|
+
// 检查业务层错误码,必要时清理缓存
|
|
3251
|
+
checkBizErrorAndClearCache(result, category);
|
|
3252
|
+
return result;
|
|
3253
|
+
};
|
|
3254
|
+
// ============================================================================
|
|
3255
|
+
// 参数解析
|
|
3256
|
+
// ============================================================================
|
|
3257
|
+
/**
|
|
3258
|
+
* 解析 args 参数:支持 JSON 字符串或直接的对象
|
|
3259
|
+
*/
|
|
3260
|
+
const parseArgs = (args) => {
|
|
3261
|
+
if (!args)
|
|
3262
|
+
return {};
|
|
3263
|
+
if (typeof args === "object")
|
|
3264
|
+
return args;
|
|
3265
|
+
try {
|
|
3266
|
+
return JSON.parse(args);
|
|
3267
|
+
}
|
|
3268
|
+
catch (err) {
|
|
3269
|
+
const detail = err instanceof SyntaxError ? err.message : String(err);
|
|
3270
|
+
throw new Error(`args 参数不是合法的 JSON: ${args} (${detail})`);
|
|
3271
|
+
}
|
|
3272
|
+
};
|
|
3273
|
+
// ============================================================================
|
|
3274
|
+
// 工具定义 & 导出
|
|
3275
|
+
// ============================================================================
|
|
3276
|
+
/**
|
|
3277
|
+
* 创建 wecom_mcp Agent Tool 定义
|
|
3278
|
+
*/
|
|
3279
|
+
function createWeComMcpTool() {
|
|
3280
|
+
return {
|
|
3281
|
+
name: "wecom_mcp",
|
|
3282
|
+
label: "企业微信 MCP 工具",
|
|
3283
|
+
description: [
|
|
3284
|
+
"通过 HTTP 直接调用企业微信 MCP Server。",
|
|
3285
|
+
"支持两种操作:",
|
|
3286
|
+
" - list: 列出指定品类的所有 MCP 工具",
|
|
3287
|
+
" - call: 调用指定品类的某个 MCP 工具",
|
|
3288
|
+
"",
|
|
3289
|
+
"使用方式:",
|
|
3290
|
+
" wecom_mcp list <category>",
|
|
3291
|
+
" wecom_mcp call <category> <method> '<jsonArgs>'",
|
|
3292
|
+
"",
|
|
3293
|
+
"示例:",
|
|
3294
|
+
" 列出 contact 品类所有工具:wecom_mcp list contact",
|
|
3295
|
+
" 调用 contact 的 getContact:wecom_mcp call contact getContact '{}'",
|
|
3296
|
+
].join("\n"),
|
|
3297
|
+
parameters: {
|
|
3298
|
+
type: "object",
|
|
3299
|
+
properties: {
|
|
3300
|
+
action: {
|
|
3301
|
+
type: "string",
|
|
3302
|
+
enum: ["list", "call"],
|
|
3303
|
+
description: "操作类型:list(列出工具)或 call(调用工具)",
|
|
3304
|
+
},
|
|
3305
|
+
category: {
|
|
3306
|
+
type: "string",
|
|
3307
|
+
description: "MCP 品类名称,如 doc、contact 等,对应 mcpConfig 中的 key",
|
|
3308
|
+
},
|
|
3309
|
+
method: {
|
|
3310
|
+
type: "string",
|
|
3311
|
+
description: "要调用的 MCP 方法名(action=call 时必填)",
|
|
3312
|
+
},
|
|
3313
|
+
args: {
|
|
3314
|
+
type: ["string", "object"],
|
|
3315
|
+
description: "调用 MCP 方法的参数,可以是 JSON 字符串或对象(action=call 时使用,默认 {})",
|
|
3316
|
+
},
|
|
3317
|
+
},
|
|
3318
|
+
required: ["action", "category"],
|
|
3319
|
+
},
|
|
3320
|
+
async execute(_toolCallId, params) {
|
|
3321
|
+
const p = params;
|
|
3322
|
+
try {
|
|
3323
|
+
switch (p.action) {
|
|
3324
|
+
case "list":
|
|
3325
|
+
return textResult(await handleList(p.category));
|
|
3326
|
+
case "call": {
|
|
3327
|
+
if (!p.method) {
|
|
3328
|
+
return textResult({ error: "action 为 call 时必须提供 method 参数" });
|
|
3329
|
+
}
|
|
3330
|
+
const args = parseArgs(p.args);
|
|
3331
|
+
return textResult(await handleCall(p.category, p.method, args));
|
|
3332
|
+
}
|
|
3333
|
+
default:
|
|
3334
|
+
return textResult({ error: `未知操作类型: ${String(p.action)},支持 list 和 call` });
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
3337
|
+
catch (err) {
|
|
3338
|
+
return errorResult(err);
|
|
3339
|
+
}
|
|
3340
|
+
},
|
|
3341
|
+
};
|
|
3342
|
+
}
|
|
3343
|
+
|
|
3344
|
+
console.log(`[wecom] v${PLUGIN_VERSION} loaded`);
|
|
2778
3345
|
const plugin = {
|
|
2779
3346
|
id: "wecom-openclaw-plugin",
|
|
2780
3347
|
name: "企业微信",
|
|
@@ -2783,6 +3350,13 @@ const plugin = {
|
|
|
2783
3350
|
register(api) {
|
|
2784
3351
|
setWeComRuntime(api.runtime);
|
|
2785
3352
|
api.registerChannel({ plugin: wecomPlugin });
|
|
3353
|
+
// 注册 wecom_mcp:通过 HTTP 直接调用企业微信 MCP Server
|
|
3354
|
+
api.registerTool(createWeComMcpTool(), { name: "wecom_mcp" });
|
|
3355
|
+
// ── Gateway 启动时自动确保 tools.alsoAllow 包含 wecom_mcp ──────────
|
|
3356
|
+
// 在 gateway_start 阶段检测并写入,保证插件安装/更新后首次启动即生效
|
|
3357
|
+
// api.on("gateway_start", async () => {
|
|
3358
|
+
// await ensureToolsAlsoAllow(api);
|
|
3359
|
+
// });
|
|
2786
3360
|
// 注入媒体发送指令和文件大小限制提示词
|
|
2787
3361
|
api.on("before_prompt_build", () => {
|
|
2788
3362
|
return {
|