things-mcp 0.2.4

Local-first MCP server bridging Claude to Things 3 on macOS — 29 tools for read, search, write, and tag CRUD.
Documentation
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Post-write verification: poll the reader pool until we see the expected
//! change (verified), the predicate proves the row will never exist
//! (NotFound — for updates and status-changes only), or the timeout elapses
//! (Timeout). Bounded `poll_timeout / poll_interval` so a misbehaving Things
//! cannot hang the MCP call.

use std::time::{Duration, Instant};

use rusqlite::Connection;

use crate::core::error::ThingsError;
use crate::core::reader::pool::ReaderPool;
use crate::core::types::{TaskKind, TaskStatus, TodoSummary};

#[derive(Debug, Clone)]
pub enum VerifyPredicate {
    /// A row with this title and creationDate ≥ since_unix should exist.
    /// `kind` selects the row's `type` column: Todo → 0, Project → 1.
    CreateByTitle {
        title: String,
        since_unix: f64,
        kind: TaskKind,
    },
    /// The row at this id should match all populated expected_* fields.
    UpdateById {
        id: String,
        expected_title: Option<String>,
        expected_notes: Option<String>,
    },
    /// The row at this id should have this status.
    StatusChange { id: String, want: TaskStatus },
    /// The row at this id should have its project/area column set to the
    /// expected_list_id. `Some(uuid)` matches when t.project = uuid OR
    /// t.area = uuid. `None` matches when BOTH columns are NULL (the inbox).
    MoveById {
        id: String,
        expected_list_id: Option<String>,
    },
    /// The row at `id` either does or doesn't have the named tag, depending
    /// on `present`. Used by `things_assign_tag` (`present: true`) and
    /// `things_unassign_tag` (`present: false`). Tag matched by title via
    /// the TMTaskTag→TMTag join.
    TagOnTodoById {
        id: String,
        tag: String,
        present: bool,
    },
}

#[derive(Debug)]
pub enum VerifyOutcome {
    Verified { row: TodoSummary, latency_ms: u64 },
    Timeout { latency_ms: u64 },
    /// Only emitted by UpdateById / StatusChange when the row never exists.
    /// Plan 4 wires this through `WriteOutcome { verified: false, id: None }`.
    NotFound { latency_ms: u64 },
}

pub async fn verify(
    pool: &ReaderPool,
    pred: VerifyPredicate,
    timeout: Duration,
    interval: Duration,
) -> Result<VerifyOutcome, ThingsError> {
    let start = Instant::now();

    // For UpdateById / StatusChange the row should already exist in the DB —
    // if it never does, no amount of polling will help, so short-circuit.
    if let VerifyPredicate::UpdateById { id, .. }
        | VerifyPredicate::StatusChange { id, .. }
        | VerifyPredicate::MoveById { id, .. }
        | VerifyPredicate::TagOnTodoById { id, .. } = &pred
    {
        let id_for_probe = id.clone();
        let exists = pool
            .with_conn(move |c| -> rusqlite::Result<bool> {
                c.query_row(
                    "SELECT EXISTS (SELECT 1 FROM TMTask WHERE uuid = ? AND trashed = 0)",
                    rusqlite::params![id_for_probe],
                    |r| r.get::<_, i64>(0).map(|n| n != 0),
                )
            })
            .await?;
        if !exists {
            return Ok(VerifyOutcome::NotFound {
                latency_ms: start.elapsed().as_millis() as u64,
            });
        }
    }

    loop {
        let pred_clone = pred.clone();
        let found = pool
            .with_conn(move |c| check_once(c, &pred_clone))
            .await?;
        if let Some(row) = found {
            return Ok(VerifyOutcome::Verified {
                row,
                latency_ms: start.elapsed().as_millis() as u64,
            });
        }
        if start.elapsed() >= timeout {
            return Ok(VerifyOutcome::Timeout {
                latency_ms: start.elapsed().as_millis() as u64,
            });
        }
        tokio::time::sleep(interval).await;
    }
}

