吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 159|回复: 1
收起左侧

[其他求助] 在线deespeek 假MCP(利用AI随便搞搞,学习一下),有缘人帮助完善一下谢谢

[复制链接]
jiangwu15 发表于 2026-1-14 18:09
25吾爱币
脚本 油猴
py 通讯

[Python] 纯文本查看 复制代码
# mcp_polling_server.py
from flask import Flask, request, jsonify
from flask_cors import CORS
from datetime import datetime
import re
import subprocess
import threading
import queue

app = Flask(__name__)
CORS(app)

# 使用线程安全的队列存储命令结果
result_queue = queue.Queue()
last_results = {}

class CommandHandler:
    @staticmethod
    def execute(cmd, param=None):
        cmd = cmd.lower().strip()
        
        if cmd == 'test':
            return "✅ 测试"
        elif cmd == 'time':
            return f"🕐 {datetime.now().strftime('%H:%M:%S')}"
        elif cmd == 'echo':
            return f"🔊 {param}" if param else "❌ 需要参数"
        elif cmd == 'cmd':
            return CommandHandler._run_system(param)
        else:
            return f"❌ 未知命令: {cmd}"
    
    @staticmethod
    def _run_system(command):
        if not command:
            return "❌ 需要命令"
        
        try:
            print(f"🚀 执行: {command}")
            
            result = subprocess.run(
                command, 
                shell=True, 
                capture_output=True, 
                text=True, 
                timeout=3
            )
            
            if result.returncode == 0:
                output = result.stdout.strip()
                return f"✅ 成功:\n{output[:500]}"
            else:
                error = result.stderr.strip()
                return f"❌ 失败:\n{error[:500]}"
                
        except subprocess.TimeoutExpired:
            return "⏰ 超时"
        except Exception as e:
            return f"💥 错误: {str(e)}"

def parse_mcp(content):
    """解析{1*1命令}1*1格式"""
    pattern = r'\{1\*1(.+?)\}1\*1'
    matches = re.findall(pattern, content)
    
    commands = []
    for match in matches:
        if ':' in match:
            cmd, param = match.split(':', 1)
            commands.append((cmd.strip(), param.strip()))
        else:
            commands.append((match.strip(), None))
    
    return commands

@app.route('/api/message', methods=['POST'])
def receive_message():
    """接收消息,执行命令,存到队列"""
    data = request.json
    content = data.get('content', '')
    
    print(f"\n[{datetime.now().strftime('%H:%M:%S')}] 📥 收到")
    print(f"内容: {content[:100]}")
    
    # 解析MCP命令
    mcp_commands = parse_mcp(content)
    execution_id = datetime.now().strftime('%Y%m%d%H%M%S%f')
    results = []
    
    for cmd, param in mcp_commands:
        print(f"执行: {cmd}" + (f" 参数: {param}" if param else ""))
        result = CommandHandler.execute(cmd, param)
        results.append({
            'cmd': cmd,
            'param': param,
            'result': result,
            'time': datetime.now().isoformat()
        })
        print(f"结果: {result[:100]}")
    
    # 存储到队列
    result_queue.put({
        'id': execution_id,
        'timestamp': datetime.now().isoformat(),
        'content': content,
        'results': results
    })
    
    # 也存到最近结果(用于GET查询)
    last_results[execution_id] = {
        'timestamp': datetime.now().isoformat(),
        'results': results
    }
    
    return jsonify({
        'ok': True,
        'id': execution_id,
        'message': f'已执行{len(results)}个命令',
        'queue_size': result_queue.qsize()
    })

