feat(mcp): add compatible protocol workflows and execution services
This commit is contained in:
31 files changed
+7317
-56
No files matched your search
@@ -11,6 +11,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { ActionCallError } from './results.js';
|
||||
import type { TraceContext } from './tracing.js';
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_STREAM_BYTES = 4 * 1024 * 1024 * 1024;
|
||||
@@ -26,7 +27,7 @@ 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 = [
|
||||
export const MCP_UPLOAD_OWNED_FIELDS = [
|
||||
'stream_id',
|
||||
'chunk_data',
|
||||
'chunk_index',
|
||||
@@ -135,6 +136,18 @@ export interface TransferProgress {
|
||||
|
||||
export interface CallOptions {
|
||||
signal?: AbortSignal;
|
||||
trace?: TraceContext;
|
||||
}
|
||||
|
||||
function requestHeaders(
|
||||
base: Record<string, string>,
|
||||
trace?: TraceContext,
|
||||
): Record<string, string> {
|
||||
return {
|
||||
...base,
|
||||
...(trace ? { traceparent: trace.traceparent } : {}),
|
||||
...(trace?.tracestate ? { tracestate: trace.tracestate } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export interface StreamCallOptions extends CallOptions {
|
||||
@@ -733,7 +746,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
|
||||
signal.throwIfAborted();
|
||||
const res = await fetchImpl(opts.endpoint, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
headers: requestHeaders(headers, options?.trace),
|
||||
body: JSON.stringify({ action, params }),
|
||||
signal,
|
||||
});
|
||||
@@ -842,6 +855,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
|
||||
(uploadParams, signal) =>
|
||||
client.callStream(action, uploadParams, {
|
||||
...(signal ? { signal } : {}),
|
||||
...(options.trace ? { trace: options.trace } : {}),
|
||||
[INTERNAL_STREAM_CALL]: true,
|
||||
} as InternalStreamCallOptions),
|
||||
options.onProgress,
|
||||
@@ -867,7 +881,7 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient {
|
||||
throwIfCancelled(options?.signal, action, 'connection');
|
||||
res = await fetchImpl(opts.endpoint, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
headers: requestHeaders(headers, options?.trace),
|
||||
body: JSON.stringify({ action, params }),
|
||||
signal: requestSignal,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
||||
import {
|
||||
createRequestStateCodec,
|
||||
fromJsonSchema,
|
||||
inputRequired,
|
||||
inputResponse,
|
||||
type InputRequiredResult,
|
||||
type ServerContext,
|
||||
type ServerOptions,
|
||||
type Tool,
|
||||
} from '@modelcontextprotocol/server';
|
||||
import { asError, type StructuredResult } from './results.js';
|
||||
|
||||
const INPUT_KEY = 'missing_parameters';
|
||||
const INPUT_NAMES = {
|
||||
query_action_with_input: 'query_action',
|
||||
invoke_action_with_input: 'invoke_action',
|
||||
} as const;
|
||||
|
||||
export type InputCompletionTool = keyof typeof INPUT_NAMES;
|
||||
|
||||
export interface InputPreparation {
|
||||
action: string;
|
||||
params: Record<string, unknown>;
|
||||
inputSchema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface InputCompletionCallbacks {
|
||||
capabilities: unknown;
|
||||
/** Runs the same permission and argument checks as the existing execution tools. */
|
||||
preflight: (args: Record<string, unknown>) => InputPreparation | StructuredResult;
|
||||
execute: (args: Record<string, unknown>) => Promise<StructuredResult>;
|
||||
}
|
||||
|
||||
interface PendingInput {
|
||||
fingerprint: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
interface InputState {
|
||||
challenge: string;
|
||||
}
|
||||
|
||||
export interface InputCompletion {
|
||||
verifyRequestState: NonNullable<NonNullable<ServerOptions['requestState']>['verify']>;
|
||||
handle: (
|
||||
name: InputCompletionTool,
|
||||
args: Record<string, unknown>,
|
||||
context: ServerContext,
|
||||
callbacks: InputCompletionCallbacks,
|
||||
) => Promise<StructuredResult | InputRequiredResult>;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export function isInputCompletionTool(name: string): name is InputCompletionTool {
|
||||
return Object.hasOwn(INPUT_NAMES, name);
|
||||
}
|
||||
|
||||
export function inputCompletionBaseTool(
|
||||
name: InputCompletionTool,
|
||||
): 'query_action' | 'invoke_action' {
|
||||
return INPUT_NAMES[name];
|
||||
}
|
||||
|
||||
/** Derive visibility, schemas, annotations and result contracts from the existing tools. */
|
||||
export function inputCompletionTools(baseTools: Tool[]): Tool[] {
|
||||
return baseTools.flatMap((tool) => {
|
||||
if (tool.name !== 'query_action' && tool.name !== 'invoke_action') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
...tool,
|
||||
name: `${tool.name}_with_input`,
|
||||
description: `${tool.description} 缺少必填参数时向支持表单的客户端请求补充;补充完成前不执行动作,已有参数不会被覆盖。`,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
// Bind every round to the exact tool and original arguments, irrespective of JSON
|
||||
// object key ordering. Values never appear in the signed token or diagnostics.
|
||||
function fingerprint(name: string, args: Record<string, unknown>): string {
|
||||
function ordered(value: unknown): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(ordered);
|
||||
}
|
||||
|
||||
if (isObject(value)) {
|
||||
return Object.fromEntries(
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((key) => [key, ordered(value[key])]),
|
||||
);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify([name, ordered(args)]))
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
function supportsForm(capabilities: unknown): boolean {
|
||||
const elicitation = isObject(capabilities) ? capabilities.elicitation : undefined;
|
||||
|
||||
if (!isObject(elicitation)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The pre-form/url capability shape declared form support with an empty object.
|
||||
return (
|
||||
isObject(elicitation.form) ||
|
||||
(elicitation.form === undefined && elicitation.url === undefined)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One instance belongs to one configured runtime, shared by its server factory.
|
||||
* Pending prompts are deliberately transient: a restart invalidates unfinished
|
||||
* input, and never resumes or retries a side effect automatically.
|
||||
*/
|
||||
export function createInputCompletion(
|
||||
options: { ttlSeconds?: number; maxPending?: number } = {},
|
||||
): InputCompletion {
|
||||
const ttlSeconds = options.ttlSeconds ?? 600;
|
||||
const maxPending = options.maxPending ?? 256;
|
||||
|
||||
if (
|
||||
!Number.isInteger(ttlSeconds) ||
|
||||
ttlSeconds < 1 ||
|
||||
!Number.isInteger(maxPending) ||
|
||||
maxPending < 1
|
||||
) {
|
||||
throw new RangeError('Input completion limits must be positive integers');
|
||||
}
|
||||
|
||||
const codec = createRequestStateCodec<InputState>({
|
||||
key: randomBytes(32),
|
||||
ttlSeconds,
|
||||
// HTTP callers must supply validated authInfo. Stdio has one trusted peer.
|
||||
// The codec hides the binding behind an HMAC, including bearer credentials.
|
||||
bind: (context) =>
|
||||
JSON.stringify([
|
||||
context.mcpReq.method,
|
||||
context.http?.authInfo?.clientId ?? null,
|
||||
context.http?.authInfo?.token ?? null,
|
||||
context.sessionId ?? null,
|
||||
]),
|
||||
});
|
||||
const pending = new Map<string, PendingInput>();
|
||||
let closed = false;
|
||||
|
||||
return {
|
||||
verifyRequestState: async (token, context) => {
|
||||
if (closed) {
|
||||
throw new Error('closed');
|
||||
}
|
||||
|
||||
return codec.verify(token, context);
|
||||
},
|
||||
close() {
|
||||
closed = true;
|
||||
pending.clear();
|
||||
},
|
||||
async handle(name, args, context, callbacks) {
|
||||
if (closed) {
|
||||
return asError('补充输入服务已关闭。', 'configuration');
|
||||
}
|
||||
|
||||
context.mcpReq.signal.throwIfAborted();
|
||||
const prepared = callbacks.preflight(args);
|
||||
|
||||
if ('structuredContent' in prepared) {
|
||||
return prepared;
|
||||
}
|
||||
|
||||
const state = context.mcpReq.requestState<unknown>();
|
||||
const required = Array.isArray(prepared.inputSchema.required)
|
||||
? prepared.inputSchema.required.filter(
|
||||
(key): key is string => typeof key === 'string',
|
||||
)
|
||||
: [];
|
||||
const missing = required.filter((key) => !Object.hasOwn(prepared.params, key));
|
||||
const original = fingerprint(name, args);
|
||||
|
||||
for (const [id, entry] of pending) {
|
||||
if (entry.expiresAt <= Date.now()) {
|
||||
pending.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
if (state !== undefined) {
|
||||
if (!isObject(state) || typeof state.challenge !== 'string') {
|
||||
return asError('补充输入状态无效。');
|
||||
}
|
||||
|
||||
const entry = pending.get(state.challenge);
|
||||
|
||||
if (!entry || entry.fingerprint !== original) {
|
||||
return asError('补充输入已过期、已使用或原始调用已变更,请重新发起调用。');
|
||||
}
|
||||
|
||||
// Claim synchronously before validation or execution can yield. A
|
||||
// replay/concurrent retry can never execute the same answer twice.
|
||||
pending.delete(state.challenge);
|
||||
const response = inputResponse(context.mcpReq.inputResponses, INPUT_KEY);
|
||||
|
||||
if (response.kind === 'elicit' && response.action !== 'accept') {
|
||||
return asError(
|
||||
'用户拒绝或取消补充输入,动作未执行。',
|
||||
'cancelled',
|
||||
'按用户意愿停止;需要时重新发起调用。',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
response.kind !== 'elicit' ||
|
||||
!isObject(response.content) ||
|
||||
typeof response.content.params_json !== 'string' ||
|
||||
Object.keys(response.content).some((key) => key !== 'params_json')
|
||||
) {
|
||||
return asError('补充输入必须包含 params_json 字符串,动作未执行。');
|
||||
}
|
||||
|
||||
let additions: unknown;
|
||||
|
||||
try {
|
||||
additions = JSON.parse(response.content.params_json);
|
||||
} catch {
|
||||
return asError('补充参数不是有效 JSON,动作未执行。');
|
||||
}
|
||||
|
||||
if (
|
||||
!isObject(additions) ||
|
||||
Object.keys(additions).some((key) => !missing.includes(key))
|
||||
) {
|
||||
return asError(
|
||||
'补充参数只能包含本次缺失的必填字段,不能覆盖已有参数或添加其他字段。',
|
||||
);
|
||||
}
|
||||
|
||||
const properties = isObject(prepared.inputSchema.properties)
|
||||
? prepared.inputSchema.properties
|
||||
: {};
|
||||
const schema = fromJsonSchema<Record<string, unknown>>({
|
||||
type: 'object',
|
||||
properties: Object.fromEntries(
|
||||
missing.map((key) => [key, properties[key] ?? {}]),
|
||||
),
|
||||
required: missing,
|
||||
additionalProperties: false,
|
||||
});
|
||||
const validated = await schema['~standard'].validate(additions);
|
||||
|
||||
if (validated.issues) {
|
||||
return asError(
|
||||
'补充参数不符合动作目录中的字段类型或约束,动作未执行。',
|
||||
'invalid_arguments',
|
||||
'使用 get_action 查看参数要求后重新发起调用。',
|
||||
);
|
||||
}
|
||||
|
||||
context.mcpReq.signal.throwIfAborted();
|
||||
|
||||
if (closed) {
|
||||
return asError('补充输入服务已关闭,动作未执行。', 'configuration');
|
||||
}
|
||||
|
||||
return callbacks.execute({
|
||||
...args,
|
||||
params: { ...prepared.params, ...validated.value },
|
||||
});
|
||||
}
|
||||
|
||||
if (context.mcpReq.inputResponses || context.mcpReq.droppedInputResponseKeys?.length) {
|
||||
return asError('补充输入缺少有效请求状态,动作未执行。');
|
||||
}
|
||||
|
||||
if (!missing.length) {
|
||||
return callbacks.execute(args);
|
||||
}
|
||||
|
||||
if (!supportsForm(callbacks.capabilities)) {
|
||||
return asError(
|
||||
'当前客户端未声明表单补充输入能力;请直接提供必填参数。',
|
||||
'configuration',
|
||||
'使用 get_action 查看参数后调用原 query_action 或 invoke_action。',
|
||||
);
|
||||
}
|
||||
|
||||
if (pending.size >= maxPending) {
|
||||
return asError(
|
||||
'待补充输入的请求数量已达上限,请完成现有请求或等待过期。',
|
||||
'execution',
|
||||
);
|
||||
}
|
||||
|
||||
const challenge = randomUUID();
|
||||
pending.set(challenge, {
|
||||
fingerprint: original,
|
||||
expiresAt: Date.now() + ttlSeconds * 1000,
|
||||
});
|
||||
|
||||
try {
|
||||
const requestState = await codec.mint({ challenge }, context);
|
||||
context.mcpReq.signal.throwIfAborted();
|
||||
|
||||
if (closed) {
|
||||
throw new Error('Input completion closed');
|
||||
}
|
||||
|
||||
const properties = isObject(prepared.inputSchema.properties)
|
||||
? prepared.inputSchema.properties
|
||||
: {};
|
||||
return inputRequired({
|
||||
inputRequests: {
|
||||
[INPUT_KEY]: inputRequired.elicit({
|
||||
mode: 'form',
|
||||
message: `请补充 ${prepared.action} 缺失的必填参数:${missing.join('、')}。仅填写这些字段的 JSON 对象,已有参数保持不变。字段要求:${JSON.stringify(Object.fromEntries(missing.map((key) => [key, properties[key] ?? {}])))}`,
|
||||
requestedSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
params_json: { type: 'string', title: '缺失参数(JSON 对象)' },
|
||||
},
|
||||
required: ['params_json'],
|
||||
},
|
||||
}),
|
||||
},
|
||||
requestState,
|
||||
});
|
||||
} catch (error) {
|
||||
pending.delete(challenge);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import type { ReadResourceResult, Resource, Tool } from '@modelcontextprotocol/server';
|
||||
import { asError, asText, RESULT_SCHEMA, type StructuredResult } from './results.js';
|
||||
|
||||
export const MESSAGE_PREVIEW_TOOL = 'preview_message';
|
||||
export const MESSAGE_APP_URI = 'ui://snowluma/message-preview.html';
|
||||
export const MESSAGE_APP_MIME_TYPE = 'text/html;profile=mcp-app';
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function supportsMessageApp(capabilities: unknown): boolean {
|
||||
if (!record(capabilities) || !record(capabilities.extensions)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ui = capabilities.extensions['io.modelcontextprotocol/ui'];
|
||||
return (
|
||||
record(ui) && Array.isArray(ui.mimeTypes) && ui.mimeTypes.includes(MESSAGE_APP_MIME_TYPE)
|
||||
);
|
||||
}
|
||||
|
||||
export function messagePreviewTool(uiSupported: boolean): Tool {
|
||||
return {
|
||||
name: MESSAGE_PREVIEW_TOOL,
|
||||
description:
|
||||
'预览一条纯文本群聊或私聊草稿,可附带引用消息编号。只生成草稿,不发送消息;支持面板的客户端可由用户点击发送,仍受写模式限制。文字按字面发送,不解释消息控制代码。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
message_type: { type: 'string', enum: ['group', 'private'] },
|
||||
target_id: { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
|
||||
text: { type: 'string', minLength: 1 },
|
||||
reply_to: {
|
||||
type: 'integer',
|
||||
minimum: -2147483648,
|
||||
maximum: 2147483647,
|
||||
not: { const: 0 },
|
||||
description: '可选引用消息编号,负值合法。',
|
||||
},
|
||||
},
|
||||
required: ['message_type', 'target_id', 'text'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
outputSchema: RESULT_SCHEMA,
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
...(uiSupported
|
||||
? { _meta: { ui: { resourceUri: MESSAGE_APP_URI, visibility: ['model', 'app'] } } }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Pure draft construction. Sending remains an ordinary invoke_action call. */
|
||||
export function previewMessage(args: Record<string, unknown>, canSend: boolean): StructuredResult {
|
||||
if (
|
||||
Object.keys(args).some(
|
||||
(key) => !['message_type', 'target_id', 'text', 'reply_to'].includes(key),
|
||||
)
|
||||
) {
|
||||
return asError('草稿包含不支持的字段。');
|
||||
}
|
||||
|
||||
const { message_type: messageType, target_id: targetId, text, reply_to: replyTo } = args;
|
||||
|
||||
if (messageType !== 'group' && messageType !== 'private') {
|
||||
return asError('message_type 必须为 group 或 private。');
|
||||
}
|
||||
|
||||
if (typeof targetId !== 'number' || !Number.isSafeInteger(targetId) || targetId <= 0) {
|
||||
return asError('target_id 必须是正的安全整数。');
|
||||
}
|
||||
|
||||
if (typeof text !== 'string' || text.trim().length === 0) {
|
||||
return asError('text 必须是非空文本。');
|
||||
}
|
||||
|
||||
if (
|
||||
replyTo !== undefined &&
|
||||
(typeof replyTo !== 'number' ||
|
||||
!Number.isInteger(replyTo) ||
|
||||
replyTo === 0 ||
|
||||
replyTo < -2147483648 ||
|
||||
replyTo > 2147483647)
|
||||
) {
|
||||
return asError('reply_to 必须是非零的有符号 32 位消息编号,负值合法。');
|
||||
}
|
||||
|
||||
const message: Array<{ type: string; data: Record<string, string> }> = [];
|
||||
|
||||
if (replyTo !== undefined) {
|
||||
message.push({ type: 'reply', data: { id: String(replyTo) } });
|
||||
}
|
||||
|
||||
// Explicit text segments preserve literal control-code-looking text.
|
||||
message.push({ type: 'text', data: { text } });
|
||||
return asText({
|
||||
draft: {
|
||||
message_type: messageType,
|
||||
target_id: targetId,
|
||||
text,
|
||||
...(replyTo !== undefined ? { reply_to: replyTo } : {}),
|
||||
},
|
||||
can_send: canSend,
|
||||
notice: '此为待发送草稿,尚未发送。',
|
||||
invocation: {
|
||||
name: 'invoke_action',
|
||||
arguments: {
|
||||
action: messageType === 'group' ? 'send_group_msg' : 'send_private_msg',
|
||||
params: { [messageType === 'group' ? 'group_id' : 'user_id']: targetId, message },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function messageAppResources(uiSupported: boolean): Resource[] {
|
||||
return uiSupported
|
||||
? [
|
||||
{
|
||||
uri: MESSAGE_APP_URI,
|
||||
name: '消息草稿预览',
|
||||
description: '查看消息草稿并按需手动发送。',
|
||||
mimeType: MESSAGE_APP_MIME_TYPE,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}
|
||||
|
||||
export async function readMessageAppResource(uri: string): Promise<ReadResourceResult | undefined> {
|
||||
if (uri !== MESSAGE_APP_URI) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// The build emits the same self-contained asset beside this compiled module.
|
||||
// A missing asset is a packaging error and must not become a blank panel.
|
||||
const text = await readFile(new URL('./message-app.html', import.meta.url), 'utf8');
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri,
|
||||
mimeType: MESSAGE_APP_MIME_TYPE,
|
||||
text,
|
||||
_meta: {
|
||||
ui: {
|
||||
csp: {
|
||||
connectDomains: [],
|
||||
resourceDomains: [],
|
||||
frameDomains: [],
|
||||
baseUriDomains: [],
|
||||
},
|
||||
prefersBorder: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';
|
||||
import type { CallToolResult, Tool } from '@modelcontextprotocol/server';
|
||||
import type { OneBotEnvelope } from './client.js';
|
||||
|
||||
export type FailureKind =
|
||||
|
||||
@@ -1,52 +1,336 @@
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
import {
|
||||
CallToolRequestSchema,
|
||||
ListResourcesRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
ReadResourceRequestSchema,
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
Server,
|
||||
ProtocolError,
|
||||
isInputRequiredResult,
|
||||
isSpecType,
|
||||
type ServerContext,
|
||||
type Tool,
|
||||
} from '@modelcontextprotocol/server';
|
||||
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
|
||||
import { callTool, computeTools, type CallCtx } from './tools.js';
|
||||
import { callTool, computeTools, prepareActionCall, type CallCtx } from './tools.js';
|
||||
import { createProgressReporter } from './progress.js';
|
||||
import { VERSION } from './version.js';
|
||||
import { createCallTrace } from './tracing.js';
|
||||
import {
|
||||
createInputCompletion,
|
||||
inputCompletionBaseTool,
|
||||
inputCompletionTools,
|
||||
isInputCompletionTool,
|
||||
type InputCompletion,
|
||||
} from './elicitation.js';
|
||||
import {
|
||||
MESSAGE_PREVIEW_TOOL,
|
||||
messageAppResources,
|
||||
messagePreviewTool,
|
||||
previewMessage,
|
||||
readMessageAppResource,
|
||||
supportsMessageApp,
|
||||
} from './message-app.js';
|
||||
import { EventSubscriptions, EVENT_TOOLS, type EventSubscriptionOptions } from './subscriptions.js';
|
||||
import {
|
||||
installTaskHandlers,
|
||||
supportsTasks,
|
||||
type PersistentTasks,
|
||||
type TaskHandle,
|
||||
} from './tasks.js';
|
||||
import { asError, asText, RESULT_SCHEMA, type StructuredResult } from './results.js';
|
||||
|
||||
export interface McpServerOptions extends Pick<CallCtx, 'mode' | 'client'> {
|
||||
inputCompletion?: InputCompletion;
|
||||
tasks?: PersistentTasks;
|
||||
events?: EventSubscriptionOptions;
|
||||
}
|
||||
|
||||
const RESOURCE_URI = 'snowluma://onebot/actions';
|
||||
|
||||
export function createMcpServer(ctx: Pick<CallCtx, 'mode' | 'client'>): Server {
|
||||
export function createMcpServer(ctx: McpServerOptions): Server {
|
||||
const input = ctx.inputCompletion ?? createInputCompletion();
|
||||
const events =
|
||||
ctx.mode !== 'docs' && ctx.events ? new EventSubscriptions(ctx.events) : undefined;
|
||||
const legacySubscriptions = new Set<string>();
|
||||
const server = new Server(
|
||||
{ name: 'snowluma-mcp', version: VERSION },
|
||||
{ capabilities: { tools: {}, resources: {} } },
|
||||
{
|
||||
capabilities: {
|
||||
tools: {},
|
||||
resources: events ? { subscribe: true, listChanged: true } : {},
|
||||
extensions: { 'io.modelcontextprotocol/ui': {} },
|
||||
},
|
||||
requestState: { verify: input.verifyRequestState },
|
||||
// Tool availability depends on the configured mode; only the bundled
|
||||
// action catalog is public. Execution and account data are never cached.
|
||||
cacheHints: {
|
||||
'tools/list': { ttlMs: 300_000, cacheScope: 'private' },
|
||||
'resources/list': { ttlMs: events ? 0 : 300_000, cacheScope: 'private' },
|
||||
'resources/read': { ttlMs: 0, cacheScope: 'private' },
|
||||
'resources/templates/list': { ttlMs: 300_000, cacheScope: 'public' },
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
||||
tools: computeTools(ctx.mode),
|
||||
const capabilities = (request: ServerContext) => {
|
||||
const envelope: Record<string, unknown> | undefined = request.mcpReq.envelope;
|
||||
|
||||
if (!envelope) {
|
||||
return server.getClientCapabilities();
|
||||
}
|
||||
|
||||
const value = envelope['io.modelcontextprotocol/clientCapabilities'];
|
||||
|
||||
if (!isSpecType.ClientCapabilities(value)) {
|
||||
throw new ProtocolError(-32602, 'Invalid client capabilities');
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
const cacheMetadata = (scope: 'public' | 'private') =>
|
||||
(server.getNegotiatedProtocolVersion() ?? '') >= '2026-07-28'
|
||||
? { ttlMs: scope === 'public' ? 300_000 : 0, cacheScope: scope }
|
||||
: {};
|
||||
const taskEnabled = (request: ServerContext) =>
|
||||
!!ctx.tasks &&
|
||||
ctx.mode === 'write' &&
|
||||
(server.getNegotiatedProtocolVersion() ?? '') >= '2026-07-28' &&
|
||||
supportsTasks(request.mcpReq.envelope);
|
||||
|
||||
const availableTools = (request: ServerContext): Tool[] => {
|
||||
const base = computeTools(ctx.mode);
|
||||
const extra = [
|
||||
...inputCompletionTools(base),
|
||||
messagePreviewTool(supportsMessageApp(capabilities(request))),
|
||||
...(events ? EVENT_TOOLS : []),
|
||||
];
|
||||
|
||||
if (taskEnabled(request)) {
|
||||
const invocation = base.find((tool) => tool.name === 'invoke_action')!;
|
||||
extra.push(
|
||||
{
|
||||
...invocation,
|
||||
name: 'invoke_action_background',
|
||||
description:
|
||||
'在后台执行一个流式传输动作,返回可跨重启查询的任务编号。仅限流式动作和写模式;重启不会自动重放未完成操作。',
|
||||
},
|
||||
{
|
||||
name: 'list_tasks',
|
||||
description: '列出本配置下持久化任务的编号和状态,不返回结果正文。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
cursor: { type: 'string' },
|
||||
limit: { type: 'integer', minimum: 1, maximum: 100 },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
outputSchema: RESULT_SCHEMA,
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return [...base, ...extra];
|
||||
};
|
||||
|
||||
if (ctx.tasks && ctx.mode === 'write') {
|
||||
installTaskHandlers(server, ctx.tasks);
|
||||
}
|
||||
|
||||
events?.onUpdate(async (uri) => {
|
||||
if (
|
||||
(server.getNegotiatedProtocolVersion() ?? '') >= '2026-07-28' ||
|
||||
legacySubscriptions.has(uri)
|
||||
) {
|
||||
await server.sendResourceUpdated({ uri });
|
||||
}
|
||||
});
|
||||
|
||||
server.onclose = () => {
|
||||
events?.close();
|
||||
legacySubscriptions.clear();
|
||||
|
||||
if (!ctx.inputCompletion) {
|
||||
input.close();
|
||||
}
|
||||
};
|
||||
|
||||
server.setRequestHandler('tools/list', async (_req, request) => ({
|
||||
tools: availableTools(request),
|
||||
}));
|
||||
server.setRequestHandler(CallToolRequestSchema, async (req, extra) => {
|
||||
const token = req.params._meta?.progressToken;
|
||||
server.setRequestHandler('tools/call', async (req, request) => {
|
||||
const { mcpReq } = request;
|
||||
const trace = createCallTrace(mcpReq._meta);
|
||||
const tool = availableTools(request).some((entry) => entry.name === req.params.name)
|
||||
? req.params.name
|
||||
: 'unlisted';
|
||||
const started = performance.now();
|
||||
|
||||
const report = (event: string, outcome?: string, kind?: string, taskId?: string) => {
|
||||
console.error(
|
||||
'[snowluma-mcp] %s',
|
||||
JSON.stringify({
|
||||
event,
|
||||
tool,
|
||||
traceparent: trace.traceparent,
|
||||
...(outcome
|
||||
? { outcome, duration_ms: Math.round(performance.now() - started) }
|
||||
: {}),
|
||||
...(kind ? { kind } : {}),
|
||||
...(taskId ? { task_id: taskId } : {}),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
report('call_started');
|
||||
const token = mcpReq._meta?.progressToken;
|
||||
const progress =
|
||||
token === undefined
|
||||
? undefined
|
||||
: createProgressReporter(
|
||||
(value) =>
|
||||
extra.sendNotification({
|
||||
mcpReq.notify({
|
||||
method: 'notifications/progress',
|
||||
params: { progressToken: token, ...value },
|
||||
}),
|
||||
extra.signal,
|
||||
mcpReq.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();
|
||||
try {
|
||||
const args = req.params.arguments ?? {};
|
||||
const callContext: CallCtx = {
|
||||
mode: ctx.mode,
|
||||
client: ctx.client,
|
||||
signal: mcpReq.signal,
|
||||
trace,
|
||||
...(progress ? { onProgress: progress.report } : {}),
|
||||
};
|
||||
|
||||
const dispatch = async (): Promise<
|
||||
StructuredResult | TaskHandle | Awaited<ReturnType<InputCompletion['handle']>>
|
||||
> => {
|
||||
if (isInputCompletionTool(req.params.name)) {
|
||||
const base = inputCompletionBaseTool(req.params.name);
|
||||
return input.handle(req.params.name, args, request, {
|
||||
capabilities: capabilities(request),
|
||||
preflight: (values) => {
|
||||
const prepared = prepareActionCall(
|
||||
values,
|
||||
callContext,
|
||||
base === 'query_action' ? 'read' : 'write',
|
||||
);
|
||||
return 'structuredContent' in prepared
|
||||
? prepared
|
||||
: {
|
||||
action: prepared.action,
|
||||
params: prepared.params,
|
||||
inputSchema: prepared.inputSchema,
|
||||
};
|
||||
},
|
||||
execute: (values) => callTool(base, values, callContext),
|
||||
});
|
||||
}
|
||||
|
||||
if (req.params.name === MESSAGE_PREVIEW_TOOL) {
|
||||
return previewMessage(args, ctx.mode === 'write' && !!ctx.client);
|
||||
}
|
||||
|
||||
if (events?.handlesTool(req.params.name)) {
|
||||
const result = await events.callTool(req.params.name, args, mcpReq.signal);
|
||||
|
||||
if (!result.isError) {
|
||||
if (
|
||||
req.params.name === 'unsubscribe_events' &&
|
||||
typeof args.uri === 'string'
|
||||
) {
|
||||
legacySubscriptions.delete(args.uri);
|
||||
}
|
||||
|
||||
await server.sendResourceListChanged();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
if (
|
||||
req.params.name === 'invoke_action_background' ||
|
||||
req.params.name === 'list_tasks'
|
||||
) {
|
||||
if (!taskEnabled(request) || !ctx.tasks) {
|
||||
return asError(
|
||||
'持久任务需配置任务目录、启用写模式,并由客户端声明新版任务能力。',
|
||||
'configuration',
|
||||
);
|
||||
}
|
||||
|
||||
if (req.params.name === 'list_tasks') {
|
||||
if (
|
||||
Object.keys(args).some((key) => key !== 'cursor' && key !== 'limit') ||
|
||||
(args.cursor !== undefined && typeof args.cursor !== 'string') ||
|
||||
(args.limit !== undefined && typeof args.limit !== 'number')
|
||||
) {
|
||||
return asError('任务列表参数无效。');
|
||||
}
|
||||
|
||||
return asText(
|
||||
ctx.tasks.list({
|
||||
cursor: args.cursor as string | undefined,
|
||||
limit: args.limit as number | undefined,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const prepared = prepareActionCall(args, callContext, 'write');
|
||||
|
||||
if ('structuredContent' in prepared) {
|
||||
return prepared;
|
||||
}
|
||||
|
||||
if (!prepared.catalog.stream) {
|
||||
return asError('后台任务仅支持流式传输动作;普通动作请使用原执行工具。');
|
||||
}
|
||||
|
||||
mcpReq.signal.throwIfAborted();
|
||||
return ctx.tasks.start(async ({ signal }) =>
|
||||
callTool('invoke_action', args, {
|
||||
mode: ctx.mode,
|
||||
client: ctx.client,
|
||||
signal,
|
||||
trace,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return callTool(req.params.name, args, callContext);
|
||||
};
|
||||
|
||||
const result = await dispatch();
|
||||
|
||||
if (isInputRequiredResult(result)) {
|
||||
report('call_input_required', 'unknown');
|
||||
return { ...result, _meta: { traceparent: trace.traceparent } };
|
||||
}
|
||||
|
||||
if (!('structuredContent' in result)) {
|
||||
report('call_detached', 'unknown', undefined, result.taskId);
|
||||
return { ...result, _meta: { traceparent: trace.traceparent } };
|
||||
}
|
||||
|
||||
if (!result.isError) {
|
||||
await progress?.finish();
|
||||
}
|
||||
|
||||
const { outcome, kind } = result.structuredContent.diagnostics;
|
||||
report(
|
||||
mcpReq.signal.aborted || kind === 'cancelled' ? 'call_cancelled' : 'call_finished',
|
||||
outcome,
|
||||
kind,
|
||||
);
|
||||
return { ...result, _meta: { ...result._meta, traceparent: trace.traceparent } };
|
||||
} catch (error) {
|
||||
report(mcpReq.signal.aborted ? 'call_cancelled' : 'call_failed', 'unknown');
|
||||
throw error;
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
||||
server.setRequestHandler('resources/list', async (_req, request) => ({
|
||||
resources: [
|
||||
{
|
||||
uri: RESOURCE_URI,
|
||||
@@ -54,14 +338,28 @@ export function createMcpServer(ctx: Pick<CallCtx, 'mode' | 'client'>): Server {
|
||||
mimeType: 'application/json',
|
||||
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
|
||||
},
|
||||
...messageAppResources(supportsMessageApp(capabilities(request))),
|
||||
...(events?.resources() ?? []),
|
||||
],
|
||||
}));
|
||||
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
|
||||
server.setRequestHandler('resources/templates/list', async () => ({ resourceTemplates: [] }));
|
||||
server.setRequestHandler('resources/read', async (req) => {
|
||||
if (events?.ownsUri(req.params.uri)) {
|
||||
return { ...events.readResource(req.params.uri), ...cacheMetadata('private') };
|
||||
}
|
||||
|
||||
const app = await readMessageAppResource(req.params.uri);
|
||||
|
||||
if (app) {
|
||||
return { ...app, ...cacheMetadata('public') };
|
||||
}
|
||||
|
||||
if (req.params.uri !== RESOURCE_URI) {
|
||||
throw new Error(`unknown resource: ${req.params.uri}`);
|
||||
}
|
||||
|
||||
return {
|
||||
...cacheMetadata('public'),
|
||||
contents: [
|
||||
{
|
||||
uri: RESOURCE_URI,
|
||||
@@ -75,5 +373,28 @@ export function createMcpServer(ctx: Pick<CallCtx, 'mode' | 'client'>): Server {
|
||||
],
|
||||
};
|
||||
});
|
||||
|
||||
if (events) {
|
||||
server.setRequestHandler('resources/subscribe', async (req) => {
|
||||
if (!events.resources().some((resource) => resource.uri === req.params.uri)) {
|
||||
throw new ProtocolError(-32602, 'Subscribe using the canonical event resource URI');
|
||||
}
|
||||
|
||||
events.readResource(req.params.uri);
|
||||
legacySubscriptions.add(req.params.uri);
|
||||
return {};
|
||||
});
|
||||
server.setRequestHandler('resources/unsubscribe', async (req) => {
|
||||
if (!events.ownsUri(req.params.uri)) {
|
||||
throw new ProtocolError(-32602, 'Unknown event resource');
|
||||
}
|
||||
|
||||
events.remove(req.params.uri);
|
||||
legacySubscriptions.delete(req.params.uri);
|
||||
await server.sendResourceListChanged();
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
return server;
|
||||
}
|
||||
@@ -20,10 +20,13 @@
|
||||
// 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).
|
||||
// SNOWLUMA_MCP_TASK_DIR Private persistent task directory (write mode only).
|
||||
// SNOWLUMA_MCP_EVENTS_URL Explicit OneBot event WebSocket endpoint.
|
||||
//
|
||||
// NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr.
|
||||
|
||||
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
||||
import { serveStdio, StdioServerTransport } from '@modelcontextprotocol/server/stdio';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
|
||||
import {
|
||||
makeHttpClient,
|
||||
@@ -33,7 +36,11 @@ import {
|
||||
} from './client.js';
|
||||
import { parseMode, type Mode } from './tools.js';
|
||||
|
||||
import { createMcpServer } from './server-factory.js';
|
||||
import { createMcpServer, type McpServerOptions } from './server-factory.js';
|
||||
import { createInputCompletion } from './elicitation.js';
|
||||
import { PersistentTasks } from './tasks.js';
|
||||
import { shutdownRuntime } from './shutdown.js';
|
||||
import { normalizeEventSubscriptionOptions } from './subscriptions.js';
|
||||
import { VERSION } from './version.js';
|
||||
|
||||
// ── resolve mode + client from the environment ────────────────────────────
|
||||
@@ -74,13 +81,95 @@ function resolveRuntime(): { mode: Mode; client?: ActionClient } {
|
||||
return { mode, client };
|
||||
}
|
||||
|
||||
const { mode, client } = resolveRuntime();
|
||||
const runtime: McpServerOptions = resolveRuntime();
|
||||
const { mode } = runtime;
|
||||
const taskDirectory = process.env.SNOWLUMA_MCP_TASK_DIR?.trim();
|
||||
const eventsUrl = process.env.SNOWLUMA_MCP_EVENTS_URL?.trim();
|
||||
|
||||
const server = createMcpServer({ mode, client });
|
||||
if (taskDirectory && mode !== 'write') {
|
||||
throw new Error('SNOWLUMA_MCP_TASK_DIR requires write mode and a configured endpoint');
|
||||
}
|
||||
|
||||
if (eventsUrl && mode !== 'docs') {
|
||||
runtime.events = normalizeEventSubscriptionOptions({
|
||||
url: eventsUrl,
|
||||
accessToken: process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined,
|
||||
timeoutMs: parseTimeoutMs(process.env.SNOWLUMA_MCP_TIMEOUT_MS),
|
||||
});
|
||||
}
|
||||
|
||||
if (taskDirectory) {
|
||||
const scopeId = createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
mode,
|
||||
endpoint: process.env.SNOWLUMA_MCP_ENDPOINT?.trim(),
|
||||
token: process.env.SNOWLUMA_MCP_TOKEN?.trim() || null,
|
||||
}),
|
||||
)
|
||||
.digest('hex');
|
||||
runtime.tasks = await PersistentTasks.open(taskDirectory, {
|
||||
scopeId,
|
||||
onChange: (task) =>
|
||||
console.error(
|
||||
'[snowluma-mcp] %s',
|
||||
JSON.stringify({ event: 'task_status', task_id: task.taskId, status: task.status }),
|
||||
),
|
||||
onError: (_error, context) => {
|
||||
console.error('[snowluma-mcp] %s', JSON.stringify(context));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const inputCompletion = createInputCompletion();
|
||||
runtime.inputCompletion = inputCompletion;
|
||||
let cleanup: Promise<void> | undefined;
|
||||
|
||||
function closeFeatures(): Promise<void> {
|
||||
return (cleanup ??= (async () => {
|
||||
inputCompletion.close();
|
||||
await runtime.tasks?.close();
|
||||
})());
|
||||
}
|
||||
|
||||
function reportShutdownError(error: unknown): void {
|
||||
console.error(
|
||||
'[snowluma-mcp] shutdown failed: %s',
|
||||
error instanceof Error ? error.name : 'unknown',
|
||||
);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
const where = client ? ` → ${process.env.SNOWLUMA_MCP_ENDPOINT?.trim()}` : '';
|
||||
const handle = serveStdio(() => createMcpServer(runtime), {
|
||||
transport,
|
||||
onerror: (error) => {
|
||||
// Protocol errors may embed client input. Keep the error category visible
|
||||
// without copying arguments or credentials into process diagnostics.
|
||||
console.error('[snowluma-mcp] protocol error: %s', error.name);
|
||||
},
|
||||
});
|
||||
const transportClosed = transport.onclose;
|
||||
|
||||
transport.onclose = () => {
|
||||
transportClosed?.();
|
||||
void closeFeatures().catch(reportShutdownError);
|
||||
};
|
||||
|
||||
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||
process.once(signal, () => {
|
||||
void shutdownRuntime({
|
||||
closeFeatures,
|
||||
closeProtocol: () => handle.close(),
|
||||
forceClose: async () => {
|
||||
await transport.close();
|
||||
process.stdout.destroy();
|
||||
},
|
||||
onLateProtocolError: reportShutdownError,
|
||||
}).catch(reportShutdownError);
|
||||
});
|
||||
}
|
||||
|
||||
console.error(
|
||||
`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}${where}`,
|
||||
`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories, mode=${mode}`,
|
||||
);
|
||||
@@ -0,0 +1,89 @@
|
||||
export interface ShutdownOptions {
|
||||
closeFeatures(): Promise<void>;
|
||||
closeProtocol(): Promise<void>;
|
||||
forceClose(): Promise<void>;
|
||||
graceMs?: number;
|
||||
onTimeout?: () => void;
|
||||
onLateProtocolError?: (error: unknown) => void;
|
||||
}
|
||||
|
||||
/** Persist task shutdown before waiting on a peer that may have stopped reading stdout. */
|
||||
export async function shutdownRuntime(options: ShutdownOptions): Promise<void> {
|
||||
const failures: unknown[] = [];
|
||||
|
||||
try {
|
||||
await options.closeFeatures();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
|
||||
const protocol = Promise.resolve()
|
||||
.then(() => options.closeProtocol())
|
||||
.then(
|
||||
() => ({ kind: 'closed' as const }),
|
||||
(error: unknown) => ({ kind: 'failed' as const, error }),
|
||||
);
|
||||
let timer!: ReturnType<typeof setTimeout>;
|
||||
const timeout = new Promise<{ kind: 'timeout' }>((resolve) => {
|
||||
timer = setTimeout(() => resolve({ kind: 'timeout' }), options.graceMs ?? 1000);
|
||||
});
|
||||
const outcome = await Promise.race([protocol, timeout]);
|
||||
clearTimeout(timer);
|
||||
|
||||
if (outcome.kind === 'failed') {
|
||||
failures.push(outcome.error);
|
||||
}
|
||||
|
||||
if (outcome.kind === 'timeout') {
|
||||
// A protocol rejection can arrive after the bounded shutdown returns.
|
||||
// Observe the settled outcome too, including races with the deadline.
|
||||
void protocol.then((late) => {
|
||||
if (late.kind !== 'failed') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (options.onLateProtocolError) {
|
||||
options.onLateProtocolError(late.error);
|
||||
} else {
|
||||
console.error(
|
||||
'[snowluma-mcp] protocol shutdown failed after timeout: %s',
|
||||
late.error instanceof Error ? late.error.name : 'unknown',
|
||||
);
|
||||
}
|
||||
} catch (reportError) {
|
||||
console.error(
|
||||
'[snowluma-mcp] late shutdown error reporting failed: %s; original: %s',
|
||||
reportError instanceof Error ? reportError.name : 'unknown',
|
||||
late.error instanceof Error ? late.error.name : 'unknown',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
if (options.onTimeout) {
|
||||
options.onTimeout();
|
||||
} else {
|
||||
console.error('[snowluma-mcp] protocol shutdown timed out; closing transport');
|
||||
}
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
}
|
||||
|
||||
if (outcome.kind !== 'closed') {
|
||||
try {
|
||||
await options.forceClose();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length === 1) {
|
||||
throw failures[0];
|
||||
}
|
||||
|
||||
if (failures.length > 1) {
|
||||
throw new AggregateError(failures, 'Runtime shutdown failed');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,722 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import {
|
||||
ProtocolError,
|
||||
type ReadResourceResult,
|
||||
type Resource,
|
||||
type Tool,
|
||||
} from '@modelcontextprotocol/server';
|
||||
import WebSocket, { type RawData } from 'ws';
|
||||
import { asError, asText, RESULT_SCHEMA, type StructuredResult } from './results.js';
|
||||
|
||||
class EventInputError extends ProtocolError {
|
||||
constructor(message: string) {
|
||||
super(-32602, message);
|
||||
}
|
||||
}
|
||||
|
||||
const PREFIX = 'snowluma://onebot/events/';
|
||||
const MAX_FRAME_BYTES = 256 * 1024;
|
||||
const MAX_BUFFER_BYTES = 1024 * 1024;
|
||||
const MAX_BUFFER_EVENTS = 256;
|
||||
const MAX_SUBSCRIPTIONS = 16;
|
||||
const MAX_FILTER_IDS = 100;
|
||||
type EventType = 'message' | 'notice' | 'request';
|
||||
type SourceStatus = 'connecting' | 'connected' | 'disconnected';
|
||||
type SourceProblem =
|
||||
| 'connection_failed'
|
||||
| 'connection_closed'
|
||||
| 'connection_timeout'
|
||||
| 'invalid_event'
|
||||
| 'account_mismatch'
|
||||
| 'frame_too_large';
|
||||
|
||||
interface Filter {
|
||||
selfId: number;
|
||||
types: Set<EventType>;
|
||||
groupIds?: Set<number>;
|
||||
userIds?: Set<number>;
|
||||
}
|
||||
|
||||
interface BufferedEvent {
|
||||
cursor: number;
|
||||
event: Record<string, unknown>;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
interface Subscription {
|
||||
uri: string;
|
||||
filter: Filter;
|
||||
events: BufferedEvent[];
|
||||
bytes: number;
|
||||
cursor: number;
|
||||
dropped: number;
|
||||
status: SourceStatus;
|
||||
problem?: SourceProblem;
|
||||
notificationFailed: boolean;
|
||||
cancelPending?: () => void;
|
||||
}
|
||||
|
||||
interface Source {
|
||||
socket: WebSocket;
|
||||
selfId: number;
|
||||
ready: Promise<void>;
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
verified: boolean;
|
||||
stopped: boolean;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
heartbeat?: ReturnType<typeof setInterval>;
|
||||
awaitingPong: boolean;
|
||||
}
|
||||
|
||||
export interface EventSubscriptionOptions {
|
||||
url: string;
|
||||
accessToken?: string;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
/** Validate startup configuration without creating resources or contacting an account. */
|
||||
export function normalizeEventSubscriptionOptions(
|
||||
options: EventSubscriptionOptions,
|
||||
): EventSubscriptionOptions & { timeoutMs: number } {
|
||||
let url: URL;
|
||||
|
||||
try {
|
||||
url = new URL(options.url);
|
||||
} catch {
|
||||
throw new Error('SNOWLUMA_MCP_EVENTS_URL must be an absolute WebSocket URL');
|
||||
}
|
||||
|
||||
if (
|
||||
!['ws:', 'wss:'].includes(url.protocol) ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.hash ||
|
||||
url.search
|
||||
) {
|
||||
throw new Error(
|
||||
'SNOWLUMA_MCP_EVENTS_URL must use ws/wss without credentials, query, or fragment; use SNOWLUMA_MCP_TOKEN for authentication',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
options.timeoutMs !== undefined &&
|
||||
(!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0)
|
||||
) {
|
||||
throw new Error('Event connection timeout must be a positive integer');
|
||||
}
|
||||
|
||||
return { ...options, url: url.href, timeoutMs: options.timeoutMs ?? 30_000 };
|
||||
}
|
||||
|
||||
const idSchema = { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER };
|
||||
const idsSchema = {
|
||||
type: 'array',
|
||||
items: idSchema,
|
||||
minItems: 1,
|
||||
maxItems: MAX_FILTER_IDS,
|
||||
uniqueItems: true,
|
||||
};
|
||||
|
||||
export const EVENT_TOOLS: Tool[] = [
|
||||
{
|
||||
name: 'subscribe_events',
|
||||
description:
|
||||
'订阅指定登录账号的实时 OneBot 事件,返回可读取的资源。消息、通知、请求可按群和用户筛选。只接收创建后的事件;有限缓存溢出和断线会明确标记缺口。通过资源更新通知获知变化,使用 unsubscribe_events 释放资源。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
self_id: {
|
||||
...idSchema,
|
||||
description:
|
||||
'预期登录账号,必须与事件连接的账号相同。可先用 get_login_info 查询。',
|
||||
},
|
||||
types: {
|
||||
type: 'array',
|
||||
items: { type: 'string', enum: ['message', 'notice', 'request'] },
|
||||
minItems: 1,
|
||||
maxItems: 3,
|
||||
uniqueItems: true,
|
||||
},
|
||||
group_ids: idsSchema,
|
||||
user_ids: idsSchema,
|
||||
},
|
||||
required: ['self_id'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
outputSchema: RESULT_SCHEMA,
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
|
||||
},
|
||||
{
|
||||
name: 'unsubscribe_events',
|
||||
description:
|
||||
'停止事件订阅并释放其缓存;最后一个事件订阅结束时断开事件连接。不发送任何 OneBot 业务操作。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { uri: { type: 'string' } },
|
||||
required: ['uri'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
outputSchema: RESULT_SCHEMA,
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
|
||||
},
|
||||
];
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function id(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
function readIds(value: unknown, field: string): Set<number> | undefined {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
value.length === 0 ||
|
||||
value.length > MAX_FILTER_IDS ||
|
||||
!value.every(id) ||
|
||||
new Set(value).size !== value.length
|
||||
) {
|
||||
throw new EventInputError(
|
||||
`${field} must contain 1..${MAX_FILTER_IDS} distinct positive integer IDs`,
|
||||
);
|
||||
}
|
||||
|
||||
return new Set(value);
|
||||
}
|
||||
|
||||
function filter(args: Record<string, unknown>): Filter {
|
||||
if (
|
||||
Object.keys(args).some(
|
||||
(key) => !['self_id', 'types', 'group_ids', 'user_ids'].includes(key),
|
||||
)
|
||||
) {
|
||||
throw new EventInputError('Unexpected event subscription parameter');
|
||||
}
|
||||
|
||||
if (!id(args.self_id)) {
|
||||
throw new EventInputError('self_id must be a positive safe integer');
|
||||
}
|
||||
|
||||
const types = args.types ?? ['message', 'notice', 'request'];
|
||||
|
||||
if (
|
||||
!Array.isArray(types) ||
|
||||
types.length === 0 ||
|
||||
types.length > 3 ||
|
||||
types.some((type) => !['message', 'notice', 'request'].includes(type)) ||
|
||||
new Set(types).size !== types.length
|
||||
) {
|
||||
throw new EventInputError('types must contain distinct message, notice, or request values');
|
||||
}
|
||||
|
||||
return {
|
||||
selfId: args.self_id,
|
||||
types: new Set(types),
|
||||
groupIds: readIds(args.group_ids, 'group_ids'),
|
||||
userIds: readIds(args.user_ids, 'user_ids'),
|
||||
};
|
||||
}
|
||||
|
||||
function eventType(value: unknown): EventType | undefined {
|
||||
if (value === 'message' || value === 'message_sent') {
|
||||
return 'message';
|
||||
}
|
||||
|
||||
if (value === 'notice' || value === 'request') {
|
||||
return value;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function hasSafeDepth(value: Record<string, unknown>): boolean {
|
||||
const pending: Array<{ value: unknown; depth: number }> = [{ value, depth: 0 }];
|
||||
|
||||
while (pending.length > 0) {
|
||||
const entry = pending.pop()!;
|
||||
|
||||
if (entry.value === null || typeof entry.value !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.depth >= 64) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const child of Object.values(entry.value)) {
|
||||
pending.push({ value: child, depth: entry.depth + 1 });
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Private, bounded event resources for one stdio client. Constructing does not connect. */
|
||||
export class EventSubscriptions {
|
||||
private readonly options: EventSubscriptionOptions;
|
||||
private readonly subscriptions = new Map<string, Subscription>();
|
||||
private readonly listeners = new Set<(uri: string) => Promise<void>>();
|
||||
private readonly pendingNotifications = new Set<string>();
|
||||
private notificationTimer?: ReturnType<typeof setTimeout>;
|
||||
private notifying = false;
|
||||
private source?: Source;
|
||||
private closed = false;
|
||||
|
||||
constructor(options: EventSubscriptionOptions) {
|
||||
this.options = normalizeEventSubscriptionOptions(options);
|
||||
}
|
||||
|
||||
handlesTool(name: string): boolean {
|
||||
return EVENT_TOOLS.some((tool) => tool.name === name);
|
||||
}
|
||||
|
||||
async callTool(
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<StructuredResult> {
|
||||
try {
|
||||
if (signal?.aborted) {
|
||||
return asError('事件订阅操作已取消。', 'cancelled');
|
||||
}
|
||||
|
||||
if (name === 'subscribe_events') {
|
||||
const subscription = await this.create(filter(args), signal);
|
||||
return asText(this.snapshot(subscription, undefined));
|
||||
}
|
||||
|
||||
if (name === 'unsubscribe_events') {
|
||||
if (
|
||||
typeof args.uri !== 'string' ||
|
||||
Object.keys(args).some((key) => key !== 'uri')
|
||||
) {
|
||||
throw new EventInputError('unsubscribe_events requires only a resource uri');
|
||||
}
|
||||
|
||||
this.remove(args.uri);
|
||||
return asText({ uri: args.uri, unsubscribed: true });
|
||||
}
|
||||
|
||||
return asError('Unknown event tool', 'not_found');
|
||||
} catch (error) {
|
||||
if (signal?.aborted) {
|
||||
return asError('事件订阅操作已取消。', 'cancelled');
|
||||
}
|
||||
|
||||
if (error instanceof EventInputError) {
|
||||
return asError(error.message, 'invalid_arguments');
|
||||
}
|
||||
|
||||
// Socket errors can contain URLs and server-controlled strings. Keep
|
||||
// those out of both tool diagnostics and stderr.
|
||||
console.error('[snowluma-mcp] event subscription establishment failed');
|
||||
return asError(
|
||||
'事件订阅未建立;检查事件地址、凭据、预期账号及服务端状态。',
|
||||
'transport',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
resources(): Resource[] {
|
||||
return Array.from(this.subscriptions.values(), ({ uri }) => ({
|
||||
uri,
|
||||
name: 'OneBot live events',
|
||||
mimeType: 'application/json',
|
||||
description:
|
||||
'有界实时事件队列。资源 URI 加 ?after=游标 可增量读取;gap=true 表示事件不完整。',
|
||||
}));
|
||||
}
|
||||
|
||||
ownsUri(uri: string): boolean {
|
||||
return uri.startsWith(PREFIX);
|
||||
}
|
||||
|
||||
readResource(uri: string): ReadResourceResult {
|
||||
const { subscription, after } = this.lookup(uri);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri,
|
||||
mimeType: 'application/json',
|
||||
text: JSON.stringify(this.snapshot(subscription, after)),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Legacy unsubscribe and the explicit tool both release the source lease. */
|
||||
remove(uri: string): void {
|
||||
const { subscription, after } = this.lookup(uri);
|
||||
|
||||
if (after !== undefined) {
|
||||
throw new EventInputError('Use the canonical event resource URI to unsubscribe');
|
||||
}
|
||||
|
||||
this.subscriptions.delete(subscription.uri);
|
||||
subscription.cancelPending?.();
|
||||
this.pendingNotifications.delete(subscription.uri);
|
||||
|
||||
if (this.subscriptions.size === 0) {
|
||||
this.stopSource();
|
||||
}
|
||||
}
|
||||
|
||||
onUpdate(listener: (uri: string) => Promise<void>): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.stopSource();
|
||||
this.subscriptions.clear();
|
||||
this.listeners.clear();
|
||||
this.pendingNotifications.clear();
|
||||
clearTimeout(this.notificationTimer);
|
||||
}
|
||||
|
||||
private lookup(uri: string): { subscription: Subscription; after?: number } {
|
||||
const match =
|
||||
/^snowluma:\/\/onebot\/events\/([a-f0-9-]{36})(?:\?after=(0|[1-9]\d*))?$/.exec(uri);
|
||||
|
||||
if (!match) {
|
||||
throw new EventInputError('Invalid event resource URI');
|
||||
}
|
||||
|
||||
const subscription = this.subscriptions.get(`${PREFIX}${match[1]}`);
|
||||
const after = match[2] === undefined ? undefined : Number(match[2]);
|
||||
|
||||
if (!subscription) {
|
||||
throw new EventInputError('Event resource not found or already unsubscribed');
|
||||
}
|
||||
|
||||
if (after !== undefined && (!Number.isSafeInteger(after) || after > subscription.cursor)) {
|
||||
throw new EventInputError('Event cursor is beyond the available stream');
|
||||
}
|
||||
|
||||
return { subscription, after };
|
||||
}
|
||||
|
||||
private snapshot(subscription: Subscription, after: number | undefined) {
|
||||
const oldest = subscription.events[0]?.cursor ?? subscription.cursor + 1;
|
||||
return {
|
||||
uri: subscription.uri,
|
||||
self_id: subscription.filter.selfId,
|
||||
status: subscription.status,
|
||||
...(subscription.problem ? { problem: subscription.problem } : {}),
|
||||
next_cursor: subscription.cursor,
|
||||
oldest_cursor: oldest,
|
||||
dropped_events: subscription.dropped,
|
||||
gap: subscription.status === 'disconnected' || (after ?? 0) < oldest - 1,
|
||||
notification_failed: subscription.notificationFailed,
|
||||
events: subscription.events
|
||||
.filter((entry) => after === undefined || entry.cursor > after)
|
||||
.map(({ cursor, event }) => ({ cursor, event })),
|
||||
};
|
||||
}
|
||||
|
||||
private async create(selected: Filter, signal?: AbortSignal): Promise<Subscription> {
|
||||
if (this.closed) {
|
||||
throw new EventInputError('Event resources are closed');
|
||||
}
|
||||
|
||||
if (this.subscriptions.size >= MAX_SUBSCRIPTIONS) {
|
||||
throw new EventInputError(`At most ${MAX_SUBSCRIPTIONS} event resources may be active`);
|
||||
}
|
||||
|
||||
if (this.source && (this.source.selfId !== selected.selfId || this.source.stopped)) {
|
||||
throw new EventInputError(
|
||||
'Release existing event resources before changing accounts or reconnecting',
|
||||
);
|
||||
}
|
||||
|
||||
const subscription: Subscription = {
|
||||
uri: `${PREFIX}${randomUUID()}`,
|
||||
filter: selected,
|
||||
events: [],
|
||||
bytes: 0,
|
||||
cursor: 0,
|
||||
dropped: 0,
|
||||
status: 'connecting',
|
||||
notificationFailed: false,
|
||||
};
|
||||
this.subscriptions.set(subscription.uri, subscription);
|
||||
let onAbort: (() => void) | undefined;
|
||||
|
||||
try {
|
||||
const source = this.source ?? this.connect(selected.selfId);
|
||||
await Promise.race([
|
||||
source.ready,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
onAbort = () => reject(new Error('Event subscription cancelled'));
|
||||
subscription.cancelPending = onAbort;
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
if (signal?.aborted) {
|
||||
onAbort();
|
||||
}
|
||||
}),
|
||||
]);
|
||||
|
||||
if (
|
||||
source.stopped ||
|
||||
signal?.aborted ||
|
||||
this.subscriptions.get(subscription.uri) !== subscription
|
||||
) {
|
||||
throw new Error('Event connection unavailable');
|
||||
}
|
||||
|
||||
subscription.status = 'connected';
|
||||
return subscription;
|
||||
} catch (error) {
|
||||
this.subscriptions.delete(subscription.uri);
|
||||
this.pendingNotifications.delete(subscription.uri);
|
||||
|
||||
if (this.subscriptions.size === 0) {
|
||||
this.stopSource();
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
subscription.cancelPending = undefined;
|
||||
|
||||
if (onAbort) {
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private connect(selfId: number): Source {
|
||||
let resolve!: () => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const ready = new Promise<void>((accept, fail) => {
|
||||
resolve = accept;
|
||||
reject = fail;
|
||||
});
|
||||
const socket = new WebSocket(this.options.url, {
|
||||
headers: this.options.accessToken
|
||||
? { Authorization: `Bearer ${this.options.accessToken}` }
|
||||
: undefined,
|
||||
maxPayload: MAX_FRAME_BYTES,
|
||||
handshakeTimeout: this.options.timeoutMs,
|
||||
followRedirects: false,
|
||||
perMessageDeflate: false,
|
||||
});
|
||||
const source: Source = {
|
||||
socket,
|
||||
selfId,
|
||||
ready,
|
||||
resolve,
|
||||
reject,
|
||||
verified: false,
|
||||
stopped: false,
|
||||
awaitingPong: false,
|
||||
};
|
||||
this.source = source;
|
||||
source.timer = setTimeout(
|
||||
() => this.failSource(source, 'connection_timeout'),
|
||||
this.options.timeoutMs,
|
||||
);
|
||||
source.timer.unref();
|
||||
socket.on('message', (raw: RawData, binary: boolean) => this.receive(source, raw, binary));
|
||||
socket.on('error', (error: Error & { code?: string }) =>
|
||||
this.failSource(
|
||||
source,
|
||||
error.code === 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
|
||||
? 'frame_too_large'
|
||||
: 'connection_failed',
|
||||
),
|
||||
);
|
||||
socket.on('close', () => this.failSource(source, 'connection_closed'));
|
||||
socket.on('pong', () => {
|
||||
source.awaitingPong = false;
|
||||
});
|
||||
return source;
|
||||
}
|
||||
|
||||
private receive(source: Source, raw: RawData, binary: boolean): void {
|
||||
if (source.stopped || source !== this.source) {
|
||||
return;
|
||||
}
|
||||
|
||||
let event: unknown;
|
||||
let byteLength: number;
|
||||
|
||||
try {
|
||||
if (binary) {
|
||||
throw new Error('Binary event frame');
|
||||
}
|
||||
|
||||
const bytes = Array.isArray(raw)
|
||||
? Buffer.concat(raw)
|
||||
: raw instanceof ArrayBuffer
|
||||
? Buffer.from(raw)
|
||||
: raw;
|
||||
byteLength = bytes.length;
|
||||
event = JSON.parse(bytes.toString('utf8'));
|
||||
} catch {
|
||||
this.failSource(source, 'invalid_event');
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!record(event) ||
|
||||
!id(event.self_id) ||
|
||||
typeof event.post_type !== 'string' ||
|
||||
!hasSafeDepth(event)
|
||||
) {
|
||||
this.failSource(source, 'invalid_event');
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.self_id !== source.selfId) {
|
||||
this.failSource(source, 'account_mismatch');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!source.verified) {
|
||||
source.verified = true;
|
||||
clearTimeout(source.timer);
|
||||
source.heartbeat = setInterval(() => {
|
||||
if (source.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (source.awaitingPong) {
|
||||
this.failSource(source, 'connection_timeout');
|
||||
return;
|
||||
}
|
||||
|
||||
source.awaitingPong = true;
|
||||
source.socket.ping();
|
||||
}, 30_000);
|
||||
source.heartbeat.unref();
|
||||
source.resolve();
|
||||
|
||||
for (const subscription of this.subscriptions.values()) {
|
||||
subscription.status = 'connected';
|
||||
this.updated(subscription.uri);
|
||||
}
|
||||
}
|
||||
|
||||
const type = eventType(event.post_type);
|
||||
|
||||
if (!type) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const subscription of this.subscriptions.values()) {
|
||||
const selected = subscription.filter;
|
||||
|
||||
if (
|
||||
!selected.types.has(type) ||
|
||||
(selected.groupIds &&
|
||||
(!id(event.group_id) || !selected.groupIds.has(event.group_id))) ||
|
||||
(selected.userIds && (!id(event.user_id) || !selected.userIds.has(event.user_id)))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
subscription.events.push({ cursor: ++subscription.cursor, event, bytes: byteLength });
|
||||
subscription.bytes += byteLength;
|
||||
|
||||
while (
|
||||
subscription.events.length > MAX_BUFFER_EVENTS ||
|
||||
subscription.bytes > MAX_BUFFER_BYTES
|
||||
) {
|
||||
const dropped = subscription.events.shift()!;
|
||||
subscription.bytes -= dropped.bytes;
|
||||
subscription.dropped++;
|
||||
}
|
||||
|
||||
this.updated(subscription.uri);
|
||||
}
|
||||
}
|
||||
|
||||
private failSource(source: Source, problem: SourceProblem): void {
|
||||
if (source.stopped) {
|
||||
return;
|
||||
}
|
||||
|
||||
source.stopped = true;
|
||||
clearTimeout(source.timer);
|
||||
clearInterval(source.heartbeat);
|
||||
source.reject(new Error('Event source unavailable'));
|
||||
source.socket.terminate();
|
||||
console.error('[snowluma-mcp] event source stopped: %s', problem);
|
||||
|
||||
for (const subscription of this.subscriptions.values()) {
|
||||
subscription.status = 'disconnected';
|
||||
subscription.problem = problem;
|
||||
this.updated(subscription.uri);
|
||||
}
|
||||
}
|
||||
|
||||
private stopSource(): void {
|
||||
if (!this.source) {
|
||||
return;
|
||||
}
|
||||
|
||||
const source = this.source;
|
||||
source.stopped = true;
|
||||
clearTimeout(source.timer);
|
||||
clearInterval(source.heartbeat);
|
||||
source.reject(new Error('Event source closed'));
|
||||
source.socket.terminate();
|
||||
this.source = undefined;
|
||||
}
|
||||
|
||||
private updated(uri: string): void {
|
||||
this.pendingNotifications.add(uri);
|
||||
|
||||
if (this.notificationTimer || this.notifying || this.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.notificationTimer = setTimeout(() => {
|
||||
this.notificationTimer = undefined;
|
||||
void this.flushNotifications();
|
||||
}, 25);
|
||||
this.notificationTimer.unref();
|
||||
}
|
||||
|
||||
private async flushNotifications(): Promise<void> {
|
||||
this.notifying = true;
|
||||
const uris = Array.from(this.pendingNotifications);
|
||||
this.pendingNotifications.clear();
|
||||
|
||||
try {
|
||||
for (const uri of uris) {
|
||||
if (!this.subscriptions.has(uri)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
await listener(uri);
|
||||
} catch {
|
||||
const subscription = this.subscriptions.get(uri);
|
||||
|
||||
if (subscription) {
|
||||
subscription.notificationFailed = true;
|
||||
}
|
||||
|
||||
console.error('[snowluma-mcp] event resource notification failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.notifying = false;
|
||||
|
||||
if (!this.closed && this.pendingNotifications.size > 0) {
|
||||
this.updated(this.pendingNotifications.values().next().value!);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,956 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { constants } from 'node:fs';
|
||||
import { lstat, mkdir, open, readdir, realpath, rename, unlink } from 'node:fs/promises';
|
||||
import { hostname } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
ProtocolError,
|
||||
ProtocolErrorCode,
|
||||
specTypeSchemas,
|
||||
type CallToolResult,
|
||||
type InputRequests,
|
||||
type InputResponses,
|
||||
type Server,
|
||||
type ServerContext,
|
||||
type StandardSchemaV1,
|
||||
} from '@modelcontextprotocol/server';
|
||||
|
||||
// The 2026 Tasks extension is server-directed and has get/update/cancel,
|
||||
// not the deprecated 2025 tasks/result or tasks/list methods.
|
||||
export const TASK_EXTENSION = 'io.modelcontextprotocol/tasks';
|
||||
export const TASK_CAPABILITIES = { extensions: { [TASK_EXTENSION]: {} } };
|
||||
const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
const MAX_RECORD_BYTES = 16 * 1024 * 1024;
|
||||
const INTERRUPTED = 'Task interrupted; remote outcome is unknown. Work was not replayed.';
|
||||
const CANCELLED = 'Task cancelled; cancellation does not undo remote effects.';
|
||||
const CANCELLATION_REQUESTED = 'Cancellation requested; remote effects may already have occurred.';
|
||||
|
||||
interface TaskBase {
|
||||
taskId: string;
|
||||
createdAt: string;
|
||||
lastUpdatedAt: string;
|
||||
ttlMs: null;
|
||||
pollIntervalMs: number;
|
||||
statusMessage?: string;
|
||||
}
|
||||
|
||||
export type PersistentTask = TaskBase &
|
||||
(
|
||||
| { status: 'working' }
|
||||
| { status: 'input_required'; inputRequests: InputRequests }
|
||||
| { status: 'completed'; result: CallToolResult & { resultType: 'complete' } }
|
||||
| { status: 'failed'; error: { code: number; message: string; data?: unknown } }
|
||||
| { status: 'cancelled' }
|
||||
);
|
||||
|
||||
export type TaskSummary = TaskBase & { status: PersistentTask['status'] };
|
||||
export type TaskHandle = TaskSummary & { resultType: 'task'; content: [] };
|
||||
|
||||
export interface TaskExecutionContext {
|
||||
taskId: string;
|
||||
signal: AbortSignal;
|
||||
requestInput(requests: InputRequests): Promise<InputResponses>;
|
||||
}
|
||||
|
||||
export interface TaskStoreOptions {
|
||||
/** Stable, non-secret digest of the configured account/endpoint and access mode. */
|
||||
scopeId: string;
|
||||
onChange?: (task: PersistentTask) => void | Promise<void>;
|
||||
onError?: (error: Error, context: { event: string; taskId?: string }) => void;
|
||||
maxConcurrent?: number;
|
||||
}
|
||||
|
||||
interface PendingInput {
|
||||
outstanding: InputRequests;
|
||||
responses: InputResponses;
|
||||
resolve: (responses: InputResponses) => void;
|
||||
reject: (error: Error) => void;
|
||||
}
|
||||
|
||||
interface ActiveTask {
|
||||
controller: AbortController;
|
||||
usedInputKeys: Set<string>;
|
||||
input?: PendingInput;
|
||||
}
|
||||
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function supportsTasks(meta?: Readonly<Record<string, unknown>>): boolean {
|
||||
const capabilities = meta?.['io.modelcontextprotocol/clientCapabilities'];
|
||||
|
||||
if (!object(capabilities) || !object(capabilities.extensions)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const extension = capabilities.extensions[TASK_EXTENSION];
|
||||
return object(extension) && Object.keys(extension).length === 0;
|
||||
}
|
||||
|
||||
function requireTasks(ctx: ServerContext, version: string | undefined): void {
|
||||
if (!version || version < '2026-07-28' || !supportsTasks(ctx.mcpReq.envelope)) {
|
||||
throw new ProtocolError(-32021, 'The request must declare the Tasks extension capability', {
|
||||
requiredCapabilities: TASK_CAPABILITIES,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function taskId(value: unknown): string {
|
||||
if (typeof value !== 'string' || !ID.test(value)) {
|
||||
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid task identifier');
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function summary(task: PersistentTask): TaskSummary {
|
||||
const { taskId, status, createdAt, lastUpdatedAt, ttlMs, pollIntervalMs, statusMessage } = task;
|
||||
return {
|
||||
taskId,
|
||||
status,
|
||||
createdAt,
|
||||
lastUpdatedAt,
|
||||
ttlMs,
|
||||
pollIntervalMs,
|
||||
...(statusMessage ? { statusMessage } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function terminal(task: PersistentTask): boolean {
|
||||
return task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled';
|
||||
}
|
||||
|
||||
function errorCode(error: unknown): string | undefined {
|
||||
return object(error) && typeof error.code === 'string' ? error.code : undefined;
|
||||
}
|
||||
|
||||
async function readPrivateJson(file: string): Promise<unknown> {
|
||||
const stat = await lstat(file);
|
||||
|
||||
if (
|
||||
!stat.isFile() ||
|
||||
stat.isSymbolicLink() ||
|
||||
(process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
|
||||
) {
|
||||
throw new Error('Task storage file must be a private regular file');
|
||||
}
|
||||
|
||||
if (stat.size > MAX_RECORD_BYTES) {
|
||||
throw new Error('Task storage record exceeds its size limit');
|
||||
}
|
||||
|
||||
const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
||||
|
||||
try {
|
||||
const contents = await handle.readFile('utf8');
|
||||
|
||||
try {
|
||||
return JSON.parse(contents);
|
||||
} catch {
|
||||
throw new Error('Invalid JSON in task storage');
|
||||
}
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
function validateRecord(value: unknown): PersistentTask {
|
||||
if (!object(value) || value.version !== 1 || !object(value.task)) {
|
||||
throw new Error('Invalid task storage record');
|
||||
}
|
||||
|
||||
const task = value.task;
|
||||
taskId(task.taskId);
|
||||
|
||||
if (
|
||||
typeof task.createdAt !== 'string' ||
|
||||
!Number.isFinite(Date.parse(task.createdAt)) ||
|
||||
typeof task.lastUpdatedAt !== 'string' ||
|
||||
!Number.isFinite(Date.parse(task.lastUpdatedAt)) ||
|
||||
task.ttlMs !== null ||
|
||||
task.pollIntervalMs !== 1000 ||
|
||||
(task.statusMessage !== undefined && typeof task.statusMessage !== 'string')
|
||||
) {
|
||||
throw new Error('Invalid task storage metadata');
|
||||
}
|
||||
|
||||
const base: TaskBase = {
|
||||
taskId: taskId(task.taskId),
|
||||
createdAt: task.createdAt,
|
||||
lastUpdatedAt: task.lastUpdatedAt,
|
||||
ttlMs: null,
|
||||
pollIntervalMs: 1000,
|
||||
...(typeof task.statusMessage === 'string' ? { statusMessage: task.statusMessage } : {}),
|
||||
};
|
||||
|
||||
switch (task.status) {
|
||||
case 'working':
|
||||
return { ...base, status: 'working' };
|
||||
|
||||
case 'input_required': {
|
||||
// In-flight work is never resumed, but corruption must not be hidden.
|
||||
const requests = validateInputRequests(task.inputRequests);
|
||||
return { ...base, status: 'input_required', inputRequests: requests };
|
||||
}
|
||||
|
||||
case 'cancelled':
|
||||
return { ...base, status: 'cancelled' };
|
||||
|
||||
case 'failed': {
|
||||
if (
|
||||
!object(task.error) ||
|
||||
!Number.isSafeInteger(task.error.code) ||
|
||||
typeof task.error.message !== 'string'
|
||||
) {
|
||||
throw new Error('Invalid persisted task error');
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
status: 'failed',
|
||||
error: {
|
||||
code: Number(task.error.code),
|
||||
message: task.error.message,
|
||||
...(task.error.data !== undefined ? { data: task.error.data } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case 'completed': {
|
||||
const validated = specTypeSchemas.CallToolResult['~standard'].validate(task.result);
|
||||
|
||||
if (validated.issues) {
|
||||
throw new Error('Invalid persisted task result');
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
status: 'completed',
|
||||
result: { ...validated.value, resultType: 'complete' },
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error('Unknown persisted task status');
|
||||
}
|
||||
}
|
||||
|
||||
function validateInputRequests(value: unknown): InputRequests {
|
||||
if (!object(value) || Object.keys(value).length === 0) {
|
||||
throw new Error('Task input requests must be a non-empty object');
|
||||
}
|
||||
|
||||
const requests: InputRequests = Object.create(null);
|
||||
|
||||
for (const [key, request] of Object.entries(value)) {
|
||||
if (!object(request)) {
|
||||
throw new Error('Invalid task input request');
|
||||
}
|
||||
|
||||
const schema =
|
||||
request.method === 'elicitation/create'
|
||||
? specTypeSchemas.ElicitRequest
|
||||
: request.method === 'sampling/createMessage'
|
||||
? specTypeSchemas.CreateMessageRequest
|
||||
: request.method === 'roots/list'
|
||||
? specTypeSchemas.ListRootsRequest
|
||||
: undefined;
|
||||
const parsed = schema?.['~standard'].validate(request);
|
||||
|
||||
if (!parsed || parsed.issues) {
|
||||
throw new Error('Invalid task input request');
|
||||
}
|
||||
|
||||
requests[key] = parsed.value;
|
||||
}
|
||||
|
||||
return requests;
|
||||
}
|
||||
|
||||
/** One runtime owns one private directory; callbacks and credentials are never persisted. */
|
||||
export class PersistentTasks {
|
||||
private readonly records = new Map<string, PersistentTask>();
|
||||
private readonly active = new Map<string, ActiveTask>();
|
||||
private queue: Promise<void> = Promise.resolve();
|
||||
private notifications: Promise<void> = Promise.resolve();
|
||||
private closed = false;
|
||||
private closingRequested = false;
|
||||
private leaseReleased = false;
|
||||
private persistenceError?: Error;
|
||||
private constructor(
|
||||
private readonly directory: string,
|
||||
private readonly lease: string,
|
||||
private readonly options: TaskStoreOptions,
|
||||
) {}
|
||||
|
||||
static async open(directory: string, options: TaskStoreOptions): Promise<PersistentTasks> {
|
||||
if (!path.isAbsolute(directory) || !/^[a-f0-9]{64}$/.test(options.scopeId)) {
|
||||
throw new Error(
|
||||
'Task storage requires an absolute directory and a SHA-256 scope identifier',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
options.maxConcurrent !== undefined &&
|
||||
(!Number.isSafeInteger(options.maxConcurrent) || options.maxConcurrent < 1)
|
||||
) {
|
||||
throw new Error('Task concurrency must be a positive integer');
|
||||
}
|
||||
|
||||
await mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
const stat = await lstat(directory);
|
||||
|
||||
if (
|
||||
!stat.isDirectory() ||
|
||||
stat.isSymbolicLink() ||
|
||||
(process.platform !== 'win32' && (stat.mode & 0o077) !== 0)
|
||||
) {
|
||||
throw new Error(
|
||||
'Task storage directory must be private (0700) and cannot be a symlink',
|
||||
);
|
||||
}
|
||||
|
||||
const resolved = await realpath(directory);
|
||||
const lease = `.lease-${randomUUID()}.json`;
|
||||
const store = new PersistentTasks(resolved, lease, options);
|
||||
|
||||
try {
|
||||
await store.save(lease, { pid: process.pid, host: hostname() });
|
||||
|
||||
// Publishing our lease before inspecting peers makes concurrent starts
|
||||
// mutually exclusive. A dead owner's lease is recoverable after a crash.
|
||||
for (const name of await readdir(resolved)) {
|
||||
if (!/^\.lease-[a-f0-9-]+\.json$/.test(name) || name === lease) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let owner: unknown;
|
||||
|
||||
try {
|
||||
owner = await readPrivateJson(path.join(resolved, name));
|
||||
} catch (error) {
|
||||
if (errorCode(error) === 'ENOENT') {
|
||||
continue;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (
|
||||
!object(owner) ||
|
||||
!Number.isSafeInteger(owner.pid) ||
|
||||
Number(owner.pid) <= 0 ||
|
||||
owner.host !== hostname()
|
||||
) {
|
||||
throw new Error('Task storage has an invalid or foreign-host lock');
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(Number(owner.pid), 0);
|
||||
throw new Error('Task storage is locked by another runtime');
|
||||
} catch (error) {
|
||||
if (errorCode(error) !== 'ESRCH') {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
await unlink(path.join(resolved, name)).catch((error: unknown) => {
|
||||
if (errorCode(error) !== 'ENOENT') {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
store.report('recovered_stale_lock');
|
||||
}
|
||||
|
||||
const entries = await readdir(resolved);
|
||||
|
||||
if (entries.includes('scope.json')) {
|
||||
const scope = await readPrivateJson(path.join(resolved, 'scope.json'));
|
||||
|
||||
if (!object(scope) || scope.version !== 1 || scope.scopeId !== options.scopeId) {
|
||||
throw new Error(
|
||||
'Task storage belongs to a different account or permission scope',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (entries.some((name) => name.endsWith('.task.json'))) {
|
||||
throw new Error('Task storage is missing its scope record');
|
||||
}
|
||||
|
||||
await store.save('scope.json', { version: 1, scopeId: options.scopeId });
|
||||
}
|
||||
|
||||
for (const name of entries) {
|
||||
if (!name.endsWith('.task.json')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = taskId(name.slice(0, -10));
|
||||
let task = validateRecord(await readPrivateJson(path.join(resolved, name)));
|
||||
|
||||
if (task.taskId !== id) {
|
||||
throw new Error('Task storage identifier mismatch');
|
||||
}
|
||||
|
||||
if (!terminal(task)) {
|
||||
task = {
|
||||
...summary(task),
|
||||
status: 'failed',
|
||||
lastUpdatedAt: new Date().toISOString(),
|
||||
statusMessage: INTERRUPTED,
|
||||
error: { code: -32603, message: INTERRUPTED },
|
||||
};
|
||||
await store.save(name, { version: 1, task });
|
||||
store.report('interrupted_task_not_replayed', id);
|
||||
}
|
||||
|
||||
store.records.set(id, task);
|
||||
}
|
||||
|
||||
return store;
|
||||
} catch (error) {
|
||||
await unlink(path.join(resolved, lease)).catch((cleanupError: unknown) => {
|
||||
if (errorCode(cleanupError) !== 'ENOENT') {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
'Task startup and lock cleanup failed',
|
||||
);
|
||||
}
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private report(event: string, id?: string): void {
|
||||
const error = new Error(`Task runtime: ${event}`);
|
||||
|
||||
if (this.options.onError) {
|
||||
try {
|
||||
this.options.onError(error, { event, ...(id ? { taskId: id } : {}) });
|
||||
} catch {
|
||||
console.error('[snowluma-mcp] task diagnostic callback failed');
|
||||
}
|
||||
} else {
|
||||
console.error(
|
||||
'[snowluma-mcp] %s',
|
||||
JSON.stringify({ event, ...(id ? { taskId: id } : {}) }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async save(name: string, data: unknown): Promise<void> {
|
||||
const serialized = JSON.stringify(data);
|
||||
|
||||
if (Buffer.byteLength(serialized) > MAX_RECORD_BYTES) {
|
||||
throw new Error('Task record exceeds its size limit');
|
||||
}
|
||||
|
||||
const temporary = path.join(this.directory, `.tmp-${randomUUID()}`);
|
||||
const file = await open(temporary, 'wx', 0o600);
|
||||
|
||||
try {
|
||||
await file.writeFile(serialized);
|
||||
await file.sync();
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
|
||||
await rename(temporary, path.join(this.directory, name));
|
||||
|
||||
// Windows does not support opening directories for fsync.
|
||||
if (process.platform !== 'win32') {
|
||||
const directory = await open(this.directory, 'r');
|
||||
|
||||
try {
|
||||
await directory.sync();
|
||||
} finally {
|
||||
await directory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private serial<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const next = this.queue.then(operation);
|
||||
this.queue = next.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return next;
|
||||
}
|
||||
|
||||
private async put(task: PersistentTask): Promise<void> {
|
||||
try {
|
||||
await this.save(`${task.taskId}.task.json`, { version: 1, task });
|
||||
} catch (error) {
|
||||
this.persistenceError = new Error(
|
||||
'Task persistence failed; stop using this runtime and inspect its storage',
|
||||
{ cause: error },
|
||||
);
|
||||
throw this.persistenceError;
|
||||
}
|
||||
|
||||
this.records.set(task.taskId, task);
|
||||
|
||||
if (this.options.onChange) {
|
||||
const snapshot = structuredClone(task);
|
||||
// Subscription backpressure must not block durable state or cancel.
|
||||
this.notifications = this.notifications
|
||||
.then(() => this.options.onChange?.(snapshot))
|
||||
.catch(() => {
|
||||
this.report('task_notification_failed', task.taskId);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
get(id: string): PersistentTask {
|
||||
if (this.persistenceError) {
|
||||
throw this.persistenceError;
|
||||
}
|
||||
|
||||
const task = this.records.get(taskId(id));
|
||||
|
||||
if (!task) {
|
||||
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Unknown task identifier');
|
||||
}
|
||||
|
||||
return structuredClone(task);
|
||||
}
|
||||
|
||||
list(options: { cursor?: string; limit?: number } = {}): {
|
||||
tasks: TaskSummary[];
|
||||
nextCursor?: string;
|
||||
} {
|
||||
if (this.persistenceError) {
|
||||
throw this.persistenceError;
|
||||
}
|
||||
|
||||
const limit = options.limit ?? 50;
|
||||
|
||||
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) {
|
||||
throw new ProtocolError(
|
||||
ProtocolErrorCode.InvalidParams,
|
||||
'Task page size must be between 1 and 100',
|
||||
);
|
||||
}
|
||||
|
||||
const entries = [...this.records.values()].sort(
|
||||
(a, b) => a.createdAt.localeCompare(b.createdAt) || a.taskId.localeCompare(b.taskId),
|
||||
);
|
||||
const previous =
|
||||
options.cursor === undefined
|
||||
? -1
|
||||
: entries.findIndex((task) => task.taskId === taskId(options.cursor));
|
||||
|
||||
if (options.cursor !== undefined && previous < 0) {
|
||||
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Unknown task cursor');
|
||||
}
|
||||
|
||||
const page = entries.slice(previous + 1, previous + 1 + limit);
|
||||
return {
|
||||
tasks: page.map(summary),
|
||||
...(previous + 1 + page.length < entries.length
|
||||
? { nextCursor: page.at(-1)!.taskId }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
async start(
|
||||
execute: (context: TaskExecutionContext) => Promise<CallToolResult>,
|
||||
): Promise<TaskHandle> {
|
||||
if (this.closingRequested) {
|
||||
throw new Error('Task runtime is closed');
|
||||
}
|
||||
|
||||
const task = await this.serial(async () => {
|
||||
if (this.closed) {
|
||||
throw new Error('Task runtime is closed');
|
||||
}
|
||||
|
||||
if (this.persistenceError) {
|
||||
throw this.persistenceError;
|
||||
}
|
||||
|
||||
if (this.active.size >= (this.options.maxConcurrent ?? 4)) {
|
||||
throw new Error('Task concurrency limit reached');
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const task: PersistentTask = {
|
||||
taskId: randomUUID(),
|
||||
status: 'working',
|
||||
createdAt: now,
|
||||
lastUpdatedAt: now,
|
||||
ttlMs: null,
|
||||
pollIntervalMs: 1000,
|
||||
};
|
||||
await this.put(task);
|
||||
this.active.set(task.taskId, {
|
||||
controller: new AbortController(),
|
||||
usedInputKeys: new Set(),
|
||||
});
|
||||
return task;
|
||||
});
|
||||
// Persist the handle before starting a callback that can have side effects.
|
||||
void this.run(task.taskId, execute);
|
||||
return { ...summary(task), resultType: 'task', content: [] };
|
||||
}
|
||||
|
||||
private async run(
|
||||
id: string,
|
||||
execute: (context: TaskExecutionContext) => Promise<CallToolResult>,
|
||||
): Promise<void> {
|
||||
// close() owns pending records too; keep them registered until it has
|
||||
// durably marked their outcome instead of dropping them in finally.
|
||||
if (this.closingRequested) {
|
||||
return;
|
||||
}
|
||||
|
||||
const active = this.active.get(id)!;
|
||||
|
||||
try {
|
||||
if (this.persistenceError) {
|
||||
throw this.persistenceError;
|
||||
}
|
||||
|
||||
if (active.controller.signal.aborted) {
|
||||
throw active.controller.signal.reason;
|
||||
}
|
||||
|
||||
const result = await execute({
|
||||
taskId: id,
|
||||
signal: active.controller.signal,
|
||||
requestInput: (requests) => this.requestInput(id, requests),
|
||||
});
|
||||
const validated = specTypeSchemas.CallToolResult['~standard'].validate(result);
|
||||
|
||||
if (validated.issues) {
|
||||
throw new Error('Invalid task execution result');
|
||||
}
|
||||
|
||||
await this.serial(async () => {
|
||||
if (this.closed || terminal(this.get(id))) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A successful late completion can win a cooperative cancellation.
|
||||
await this.put({
|
||||
...summary(this.get(id)),
|
||||
status: 'completed',
|
||||
statusMessage: undefined,
|
||||
lastUpdatedAt: new Date().toISOString(),
|
||||
result: { ...validated.value, resultType: 'complete' },
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
try {
|
||||
await this.serial(async () => {
|
||||
if (this.closed || terminal(this.get(id))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const base = {
|
||||
...summary(this.get(id)),
|
||||
lastUpdatedAt: new Date().toISOString(),
|
||||
};
|
||||
await this.put(
|
||||
active.controller.signal.aborted
|
||||
? { ...base, status: 'cancelled', statusMessage: CANCELLED }
|
||||
: {
|
||||
...base,
|
||||
status: 'failed',
|
||||
statusMessage:
|
||||
'Task execution failed; check the correlated call diagnostics.',
|
||||
error: {
|
||||
code: error instanceof ProtocolError ? error.code : -32603,
|
||||
message:
|
||||
error instanceof ProtocolError
|
||||
? error.message
|
||||
: 'Task execution failed; remote outcome may be unknown.',
|
||||
...(error instanceof ProtocolError && error.data !== undefined
|
||||
? { data: error.data }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
} catch {
|
||||
this.report('task_persistence_failed', id);
|
||||
}
|
||||
|
||||
if (!active.controller.signal.aborted) {
|
||||
this.report('task_execution_failed', id);
|
||||
}
|
||||
} finally {
|
||||
active.input?.reject(new Error('Task execution ended'));
|
||||
this.active.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
private async requestInput(id: string, requests: InputRequests): Promise<InputResponses> {
|
||||
const validated = validateInputRequests(requests);
|
||||
const pending = await this.serial(async () => {
|
||||
const active = this.active.get(id);
|
||||
|
||||
if (
|
||||
!active ||
|
||||
active.controller.signal.aborted ||
|
||||
this.closed ||
|
||||
terminal(this.get(id))
|
||||
) {
|
||||
throw new Error(CANCELLED);
|
||||
}
|
||||
|
||||
if (active.input) {
|
||||
throw new Error('Task already has pending input');
|
||||
}
|
||||
|
||||
if (Object.keys(validated).some((key) => active.usedInputKeys.has(key))) {
|
||||
throw new Error('Task input keys must be unique for its entire lifetime');
|
||||
}
|
||||
|
||||
await this.put({
|
||||
...summary(this.get(id)),
|
||||
status: 'input_required',
|
||||
lastUpdatedAt: new Date().toISOString(),
|
||||
inputRequests: validated,
|
||||
});
|
||||
let resolve!: (responses: InputResponses) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<InputResponses>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
active.input = {
|
||||
outstanding: validated,
|
||||
responses: Object.create(null),
|
||||
resolve,
|
||||
reject,
|
||||
};
|
||||
|
||||
for (const key of Object.keys(validated)) {
|
||||
active.usedInputKeys.add(key);
|
||||
}
|
||||
|
||||
return { promise };
|
||||
});
|
||||
return pending.promise;
|
||||
}
|
||||
|
||||
async update(id: string, responses: unknown): Promise<void> {
|
||||
if (!object(responses)) {
|
||||
throw new ProtocolError(
|
||||
ProtocolErrorCode.InvalidParams,
|
||||
'Input responses must be an object',
|
||||
);
|
||||
}
|
||||
|
||||
await this.serial(async () => {
|
||||
if (this.closed) {
|
||||
throw new Error('Task runtime is closed');
|
||||
}
|
||||
|
||||
const task = this.get(id);
|
||||
const active = this.active.get(id);
|
||||
const pending = active?.input;
|
||||
|
||||
if (task.status !== 'input_required' || !pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
const accepted: InputResponses = Object.create(null);
|
||||
|
||||
for (const [key, response] of Object.entries(responses)) {
|
||||
if (!Object.hasOwn(pending.outstanding, key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const request = pending.outstanding[key];
|
||||
|
||||
if (!request) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const schema =
|
||||
request.method === 'elicitation/create'
|
||||
? specTypeSchemas.ElicitResult
|
||||
: request.method === 'sampling/createMessage'
|
||||
? specTypeSchemas.CreateMessageResult
|
||||
: specTypeSchemas.ListRootsResult;
|
||||
const parsed = schema['~standard'].validate(response);
|
||||
|
||||
if (parsed.issues) {
|
||||
throw new ProtocolError(
|
||||
ProtocolErrorCode.InvalidParams,
|
||||
'Invalid task input response',
|
||||
);
|
||||
}
|
||||
|
||||
accepted[key] = parsed.value;
|
||||
}
|
||||
|
||||
if (Object.keys(accepted).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const outstanding = { ...pending.outstanding };
|
||||
|
||||
for (const key of Object.keys(accepted)) {
|
||||
delete outstanding[key];
|
||||
}
|
||||
|
||||
const done = Object.keys(outstanding).length === 0;
|
||||
await this.put(
|
||||
done
|
||||
? {
|
||||
...summary(task),
|
||||
status: 'working',
|
||||
lastUpdatedAt: new Date().toISOString(),
|
||||
}
|
||||
: {
|
||||
...summary(task),
|
||||
status: 'input_required',
|
||||
lastUpdatedAt: new Date().toISOString(),
|
||||
inputRequests: outstanding,
|
||||
},
|
||||
);
|
||||
Object.assign(pending.responses, accepted);
|
||||
pending.outstanding = outstanding;
|
||||
|
||||
if (done) {
|
||||
active.input = undefined;
|
||||
pending.resolve(pending.responses);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async cancel(id: string): Promise<void> {
|
||||
await this.serial(async () => {
|
||||
if (this.closed) {
|
||||
throw new Error('Task runtime is closed');
|
||||
}
|
||||
|
||||
const task = this.get(id);
|
||||
|
||||
if (terminal(task)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const active = this.active.get(id);
|
||||
|
||||
if (!active) {
|
||||
throw new Error('Task execution is unavailable');
|
||||
}
|
||||
|
||||
await this.put({
|
||||
...task,
|
||||
lastUpdatedAt: new Date().toISOString(),
|
||||
statusMessage: CANCELLATION_REQUESTED,
|
||||
});
|
||||
active.controller.abort(new Error(CANCELLED));
|
||||
active.input?.reject(new Error(CANCELLED));
|
||||
});
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.closingRequested = true;
|
||||
await this.serial(async () => {
|
||||
if (this.leaseReleased) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.closed = true;
|
||||
const activeTasks = [...this.active.entries()];
|
||||
|
||||
// Abort all executions even when persistence has failed. Failed writes
|
||||
// still reject close; a later process will terminate the durable state.
|
||||
for (const [, active] of activeTasks) {
|
||||
active.controller.abort(new Error(INTERRUPTED));
|
||||
active.input?.reject(new Error(INTERRUPTED));
|
||||
}
|
||||
|
||||
let failure: unknown;
|
||||
|
||||
for (const [id] of activeTasks) {
|
||||
const task = this.records.get(id)!;
|
||||
|
||||
try {
|
||||
if (!terminal(task)) {
|
||||
await this.put({
|
||||
...summary(task),
|
||||
status: 'failed',
|
||||
lastUpdatedAt: new Date().toISOString(),
|
||||
statusMessage: INTERRUPTED,
|
||||
error: { code: -32603, message: INTERRUPTED },
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
failure ??= error;
|
||||
}
|
||||
}
|
||||
|
||||
await unlink(path.join(this.directory, this.lease));
|
||||
this.leaseReleased = true;
|
||||
this.active.clear();
|
||||
|
||||
if (failure) {
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const taskParams: StandardSchemaV1<unknown, { taskId: string }> = {
|
||||
'~standard': {
|
||||
version: 1 as const,
|
||||
vendor: 'snowluma',
|
||||
validate(value: unknown) {
|
||||
if (!object(value) || typeof value.taskId !== 'string' || !ID.test(value.taskId)) {
|
||||
return { issues: [{ message: 'Invalid task identifier' }] };
|
||||
}
|
||||
|
||||
return { value: { taskId: value.taskId } };
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export function installTaskHandlers(
|
||||
server: Server,
|
||||
tasks: PersistentTasks,
|
||||
options: { authorize?: (ctx: ServerContext) => void } = {},
|
||||
): void {
|
||||
const authorize = (ctx: ServerContext) => {
|
||||
requireTasks(ctx, server.getNegotiatedProtocolVersion());
|
||||
options.authorize?.(ctx);
|
||||
};
|
||||
|
||||
server.registerCapabilities(TASK_CAPABILITIES);
|
||||
server.setRequestHandler('tasks/get', { params: taskParams }, (params, ctx) => {
|
||||
authorize(ctx);
|
||||
return { ...tasks.get(params.taskId) };
|
||||
});
|
||||
server.setRequestHandler('tasks/cancel', { params: taskParams }, async (params, ctx) => {
|
||||
authorize(ctx);
|
||||
await tasks.cancel(params.taskId);
|
||||
return {};
|
||||
});
|
||||
server.setRequestHandler('tasks/update', { params: taskParams }, async (params, ctx) => {
|
||||
authorize(ctx);
|
||||
const task = tasks.get(params.taskId);
|
||||
const invalidOutstanding =
|
||||
task.status === 'input_required' &&
|
||||
ctx.mcpReq.droppedInputResponseKeys?.some((key) =>
|
||||
Object.hasOwn(task.inputRequests, key),
|
||||
);
|
||||
|
||||
if (!ctx.mcpReq.inputResponses || invalidOutstanding) {
|
||||
throw new ProtocolError(
|
||||
ProtocolErrorCode.InvalidParams,
|
||||
'Invalid task input responses',
|
||||
);
|
||||
}
|
||||
|
||||
await tasks.update(params.taskId, ctx.mcpReq.inputResponses);
|
||||
return {};
|
||||
});
|
||||
}
|
||||
@@ -8,10 +8,11 @@
|
||||
// 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 { Tool } from '@modelcontextprotocol/sdk/types.js';
|
||||
import type { Tool } from '@modelcontextprotocol/server';
|
||||
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
|
||||
import type { CatalogAction } from './types.js';
|
||||
import type { ActionClient } from './client.js';
|
||||
import { MCP_UPLOAD_OWNED_FIELDS } from './client.js';
|
||||
import { discover, FILTER_PROPERTIES } from './discovery.js';
|
||||
import {
|
||||
asText,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
} from './results.js';
|
||||
import { VERSION } from './version.js';
|
||||
import type { TransferProgress } from './client.js';
|
||||
import type { TraceContext } from './tracing.js';
|
||||
|
||||
export type Mode = 'docs' | 'read' | 'write';
|
||||
|
||||
@@ -186,6 +188,7 @@ export interface CallCtx {
|
||||
mode: Mode;
|
||||
client?: ActionClient;
|
||||
signal?: AbortSignal;
|
||||
trace?: TraceContext;
|
||||
onProgress?: (progress: TransferProgress) => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -232,13 +235,21 @@ export async function callTool(
|
||||
}
|
||||
}
|
||||
|
||||
/** Shared execution path for query_action (read) / invoke_action (write).
|
||||
* Re-checks mode + readOnly routing regardless of which tools were listed. */
|
||||
async function execute(
|
||||
export interface PreparedActionCall {
|
||||
action: string;
|
||||
params: Record<string, unknown>;
|
||||
inputFile?: string;
|
||||
catalog: CatalogAction;
|
||||
client: ActionClient;
|
||||
inputSchema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** The same side-effect-free gate is used before execution and input collection. */
|
||||
export function prepareActionCall(
|
||||
args: Record<string, unknown>,
|
||||
ctx: CallCtx,
|
||||
kind: 'read' | 'write',
|
||||
): Promise<ToolResult> {
|
||||
): PreparedActionCall | ToolResult {
|
||||
if (kind === 'write' && ctx.mode !== 'write') {
|
||||
return asError(
|
||||
'写操作未启用:需设置 SNOWLUMA_MCP_MODE=write。',
|
||||
@@ -321,22 +332,54 @@ async function execute(
|
||||
return asError('execution.input_file 仅可用于 upload_file_stream。');
|
||||
}
|
||||
|
||||
const inputSchema =
|
||||
inputFile && Array.isArray(cat.inputSchema.required)
|
||||
? {
|
||||
...cat.inputSchema,
|
||||
required: cat.inputSchema.required.filter(
|
||||
(key) => !MCP_UPLOAD_OWNED_FIELDS.includes(key),
|
||||
),
|
||||
}
|
||||
: cat.inputSchema;
|
||||
return { action, params, inputFile, catalog: cat, client: ctx.client, inputSchema };
|
||||
}
|
||||
|
||||
/** Shared execution path for query_action (read) / invoke_action (write). */
|
||||
async function execute(
|
||||
args: Record<string, unknown>,
|
||||
ctx: CallCtx,
|
||||
kind: 'read' | 'write',
|
||||
): Promise<ToolResult> {
|
||||
const prepared = prepareActionCall(args, ctx, kind);
|
||||
|
||||
if ('structuredContent' in prepared) {
|
||||
return prepared;
|
||||
}
|
||||
|
||||
const { action, params, inputFile, catalog: cat, client } = prepared;
|
||||
|
||||
try {
|
||||
ctx.signal?.throwIfAborted();
|
||||
|
||||
if (cat.stream) {
|
||||
const result = await ctx.client.callStream(action, params, {
|
||||
const result = await client.callStream(action, params, {
|
||||
...(inputFile ? { inputFile } : {}),
|
||||
...(ctx.signal ? { signal: ctx.signal } : {}),
|
||||
...(ctx.trace ? { trace: ctx.trace } : {}),
|
||||
...(ctx.onProgress ? { onProgress: ctx.onProgress } : {}),
|
||||
});
|
||||
return asText(result, envelopeDiagnostics(result.terminal));
|
||||
}
|
||||
|
||||
const result = await ctx.client.call(
|
||||
const result = await client.call(
|
||||
action,
|
||||
params,
|
||||
ctx.signal ? { signal: ctx.signal } : undefined,
|
||||
ctx.signal || ctx.trace
|
||||
? {
|
||||
...(ctx.signal ? { signal: ctx.signal } : {}),
|
||||
...(ctx.trace ? { trace: ctx.trace } : {}),
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
return asText(result, envelopeDiagnostics(result));
|
||||
} catch (err) {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
|
||||
export interface TraceContext {
|
||||
traceparent: string;
|
||||
tracestate?: string;
|
||||
}
|
||||
|
||||
function parentFields(value: unknown): { traceId: string; flags: string } | undefined {
|
||||
if (typeof value !== 'string' || /[^\x21-\x7e]/.test(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const match = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(.*)$/.exec(value);
|
||||
|
||||
if (
|
||||
!match ||
|
||||
match[1] === 'ff' ||
|
||||
/^0+$/.test(match[2]!) ||
|
||||
/^0+$/.test(match[3]!) ||
|
||||
(match[1] === '00' ? match[5] !== '' : match[5] !== '' && !match[5]!.startsWith('-'))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Participate using version 00, retaining only its defined sampled flag.
|
||||
return { traceId: match[2]!, flags: (Number.parseInt(match[4]!, 16) & 1) === 1 ? '01' : '00' };
|
||||
}
|
||||
|
||||
function traceState(value: unknown): string | undefined {
|
||||
if (typeof value !== 'string' || value.length > 512 || /[^\x20-\x7e\t]/.test(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const members = value.split(',');
|
||||
|
||||
if (members.length > 32) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const keys = new Set<string>();
|
||||
const normalized: string[] = [];
|
||||
|
||||
for (const raw of members) {
|
||||
const member = raw.replace(/^[ \t]+|[ \t]+$/g, '');
|
||||
|
||||
if (!member) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separator = member.indexOf('=');
|
||||
const key = member.slice(0, separator);
|
||||
const entry = member.slice(separator + 1);
|
||||
|
||||
if (
|
||||
separator < 1 ||
|
||||
!/^(?:[a-z][a-z0-9_*/-]{0,255}|[a-z0-9][a-z0-9_*/-]{0,240}@[a-z][a-z0-9_*/-]{0,13})$/.test(
|
||||
key,
|
||||
) ||
|
||||
!/^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/.test(entry) ||
|
||||
keys.has(key)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
keys.add(key);
|
||||
normalized.push(member);
|
||||
}
|
||||
|
||||
return normalized.join(',');
|
||||
}
|
||||
|
||||
function identifier(bytes: number): string {
|
||||
let value: string;
|
||||
|
||||
do {
|
||||
value = randomBytes(bytes).toString('hex');
|
||||
} while (/^0+$/.test(value));
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Trace metadata is advisory: invalid fields never reject a tool or enter its params. */
|
||||
export function createCallTrace(meta?: Record<string, unknown>): TraceContext {
|
||||
const parent = parentFields(meta?.traceparent);
|
||||
|
||||
if (meta?.traceparent !== undefined && !parent) {
|
||||
console.error('[snowluma-mcp] trace metadata ignored: invalid traceparent');
|
||||
}
|
||||
|
||||
let state: string | undefined;
|
||||
|
||||
if (meta?.tracestate !== undefined) {
|
||||
if (parent) {
|
||||
state = traceState(meta.tracestate);
|
||||
|
||||
if (state === undefined) {
|
||||
console.error('[snowluma-mcp] trace metadata ignored: invalid tracestate');
|
||||
}
|
||||
} else {
|
||||
console.error(
|
||||
'[snowluma-mcp] trace metadata ignored: tracestate without valid traceparent',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
traceparent: `00-${parent?.traceId ?? identifier(16)}-${identifier(8)}-${parent?.flags ?? '00'}`,
|
||||
...(state ? { tracestate: state } : {}),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user