feat(mcp): improve agent discovery and execution feedback

Add structured results, optional keyword search and pagination, and runtime information with explicit connection checks. Preserve existing text responses and execution permissions.

Support request cancellation and transfer progress. Verify compatibility with the full CI suite and isolated MCP and HTTP integration tests.
This commit is contained in:
DrSmoothl committed 2026-10-23 15:14:18 +08:00
1 parent 9b5ce9b502
commit 34a73084e0
16 files changed
+1552 -155

No files matched your search

+147 -36
View File
@@ -2,16 +2,15 @@
//
// 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`).
// with `fetch`. This client also owns MCP-host file admission and bounded stream
// summaries. The wire shape — not a shared client type — is the seam (ADR-0005);
// tests inject a fake `ActionClient` (or a fake `fetch`).
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { ActionCallError } from './results.js';
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_STREAM_BYTES = 4 * 1024 * 1024 * 1024;
@@ -102,9 +101,14 @@ export interface OneBotEnvelope {
}
export interface ActionClient {
readonly info?: ClientInfo;
/** 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<string, unknown>): Promise<OneBotEnvelope>;
call(
action: string,
params: Record<string, unknown>,
options?: CallOptions,
): Promise<OneBotEnvelope>;
/** Execute a Stream Action over the HTTP multi-frame transport. */
callStream(
action: string,
@@ -113,11 +117,30 @@ export interface ActionClient {
): Promise<StreamCallResult>;
}
export interface StreamCallOptions {
export interface ClientInfo {
timeout_ms: number;
max_stream_bytes: number;
download_quota_bytes: number;
max_active_streams: number;
download_directory: string;
upload_root: string | null;
upload_enabled: boolean;
}
export interface TransferProgress {
progress: number;
total?: number;
message: string;
}
export interface CallOptions {
signal?: AbortSignal;
}
export interface StreamCallOptions extends CallOptions {
/** MCP-host file to upload. Only valid for upload_file_stream. */
inputFile?: string;
/** Cancellation from the originating MCP request. */
signal?: AbortSignal;
onProgress?: (progress: TransferProgress) => Promise<void>;
}
type InternalStreamCallOptions = StreamCallOptions & { [INTERNAL_STREAM_CALL]?: true };
@@ -346,7 +369,10 @@ function abortReason(signal: AbortSignal): string {
function throwIfCancelled(signal: AbortSignal | undefined, action: string, stage: string): void {
if (signal?.aborted) {
throw new Error(`action ${action} stream ${stage}: cancelled: ${abortReason(signal)}`);
throw new ActionCallError(
`action ${action} stream ${stage}: cancelled: ${abortReason(signal)}`,
'cancelled',
);
}
}
@@ -360,8 +386,9 @@ async function readWithIdleTimeout(
frameIndex: number,
): Promise<ByteStreamReadResult> {
if (callerSignal?.aborted) {
throw new Error(
throw new ActionCallError(
`action ${action} stream read frame ${frameIndex}: cancelled: ${abortReason(callerSignal)}`,
'cancelled',
);
}
@@ -382,8 +409,9 @@ async function readWithIdleTimeout(
const onAbort = (): void =>
finish(() =>
reject(
new Error(
new ActionCallError(
`action ${action} stream read frame ${frameIndex}: cancelled: ${callerSignal ? abortReason(callerSignal) : 'aborted'}`,
'cancelled',
),
),
);
@@ -391,8 +419,9 @@ async function readWithIdleTimeout(
() =>
finish(() =>
reject(
new Error(
new ActionCallError(
`action ${action} stream read frame ${frameIndex}: idle timeout after ${timeoutMs}ms`,
'timeout',
),
),
),
@@ -418,6 +447,7 @@ async function uploadLocalFile(
maxStreamBytes: number,
callerSignal: AbortSignal | undefined,
post: (params: Record<string, unknown>, signal?: AbortSignal) => Promise<StreamCallResult>,
onProgress?: StreamCallOptions['onProgress'],
): Promise<UploadStreamResult> {
const streamId = randomUUID();
let handle: fs.promises.FileHandle | undefined;
@@ -442,6 +472,11 @@ async function uploadLocalFile(
}
const totalChunks = Math.max(1, Math.ceil(initial.size / UPLOAD_CHUNK_BYTES));
await onProgress?.({
progress: 0,
...(initial.size > 0 ? { total: initial.size } : {}),
message: '上传开始(字节)',
});
const baseParams = { ...params };
for (const key of MCP_UPLOAD_OWNED_FIELDS) {
@@ -507,6 +542,12 @@ async function uploadLocalFile(
`unexpected chunk acknowledgement: ${JSON.stringify(ack.terminal)}`,
);
}
await onProgress?.({
progress: bytesRead,
...(initial.size > 0 ? { total: initial.size } : {}),
message: '已确认上传(字节);等待最终校验',
});
}
stage = 'verify input';
@@ -605,6 +646,7 @@ async function uploadLocalFile(
throw new Error(
`action ${action} stream ${stage}: ${detail}${closeFailure}${resetFailure}`,
{ cause: error },
);
}
}
@@ -667,36 +709,75 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
let client: ActionClient;
let activeStreams = 0;
client = {
async call(action, params) {
let res: Response;
info: Object.freeze({
timeout_ms: timeoutMs,
max_stream_bytes: maxStreamBytes,
download_quota_bytes: 2 * maxStreamBytes,
max_active_streams: MAX_ACTIVE_STREAMS,
download_directory: streamDir,
upload_root: uploadRoot ?? null,
upload_enabled: uploadRoot !== undefined,
}),
async call(action, params, options) {
const deadline = new AbortController();
const signal = options?.signal
? AbortSignal.any([options.signal, deadline.signal])
: deadline.signal;
const timer = setTimeout(
() => deadline.abort(new Error(`timeout after ${timeoutMs}ms`)),
timeoutMs,
);
timer.unref();
try {
res = await fetchImpl(opts.endpoint, {
signal.throwIfAborted();
const res = await fetchImpl(opts.endpoint, {
method: 'POST',
headers,
body: JSON.stringify({ action, params }),
signal: AbortSignal.timeout(timeoutMs),
signal,
});
const text = await res.text();
signal.throwIfAborted();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
throw new ActionCallError(
`OneBot returned non-JSON (HTTP ${res.status})`,
res.status === 401 || res.status === 403
? 'authentication'
: 'invalid_response',
);
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new ActionCallError(
`OneBot returned an unexpected response (HTTP ${res.status})`,
'invalid_response',
);
}
return parsed as OneBotEnvelope;
} catch (error) {
throw new Error(
if (error instanceof ActionCallError) {
throw error;
}
const kind = options?.signal?.aborted
? 'cancelled'
: deadline.signal.aborted
? 'timeout'
: 'transport';
throw new ActionCallError(
`action ${action} request: ${error instanceof Error ? error.message : String(error)}`,
kind,
{ cause: error },
);
} finally {
clearTimeout(timer);
}
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;
},
async callStream(action, params, options) {
const internalOptions = options as InternalStreamCallOptions | undefined;
@@ -763,6 +844,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
...(signal ? { signal } : {}),
[INTERNAL_STREAM_CALL]: true,
} as InternalStreamCallOptions),
options.onProgress,
);
}
@@ -782,6 +864,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
}
try {
throwIfCancelled(options?.signal, action, 'connection');
res = await fetchImpl(opts.endpoint, {
method: 'POST',
headers,
@@ -796,14 +879,23 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
: error instanceof Error
? error.message
: String(error);
throw new Error(`action ${action} stream connection: ${detail}`);
throw new ActionCallError(
`action ${action} stream connection: ${detail}`,
options?.signal?.aborted
? 'cancelled'
: connectionController.signal.aborted
? 'timeout'
: 'transport',
{ cause: error },
);
} finally {
clearTimeout(connectionTimer);
}
if (!res.ok) {
throw new Error(
throw new ActionCallError(
`action ${action} stream HTTP: unexpected status ${res.status}`,
res.status === 401 || res.status === 403 ? 'authentication' : 'transport',
);
}
@@ -833,6 +925,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
frame: OneBotEnvelope,
rawBytes: number,
): Promise<void> => {
throwIfCancelled(options?.signal, action, `frame ${frameIndex}`);
const data = record(frame.data);
const dataType = data?.data_type;
const resetAck =
@@ -942,6 +1035,12 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
throw error;
}
await options?.onProgress?.({
progress: 0,
...(declaredSize !== undefined ? { total: declaredSize } : {}),
message: '下载开始(字节)',
});
return;
}
@@ -1008,6 +1107,11 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
fileHash.update(chunk);
fileBytes += chunk.length;
fileChunks++;
await options?.onProgress?.({
progress: fileBytes,
...(declaredSize !== undefined ? { total: declaredSize } : {}),
message: '已接收下载(字节);等待最终校验',
});
return;
}
@@ -1046,6 +1150,11 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
if (data?.type === 'response') {
genericTerminalIndex = frameIndex;
}
await options?.onProgress?.({
progress: frames.length,
message: '已接收数据帧',
});
};
try {
@@ -1112,6 +1221,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
throw new Error(
`action ${action} stream frame ${frameIndex}: frame handling failed: ${detail}`,
{ cause: error },
);
}
@@ -1173,6 +1283,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
}
const sha256 = fileHash.digest('hex');
throwIfCancelled(options?.signal, action, 'commit download');
await fileHandle.close();
fileHandle = undefined;
await fs.promises.rename(partPath!, finalPath!);
@@ -1243,7 +1354,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
const suffix = cleanupErrors.length
? `; cleanup failed (${cleanupErrors.join('; ')})`
: '';
throw new Error(base + suffix);
throw new Error(base + suffix, { cause: error });
} finally {
reader.releaseLock();
}
+119
View File
@@ -0,0 +1,119 @@
import type { CatalogAction } from './types.js';
export const FILTER_PROPERTIES = {
category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' },
read_only: { type: 'boolean', description: '只返回指定读写类型的动作' },
stream: { type: 'boolean', description: '只返回指定流式类型的动作' },
limit: {
type: 'integer',
minimum: 1,
maximum: 200,
description: '每页数量;省略时返回全部匹配项',
},
offset: { type: 'integer', minimum: 0, description: '跳过的匹配项数量,默认 0' },
};
const SYNONYMS = [
['历史消息', '消息历史', 'history'],
['群聊', '群', 'group'],
['私聊', '好友', 'private', 'friend'],
['禁言', 'ban', 'mute'],
['撤回', '撤销消息', 'delete_msg', 'recall'],
['图片', 'image', 'photo'],
['语音', 'record', 'voice'],
['文件', 'file'],
['上传', 'upload'],
['下载', 'download'],
];
export function lite(action: CatalogAction) {
return {
name: action.name,
category: action.category,
summary: action.summary,
aliases: action.aliases,
readOnly: action.readOnly,
stream: action.stream ?? false,
};
}
/** Optional controls must not change legacy matching, order or response fields. */
export function discover(actions: CatalogAction[], args: Record<string, unknown>, search: boolean) {
for (const key of ['read_only', 'stream']) {
if (args[key] !== undefined && typeof args[key] !== 'boolean') {
throw new Error(`${key} 必须是布尔值。`);
}
}
for (const key of ['limit', 'offset']) {
const value = args[key];
if (
value !== undefined &&
(typeof value !== 'number' ||
!Number.isSafeInteger(value) ||
value < (key === 'limit' ? 1 : 0) ||
(key === 'limit' && value > 200))
) {
throw new Error(`${key} 必须是有效整数(limit 为 1–200,offset 不小于 0)。`);
}
}
if (args.match !== undefined && args.match !== 'substring' && args.match !== 'keywords') {
throw new Error('match 必须为 substring 或 keywords。');
}
const query = (typeof args.query === 'string' ? args.query : '').toLowerCase();
const category = typeof args.category === 'string' ? args.category : undefined;
const keywords = query.trim().split(/\s+/u).filter(Boolean);
let list = actions.filter((action) => {
if (
(category && action.category !== category) ||
(args.read_only !== undefined && action.readOnly !== args.read_only) ||
(args.stream !== undefined && (action.stream ?? false) !== args.stream)
) {
return false;
}
if (!search) {
return true;
}
const fields = [action.name, action.summary ?? '', ...action.aliases].map((s) =>
s.toLowerCase(),
);
if (args.match !== 'keywords') {
return fields.some((field) => field.includes(query));
}
return keywords.every((keyword) => {
const alternatives = SYNONYMS.find((group) => group.includes(keyword)) ?? [keyword];
return alternatives.some((alternative) =>
fields.some((field) => field.includes(alternative)),
);
});
});
if (search && args.match === 'keywords') {
const exact = (action: CatalogAction) =>
action.name.toLowerCase() === query.trim() ||
action.aliases.some((alias) => alias.toLowerCase() === query.trim());
list = list.sort((a, b) => Number(exact(b)) - Number(exact(a)));
}
const offset = typeof args.offset === 'number' ? args.offset : 0;
const limit = typeof args.limit === 'number' ? args.limit : list.length;
const page = list.slice(offset, offset + limit).map(lite);
const paginated = args.limit !== undefined || args.offset !== undefined;
return {
count: page.length,
actions: page,
...(paginated
? {
total: list.length,
next_offset: offset + page.length < list.length ? offset + page.length : null,
}
: {}),
};
}
+44
View File
@@ -0,0 +1,44 @@
import type { TransferProgress } from './client.js';
/** One reporter per request. No timers or notifications survive the request. */
export function createProgressReporter(
send: (progress: TransferProgress) => Promise<void>,
signal: AbortSignal,
now: () => number = Date.now,
) {
let latest: TransferProgress | undefined;
let sent = -1;
let sentAt = -Infinity;
const flush = async (): Promise<void> => {
if (!latest || latest.progress <= sent || signal.aborted) {
return;
}
await send(latest);
sent = latest.progress;
sentAt = now();
};
return {
async report(progress: TransferProgress): Promise<void> {
if (
!Number.isFinite(progress.progress) ||
progress.progress < (latest?.progress ?? 0) ||
(progress.total !== undefined &&
(!Number.isFinite(progress.total) ||
progress.total <= 0 ||
progress.progress > progress.total))
) {
throw new Error('Invalid transfer progress');
}
latest = progress;
if (now() - sentAt >= 250) {
await flush();
}
},
finish: flush,
};
}
+142
View File
@@ -0,0 +1,142 @@
import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';
import type { OneBotEnvelope } from './client.js';
export type FailureKind =
| 'invalid_arguments'
| 'not_found'
| 'permission'
| 'configuration'
| 'business'
| 'authentication'
| 'cancelled'
| 'timeout'
| 'transport'
| 'invalid_response'
| 'execution';
export interface Diagnostics {
outcome: 'success' | 'failed' | 'unknown';
kind?: FailureKind;
message?: string;
next_step?: string;
}
export type StructuredResult = CallToolResult & {
structuredContent: { result: unknown; diagnostics: Diagnostics };
};
export class ActionCallError extends Error {
constructor(
message: string,
readonly kind: FailureKind,
options?: ErrorOptions,
) {
super(message, options);
this.name = 'ActionCallError';
}
}
export const RESULT_SCHEMA: Tool['outputSchema'] = {
type: 'object',
properties: {
result: {},
diagnostics: {
type: 'object',
properties: {
outcome: { type: 'string', enum: ['success', 'failed', 'unknown'] },
kind: { type: 'string' },
message: { type: 'string' },
next_step: { type: 'string' },
},
required: ['outcome'],
additionalProperties: false,
},
},
required: ['result', 'diagnostics'],
additionalProperties: false,
};
// The text block is the original public contract; structured metadata is additive.
export function asText(
data: unknown,
diagnostics: Diagnostics = { outcome: 'success' },
): StructuredResult {
return {
content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
structuredContent: { result: data, diagnostics: { ...diagnostics } },
};
}
export function asError(
message: string,
kind: FailureKind = 'invalid_arguments',
nextStep = '检查工具参数;使用 get_action 查看动作要求。',
outcome: Diagnostics['outcome'] = 'failed',
): StructuredResult {
return {
content: [{ type: 'text', text: message }],
isError: true,
structuredContent: {
result: null,
diagnostics: { outcome, kind, message, next_step: nextStep },
},
};
}
export function envelopeDiagnostics(envelope: OneBotEnvelope): Diagnostics {
if (envelope.status === 'ok' && envelope.retcode === 0) {
return { outcome: 'success' };
}
if (envelope.status === 'async') {
return { outcome: 'unknown', next_step: '请求已受理,尚未确认完成;不要重复执行写操作。' };
}
if (
envelope.status === 'failed' ||
(typeof envelope.retcode === 'number' && envelope.retcode !== 0)
) {
return {
outcome: 'failed',
kind: 'business',
message:
(typeof envelope.wording === 'string' && envelope.wording) ||
(typeof envelope.message === 'string' && envelope.message) ||
`retcode=${envelope.retcode}`,
next_step: '检查原始响应的 retcode、wording 和动作参数;不要盲目重试写操作。',
};
}
return {
outcome: 'unknown',
kind: 'invalid_response',
next_step: '响应未确认成功;检查服务端版本和日志。',
};
}
export function executionError(
action: string,
error: unknown,
signal?: AbortSignal,
): StructuredResult {
const message = `调用失败 (${action}): ${error instanceof Error ? error.message : String(error)}`;
let cause = error;
const seen = new Set<unknown>();
while (cause instanceof Error && !(cause instanceof ActionCallError) && !seen.has(cause)) {
seen.add(cause);
cause = cause.cause;
}
const kind = signal?.aborted
? 'cancelled'
: cause instanceof ActionCallError
? cause.kind
: 'execution';
return asError(
message,
kind,
'操作结果可能未知。检查连接、配置和服务端状态;取消或超时不代表撤销,确认结果后再决定是否重试。',
'unknown',
);
}
+79
View File
@@ -0,0 +1,79 @@
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import { callTool, computeTools, type CallCtx } from './tools.js';
import { createProgressReporter } from './progress.js';
import { VERSION } from './version.js';
const RESOURCE_URI = 'snowluma://onebot/actions';
export function createMcpServer(ctx: Pick<CallCtx, 'mode' | 'client'>): Server {
const server = new Server(
{ name: 'snowluma-mcp', version: VERSION },
{ capabilities: { tools: {}, resources: {} } },
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: computeTools(ctx.mode),
}));
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
const token = req.params._meta?.progressToken;
const progress =
token === undefined
? undefined
: createProgressReporter(
(value) =>
extra.sendNotification({
method: 'notifications/progress',
params: { progressToken: token, ...value },
}),
extra.signal,
);
const result = await callTool(req.params.name, req.params.arguments ?? {}, {
...ctx,
signal: extra.signal,
...(progress ? { onProgress: progress.report } : {}),
});
if (!result.isError) {
await progress?.finish();
}
return result;
});
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)。`,
},
],
}));
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,
),
},
],
};
});
return server;
}
+4 -57
View File
@@ -23,15 +23,7 @@
//
// NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr.
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,
} from '@modelcontextprotocol/sdk/types.js';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import {
makeHttpClient,
@@ -39,14 +31,10 @@ import {
parseTimeoutMs,
type ActionClient,
} from './client.js';
import { callTool, computeTools, parseMode, type Mode } from './tools.js';
import { parseMode, 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';
import { createMcpServer } from './server-factory.js';
import { VERSION } from './version.js';
// ── resolve mode + client from the environment ────────────────────────────
function resolveRuntime(): { mode: Mode; client?: ActionClient } {
@@ -88,48 +76,7 @@ function resolveRuntime(): { mode: Mode; client?: ActionClient } {
const { mode, client } = resolveRuntime();
const server = new Server(
{ 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 });
});
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)。`,
},
],
}));
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,
),
},
],
};
});
const server = createMcpServer({ mode, client });
const transport = new StdioServerTransport();
await server.connect(transport);
+152 -54
View File
@@ -8,10 +8,22 @@
// 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 type { 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';
import { discover, FILTER_PROPERTIES } from './discovery.js';
import {
asText,
asError,
envelopeDiagnostics,
executionError,
RESULT_SCHEMA,
type Diagnostics,
type StructuredResult,
} from './results.js';
import { VERSION } from './version.js';
import type { TransferProgress } from './client.js';
export type Mode = 'docs' | 'read' | 'write';
@@ -38,26 +50,15 @@ for (const a of ACTIONS) {
}
}
/** 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,
};
}
const DOCS_TOOLS: Tool[] = [
{
name: 'list_actions',
description: '列出 OneBot action,支持按分类过滤。返回名称、摘要、别名及执行类型。',
description:
'列出 OneBot action,支持分类、读写类型、流式类型筛选和可选分页。省略分页时返回全部匹配项。',
inputSchema: {
type: 'object',
properties: {
category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' },
...FILTER_PROPERTIES,
},
additionalProperties: false,
},
@@ -76,10 +77,19 @@ const DOCS_TOOLS: Tool[] = [
},
{
name: 'search_actions',
description: '按名称、摘要或别名搜索 action。',
description:
'按名称、摘要或别名搜索 action。默认保留子串匹配;match=keywords 启用多关键词和常用中英文同义词,支持筛选及分页。',
inputSchema: {
type: 'object',
properties: { query: { type: 'string', description: '关键字' } },
properties: {
query: { type: 'string', description: '关键字;keywords 模式可用空格分隔多个词' },
match: {
type: 'string',
enum: ['substring', 'keywords'],
description: '默认 substring',
},
...FILTER_PROPERTIES,
},
required: ['query'],
additionalProperties: false,
},
@@ -91,6 +101,22 @@ const DOCS_TOOLS: Tool[] = [
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
annotations: { readOnlyHint: true, openWorldHint: false },
},
{
name: 'get_runtime_info',
description:
'查看当前 MCP 模式、执行能力、文件限制和目录版本。默认不访问服务端;check_connection=true 仅在执行模式主动查询登录账号、状态和版本。静态目录不代表服务端支持全部动作。',
inputSchema: {
type: 'object',
properties: {
check_connection: {
type: 'boolean',
description: '主动进行三项只读查询,默认 false',
},
},
additionalProperties: false,
},
annotations: { readOnlyHint: true, openWorldHint: true },
},
];
const EXEC_INPUT_SCHEMA = {
@@ -150,23 +176,16 @@ export function computeTools(mode: Mode): Tool[] {
tools.push(invokeTool());
}
return tools;
return tools.map((tool) => ({ ...tool, outputSchema: RESULT_SCHEMA }));
}
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 type ToolResult = StructuredResult;
export interface CallCtx {
mode: Mode;
client?: ActionClient;
signal?: AbortSignal;
onProgress?: (progress: TransferProgress) => Promise<void>;
}
export async function callTool(
@@ -175,10 +194,13 @@ export async function callTool(
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 'list_actions':
case 'search_actions': {
try {
return asText(discover(ACTIONS, args, name === 'search_actions'));
} catch (error) {
return asError(error instanceof Error ? error.message : String(error));
}
}
case 'get_action': {
@@ -188,31 +210,24 @@ export async function callTool(
if (!action) {
return asError(
`未找到 action: ${JSON.stringify(q)}。用 list_actions / search_actions 查可用项。`,
'not_found',
'使用 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 'get_runtime_info':
return runtimeInfo(args, ctx);
case 'query_action':
return execute(args, ctx, 'read');
case 'invoke_action':
return execute(args, ctx, 'write');
default:
return asError(`未知工具: ${name}`);
return asError(`未知工具: ${name}`, 'not_found', '使用 tools/list 查看可用工具。');
}
}
@@ -224,15 +239,27 @@ async function execute(
kind: 'read' | 'write',
): Promise<ToolResult> {
if (kind === 'write' && ctx.mode !== 'write') {
return asError('写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。');
return asError(
'写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。',
'permission',
'需要写操作时,请由操作者明确启用 write 模式。',
);
}
if (kind === 'read' && ctx.mode !== 'read' && ctx.mode !== 'write') {
return asError('执行未启用:需配置 SNOWLUMA_MCP_ENDPOINT。');
return asError(
'执行未启用:需配置 SNOWLUMA_MCP_ENDPOINT。',
'permission',
'配置端点并选择 read 或 write 模式后重启 MCP。',
);
}
if (!ctx.client) {
return asError('未配置 OneBot 端点(SNOWLUMA_MCP_ENDPOINT),无法执行。');
return asError(
'未配置 OneBot 端点(SNOWLUMA_MCP_ENDPOINT),无法执行。',
'configuration',
'检查 MCP 端点配置。',
);
}
const action = typeof args.action === 'string' ? args.action : '';
@@ -241,12 +268,16 @@ async function execute(
if (!cat) {
return asError(
`未知 action: ${JSON.stringify(action)}。用 list_actions / search_actions 查可用项。`,
'not_found',
'使用 list_actions / search_actions 查找动作。',
);
}
if (kind === 'read' && !cat.readOnly) {
return asError(
`${action} 是写操作,不能用 query_action;请用 invoke_action(需 SNOWLUMA_MCP_MODE=write)。`,
'permission',
'需写模式和 invoke_action;不要通过只读工具绕过写操作限制。',
);
}
@@ -290,14 +321,81 @@ async function execute(
}
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);
ctx.signal?.throwIfAborted();
if (cat.stream) {
const result = await ctx.client.callStream(action, params, {
...(inputFile ? { inputFile } : {}),
...(ctx.signal ? { signal: ctx.signal } : {}),
...(ctx.onProgress ? { onProgress: ctx.onProgress } : {}),
});
return asText(result, envelopeDiagnostics(result.terminal));
}
const result = await ctx.client.call(
action,
params,
ctx.signal ? { signal: ctx.signal } : undefined,
);
return asText(result, envelopeDiagnostics(result));
} catch (err) {
return asError(`调用失败 (${action}): ${err instanceof Error ? err.message : String(err)}`);
return executionError(action, err, ctx.signal);
}
}
async function runtimeInfo(args: Record<string, unknown>, ctx: CallCtx): Promise<ToolResult> {
if (args.check_connection !== undefined && typeof args.check_connection !== 'boolean') {
return asError('check_connection 必须是布尔值。');
}
const enabled = ctx.mode !== 'docs' && !!ctx.client;
if (args.check_connection && !enabled) {
return asError(
'当前模式不能检查连接:需配置端点并启用 read 或 write 模式。',
'permission',
'先用 get_runtime_info 查看本地模式,再由操作者配置连接。',
);
}
const overview = {
mode: ctx.mode,
execution_enabled: enabled,
write_enabled: enabled && ctx.mode === 'write',
catalog: {
version: VERSION,
action_count: ACTIONS.length,
source: 'bundled',
server_support: 'unknown',
},
transport: enabled ? (ctx.client?.info ?? null) : null,
connection_checked: args.check_connection === true,
};
if (!args.check_connection) {
return asText(overview);
}
const checks: Record<string, unknown> = {};
let outcome: Diagnostics['outcome'] = 'success';
for (const action of ['get_login_info', 'get_status', 'get_version_info']) {
const result = await execute({ action }, ctx, 'read');
checks[action] = result.structuredContent;
const diagnostics = result.structuredContent.diagnostics;
if (
diagnostics.outcome === 'unknown' ||
(diagnostics.outcome === 'failed' && outcome === 'success')
) {
outcome = diagnostics.outcome;
}
}
return asText(
{ ...overview, checks },
outcome === 'success'
? { outcome }
: { outcome, next_step: '查看 checks 中各项诊断;目录版本不等于服务端能力声明。' },
);
}
+6
View File
@@ -0,0 +1,6 @@
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {
version: string;
};
export const VERSION = pkg.version;