@app.route('/api/results/poll', methods=['GET'])
def poll_results():
    """轮询获取结果(取一个就删除)"""
    try:
        if result_queue.empty():
            return jsonify({
                'has_result': False,
                'message': '队列为空',
                'queue_size': 0
            })
        
        # 从队列取出一个结果
        result = result_queue.get_nowait()
        
        return jsonify({
            'has_result': True,
            'result': result,
            'queue_size': result_queue.qsize()
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/results/peek', methods=['GET'])
def peek_results():
    """查看结果但不删除"""
    results_list = []
    
    # 获取队列中的所有结果(但不删除)
    temp_queue = queue.Queue()
    while not result_queue.empty():
        item = result_queue.get()
        results_list.append(item)
        temp_queue.put(item)
    
    # 恢复队列
    while not temp_queue.empty():
        result_queue.put(temp_queue.get())
    
    return jsonify({
        'count': len(results_list),
        'results': results_list,
        'queue_size': result_queue.qsize()
    })

@app.route('/api/results/clear', methods=['POST'])
def clear_results():
    """清空所有结果"""
    while not result_queue.empty():
        try:
            result_queue.get_nowait()
        except:
            pass
    
    last_results.clear()
    
    return jsonify({
        'ok': True,
        'message': '已清空结果队列',
        'queue_size': 0
    })

@app.route('/api/results/latest', methods=['GET'])
def get_latest():
    """获取最新的结果(不删除)"""
    if not last_results:
        return jsonify({'has_result': False})
    
    latest_id = max(last_results.keys())
    return jsonify({
        'has_result': True,
        'result': last_results[latest_id],
        'id': latest_id
    })

if __name__ == '__main__':
    print("="*60)
    print("🔄 MCP轮询服务器 (端口:5003)")
    print("📡 POST: http://127.0.0.1:5003/api/message")
    print("🔄 GET:  http://127.0.0.1:5003/api/results/poll")
    print("👀 GET:  http://127.0.0.1:5003/api/results/peek")
    print("🗑️ POST: http://127.0.0.1:5003/api/results/clear")
    print("\n📋 命令格式: {1*1命令}1*1 或 {1*1命令:参数}1*1")
    print("="*60)
    
    app.run(host='0.0.0.0', port=5003, debug=False)


[JavaScript] 纯文本查看 复制代码
// ==UserScript==
// @name         DeepSeek MCP监控器
// @namespace    https://chat.deepseek.com/*
// @version      2.0
// @description  悬浮框+MCP命令轮询+自动回复
// @author       You
// @match        https://chat.deepseek.com/*
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';
    
    // 存储当前URL路径和标题
    let currentPath = window.location.pathname;
    let lastTitle = '';
    
    // MCP服务器地址
    const MCP_POST_API = 'http://127.0.0.1:5003/api/message';
    const MCP_POLL_API = 'http://127.0.0.1:5003/api/results/poll';
    
    // 轮询状态
    let isPolling = false;
    let pollInterval = null;
    let lastMessageId = null;
    
    // 获取页面ID函数
    function getPageId() {
        const match = currentPath.match(/\/a\/chat\/s\/([a-f0-9-]+)/);
        return match ? match[1] : null;
    }
    
    // 获取初始化键名
    function getInitializedKey() {
        const pageId = getPageId();
        return pageId ? `deepseek_initialized_${pageId}` : 'deepseek_initialized_default';
    }
    
    // 显示悬浮框的函数
    function showFloatingBox() {
        const floatingBox = document.getElementById('simple-floating-box');
        if (floatingBox) {
            floatingBox.style.display = 'block';
        }
        const reopenBtn = document.getElementById('reopen-floating-box');
        if (reopenBtn) {
            reopenBtn.style.display = 'none';
        }
    }
    
    // 隐藏悬浮框的函数
    function hideFloatingBox() {
        const floatingBox = document.getElementById('simple-floating-box');
        if (floatingBox) {
            floatingBox.style.display = 'none';
        }
        createReopenButton();
    }
    
    // 创建重新打开按钮
    function createReopenButton() {
        let reopenBtn = document.getElementById('reopen-floating-box');
        if (reopenBtn) {
            reopenBtn.style.display = 'block';
            return;
        }
        
        reopenBtn = document.createElement('div');
        reopenBtn.id = 'reopen-floating-box';
        reopenBtn.style.cssText = `
            position: fixed;
            top: 60px;
            right: 20px;
            width: 30px;
            height: 30px;
            background: #4a6fa5;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 9998;
            font-size: 14px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            user-select: none;
        `;
        reopenBtn.textContent = '▶';
        reopenBtn.title = '重新打开悬浮框';
        
        reopenBtn.addEventListener('click', showFloatingBox);
        document.body.appendChild(reopenBtn);
    }
    
    // 提取SSE消息中的完整文本
    function extractFullMessage(responseText) {
        let fullMessage = '';
        const lines = responseText.split('\n');
        
        for (const line of lines) {
            if (line.startsWith('data: ') && line !== 'data: [DONE]') {
                try {
                    const json = JSON.parse(line.substring(6));
                    if (json.v && typeof json.v === 'string') {
                        fullMessage += json.v;
                    }
                    if (json.p && json.o === 'APPEND' && json.v && typeof json.v === 'string') {
                        fullMessage += json.v;
                    }
                } catch(e) {}
            }
        }
        
        return fullMessage;
    }
    
    // 发送消息到MCP服务器
    function sendToMCPAPI(content) {
        GM_xmlhttpRequest({
            method: 'POST',
            url: MCP_POST_API,
            headers: {'Content-Type': 'application/json'},
            data: JSON.stringify({
                content: content,
                timestamp: new Date().toISOString(),
                url: currentPath
            }),
            onload: function(response) {
                try {
                    const result = JSON.parse(response.responseText);
                    console.log('📤 MCP发送成功 ID:', result.id);
                    lastMessageId = result.id;
                    startPolling(); // 开始轮询结果
                    updateMCPStatus(`已发送,队列: ${result.queue_size}`);
                } catch(e) {
                    console.error('解析响应失败:', e);
                }
            },
            onerror: function(error) {
                console.error('❌ MCP发送失败:', error);
                updateMCPStatus('发送失败');
            }
        });
    }
    
    // 开始轮询MCP结果
    function startPolling() {
        if (isPolling) return;
        
        isPolling = true;
        updateMCPStatus('轮询中...');
        
        pollInterval = setInterval(() => {
            pollMCPResults();
        }, 1000);
    }
    
    // 停止轮询
    function stopPolling() {
        isPolling = false;
        if (pollInterval) {
            clearInterval(pollInterval);
            pollInterval = null;
        }
        updateMCPStatus('停止');
    }
    
    // 轮询MCP结果
    function pollMCPResults() {
        GM_xmlhttpRequest({
            method: 'GET',
            url: MCP_POLL_API,
            onload: function(response) {
                try {
                    const result = JSON.parse(response.responseText);
                    
                    if (result.has_result) {
                        console.log('🎯 获取到MCP结果:', result.result.id);
                        displayMCPResult(result.result);
                        
                        // 自动回复结果
                        autoReplyWithMCPResult(result.result.results);
                        
                        if (result.queue_size === 0) {
                            stopPolling();
                            updateMCPStatus('完成');
                        } else {
                            updateMCPStatus(`有结果,队列: ${result.queue_size}`);
                        }
                    } else {
                        updateMCPStatus(`轮询中,队列: ${result.queue_size}`);
                    }
                } catch(e) {
                    console.error('轮询解析失败:', e);
                }
            },
            onerror: function(error) {
                console.error('❌ 轮询失败:', error);
            }
        });
    }
    
    // 显示MCP结果
    function displayMCPResult(result) {
        const statusDiv = document.getElementById('mcp-status-display');
        if (statusDiv) {
            let html = '<strong>&#128203; MCP结果:</strong><br>';
            
            if (result.results && result.results.length > 0) {
                result.results.forEach((item, index) => {
                    html += `${index + 1}. <strong>${item.cmd}</strong>: ${item.result.substring(0, 50)}...<br>`;
                });
            }
            
            statusDiv.innerHTML = html;
        }
    }
    
    // 自动回复MCP结果
    function autoReplyWithMCPResult(results) {
    const textarea = getTextarea();
    if (!textarea || !results || results.length === 0) {
        console.log('&#10060; 无法自动回复:无输入框或无结果');
        return;
    }
    
    let reply = '&#128295; 命令执行结果:\n\n';
    
    results.forEach(item => {
        reply += `【${item.cmd}】\n${item.result}\n\n`;
    });
    
    console.log('&#128221; 准备填充MCP结果到输入框');
    
    // 填充到输入框
    textarea.value = reply;
    textarea.dispatchEvent(new Event('input', { bubbles: true }));
    textarea.dispatchEvent(new Event('change', { bubbles: true }));
    
    console.log('&#9989; MCP结果已填充到输入框');
    
    // 延迟发送(确保页面更新)
    setTimeout(() => {
        console.log('&#128640; 开始发送MCP结果...');
        
        // 方法1:使用sendMessage相同的按钮查找逻辑
        const sendBtn = document.querySelector('button[aria-label*="发送"], button[type="submit"]');
        console.log('&#128269; 查找发送按钮:', sendBtn ? '找到' : '未找到');
        
        if (sendBtn) {
            console.log('&#127919; 发送按钮信息:', {
                tag: sendBtn.tagName,
                disabled: sendBtn.disabled,
                'aria-disabled': sendBtn.getAttribute('aria-disabled'),
                text: sendBtn.textContent || sendBtn.innerHTML.substring(0, 50)
            });
            
            if (!sendBtn.disabled && sendBtn.getAttribute('aria-disabled') !== 'true') {
                sendBtn.click();
                console.log('&#9989; MCP结果已通过按钮发送');
                updateMCPStatus('&#9989; 自动回复已发送');
            } else {
                console.log('&#9888;&#65039; 按钮不可用,尝试键盘方式');
                // 键盘备选方案
                textarea.dispatchEvent(new KeyboardEvent('keydown', {
                    key: 'Enter',
                    ctrlKey: true,
                    bubbles: true
                }));
                console.log('&#9989; MCP结果已通过键盘发送');
                updateMCPStatus('&#9989; 自动回复已发送(键盘)');
            }
        } else {
            console.log('&#10060; 未找到发送按钮,尝试键盘方式');
            // 键盘备选方案
            textarea.dispatchEvent(new KeyboardEvent('keydown', {
                key: 'Enter',
                ctrlKey: true,
                bubbles: true
            }));
            console.log('&#9989; MCP结果已通过键盘发送');
            updateMCPStatus('&#9989; 自动回复已发送(键盘)');
        }

        sendMessage();
    }, 1000); // 增加延迟确保可靠
}
    

    // 获取输入框
    function getTextarea() {
        const textareas = document.querySelectorAll('textarea');
        return textareas.length > 0 ? textareas[0] : null;
    }
    function triggerDebugButton() {
        const focusRing = document.querySelector('.ds-focus-ring[style*="--ds-focus-ring-offset: -2px"]');
        if (focusRing && focusRing.parentElement) {
            focusRing.parentElement.click();
            console.log('调试按钮点击成功');
            return '按钮点击成功';
        }
        console.log('未找到调试按钮');
        return '未找到按钮';
    }

    // 发送消息
    function sendMessage(message) {
        const textarea = getTextarea();
        if (!textarea) {
            console.error('未找到输入框');
            return false;
        }
        
        textarea.value = message;
        textarea.dispatchEvent(new Event('input', { bubbles: true }));
        
        setTimeout(() => {
            
            const sendBtn = document.querySelector('button[aria-label*="发送"], button[type="submit"]');
            if (sendBtn) {
                sendBtn.click();
                console.log('&#9989; 消息已发送:', message);
            } else {
                textarea.dispatchEvent(new KeyboardEvent('keydown', {
                    key: 'Enter',
                    ctrlKey: true,
                    bubbles: true
                }));
                console.log('&#9989; 已尝试发送消息');
                triggerDebugButton();
            }
        }, 500);
        triggerDebugButton();
        return true;
    }
    
    // 更新MCP状态显示
    function updateMCPStatus(text) {
        const statusDiv = document.getElementById('mcp-status-display');
        if (statusDiv) {
            statusDiv.innerHTML = `&#128260; ${text}`;
        }
    }
    
    // 初始化函数
    function init() {
        console.log('脚本初始化,当前路径:', currentPath);
        
        // 获取页面标题
        const pageTitle = getPageTitle();
        
        if (pageTitle && pageTitle !== lastTitle) {
            lastTitle = pageTitle;
            createFloatingBox(pageTitle);
            startUrlChangeListener();
        }
    }
    
    // 获取页面标题函数
    function getPageTitle() {
        const titleElement = document.querySelector('div[tabindex="0"][style="outline: none;"]');
        return titleElement ? titleElement.textContent.trim() : null;
    }
    
    // 创建悬浮框函数
    function createFloatingBox(title) {
        const oldBox = document.getElementById('simple-floating-box');
        if (oldBox) oldBox.remove();
        
        const pageId = getPageId();
        const INITIALIZED_KEY = getInitializedKey();
        const isInitialized = localStorage.getItem(INITIALIZED_KEY) === 'true';
        
        // 添加样式
        GM_addStyle(`
            #simple-floating-box {
                position: fixed;
                top: 10px;
                right: 10px;
                width: 350px;
                background: white;
                border: 2px solid #4a6fa5;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 9999;
                font-family: Arial, sans-serif;
                display: block;
                opacity: 1 !important;
            }
            
            #simple-header {
                background: #4a6fa5;
                color: white;
                padding: 12px 15px;
                font-weight: bold;
                font-size: 14px;
                border-top-left-radius: 6px;
                border-top-right-radius: 6px;
                border-bottom: 2px solid #3a5a85;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            
            #simple-content {
                padding: 15px;
                font-size: 14px;
                line-height: 1.5;
                background: white;
            }
            
            .simple-buttons {
                display: flex;
                gap: 10px;
                margin: 10px 0;
            }
            
            .simple-btn {
                flex: 1;
                padding: 8px 0;
                border: none;
                border-radius: 4px;
                font-size: 14px;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s;
            }
            
            #mcp-status {
                margin-top: 10px;
                padding: 8px;
                background: #f0f8ff;
                border: 1px solid #d1e3ff;
                border-radius: 4px;
                font-size: 12px;
                min-height: 40px;
            }
        `);
        
        // 创建悬浮框
        const floatingBox = document.createElement('div');
        floatingBox.id = 'simple-floating-box';
        
        floatingBox.innerHTML = `
            <div id="simple-header">
                <span>&#128295; MCP监控器</span>
                <div>
                    <button id="simple-minimize" title="最小化" style="background:none; border:none; color:white; font-size:16px; cursor:pointer; padding:0 5px;">_</button>
                    <button id="simple-close" title="关闭" style="background:none; border:none; color:white; font-size:20px; cursor:pointer; padding:0 5px;">×</button>
                </div>
            </div>
            <div id="simple-content">
                <div style="margin-bottom: 10px;">
                    <strong>会话:</strong> ${title}<br>
                    <strong>页面ID:</strong> ${pageId || '未获取'}
                </div>
                
                <div class="simple-buttons">
                    <button id="send-test-btn" class="simple-btn" style="background: #28a745; color: white;">
                        发送测试消息
                    </button>
                    <button id="send-mcp-btn" class="simple-btn" style="background: #2196F3; color: white;">
                        发送MCP命令
                    </button>
                </div>
                
                <div class="simple-buttons">
                    <button id="auto-reply-btn" class="simple-btn" style="background: #FF9800; color: white;">
                        自动回复开关
                    </button>
                    <button id="poll-toggle-btn" class="simple-btn" style="background: #9C27B0; color: white;">
                        轮询开关
                    </button>
                </div>
                
                <div id="mcp-status">
                    <div id="mcp-status-display">等待命令执行...</div>
                </div>
            </div>
        `;
        
        document.body.appendChild(floatingBox);
        
        // 按钮事件
        document.getElementById('simple-minimize').addEventListener('click', hideFloatingBox);
        document.getElementById('simple-close').addEventListener('click', hideFloatingBox);
        
        document.getElementById('send-test-btn').addEventListener('click', function() {
            sendMessage('这是一个测试消息');
        });
        
        document.getElementById('send-mcp-btn').addEventListener('click', function() {
            sendMessage('测试 {1*1cmd:dir}1*1 命令');
        });
        
        let autoReplyEnabled = true;
        document.getElementById('auto-reply-btn').addEventListener('click', function() {
            autoReplyEnabled = !autoReplyEnabled;
            this.style.background = autoReplyEnabled ? '#FF9800' : '#666';
            updateMCPStatus(autoReplyEnabled ? '自动回复已开启' : '自动回复已关闭');
        });
        
        document.getElementById('poll-toggle-btn').addEventListener('click', function() {
            if (isPolling) {
                stopPolling();
                this.style.background = '#666';
            } else {
                startPolling();
                this.style.background = '#9C27B0';
            }
        });
    }
    
    // 监听XHR请求
    const originalOpen = XMLHttpRequest.prototype.open;
    const originalSend = XMLHttpRequest.prototype.send;
    
    XMLHttpRequest.prototype.open = function(method, url) {
        this._url = url;
        return originalOpen.apply(this, arguments);
    };
    
    XMLHttpRequest.prototype.send = function() {
        if (this._url && this._url.includes('/api/v0/chat/completion')) {
            console.log('&#127919; 捕获AI请求');
            
            const originalOnReadyStateChange = this.onreadystatechange;
            this.onreadystatechange = function() {
                if (this.readyState === 4 && this.responseText) {
                    const fullMessage = extractFullMessage(this.responseText);
                    
                    if (fullMessage) {
                        console.log('&#128214; 收到AI回复,发送到MCP服务器');
                        sendToMCPAPI(fullMessage);
                    }
                }
                
                if (originalOnReadyStateChange) {
                    originalOnReadyStateChange.apply(this, arguments);
                }
            };
        }
        
        return originalSend.apply(this, arguments);
    };
    
    // URL变化监听
    function startUrlChangeListener() {
        console.log('开始监听URL变化');
        
        window.addEventListener('popstate', handleUrlChange);
        window.addEventListener('hashchange', handleUrlChange);
        
        const originalPushState = history.pushState;
        const originalReplaceState = history.replaceState;
        
        history.pushState = function() {
            originalPushState.apply(this, arguments);
            setTimeout(handleUrlChange, 100);
        };
        
        history.replaceState = function() {
            originalReplaceState.apply(this, arguments);
            setTimeout(handleUrlChange, 100);
        };
        
        setInterval(checkUrlChange, 500);
    }
    
    function checkUrlChange() {
        const newPath = window.location.pathname;
        if (newPath.startsWith('/a/chat/s/') && newPath !== currentPath) {
            currentPath = newPath;
            updateTitleOnUrlChange();
        }
    }
    
    function handleUrlChange() {
        const newPath = window.location.pathname;
        if (newPath.startsWith('/a/chat/s/') && newPath !== currentPath) {
            currentPath = newPath;
            setTimeout(updateTitleOnUrlChange, 300);
        }
    }
    
    function updateTitleOnUrlChange() {
        const pageTitle = getPageTitle();
        if (pageTitle && pageTitle !== lastTitle) {
            lastTitle = pageTitle;
            createFloatingBox(pageTitle);
        }
    }
    
    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        setTimeout(init, 1000);
    }
    
    console.log('&#9989; DeepSeek MCP监控器已加载');
    
})();

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| jiangwu15 发表于 2026-1-14 22:32
完整版:可以的话大佬帮我优化一下
初始化,就是发送角色卡,告诉AI调用命令。



