File size: 11,296 Bytes
caf8059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
"""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()