Compare commits

..

5 Commits

Author SHA1 Message Date
b350b3e8c1 Tidy MCP deadline guard for analyzer
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file-length / file length <= 250 lines (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Guard moves to request_guard.dart (file-length gate); README notes
the token reload, deadline and timeouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 08:06:05 +01:00
e885465f55 todo-mcp unit raises LimitNOFILE to 65536
The 1024 soft limit was exhausted in the 2026-11-16 outage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 08:04:41 +01:00
be6bf6fc48 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
2026-11-16 08:04:40 +01:00
b2ffc346c3 Bound every Firebase and token HTTP call
package:http has no timeout; a dead connection wedged sync forever.
CliSession now wraps its client: 30 s to headers, 30 s per body chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 08:01:50 +01:00
0ce9c42ff6 MCP tokens load once, keep last good set
A read error no longer clears the accepted tokens; with no good
load the answer is 503, not 403. A request costs one stat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
2026-11-16 07:59:31 +01:00
16 changed files with 639 additions and 58 deletions

26
lib/cli/cli_paths.dart Normal file
View File

@ -0,0 +1,26 @@
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:todo/cli/cli_session.dart' show CliSession;
/// Default data dir: `$XDG_DATA_HOME/todo-cli`, else `~/.local/share/todo-cli`.
String defaultDataDir(Map<String, String> env) {
final xdg = env['XDG_DATA_HOME'] ?? '';
final base = xdg.isNotEmpty
? xdg
: p.join(env['HOME'] ?? '', '.local', 'share');
return p.join(base, 'todo-cli');
}
/// Node ids of the installs Claude files notes through: the MCP server and
/// the CLI under the same data root as [defaultDataDir]. Missing ones are
/// skipped.
Set<String> claudeNodeIds(Map<String, String> env) {
final cli = defaultDataDir(env);
return {
for (final dir in [cli, p.join(p.dirname(cli), 'todo-mcp')])
if (File(p.join(dir, CliSession.nodeIdFileName)) case final f
when f.existsSync())
f.readAsStringSync().trim(),
}..remove('');
}

View File

@ -16,32 +16,13 @@ import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import 'package:todo/cli/file_credential_store.dart'; import 'package:todo/cli/file_credential_store.dart';
import 'package:todo/cli/pull_only_store.dart'; import 'package:todo/cli/pull_only_store.dart';
import 'package:todo/cli/timeout_client.dart';
import 'package:todo/data/note_repository.dart'; import 'package:todo/data/note_repository.dart';
import 'package:todo/sync/firebase_project.dart'; import 'package:todo/sync/firebase_project.dart';
import 'package:todo/sync/sync_service.dart'; import 'package:todo/sync/sync_service.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
/// Default data dir: `$XDG_DATA_HOME/todo-cli`, else `~/.local/share/todo-cli`. export 'package:todo/cli/cli_paths.dart';
String defaultDataDir(Map<String, String> env) {
final xdg = env['XDG_DATA_HOME'] ?? '';
final base = xdg.isNotEmpty
? xdg
: p.join(env['HOME'] ?? '', '.local', 'share');
return p.join(base, 'todo-cli');
}
/// Node ids of the installs Claude files notes through: the MCP server and
/// the CLI under the same data root as [defaultDataDir]. Missing ones are
/// skipped.
Set<String> claudeNodeIds(Map<String, String> env) {
final cli = defaultDataDir(env);
return {
for (final dir in [cli, p.join(p.dirname(cli), 'todo-mcp')])
if (File(p.join(dir, CliSession.nodeIdFileName)) case final f
when f.existsSync())
f.readAsStringSync().trim(),
}..remove('');
}
/// The open state of one CLI invocation. Call [close] when done. /// The open state of one CLI invocation. Call [close] when done.
class CliSession { class CliSession {
@ -83,13 +64,19 @@ class CliSession {
/// Opens (creating on first use) the session rooted at [dataDir]. /// Opens (creating on first use) the session rooted at [dataDir].
/// ///
/// [seedCredentials] is todo's desktop session, read once and never written. /// [seedCredentials] is todo's desktop session, read once and never written.
/// [httpClient] replaces the real network client (tests only). /// [httpClient] replaces the real network client (tests only). Either way
/// every request is bounded by [requestTimeout] (see [TimeoutClient]).
static Future<CliSession> open( static Future<CliSession> open(
String dataDir, { String dataDir, {
required String seedCredentials, required String seedCredentials,
String seedApp = 'todo', String seedApp = 'todo',
http.Client? httpClient, http.Client? httpClient,
Duration requestTimeout = const Duration(seconds: 30),
}) async { }) async {
final network = TimeoutClient(
httpClient ?? http.Client(),
timeout: requestTimeout,
);
final dir = Directory(dataDir); final dir = Directory(dataDir);
await dir.create(recursive: true); await dir.create(recursive: true);
// Holds a database-write credential: owner-only, like ~/.config/todo. // Holds a database-write credential: owner-only, like ~/.config/todo.
@ -102,7 +89,7 @@ class CliSession {
); );
final auth = FirebaseTokenProvider( final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey, apiKey: kProject.apiKey,
httpClient: httpClient, httpClient: network,
store: FileCredentialStore( store: FileCredentialStore(
file: File(p.join(dataDir, credentialsFileName)), file: File(p.join(dataDir, credentialsFileName)),
seedFile: File(seedCredentials), seedFile: File(seedCredentials),
@ -118,7 +105,7 @@ class CliSession {
final firebase = FirebaseRestClient( final firebase = FirebaseRestClient(
databaseUrl: kProject.databaseUrl, databaseUrl: kProject.databaseUrl,
auth: auth, auth: auth,
httpClient: httpClient, httpClient: network,
); );
return CliSession( return CliSession(
dataDir, dataDir,

View File

@ -0,0 +1,58 @@
import 'dart:async';
import 'package:http/http.dart' as http;
/// An HTTP client whose every request is bounded.
///
/// `package:http` has no timeout of its own, and neither do the Firebase and
/// token clients built on it: one dead connection (after boot, a network
/// blip) made a sync wait forever and wedged the MCP server's serial queue.
/// [timeout] bounds the wait for the response headers and then each gap
/// between body chunks, so a large body that keeps moving is never cut off.
class TimeoutClient extends http.BaseClient {
/// Wraps [_inner]; each wait fails with a [TimeoutException] after [timeout].
TimeoutClient(this._inner, {this.timeout = const Duration(seconds: 30)});
final http.Client _inner;
/// Longest wait for the headers, and for the next body chunk.
final Duration timeout;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final response = await _inner
.send(request)
.timeout(
timeout,
onTimeout: () => throw TimeoutException(
'${request.method} ${request.url.host} got no response',
timeout,
),
);
return http.StreamedResponse(
response.stream.timeout(
timeout,
onTimeout: (sink) {
sink
..addError(
TimeoutException(
'${request.method} ${request.url.host} body stalled',
timeout,
),
)
..close();
},
),
response.statusCode,
contentLength: response.contentLength,
request: response.request,
headers: response.headers,
isRedirect: response.isRedirect,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase,
);
}
@override
void close() => _inner.close();
}

View File

@ -0,0 +1,40 @@
import 'dart:async';
import 'dart:io';
/// Answers 503 here because the library can only say 403 for a refusal; it
/// then fails to write its own 403 ("Header already sent", swallowed by the
/// zone guard in `TodoMcpServer.start`) and the request stays refused.
bool answerUnavailable(HttpRequest request) {
request.response
..statusCode = HttpStatus.serviceUnavailable
..write('Service Unavailable')
..close().ignore();
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 Object {
// Headers already sent: just end the stream.
}
try {
await response.close();
} on Object {
// The peer is gone; the socket is released either way.
}
});
unawaited(
response.done
.then<void>((_) {}, onError: (_) {})
.whenComplete(timer.cancel),
);
}

View File

@ -25,6 +25,8 @@ class TaskService {
final CliSession _session; final CliSession _session;
final BoardClient? _board; final BoardClient? _board;
/// Longest one call may run before it fails with a TimeoutException.
final Duration callTimeout; final Duration callTimeout;
Future<void> _tail = Future.value(); Future<void> _tail = Future.value();

View File

@ -1,6 +1,8 @@
import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'package:mcp_dart/mcp_dart.dart'; import 'package:mcp_dart/mcp_dart.dart';
import 'package:todo/mcp/request_guard.dart';
import 'package:todo/mcp/task_service.dart'; import 'package:todo/mcp/task_service.dart';
import 'package:todo/mcp/token_file.dart'; import 'package:todo/mcp/token_file.dart';
@ -34,26 +36,50 @@ class TodoMcpServer {
/// `http://<host>:<bound port>/mcp`. /// `http://<host>:<bound port>/mcp`.
Uri get uri => Uri.parse('http://${_http.host}:${_http.boundPort}/mcp'); Uri get uri => Uri.parse('http://${_http.host}:${_http.boundPort}/mcp');
/// Binds [host]:[port] (0 = any free port); [tokens] is read per request. /// 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({ static Future<TodoMcpServer> start({
required TaskService tasks, required TaskService tasks,
required File tokens, required File tokens,
String host = '127.0.0.1', String host = '127.0.0.1',
int port = kTodoMcpPort, int port = kTodoMcpPort,
Duration requestDeadline = const Duration(seconds: 90),
void Function(String)? log,
}) async { }) async {
final out = log ?? (String line) => stderr.writeln(line);
final store = TokenStore(tokens, log: out);
final http = StreamableMcpServer( final http = StreamableMcpServer(
serverFactory: (_) => _server(tasks), serverFactory: (_) => _server(tasks),
host: host, host: host,
port: port, port: port,
authenticator: (request) => tokenAccepted( authenticator: (request) {
tokens, if (request is! HttpRequest) return false;
request is HttpRequest guardDeadline(request, requestDeadline);
? request.headers.value(HttpHeaders.authorizationHeader) return switch (store.verdict(
: null, request.headers.value(HttpHeaders.authorizationHeader),
), )) {
TokenVerdict.accepted => true,
TokenVerdict.rejected => false,
TokenVerdict.unavailable => answerUnavailable(request),
};
},
allowedHosts: const {'localhost', '127.0.0.1', '::1', _publicHost}, allowedHosts: const {'localhost', '127.0.0.1', '::1', _publicHost},
); );
await http.start(); // The library runs each request as an unawaited future in the zone that
// called start(): without a guard, one failed write (a response we closed
// first) would be an uncaught error and kill the process.
await runZonedGuarded(http.start, (error, stack) {
if (error is StateError && '$error'.contains('Header already sent')) {
return; // the library answering a request we already answered
}
out('todo-mcp: request error: $error');
});
return TodoMcpServer._(http); return TodoMcpServer._(http);
} }

View File

@ -5,27 +5,78 @@ import 'package:crdt_sync/crdt_sync.dart';
/// sha256 hex of [token] (crdt_sync's `revisionOf` is exactly that). /// sha256 hex of [token] (crdt_sync's `revisionOf` is exactly that).
String tokenHash(String token) => revisionOf(token); String tokenHash(String token) => revisionOf(token);
Set<String> _hashes(File tokens) { /// What the tokens file says about one `Authorization` header.
final String text; enum TokenVerdict {
try { /// A listed token: let the request in.
text = tokens.readAsStringSync(); accepted,
} on FileSystemException {
return const {}; /// Missing, malformed or unlisted: HTTP 403.
rejected,
/// No token set has ever loaded, so nothing can be judged: HTTP 503.
unavailable,
}
/// The sha256-hashed bearer tokens of [file], loaded once.
///
/// A request costs one `stat`; the file is re-read only when its mtime or
/// size changed. A failed read keeps the last good set (an exhausted fd table
/// once made every valid token read as "no tokens", i.e. 403) and is logged
/// once per distinct error. Until a first good load every well-formed bearer
/// is [TokenVerdict.unavailable], never a refusal.
class TokenStore {
/// Watches [file]; [log] gets read errors.
TokenStore(this.file, {required this.log});
/// The `<sha256> <name>` lines, `#` comments allowed.
final File file;
/// Receives read errors, one line each.
final void Function(String) log;
Set<String>? _hashes;
(DateTime, int)? _seen;
String? _lastError;
/// Judges [authorization] (an `Authorization` header value or null).
TokenVerdict verdict(String? authorization) {
const scheme = 'bearer ';
if (authorization == null ||
!authorization.toLowerCase().startsWith(scheme)) {
return TokenVerdict.rejected;
}
final token = authorization.substring(scheme.length).trim();
if (token.isEmpty) return TokenVerdict.rejected;
_refresh();
final hashes = _hashes;
if (hashes == null) return TokenVerdict.unavailable;
return hashes.contains(tokenHash(token))
? TokenVerdict.accepted
: TokenVerdict.rejected;
} }
return {
void _refresh() {
try {
final stat = file.statSync();
if (stat.type == FileSystemEntityType.notFound) {
throw FileSystemException('no such file', file.path);
}
final key = (stat.modified, stat.size);
if (key == _seen) return;
_hashes = _parse(file.readAsStringSync());
_seen = key;
_lastError = null;
} on FileSystemException catch (e) {
// Keep the last good set; `_seen` stays, so the next request retries.
final message = '${e.message} ${e.path} ${e.osError?.errorCode}';
if (message != _lastError) log('tokens: keeping last set: $message');
_lastError = message;
}
}
static Set<String> _parse(String text) => {
for (final line in text.split('\n')) for (final line in text.split('\n'))
if (line.trim() case final t when t.isNotEmpty && !t.startsWith('#')) if (line.trim() case final t when t.isNotEmpty && !t.startsWith('#'))
t.split(RegExp(r'\s+')).first.toLowerCase(), t.split(RegExp(r'\s+')).first.toLowerCase(),
}; };
} }
/// Whether [authorization] bears a token hashed in [tokens], read per call.
bool tokenAccepted(File tokens, String? authorization) {
const scheme = 'bearer ';
if (authorization == null ||
!authorization.toLowerCase().startsWith(scheme)) {
return false;
}
final token = authorization.substring(scheme.length).trim();
return token.isNotEmpty && _hashes(tokens).contains(tokenHash(token));
}

View File

@ -33,4 +33,8 @@ systemctl --user enable --now todo-mcp.service
``` ```
Deploy a new build: `mcp/install.sh` (restarts a running unit). Deploy a new build: `mcp/install.sh` (restarts a running unit).
Revoke a token: delete its line in `tokens`; no restart needed. Revoke a token: delete its line in `tokens`; no restart needed. The file is
loaded once and re-read when its mtime or size changes; a read error (or a
deleted file) keeps the last good set, and before any good load the answer is
503, not 403. A POST open for 90 s gets 503 and its socket closed; sync HTTP
calls time out after 30 s; the unit sets `LimitNOFILE=65536`.

View File

@ -7,6 +7,8 @@ Wants=network-online.target
ExecStart=%h/.local/lib/todo-mcp/todo_mcp ExecStart=%h/.local/lib/todo-mcp/todo_mcp
Restart=on-failure Restart=on-failure
RestartSec=30 RestartSec=30
# The default soft limit is 1024; leaked sockets once used every one of them.
LimitNOFILE=65536
[Install] [Install]
WantedBy=default.target WantedBy=default.target

View File

@ -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 # 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 # 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. # of the product and file versions while build-number is used as the build suffix.
version: 1.0.89+1 version: 1.0.94+1
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2

View File

@ -0,0 +1,85 @@
// Every Firebase and token call a CliSession makes is bounded: a request that
// never answers (dead connection, blackholed route) must fail with a
// TimeoutException instead of holding the MCP server's one-at-a-time queue.
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
import 'package:todo/cli/cli_session.dart';
import 'package:todo/cli/timeout_client.dart';
import 'fake_rtdb.dart';
const _limit = Duration(milliseconds: 150);
http.Client _answering({Stream<List<int>>? body}) =>
http_testing.MockClient.streaming(
(request, _) async =>
http.StreamedResponse(body ?? Stream.value([111, 107]), 200),
);
void main() {
test('a fast response passes through untouched', () async {
final client = TimeoutClient(_answering(), timeout: _limit);
expect((await client.get(Uri.parse('http://x.test/'))).body, 'ok');
});
test('[T-http-timeout] a request that never answers times out', () async {
final client = TimeoutClient(
http_testing.MockClient((_) => Completer<http.Response>().future),
timeout: _limit,
);
await expectLater(
client.get(Uri.parse('http://x.test/')),
throwsA(isA<TimeoutException>()),
);
});
test('a body that stalls after the headers times out', () async {
final stalled = StreamController<List<int>>()..add([1]);
final client = TimeoutClient(
_answering(body: stalled.stream),
timeout: _limit,
);
await expectLater(
client.get(Uri.parse('http://x.test/')),
throwsA(isA<TimeoutException>()),
);
await stalled.close();
});
test('a slow but moving body is not cut off', () async {
final slow = Stream.periodic(
const Duration(milliseconds: 60),
(i) => [i],
).take(5);
final client = TimeoutClient(_answering(body: slow), timeout: _limit);
expect(
(await client.get(Uri.parse('http://x.test/'))).bodyBytes,
hasLength(5),
);
});
test(
'[T-http-timeout] a CliSession sync against a dead network fails',
() async {
final tmp = Directory.systemTemp.createTempSync('timeout_client');
addTearDown(() => tmp.deleteSync(recursive: true));
final session = await CliSession.open(
'${tmp.path}/data',
seedCredentials: writeSeedCredentials(tmp).path,
httpClient: http_testing.MockClient(
(_) => Completer<http.Response>().future,
),
requestTimeout: _limit,
);
addTearDown(session.close);
await expectLater(
session.sync(push: true),
throwsA(isA<TimeoutException>()),
);
},
);
}

View File

@ -1,6 +1,9 @@
// Bearer tokens are checked against sha256 hashes in the tokens file, re-read // Bearer tokens are checked against sha256 hashes in the tokens file, re-read
// per request so revoking a line takes effect without a restart; the Host // when it changes so revoking a line takes effect without a restart; a read
// check admits loopback and the public proxy name only. // error keeps the last good set, and with none loaded the answer is 503. The
// Host check admits loopback and the public proxy name only.
import 'dart:io';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'mcp_harness.dart'; import 'mcp_harness.dart';
@ -33,9 +36,25 @@ void main() {
expect(await h.rawInitialize({'authorization': ok}), anyOf(401, 403)); expect(await h.rawInitialize({'authorization': ok}), anyOf(401, 403));
}); });
test('a missing tokens file admits nobody', () async { test('a vanished tokens file keeps the tokens already loaded', () async {
expect(await h.rawInitialize({'authorization': ok}), 200);
h.tokens.deleteSync(); h.tokens.deleteSync();
expect(await h.rawInitialize({'authorization': ok}), anyOf(401, 403)); expect(await h.rawInitialize({'authorization': ok}), 200);
});
test('[T-tokens-keep] an unreadable file keeps the loaded tokens', () async {
expect(await h.rawInitialize({'authorization': ok}), 200);
h.tokens.writeAsStringSync('# rewritten, then locked\n');
Process.runSync('chmod', ['000', h.tokens.path]);
expect(await h.rawInitialize({'authorization': ok}), 200);
});
test('[T-tokens-503] no good load yet answers 503, not 403', () async {
Process.runSync('chmod', ['000', h.tokens.path]);
expect(await h.rawInitialize({'authorization': ok}), 503);
expect(await h.rawInitialize({}), 403, reason: 'no bearer: plain refusal');
Process.runSync('chmod', ['600', h.tokens.path]);
expect(await h.rawInitialize({'authorization': ok}), 200);
}); });
test('the proxy host is admitted, a foreign host is not', () async { test('the proxy host is admitted, a foreign host is not', () async {

View File

@ -24,7 +24,7 @@ class McpHarness {
final BoardClient? board; final BoardClient? board;
static const token = 'test-token-for-pc'; static const token = 'test-token-for-pc';
final tmp = Directory.systemTemp.createTempSync('mcp_harness'); final Directory tmp = Directory.systemTemp.createTempSync('mcp_harness');
final db = FakeRtdb(); final db = FakeRtdb();
late final File tokens = File('${tmp.path}/tokens'); late final File tokens = File('${tmp.path}/tokens');
late final CliSession session; late final CliSession session;
@ -135,4 +135,4 @@ class McpHarness {
/// The first full uuid in [text]. /// The first full uuid in [text].
String idIn(String text) => String idIn(String text) =>
RegExp(r'[0-9a-f]{8}-[0-9a-f-]{27}').firstMatch(text)!.group(0)!; RegExp('[0-9a-f]{8}-[0-9a-f-]{27}').firstMatch(text)!.group(0)!;

162
test/mcp/mcp_leak_test.dart Normal file
View 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');
});
}

View File

@ -0,0 +1,19 @@
// The unit mcp/install.sh installs must lift the 1024-fd soft limit: the
// 2026-11-16 outage ended with the process at 1023 of 1024 fds.
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('[T-nofile] the installed unit raises LimitNOFILE', () {
final unit = File('mcp/todo-mcp.service').readAsStringSync();
expect(unit, matches(RegExp(r'^LimitNOFILE=65536$', multiLine: true)));
final service = unit.split('[Service]')[1].split('[Install]').first;
expect(service, contains('LimitNOFILE=65536'), reason: 'in [Service]');
expect(
File('mcp/install.sh').readAsStringSync(),
contains(r'install -m 644 "$ROOT/mcp/$UNIT"'),
reason: 'install.sh ships this very file',
);
});
}

View File

@ -0,0 +1,100 @@
// The tokens file is read once and again only when its mtime or size changes.
// A read error keeps the last good set (an exhausted fd table once made every
// valid token read as 403); with no good load yet the answer is "unavailable".
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:todo/mcp/token_file.dart';
void main() {
late Directory tmp;
late File file;
late List<String> logged;
late TokenStore store;
setUp(() {
tmp = Directory.systemTemp.createTempSync('token_store');
file = File('${tmp.path}/tokens')
..writeAsStringSync('${tokenHash('good')} pc\n# note\n');
logged = [];
store = TokenStore(file, log: logged.add);
});
tearDown(() {
if (file.existsSync()) Process.runSync('chmod', ['600', file.path]);
tmp.deleteSync(recursive: true);
});
TokenVerdict check(String token) => store.verdict('Bearer $token');
/// Rewrites [file] and moves its mtime on, so the change is always seen.
void rewrite(String text) {
final before = file.lastModifiedSync();
file
..writeAsStringSync(text)
..setLastModifiedSync(before.add(const Duration(seconds: 5)));
}
test('a listed token is accepted, others and malformed headers rejected', () {
expect(check('good'), TokenVerdict.accepted);
expect(check('bad'), TokenVerdict.rejected);
expect(store.verdict(null), TokenVerdict.rejected);
expect(store.verdict('Basic good'), TokenVerdict.rejected);
expect(store.verdict('Bearer '), TokenVerdict.rejected);
});
test('[T-tokens-mtime] the file is not re-read while its mtime holds', () {
expect(check('good'), TokenVerdict.accepted);
final mtime = file.lastModifiedSync();
// Same length, same mtime: only a re-read could notice the new hash.
file
..writeAsStringSync('${tokenHash('other')} pc\n# note\n')
..setLastModifiedSync(mtime);
expect(check('good'), TokenVerdict.accepted);
expect(check('other'), TokenVerdict.rejected);
});
test('a changed mtime reloads, so deleting a line revokes it', () {
expect(check('good'), TokenVerdict.accepted);
rewrite('# revoked\n');
expect(check('good'), TokenVerdict.rejected);
});
test('[T-tokens-keep] an unreadable file after a good load keeps tokens', () {
expect(check('good'), TokenVerdict.accepted);
rewrite('${tokenHash('good')} pc\n${tokenHash('new')} pc2\n');
Process.runSync('chmod', ['000', file.path]);
expect(check('good'), TokenVerdict.accepted);
expect(check('new'), TokenVerdict.rejected);
expect(logged, isNotEmpty);
});
test('a vanished file after a good load keeps the last set', () {
expect(check('good'), TokenVerdict.accepted);
file.deleteSync();
expect(check('good'), TokenVerdict.accepted);
});
test('the file coming back readable is picked up again', () {
expect(check('good'), TokenVerdict.accepted);
rewrite('${tokenHash('new')} pc\n');
Process.runSync('chmod', ['000', file.path]);
expect(check('new'), TokenVerdict.rejected);
Process.runSync('chmod', ['600', file.path]);
expect(check('new'), TokenVerdict.accepted);
expect(check('good'), TokenVerdict.rejected);
});
test('[T-tokens-503] no good load yet is unavailable, not rejected', () {
Process.runSync('chmod', ['000', file.path]);
expect(check('good'), TokenVerdict.unavailable);
expect(check('bad'), TokenVerdict.unavailable);
expect(logged, hasLength(1), reason: 'the same error is logged once');
Process.runSync('chmod', ['600', file.path]);
expect(check('good'), TokenVerdict.accepted);
});
test('a missing file with no good load is unavailable', () {
file.deleteSync();
expect(check('good'), TokenVerdict.unavailable);
});
}