// @bun
import {
  MCPRemoteServerMenu,
  MCPStdioServerMenu,
  MCPToolDetailView,
  MCPToolListView,
  PluginSettings,
  init_MCPRemoteServerMenu,
  init_MCPStdioServerMenu,
  init_MCPToolDetailView,
  init_MCPToolListView,
  init_PluginSettings
} from "./chunk-grcc3hvf.js";
import"./chunk-ezf40808.js";
import {
  init_MCPConnectionManager,
  useMcpReconnect,
  useMcpToggleEnabled
} from "./chunk-ymqv4hyz.js";
import"./chunk-4e3x31c9.js";
import"./chunk-gmrghcqg.js";
import"./chunk-0z13a78r.js";
import"./chunk-6gt42kvj.js";
import"./chunk-3apkj8j9.js";
import {
  McpParsingWarnings,
  init_McpParsingWarnings
} from "./chunk-467w66fx.js";
import"./chunk-awgdfggg.js";
import"./chunk-ned5qknr.js";
import {
  AuthenticationCancelledError,
  ClaudeAuthProvider,
  ConfigurableShortcutHint,
  Select,
  Spinner,
  describeMcpConfigFilePath,
  extractAgentMcpServers,
  filterToolsByServer,
  init_AppState,
  init_ConfigurableShortcutHint,
  init_CustomSelect,
  init_Spinner,
  init_auth,
  init_utils,
  performMCPOAuthFlow,
  useAppState,
  useAppStateStore
} from "./chunk-421yegj3.js";
import"./chunk-aaxz8a5g.js";
import"./chunk-2kcgxnvp.js";
import"./chunk-14p6wvsq.js";
import"./chunk-6s0q1s5r.js";
import"./chunk-0cpg8qh8.js";
import {
  getSessionIngressAuthToken,
  init_sessionIngressAuth
} from "./chunk-9phn5khx.js";
import"./chunk-vk9xcryd.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-7fcmqvbz.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-q3b4n194.js";
import"./chunk-zaqfb3tz.js";
import"./chunk-6hzx0kqr.js";
import"./chunk-71sdcaq6.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-dxa3y9vh.js";
import"./chunk-gjvhjywj.js";
import"./chunk-1w20m7gw.js";
import"./chunk-3gam18xn.js";
import"./chunk-rpmntgyh.js";
import"./chunk-24kv69g3.js";
import"./chunk-tzcrwnrf.js";
import"./chunk-k7xszak2.js";
import"./chunk-ztmb7geg.js";
import"./chunk-tbdkekz3.js";
import {
  init_useKeybinding
} from "./chunk-65zbgg1n.js";
import"./chunk-4spgkgr3.js";
import"./chunk-60fkafk2.js";
import"./chunk-h5zz0vxy.js";
import"./chunk-6hygvrhn.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-8gv2pjby.js";
import"./chunk-pn23dh3d.js";
import"./chunk-rpdh02rm.js";
import"./chunk-j1wktfe2.js";
import"./chunk-fjtzfz1t.js";
import"./chunk-6hr7742d.js";
import"./chunk-xyg1sk2w.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-hem4f4gz.js";
import"./chunk-hqxp6b72.js";
import"./chunk-ccw8pse0.js";
import"./chunk-wsnxtggw.js";
import"./chunk-k8nwt8yq.js";
import"./chunk-vxbjzggp.js";
import"./chunk-d6h68rz1.js";
import"./chunk-8yvsnrkr.js";
import"./chunk-5mmhfbxb.js";
import {
  capitalize,
  init_stringUtils,
  plural
} from "./chunk-s2t5anwv.js";
import"./chunk-ga1jkyqy.js";
import"./chunk-9hbhydvp.js";
import"./chunk-ck9r8hpf.js";
import"./chunk-k7hexw3v.js";
import"./chunk-trqrj23e.js";
import"./chunk-za3k6h2h.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-hjxqmtg5.js";
import"./chunk-bzyzrq0k.js";
import"./chunk-vwenx8ke.js";
import"./chunk-q2h79ncs.js";
import"./chunk-v4ypszbb.js";
import"./chunk-qfsn720k.js";
import"./chunk-7qx3xhv3.js";
import"./chunk-j9475b46.js";
import"./chunk-fdwabr8p.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-dbts5q5p.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-q1vrhh0q.js";
import"./chunk-hn4w9pkj.js";
import {
  Byline,
  Dialog,
  KeyboardShortcutHint,
  Link,
  ThemedBox_default,
  ThemedText,
  color,
  init_src,
  useKeybinding,
  useKeybindings,
  useTheme
} from "./chunk-2g0ytd9d.js";
import {
  require_jsx_dev_runtime,
  require_react
} from "./chunk-de0qnnf7.js";
import"./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-92bjkrf2.js";
import"./chunk-10k5jfc5.js";
import"./chunk-n9g24mwe.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-hzmzwte2.js";
import"./chunk-pdvg91cg.js";
import"./chunk-c696122m.js";
import"./chunk-xbj5keyy.js";
import"./chunk-c1yc761e.js";
import {
  figures_default,
  init_figures
} from "./chunk-c5g9shkw.js";
import"./chunk-aeysytks.js";
import {
  init_debug,
  isDebugMode
} from "./chunk-s3hafnk3.js";
import"./chunk-kb3758f7.js";
import"./chunk-9h9k5vz3.js";
import"./chunk-xmpgmeb8.js";
import"./chunk-2kz09j2s.js";
import"./chunk-c0k7b0jw.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __esm,
  __toESM
} from "./chunk-hhsxm2yr.js";

