{% extends "base.html" %} {% block title %}MCP服务器管理 - Amrita Dashboard{%
endblock %} {% block topbar_title %}MCP服务器管理{% endblock %} {% block
extra_css %}
<style>
  .mcp-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
  }

  body.dark-mode .mcp-header {
    border-bottom: 1px solid var(--dark-border-color);
  }

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: var(--primary-color);
  }

  body.dark-mode .page-title {
    color: var(--accent-color);
  }

  .actions-container {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
    margin-top: 5px;
  }

  .action-btn {
    background: var(--primary-color);
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    transition: background 0.3s;
  }

  .action-btn:hover {
    background: var(--accent-color);
  }

  .action-btn i {
    margin-right: 5px;
  }

  .action-btn.secondary {
    background: #6c757d;
    color: white;
  }

  .action-btn.secondary:hover {
    background: #5a6268;
  }

  .search-box {
    position: relative;
    flex-grow: 1;
    max-width: 300px;
  }

  .search-input {
    width: 100%;
    padding: 8px 12px 8px 35px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }

  body.dark-mode .search-input {
    border: 1px solid var(--dark-border-color);
    background: var(--dark-card-bg);
    color: var(--dark-text-color);
  }

  .search-icon {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #777;
  }

  body.dark-mode .search-icon {
    color: #aaa;
  }

  .mcp-container {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    padding: 20px;
    border: 1px solid #eee;
  }

  body.dark-mode .mcp-container {
    background: var(--dark-card-bg);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
    border: 1px solid var(--dark-border-color);
  }

  .section-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 15px;
    color: var(--text-color);
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }

  body.dark-mode .section-title {
    color: var(--accent-color);
    border-bottom: 1px solid var(--dark-border-color);
  }

  .mcp-card {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    border: 1px solid #e9ecef;
    position: relative;
  }

  body.dark-mode .mcp-card {
    background: #2d2d2d;
    border: 1px solid var(--dark-border-color);
  }

  .mcp-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .mcp-name {
    font-weight: 600;
    color: var(--primary-color);
    word-break: break-word;
    flex-grow: 1;
  }

  body.dark-mode .mcp-name {
    color: var(--accent-color);
  }

  .mcp-actions {
    display: flex;
    gap: 8px;
  }

  .mcp-btn {
    padding: 5px 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: background 0.3s;
    display: flex;
    align-items: center;
  }

  .mcp-btn i {
    margin-right: 3px;
  }

  .btn-add {
    background: #28a745;
    color: white;
  }

  .btn-add:hover {
    background: #218838;
  }

  .btn-edit {
    background: #3498db;
    color: white;
  }

  .btn-edit:hover {
    background: #2980b9;
  }

  .btn-delete {
    background: #e74c3c;
    color: white;
  }

  .btn-delete:hover {
    background: #c0392b;
  }

  .btn-reload {
    background: #ffc107;
    color: #212529;
  }

  .btn-reload:hover {
    background: #e0a800;
  }

  .mcp-info {
    display: flex;
    gap: 15px;
    margin-top: 10px;
    flex-wrap: wrap;
  }

  .info-item {
    flex: 1;
    min-width: 150px;
  }

  .info-label {
    font-weight: 500;
    color: #555;
    font-size: 14px;
    margin-bottom: 3px;
  }

  body.dark-mode .info-label {
    color: #aaa;
  }

  .info-value {
    padding: 6px 10px;
    border: 1px solid #ddd;
    border-radius: 8px;
    background: rgba(255, 255, 255, var(--glass-opacity-light));
    backdrop-filter: blur(var(--blur-intensity));
    -webkit-backdrop-filter: blur(var(--blur-intensity));
    word-break: break-all;
  }

  body.dark-mode .info-value {
    background: rgba(37, 37, 37, var(--glass-opacity-light));
    border: 1px solid var(--dark-border-color);
    color: var(--dark-text-color);
  }

  .status-indicator {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 5px;
  }

  .status-connected {
    background-color: #28a745;
  }

  .status-disconnected {
    background-color: #dc3545;
  }

  .modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .modal-content {
    background-color: var(--bg-color);
    margin: 5% auto;
    padding: 20px;
    border: none;
    border-radius: 10px;
    width: 90%;
    max-width: 600px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    position: relative;
    max-height: 80vh;
    overflow-y: auto;
  }

  body.dark-mode .modal-content {
    background-color: var(--dark-bg-color);
  }

  .close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    line-height: 1;
    position: absolute;
    right: 15px;
    top: 10px;
  }

  .close:hover,
  .close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
  }

  body.dark-mode .close:hover,
  body.dark-mode .close:focus {
    color: #fff;
  }

  .form-group {
    margin-bottom: 15px;
  }

  .form-label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
    color: #555;
  }

  body.dark-mode .form-label {
    color: #aaa;
  }

  .form-control {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box;
  }

  body.dark-mode .form-control {
    border: 1px solid var(--dark-border-color);
    background: var(--dark-card-bg);
    color: var(--dark-text-color);
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }

  .alert {
    padding: 12px 15px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: none;
  }

  .alert-success {
    background-color: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
  }

  .alert-danger {
    background-color: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
  }

  body.dark-mode .alert-success {
    background-color: rgba(40, 167, 69, 0.1);
    border: 1px solid rgba(40, 167, 69, 0.2);
    color: #28a745;
  }

  body.dark-mode .alert-danger {
    background-color: rgba(220, 53, 69, 0.1);
    border: 1px solid rgba(220, 53, 69, 0.2);
    color: #dc3545;
  }

  @media (max-width: 768px) {
    .mcp-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
    }

    .actions-container {
      width: 100%;
      justify-content: space-between;
    }
  }
