feat(mcp): execution mode — query/invoke OneBot actions with a read/write safety gate
@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.
This commit is contained in:
16 files changed
+684
-89
No files matched your search
+46
-88
@@ -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<string, CatalogAction>();
|
||||
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<string, unknown>;
|
||||
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}`);
|
||||
Reference in new issue
Block a user