// src/components/mcp/MCPAgentServerMenu.tsx
function MCPAgentServerMenu({ agentServer, onCancel, onComplete }) {
  const [theme] = useTheme();
  const [isAuthenticating, setIsAuthenticating] = import_react.useState(false);
  const [error, setError] = import_react.useState(null);
  const [authorizationUrl, setAuthorizationUrl] = import_react.useState(null);
  const authAbortControllerRef = import_react.useRef(null);
  import_react.useEffect(() => () => authAbortControllerRef.current?.abort(), []);
  const handleEscCancel = import_react.useCallback(() => {
    if (isAuthenticating) {
      authAbortControllerRef.current?.abort();
      authAbortControllerRef.current = null;
      setIsAuthenticating(false);
      setAuthorizationUrl(null);
    }
  }, [isAuthenticating]);
  useKeybinding("confirm:no", handleEscCancel, {
    context: "Confirmation",
    isActive: isAuthenticating
  });
  const handleAuthenticate = import_react.useCallback(async () => {
    if (!agentServer.needsAuth || !agentServer.url) {
      return;
    }
    setIsAuthenticating(true);
    setError(null);
    const controller = new AbortController;
    authAbortControllerRef.current = controller;
    try {
      const tempConfig = {
        type: agentServer.transport,
        url: agentServer.url
      };
      await performMCPOAuthFlow(agentServer.name, tempConfig, setAuthorizationUrl, controller.signal);
      onComplete?.(`Authentication successful for ${agentServer.name}. The server will connect when the agent runs.`);
    } catch (err) {
      if (err instanceof Error && !(err instanceof AuthenticationCancelledError)) {
        setError(err.message);
      }
    } finally {
      setIsAuthenticating(false);
      authAbortControllerRef.current = null;
    }
  }, [agentServer, onComplete]);
  const capitalizedServerName = capitalize(String(agentServer.name));
  if (isAuthenticating) {
    return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
      flexDirection: "column",
      gap: 1,
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
          color: "claude",
          children: [
            "Authenticating with ",
            agentServer.name,
            "\u2026"
          ]
        }, undefined, true, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
          children: [
            /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Spinner, {}, undefined, false, undefined, this),
            /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
              children: " A browser window will open for authentication"
            }, undefined, false, undefined, this)
          ]
        }, undefined, true, undefined, this),
        authorizationUrl && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
          flexDirection: "column",
          children: [
            /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
              dimColor: true,
              children: "If your browser doesn't open automatically, copy this URL manually:"
            }, undefined, false, undefined, this),
            /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Link, {
              url: authorizationUrl
            }, undefined, false, undefined, this)
          ]
        }, undefined, true, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
          marginLeft: 3,
          children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
            dimColor: true,
            children: [
              "Return here after authenticating in your browser.",
              " ",
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ConfigurableShortcutHint, {
                action: "confirm:no",
                context: "Confirmation",
                fallback: "Esc",
                description: "go back"
              }, undefined, false, undefined, this)
            ]
          }, undefined, true, undefined, this)
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this);
  }
  const menuOptions = [];
  if (agentServer.needsAuth) {
    menuOptions.push({
      label: agentServer.isAuthenticated ? "Re-authenticate" : "Authenticate",
      value: "auth"
    });
  }
  menuOptions.push({
    label: "Back",
    value: "back"
  });
  return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Dialog, {
    title: `${capitalizedServerName} MCP Server`,
    subtitle: "agent-only",
    onCancel,
    inputGuide: (exitState) => exitState.pending ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
      children: [
        "Press ",
        exitState.keyName,
        " again to exit"
      ]
    }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Byline, {
      children: [
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(KeyboardShortcutHint, {
          shortcut: "\u2191\u2193",
          action: "navigate"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(KeyboardShortcutHint, {
          shortcut: "Enter",
          action: "confirm"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ConfigurableShortcutHint, {
          action: "confirm:no",
          context: "Confirmation",
          fallback: "Esc",
          description: "go back"
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    children: [
      /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
        flexDirection: "column",
        gap: 0,
        children: [
          /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                bold: true,
                children: "Type: "
              }, undefined, false, undefined, this),
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                dimColor: true,
                children: agentServer.transport
              }, undefined, false, undefined, this)
            ]
          }, undefined, true, undefined, this),
          agentServer.url && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                bold: true,
                children: "URL: "
              }, undefined, false, undefined, this),
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                dimColor: true,
                children: agentServer.url
              }, undefined, false, undefined, this)
            ]
          }, undefined, true, undefined, this),
          agentServer.command && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                bold: true,
                children: "Command: "
              }, undefined, false, undefined, this),
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                dimColor: true,
                children: agentServer.command
              }, undefined, false, undefined, this)
            ]
          }, undefined, true, undefined, this),
          /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                bold: true,
                children: "Used by: "
              }, undefined, false, undefined, this),
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                dimColor: true,
                children: agentServer.sourceAgents.join(", ")
              }, undefined, false, undefined, this)
            ]
          }, undefined, true, undefined, this),
          /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
            marginTop: 1,
            children: [
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                bold: true,
                children: "Status: "
              }, undefined, false, undefined, this),
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                children: [
                  color("inactive", theme)(figures_default.radioOff),
                  " not connected (agent-only)"
                ]
              }, undefined, true, undefined, this)
            ]
          }, undefined, true, undefined, this),
          agentServer.needsAuth && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                bold: true,
                children: "Auth: "
              }, undefined, false, undefined, this),
              agentServer.isAuthenticated ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                children: [
                  color("success", theme)(figures_default.tick),
                  " authenticated"
                ]
              }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
                children: [
                  color("warning", theme)(figures_default.triangleUpOutline),
                  " may need authentication"
                ]
              }, undefined, true, undefined, this)
            ]
          }, undefined, true, undefined, this)
        ]
      }, undefined, true, undefined, this),
      /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
          dimColor: true,
          children: "This server connects only when running the agent."
        }, undefined, false, undefined, this)
      }, undefined, false, undefined, this),
      error && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
          color: "error",
          children: [
            "Error: ",
            error
          ]
        }, undefined, true, undefined, this)
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Select, {
          options: menuOptions,
          onChange: async (value) => {
            switch (value) {
              case "auth":
                await handleAuthenticate();
                break;
              case "back":
                onCancel();
                break;
            }
          },
          onCancel
        }, undefined, false, undefined, this)
      }, undefined, false, undefined, this)
    ]
  }, undefined, true, undefined, this);
}
var import_react, jsx_dev_runtime;
var init_MCPAgentServerMenu = __esm(() => {
  init_figures();
  init_src();
  init_useKeybinding();
  init_auth();
  init_stringUtils();
  init_ConfigurableShortcutHint();
  init_CustomSelect();
  init_src();
  init_Spinner();
  import_react = __toESM(require_react(), 1);
  jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1);
});

