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 "./cli/errors.js"; import { VERSION } from "./version.js"; const serverEntryFile = fileURLToPath(import.meta.url); // Repo/checkout root when running from src/server.ts (`seal-use mcp`); there is // no packaged bundle anymore, so two levels up is always the app root. const pluginRoot = dirname(dirname(serverEntryFile)); 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 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 => 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 => executeCliCommand(command, { requireReadOnly: false }) ); } return server; } async function executeCliCommand( command: string | undefined, options: { requireReadOnly: boolean } ): Promise { 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: serverEntryFile, launcher: { command: process.execPath, args: [serverEntryFile, "--seal-use-cli"] } })); } 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 { 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: serverEntryFile, launcher: { command: process.execPath, args: [serverEntryFile, "--seal-use-cli"] } }); 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; } 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; } } }