v0.7: 以 AALC 为底座重建 MCP server

Browse Source
- AALC 作为 submodule (vendor/aalc @ 7452fad), 不改其代码
- 低层工具走 AALC auto/ocr/模板匹配; 高层 run_task 跑 AALC 现成流程(子进程, 可强杀)
- 常驻服务跑在交互桌面会话 + stdio bridge (token 认证), 取代每次截图注册计划任务
- 删除自写的截图/输入/OCR 后端
- 测试: FakeEngine 覆盖协议、任务生命周期、TCP+bridge 端到端

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-10-02 01:39:06 +00:00
co-authored by Claude Opus 5.5
parent 809a7fb017
commit a4b27f991c
31 changed files with 1179 additions and 1557 deletions
+4
View File
@@ -0,0 +1,4 @@
# -*- coding: utf-8 -*-
"""lc-mcp: 以 AALC (AhabAssistantLimbusCompany) 为底座的 Limbus Company MCP server。"""
VERSION = '0.7.0'
+143
View File
@@ -0,0 +1,143 @@
# -*- coding: utf-8 -*-
"""AALC 引擎: 截图/OCR/模板匹配/输入全部走 AALC 的 module.automation。
只能在 Windows 的交互桌面会话里运行(找窗口句柄、后台截图、PostMessage 都依赖它)。
AALC 代码按相对路径读 assets/ 和 config.yaml, 所以 bootstrap() 会 chdir 到 AALC 目录。
"""
import glob
import os
import sys
import time
from .engine import Engine
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEFAULT_AALC_DIR = os.path.join(REPO, 'vendor', 'aalc')
_booted = None
def aalc_dir():
return os.path.abspath(os.environ.get('AALC_DIR') or DEFAULT_AALC_DIR)
def bootstrap():
"""进程内初始化 AALC (幂等)。必须在 import 任何 AALC 模块之前调用。"""
global _booted
if _booted:
return _booted
d = aalc_dir()
if not os.path.isfile(os.path.join(d, 'main.py')):
raise RuntimeError('AALC 目录无效: %s (git submodule update --init, 或设置 AALC_DIR)' % d)
os.chdir(d)
if d not in sys.path:
sys.path.insert(0, d)
# 与 AALC main.py 相同的 DPI 设置, 否则截图/点击坐标在缩放下错位
from ctypes import c_void_p, windll
try:
windll.user32.SetProcessDpiAwarenessContext(c_void_p(-4))
except (AttributeError, OSError):
try:
windll.shcore.SetProcessDpiAwareness(2)
except (AttributeError, OSError):
windll.user32.SetProcessDPIAware()
from module.logger.my_log import Logger
Logger()
_booted = d
return d
def prune(directory, pattern, keep):
files = sorted(glob.glob(os.path.join(directory, pattern)), key=os.path.getmtime)
for p in files[:-keep] if keep > 0 else []:
try:
os.remove(p)
except OSError:
pass
class AalcEngine(Engine):
def __init__(self, shot_dir, keep_shots=30):
self.shot_dir = os.path.abspath(shot_dir)
os.makedirs(self.shot_dir, exist_ok=True)
self.keep_shots = keep_shots
root = bootstrap()
from module.automation import auto
from module.automation.input_handlers.input import key_list
from module.automation.screenshot import ScreenShot
from module.config import cfg
from module.game_and_screen import screen
from module.ocr import ocr
from utils.path_manager import path_manager
path_manager.initialize_paths()
self.auto, self.cfg, self.screen, self.ocr_engine = auto, cfg, screen, ocr
self.ScreenShot = ScreenShot
self.key_names = sorted(key_list)
self.images_root = os.path.join(root, 'assets', 'images')
# ---- 看 ----
def _grab(self, gray):
if not self.cfg.simulator and not self.screen.handle.hwnd:
raise RuntimeError('未找到游戏窗口 %r: 先启动游戏(run_task 会自动启动)' % self.cfg.game_title_name)
# 不用 auto.take_screenshot: 它连续失败 60 秒会直接 taskkill 游戏
with self.auto._screenshot_lock:
img = self.ScreenShot.take_screenshot(gray)
if img is None:
raise RuntimeError('AALC 截图失败(窗口最小化/被遮挡? 见 AALC logs)')
self.auto.screenshot = img # find_image_element 读这个
return img
def _save(self, img):
stamp = time.strftime('%Y%m%d_%H%M%S') + '_%03d' % (int(time.time() * 1000) % 1000)
path = os.path.join(self.shot_dir, 'shot_%s.png' % stamp)
img.save(path)
prune(self.shot_dir, 'shot_*.png', self.keep_shots)
return {'path': path.replace('\\', '/'), 'w': img.width, 'h': img.height}
def screenshot(self):
return self._save(self._grab(gray=False))
def ocr(self):
img = self._grab(gray=False)
shot = self._save(img)
res = self.ocr_engine.run(img)
items = []
boxes = res.boxes if res.boxes is not None else []
scores = res.scores if res.scores is not None else [1.0] * len(boxes)
for box, text, score in zip(boxes, res.txts or (), scores):
xs = [p[0] for p in box]
ys = [p[1] for p in box]
x0, y0 = int(min(xs)), int(min(ys))
items.append({'text': text, 'x': x0, 'y': y0,
'w': int(max(xs)) - x0, 'h': int(max(ys)) - y0,
'score': round(float(score), 3)})
return shot, items
def list_images(self, prefix=''):
names = set()
for theme in ('dark', 'default'):
for lang in ('zh_cn', 'en', 'share'):
base = os.path.join(self.images_root, theme, lang)
for p in glob.glob(os.path.join(base, '**', '*.png'), recursive=True):
names.add(os.path.relpath(p, base).replace('\\', '/'))
return sorted(n for n in names if n.startswith(prefix))
def find_image(self, name, threshold=0.8, model='normal'):
if name not in self.list_images(name):
raise ValueError('没有模板图 %r (用 list_images 查)' % name)
self._grab(gray=True)
pos = self.auto.find_image_element(name, threshold, model=model)
return (int(pos[0]), int(pos[1])) if pos else None
# ---- 动手 (AALC 输入后端, 由 config.yaml win_input_type 决定: 默认后台 PostMessage) ----
def click(self, x, y, times=1):
self.auto.mouse_click(int(x), int(y), times=int(times))
def keypress(self, key):
k = str(key).lower()
if k not in self.key_names:
raise ValueError('AALC 不支持按键 %r, 可用: %s' % (key, ' '.join(self.key_names)))
self.auto.key_press(k)
def type_text(self, text):
self.auto.input_text(str(text))
+81
View File
@@ -0,0 +1,81 @@
# -*- coding: utf-8 -*-
"""子进程入口: 跑 AALC 现成的任务流程。
用法: python -m lc_mcp.aalc_task <task> [json_params]
放在子进程里跑, 停止 = 杀进程树; 不会像 QThread.terminate 那样留下被占用的锁。
"""
import json
import sys
from .aalc_engine import bootstrap
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
TASKS = {
'all': {}, # 完全按 config.yaml 里勾选的任务跑, 等价于 AALC 界面点"开始"
'daily': {'exp': 'set_EXP_count', 'thread': 'set_thread_count'},
'reward': {},
'enkephalin': {'times': 'set_lunacy_to_enkephalin'},
'mirror': {'count': 'set_mirror_count'},
}
def run(task, params):
bootstrap()
from module.automation import auto
from module.config import cfg
from tasks.base import script_task_scheme as scheme
from tasks.base.retry_monitor import retry_monitor
from tasks.battle import battle
from utils.path_manager import path_manager
originals = {}
for name, value in params.items():
key = TASKS[task][name]
originals[key] = cfg.get_value(key)
cfg.unsaved_set_value(key, int(value))
try:
if task == 'all':
scheme.script_task()
return
# 与 script_task() 相同的前置步骤
scheme.init_game()
path_manager.initialize_paths()
auto.clear_img_cache()
retry_monitor.start()
get_reward = None
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
get_reward = battle.fight()
{
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
'reward': scheme.to_get_reward,
'enkephalin': scheme.Buy_enkephalin,
'mirror': scheme.Mirror_task,
}[task]()
finally:
retry_monitor.stop()
# AALC 运行中会自行保存配置(换队伍队列等), 把临时覆盖的次数写回原值
for key, value in originals.items():
cfg.set_value(key, value)
if originals:
cfg.flush()
def main(argv):
if len(argv) < 2 or argv[1] not in TASKS:
print('usage: python -m lc_mcp.aalc_task <%s> [json]' % '|'.join(TASKS), file=sys.stderr)
return 2
task = argv[1]
params = json.loads(argv[2]) if len(argv) > 2 else {}
unknown = set(params) - set(TASKS[task])
if unknown:
print('unknown params for %s: %s' % (task, ', '.join(sorted(unknown))), file=sys.stderr)
return 2
print('[lc_mcp] task %s start %s' % (task, json.dumps(params)), flush=True)
run(task, params)
print('[lc_mcp] task %s done' % task, flush=True)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
+84
View File
@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
"""stdio <-> 常驻服务 的中继。MCP 客户端(经 ssh)启动的是这个, 只用标准库。
ssh win python C:/path/lc-mcp/lc_mcp/bridge.py
为什么不直接 ssh 跑 server: SSH 会话在 session 0, 看不到游戏窗口、也发不了输入。
服务没起来时, 对每个请求回明确的错误, 而不是让客户端干等。
"""
import json
import os
import socket
import sys
import threading
HOME = os.path.join(os.path.expanduser('~'), 'lc_mcp')
TOKEN_FILE = os.path.join(HOME, 'token')
PORT = int(os.environ.get('LCP_PORT', '8765'))
def connect(port=PORT, token_file=TOKEN_FILE):
with open(token_file, encoding='ascii') as f:
token = f.read().strip()
sock = socket.create_connection(('127.0.0.1', port), timeout=5)
sock.settimeout(None)
sock.sendall(('AUTH %s\n' % token).encode('ascii'))
rfile = sock.makefile('rb')
if rfile.readline().strip() != b'OK':
raise ConnectionError('token 被拒绝 (%s 与服务端不一致?)' % token_file)
return sock, rfile
def relay(sock, rfile, stdin, stdout):
def up():
try:
for line in iter(stdin.readline, b''):
sock.sendall(line)
finally:
try:
sock.shutdown(socket.SHUT_WR)
except OSError:
pass
threading.Thread(target=up, daemon=True).start()
for line in iter(rfile.readline, b''):
stdout.write(line)
stdout.flush()
def answer_offline(reason, stdin, stdout):
"""服务不可达: 仍完成握手, 但每个工具调用都返回原因。"""
for raw in iter(stdin.readline, b''):
try:
msg = json.loads(raw)
except ValueError:
continue
if not isinstance(msg, dict) or msg.get('id') is None:
continue
if msg.get('method') == 'initialize':
resp = {'protocolVersion': '2024-11-05', 'capabilities': {'tools': {}},
'serverInfo': {'name': 'lc-mcp (offline)', 'version': '0'}}
out = {'jsonrpc': '2.0', 'id': msg['id'], 'result': resp}
elif msg.get('method') == 'tools/list':
out = {'jsonrpc': '2.0', 'id': msg['id'], 'result': {'tools': []}}
else:
out = {'jsonrpc': '2.0', 'id': msg['id'], 'error': {'code': -32000, 'message': reason}}
stdout.write((json.dumps(out, ensure_ascii=False) + '\n').encode('utf-8'))
stdout.flush()
def main():
stdin, stdout = sys.stdin.buffer, sys.stdout.buffer
try:
sock, rfile = connect()
except (OSError, ConnectionError) as e:
reason = ('lc-mcp 服务未运行或不可达 (%s)。在 Windows 桌面会话里启动: '
'scripts/install_logon_task.ps1 或 python -m lc_mcp.server' % e)
sys.stderr.write(reason + '\n')
answer_offline(reason, stdin, stdout)
return 1
relay(sock, rfile, stdin, stdout)
return 0
if __name__ == '__main__':
sys.exit(main())
+58
View File
@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
"""引擎接口 + 平台无关的文字匹配。
引擎 = "看屏幕 + 动手" 的最小集合, 坐标一律是游戏窗口客户区截图里的像素坐标。
实现: AalcEngine(Windows, 调 AALC) / FakeEngine(测试)。
"""
import re
_WS = re.compile(r'\s+')
def norm(s):
"""匹配用归一化: 去全部空白 + 小写 (OCR 常把 "Hong Lu" 识别成 "HongLu" 或反之)。"""
return _WS.sub('', str(s)).lower()
def find_hits(text, items):
"""在 OCR items 里找包含 text 的项, 返回中心点列表。完全相等的排前面。"""
key = norm(text)
if not key:
return []
exact, partial = [], []
for it in items:
t = norm(it['text'])
if key not in t:
continue
hit = {'text': it['text'], 'x': it['x'] + it['w'] // 2, 'y': it['y'] + it['h'] // 2}
(exact if t == key else partial).append(hit)
return exact + partial
class Engine:
"""所有方法失败时抛异常, 由协议层转成 isError 结果。"""
def screenshot(self):
"""截图并落盘。返回 {'path': str, 'w': int, 'h': int}。"""
raise NotImplementedError
def ocr(self):
"""截图 + OCR。返回 (shot, items); items = [{text, x, y, w, h, score}]。"""
raise NotImplementedError
def find_image(self, name, threshold=0.8, model='normal'):
"""在当前画面找 AALC 模板图 (如 'battle/turn_assets.png')。返回 (x, y) 或 None。"""
raise NotImplementedError
def list_images(self, prefix=''):
"""列出可用模板图的相对路径。"""
raise NotImplementedError
def click(self, x, y, times=1):
raise NotImplementedError
def keypress(self, key):
raise NotImplementedError
def type_text(self, text):
raise NotImplementedError
+37
View File
@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
"""测试用引擎: 屏幕内容由测试脚本预设, 记录所有输入动作。"""
from .engine import Engine
class FakeEngine(Engine):
def __init__(self, frames=None, images=None):
# frames: 每次 ocr() 依次返回的 items 列表; 用完后停在最后一帧
self.frames = list(frames or [[]])
self.images = dict(images or {}) # name -> (x, y)
self.actions = []
self.shots = 0
def screenshot(self):
self.shots += 1
return {'path': 'fake/shot_%d.png' % self.shots, 'w': 1920, 'h': 1080}
def ocr(self):
shot = self.screenshot()
items = self.frames.pop(0) if len(self.frames) > 1 else self.frames[0]
return shot, [dict(it, score=it.get('score', 0.99)) for it in items]
def find_image(self, name, threshold=0.8, model='normal'):
return self.images.get(name)
def list_images(self, prefix=''):
return sorted(n for n in self.images if n.startswith(prefix))
def click(self, x, y, times=1):
self.actions.append(('click', int(x), int(y), int(times)))
def keypress(self, key):
self.actions.append(('key', key))
def type_text(self, text):
self.actions.append(('type', text))
+209
View File
@@ -0,0 +1,209 @@
# -*- coding: utf-8 -*-
"""MCP (JSON-RPC 2.0) 处理: 与传输方式无关, handle(msg) -> 响应 dict 或 None(通知)。"""
import json
import threading
import time
from . import VERSION
from .aalc_task import TASKS
from .engine import find_hits
MAX_WAIT = 300.0
WAIT_INTERVAL = 1.0
INPUT_TOOLS = {'click', 'click_text', 'click_image', 'keypress', 'type_text'}
TASK_TOOLS = {'run_task', 'task_status', 'stop_task'}
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': 'get_state', 'description': '截图 + OCR, 返回游戏窗口内全部文字(含坐标/置信度)。决策前先调这个, 不要猜坐标',
'inputSchema': _obj()},
{'name': 'click_text', 'description': '按文字点击: OCR 定位后点中心。子串匹配、忽略空格, 完全相同的优先; index 选第几个命中',
'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)',
'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',
'inputSchema': _obj({'key': _STR}, ['key'])},
{'name': 'type_text', 'description': '向游戏窗口输入文本', 'inputSchema': _obj({'text': _STR}, ['text'])},
{'name': 'run_task', 'description': (
'后台运行 AALC 现成的完整任务流程(会自动启动游戏、处理战斗/掉线重试)。立即返回, 用 task_status 看进度。'
'all=按 AALC config.yaml 勾选的全部任务; daily=经验本+纽本(exp/thread 次数); reward=领奖励; '
'enkephalin=狂气换体力(times); mirror=镜牢(count 次数)。任务运行期间禁止手动点击类工具'),
'inputSchema': _obj({'task': {'type': 'string', 'enum': sorted(TASKS)},
'exp': _NUM, 'thread': _NUM, 'times': _NUM, 'count': _NUM}, ['task'])},
{'name': 'task_status', 'description': '查看任务状态(idle/running/succeeded/failed/stopped)和日志尾部',
'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')
if method == 'initialize':
return _ok(mid, {'protocolVersion': '2024-11-05',
'capabilities': {'tools': {'listChanged': False}},
'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':
params = msg.get('params') or {}
result = self.call_tool(params.get('name'), params.get('arguments') or {})
return _ok(mid, {'content': [{'type': 'text', 'text': json.dumps(result, ensure_ascii=False)}],
'isError': not result.get('ok', False)})
if mid is None:
return None # 通知 (notifications/*) 不回
return _error(mid, -32601, 'method not found: %s' % method)
def call_tool(self, name, args):
try:
if name in TASK_TOOLS: # 不抢游戏锁: wait_for_text 期间也能查任务/停任务
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}
return self.tasks.start(task, params)
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 == '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 == '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:
return json.loads(line), None
except ValueError as e:
return None, _error(None, -32700, 'parse error: %s' % e)
+136
View File
@@ -0,0 +1,136 @@
# -*- coding: utf-8 -*-
"""lc-mcp 常驻服务: 跑在 Windows 交互桌面会话里(登录时由计划任务启动)。
python -m lc_mcp.server 监听 127.0.0.1:PORT, MCP 客户端经 bridge.py 连入
python -m lc_mcp.server --stdio 直接走 stdio (本机、且本进程就在桌面会话时用)
--fake 用 FakeEngine (开发/测试, 不需要 Windows/AALC)
TCP 协议: 首行 "AUTH <token>", 服务端回 "OK"; 之后逐行 JSON-RPC。
token 存在 ~/lc_mcp/token (用户目录默认只有本人可读), 防止同机其他用户/进程连进来操作游戏。
"""
import argparse
import hmac
import os
import secrets
import socketserver
import sys
import threading
from .protocol import Server, parse_line
from .tasks import TaskRunner
HOME = os.path.join(os.path.expanduser('~'), 'lc_mcp')
TOKEN_FILE = os.path.join(HOME, 'token')
DEFAULT_PORT = int(os.environ.get('LCP_PORT', '8765'))
def log(msg):
sys.stderr.write('[lc_mcp] %s\n' % msg)
sys.stderr.flush()
def load_token(create=False):
try:
with open(TOKEN_FILE, encoding='ascii') as f:
tok = f.read().strip()
if tok:
return tok
except OSError:
if not create:
raise
os.makedirs(HOME, exist_ok=True)
tok = secrets.token_hex(24)
fd = os.open(TOKEN_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, 'w', encoding='ascii') as f:
f.write(tok)
return tok
def build_server(fake=False):
os.makedirs(HOME, exist_ok=True)
tasks = TaskRunner(os.path.join(HOME, 'runs'))
if fake:
from .fake_engine import FakeEngine
return Server(FakeEngine(), tasks)
try:
from .aalc_engine import AalcEngine
return Server(AalcEngine(os.path.join(HOME, 'shots'), int(os.environ.get('LCP_KEEP_SHOTS', '30'))), tasks)
except Exception as e:
# 引擎起不来也继续服务: run_task 仍可用, 其他工具返回原因
log('AALC engine init failed: %r' % e)
return Server(None, tasks, engine_error='%s: %s' % (type(e).__name__, e))
def serve_lines(server, readline, write):
"""逐行处理直到 EOF。坏行回 parse error 后继续, 不退出。"""
import json
while True:
line = readline()
if not line:
return
msg, err = parse_line(line)
resp = err if err else (server.handle(msg) if msg is not None else None)
if resp is not None:
write(json.dumps(resp, ensure_ascii=False) + '\n')
def run_stdio(server):
out = sys.stdout
sys.stdout = sys.stderr # AALC 或第三方库的 print 不能混进协议流
def write(s):
out.write(s)
out.flush()
serve_lines(server, sys.stdin.readline, write)
class _Handler(socketserver.StreamRequestHandler):
def handle(self):
rfile, wfile = self.rfile, self.wfile
first = rfile.readline(256).decode('utf-8', 'replace').strip()
if not (first.startswith('AUTH ') and hmac.compare_digest(first[5:], self.server.token)):
wfile.write(b'DENIED\n')
log('rejected connection from %s' % (self.client_address,))
return
wfile.write(b'OK\n')
wfile.flush()
wlock = threading.Lock()
def write(s):
with wlock:
wfile.write(s.encode('utf-8'))
wfile.flush()
serve_lines(self.server.mcp, lambda: rfile.readline().decode('utf-8', 'replace'), write)
class TCPServer(socketserver.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = False # Windows 上 SO_REUSEADDR 允许端口劫持
def make_tcp(mcp, host, port, token):
srv = TCPServer((host, port), _Handler)
srv.mcp, srv.token = mcp, token
return srv
def main(argv=None):
ap = argparse.ArgumentParser(prog='lc_mcp.server')
ap.add_argument('--stdio', action='store_true')
ap.add_argument('--fake', action='store_true')
ap.add_argument('--host', default='127.0.0.1')
ap.add_argument('--port', type=int, default=DEFAULT_PORT)
args = ap.parse_args(argv)
mcp = build_server(fake=args.fake)
if args.stdio:
return run_stdio(mcp)
if args.host not in ('127.0.0.1', '::1', 'localhost'):
log('WARNING: 监听 %s 会把游戏控制权暴露到网络上, 建议走 SSH 隧道' % args.host)
srv = make_tcp(mcp, args.host, args.port, load_token(create=True))
log('listening on %s:%d (token: %s)' % (args.host, args.port, TOKEN_FILE))
srv.serve_forever()
if __name__ == '__main__':
main()
+107
View File
@@ -0,0 +1,107 @@
# -*- coding: utf-8 -*-
"""长任务管理: 同一时刻最多一个 AALC 任务子进程。"""
import glob
import json
import os
import signal
import subprocess
import sys
import threading
import time
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IS_WIN = sys.platform.startswith('win')
def default_argv(task, params):
return [sys.executable, '-m', 'lc_mcp.aalc_task', task, json.dumps(params)]
def tail(path, n):
try:
with open(path, 'rb') as f:
f.seek(0, os.SEEK_END)
f.seek(max(0, f.tell() - 64 * 1024))
lines = f.read().decode('utf-8', 'replace').splitlines()
return lines[-n:]
except OSError:
return []
class TaskRunner:
def __init__(self, run_dir, argv_factory=default_argv, keep_logs=20):
self.run_dir = os.path.abspath(run_dir)
os.makedirs(self.run_dir, exist_ok=True)
self.argv_factory = argv_factory
self.keep_logs = keep_logs
self._lock = threading.Lock()
self.proc = None
self.info = None
def running(self):
return self.proc is not None and self.proc.poll() is None
def start(self, task, params):
with self._lock:
if self.running():
return {'ok': False, 'error': '已有任务在跑: %s (先 stop_task)' % self.info['task']}
stamp = time.strftime('%Y%m%d_%H%M%S')
log_path = os.path.join(self.run_dir, 'task_%s_%s.log' % (stamp, task))
env = dict(os.environ, PYTHONPATH=REPO + os.pathsep + os.environ.get('PYTHONPATH', ''),
PYTHONIOENCODING='utf-8', PYTHONUNBUFFERED='1')
kw = {'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP} if IS_WIN else {'start_new_session': True}
with open(log_path, 'wb') as logf:
self.proc = subprocess.Popen(self.argv_factory(task, params), cwd=REPO, env=env,
stdin=subprocess.DEVNULL, stdout=logf, stderr=subprocess.STDOUT, **kw)
self.info = {'task': task, 'params': params, 'log': log_path.replace('\\', '/'),
'started': time.time(), 'stopped_by_user': False}
self._prune()
return {'ok': True, 'task': task, 'pid': self.proc.pid, 'log': self.info['log']}
def status(self, lines=30):
with self._lock:
if self.info is None:
return {'ok': True, 'state': 'idle'}
code = self.proc.poll()
if code is None:
state = 'running'
elif self.info['stopped_by_user']:
state = 'stopped'
else:
state = 'succeeded' if code == 0 else 'failed'
r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'],
'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']),
'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))}
if code is not None:
r['exit_code'] = code
self.info.setdefault('ended', time.time())
return r
def stop(self):
with self._lock:
if not self.running():
return {'ok': True, 'state': 'idle', 'note': '没有在跑的任务'}
self.info['stopped_by_user'] = True
pid = self.proc.pid
if IS_WIN:
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True)
else:
try:
os.killpg(pid, signal.SIGKILL)
except ProcessLookupError:
pass
try:
self.proc.wait(timeout=10)
except subprocess.TimeoutExpired:
return {'ok': False, 'error': '进程 %d 10 秒内没退出' % pid}
self.info['ended'] = time.time()
return {'ok': True, 'state': 'stopped', 'task': self.info['task']}
def _prune(self):
logs = sorted(glob.glob(os.path.join(self.run_dir, 'task_*.log')), key=os.path.getmtime)
for p in logs[:-self.keep_logs]:
try:
os.remove(p)
except OSError:
pass