Files
lc-mcp/scripts/mcp_session.py
T

64 lines
2.2 KiB
Python

"""Reusable client for the installed stdio MCP bridge; no direct game input."""
import json
import os
import subprocess
import sys
from pathlib import Path
class Session:
def __init__(self):
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
self.request('initialize', {
'protocolVersion': '2024-11-05', 'capabilities': {},
'clientInfo': {'name': 'lc-mcp-session', 'version': '1'},
})
self.process.stdin.write(json.dumps({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + '\n')
self.process.stdin.flush()
def request(self, method, params):
self.sequence += 1
mid = self.sequence
request = {'jsonrpc': '2.0', 'id': mid, 'method': method, 'params': params}
self.process.stdin.write(json.dumps(request, ensure_ascii=False) + '\n')
self.process.stdin.flush()
while True:
line = self.process.stdout.readline()
if not line:
raise ConnectionError('MCP bridge closed')
result = json.loads(line)
if result.get('id') == mid:
if 'error' in result:
raise RuntimeError(result['error']['message'])
return result['result']
def call(self, name, arguments=None):
result = self.request('tools/call', {'name': name, 'arguments': arguments or {}})
data = json.loads(result['content'][0]['text'])
if result.get('isError'):
raise RuntimeError(data)
return data
def close(self):
self.process.stdin.close()
try:
self.process.wait(5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
self.process.stdout.close()
self.process.stderr.close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()