import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:cutdex_core/mcp.dart'; /// Private loopback transport for the stdio launcher. This is not an MCP HTTP /// endpoint. The first line authenticates; remaining bytes are MCP stdio frames. class LocalMcpBridge { LocalMcpBridge._(this._listener, this._server, this._token) { _listener.listen(_accept); } final ServerSocket _listener; final CutdexMcpServer _server; final String _token; final _sockets = {}; final _sessions = >{}; bool _closed = false; int get port => _listener.port; static Future start( CutdexMcpServer server, { required int port, required String token, }) async { if (port < 0 || port > 65535 || token.length < 32 || token.length > 1024 || token.contains('\n') || token.contains('\r')) { throw ArgumentError( 'MCP requires a valid port and a 32-1024 character token', ); } final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, port); return LocalMcpBridge._(socket, server, token); } void _accept(Socket socket) { if (_closed || _sockets.length >= 32) { socket.destroy(); return; } _sockets.add(socket); final task = _serve(socket); _sessions.add(task); unawaited( task.whenComplete(() { _sessions.remove(task); }), ); } Future _serve(Socket socket) async { final input = StreamIterator>(socket); try { final bytes = []; final deadline = DateTime.now().add(const Duration(seconds: 5)); while (await input.moveNext().timeout( deadline.difference(DateTime.now()), )) { final chunk = input.current; final newline = chunk.indexOf(10); final count = newline < 0 ? chunk.length : newline; if (bytes.length + count > 4096) return; bytes.addAll(chunk.take(count)); if (newline < 0) continue; if (utf8.decode(bytes) != _token) return; Stream> frames() async* { if (newline + 1 < chunk.length) yield chunk.sublist(newline + 1); while (await input.moveNext()) { yield input.current; } } await serveMcpStdio(_server, input: frames(), output: socket); return; } } catch (_) { // Transport failures end this connection, not the project or other clients. } finally { socket.destroy(); await input.cancel(); _sockets.remove(socket); } } Future close() async { if (_closed) return; _closed = true; await _listener.close(); for (final socket in _sockets.toList()) { socket.destroy(); } await Future.wait(_sessions.toList()); } }