import { PACKAGE_VERSION, init_package_version } from "../package-version.js";
import { init_loader, loadConfig } from "../config/loader.js";
import { ClaudePermissionRequestSchema } from "./channel-shared.js";
import { XopcChannelBridge } from "./channel-bridge.js";
import { getChannelMcpCapabilities, registerChannelMcpTools } from "./channel-tools.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
//#region src/mcp/channel-server.ts
init_loader();
init_package_version();
async function createXopcChannelMcpServer(opts = {}) {
	const cfg = opts.config ?? loadConfig();
	const claudeChannelMode = opts.claudeChannelMode ?? "auto";
	const capabilities = getChannelMcpCapabilities(claudeChannelMode);
	const server = new McpServer({
		name: "xopc",
		version: PACKAGE_VERSION
	}, capabilities ? { capabilities } : void 0);
	const bridge = new XopcChannelBridge(cfg, {
		gatewayUrl: opts.gatewayUrl,
		gatewayToken: opts.gatewayToken,
		claudeChannelMode,
		verbose: opts.verbose ?? false
	});
	bridge.setServer(server);
	server.server.setNotificationHandler(ClaudePermissionRequestSchema, async ({ params }) => {
		await bridge.handleClaudePermissionRequest({
			requestId: params.request_id,
			toolName: params.tool_name,
			description: params.description,
			inputPreview: params.input_preview
		});
	});
	registerChannelMcpTools(server, bridge);
	return {
		server,
		bridge,
		start: async () => {
			await bridge.start();
		},
		close: async () => {
			await bridge.close();
			await server.close();
		}
	};
}
async function serveXopcChannelMcpImpl(opts = {}) {
	const { server, start, close } = await createXopcChannelMcpServer(opts);
	const transport = new StdioServerTransport();
	let shuttingDown = false;
	let resolveClosed;
	const closed = new Promise((resolve) => {
		resolveClosed = resolve;
	});
	const shutdown = () => {
		if (shuttingDown) return;
		shuttingDown = true;
		process.stdin.off("end", shutdown);
		process.stdin.off("close", shutdown);
		process.off("SIGINT", shutdown);
		process.off("SIGTERM", shutdown);
		transport["onclose"] = void 0;
		close().then(resolveClosed, resolveClosed);
	};
	transport["onclose"] = shutdown;
	process.stdin.once("end", shutdown);
	process.stdin.once("close", shutdown);
	process.once("SIGINT", shutdown);
	process.once("SIGTERM", shutdown);
	try {
		await server.connect(transport);
		await start();
		await closed;
	} finally {
		shutdown();
		await closed;
	}
}
//#endregion
export { createXopcChannelMcpServer, serveXopcChannelMcpImpl };

//# sourceMappingURL=channel-server.js.map