mirror of
https://github.com/kuhyx/todo-app.git
synced 2026-11-20 12:52:20 +01:00
MCP closes requests that outlive a deadline
Dart's HttpServer never notices a client that hung up on a request still in flight, so abandoned calls held their sockets (1010 in CLOSE-WAIT, fd limit hit). POST/DELETE open past 90 s now get 503 and close; the library's server is private, so idleTimeout stays default. A zone guard keeps late write errors from killing the process. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
This commit is contained in:
parent
b2ffc346c3
commit
be6bf6fc48
@ -38,11 +38,17 @@ class TodoMcpServer {
|
||||
/// Binds [host]:[port] (0 = any free port); [tokens] is loaded once and
|
||||
/// re-read when its mtime changes, errors going to [log] (default stderr).
|
||||
///
|
||||
/// A POST or DELETE that has no answer after [requestDeadline] is closed
|
||||
/// with 503, which also frees its socket when the client already gave up
|
||||
/// (Dart's HttpServer never notices a half-closed idle request). Keep it
|
||||
/// above [TaskService.callTimeout] so a stuck tool call reports its own
|
||||
/// error first. GET streams are long-lived by design and exempt.
|
||||
static Future<TodoMcpServer> start({
|
||||
required TaskService tasks,
|
||||
required File tokens,
|
||||
String host = '127.0.0.1',
|
||||
int port = kTodoMcpPort,
|
||||
Duration requestDeadline = const Duration(seconds: 90),
|
||||
void Function(String)? log,
|
||||
}) async {
|
||||
final out = log ?? (String line) => stderr.writeln(line);
|
||||
@ -53,6 +59,7 @@ class TodoMcpServer {
|
||||
port: port,
|
||||
authenticator: (request) {
|
||||
if (request is! HttpRequest) return false;
|
||||
_guardDeadline(request, requestDeadline);
|
||||
return switch (store.verdict(
|
||||
request.headers.value(HttpHeaders.authorizationHeader),
|
||||
)) {
|
||||
@ -90,6 +97,29 @@ bool _answerUnavailable(HttpRequest request) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Closes [request]'s response with 503 once [deadline] passes, unless it was
|
||||
/// answered first. Safe on any state: a response already closed or a dead
|
||||
/// socket is ignored.
|
||||
void _guardDeadline(HttpRequest request, Duration deadline) {
|
||||
if (request.method == 'GET') return;
|
||||
final response = request.response;
|
||||
final timer = Timer(deadline, () async {
|
||||
try {
|
||||
response
|
||||
..statusCode = HttpStatus.serviceUnavailable
|
||||
..write('Request timed out');
|
||||
} on StateError {
|
||||
// Headers already sent: just end the stream.
|
||||
}
|
||||
try {
|
||||
await response.close();
|
||||
} on Object {
|
||||
// The peer is gone; the socket is released either way.
|
||||
}
|
||||
});
|
||||
response.done.then<void>((_) {}, onError: (_) {}).whenComplete(timer.cancel);
|
||||
}
|
||||
|
||||
McpServer _server(TaskService tasks) {
|
||||
final server = McpServer(
|
||||
const Implementation(name: 'todo', version: '1.0.0'),
|
||||
|
||||
@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 1.0.91+1
|
||||
version: 1.0.92+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
||||
162
test/mcp/mcp_leak_test.dart
Normal file
162
test/mcp/mcp_leak_test.dart
Normal file
@ -0,0 +1,162 @@
|
||||
// Abandoned requests must not leak sockets. Dart's HttpServer never notices a
|
||||
// client that hung up on a request still being worked on, so 1010 sockets sat
|
||||
// in CLOSE-WAIT and the process ran out of fds (2026-11-16). The server now
|
||||
// answers 503 and closes any request still open at its deadline.
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:todo/cli/cli_session.dart';
|
||||
import 'package:todo/data/note_repository.dart';
|
||||
import 'package:todo/mcp/task_service.dart';
|
||||
import 'package:todo/mcp/todo_mcp_server.dart';
|
||||
import 'package:todo/mcp/token_file.dart';
|
||||
import 'package:todo/sync/sync_service.dart';
|
||||
|
||||
/// A session whose sync never returns: every tool call wedges.
|
||||
class _Wedged extends CliSession {
|
||||
_Wedged(NoteRepository repo, FirebaseRestClient firebase)
|
||||
: super('unused', repo, firebase);
|
||||
|
||||
@override
|
||||
Future<SyncResult> sync({required bool push}) =>
|
||||
Completer<SyncResult>().future;
|
||||
}
|
||||
|
||||
int _openFds() => Directory('/proc/self/fd').listSync().length;
|
||||
|
||||
const _init =
|
||||
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":'
|
||||
'{"protocolVersion":"2025-06-18","capabilities":{},'
|
||||
'"clientInfo":{"name":"leak","version":"1"}}}';
|
||||
const _ready = '{"jsonrpc":"2.0","method":"notifications/initialized"}';
|
||||
const _call =
|
||||
'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":'
|
||||
'{"name":"list_tasks","arguments":{}}}';
|
||||
|
||||
void main() {
|
||||
late Directory tmp;
|
||||
late TodoMcpServer server;
|
||||
late List<String> logged;
|
||||
|
||||
Future<void> start({required Duration callTimeout}) async {
|
||||
tmp = Directory.systemTemp.createTempSync('mcp_leak');
|
||||
final firebase = FirebaseRestClient(
|
||||
databaseUrl: 'https://example.test',
|
||||
auth: FirebaseTokenProvider(
|
||||
apiKey: 'k',
|
||||
store: InMemoryCredentialStore(
|
||||
FirebaseCredentials(
|
||||
idToken: 'id',
|
||||
refreshToken: 'rt',
|
||||
expiresAt: DateTime.utc(2099),
|
||||
),
|
||||
),
|
||||
),
|
||||
httpClient: http.Client(),
|
||||
);
|
||||
final tokens = File('${tmp.path}/tokens')
|
||||
..writeAsStringSync('${tokenHash('t')} pc\n');
|
||||
logged = [];
|
||||
server = await TodoMcpServer.start(
|
||||
tasks: TaskService(
|
||||
_Wedged(await NoteRepository.openInMemory(), firebase),
|
||||
callTimeout: callTimeout,
|
||||
),
|
||||
tokens: tokens,
|
||||
port: 0,
|
||||
requestDeadline: const Duration(milliseconds: 400),
|
||||
log: logged.add,
|
||||
);
|
||||
}
|
||||
|
||||
tearDown(() async {
|
||||
await server.close();
|
||||
tmp.deleteSync(recursive: true);
|
||||
});
|
||||
|
||||
/// POSTs [body] with the bearer token and returns status and session id.
|
||||
Future<(int, String?)> post(String body, {String? session}) async {
|
||||
final client = HttpClient();
|
||||
try {
|
||||
final req = await client.postUrl(server.uri);
|
||||
req.headers
|
||||
..set('content-type', 'application/json')
|
||||
..set('accept', 'application/json, text/event-stream')
|
||||
..set('authorization', 'Bearer t');
|
||||
if (session != null) req.headers.set('mcp-session-id', session);
|
||||
req.write(body);
|
||||
final res = await req.close();
|
||||
await res.drain<void>();
|
||||
return (res.statusCode, res.headers.value('mcp-session-id'));
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a ready session and returns its id.
|
||||
Future<String> open() async {
|
||||
final (status, session) = await post(_init);
|
||||
expect(status, 200);
|
||||
expect((await post(_ready, session: session)).$1, 202);
|
||||
return session!;
|
||||
}
|
||||
|
||||
/// Sends a tools/call, then hangs up before any answer.
|
||||
Future<void> callAndAbort(String session) async {
|
||||
final client = HttpClient();
|
||||
final req = await client.postUrl(server.uri);
|
||||
req.headers
|
||||
..set('content-type', 'application/json')
|
||||
..set('accept', 'application/json, text/event-stream')
|
||||
..set('authorization', 'Bearer t')
|
||||
..set('mcp-session-id', session);
|
||||
req.add(utf8.encode(_call));
|
||||
unawaited(req.close().then<void>((_) {}, onError: (_) {}));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 80));
|
||||
client.close(force: true);
|
||||
}
|
||||
|
||||
Future<void> expectFdsBackTo(int baseline) async {
|
||||
final end = DateTime.now().add(const Duration(seconds: 5));
|
||||
while (_openFds() > baseline && DateTime.now().isBefore(end)) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
}
|
||||
expect(_openFds(), lessThanOrEqualTo(baseline));
|
||||
}
|
||||
|
||||
test('[T-fd-leak] aborted requests against a wedged call free their '
|
||||
'sockets', () async {
|
||||
await start(callTimeout: const Duration(hours: 1));
|
||||
final session = await open();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
final baseline = _openFds();
|
||||
|
||||
for (var i = 0; i < 12; i++) {
|
||||
await callAndAbort(session);
|
||||
}
|
||||
|
||||
await expectFdsBackTo(baseline);
|
||||
// The server still answers afterwards.
|
||||
expect((await post(_init)).$1, 200);
|
||||
});
|
||||
|
||||
test('[T-fd-leak] the late tool error after the deadline cannot crash '
|
||||
'the server', () async {
|
||||
await start(callTimeout: const Duration(milliseconds: 900));
|
||||
await callAndAbort(await open());
|
||||
// Deadline (400 ms) closes the response; the call errors at 900 ms and
|
||||
// tries to write into it.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1400));
|
||||
expect((await post(_init)).$1, 200);
|
||||
});
|
||||
|
||||
test('a call that finishes before the deadline is untouched', () async {
|
||||
await start(callTimeout: const Duration(milliseconds: 100));
|
||||
final (status, _) = await post(_call, session: await open());
|
||||
expect(status, 200, reason: 'tool error is a normal 200 result');
|
||||
});
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user