From 6d92a28e2b4298b0e9c291877022cb24bdb8f02d Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 3 Jun 2026 21:53:02 +0800 Subject: [PATCH] =?UTF-8?q?feat(mcp):=20execution=20mode=20=E2=80=94=20que?= =?UTF-8?q?ry/invoke=20OneBot=20actions=20with=20a=20read/write=20safety?= =?UTF-8?q?=20gate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @snowluma/mcp gains execution alongside the read-only catalog: when SNOWLUMA_MCP_ENDPOINT is set it exposes query_action (read-only actions, readOnlyHint) and, in write mode, invoke_action (any known action, destructiveHint), proxied to a running OneBot instance over HTTP. Without an endpoint it degrades to docs-only. SNOWLUMA_MCP_MODE (docs|read|write) gates tool visibility AND is re-checked in execute(), so an unlisted tool cannot be called; unknown/legacy actions are non-invokable. Read vs write is classified precisely at the source: defineAction/preset gain readOnly (default false = write, the safe default), flowed through describe() into the generated catalog snapshot. 58 actions are marked read-only by what their run() actually does -- name-traps like get_ai_record (publishes to the group), request_decrypt_key (returns a DB key), and download_file (arbitrary URL + disk write) stay writes. The HTTP call is a ~20-line fetch bridge rather than @snowluma/sdk: the SDK's published dist is bundler-only ESM (extensionless imports) that native node cannot load, and the bin stays a plain tsc build. onebot 332 tests pass (readOnly is metadata-only, no behavior change); mcp gains 21 tests for mode gating / read-write routing / envelope passthrough / error mapping. Full workspace typecheck clean; native node smoke verified. --- packages/mcp/src/client.ts | 69 ++++++++ packages/mcp/src/generated/catalog.ts | 138 ++++++++++++++++ packages/mcp/src/server.ts | 134 ++++++--------- packages/mcp/src/tools.ts | 182 +++++++++++++++++++++ packages/mcp/src/types.ts | 4 + packages/mcp/tests/client.test.ts | 39 +++++ packages/mcp/tests/tools.test.ts | 138 ++++++++++++++++ packages/mcp/vitest.config.ts | 2 +- packages/onebot/src/action-kit.ts | 9 + packages/onebot/src/actions/extended.ts | 38 +++++ packages/onebot/src/actions/friend.ts | 2 + packages/onebot/src/actions/group-album.ts | 2 + packages/onebot/src/actions/group-file.ts | 4 + packages/onebot/src/actions/group-info.ts | 6 + packages/onebot/src/actions/info.ts | 5 + packages/onebot/src/actions/message.ts | 1 + 16 files changed, 684 insertions(+), 89 deletions(-) create mode 100644 packages/mcp/src/client.ts create mode 100644 packages/mcp/src/tools.ts create mode 100644 packages/mcp/tests/client.test.ts create mode 100644 packages/mcp/tests/tools.test.ts diff --git a/packages/mcp/src/client.ts b/packages/mcp/src/client.ts new file mode 100644 index 00000000..155a52c1 --- /dev/null +++ b/packages/mcp/src/client.ts @@ -0,0 +1,69 @@ +// Thin HTTP bridge to a running OneBot instance. +// +// The OneBot v11 HTTP action protocol is trivial — POST `{ action, params }` to +// the endpoint, read back the JSON envelope — so the MCP talks to it directly +// with `fetch`. We deliberately do NOT depend on @snowluma/sdk here: its +// published dist is bundler-targeted ESM (extensionless relative imports) that +// native `node` cannot resolve without a bundler, and this package is a plain +// `tsc`-built stdio bin. The wire shape — not a shared client type — is the seam +// (ADR-0005); tests inject a fake `ActionClient` (or a fake `fetch`). + +const DEFAULT_TIMEOUT_MS = 30_000; + +/** OneBot v11 response envelope, passed through to the LLM verbatim. */ +export interface OneBotEnvelope { + status: string; + retcode: number; + data?: unknown; + message?: string; + wording?: string; + echo?: unknown; + [k: string]: unknown; +} + +export interface ActionClient { + /** Send one OneBot action; resolves the full envelope (even on retcode≠0), + * rejects only on transport-level failure (timeout / connection / bad body). */ + call(action: string, params: Record): Promise; +} + +export interface HttpClientOptions { + /** OneBot HTTP endpoint, e.g. http://127.0.0.1:3000/. */ + endpoint: string; + accessToken?: string; + timeoutMs?: number; + /** Injectable fetch for tests; defaults to the global fetch. */ + fetch?: typeof fetch; +} + +export function makeHttpClient(opts: HttpClientOptions): ActionClient { + const fetchImpl = opts.fetch ?? globalThis.fetch; + const timeoutMs = opts.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS; + const headers: Record = { + 'Content-Type': 'application/json', + Accept: 'application/json', + }; + if (opts.accessToken) headers.Authorization = `Bearer ${opts.accessToken}`; + + return { + async call(action, params) { + const res = await fetchImpl(opts.endpoint, { + method: 'POST', + headers, + body: JSON.stringify({ action, params }), + signal: AbortSignal.timeout(timeoutMs), + }); + const text = await res.text(); + let parsed: unknown; + try { + parsed = text ? JSON.parse(text) : null; + } catch { + throw new Error(`OneBot returned non-JSON (HTTP ${res.status})`); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`OneBot returned an unexpected response (HTTP ${res.status})`); + } + return parsed as OneBotEnvelope; + }, + }; +} diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 37df0c15..acccda55 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -7,6 +7,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_del_group_notice", "aliases": [], "summary": "删除群公告(fid 或 notice_id 二选一)", + "readOnly": false, "params": [ { "name": "group_id", @@ -62,6 +63,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_get_group_notice", "aliases": [], "summary": "获取群公告", + "readOnly": true, "params": [ { "name": "group_id", @@ -95,6 +97,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_get_model_show", "aliases": [], "summary": "获取机型展示(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -108,6 +111,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_mark_all_as_read", "aliases": [], "summary": "标记全部已读", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -121,6 +125,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_send_group_notice", "aliases": [], "summary": "发送群公告", + "readOnly": false, "params": [ { "name": "group_id", @@ -202,6 +207,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "_set_model_show", "aliases": [], "summary": "设置机型展示(占位)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -215,6 +221,7 @@ export const ACTIONS: CatalogAction[] = [ "name": ".get_word_slices", "aliases": [], "summary": "分词(未实现)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -228,6 +235,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "bot_exit", "aliases": [], "summary": "退出机器人", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -240,6 +248,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "can_send_image", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -252,6 +261,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "can_send_record", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -264,6 +274,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "cancel_group_album_media_like", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -336,6 +347,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "cancel_group_todo", "aliases": [], "summary": "取消群待办", + "readOnly": false, "params": [ { "name": "group_id", @@ -387,6 +399,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "check_url_safely", "aliases": [], "summary": "检查链接安全性", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -400,6 +413,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "clean_cache", "aliases": [], "summary": "清理缓存", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -413,6 +427,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "click_inline_keyboard_button", "aliases": [], "summary": "点击内联键盘按钮", + "readOnly": false, "params": [ { "name": "group_id", @@ -474,6 +489,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "complete_group_todo", "aliases": [], "summary": "完成群待办", + "readOnly": false, "params": [ { "name": "group_id", @@ -525,6 +541,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "create_collection", "aliases": [], "summary": "创建收藏(未实现)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -538,6 +555,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "create_group_file_folder", "aliases": [], "summary": "创建群文件夹", + "readOnly": false, "params": [ { "name": "group_id", @@ -597,6 +615,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "del_group_album_media", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -658,6 +677,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_essence_msg", "aliases": [], "summary": "移除精华消息", + "readOnly": false, "params": [ { "name": "message_id", @@ -693,6 +713,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_friend", "aliases": [], "summary": "删除好友", + "readOnly": false, "params": [ { "name": "user_id", @@ -739,6 +760,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_group_file", "aliases": [], "summary": "删除群文件", + "readOnly": false, "params": [ { "name": "group_id", @@ -786,6 +808,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_group_file_folder", "aliases": [], "summary": "删除群文件夹", + "readOnly": false, "params": [ { "name": "group_id", @@ -833,6 +856,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_group_folder", "aliases": [], "summary": "删除群文件夹", + "readOnly": false, "params": [ { "name": "group_id", @@ -880,6 +904,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "delete_msg", "aliases": [], "summary": "撤回消息", + "readOnly": false, "params": [ { "name": "message_id", @@ -914,6 +939,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "do_group_album_comment", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -990,6 +1016,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "下载文件(url 或 base64)到 data/downloads", "returns": "{ file }", + "readOnly": false, "params": [ { "name": "url", @@ -1044,6 +1071,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "fetch_custom_face", "aliases": [], "summary": "获取自定义表情", + "readOnly": true, "params": [ { "name": "count", @@ -1074,6 +1102,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "fetch_emoji_like", "aliases": [], "summary": "获取表情回应用户(NapCat 分页)", + "readOnly": true, "params": [ { "name": "message_id", @@ -1154,6 +1183,7 @@ export const ACTIONS: CatalogAction[] = [ "get_record_text" ], "summary": "获取语音转文字结果", + "readOnly": true, "params": [ { "name": "message_id", @@ -1182,6 +1212,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "forward_friend_single_msg", "aliases": [], "summary": "转发单条消息给好友", + "readOnly": false, "params": [ { "name": "message_id", @@ -1231,6 +1262,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "forward_group_single_msg", "aliases": [], "summary": "转发单条消息到群", + "readOnly": false, "params": [ { "name": "message_id", @@ -1280,6 +1312,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "friend_poke", "aliases": [], "summary": "好友拍一拍", + "readOnly": false, "params": [ { "name": "user_id", @@ -1324,6 +1357,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_ai_characters", "aliases": [], "summary": "获取 AI 语音角色", + "readOnly": true, "params": [ { "name": "group_id", @@ -1372,6 +1406,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_ai_record", "aliases": [], "summary": "生成 AI 语音", + "readOnly": false, "params": [ { "name": "group_id", @@ -1448,6 +1483,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_clientkey", "aliases": [], "summary": "获取 clientkey", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1461,6 +1497,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_collection_list", "aliases": [], "summary": "获取收藏列表(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1474,6 +1511,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_cookies", "aliases": [], "summary": "获取 Cookies", + "readOnly": true, "params": [ { "name": "domain", @@ -1502,6 +1540,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_credentials", "aliases": [], "summary": "获取凭证", + "readOnly": true, "params": [ { "name": "domain", @@ -1530,6 +1569,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_csrf_token", "aliases": [], "summary": "获取 CSRF 令牌", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1543,6 +1583,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_emoji_likes", "aliases": [], "summary": "获取表情回应用户", + "readOnly": true, "params": [ { "name": "message_id", @@ -1592,6 +1633,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_essence_msg_list", "aliases": [], "summary": "获取精华消息列表", + "readOnly": true, "params": [ { "name": "group_id", @@ -1625,6 +1667,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_file", "aliases": [], "summary": "获取文件(未实现)", + "readOnly": true, "params": [ { "name": "file_id", @@ -1667,6 +1710,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "获取合并转发消息(id 或 message_id)", "returns": "{ messages }", + "readOnly": true, "params": [ { "name": "id", @@ -1693,6 +1737,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_friend_list", "aliases": [], "summary": "获取好友列表", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1706,6 +1751,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_friend_msg_history", "aliases": [], "summary": "获取好友消息历史", + "readOnly": true, "params": [ { "name": "user_id", @@ -1767,6 +1813,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_friends_with_category", "aliases": [], "summary": "获取分组好友列表", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -1779,6 +1826,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_group_album_list", "aliases": [], + "readOnly": true, "params": [ { "name": "group_id", @@ -1811,6 +1859,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_group_album_media_list", "aliases": [], + "readOnly": true, "params": [ { "name": "group_id", @@ -1871,6 +1920,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_at_all_remain", "aliases": [], "summary": "获取群 @全体成员 剩余次数", + "readOnly": true, "params": [ { "name": "group_id", @@ -1904,6 +1954,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_detail_info", "aliases": [], "summary": "获取群详细信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -1935,6 +1986,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_file_system_info", "aliases": [], "summary": "获取群文件系统信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -1969,6 +2021,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "获取群文件下载链接", "returns": "{ url: string }", + "readOnly": true, "params": [ { "name": "group_id", @@ -2031,6 +2084,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_files_by_folder", "aliases": [], "summary": "获取群子目录文件列表", + "readOnly": true, "params": [ { "name": "group_id", @@ -2090,6 +2144,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_honor_info", "aliases": [], "summary": "获取群荣誉信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -2130,6 +2185,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_ignore_add_request", "aliases": [], "summary": "获取被忽略的入群请求(NapCat)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2143,6 +2199,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_ignored_notifies", "aliases": [], "summary": "获取被过滤的入群请求", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2156,6 +2213,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_info", "aliases": [], "summary": "获取群信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -2202,6 +2260,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_info_ex", "aliases": [], "summary": "获取群信息(扩展)", + "readOnly": true, "params": [ { "name": "group_id", @@ -2233,6 +2292,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_list", "aliases": [], "summary": "获取群列表", + "readOnly": true, "params": [ { "name": "no_cache", @@ -2261,6 +2321,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_member_info", "aliases": [], "summary": "获取群成员信息", + "readOnly": true, "params": [ { "name": "group_id", @@ -2323,6 +2384,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_member_list", "aliases": [], "summary": "获取群成员列表", + "readOnly": true, "params": [ { "name": "group_id", @@ -2369,6 +2431,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_msg_history", "aliases": [], "summary": "获取群消息历史", + "readOnly": true, "params": [ { "name": "group_id", @@ -2432,6 +2495,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_root_files", "aliases": [], "summary": "获取群根目录文件列表", + "readOnly": true, "params": [ { "name": "group_id", @@ -2465,6 +2529,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_shut_list", "aliases": [], "summary": "获取群禁言列表(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2478,6 +2543,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_system_msg", "aliases": [], "summary": "获取群系统消息", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2491,6 +2557,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_image", "aliases": [], "summary": "获取图片信息", + "readOnly": true, "params": [ { "name": "file", @@ -2531,6 +2598,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_login_info", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2544,6 +2612,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_mini_app_ark", "aliases": [], "summary": "获取小程序卡片 ark", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2557,6 +2626,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_msg", "aliases": [], "summary": "获取消息", + "readOnly": true, "params": [ { "name": "message_id", @@ -2592,6 +2662,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_online_clients", "aliases": [], "summary": "获取在线客户端(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2606,6 +2677,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "获取私聊文件下载链接", "returns": "{ url: string }", + "readOnly": true, "params": [ { "name": "user_id", @@ -2665,6 +2737,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_profile_like", "aliases": [], "summary": "获取资料点赞", + "readOnly": true, "params": [ { "name": "user_id", @@ -2725,6 +2798,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_record", "aliases": [], "summary": "获取语音信息", + "readOnly": true, "params": [ { "name": "file", @@ -2768,6 +2842,7 @@ export const ACTIONS: CatalogAction[] = [ "nc_get_rkey" ], "summary": "获取下载 rkey", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2780,6 +2855,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_status", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2793,6 +2869,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_stranger_info", "aliases": [], "summary": "获取陌生人信息", + "readOnly": true, "params": [ { "name": "user_id", @@ -2826,6 +2903,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_unidirectional_friend_list", "aliases": [], "summary": "获取单向好友列表", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2838,6 +2916,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "get_version_info", "aliases": [], + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -2851,6 +2930,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_poke", "aliases": [], "summary": "群拍一拍", + "readOnly": false, "params": [ { "name": "group_id", @@ -2900,6 +2980,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "mark_group_msg_as_read", "aliases": [], "summary": "标记群消息已读", + "readOnly": false, "params": [ { "name": "message_id", @@ -2948,6 +3029,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "mark_msg_as_read", "aliases": [], "summary": "标记消息已读(群聊/私聊自动路由)", + "readOnly": false, "params": [ { "name": "message_id", @@ -2996,6 +3078,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "mark_private_msg_as_read", "aliases": [], "summary": "标记私聊消息已读", + "readOnly": false, "params": [ { "name": "message_id", @@ -3044,6 +3127,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "move_group_file", "aliases": [], "summary": "移动群文件", + "readOnly": false, "params": [ { "name": "group_id", @@ -3119,6 +3203,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "nc_get_packet_status", "aliases": [], "summary": "获取 packet 状态(占位)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -3132,6 +3217,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "nc_get_user_status", "aliases": [], "summary": "获取用户在线/扩展状态", + "readOnly": true, "params": [ { "name": "user_id", @@ -3165,6 +3251,7 @@ export const ACTIONS: CatalogAction[] = [ ".ocr_image" ], "summary": "OCR 图片(未实现)", + "readOnly": true, "params": [], "invariants": [], "inputSchema": { @@ -3178,6 +3265,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "rename_group_file", "aliases": [], "summary": "重命名群文件(未实现)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -3191,6 +3279,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "rename_group_file_folder", "aliases": [], "summary": "重命名群文件夹", + "readOnly": false, "params": [ { "name": "group_id", @@ -3264,6 +3353,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "request_decrypt_key", "aliases": [], "summary": "请求数据库解密密钥", + "readOnly": false, "params": [ { "name": "db_path", @@ -3296,6 +3386,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送合并转发(按 message_type/群号自动路由)", "returns": "{ message_id, res_id, forward_id }", + "readOnly": false, "params": [ { "name": "messages", @@ -3333,6 +3424,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "send_group_ai_record", "aliases": [], "summary": "发送 AI 语音到群", + "readOnly": false, "params": [ { "name": "group_id", @@ -3410,6 +3502,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送群合并转发", "returns": "{ message_id, res_id, forward_id }", + "readOnly": false, "params": [ { "name": "group_id", @@ -3466,6 +3559,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送群消息", "returns": "{ message_id: number }", + "readOnly": false, "params": [ { "name": "group_id", @@ -3524,6 +3618,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "send_like", "aliases": [], "summary": "点赞", + "readOnly": false, "params": [ { "name": "user_id", @@ -3571,6 +3666,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送消息(按 message_type/群号 自动路由群聊或私聊)", "returns": "{ message_id: number }", + "readOnly": false, "params": [ { "name": "message", @@ -3652,6 +3748,7 @@ export const ACTIONS: CatalogAction[] = [ ".send_packet" ], "summary": "发送原始 SSO 包(cmd + hex data)", + "readOnly": false, "params": [ { "name": "cmd", @@ -3709,6 +3806,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "send_poke", "aliases": [], "summary": "拍一拍(群聊/私聊自动路由)", + "readOnly": false, "params": [ { "name": "user_id", @@ -3754,6 +3852,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送私聊合并转发", "returns": "{ message_id, res_id, forward_id }", + "readOnly": false, "params": [ { "name": "user_id", @@ -3808,6 +3907,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "发送私聊消息", "returns": "{ message_id: number }", + "readOnly": false, "params": [ { "name": "user_id", @@ -3864,6 +3964,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_diy_online_status", "aliases": [], "summary": "设置自定义在线状态", + "readOnly": false, "params": [ { "name": "face_id", @@ -3923,6 +4024,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_essence_msg", "aliases": [], "summary": "设置精华消息", + "readOnly": false, "params": [ { "name": "message_id", @@ -3958,6 +4060,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_friend_add_request", "aliases": [], "summary": "处理好友添加请求", + "readOnly": false, "params": [ { "name": "flag", @@ -4002,6 +4105,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_friend_remark", "aliases": [], "summary": "设置好友备注", + "readOnly": false, "params": [ { "name": "user_id", @@ -4045,6 +4149,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_add_option", "aliases": [], "summary": "设置加群选项", + "readOnly": false, "params": [ { "name": "group_id", @@ -4093,6 +4198,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_add_request", "aliases": [], "summary": "处理加群请求", + "readOnly": false, "params": [ { "name": "flag", @@ -4164,6 +4270,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_admin", "aliases": [], "summary": "设置/取消管理员", + "readOnly": false, "params": [ { "name": "group_id", @@ -4225,6 +4332,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "set_group_album_media_like", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -4297,6 +4405,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_anonymous", "aliases": [], "summary": "匿名开关(未实现,返回 ok)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -4310,6 +4419,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_anonymous_ban", "aliases": [], "summary": "匿名禁言(未实现,返回 ok)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -4323,6 +4433,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_ban", "aliases": [], "summary": "禁言群成员(duration=0 解除)", + "readOnly": false, "params": [ { "name": "group_id", @@ -4387,6 +4498,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_card", "aliases": [], "summary": "设置群名片(空字符串清除)", + "readOnly": false, "params": [ { "name": "group_id", @@ -4449,6 +4561,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_kick", "aliases": [], "summary": "踢出群成员", + "readOnly": false, "params": [ { "name": "group_id", @@ -4511,6 +4624,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_kick_members", "aliases": [], "summary": "批量踢出群成员", + "readOnly": false, "params": [ { "name": "group_id", @@ -4579,6 +4693,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_leave", "aliases": [], "summary": "退群", + "readOnly": false, "params": [ { "name": "group_id", @@ -4612,6 +4727,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_name", "aliases": [], "summary": "设置群名", + "readOnly": false, "params": [ { "name": "group_id", @@ -4658,6 +4774,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_portrait", "aliases": [], "summary": "设置群头像", + "readOnly": false, "params": [ { "name": "group_id", @@ -4705,6 +4822,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_reaction", "aliases": [], "summary": "群聊表情回应", + "readOnly": false, "params": [ { "name": "group_id", @@ -4780,6 +4898,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_remark", "aliases": [], "summary": "设置群备注", + "readOnly": false, "params": [ { "name": "group_id", @@ -4823,6 +4942,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_search", "aliases": [], "summary": "允许群被搜索", + "readOnly": false, "params": [ { "name": "group_id", @@ -4858,6 +4978,7 @@ export const ACTIONS: CatalogAction[] = [ "send_group_sign" ], "summary": "群签到", + "readOnly": false, "params": [ { "name": "group_id", @@ -4891,6 +5012,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_special_title", "aliases": [], "summary": "设置群头衔", + "readOnly": false, "params": [ { "name": "group_id", @@ -4953,6 +5075,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_todo", "aliases": [], "summary": "设置群待办", + "readOnly": false, "params": [ { "name": "group_id", @@ -5004,6 +5127,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_group_whole_ban", "aliases": [], "summary": "全员禁言开关", + "readOnly": false, "params": [ { "name": "group_id", @@ -5050,6 +5174,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_input_status", "aliases": [], "summary": "设置输入状态", + "readOnly": false, "params": [ { "name": "user_id", @@ -5094,6 +5219,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_msg_emoji_like", "aliases": [], "summary": "设置消息表情回应", + "readOnly": false, "params": [ { "name": "message_id", @@ -5156,6 +5282,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_online_status", "aliases": [], "summary": "设置在线状态", + "readOnly": false, "params": [ { "name": "status", @@ -5221,6 +5348,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_qq_avatar", "aliases": [], "summary": "设置 QQ 头像", + "readOnly": false, "params": [ { "name": "file", @@ -5252,6 +5380,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_qq_profile", "aliases": [], "summary": "设置 QQ 资料", + "readOnly": false, "params": [ { "name": "nickname", @@ -5289,6 +5418,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_restart", "aliases": [], "summary": "重启(不支持)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -5302,6 +5432,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "set_self_longnick", "aliases": [], "summary": "设置个性签名(longNick/long_nick,严格 string)", + "readOnly": false, "params": [ { "name": "longNick", @@ -5331,6 +5462,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "trans_group_file", "aliases": [], "summary": "转存群文件(未实现)", + "readOnly": false, "params": [], "invariants": [], "inputSchema": { @@ -5345,6 +5477,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "英译中", "returns": "{ words }", + "readOnly": true, "params": [ { "name": "words", @@ -5367,6 +5500,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "upload_forward_msg", "aliases": [], "summary": "上传转发消息", + "readOnly": false, "params": [ { "name": "messages", @@ -5417,6 +5551,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "upload_foward_msg", "aliases": [], "summary": "上传转发消息(别名拼写)", + "readOnly": false, "params": [ { "name": "messages", @@ -5468,6 +5603,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "上传群文件", "returns": "{ file_id: string }", + "readOnly": false, "params": [ { "name": "group_id", @@ -5566,6 +5702,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "upload_image_to_qun_album", "aliases": [], + "readOnly": false, "params": [ { "name": "group_id", @@ -5642,6 +5779,7 @@ export const ACTIONS: CatalogAction[] = [ "aliases": [], "summary": "上传私聊文件", "returns": "{ file_id: string }", + "readOnly": false, "params": [ { "name": "user_id", diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index 57c92fb1..93dc5df7 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -1,10 +1,21 @@ #!/usr/bin/env node -// @snowluma/mcp — a read-only MCP server that exposes the SnowLuma OneBot action -// catalog (docs + per-action JSON Schemas) to LLM clients over stdio. +// @snowluma/mcp — an MCP server for the SnowLuma OneBot action catalog. // -// The catalog is a build-time snapshot (src/generated/catalog.ts), regenerated -// from @snowluma/onebot's live action specs on every build — so it auto-tracks -// action add/remove and ships zero runtime dependency on onebot. +// Two modes in one binary: +// • docs (default, no endpoint): read-only catalog tools (list/get/search/ +// categories) + a catalog resource. Zero contact with any live instance. +// • read / write (when SNOWLUMA_MCP_ENDPOINT is set): the catalog tools PLUS +// execution — query_action (read-only actions) and, in write mode, +// invoke_action (any known action) — proxied to a running OneBot instance +// over HTTP. +// +// Env: +// SNOWLUMA_MCP_ENDPOINT OneBot HTTP endpoint (e.g. http://127.0.0.1:3000/). +// Absent → docs-only (execution tools hidden). +// SNOWLUMA_MCP_TOKEN access token (Bearer) for the endpoint. +// SNOWLUMA_MCP_TIMEOUT_MS per-request timeout (default SDK 30s). +// SNOWLUMA_MCP_MODE docs | read | write. Default: read when an +// endpoint is set, else docs. // // NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr. @@ -18,105 +29,51 @@ import { ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; import { ACTIONS, CATEGORIES } from './generated/catalog.js'; -import type { CatalogAction } from './types.js'; +import { makeHttpClient, type ActionClient } from './client.js'; +import { callTool, computeTools, type Mode } from './tools.js'; const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }; const VERSION = pkg.version; const RESOURCE_URI = 'snowluma://onebot/actions'; -// name + every alias → the action, so get_action accepts aliases too. -const byName = new Map(); -for (const a of ACTIONS) { - for (const n of [a.name, ...a.aliases]) byName.set(n, a); +// ── resolve mode + client from the environment ──────────────────────────── +function resolveRuntime(): { mode: Mode; client?: ActionClient } { + const endpoint = process.env.SNOWLUMA_MCP_ENDPOINT?.trim(); + const token = process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined; + const timeoutRaw = Number(process.env.SNOWLUMA_MCP_TIMEOUT_MS); + const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined; + const requested = process.env.SNOWLUMA_MCP_MODE?.trim().toLowerCase(); + const validRequest = requested === 'docs' || requested === 'read' || requested === 'write' ? requested : undefined; + + if (!endpoint) { + if (validRequest && validRequest !== 'docs') { + console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${validRequest} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`); + } + return { mode: 'docs' }; + } + + const mode: Mode = validRequest ?? 'read'; + if (mode === 'docs') { + // Endpoint set but operator explicitly wants docs-only — honor it. + return { mode: 'docs' }; + } + const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs }); + return { mode, client }; } -/** Lightweight index entry (keeps list/search payloads small). */ -function lite(a: CatalogAction) { - return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases }; -} - -const TOOLS = [ - { - name: 'list_actions', - description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名)。', - inputSchema: { - type: 'object', - properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } }, - additionalProperties: false, - }, - }, - { - name: 'get_action', - description: '获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。', - inputSchema: { - type: 'object', - properties: { name: { type: 'string', description: 'action 名(接受别名)' } }, - required: ['name'], - additionalProperties: false, - }, - }, - { - name: 'search_actions', - description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。', - inputSchema: { - type: 'object', - properties: { query: { type: 'string', description: '关键字' } }, - required: ['query'], - additionalProperties: false, - }, - }, - { - name: 'list_categories', - description: '列出所有分类及其 action 数量。', - inputSchema: { type: 'object', properties: {}, additionalProperties: false }, - }, -]; - -function asText(data: unknown) { - return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] }; -} -function asError(message: string) { - return { content: [{ type: 'text' as const, text: message }], isError: true }; -} +const { mode, client } = resolveRuntime(); const server = new Server( { name: 'snowluma-mcp', version: VERSION }, { capabilities: { tools: {}, resources: {} } }, ); -server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS })); +server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) })); server.setRequestHandler(CallToolRequestSchema, async (req) => { - const name = req.params.name; const args = (req.params.arguments ?? {}) as Record; - switch (name) { - case 'list_actions': { - const category = typeof args.category === 'string' ? args.category : undefined; - const list = ACTIONS.filter((a) => !category || a.category === category).map(lite); - return asText({ count: list.length, actions: list }); - } - case 'get_action': { - const q = typeof args.name === 'string' ? args.name : ''; - const action = byName.get(q); - if (!action) return asError(`未找到 action: ${JSON.stringify(q)}。用 list_actions / search_actions 查可用项。`); - return asText(action); - } - case 'search_actions': { - const q = (typeof args.query === 'string' ? args.query : '').toLowerCase(); - const list = ACTIONS.filter( - (a) => - a.name.toLowerCase().includes(q) || - (a.summary ?? '').toLowerCase().includes(q) || - a.aliases.some((al) => al.toLowerCase().includes(q)), - ).map(lite); - return asText({ count: list.length, actions: list }); - } - case 'list_categories': - return asText(CATEGORIES); - default: - return asError(`未知工具: ${name}`); - } + return callTool(req.params.name, args, { mode, client }); }); server.setRequestHandler(ListResourcesRequestSchema, async () => ({ @@ -145,4 +102,5 @@ server.setRequestHandler(ReadResourceRequestSchema, async (req) => { const transport = new StdioServerTransport(); await server.connect(transport); -console.error(`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories`); +const where = client ? ` → ${process.env.SNOWLUMA_MCP_ENDPOINT?.trim()}` : ''; +console.error(`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}${where}`); diff --git a/packages/mcp/src/tools.ts b/packages/mcp/src/tools.ts new file mode 100644 index 00000000..ca1e21af --- /dev/null +++ b/packages/mcp/src/tools.ts @@ -0,0 +1,182 @@ +// Tool surface for the MCP — kept free of any stdio / transport / env concerns +// so it is directly unit-testable. `server.ts` reads the environment, builds a +// client, and wires `computeTools` / `callTool` into the MCP request handlers. +// +// Two execution tools partition the action space by side-effect: +// • query_action — read-only actions only (readOnlyHint) +// • invoke_action — any known action (destructiveHint, write mode) +// Visibility is gated by `mode`, and `callTool` RE-checks every permission +// (defense in depth: a client may call a tool that was never listed). + +import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js'; +import { ACTIONS, CATEGORIES } from './generated/catalog.js'; +import type { CatalogAction } from './types.js'; +import type { ActionClient } from './client.js'; + +export type Mode = 'docs' | 'read' | 'write'; + +// name + every alias → action, so lookups accept aliases too. +const byName = new Map(); +for (const a of ACTIONS) { + for (const n of [a.name, ...a.aliases]) byName.set(n, a); +} + +/** Lightweight index entry (keeps list/search payloads small). */ +function lite(a: CatalogAction) { + return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases, readOnly: a.readOnly }; +} + +const DOCS_TOOLS: Tool[] = [ + { + name: 'list_actions', + description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读)。', + inputSchema: { + type: 'object', + properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } }, + additionalProperties: false, + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + { + name: 'get_action', + description: '获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回、是否只读,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。', + inputSchema: { + type: 'object', + properties: { name: { type: 'string', description: 'action 名(接受别名)' } }, + required: ['name'], + additionalProperties: false, + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + { + name: 'search_actions', + description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。', + inputSchema: { + type: 'object', + properties: { query: { type: 'string', description: '关键字' } }, + required: ['query'], + additionalProperties: false, + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + { + name: 'list_categories', + description: '列出所有分类及其 action 数量。', + inputSchema: { type: 'object', properties: {}, additionalProperties: false }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, +]; + +const EXEC_INPUT_SCHEMA = { + type: 'object' as const, + properties: { + action: { type: 'string', description: 'action 名(接受别名)。先用 get_action 查它的参数 inputSchema。' }, + params: { type: 'object', description: '该 action 的参数对象', additionalProperties: true }, + }, + required: ['action'], + additionalProperties: false, +}; + +function queryTool(): Tool { + return { + name: 'query_action', + description: '调用一个【只读】OneBot action(如 get_*/can_*)并返回完整响应。仅接受只读 action;写操作请用 invoke_action。', + inputSchema: EXEC_INPUT_SCHEMA, + annotations: { readOnlyHint: true, openWorldHint: true }, + }; +} + +function invokeTool(): Tool { + return { + name: 'invoke_action', + description: '调用一个 OneBot action(可产生副作用:发消息、改群、改资料等)并返回完整响应。仅在写模式可用。', + inputSchema: EXEC_INPUT_SCHEMA, + annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, + }; +} + +/** Tools visible for a given mode: docs always; +query in read/write; +invoke in write. */ +export function computeTools(mode: Mode): Tool[] { + const tools: Tool[] = [...DOCS_TOOLS]; + if (mode === 'read' || mode === 'write') tools.push(queryTool()); + if (mode === 'write') tools.push(invokeTool()); + return tools; +} + +export type ToolResult = CallToolResult; + +function asText(data: unknown): ToolResult { + return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }; +} +function asError(message: string): ToolResult { + return { content: [{ type: 'text', text: message }], isError: true }; +} + +export interface CallCtx { + mode: Mode; + client?: ActionClient; +} + +export async function callTool(name: string, args: Record, ctx: CallCtx): Promise { + switch (name) { + case 'list_actions': { + const category = typeof args.category === 'string' ? args.category : undefined; + const list = ACTIONS.filter((a) => !category || a.category === category).map(lite); + return asText({ count: list.length, actions: list }); + } + case 'get_action': { + const q = typeof args.name === 'string' ? args.name : ''; + const action = byName.get(q); + if (!action) return asError(`未找到 action: ${JSON.stringify(q)}。用 list_actions / search_actions 查可用项。`); + return asText(action); + } + case 'search_actions': { + const q = (typeof args.query === 'string' ? args.query : '').toLowerCase(); + const list = ACTIONS.filter( + (a) => + a.name.toLowerCase().includes(q) || + (a.summary ?? '').toLowerCase().includes(q) || + a.aliases.some((al) => al.toLowerCase().includes(q)), + ).map(lite); + return asText({ count: list.length, actions: list }); + } + case 'list_categories': + return asText(CATEGORIES); + case 'query_action': + return execute(args, ctx, 'read'); + case 'invoke_action': + return execute(args, ctx, 'write'); + default: + return asError(`未知工具: ${name}`); + } +} + +/** Shared execution path for query_action (read) / invoke_action (write). + * Re-checks mode + readOnly routing regardless of which tools were listed. */ +async function execute(args: Record, ctx: CallCtx, kind: 'read' | 'write'): Promise { + if (kind === 'write' && ctx.mode !== 'write') { + return asError('写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。'); + } + if (kind === 'read' && ctx.mode !== 'read' && ctx.mode !== 'write') { + return asError('执行未启用:需配置 SNOWLUMA_MCP_ENDPOINT。'); + } + if (!ctx.client) return asError('未配置 OneBot 端点(SNOWLUMA_MCP_ENDPOINT),无法执行。'); + + const action = typeof args.action === 'string' ? args.action : ''; + const cat = byName.get(action); + if (!cat) return asError(`未知 action: ${JSON.stringify(action)}。用 list_actions / search_actions 查可用项。`); + if (kind === 'read' && !cat.readOnly) { + return asError(`${action} 是写操作,不能用 query_action;请用 invoke_action(需 SNOWLUMA_MCP_MODE=write)。`); + } + + const params = + args.params && typeof args.params === 'object' && !Array.isArray(args.params) + ? (args.params as Record) + : {}; + try { + const envelope = await ctx.client.call(action, params); + return asText(envelope); + } catch (err) { + return asError(`调用失败: ${err instanceof Error ? err.message : String(err)}`); + } +} diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts index 92334a01..65c176cb 100644 --- a/packages/mcp/src/types.ts +++ b/packages/mcp/src/types.ts @@ -21,6 +21,10 @@ export interface CatalogAction { category?: string; summary?: string; returns?: string; + /** True only for pure data-fetch actions (no side effects). Drives the + * read/write tool routing: read-only → query_action, else → invoke_action. + * Classified at the source spec by what the action's `run` actually does. */ + readOnly: boolean; params: CatalogParam[]; /** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */ invariants: string[]; diff --git a/packages/mcp/tests/client.test.ts b/packages/mcp/tests/client.test.ts new file mode 100644 index 00000000..28994e67 --- /dev/null +++ b/packages/mcp/tests/client.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect } from 'vitest'; +import { makeHttpClient } from '../src/client'; + +// Verifies the HTTP bridge: a OneBot action becomes a POST of `{ action, params }` +// to the endpoint (with Bearer auth), and the JSON envelope comes back verbatim. +// A fake fetch stands in for the network. +describe('makeHttpClient — OneBot HTTP wiring', () => { + it('POSTs {action, params} to the endpoint and returns the parsed envelope', async () => { + const calls: Array<{ url: string; body: any; auth?: string }> = []; + const fakeFetch = (async (url: unknown, init: any) => { + calls.push({ + url: String(url), + body: JSON.parse(init.body as string), + auth: (init.headers as Record)?.Authorization, + }); + return new Response(JSON.stringify({ status: 'ok', retcode: 0, data: { ok: true } }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }) as unknown as typeof fetch; + + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', accessToken: 'tok', fetch: fakeFetch }); + const env = await client.call('get_status', { x: 1 }); + + expect(env.status).toBe('ok'); + expect(env.retcode).toBe(0); + expect(calls).toHaveLength(1); + expect(calls[0].url).toBe('http://127.0.0.1:9999/'); + expect(calls[0].body.action).toBe('get_status'); + expect(calls[0].body.params).toEqual({ x: 1 }); + expect(calls[0].auth).toBe('Bearer tok'); + }); + + it('propagates a transport failure as a rejection (so the tool layer can map it)', async () => { + const fakeFetch = (async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + await expect(client.call('get_status', {})).rejects.toThrow(); + }); +}); diff --git a/packages/mcp/tests/tools.test.ts b/packages/mcp/tests/tools.test.ts new file mode 100644 index 00000000..800d4c23 --- /dev/null +++ b/packages/mcp/tests/tools.test.ts @@ -0,0 +1,138 @@ +import { describe, it, expect } from 'vitest'; +import { computeTools, callTool } from '../src/tools'; +import type { ActionClient, OneBotEnvelope } from '../src/client'; + +type Res = Awaited>; +function text(res: Res): string { + const block = res.content?.[0]; + return block && block.type === 'text' ? block.text : ''; +} +function parsed(res: Res): any { + return JSON.parse(text(res)); +} + +/** A fake ActionClient — no transport. Records the last call and returns a + * canned envelope (overridable per test). */ +function fakeClient(impl?: (action: string, params: Record) => OneBotEnvelope): ActionClient { + return { + call: async (action, params) => impl?.(action, params) ?? { status: 'ok', retcode: 0, data: { action, params } }, + }; +} + +describe('computeTools — mode gating', () => { + it('docs mode exposes only the 4 catalog tools', () => { + expect(computeTools('docs').map((t) => t.name)).toEqual([ + 'list_actions', 'get_action', 'search_actions', 'list_categories', + ]); + }); + it('read mode adds query_action only (no invoke_action)', () => { + const names = computeTools('read').map((t) => t.name); + expect(names).toContain('query_action'); + expect(names).not.toContain('invoke_action'); + }); + it('write mode adds both query_action and invoke_action', () => { + const names = computeTools('write').map((t) => t.name); + expect(names).toContain('query_action'); + expect(names).toContain('invoke_action'); + }); + it('annotations are honest: query=readOnly, invoke=destructive', () => { + const q = computeTools('write').find((t) => t.name === 'query_action'); + const inv = computeTools('write').find((t) => t.name === 'invoke_action'); + expect(q?.annotations?.readOnlyHint).toBe(true); + expect(inv?.annotations?.readOnlyHint).toBe(false); + expect(inv?.annotations?.destructiveHint).toBe(true); + }); +}); + +describe('callTool — docs tools (no client needed)', () => { + it('list_actions returns entries that carry readOnly', async () => { + const data = parsed(await callTool('list_actions', {}, { mode: 'docs' })); + expect(data.count).toBeGreaterThan(100); + expect(typeof data.actions[0].readOnly).toBe('boolean'); + }); + it('get_action resolves a known read-only action', async () => { + const a = parsed(await callTool('get_action', { name: 'get_status' }, { mode: 'docs' })); + expect(a.name).toBe('get_status'); + expect(a.readOnly).toBe(true); + }); + it('get_action on a write action reports readOnly=false', async () => { + expect(parsed(await callTool('get_action', { name: 'send_group_msg' }, { mode: 'docs' })).readOnly).toBe(false); + }); + it('get_action accepts an alias', async () => { + // nc_get_rkey is an alias of get_rkey (read-only). + const a = parsed(await callTool('get_action', { name: 'nc_get_rkey' }, { mode: 'docs' })); + expect(a.name).toBe('get_rkey'); + }); +}); + +describe('callTool — query_action (read)', () => { + it('executes a read-only action and passes the envelope through', async () => { + const res = await callTool('query_action', { action: 'get_status', params: {} }, { mode: 'read', client: fakeClient() }); + expect(res.isError).toBeFalsy(); + expect(parsed(res).retcode).toBe(0); + }); + it('refuses a write action and points to invoke_action', async () => { + const res = await callTool('query_action', { action: 'send_group_msg', params: {} }, { mode: 'read', client: fakeClient() }); + expect(res.isError).toBe(true); + expect(text(res)).toContain('invoke_action'); + }); + it('refuses an unknown action', async () => { + const res = await callTool('query_action', { action: 'no_such_action' }, { mode: 'read', client: fakeClient() }); + expect(res.isError).toBe(true); + expect(text(res)).toContain('未知 action'); + }); + it('is blocked in docs mode even when called directly (defense in depth)', async () => { + const res = await callTool('query_action', { action: 'get_status' }, { mode: 'docs' }); + expect(res.isError).toBe(true); + }); + it('errors clearly when no client is wired', async () => { + const res = await callTool('query_action', { action: 'get_status' }, { mode: 'read' }); + expect(res.isError).toBe(true); + expect(text(res)).toContain('未配置'); + }); +}); + +describe('callTool — invoke_action (write)', () => { + it('executes a write action in write mode and forwards action+params', async () => { + let seen: { action: string; params: Record } | null = null; + const client: ActionClient = { + call: async (action, params) => { + seen = { action, params }; + return { status: 'ok', retcode: 0, data: { message_id: 42 } }; + }, + }; + const res = await callTool('invoke_action', { action: 'send_group_msg', params: { group_id: 1, message: 'hi' } }, { mode: 'write', client }); + expect(res.isError).toBeFalsy(); + expect(seen!.action).toBe('send_group_msg'); + expect(seen!.params).toEqual({ group_id: 1, message: 'hi' }); + expect(parsed(res).data.message_id).toBe(42); + }); + it('is blocked in read mode (write gate cannot be bypassed)', async () => { + const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'read', client: fakeClient() }); + expect(res.isError).toBe(true); + expect(text(res)).toContain('写操作未启用'); + }); + it('passes a retcode≠0 envelope through as data, NOT isError', async () => { + const client = fakeClient(() => ({ status: 'failed', retcode: 1404, message: 'not found', wording: '未找到' })); + const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client }); + expect(res.isError).toBeFalsy(); + expect(parsed(res).retcode).toBe(1404); + expect(parsed(res).wording).toBe('未找到'); + }); + it('maps a transport-level throw to isError', async () => { + const client: ActionClient = { call: async () => { throw new Error('connection refused'); } }; + const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client }); + expect(res.isError).toBe(true); + expect(text(res)).toContain('调用失败'); + expect(text(res)).toContain('connection refused'); + }); + it('accepts a read-only action too (invoke is a superset)', async () => { + const res = await callTool('invoke_action', { action: 'get_status', params: {} }, { mode: 'write', client: fakeClient() }); + expect(res.isError).toBeFalsy(); + }); + it('refuses an unknown action (typo safety)', async () => { + const res = await callTool('invoke_action', { action: 'frobnicate' }, { mode: 'write', client: fakeClient() }); + expect(res.isError).toBe(true); + expect(text(res)).toContain('未知 action'); + }); +}); diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts index 20b7342c..3a164bb3 100644 --- a/packages/mcp/vitest.config.ts +++ b/packages/mcp/vitest.config.ts @@ -8,7 +8,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ plugins: [protobufVitePlugin()], test: { - include: ['scripts/**/*.test.ts'], + include: ['scripts/**/*.test.ts', 'tests/**/*.test.ts'], environment: 'node', env: { SNOWLUMA_LOG_FILE: '0', diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index d3944431..04ad724e 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -331,6 +331,9 @@ export interface ActionDoc { category?: string; summary?: string; returns?: string; + /** True only for pure data-fetch actions (no side effects). Drives the MCP's + * read/write tool routing; defaults to false (treated as a write). */ + readOnly: boolean; params: ParamDoc[]; invariants: string[]; /** Composed JSON Schema for the whole params object (properties + required). */ @@ -355,6 +358,10 @@ interface ActionDef { name: string | readonly [string, ...string[]]; summary?: string; returns?: string; + /** Mark true ONLY for pure data-fetch actions with no side effects. Default + * false = write. Surfaced via describe() into the catalog for the MCP's + * read/write routing. Classify by what `run` actually does, not the name. */ + readOnly?: boolean; params: S; rules?: (r: RuleBuilders>) => readonly CrossFieldRule[]; /** `raw` is the original untouched params — an escape hatch for the @@ -418,6 +425,7 @@ export function defineAction(def: ActionDef): ActionSpec { aliases: names.slice(1), summary: def.summary, returns: def.returns, + readOnly: def.readOnly ?? false, params: entries.map(([name, field]) => ({ name, ...field.doc })), invariants: rules.map((rule) => rule.doc), inputSchema, @@ -442,6 +450,7 @@ interface PresetDef { name: string | readonly [string, ...string[]]; summary?: string; returns?: string; + readOnly?: boolean; params?: S; rules?: (r: RuleBuilders & Extra>) => readonly CrossFieldRule[]; run: (p: InferParams & Extra, ctx: ApiActionContext, raw: JsonObject) => Promise | ApiResponse; diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index f2818d4b..d8cb20af 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -174,6 +174,7 @@ export const actions = [ groupAction({ name: 'get_essence_msg_list', summary: '获取精华消息列表', + readOnly: true, run: async (p, ctx) => { try { const essenceDataAll = await ctx.bridge.apis.web.getEssenceAll(p.group_id); @@ -216,6 +217,7 @@ export const actions = [ groupAction({ name: 'get_group_msg_history', summary: '获取群消息历史', + readOnly: true, params: { // 原实现用 `asNumber(message_id) || 0`,present 0 也映射为 0。 message_id: f.int({ min: 0 }).default(0), @@ -230,6 +232,7 @@ export const actions = [ defineAction({ name: 'get_friend_msg_history', summary: '获取好友消息历史', + readOnly: true, params: { user_id: f.uint(), message_id: f.int({ min: 0 }).default(0), @@ -341,6 +344,7 @@ export const actions = [ groupAction({ name: '_get_group_notice', summary: '获取群公告', + readOnly: true, run: async (p, ctx) => { try { const notices = await ctx.bridge.apis.web.getNotice(p.group_id); @@ -397,6 +401,7 @@ export const actions = [ defineAction({ name: 'get_image', summary: '获取图片信息', + readOnly: true, params: { file: f.string().default(''), file_id: f.string().default(''), @@ -413,6 +418,7 @@ export const actions = [ defineAction({ name: 'get_record', summary: '获取语音信息', + readOnly: true, params: { file: f.string().default(''), file_id: f.string().default(''), @@ -430,6 +436,7 @@ export const actions = [ // Primary name matches NapCat for drop-in migration; the rest are aliases. name: ['fetch_ptt_text', 'get_ptt_text', 'get_record_text'], summary: '获取语音转文字结果', + readOnly: true, params: { message_id: f.string().default(''), }, @@ -449,6 +456,7 @@ export const actions = [ defineAction({ name: 'get_cookies', summary: '获取 Cookies', + readOnly: true, params: { domain: f.string().default('qun.qq.com') }, run: async (p, ctx) => { try { @@ -463,6 +471,7 @@ export const actions = [ defineAction({ name: 'get_csrf_token', summary: '获取 CSRF 令牌', + readOnly: true, params: {}, run: async (_p, ctx) => { try { @@ -477,6 +486,7 @@ export const actions = [ defineAction({ name: 'get_credentials', summary: '获取凭证', + readOnly: true, params: { domain: f.string().default('qun.qq.com') }, run: async (p, ctx) => { try { @@ -560,6 +570,7 @@ export const actions = [ groupAction({ name: 'get_group_file_system_info', summary: '获取群文件系统信息', + readOnly: true, run: async (p, ctx) => { const info = await ctx.bridge.apis.groupFile.getCount(p.group_id); return okResponse({ @@ -574,6 +585,7 @@ export const actions = [ defineAction({ name: 'check_url_safely', summary: '检查链接安全性', + readOnly: true, params: {}, run: async () => { return okResponse({ level: 1 }); @@ -644,6 +656,7 @@ export const actions = [ defineAction({ name: 'get_group_ignored_notifies', summary: '获取被过滤的入群请求', + readOnly: true, params: {}, run: async (_p, ctx) => { const reqs = await fetchFilteredGroupRequests(ctx); @@ -669,6 +682,7 @@ export const actions = [ defineAction({ name: 'get_group_ignore_add_request', summary: '获取被忽略的入群请求(NapCat)', + readOnly: true, params: {}, run: async (_p, ctx) => { const reqs = await fetchFilteredGroupRequests(ctx); @@ -691,6 +705,7 @@ export const actions = [ defineAction({ name: 'get_group_shut_list', summary: '获取群禁言列表(占位)', + readOnly: true, params: {}, run: async () => { return okResponse([]); @@ -734,6 +749,7 @@ export const actions = [ defineAction({ name: 'get_profile_like', summary: '获取资料点赞', + readOnly: true, params: { // 原实现 user_id 经 asNumber,无校验(0 也透传)。 user_id: f.int({ min: 0 }).default(0), @@ -753,6 +769,7 @@ export const actions = [ defineAction({ name: 'fetch_custom_face', summary: '获取自定义表情', + readOnly: true, params: { count: f.int({ min: 0 }).default(10) }, run: async (p, ctx) => { try { @@ -767,6 +784,7 @@ export const actions = [ defineAction({ name: 'get_emoji_likes', summary: '获取表情回应用户', + readOnly: true, params: { message_id: f.messageId(), emoji_id: f.string({ allowEmpty: false }), @@ -786,6 +804,7 @@ export const actions = [ defineAction({ name: 'fetch_emoji_like', summary: '获取表情回应用户(NapCat 分页)', + readOnly: true, params: { message_id: f.messageId(), emojiId: f.string({ allowEmpty: false }), @@ -815,6 +834,7 @@ export const actions = [ defineAction({ name: 'get_friends_with_category', summary: '获取分组好友列表', + readOnly: true, params: {}, run: async (_p, ctx) => { if (ctx.getFriendList) { @@ -828,6 +848,7 @@ export const actions = [ defineAction({ name: 'get_online_clients', summary: '获取在线客户端(占位)', + readOnly: true, params: {}, run: async () => { return okResponse({ clients: [] }); @@ -837,6 +858,7 @@ export const actions = [ defineAction({ name: '_get_model_show', summary: '获取机型展示(占位)', + readOnly: true, params: {}, run: async () => { return okResponse({ variants: [] }); @@ -855,6 +877,7 @@ export const actions = [ groupAction({ name: 'get_group_at_all_remain', summary: '获取群 @全体成员 剩余次数', + readOnly: true, run: async (p, ctx) => { try { const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id); @@ -868,6 +891,7 @@ export const actions = [ defineAction({ name: 'get_unidirectional_friend_list', summary: '获取单向好友列表', + readOnly: true, params: {}, run: async (_p, ctx) => { try { @@ -882,6 +906,7 @@ export const actions = [ defineAction({ name: 'get_clientkey', summary: '获取 clientkey', + readOnly: true, params: {}, run: async (_p, ctx) => { const clientKeyInfo = await ctx.bridge.apis.web.forceFetchClientKey(); @@ -895,6 +920,7 @@ export const actions = [ defineAction({ name: 'get_collection_list', summary: '获取收藏列表(占位)', + readOnly: true, params: {}, run: async () => { return okResponse([]); @@ -913,6 +939,7 @@ export const actions = [ defineAction({ name: '.get_word_slices', summary: '分词(未实现)', + readOnly: true, params: {}, run: async () => { return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); @@ -954,6 +981,7 @@ export const actions = [ defineAction({ name: 'get_group_info_ex', summary: '获取群信息(扩展)', + readOnly: true, params: { group_id: f.uint() }, run: async (p, ctx) => { if (ctx.getGroupInfo) { @@ -966,6 +994,7 @@ export const actions = [ defineAction({ name: 'get_group_detail_info', summary: '获取群详细信息', + readOnly: true, params: { group_id: f.uint() }, run: async (p, ctx) => { if (ctx.getGroupInfo) { @@ -996,6 +1025,7 @@ export const actions = [ defineAction({ name: 'get_file', summary: '获取文件(未实现)', + readOnly: true, params: { file_id: f.string().default(''), file: f.string().default(''), @@ -1021,6 +1051,7 @@ export const actions = [ defineAction({ name: 'nc_get_packet_status', summary: '获取 packet 状态(占位)', + readOnly: true, params: {}, run: async () => { return okResponse(null); @@ -1044,6 +1075,7 @@ export const actions = [ defineAction({ name: 'nc_get_user_status', summary: '获取用户在线/扩展状态', + readOnly: true, params: { user_id: f.uint() }, run: async (p, ctx) => { const status = await ctx.bridge.apis.extras.getStrangerStatus(p.user_id); @@ -1056,6 +1088,7 @@ export const actions = [ groupAction({ name: 'get_ai_characters', summary: '获取 AI 语音角色', + readOnly: true, params: { chat_type: f.int({ min: 0 }).default(1) }, run: async (p, ctx) => { try { @@ -1149,6 +1182,7 @@ export const actions = [ defineAction({ name: ['get_rkey', 'nc_get_rkey'], summary: '获取下载 rkey', + readOnly: true, params: {}, run: async (_p, ctx) => ctx.getDownloadRKeys @@ -1159,6 +1193,7 @@ export const actions = [ defineAction({ name: ['ocr_image', '.ocr_image'], summary: 'OCR 图片(未实现)', + readOnly: true, params: {}, run: () => failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'), }), @@ -1238,6 +1273,7 @@ export const actions = [ defineAction({ name: 'get_forward_msg', summary: '获取合并转发消息(id 或 message_id)', + readOnly: true, returns: '{ messages }', params: { id: f.string().optional() }, run: async (p, ctx, raw) => { @@ -1314,6 +1350,7 @@ export const actions = [ defineAction({ name: 'translate_en2zh', summary: '英译中', + readOnly: true, returns: '{ words }', params: { words: f.raw() }, run: async (p, ctx) => { @@ -1348,6 +1385,7 @@ export const actions = [ defineAction({ name: 'get_mini_app_ark', summary: '获取小程序卡片 ark', + readOnly: true, params: {}, run: async (_p, ctx, raw) => { const type = raw.type || 'bili'; diff --git a/packages/onebot/src/actions/friend.ts b/packages/onebot/src/actions/friend.ts index f1ca2b02..93189af2 100644 --- a/packages/onebot/src/actions/friend.ts +++ b/packages/onebot/src/actions/friend.ts @@ -6,6 +6,7 @@ export const actions = [ defineAction({ name: 'get_friend_list', summary: '获取好友列表', + readOnly: true, params: {}, run: async (_p, ctx) => { if (ctx.getFriendList) { @@ -18,6 +19,7 @@ export const actions = [ defineAction({ name: 'get_stranger_info', summary: '获取陌生人信息', + readOnly: true, params: { user_id: f.uint().describe('QQ 号') }, run: async (p, ctx) => { const userId = p.user_id; diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index fa646639..242f7832 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -6,6 +6,7 @@ import { RETCODE, failedResponse, okResponse } from '../types'; export const actions = [ groupAction({ name: 'get_group_album_list', + readOnly: true, run: async (p, ctx) => { try { const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id); @@ -37,6 +38,7 @@ export const actions = [ groupAction({ name: 'get_group_album_media_list', + readOnly: true, params: { album_id: f.string({ allowEmpty: false }), attach_info: f.string().default(''), diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 7792ec4e..16fbd98c 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -43,6 +43,7 @@ export const actions = [ groupAction({ name: 'get_group_file_url', summary: '获取群文件下载链接', + readOnly: true, returns: '{ url: string }', // busid: legacy `asNumber(busid) || 102` mapped absent/0/invalid → 102. // f.int({min:0}).default(102) keeps absent → 102, but a present 0 now @@ -57,6 +58,7 @@ export const actions = [ groupAction({ name: 'get_group_root_files', summary: '获取群根目录文件列表', + readOnly: true, run: async (p, ctx) => { return okResponse(await ctx.getGroupFiles(p.group_id, '/')); }, @@ -65,6 +67,7 @@ export const actions = [ groupAction({ name: 'get_group_files_by_folder', summary: '获取群子目录文件列表', + readOnly: true, // folder_id / folder are aliases; first non-empty wins, else '/'. params: { folder_id: f.string().default(''), folder: f.string().default('') }, run: async (p, ctx) => { @@ -136,6 +139,7 @@ export const actions = [ defineAction({ name: 'get_private_file_url', summary: '获取私聊文件下载链接', + readOnly: true, returns: '{ url: string }', params: { user_id: f.uint(), diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index 15c89d84..7fbb6e26 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -8,6 +8,7 @@ export const actions = [ defineAction({ name: 'get_group_list', summary: '获取群列表', + readOnly: true, params: { no_cache: f.bool().default(false) }, run: async (p, ctx) => { const noCache = p.no_cache; @@ -21,6 +22,7 @@ export const actions = [ groupAction({ name: 'get_group_info', summary: '获取群信息', + readOnly: true, params: { no_cache: f.bool().default(false) }, run: async (p, ctx) => { const groupId = p.group_id; @@ -36,6 +38,7 @@ export const actions = [ groupAction({ name: 'get_group_member_list', summary: '获取群成员列表', + readOnly: true, params: { no_cache: f.bool().default(false) }, run: async (p, ctx) => { const groupId = p.group_id; @@ -50,6 +53,7 @@ export const actions = [ groupUserAction({ name: 'get_group_member_info', summary: '获取群成员信息', + readOnly: true, params: { no_cache: f.bool().default(false) }, run: async (p, ctx) => { const groupId = p.group_id; @@ -77,6 +81,7 @@ export const actions = [ groupAction({ name: 'get_group_honor_info', summary: '获取群荣誉信息', + readOnly: true, params: { type: f.raw() }, run: async (p, ctx) => { const groupId = p.group_id; @@ -99,6 +104,7 @@ export const actions = [ defineAction({ name: 'get_group_system_msg', summary: '获取群系统消息', + readOnly: true, params: {}, run: async (_p, ctx) => { if (ctx.handleGetGroupSystemMsg) { diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index 1b9657c3..b83cc0f3 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -8,6 +8,7 @@ const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'd export const actions = [ defineAction({ name: 'get_login_info', + readOnly: true, params: {}, run: (_p, ctx) => { const login = ctx.getLoginInfo(); @@ -17,6 +18,7 @@ export const actions = [ defineAction({ name: 'get_status', + readOnly: true, params: {}, run: (_p, ctx) => { const online = ctx.isOnline(); @@ -26,6 +28,7 @@ export const actions = [ defineAction({ name: 'get_version_info', + readOnly: true, params: {}, run: () => { return okResponse({ @@ -38,6 +41,7 @@ export const actions = [ defineAction({ name: 'can_send_image', + readOnly: true, params: {}, run: (_p, ctx) => { return okResponse({ yes: ctx.canSendImage?.() ?? false }); @@ -46,6 +50,7 @@ export const actions = [ defineAction({ name: 'can_send_record', + readOnly: true, params: {}, run: (_p, ctx) => { return okResponse({ yes: ctx.canSendRecord?.() ?? false }); diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index 73fd711f..40e229c6 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -85,6 +85,7 @@ export const actions = [ defineAction({ name: 'get_msg', summary: '获取消息', + readOnly: true, params: { message_id: f.messageId() }, run: async (p, ctx) => { const data = ctx.getMessage(p.message_id);