// src/components/mcp/MCPListPanel.tsx
function getScopeHeading(scope) {
  switch (scope) {
    case "project":
      return { label: "Project MCPs", path: describeMcpConfigFilePath(scope) };
    case "user":
      return { label: "User MCPs", path: describeMcpConfigFilePath(scope) };
    case "local":
      return { label: "Local MCPs", path: describeMcpConfigFilePath(scope) };
    case "enterprise":
      return { label: "Enterprise MCPs" };
    case "dynamic":
      return { label: "Built-in MCPs", path: "always available" };
    default:
      return { label: scope };
  }
}
function groupServersByScope(serverList) {
  const groups = new Map;
  for (const server of serverList) {
    const scope = server.scope;
    if (!groups.has(scope)) {
      groups.set(scope, []);
    }
    groups.get(scope).push(server);
  }
  for (const [, groupServers] of groups) {
    groupServers.sort((a, b) => a.name.localeCompare(b.name));
  }
  return groups;
}
function MCPListPanel({
  servers,
  agentServers = [],
  onSelectServer,
  onSelectAgentServer,
  onComplete
}) {
  const [theme] = useTheme();
  const [selectedIndex, setSelectedIndex] = import_react2.useState(0);
  const serversByScope = import_react2.default.useMemo(() => {
    const regularServers = servers.filter((s) => s.client.config.type !== "claudeai-proxy");
    return groupServersByScope(regularServers);
  }, [servers]);
  const claudeAiServers = import_react2.default.useMemo(() => servers.filter((s) => s.client.config.type === "claudeai-proxy").sort((a, b) => a.name.localeCompare(b.name)), [servers]);
  const dynamicServers = import_react2.default.useMemo(() => (serversByScope.get("dynamic") ?? []).sort((a, b) => a.name.localeCompare(b.name)), [serversByScope]);
  const dynamicHeading = getScopeHeading("dynamic");
  const selectableItems = import_react2.default.useMemo(() => {
    const items = [];
    for (const scope of SCOPE_ORDER) {
      const scopeServers = serversByScope.get(scope) ?? [];
      for (const server of scopeServers) {
        items.push({ type: "server", server });
      }
    }
    for (const server of claudeAiServers) {
      items.push({ type: "server", server });
    }
    for (const agentServer of agentServers) {
      items.push({ type: "agent-server", agentServer });
    }
    for (const server of dynamicServers) {
      items.push({ type: "server", server });
    }
    return items;
  }, [serversByScope, claudeAiServers, agentServers, dynamicServers]);
  const handleCancel = import_react2.useCallback(() => {
    onComplete("MCP dialog dismissed", {
      display: "system"
    });
  }, [onComplete]);
  const handleSelect = import_react2.useCallback(() => {
    const item = selectableItems[selectedIndex];
    if (!item)
      return;
    if (item.type === "server") {
      onSelectServer(item.server);
    } else if (item.type === "agent-server" && onSelectAgentServer) {
      onSelectAgentServer(item.agentServer);
    }
  }, [selectableItems, selectedIndex, onSelectServer, onSelectAgentServer]);
  useKeybindings({
    "confirm:previous": () => setSelectedIndex((prev) => prev === 0 ? selectableItems.length - 1 : prev - 1),
    "confirm:next": () => setSelectedIndex((prev) => prev === selectableItems.length - 1 ? 0 : prev + 1),
    "confirm:yes": handleSelect,
    "confirm:no": handleCancel
  }, { context: "Confirmation" });
  const getServerIndex = (server) => {
    return selectableItems.findIndex((item) => item.type === "server" && item.server === server);
  };
  const getAgentServerIndex = (agentServer) => {
    return selectableItems.findIndex((item) => item.type === "agent-server" && item.agentServer === agentServer);
  };
  const debugMode = isDebugMode();
  const hasFailedClients = servers.some((s) => s.client.type === "failed");
  if (servers.length === 0 && agentServers.length === 0) {
    return null;
  }
  const renderServerItem = (server) => {
    const index = getServerIndex(server);
    const isSelected = selectedIndex === index;
    let statusIcon = "";
    let statusText = "";
    if (server.client.type === "disabled") {
      statusIcon = color("inactive", theme)(figures_default.radioOff);
      statusText = "disabled";
    } else if (server.client.type === "connected") {
      statusIcon = color("success", theme)(figures_default.tick);
      statusText = "connected";
    } else if (server.client.type === "pending") {
      statusIcon = color("inactive", theme)(figures_default.radioOff);
      const { reconnectAttempt, maxReconnectAttempts } = server.client;
      if (reconnectAttempt && maxReconnectAttempts) {
        statusText = `reconnecting (${reconnectAttempt}/${maxReconnectAttempts})\u2026`;
      } else {
        statusText = "connecting\u2026";
      }
    } else if (server.client.type === "needs-auth") {
      statusIcon = color("warning", theme)(figures_default.triangleUpOutline);
      statusText = "needs authentication";
    } else {
      statusIcon = color("error", theme)(figures_default.cross);
      statusText = "failed";
    }
    return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
      children: [
        /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          color: isSelected ? "suggestion" : undefined,
          children: isSelected ? `${figures_default.pointer} ` : "  "
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          color: isSelected ? "suggestion" : undefined,
          children: server.name
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          dimColor: !isSelected,
          children: [
            " \xB7 ",
            statusIcon,
            " "
          ]
        }, undefined, true, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          dimColor: !isSelected,
          children: statusText
        }, undefined, false, undefined, this)
      ]
    }, `${server.name}-${index}`, true, undefined, this);
  };
  const renderAgentServerItem = (agentServer) => {
    const index = getAgentServerIndex(agentServer);
    const isSelected = selectedIndex === index;
    const statusIcon = agentServer.needsAuth ? color("warning", theme)(figures_default.triangleUpOutline) : color("inactive", theme)(figures_default.radioOff);
    const statusText = agentServer.needsAuth ? "may need auth" : "agent-only";
    return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
      children: [
        /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          color: isSelected ? "suggestion" : undefined,
          children: isSelected ? `${figures_default.pointer} ` : "  "
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          color: isSelected ? "suggestion" : undefined,
          children: agentServer.name
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          dimColor: !isSelected,
          children: [
            " \xB7 ",
            statusIcon,
            " "
          ]
        }, undefined, true, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          dimColor: !isSelected,
          children: statusText
        }, undefined, false, undefined, this)
      ]
    }, `agent-${agentServer.name}-${index}`, true, undefined, this);
  };
  const totalServers = servers.length + agentServers.length;
  return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
    flexDirection: "column",
    children: [
      /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(McpParsingWarnings, {}, undefined, false, undefined, this),
      /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(Dialog, {
        title: "Manage MCP servers",
        subtitle: `${totalServers} ${plural(totalServers, "server")}`,
        onCancel: handleCancel,
        hideInputGuide: true,
        children: /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
          flexDirection: "column",
          children: [
            SCOPE_ORDER.map((scope) => {
              const scopeServers = serversByScope.get(scope);
              if (!scopeServers || scopeServers.length === 0)
                return null;
              const heading = getScopeHeading(scope);
              return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
                flexDirection: "column",
                marginBottom: 1,
                children: [
                  /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
                    paddingLeft: 2,
                    children: [
                      /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                        bold: true,
                        children: heading.label
                      }, undefined, false, undefined, this),
                      heading.path && /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                        dimColor: true,
                        children: [
                          " (",
                          heading.path,
                          ")"
                        ]
                      }, undefined, true, undefined, this)
                    ]
                  }, undefined, true, undefined, this),
                  scopeServers.map((server) => renderServerItem(server))
                ]
              }, scope, true, undefined, this);
            }),
            claudeAiServers.length > 0 && /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
              flexDirection: "column",
              marginBottom: 1,
              children: [
                /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
                  paddingLeft: 2,
                  children: /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                    bold: true,
                    children: "claude.ai"
                  }, undefined, false, undefined, this)
                }, undefined, false, undefined, this),
                claudeAiServers.map((server) => renderServerItem(server))
              ]
            }, undefined, true, undefined, this),
            agentServers.length > 0 && /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
              flexDirection: "column",
              marginBottom: 1,
              children: [
                /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
                  paddingLeft: 2,
                  children: /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                    bold: true,
                    children: "Agent MCPs"
                  }, undefined, false, undefined, this)
                }, undefined, false, undefined, this),
                [...new Set(agentServers.flatMap((s) => s.sourceAgents))].map((agentName) => /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
                  flexDirection: "column",
                  marginTop: 1,
                  children: [
                    /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
                      paddingLeft: 2,
                      children: /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                        dimColor: true,
                        children: [
                          "@",
                          agentName
                        ]
                      }, undefined, true, undefined, this)
                    }, undefined, false, undefined, this),
                    agentServers.filter((s) => s.sourceAgents.includes(agentName)).map((agentServer) => renderAgentServerItem(agentServer))
                  ]
                }, agentName, true, undefined, this))
              ]
            }, undefined, true, undefined, this),
            dynamicServers.length > 0 && /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
              flexDirection: "column",
              marginBottom: 1,
              children: [
                /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
                  paddingLeft: 2,
                  children: [
                    /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                      bold: true,
                      children: dynamicHeading.label
                    }, undefined, false, undefined, this),
                    dynamicHeading.path && /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                      dimColor: true,
                      children: [
                        " (",
                        dynamicHeading.path,
                        ")"
                      ]
                    }, undefined, true, undefined, this)
                  ]
                }, undefined, true, undefined, this),
                dynamicServers.map((server) => renderServerItem(server))
              ]
            }, undefined, true, undefined, this),
            /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
              flexDirection: "column",
              children: [
                hasFailedClients && /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                  dimColor: true,
                  children: debugMode ? "\u203B Error logs shown inline with --debug" : "\u203B Run redscope --debug to see error logs"
                }, undefined, false, undefined, this),
                /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
                  dimColor: true,
                  children: [
                    /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(Link, {
                      url: "https://code.claude.com/docs/en/mcp",
                      children: "https://code.claude.com/docs/en/mcp"
                    }, undefined, false, undefined, this),
                    " for help"
                  ]
                }, undefined, true, undefined, this)
              ]
            }, undefined, true, undefined, this)
          ]
        }, undefined, true, undefined, this)
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedBox_default, {
        paddingX: 1,
        children: /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ThemedText, {
          dimColor: true,
          italic: true,
          children: /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(Byline, {
            children: [
              /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(KeyboardShortcutHint, {
                shortcut: "\u2191\u2193",
                action: "navigate"
              }, undefined, false, undefined, this),
              /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(KeyboardShortcutHint, {
                shortcut: "Enter",
                action: "confirm"
              }, undefined, false, undefined, this),
              /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ConfigurableShortcutHint, {
                action: "confirm:no",
                context: "Confirmation",
                fallback: "Esc",
                description: "cancel"
              }, undefined, false, undefined, this)
            ]
          }, undefined, true, undefined, this)
        }, undefined, false, undefined, this)
      }, undefined, false, undefined, this)
    ]
  }, undefined, true, undefined, this);
}
var import_react2, jsx_dev_runtime2, SCOPE_ORDER;
var init_MCPListPanel = __esm(() => {
  init_figures();
  init_src();
  init_useKeybinding();
  init_utils();
  init_debug();
  init_stringUtils();
  init_ConfigurableShortcutHint();
  init_src();
  init_McpParsingWarnings();
  import_react2 = __toESM(require_react(), 1);
  jsx_dev_runtime2 = __toESM(require_jsx_dev_runtime(), 1);
  SCOPE_ORDER = ["project", "local", "user", "enterprise"];
});

