89 lines
3.2 KiB
Python
89 lines
3.2 KiB
Python
# -*- 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():
|
|
# The protocol is bytes, but Chinese diagnostics still use stderr text.
|
|
# Windows may otherwise encode errors as cp936 for a UTF-8 MCP client.
|
|
if hasattr(sys.stderr, 'reconfigure'):
|
|
sys.stderr.reconfigure(encoding='utf-8')
|
|
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())
|