// @bun
import {
  cliError,
  cliOk
} from "./chunk-z2dp53wn.js";
import {
  AppStateProvider,
  ConfigurableShortcutHint,
  KeybindingSetup,
  SelectMulti,
  addMcpConfig,
  clearMcpClientConfig,
  clearServerTokensFromLocalStorage,
  connectToServer,
  describeMcpConfigFilePath,
  ensureConfigScope,
  getAllMcpConfigs,
  getMcpClientConfig,
  getMcpConfigByName,
  getMcpConfigsByScope,
  getMcpServerConnectionBatchSize,
  getScopeLabel,
  gracefulShutdown,
  init_AppState,
  init_ConfigurableShortcutHint,
  init_KeybindingProviderSetup,
  init_SelectMulti,
  init_auth,
  init_client,
  init_config as init_config2,
  init_gracefulShutdown,
  init_utils,
  readClientSecret,
  removeMcpConfig,
  saveMcpClientSecret
} from "./chunk-4vz571bb.js";
import"./chunk-14p6wvsq.js";
import"./chunk-8hseq8b1.js";
import"./chunk-ddtxq6k5.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-ptxteaeh.js";
import"./chunk-wd53a7m4.js";
import"./chunk-hms8ge0k.js";
import"./chunk-whpphypt.js";
import"./chunk-pht800m5.js";
import"./chunk-pjkqh1kq.js";
import {
  init_p_map,
  pMap
} from "./chunk-9a9g5hbj.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-qd3r2s2n.js";
import"./chunk-djzd7tef.js";
import"./chunk-gyhnpbkx.js";
import"./chunk-71sdcaq6.js";
import"./chunk-60gf7p5s.js";
import"./chunk-sj3d0nqx.js";
import"./chunk-9pk9rk2w.js";
import"./chunk-javpza6a.js";
import"./chunk-6v7bre98.js";
import"./chunk-24kv69g3.js";
import"./chunk-fcqebw9m.js";
import"./chunk-dnfd3c9s.js";
import"./chunk-15ezj4ww.js";
import"./chunk-1h284c6e.js";
import"./chunk-582g9yce.js";
import"./chunk-y3ztgztb.js";
import"./chunk-4spgkgr3.js";
import"./chunk-n8kbhswc.js";
import"./chunk-60fkafk2.js";
import"./chunk-fgbkrbk3.js";
import"./chunk-ssw61jfd.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-k8wq4qsj.js";
import"./chunk-g7d3xx1p.js";
import"./chunk-3wrx2943.js";
import"./chunk-7p9kkh0f.js";
import"./chunk-qp8cgz66.js";
import"./chunk-1mg610h2.js";
import"./chunk-93hc149s.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-nnat9jw5.js";
import"./chunk-hqxp6b72.js";
import"./chunk-4jzkqgf1.js";
import"./chunk-33rd41ng.js";
import"./chunk-f257kqw9.js";
import"./chunk-w5hnghah.js";
import"./chunk-36twraxy.js";
import"./chunk-1bkvnj0y.js";
import"./chunk-akdpcc5p.js";
import {
  getCurrentProjectConfig,
  getGlobalConfig,
  init_config1 as init_config,
  init_stringUtils,
  plural,
  saveCurrentProjectConfig
} from "./chunk-7rrkrej7.js";
import {
  init_json,
  safeParseJSON
} from "./chunk-6r0bxrh6.js";
import"./chunk-d6500tvx.js";
import"./chunk-jg4bw4hp.js";
import"./chunk-epvbnq43.js";
import"./chunk-tn2sx7j6.js";
import"./chunk-6tzyv21c.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import {
  getPlatform,
  init_platform
} from "./chunk-ch4pgvwq.js";
import"./chunk-99jc4tcw.js";
import"./chunk-fghczfqt.js";
import"./chunk-vwenx8ke.js";
import"./chunk-f86mwfyd.js";
import"./chunk-v4ypszbb.js";
import"./chunk-bk6ck5c2.js";
import"./chunk-ym6j0wv1.js";
import"./chunk-hjmatcgt.js";
import"./chunk-6mdh70q0.js";
import"./chunk-ch92ycde.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-nt5dmk8q.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-0gp4q8aq.js";
import"./chunk-hn4w9pkj.js";
import {
  Byline,
  Dialog,
  KeyboardShortcutHint,
  ThemedBox_default,
  ThemedText,
  color,
  init_src,
  require_react,
  root_default,
  useTheme
} from "./chunk-0r6npc3t.js";
import {
  require_jsx_runtime
} from "./chunk-gxyx8b8w.js";
import {
  init_analytics,
  logEvent
} from "./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-t0450ma3.js";
import"./chunk-0cqw3y8h.js";
import"./chunk-k1sw7km0.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-sc9ycxra.js";
import"./chunk-hhta0nge.js";
import"./chunk-8wsj9fff.js";
import"./chunk-m28vg9w4.js";
import"./chunk-f8prtxs3.js";
import"./chunk-41a6f2kv.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import {
  init_errors,
  isFsInaccessible
} from "./chunk-byd20vdq.js";
import {
  init_process,
  writeToStdout
} from "./chunk-kb3758f7.js";
import"./chunk-3j8w0rq8.js";
import"./chunk-tj0dzck2.js";
import"./chunk-aeysytks.js";
import"./chunk-ns1htxgd.js";
import"./chunk-ztqzmfx1.js";
import"./chunk-6k1rsk85.js";
import"./chunk-nxzx0ey9.js";
import"./chunk-yes1my80.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __require,
  __toESM
} from "./chunk-hhsxm2yr.js";

