Files
seal-use/src/server.ts
T
gitea db5a3f7139 fix: 修复审核记录导出进度与后台等待机制
为审核记录导出增加可复用的本地后台任务及 status/wait/list,等待超时或观察进程退出后任务继续执行。
统一实时脱敏诊断输出,保留 stdout 单一 JSON;补齐高级参数、预览和筛选配置摘要。
默认保留合思未找到单据,分别统计单据与审核记录,并显式报告部分补取失败。
补充 CLI/Skill 版本诊断、技能路由及回归测试,修复企业列表加载开销和源码更新测试隔离。
2026-10-27 15:59:04 +08:00

227 lines
7.6 KiB
TypeScript

import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { McpServer, type CallToolResult } from "@modelcontextprotocol/server";
import { serveStdio, type StdioServerHandle } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import { runCli } from "./cli/runner.js";
import { isReadOnlyCliCommand } from "./cli/read-only.js";
import { normalizeCliArgs, tokenizeCommand } from "./cli/tokenize.js";
import { classifyCliError } from "./core/errors.js";
import { VERSION } from "./version.js";
import { isCompiledBinary, resolveAppRoot, resolveDefaultLauncher } from "./core/runtime.js";
const serverEntryFile = fileURLToPath(import.meta.url);
// Source servers and compiled CLI servers share the launcher rules. In a binary,
// $bunfs paths identify bundled modules, not files a child process can execute.
const cliEntryFile = resolve(dirname(serverEntryFile), "cli.ts");
const pluginRoot = resolveAppRoot(cliEntryFile);
export const SEAL_USE_MCP_TOOL_NAME = "seal_use";
export const SEAL_USE_MCP_WRITE_TOOL_NAME = "seal_use_write";
export const SEAL_MCP_ENABLED_ENV = "SEAL_USE_MCP_ENABLED";
export const LEGACY_SEAL_MCP_ENABLED_ENV = "SEAL_HOME_MCP_ENABLED";
export function resolveServerCliLauncher(entryFile = serverEntryFile, compiled = isCompiledBinary(), execPath = process.execPath) {
return resolveDefaultLauncher(resolve(dirname(entryFile), "cli.ts"), compiled, execPath);
}
export function resolveMcpEnabled(
value = process.env[SEAL_MCP_ENABLED_ENV] ?? process.env[LEGACY_SEAL_MCP_ENABLED_ENV]
): boolean {
if (value === undefined) return false;
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
export function createServer(options: { enableCli?: boolean } = {}): McpServer {
const enableCli = options.enableCli ?? true;
const server = new McpServer(
{
name: "seal-use",
version: VERSION
},
{
// Declared explicitly so that `tools/list` answers with an empty list (rather than a
// method-not-found error) when seal_use is switched off by configuration.
capabilities: { tools: {} }
}
);
if (enableCli) {
const inputSchema = z.strictObject({
command: z
.string()
.describe("A seal-use CLI command, with or without the leading 'seal-use' or 'seal-home'.")
});
server.registerTool(
SEAL_USE_MCP_TOOL_NAME,
{
title: "Run read-only seal-use CLI command",
description:
"Run a read-only seal-use CLI command and return its JSON stdout. Only commands that " +
"read tenant state without changing it are accepted here; anything that mutates tenant " +
"state, publishes configuration, mints credentials, self-updates or starts a server is " +
`refused — use ${SEAL_USE_MCP_WRITE_TOOL_NAME} for those after confirming with the user.`,
inputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true
}
},
async ({ command }): Promise<CallToolResult> =>
executeCliCommand(command, { requireReadOnly: true })
);
server.registerTool(
SEAL_USE_MCP_WRITE_TOOL_NAME,
{
title: "Run mutating seal-use CLI command",
description:
"Run a seal-use CLI command that changes tenant state, publishes configuration, or sends " +
"things outward (create/update/push/mark/bind/sync/deploy/delete/reset-password, rule " +
"publishing, simulation batches, self-update). Confirm the exact command with the user " +
"before calling this tool.",
inputSchema,
annotations: {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true
}
},
async ({ command }): Promise<CallToolResult> => executeCliCommand(command, { requireReadOnly: false })
);
}
return server;
}
async function executeCliCommand(
command: string | undefined,
options: { requireReadOnly: boolean }
): Promise<CallToolResult> {
const toolName = options.requireReadOnly ? SEAL_USE_MCP_TOOL_NAME : SEAL_USE_MCP_WRITE_TOOL_NAME;
if (!command?.trim()) {
return cliResult({
stdout: "",
stderr: `${toolName} requires a non-empty command string`,
isError: true,
exitCode: 2
});
}
let cliArgs: string[];
try {
cliArgs = normalizeCliArgs(tokenizeCommand(command));
if (!cliArgs.length) {
throw new Error(`${toolName} requires a non-empty command string`);
}
} catch (error) {
const classification = classifyCliError(error);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: classification.exitCode
});
}
// Enforced, not just annotated: a client that auto-approves the read-only tool must not be able
// to reach a mutating command through it, and unclassified commands fail closed.
if (options.requireReadOnly && !isReadOnlyCliCommand(cliArgs)) {
return cliResult({
stdout: "",
stderr:
`${SEAL_USE_MCP_TOOL_NAME} only runs read-only commands, and "${cliArgs.join(" ")}" is not one of ` +
`them. Confirm the command with the user, then call ${SEAL_USE_MCP_WRITE_TOOL_NAME}.`,
isError: true,
exitCode: 2
});
}
try {
return cliResult(await runCli(cliArgs, {
appRoot: pluginRoot,
entryFile: cliEntryFile,
launcher: resolveServerCliLauncher()
}));
} catch (error) {
const classification = classifyCliError(error);
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
isError: true,
exitCode: classification.exitCode
});
}
}
export function startServer(): StdioServerHandle {
const enableCli = resolveMcpEnabled();
const handle = serveStdio(() => createServer({ enableCli }));
console.error(
enableCli
? "seal-use MCP server running on stdio"
: "seal-use MCP server connected with seal_use disabled by configuration"
);
return handle;
}
export { tokenizeCommand };
function cliResult(result: { stdout: string; stderr: string; isError: boolean; exitCode: number }): CallToolResult {
// Confirmation-required (exit 10) or partially-executed write commands (exit 1)
// can emit a structured JSON payload on stdout alongside stderr guidance.
// Preserve both for MCP consumers instead of returning only the prose.
if (result.isError && result.stdout) {
return {
content: [
{ type: "text", text: result.stdout },
...(result.stderr ? [{ type: "text" as const, text: result.stderr }] : [])
],
isError: true
};
}
const text = result.isError ? result.stderr || result.stdout : result.stdout;
return {
content: [
{
type: "text" as const,
text
}
],
isError: result.isError
};
}
async function runEmbeddedCli() {
const result = await runCli(process.argv.slice(3), {
appRoot: pluginRoot,
entryFile: cliEntryFile,
launcher: resolveServerCliLauncher(),
onStderr: (text) => process.stderr.write(text)
});
if (result.stdout) process.stdout.write(result.stdout);
process.exitCode = result.exitCode;
}
const isMainModule = Boolean(
(import.meta as any).main ||
(!import.meta.url.includes("$bunfs") && process.argv[1] && resolve(process.argv[1]) === resolve(serverEntryFile))
);
if (isMainModule) {
if (process.argv[2] === "--seal-use-cli") {
await runEmbeddedCli();
} else {
try {
startServer();
} catch (error) {
console.error(error);
process.exitCode = 1;
}
}
}