// src/components/mcp/MCPReconnect.tsx
function MCPReconnect({ serverName, onComplete }) {
  const [theme] = useTheme();
  const store = useAppStateStore();
  const reconnectMcpServer = useMcpReconnect();
  const [isReconnecting, setIsReconnecting] = import_react3.useState(true);
  const [error, setError] = import_react3.useState(null);
  import_react3.useEffect(() => {
    async function attemptReconnect() {
      try {
        const server = store.getState().mcp.clients.find((c) => c.name === serverName);
        if (!server) {
          setError(`MCP server "${serverName}" not found`);
          setIsReconnecting(false);
          onComplete(`MCP server "${serverName}" not found`);
          return;
        }
        const result = await reconnectMcpServer(serverName);
        switch (result.client.type) {
          case "connected":
            setIsReconnecting(false);
            onComplete(`Successfully reconnected to ${serverName}`);
            break;
          case "needs-auth":
            setError(`${serverName} requires authentication`);
            setIsReconnecting(false);
            onComplete(`${serverName} requires authentication. Use /mcp to authenticate.`);
            break;
          case "pending":
          case "failed":
          case "disabled":
            setError(`Failed to reconnect to ${serverName}`);
            setIsReconnecting(false);
            onComplete(`Failed to reconnect to ${serverName}`);
            break;
        }
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        setError(errorMessage);
        setIsReconnecting(false);
        onComplete(`Error: ${errorMessage}`);
      }
    }
    attemptReconnect();
  }, [serverName, reconnectMcpServer, store, onComplete]);
  if (isReconnecting) {
    return /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedBox_default, {
      flexDirection: "column",
      gap: 1,
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedText, {
          color: "text",
          children: [
            "Reconnecting to ",
            /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedText, {
              bold: true,
              children: serverName
            }, undefined, false, undefined, this)
          ]
        }, undefined, true, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedBox_default, {
          children: [
            /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(Spinner, {}, undefined, false, undefined, this),
            /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedText, {
              children: " Establishing connection to MCP server"
            }, undefined, false, undefined, this)
          ]
        }, undefined, true, undefined, this)
      ]
    }, undefined, true, undefined, this);
  }
  if (error) {
    return /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedBox_default, {
      flexDirection: "column",
      gap: 1,
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedBox_default, {
          children: [
            /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedText, {
              children: [
                color("error", theme)(figures_default.cross),
                " "
              ]
            }, undefined, true, undefined, this),
            /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedText, {
              color: "error",
              children: [
                "Failed to reconnect to ",
                serverName
              ]
            }, undefined, true, undefined, this)
          ]
        }, undefined, true, undefined, this),
        /* @__PURE__ */ jsx_dev_runtime3.jsxDEV(ThemedText, {
          dimColor: true,
          children: [
            "Error: ",
            error
          ]
        }, undefined, true, undefined, this)
      ]
    }, undefined, true, undefined, this);
  }
  return null;
}
var import_react3, jsx_dev_runtime3;
var init_MCPReconnect = __esm(() => {
  init_figures();
  init_src();
  init_MCPConnectionManager();
  init_AppState();
  init_Spinner();
  import_react3 = __toESM(require_react(), 1);
  jsx_dev_runtime3 = __toESM(require_jsx_dev_runtime(), 1);
});