py
[Python] 纯文本查看 复制代码
# mcp_polling_server.py - 直接传递版本
from flask import Flask, request, jsonify
from flask_cors import CORS
from datetime import datetime
import re
import subprocess
import queue

app = Flask(__name__)
CORS(app)

# 使用线程安全的队列存储命令结果
result_queue = queue.Queue()
last_results = {}

def parse_mcp(content):
    """解析各种可能的MCP命令格式 - 增强版"""
    import re
    
    commands = []
    
    print(f"&#128269; 开始解析内容: '{content}'")
    
    # 模式1:标准格式 {1*1...}1*1
    pattern1 = r'\{1\*1([^}]+)\}1\*1'
    matches1 = re.findall(pattern1, content)
    for match in matches1:
        match = match.strip()
        if match:
            commands.append((match, None))
    
    # 模式2:漏掉{的格式 1*1...}1*1
    pattern2 = r'1\*1([^}]+)\}1\*1'
    matches2 = re.findall(pattern2, content)
    for match in matches2:
        match = match.strip()
        if match and (match, None) not in commands:
            commands.append((match, None))
    
    # 模式3:更宽松的匹配
    if not commands:
        if '1*1' in content:
            # 查找 1*1 和 }1*1 之间的内容
            start_idx = content.find('1*1')
            if start_idx != -1:
                start_idx += 3  # 跳过 "1*1"
                end_idx = content.find('}1*1', start_idx)
                
                if end_idx != -1:
                    cmd = content[start_idx:end_idx].strip()
                    if cmd:
                        commands.append((cmd, None))
                else:
                    # 如果没有找到}1*1,取到字符串结束
                    cmd = content[start_idx:].strip()
                    if cmd:
                        commands.append((cmd, None))
    
    print(f"&#128202; 解析结果: 找到 {len(commands)} 个命令")
    for i, (cmd, _) in enumerate(commands):
        print(f"  命令{i+1}: '{cmd}'")
    
    return commands
   
