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

+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;
});
}
}