Files
lc-mcp/scripts/mcp_session.py
ywsandClaude Opus 5.5 a993210760 合并 codex/mcp-runtime-reliability: 运行可靠性、局状态与决策交接
与 main 上的审查修复及 2131f89 (story-test) 合并, 冲突处理:
- mcp_session: 保留超时/取消客户端, 补回 raise_on_error
- 执行器: 局状态改用 run_state (run_id 绑定), 取代完成后归档 context;
  Jev 请求统一经 jev_client.request_answer (支持 baseUrl/curl, 返回置信度与概率);
  保留截图解码缓存、地图模板缓存、按坐标点按钮、use_last_error 单实例互斥;
  刷新计数与开战标记只在动作成功后更新
- battle_batch: 取消/预算框架 + 只在看到胜率按钮时点胜率再回车;
  回合标签改为包含匹配 (OCR 常输出 'wave1')
- 文档采用 reliability 版本 (已是仓库相对路径), 注明 jev_client
- 测试: 互斥量桩改为 WinDLL/get_last_error, 战斗批次测试按胜率语义重写,
  Jev 测试改为对 jev_client 打桩, 生命周期测试改为轮询; 145 项通过

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 03:12:48 +00:00

184 lines
7.1 KiB
Python

"""Reusable client for the installed stdio MCP bridge; no direct game input."""
import json
import math
import os
import queue
import subprocess
import sys
import threading
import time
from collections import deque
from pathlib import Path
class SessionCancelled(InterruptedError):
"""The caller stopped waiting; a sent remote action may have completed."""
def __init__(self, message, outcome_unknown=False):
super().__init__(message)
self.outcome_unknown = outcome_unknown
class SessionTimeout(TimeoutError):
outcome_unknown = True
class Session:
def __init__(self, timeout=30, cancelled=None, raise_on_error=True):
self.timeout = float(timeout)
if not math.isfinite(self.timeout) or self.timeout <= 0:
raise ValueError('MCP timeout must be finite and positive')
self.cancelled = cancelled or (lambda: False)
# False: 工具失败按 {'ok': False, ...} 返回, 由调用方观察后继续; 协议层错误仍抛异常
self.raise_on_error = raise_on_error
self._closed = False
self._lock = threading.Lock()
self._responses = queue.Queue()
self._outgoing = queue.Queue()
self.stderr_tail = deque(maxlen=20)
root = Path(__file__).resolve().parents[1]
self.process = subprocess.Popen(
[sys.executable, '-X', 'utf8', str(root / 'lc_mcp' / 'bridge.py')],
cwd=root, env=dict(os.environ, PYTHONUTF8='1'),
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding='utf-8', bufsize=1,
)
self.sequence = 0
# Windows pipes cannot be polled with select(). Dedicated readers and
# a writer let the caller cancel even if a pipe read/write is blocked.
self._threads = [threading.Thread(target=target, daemon=True) for target in
(self._read_responses, self._write_requests, self._drain_stderr)]
for thread in self._threads:
thread.start()
try:
self.request('initialize', {
'protocolVersion': '2024-11-05', 'capabilities': {},
'clientInfo': {'name': 'lc-mcp-session', 'version': '1'},
})
self._send({'jsonrpc': '2.0', 'method': 'notifications/initialized'})
except BaseException:
self._abort()
raise
def _read_responses(self):
try:
for line in self.process.stdout:
self._responses.put(line)
except (OSError, ValueError, UnicodeError) as error:
self._responses.put(error)
finally:
self._responses.put(None)
def _write_requests(self):
try:
while True:
line = self._outgoing.get()
if line is None:
break
self.process.stdin.write(line)
self.process.stdin.flush()
except (OSError, ValueError) as error:
self._responses.put(error)
finally:
try:
self.process.stdin.close()
except (OSError, ValueError):
pass
def _drain_stderr(self):
try:
for line in self.process.stderr:
self.stderr_tail.append(line.rstrip()[-2000:])
except (OSError, ValueError, UnicodeError):
return
def _send(self, message):
if self._closed:
raise ConnectionError('MCP session is closed')
self._outgoing.put(json.dumps(message, ensure_ascii=False) + '\n')
def request(self, method, params, timeout=None):
limit = self.timeout if timeout is None else float(timeout)
if not math.isfinite(limit) or limit <= 0:
raise ValueError('MCP timeout must be finite and positive')
with self._lock:
if self.cancelled():
self._abort()
raise SessionCancelled('MCP request cancelled before sending')
self.sequence += 1
mid = self.sequence
self._send({'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params})
deadline = time.monotonic() + limit
while True:
if self.cancelled():
self._abort()
error = SessionCancelled('MCP request cancelled; remote outcome unknown', True)
error.tool = params.get('name') if isinstance(params, dict) else None
raise error
remaining = deadline - time.monotonic()
if remaining <= 0:
self._abort()
error = SessionTimeout('MCP %s timed out; remote outcome unknown; request was not retried' % method)
error.tool = params.get('name') if isinstance(params, dict) else None
raise error
try:
line = self._responses.get(timeout=min(.1, remaining))
except queue.Empty:
continue
if line is None or isinstance(line, Exception):
self._abort()
raise ConnectionError('MCP bridge closed') from (line if isinstance(line, Exception) else None)
try:
result = json.loads(line)
if not isinstance(result, dict):
raise ValueError('response must be an object')
except ValueError as error:
self._abort()
raise ConnectionError('MCP bridge returned invalid JSON-RPC') from error
if result.get('id') == mid:
if 'error' in result:
raise RuntimeError(result['error']['message'])
return result['result']
def call(self, name, arguments=None):
arguments = {} if arguments is None else arguments
timeout = self.timeout
if name in ('wait_for_text', 'wait_for_text_gone') and isinstance(arguments, dict):
try:
wait = float(arguments.get('timeout', 30))
if math.isfinite(wait):
timeout = max(timeout, min(300, max(0, wait)) + 5)
except (TypeError, ValueError):
pass # The server reports invalid tool arguments.
result = self.request('tools/call', {'name': name, 'arguments': arguments}, timeout)
data = json.loads(result['content'][0]['text'])
if result.get('isError') and self.raise_on_error:
raise RuntimeError(data)
return data
def _abort(self):
if self.process.poll() is None:
self.process.kill()
self.close()
def close(self):
if self._closed:
return
self._closed = True
self._outgoing.put(None)
try:
self.process.wait(1)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
for thread in self._threads:
thread.join(1)
for stream in (self.process.stdin, self.process.stdout, self.process.stderr):
stream.close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()