lint
This commit is contained in:
977 files changed
+198426
-158324
No files matched your search
@@ -9,31 +9,32 @@ import { it, expect } from 'vitest';
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
|
||||
it('generates src/generated/catalog.ts from the live action specs', () => {
|
||||
const actions = collectActionDocs();
|
||||
const categories = collectCategories();
|
||||
const actions = collectActionDocs();
|
||||
const categories = collectCategories();
|
||||
|
||||
expect(actions.length).toBeGreaterThan(100);
|
||||
// every action must carry a composed input schema (the MCP's payoff)
|
||||
for (const a of actions) {
|
||||
expect(a.inputSchema).toBeTypeOf('object');
|
||||
expect(a.name).toBeTruthy();
|
||||
}
|
||||
expect(actions.length).toBeGreaterThan(100);
|
||||
|
||||
const body =
|
||||
'// GENERATED by scripts/gen-catalog.test.ts — do not edit. Run `pnpm gen`.\n' +
|
||||
'/* eslint-disable */\n' +
|
||||
"import type { CatalogAction, CatalogCategory } from '../types.js';\n\n" +
|
||||
`export const ACTIONS: CatalogAction[] = ${JSON.stringify(actions, null, 2)};\n\n` +
|
||||
`export const CATEGORIES: CatalogCategory[] = ${JSON.stringify(categories, null, 2)};\n`;
|
||||
// every action must carry a composed input schema (the MCP's payoff)
|
||||
for (const a of actions) {
|
||||
expect(a.inputSchema).toBeTypeOf('object');
|
||||
expect(a.name).toBeTruthy();
|
||||
}
|
||||
|
||||
const dir = new URL('../src/generated/', import.meta.url);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
|
||||
const body =
|
||||
'// GENERATED by scripts/gen-catalog.test.ts — do not edit. Run `pnpm gen`.\n' +
|
||||
'/* eslint-disable */\n' +
|
||||
"import type { CatalogAction, CatalogCategory } from '../types.js';\n\n" +
|
||||
`export const ACTIONS: CatalogAction[] = ${JSON.stringify(actions, null, 2)};\n\n` +
|
||||
`export const CATEGORIES: CatalogCategory[] = ${JSON.stringify(categories, null, 2)};\n`;
|
||||
|
||||
// Plain-JSON twin of the catalog, consumed by the docs site (SnowLumaDocs)
|
||||
// via the sync-docs-catalog workflow. Same data as catalog.ts.
|
||||
writeFileSync(
|
||||
new URL('../src/generated/catalog.json', import.meta.url),
|
||||
JSON.stringify({ actions, categories }, null, 2) + '\n',
|
||||
);
|
||||
const dir = new URL('../src/generated/', import.meta.url);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
|
||||
|
||||
// Plain-JSON twin of the catalog, consumed by the docs site (SnowLumaDocs)
|
||||
// via the sync-docs-catalog workflow. Same data as catalog.ts.
|
||||
writeFileSync(
|
||||
new URL('../src/generated/catalog.json', import.meta.url),
|
||||
JSON.stringify({ actions, categories }, null, 2) + '\n',
|
||||
);
|
||||
});
|
||||
+1116
-662
File diff suppressed because it is too large.
Load diff
+76
-48
@@ -27,85 +27,113 @@ import { readFileSync } from 'node:fs';
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
||||
import {
|
||||
CallToolRequestSchema,
|
||||
ListResourcesRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
ReadResourceRequestSchema,
|
||||
CallToolRequestSchema,
|
||||
ListResourcesRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
ReadResourceRequestSchema,
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
|
||||
import { makeHttpClient, parseMaxStreamBytes, parseTimeoutMs, type ActionClient } from './client.js';
|
||||
import {
|
||||
makeHttpClient,
|
||||
parseMaxStreamBytes,
|
||||
parseTimeoutMs,
|
||||
type ActionClient,
|
||||
} from './client.js';
|
||||
import { callTool, computeTools, parseMode, type Mode } from './tools.js';
|
||||
|
||||
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };
|
||||
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';
|
||||
|
||||
// ── 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 streamDir = process.env.SNOWLUMA_MCP_STREAM_DIR?.trim() || undefined;
|
||||
const uploadRoot = process.env.SNOWLUMA_MCP_UPLOAD_ROOT?.trim() || undefined;
|
||||
const maxStreamBytes = parseMaxStreamBytes(process.env.SNOWLUMA_MCP_MAX_STREAM_BYTES);
|
||||
const timeoutMs = parseTimeoutMs(process.env.SNOWLUMA_MCP_TIMEOUT_MS);
|
||||
const requested = parseMode(process.env.SNOWLUMA_MCP_MODE);
|
||||
const endpoint = process.env.SNOWLUMA_MCP_ENDPOINT?.trim();
|
||||
const token = process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined;
|
||||
const streamDir = process.env.SNOWLUMA_MCP_STREAM_DIR?.trim() || undefined;
|
||||
const uploadRoot = process.env.SNOWLUMA_MCP_UPLOAD_ROOT?.trim() || undefined;
|
||||
const maxStreamBytes = parseMaxStreamBytes(process.env.SNOWLUMA_MCP_MAX_STREAM_BYTES);
|
||||
const timeoutMs = parseTimeoutMs(process.env.SNOWLUMA_MCP_TIMEOUT_MS);
|
||||
const requested = parseMode(process.env.SNOWLUMA_MCP_MODE);
|
||||
|
||||
if (!endpoint) {
|
||||
if (requested && requested !== 'docs') {
|
||||
console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${requested} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`);
|
||||
if (!endpoint) {
|
||||
if (requested && requested !== 'docs') {
|
||||
console.error(
|
||||
`[snowluma-mcp] SNOWLUMA_MCP_MODE=${requested} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`,
|
||||
);
|
||||
}
|
||||
|
||||
return { mode: 'docs' };
|
||||
}
|
||||
return { mode: 'docs' };
|
||||
}
|
||||
|
||||
const mode: Mode = requested ?? 'read';
|
||||
if (mode === 'docs') {
|
||||
// Endpoint set but operator explicitly wants docs-only — honor it.
|
||||
return { mode: 'docs' };
|
||||
}
|
||||
const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs, streamDir, uploadRoot, maxStreamBytes });
|
||||
return { mode, client };
|
||||
const mode: Mode = requested ?? 'read';
|
||||
|
||||
if (mode === 'docs') {
|
||||
// Endpoint set but operator explicitly wants docs-only — honor it.
|
||||
return { mode: 'docs' };
|
||||
}
|
||||
|
||||
const client = makeHttpClient({
|
||||
endpoint,
|
||||
accessToken: token,
|
||||
timeoutMs,
|
||||
streamDir,
|
||||
uploadRoot,
|
||||
maxStreamBytes,
|
||||
});
|
||||
return { mode, client };
|
||||
}
|
||||
|
||||
const { mode, client } = resolveRuntime();
|
||||
|
||||
const server = new Server(
|
||||
{ name: 'snowluma-mcp', version: VERSION },
|
||||
{ capabilities: { tools: {}, resources: {} } },
|
||||
{ name: 'snowluma-mcp', version: VERSION },
|
||||
{ capabilities: { tools: {}, resources: {} } },
|
||||
);
|
||||
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) }));
|
||||
|
||||
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
|
||||
const args = (req.params.arguments ?? {}) as Record<string, unknown>;
|
||||
return callTool(req.params.name, args, { mode, client, signal: extra.signal });
|
||||
const args = (req.params.arguments ?? {}) as Record<string, unknown>;
|
||||
return callTool(req.params.name, args, { mode, client, signal: extra.signal });
|
||||
});
|
||||
|
||||
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
||||
resources: [
|
||||
{
|
||||
uri: RESOURCE_URI,
|
||||
name: 'SnowLuma OneBot action catalog',
|
||||
mimeType: 'application/json',
|
||||
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
|
||||
},
|
||||
],
|
||||
resources: [
|
||||
{
|
||||
uri: RESOURCE_URI,
|
||||
name: 'SnowLuma OneBot action catalog',
|
||||
mimeType: 'application/json',
|
||||
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
|
||||
},
|
||||
],
|
||||
}));
|
||||
|
||||
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
|
||||
if (req.params.uri !== RESOURCE_URI) throw new Error(`unknown resource: ${req.params.uri}`);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: RESOURCE_URI,
|
||||
mimeType: 'application/json',
|
||||
text: JSON.stringify({ version: VERSION, categories: CATEGORIES, actions: ACTIONS }, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
if (req.params.uri !== RESOURCE_URI) {
|
||||
throw new Error(`unknown resource: ${req.params.uri}`);
|
||||
}
|
||||
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: RESOURCE_URI,
|
||||
mimeType: 'application/json',
|
||||
text: JSON.stringify(
|
||||
{ version: VERSION, categories: CATEGORIES, actions: ACTIONS },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
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}`);
|
||||
console.error(
|
||||
`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}${where}`,
|
||||
);
|
||||
+237
-159
@@ -16,212 +16,290 @@ import type { ActionClient } from './client.js';
|
||||
export type Mode = 'docs' | 'read' | 'write';
|
||||
|
||||
export function parseMode(raw: string | undefined): Mode | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
const value = raw.trim().toLowerCase();
|
||||
if (value === 'docs' || value === 'read' || value === 'write') return value;
|
||||
throw new Error('SNOWLUMA_MCP_MODE must be one of: docs, read, write');
|
||||
if (raw === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const value = raw.trim().toLowerCase();
|
||||
|
||||
if (value === 'docs' || value === 'read' || value === 'write') {
|
||||
return value;
|
||||
}
|
||||
|
||||
throw new Error('SNOWLUMA_MCP_MODE must be one of: docs, read, write');
|
||||
}
|
||||
|
||||
// name + every alias → action, so lookups accept 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);
|
||||
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, stream: a.stream ?? false };
|
||||
return {
|
||||
name: a.name,
|
||||
category: a.category,
|
||||
summary: a.summary,
|
||||
aliases: a.aliases,
|
||||
readOnly: a.readOnly,
|
||||
stream: a.stream ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
const DOCS_TOOLS: Tool[] = [
|
||||
{
|
||||
name: 'list_actions',
|
||||
description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读/是否为 Stream Action)。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } },
|
||||
additionalProperties: false,
|
||||
{
|
||||
name: 'list_actions',
|
||||
description:
|
||||
'列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读/是否为 Stream Action)。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
annotations: { readOnlyHint: true, openWorldHint: 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,
|
||||
{
|
||||
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 },
|
||||
},
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
},
|
||||
{
|
||||
name: 'search_actions',
|
||||
description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { query: { type: 'string', description: '关键字' } },
|
||||
required: ['query'],
|
||||
additionalProperties: 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 },
|
||||
},
|
||||
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 },
|
||||
execution: {
|
||||
type: 'object',
|
||||
description: 'MCP 主机侧执行选项(不会发送为 OneBot params)。自动上传本地文件时使用。',
|
||||
properties: {
|
||||
input_file: {
|
||||
type: 'string',
|
||||
description: 'MCP 主机上的文件路径。仅用于 upload_file_stream,且必须位于 SNOWLUMA_MCP_UPLOAD_ROOT。',
|
||||
type: 'object' as const,
|
||||
properties: {
|
||||
action: {
|
||||
type: 'string',
|
||||
description: 'action 名(接受别名)。先用 get_action 查它的参数 inputSchema。',
|
||||
},
|
||||
params: { type: 'object', description: '该 action 的参数对象', additionalProperties: true },
|
||||
execution: {
|
||||
type: 'object',
|
||||
description: 'MCP 主机侧执行选项(不会发送为 OneBot params)。自动上传本地文件时使用。',
|
||||
properties: {
|
||||
input_file: {
|
||||
type: 'string',
|
||||
description:
|
||||
'MCP 主机上的文件路径。仅用于 upload_file_stream,且必须位于 SNOWLUMA_MCP_UPLOAD_ROOT。',
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
required: ['action'],
|
||||
additionalProperties: false,
|
||||
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 },
|
||||
};
|
||||
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(可产生副作用)。Stream 下载会写入 MCP 主机受控目录并只返回文件元数据;upload_file_stream 可用 execution.input_file 自动分块上传。仅在写模式可用。',
|
||||
inputSchema: EXEC_INPUT_SCHEMA,
|
||||
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
|
||||
};
|
||||
return {
|
||||
name: 'invoke_action',
|
||||
description:
|
||||
'调用一个 OneBot action(可产生副作用)。Stream 下载会写入 MCP 主机受控目录并只返回文件元数据;upload_file_stream 可用 execution.input_file 自动分块上传。仅在写模式可用。',
|
||||
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;
|
||||
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) }] };
|
||||
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
|
||||
}
|
||||
|
||||
function asError(message: string): ToolResult {
|
||||
return { content: [{ type: 'text', text: message }], isError: true };
|
||||
return { content: [{ type: 'text', text: message }], isError: true };
|
||||
}
|
||||
|
||||
export interface CallCtx {
|
||||
mode: Mode;
|
||||
client?: ActionClient;
|
||||
signal?: AbortSignal;
|
||||
mode: Mode;
|
||||
client?: ActionClient;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export async function callTool(name: string, args: Record<string, unknown>, ctx: CallCtx): Promise<ToolResult> {
|
||||
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 });
|
||||
export async function callTool(
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
ctx: CallCtx,
|
||||
): Promise<ToolResult> {
|
||||
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}`);
|
||||
}
|
||||
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<string, unknown>, ctx: CallCtx, kind: 'read' | 'write'): Promise<ToolResult> {
|
||||
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<string, unknown>)
|
||||
: {};
|
||||
let inputFile: string | undefined;
|
||||
if (args.execution !== undefined) {
|
||||
if (!args.execution || typeof args.execution !== 'object' || Array.isArray(args.execution)) {
|
||||
return asError('execution 必须是对象。');
|
||||
async function execute(
|
||||
args: Record<string, unknown>,
|
||||
ctx: CallCtx,
|
||||
kind: 'read' | 'write',
|
||||
): Promise<ToolResult> {
|
||||
if (kind === 'write' && ctx.mode !== 'write') {
|
||||
return asError('写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。');
|
||||
}
|
||||
const execution = args.execution as Record<string, unknown>;
|
||||
const unknown = Object.keys(execution).filter((key) => key !== 'input_file');
|
||||
if (unknown.length) return asError(`未知 MCP execution 选项: ${unknown.join(', ')}`);
|
||||
if (execution.input_file !== undefined) {
|
||||
if (typeof execution.input_file !== 'string' || !execution.input_file.trim()) {
|
||||
return asError('execution.input_file 必须是非空字符串。');
|
||||
}
|
||||
inputFile = execution.input_file;
|
||||
|
||||
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<string, unknown>)
|
||||
: {};
|
||||
let inputFile: string | undefined;
|
||||
|
||||
if (args.execution !== undefined) {
|
||||
if (
|
||||
!args.execution ||
|
||||
typeof args.execution !== 'object' ||
|
||||
Array.isArray(args.execution)
|
||||
) {
|
||||
return asError('execution 必须是对象。');
|
||||
}
|
||||
|
||||
const execution = args.execution as Record<string, unknown>;
|
||||
const unknown = Object.keys(execution).filter((key) => key !== 'input_file');
|
||||
|
||||
if (unknown.length) {
|
||||
return asError(`未知 MCP execution 选项: ${unknown.join(', ')}`);
|
||||
}
|
||||
|
||||
if (execution.input_file !== undefined) {
|
||||
if (typeof execution.input_file !== 'string' || !execution.input_file.trim()) {
|
||||
return asError('execution.input_file 必须是非空字符串。');
|
||||
}
|
||||
|
||||
inputFile = execution.input_file;
|
||||
}
|
||||
}
|
||||
|
||||
if (inputFile && cat.name !== 'upload_file_stream') {
|
||||
return asError('execution.input_file 仅可用于 upload_file_stream。');
|
||||
}
|
||||
|
||||
if (inputFile && !cat.stream) {
|
||||
return asError(`${action} 不是 Stream Action,不能使用 execution.input_file。`);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = cat.stream
|
||||
? await ctx.client.callStream(action, params, {
|
||||
...(inputFile ? { inputFile } : {}),
|
||||
...(ctx.signal ? { signal: ctx.signal } : {}),
|
||||
})
|
||||
: await ctx.client.call(action, params);
|
||||
return asText(result);
|
||||
} catch (err) {
|
||||
return asError(`调用失败 (${action}): ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
if (inputFile && cat.name !== 'upload_file_stream') {
|
||||
return asError('execution.input_file 仅可用于 upload_file_stream。');
|
||||
}
|
||||
if (inputFile && !cat.stream) {
|
||||
return asError(`${action} 不是 Stream Action,不能使用 execution.input_file。`);
|
||||
}
|
||||
try {
|
||||
const result = cat.stream
|
||||
? await ctx.client.callStream(action, params, {
|
||||
...(inputFile ? { inputFile } : {}),
|
||||
...(ctx.signal ? { signal: ctx.signal } : {}),
|
||||
})
|
||||
: await ctx.client.call(action, params);
|
||||
return asText(result);
|
||||
} catch (err) {
|
||||
return asError(`调用失败 (${action}): ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
+35
-35
@@ -4,45 +4,45 @@
|
||||
// only contract (ADR-0005: the wire/data shape is the seam, not a shared type).
|
||||
|
||||
export interface CatalogParam {
|
||||
name: string;
|
||||
/** Display type ('uint' | 'int' | 'messageId' | 'string' | 'bool' | 'message' | 'enum' | 'X[]' | 'raw'). */
|
||||
type: string;
|
||||
required: boolean;
|
||||
default?: unknown;
|
||||
desc?: string;
|
||||
values?: ReadonlyArray<string | number>;
|
||||
/** Semantic role (group_id / user_id / member_id / image / face_id / …),
|
||||
* orthogonal to `type`; drives smart-widget selection in the WebUI console.
|
||||
* Kept as a loose string here so the package stays decoupled from onebot's
|
||||
* FieldRole union. */
|
||||
role?: string;
|
||||
/** JSON Schema fragment for this single field. */
|
||||
schema?: Record<string, unknown>;
|
||||
name: string;
|
||||
/** Display type ('uint' | 'int' | 'messageId' | 'string' | 'bool' | 'message' | 'enum' | 'X[]' | 'raw'). */
|
||||
type: string;
|
||||
required: boolean;
|
||||
default?: unknown;
|
||||
desc?: string;
|
||||
values?: ReadonlyArray<string | number>;
|
||||
/** Semantic role (group_id / user_id / member_id / image / face_id / …),
|
||||
* orthogonal to `type`; drives smart-widget selection in the WebUI console.
|
||||
* Kept as a loose string here so the package stays decoupled from onebot's
|
||||
* FieldRole union. */
|
||||
role?: string;
|
||||
/** JSON Schema fragment for this single field. */
|
||||
schema?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CatalogAction {
|
||||
name: string;
|
||||
aliases: string[];
|
||||
category?: string;
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** JSON Schema for the action's `data` payload (absent when undocumented). */
|
||||
returnsSchema?: Record<string, unknown>;
|
||||
/** 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;
|
||||
/** True for Stream API actions (multi-frame transport). Absent ⇒ ordinary
|
||||
* single-response action. */
|
||||
stream?: boolean;
|
||||
params: CatalogParam[];
|
||||
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
|
||||
invariants: string[];
|
||||
/** Composed JSON Schema for the whole params object. */
|
||||
inputSchema: Record<string, unknown>;
|
||||
name: string;
|
||||
aliases: string[];
|
||||
category?: string;
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** JSON Schema for the action's `data` payload (absent when undocumented). */
|
||||
returnsSchema?: Record<string, unknown>;
|
||||
/** 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;
|
||||
/** True for Stream API actions (multi-frame transport). Absent ⇒ ordinary
|
||||
* single-response action. */
|
||||
stream?: boolean;
|
||||
params: CatalogParam[];
|
||||
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
|
||||
invariants: string[];
|
||||
/** Composed JSON Schema for the whole params object. */
|
||||
inputSchema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CatalogCategory {
|
||||
category: string;
|
||||
count: number;
|
||||
category: string;
|
||||
count: number;
|
||||
}
|
||||
+1339
-657
File diff suppressed because it is too large.
Load diff
+285
-185
@@ -1,219 +1,319 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { computeTools, callTool, parseMode } from '../src/tools';
|
||||
import type { ActionClient, OneBotEnvelope, StreamCallOptions, StreamCallResult } from '../src/client';
|
||||
import type {
|
||||
ActionClient,
|
||||
OneBotEnvelope,
|
||||
StreamCallOptions,
|
||||
StreamCallResult,
|
||||
} from '../src/client';
|
||||
|
||||
type Res = Awaited<ReturnType<typeof callTool>>;
|
||||
|
||||
function text(res: Res): string {
|
||||
const block = res.content?.[0];
|
||||
return block && block.type === 'text' ? block.text : '';
|
||||
const block = res.content?.[0];
|
||||
return block && block.type === 'text' ? block.text : '';
|
||||
}
|
||||
|
||||
function parsed(res: Res): any {
|
||||
return JSON.parse(text(res));
|
||||
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<string, unknown>) => OneBotEnvelope,
|
||||
streamImpl?: (action: string, params: Record<string, unknown>, options?: StreamCallOptions) => StreamCallResult,
|
||||
impl?: (action: string, params: Record<string, unknown>) => OneBotEnvelope,
|
||||
streamImpl?: (
|
||||
action: string,
|
||||
params: Record<string, unknown>,
|
||||
options?: StreamCallOptions,
|
||||
) => StreamCallResult,
|
||||
): ActionClient {
|
||||
return {
|
||||
call: async (action, params) => impl?.(action, params) ?? { status: 'ok', retcode: 0, data: { action, params } },
|
||||
callStream: async (action, params, options) => streamImpl?.(action, params, options) ?? {
|
||||
frame_count: 1,
|
||||
frames: [],
|
||||
terminal: { status: 'ok', retcode: 0, data: { type: 'response', action, params } },
|
||||
},
|
||||
};
|
||||
return {
|
||||
call: async (action, params) =>
|
||||
impl?.(action, params) ?? { status: 'ok', retcode: 0, data: { action, params } },
|
||||
callStream: async (action, params, options) =>
|
||||
streamImpl?.(action, params, options) ?? {
|
||||
frame_count: 1,
|
||||
frames: [],
|
||||
terminal: { status: 'ok', retcode: 0, data: { type: 'response', action, params } },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('computeTools — mode gating', () => {
|
||||
it('fails fast on an invalid SNOWLUMA_MCP_MODE', () => {
|
||||
expect(parseMode(undefined)).toBeUndefined();
|
||||
expect(parseMode('WRITE')).toBe('write');
|
||||
for (const invalid of ['', 'unsafe', 'reader']) {
|
||||
expect(() => parseMode(invalid), invalid).toThrow(/SNOWLUMA_MCP_MODE/);
|
||||
}
|
||||
});
|
||||
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);
|
||||
});
|
||||
it('fails fast on an invalid SNOWLUMA_MCP_MODE', () => {
|
||||
expect(parseMode(undefined)).toBeUndefined();
|
||||
expect(parseMode('WRITE')).toBe('write');
|
||||
|
||||
for (const invalid of ['', 'unsafe', 'reader']) {
|
||||
expect(() => parseMode(invalid), invalid).toThrow(/SNOWLUMA_MCP_MODE/);
|
||||
}
|
||||
});
|
||||
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');
|
||||
});
|
||||
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('未配置');
|
||||
});
|
||||
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<string, unknown> } | null = null;
|
||||
const client: ActionClient = {
|
||||
call: async (action, params) => {
|
||||
seen = { action, params };
|
||||
return { status: 'ok', retcode: 0, data: { message_id: 42 } };
|
||||
},
|
||||
callStream: async () => { throw new Error('unexpected stream call'); },
|
||||
};
|
||||
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'); },
|
||||
callStream: async () => { throw new Error('unexpected stream call'); },
|
||||
};
|
||||
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');
|
||||
});
|
||||
|
||||
it('routes catalog Stream Actions through callStream and returns the bounded summary', async () => {
|
||||
let ordinaryCalls = 0;
|
||||
let streamCalls = 0;
|
||||
const terminal = { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete' } };
|
||||
const client: ActionClient = {
|
||||
call: async () => { ordinaryCalls++; return { status: 'ok', retcode: 0 }; },
|
||||
callStream: async (action, params) => {
|
||||
streamCalls++;
|
||||
expect(action).toBe('test_download_stream');
|
||||
expect(params).toEqual({ error: false });
|
||||
return { frame_count: 1, frames: [], terminal };
|
||||
},
|
||||
};
|
||||
|
||||
const res = await callTool('invoke_action', { action: 'test_download_stream', params: { error: false } }, { mode: 'write', client });
|
||||
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(parsed(res)).toEqual({ frame_count: 1, frames: [], terminal });
|
||||
expect(streamCalls).toBe(1);
|
||||
expect(ordinaryCalls).toBe(0);
|
||||
});
|
||||
|
||||
it('passes execution.input_file only as an MCP upload option, never as OneBot params', async () => {
|
||||
let seen: { params: Record<string, unknown>; inputFile?: string } | undefined;
|
||||
const client = fakeClient(undefined, (_action, params, options) => {
|
||||
seen = { params, inputFile: options?.inputFile };
|
||||
return {
|
||||
file_path: '/remote/local.txt', file_size: 5, sha256: 'abc', chunk_count: 1, stream_id: 'id',
|
||||
terminal: { status: 'ok', retcode: 0, data: { type: 'response', status: 'file_complete' } },
|
||||
};
|
||||
it('executes a write action in write mode and forwards action+params', async () => {
|
||||
let seen: { action: string; params: Record<string, unknown> } | null = null;
|
||||
const client: ActionClient = {
|
||||
call: async (action, params) => {
|
||||
seen = { action, params };
|
||||
return { status: 'ok', retcode: 0, data: { message_id: 42 } };
|
||||
},
|
||||
callStream: async () => {
|
||||
throw new Error('unexpected stream call');
|
||||
},
|
||||
};
|
||||
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');
|
||||
},
|
||||
callStream: async () => {
|
||||
throw new Error('unexpected stream call');
|
||||
},
|
||||
};
|
||||
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');
|
||||
});
|
||||
|
||||
const res = await callTool('invoke_action', {
|
||||
action: 'upload_file_stream',
|
||||
params: { file_retention: 0 },
|
||||
execution: { input_file: '/allowed/local.txt' },
|
||||
}, { mode: 'write', client });
|
||||
it('routes catalog Stream Actions through callStream and returns the bounded summary', async () => {
|
||||
let ordinaryCalls = 0;
|
||||
let streamCalls = 0;
|
||||
const terminal = {
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { type: 'response', data_type: 'data_complete' },
|
||||
};
|
||||
const client: ActionClient = {
|
||||
call: async () => {
|
||||
ordinaryCalls++;
|
||||
return { status: 'ok', retcode: 0 };
|
||||
},
|
||||
callStream: async (action, params) => {
|
||||
streamCalls++;
|
||||
expect(action).toBe('test_download_stream');
|
||||
expect(params).toEqual({ error: false });
|
||||
return { frame_count: 1, frames: [], terminal };
|
||||
},
|
||||
};
|
||||
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(seen).toEqual({ params: { file_retention: 0 }, inputFile: '/allowed/local.txt' });
|
||||
});
|
||||
const res = await callTool(
|
||||
'invoke_action',
|
||||
{ action: 'test_download_stream', params: { error: false } },
|
||||
{ mode: 'write', client },
|
||||
);
|
||||
|
||||
it('forwards MCP request cancellation to Stream Action execution', async () => {
|
||||
const controller = new AbortController();
|
||||
let seenSignal: AbortSignal | undefined;
|
||||
const client = fakeClient(undefined, (_action, _params, options) => {
|
||||
seenSignal = options?.signal;
|
||||
return {
|
||||
frame_count: 1,
|
||||
frames: [],
|
||||
terminal: { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete' } },
|
||||
};
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(parsed(res)).toEqual({ frame_count: 1, frames: [], terminal });
|
||||
expect(streamCalls).toBe(1);
|
||||
expect(ordinaryCalls).toBe(0);
|
||||
});
|
||||
|
||||
const res = await callTool('invoke_action', { action: 'test_download_stream', params: {} }, {
|
||||
mode: 'write', client, signal: controller.signal,
|
||||
it('passes execution.input_file only as an MCP upload option, never as OneBot params', async () => {
|
||||
let seen: { params: Record<string, unknown>; inputFile?: string } | undefined;
|
||||
const client = fakeClient(undefined, (_action, params, options) => {
|
||||
seen = { params, inputFile: options?.inputFile };
|
||||
return {
|
||||
file_path: '/remote/local.txt',
|
||||
file_size: 5,
|
||||
sha256: 'abc',
|
||||
chunk_count: 1,
|
||||
stream_id: 'id',
|
||||
terminal: {
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { type: 'response', status: 'file_complete' },
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const res = await callTool(
|
||||
'invoke_action',
|
||||
{
|
||||
action: 'upload_file_stream',
|
||||
params: { file_retention: 0 },
|
||||
execution: { input_file: '/allowed/local.txt' },
|
||||
},
|
||||
{ mode: 'write', client },
|
||||
);
|
||||
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(seen).toEqual({ params: { file_retention: 0 }, inputFile: '/allowed/local.txt' });
|
||||
});
|
||||
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(seenSignal).toBe(controller.signal);
|
||||
});
|
||||
it('forwards MCP request cancellation to Stream Action execution', async () => {
|
||||
const controller = new AbortController();
|
||||
let seenSignal: AbortSignal | undefined;
|
||||
const client = fakeClient(undefined, (_action, _params, options) => {
|
||||
seenSignal = options?.signal;
|
||||
return {
|
||||
frame_count: 1,
|
||||
frames: [],
|
||||
terminal: {
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { type: 'response', data_type: 'data_complete' },
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const res = await callTool(
|
||||
'invoke_action',
|
||||
{ action: 'test_download_stream', params: {} },
|
||||
{
|
||||
mode: 'write',
|
||||
client,
|
||||
signal: controller.signal,
|
||||
},
|
||||
);
|
||||
|
||||
expect(res.isError).toBeFalsy();
|
||||
expect(seenSignal).toBe(controller.signal);
|
||||
});
|
||||
});
|
||||
@@ -6,12 +6,12 @@ import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [protobufVitePlugin()],
|
||||
test: {
|
||||
include: ['scripts/**/*.test.ts', 'tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
env: {
|
||||
SNOWLUMA_LOG_FILE: '0',
|
||||
plugins: [protobufVitePlugin()],
|
||||
test: {
|
||||
include: ['scripts/**/*.test.ts', 'tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
env: {
|
||||
SNOWLUMA_LOG_FILE: '0',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user