Add seal-home ZCode plugin packaging

This commit is contained in:
gitea committed 2026-08-12 14:35:40 +08:00
1 parent 0959cef1cc
commit 38610d3573
24 files changed
+31884 -1655

No files matched your search

+1
View File
@@ -0,0 +1 @@
../../skills/seal-home
+13
View File
@@ -0,0 +1,13 @@
{
"mcpServers": {
"seal-home": {
"type": "stdio",
"command": "node",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
],
"enabled": false,
"timeoutMs": 120000
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "seal-home",
"version": "0.5.0",
"description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
},
"license": "MIT",
"skills": "skills",
"mcpServers": "./.mcp.json"
}
+19 -16
View File
@@ -84,7 +84,20 @@ enterprises/*.json
!enterprises/example.*.json
```
The standard Codex skill lives at `.agents/skills/seal-home`. Install or copy that folder into a Codex skills directory when you want Codex to invoke the workflow as `$seal-home`.
The canonical plugin skill lives at `skills/seal-home`; `.agents/skills/seal-home` is a workspace symlink to the same files. Install or copy that folder into a Codex skills directory when you want Codex to invoke the workflow as `$seal-home`.
## ZCode Plugin
The repository is also a ZCode plugin. Install `seal-home` from the `yingqing-plugins` marketplace in **Settings → Plugin Management**, or add this repository as a local plugin directory while developing. The plugin provides the `skills/seal-home` skill and an optional MCP server.
The MCP server is disabled by default. Enable `seal-home` in **Settings → MCP** when an agent needs the `seal_cli` tool; disable it again when only the skill or global CLI is needed. The tool accepts the same command syntax as the global CLI, including `version` and `seal-home version`.
For a standalone compiled CLI, build and run the binary from a checkout:
```bash
bun run build:binary
./dist/bin/seal-home version
```
## CLI
@@ -188,26 +201,16 @@ The service is intentionally local and currently acts as a lifecycle wrapper for
Most users do not need MCP. The public/shared path is the global `seal-home` CLI plus the optional local service.
For protocol-native development clients, the MCP server intentionally keeps a narrow exported surface:
- `seal_corp_switch`: switch the active local enterprise config.
- `seal_whoami`: current Seal user and tenant.
- `seal_approval_search`: keyword search across approval rules, documents, approval preferences, and optionally published rule history. Results include area, entity, field, line number, and surrounding context. Search data is cached in memory for 5 minutes only within a long-lived process such as the MCP server; separate CLI invocations do not share this cache.
- `seal_approval_context_get`: read current approval rules, approval documents, and approval style preferences in one call.
- `seal_runs_search`: search the approval run history from `api/v1/approvals`. This is the broad record table for historical runs and returns compact run fields; set `includeBridge` only when full Langfuse bridge rows are needed.
- `seal_action`: low-frequency management router. Use `action: "help"` or `payload.topic` to discover actions.
`seal_corps_list`, `seal_source_config`, and older fine-grained tool names are still accepted by the MCP call handler for compatibility, but they are not advertised by MCP `tools/list`.
`seal_action` uses this shape:
The MCP server advertises exactly one tool, `seal_cli`:
```json
{
"action": "rule.create | rule.update | rule.publish | doc.create | doc.update | runs.summary | langfuse.bridge.get",
"payload": {}
"command": "version"
}
```
It runs the same CLI dispatcher as the global binary, so read operations, write operations, `config`, `service`, and `update` remain available. Write-operation confirmations and explicit enterprise-ID rules continue to be defined by this skill.
## CLI Tools
These tools remain available to the CLI:
@@ -262,7 +265,7 @@ When `_langfuseTraceId` exists, downstream tools should fetch the trace directly
- Prefer Bun-native commands in this repository: `bun run check`, `bun test`, and `seal-home ...`. `npm run check` may work, but Bun is the project runtime and lockfile owner.
- Keep CLI entry points thin. Shared behavior belongs in `src/core` and `src/domains`; `src/cli.ts` should only handle command parsing, process lifecycle, and JSON output.
- Do not print diagnostic text to stdout from the MCP server. MCP uses stdout as the protocol stream; use stderr for server diagnostics.
- Keep any MCP exported surface narrow. High-frequency read tools can be direct MCP tools; low-frequency maintenance should go through `seal_action` or CLI commands.
- Keep the MCP exported surface to the single `seal_cli` router; command knowledge belongs in this skill and its focused references.
- Prefer CLI or script processing for large tool responses. For daily approval questions, call `seal-home approval-runs summary --corp <corpId> ...` instead of reading long `seal_approval_runs_search` output manually.
- Keep broad search tools compact by default. Add explicit opt-in flags such as `includeBridge` for verbose fields that are useful only in deeper debugging.
- When Seal API timestamp filters are uncertain, filter again in tool code by `createdAt` and explicit timezone before presenting date-based answers.
+29765
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "seal-home",
"version": "0.4.3",
"version": "0.5.0",
"type": "module",
"module": "src/server.ts",
"bin": {
@@ -12,7 +12,8 @@
"probe": "bun run src/probe.ts",
"cli": "bun run src/cli.ts",
"check": "tsc --noEmit",
"build:binary": "bun build --compile --outfile dist/bin/seal-home src/cli.ts",
"build:binary": "node scripts/build-binary.mjs",
"build:plugin": "node scripts/build-plugin.mjs",
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
"test": "bun test"
},
+148
View File
@@ -0,0 +1,148 @@
# seal-home 插件化改造计划(供 Codex 执行)
> 状态:已完成(2026-08-12)。全局配置改造已先合入 `master`;插件改造已从最新 `master` 分支完成、快进合并并推送。
> 本文件记录实际交付结果与验收项。
## 1. 背景
seal-home 是一个 Bun + TypeScript 的 CLI + MCP server 工具仓库(v0.5.0),skill 文档位于 `skills/seal-home/`,工作区入口 `.agents/skills/seal-home` 为符号链接。目标是把仓库包装成标准的 ZCode 插件,同时保留全局 CLI 能力。
**最终形态(混合模式,两条线并存):**
| 线 | 面向 | 形态 |
|---|---|---|
| 全局 CLI | 客户/脚本/手动 | `seal-home` 二进制(`bun build --compile`),可独立安装、可与其他 shell 命令组合使用,**保留现状** |
| ZCode 插件 | agent | `skills/seal-home/`(知识层)+ MCP server(可选启用,执行层) |
**插件内的 MCP 采用单工具模式:** 只注册一个 `seal_cli` 工具,接受一个命令行字符串,内部透传到 CLI 的命令分发层。命令知识全部收敛在 skill 文档,工具 schema 只做路由(一句 description 指针),不写教程。
## 2. 目标布局
```
seal-home/ # 仓库根即插件根
├── .zcode-plugin/plugin.json # 插件清单(新增)
├── .mcp.json # MCP server 声明,enabled: false(新增)
├── skills/
│ └── seal-home/ # 从 .agents/skills/seal-home 迁入
│ ├── SKILL.md
│ └── references/
├── dist/
│ ├── bin/seal-home # 全局 CLI 编译产物(已有 build:binary)
│ └── mcp/server.js # MCP server 单文件 bundle(新增)
├── src/ # 源码保留,仓库继续独立开发测试
├── openapi/ package.json README.md
└── .agents/skills/seal-home # 保留为指向 skills/seal-home 的链接或副本(开发期 workspace 使用)
```
## 3. 已定决策(执行时不要更改)
1. **MCP 默认不启用**:`.mcp.json` 中 `enabled: false`,用户需要时在 ZCode Settings → MCP 一键启用。
2. **MCP 单工具 `seal_cli`**:schema 只含 `command: string`;description 用一句话指针(如 "Run seal-home CLI commands. See the seal-home skill for command reference."),具体用法在 SKILL.md。
3. **CLI 命令语法不变**:MCP 与全局 CLI 共享同一命令分发实现,不允许两套逻辑。
4. **企业配置不迁移到 userConfig**:`enterprises/*.json` 与 `~/.config/seal-home/enterprises` 的现有加载机制保持不变。
5. **插件格式**:`.zcode-plugin/plugin.json`(ZCode 原生);如本机验证 ZCode 不识别,再补 `.claude-plugin/plugin.json` 兼容副本。
6. **版本号**:改造完成后统一升到 `0.5.0`(`package.json`、SKILL.md frontmatter、marketplace 条目三处对齐)。
7. **发布时间**:主功能迭代完成后,在干净的 release 基础上单独开分支执行。
## 4. 任务拆解(按序执行)
### T1 构建产物
- 新增 `scripts/build-plugin.mjs`(或扩展 package.json scripts):
- MCP server 单文件 bundle:`bun build src/server.ts --target=node --outfile dist/mcp/server.js`(优先 node target;若因 `@modelcontextprotocol/sdk`/ky 等依赖无法 bundle 成功,退回 `--target=bun` 并在 `.mcp.json` 用 `command: "bun"`)。
- 保留/复用 `build:binary` 产出 `dist/bin/seal-home`。
- 若 CLI 运行时读取 `dist/openapi.json` 则随包拷贝,否则不打包(先 grep 确认是否有运行时读取)。
- `bun run check`、`bun test` 必须通过。
### T2 CLI 分发层抽离(MCP 复用的前提)
- 当前 `src/cli.ts` 是 1441 行的 bin 入口。抽出纯逻辑分发层(如 `src/cli/runner.ts`),导出类似 `runCli(args: string[]): Promise<{ stdout: string; isError: boolean }>` 的可复用函数。
- **关键约束**:分发层内部禁止 `process.exit`,错误一律通过返回值/异常传播;`src/cli.ts` 变薄为"调 runner + 处理退出码"。
- 保持 CLI 行为与输出格式(JSON stdout / 诊断走 stderr)完全不变,现有 `cli.test.ts` 全绿。
### T3 MCP 单工具改造
- `src/server.ts`:从"注册 ~20 个 sealMcpTools"改为只注册 `seal_cli` 一个工具。
- handler 收到 `command` 字符串后调用 T2 的 `runCli`(同进程调用,不 spawn 子进程、不依赖全局二进制)。
- 返回 `{ content: [{ type: "text", text: <stdout> }], isError: <失败标记> }`,透传 CLI 的 JSON 输出。
- 原 `sealMcpTools` 的逐一注册逻辑可保留在代码中但不再注册(或标记废弃),避免删除时牵连未迁移命令。
### T4 skill 迁移
- 将 `.agents/skills/seal-home/` 整体迁到 `skills/seal-home/`(根目录 `skills/` 目前为空)。
- `.agents/skills/seal-home` 改为指向 `skills/seal-home` 的符号链接(或最小副本),保证当前 workspace skill 加载不中断;AGENTS.md 中 `.agents/` authoritative 的约定不受影响(链接不改变内容来源)。
- SKILL.md 执行路径更新为:**优先 `seal_cli` MCP 工具(若会话中可用),否则回退全局 `seal-home` 命令**;命令语法部分不变。
- 清理:`~/.agents/skills/seal-home` 若为空目录则删除(先确认无内容);`~/.agents/skills/seal` bundle 与插件 skill 的共存关系保持不变,不做合并。
### T5 插件清单与 MCP 声明
- `.zcode-plugin/plugin.json`:
```json
{
"name": "seal-home",
"version": "0.5.0",
"description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, search.",
"author": { "name": "yingqing" },
"license": "MIT",
"skills": "skills",
"mcpServers": "./.mcp.json"
}
```
- `.mcp.json`:
```json
{
"mcpServers": {
"seal-home": {
"type": "stdio",
"command": "node",
"args": ["${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"],
"enabled": false
}
}
}
```
(若 T1 退化为 bun target,则 `command: "bun"`;变量名以本机 ZCode 支持的插件根变量为准,先查 zcode 文档/已有插件示例再定。)
### T6 本地安装验证
- 通过 ZCode **Settings → Plugin Management** 添加本仓库目录,验证:
1. 插件 skill 可发现(`seal-home` skill 出现在 skill 列表,来源为插件)。
2. Settings → MCP 中 `seal-home` server 显示 disabled。
3. 启用后,`seal_cli` 工具可用,端到端跑通一个命令(如 `seal-home corps list`、`seal-home version`)。
4. 全局 CLI 仍可 `bun run build:binary` 并独立使用。
### T7 发布(marketplace)
- 在 `yunyingk/yingqing-plugins` 的 `marketplace.json` 增加 `seal-home` 条目。
- 优先使用 github source 引用本仓库(参照已有条目 xiaohongshu-skills 的 `source: {source: "github", repo, ref, sha}` 写法 + `skills: "./skills"`);若 marketplace 结构不支持,则退化为把插件 payload(`.zcode-plugin/`、`.mcp.json`、`skills/`、`dist/`、README)镜像到 `plugins/seal-home/` 并同步维护。
- 三处版本对齐:`package.json` / SKILL.md frontmatter / marketplace.json。
- 敏感检查:确认发布内容不含 `enterprises/local.json` 等真实凭据(对照 `.gitignore`)。
### T8 文档
- README 增加"插件安装"小节:marketplace 安装方式、MCP 启用/关闭方式、全局 CLI 安装方式对比。
- 本计划文件在改造完成后更新状态或归档。
## 5. 验收标准
- [x] `bun run check`、`bun test` 通过;CLI 输出格式与改造前一致。
- [x] 仓库根结构符合 §2 目标布局。
- [x] 本机插件安装后 skill 可发现、MCP 默认 disabled、启用后 `seal_cli` 端到端可用。
- [x] 全局 `seal-home` 二进制可独立构建、安装、与 shell 命令组合使用。
- [x] `.agents/skills/seal-home` 在开发环境中仍可加载(链接生效)。
- [x] marketplace 条目存在且版本一致,无真实凭据泄漏。
- [x] skill 文档中 MCP/CLI 双路径指引明确。
## 6. 非目标
- 不把 MCP 拆成多个细粒度工具(保持单工具)。
- 不迁移企业配置存储方式、不改 CLI 命令语法。
- 不合并 `~/.agents/skills/seal` bundle。
- 不处理主功能迭代中的需求(本计划在其之后执行)。
## 7. 风险与注意
- **cli.ts 抽离是最大改动面**:1441 行的 bin 入口重构需保证零行为变化,以 `cli.test.ts` + 手工冒烟为准。
- **node target bundle 可行性未验证**:`@modelcontextprotocol/sdk` 为纯 JS、ky/zod 通用,预期可行;失败则退 bun target,不影响整体设计。
- **插件根变量名**:`${CLAUDE_PLUGIN_ROOT}` 是 Claude 生态约定,ZCode 是否沿用需以本机实测为准。
- **workspace skill 来源变更**:迁移后开发期 workspace 的 seal-home skill 来自符号链接,若 ZCode 不支持链接目录,改用副本并接受双份维护(以 §4 T4 的验证结果为准)。
+29
View File
@@ -0,0 +1,29 @@
import { mkdirSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bun = process.env.BUN_BIN || "bun";
const output = resolve(root, "dist/bin/seal-home");
mkdirSync(dirname(output), { recursive: true });
run(bun, ["build", "--compile", "--outfile", output, "src/cli.ts"]);
// Bun's macOS standalone output can carry a stale code-signature blob on
// development machines. Re-signing ad hoc keeps the local binary executable.
if (process.platform === "darwin") {
run("/usr/bin/codesign", ["--remove-signature", output]);
run("/usr/bin/codesign", ["--force", "--sign", "-", output]);
}
function run(command, args) {
const result = spawnSync(command, args, {
cwd: root,
stdio: "inherit"
});
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}`);
}
}
+24
View File
@@ -0,0 +1,24 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bun = process.env.BUN_BIN || "bun";
function run(args) {
const result = spawnSync(bun, args, {
cwd: root,
stdio: "inherit"
});
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`${bun} ${args.join(" ")} failed with status ${result.status}`);
}
}
const mcpOutput = resolve(root, "dist/mcp/server.js");
mkdirSync(dirname(mcpOutput), { recursive: true });
run(["build", "src/server.ts", "--target=node", "--outfile", mcpOutput]);
writeFileSync(mcpOutput, readFileSync(mcpOutput, "utf8").replace(/[ \t]+$/gm, ""));
run(["run", "build:binary"]);
@@ -1,14 +1,14 @@
---
name: seal-home
description: "v0.4.3: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
description: "v0.5.0: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search."
metadata:
version: 0.4.3
short-description: Seal tenant and Hose approval automation (v0.4.3)
version: 0.5.0
short-description: Seal tenant and Hose approval automation (v0.5.0)
---
# Seal Home (v0.4.3)
# Seal Home (v0.5.0)
Use the global `seal-home` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-home` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
```bash
seal-home help
+13 -1486
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, test } from "bun:test";
import { runCli } from "./runner.js";
describe("CLI runner", () => {
test("returns version output without touching the process lifecycle", async () => {
const result = await runCli(["version"]);
expect(result).toMatchObject({
stderr: "",
isError: false,
exitCode: 0
});
expect(JSON.parse(result.stdout)).toMatchObject({ name: "seal-home" });
});
test("returns diagnostics and a non-zero exit code for invalid commands", async () => {
const result = await runCli(["not-a-command"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("Unknown command: not-a-command");
});
});
+1582
View File
File diff suppressed because it is too large. Load diff
+38 -27
View File
@@ -7,27 +7,31 @@ export type ServiceConfig = {
entryFile: string;
stateDir: string;
version?: string;
launcher?: {
command: string;
args?: string[];
};
};
export async function runServiceCommand(action: string | undefined, config: ServiceConfig) {
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean } = {}
) {
switch (action) {
case "run":
await runService(config);
return;
return undefined;
case "start":
startService(config);
return;
return startService(config);
case "stop":
stopService(config);
return;
return stopService(config, options);
case "restart":
stopService(config, { quiet: true });
startService(config);
return;
return startService(config);
case "status":
case undefined:
console.log(JSON.stringify(serviceStatus(config), null, 2));
return;
return serviceStatus(config);
default:
throw new Error("Usage: seal-home service <start|stop|restart|status>");
}
@@ -67,28 +71,36 @@ async function runService(config: ServiceConfig) {
appendLog(logFile, `stopped pid=${process.pid}`);
};
process.on("SIGTERM", () => {
cleanup();
process.exit(0);
await new Promise<void>((resolve) => {
let stopped = false;
const heartbeat = setInterval(() => {}, 60_000);
const stop = () => {
if (stopped) return;
stopped = true;
cleanup();
clearInterval(heartbeat);
process.off("SIGTERM", stop);
process.off("SIGINT", stop);
resolve();
};
process.once("SIGTERM", stop);
process.once("SIGINT", stop);
});
process.on("SIGINT", () => {
cleanup();
process.exit(0);
});
setInterval(() => {}, 60_000);
await new Promise(() => {});
}
function startService(config: ServiceConfig) {
ensureStateDir(config.stateDir);
const current = serviceStatus(config);
if (current.running) {
console.log(JSON.stringify(current, null, 2));
return;
return current;
}
const child = spawn(process.execPath, [config.entryFile, "service", "run"], {
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
const child = spawn(launcher.command, [
...(launcher.args ?? []),
"service",
"run"
], {
cwd: config.appRoot,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
@@ -99,7 +111,7 @@ function startService(config: ServiceConfig) {
const pidFile = getPidFile(config);
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
appendLog(getLogFile(config), `started pid=${child.pid}`);
console.log(JSON.stringify({ started: true, ...serviceStatus(config) }, null, 2));
return { started: true, ...serviceStatus(config) };
}
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
@@ -107,14 +119,13 @@ function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
const pid = readServicePid(pidFile);
if (!pid || !isSealHomeProcess(pid, config.appRoot)) {
rmSync(pidFile, { force: true });
if (!options.quiet) console.log(JSON.stringify({ stopped: false, reason: "not running" }, null, 2));
return;
return options.quiet ? undefined : { stopped: false, reason: "not running" };
}
process.kill(pid, "SIGTERM");
rmSync(pidFile, { force: true });
appendLog(getLogFile(config), `stop requested pid=${pid}`);
if (!options.quiet) console.log(JSON.stringify({ stopped: true, pid }, null, 2));
return options.quiet ? undefined : { stopped: true, pid };
}
function isSealHomeProcess(pid: number, appRoot: string) {
+67
View File
@@ -0,0 +1,67 @@
import { describe, expect, test } from "bun:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { createServer, SEAL_CLI_TOOL_NAME, tokenizeCommand } from "./server.js";
describe("seal-home MCP server", () => {
test("tokenizes quoted JSON without invoking a shell", () => {
expect(tokenizeCommand(
`seal-home tool seal_approval_search --json '{"keywords":["差旅 发票"]}' --corp corp-a`
)).toEqual([
"seal-home",
"tool",
"seal_approval_search",
"--json",
'{"keywords":["差旅 发票"]}',
"--corp",
"corp-a"
]);
});
test("advertises one tool and executes version through the CLI runner", async () => {
const server = createServer();
const client = new Client({ name: "seal-home-test", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport)
]);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(1);
expect(listed.tools[0]?.name).toBe(SEAL_CLI_TOOL_NAME);
expect(listed.tools[0]?.inputSchema).toMatchObject({
type: "object",
required: ["command"]
});
const result = await client.callTool({
name: SEAL_CLI_TOOL_NAME,
arguments: { command: "seal-home version" }
});
const content = result.content as Array<{ type: "text"; text: string }>;
const text = content[0];
expect(result.isError).not.toBe(true);
expect(text?.type).toBe("text");
if (text?.type === "text") {
expect(JSON.parse(text.text)).toMatchObject({ name: "seal-home" });
}
const invalid = await client.callTool({
name: SEAL_CLI_TOOL_NAME,
arguments: { command: "not-a-command" }
});
expect(invalid.isError).toBe(true);
const invalidContent = invalid.content as Array<{ type: "text"; text: string }>;
const errorText = invalidContent[0];
expect(errorText?.type).toBe("text");
if (errorText?.type === "text") {
expect(errorText.text).toContain("Unknown command: not-a-command");
}
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
});
+143 -119
View File
@@ -1,26 +1,22 @@
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import {
getEnterprisesDirCandidates,
loadCorpConfigs,
loadGlobalConfig,
saveGlobalConfig
} from "./core/config/loader.js";
import { CorpContext } from "./core/config/manager.js";
import { createSealClient } from "./core/http/factory.js";
import { resolveLiveSealEnterpriseConfig } from "./domains/seal/source.js";
import { findSealMcpTool, findSealTool, sealMcpTools } from "./domains/seal/tools.js";
import { runCli } from "./cli/runner.js";
import { VERSION } from "./version.js";
async function main() {
const corps = loadCorpConfigs();
const corpContext = new CorpContext(corps, loadGlobalConfig());
const serverEntryFile = fileURLToPath(import.meta.url);
const pluginRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.includes("\\dist\\mcp\\")
? dirname(dirname(dirname(serverEntryFile)))
: dirname(dirname(serverEntryFile));
export const SEAL_CLI_TOOL_NAME = "seal_cli";
export function createServer() {
const server = new Server(
{
name: "seal-home",
@@ -36,142 +32,170 @@ async function main() {
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: "seal_corps_list",
description: "列出当前已加载的 Seal 企业配置及选中状态",
inputSchema: {
type: "object",
properties: {}
}
},
{
name: "seal_corp_switch",
description: "切换当前 Seal 企业",
name: SEAL_CLI_TOOL_NAME,
description: "Run seal-home CLI commands. See the seal-home skill for command reference.",
inputSchema: {
type: "object",
properties: {
corpId: { type: "string", description: "企业配置 ID" }
command: {
type: "string",
description: "A seal-home CLI command, with or without the leading 'seal-home'."
}
},
required: ["corpId"]
required: ["command"],
additionalProperties: false
}
},
...sealMcpTools.map((tool) => ({
name: tool.name,
description: tool.description,
inputSchema: mcpInputSchema(tool.parameters, loadGlobalConfig().stateful)
}))
}
]
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const globalConfig = loadGlobalConfig();
corpContext.refresh(loadCorpConfigs(), globalConfig);
if (name === "seal_corps_list") {
return textResult(corpContext.listCorps());
}
if (name === "seal_corp_switch") {
const { corpId } = args as { corpId: string };
if (!globalConfig.stateful) {
return textResult({
success: false,
message: "Cannot switch the default enterprise while stateless mode is enabled. " +
"Set config mode to stateful first."
}, true);
}
const success = corpContext.switchCorp(corpId);
if (success) {
saveGlobalConfig({ ...globalConfig, stateful: true, defaultCorpId: corpId });
}
return textResult(
success ? { success: true, current: corpId } : { success: false, message: `Unknown corp: ${corpId}` },
!success
);
}
const requestedCorpId = getCorpId(args);
const currentCorp = corpContext.resolve(requestedCorpId);
if (!currentCorp) {
return textResult(
{
error: requestedCorpId
? `No enterprise config found for ${requestedCorpId}`
: globalConfig.stateful
? "No enterprise config loaded. Add a non-example JSON file to an enterprises config directory."
: "Stateless mode is enabled. Every enterprise tool call requires corpId.",
candidates: getEnterprisesDirCandidates()
},
true
);
const args = request.params.arguments;
const command = args && typeof args.command === "string" ? args.command : undefined;
if (!command?.trim()) {
return cliResult({
stdout: "",
stderr: "seal_cli requires a non-empty command string",
isError: true,
exitCode: 1
});
}
try {
if (name === "seal_source_config") {
return textResult(await resolveLiveSealEnterpriseConfig(currentCorp));
const tokens = tokenizeCommand(command);
const cliArgs = normalizeCliArgs(tokens);
if (!cliArgs.length) {
throw new Error("seal_cli requires a non-empty command string");
}
const tool = findSealMcpTool(name) ?? findSealTool(name);
if (!tool) {
return textResult({ error: `Unknown tool: ${name}` }, true);
}
const client = await createSealClient(currentCorp);
const result = await tool.handler(client, args as never, { corp: currentCorp });
return textResult(result);
return cliResult(await runCli(cliArgs, {
appRoot: pluginRoot,
entryFile: serverEntryFile,
launcher: {
command: process.execPath,
args: [serverEntryFile, "--seal-home-cli"]
}
}));
} catch (error) {
return textResult(
{ error: error instanceof Error ? error.message : String(error) },
true
);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: 1
});
}
});
return server;
}
export async function startServer() {
const server = createServer();
await server.connect(new StdioServerTransport());
console.error("seal-home MCP server running on stdio");
}
function textResult(value: unknown, isError = false) {
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
let quote: "'" | '"' | undefined;
let escaped = false;
let tokenStarted = false;
for (const character of command) {
if (escaped) {
token += character;
escaped = false;
tokenStarted = true;
continue;
}
if (character === "\\" && quote !== "'") {
escaped = true;
tokenStarted = true;
continue;
}
if (quote) {
if (character === quote) {
quote = undefined;
} else {
token += character;
}
tokenStarted = true;
continue;
}
if (character === "'" || character === '"') {
quote = character;
tokenStarted = true;
continue;
}
if (/\s/.test(character)) {
if (tokenStarted) {
tokens.push(token);
token = "";
tokenStarted = false;
}
continue;
}
token += character;
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}
function normalizeCliArgs(tokens: string[]): string[] {
const first = tokens[0];
if (!first) return [];
if (first === "seal-home" || first.endsWith("/seal-home")) return tokens.slice(1);
return tokens;
}
function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }) {
const text = result.isError ? result.stderr || result.stdout : result.stdout;
return {
content: [
{
type: "text" as const,
text: JSON.stringify(value, null, 2)
text
}
],
isError
isError: result.isError
};
}
function getCorpId(args: unknown): string | undefined {
if (!args || typeof args !== "object" || Array.isArray(args)) return undefined;
const value = (args as Record<string, unknown>).corpId;
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
function mcpInputSchema(parameters: z.ZodType, stateful: boolean) {
const schema = z.toJSONSchema(parameters) as {
type?: string;
properties?: Record<string, unknown>;
required?: string[];
};
schema.type = "object";
schema.properties = {
...(schema.properties ?? {}),
corpId: {
type: "string",
description: stateful
? "可选:企业配置 ID;省略时使用当前默认企业"
: "必填:企业配置 ID"
async function runEmbeddedCli() {
const result = await runCli(process.argv.slice(3), {
appRoot: pluginRoot,
entryFile: serverEntryFile,
launcher: {
command: process.execPath,
args: [serverEntryFile, "--seal-home-cli"]
}
};
if (!stateful) {
schema.required = [...(schema.required ?? []), "corpId"];
}
return schema;
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
process.exitCode = result.exitCode;
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
const isMainModule = process.argv[1]
? resolve(process.argv[1]) === resolve(serverEntryFile)
: false;
if (isMainModule) {
if (process.argv[2] === "--seal-home-cli") {
await runEmbeddedCli();
} else {
startServer().catch((error) => {
console.error(error);
process.exitCode = 1;
});
}
}