</style>
{% endblock %} {% block content %}
<div class="config-container">
  <div class="alert alert-success" id="success-alert" style="display: none">
    操作成功！
  </div>

  <div class="alert alert-danger" id="error-alert" style="display: none">
    操作失败，请重试。
  </div>

  <div class="mcp-header">
    <h1 class="page-title">MCP服务器管理</h1>
    <div class="actions-container">
      <button class="action-btn" onclick="openAddModal()">
        <i class="fas fa-plus"></i> 添加MCP服务器
      </button>
      <button class="action-btn secondary" onclick="reloadMcpServers()">
        <i class="fas fa-sync-alt"></i> 重载所有服务器
      </button>
      <button class="action-btn secondary" onclick="refreshMcpServers()">
        <i class="fas fa-sync"></i> 刷新
      </button>
    </div>
  </div>

  <div class="mcp-container">
    <div class="section-title">MCP服务器列表</div>
    <div id="mcp-servers-container">
      <!-- MCP服务器卡片将通过JavaScript动态加载 -->
    </div>
  </div>

  <!-- 添加/编辑MCP服务器的模态框 -->
  <div id="mcpModal" class="modal">
    <div class="modal-content">
      <span class="close" onclick="closeModal()">&times;</span>
      <h2 id="modalTitle">添加MCP服务器</h2>
      <form id="mcpForm">
        <input type="hidden" id="mcpId" name="id" />
        <div class="form-group">
          <label class="form-label" for="mcpScript">服务器脚本路径</label>
          <input
            type="text"
            class="form-control"
            id="mcpScript"
            name="server_script"
            placeholder="请输入MCP服务器脚本路径或URI"
            required
          />
        </div>
        <div class="form-actions">
          <button
            type="button"
            class="btn btn-secondary"
            onclick="closeModal()"
          >
            取消
          </button>
          <button type="submit" class="btn btn-primary">保存</button>
        </div>
      </form>
    </div>
  </div>