def execute_command(command):
    """执行单个系统命令"""
    if not command:
        return "&#10060; 空命令"
    
    try:
        print(f"  执行: {command[:50]}...")
        
        # 增加超时保护
        result = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            encoding='gbk',
            errors='ignore',
            timeout=30  # 单个命令30秒超时
        )
        
        # 处理输出
        output = ""
        
        if result.stdout:
            stdout = result.stdout.strip()
            # 限制输出长度,防止过长
            if len(stdout) > 5000:
                stdout = stdout[:5000] + "\n...(输出过长,已截断)"
            output += f"&#128228; 输出:\n{stdout}\n"
        
        if result.stderr:
            stderr = result.stderr.strip()
            if stderr:
                output += f"&#128228; 错误输出:\n{stderr}\n"
        
        if not output.strip():
            output = "&#9989; 命令执行完成(无输出)"
        
        # 添加执行状态
        if result.returncode == 0:
            return output
        else:
            return f"&#9888;&#65039; 命令返回非零代码 {result.returncode}\n{output}"
            
    except subprocess.TimeoutExpired:
        return "&#9200; 命令执行超时(超过30秒)"
    except Exception as e:
        return f"&#128293; 执行异常: {str(e)}"

@app.route('/api/message', methods=['POST'])
def receive_message():
    """接收消息,执行命令,存到队列"""
    data = request.json
    content = data.get('content', '')
    
    print(f"\n[{datetime.now().strftime('%H:%M:%S')}] &#128233; 收到消息")
    print(f"内容长度: {len(content)} 字符")
    
    # 解析MCP命令
    mcp_commands = parse_mcp(content)
    execution_id = datetime.now().strftime('%Y%m%d%H%M%S%f')
    results = []
    
    print(f"&#128202; 解析到 {len(mcp_commands)} 个命令")
    
    # &#128640; 使用循环处理多个命令
    for i, (cmd, _) in enumerate(mcp_commands):
        print(f"\n&#128260; 处理命令 [{i+1}/{len(mcp_commands)}]: {cmd}")
        
        try:
            # 执行单个命令
            result = execute_command(cmd)
            
            # 添加到结果列表
            results.append({
                'cmd': cmd,
                'result': result,
                'time': datetime.now().isoformat()
            })
            
            print(f"&#9989; 命令 [{i+1}] 执行完成")
            
        except Exception as e:
            error_result = f"&#10060; 命令执行异常: {str(e)}"
            results.append({
                'cmd': cmd,
                'result': error_result,
                'time': datetime.now().isoformat()
            })
            print(f"&#10060; 命令 [{i+1}] 执行失败: {e}")
    
    # 如果没有任何命令,返回空
    if not results:
        print("&#128237; 没有可执行的命令")
        return jsonify({
            'ok': True,
            'id': execution_id,
            'message': '未找到MCP命令格式',
            'queue_size': result_queue.qsize()
        })
    
    # 汇总所有结果
    summary = {
        'id': execution_id,
        'timestamp': datetime.now().isoformat(),
        'content': content,
        'results': results,
        'total_commands': len(results),
        'success_count': len([r for r in results if not r['result'].startswith('&#10060;')])
    }
    
    # 存储到队列
    print(f"&#128230; 将汇总结果放入队列")
    result_queue.put(summary)
    
    print(f"&#127919; 所有命令处理完成,成功 {summary['success_count']}/{summary['total_commands']}")
    
    return jsonify({
        'ok': True,
        'id': execution_id,
        'message': f'已处理{len(results)}个命令',
        'queue_size': result_queue.qsize()
    })
    
    
    # &#128640; 如果没有解析到命令,返回空结果
    if not mcp_commands:
        print("&#128237; 未解析到MCP命令,跳过执行")
        
        # 仍然返回成功,但结果为空
        return jsonify({
            'ok': True,
            'id': execution_id,
            'message': '未找到MCP命令格式',
            'queue_size': result_queue.qsize()
        })
    
    for cmd, _ in mcp_commands:
        print(f"&#128260; 开始执行命令: '{cmd}'")
        result = execute_command(cmd)
        print(f"命令执行结果长度: {len(result)} 字符")
        
        results.append({
            'cmd': cmd,
            'result': result,
            'time': datetime.now().isoformat()
        })
    
    # 存储到队列
    print(f"&#128230; 将结果放入队列,当前队列大小: {result_queue.qsize()}")
    result_queue.put({
        'id': execution_id,
        'timestamp': datetime.now().isoformat(),
        'content': content,
        'results': results
    })
    print(f"&#128230; 放入队列后,队列大小: {result_queue.qsize()}")
    
    return jsonify({
        'ok': True,
        'id': execution_id,
        'message': f'已执行{len(results)}个命令',
        'queue_size': result_queue.qsize()
    })