// src/components/mcp/MCPSettings.tsx
function MCPSettings({ onComplete }) {
  const mcp = useAppState((s) => s.mcp);
  const agentDefinitions = useAppState((s) => s.agentDefinitions);
  const mcpClients = mcp.clients;
  const [viewState, setViewState] = import_react4.default.useState({
    type: "list"
  });
  const [servers, setServers] = import_react4.default.useState([]);
  const agentMcpServers = import_react4.useMemo(() => extractAgentMcpServers(agentDefinitions.allAgents), [agentDefinitions.allAgents]);
  const filteredClients = import_react4.default.useMemo(() => mcpClients.filter((client) => client.name !== "ide").sort((a, b) => a.name.localeCompare(b.name)), [mcpClients]);
  import_react4.default.useEffect(() => {
    let cancelled = false;
    async function prepareServers() {
      const serverInfos = await Promise.all(filteredClients.map(async (client) => {
        const scope = client.config.scope;
        const isSSE = client.config.type === "sse";
        const isHTTP = client.config.type === "http";
        const isClaudeAIProxy = client.config.type === "claudeai-proxy";
        let isAuthenticated;
        if (isSSE || isHTTP) {
          const authProvider = new ClaudeAuthProvider(client.name, client.config);
          const tokens = await authProvider.tokens();
          const hasSessionAuth = getSessionIngressAuthToken() !== null && client.type === "connected";
          const hasToolsAndConnected = client.type === "connected" && filterToolsByServer(mcp.tools, client.name).length > 0;
          isAuthenticated = Boolean(tokens) || hasSessionAuth || hasToolsAndConnected;
        }
        const baseInfo = {
          name: client.name,
          client,
          scope
        };
        if (isClaudeAIProxy) {
          return {
            ...baseInfo,
            transport: "claudeai-proxy",
            isAuthenticated: false,
            config: client.config
          };
        } else if (isSSE) {
          return {
            ...baseInfo,
            transport: "sse",
            isAuthenticated,
            config: client.config
          };
        } else if (isHTTP) {
          return {
            ...baseInfo,
            transport: "http",
            isAuthenticated,
            config: client.config
          };
        } else {
          return {
            ...baseInfo,
            transport: "stdio",
            config: client.config
          };
        }
      }));
      if (cancelled)
        return;
      setServers(serverInfos);
    }
    prepareServers();
    return () => {
      cancelled = true;
    };
  }, [filteredClients, mcp.tools]);
  import_react4.useEffect(() => {
    if (servers.length === 0 && filteredClients.length > 0) {
      return;
    }
    if (servers.length === 0 && agentMcpServers.length === 0) {
      onComplete("No MCP servers configured. Please run /doctor if this is unexpected. Otherwise, run `redscope mcp --help` or visit https://code.claude.com/docs/en/mcp to learn more.");
    }
  }, [servers.length, filteredClients.length, agentMcpServers.length, onComplete]);
  switch (viewState.type) {
    case "list":
      return /* @__PURE__ */ jsx_dev_runtime4.jsxDEV(MCPListPanel, {
        servers,
        agentServers: agentMcpServers,
        onSelectServer: (server) => setViewState({ type: "server-menu", server }),
        onSelectAgentServer: (agentServer) => setViewState({ type: "agent-server-menu", agentServer }),
        onComplete,
        defaultTab: viewState.defaultTab
      }, undefined, false, undefined, this);
    case "server-menu": {
      const serverTools = filterToolsByServer(mcp.tools, viewState.server.name);
      const defaultTab = viewState.server.transport === "claudeai-proxy" ? "claude.ai" : "RedScope AI";
      if (viewState.server.transport === "stdio") {
        return /* @__PURE__ */ jsx_dev_runtime4.jsxDEV(MCPStdioServerMenu, {
          server: viewState.server,
          serverToolsCount: serverTools.length,
          onViewTools: () => setViewState({ type: "server-tools", server: viewState.server }),
          onCancel: () => setViewState({ type: "list", defaultTab }),
          onComplete
        }, undefined, false, undefined, this);
      } else {
        return /* @__PURE__ */ jsx_dev_runtime4.jsxDEV(MCPRemoteServerMenu, {
          server: viewState.server,
          serverToolsCount: serverTools.length,
          onViewTools: () => setViewState({ type: "server-tools", server: viewState.server }),
          onCancel: () => setViewState({ type: "list", defaultTab }),
          onComplete
        }, undefined, false, undefined, this);
      }
    }
    case "server-tools":
      return /* @__PURE__ */ jsx_dev_runtime4.jsxDEV(MCPToolListView, {
        server: viewState.server,
        onSelectTool: (_, index) => setViewState({
          type: "server-tool-detail",
          server: viewState.server,
          toolIndex: index
        }),
        onBack: () => setViewState({ type: "server-menu", server: viewState.server })
      }, undefined, false, undefined, this);
    case "server-tool-detail": {
      const serverTools = filterToolsByServer(mcp.tools, viewState.server.name);
      const tool = serverTools[viewState.toolIndex];
      if (!tool) {
        setViewState({ type: "server-tools", server: viewState.server });
        return null;
      }
      return /* @__PURE__ */ jsx_dev_runtime4.jsxDEV(MCPToolDetailView, {
        tool,
        server: viewState.server,
        onBack: () => setViewState({ type: "server-tools", server: viewState.server })
      }, undefined, false, undefined, this);
    }
    case "agent-server-menu":
      return /* @__PURE__ */ jsx_dev_runtime4.jsxDEV(MCPAgentServerMenu, {
        agentServer: viewState.agentServer,
        onCancel: () => setViewState({ type: "list", defaultTab: "Agents" }),
        onComplete
      }, undefined, false, undefined, this);
  }
}
var import_react4, jsx_dev_runtime4;
var init_MCPSettings = __esm(() => {
  init_auth();
  init_utils();
  init_AppState();
  init_sessionIngressAuth();
  init_MCPAgentServerMenu();
  init_MCPListPanel();
  init_MCPRemoteServerMenu();
  init_MCPStdioServerMenu();
  init_MCPToolDetailView();
  init_MCPToolListView();
  import_react4 = __toESM(require_react(), 1);
  jsx_dev_runtime4 = __toESM(require_jsx_dev_runtime(), 1);
});

