好友
阅读权限10
听众
最后登录1970-1-1
|
完整版:可以的话大佬帮我优化一下
初始化,就是发送角色卡,告诉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"🔍 开始解析内容: '{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"📊 解析结果: 找到 {len(commands)} 个命令")
for i, (cmd, _) in enumerate(commands):
print(f" 命令{i+1}: '{cmd}'")
return commands
def execute_command(command):
"""执行单个系统命令"""
if not command:
return "❌ 空命令"
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"📤 输出:\n{stdout}\n"
if result.stderr:
stderr = result.stderr.strip()
if stderr:
output += f"📤 错误输出:\n{stderr}\n"
if not output.strip():
output = "✅ 命令执行完成(无输出)"
# 添加执行状态
if result.returncode == 0:
return output
else:
return f"⚠️ 命令返回非零代码 {result.returncode}\n{output}"
except subprocess.TimeoutExpired:
return "⏰ 命令执行超时(超过30秒)"
except Exception as e:
return f"🔥 执行异常: {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')}] 📩 收到消息")
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"📊 解析到 {len(mcp_commands)} 个命令")
# 🚀 使用循环处理多个命令
for i, (cmd, _) in enumerate(mcp_commands):
print(f"\n🔄 处理命令 [{i+1}/{len(mcp_commands)}]: {cmd}")
try:
# 执行单个命令
result = execute_command(cmd)
# 添加到结果列表
results.append({
'cmd': cmd,
'result': result,
'time': datetime.now().isoformat()
})
print(f"✅ 命令 [{i+1}] 执行完成")
except Exception as e:
error_result = f"❌ 命令执行异常: {str(e)}"
results.append({
'cmd': cmd,
'result': error_result,
'time': datetime.now().isoformat()
})
print(f"❌ 命令 [{i+1}] 执行失败: {e}")
# 如果没有任何命令,返回空
if not results:
print("📭 没有可执行的命令")
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('❌')])
}
# 存储到队列
print(f"📦 将汇总结果放入队列")
result_queue.put(summary)
print(f"🎯 所有命令处理完成,成功 {summary['success_count']}/{summary['total_commands']}")
return jsonify({
'ok': True,
'id': execution_id,
'message': f'已处理{len(results)}个命令',
'queue_size': result_queue.qsize()
})
# 🚀 如果没有解析到命令,返回空结果
if not mcp_commands:
print("📭 未解析到MCP命令,跳过执行")
# 仍然返回成功,但结果为空
return jsonify({
'ok': True,
'id': execution_id,
'message': '未找到MCP命令格式',
'queue_size': result_queue.qsize()
})
for cmd, _ in mcp_commands:
print(f"🔄 开始执行命令: '{cmd}'")
result = execute_command(cmd)
print(f"命令执行结果长度: {len(result)} 字符")
results.append({
'cmd': cmd,
'result': result,
'time': datetime.now().isoformat()
})
# 存储到队列
print(f"📦 将结果放入队列,当前队列大小: {result_queue.qsize()}")
result_queue.put({
'id': execution_id,
'timestamp': datetime.now().isoformat(),
'content': content,
'results': results
})
print(f"📦 放入队列后,队列大小: {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("🤖 MCP通用系统命令服务器")
print("📡 地址: http://127.0.0.1:5003")
print("📨 接收: POST /api/message")
print("📥 轮询: GET /api/results/poll")
print("")
print("💡 命令格式: {1*1命令}1*1")
print("💡 例如: {1*1systeminfo}1*1")
print("💡 例如: {1*1powershell Get-Process}1*1")
print("💡 例如: {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('🔍 检查MCP命令,原始内容:', content);
// 先看看内容是否包含我们需要的关键词
if (content.includes('1*1') && content.includes('}1*1')) {
console.log('✅ 检测到可能的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 = '▶';
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('📤 发送到MCP服务器:', content.substring(0, 100));
// 🚀 关键修改:不再检查,直接发送所有内容
// 让后端去判断是否是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('✅ 内容已发送到MCP服务器');
} else {
console.error('❌ MCP服务器返回错误:', response.status);
}
},
onerror: function(error) {
console.error('❌ 发送失败:', error.statusText || '未知错误');
}
});
}
// 开始轮询MCP结果(默认开启)
function startPolling() {
if (isPolling) return;
isPolling = true;
console.log('🔄 开始轮询MCP结果');
updateMCPStatus('轮询中...');
pollInterval = setInterval(() => {
pollMCPResults();
}, 1000);
}
// 停止轮询
function stopPolling() {
isPolling = false;
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = null;
}
console.log('🛑 停止轮询');
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);
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>📋 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('❌ 无法自动回复:无结果');
return;
}
console.log('📝 MCP结果已收到,显示弹窗...');
// 显示弹窗
showCenterNotification("🔄 MCP处理中", "正在发送命令结果,请勿点击...");
// 构建回复消息
let reply = '🔧 命令执行结果:\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('✅ MCP结果已调用sendMessage发送');
updateMCPStatus('✅ 自动回复已发送');
// 发送完成后1.5秒移除弹窗
setTimeout(() => {
removeCenterNotification();
console.log('✅ 弹窗已移除');
}, 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('✅ 消息已发送:', message.substring(0, 50) + '...');
} else {
textarea.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Enter',
ctrlKey: true,
bubbles: true
}));
console.log('✅ 已尝试发送消息');
// 🚀 关键:添加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('🔘 通过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('🔘 通过focus-ring找到发送按钮');
found = true;
}
}
if (!found) {
console.log('🔍 未找到发送按钮,尝试其他方法');
// 尝试模拟Ctrl+Enter
const textarea = getTextarea();
if (textarea) {
textarea.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Enter',
ctrlKey: true,
bubbles: true
}));
console.log('🔘 已模拟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 = "🔄 处理中", 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 = `# 🛠️ MCP系统命令说明
你好!我是MCP系统助手。我可以通过特殊的命令格式帮你执行系统操作:
## 📝 命令格式
命令格式: {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
## ⚠️ 注意事项
- 每条消息可以包含多个命令
- 命令执行结果会自动回复
- 请谨慎执行系统命令
- 调用过程中恢复给用户的不要建议多余的命令
- 遵守MCP 隐藏对话协议
- 轮询过程中,你不要建议或者添加任意额外需要执行的多余命令!
- 调用命令的过程中严格规范格式
现在你可以尝试发送命令了!,以上收到后你回复收到!,不要输出任何东西`;
// 发送系统说明
setTimeout(() => {
sendMessage(systemMessage);
// 标记为已初始化
localStorage.setItem(INITIALIZED_KEY, 'true');
console.log('✅ 系统命令说明已发送,页面标记为已初始化');
// 更新悬浮框状态
const initBtn = document.getElementById('init-button');
if (initBtn) {
initBtn.disabled = true;
initBtn.textContent = '✓ 已初始化';
initBtn.style.background = '#6c757d';
}
}, 1000);
}
// 初始化函数
function init() {
console.log('脚本初始化,当前路径:', currentPath);
// 获取页面标题
const pageTitle = getPageTitle();
if (pageTitle && pageTitle !== lastTitle) {
lastTitle = pageTitle;
createFloatingBox(pageTitle);
startUrlChangeListener();
}
// 🚀 关键修改:默认开启轮询
setTimeout(() => {
console.log('🔄 默认开启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>🔧 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 ? '✅ 已初始化' : '⏳ 等待初始化'}
</div>
</div>
<div class="simple-buttons">
<button id="init-button" class="simple-btn" ${isInitialized ? 'disabled' : ''}>
${isInitialized ? '✓ 已初始化' : '初始化'}
</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">🔄 等待轮询启动...</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('🎯 捕获AI请求');
const originalOnReadyStateChange = this.onreadystatechange;
this.onreadystatechange = function() {
if (this.readyState === 4 && this.responseText) {
const fullMessage = extractFullMessage(this.responseText);
if (fullMessage) {
console.log('📖 收到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('✅ DeepSeek MCP监控器已加载(自动轮询版)');
})(); |
|