@app.route('/api/results/poll', methods=['GET'])
def poll_results():
    """轮询获取结果"""
    try:
        if result_queue.empty():
            return jsonify({
                'has_result': False,
                'message': '队列为空',
                'queue_size': 0
            })
        
        result = result_queue.get_nowait()
        
        return jsonify({
            'has_result': True,
            'result': result,
            'queue_size': result_queue.qsize()
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/results/clear', methods=['POST'])
def clear_results():
    """清空所有结果"""
    while not result_queue.empty():
        try:
            result_queue.get_nowait()
        except:
            pass
    
    return jsonify({
        'ok': True,
        'message': '已清空结果队列',
        'queue_size': 0
    })

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'queue_size': result_queue.qsize()
    })

if __name__ == '__main__':
    print("="*60)
    print("&#129302; MCP通用系统命令服务器")
    print("&#128225; 地址: http://127.0.0.1:5003")
    print("&#128232; 接收: POST /api/message")
    print("&#128229; 轮询: GET /api/results/poll")
    print("")
    print("&#128161; 命令格式: {1*1命令}1*1")
    print("&#128161; 例如: {1*1systeminfo}1*1")
    print("&#128161; 例如: {1*1powershell Get-Process}1*1")
    print("&#128161; 例如: {1*1cmd /c dir C:\\}1*1")
    print("="*60)
    
    app.run(host='0.0.0.0', port=5003, debug=False)



