feat(mcp): @snowluma/mcp — read-only MCP server for the OneBot action catalog

A new published package that exposes every OneBot action's docs + a ready-to-use
JSON Schema to LLM clients over stdio. Tools: list_actions / get_action /
search_actions / list_categories, plus the whole catalog as a resource.

The catalog is a build-time snapshot generated from @snowluma/onebot's live
action specs (collectActionDocs()) — so it auto-tracks action add/remove and the
published package carries zero runtime dependency on the private onebot package.

action-kit enrichment (the data source):
- Field.toJsonSchema() per coercer (uint→integer/minimum:1, messageId→integer/
  not-const-0, int→min/max, string→minLength/maxLength, array→items, enum→enum).
- describe() composes a per-action inputSchema; ActionDoc gains inputSchema +
  category. action-docs.ts tags each doc with its domain category.

Wiring: onebot exports ./action-kit + ./action-docs; root build:all includes mcp;
mcp-npm-publish.yml mirrors the sdk/ui publish workflows (triggers on changes
under packages/mcp/** or packages/onebot/**, since the catalog derives from it).

onebot typecheck + 318 tests green; mcp typecheck/build/smoke green; the 142
registered OneBot action names are unchanged.
This commit is contained in:
DrSmoothl committed 2026-06-02 22:45:30 +08:00
1 parent fc21d87a9b
commit 69c8960ea9
16 files changed
+7012 -33

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
name: Publish MCP to npm
on:
push:
branches: [main]
paths:
- 'packages/mcp/**'
# The action catalog is generated from @snowluma/onebot's specs, so an
# action change must republish the MCP snapshot.
- 'packages/onebot/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'pnpm-workspace.yaml'
- 'tsconfig.base.json'
workflow_dispatch:
permissions:
contents: read
id-token: write
concurrency:
group: mcp-npm-publish-${{ github.ref }}
cancel-in-progress: false
jobs:
publish:
name: Build, test, and publish MCP
runs-on: ubuntu-latest
environment: SnowLuma
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
with:
version: 10.28.0
run_install: false
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Type check MCP
run: pnpm --filter @snowluma/mcp typecheck
- name: Test MCP (regenerates + validates the action catalog)
run: pnpm --filter @snowluma/mcp test
- name: Build MCP
run: pnpm --filter @snowluma/mcp build
- name: Check npm package version
id: npm
working-directory: packages/mcp
shell: bash
run: |
set -euo pipefail
package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")"
package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")"
{
echo "package_name=${package_name}"
echo "package_version=${package_version}"
} >> "${GITHUB_OUTPUT}"
if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then
echo "already_published=true" >> "${GITHUB_OUTPUT}"
echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish."
else
echo "already_published=false" >> "${GITHUB_OUTPUT}"
fi
- name: Validate npm token
if: steps.npm.outputs.already_published != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "${NODE_AUTH_TOKEN}" ]; then
echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2
exit 1
fi
- name: Publish MCP to npm
if: steps.npm.outputs.already_published != 'true'
working-directory: packages/mcp
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public --provenance
- name: Summary
shell: bash
run: |
{
echo "## MCP npm publish"
echo
echo "| Key | Value |"
echo "| --- | --- |"
echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |"
echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |"
echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |"
echo "| Environment | \`SnowLuma\` |"
} >> "${GITHUB_STEP_SUMMARY}"
+2 -1
View File
@@ -8,7 +8,8 @@
"build": "pnpm --filter @snowluma/core build",
"build:sdk": "pnpm --filter @snowluma/sdk build",
"build:webui": "pnpm --filter webui build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter webui build",
"build:mcp": "pnpm --filter @snowluma/mcp build",
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter webui build",
"dev": "pnpm --filter @snowluma/core dev",
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
"dev:web": "pnpm --filter webui dev",
+1
View File
@@ -0,0 +1 @@
dist/
+40
View File
@@ -0,0 +1,40 @@
# @snowluma/mcp
A read-only [MCP](https://modelcontextprotocol.io) server that exposes the
**SnowLuma OneBot action catalog** — every action's docs, parameters, cross-field
constraints, and a ready-to-use **JSON Schema** — to LLM clients.
Point an LLM at it and it can answer "what params does `set_group_ban` take?" or
"which actions send messages?" on demand, without holding the whole catalog in
context.
## Usage
Add to your MCP client (Claude Desktop, Cline, …):
```json
{
"mcpServers": {
"snowluma": { "command": "npx", "args": ["-y", "@snowluma/mcp"] }
}
}
```
## Tools
- `list_actions({ category? })` — lightweight index (name / category / summary / aliases).
- `get_action({ name })` — full doc for one action incl. `inputSchema` (accepts aliases).
- `search_actions({ query })` — fuzzy match over name / summary / aliases.
- `list_categories()` — categories and their action counts.
Also exposes the whole catalog as a resource: `snowluma://onebot/actions`.
## How it stays in sync
The catalog is a **build-time snapshot** generated from `@snowluma/onebot`'s live
action specs (`collectActionDocs()`) on every build — so it auto-tracks action
add/remove and the published package carries **zero runtime dependency** on the
private `@snowluma/onebot`. The snapshot is pinned to the SnowLuma version it was
built from; a new SnowLuma release republishes a fresh catalog.
This package is generated; do not hand-edit `src/generated/catalog.ts`.
+49
View File
@@ -0,0 +1,49 @@
{
"name": "@snowluma/mcp",
"version": "1.9.4",
"description": "MCP server exposing the SnowLuma OneBot action catalog (read-only docs + JSON Schemas) to LLM clients.",
"type": "module",
"bin": {
"snowluma-mcp": "./dist/server.js"
},
"main": "./dist/server.js",
"types": "./dist/server.d.ts",
"files": [
"dist",
"README.md"
],
"scripts": {
"clean": "node -e \"const fs=require('node:fs');fs.rmSync('dist',{recursive:true,force:true})\"",
"gen": "vitest run scripts/gen-catalog.test.ts",
"prebuild": "pnpm run clean && pnpm run gen",
"build": "tsc -p tsconfig.json",
"prepack": "pnpm run build",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"start": "node dist/server.js"
},
"keywords": [
"mcp",
"model-context-protocol",
"onebot",
"snowluma",
"qq"
],
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0"
},
"devDependencies": {
"@snowluma/onebot": "workspace:*",
"@snowluma/proton": "workspace:*",
"@types/node": "^24.12.2",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
},
"engines": {
"node": ">=22"
},
"publishConfig": {
"access": "public"
}
}
+32
View File
@@ -0,0 +1,32 @@
// Catalog generator. Runs under vitest (so @snowluma/onebot/action-docs resolves
// via the proton plugin, exactly as onebot's own tests do) and writes a build-time
// snapshot of the OneBot action catalog into src/generated/catalog.ts.
//
// This is the whole "auto-track Action 增减" mechanic: the snapshot is regenerated
// from the live specs on every build, so it can never describe a stale action set.
import { mkdirSync, writeFileSync } from 'node:fs';
import { it, expect } from 'vitest';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
it('generates src/generated/catalog.ts from the live action specs', () => {
const actions = collectActionDocs();
const categories = collectCategories();
expect(actions.length).toBeGreaterThan(100);
// every action must carry a composed input schema (the MCP's payoff)
for (const a of actions) {
expect(a.inputSchema).toBeTypeOf('object');
expect(a.name).toBeTruthy();
}
const body =
'// GENERATED by scripts/gen-catalog.test.ts — do not edit. Run `pnpm gen`.\n' +
'/* eslint-disable */\n' +
"import type { CatalogAction, CatalogCategory } from '../types.js';\n\n" +
`export const ACTIONS: CatalogAction[] = ${JSON.stringify(actions, null, 2)};\n\n` +
`export const CATEGORIES: CatalogCategory[] = ${JSON.stringify(categories, null, 2)};\n`;
const dir = new URL('../src/generated/', import.meta.url);
mkdirSync(dir, { recursive: true });
writeFileSync(new URL('../src/generated/catalog.ts', import.meta.url), body);
});
File diff suppressed because it is too large. Load diff
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env node
// @snowluma/mcp — a read-only MCP server that exposes the SnowLuma OneBot action
// catalog (docs + per-action JSON Schemas) to LLM clients over stdio.
//
// The catalog is a build-time snapshot (src/generated/catalog.ts), regenerated
// from @snowluma/onebot's live action specs on every build — so it auto-tracks
// action add/remove and ships zero runtime dependency on onebot.
//
// NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr.
import { readFileSync } from 'node:fs';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { ACTIONS, CATEGORIES } from './generated/catalog.js';
import type { CatalogAction } from './types.js';
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string };
const VERSION = pkg.version;
const RESOURCE_URI = 'snowluma://onebot/actions';
// name + every alias → the action, so get_action accepts aliases too.
const byName = new Map<string, CatalogAction>();
for (const a of ACTIONS) {
for (const n of [a.name, ...a.aliases]) byName.set(n, a);
}
/** Lightweight index entry (keeps list/search payloads small). */
function lite(a: CatalogAction) {
return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases };
}
const TOOLS = [
{
name: 'list_actions',
description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名)。',
inputSchema: {
type: 'object',
properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } },
additionalProperties: false,
},
},
{
name: 'get_action',
description: '获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。',
inputSchema: {
type: 'object',
properties: { name: { type: 'string', description: 'action 名(接受别名)' } },
required: ['name'],
additionalProperties: false,
},
},
{
name: 'search_actions',
description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。',
inputSchema: {
type: 'object',
properties: { query: { type: 'string', description: '关键字' } },
required: ['query'],
additionalProperties: false,
},
},
{
name: 'list_categories',
description: '列出所有分类及其 action 数量。',
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
},
];
function asText(data: unknown) {
return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
}
function asError(message: string) {
return { content: [{ type: 'text' as const, text: message }], isError: true };
}
const server = new Server(
{ name: 'snowluma-mcp', version: VERSION },
{ capabilities: { tools: {}, resources: {} } },
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
server.setRequestHandler(CallToolRequestSchema, async (req) => {
const name = req.params.name;
const args = (req.params.arguments ?? {}) as Record<string, unknown>;
switch (name) {
case 'list_actions': {
const category = typeof args.category === 'string' ? args.category : undefined;
const list = ACTIONS.filter((a) => !category || a.category === category).map(lite);
return asText({ count: list.length, actions: list });
}
case 'get_action': {
const q = typeof args.name === 'string' ? args.name : '';
const action = byName.get(q);
if (!action) return asError(`未找到 action: ${JSON.stringify(q)}。用 list_actions / search_actions 查可用项。`);
return asText(action);
}
case 'search_actions': {
const q = (typeof args.query === 'string' ? args.query : '').toLowerCase();
const list = ACTIONS.filter(
(a) =>
a.name.toLowerCase().includes(q) ||
(a.summary ?? '').toLowerCase().includes(q) ||
a.aliases.some((al) => al.toLowerCase().includes(q)),
).map(lite);
return asText({ count: list.length, actions: list });
}
case 'list_categories':
return asText(CATEGORIES);
default:
return asError(`未知工具: ${name}`);
}
});
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: [
{
uri: RESOURCE_URI,
name: 'SnowLuma OneBot action catalog',
mimeType: 'application/json',
description: `SnowLuma v${VERSION} 的 ${ACTIONS.length} 个 OneBot action 完整目录(文档 + JSON Schema)。`,
},
],
}));
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
if (req.params.uri !== RESOURCE_URI) throw new Error(`unknown resource: ${req.params.uri}`);
return {
contents: [
{
uri: RESOURCE_URI,
mimeType: 'application/json',
text: JSON.stringify({ version: VERSION, categories: CATEGORIES, actions: ACTIONS }, null, 2),
},
],
};
});
const transport = new StdioServerTransport();
await server.connect(transport);
console.error(`[snowluma-mcp] v${VERSION} ready — ${ACTIONS.length} actions, ${CATEGORIES.length} categories`);
+34
View File
@@ -0,0 +1,34 @@
// The MCP's own view of the OneBot action catalog. Mirrors @snowluma/onebot's
// ActionDoc, but is defined HERE so the published package does not couple to
// onebot's internals — the generated `catalog.ts` (a build-time snapshot) is the
// only contract (ADR-0005: the wire/data shape is the seam, not a shared type).
export interface CatalogParam {
name: string;
/** Display type ('uint' | 'int' | 'messageId' | 'string' | 'bool' | 'message' | 'enum' | 'X[]' | 'raw'). */
type: string;
required: boolean;
default?: unknown;
desc?: string;
values?: ReadonlyArray<string | number>;
/** JSON Schema fragment for this single field. */
schema?: Record<string, unknown>;
}
export interface CatalogAction {
name: string;
aliases: string[];
category?: string;
summary?: string;
returns?: string;
params: CatalogParam[];
/** Cross-field invariants, e.g. "exactly one of: message_id | (group_id+user_id)". */
invariants: string[];
/** Composed JSON Schema for the whole params object. */
inputSchema: Record<string, unknown>;
}
export interface CatalogCategory {
category: string;
count: number;
}
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"noEmit": false,
"types": ["node"]
},
"include": ["src/**/*"]
}
+17
View File
@@ -0,0 +1,17 @@
// Vitest config — used only to RUN the catalog generator (scripts/gen-catalog.test.ts)
// in an environment where `@snowluma/onebot/action-docs` resolves. The proton
// plugin provides the same bare-specifier resolver @snowluma/onebot's own tests
// use, so importing the action specs works identically here.
import protobufVitePlugin from '@snowluma/proton/vite';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [protobufVitePlugin()],
test: {
include: ['scripts/**/*.test.ts'],
environment: 'node',
env: {
SNOWLUMA_LOG_FILE: '0',
},
},
});
+8
View File
@@ -11,6 +11,14 @@
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./action-kit": {
"types": "./src/action-kit.ts",
"default": "./src/action-kit.ts"
},
"./action-docs": {
"types": "./src/action-docs.ts",
"default": "./src/action-docs.ts"
},
"./manager": {
"types": "./src/manager.ts",
"default": "./src/manager.ts"
+23 -14
View File
@@ -25,21 +25,29 @@ import { actions as groupAlbumActions } from './actions/group-album';
type AnySpec = ActionSpec<Record<string, Field<unknown>>>;
const ALL_SPECS: readonly AnySpec[] = [
...infoActions,
...messageActions,
...friendActions,
...groupInfoActions,
...groupAdminActions,
...groupFileActions,
...requestActions,
...extendedActions,
...groupAlbumActions,
// Source file = domain category. Each doc is tagged so the MCP / UI can group.
const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [
{ category: '信息', specs: infoActions },
{ category: '消息', specs: messageActions },
{ category: '好友', specs: friendActions },
{ category: '群信息', specs: groupInfoActions },
{ category: '群管理', specs: groupAdminActions },
{ category: '群文件', specs: groupFileActions },
{ category: '请求', specs: requestActions },
{ category: '扩展', specs: extendedActions },
{ category: '群相册', specs: groupAlbumActions },
];
/** Every declarative action's doc, sorted by name. */
export function collectActionDocs(specs: readonly AnySpec[] = ALL_SPECS): ActionDoc[] {
return specs.map((s) => s.describe()).sort((a, b) => a.name.localeCompare(b.name));
/** Every declarative action's doc (with category), sorted by name. */
export function collectActionDocs(): ActionDoc[] {
return GROUPS
.flatMap(({ category, specs }) => specs.map((s) => ({ ...s.describe(), category })))
.sort((a, b) => a.name.localeCompare(b.name));
}
/** Distinct categories with action counts. */
export function collectCategories(): Array<{ category: string; count: number }> {
return GROUPS.map(({ category, specs }) => ({ category, count: specs.length }));
}
function paramRow(p: ActionDoc['params'][number]): string {
@@ -52,7 +60,8 @@ function paramRow(p: ActionDoc['params'][number]): string {
function renderAction(doc: ActionDoc): string {
const lines: string[] = [];
const alias = doc.aliases.length ? ` _(别名: ${doc.aliases.map((a) => `\`${a}\``).join(', ')})_` : '';
lines.push(`### \`${doc.name}\`${alias}`);
const cat = doc.category ? ` · ${doc.category}` : '';
lines.push(`### \`${doc.name}\`${cat}${alias}`);
if (doc.summary) lines.push('', doc.summary);
if (doc.params.length) {
lines.push('', '| 参数 | 类型 | 必填 | 默认 | 说明 |', '| --- | --- | --- | --- | --- |');
+74 -18
View File
@@ -39,12 +39,19 @@ type Raw = JsonValue | typeof MISSING;
// ─────────────────────────── Field (param coercer) ───────────────────────────
/** A JSON Schema fragment (loose). Each coercer emits one; `describe()` composes
* them into an action's `inputSchema` (consumed by docs / the MCP). */
export type JsonSchema = Record<string, unknown>;
export interface FieldDoc {
type: string;
required: boolean;
default?: JsonValue;
desc?: string;
values?: readonly (string | number)[];
/** JSON Schema fragment for this field's value (constraints only; presence
* and default are applied at the object level by `describe()`). */
schema?: JsonSchema;
}
export interface Field<T> {
@@ -57,6 +64,9 @@ export interface Field<T> {
* numeric field is an error, not a silent fallback). */
default(value: T): Field<T>;
describe(text: string): Field<T>;
/** Complete JSON Schema for this field's value (constraints + description +
* default). Object-level required-ness is handled by `describe()`. */
toJsonSchema(): JsonSchema;
}
/** Core coerces a PRESENT value (never MISSING). Presence policy is applied
@@ -92,6 +102,13 @@ class FieldImpl<T> implements Field<T> {
describe(text: string): Field<T> {
return new FieldImpl<T>(this.core, { ...this.doc, desc: text });
}
toJsonSchema(): JsonSchema {
const out: JsonSchema = { ...(this.doc.schema ?? {}) };
if (this.doc.desc) out.description = this.doc.desc;
if (this.doc.default !== undefined) out.default = this.doc.default;
return out;
}
}
// ─────────────────────────── coercer vocabulary `f` ───────────────────────────
@@ -113,8 +130,23 @@ function intCore(typeName: string, opts: IntOpts): Core<number> {
};
}
function intSchema(opts: IntOpts): JsonSchema {
const s: JsonSchema = { type: 'integer' };
if (opts.min !== undefined) s.minimum = opts.min;
if (opts.max !== undefined) s.maximum = opts.max;
if (opts.nonZero) s.not = { const: 0 };
return s;
}
interface StrOpts { allowEmpty?: boolean; maxLen?: number }
function strSchema(opts: StrOpts): JsonSchema {
const s: JsonSchema = { type: 'string' };
if (opts.allowEmpty === false) s.minLength = 1;
if (opts.maxLen !== undefined) s.maxLength = opts.maxLen;
return s;
}
function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { nonEmpty(): Field<E[]> } {
const core: Core<E[]> = (raw, field) => {
if (!Array.isArray(raw)) return err(field, 'expected an array');
@@ -127,24 +159,28 @@ function arrayField<E>(el: Field<E>, mustBeNonEmpty: boolean): Field<E[]> & { no
if (mustBeNonEmpty && out.length === 0) return err(field, 'must not be empty');
return ok(out);
};
const base = new FieldImpl<E[]>(core, { type: `${el.doc.type}[]`, required: true });
const base = new FieldImpl<E[]>(core, {
type: `${el.doc.type}[]`,
required: true,
schema: { type: 'array', items: el.toJsonSchema(), ...(mustBeNonEmpty ? { minItems: 1 } : {}) },
});
return Object.assign(base, { nonEmpty: () => arrayField(el, true) });
}
export const f = {
/** Positive integer (>0): group_id / user_id / message_id. */
uint(): Field<number> {
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true });
return new FieldImpl<number>(intCore('a positive integer', { min: 1 }), { type: 'uint', required: true, schema: intSchema({ min: 1 }) });
},
/** Integer with optional bounds; allows 0 / negatives unless bounded.
* e.g. a duration where 0 is meaningful: `f.int({ min: 0 })`. */
int(opts: IntOpts = {}): Field<number> {
return new FieldImpl<number>(intCore('an integer', opts), { type: 'int', required: true });
return new FieldImpl<number>(intCore('an integer', opts), { type: 'int', required: true, schema: intSchema(opts) });
},
/** OneBot message id: a non-zero integer. NEGATIVES ARE VALID (ids are a
* signed int32 hash) — do NOT use `uint()` for message_id. */
messageId(): Field<number> {
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true });
return new FieldImpl<number>(intCore('a message id', { nonZero: true }), { type: 'messageId', required: true, schema: intSchema({ nonZero: true }) });
},
/** Finite number (fractions allowed). */
number(): Field<number> {
@@ -152,7 +188,7 @@ export const f = {
if (typeof raw === 'number' && Number.isFinite(raw)) return ok(raw);
if (typeof raw === 'string' && raw.trim() !== '' && Number.isFinite(Number(raw))) return ok(Number(raw));
return err(field, 'expected a number');
}, { type: 'number', required: true });
}, { type: 'number', required: true, schema: { type: 'number' } });
},
/** String. Numbers/booleans stringify (matches legacy `asString`). Empty
* allowed by default; `{ allowEmpty: false }` rejects ''. */
@@ -165,7 +201,7 @@ export const f = {
if (opts.allowEmpty === false && s === '') return err(field, 'must not be empty');
if (opts.maxLen !== undefined && s.length > opts.maxLen) return err(field, `must be <= ${opts.maxLen} chars`);
return ok(s);
}, { type: 'string', required: true });
}, { type: 'string', required: true, schema: strSchema(opts) });
},
/** true/1/yes/on ⇒ true; false/0/no/off ⇒ false (matches legacy `asBoolean`). */
bool(): Field<boolean> {
@@ -178,7 +214,7 @@ export const f = {
if (t === 'false' || t === '0' || t === 'no' || t === 'off') return ok(false);
}
return err(field, 'expected a boolean');
}, { type: 'bool', required: true });
}, { type: 'bool', required: true, schema: { type: 'boolean' } });
},
/** OneBot message union: string | segment[] | object. A string that looks
* like a JSON array is parsed (matches legacy `asMessage`); otherwise the
@@ -197,7 +233,7 @@ export const f = {
}
}
return ok(raw);
}, { type: 'message', required: true });
}, { type: 'message', required: true, schema: { description: 'OneBot message: string | segment[] | object' } });
},
/** Homogeneous array; `.nonEmpty()` rejects []. */
array<E>(el: Field<E>): Field<E[]> & { nonEmpty(): Field<E[]> } {
@@ -210,11 +246,11 @@ export const f = {
return ok(raw as V[number]);
}
return err(field, `expected one of: ${values.join(', ')}`);
}, { type: 'enum', required: true, values });
}, { type: 'enum', required: true, values, schema: { enum: [...values] } });
},
/** Escape hatch — pass the raw value (or undefined) through, validate nothing. */
raw(): Field<JsonValue | undefined> {
return new FieldImpl<JsonValue | undefined>((raw) => ok(raw), { type: 'raw', required: false, default: undefined });
return new FieldImpl<JsonValue | undefined>((raw) => ok(raw), { type: 'raw', required: false, default: undefined, schema: {} });
},
};
@@ -291,10 +327,14 @@ export interface ParamDoc extends FieldDoc {
export interface ActionDoc {
name: string;
aliases: string[];
/** Domain category (set by the doc collector, e.g. 群管理/消息). */
category?: string;
summary?: string;
returns?: string;
params: ParamDoc[];
invariants: string[];
/** Composed JSON Schema for the whole params object (properties + required). */
inputSchema: JsonSchema;
}
type Handler = (params: JsonObject) => Promise<ApiResponse>;
@@ -359,14 +399,30 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
params: def.params,
parse,
toHandler,
describe: () => ({
name: names[0],
aliases: names.slice(1),
summary: def.summary,
returns: def.returns,
params: Object.entries(def.params).map(([name, field]) => ({ name, ...field.doc })),
invariants: rules.map((rule) => rule.doc),
}),
describe: () => {
const entries = Object.entries(def.params);
const properties: Record<string, JsonSchema> = {};
const required: string[] = [];
for (const [name, field] of entries) {
properties[name] = field.toJsonSchema();
if (field.doc.required) required.push(name);
}
const inputSchema: JsonSchema = {
type: 'object',
properties,
...(required.length ? { required } : {}),
additionalProperties: true,
};
return {
name: names[0],
aliases: names.slice(1),
summary: def.summary,
returns: def.returns,
params: entries.map(([name, field]) => ({ name, ...field.doc })),
invariants: rules.map((rule) => rule.doc),
inputSchema,
};
},
register: (h, ctx) => {
const handler = toHandler(ctx);
for (const name of names) h.registerAction(name, handler);
+36
View File
@@ -164,6 +164,42 @@ describe('run raw escape hatch — original params as 3rd arg', () => {
});
});
describe('toJsonSchema / inputSchema (for the MCP)', () => {
it('emits a JSON Schema fragment per coercer', () => {
expect(f.uint().toJsonSchema()).toEqual({ type: 'integer', minimum: 1 });
expect(f.messageId().toJsonSchema()).toEqual({ type: 'integer', not: { const: 0 } });
expect(f.int({ min: 0 }).default(1800).toJsonSchema()).toEqual({ type: 'integer', minimum: 0, default: 1800 });
expect(f.string({ allowEmpty: false }).toJsonSchema()).toEqual({ type: 'string', minLength: 1 });
expect(f.bool().toJsonSchema()).toEqual({ type: 'boolean' });
expect(f.enum('a', 'b').toJsonSchema()).toEqual({ enum: ['a', 'b'] });
expect(f.array(f.uint()).nonEmpty().toJsonSchema()).toEqual({
type: 'array',
items: { type: 'integer', minimum: 1 },
minItems: 1,
});
expect(f.uint().describe('群号').toJsonSchema()).toEqual({ type: 'integer', minimum: 1, description: '群号' });
});
it('composes an action inputSchema (object + required + defaults)', () => {
const spec = groupUserAction({
name: 'set_group_ban',
params: { duration: f.int({ min: 0 }).default(1800) },
run: () => okResponse(),
});
const { inputSchema } = spec.describe();
expect(inputSchema).toMatchObject({
type: 'object',
additionalProperties: true,
required: ['group_id', 'user_id'],
properties: {
group_id: { type: 'integer', minimum: 1 },
user_id: { type: 'integer', minimum: 1 },
duration: { type: 'integer', minimum: 0, default: 1800 },
},
});
});
});
describe('describe — doc metadata for self-generated docs (D4)', () => {
const spec = groupUserAction({
name: ['set_group_ban', 'ban'],
+675
View File
File diff suppressed because it is too large. Load diff