</div>
{% endblock %} {% block scripts %}
<script>
  async function loadMcpServers() {
    try {
      const response = await fetch("/api/chat/mcp/servers");
      const result = await response.json();

      if (result.success) {
        const container = document.getElementById("mcp-servers-container");
        container.innerHTML = "";

        result.servers.forEach((server) => {
          const serverCard = document.createElement("div");
          serverCard.className = "mcp-card";

          const statusClass =
            server.status === "connected"
              ? "status-connected"
              : "status-disconnected";
          const statusText =
            server.status === "connected" ? "已连接" : "未连接";

          serverCard.innerHTML = `
            <div class="mcp-header-row">
              <div class="mcp-name">
                <span class="status-indicator ${statusClass}"></span>
                ${server.server_script}
              </div>
              <div class="mcp-actions">
                <button class="mcp-btn btn-edit" onclick="openEditModal('${server.server_script}')">
                  <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="mcp-btn btn-delete" onclick="deleteMcpServer('${server.server_script}')">
                  <i class="fas fa-trash"></i> 删除
                </button>
              </div>
            </div>
            <div class="mcp-info">
              <div class="info-item">
                <div class="info-label">工具数量</div>
                <div class="info-value">${server.tools_count}</div>
              </div>
              <div class="info-item">
                <div class="info-label">连接状态</div>
                <div class="info-value">
                  <span class="status-indicator ${statusClass}"></span>
                  ${statusText}
                </div>
              </div>
            </div>
          `;

          container.appendChild(serverCard);
        });
      } else {
        showAlert("danger", result.message || "获取MCP服务器列表失败");
      }
    } catch (error) {
      console.error("加载MCP服务器列表失败:", error);
      showAlert("danger", "加载MCP服务器列表失败: " + error.message);
    }
  }

  function openAddModal() {
    document.getElementById("modalTitle").textContent = "添加MCP服务器";
    document.getElementById("mcpForm").reset();
    document.getElementById("mcpId").value = "";

    document.getElementById("mcpModal").style.display = "block";
  }

  function openEditModal(serverScript) {
    document.getElementById("modalTitle").textContent = "编辑MCP服务器";
    document.getElementById("mcpScript").value = serverScript;
    document.getElementById("mcpId").value = serverScript;

    document.getElementById("mcpModal").style.display = "block";
  }

  function closeModal() {
    document.getElementById("mcpModal").style.display = "none";
  }

  document
    .getElementById("mcpForm")
    .addEventListener("submit", async function (e) {
      e.preventDefault();

      const formData = new FormData(this);
      const mcpData = Object.fromEntries(formData.entries());

      try {
        const isEdit = document.getElementById("mcpId").value !== "";

        if (isEdit) {
          // 对于编辑，发送PUT请求，使用查询参数传递原始路径
          const response = await fetch(
            `/api/chat/mcp/servers?server_script=${encodeURIComponent(
              document.getElementById("mcpId").value,
            )}`,
            {
              method: "PUT",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify(mcpData),
            },
          );

          const result = await response.json();

          if (result.success) {
            showAlert("success", result.message || "MCP服务器已更新");
            loadMcpServers(); // 重新加载服务器列表
            closeModal();
          } else {
            showAlert("danger", result.message || "更新失败");
          }
        } else {
          // 对于新增，发送POST请求
          const response = await fetch("/api/chat/mcp/servers", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(mcpData),
          });

          const result = await response.json();

          if (result.success) {
            showAlert("success", result.message || "MCP服务器已添加");
            loadMcpServers(); // 重新加载服务器列表
            closeModal();
          } else {
            showAlert("danger", result.message || "添加失败");
          }
        }
      } catch (error) {
        console.error("保存MCP服务器失败:", error);
        showAlert("danger", "保存失败: " + error.message);
      }
    });

  async function deleteMcpServer(serverScript) {
    if (
      !confirm(`确定要删除MCP服务器 "${serverScript}" 吗？此操作不可撤销。`)
    ) {
      return;
    }

    try {
      // 使用查询参数而不是路径参数
      const response = await fetch(
        `/api/chat/mcp/servers?server_script=${encodeURIComponent(
          serverScript,
        )}`,
        {
          method: "DELETE",
        },
      );

      const result = await response.json();

      if (result.success) {
        showAlert("success", result.message || "MCP服务器已删除");
        loadMcpServers(); // 重新加载服务器列表
      } else {
        showAlert("danger", result.message || "删除失败");
      }
    } catch (error) {
      console.error("删除MCP服务器失败:", error);
      showAlert("danger", "删除失败: " + error.message);
    }
  }

  async function reloadMcpServers() {
    if (!confirm("确定要重载所有MCP服务器吗？这将重新连接所有服务器。")) {
      return;
    }

    try {
      const response = await fetch("/api/chat/mcp/servers/reload", {
        method: "POST",
      });

      const result = await response.json();

      if (result.success) {
        showAlert("success", result.message || "MCP服务器重载成功");
        loadMcpServers(); // 重新加载服务器列表
      } else {
        showAlert("danger", result.message || "重载失败");
      }
    } catch (error) {
      console.error("重载MCP服务器失败:", error);
      showAlert("danger", "重载失败: " + error.message);
    }
  }

  async function refreshMcpServers() {
    try {
      loadMcpServers();
      showAlert("success", "MCP服务器列表已刷新");
    } catch (error) {
      console.error("刷新MCP服务器列表失败:", error);
      showAlert("danger", "刷新失败: " + error.message);
    }
  }

  function showAlert(type, message) {
    const successAlert = document.getElementById("success-alert");
    const errorAlert = document.getElementById("error-alert");

    successAlert.style.display = "none";
    errorAlert.style.display = "none";

    if (type === "success") {
      successAlert.textContent = message;
      successAlert.style.display = "block";
    } else {
      errorAlert.textContent = message;
      errorAlert.style.display = "block";
    }

    setTimeout(() => {
      successAlert.style.display = "none";
      errorAlert.style.display = "none";
    }, 3000);
  }

  // 点击模态框外部关闭
  window.onclick = function (event) {
    const modal = document.getElementById("mcpModal");
    if (event.target === modal) {
      closeModal();
    }
  };

  // ESC键关闭模态框
  document.addEventListener("keydown", function (event) {
    if (event.key === "Escape") {
      closeModal();
    }
  });

  // 页面加载完成后自动加载MCP服务器列表
  document.addEventListener("DOMContentLoaded", function () {
    loadMcpServers();
  });
</script>
{% endblock %}