脚本
[JavaScript] 纯文本查看 复制代码
// ==UserScript==
// @name         DeepSeek MCP监控器
// @namespace    https://chat.deepseek.com/*
// @version      2.1
// @description  悬浮框+MCP命令轮询+自动回复(自动轮询版)
// [url=home.php?mod=space&uid=686208]@AuThor[/url]       You
// [url=home.php?mod=space&uid=195849]@match[/url]        https://chat.deepseek.com/*
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';
    
    // 存储当前URL路径和标题
    let currentPath = window.location.pathname;
    let lastTitle = '';
    
    // MCP服务器地址
    const MCP_POST_API = 'http://127.0.0.1:5003/api/message';
    const MCP_POLL_API = 'http://127.0.0.1:5003/api/results/poll';
    
    // 轮询状态
    let isPolling = false;
    let pollInterval = null;
    const MCP_COMMAND_PATTERN = /1\*1([^}]+)\}1\*1/g;
    
    // 获取页面ID函数
    function getPageId() {
        const match = currentPath.match(/\/a\/chat\/s\/([a-f0-9-]+)/);
        return match ? match[1] : null;
    }
    
   function hasMCPCommands(content) {
    console.log('&#128269; 检查MCP命令,原始内容:', content);
    
    // 先看看内容是否包含我们需要的关键词
    if (content.includes('1*1') && content.includes('}1*1')) {
        console.log('&#9989; 检测到可能的MCP命令格式');
    }
    
    const matches = content.match(MCP_COMMAND_PATTERN);
    console.log('正则匹配结果:', matches);
    
    return matches && matches.length > 0;
}
    
    // 获取初始化键名
    function getInitializedKey() {
        const pageId = getPageId();
        return pageId ? `deepseek_initialized_${pageId}` : 'deepseek_initialized_default';
    }
    
    // 显示悬浮框
    function showFloatingBox() {
        const floatingBox = document.getElementById('simple-floating-box');
        if (floatingBox) {
            floatingBox.style.display = 'block';
        }
        const reopenBtn = document.getElementById('reopen-floating-box');
        if (reopenBtn) {
            reopenBtn.style.display = 'none';
        }
    }
    
    // 隐藏悬浮框
    function hideFloatingBox() {
        const floatingBox = document.getElementById('simple-floating-box');
        if (floatingBox) {
            floatingBox.style.display = 'none';
        }
        createReopenButton();
    }
    
    // 创建重新打开按钮
    function createReopenButton() {
        let reopenBtn = document.getElementById('reopen-floating-box');
        if (reopenBtn) {
            reopenBtn.style.display = 'block';
            return;
        }
        
        reopenBtn = document.createElement('div');
        reopenBtn.id = 'reopen-floating-box';
        reopenBtn.style.cssText = `
            position: fixed;
            top: 60px;
            right: 20px;
            width: 30px;
            height: 30px;
            background: #4a6fa5;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 9998;
            font-size: 14px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            user-select: none;
        `;
        reopenBtn.textContent = '&#9654;';
        reopenBtn.title = '重新打开悬浮框';
        
        reopenBtn.addEventListener('click', showFloatingBox);
        document.body.appendChild(reopenBtn);
    }
    
    // 提取SSE消息中的完整文本
    function extractFullMessage(responseText) {
        let fullMessage = '';
        const lines = responseText.split('\n');
        
        for (const line of lines) {
            if (line.startsWith('data: ') && line !== 'data: [DONE]') {
                try {
                    const json = JSON.parse(line.substring(6));
                    if (json.v && typeof json.v === 'string') {
                        fullMessage += json.v;
                    }
                    if (json.p && json.o === 'APPEND' && json.v && typeof json.v === 'string') {
                        fullMessage += json.v;
                    }
                } catch(e) {}
            }
        }
        
        return fullMessage;
    }
    
    // 发送消息到MCP服务器
    function sendToMCPAPI(content) {
    console.log('&#128228; 发送到MCP服务器:', content.substring(0, 100));
    
    // &#128640; 关键修改:不再检查,直接发送所有内容
    // 让后端去判断是否是MCP命令
    
    GM_xmlhttpRequest({
        method: 'POST',
        url: MCP_POST_API,
        headers: {'Content-Type': 'application/json'},
        data: JSON.stringify({
            content: content,
            timestamp: new Date().toISOString(),
            url: currentPath
        }),
        onload: function(response) {
            if (response.status >= 200 && response.status < 300) {
                console.log('&#9989; 内容已发送到MCP服务器');
            } else {
                console.error('&#10060; MCP服务器返回错误:', response.status);
            }
        },
        onerror: function(error) {
            console.error('&#10060; 发送失败:', error.statusText || '未知错误');
        }
    });
}
    
    // 开始轮询MCP结果(默认开启)
    function startPolling() {
        if (isPolling) return;
        
        isPolling = true;
        console.log('&#128260; 开始轮询MCP结果');
        updateMCPStatus('轮询中...');
        
        pollInterval = setInterval(() => {
            pollMCPResults();
        }, 1000);
    }
    
    // 停止轮询
    function stopPolling() {
        isPolling = false;
        if (pollInterval) {
            clearInterval(pollInterval);
            pollInterval = null;
        }
        console.log('&#128721; 停止轮询');
        updateMCPStatus('停止');
    }
    
    // 轮询MCP结果
    function pollMCPResults() {
        GM_xmlhttpRequest({
            method: 'GET',
            url: MCP_POLL_API,
            onload: function(response) {
                try {
                    const result = JSON.parse(response.responseText);
                    
                    if (result.has_result) {
                        console.log('&#127919; 获取到MCP结果:', result.result.id);
                        displayMCPResult(result.result);
                        
                        // 自动回复结果
                        autoReplyWithMCPResult(result.result.results);
                        
                        updateMCPStatus(`&#9989; 有结果,队列: ${result.queue_size}`);
                    } else {
                        updateMCPStatus(`&#9203; 轮询中,队列: ${result.queue_size}`);
                    }
                } catch(e) {
                    console.error('轮询解析失败:', e);
                }
            },
            onerror: function(error) {
                console.error('&#10060; 轮询失败:', error);
            }
        });
    }
    
    // 显示MCP结果
    function displayMCPResult(result) {
        const statusDiv = document.getElementById('mcp-status-display');
        if (statusDiv) {
            let html = '<strong>&#128203; MCP结果:</strong><br>';
            
            if (result.results && result.results.length > 0) {
                result.results.forEach((item, index) => {
                    html += `${index + 1}. <strong>${item.cmd}</strong>: ${item.result.substring(0, 50)}...<br>`;
                });
            }
            
            statusDiv.innerHTML = html;
        }
    }
    
    // 自动回复MCP结果
    function autoReplyWithMCPResult(results) {
        if (!results || results.length === 0) {
            console.log('&#10060; 无法自动回复:无结果');
            return;
        }
        
        console.log('&#128221; MCP结果已收到,显示弹窗...');
        
        // 显示弹窗
        showCenterNotification("&#128260; MCP处理中", "正在发送命令结果,请勿点击...");
        
        // 构建回复消息
        let reply = '&#128295; 命令执行结果:\n\n';
        results.forEach((item, index) => {
            reply += `【${item.cmd}】\n${item.result}\n\n`;
            updateCenterNotification(`处理命令 ${index + 1}/${results.length}...`);
        });
        
        // 延迟一点时间让弹窗显示出来
        setTimeout(() => {
            updateCenterNotification('正在发送到聊天框...');
            
            // 直接调用sendMessage发送
            sendMessage(reply);
            
            console.log('&#9989; MCP结果已调用sendMessage发送');
            updateMCPStatus('&#9989; 自动回复已发送');
            
            // 发送完成后1.5秒移除弹窗
            setTimeout(() => {
                removeCenterNotification();
                console.log('&#9989; 弹窗已移除');
            }, 1500);
            
        }, 500);
        triggerDebugButton()
    }
    
    // 获取输入框
    function getTextarea() {
        const textareas = document.querySelectorAll('textarea');
        return textareas.length > 0 ? textareas[0] : null;
    }
    
    // 发送消息
    // 发送消息
function sendMessage(message) {
    const textarea = getTextarea();
    if (!textarea) {
        console.error('未找到输入框');
        return false;
    }
    
    textarea.value = message;
    textarea.dispatchEvent(new Event('input', { bubbles: true }));
    
    setTimeout(() => {
        const sendBtn = document.querySelector('button[aria-label*="发送"], button[type="submit"]');
        if (sendBtn) {
            sendBtn.click();
            console.log('&#9989; 消息已发送:', message.substring(0, 50) + '...');
        } else {
            textarea.dispatchEvent(new KeyboardEvent('keydown', {
                key: 'Enter',
                ctrlKey: true,
                bubbles: true
            }));
            console.log('&#9989; 已尝试发送消息');
            
            // &#128640; 关键:添加triggerDebugButton调用
            setTimeout(() => {
                triggerDebugButton();
            }, 100);
        }
    }, 500);
    
    // 同时立即触发一次
    setTimeout(() => {
        triggerDebugButton();
    }, 300);
    
    return true;
}