// src/components/mcp/index.ts
var init_mcp = __esm(() => {
  init_MCPAgentServerMenu();
  init_MCPListPanel();
  init_MCPReconnect();
  init_MCPRemoteServerMenu();
  init_MCPSettings();
  init_MCPStdioServerMenu();
  init_MCPToolDetailView();
  init_MCPToolListView();
});

// src/commands/mcp/mcp.tsx
function MCPToggle({
  action,
  target,
  onComplete
}) {
  const mcpClients = useAppState((s) => s.mcp.clients);
  const toggleMcpServer = useMcpToggleEnabled();
  const didRun = import_react5.useRef(false);
  import_react5.useEffect(() => {
    if (didRun.current)
      return;
    didRun.current = true;
    const isEnabling = action === "enable";
    const clients = mcpClients.filter((c) => c.name !== "ide");
    const toToggle = target === "all" ? clients.filter((c) => isEnabling ? c.type === "disabled" : c.type !== "disabled") : clients.filter((c) => c.name === target);
    if (toToggle.length === 0) {
      onComplete(target === "all" ? `All MCP servers are already ${isEnabling ? "enabled" : "disabled"}` : `MCP server "${target}" not found`);
      return;
    }
    for (const s of toToggle) {
      toggleMcpServer(s.name);
    }
    onComplete(target === "all" ? `${isEnabling ? "Enabled" : "Disabled"} ${toToggle.length} MCP server(s)` : `MCP server "${target}" ${isEnabling ? "enabled" : "disabled"}`);
  }, [action, target, mcpClients, toggleMcpServer, onComplete]);
  return null;
}
async function call(onDone, _context, args) {
  if (args) {
    const parts = args.trim().split(/\s+/);
    if (parts[0] === "no-redirect") {
      return /* @__PURE__ */ jsx_dev_runtime5.jsxDEV(MCPSettings, {
        onComplete: onDone
      }, undefined, false, undefined, this);
    }
    if (parts[0] === "reconnect" && parts[1]) {
      return /* @__PURE__ */ jsx_dev_runtime5.jsxDEV(MCPReconnect, {
        serverName: parts.slice(1).join(" "),
        onComplete: onDone
      }, undefined, false, undefined, this);
    }
    if (parts[0] === "enable" || parts[0] === "disable") {
      return /* @__PURE__ */ jsx_dev_runtime5.jsxDEV(MCPToggle, {
        action: parts[0],
        target: parts.length > 1 ? parts.slice(1).join(" ") : "all",
        onComplete: onDone
      }, undefined, false, undefined, this);
    }
  }
  if (process.env.USER_TYPE === "ant") {
    return /* @__PURE__ */ jsx_dev_runtime5.jsxDEV(PluginSettings, {
      onComplete: onDone,
      args: "manage",
      showMcpRedirectMessage: true
    }, undefined, false, undefined, this);
  }
  return /* @__PURE__ */ jsx_dev_runtime5.jsxDEV(MCPSettings, {
    onComplete: onDone
  }, undefined, false, undefined, this);
}
var import_react5, jsx_dev_runtime5;
var init_mcp2 = __esm(() => {
  init_mcp();
  init_MCPReconnect();
  init_MCPConnectionManager();
  init_AppState();
  init_PluginSettings();
  import_react5 = __toESM(require_react(), 1);
  jsx_dev_runtime5 = __toESM(require_jsx_dev_runtime(), 1);
});
init_mcp2();

export {
  call
};
