"""Fixed local MCP stdio server and bounded client. Never executes model code.""" import json import os import queue import subprocess import sys import threading import time from pathlib import Path ROOT = Path(__file__).resolve().parents[3] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from src.adapters.persistence.local_identity import LocalIdentity from src.modules.knowledge.erp_mcp import BusinessKnowledgeStore, TOOLS from src.modules.skill.domain.models import SkillError, digest PROTOCOL = '2025-06-18' MAX_MESSAGE = 32768 class MCPServer: def __init__(self, store): self.store, self.initialized, self.ready = store, False, False def handle(self, message): request_id = message.get('id') if isinstance(message, dict) else None try: if not isinstance(message, dict) or message.get('jsonrpc') != '2.0' or not isinstance(message.get('method'), str): raise ValueError('invalid request') method, params = message['method'], message.get('params', {}) if not isinstance(params, dict): raise ValueError('invalid params') if method == 'notifications/initialized' and request_id is None: self.ready = self.initialized return None if request_id is None or type(request_id) not in (str, int): raise ValueError('request id required') if method == 'initialize': if self.initialized or params.get('protocolVersion') != PROTOCOL: raise ValueError('protocol version or state invalid') self.initialized = True result = {'protocolVersion': PROTOCOL, 'capabilities': {'tools': {'listChanged': False}}, 'serverInfo': {'name': 'zkcoding-business-knowledge', 'version': '1.0.0'}} elif not self.ready: return self.error(request_id, -32002, 'MCP session is not initialized') elif method == 'tools/list': if params: raise ValueError('list parameters invalid') result = {'tools': TOOLS} elif method == 'tools/call': if set(params) != {'name', 'arguments'} or not isinstance(params['name'], str): raise ValueError('call parameters invalid') try: data = self.store.execute(params['name'], params['arguments']) result = {'content': [{'type': 'text', 'text': json.dumps(data, ensure_ascii=False)}], 'structuredContent': data, 'isError': False} except SkillError as exc: data = {'code': exc.code, 'message': exc.message, 'status': exc.status} result = {'content': [{'type': 'text', 'text': json.dumps(data, ensure_ascii=False)}], 'structuredContent': data, 'isError': True} elif method == 'ping': result = {} else: return self.error(request_id, -32601, 'Method not found') return {'jsonrpc': '2.0', 'id': request_id, 'result': result} except ValueError: return self.error(request_id, -32602, 'Invalid request or parameters') except Exception: return self.error(request_id, -32603, 'Internal MCP error') @staticmethod def error(request_id, code, message): return {'jsonrpc': '2.0', 'id': request_id, 'error': {'code': code, 'message': message}} class MCPClient: def __init__(self, database, identity_path, actor_id, timeout=15): self.database, self.identity_path, self.actor_id, self.timeout = Path(database), Path(identity_path), actor_id, timeout def exchange(self, calls): if len(calls) > 16 or len(json.dumps(calls, ensure_ascii=False).encode('utf-8')) > MAX_MESSAGE: raise SkillError('MCP_INPUT_TOO_LARGE', '工具请求过大。', 413) env = {key: value for key, value in os.environ.items() if key.upper() in {'SYSTEMROOT', 'WINDIR', 'TEMP', 'TMP'}} command = [sys.executable, '-I', str(Path(__file__).resolve()), '--database', str(self.database.resolve()), '--identity', str(self.identity_path.resolve()), '--actor', self.actor_id] process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env, cwd=str(ROOT), creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) deadline = time.monotonic() + self.timeout responses, stopped = queue.Queue(maxsize=1), threading.Event() completed = False def read_output(): total = 0 while not stopped.is_set(): try: line = process.stdout.readline(2_000_001) total += len(line) item = ('data', line) if line and total <= 2_000_000 else ('invalid', None) except (OSError, ValueError): item = ('invalid', None) while not stopped.is_set(): try: responses.put(item, timeout=0.05) break except queue.Full: continue if item[0] != 'data': return reader = threading.Thread(target=read_output, name='business-mcp-stdout', daemon=True) reader.start() def send(message): if time.monotonic() >= deadline: raise SkillError('MCP_DEADLINE_EXCEEDED', '业务工具超时;请查询当前记录状态后重试同一请求。', 504) try: process.stdin.write((json.dumps(message, ensure_ascii=False) + '\n').encode('utf-8')) process.stdin.flush() except (BrokenPipeError, OSError): raise SkillError('MCP_TRANSPORT_FAILED', '本地业务工具暂时不可用。', 503) from None def request(request_id, method, params=None): message = dict(jsonrpc='2.0', id=request_id, method=method) if params is not None: message['params'] = params send(message) remaining = deadline - time.monotonic() try: if remaining <= 0: raise queue.Empty kind, line = responses.get(timeout=remaining) except queue.Empty: raise SkillError('MCP_DEADLINE_EXCEEDED', '业务工具超时;请查询当前记录状态后重试同一请求。', 504) from None if kind != 'data': raise SkillError('MCP_TRANSPORT_FAILED', '本地业务工具暂时不可用。', 503) response = json.loads(line.decode('utf-8')) if response.get('jsonrpc') != '2.0' or response.get('id') != request_id or 'error' in response: raise ValueError('response id or protocol mismatch') return response['result'] try: initialized = request(1, 'initialize', {'protocolVersion': PROTOCOL, 'capabilities': {}, 'clientInfo': {'name': 'zkcoding-workbench', 'version': '1.0.0'}}) if initialized['protocolVersion'] != PROTOCOL or 'tools' not in initialized['capabilities']: raise ValueError('protocol mismatch') # Continue only after validating the negotiated initialize response. send(dict(jsonrpc='2.0', method='notifications/initialized')) catalog = request(2, 'tools/list') if catalog['tools'] != TOOLS: raise ValueError('unapproved tool catalog') results, evidence = [], [] for request_id, (name, arguments) in enumerate(calls, 3): result = request(request_id, 'tools/call', {'name': name, 'arguments': arguments}) data = result['structuredContent'] if result['isError']: raise SkillError(data['code'], data['message'], data['status']) results.append(data) evidence.append({'tool': name, 'arguments': arguments, 'transport': 'stdio', 'protocol': PROTOCOL, 'process_id': process.pid, 'request_id': request_id, 'result_digest': digest(data), 'audit_id': data.get('audit_id'), 'success': True}) process.stdin.close() try: process.wait(timeout=max(0.01, deadline - time.monotonic())) except subprocess.TimeoutExpired: raise SkillError('MCP_DEADLINE_EXCEEDED', '本地业务工具未按时结束。', 504) from None if process.returncode != 0: raise SkillError('MCP_TRANSPORT_FAILED', '本地业务工具暂时不可用。', 503) completed = True return {'results': results, 'tool_calls': evidence, 'tools': catalog['tools'], 'health': {'status': 'connected', 'transport': 'stdio', 'protocol': PROTOCOL, 'server': initialized['serverInfo'], 'process_id': process.pid, 'receipts': [{'method': 'initialize', 'request_id': 1, 'response_validated': True}, {'method': 'notifications/initialized', 'sent': True}, {'method': 'tools/list', 'request_id': 2, 'response_validated': True}], 'process_exited': process.returncode == 0}} except (ValueError, KeyError, TypeError, UnicodeError): raise SkillError('MCP_PROTOCOL_INVALID', '本地业务工具返回了无效响应。', 502) from None finally: stopped.set() if not completed and process.poll() is None: process.kill() process.wait(timeout=2) for stream in (process.stdin, process.stdout): try: stream.close() except OSError: pass reader.join(timeout=1) def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument('--database', required=True) parser.add_argument('--identity', required=True) parser.add_argument('--actor', required=True) args = parser.parse_args() server = MCPServer(BusinessKnowledgeStore(args.database, LocalIdentity(args.identity), args.actor)) while True: line = sys.stdin.buffer.readline(MAX_MESSAGE + 1) if not line: break if len(line) > MAX_MESSAGE: response = server.error(None, -32600, 'Message too large') sys.stdout.buffer.write((json.dumps(response) + '\n').encode()) sys.stdout.buffer.flush() break try: response = server.handle(json.loads(line.decode('utf-8'))) except (ValueError, UnicodeDecodeError): response = server.error(None, -32700, 'Parse error') if response is not None: sys.stdout.buffer.write((json.dumps(response, ensure_ascii=False) + '\n').encode('utf-8')) sys.stdout.buffer.flush() if __name__ == '__main__': main()