// 添加triggerDebugButton函数(如果不存在)
function triggerDebugButton() {
    try {
        // 查找可能的发送按钮
        const sendButtons = document.querySelectorAll('button');
        let found = false;
        
        sendButtons.forEach(btn => {
            const ariaLabel = btn.getAttribute('aria-label');
            if (ariaLabel && ariaLabel.includes('发送')) {
                btn.click();
                console.log('&#128280; 通过aria-label找到发送按钮');
                found = true;
            }
        });
        
        if (!found) {
            // 尝试查找特定样式的按钮
            const focusRing = document.querySelector('.ds-focus-ring[style*="--ds-focus-ring-offset: -2px"]');
            if (focusRing && focusRing.parentElement) {
                focusRing.parentElement.click();
                console.log('&#128280; 通过focus-ring找到发送按钮');
                found = true;
            }
        }
        
        if (!found) {
            console.log('&#128269; 未找到发送按钮,尝试其他方法');
            
            // 尝试模拟Ctrl+Enter
            const textarea = getTextarea();
            if (textarea) {
                textarea.dispatchEvent(new KeyboardEvent('keydown', {
                    key: 'Enter',
                    ctrlKey: true,
                    bubbles: true
                }));
                console.log('&#128280; 已模拟Ctrl+Enter发送');
            }
        }
        
        return found ? '按钮点击成功' : '未找到按钮';
    } catch (error) {
        console.error('triggerDebugButton出错:', error);
        return '出错';
    }
    function triggerDebugButton() {
        const focusRing = document.querySelector('.ds-focus-ring[style*="--ds-focus-ring-offset: -2px"]');
        if (focusRing && focusRing.parentElement) {
            focusRing.parentElement.click();
            console.log('调试按钮点击成功');
            return '按钮点击成功';
        }
        console.log('未找到调试按钮');
        return '未找到按钮';
    }
}
    
    // 显示中心通知
    function showCenterNotification(title = "&#128260; 处理中", text = "请勿点击,正在发送MCP结果...") {
        // 移除已有的弹窗
        removeCenterNotification();
        
        const notification = document.createElement('div');
        notification.id = 'mcp-notification-center';
        
        notification.innerHTML = `
            <div id="mcp-notification-content">
                <div id="mcp-notification-spinner"></div>
                <div id="mcp-notification-title">${title}</div>
                <div id="mcp-notification-text">${text}</div>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // 5秒后自动消失(防止卡住)
        setTimeout(() => {
            removeCenterNotification();
        }, 5000);
        
        return notification;
    }
    
    // 更新弹窗文本
    function updateCenterNotification(text) {
        const textEl = document.getElementById('mcp-notification-text');
        if (textEl) {
            textEl.textContent = text;
        }
    }
    
    // 移除弹窗
    function removeCenterNotification() {
        const notification = document.getElementById('mcp-notification-center');
        if (notification) {
            notification.remove();
        }
    }
    
    // 更新MCP状态显示
    function updateMCPStatus(text) {
        const statusDiv = document.getElementById('mcp-status-display');
        if (statusDiv) {
            statusDiv.innerHTML = `${text}`;
        }
    }
    
    // 初始化函数 - 发送系统命令说明给AI
    function sendSystemCommandsInfo() {
        const pageId = getPageId();
        const INITIALIZED_KEY = getInitializedKey();
        const isInitialized = localStorage.getItem(INITIALIZED_KEY) === 'true';
        
        if (isInitialized) {
            console.log('当前页面已初始化');
            return;
        }
        
        console.log('开始发送系统命令说明...');
        
        // 系统命令说明消息
        const systemMessage = `# &#128736;&#65039; MCP系统命令说明

你好!我是MCP系统助手。我可以通过特殊的命令格式帮你执行系统操作:

## &#128221; 命令格式
命令格式: {1*1echo 测试1}1*1 或者多次一次性 {1*1echo 测试1}1*1 {1*1echo 测试2}1*1 {1*1echo 测试3}1*1

### 系统CMD管道命令
1. {1*1echo 测试1}1*1
2. {1*1其他任意命令 测试1}1*1

## &#9888;&#65039; 注意事项
- 每条消息可以包含多个命令
- 命令执行结果会自动回复
- 请谨慎执行系统命令
- 调用过程中恢复给用户的不要建议多余的命令
- 遵守MCP 隐藏对话协议
- 轮询过程中,你不要建议或者添加任意额外需要执行的多余命令!
- 调用命令的过程中严格规范格式
现在你可以尝试发送命令了!,以上收到后你回复收到!,不要输出任何东西`;

        // 发送系统说明
        setTimeout(() => {
            sendMessage(systemMessage);
            
            // 标记为已初始化
            localStorage.setItem(INITIALIZED_KEY, 'true');
            console.log('&#9989; 系统命令说明已发送,页面标记为已初始化');
            
            // 更新悬浮框状态
            const initBtn = document.getElementById('init-button');
            if (initBtn) {
                initBtn.disabled = true;
                initBtn.textContent = '&#10003; 已初始化';
                initBtn.style.background = '#6c757d';
            }
        }, 1000);
    }
    
    // 初始化函数
    function init() {
        console.log('脚本初始化,当前路径:', currentPath);
        
        // 获取页面标题
        const pageTitle = getPageTitle();
        
        if (pageTitle && pageTitle !== lastTitle) {
            lastTitle = pageTitle;
            createFloatingBox(pageTitle);
            startUrlChangeListener();
        }
        
        // &#128640; 关键修改:默认开启轮询
        setTimeout(() => {
            console.log('&#128260; 默认开启MCP结果轮询');
            startPolling();
        }, 2000);
    }
    
    // 获取页面标题函数
    function getPageTitle() {
        const titleElement = document.querySelector('div[tabindex="0"][style="outline: none;"]');
        return titleElement ? titleElement.textContent.trim() : null;
    }
    
    // 创建悬浮框函数(简化版)
    function createFloatingBox(title) {
        const oldBox = document.getElementById('simple-floating-box');
        if (oldBox) oldBox.remove();
        
        const pageId = getPageId();
        const INITIALIZED_KEY = getInitializedKey();
        const isInitialized = localStorage.getItem(INITIALIZED_KEY) === 'true';
        
        // 添加样式
        GM_addStyle(`
            #simple-floating-box {
                position: fixed;
                top: 10px;
                right: 10px;
                width: 350px;
                background: white;
                border: 2px solid #4a6fa5;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 9999;
                font-family: Arial, sans-serif;
                display: block;
            }
            
            #simple-header {
                background: #4a6fa5;
                color: white;
                padding: 12px 15px;
                font-weight: bold;
                font-size: 14px;
                border-top-left-radius: 6px;
                border-top-right-radius: 6px;
                border-bottom: 2px solid #3a5a85;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            
            #simple-content {
                padding: 15px;
                font-size: 14px;
                line-height: 1.5;
                background: white;
            }
            
            .simple-buttons {
                display: flex;
                gap: 10px;
                margin: 10px 0;
            }
            
            .simple-btn {
                flex: 1;
                padding: 8px 0;
                border: none;
                border-radius: 4px;
                font-size: 14px;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s;
            }
            
            #mcp-status {
                margin-top: 10px;
                padding: 8px;
                background: #f0f8ff;
                border: 1px solid #d1e3ff;
                border-radius: 4px;
                font-size: 12px;
                min-height: 40px;
            }
            
            #init-button {
                background: ${isInitialized ? '#6c757d' : '#28a745'};
                color: white;
            }
            
            #init-button:hover:not(:disabled) {
                background: ${isInitialized ? '#5a6268' : '#218838'};
            }
            
            #init-button:disabled {
                cursor: not-allowed;
                opacity: 0.7;
            }
            
            /* 弹窗样式 */
            #mcp-notification-center {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 9999;
                pointer-events: none;
            }
            
            #mcp-notification-content {
                background: rgba(74, 111, 165, 0.95);
                color: white;
                padding: 25px 35px;
                border-radius: 15px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                text-align: center;
                min-width: 300px;
                max-width: 400px;
                pointer-events: auto;
                border: 2px solid rgba(255,255,255,0.2);
                backdrop-filter: blur(10px);
                animation: mcp-fade-in 0.3s ease-out;
            }
            
            #mcp-notification-spinner {
                width: 40px;
                height: 40px;
                border: 4px solid rgba(255,255,255,0.3);
                border-top: 4px solid white;
                border-radius: 50%;
                margin: 0 auto 15px;
                animation: mcp-spin 1s linear infinite;
            }
        `);
        
        // 创建悬浮框
        const floatingBox = document.createElement('div');
        floatingBox.id = 'simple-floating-box';
        
        floatingBox.innerHTML = `
            <div id="simple-header">
                <span>&#128295; MCP监控器 (自动轮询)</span>
                <div>
                    <button id="simple-minimize" title="最小化" style="background:none; border:none; color:white; font-size:16px; cursor:pointer; padding:0 5px;">_</button>
                    <button id="simple-close" title="关闭" style="background:none; border:none; color:white; font-size:20px; cursor:pointer; padding:0 5px;">×</button>
                </div>
            </div>
            <div id="simple-content">
                <div style="margin-bottom: 10px;">
                    <strong>会话:</strong> ${title}<br>
                    <strong>页面ID:</strong> ${pageId || '未获取'}
                    <div style="color: #28a745; font-size: 12px; margin-top: 5px;">
                        ${isInitialized ? '&#9989; 已初始化' : '&#9203; 等待初始化'}
                    </div>
                </div>
                
                <div class="simple-buttons">
                    <button id="init-button" class="simple-btn" ${isInitialized ? 'disabled' : ''}>
                        ${isInitialized ? '&#10003; 已初始化' : '初始化'}
                    </button>
                    <button id="send-test-btn" class="simple-btn" style="background: #28a745; color: white;">
                        测试消息
                    </button>
                </div>
                
                <div class="simple-buttons">
                    <button id="send-mcp-btn" class="simple-btn" style="background: #2196F3; color: white;">
                        MCP命令
                    </button>
                </div>
                
                <div id="mcp-status">
                    <div id="mcp-status-display">&#128260; 等待轮询启动...</div>
                </div>
            </div>
        `;
        
        document.body.appendChild(floatingBox);
        
        // 按钮事件
        document.getElementById('simple-minimize').addEventListener('click', hideFloatingBox);
        document.getElementById('simple-close').addEventListener('click', hideFloatingBox);
        
        // 初始化按钮事件
        document.getElementById('init-button').addEventListener('click', function() {
            if (!isInitialized) {
                console.log('开始初始化...');
                updateMCPStatus('初始化中...');
                sendSystemCommandsInfo();
            }
        });
        
        document.getElementById('send-test-btn').addEventListener('click', function() {
            sendMessage('这是一个测试消息');
        });
        
        document.getElementById('send-mcp-btn').addEventListener('click', function() {
            sendMessage('测试 {1*1systeminfo}1*1 命令');
        });
    }
   
    // 监听XHR请求
    const originalOpen = XMLHttpRequest.prototype.open;
    const originalSend = XMLHttpRequest.prototype.send;
    
    XMLHttpRequest.prototype.open = function(method, url) {
        this._url = url;
        return originalOpen.apply(this, arguments);
    };
    
    XMLHttpRequest.prototype.send = function() {
        if (this._url && this._url.includes('/api/v0/chat/completion')) {
            console.log('&#127919; 捕获AI请求');
            
            const originalOnReadyStateChange = this.onreadystatechange;
            this.onreadystatechange = function() {
                if (this.readyState === 4 && this.responseText) {
                    const fullMessage = extractFullMessage(this.responseText);
                    
                    if (fullMessage) {
                        console.log('&#128214; 收到AI回复,发送到MCP服务器');
                        sendToMCPAPI(fullMessage);
                    }
                }
                
                if (originalOnReadyStateChange) {
                    originalOnReadyStateChange.apply(this, arguments);
                }
            };
        }
        
        return originalSend.apply(this, arguments);
    };
    
    // URL变化监听
    function startUrlChangeListener() {
        console.log('开始监听URL变化');
        
        window.addEventListener('popstate', handleUrlChange);
        window.addEventListener('hashchange', handleUrlChange);
        
        const originalPushState = history.pushState;
        const originalReplaceState = history.replaceState;
        
        history.pushState = function() {
            originalPushState.apply(this, arguments);
            setTimeout(handleUrlChange, 100);
        };
        
        history.replaceState = function() {
            originalReplaceState.apply(this, arguments);
            setTimeout(handleUrlChange, 100);
        };
        
        setInterval(checkUrlChange, 500);
    }
    
    function checkUrlChange() {
        const newPath = window.location.pathname;
        if (newPath.startsWith('/a/chat/s/') && newPath !== currentPath) {
            currentPath = newPath;
            updateTitleOnUrlChange();
        }
    }
    
    function handleUrlChange() {
        const newPath = window.location.pathname;
        if (newPath.startsWith('/a/chat/s/') && newPath !== currentPath) {
            currentPath = newPath;
            setTimeout(updateTitleOnUrlChange, 300);
        }
    }
    
    function updateTitleOnUrlChange() {
        const pageTitle = getPageTitle();
        if (pageTitle && pageTitle !== lastTitle) {
            lastTitle = pageTitle;
            createFloatingBox(pageTitle);
        }
    }
    
    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        setTimeout(init, 1000);
    }
    
    console.log('&#9989; DeepSeek MCP监控器已加载(自动轮询版)');
    
})();
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-1-17 04:05

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表