// src/cli/handlers/mcp.tsx
init_p_map();
import { stat } from "fs/promises";
import { cwd } from "process";

// src/components/MCPServerDesktopImportDialog.tsx
init_gracefulShutdown();
init_process();
init_src();
init_config2();
init_stringUtils();
init_ConfigurableShortcutHint();
init_SelectMulti();
var import_react = __toESM(require_react(), 1);
var jsx_runtime = __toESM(require_jsx_runtime(), 1);
function MCPServerDesktopImportDialog({ servers, scope, onDone }) {
  const serverNames = Object.keys(servers);
  const [existingServers, setExistingServers] = import_react.useState({});
  import_react.useEffect(() => {
    getAllMcpConfigs().then(({ servers: servers2 }) => setExistingServers(servers2));
  }, []);
  const collisions = serverNames.filter((name) => existingServers[name] !== undefined);
  async function onSubmit(selectedServers) {
    let importedCount = 0;
    for (const serverName of selectedServers) {
      const serverConfig = servers[serverName];
      if (serverConfig) {
        let finalName = serverName;
        if (existingServers[finalName] !== undefined) {
          let counter = 1;
          while (existingServers[`${serverName}_${counter}`] !== undefined) {
            counter++;
          }
          finalName = `${serverName}_${counter}`;
        }
        await addMcpConfig(finalName, serverConfig, scope);
        importedCount++;
      }
    }
    done(importedCount);
  }
  const [theme] = useTheme();
  const done = import_react.useCallback((importedCount) => {
    if (importedCount > 0) {
      writeToStdout(`
${color("success", theme)(`Successfully imported ${importedCount} MCP ${plural(importedCount, "server")} to ${scope} config.`)}
`);
    } else {
      writeToStdout(`
No servers were imported.`);
    }
    onDone();
    gracefulShutdown();
  }, [theme, scope, onDone]);
  const handleEscCancel = import_react.useCallback(() => {
    done(0);
  }, [done]);
  return /* @__PURE__ */ jsx_runtime.jsxs(jsx_runtime.Fragment, {
    children: [
      /* @__PURE__ */ jsx_runtime.jsxs(Dialog, {
        title: "Import MCP Servers from Claude Desktop",
        subtitle: `Found ${serverNames.length} MCP ${plural(serverNames.length, "server")} in Claude Desktop.`,
        color: "success",
        onCancel: handleEscCancel,
        hideInputGuide: true,
        children: [
          collisions.length > 0 && /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
            color: "warning",
            children: "Note: Some servers already exist with the same name. If selected, they will be imported with a numbered suffix."
          }),
          /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
            children: "Please select the servers you want to import:"
          }),
          /* @__PURE__ */ jsx_runtime.jsx(SelectMulti, {
            options: serverNames.map((server) => ({
              label: `${server}${collisions.includes(server) ? " (already exists)" : ""}`,
              value: server
            })),
            defaultValue: serverNames.filter((name) => !collisions.includes(name)),
            onSubmit,
            onCancel: handleEscCancel,
            hideIndexes: true
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        paddingX: 1,
        children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          italic: true,
          children: /* @__PURE__ */ jsx_runtime.jsxs(Byline, {
            children: [
              /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
                shortcut: "Space",
                action: "select"
              }),
              /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
                shortcut: "Enter",
                action: "confirm"
              }),
              /* @__PURE__ */ jsx_runtime.jsx(ConfigurableShortcutHint, {
                action: "confirm:no",
                context: "Confirmation",
                fallback: "Esc",
                description: "cancel"
              })
            ]
          })
        })
      })
    ]
  });
}

