# -*- coding: utf-8 -*- """MCP (JSON-RPC 2.0) 处理: 与传输方式无关, handle(msg) -> 响应 dict 或 None(通知)。""" import json import math import threading import time from . import VERSION from .aalc_task import TASK_OPTIONS, TASKS from .engine import find_hits MAX_WAIT = 300.0 WAIT_INTERVAL = 1.0 INPUT_TOOLS = {'click', 'click_text', 'click_image', 'keypress', 'type_text', 'drag', 'show_game_background'} TASK_TOOLS = {'run_task', 'task_status', 'stop_task'} AUTOMATION_INSTRUCTIONS = ( '常规日常刷取、领奖励、普通镜牢优先使用 AALC 的 run_task 自动流程。' '先用 task_status 检查是否已有任务;已有任务时查看进度,不重复启动或为抢占而停止它。' '日常用 task="daily",领奖用 task="reward",镜牢用 task="mirror";次数按用户要求传入。' '例如一局镜牢调用 run_task({"task":"mirror","count":1});' '只刷经验本时传 exp 次数和 thread=0,只刷纽本时传 thread 次数和 exp=0,避免沿用另一项配置。' '启动成功仅表示任务已启动,随后轮询 task_status,最终同时检查 state、errors 和 pending_restore;' 'succeeded 带 errors 不能报告完整成功;镜牢完成局数不足时报 failed 并在 errors 写明 已完成/应打 局数。' '运行中不用逐帧 get_state/click/keypress 重做流程。' '出现 stall 时先 stop_task 并确认停止,再 get_state 排障;停止失败不发送输入。' '用户停止或退出码130时结束,不自动重试。' '主线、特殊速通路线、用户明确要求逐步控制或自动流程不支持的操作,才使用低层观察与输入;' '这时先 get_state 核对当前画面。只查看状态或截图的请求不启动任务。' 'all 仅用于用户明确要求按配置运行全部任务;enkephalin 会花狂气,仅在明确授权消费时使用。' '免费体力合成模块不属于 enkephalin;不把它改派为刷取或花狂气。' ) def _obj(props=None, required=()): s = {'type': 'object', 'properties': props or {}} if required: s['required'] = list(required) return s _STR = {'type': 'string'} _NUM = {'type': 'number'} _TIMEOUT = {'type': 'number', 'default': 30, 'description': '秒, 上限 300'} _IMG = {'name': {'type': 'string', 'description': 'AALC 模板图相对路径, 如 battle/turn_assets.png'}, 'threshold': {'type': 'number', 'default': 0.8}, 'model': {'type': 'string', 'enum': ['clam', 'normal', 'aggressive'], 'default': 'normal', 'description': 'clam=只在模板原位置找, normal=扩大范围, aggressive=全屏'}} TOOLS = [ {'name': 'show_game_background', 'description': '后台显示/恢复游戏窗口,使隐藏窗口继续渲染;不激活前台、不发送鼠标或键盘输入。', 'inputSchema': _obj()}, {'name': 'get_state', 'description': '截图 + OCR,返回窗口文字、坐标和置信度。用于观察、故障诊断和逐步控制前核对画面。' '常规日常/领奖/普通镜牢优先 run_task,运行进度用 task_status,无需逐帧操作。', 'inputSchema': _obj()}, {'name': 'click_text', 'description': '逐步控制/故障恢复用:按文字定位后点中心,完全匹配优先,index 选命中。' '常规日常/领奖/普通镜牢优先 run_task。', 'inputSchema': _obj({'text': _STR, 'index': {'type': 'number', 'default': 0}}, ['text'])}, {'name': 'wait_for_text', 'description': '轮询 OCR 直到文字出现', 'inputSchema': _obj({'text': _STR, 'timeout': _TIMEOUT}, ['text'])}, {'name': 'wait_for_text_gone', 'description': '轮询 OCR 直到文字消失', 'inputSchema': _obj({'text': _STR, 'timeout': _TIMEOUT}, ['text'])}, {'name': 'find_image', 'description': '用 AALC 模板图在当前画面里找图标/按钮(比 OCR 稳, 适合没有文字的按钮)', 'inputSchema': _obj(_IMG, ['name'])}, {'name': 'click_image', 'description': '找到 AALC 模板图并点击它', 'inputSchema': _obj(_IMG, ['name'])}, {'name': 'list_images', 'description': '列出 AALC 模板图(按前缀过滤, 如 mirror/ battle/ home/)', 'inputSchema': _obj({'prefix': {'type': 'string', 'default': ''}})}, {'name': 'screenshot', 'description': '截游戏窗口, 返回 PNG 路径和尺寸', 'inputSchema': _obj()}, {'name': 'click', 'description': '逐步控制/故障恢复用:按最新窗口截图的像素坐标点击,优先 click_text / click_image。' '常规日常/领奖/普通镜牢优先 run_task。', 'inputSchema': _obj({'x': _NUM, 'y': _NUM, 'times': {'type': 'number', 'default': 1}}, ['x', 'y'])}, {'name': 'keypress', 'description': '逐步控制/故障恢复用:按一次 a-z 0-9 enter esc space tab shift ctrl alt up down left right。' '常规日常/领奖/普通镜牢优先 run_task,无需自行循环战斗按键。', 'inputSchema': _obj({'key': _STR}, ['key'])}, {'name': 'drag', 'description': '在游戏客户区保持左键按下并缓慢拖动,适用于卡包下拉;duration 是移动秒数,0.1–10,默认 1。先 get_state 核对坐标', 'inputSchema': _obj({'from_x': _NUM, 'from_y': _NUM, 'to_x': _NUM, 'to_y': _NUM, 'duration': {'type': 'number', 'default': 1.0, 'minimum': 0.1, 'maximum': 10}}, ['from_x', 'from_y', 'to_x', 'to_y'])}, {'name': 'type_text', 'description': '向游戏窗口输入文本', 'inputSchema': _obj({'text': _STR}, ['text'])}, {'name': 'run_task', 'description': ( '常规日常刷取、领奖励、普通镜牢的首选工具;自动完成流程,无需逐按钮点击。先 task_status 确认没有任务在跑。' '后台运行 AALC 现成的完整任务流程(会自动启动游戏、处理战斗/掉线重试)。立即返回, 用 task_status 看进度。' 'all=按 AALC config.yaml 勾选的全部任务; daily=经验本+纽本(exp/thread 次数); reward=领奖励; ' 'enkephalin=狂气换体力(times); mirror=镜牢(count 次数)。一局镜牢传 task=mirror,count=1;' '传 count 时本次临时关闭 AALC 无限刷牢,结束后恢复;完成局数不足时任务报 failed。' '只刷一种日常时把另一种次数显式设为0,省略次数沿用配置。' 'all 需明确要求全部任务;enkephalin 需明确授权花狂气,免费合成模块不能用它。' '任务运行期间禁止手动点击类工具;最终 succeeded 也要检查 errors,用户停止后不自动重跑。' 'mirror 可加 strategy="rabbit_hole":兔子洞速刷(黑兽-卯 浮士德每回合放 E.G.O「空洞」,每场第一回合超频),' '编队、长按点、路线卡包见 lc_mcp/data/rabbit_hole.json。'), 'inputSchema': _obj({'task': {'type': 'string', 'enum': sorted(TASKS)}, 'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM, 'strategy': {'type': 'string', 'enum': sorted({v for o in TASK_OPTIONS.values() for v in o['strategy']})}}, ['task'])}, {'name': 'task_status', 'description': '启动 run_task 前检查占用,启动后轮询此工具监控,避免逐帧截图和重复启动。' '返回 idle/running/succeeded/failed/stopped、日志及异常;' 'decisions.counts 按阶段统计选队/寻路/卡包/饰品/事件/商店的决策理由。' 'succeeded 也要看 errors 和 pending_restore;running 出现 stall 应 stop_task 并确认停止后排障;' 'stopped/退出码130 表示用户停止,不自动重跑。', 'inputSchema': _obj({'lines': {'type': 'number', 'default': 30}})}, {'name': 'stop_task', 'description': '强制停止当前任务(杀掉任务进程)', 'inputSchema': _obj()}, ] class Server: def __init__(self, engine, tasks, engine_error=None): self.engine = engine self.engine_error = engine_error self.tasks = tasks # 游戏只有一个: 所有工具调用串行, 防止两个客户端同时点 self.lock = threading.Lock() # ---- JSON-RPC ---- def handle(self, msg): if not isinstance(msg, dict): return _error(None, -32600, 'request must be a JSON object') method, mid = msg.get('method'), msg.get('id') valid_id = (mid is None or isinstance(mid, str) or isinstance(mid, (int, float)) and not isinstance(mid, bool) and (not isinstance(mid, float) or math.isfinite(mid))) if msg.get('jsonrpc') != '2.0' or not isinstance(method, str) or not method or not valid_id: return _error(mid if valid_id else None, -32600, 'invalid JSON-RPC request') notification = 'id' not in msg params = msg.get('params', {}) if not isinstance(params, dict): return None if notification else _error(mid, -32602, 'params must be an object') # Notifications never produce responses or trigger request-only tools. if notification: return None if method == 'initialize': return _ok(mid, {'protocolVersion': '2024-11-05', 'capabilities': {'tools': {'listChanged': False}}, 'instructions': AUTOMATION_INSTRUCTIONS, 'serverInfo': {'name': 'lc-mcp', 'version': VERSION}}) if method == 'ping': return _ok(mid, {}) if method == 'tools/list': return _ok(mid, {'tools': TOOLS}) if method == 'tools/call': name, arguments = params.get('name'), params.get('arguments', {}) if not isinstance(name, str) or not name.strip() or not isinstance(arguments, dict): return _error(mid, -32602, 'tools/call requires a name and object arguments') result = self.call_tool(name, arguments) return _ok(mid, {'content': [{'type': 'text', 'text': json.dumps(result, ensure_ascii=False)}], 'isError': not result.get('ok', False)}) return _error(mid, -32601, 'method not found: %s' % method) def call_tool(self, name, args): try: if name in TASK_TOOLS: # 查任务/停任务不等待正在执行的游戏工具 return self._task_tool(name, args) with self.lock: return self._call(name, args) except (KeyError, TypeError, ValueError) as e: return {'ok': False, 'error': 'bad arguments: %s: %s' % (type(e).__name__, e)} except Exception as e: return {'ok': False, 'error': '%s: %s' % (type(e).__name__, e)} # ---- 工具 ---- def _task_tool(self, name, a): if name == 'run_task': task = a['task'] if task not in TASKS: raise ValueError('unknown task %r' % task) params = {k: int(a[k]) for k in TASKS[task] if a.get(k) is not None} options = TASK_OPTIONS.get(task, {}) for key in ('strategy',): if a.get(key) is None: continue if a[key] not in options.get(key, ()): raise ValueError('%s 不支持 %s=%r' % (task, key, a[key])) params[key] = a[key] # Starting must not race a click that has already checked running(). # Reject promptly when busy instead of waiting behind a long OCR poll. if not self.lock.acquire(blocking=False): return {'ok': False, 'error': 'MCP 工具正在执行,完成后再启动 AALC 任务'} try: return self.tasks.start(task, params) finally: self.lock.release() if name == 'task_status': return self.tasks.status(a.get('lines', 30)) return self.tasks.stop() def _call(self, name, a): if not any(t['name'] == name for t in TOOLS): return {'ok': False, 'error': 'unknown tool %s' % name} if self.engine is None: return {'ok': False, 'error': 'AALC 引擎不可用: %s' % self.engine_error} if name in INPUT_TOOLS and self.tasks.running(): return {'ok': False, 'error': 'AALC 任务 %s 正在运行, 手动输入会打乱它; 先 stop_task' % self.tasks.info['task']} e = self.engine if name == 'show_game_background': return dict(e.show_game_background(), ok=True) if name == 'screenshot': return dict(e.screenshot(), ok=True) if name == 'get_state': shot, items = e.ocr() return {'ok': True, 'screen': shot, 'items': items} if name == 'click_text': text = _text(a) shot, items = e.ocr() hits = find_hits(text, items) if not hits: return {'ok': False, 'error': 'text not found: %s' % text, 'screen': shot, 'items': items} idx = int(a.get('index', 0)) if not 0 <= idx < len(hits): return {'ok': False, 'error': 'index %d out of range (%d hits)' % (idx, len(hits)), 'hits': hits[:10]} h = hits[idx] e.click(h['x'], h['y']) return {'ok': True, 'clicked': h, 'other_hits': len(hits) - 1} if name in ('wait_for_text', 'wait_for_text_gone'): return self._wait(_text(a), float(a.get('timeout', 30)), name == 'wait_for_text') if name in ('find_image', 'click_image'): pos = e.find_image(a['name'], float(a.get('threshold', 0.8)), a.get('model', 'normal')) if pos is None: return {'ok': name == 'find_image', 'found': False, 'name': a['name']} if name == 'click_image': e.click(*pos) return {'ok': True, 'found': True, 'name': a['name'], 'x': pos[0], 'y': pos[1]} if name == 'list_images': imgs = e.list_images(a.get('prefix', '')) return {'ok': True, 'count': len(imgs), 'images': imgs[:300], 'truncated': len(imgs) > 300} if name == 'click': e.click(int(a['x']), int(a['y']), max(1, int(a.get('times', 1)))) return {'ok': True, 'clicked': [int(a['x']), int(a['y'])]} if name == 'keypress': e.keypress(str(a['key'])) return {'ok': True, 'key': str(a['key'])} if name == 'drag': duration = float(a.get('duration', 1.0)) if not math.isfinite(duration) or not 0.1 <= duration <= 10: raise ValueError('duration must be between 0.1 and 10 seconds') points = [int(a[k]) for k in ('from_x', 'from_y', 'to_x', 'to_y')] e.drag(*points, duration=duration) return {'ok': True, 'from': points[:2], 'to': points[2:], 'duration': duration} if name == 'type_text': e.type_text(str(a['text'])) return {'ok': True, 'typed': str(a['text'])} return {'ok': False, 'error': 'unknown tool %s' % name} def _wait(self, text, timeout, want_present): deadline = time.monotonic() + max(0.0, min(timeout, MAX_WAIT)) items, last_err = [], None while True: try: shot, items = self.engine.ocr() hits = find_hits(text, items) if bool(hits) == want_present: return {'ok': True, 'present': want_present, 'hits': hits[:5], 'screen': shot} except Exception as ex: last_err = '%s: %s' % (type(ex).__name__, ex) if time.monotonic() + WAIT_INTERVAL > deadline: break time.sleep(WAIT_INTERVAL) r = {'ok': False, 'error': 'timeout waiting %r (want present=%s)' % (text, want_present), 'last_items': items[:15]} if last_err: r['last_error'] = last_err return r def _text(a): text = str(a.get('text', '')) if not text.strip(): raise ValueError('text must be non-empty') return text def _ok(mid, result): return {'jsonrpc': '2.0', 'id': mid, 'result': result} def _error(mid, code, message): return {'jsonrpc': '2.0', 'id': mid, 'error': {'code': code, 'message': message}} def parse_line(line): """一行 -> (msg, error_response)。空行返回 (None, None)。""" line = line.strip() if not line: return None, None try: msg = json.loads(line) if msg is None: return None, _error(None, -32600, 'request must be a JSON object') return msg, None except ValueError as e: return None, _error(None, -32700, 'parse error: %s' % e)