From bb560309794e208f3fedb268627b462ba5e10185 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 10 Jul 2026 03:06:13 +0800 Subject: [PATCH] feat(mcp): support stream actions --- packages/mcp/README.md | 74 ++- packages/mcp/src/client.ts | 751 +++++++++++++++++++++++++++++- packages/mcp/src/server.ts | 31 +- packages/mcp/src/tools.ts | 57 ++- packages/mcp/tests/client.test.ts | 655 +++++++++++++++++++++++++- packages/mcp/tests/tools.test.ts | 89 +++- 6 files changed, 1616 insertions(+), 41 deletions(-) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 91fcda6c..92bea428 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -23,7 +23,7 @@ Add to your MCP client (Claude Desktop, Cline, …) — no endpoint, no executio ### Docs tools -- `list_actions({ category? })` — lightweight index (name / category / summary / aliases / `readOnly`). +- `list_actions({ category? })` — lightweight index (name / category / summary / aliases / `readOnly` / `stream`). - `get_action({ name })` — full doc for one action incl. `inputSchema` and `readOnly` (accepts aliases). - `search_actions({ query })` — fuzzy match over name / summary / aliases. - `list_categories()` — categories and their action counts. @@ -38,12 +38,15 @@ Point the server at a running SnowLuma instance's **OneBot HTTP endpoint** (the - `query_action({ action, params? })` — calls a **read-only** action (e.g. `get_*`, `can_*`) and returns the full OneBot response. Annotated `readOnlyHint`. Refuses write actions (points you to `invoke_action`). -- `invoke_action({ action, params? })` — calls **any known** action, including ones +- `invoke_action({ action, params?, execution? })` — calls **any known** action, including ones with side effects (send a message, change a group, …). Annotated `destructiveHint` - + `openWorldHint`. **Only available in write mode.** + + `openWorldHint`. **Only available in write mode.** For automatic local-file + upload, pass `execution: { input_file: "/path/on/the/mcp/host" }` with + `action: "upload_file_stream"`; this option is never forwarded as OneBot params. -Both pass the OneBot envelope through verbatim — a logical failure (`retcode≠0`) -comes back as data with its `wording`; only a transport failure is an error. +Ordinary actions pass the OneBot envelope through verbatim — a logical failure +(`retcode≠0`) comes back as data with its `wording`. Stream protocol failures are +reported as MCP errors because they mean no complete stream result was committed. ### Configuration (env) @@ -51,8 +54,11 @@ comes back as data with its `wording`; only a transport failure is an error. | --- | --- | | `SNOWLUMA_MCP_ENDPOINT` | OneBot HTTP endpoint, e.g. `http://127.0.0.1:3000/`. **Absent → docs-only** (execution tools hidden). | | `SNOWLUMA_MCP_TOKEN` | Access token (sent as `Authorization: Bearer …`), if the endpoint requires one. | -| `SNOWLUMA_MCP_TIMEOUT_MS` | Per-request timeout (default `30000`). | -| `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. | +| `SNOWLUMA_MCP_TIMEOUT_MS` | Ordinary-action request timeout; for Stream Actions, connection timeout **and per-read idle timeout** (the idle deadline resets after every body read). Default `30000`. Invalid values fail startup. | +| `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. Invalid values fail startup. | +| `SNOWLUMA_MCP_STREAM_DIR` | Directory on the MCP host for completed Stream Action downloads. Created and validated at startup. Default: `os.tmpdir()/snowluma-mcp/downloads`. | +| `SNOWLUMA_MCP_UPLOAD_ROOT` | Existing directory on the MCP host from which automatic uploads may read. Automatic upload is disabled when absent. | +| `SNOWLUMA_MCP_MAX_STREAM_BYTES` | Per-file download/upload ceiling in bytes. Positive integer up to 4 GiB; default `4294967296`. Invalid values fail server startup. | **Read mode** — the LLM can query read-only actions, but cannot perform any write: @@ -83,13 +89,62 @@ groups, etc.). Enable deliberately: "env": { "SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/", "SNOWLUMA_MCP_TOKEN": "your-access-token", - "SNOWLUMA_MCP_MODE": "write" + "SNOWLUMA_MCP_MODE": "write", + "SNOWLUMA_MCP_STREAM_DIR": "/var/tmp/snowluma-mcp-downloads", + "SNOWLUMA_MCP_UPLOAD_ROOT": "/home/me/mcp-share" } } } } ``` +### Stream Actions + +The existing `query_action` / `invoke_action` tools automatically select the +ordinary or Stream Action HTTP transport from the generated catalog. No separate +MCP tool is needed. + +- File downloads (`download_file_stream`, `download_file_image_stream`, and + `download_file_record_stream`) are parsed frame-by-frame. Base64 chunks are + decoded directly into a randomly named `.part` file under the controlled + download directory, hashed incrementally, and atomically renamed only after a + valid `file_complete` terminal frame. The MCP result contains only + `file_path`, `file_size`, `sha256`, `frame_count`, and `terminal`; the file path + is on the **MCP host**. +- A client admits at most four top-level active Stream Actions. Download files + share a directory quota of `2 * SNOWLUMA_MCP_MAX_STREAM_BYTES`; an unknown-size + download reserves the full per-file limit while active. Successfully committed + files are **not automatically deleted** by MCP and continue consuming quota; + the operator must move or delete them when no longer needed. +- Non-file streams such as `test_download_stream` return a bounded frame summary. + Frame count, summary text, individual wire-frame size, total file bytes, and + file chunk count are capped. A malformed frame, disconnect, timeout, size + violation, caller cancellation, idle timeout, or invalid terminal cancels the + response and removes the partial file. `file_chunk` / `file_complete` frames + are never admitted without a preceding `file_info` header. +- Automatic upload reads `execution.input_file` only after resolving it inside + `SNOWLUMA_MCP_UPLOAD_ROOT` (symlink escapes are rejected), hashes and sends it + in fixed-size chunks, and asks SnowLuma to verify the final SHA-256. Transfer + fields such as `stream_id`, `chunk_data`, and `chunk_index` are MCP-owned and + must not also be supplied in `params`. The returned `file_path` is on the + **SnowLuma/OneBot host** and can be passed to a normal send-file action. +- Automatic upload reset is best-effort **before commit**. If SnowLuma commits + the file but the `file_complete` response is lost, the upload state has already + gone and reset cannot remove that committed file. Keep `file_retention` + non-zero (the default is `300000` ms) so SnowLuma eventually reclaims it. +- Stream Actions remain classified as write operations by the current catalog, + so they require `SNOWLUMA_MCP_MODE=write` and `invoke_action`. + +Example automatic upload: + +```json +{ + "action": "upload_file_stream", + "params": { "file_retention": 300000 }, + "execution": { "input_file": "/home/me/mcp-share/report.pdf" } +} +``` + ### Safety model - **Read/write is classified per action** in the source specs (by what the action @@ -99,6 +154,9 @@ groups, etc.). Enable deliberately: `invoke_action` outside write mode is refused even if a client sends it directly. - **Unknown actions are rejected** by both tools (only catalog actions are callable), so typos and non-catalog internal actions can't be driven. +- Stream downloads never put file Base64 into the model result. Downloads use a + `.part` + atomic-rename commit; automatic uploads require an explicit realpath- + fenced root and attempt a pre-commit remote reset if transfer fails. - A well-behaved client can auto-approve `query_action` (read-only) and prompt for `invoke_action` (destructive) using the MCP tool annotations. diff --git a/packages/mcp/src/client.ts b/packages/mcp/src/client.ts index 155a52c1..c80b0595 100644 --- a/packages/mcp/src/client.ts +++ b/packages/mcp/src/client.ts @@ -8,7 +8,60 @@ // `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`). +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { createHash, randomUUID } from 'node:crypto'; + const DEFAULT_TIMEOUT_MS = 30_000; +const DEFAULT_MAX_STREAM_BYTES = 4 * 1024 * 1024 * 1024; +const DEFAULT_STREAM_DIR = path.join(os.tmpdir(), 'snowluma-mcp', 'downloads'); +const MAX_GENERIC_FRAMES = 256; +const MAX_GENERIC_TEXT_BYTES = 256 * 1024; +// OneBot permits a 16 MiB decoded download chunk. Base64 expands that to +// ~21.34 MiB; 24 MiB leaves room for the JSON envelope without allowing an +// unterminated peer to grow our parser buffer without bound. +const MAX_WIRE_FRAME_BYTES = 24 * 1024 * 1024; +const UPLOAD_CHUNK_BYTES = 512 * 1024; +const MAX_FILE_CHUNKS = 200_000; +const RESET_TIMEOUT_MS = 5_000; +const MAX_ACTIVE_STREAMS = 4; +const INTERNAL_STREAM_CALL = Symbol('snowluma.mcp.internalStreamCall'); +const MCP_UPLOAD_OWNED_FIELDS = [ + 'stream_id', 'chunk_data', 'chunk_index', 'total_chunks', 'file_size', + 'expected_sha256', 'is_complete', 'reset', 'verify_only', +] as const; +const FILE_DOWNLOAD_ACTIONS = new Set([ + 'download_file_stream', + 'download_file_image_stream', + 'download_file_record_stream', +]); + +export function parseMaxStreamBytes(raw: string | undefined): number | undefined { + if (raw === undefined) return undefined; + const value = raw.trim(); + if (!/^[1-9]\d*$/.test(value)) { + throw new Error(`SNOWLUMA_MCP_MAX_STREAM_BYTES must be an integer between 1 and ${DEFAULT_MAX_STREAM_BYTES}`); + } + const parsed = Number(value); + if (!Number.isSafeInteger(parsed) || parsed > DEFAULT_MAX_STREAM_BYTES) { + throw new Error(`SNOWLUMA_MCP_MAX_STREAM_BYTES must be an integer between 1 and ${DEFAULT_MAX_STREAM_BYTES}`); + } + return parsed; +} + +export function parseTimeoutMs(raw: string | undefined): number | undefined { + if (raw === undefined) return undefined; + const value = raw.trim(); + if (!/^[1-9]\d*$/.test(value)) { + throw new Error('SNOWLUMA_MCP_TIMEOUT_MS must be a positive integer'); + } + const parsed = Number(value); + if (!Number.isSafeInteger(parsed) || parsed > 2_147_483_647) { + throw new Error('SNOWLUMA_MCP_TIMEOUT_MS must be a positive integer no greater than 2147483647'); + } + return parsed; +} /** OneBot v11 response envelope, passed through to the LLM verbatim. */ export interface OneBotEnvelope { @@ -25,34 +78,415 @@ export interface ActionClient { /** Send one OneBot action; resolves the full envelope (even on retcode≠0), * rejects only on transport-level failure (timeout / connection / bad body). */ call(action: string, params: Record): Promise; + /** Execute a Stream Action over the HTTP multi-frame transport. */ + callStream(action: string, params: Record, options?: StreamCallOptions): Promise; } +export interface StreamCallOptions { + /** MCP-host file to upload. Only valid for upload_file_stream. */ + inputFile?: string; + /** Cancellation from the originating MCP request. */ + signal?: AbortSignal; +} + +type InternalStreamCallOptions = StreamCallOptions & { [INTERNAL_STREAM_CALL]?: true }; + +interface DownloadReservation { + streamDir: string; + partPath: string; + finalPath: string; + bytes: number; +} + +// Process-wide because multiple MCP clients can target the same directory. +const downloadReservations = new Map>(); + +function reserveDownloadQuota( + streamDir: string, + partPath: string, + finalPath: string, + bytes: number, + quotaBytes: number, +): DownloadReservation { + const active = downloadReservations.get(streamDir) ?? new Map(); + const activePaths = new Set(); + let reservedBytes = 0; + for (const reservation of active.values()) { + activePaths.add(reservation.partPath); + activePaths.add(reservation.finalPath); + reservedBytes += reservation.bytes; + } + let existingBytes = 0; + for (const entry of fs.readdirSync(streamDir, { withFileTypes: true })) { + const target = path.join(streamDir, entry.name); + if (activePaths.has(target) || !entry.isFile()) continue; + try { + existingBytes += fs.lstatSync(target).size; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + } + if (existingBytes + reservedBytes + bytes > quotaBytes) { + throw new Error( + `download directory quota ${quotaBytes} bytes exceeded: existing=${existingBytes}, reserved=${reservedBytes}, requested reserve=${bytes}`, + ); + } + const reservation = { streamDir, partPath, finalPath, bytes }; + active.set(partPath, reservation); + downloadReservations.set(streamDir, active); + return reservation; +} + +function releaseDownloadQuota(reservation: DownloadReservation | undefined): void { + if (!reservation) return; + const active = downloadReservations.get(reservation.streamDir); + if (!active) return; + active.delete(reservation.partPath); + if (active.size === 0) downloadReservations.delete(reservation.streamDir); +} + +function validateStreamDirectory(streamDir: string): void { + try { + fs.accessSync( + streamDir, + fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK, + ); + // Quota admission scans the directory before opening a partial file, so + // list access is a startup requirement too. + fs.readdirSync(streamDir); + } catch (error) { + throw new Error(`streamDir is not readable, writable, and traversable: ${error instanceof Error ? error.message : String(error)}`); + } + + const probePath = path.join(streamDir, `.snowluma-mcp-write-probe-${randomUUID()}`); + let probeFd: number | undefined; + const cleanupErrors: string[] = []; + try { + probeFd = fs.openSync(probePath, 'wx', 0o600); + } catch (error) { + throw new Error(`streamDir cannot create files: ${error instanceof Error ? error.message : String(error)}`); + } + try { + fs.closeSync(probeFd); + probeFd = undefined; + } catch (error) { + cleanupErrors.push(`close probe: ${error instanceof Error ? error.message : String(error)}`); + } + try { + fs.unlinkSync(probePath); + } catch (error) { + cleanupErrors.push(`remove probe: ${error instanceof Error ? error.message : String(error)}`); + } + if (cleanupErrors.length > 0) { + throw new Error(`streamDir write probe cleanup failed: ${cleanupErrors.join('; ')}`); + } +} + +export interface GenericStreamResult { + frame_count: number; + /** Intermediate frames only. Kept bounded by the HTTP client. */ + frames: OneBotEnvelope[]; + /** Last frame received. upload_file_stream acknowledgements are single-frame responses. */ + terminal: OneBotEnvelope; +} + +export interface FileStreamResult { + file_path: string; + file_size: number; + sha256: string; + frame_count: number; + terminal: OneBotEnvelope; +} + +export interface UploadStreamResult { + file_path: string; + file_size: number; + sha256: string; + chunk_count: number; + stream_id: string; + terminal: OneBotEnvelope; +} + +export type StreamCallResult = GenericStreamResult | FileStreamResult | UploadStreamResult; + export interface HttpClientOptions { /** OneBot HTTP endpoint, e.g. http://127.0.0.1:3000/. */ endpoint: string; accessToken?: string; timeoutMs?: number; + /** Directory on the MCP host where downloaded Stream Actions are committed. */ + streamDir?: string; + /** Per-file cap. Defaults to OneBot's 4 GiB limit. */ + maxStreamBytes?: number; + /** Existing MCP-host directory from which automatic uploads may read. */ + uploadRoot?: string; /** Injectable fetch for tests; defaults to the global fetch. */ fetch?: typeof fetch; } +function record(value: unknown): Record | undefined { + return value && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : undefined; +} + +function isWithin(root: string, target: string): boolean { + const relative = path.relative(root, target); + return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative); +} + +function safeDownloadName(value: unknown): string { + const raw = typeof value === 'string' ? path.basename(value) : 'download.bin'; + const safe = raw.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '').slice(0, 180); + return safe || 'download.bin'; +} + +function decodeBase64Chunk(value: string): Buffer { + const valid = value.length % 4 === 0 && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value); + if (!valid) throw new Error('file_chunk.data is not valid canonical base64'); + return Buffer.from(value, 'base64'); +} + +async function writeAll(handle: fs.promises.FileHandle, data: Buffer): Promise { + let offset = 0; + while (offset < data.length) { + const { bytesWritten } = await handle.write(data, offset, data.length - offset); + if (bytesWritten <= 0) throw new Error('file write made no progress'); + offset += bytesWritten; + } +} + +function terminalData(result: StreamCallResult): Record | undefined { + return record(result.terminal.data); +} + +function abortReason(signal: AbortSignal): string { + const reason = signal.reason; + return reason instanceof Error ? reason.message : reason === undefined ? 'aborted' : String(reason); +} + +function throwIfCancelled(signal: AbortSignal | undefined, action: string, stage: string): void { + if (signal?.aborted) { + throw new Error(`action ${action} stream ${stage}: cancelled: ${abortReason(signal)}`); + } +} + +type ByteStreamReadResult = Awaited['read']>>; + +async function readWithIdleTimeout( + reader: ReadableStreamDefaultReader, + timeoutMs: number, + callerSignal: AbortSignal | undefined, + action: string, + frameIndex: number, +): Promise { + if (callerSignal?.aborted) { + throw new Error(`action ${action} stream read frame ${frameIndex}: cancelled: ${abortReason(callerSignal)}`); + } + return new Promise((resolve, reject) => { + let settled = false; + const finish = (fn: () => void): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + callerSignal?.removeEventListener('abort', onAbort); + fn(); + }; + const onAbort = (): void => finish(() => reject(new Error( + `action ${action} stream read frame ${frameIndex}: cancelled: ${callerSignal ? abortReason(callerSignal) : 'aborted'}`, + ))); + const timer = setTimeout(() => finish(() => reject(new Error( + `action ${action} stream read frame ${frameIndex}: idle timeout after ${timeoutMs}ms`, + ))), timeoutMs); + if (typeof timer.unref === 'function') timer.unref(); + callerSignal?.addEventListener('abort', onAbort, { once: true }); + void reader.read().then( + (result) => finish(() => resolve(result)), + (error) => finish(() => reject(error)), + ); + }); +} + +async function uploadLocalFile( + action: string, + inputFile: string, + params: Record, + maxStreamBytes: number, + callerSignal: AbortSignal | undefined, + post: (params: Record, signal?: AbortSignal) => Promise, +): Promise { + const streamId = randomUUID(); + let handle: fs.promises.FileHandle | undefined; + let stage = 'open input'; + let remoteTouched = false; + try { + throwIfCancelled(callerSignal, action, stage); + handle = await fs.promises.open( + inputFile, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + throwIfCancelled(callerSignal, action, stage); + const initial = await handle.stat(); + if (!initial.isFile()) throw new Error('input_file is not a regular file'); + if (initial.size > maxStreamBytes) throw new Error(`input_file exceeds limit (${maxStreamBytes} bytes)`); + + const totalChunks = Math.max(1, Math.ceil(initial.size / UPLOAD_CHUNK_BYTES)); + const baseParams = { ...params }; + for (const key of MCP_UPLOAD_OWNED_FIELDS) { + delete baseParams[key]; + } + const filename = typeof params.filename === 'string' && params.filename ? params.filename : path.basename(inputFile); + const hash = createHash('sha256'); + let bytesRead = 0; + + for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { + stage = `read chunk ${chunkIndex}`; + throwIfCancelled(callerSignal, action, stage); + const wanted = initial.size === 0 ? 0 : Math.min(UPLOAD_CHUNK_BYTES, initial.size - bytesRead); + const chunk = Buffer.allocUnsafe(wanted); + let filled = 0; + while (filled < wanted) { + const read = await handle.read(chunk, filled, wanted - filled, bytesRead + filled); + if (read.bytesRead === 0) break; + filled += read.bytesRead; + } + if (filled !== wanted) throw new Error(`input_file changed while reading (expected ${wanted} bytes, read ${filled})`); + throwIfCancelled(callerSignal, action, stage); + const payload = filled === chunk.length ? chunk : chunk.subarray(0, filled); + hash.update(payload); + bytesRead += payload.length; + + stage = `send chunk ${chunkIndex}`; + throwIfCancelled(callerSignal, action, stage); + remoteTouched = true; + const ack = await post({ + ...baseParams, + stream_id: streamId, + chunk_data: payload.toString('base64'), + chunk_index: chunkIndex, + total_chunks: totalChunks, + file_size: initial.size, + filename, + }, callerSignal); + throwIfCancelled(callerSignal, action, stage); + const ackData = terminalData(ack); + if (ackData?.type !== 'stream' || ackData.status !== 'chunk_received') { + throw new Error(`unexpected chunk acknowledgement: ${JSON.stringify(ack.terminal)}`); + } + } + + stage = 'verify input'; + throwIfCancelled(callerSignal, action, stage); + const afterRead = await handle.stat(); + throwIfCancelled(callerSignal, action, stage); + if (afterRead.size !== initial.size || afterRead.mtimeMs !== initial.mtimeMs) { + throw new Error('input_file changed during upload'); + } + if (bytesRead !== initial.size) throw new Error(`input_file size mismatch (expected ${initial.size}, read ${bytesRead})`); + const sha256 = hash.digest('hex'); + + stage = 'close input'; + await handle.close(); + handle = undefined; + + stage = 'complete upload'; + throwIfCancelled(callerSignal, action, stage); + const completed = await post({ + ...baseParams, + stream_id: streamId, + total_chunks: totalChunks, + file_size: initial.size, + expected_sha256: sha256, + is_complete: true, + filename, + }, callerSignal); + throwIfCancelled(callerSignal, action, stage); + const data = terminalData(completed); + if (data?.type !== 'response' || data.status !== 'file_complete') { + throw new Error(`unexpected completion acknowledgement: ${JSON.stringify(completed.terminal)}`); + } + if (data.file_size !== initial.size) throw new Error(`remote file_size mismatch (expected ${initial.size}, got ${String(data.file_size)})`); + if (data.sha256 !== sha256) throw new Error(`remote sha256 mismatch (expected ${sha256}, got ${String(data.sha256)})`); + if (typeof data.file_path !== 'string' || !data.file_path) throw new Error('completion acknowledgement has no file_path'); + + return { + file_path: data.file_path, + file_size: initial.size, + sha256, + chunk_count: totalChunks, + stream_id: streamId, + terminal: completed.terminal, + }; + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + let closeFailure = ''; + if (handle) { + try { + await handle.close(); + handle = undefined; + } catch (closeError) { + closeFailure = `; close input failed: ${closeError instanceof Error ? closeError.message : String(closeError)}`; + } + } + let resetFailure = ''; + if (remoteTouched) { + try { + await post({ stream_id: streamId, reset: true }, AbortSignal.timeout(RESET_TIMEOUT_MS)); + } catch (resetError) { + resetFailure = `; remote reset failed: ${resetError instanceof Error ? resetError.message : String(resetError)}`; + } + } + throw new Error(`action ${action} stream ${stage}: ${detail}${closeFailure}${resetFailure}`); + } +} + export function makeHttpClient(opts: HttpClientOptions): ActionClient { const fetchImpl = opts.fetch ?? globalThis.fetch; - const timeoutMs = opts.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS; + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; + if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) { + throw new Error('timeoutMs must be a positive integer no greater than 2147483647'); + } + const maxStreamBytes = opts.maxStreamBytes ?? DEFAULT_MAX_STREAM_BYTES; + if (!Number.isSafeInteger(maxStreamBytes) || maxStreamBytes <= 0 || maxStreamBytes > DEFAULT_MAX_STREAM_BYTES) { + throw new Error(`maxStreamBytes must be an integer between 1 and ${DEFAULT_MAX_STREAM_BYTES}`); + } + const configuredStreamDir = path.resolve(opts.streamDir ?? DEFAULT_STREAM_DIR); + try { + fs.mkdirSync(configuredStreamDir, { recursive: true, mode: 0o700 }); + } catch (error) { + throw new Error(`streamDir cannot be created: ${error instanceof Error ? error.message : String(error)}`); + } + if (!fs.statSync(configuredStreamDir).isDirectory()) { + throw new Error(`streamDir is not a directory: ${configuredStreamDir}`); + } + const streamDir = fs.realpathSync(configuredStreamDir); + validateStreamDirectory(streamDir); + let uploadRoot: string | undefined; + if (opts.uploadRoot) { + uploadRoot = fs.realpathSync(opts.uploadRoot); + if (!fs.statSync(uploadRoot).isDirectory()) throw new Error(`uploadRoot is not a directory: ${uploadRoot}`); + } const headers: Record = { 'Content-Type': 'application/json', Accept: 'application/json', }; if (opts.accessToken) headers.Authorization = `Bearer ${opts.accessToken}`; - return { + let client: ActionClient; + let activeStreams = 0; + client = { async call(action, params) { - const res = await fetchImpl(opts.endpoint, { - method: 'POST', - headers, - body: JSON.stringify({ action, params }), - signal: AbortSignal.timeout(timeoutMs), - }); + let res: Response; + try { + res = await fetchImpl(opts.endpoint, { + method: 'POST', + headers, + body: JSON.stringify({ action, params }), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (error) { + throw new Error(`action ${action} request: ${error instanceof Error ? error.message : String(error)}`); + } const text = await res.text(); let parsed: unknown; try { @@ -65,5 +499,306 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient { } return parsed as OneBotEnvelope; }, + async callStream(action, params, options) { + const internalOptions = options as InternalStreamCallOptions | undefined; + const ownsSlot = internalOptions?.[INTERNAL_STREAM_CALL] !== true; + if (ownsSlot) { + if (activeStreams >= MAX_ACTIVE_STREAMS) { + throw new Error(`action ${action} stream admission: active Stream Action limit reached (${MAX_ACTIVE_STREAMS})`); + } + activeStreams++; + } + try { + let resolvedInputFile: string | undefined; + if (options?.inputFile) { + if (action !== 'upload_file_stream') { + throw new Error(`action ${action} stream resolve input: input_file is only valid for upload_file_stream`); + } + if (!uploadRoot) { + throw new Error(`action ${action} stream resolve input: SNOWLUMA_MCP_UPLOAD_ROOT is not configured`); + } + const conflicts = MCP_UPLOAD_OWNED_FIELDS.filter((key) => Object.hasOwn(params, key)); + if (conflicts.length) { + throw new Error(`action ${action} stream prepare upload: params conflict with MCP-owned transfer fields: ${conflicts.join(', ')}`); + } + try { + resolvedInputFile = fs.realpathSync(options.inputFile); + } catch (error) { + throw new Error(`action ${action} stream resolve input: ${error instanceof Error ? error.message : String(error)}`); + } + if (!isWithin(uploadRoot, resolvedInputFile)) { + throw new Error(`action ${action} stream resolve input: resolved path is outside the configured upload root`); + } + return uploadLocalFile( + action, + resolvedInputFile, + params, + maxStreamBytes, + options.signal, + (uploadParams, signal) => client.callStream(action, uploadParams, { + ...(signal ? { signal } : {}), + [INTERNAL_STREAM_CALL]: true, + } as InternalStreamCallOptions), + ); + } + let res: Response; + const connectionController = new AbortController(); + const requestSignal = options?.signal + ? AbortSignal.any([options.signal, connectionController.signal]) + : connectionController.signal; + const connectionTimer = setTimeout(() => { + connectionController.abort(new Error(`connection timeout after ${timeoutMs}ms`)); + }, timeoutMs); + if (typeof connectionTimer.unref === 'function') connectionTimer.unref(); + try { + res = await fetchImpl(opts.endpoint, { + method: 'POST', + headers, + body: JSON.stringify({ action, params }), + signal: requestSignal, + }); + } catch (error) { + const detail = options?.signal?.aborted + ? `cancelled: ${abortReason(options.signal)}` + : connectionController.signal.aborted + ? abortReason(connectionController.signal) + : error instanceof Error ? error.message : String(error); + throw new Error(`action ${action} stream connection: ${detail}`); + } finally { + clearTimeout(connectionTimer); + } + if (!res.ok) throw new Error(`action ${action} stream HTTP: unexpected status ${res.status}`); + if (!res.body) throw new Error(`action ${action} stream body: response body is unavailable`); + + const reader = res.body.getReader(); + const decoder = new TextDecoder('utf-8', { fatal: true }); + const frames: OneBotEnvelope[] = []; + let buffer = ''; + let bufferWireBytes = 0; + let frameIndex = 0; + let fileHandle: fs.promises.FileHandle | undefined; + let partPath: string | undefined; + let finalPath: string | undefined; + let declaredSize: number | undefined; + let fileBytes = 0; + let fileChunks = 0; + let fileTerminal: OneBotEnvelope | undefined; + let quotaReservation: DownloadReservation | undefined; + let genericTextBytes = 0; + let genericTerminalIndex: number | undefined; + const fileHash = createHash('sha256'); + + const acceptFrame = async (frame: OneBotEnvelope, rawBytes: number): Promise => { + const data = record(frame.data); + const dataType = data?.data_type; + const resetAck = action === 'upload_file_stream' && params.reset === true && + /stream reset completed/i.test(String(frame.wording ?? frame.message ?? '')); + if (!resetAck && (frame.status !== 'ok' || frame.retcode !== 0 || data?.type === 'error')) { + const detail = frame.wording || frame.message || `retcode=${String(frame.retcode)}`; + throw new Error(`action ${action} stream frame ${frameIndex}: terminal error: ${detail}`); + } + if (frameIndex === 0 && FILE_DOWNLOAD_ACTIONS.has(action) && dataType !== 'file_info') { + throw new Error(`action ${action} stream frame 0: first successful frame must be file_info`); + } + if (!fileHandle && (dataType === 'file_chunk' || dataType === 'file_complete')) { + throw new Error(`action ${action} stream frame ${frameIndex}: ${String(dataType)} received without file_info`); + } + if (dataType === 'file_info') { + if (!data) throw new Error(`action ${action} stream frame ${frameIndex}: file_info data must be an object`); + if (frameIndex !== 0 || fileHandle) throw new Error(`action ${action} stream frame ${frameIndex}: file_info must be the first and only header`); + const size = data.file_size; + if (!Number.isSafeInteger(size) || (size as number) < 0) { + throw new Error(`action ${action} stream frame ${frameIndex}: invalid file_size`); + } + if ((size as number) > maxStreamBytes) { + throw new Error(`action ${action} stream frame ${frameIndex}: file_size exceeds limit (${maxStreamBytes} bytes)`); + } + if (data.chunk_size !== undefined) { + if (!Number.isSafeInteger(data.chunk_size) || (data.chunk_size as number) <= 0) { + throw new Error(`action ${action} stream frame ${frameIndex}: invalid chunk_size`); + } + const expectedChunks = Math.ceil((size as number) / (data.chunk_size as number)); + if (expectedChunks > MAX_FILE_CHUNKS) { + throw new Error(`action ${action} stream frame ${frameIndex}: declared file chunks exceed limit (${MAX_FILE_CHUNKS})`); + } + } + // NapCat/SnowLuma use 0 when the source length is unknown. Only a + // positive header value is a strict declaration. + declaredSize = (size as number) > 0 ? size as number : undefined; + const filename = `${randomUUID()}-${safeDownloadName(data.file_name)}`; + finalPath = path.join(streamDir, filename); + partPath = `${finalPath}.part`; + quotaReservation = reserveDownloadQuota( + streamDir, + partPath, + finalPath, + declaredSize ?? maxStreamBytes, + 2 * maxStreamBytes, + ); + try { + fileHandle = await fs.promises.open(partPath, 'wx', 0o600); + } catch (error) { + releaseDownloadQuota(quotaReservation); + quotaReservation = undefined; + throw error; + } + return; + } + + if (fileHandle) { + if (fileTerminal) throw new Error(`action ${action} stream frame ${frameIndex}: frame received after terminal`); + if (dataType === 'file_chunk') { + if (fileChunks >= MAX_FILE_CHUNKS) { + throw new Error(`action ${action} stream frame ${frameIndex}: file chunks exceed limit (${MAX_FILE_CHUNKS})`); + } + if (!data || typeof data.data !== 'string') throw new Error(`action ${action} stream frame ${frameIndex}: file_chunk.data must be base64 text`); + if (!Number.isSafeInteger(data.index) || data.index !== fileChunks) { + throw new Error(`action ${action} stream frame ${frameIndex}: expected chunk index ${fileChunks}, got ${String(data.index)}`); + } + let chunk: Buffer; + try { + chunk = decodeBase64Chunk(data.data); + } catch (error) { + throw new Error(`action ${action} stream frame ${frameIndex}: ${error instanceof Error ? error.message : String(error)}`); + } + if (data.size !== undefined && (!Number.isSafeInteger(data.size) || data.size !== chunk.length)) { + throw new Error(`action ${action} stream frame ${frameIndex}: file_chunk.size does not match decoded base64 bytes`); + } + const nextBytes = fileBytes + chunk.length; + if (declaredSize !== undefined && nextBytes > declaredSize) { + throw new Error(`action ${action} stream frame ${frameIndex}: downloaded bytes exceed declared file_size (${declaredSize} bytes)`); + } + if (nextBytes > maxStreamBytes) { + throw new Error(`action ${action} stream frame ${frameIndex}: downloaded bytes exceed limit (${maxStreamBytes} bytes)`); + } + await writeAll(fileHandle, chunk); + fileHash.update(chunk); + fileBytes += chunk.length; + fileChunks++; + return; + } + if (data?.type === 'response' && dataType === 'file_complete') { + fileTerminal = frame; + return; + } + throw new Error(`action ${action} stream frame ${frameIndex}: unexpected file frame ${String(dataType ?? data?.type ?? 'unknown')}`); + } + + if (frames.length >= MAX_GENERIC_FRAMES) { + throw new Error(`action ${action} stream frame ${frameIndex}: generic frame summary exceeds limit (${MAX_GENERIC_FRAMES})`); + } + if (genericTerminalIndex !== undefined) { + throw new Error(`action ${action} stream frame ${frameIndex}: frame received after response terminal at frame ${genericTerminalIndex}`); + } + genericTextBytes += rawBytes; + if (genericTextBytes > MAX_GENERIC_TEXT_BYTES) { + throw new Error(`action ${action} stream frame ${frameIndex}: generic summary text exceeds limit (${MAX_GENERIC_TEXT_BYTES} bytes)`); + } + frames.push(frame); + if (data?.type === 'response') genericTerminalIndex = frameIndex; + }; + try { + while (true) { + const { done, value } = await readWithIdleTimeout(reader, timeoutMs, options?.signal, action, frameIndex); + if (done) break; + bufferWireBytes += value.byteLength; + buffer += decoder.decode(value, { stream: true }); + let delimiter: number; + while ((delimiter = buffer.indexOf('\r\n\r\n')) >= 0) { + const raw = buffer.slice(0, delimiter); + buffer = buffer.slice(delimiter + 4); + const rawBytes = Buffer.byteLength(raw, 'utf8'); + bufferWireBytes -= rawBytes + 4; + if (rawBytes > MAX_WIRE_FRAME_BYTES) { + throw new Error(`action ${action} stream frame ${frameIndex}: wire frame exceeds limit (${MAX_WIRE_FRAME_BYTES} bytes)`); + } + if (!raw) throw new Error(`action ${action} stream frame ${frameIndex}: empty frame`); + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (error) { + throw new Error(`action ${action} stream frame ${frameIndex}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`action ${action} stream frame ${frameIndex}: expected an object envelope`); + } + try { + await acceptFrame(parsed as OneBotEnvelope, rawBytes); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + if (detail.startsWith(`action ${action} `)) throw error; + throw new Error(`action ${action} stream frame ${frameIndex}: frame handling failed: ${detail}`); + } + frameIndex++; + } + if (bufferWireBytes > MAX_WIRE_FRAME_BYTES) { + throw new Error(`action ${action} stream frame ${frameIndex}: wire frame exceeds limit (${MAX_WIRE_FRAME_BYTES} bytes)`); + } + } + buffer += decoder.decode(); + if (buffer.trim()) throw new Error(`action ${action} stream EOF after frame ${frameIndex}: unterminated frame`); + if (fileHandle) { + if (!fileTerminal) throw new Error(`action ${action} stream EOF after frame ${frameIndex}: missing file_complete terminal`); + if (declaredSize !== undefined && declaredSize !== fileBytes) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: expected ${declaredSize} bytes, received ${fileBytes}`); + } + const terminalData = record(fileTerminal.data); + if (!Number.isSafeInteger(terminalData?.total_bytes) || (terminalData!.total_bytes as number) < 0) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: terminal total_bytes is missing or invalid`); + } + if (terminalData!.total_bytes !== fileBytes) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: terminal total_bytes mismatch`); + } + if (terminalData?.total_chunks !== undefined && terminalData.total_chunks !== fileChunks) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: terminal total_chunks mismatch`); + } + const sha256 = fileHash.digest('hex'); + await fileHandle.close(); + fileHandle = undefined; + await fs.promises.rename(partPath!, finalPath!); + partPath = undefined; + releaseDownloadQuota(quotaReservation); + quotaReservation = undefined; + return { + file_path: finalPath!, + file_size: fileBytes, + sha256, + frame_count: frameIndex, + terminal: fileTerminal, + }; + } + if (!frames.length) throw new Error(`action ${action} stream EOF: no frames received`); + const uploadAck = action === 'upload_file_stream' && frames.length === 1; + if (genericTerminalIndex === undefined && !uploadAck) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: missing response terminal`); + } + return { frame_count: frames.length, frames: frames.slice(0, -1), terminal: frames.at(-1)! }; + } catch (error) { + const cleanupErrors: string[] = []; + try { await reader.cancel(error instanceof Error ? error.message : String(error)); } catch (cleanupError) { + cleanupErrors.push(`cancel response body: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`); + } + try { await fileHandle?.close(); } catch (cleanupError) { + cleanupErrors.push(`close: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`); + } + if (partPath) { + try { await fs.promises.rm(partPath, { force: true }); } catch (cleanupError) { + cleanupErrors.push(`remove ${partPath}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`); + } + } + releaseDownloadQuota(quotaReservation); + quotaReservation = undefined; + const detail = error instanceof Error ? error.message : String(error); + const base = detail.startsWith(`action ${action} `) ? detail : `action ${action} stream body: ${detail}`; + const suffix = cleanupErrors.length ? `; cleanup failed (${cleanupErrors.join('; ')})` : ''; + throw new Error(base + suffix); + } finally { + reader.releaseLock(); + } + } finally { + if (ownsSlot) activeStreams--; + } + }, }; + return client; } diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index 93dc5df7..63718d96 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -13,9 +13,13 @@ // SNOWLUMA_MCP_ENDPOINT OneBot HTTP endpoint (e.g. http://127.0.0.1:3000/). // Absent → docs-only (execution tools hidden). // SNOWLUMA_MCP_TOKEN access token (Bearer) for the endpoint. -// SNOWLUMA_MCP_TIMEOUT_MS per-request timeout (default SDK 30s). +// SNOWLUMA_MCP_TIMEOUT_MS ordinary request timeout; Stream connection and +// per-read idle timeout (default 30s). // SNOWLUMA_MCP_MODE docs | read | write. Default: read when an // endpoint is set, else docs. +// SNOWLUMA_MCP_STREAM_DIR MCP-host directory for completed downloads. +// SNOWLUMA_MCP_UPLOAD_ROOT Existing MCP-host directory allowed for uploads. +// SNOWLUMA_MCP_MAX_STREAM_BYTES Per-file cap (1..4 GiB; default 4 GiB). // // NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr. @@ -29,8 +33,8 @@ import { ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; import { ACTIONS, CATEGORIES } from './generated/catalog.js'; -import { makeHttpClient, type ActionClient } from './client.js'; -import { callTool, computeTools, type Mode } from './tools.js'; +import { makeHttpClient, parseMaxStreamBytes, parseTimeoutMs, type ActionClient } from './client.js'; +import { callTool, computeTools, parseMode, type Mode } from './tools.js'; const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }; const VERSION = pkg.version; @@ -41,24 +45,25 @@ const RESOURCE_URI = 'snowluma://onebot/actions'; function resolveRuntime(): { mode: Mode; client?: ActionClient } { const endpoint = process.env.SNOWLUMA_MCP_ENDPOINT?.trim(); const token = process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined; - const timeoutRaw = Number(process.env.SNOWLUMA_MCP_TIMEOUT_MS); - const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined; - const requested = process.env.SNOWLUMA_MCP_MODE?.trim().toLowerCase(); - const validRequest = requested === 'docs' || requested === 'read' || requested === 'write' ? requested : undefined; + const streamDir = process.env.SNOWLUMA_MCP_STREAM_DIR?.trim() || undefined; + const uploadRoot = process.env.SNOWLUMA_MCP_UPLOAD_ROOT?.trim() || undefined; + const maxStreamBytes = parseMaxStreamBytes(process.env.SNOWLUMA_MCP_MAX_STREAM_BYTES); + const timeoutMs = parseTimeoutMs(process.env.SNOWLUMA_MCP_TIMEOUT_MS); + const requested = parseMode(process.env.SNOWLUMA_MCP_MODE); if (!endpoint) { - if (validRequest && validRequest !== 'docs') { - console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${validRequest} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`); + if (requested && requested !== 'docs') { + console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${requested} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`); } return { mode: 'docs' }; } - const mode: Mode = validRequest ?? 'read'; + const mode: Mode = requested ?? 'read'; if (mode === 'docs') { // Endpoint set but operator explicitly wants docs-only — honor it. return { mode: 'docs' }; } - const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs }); + const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs, streamDir, uploadRoot, maxStreamBytes }); return { mode, client }; } @@ -71,9 +76,9 @@ const server = new Server( server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) })); -server.setRequestHandler(CallToolRequestSchema, async (req) => { +server.setRequestHandler(CallToolRequestSchema, async (req, extra) => { const args = (req.params.arguments ?? {}) as Record; - return callTool(req.params.name, args, { mode, client }); + return callTool(req.params.name, args, { mode, client, signal: extra.signal }); }); server.setRequestHandler(ListResourcesRequestSchema, async () => ({ diff --git a/packages/mcp/src/tools.ts b/packages/mcp/src/tools.ts index ca1e21af..0099ae1e 100644 --- a/packages/mcp/src/tools.ts +++ b/packages/mcp/src/tools.ts @@ -15,6 +15,13 @@ import type { ActionClient } from './client.js'; export type Mode = 'docs' | 'read' | 'write'; +export function parseMode(raw: string | undefined): Mode | undefined { + if (raw === undefined) return undefined; + const value = raw.trim().toLowerCase(); + if (value === 'docs' || value === 'read' || value === 'write') return value; + throw new Error('SNOWLUMA_MCP_MODE must be one of: docs, read, write'); +} + // name + every alias → action, so lookups accept aliases too. const byName = new Map(); for (const a of ACTIONS) { @@ -23,13 +30,13 @@ 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 }; + return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases, readOnly: a.readOnly, stream: a.stream ?? false }; } const DOCS_TOOLS: Tool[] = [ { name: 'list_actions', - description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读)。', + description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读/是否为 Stream Action)。', inputSchema: { type: 'object', properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } }, @@ -72,6 +79,17 @@ const EXEC_INPUT_SCHEMA = { properties: { action: { type: 'string', description: 'action 名(接受别名)。先用 get_action 查它的参数 inputSchema。' }, params: { type: 'object', description: '该 action 的参数对象', additionalProperties: true }, + execution: { + type: 'object', + description: 'MCP 主机侧执行选项(不会发送为 OneBot params)。自动上传本地文件时使用。', + properties: { + input_file: { + type: 'string', + description: 'MCP 主机上的文件路径。仅用于 upload_file_stream,且必须位于 SNOWLUMA_MCP_UPLOAD_ROOT。', + }, + }, + additionalProperties: false, + }, }, required: ['action'], additionalProperties: false, @@ -89,7 +107,7 @@ function queryTool(): Tool { function invokeTool(): Tool { return { name: 'invoke_action', - description: '调用一个 OneBot action(可产生副作用:发消息、改群、改资料等)并返回完整响应。仅在写模式可用。', + description: '调用一个 OneBot action(可产生副作用)。Stream 下载会写入 MCP 主机受控目录并只返回文件元数据;upload_file_stream 可用 execution.input_file 自动分块上传。仅在写模式可用。', inputSchema: EXEC_INPUT_SCHEMA, annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, }; @@ -115,6 +133,7 @@ function asError(message: string): ToolResult { export interface CallCtx { mode: Mode; client?: ActionClient; + signal?: AbortSignal; } export async function callTool(name: string, args: Record, ctx: CallCtx): Promise { @@ -173,10 +192,36 @@ async function execute(args: Record, ctx: CallCtx, kind: 'read' args.params && typeof args.params === 'object' && !Array.isArray(args.params) ? (args.params as Record) : {}; + let inputFile: string | undefined; + if (args.execution !== undefined) { + if (!args.execution || typeof args.execution !== 'object' || Array.isArray(args.execution)) { + return asError('execution 必须是对象。'); + } + const execution = args.execution as Record; + const unknown = Object.keys(execution).filter((key) => key !== 'input_file'); + if (unknown.length) return asError(`未知 MCP execution 选项: ${unknown.join(', ')}`); + if (execution.input_file !== undefined) { + if (typeof execution.input_file !== 'string' || !execution.input_file.trim()) { + return asError('execution.input_file 必须是非空字符串。'); + } + inputFile = execution.input_file; + } + } + if (inputFile && cat.name !== 'upload_file_stream') { + return asError('execution.input_file 仅可用于 upload_file_stream。'); + } + if (inputFile && !cat.stream) { + return asError(`${action} 不是 Stream Action,不能使用 execution.input_file。`); + } try { - const envelope = await ctx.client.call(action, params); - return asText(envelope); + const result = cat.stream + ? await ctx.client.callStream(action, params, { + ...(inputFile ? { inputFile } : {}), + ...(ctx.signal ? { signal: ctx.signal } : {}), + }) + : await ctx.client.call(action, params); + return asText(result); } catch (err) { - return asError(`调用失败: ${err instanceof Error ? err.message : String(err)}`); + return asError(`调用失败 (${action}): ${err instanceof Error ? err.message : String(err)}`); } } diff --git a/packages/mcp/tests/client.test.ts b/packages/mcp/tests/client.test.ts index 28994e67..bf8b0cf8 100644 --- a/packages/mcp/tests/client.test.ts +++ b/packages/mcp/tests/client.test.ts @@ -1,10 +1,73 @@ -import { describe, it, expect } from 'vitest'; -import { makeHttpClient } from '../src/client'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +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'; + +const tempDirs: string[] = []; + +afterEach(() => { + vi.restoreAllMocks(); + for (const dir of tempDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); +}); // Verifies the HTTP bridge: a OneBot action becomes a POST of `{ action, params }` // to the endpoint (with Bearer auth), and the JSON envelope comes back verbatim. // A fake fetch stands in for the network. describe('makeHttpClient — OneBot HTTP wiring', () => { + it('validates SNOWLUMA_MCP_MAX_STREAM_BYTES as a positive 4 GiB-or-lower integer', () => { + expect(parseMaxStreamBytes(undefined)).toBeUndefined(); + expect(parseMaxStreamBytes('1048576')).toBe(1048576); + for (const invalid of ['', '0', '-1', '1.5', '1e6', String(4 * 1024 * 1024 * 1024 + 1), 'nope']) { + expect(() => parseMaxStreamBytes(invalid), invalid).toThrow(/SNOWLUMA_MCP_MAX_STREAM_BYTES/); + } + }); + + it('fails fast on an invalid SNOWLUMA_MCP_TIMEOUT_MS', () => { + expect(parseTimeoutMs(undefined)).toBeUndefined(); + expect(parseTimeoutMs('30000')).toBe(30000); + for (const invalid of ['', '0', '-1', '1.5', '1e3', 'nope']) { + expect(() => parseTimeoutMs(invalid), invalid).toThrow(/SNOWLUMA_MCP_TIMEOUT_MS/); + } + }); + + it('rejects an invalid programmatic timeout instead of silently using the default', () => { + for (const timeoutMs of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', timeoutMs }), String(timeoutMs)) + .toThrow(/timeoutMs.*positive.*integer/i); + } + }); + + it('creates the configured stream directory at client startup and rejects a file path', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-config-')); + tempDirs.push(root); + const nested = path.join(root, 'nested', 'downloads'); + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', streamDir: nested })).not.toThrow(); + expect(fs.statSync(nested).isDirectory()).toBe(true); + + const filePath = path.join(root, 'not-a-directory'); + fs.writeFileSync(filePath, 'x'); + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', streamDir: filePath })).toThrow(/streamDir.*(?:not a directory|cannot be created)/i); + }); + + it('fails startup when the stream directory cannot be accessed or create files', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-config-')); + tempDirs.push(root); + + vi.spyOn(fs, 'accessSync').mockImplementationOnce(() => { + throw Object.assign(new Error('permission denied'), { code: 'EACCES' }); + }); + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', streamDir: root })) + .toThrow(/streamDir.*readable.*writable.*traversable.*permission denied/i); + + vi.spyOn(fs, 'openSync').mockImplementationOnce(() => { + throw Object.assign(new Error('create denied'), { code: 'EACCES' }); + }); + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', streamDir: root })) + .toThrow(/streamDir.*cannot create files.*create denied/i); + }); + it('POSTs {action, params} to the endpoint and returns the parsed envelope', async () => { const calls: Array<{ url: string; body: any; auth?: string }> = []; const fakeFetch = (async (url: unknown, init: any) => { @@ -36,4 +99,592 @@ describe('makeHttpClient — OneBot HTTP wiring', () => { const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); await expect(client.call('get_status', {})).rejects.toThrow(); }); + + it('incrementally parses stream frames across arbitrary network chunk boundaries', async () => { + const frames = [ + { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'stream', data_type: 'data_chunk', data: 'Index-> 1' } }, + { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'response', data_type: 'data_complete', data: 'done' } }, + ]; + const wire = frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + const cuts = [1, 7, 19, 31, 57, wire.length]; + const chunks: Uint8Array[] = []; + let offset = 0; + for (const cut of cuts) { + chunks.push(new TextEncoder().encode(wire.slice(offset, cut))); + offset = cut; + } + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk); + controller.close(); + }, + }), { status: 200 })) 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', {}); + + expect(result).toEqual({ frame_count: 2, frames: [frames[0]], terminal: frames[1] }); + }); + + it('writes a multi-frame file download atomically and returns metadata instead of base64', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const content = Buffer.from('streamed file content '.repeat(200)); + const parts = [content.subarray(0, 997), content.subarray(997)]; + const frames = [ + { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'stream', data_type: 'file_info', file_name: '../unsafe.bin', file_size: content.length, chunk_size: 997 } }, + ...parts.map((part, index) => ({ status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'stream', data_type: 'file_chunk', index, size: part.length, data: part.toString('base64') } })), + { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'response', data_type: 'file_complete', total_chunks: parts.length, total_bytes: content.length } }, + ]; + const wire = frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + const fakeFetch = (async () => new Response(wire, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + const result = await client.callStream('download_file_stream', { file: 'remote-id' }); + + expect(Object.keys(result).sort()).toEqual(['file_path', 'file_size', 'frame_count', 'sha256', 'terminal']); + expect(result.file_size).toBe(content.length); + expect(result.frame_count).toBe(frames.length); + expect(result.sha256).toBe(createHash('sha256').update(content).digest('hex')); + expect(path.isAbsolute(result.file_path)).toBe(true); + expect(path.dirname(result.file_path)).toBe(fs.realpathSync(streamDir)); + expect(fs.readFileSync(result.file_path).equals(content)).toBe(true); + expect(fs.readdirSync(streamDir).some((name) => name.endsWith('.part'))).toBe(false); + expect(JSON.stringify(result)).not.toContain(parts[0].toString('base64')); + }); + + it('surfaces a terminal stream error with action/frame context and removes the partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'broken.bin', file_size: 3 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 3, data: Buffer.from('abc').toString('base64') } }, + { status: 'failed', retcode: 100, wording: 'source disconnected', data: { type: 'error', data_type: 'error' } }, + ]; + const wire = frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + const fakeFetch = (async () => new Response(wire, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*frame 2.*source disconnected/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('removes the partial file when the response body disconnects before a terminal frame', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const prefix = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'cut.bin', file_size: 6 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 3, data: Buffer.from('abc').toString('base64') } }, + ].map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(prefix)); + controller.error(new Error('socket reset')); + }, + }), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*body.*socket reset/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('enforces the configured byte ceiling while streaming and removes the partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'too-big.bin', file_size: 3 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 4, data: Buffer.from('abcd').toString('base64') } }, + ]; + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, maxStreamBytes: 3 }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/frame 1.*exceed.*3 bytes/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('fails fast when a non-file stream exceeds the bounded frame summary count', async () => { + const frames = Array.from({ length: 257 }, (_, index) => ({ + status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: `frame-${index}` }, + })); + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*frame 256.*summary.*256/i); + }); + + it('fails fast when a non-file stream exceeds the bounded summary text size', async () => { + const frame = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'x'.repeat(256 * 1024) } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*frame 0.*summary text.*262144/i); + }); + + it('rejects malformed base64 file frames and removes the partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'bad.bin', file_size: 0 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 0, data: '%%%=' } }, + ]; + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*frame 1.*base64/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('accepts upload_file_stream single-frame acknowledgements without requiring a response-type terminal', async () => { + const ack = { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 2 } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(ack)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('upload_file_stream', { stream_id: 'id', chunk_index: 0, chunk_data: 'YQ==' })) + .resolves.toEqual({ frame_count: 1, frames: [], terminal: ack }); + }); + + it('refuses MCP-host file upload unless an upload root is explicitly configured', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-upload-')); + tempDirs.push(dir); + const inputFile = path.join(dir, 'local.txt'); + fs.writeFileSync(inputFile, 'local'); + let fetchCalls = 0; + const fakeFetch = (async () => { fetchCalls++; throw new Error('fetch must not run'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile })).rejects.toThrow(/upload_file_stream.*resolve input.*SNOWLUMA_MCP_UPLOAD_ROOT/i); + expect(fetchCalls).toBe(0); + }); + + it('rejects an unterminated wire frame before its buffer can grow beyond the 24 MiB frame cap', async () => { + const oversized = new Uint8Array(24 * 1024 * 1024 + 1).fill(0x78); + const fakeFetch = (async () => new Response(oversized, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*frame 0.*wire.*25165824/i); + }); + + it('actively cancels the response body when frame parsing fails', async () => { + let cancelled = false; + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('not-json\r\n\r\n')); + }, + cancel() { + cancelled = true; + }, + }); + const fakeFetch = (async () => new Response(body, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/frame 0.*invalid JSON/i); + expect(cancelled).toBe(true); + }); + + it('rejects EOF on a generic stream that never produced a response terminal', async () => { + const frame = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'only-intermediate' } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*EOF.*missing.*response terminal/i); + }); + + it('rejects any generic frame after the unique response terminal', async () => { + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete', data: 'done' } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'late' } }, + ]; + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*frame 1.*after response terminal.*frame 0/i); + }); + + it('realpaths upload inputs and rejects a symlink that escapes the configured upload root', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-outside-')); + tempDirs.push(root, outside); + const outsideFile = path.join(outside, 'secret.txt'); + const link = path.join(root, 'escape.txt'); + fs.writeFileSync(outsideFile, 'secret'); + fs.symlinkSync(outsideFile, link); + let fetchCalls = 0; + const fakeFetch = (async () => { fetchCalls++; throw new Error('fetch must not run'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile: link })).rejects.toThrow(/upload_file_stream.*resolve input.*outside.*upload root/i); + expect(fetchCalls).toBe(0); + }); + + it('uploads an allowed MCP-host file in fixed chunks and returns a base64-free summary', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'payload.bin'); + const content = Buffer.alloc(600 * 1024); + for (let i = 0; i < content.length; i++) content[i] = i % 251; + fs.writeFileSync(inputFile, content); + const sha256 = createHash('sha256').update(content).digest('hex'); + const requests: Array> = []; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const request = JSON.parse(String(init.body)) as Record; + requests.push(request); + const p = request.params; + const data = p.is_complete + ? { type: 'response', status: 'file_complete', file_path: '/snowluma/upload/payload.bin', file_size: content.length, sha256, total_chunks: 2 } + : { type: 'stream', status: 'chunk_received', received_chunks: p.chunk_index + 1, total_chunks: 2 }; + const frame = { status: 'ok', retcode: 0, stream: 'stream-action', data }; + return new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + const result = await client.callStream('upload_file_stream', { file_retention: 0 }, { inputFile }); + + expect(requests).toHaveLength(3); + expect(requests.every((request) => request.action === 'upload_file_stream')).toBe(true); + const chunks = requests.slice(0, 2).map((request) => Buffer.from(request.params.chunk_data, 'base64')); + expect(Buffer.concat(chunks).equals(content)).toBe(true); + expect(requests[0].params).toMatchObject({ chunk_index: 0, total_chunks: 2, file_size: content.length, filename: 'payload.bin', file_retention: 0 }); + expect(requests[1].params).toMatchObject({ chunk_index: 1, total_chunks: 2 }); + expect(requests[2].params).toMatchObject({ is_complete: true, expected_sha256: sha256, file_size: content.length }); + expect(new Set(requests.map((request) => request.params.stream_id)).size).toBe(1); + expect(result).toMatchObject({ + file_path: '/snowluma/upload/payload.bin', + file_size: content.length, + sha256, + chunk_count: 2, + stream_id: requests[0].params.stream_id, + }); + expect(JSON.stringify(result)).not.toContain(requests[0].params.chunk_data); + }); + + it('attempts to reset the remote upload stream after a chunk failure and preserves the original stage error', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'payload.bin'); + fs.writeFileSync(inputFile, Buffer.alloc(600 * 1024, 7)); + const requests: Array> = []; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const request = JSON.parse(String(init.body)) as Record; + requests.push(request); + let frame: Record; + if (request.params.reset) { + frame = { status: 'failed', retcode: 100, wording: 'Stream reset completed', data: { type: 'error', data_type: 'error' } }; + } else if (request.params.chunk_index === 1) { + frame = { status: 'failed', retcode: 100, wording: 'disk full', data: { type: 'error', data_type: 'error' } }; + } else { + frame = { status: 'ok', retcode: 0, data: { type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 2 } }; + } + return new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile })).rejects.toThrow(/upload_file_stream.*send chunk 1.*disk full/i); + expect(requests.at(-1)?.params).toMatchObject({ stream_id: requests[0].params.stream_id, reset: true }); + }); + + it('adds action and request-stage context to a stream transport failure', async () => { + const fakeFetch = (async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/action test_download_stream.*connection.*ECONNREFUSED/i); + }); + + it('fails fast when automatic-upload params conflict with MCP-owned transfer fields', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'empty.bin'); + fs.writeFileSync(inputFile, ''); + let fetchCalls = 0; + const fakeFetch = (async () => { fetchCalls++; throw new Error('fetch must not run'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', { stream_id: 'caller-owned', chunk_data: 'YQ==' }, { inputFile })) + .rejects.toThrow(/upload_file_stream.*prepare upload.*conflict.*stream_id.*chunk_data/i); + expect(fetchCalls).toBe(0); + }); + + it('uploads an empty file as one empty chunk followed by explicit completion', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'empty.bin'); + fs.writeFileSync(inputFile, ''); + const sha256 = createHash('sha256').update('').digest('hex'); + const requests: Array> = []; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const request = JSON.parse(String(init.body)) as Record; + requests.push(request); + const data = request.params.is_complete + ? { type: 'response', status: 'file_complete', file_path: '/remote/empty.bin', file_size: 0, sha256 } + : { type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 1 }; + return new Response(`${JSON.stringify({ status: 'ok', retcode: 0, data })}\r\n\r\n`, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + const result = await client.callStream('upload_file_stream', {}, { inputFile }); + + expect(requests).toHaveLength(2); + expect(requests[0].params).toMatchObject({ chunk_data: '', chunk_index: 0, total_chunks: 1, file_size: 0 }); + expect(requests[1].params).toMatchObject({ is_complete: true, expected_sha256: sha256 }); + expect(result).toMatchObject({ file_path: '/remote/empty.bin', file_size: 0, sha256, chunk_count: 1 }); + }); + + it('rejects an upload input that resolves to a directory before any network call', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + const dir = path.join(root, 'nested'); + fs.mkdirSync(dir); + tempDirs.push(root); + let fetchCalls = 0; + const fakeFetch = (async () => { fetchCalls++; throw new Error('fetch must not run'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile: dir })).rejects.toThrow(/upload_file_stream.*open input.*not a regular file/i); + expect(fetchCalls).toBe(0); + }); + + it('reports a failed best-effort remote reset instead of silently dropping it', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'one.bin'); + fs.writeFileSync(inputFile, 'x'); + let calls = 0; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + calls++; + const request = JSON.parse(String(init.body)) as Record; + if (request.params.reset) throw new Error('reset connection lost'); + const frame = { status: 'failed', retcode: 100, wording: 'chunk rejected', data: { type: 'error' } }; + return new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile })) + .rejects.toThrow(/send chunk 0.*chunk rejected.*remote reset failed.*reset connection lost/i); + expect(calls).toBe(2); + }); + + it('rejects file_info whose declared chunk geometry exceeds the 200000-frame file cap', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const frame = { + status: 'ok', retcode: 0, + data: { type: 'stream', data_type: 'file_info', file_name: 'tiny-chunks.bin', file_size: 200_001, chunk_size: 1 }, + }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/frame 0.*file chunks.*200000/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('treats file_size=0 as unknown and commits a non-empty download using terminal.total_bytes', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const content = Buffer.from('unknown-size payload'); + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'unknown.bin', file_size: 0, chunk_size: 65536 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: content.length, data: content.toString('base64') } }, + { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'file_complete', total_chunks: 1, total_bytes: content.length } }, + ]; + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + const result = await client.callStream('download_file_stream', {}); + + expect(result.file_size).toBe(content.length); + expect(fs.readFileSync(result.file_path).equals(content)).toBe(true); + }); + + it('requires file_info as the first successful frame for known file-download actions', async () => { + const frame = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'unexpected' } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*frame 0.*first.*file_info/i); + }); + + it('never treats file_chunk or file_complete without file_info as a generic frame summary', async () => { + for (const dataType of ['file_chunk', 'file_complete']) { + const secret = Buffer.from(`secret-${dataType}`).toString('base64'); + const frame = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: dataType, data: secret } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + let message = ''; + try { await client.callStream('test_download_stream', {}); } catch (error) { message = String(error); } + expect(message).toMatch(/frame 0.*without file_info/i); + expect(message).not.toContain(secret); + } + }); + + it('cancels an in-flight download from the MCP signal and removes its partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const prefix = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'cancel.bin', file_size: 6, chunk_size: 3 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 3, data: Buffer.from('abc').toString('base64') } }, + ].map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + let bodyCancelled = false; + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(prefix)); }, + cancel() { bodyCancelled = true; }, + }), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, timeoutMs: 1_000 }); + const controller = new AbortController(); + const pending = client.callStream('download_file_stream', {}, { signal: controller.signal }); + + for (let i = 0; i < 50 && !fs.readdirSync(streamDir).some((name) => name.endsWith('.part')); i++) { + await new Promise((resolve) => setImmediate(resolve)); + } + controller.abort(new Error('MCP caller cancelled')); + const outcome = await Promise.race([ + pending.then((value) => ({ value }), (error) => ({ error })), + new Promise<{ pending: true }>((resolve) => setTimeout(() => resolve({ pending: true }), 250)), + ]); + + expect(outcome).toHaveProperty('error'); + expect(String('error' in outcome ? outcome.error : '')).toMatch(/download_file_stream.*cancel.*MCP caller cancelled/i); + expect(bodyCancelled).toBe(true); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('resets the idle deadline after every frame instead of imposing an overall stream timeout', async () => { + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'one' } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'two' } }, + { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete', data: 'done' } }, + ]; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const signal = init.signal as AbortSignal; + const body = new ReadableStream({ + start(controller) { + const timers = frames.map((frame, index) => setTimeout(() => { + controller.enqueue(new TextEncoder().encode(`${JSON.stringify(frame)}\r\n\r\n`)); + if (index === frames.length - 1) controller.close(); + }, [10, 35, 65][index])); + signal.addEventListener('abort', () => { + for (const timer of timers) clearTimeout(timer); + controller.error(signal.reason); + }, { once: true }); + }, + }); + return new Response(body, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, timeoutMs: 40 }); + + const result = await client.callStream('test_download_stream', {}); + + expect(result).toMatchObject({ frame_count: 3, terminal: frames[2] }); + }); + + it('cancels a stalled body at the per-read idle deadline and removes the partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const info = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'idle.bin', file_size: 4, chunk_size: 4 } }; + let cancelled = false; + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(`${JSON.stringify(info)}\r\n\r\n`)); }, + cancel() { cancelled = true; }, + }), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, timeoutMs: 20 }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*idle timeout.*20ms/i); + expect(cancelled).toBe(true); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('propagates upload cancellation but performs remote reset with an independent cleanup signal', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'cancel-upload.bin'); + fs.writeFileSync(inputFile, 'x'); + const requests: Array> = []; + const signals: AbortSignal[] = []; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const request = JSON.parse(String(init.body)) as Record; + requests.push(request); + signals.push(init.signal as AbortSignal); + if (request.params.reset) { + const reset = { status: 'failed', retcode: 100, wording: 'Stream reset completed', data: { type: 'error' } }; + return new Response(`${JSON.stringify(reset)}\r\n\r\n`, { status: 200 }); + } + return new Response(new ReadableStream({ start() {} }), { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root, timeoutMs: 1_000 }); + const controller = new AbortController(); + const pending = client.callStream('upload_file_stream', {}, { inputFile, signal: controller.signal }); + for (let i = 0; i < 50 && requests.length === 0; i++) await new Promise((resolve) => setImmediate(resolve)); + + controller.abort(new Error('cancel automatic upload')); + const outcome = await Promise.race([ + pending.then((value) => ({ value }), (error) => ({ error })), + new Promise<{ pending: true }>((resolve) => setTimeout(() => resolve({ pending: true }), 250)), + ]); + + expect(outcome).toHaveProperty('error'); + expect(String('error' in outcome ? outcome.error : '')).toMatch(/upload_file_stream.*cancel automatic upload/i); + expect(requests.at(-1)?.params).toMatchObject({ reset: true, stream_id: requests[0].params.stream_id }); + expect(signals).toHaveLength(2); + expect(signals[1]).not.toBe(controller.signal); + expect(signals[1].aborted).toBe(false); + }); + + it('limits each client to four top-level active Stream Actions', async () => { + const resolvers: Array<(response: Response) => void> = []; + const fakeFetch = (async () => new Promise((resolve) => { resolvers.push(resolve); })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, timeoutMs: 1_000 }); + const active = Array.from({ length: 4 }, () => client.callStream('test_download_stream', {})); + const fifth = client.callStream('test_download_stream', {}); + const fifthOutcomePromise = fifth.then((value) => ({ value }), (error) => ({ error })); + await new Promise((resolve) => setImmediate(resolve)); + const startedRequests = resolvers.length; + const terminal = { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete' } }; + for (const resolve of resolvers) { + resolve(new Response(`${JSON.stringify(terminal)}\r\n\r\n`, { status: 200 })); + } + const fifthOutcome = await fifthOutcomePromise; + await Promise.all(active); + + expect(startedRequests).toBe(4); + expect(fifthOutcome).toHaveProperty('error'); + expect(String('error' in fifthOutcome ? fifthOutcome.error : '')).toMatch(/active Stream Action.*limit.*4/i); + }); + + it('enforces the download-directory quota and reserves maxStreamBytes for unknown-size files', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-quota-')); + tempDirs.push(streamDir); + fs.writeFileSync(path.join(streamDir, 'existing.bin'), Buffer.alloc(11)); + const info = { + status: 'ok', retcode: 0, + data: { type: 'stream', data_type: 'file_info', file_name: 'unknown.bin', file_size: 0, chunk_size: 4 }, + }; + const fakeFetch = (async () => new Response(`${JSON.stringify(info)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, maxStreamBytes: 10 }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download directory quota.*20.*existing.*11.*reserve.*10/i); + expect(fs.readdirSync(streamDir)).toEqual(['existing.bin']); + }); + + it('includes in-process reservations when admitting concurrent downloads', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-quota-')); + tempDirs.push(streamDir); + fs.writeFileSync(path.join(streamDir, 'existing.bin'), Buffer.alloc(1)); + const info = { + status: 'ok', retcode: 0, + data: { type: 'stream', data_type: 'file_info', file_name: 'pending.bin', file_size: 0, chunk_size: 4 }, + }; + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(`${JSON.stringify(info)}\r\n\r\n`)); }, + }), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, maxStreamBytes: 10, timeoutMs: 1_000 }); + const firstController = new AbortController(); + const first = client.callStream('download_file_stream', { id: 1 }, { signal: firstController.signal }); + const firstOutcome = first.then((value) => ({ value }), (error) => ({ error })); + for (let i = 0; i < 50 && !fs.readdirSync(streamDir).some((name) => name.endsWith('.part')); i++) { + await new Promise((resolve) => setImmediate(resolve)); + } + + await expect(client.callStream('download_file_stream', { id: 2 })).rejects.toThrow(/quota.*reserved=10.*reserve=10/i); + firstController.abort(new Error('test cleanup')); + await firstOutcome; + expect(fs.readdirSync(streamDir)).toEqual(['existing.bin']); + }); }); diff --git a/packages/mcp/tests/tools.test.ts b/packages/mcp/tests/tools.test.ts index 800d4c23..142d6479 100644 --- a/packages/mcp/tests/tools.test.ts +++ b/packages/mcp/tests/tools.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { computeTools, callTool } from '../src/tools'; -import type { ActionClient, OneBotEnvelope } from '../src/client'; +import { computeTools, callTool, parseMode } from '../src/tools'; +import type { ActionClient, OneBotEnvelope, StreamCallOptions, StreamCallResult } from '../src/client'; type Res = Awaited>; function text(res: Res): string { @@ -13,13 +13,28 @@ function parsed(res: Res): any { /** A fake ActionClient — no transport. Records the last call and returns a * canned envelope (overridable per test). */ -function fakeClient(impl?: (action: string, params: Record) => OneBotEnvelope): ActionClient { +function fakeClient( + impl?: (action: string, params: Record) => OneBotEnvelope, + streamImpl?: (action: string, params: Record, options?: StreamCallOptions) => StreamCallResult, +): ActionClient { return { call: async (action, params) => impl?.(action, params) ?? { status: 'ok', retcode: 0, data: { action, params } }, + callStream: async (action, params, options) => streamImpl?.(action, params, options) ?? { + frame_count: 1, + frames: [], + terminal: { status: 'ok', retcode: 0, data: { type: 'response', action, params } }, + }, }; } describe('computeTools — mode gating', () => { + it('fails fast on an invalid SNOWLUMA_MCP_MODE', () => { + expect(parseMode(undefined)).toBeUndefined(); + expect(parseMode('WRITE')).toBe('write'); + for (const invalid of ['', 'unsafe', 'reader']) { + expect(() => parseMode(invalid), invalid).toThrow(/SNOWLUMA_MCP_MODE/); + } + }); it('docs mode exposes only the 4 catalog tools', () => { expect(computeTools('docs').map((t) => t.name)).toEqual([ 'list_actions', 'get_action', 'search_actions', 'list_categories', @@ -100,6 +115,7 @@ describe('callTool — invoke_action (write)', () => { seen = { action, params }; return { status: 'ok', retcode: 0, data: { message_id: 42 } }; }, + callStream: async () => { throw new Error('unexpected stream call'); }, }; const res = await callTool('invoke_action', { action: 'send_group_msg', params: { group_id: 1, message: 'hi' } }, { mode: 'write', client }); expect(res.isError).toBeFalsy(); @@ -120,7 +136,10 @@ describe('callTool — invoke_action (write)', () => { expect(parsed(res).wording).toBe('未找到'); }); it('maps a transport-level throw to isError', async () => { - const client: ActionClient = { call: async () => { throw new Error('connection refused'); } }; + const client: ActionClient = { + call: async () => { throw new Error('connection refused'); }, + callStream: async () => { throw new Error('unexpected stream call'); }, + }; const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client }); expect(res.isError).toBe(true); expect(text(res)).toContain('调用失败'); @@ -135,4 +154,66 @@ describe('callTool — invoke_action (write)', () => { expect(res.isError).toBe(true); expect(text(res)).toContain('未知 action'); }); + + it('routes catalog Stream Actions through callStream and returns the bounded summary', async () => { + let ordinaryCalls = 0; + let streamCalls = 0; + const terminal = { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete' } }; + const client: ActionClient = { + call: async () => { ordinaryCalls++; return { status: 'ok', retcode: 0 }; }, + callStream: async (action, params) => { + streamCalls++; + expect(action).toBe('test_download_stream'); + expect(params).toEqual({ error: false }); + return { frame_count: 1, frames: [], terminal }; + }, + }; + + const res = await callTool('invoke_action', { action: 'test_download_stream', params: { error: false } }, { mode: 'write', client }); + + expect(res.isError).toBeFalsy(); + expect(parsed(res)).toEqual({ frame_count: 1, frames: [], terminal }); + expect(streamCalls).toBe(1); + expect(ordinaryCalls).toBe(0); + }); + + it('passes execution.input_file only as an MCP upload option, never as OneBot params', async () => { + let seen: { params: Record; inputFile?: string } | undefined; + const client = fakeClient(undefined, (_action, params, options) => { + seen = { params, inputFile: options?.inputFile }; + return { + file_path: '/remote/local.txt', file_size: 5, sha256: 'abc', chunk_count: 1, stream_id: 'id', + terminal: { status: 'ok', retcode: 0, data: { type: 'response', status: 'file_complete' } }, + }; + }); + + const res = await callTool('invoke_action', { + action: 'upload_file_stream', + params: { file_retention: 0 }, + execution: { input_file: '/allowed/local.txt' }, + }, { mode: 'write', client }); + + expect(res.isError).toBeFalsy(); + expect(seen).toEqual({ params: { file_retention: 0 }, inputFile: '/allowed/local.txt' }); + }); + + it('forwards MCP request cancellation to Stream Action execution', async () => { + const controller = new AbortController(); + let seenSignal: AbortSignal | undefined; + const client = fakeClient(undefined, (_action, _params, options) => { + seenSignal = options?.signal; + return { + frame_count: 1, + frames: [], + terminal: { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete' } }, + }; + }); + + const res = await callTool('invoke_action', { action: 'test_download_stream', params: {} }, { + mode: 'write', client, signal: controller.signal, + }); + + expect(res.isError).toBeFalsy(); + expect(seenSignal).toBe(controller.signal); + }); });