Add seal-home ZCode plugin packaging
This commit is contained in:
1 parent
0959cef1cc
commit
38610d3573
24 files changed
+31884
-1655
No files matched your search
+13
-1486
File diff suppressed because it is too large.
Load diff
@@ -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");
|
||||
});
|
||||
});
|
||||
Executable
+1582
File diff suppressed because it is too large.
Load diff
+38
-27
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user