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

+1
View File
@@ -76,6 +76,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
- **Shared types or actions:** run workspace typechecking as well as behavior tests. A passing Vitest run does not prove type correctness.
- **SDK packaging:** keep the SDK's `NodeNext` build and explicit `.js` relative imports, including type-only exports. Its package tests compile fresh output and check native Node.js imports, consumer declarations, and complete action-map coverage. The SDK action catalog must match OneBot's executable names; `packages/onebot/tests/sdk-actions.test.ts` checks this without adding a runtime dependency on server code. SDK parameter/result contracts remain independent of server types; keep consumer examples under `packages/sdk/tests/fixtures` aligned with the server parser checks in `packages/onebot/tests/sdk-action-params.test.ts`.
- **SDK streams:** preserve the single-response client methods and use the additive interfaces in [STREAMING.md](packages/sdk/STREAMING.md) for file transfers. Test framing, cancellation, bounded buffering and incomplete transfers in the SDK; `packages/onebot/tests/sdk-streaming.test.ts` checks real adapter/handler round trips in temporary storage without QQ.
- **MCP agents:** preserve existing text results, business-error envelopes, default search matching and mode gates when extending the tools. Additive structured results, discovery controls, runtime checks, cancellation and progress are documented in [AGENT_FEATURES.md](packages/mcp/AGENT_FEATURES.md). Use isolated HTTP and MCP transports in tests; local runtime inspection must not query a live account.
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
+103
View File
@@ -0,0 +1,103 @@
# MCP agent features
These additions preserve the existing tool names, action parameters, text results,
and read/write gates. No endpoint is contacted by catalog tools or by a local
runtime overview. The action catalog remains a bundled snapshot, not a claim
about the connected server's capabilities.
## Structured results
Every tool advertises an `outputSchema` and returns `structuredContent` alongside
the existing `content` text block:
```json
{
"result": { "status": "ok", "retcode": 0, "data": { "message_id": -123 } },
"diagnostics": { "outcome": "success" }
}
```
`result` is the original payload, including arrays such as the category list.
It is `null` for an MCP tool error. `diagnostics.outcome` is `success`, `failed`,
or `unknown`; failures can include `kind`, `message`, and `next_step`.
Ordinary OneBot business failures still return their original envelope without
setting `isError`. Their structured diagnostics indicate failure. An asynchronous
acknowledgement or a response that does not confirm success has outcome `unknown`.
Transport errors and existing tool/stream errors still set `isError: true`.
Error categories describe known causes; unclassified execution errors are not
guessed from message strings. Neither tool execution nor connection checks retry
automatically. Negative message IDs remain valid and are preserved unchanged.
## Search, filters, and pagination
`search_actions` retains its original case-insensitive substring matching and
catalog order unless `match: "keywords"` is requested. Keyword mode combines
space-separated terms with AND, recognizes a small set of common Chinese/English
synonyms, and ranks exact action names or aliases first.
```json
{
"query": "群 禁言",
"match": "keywords",
"read_only": false,
"stream": false,
"limit": 10,
"offset": 0
}
```
Both `list_actions` and `search_actions` accept optional `category`, `read_only`,
`stream`, `limit` (1–200), and `offset` (non-negative integer). Omitting pagination
returns the complete matching list and preserves `{count, actions}`. With `limit`
or `offset`, `count` is the returned page size, `total` is the matching count, and
`next_offset` is the next page offset or `null`. Pagination applies to the bundled
catalog; it does not issue server requests.
## Runtime overview
`get_runtime_info({})` returns:
- The effective `mode`, `execution_enabled`, and `write_enabled`.
- The bundled catalog version and action count. `server_support` remains
`unknown`; a matching version alone does not prove action support.
- In execution mode, effective request timeout, file size and directory quota
limits, concurrent stream limit, download directory, upload root, and whether
automatic upload is enabled. In docs mode, `transport` is `null`.
- `connection_checked: false`. Local configuration is not proof of a live login.
The overview does not expose the endpoint, access token, or authorization headers.
Configured file paths are paths on the MCP host. All stream actions still require
write mode; `upload_enabled` describes the configured file root, not permission
to bypass that gate.
`get_runtime_info({"check_connection": true})` is available only in read/write
mode with a client. It explicitly queries `get_login_info`, `get_status`, and
`get_version_info`, using the ordinary read-only execution gate. Each entry under
`checks` contains its original response and diagnostics. Partial failures remain
visible. Check the returned status data for online state; a successful HTTP
exchange alone does not establish that the account is online.
## Cancellation and progress
MCP cancellation now reaches ordinary HTTP calls as well as stream actions,
including response-body reads. Ordinary calls retain their request timeout;
streams retain separate connection and per-read idle timeouts. A cancelled call
does not automatically retry. Cancellation or timeout can leave a remote write's
outcome unknown: stopping the wait does not undo an operation already received
by SnowLuma.
When a caller includes `_meta.progressToken`, stream execution emits standard
`notifications/progress` notifications with the same token. File downloads report
decoded bytes written; automatic uploads report bytes acknowledged by the server.
Generic streams report accepted frame counts. A total is included only when a
positive file size is known. Empty files and unknown-size downloads omit it.
Notifications are limited to one per 250 ms, plus the final pending update before
a successful response. Values increase, notifications stop on cancellation or
completion, and callers without a progress token receive none. Notification
delivery failures are surfaced. Progress describes transferred data, not final
commit: only a successful tool result confirms file validation and completion.
The existing file containment, quotas, partial-file cleanup and upload-reset
behavior are unchanged. File bytes never appear in progress messages.
+2 -1
View File
@@ -20,7 +20,8 @@
"types": "./dist/server.d.ts",
"files": [
"dist",
"README.md"
"README.md",
"AGENT_FEATURES.md"
],
"scripts": {
"clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true})\"",
+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;
+275
View File
@@ -0,0 +1,275 @@
import { describe, expect, it, vi } from 'vitest';
import { callTool, computeTools } from '../src/tools';
import { ACTIONS } from '../src/generated/catalog';
import type { ActionClient, OneBotEnvelope } from '../src/client';
import { ActionCallError } from '../src/results';
const docs = { mode: 'docs' as const };
function client(
reply: OneBotEnvelope = { status: 'ok', retcode: 0, data: { message_id: -123 } },
): ActionClient {
return {
call: vi.fn(async () => reply),
callStream: vi.fn(async () => ({ frame_count: 1, frames: [], terminal: reply })),
};
}
function text(result: Awaited<ReturnType<typeof callTool>>) {
expect(result.content[0].type).toBe('text');
return result.content[0].type === 'text' ? result.content[0].text : '';
}
describe('additive structured results', () => {
it.each(['list_actions', 'list_categories', 'get_action', 'search_actions'])(
'keeps the original text payload for %s',
async (name) => {
const result = await callTool(name, { name: 'get_status', query: 'get_status' }, docs);
expect(result.structuredContent.result).toEqual(JSON.parse(text(result)));
expect(result.structuredContent.diagnostics).toEqual({ outcome: 'success' });
expect(
computeTools('docs').find((tool) => tool.name === name)?.outputSchema,
).toBeDefined();
},
);
it.each([
{ status: 'ok', retcode: 0, data: { message_id: -123 } },
{ status: 'failed', retcode: 1404, wording: 'not found' },
{ status: 'async', retcode: 1 },
])('preserves the OneBot envelope and isError contract ($status)', async (reply) => {
const result = await callTool(
'invoke_action',
{ action: 'send_group_msg' },
{ mode: 'write', client: client(reply) },
);
expect(text(result)).toBe(JSON.stringify(reply, null, 2));
expect(result.isError).toBeUndefined();
expect(result.structuredContent.result).toEqual(reply);
expect(result.structuredContent.diagnostics.outcome).toBe(
reply.status === 'ok' ? 'success' : reply.status === 'failed' ? 'failed' : 'unknown',
);
});
it('reports permission failures without contacting OneBot', async () => {
const onebot = client();
const result = await callTool(
'query_action',
{ action: 'send_group_msg' },
{ mode: 'read', client: onebot },
);
expect(result.isError).toBe(true);
expect(result.structuredContent.diagnostics).toMatchObject({
outcome: 'failed',
kind: 'permission',
});
expect(onebot.call).not.toHaveBeenCalled();
});
it.each(['timeout', 'cancelled', 'authentication', 'transport', 'invalid_response'] as const)(
'makes %s observable without claiming a write was rolled back',
async (kind) => {
const onebot = client();
onebot.call = vi.fn(async () => {
throw new ActionCallError('request failed', kind);
});
const result = await callTool(
'invoke_action',
{ action: 'send_group_msg' },
{ mode: 'write', client: onebot },
);
expect(result.isError).toBe(true);
expect(result.structuredContent.diagnostics).toMatchObject({
outcome: 'unknown',
kind,
});
expect(result.structuredContent.diagnostics.next_step).toContain('不代表撤销');
expect(onebot.call).toHaveBeenCalledTimes(1);
},
);
it('does not report an incomplete response as successful', async () => {
const onebot = client();
onebot.call = async () => JSON.parse('{"data":null}');
const result = await callTool(
'query_action',
{ action: 'get_status' },
{ mode: 'read', client: onebot },
);
expect(result.structuredContent.diagnostics).toMatchObject({
outcome: 'unknown',
kind: 'invalid_response',
});
expect(text(result)).toBe('{\n "data": null\n}');
});
it('keeps malformed peer fields in the original payload without breaking the diagnostics schema', async () => {
const onebot = client();
onebot.call = async () =>
JSON.parse('{"status":"failed","retcode":1400,"wording":{"unexpected":true}}');
const result = await callTool(
'query_action',
{ action: 'get_status' },
{ mode: 'read', client: onebot },
);
expect(result.structuredContent.diagnostics.message).toBe('retcode=1400');
expect(JSON.parse(text(result)).wording).toEqual({ unexpected: true });
});
});
describe('optional discovery controls', () => {
it('keeps legacy matching, ordering and response fields by default', async () => {
const result = await callTool('search_actions', { query: '群 禁言' }, docs);
expect(JSON.parse(text(result))).toEqual({ count: 0, actions: [] });
const all = JSON.parse(text(await callTool('list_actions', {}, docs)));
expect(Object.keys(all)).toEqual(['count', 'actions']);
expect(all.actions.map((action: { name: string }) => action.name)).toEqual(
ACTIONS.map((action) => action.name),
);
});
it.each([
['群 禁言', 'set_group_ban'],
['历史消息', 'get_group_msg_history'],
['私聊 history', 'get_friend_msg_history'],
['group mute', 'set_group_ban'],
])('finds %s with optional keyword matching', async (query, expected) => {
const data = JSON.parse(
text(await callTool('search_actions', { query, match: 'keywords' }, docs)),
);
expect(data.actions.map((action: { name: string }) => action.name)).toContain(expected);
});
it('ranks an exact alias first and combines filters', async () => {
const exact = JSON.parse(
text(
await callTool('search_actions', { query: 'nc_get_rkey', match: 'keywords' }, docs),
),
);
expect(exact.actions[0].name).toBe('get_rkey');
const filtered = JSON.parse(
text(
await callTool(
'search_actions',
{
query: '群',
match: 'keywords',
category: '群管理',
read_only: false,
stream: false,
},
docs,
),
),
);
expect(filtered.count).toBeGreaterThan(0);
expect(
filtered.actions.every(
(action: { category: string; readOnly: boolean; stream: boolean }) =>
action.category === '群管理' && !action.readOnly && !action.stream,
),
).toBe(true);
});
it('paginates deterministically with explicit totals and termination', async () => {
const names: string[] = [];
let offset: number | null = 0;
while (offset !== null) {
const data = JSON.parse(
text(await callTool('list_actions', { limit: 37, offset }, docs)),
);
expect(data.total).toBe(ACTIONS.length);
expect(data.count).toBe(data.actions.length);
names.push(...data.actions.map((action: { name: string }) => action.name));
offset = data.next_offset;
}
expect(names).toEqual(ACTIONS.map((action) => action.name));
const beyond = JSON.parse(text(await callTool('list_actions', { offset: 9999 }, docs)));
expect(beyond).toEqual({ count: 0, actions: [], total: ACTIONS.length, next_offset: null });
});
it.each([
{ limit: 0 },
{ limit: 201 },
{ offset: -1 },
{ offset: 0.5 },
{ stream: 'true' },
{ read_only: 1 },
{ match: 'typo' },
])('rejects invalid new options (%j)', async (options) => {
const result = await callTool('search_actions', { query: '', ...options }, docs);
expect(result.isError).toBe(true);
expect(result.structuredContent.diagnostics.kind).toBe('invalid_arguments');
});
});
describe('runtime overview and caller cancellation', () => {
it('does not contact OneBot for a local overview, even if a client exists in docs mode', async () => {
const onebot = client();
const result = await callTool('get_runtime_info', {}, { ...docs, client: onebot });
expect(result.structuredContent.result).toMatchObject({
mode: 'docs',
execution_enabled: false,
write_enabled: false,
transport: null,
connection_checked: false,
catalog: { action_count: ACTIONS.length, server_support: 'unknown' },
});
expect(onebot.call).not.toHaveBeenCalled();
const denied = await callTool(
'get_runtime_info',
{ check_connection: true },
{ ...docs, client: onebot },
);
expect(denied.isError).toBe(true);
expect(onebot.call).not.toHaveBeenCalled();
});
it('only performs the three explicit read-only checks and preserves individual failures', async () => {
const onebot = client();
const controller = new AbortController();
onebot.call = vi.fn(async (action, _params, options) => {
expect(options?.signal).toBe(controller.signal);
return action === 'get_status'
? { status: 'failed', retcode: 1401, wording: 'unauthorized' }
: { status: 'ok', retcode: 0, data: { action } };
});
const result = await callTool(
'get_runtime_info',
{ check_connection: true },
{ mode: 'read', client: onebot, signal: controller.signal },
);
expect(vi.mocked(onebot.call).mock.calls.map(([action]) => action)).toEqual([
'get_login_info',
'get_status',
'get_version_info',
]);
expect(result.structuredContent.diagnostics.outcome).toBe('failed');
expect(result.structuredContent.result).toMatchObject({
checks: {
get_status: { result: { retcode: 1401 }, diagnostics: { outcome: 'failed' } },
},
});
});
it('forwards ordinary request cancellation and does not start pre-cancelled calls', async () => {
const controller = new AbortController();
const onebot = client();
await callTool(
'query_action',
{ action: 'get_status' },
{ mode: 'read', client: onebot, signal: controller.signal },
);
expect(onebot.call).toHaveBeenCalledWith('get_status', {}, { signal: controller.signal });
controller.abort();
const result = await callTool(
'query_action',
{ action: 'get_status' },
{ mode: 'read', client: onebot, signal: controller.signal },
);
expect(onebot.call).toHaveBeenCalledTimes(1);
expect(result.structuredContent.diagnostics.kind).toBe('cancelled');
});
});
+124
View File
@@ -0,0 +1,124 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createServer, type Server } from 'node:http';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { makeHttpClient } from '../src/client';
const dirs: string[] = [];
const servers: Server[] = [];
afterEach(async () => {
for (const server of servers.splice(0)) {
server.closeAllConnections();
await new Promise<void>((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
);
}
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function directory() {
const dir = mkdtempSync(join(tmpdir(), 'mcp-cancel-'));
dirs.push(dir);
return dir;
}
describe('ordinary HTTP cancellation', () => {
it.each([false, true])(
'aborts the actual HTTP request (headers received: %s)',
async (sendHeaders) => {
const started = Promise.withResolvers<void>();
const disconnected = Promise.withResolvers<void>();
let count = 0;
const server = createServer((_request, response) => {
count++;
response.on('close', () => disconnected.resolve());
if (sendHeaders) {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.write('{"status":');
}
started.resolve();
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') {
throw new Error('missing test server port');
}
const client = makeHttpClient({
endpoint: `http://127.0.0.1:${address.port}`,
streamDir: directory(),
timeoutMs: 5000,
});
const controller = new AbortController();
const outcome = client
.call('get_status', {}, { signal: controller.signal })
.catch((error) => error);
await started.promise;
controller.abort(new Error('caller cancelled'));
expect(await outcome).toMatchObject({ kind: 'cancelled' });
await disconnected.promise;
expect(count).toBe(1);
},
);
it('does not issue an HTTP request when already cancelled', async () => {
const fetcher = vi.fn<typeof fetch>();
const client = makeHttpClient({
endpoint: 'http://unused.invalid',
streamDir: directory(),
fetch: fetcher,
});
await expect(
client.call('get_status', {}, { signal: AbortSignal.abort() }),
).rejects.toMatchObject({ kind: 'cancelled' });
expect(fetcher).not.toHaveBeenCalled();
});
it('retains the ordinary timeout and exposes its cause', async () => {
const fetcher: typeof fetch = vi.fn(
async (_input, init) =>
new Promise((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), {
once: true,
});
}),
);
const client = makeHttpClient({
endpoint: 'http://unused.invalid',
streamDir: directory(),
fetch: fetcher,
timeoutMs: 20,
});
await expect(client.call('get_status', {})).rejects.toMatchObject({ kind: 'timeout' });
expect(fetcher).toHaveBeenCalledTimes(1);
});
it('reports resolved limits and paths without endpoint credentials', () => {
const dir = directory();
const client = makeHttpClient({
endpoint: 'https://user:[email protected]/path?token=secret',
accessToken: 'secret',
streamDir: dir,
uploadRoot: dir,
maxStreamBytes: 123,
timeoutMs: 456,
});
expect(client.info).toMatchObject({
timeout_ms: 456,
max_stream_bytes: 123,
download_quota_bytes: 246,
max_active_streams: 4,
upload_enabled: true,
});
expect(client.info?.upload_root).toBe(client.info?.download_directory);
expect(JSON.stringify(client.info)).not.toMatch(/secret|example\.invalid/);
});
});
+154 -6
View File
@@ -3,7 +3,12 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { makeHttpClient, parseMaxStreamBytes, parseTimeoutMs } from '../src/client';
import {
makeHttpClient,
parseMaxStreamBytes,
parseTimeoutMs,
type TransferProgress,
} from '../src/client';
const tempDirs: string[] = [];
@@ -169,7 +174,17 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
)) as unknown as typeof fetch;
const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch });
const result = await client.callStream('test_download_stream', {});
const progress: TransferProgress[] = [];
const result = await client.callStream(
'test_download_stream',
{},
{
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(progress.map((update) => update.progress)).toEqual([1, 2]);
expect(result).toEqual({ frame_count: 2, frames: [frames[0]], terminal: frames[1] });
});
@@ -225,7 +240,18 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
streamDir,
});
const result = await client.callStream('download_file_stream', { file: 'remote-id' });
const progress: TransferProgress[] = [];
const result = await client.callStream(
'download_file_stream',
{ file: 'remote-id' },
{
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(progress.map((update) => update.progress)).toEqual([0, 997, content.length]);
expect(progress.every((update) => update.total === content.length)).toBe(true);
expect(Object.keys(result).sort()).toEqual([
'file_path',
@@ -632,11 +658,19 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
uploadRoot: root,
});
const progress: TransferProgress[] = [];
const result = await client.callStream(
'upload_file_stream',
{ file_retention: 0 },
{ inputFile },
{
inputFile,
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(progress.map((update) => update.progress)).toEqual([0, 512 * 1024, content.length]);
expect(progress.every((update) => update.total === content.length)).toBe(true);
expect(requests).toHaveLength(3);
expect(requests.every((request) => request.action === 'upload_file_stream')).toBe(true);
@@ -789,7 +823,21 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
uploadRoot: root,
});
const result = await client.callStream('upload_file_stream', {}, { inputFile });
const progress: TransferProgress[] = [];
const result = await client.callStream(
'upload_file_stream',
{},
{
inputFile,
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(
progress.every((update) => update.progress === 0 && update.total === undefined),
).toBe(true);
expect(progress).toHaveLength(2);
expect(requests).toHaveLength(2);
expect(requests[0].params).toMatchObject({
@@ -941,10 +989,110 @@ describe('makeHttpClient — OneBot HTTP wiring', () => {
streamDir,
});
const result = await client.callStream('download_file_stream', {});
const progress: TransferProgress[] = [];
const result = await client.callStream(
'download_file_stream',
{},
{
onProgress: async (update) => {
progress.push(update);
},
},
);
expect(result.file_size).toBe(content.length);
expect(fs.readFileSync(result.file_path).equals(content)).toBe(true);
expect(progress.map((update) => update.progress)).toEqual([0, content.length]);
expect(progress.every((update) => update.total === undefined)).toBe(true);
});
it('cleans partial downloads and releases admission when progress delivery fails', async () => {
const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-progress-'));
tempDirs.push(streamDir);
const frame = {
status: 'ok',
retcode: 0,
data: { type: 'stream', data_type: 'file_info', file_name: 'test.bin', file_size: 3 },
};
const fakeFetch: typeof fetch = async () =>
new Response(`${JSON.stringify(frame)}\r\n\r\n`);
const client = makeHttpClient({
endpoint: 'http://unused.invalid',
streamDir,
maxStreamBytes: 3,
fetch: fakeFetch,
});
for (let attempt = 0; attempt < 5; attempt++) {
await expect(
client.callStream(
'download_file_stream',
{},
{
onProgress: async () => {
throw new Error('notification failed');
},
},
),
).rejects.toThrow('notification failed');
expect(fs.readdirSync(streamDir)).toEqual([]);
}
});
it('stops processing already-buffered frames after a cancellation during progress', async () => {
const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-progress-'));
tempDirs.push(streamDir);
const frames = [
{
status: 'ok',
retcode: 0,
data: {
type: 'stream',
data_type: 'file_info',
file_name: 'test.bin',
file_size: 1,
},
},
{
status: 'ok',
retcode: 0,
data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 1, data: 'eA==' },
},
{
status: 'ok',
retcode: 0,
data: {
type: 'response',
data_type: 'file_complete',
total_bytes: 1,
total_chunks: 1,
},
},
];
const controller = new AbortController();
const fakeFetch: typeof fetch = async () =>
new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''));
const client = makeHttpClient({
endpoint: 'http://unused.invalid',
streamDir,
fetch: fakeFetch,
});
const updates: number[] = [];
await expect(
client.callStream(
'download_file_stream',
{},
{
signal: controller.signal,
onProgress: async (update) => {
updates.push(update.progress);
controller.abort();
},
},
),
).rejects.toThrow(/cancelled/);
expect(updates).toEqual([0]);
expect(fs.readdirSync(streamDir)).toEqual([]);
});
it('requires file_info as the first successful frame for known file-download actions', async () => {
+198
View File
@@ -0,0 +1,198 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
import { createMcpServer } from '../src/server-factory';
import { createProgressReporter } from '../src/progress';
import type { ActionClient, TransferProgress } from '../src/client';
const close: Array<() => Promise<void>> = [];
afterEach(async () => {
for (const cleanup of close.splice(0).reverse()) {
await cleanup();
}
});
async function connect(onebot?: ActionClient) {
const server = createMcpServer({ mode: onebot ? 'write' : 'docs', client: onebot });
const client = new Client({ name: 'test-agent', version: '1.0.0' });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
close.push(
() => server.close(),
() => client.close(),
);
await server.connect(serverTransport);
await client.connect(clientTransport);
return { client, serverTransport };
}
function fakeOneBot(): ActionClient {
return {
call: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { online: true } })),
callStream: vi.fn(async (_action, _params, options) => {
for (const progress of [0, 3, 7]) {
await options?.onProgress?.({ progress, total: 7, message: 'transferred bytes' });
}
return { frame_count: 2, frames: [], terminal: { status: 'ok', retcode: 0 } };
}),
};
}
describe('MCP protocol compatibility', () => {
it('publishes output schemas that a real MCP client can validate for every tool', async () => {
const { client } = await connect(fakeOneBot());
const tools = await client.listTools();
for (const tool of tools.tools) {
expect(tool.outputSchema).toBeDefined();
const result = await client.callTool({
name: tool.name,
arguments: { name: 'get_status', query: 'history', action: 'get_status' },
});
expect(result.isError).toBeUndefined();
expect(result.structuredContent).toMatchObject({ diagnostics: { outcome: 'success' } });
}
const failure = await client.callTool({
name: 'get_action',
arguments: { name: 'missing_action' },
});
expect(failure.isError).toBe(true);
expect(failure.structuredContent).toMatchObject({ diagnostics: { kind: 'not_found' } });
const resources = await client.listResources();
expect(resources.resources.map((resource) => resource.uri)).toEqual([
'snowluma://onebot/actions',
]);
const catalog = await client.readResource({ uri: 'snowluma://onebot/actions' });
expect(catalog.contents).toHaveLength(1);
});
it('sends bounded progress only when requested and flushes the final update before the response', async () => {
const { client, serverTransport } = await connect(fakeOneBot());
const send = vi.spyOn(serverTransport, 'send');
await client.callTool({
name: 'invoke_action',
arguments: { action: 'test_download_stream' },
});
expect(
send.mock.calls.some(
([message]) => 'method' in message && message.method === 'notifications/progress',
),
).toBe(false);
const progress: number[] = [];
const result = await client.callTool(
{ name: 'invoke_action', arguments: { action: 'test_download_stream' } },
undefined,
{
onprogress: (update) => {
progress.push(update.progress);
},
},
);
expect(progress).toEqual([0, 7]);
expect(result.isError).toBeUndefined();
const count = progress.length;
await new Promise((resolve) => setImmediate(resolve));
expect(progress).toHaveLength(count);
});
it.each([0, 'upload-token'])('preserves progress token %j', async (token) => {
const { client, serverTransport } = await connect(fakeOneBot());
const send = vi.spyOn(serverTransport, 'send');
await client.request(
{
method: 'tools/call',
params: {
name: 'invoke_action',
arguments: { action: 'test_download_stream' },
_meta: { progressToken: token },
},
},
CallToolResultSchema,
);
const notifications = send.mock.calls
.map(([message]) => message)
.filter(
(message) => 'method' in message && message.method === 'notifications/progress',
);
expect(notifications).toHaveLength(2);
for (const notification of notifications) {
expect(notification).toMatchObject({ params: { progressToken: token } });
}
});
it('propagates a real MCP cancellation notification to ordinary execution', async () => {
const started = Promise.withResolvers<void>();
const aborted = Promise.withResolvers<void>();
const onebot = fakeOneBot();
onebot.call = vi.fn(
async (_action, _params, options) =>
new Promise((_resolve, reject) => {
options?.signal?.addEventListener(
'abort',
() => {
aborted.resolve();
reject(options.signal?.reason);
},
{ once: true },
);
started.resolve();
}),
);
const { client } = await connect(onebot);
const controller = new AbortController();
const outcome = client
.callTool({ name: 'query_action', arguments: { action: 'get_status' } }, undefined, {
signal: controller.signal,
})
.catch((error) => error);
await started.promise;
controller.abort(new Error('cancel wait'));
expect(await outcome).toBeInstanceOf(Error);
await aborted.promise;
expect(onebot.call).toHaveBeenCalledTimes(1);
});
});
describe('per-request progress', () => {
it('rate limits, enforces increasing values, and stops on cancellation', async () => {
let time = 0;
const controller = new AbortController();
const updates: TransferProgress[] = [];
const reporter = createProgressReporter(
async (value) => {
updates.push(value);
},
controller.signal,
() => time,
);
await reporter.report({ progress: 0, message: 'start' });
await reporter.report({ progress: 1, message: 'one' });
await reporter.report({ progress: 2, message: 'two' });
expect(updates.map((value) => value.progress)).toEqual([0]);
time = 250;
await reporter.report({ progress: 3, message: 'three' });
await reporter.report({ progress: 3, message: 'duplicate' });
await reporter.finish();
expect(updates.map((value) => value.progress)).toEqual([0, 3]);
await expect(reporter.report({ progress: 2, message: 'backwards' })).rejects.toThrow(
'Invalid transfer progress',
);
controller.abort();
time = 500;
await reporter.report({ progress: 4, message: 'cancelled' });
await reporter.finish();
expect(updates).toHaveLength(2);
});
it('surfaces notification delivery failure', async () => {
const reporter = createProgressReporter(async () => {
throw new Error('transport closed');
}, new AbortController().signal);
await expect(reporter.report({ progress: 1, message: 'one' })).rejects.toThrow(
'transport closed',
);
});
});
+2 -1
View File
@@ -49,12 +49,13 @@ describe('computeTools — mode gating', () => {
expect(() => parseMode(invalid), invalid).toThrow(/SNOWLUMA_MCP_MODE/);
}
});
it('docs mode exposes only the 4 catalog tools', () => {
it('docs mode exposes catalog tools and local runtime information', () => {
expect(computeTools('docs').map((t) => t.name)).toEqual([
'list_actions',
'get_action',
'search_actions',
'list_categories',
'get_runtime_info',
]);
});
it('read mode adds query_action only (no invoke_action)', () => {