// @bun
import {
  MCPRemoteServerMenu,
  MCPStdioServerMenu,
  MCPToolDetailView,
  MCPToolListView,
  PluginSettings,
  init_MCPRemoteServerMenu,
  init_MCPStdioServerMenu,
  init_MCPToolDetailView,
  init_MCPToolListView,
  init_PluginSettings
} from "./chunk-q65fa55y.js";
import"./chunk-6q4sp97q.js";
import {
  init_MCPConnectionManager,
  useMcpReconnect,
  useMcpToggleEnabled
} from "./chunk-7p2w8v1q.js";
import"./chunk-3vx6zzh5.js";
import"./chunk-zpkvp3rx.js";
import"./chunk-mj78e7py.js";
import"./chunk-tpe57t9s.js";
import"./chunk-xye9mn8j.js";
import"./chunk-1xk07zm3.js";
import"./chunk-7h2syxb4.js";
import {
  McpParsingWarnings,
  init_McpParsingWarnings
} from "./chunk-gjgrtgmg.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-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 {
  getSessionIngressAuthToken,
  init_sessionIngressAuth
} from "./chunk-pht800m5.js";
import"./chunk-pjkqh1kq.js";
import"./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 {
  init_useKeybinding
} from "./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 {
  capitalize,
  init_stringUtils,
  plural
} from "./chunk-7rrkrej7.js";
import"./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"./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,
  Link,
  ThemedBox_default,
  ThemedText,
  color,
  init_src,
  require_react,
  useKeybinding,
  useKeybindings,
  useTheme
} from "./chunk-0r6npc3t.js";
import {
  require_jsx_runtime
} from "./chunk-gxyx8b8w.js";
import"./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 {
  figures_default,
  init_figures
} from "./chunk-c5g9shkw.js";
import {
  init_debug,
  isDebugMode
} from "./chunk-byd20vdq.js";
import"./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 {
  __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_runtime.jsxs(ThemedBox_default, {
      flexDirection: "column",
      gap: 1,
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
          color: "claude",
          children: [
            "Authenticating with ",
            agentServer.name,
            "\u2026"
          ]
        }),
        /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
          children: [
            /* @__PURE__ */ jsx_runtime.jsx(Spinner, {}),
            /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              children: " A browser window will open for authentication"
            })
          ]
        }),
        authorizationUrl && /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
          flexDirection: "column",
          children: [
            /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              dimColor: true,
              children: "If your browser doesn't open automatically, copy this URL manually:"
            }),
            /* @__PURE__ */ jsx_runtime.jsx(Link, {
              url: authorizationUrl
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
          marginLeft: 3,
          children: /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
            dimColor: true,
            children: [
              "Return here after authenticating in your browser.",
              " ",
              /* @__PURE__ */ jsx_runtime.jsx(ConfigurableShortcutHint, {
                action: "confirm:no",
                context: "Confirmation",
                fallback: "Esc",
                description: "go back"
              })
            ]
          })
        })
      ]
    });
  }
  const menuOptions = [];
  if (agentServer.needsAuth) {
    menuOptions.push({
      label: agentServer.isAuthenticated ? "Re-authenticate" : "Authenticate",
      value: "auth"
    });
  }
  menuOptions.push({
    label: "Back",
    value: "back"
  });
  return /* @__PURE__ */ jsx_runtime.jsxs(Dialog, {
    title: `${capitalizedServerName} MCP Server`,
    subtitle: "agent-only",
    onCancel,
    inputGuide: (exitState) => exitState.pending ? /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
      children: [
        "Press ",
        exitState.keyName,
        " again to exit"
      ]
    }) : /* @__PURE__ */ jsx_runtime.jsxs(Byline, {
      children: [
        /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
          shortcut: "\u2191\u2193",
          action: "navigate"
        }),
        /* @__PURE__ */ jsx_runtime.jsx(KeyboardShortcutHint, {
          shortcut: "Enter",
          action: "confirm"
        }),
        /* @__PURE__ */ jsx_runtime.jsx(ConfigurableShortcutHint, {
          action: "confirm:no",
          context: "Confirmation",
          fallback: "Esc",
          description: "go back"
        })
      ]
    }),
    children: [
      /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
        flexDirection: "column",
        gap: 0,
        children: [
          /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: "Type: "
              }),
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                dimColor: true,
                children: agentServer.transport
              })
            ]
          }),
          agentServer.url && /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: "URL: "
              }),
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                dimColor: true,
                children: agentServer.url
              })
            ]
          }),
          agentServer.command && /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: "Command: "
              }),
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                dimColor: true,
                children: agentServer.command
              })
            ]
          }),
          /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: "Used by: "
              }),
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                dimColor: true,
                children: agentServer.sourceAgents.join(", ")
              })
            ]
          }),
          /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
            marginTop: 1,
            children: [
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: "Status: "
              }),
              /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
                children: [
                  color("inactive", theme)(figures_default.radioOff),
                  " not connected (agent-only)"
                ]
              })
            ]
          }),
          agentServer.needsAuth && /* @__PURE__ */ jsx_runtime.jsxs(ThemedBox_default, {
            children: [
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: "Auth: "
              }),
              agentServer.isAuthenticated ? /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
                children: [
                  color("success", theme)(figures_default.tick),
                  " authenticated"
                ]
              }) : /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
                children: [
                  color("warning", theme)(figures_default.triangleUpOutline),
                  " may need authentication"
                ]
              })
            ]
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: "This server connects only when running the agent."
        })
      }),
      error && /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
          color: "error",
          children: [
            "Error: ",
            error
          ]
        })
      }),
      /* @__PURE__ */ jsx_runtime.jsx(ThemedBox_default, {
        children: /* @__PURE__ */ jsx_runtime.jsx(Select, {
          options: menuOptions,
          onChange: async (value) => {
            switch (value) {
              case "auth":
                await handleAuthenticate();
                break;
              case "back":
                onCancel();
                break;
            }
          },
          onCancel
        })
      })
    ]
  });
}
var import_react, jsx_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_runtime = __toESM(require_jsx_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_runtime2.jsxs(ThemedBox_default, {
      children: [
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          color: isSelected ? "suggestion" : undefined,
          children: isSelected ? `${figures_default.pointer} ` : "  "
        }),
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          color: isSelected ? "suggestion" : undefined,
          children: server.name
        }),
        /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
          dimColor: !isSelected,
          children: [
            " \xB7 ",
            statusIcon,
            " "
          ]
        }),
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          dimColor: !isSelected,
          children: statusText
        })
      ]
    }, `${server.name}-${index}`);
  };
  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_runtime2.jsxs(ThemedBox_default, {
      children: [
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          color: isSelected ? "suggestion" : undefined,
          children: isSelected ? `${figures_default.pointer} ` : "  "
        }),
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          color: isSelected ? "suggestion" : undefined,
          children: agentServer.name
        }),
        /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
          dimColor: !isSelected,
          children: [
            " \xB7 ",
            statusIcon,
            " "
          ]
        }),
        /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          dimColor: !isSelected,
          children: statusText
        })
      ]
    }, `agent-${agentServer.name}-${index}`);
  };
  const totalServers = servers.length + agentServers.length;
  return /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
    flexDirection: "column",
    children: [
      /* @__PURE__ */ jsx_runtime2.jsx(McpParsingWarnings, {}),
      /* @__PURE__ */ jsx_runtime2.jsx(Dialog, {
        title: "Manage MCP servers",
        subtitle: `${totalServers} ${plural(totalServers, "server")}`,
        onCancel: handleCancel,
        hideInputGuide: true,
        children: /* @__PURE__ */ jsx_runtime2.jsxs(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_runtime2.jsxs(ThemedBox_default, {
                flexDirection: "column",
                marginBottom: 1,
                children: [
                  /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
                    paddingLeft: 2,
                    children: [
                      /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
                        bold: true,
                        children: heading.label
                      }),
                      heading.path && /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
                        dimColor: true,
                        children: [
                          " (",
                          heading.path,
                          ")"
                        ]
                      })
                    ]
                  }),
                  scopeServers.map((server) => renderServerItem(server))
                ]
              }, scope);
            }),
            claudeAiServers.length > 0 && /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
              flexDirection: "column",
              marginBottom: 1,
              children: [
                /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
                  paddingLeft: 2,
                  children: /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
                    bold: true,
                    children: "claude.ai"
                  })
                }),
                claudeAiServers.map((server) => renderServerItem(server))
              ]
            }),
            agentServers.length > 0 && /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
              flexDirection: "column",
              marginBottom: 1,
              children: [
                /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
                  paddingLeft: 2,
                  children: /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
                    bold: true,
                    children: "Agent MCPs"
                  })
                }),
                [...new Set(agentServers.flatMap((s) => s.sourceAgents))].map((agentName) => /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
                  flexDirection: "column",
                  marginTop: 1,
                  children: [
                    /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
                      paddingLeft: 2,
                      children: /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
                        dimColor: true,
                        children: [
                          "@",
                          agentName
                        ]
                      })
                    }),
                    agentServers.filter((s) => s.sourceAgents.includes(agentName)).map((agentServer) => renderAgentServerItem(agentServer))
                  ]
                }, agentName))
              ]
            }),
            dynamicServers.length > 0 && /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
              flexDirection: "column",
              marginBottom: 1,
              children: [
                /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
                  paddingLeft: 2,
                  children: [
                    /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
                      bold: true,
                      children: dynamicHeading.label
                    }),
                    dynamicHeading.path && /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
                      dimColor: true,
                      children: [
                        " (",
                        dynamicHeading.path,
                        ")"
                      ]
                    })
                  ]
                }),
                dynamicServers.map((server) => renderServerItem(server))
              ]
            }),
            /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
              flexDirection: "column",
              children: [
                hasFailedClients && /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
                  dimColor: true,
                  children: debugMode ? "\u203B Error logs shown inline with --debug" : "\u203B Run claude --debug to see error logs"
                }),
                /* @__PURE__ */ jsx_runtime2.jsxs(ThemedText, {
                  dimColor: true,
                  children: [
                    /* @__PURE__ */ jsx_runtime2.jsx(Link, {
                      url: "https://code.claude.com/docs/en/mcp",
                      children: "https://code.claude.com/docs/en/mcp"
                    }),
                    " for help"
                  ]
                })
              ]
            })
          ]
        })
      }),
      /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
        paddingX: 1,
        children: /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
          dimColor: true,
          italic: true,
          children: /* @__PURE__ */ jsx_runtime2.jsxs(Byline, {
            children: [
              /* @__PURE__ */ jsx_runtime2.jsx(KeyboardShortcutHint, {
                shortcut: "\u2191\u2193",
                action: "navigate"
              }),
              /* @__PURE__ */ jsx_runtime2.jsx(KeyboardShortcutHint, {
                shortcut: "Enter",
                action: "confirm"
              }),
              /* @__PURE__ */ jsx_runtime2.jsx(ConfigurableShortcutHint, {
                action: "confirm:no",
                context: "Confirmation",
                fallback: "Esc",
                description: "cancel"
              })
            ]
          })
        })
      })
    ]
  });
}
var import_react2, jsx_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_runtime2 = __toESM(require_jsx_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_runtime3.jsxs(ThemedBox_default, {
      flexDirection: "column",
      gap: 1,
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
          color: "text",
          children: [
            "Reconnecting to ",
            /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
              bold: true,
              children: serverName
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime3.jsxs(ThemedBox_default, {
          children: [
            /* @__PURE__ */ jsx_runtime3.jsx(Spinner, {}),
            /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
              children: " Establishing connection to MCP server"
            })
          ]
        })
      ]
    });
  }
  if (error) {
    return /* @__PURE__ */ jsx_runtime3.jsxs(ThemedBox_default, {
      flexDirection: "column",
      gap: 1,
      padding: 1,
      children: [
        /* @__PURE__ */ jsx_runtime3.jsxs(ThemedBox_default, {
          children: [
            /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
              children: [
                color("error", theme)(figures_default.cross),
                " "
              ]
            }),
            /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
              color: "error",
              children: [
                "Failed to reconnect to ",
                serverName
              ]
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
          dimColor: true,
          children: [
            "Error: ",
            error
          ]
        })
      ]
    });
  }
  return null;
}
var import_react3, jsx_runtime3;
var init_MCPReconnect = __esm(() => {
  init_figures();
  init_src();
  init_MCPConnectionManager();
  init_AppState();
  init_Spinner();
  import_react3 = __toESM(require_react(), 1);
  jsx_runtime3 = __toESM(require_jsx_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 `claude 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_runtime4.jsx(MCPListPanel, {
        servers,
        agentServers: agentMcpServers,
        onSelectServer: (server) => setViewState({ type: "server-menu", server }),
        onSelectAgentServer: (agentServer) => setViewState({ type: "agent-server-menu", agentServer }),
        onComplete,
        defaultTab: viewState.defaultTab
      });
    case "server-menu": {
      const serverTools = filterToolsByServer(mcp.tools, viewState.server.name);
      const defaultTab = viewState.server.transport === "claudeai-proxy" ? "claude.ai" : "Chris Code";
      if (viewState.server.transport === "stdio") {
        return /* @__PURE__ */ jsx_runtime4.jsx(MCPStdioServerMenu, {
          server: viewState.server,
          serverToolsCount: serverTools.length,
          onViewTools: () => setViewState({ type: "server-tools", server: viewState.server }),
          onCancel: () => setViewState({ type: "list", defaultTab }),
          onComplete
        });
      } else {
        return /* @__PURE__ */ jsx_runtime4.jsx(MCPRemoteServerMenu, {
          server: viewState.server,
          serverToolsCount: serverTools.length,
          onViewTools: () => setViewState({ type: "server-tools", server: viewState.server }),
          onCancel: () => setViewState({ type: "list", defaultTab }),
          onComplete
        });
      }
    }
    case "server-tools":
      return /* @__PURE__ */ jsx_runtime4.jsx(MCPToolListView, {
        server: viewState.server,
        onSelectTool: (_, index) => setViewState({
          type: "server-tool-detail",
          server: viewState.server,
          toolIndex: index
        }),
        onBack: () => setViewState({ type: "server-menu", server: viewState.server })
      });
    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_runtime4.jsx(MCPToolDetailView, {
        tool,
        server: viewState.server,
        onBack: () => setViewState({ type: "server-tools", server: viewState.server })
      });
    }
    case "agent-server-menu":
      return /* @__PURE__ */ jsx_runtime4.jsx(MCPAgentServerMenu, {
        agentServer: viewState.agentServer,
        onCancel: () => setViewState({ type: "list", defaultTab: "Agents" }),
        onComplete
      });
  }
}
var import_react4, jsx_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_runtime4 = __toESM(require_jsx_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_runtime5.jsx(MCPSettings, {
        onComplete: onDone
      });
    }
    if (parts[0] === "reconnect" && parts[1]) {
      return /* @__PURE__ */ jsx_runtime5.jsx(MCPReconnect, {
        serverName: parts.slice(1).join(" "),
        onComplete: onDone
      });
    }
    if (parts[0] === "enable" || parts[0] === "disable") {
      return /* @__PURE__ */ jsx_runtime5.jsx(MCPToggle, {
        action: parts[0],
        target: parts.length > 1 ? parts.slice(1).join(" ") : "all",
        onComplete: onDone
      });
    }
  }
  if (process.env.USER_TYPE === "ant") {
    return /* @__PURE__ */ jsx_runtime5.jsx(PluginSettings, {
      onComplete: onDone,
      args: "manage",
      showMcpRedirectMessage: true
    });
  }
  return /* @__PURE__ */ jsx_runtime5.jsx(MCPSettings, {
    onComplete: onDone
  });
}
var import_react5, jsx_runtime5;
var init_mcp2 = __esm(() => {
  init_mcp();
  init_MCPReconnect();
  init_MCPConnectionManager();
  init_AppState();
  init_PluginSettings();
  import_react5 = __toESM(require_react(), 1);
  jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
});
init_mcp2();

export {
  call
};

//# debugId=3C66DFF676F97AE064756E2164756E21
//# sourceMappingURL=chunk-xkp9n6a9.js.map
