This website requires JavaScript.
0
Issues
Pull Requests
Milestones
Explore
0
Create…
New Repository
New Migration
New Organization
public
Signed in as
public
Profile
Starred
Subscriptions
Settings
Help
Sign Out
yws
/
lc-mcp
Watch
1
Star
0
Fork
0
Code
Issues
Pull Requests
Actions
Packages
Projects
Releases
Wiki
Activity
Files
lc-mcp
/
scripts
/
or
Cancel
Edit File
Preview
Preview Changes
Spaces
Tabs
2
4
8
Wrap
No wrap
"""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()
Commit Changes
Add a Signed-off-by trailer by the committer at the end of the commit log message.
Commit directly to the
fix/team-scroll-patch
branch.
Create a
new branch
for this commit and start a pull request.
Commit Changes
Cancel