// src/cli/handlers/mcp.tsx
init_src();
init_KeybindingProviderSetup();
init_analytics();
init_auth();
init_client();
init_config2();
init_utils();
init_AppState();
init_config();
init_errors();
init_gracefulShutdown();
init_json();
init_platform();
var jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
async function checkMcpServerHealth(name, server) {
  try {
    const result = await connectToServer(name, server);
    if (result.type === "connected") {
      return "\u2713 Connected";
    } else if (result.type === "needs-auth") {
      return "! Needs authentication";
    } else {
      return "\u2717 Failed to connect";
    }
  } catch (_error) {
    return "\u2717 Connection error";
  }
}
async function mcpServeHandler({ debug, verbose }) {
  const providedCwd = cwd();
  logEvent("tengu_mcp_start", {});
  try {
    await stat(providedCwd);
  } catch (error) {
    if (isFsInaccessible(error)) {
      cliError(`Error: Directory ${providedCwd} does not exist`);
    }
    throw error;
  }
  try {
    const { setup } = await import("./chunk-9k0fnb6f.js");
    await setup(providedCwd, "default", false, false, undefined, false);
    const { startMCPServer } = await import("./chunk-bnxka6ps.js");
    await startMCPServer(providedCwd, debug ?? false, verbose ?? false);
  } catch (error) {
    cliError(`Error: Failed to start MCP server: ${error}`);
  }
}
async function mcpRemoveHandler(name, options) {
  const serverBeforeRemoval = getMcpConfigByName(name);
  const cleanupSecureStorage = () => {
    if (serverBeforeRemoval && (serverBeforeRemoval.type === "sse" || serverBeforeRemoval.type === "http")) {
      clearServerTokensFromLocalStorage(name, serverBeforeRemoval);
      clearMcpClientConfig(name, serverBeforeRemoval);
    }
  };
  try {
    if (options.scope) {
      const scope = ensureConfigScope(options.scope);
      logEvent("tengu_mcp_delete", {
        name,
        scope
      });
      await removeMcpConfig(name, scope);
      cleanupSecureStorage();
      process.stdout.write(`Removed MCP server ${name} from ${scope} config
`);
      cliOk(`File modified: ${describeMcpConfigFilePath(scope)}`);
    }
    const projectConfig = getCurrentProjectConfig();
    const globalConfig = getGlobalConfig();
    const { servers: projectServers } = getMcpConfigsByScope("project");
    const mcpJsonExists = !!projectServers[name];
    const scopes = [];
    if (projectConfig.mcpServers?.[name])
      scopes.push("local");
    if (mcpJsonExists)
      scopes.push("project");
    if (globalConfig.mcpServers?.[name])
      scopes.push("user");
    if (scopes.length === 0) {
      cliError(`No MCP server found with name: "${name}"`);
    } else if (scopes.length === 1) {
      const scope = scopes[0];
      logEvent("tengu_mcp_delete", {
        name,
        scope
      });
      await removeMcpConfig(name, scope);
      cleanupSecureStorage();
      process.stdout.write(`Removed MCP server "${name}" from ${scope} config
`);
      cliOk(`File modified: ${describeMcpConfigFilePath(scope)}`);
    } else {
      process.stderr.write(`MCP server "${name}" exists in multiple scopes:
`);
      scopes.forEach((scope) => {
        process.stderr.write(`  - ${getScopeLabel(scope)} (${describeMcpConfigFilePath(scope)})
`);
      });
      process.stderr.write(`
To remove from a specific scope, use:
`);
      scopes.forEach((scope) => {
        process.stderr.write(`  claude mcp remove "${name}" -s ${scope}
`);
      });
      cliError();
    }
  } catch (error) {
    cliError(error.message);
  }
}
async function mcpListHandler() {
  logEvent("tengu_mcp_list", {});
  const { servers: configs } = await getAllMcpConfigs();
  if (Object.keys(configs).length === 0) {
    console.log("No MCP servers configured. Use `claude mcp add` to add a server.");
  } else {
    console.log(`Checking MCP server health...
`);
    const entries = Object.entries(configs);
    const results = await pMap(entries, async ([name, server]) => ({
      name,
      server,
      status: await checkMcpServerHealth(name, server)
    }), { concurrency: getMcpServerConnectionBatchSize() });
    for (const { name, server, status } of results) {
      if (server.type === "sse") {
        console.log(`${name}: ${server.url} (SSE) - ${status}`);
      } else if (server.type === "http") {
        console.log(`${name}: ${server.url} (HTTP) - ${status}`);
      } else if (server.type === "claudeai-proxy") {
        console.log(`${name}: ${server.url} - ${status}`);
      } else if (!server.type || server.type === "stdio") {
        const stdioServer = server;
        const args = Array.isArray(stdioServer.args) ? stdioServer.args : [];
        console.log(`${name}: ${stdioServer.command} ${args.join(" ")} - ${status}`);
      }
    }
  }
  await gracefulShutdown(0);
}
async function mcpGetHandler(name) {
  logEvent("tengu_mcp_get", {
    name
  });
  const server = getMcpConfigByName(name);
  if (!server) {
    cliError(`No MCP server found with name: ${name}`);
  }
  console.log(`${name}:`);
  console.log(`  Scope: ${getScopeLabel(server.scope)}`);
  const status = await checkMcpServerHealth(name, server);
  console.log(`  Status: ${status}`);
  if (server.type === "sse") {
    console.log(`  Type: sse`);
    console.log(`  URL: ${server.url}`);
    if (server.headers) {
      console.log("  Headers:");
      for (const [key, value] of Object.entries(server.headers)) {
        console.log(`    ${key}: ${value}`);
      }
    }
    if (server.oauth?.clientId || server.oauth?.callbackPort) {
      const parts = [];
      if (server.oauth.clientId) {
        parts.push("client_id configured");
        const clientConfig = getMcpClientConfig(name, server);
        if (clientConfig?.clientSecret)
          parts.push("client_secret configured");
      }
      if (server.oauth.callbackPort)
        parts.push(`callback_port ${server.oauth.callbackPort}`);
      console.log(`  OAuth: ${parts.join(", ")}`);
    }
  } else if (server.type === "http") {
    console.log(`  Type: http`);
    console.log(`  URL: ${server.url}`);
    if (server.headers) {
      console.log("  Headers:");
      for (const [key, value] of Object.entries(server.headers)) {
        console.log(`    ${key}: ${value}`);
      }
    }
    if (server.oauth?.clientId || server.oauth?.callbackPort) {
      const parts = [];
      if (server.oauth.clientId) {
        parts.push("client_id configured");
        const clientConfig = getMcpClientConfig(name, server);
        if (clientConfig?.clientSecret)
          parts.push("client_secret configured");
      }
      if (server.oauth.callbackPort)
        parts.push(`callback_port ${server.oauth.callbackPort}`);
      console.log(`  OAuth: ${parts.join(", ")}`);
    }
  } else if (server.type === "stdio") {
    console.log(`  Type: stdio`);
    console.log(`  Command: ${server.command}`);
    const args = Array.isArray(server.args) ? server.args : [];
    console.log(`  Args: ${args.join(" ")}`);
    if (server.env) {
      console.log("  Environment:");
      for (const [key, value] of Object.entries(server.env)) {
        console.log(`    ${key}=${value}`);
      }
    }
  }
  console.log(`
To remove this server, run: claude mcp remove "${name}" -s ${server.scope}`);
  await gracefulShutdown(0);
}
async function mcpAddJsonHandler(name, json, options) {
  try {
    const scope = ensureConfigScope(options.scope);
    const parsedJson = safeParseJSON(json);
    const needsSecret = options.clientSecret && parsedJson && typeof parsedJson === "object" && "type" in parsedJson && (parsedJson.type === "sse" || parsedJson.type === "http") && "url" in parsedJson && typeof parsedJson.url === "string" && "oauth" in parsedJson && parsedJson.oauth && typeof parsedJson.oauth === "object" && "clientId" in parsedJson.oauth;
    const clientSecret = needsSecret ? await readClientSecret() : undefined;
    await addMcpConfig(name, parsedJson, scope);
    const transportType = parsedJson && typeof parsedJson === "object" && "type" in parsedJson ? String(parsedJson.type || "stdio") : "stdio";
    if (clientSecret && parsedJson && typeof parsedJson === "object" && "type" in parsedJson && (parsedJson.type === "sse" || parsedJson.type === "http") && "url" in parsedJson && typeof parsedJson.url === "string") {
      saveMcpClientSecret(name, { type: parsedJson.type, url: parsedJson.url }, clientSecret);
    }
    logEvent("tengu_mcp_add", {
      scope,
      source: "json",
      type: transportType
    });
    cliOk(`Added ${transportType} MCP server ${name} to ${scope} config`);
  } catch (error) {
    cliError(error.message);
  }
}
async function mcpAddFromDesktopHandler(options) {
  try {
    const scope = ensureConfigScope(options.scope);
    const platform = getPlatform();
    logEvent("tengu_mcp_add", {
      scope,
      platform,
      source: "desktop"
    });
    const { readClaudeDesktopMcpServers } = await import("./chunk-z00w7552.js");
    const servers = await readClaudeDesktopMcpServers();
    if (Object.keys(servers).length === 0) {
      cliOk("No MCP servers found in Claude Desktop configuration or configuration file does not exist.");
    }
    const { unmount } = await root_default(/* @__PURE__ */ jsx_runtime2.jsx(AppStateProvider, {
      children: /* @__PURE__ */ jsx_runtime2.jsx(KeybindingSetup, {
        children: /* @__PURE__ */ jsx_runtime2.jsx(MCPServerDesktopImportDialog, {
          servers,
          scope,
          onDone: () => {
            unmount();
          }
        })
      })
    }), { exitOnCtrlC: true });
  } catch (error) {
    cliError(error.message);
  }
}
async function mcpResetChoicesHandler() {
  logEvent("tengu_mcp_reset_mcpjson_choices", {});
  saveCurrentProjectConfig((current) => ({
    ...current,
    enabledMcpjsonServers: [],
    disabledMcpjsonServers: [],
    enableAllProjectMcpServers: false
  }));
  cliOk(`All project-scoped (.mcp.json) server approvals and rejections have been reset.
You will be prompted for approval next time you start Chris Code.`);
}
export {
  mcpServeHandler,
  mcpResetChoicesHandler,
  mcpRemoveHandler,
  mcpListHandler,
  mcpGetHandler,
  mcpAddJsonHandler,
  mcpAddFromDesktopHandler
};

//# debugId=9093D643311B206764756E2164756E21
//# sourceMappingURL=chunk-1axrabwp.js.map
