| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004 |
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>MCP 助手</title>
- <script src="https://cdn.tailwindcss.com"></script>
- <style>
- .chat-container {
- height: calc(100vh - 200px);
- }
- /* 移动端优化 */
- @media (max-width: 768px) {
- .chat-container {
- height: calc(100vh - 180px);
- }
- /* 头部固定 */
- header {
- position: sticky;
- top: 0;
- z-index: 50;
- }
- /* 消息气泡宽度 */
- .message-bubble {
- max-width: 85vw !important;
- }
- /* 输入区域固定 */
- .input-area {
- position: sticky;
- bottom: 0;
- z-index: 50;
- background: white;
- border-top-left-radius: 0;
- border-top-right-radius: 0;
- }
- }
- /* 参数/结果可折叠区域 */
- .collapsible-section {
- margin-top: 6px;
- }
- .collapsible-header {
- display: flex;
- align-items: center;
- gap: 4px;
- padding: 4px 8px;
- background: rgba(255, 255, 255, 0.05);
- border-radius: 4px;
- cursor: pointer;
- font-size: 11px;
- color: #9ca3af;
- user-select: none;
- }
- .collapsible-header:hover {
- background: rgba(255, 255, 255, 0.08);
- }
- .collapsible-content {
- max-height: 0;
- overflow: hidden;
- transition: max-height 0.3s ease-out;
- }
- .collapsible-content.expanded {
- max-height: 300px;
- overflow-y: auto;
- }
- .collapsible-icon {
- transition: transform 0.3s;
- font-size: 10px;
- }
- .collapsible-icon.expanded {
- transform: rotate(90deg);
- }
- /* MCP 服务器横向滚动 */
- .mcp-servers-scroll {
- display: flex;
- gap: 8px;
- overflow-x: auto;
- padding: 4px 0;
- scrollbar-width: thin;
- -webkit-overflow-scrolling: touch;
- }
- .mcp-servers-scroll::-webkit-scrollbar {
- height: 4px;
- }
- .mcp-servers-scroll::-webkit-scrollbar-thumb {
- background: rgba(0, 0, 0, 0.2);
- border-radius: 2px;
- }
- .mcp-server-tag {
- flex-shrink: 0;
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 8px 12px;
- border-radius: 8px;
- font-size: 12px;
- white-space: nowrap;
- }
- .mcp-server-tag.enabled {
- background: #d1fae5;
- color: #065f46;
- }
- .mcp-server-tag.disabled {
- background: #f3f4f6;
- color: #6b7280;
- }
- .mcp-status-dot {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- }
- .mcp-status-dot.online {
- background: #10b981;
- }
- .mcp-status-dot.offline {
- background: #9ca3af;
- }
- .message-user {
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
- }
- .message-assistant {
- background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
- }
- .typing-indicator span {
- animation: bounce 1.4s infinite ease-in-out both;
- }
- .typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
- .typing-indicator span:nth-child(2) { animation-delay: -0.16s; }
- @keyframes bounce {
- 0%, 80%, 100% { transform: scale(0); }
- 40% { transform: scale(1); }
- }
- /* 工具调用面板样式 */
- .tool-call-panel {
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
- border-radius: 8px;
- margin: 12px 0;
- overflow: hidden;
- border: 1px solid #3a3a5a;
- }
- .tool-panel-header {
- background: rgba(255, 255, 255, 0.05);
- padding: 10px 14px;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: space-between;
- transition: background 0.2s;
- }
- .tool-panel-header:hover {
- background: rgba(255, 255, 255, 0.08);
- }
- .tool-panel-title {
- display: flex;
- align-items: center;
- gap: 8px;
- color: #e0e0e0;
- font-size: 13px;
- font-weight: 500;
- }
- .tool-panel-content {
- padding: 0;
- max-height: 0;
- overflow: hidden;
- transition: max-height 0.3s ease-out, padding 0.3s ease-out;
- }
- .tool-panel-content.collapsed {
- max-height: 0;
- }
- .tool-panel-content.expanded {
- max-height: 800px;
- padding: 12px;
- overflow-y: auto;
- }
- .tool-panel-content::-webkit-scrollbar {
- width: 6px;
- }
- .tool-panel-content::-webkit-scrollbar-track {
- background: rgba(255, 255, 255, 0.05);
- }
- .tool-panel-content::-webkit-scrollbar-thumb {
- background: rgba(255, 255, 255, 0.2);
- border-radius: 3px;
- }
- /* 工具调用项样式 */
- .tool-call-item {
- background: rgba(255, 255, 255, 0.03);
- border-radius: 6px;
- padding: 10px 12px;
- margin-bottom: 8px;
- border-left: 3px solid #555;
- transition: all 0.2s;
- }
- .tool-call-item:last-child {
- margin-bottom: 0;
- }
- .tool-call-item.pending {
- border-left-color: #f59e0b;
- animation: pulse-border 1.5s infinite;
- }
- .tool-call-item.success {
- border-left-color: #10b981;
- }
- .tool-call-item.error {
- border-left-color: #ef4444;
- }
- @keyframes pulse-border {
- 0%, 100% { border-left-color: #f59e0b; }
- 50% { border-left-color: #fbbf24; }
- }
- .tool-call-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 6px;
- }
- .tool-name {
- color: #e0e0e0;
- font-size: 13px;
- font-weight: 500;
- display: flex;
- align-items: center;
- gap: 6px;
- }
- .tool-status {
- font-size: 11px;
- padding: 2px 8px;
- border-radius: 10px;
- font-weight: 500;
- }
- .tool-status.pending {
- background: rgba(245, 158, 11, 0.2);
- color: #fbbf24;
- }
- .tool-status.success {
- background: rgba(16, 185, 129, 0.2);
- color: #34d399;
- }
- .tool-status.error {
- background: rgba(239, 68, 68, 0.2);
- color: #f87171;
- }
- .tool-params {
- background: rgba(0, 0, 0, 0.3);
- border-radius: 4px;
- padding: 8px;
- margin-top: 6px;
- font-size: 11px;
- color: #9ca3af;
- overflow-x: auto;
- }
- .tool-params::-webkit-scrollbar {
- height: 4px;
- }
- .tool-params::-webkit-scrollbar-thumb {
- background: rgba(255, 255, 255, 0.2);
- border-radius: 2px;
- }
- .tool-result {
- background: rgba(16, 185, 129, 0.1);
- border-radius: 4px;
- padding: 8px;
- margin-top: 6px;
- font-size: 11px;
- color: #6ee7b7;
- }
- .tool-result.error {
- background: rgba(239, 68, 68, 0.1);
- color: #fca5a5;
- }
- .tool-result-content {
- max-height: 100px;
- overflow-y: auto;
- word-break: break-all;
- }
- .tool-result-content::-webkit-scrollbar {
- width: 4px;
- }
- .tool-result-content::-webkit-scrollbar-thumb {
- background: rgba(255, 255, 255, 0.2);
- border-radius: 2px;
- }
- .expand-icon {
- transition: transform 0.3s;
- }
- .expand-icon.expanded {
- transform: rotate(180deg);
- }
- /* 加载动画 */
- .spinner {
- width: 14px;
- height: 14px;
- border: 2px solid rgba(251, 191, 36, 0.3);
- border-top-color: #fbbf24;
- border-radius: 50%;
- animation: spin 0.8s linear infinite;
- }
- @keyframes spin {
- to { transform: rotate(360deg); }
- }
- /* 状态指示器 */
- .process-indicator {
- display: flex;
- align-items: center;
- gap: 6px;
- padding: 6px 10px;
- background: rgba(245, 158, 11, 0.1);
- border-radius: 6px;
- font-size: 12px;
- color: #fbbf24;
- }
- .process-indicator.success {
- background: rgba(16, 185, 129, 0.1);
- color: #34d399;
- }
- .process-indicator .spinner {
- width: 12px;
- height: 12px;
- }
- pre {
- background: #1e1e1e;
- color: #d4d4d4;
- padding: 1rem;
- border-radius: 0.5rem;
- overflow-x: auto;
- }
- code {
- font-family: 'Courier New', monospace;
- }
- </style>
- </head>
- <body class="bg-gray-100 min-h-screen">
- <div class="container mx-auto px-4 py-6 max-w-4xl">
- <!-- Header -->
- <header class="bg-white rounded-lg shadow-md p-4 mb-4">
- <div class="flex items-center justify-between">
- <div class="flex items-center space-x-3">
- <div class="w-10 h-10 bg-gradient-to-br from-purple-500 to-indigo-600 rounded-lg flex items-center justify-center">
- <span class="text-white font-bold">AI</span>
- </div>
- <div>
- <h1 class="text-xl font-bold text-gray-800">AI MCP Web UI</h1>
- <p class="text-sm text-gray-500">通用 MCP 服务器 Web 界面</p>
- </div>
- </div>
- <div id="status-indicator" class="flex items-center space-x-2">
- <span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
- <span class="text-sm text-gray-600">已连接</span>
- </div>
- </div>
- </header>
- <!-- Chat Container -->
- <div class="bg-white rounded-lg shadow-md">
- <!-- Messages -->
- <div id="chat-messages" class="chat-container overflow-y-auto p-4 space-y-4">
- <!-- Welcome Message -->
- <div class="flex justify-start">
- <div class="message-assistant message-bubble rounded-lg p-4 max-w-[80%] shadow-sm">
- <p class="text-gray-800">你好!我是 AI MCP Web UI 助手。我可以帮助你:</p>
- <ul class="mt-2 text-gray-700 list-disc list-inside">
- <li>与 Claude AI 进行对话</li>
- <li>调用 MCP 服务器工具</li>
- <li>自动化各种任务</li>
- </ul>
- <p class="mt-2 text-gray-600 text-sm">请问有什么可以帮助你的?</p>
- </div>
- </div>
- </div>
- <!-- Input Area -->
- <div class="border-t border-gray-200 p-4 input-area">
- <form id="chat-form" class="flex space-x-3">
- <input
- type="text"
- id="user-input"
- placeholder="输入你的消息..."
- class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
- style="font-size: 16px;"
- autocomplete="off"
- >
- <button
- type="submit"
- id="send-button"
- class="px-6 py-3 bg-gradient-to-r from-purple-500 to-indigo-600 text-white rounded-lg hover:from-purple-600 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
- style="font-size: 16px;"
- >
- 发送
- </button>
- </form>
- </div>
- </div>
- <!-- MCP Servers Status -->
- <div class="mt-4 bg-white rounded-lg shadow-md p-4">
- <h2 class="text-sm font-semibold text-gray-800 mb-2">MCP 服务器</h2>
- <div id="mcp-servers" class="mcp-servers-scroll">
- <!-- MCP server tags will be inserted here -->
- </div>
- </div>
- </div>
- <script>
- // State
- let conversationHistory = [];
- let isTyping = false;
- // DOM Elements
- const chatMessages = document.getElementById('chat-messages');
- const chatForm = document.getElementById('chat-form');
- const userInput = document.getElementById('user-input');
- const sendButton = document.getElementById('send-button');
- const mcpServers = document.getElementById('mcp-servers');
- const statusIndicator = document.getElementById('status-indicator');
- // API Base URL
- const API_BASE = window.location.origin;
- // Format message content (handle code blocks, etc.)
- function formatMessage(content) {
- // Simple markdown-like formatting
- let formatted = content
- .replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
- .replace(/`([^`]+)`/g, '<code class="bg-gray-200 px-1 rounded">$1</code>')
- .replace(/\n/g, '<br>');
- return formatted;
- }
- // Add message to chat
- function addMessage(role, content) {
- const messageDiv = document.createElement('div');
- messageDiv.className = `flex ${role === 'user' ? 'justify-end' : 'justify-start'}`;
- const bubbleClass = role === 'user' ? 'message-user text-white' : 'message-assistant text-gray-800';
- messageDiv.innerHTML = `
- <div class="${bubbleClass} message-bubble rounded-lg p-4 max-w-[80%] shadow-sm">
- <div>${formatMessage(content)}</div>
- </div>
- `;
- chatMessages.appendChild(messageDiv);
- chatMessages.scrollTop = chatMessages.scrollHeight;
- }
- // Add typing indicator
- function addTypingIndicator() {
- const typingDiv = document.createElement('div');
- typingDiv.id = 'typing-indicator';
- typingDiv.className = 'flex justify-start';
- typingDiv.innerHTML = `
- <div class="message-assistant rounded-lg p-4 shadow-sm">
- <div class="typing-indicator flex space-x-1">
- <span class="w-2 h-2 bg-gray-500 rounded-full"></span>
- <span class="w-2 h-2 bg-gray-500 rounded-full"></span>
- <span class="w-2 h-2 bg-gray-500 rounded-full"></span>
- </div>
- </div>
- `;
- chatMessages.appendChild(typingDiv);
- chatMessages.scrollTop = chatMessages.scrollHeight;
- }
- // Remove typing indicator
- function removeTypingIndicator() {
- const indicator = document.getElementById('typing-indicator');
- if (indicator) indicator.remove();
- }
- // 创建工具调用面板
- function createToolCallPanel() {
- const panel = document.createElement('div');
- panel.className = 'tool-call-panel';
- panel.innerHTML = `
- <div class="tool-panel-header" onclick="toggleToolPanel(this)">
- <div class="tool-panel-title">
- <span class="expand-icon">▶</span>
- <span>🔧 工具调用</span>
- <span class="tool-count">(0)</span>
- </div>
- <div class="process-indicator">
- <div class="spinner"></div>
- <span>处理中...</span>
- </div>
- </div>
- <div class="tool-panel-content">
- <div class="tool-calls-container"></div>
- </div>
- `;
- return panel;
- }
- // 切换工具面板展开/收起
- function toggleToolPanel(header) {
- const content = header.nextElementSibling;
- const icon = header.querySelector('.expand-icon');
- content.classList.toggle('expanded');
- icon.classList.toggle('expanded');
- }
- // 切换参数/结果折叠区域
- function toggleCollapsible(header) {
- const content = header.nextElementSibling;
- const icon = header.querySelector('.collapsible-icon');
- content.classList.toggle('expanded');
- icon.classList.toggle('expanded');
- }
- // 添加工具调用项
- function addToolCallItem(container, toolName, params, toolUseId = null) {
- const item = document.createElement('div');
- item.className = 'tool-call-item pending';
- const uniqueId = `tool-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
- item.id = uniqueId;
- // 存储 tool_use_id 和 tool_name 以便后续匹配
- if (toolUseId) {
- item.dataset.toolUseId = toolUseId;
- }
- item.dataset.toolName = toolName;
- console.log('[addToolCallItem] Created item:', { id: uniqueId, toolName, toolUseId });
- // 简化工具名称显示 - 去掉 mcp__ 前缀和下划线
- let displayName = toolName;
- if (toolName.startsWith('mcp__')) {
- displayName = toolName.replace('mcp__', '').replace(/_/g, ' ');
- }
- // 首字母大写
- displayName = displayName.charAt(0).toUpperCase() + displayName.slice(1);
- const paramsStr = params ? JSON.stringify(params, null, 2) : '{}';
- const hasParams = params && Object.keys(params).length > 0;
- item.innerHTML = `
- <div class="tool-call-header">
- <div class="tool-name">
- <span>🔧</span>
- <span>${escapeHtml(displayName)}</span>
- </div>
- <div class="tool-status pending">
- <div class="spinner"></div>
- <span>执行中</span>
- </div>
- </div>
- ${hasParams ? `
- <div class="collapsible-section">
- <div class="collapsible-header" onclick="toggleCollapsible(this)">
- <span class="collapsible-icon">▶</span>
- <span>查看参数</span>
- </div>
- <div class="collapsible-content">
- <div class="tool-params"><pre style="margin:0;padding:0;background:transparent;font-size:10px;">${escapeHtml(paramsStr)}</pre></div>
- </div>
- </div>
- ` : ''}
- `;
- container.appendChild(item);
- return { id: uniqueId, toolUseId: toolUseId, toolName: toolName };
- }
- // 更新工具调用状态
- function updateToolCallStatus(itemId, status, result = null) {
- const item = document.getElementById(itemId);
- if (!item) {
- console.warn('[updateToolCallStatus] Item not found:', itemId);
- return;
- }
- const statusEl = item.querySelector('.tool-status');
- item.classList.remove('pending', 'success', 'error');
- if (status === 'success') {
- item.classList.add('success');
- statusEl.className = 'tool-status success';
- statusEl.innerHTML = '✅ 完成';
- // 总是显示结果区域(即使结果为空)
- const resultText = result ? (typeof result === 'string' ? result : JSON.stringify(result, null, 2)) : '';
- const displayResult = resultText || '(无返回结果)';
- const truncatedResult = displayResult.substring(0, 1000) + (displayResult.length > 1000 ? '...' : '');
- const resultDiv = document.createElement('div');
- resultDiv.className = 'collapsible-section';
- resultDiv.innerHTML = `
- <div class="collapsible-header" onclick="toggleCollapsible(this)">
- <span class="collapsible-icon">▶</span>
- <span>查看结果</span>
- </div>
- <div class="collapsible-content">
- <div class="tool-result"><div class="tool-result-content">${escapeHtml(truncatedResult)}</div></div>
- </div>
- `;
- item.appendChild(resultDiv);
- } else if (status === 'error') {
- item.classList.add('error');
- statusEl.className = 'tool-status error';
- statusEl.innerHTML = '❌ 失败';
- const errorDiv = document.createElement('div');
- errorDiv.className = 'collapsible-section';
- errorDiv.innerHTML = `
- <div class="collapsible-header" onclick="toggleCollapsible(this)">
- <span class="collapsible-icon">▶</span>
- <span>查看错误</span>
- </div>
- <div class="collapsible-content expanded">
- <div class="tool-result error">${escapeHtml(result || '未知错误')}</div>
- </div>
- `;
- item.appendChild(errorDiv);
- }
- }
- // 更新工具面板状态
- function updateToolPanelStatus(panel, status, totalCalls = 0) {
- const indicator = panel.querySelector('.process-indicator');
- const countEl = panel.querySelector('.tool-count');
- const content = panel.querySelector('.tool-panel-content');
- const icon = panel.querySelector('.expand-icon');
- countEl.textContent = `(${totalCalls})`;
- if (status === 'running') {
- // 保持处理中状态,不改变
- indicator.className = 'process-indicator';
- indicator.innerHTML = `<div class="spinner"></div><span>处理中...</span>`;
- } else if (status === 'complete') {
- indicator.className = 'process-indicator success';
- indicator.innerHTML = `<span>✅ 完成 - ${totalCalls} 个工具调用</span>`;
- // 自动展开面板以便查看结果
- if (content && !content.classList.contains('expanded')) {
- content.classList.add('expanded');
- if (icon) icon.classList.add('expanded');
- }
- } else if (status === 'error') {
- indicator.className = 'process-indicator';
- indicator.style.background = 'rgba(239, 68, 68, 0.1)';
- indicator.style.color = '#f87171';
- indicator.innerHTML = `<span>❌ 部分失败</span>`;
- }
- }
- // HTML 转义
- function escapeHtml(text) {
- const div = document.createElement('div');
- div.textContent = text;
- return div.innerHTML;
- }
- function scrollToBottom() {
- chatMessages.scrollTop = chatMessages.scrollHeight;
- }
- // ========== 流式聊天功能 ==========
- async function chatStream(message, onEvent) {
- const events = [];
- try {
- const response = await fetch('/api/chat/stream', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ message, history: conversationHistory })
- });
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- // 处理 SSE 格式: "event: xxx\ndata: {...}\n\n"
- const lines = buffer.split('\n');
- buffer = lines.pop() || ''; // 保留未完成的行
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
- if (!line) continue;
- if (line.startsWith('event:')) {
- const eventType = line.substring(6).trim();
- events.push({ type: eventType, data: null });
- } else if (line.startsWith('data:')) {
- const data = line.substring(5).trim();
- if (events.length > 0) {
- events[events.length - 1].data = data;
- }
- }
- // 处理完整的事件
- while (events.length > 0 && events[0].data) {
- const event = events.shift();
- try {
- const data = JSON.parse(event.data);
- onEvent(event.type, data);
- } catch (e) {
- console.error('Parse error:', e, event.data);
- }
- }
- }
- }
- } catch (error) {
- onEvent('error', { error: error.message });
- }
- }
- async function sendMessageStream(message) {
- if (isTyping) return;
- isTyping = true;
- sendButton.disabled = true;
- // 添加用户消息
- addMessage('user', message);
- conversationHistory.push({ role: 'user', content: message });
- // 创建助手消息容器
- const assistantMsgDiv = document.createElement('div');
- assistantMsgDiv.className = 'flex justify-start';
- assistantMsgDiv.innerHTML = `
- <div class="message-assistant message-bubble rounded-lg p-4 shadow-sm">
- <div class="response-content">
- <div class="text" id="currentResponse"></div>
- </div>
- <div id="toolCallContainer"></div>
- </div>
- `;
- chatMessages.appendChild(assistantMsgDiv);
- const responseDiv = assistantMsgDiv.querySelector('#currentResponse');
- const toolContainer = assistantMsgDiv.querySelector('#toolCallContainer');
- let currentText = '';
- let toolCallsCount = 0;
- let toolCallItems = []; // 改为数组存储,按索引匹配
- let finalResponse = '';
- let toolCallPanel = null;
- let toolCallsContainer = null;
- await chatStream(message, (eventType, data) => {
- switch (eventType) {
- case 'start':
- responseDiv.innerHTML = '<span style="color: #888; font-style: italic;">🤔 AI 正在思考...</span>';
- break;
- case 'token':
- // 移除思考提示
- if (currentText === '') {
- responseDiv.innerHTML = '';
- }
- currentText += data.text || '';
- responseDiv.innerHTML = formatMessage(currentText);
- scrollToBottom();
- break;
- case 'tool_call':
- // 首次工具调用时创建面板
- if (!toolCallPanel) {
- toolCallPanel = createToolCallPanel();
- toolContainer.appendChild(toolCallPanel);
- toolCallsContainer = toolCallPanel.querySelector('.tool-calls-container');
- // 清空思考提示
- if (currentText === '' || currentText.includes('正在思考')) {
- responseDiv.innerHTML = '<span style="color: #888; font-style: italic;">🔧 正在调用工具...</span>';
- }
- }
- // 添加工具调用项
- const toolName = data.tool || 'unknown';
- const params = data.args || data.params || null;
- const toolUseId = data.tool_id || null;
- console.log('[tool_call] Adding tool:', { toolName, toolUseId, params });
- const itemInfo = addToolCallItem(toolCallsContainer, toolName, params, toolUseId);
- toolCallItems.push(itemInfo);
- toolCallsCount++;
- console.log('[tool_call] Current toolCallItems:', toolCallItems);
- updateToolPanelStatus(toolCallPanel, 'running', toolCallsCount);
- scrollToBottom();
- break;
- case 'tools_start':
- // 批量工具开始
- if (!toolCallPanel) {
- toolCallPanel = createToolCallPanel();
- toolContainer.appendChild(toolCallPanel);
- toolCallsContainer = toolCallPanel.querySelector('.tool-calls-container');
- }
- if (currentText === '' || currentText.includes('正在思考')) {
- responseDiv.innerHTML = '<span style="color: #888; font-style: italic;">🔧 正在调用工具...</span>';
- }
- scrollToBottom();
- break;
- case 'tool_done':
- // 工具执行完成 - 按 tool_use_id 或 tool_name 匹配
- const doneToolUseId = data.tool_id;
- const doneToolName = data.tool;
- const doneResult = data.result;
- console.log('[tool_done] Looking for tool:', { tool_id: doneToolUseId, tool: doneToolName });
- console.log('[tool_done] Current toolCallItems:', toolCallItems);
- // 查找匹配的工具调用项
- const doneItem = toolCallItems.find(item =>
- item.toolUseId === doneToolUseId || item.toolName === doneToolName
- );
- if (doneItem) {
- console.log('[tool_done] Found item, updating status:', doneItem.id);
- updateToolCallStatus(doneItem.id, 'success', doneResult);
- } else {
- console.warn('[tool_done] Tool item not found for:', { tool_id: doneToolUseId, tool: doneToolName });
- // 如果找不到匹配项,尝试通过 DOM 查找
- const fallbackItem = Array.from(document.querySelectorAll('.tool-call-item')).find(el => {
- return el.dataset.toolUseId === doneToolUseId || el.dataset.toolName === doneToolName;
- });
- if (fallbackItem) {
- console.log('[tool_done] Found via DOM fallback:', fallbackItem.id);
- updateToolCallStatus(fallbackItem.id, 'success', doneResult);
- }
- }
- scrollToBottom();
- break;
- case 'tool_error':
- // 工具执行错误 - 按 tool_use_id 或 tool_name 匹配
- const errorToolUseId = data.tool_id;
- const errorToolName = data.tool;
- const errorItem = toolCallItems.find(item =>
- item.toolUseId === errorToolUseId || item.toolName === errorToolName
- );
- if (errorItem) {
- updateToolCallStatus(errorItem.id, 'error', data.error);
- }
- if (toolCallPanel) {
- updateToolPanelStatus(toolCallPanel, 'error', toolCallsCount);
- }
- scrollToBottom();
- break;
- case 'complete':
- // 完成
- console.log('[complete] Tool calls finished, updating panel status');
- if (toolCallPanel) {
- updateToolPanelStatus(toolCallPanel, 'complete', toolCallsCount);
- }
- // 清空临时提示并显示最终响应
- if (data.response || currentText) {
- finalResponse = data.response || currentText;
- responseDiv.innerHTML = formatMessage(finalResponse);
- }
- conversationHistory.push({ role: 'assistant', content: finalResponse });
- scrollToBottom();
- break;
- case 'error':
- responseDiv.innerHTML = `<span style="color: #ef4444;">❌ 错误: ${escapeHtml(data.error || '未知错误')}</span>`;
- if (toolCallPanel) {
- updateToolPanelStatus(toolCallPanel, 'error', toolCallsCount);
- }
- scrollToBottom();
- break;
- }
- });
- // 重置状态
- isTyping = false;
- sendButton.disabled = false;
- userInput.focus();
- }
- // Load MCP servers
- async function loadMCPServers() {
- try {
- const response = await fetch(`${API_BASE}/api/mcp/servers`);
- const data = await response.json();
- mcpServers.innerHTML = data.servers.map(server => `
- <div class="mcp-server-tag ${server.enabled ? 'enabled' : 'disabled'}">
- <span class="mcp-status-dot ${server.enabled ? 'online' : 'offline'}"></span>
- <span class="font-medium">${server.name}</span>
- ${server.auth_type === 'jwt' ? '<span>🔒</span>' : ''}
- </div>
- `).join('');
- } catch (error) {
- console.error('Failed to load MCP servers:', error);
- }
- }
- // Check health
- async function checkHealth() {
- try {
- const response = await fetch(`${API_BASE}/api/health`);
- if (response.ok) {
- statusIndicator.innerHTML = `
- <span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
- <span class="text-sm text-gray-600">已连接</span>
- `;
- } else {
- throw new Error('Health check failed');
- }
- } catch (error) {
- statusIndicator.innerHTML = `
- <span class="w-2 h-2 bg-red-500 rounded-full"></span>
- <span class="text-sm text-gray-600">连接失败</span>
- `;
- }
- }
- // Event listeners
- chatForm.addEventListener('submit', (e) => {
- e.preventDefault();
- const message = userInput.value.trim();
- if (message) {
- sendMessageStream(message);
- userInput.value = '';
- }
- });
- // Initialize
- loadMCPServers();
- checkHealth();
- userInput.focus();
- // Make toggle functions global
- window.toggleToolPanel = toggleToolPanel;
- window.toggleCollapsible = toggleCollapsible;
- </script>
- </body>
- </html>
|