MCP reads reuse a sync done within 2 s

A board fetch makes 15 MCP calls and each one synced with Firebase
(0.5-1 s), so a fetch took 12 s. Reads skip the sync when one ended
within readFreshness; writes always pull and push.

Todo: 475dc1d1
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXu5EV5tPkCTEu6nxf
This commit is contained in:
Krzysztof Rudnicki 2026-11-19 11:17:50 +01:00
parent 5acd9d4863
commit fafefabab6
5 changed files with 127 additions and 12 deletions

View File

@ -8,6 +8,7 @@ import 'package:todo/data/note_repository.dart';
import 'package:todo/data/repo_note.dart';
import 'package:todo/mcp/board_client.dart';
import 'package:todo/mcp/task_split.dart';
import 'package:todo/sync/sync_service.dart';
/// The six task tools over one persistent sync node; calls run one at a time.
class TaskService {
@ -21,6 +22,7 @@ class TaskService {
this._session, {
this._board,
this.callTimeout = const Duration(seconds: 60),
this.readFreshness = const Duration(seconds: 2),
});
final CliSession _session;
@ -28,6 +30,13 @@ class TaskService {
/// Longest one call may run before it fails with a TimeoutException.
final Duration callTimeout;
/// How long a finished sync still counts for the read calls (list, search,
/// get). The board reads 15 times per fetch and each sync is a Firebase
/// round trip of 0.5-1 s, so reads inside the window skip it; every write
/// still pulls and pushes. [Duration.zero] syncs on every read.
final Duration readFreshness;
final Stopwatch _since = Stopwatch();
Future<void> _tail = Future.value();
Future<T> _serial<T>(Future<T> Function() body) {
@ -36,22 +45,34 @@ class TaskService {
return run;
}
Future<List<Note>> _pull() async {
final skipped = (await _session.sync(push: true)).skippedFiles;
if (skipped.isNotEmpty) throw StateError('sync: unmergeable $skipped');
Future<SyncResult> _sync() async {
final result = await _session.sync(push: true);
_since
..reset()
..start();
return result;
}
/// Pulls every peer, unless [read] and a sync ended within [readFreshness].
Future<List<Note>> _pull({bool read = false}) async {
final fresh = _since.isRunning && _since.elapsed < readFreshness;
if (!read || !fresh) {
final skipped = (await _sync()).skippedFiles;
if (skipped.isNotEmpty) throw StateError('sync: unmergeable $skipped');
}
return await _session.repository.listNotes();
}
Future<String> _save(Note note, String verb) async {
await _session.repository.upsert(note.copyWith(updatedAt: DateTime.now()));
await _session.sync(push: true);
await _sync();
return '$verb ${note.id}\n${listLine(note)}';
}
Future<Note> _find(_Args a) async {
Future<Note> _find(_Args a, {bool read = false}) async {
final id = a.required('id');
try {
return findNote(await _pull(), id);
return findNote(await _pull(read: read), id);
} on NoteLookupError catch (e) {
throw FormatException('id: $e');
}
@ -102,7 +123,7 @@ class TaskService {
final repo = a.repo();
final statuses = a.statuses();
final ideas = a.flag('no_repo');
await _pull();
await _pull(read: true);
final notes = await _session.repository.listNotes(
filter: NoteFilter(statuses: statuses, repo: repo, repoTasksOnly: !ideas),
);
@ -112,7 +133,7 @@ class TaskService {
/// `search_tasks`: repo tasks of any status whose text or repo matches.
Future<String> search(Map<String, dynamic> args) => _serial(() async {
final query = _Args(args).required('query');
await _pull();
await _pull(read: true);
return _lines(
await _session.repository.listNotes(
filter: NoteFilter(query: query, repoTasksOnly: true),
@ -122,7 +143,7 @@ class TaskService {
/// `get_task`: one note in full.
Future<String> get(Map<String, dynamic> args) =>
_serial(() async => noteDetail(await _find(_Args(args))));
_serial(() async => noteDetail(await _find(_Args(args), read: true)));
/// `update_task`: changes only the keys given; `done_check: ""` clears it.
Future<String> update(Map<String, dynamic> args) => _serial(() async {

View File

@ -23,6 +23,10 @@ task (`id8 status priority repo title created_by`); `get_task` prints
| Log, node id, session copy (0600) | `~/.local/share/todo-mcp/` |
| Binary | `~/.local/lib/todo-mcp/todo_mcp` |
Reads (`list_tasks`, `search_tasks`, `get_task`) reuse a Firebase sync that finished within
the last 2 s (`TaskService.readFreshness`); every write pulls and pushes. One board fetch
makes about 15 calls, each used to be a 0.5-1 s sync.
## One-time setup
```bash

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
# 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.98+1
version: 1.0.99+1
environment:
sdk: ^3.12.2

View File

@ -19,9 +19,12 @@ import '../cli/fake_rtdb.dart';
class McpHarness {
/// [board] is the fake board `new_note` talks to; none by default.
McpHarness({this.board});
/// [readFreshness] defaults to zero so every read syncs, as a test expects;
/// `task_service_fresh_test.dart` covers the production window.
McpHarness({this.board, this.readFreshness = Duration.zero});
final BoardClient? board;
final Duration readFreshness;
static const token = 'test-token-for-pc';
final Directory tmp = Directory.systemTemp.createTempSync('mcp_harness');
@ -39,7 +42,7 @@ class McpHarness {
httpClient: db.client,
);
server = await TodoMcpServer.start(
tasks: TaskService(session, board: board),
tasks: TaskService(session, board: board, readFreshness: readFreshness),
tokens: tokens,
port: 0,
);

View File

@ -0,0 +1,87 @@
// A read call (list/search/get) used to sync with Firebase every time, so the
// board's one fetch of 15 calls took 12 s and a note added in the app showed
// up 10-40 s later. Reads now reuse a sync that finished within
// `readFreshness`; every write still pulls and pushes.
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/sync/sync_service.dart';
/// Counts [sync] calls; each one answers at once.
class _Counting extends CliSession {
_Counting(NoteRepository repo, FirebaseRestClient firebase)
: super('unused', repo, firebase);
int syncs = 0;
@override
Future<SyncResult> sync({required bool push}) {
syncs++;
return Future.value(const SyncResult(mergedDevices: 0, pushed: false));
}
}
Future<_Counting> _session() async {
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(),
);
return _Counting(await NoteRepository.openInMemory(), firebase);
}
void main() {
const window = Duration(milliseconds: 300);
late _Counting session;
late TaskService tasks;
setUp(() async {
session = await _session();
tasks = TaskService(session, readFreshness: window);
});
test('[T-fresh] reads inside the window share one sync', () async {
await tasks.list({});
await tasks.list({'no_repo': true});
await tasks.search({'query': 'x'});
expect(session.syncs, 1);
});
test('[T-fresh] a read after the window syncs again', () async {
await tasks.list({});
await Future<void>.delayed(window + const Duration(milliseconds: 100));
await tasks.list({});
expect(session.syncs, 2);
});
test(
'[T-fresh] a write always syncs, and counts as fresh for reads',
() async {
await tasks.list({});
await tasks.add({'repo': 'kuhyx/x', 'title': 'a task'});
final afterAdd = session.syncs;
expect(afterAdd, greaterThan(1));
await tasks.list({});
expect(session.syncs, afterAdd);
},
);
test('[T-fresh] a zero window keeps the old sync-every-read', () async {
final strict = TaskService(session, readFreshness: Duration.zero);
await strict.list({});
await strict.list({});
expect(session.syncs, 2);
});
}