Fix MCP cancellation, mirror run state, and battle boundaries

Browse Source
This commit is contained in:
Codex
2026-10-03 01:21:51 +08:00
parent 97eca204c2
commit 7188b4ac0f
12 changed files with 926 additions and 117 deletions
+145 -27
View File
@@ -1,13 +1,39 @@
"""Reusable client for the installed stdio MCP bridge; no direct game input.""" """Reusable client for the installed stdio MCP bridge; no direct game input."""
import json import json
import math
import os import os
import queue
import subprocess import subprocess
import sys import sys
import threading
import time
from collections import deque
from pathlib import Path 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: class Session:
def __init__(self): def __init__(self, timeout=30, cancelled=None):
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)
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] root = Path(__file__).resolve().parents[1]
self.process = subprocess.Popen( self.process = subprocess.Popen(
[sys.executable, '-X', 'utf8', str(root / 'lc_mcp' / 'bridge.py')], [sys.executable, '-X', 'utf8', str(root / 'lc_mcp' / 'bridge.py')],
@@ -16,45 +42,137 @@ class Session:
text=True, encoding='utf-8', bufsize=1, text=True, encoding='utf-8', bufsize=1,
) )
self.sequence = 0 self.sequence = 0
self.request('initialize', { # Windows pipes cannot be polled with select(). Dedicated readers and
'protocolVersion': '2024-11-05', 'capabilities': {}, # a writer let the caller cancel even if a pipe read/write is blocked.
'clientInfo': {'name': 'lc-mcp-session', 'version': '1'}, self._threads = [threading.Thread(target=target, daemon=True) for target in
}) (self._read_responses, self._write_requests, self._drain_stderr)]
self.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + '\n') for thread in self._threads:
self.process.stdin.flush() 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 request(self, method, params): def _read_responses(self):
self.sequence += 1 try:
mid = self.sequence for line in self.process.stdout:
request = {'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params} self._responses.put(line)
self.process.stdin.write(json.dumps(request, ensure_ascii=False) + '\n') except (OSError, ValueError, UnicodeError) as error:
self.process.stdin.flush() self._responses.put(error)
while True: finally:
line = self.process.stdout.readline() self._responses.put(None)
if not line:
raise ConnectionError('MCP bridge closed') def _write_requests(self):
result = json.loads(line) try:
if result.get('id') == mid: while True:
if 'error' in result: line = self._outgoing.get()
raise RuntimeError(result['error']['message']) if line is None:
return result['result'] 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): def call(self, name, arguments=None):
result = self.request('tools/call', {'name': name, 'arguments': arguments or {}}) 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']) data = json.loads(result['content'][0]['text'])
if result.get('isError'): if result.get('isError'):
raise RuntimeError(data) raise RuntimeError(data)
return data return data
def _abort(self):
if self.process.poll() is None:
self.process.kill()
self.close()
def close(self): def close(self):
self.process.stdin.close() if self._closed:
return
self._closed = True
self._outgoing.put(None)
try: try:
self.process.wait(5) self.process.wait(1)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
self.process.kill() self.process.kill()
self.process.wait() self.process.wait()
self.process.stdout.close() for thread in self._threads:
self.process.stderr.close() thread.join(1)
for stream in (self.process.stdin, self.process.stdout, self.process.stderr):
stream.close()
def __enter__(self): def __enter__(self):
return self return self