fn check_once(c: &Connection, pred: &VerifyPredicate) -> rusqlite::Result<Option<TodoSummary>> {
    use crate::core::reader::queries::{row_to_summary, SUMMARY_COLS, SUMMARY_COLS_LEN};
    match pred {
        VerifyPredicate::CreateByTitle { title, since_unix, kind } => {
            let type_int: i64 = match kind {
                TaskKind::Todo => 0,
                TaskKind::Project => 1,
                TaskKind::Heading => 2,
            };
            let sql = format!(
                r#"
                SELECT {SUMMARY_COLS}
                FROM TMTask AS t
                WHERE t.trashed = 0
                  AND t.type = ?
                  AND t.title = ?
                  AND t.creationDate >= ?
                ORDER BY t.creationDate DESC
                LIMIT 1
                "#
            );
            let mut stmt = c.prepare_cached(&sql)?;
            let mut rows = stmt.query(rusqlite::params![type_int, title, since_unix])?;
            if let Some(r) = rows.next()? {
                return row_to_summary(r).map(Some);
            }
            Ok(None)
        }
        VerifyPredicate::UpdateById {
            id,
            expected_title,
            expected_notes,
        } => {
            let sql = format!(
                r#"
                SELECT {SUMMARY_COLS}, t.notes
                FROM TMTask AS t
                WHERE t.uuid = ? AND t.trashed = 0
                LIMIT 1
                "#
            );
            let mut stmt = c.prepare_cached(&sql)?;
            let mut rows = stmt.query(rusqlite::params![id])?;
            let Some(r) = rows.next()? else {
                return Ok(None);
            };
            let summary = row_to_summary(r)?;
            let notes: Option<String> = r.get(SUMMARY_COLS_LEN)?;
            if let Some(want) = expected_title.as_ref() {
                if summary.title != *want {
                    return Ok(None);
                }
            }
            if let Some(want) = expected_notes.as_ref() {
                if notes.as_deref() != Some(want.as_str()) {
                    return Ok(None);
                }
            }
            Ok(Some(summary))
        }
        VerifyPredicate::StatusChange { id, want } => {
            let sql = format!(
                r#"
                SELECT {SUMMARY_COLS}
                FROM TMTask AS t
                WHERE t.uuid = ? AND t.trashed = 0
                LIMIT 1
                "#
            );
            let mut stmt = c.prepare_cached(&sql)?;
            let mut rows = stmt.query(rusqlite::params![id])?;
            let Some(r) = rows.next()? else {
                return Ok(None);
            };
            let summary = row_to_summary(r)?;
            if summary.status == *want {
                Ok(Some(summary))
            } else {
                Ok(None)
            }
        }
        VerifyPredicate::MoveById { id, expected_list_id } => {
            let sql = format!(
                r#"
                SELECT {SUMMARY_COLS}
                FROM TMTask AS t
                WHERE t.uuid = ? AND t.trashed = 0
                LIMIT 1
                "#
            );
            let mut stmt = c.prepare_cached(&sql)?;
            let mut rows = stmt.query(rusqlite::params![id])?;
            let Some(r) = rows.next()? else {
                return Ok(None);
            };
            let summary = row_to_summary(r)?;
            let matches = match expected_list_id.as_deref() {
                None => summary.project_id.is_none() && summary.area_id.is_none(),
                Some(want) => {
                    summary.project_id.as_deref() == Some(want)
                        || summary.area_id.as_deref() == Some(want)
                }
            };
            if matches {
                Ok(Some(summary))
            } else {
                Ok(None)
            }
        }
        VerifyPredicate::TagOnTodoById { id, tag, present } => {
            // Tag-presence join: TMTaskTag.tasks = task uuid, TMTaskTag.tags
            // = tag uuid, TMTag.title = tag's user-facing name.
            let has_tag_sql = r#"
                SELECT EXISTS (
                    SELECT 1
                    FROM TMTaskTag AS tt
                    JOIN TMTag      AS g  ON g.uuid = tt.tags
                    WHERE tt.tasks = ? AND g.title = ?
                )
            "#;
            let mut stmt = c.prepare_cached(has_tag_sql)?;
            let has_tag: bool = stmt
                .query_row(rusqlite::params![id, tag], |r| {
                    r.get::<_, i64>(0).map(|n| n != 0)
                })?;
            if has_tag != *present {
                return Ok(None);
            }
            // Emit a summary just like the other arms do.
            let summary_sql = format!(
                r#"
                SELECT {SUMMARY_COLS}
                FROM TMTask AS t
                WHERE t.uuid = ? AND t.trashed = 0
                LIMIT 1
                "#
            );
            let mut summary_stmt = c.prepare_cached(&summary_sql)?;
            let mut rows = summary_stmt.query(rusqlite::params![id])?;
            let Some(r) = rows.next()? else { return Ok(None) };
            row_to_summary(r).map(Some)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::reader::fixture::build_fixture;
    use tempfile::tempdir;

    fn cfg() -> (Duration, Duration) {
        (Duration::from_millis(500), Duration::from_millis(20))
    }

    async fn open_pool() -> (tempfile::TempDir, ReaderPool) {
        let tmp = tempdir().unwrap();
        let path = tmp.path().join("p.sqlite");
        build_fixture(&path).unwrap();
        let pool = ReaderPool::new(path, 2).await.unwrap();
        (tmp, pool)
    }

    #[tokio::test]
    async fn verify_create_by_title_finds_existing_row() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        // The fixture seeds 'Buy milk' with creationDate=1715000000.0.
        let out = verify(
            &pool,
            VerifyPredicate::CreateByTitle {
                title: "Buy milk".into(),
                since_unix: 0.0,
                kind: TaskKind::Todo,
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        match out {
            VerifyOutcome::Verified { row, .. } => assert_eq!(row.title, "Buy milk"),
            other => panic!("expected Verified, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn verify_create_by_title_times_out_when_title_absent() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        let out = verify(
            &pool,
            VerifyPredicate::CreateByTitle {
                title: "Nothing in the fixture matches this".into(),
                since_unix: 0.0,
                kind: TaskKind::Todo,
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        assert!(matches!(out, VerifyOutcome::Timeout { .. }));
    }

    #[tokio::test]
    async fn verify_update_by_id_matches_when_fields_align() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        let out = verify(
            &pool,
            VerifyPredicate::UpdateById {
                id: "todo-1".into(),
                expected_title: Some("Buy milk".into()),
                expected_notes: None,
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        match out {
            VerifyOutcome::Verified { row, .. } => assert_eq!(row.id, "todo-1"),
            other => panic!("expected Verified, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn verify_update_by_id_not_found_short_circuits() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        let start = std::time::Instant::now();
        let out = verify(
            &pool,
            VerifyPredicate::UpdateById {
                id: "does-not-exist".into(),
                expected_title: None,
                expected_notes: None,
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        assert!(matches!(out, VerifyOutcome::NotFound { .. }));
        // Must short-circuit well under the timeout.
        assert!(
            start.elapsed() < Duration::from_millis(200),
            "expected NotFound to short-circuit, took {:?}",
            start.elapsed()
        );
    }

    #[tokio::test]
    async fn verify_status_change_matches_when_status_equals_want() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        // The fixture's 'todo-3 Pay tax bill' has SQLite status=3 → TaskStatus::Completed.
        let out = verify(
            &pool,
            VerifyPredicate::StatusChange {
                id: "todo-3".into(),
                want: TaskStatus::Completed,
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        match out {
            VerifyOutcome::Verified { row, .. } => assert_eq!(row.id, "todo-3"),
            other => panic!("expected Verified, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn verify_move_by_id_matches_when_row_under_expected_list() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        // The fixture's todo-4 lives under project proj-1.
        let out = verify(
            &pool,
            VerifyPredicate::MoveById {
                id: "todo-4".into(),
                expected_list_id: Some("proj-1".into()),
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        match out {
            VerifyOutcome::Verified { row, .. } => {
                assert_eq!(row.id, "todo-4");
                assert_eq!(row.project_id.as_deref(), Some("proj-1"));
            }
            other => panic!("expected Verified, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn verify_move_by_id_inbox_matches_when_both_parent_columns_null() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        // The fixture's todo-1 ('Buy milk') has no project + no area.
        let out = verify(
            &pool,
            VerifyPredicate::MoveById {
                id: "todo-1".into(),
                expected_list_id: None,
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        assert!(matches!(out, VerifyOutcome::Verified { .. }));
    }

    #[tokio::test]
    async fn verify_tag_on_todo_by_id_matches_when_present_true_and_tag_set() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        // Fixture: todo-2 carries the 'Errand' tag.
        let out = verify(
            &pool,
            VerifyPredicate::TagOnTodoById {
                id: "todo-2".into(),
                tag: "Errand".into(),
                present: true,
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        match out {
            VerifyOutcome::Verified { row, .. } => assert_eq!(row.id, "todo-2"),
            other => panic!("expected Verified, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn verify_tag_on_todo_by_id_matches_when_present_false_and_tag_absent() {
        let (_tmp, pool) = open_pool().await;
        let (timeout, interval) = cfg();
        // Fixture: todo-1 ('Buy milk') has no tags.
        let out = verify(
            &pool,
            VerifyPredicate::TagOnTodoById {
                id: "todo-1".into(),
                tag: "Errand".into(),
                present: false,
            },
            timeout,
            interval,
        )
        .await
        .unwrap();
        assert!(matches!(out, VerifyOutcome::Verified { .. }));
    }
}