feat(mcp): complete action results and invocation examples
Document result shapes and practical calls for all built-in actions, including prerequisites, streaming workflows and compatibility limits. Preserve existing interfaces and execution behavior, and verify the catalog against action validation and representative responses.
This commit is contained in:
27 files changed
+14140
-33
No files matched your search
@@ -5,6 +5,48 @@ and read/write gates. No endpoint is contacted by catalog tools or by a local
|
||||
runtime overview. The action catalog remains a bundled snapshot, not a claim
|
||||
about the connected server's capabilities.
|
||||
|
||||
## Action result schemas and examples
|
||||
|
||||
`get_action` and `snowluma://onebot/actions` include `returnsSchema` and
|
||||
`examples` for every bundled action, including aliases. Both are authored beside
|
||||
the OneBot action definition and copied into the generated catalog. List/search
|
||||
responses remain compact; use `get_action` to retrieve the complete contract.
|
||||
|
||||
`returnsSchema` describes successful OneBot **`data`**, not the full OneBot
|
||||
envelope or the MCP `structuredContent` wrapper. Check `status` and `retcode`
|
||||
before reading it. For stream actions, the schema describes each successful
|
||||
frame's `data`; MCP downloads instead return saved-file metadata and generic
|
||||
streams return a frame collection. Error frames and failed envelopes are not
|
||||
successful results. Unsupported actions use `{ "not": {} }` because they have no
|
||||
successful result. Compatibility placeholders explicitly document their limits.
|
||||
|
||||
Each example has `summary`, `params`, and optional `notes` explaining prerequisites
|
||||
and identifier sources. These are illustrative calls, never run by catalog tools.
|
||||
Replace example account/group IDs, opaque handles and paths with values from the
|
||||
current account before execution. Notes identify operations with multiple steps,
|
||||
such as completing an upload after all chunks have been acknowledged.
|
||||
|
||||
For example, `get_action({ "name": "get_msg" })` documents signed message IDs:
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "get_msg",
|
||||
"params": { "message_id": -123456 }
|
||||
}
|
||||
```
|
||||
|
||||
Pass this object to `query_action` with a real message ID. Writes and streams use
|
||||
`invoke_action` in write mode. For automatic upload, pass
|
||||
`{ "action": "upload_file_stream", "execution": { "input_file": "/allowed/hello.txt" } }`
|
||||
to `invoke_action`, with a real file inside the configured upload root. Ordinary
|
||||
action paths refer to the SnowLuma server, whereas `execution.input_file` and MCP
|
||||
download paths refer to the MCP host.
|
||||
|
||||
Do not substitute zero for a signed message ID. Resource-only forward uploads
|
||||
and flash shares have a documented `message_id: 0` sentinel; it cannot be used
|
||||
for message lookup or recall. Also preserve `null` versus `{}`, optional fields,
|
||||
and decimal strings such as media `file_size` exactly as documented.
|
||||
|
||||
## Structured results
|
||||
|
||||
Every tool advertises an `outputSchema` and returns `structuredContent` alongside
|
||||
|
||||
@@ -18,6 +18,8 @@ it('generates src/generated/catalog.ts from the live action specs', () => {
|
||||
for (const a of actions) {
|
||||
expect(a.inputSchema).toBeTypeOf('object');
|
||||
expect(a.name).toBeTruthy();
|
||||
expect(a.returnsSchema, `${a.name} result schema`).toBeTypeOf('object');
|
||||
expect(a.examples?.length, `${a.name} invocation examples`).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
const body =
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -66,7 +66,8 @@ const DOCS_TOOLS: Tool[] = [
|
||||
},
|
||||
{
|
||||
name: 'get_action',
|
||||
description: '获取 action 文档、参数 JSON Schema、约束和返回类型。',
|
||||
description:
|
||||
'获取 action 文档、参数与返回数据 JSON Schema、约束和调用示例。示例中的标识和路径需替换;流式返回结构描述单帧数据。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { name: { type: 'string', description: 'action 名(接受别名)' } },
|
||||
|
||||
@@ -26,8 +26,15 @@ export interface CatalogAction {
|
||||
category?: string;
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
/** JSON Schema for the action's `data` payload (absent when undocumented). */
|
||||
/** Successful OneBot `data`, or one successful stream frame's `data`.
|
||||
* Does not describe the envelope or MCP's aggregated stream result. */
|
||||
returnsSchema?: Record<string, unknown>;
|
||||
/** Illustrative OneBot params; identifiers/paths must be replaced before use. */
|
||||
examples?: ReadonlyArray<{
|
||||
summary: string;
|
||||
params: Record<string, unknown>;
|
||||
notes?: string;
|
||||
}>;
|
||||
/** True only for pure data-fetch actions (no side effects). Drives the
|
||||
* read/write tool routing: read-only → query_action, else → invoke_action.
|
||||
* Classified at the source spec by what the action's `run` actually does. */
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv-provider.js';
|
||||
import { collectActionDocs } from '@snowluma/onebot/action-docs';
|
||||
import { ApiHandler, type ApiActionContext } from '@snowluma/onebot/api-handler';
|
||||
import type { JsonObject, JsonValue } from '@snowluma/onebot/types';
|
||||
import { ACTIONS } from '../src/generated/catalog';
|
||||
import { callTool } from '../src/tools';
|
||||
|
||||
const validator = new AjvJsonSchemaValidator();
|
||||
|
||||
function resultValidator(name: string) {
|
||||
const action = ACTIONS.find((entry) => entry.name === name);
|
||||
|
||||
if (!action?.returnsSchema) {
|
||||
throw new Error(`missing result schema: ${name}`);
|
||||
}
|
||||
|
||||
return validator.getValidator(action.returnsSchema);
|
||||
}
|
||||
|
||||
function matchesResult(name: string, data: unknown): void {
|
||||
const result = resultValidator(name)(data);
|
||||
expect(result.valid, `${name}: ${result.errorMessage}`).toBe(true);
|
||||
}
|
||||
|
||||
/** Unexpected dependencies fail rather than contacting an account or a network. */
|
||||
function context(values: Record<string, unknown> = {}): ApiActionContext {
|
||||
return new Proxy(values, {
|
||||
get(target, key) {
|
||||
if (typeof key === 'string' && Object.hasOwn(target, key)) {
|
||||
return target[key];
|
||||
}
|
||||
|
||||
throw new Error(`unstubbed action context: ${String(key)}`);
|
||||
},
|
||||
}) as unknown as ApiActionContext;
|
||||
}
|
||||
|
||||
describe('bundled action contracts', () => {
|
||||
it('matches the owning specs, without relying on a second hand-authored registry', () => {
|
||||
expect(ACTIONS).toEqual(JSON.parse(JSON.stringify(collectActionDocs())));
|
||||
});
|
||||
|
||||
it.each(ACTIONS)('$name publishes compilable schemas and schema-valid examples', (action) => {
|
||||
expect(() => resultValidator(action.name)).not.toThrow();
|
||||
const validateInput = validator.getValidator(action.inputSchema);
|
||||
expect(action.examples?.length).toBeGreaterThan(0);
|
||||
|
||||
for (const example of action.examples ?? []) {
|
||||
const result = validateInput(example.params);
|
||||
expect(result.valid, `${action.name}: ${result.errorMessage}`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('exposes full contracts through get_action and aliases without executing anything', async () => {
|
||||
const client = { call: vi.fn(), callStream: vi.fn() };
|
||||
|
||||
for (const action of ACTIONS) {
|
||||
for (const name of [action.name, ...action.aliases]) {
|
||||
const result = await callTool('get_action', { name }, { mode: 'docs', client });
|
||||
expect(result.structuredContent.result).toEqual(action);
|
||||
expect(result.content[0]).toEqual({
|
||||
type: 'text',
|
||||
text: JSON.stringify(action, null, 2),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
expect(client.call).not.toHaveBeenCalled();
|
||||
expect(client.callStream).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['list_actions', 'search_actions'])('keeps %s compact', async (name) => {
|
||||
const result = await callTool(name, { query: 'send_group_msg' }, { mode: 'docs' });
|
||||
const block = result.content[0];
|
||||
expect(block.type).toBe('text');
|
||||
|
||||
if (block.type !== 'text') {
|
||||
throw new Error('expected text result');
|
||||
}
|
||||
|
||||
const payload = JSON.parse(block.text);
|
||||
expect(payload.actions.length).toBeGreaterThan(0);
|
||||
|
||||
for (const action of payload.actions) {
|
||||
expect(action).not.toHaveProperty('examples');
|
||||
expect(action).not.toHaveProperty('returnsSchema');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('result schemas against actual OneBot handlers', () => {
|
||||
it('preserves signed message IDs and documents the upload-only sentinel separately', async () => {
|
||||
const api = new ApiHandler(
|
||||
context({
|
||||
sendGroupMessage: async () => ({ messageId: -123 }),
|
||||
sendForwardMsg: async () => ({ forwardId: 'example-forward' }),
|
||||
}),
|
||||
);
|
||||
const send = await api.handle('send_group_msg', { group_id: 20001, message: 'hello' });
|
||||
expect(send).toEqual({ status: 'ok', retcode: 0, data: { message_id: -123 } });
|
||||
matchesResult('send_group_msg', send.data);
|
||||
expect(resultValidator('send_group_msg')({ message_id: 0 }).valid).toBe(false);
|
||||
|
||||
for (const name of ['upload_forward_msg', 'upload_foward_msg']) {
|
||||
const uploaded = await api.handle(name, {
|
||||
group_id: 20001,
|
||||
messages: [
|
||||
{
|
||||
type: 'node',
|
||||
data: { user_id: 10001, nickname: 'example', content: 'hello' },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(uploaded.status).toBe('ok');
|
||||
expect(uploaded.data).toMatchObject({ message_id: 0, res_id: 'example-forward' });
|
||||
matchesResult(name, uploaded.data);
|
||||
|
||||
if (name === 'upload_forward_msg') {
|
||||
expect(uploaded.data).toHaveProperty('group_id', 20001);
|
||||
} else {
|
||||
expect(uploaded.data).not.toHaveProperty('group_id');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('distinguishes null, empty objects, and failed unsupported calls', async () => {
|
||||
const api = new ApiHandler(
|
||||
context({
|
||||
bridge: {
|
||||
apis: {
|
||||
friend: { setRemark: async () => {} },
|
||||
profile: { setInputStatus: async () => {} },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const empty = await api.handle('set_friend_remark', { user_id: 10001, remark: 'example' });
|
||||
expect(empty.data).toBeNull();
|
||||
matchesResult('set_friend_remark', empty.data);
|
||||
expect(resultValidator('set_friend_remark')({}).valid).toBe(false);
|
||||
const object = await api.handle('set_input_status', { user_id: 10001 });
|
||||
expect(object.data).toEqual({});
|
||||
matchesResult('set_input_status', object.data);
|
||||
expect(resultValidator('set_input_status')(null).valid).toBe(false);
|
||||
|
||||
for (const name of ['set_restart', 'create_collection', '.get_word_slices']) {
|
||||
const failure = await api.handle(name, {});
|
||||
expect(failure.status).toBe('failed');
|
||||
expect(resultValidator(name)(failure.data).valid).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('documents actual media string sizes and optional converted record fields', async () => {
|
||||
const media = {
|
||||
file: 'https://example.com/media',
|
||||
url: 'https://example.com/media',
|
||||
file_size: '42',
|
||||
file_name: 'voice.amr',
|
||||
};
|
||||
const api = new ApiHandler(
|
||||
context({
|
||||
getImageInfo: async () => media,
|
||||
getRecordInfo: async () => media,
|
||||
bridge: {
|
||||
apis: {
|
||||
extras: { convertRecord: async () => ({ base64: 'aGVsbG8=', size: 5 }) },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
for (const name of ['get_image', 'get_file', 'get_record']) {
|
||||
const result = await api.handle(name, { file: 'cached-media' });
|
||||
expect(result.status).toBe('ok');
|
||||
matchesResult(name, result.data);
|
||||
expect(resultValidator(name)({ ...media, file_size: 42 }).valid).toBe(false);
|
||||
}
|
||||
|
||||
const converted = await api.handle('get_record', {
|
||||
file: 'cached-media',
|
||||
out_format: 'mp3',
|
||||
});
|
||||
expect(converted.data).toEqual({ ...media, out_format: 'mp3', base64: 'aGVsbG8=' });
|
||||
matchesResult('get_record', converted.data);
|
||||
});
|
||||
|
||||
it('describes get_msg data without the event envelope for both conversation types', async () => {
|
||||
for (const messageType of ['group', 'private']) {
|
||||
const event: JsonObject = {
|
||||
post_type: 'message',
|
||||
self_id: 10002,
|
||||
message_type: messageType,
|
||||
message_id: -123,
|
||||
user_id: 10001,
|
||||
time: 1700000000,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'hello',
|
||||
...(messageType === 'group' ? { group_id: 20001 } : { target_id: 10002 }),
|
||||
};
|
||||
const api = new ApiHandler(
|
||||
context({
|
||||
getMessage: async () => event,
|
||||
refreshMessageMedia: async () => {},
|
||||
}),
|
||||
);
|
||||
const result = await api.handle('get_msg', { message_id: -123 });
|
||||
expect(result.status).toBe('ok');
|
||||
expect(result.data).toMatchObject({ real_id: -123, message_id: -123 });
|
||||
expect(result.data).not.toHaveProperty('post_type');
|
||||
expect(result.data).not.toHaveProperty('self_id');
|
||||
matchesResult('get_msg', result.data);
|
||||
}
|
||||
});
|
||||
|
||||
it('describes successful stream frame data, not MCP aggregate results or failed frames', async () => {
|
||||
const api = new ApiHandler(context());
|
||||
const frames: JsonValue[] = [];
|
||||
const response = await api.handle(
|
||||
'test_download_stream',
|
||||
{ error: false },
|
||||
{
|
||||
send: async (frame) => {
|
||||
frames.push(frame);
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(frames).toHaveLength(10);
|
||||
expect(response.status).toBe('ok');
|
||||
|
||||
for (const frame of [...frames, response.data]) {
|
||||
matchesResult('test_download_stream', frame);
|
||||
}
|
||||
|
||||
expect(
|
||||
resultValidator('test_download_stream')({ frame_count: 11, frames, terminal: response })
|
||||
.valid,
|
||||
).toBe(false);
|
||||
expect(
|
||||
resultValidator('test_download_stream')({ type: 'error', data_type: 'error' }).valid,
|
||||
).toBe(false);
|
||||
const failure = await api.handle('test_download_stream', { error: true });
|
||||
expect(failure.status).toBe('failed');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user