feat(mcp): task write tools and the agent action journal (#203)
Five write tools, registered for a read-write token only: create_task, update_task, complete_task, reopen_task and set_task_tags. None deletes anything. Each one goes through registerWriteTool, the single envelope of the writes, inside the envelope of every tool (limit mcp-write): one transaction, the write of taskWrites.ts, its journal line in the same transaction when it changed something, then, after the commit, one notification and the answer. A call that changes nothing writes no journal line and notifies nobody. A journal line that cannot be written takes the write back. A task, a list, a parent or a tag of another account answers like one that does not exist. Resolves #203 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
797b6c608c
commit
84a85169a5
3 changed files with 1037 additions and 5 deletions
|
|
@ -9,10 +9,13 @@ import type { PGlite } from 'electric-sql-pglite';
|
|||
// verification, the real pilot, the real rate limiter and the real queries,
|
||||
// against an in-memory Postgres (PGlite) with the companion migrations.
|
||||
// Requests are JSON-RPC messages written by hand, in both generations of the
|
||||
// protocol: no MCP client is installed. Two modules are replaced:
|
||||
// - the database client, by PGlite;
|
||||
// protocol: no MCP client is installed. Three modules are replaced:
|
||||
// - the database client, by PGlite, which also counts the transactions
|
||||
// opened through db.transaction and those still open (#203);
|
||||
// - the Logto session helper (vitest cannot load @logto/next), which gives
|
||||
// the session a test sets and counts how often it is asked.
|
||||
// the session a test sets and counts how often it is asked;
|
||||
// - the WebSocket notice, which is recorded with whether every transaction
|
||||
// had settled when it left (#203).
|
||||
// Every request is sent to the container's host, as in production.
|
||||
|
||||
const h = await vi.hoisted(async () => {
|
||||
|
|
@ -21,13 +24,31 @@ const h = await vi.hoisted(async () => {
|
|||
pg: new PGlite() as PGlite,
|
||||
session: null as { userId: string } | null,
|
||||
sessionReads: 0,
|
||||
// Transactions opened through db.transaction: all of them, and those
|
||||
// that have not settled yet.
|
||||
transactions: 0,
|
||||
openTransactions: 0,
|
||||
// WebSocket notices, in order: the account, and whether the notice left
|
||||
// after the commit.
|
||||
notified: [] as { userId: string; afterCommit: boolean }[],
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('@/db/client', async () => {
|
||||
const { drizzle } = await import('drizzle-orm/pglite');
|
||||
const schema = await import('@/db/schema');
|
||||
return { db: drizzle(h.pg, { schema }) };
|
||||
const db = drizzle(h.pg, { schema });
|
||||
const transaction = db.transaction.bind(db);
|
||||
db.transaction = (async (...args: Parameters<typeof transaction>) => {
|
||||
h.transactions++;
|
||||
h.openTransactions++;
|
||||
try {
|
||||
return await transaction(...args);
|
||||
} finally {
|
||||
h.openTransactions--;
|
||||
}
|
||||
}) as typeof db.transaction;
|
||||
return { db };
|
||||
});
|
||||
|
||||
vi.mock('@/lib/auth', () => ({
|
||||
|
|
@ -37,6 +58,12 @@ vi.mock('@/lib/auth', () => ({
|
|||
},
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/ws', () => ({
|
||||
notifyUserChanged: (userId: string) => {
|
||||
h.notified.push({ userId, afterCommit: h.openTransactions === 0 });
|
||||
},
|
||||
}));
|
||||
|
||||
const route = await import('./route');
|
||||
const { POST } = route;
|
||||
const { createAgentToken, revokeAgentToken } = await import('@/lib/agentTokens');
|
||||
|
|
@ -44,6 +71,9 @@ const { rateLimit, rateLimitDelay } = await import('@/lib/rateLimit');
|
|||
const { loadAccountTags } = await import('@/lib/taskQueries');
|
||||
const { TOOL_ERROR_MESSAGES, errorName } = await import('@/lib/mcp/errors');
|
||||
const { instructionsFor, mcpHandler } = await import('@/lib/mcp/server');
|
||||
const { WRITE_TOOL_NAMES } = await import('@/lib/mcp/writeTools');
|
||||
const { listActions } = await import('@/lib/agentJournal');
|
||||
const { db } = await import('@/db/client');
|
||||
|
||||
const SITE = 'https://liste.lacompagniemaximus.com';
|
||||
// Origin of `request.url` in production: the container's, not the site's.
|
||||
|
|
@ -56,7 +86,13 @@ const ENVELOPE = {
|
|||
};
|
||||
const ERAS = ['modern', 'legacy'] as const;
|
||||
const READ_TOOLS = ['get_task', 'list_lists', 'list_tags', 'list_tasks'];
|
||||
const WRITE_TOOLS = ['complete_task', 'create_task', 'reopen_task', 'set_task_tags', 'update_task'];
|
||||
const READ_ONLY = { readOnlyHint: true, openWorldHint: false };
|
||||
// Keys of a top-level task as a tool returns it, in order.
|
||||
const TASK_KEYS = [
|
||||
'id', 'title', 'notes', 'completed', 'completed_at', 'priority', 'due_date', 'recurrence',
|
||||
'list_id', 'parent_id', 'created_at', 'updated_at', 'tags', 'subtasks',
|
||||
];
|
||||
const UNAUTHORIZED = { status: 401, message: { error: 'unauthorized' } };
|
||||
const FORBIDDEN = { status: 403, message: { error: 'forbidden' } };
|
||||
const GONE = '2026-02-01T00:00:00.000Z';
|
||||
|
|
@ -227,6 +263,61 @@ async function connected(scope: 'read' | 'write' = 'read'): Promise<Account & To
|
|||
return { ...account, ...(await newToken(account, { scope })) };
|
||||
}
|
||||
|
||||
// An account that never synced a device: a read-write token, and no list.
|
||||
async function bare(): Promise<Account & Token> {
|
||||
const account = { userId: `user-${u()}`, inbox: '' };
|
||||
seen.users.push(account.userId);
|
||||
return { ...account, ...(await newToken(account, { scope: 'write' })) };
|
||||
}
|
||||
|
||||
// Columns of sl_tasks the write tests read, as PGlite returns a row.
|
||||
type StoredTask = {
|
||||
id: string; user_id: string; title: string; list_id: string; parent_id: string | null; position: number;
|
||||
completed: boolean; updated_at: Date; deleted_at: Date | null;
|
||||
};
|
||||
|
||||
async function stored(id: string): Promise<StoredTask> {
|
||||
return (await h.pg.query<StoredTask>('SELECT * FROM sl_tasks WHERE id = $1', [id])).rows[0];
|
||||
}
|
||||
|
||||
type JournalLine = { tool: string; entity_type: string; entity_id: string; token_id: string | null; token_name: string };
|
||||
|
||||
// The journal lines of an account, oldest first.
|
||||
async function journal(userId: string): Promise<JournalLine[]> {
|
||||
return (await h.pg.query<JournalLine>(
|
||||
'SELECT tool, entity_type, entity_id, token_id, token_name FROM sl_agent_actions WHERE user_id = $1 ORDER BY created_at, id',
|
||||
[userId],
|
||||
)).rows;
|
||||
}
|
||||
|
||||
// The journal line a write tool leaves for a task, written with this token.
|
||||
function lineOf(tool: string, taskId: string, token: Token): JournalLine {
|
||||
return { tool, entity_type: 'task', entity_id: taskId, token_id: token.id, token_name: 'Assistant' };
|
||||
}
|
||||
|
||||
// The WebSocket notices sent to an account, in order: true for a notice that
|
||||
// left after the commit, false for one sent while a transaction was open.
|
||||
function notices(userId: string): boolean[] {
|
||||
return h.notified.filter((notice) => notice.userId === userId).map((notice) => notice.afterCommit);
|
||||
}
|
||||
|
||||
// Every row of the accounts, every column: lists, tasks, tags, links and
|
||||
// journal lines. What a refused write must leave exactly as it was.
|
||||
async function state(...accounts: Account[]) {
|
||||
const users = accounts.map((account) => account.userId);
|
||||
const marks = users.map((_, i) => `$${i + 1}`).join(', ');
|
||||
const read = async (sql: string) => (await h.pg.query(sql, users)).rows;
|
||||
return {
|
||||
lists: await read(`SELECT * FROM sl_lists WHERE user_id IN (${marks}) ORDER BY id`),
|
||||
tasks: await read(`SELECT * FROM sl_tasks WHERE user_id IN (${marks}) ORDER BY id`),
|
||||
tags: await read(`SELECT * FROM sl_tags WHERE user_id IN (${marks}) ORDER BY id`),
|
||||
links: await read(
|
||||
`SELECT tt.* FROM sl_task_tags tt JOIN sl_tasks t ON t.id = tt.task_id WHERE t.user_id IN (${marks}) ORDER BY tt.task_id, tt.tag_id`,
|
||||
),
|
||||
journal: await read(`SELECT * FROM sl_agent_actions WHERE user_id IN (${marks}) ORDER BY id`),
|
||||
};
|
||||
}
|
||||
|
||||
async function answer(res: Response): Promise<Answer> {
|
||||
const text = await res.text();
|
||||
let messages: Json[] = [];
|
||||
|
|
@ -438,6 +529,7 @@ beforeEach(() => {
|
|||
pilot('*');
|
||||
h.session = null;
|
||||
h.sessionReads = 0;
|
||||
h.notified = [];
|
||||
seen.users = [];
|
||||
seen.tokens = [];
|
||||
seen.content = [];
|
||||
|
|
@ -803,6 +895,698 @@ describe('the tools of a token', () => {
|
|||
const a = await connected('write');
|
||||
expect((await listTools(a.token)).map((tool) => tool.name)).toEqual(expect.arrayContaining(READ_TOOLS));
|
||||
});
|
||||
|
||||
it('a read-write token sees the five write tools as well, the same in both generations', async () => {
|
||||
const a = await connected('write');
|
||||
const [modern, legacy] = [await listTools(a.token), await listTools(a.token, { era: 'legacy' })];
|
||||
expect(legacy).toEqual(modern);
|
||||
expect(modern.map((tool) => tool.name).sort()).toEqual([...READ_TOOLS, ...WRITE_TOOLS].sort());
|
||||
// The names the journal holds are the names of the write tools, all of them.
|
||||
expect([...WRITE_TOOL_NAMES].sort()).toEqual(WRITE_TOOLS);
|
||||
|
||||
const byName = Object.fromEntries(modern.map((tool) => [tool.name, tool]));
|
||||
// Additive, or overwriting a value; calling again with the same arguments changes nothing more.
|
||||
expect(byName.create_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, openWorldHint: false });
|
||||
expect(byName.update_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false });
|
||||
expect(byName.complete_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false });
|
||||
expect(byName.reopen_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false });
|
||||
expect(byName.set_task_tags.annotations).toEqual({ readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false });
|
||||
for (const name of READ_TOOLS) expect(byName[name].annotations).toEqual(READ_ONLY);
|
||||
|
||||
const inputs = Object.fromEntries(WRITE_TOOLS.map((name) => [name, byName[name].inputSchema as { properties: Json; required?: string[] }]));
|
||||
for (const name of WRITE_TOOLS) {
|
||||
expect(byName[name].description.length).toBeGreaterThan(20);
|
||||
// Strict input: an unknown key is refused.
|
||||
expect(inputs[name]).toMatchObject({ type: 'object', additionalProperties: false });
|
||||
expect(byName[name]).not.toHaveProperty('outputSchema');
|
||||
}
|
||||
expect(Object.keys(inputs.create_task.properties).sort()).toEqual(
|
||||
['due_date', 'list_id', 'notes', 'parent_id', 'priority', 'recurrence', 'tag_ids', 'title'],
|
||||
);
|
||||
expect(inputs.create_task.required).toEqual(['title']);
|
||||
expect(inputs.create_task.properties).toMatchObject({
|
||||
title: { type: 'string', minLength: 1, maxLength: 500 },
|
||||
notes: { type: 'string', maxLength: 5000 },
|
||||
priority: { type: 'integer', minimum: 0, maximum: 3 },
|
||||
recurrence: { enum: ['daily', 'weekly', 'monthly', 'yearly'] },
|
||||
tag_ids: { type: 'array', maxItems: 20 },
|
||||
});
|
||||
expect(Object.keys(inputs.update_task.properties).sort()).toEqual(
|
||||
['due_date', 'list_id', 'notes', 'priority', 'recurrence', 'task_id', 'title'],
|
||||
);
|
||||
expect(inputs.update_task.required).toEqual(['task_id']);
|
||||
for (const name of ['complete_task', 'reopen_task']) {
|
||||
expect(Object.keys(inputs[name].properties)).toEqual(['task_id']);
|
||||
expect(inputs[name].required).toEqual(['task_id']);
|
||||
}
|
||||
expect(Object.keys(inputs.set_task_tags.properties).sort()).toEqual(['tag_ids', 'task_id']);
|
||||
expect(inputs.set_task_tags.required?.sort()).toEqual(['tag_ids', 'task_id']);
|
||||
expect(inputs.set_task_tags.properties).toMatchObject({ tag_ids: { type: 'array', maxItems: 20 } });
|
||||
// No tool takes an account, and none deletes.
|
||||
const text = JSON.stringify(modern);
|
||||
expect(text).not.toMatch(/user_id|userId/);
|
||||
expect(modern.map((tool) => tool.name).filter((name) => /delete|remove/.test(name))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// A tool call sent straight to the handler, with the context the route would
|
||||
// have written for a token: what a request looks like once it is
|
||||
// authenticated, whatever became of its token since.
|
||||
async function handled(
|
||||
extra: { userId: string; scope: 'read' | 'write'; tokenId: string | null; tokenName: string },
|
||||
name: string,
|
||||
args: Json,
|
||||
): Promise<{ isError: boolean; data: Json }> {
|
||||
const request = new Request(`${CONTAINER}/api/mcp`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'mcp-protocol-version': MODERN, 'mcp-method': 'tools/call', 'mcp-name': name },
|
||||
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args, _meta: ENVELOPE } }),
|
||||
});
|
||||
const served = await answer(await mcpHandler.fetch(request, {
|
||||
authInfo: { token: '', clientId: extra.tokenId ?? '', scopes: [extra.scope], extra },
|
||||
}));
|
||||
const result = resultOf(served) as { content: { text: string }[]; isError?: boolean };
|
||||
return { isError: result.isError === true, data: JSON.parse(result.content[0].text) as Json };
|
||||
}
|
||||
|
||||
describe('create_task', () => {
|
||||
it.each(ERAS)('creates a task at the end of the Inbox, returns it, journals it and notifies once, after the commit (%s)', async (era) => {
|
||||
const a = await connected('write');
|
||||
await newTask(a, { position: 3 });
|
||||
const title = words('title');
|
||||
|
||||
const created = await ok(a.token, 'create_task', { title }, { era });
|
||||
expect(Object.keys(created)).toEqual(['task']);
|
||||
const task = created.task as ShapedTask;
|
||||
expect(Object.keys(task)).toEqual(TASK_KEYS);
|
||||
expect(task).toMatchObject({
|
||||
title, notes: null, completed: false, completed_at: null, priority: 0, due_date: null, recurrence: null,
|
||||
list_id: a.inbox, parent_id: null, tags: [], subtasks: [],
|
||||
});
|
||||
expect(task.created_at).toBe(task.updated_at);
|
||||
expect(await stored(task.id)).toMatchObject({ user_id: a.userId, title, list_id: a.inbox, parent_id: null, position: 4, deleted_at: null });
|
||||
|
||||
expect(await journal(a.userId)).toEqual([lineOf('create_task', task.id, a)]);
|
||||
expect(notices(a.userId)).toEqual([true]);
|
||||
expect(logLines('mcp-tool')).toEqual([{ at: 'mcp-tool', tool: 'create_task', outcome: 'ok', ms: expect.any(Number), token: a.id }]);
|
||||
// The read tools return the same task.
|
||||
expect((await ok(a.token, 'get_task', { task_id: task.id }, { era })).task).toEqual(task);
|
||||
});
|
||||
|
||||
it('stores every argument: notes, a priority, a due date at noon UTC, a recurrence and tags', async () => {
|
||||
const a = await connected('write');
|
||||
const list = await newList(a);
|
||||
const [red, blue] = [await newTag(a, { name: words('a-red') }), await newTag(a, { name: words('b-blue') })];
|
||||
const [title, notes] = [words('title'), words('notes')];
|
||||
|
||||
const { task } = await ok(a.token, 'create_task', {
|
||||
title, list_id: list, notes, priority: 3, due_date: '2026-12-24', recurrence: 'yearly', tag_ids: [blue, red],
|
||||
}) as { task: ShapedTask };
|
||||
expect(task).toMatchObject({
|
||||
title, notes, priority: 3, due_date: '2026-12-24T12:00:00.000Z', recurrence: 'yearly', list_id: list, parent_id: null,
|
||||
tags: [{ id: red }, { id: blue }], subtasks: [],
|
||||
});
|
||||
// A date-time is kept as it is: an evening in Quebec (UTC-5), the next day in UTC.
|
||||
const evening = (await ok(a.token, 'create_task', { title: words('title'), due_date: '2026-12-24T19:30:00-05:00' })).task as ShapedTask;
|
||||
expect(evening.due_date).toBe('2026-12-25T00:30:00.000Z');
|
||||
expect(await taskIds(a.token, { tag_ids: [red] })).toEqual([task.id]);
|
||||
});
|
||||
|
||||
it('gives an account without a list its Inbox, and only one after two creations', async () => {
|
||||
const a = await bare();
|
||||
const first = (await ok(a.token, 'create_task', { title: words('title') })).task as ShapedTask;
|
||||
const second = (await ok(a.token, 'create_task', { title: words('title') })).task as ShapedTask;
|
||||
expect(second.list_id).toBe(first.list_id);
|
||||
expect((await ok(a.token, 'list_lists')).lists).toEqual([
|
||||
{ id: first.list_id, name: 'Inbox', color: null, icon: null, is_inbox: true, open_task_count: 2 },
|
||||
]);
|
||||
// Two lines, for the two tasks: the Inbox has none.
|
||||
expect((await journal(a.userId)).map((line) => `${line.tool} ${line.entity_type} ${line.entity_id}`).sort())
|
||||
.toEqual([first.id, second.id].map((id) => `create_task task ${id}`).sort());
|
||||
expect(notices(a.userId)).toEqual([true, true]);
|
||||
});
|
||||
|
||||
it('creates a subtask in the list of its parent, at the end of its subtasks, and ignores list_id', async () => {
|
||||
const [a, b] = [await connected('write'), await connected()];
|
||||
const list = await newList(a);
|
||||
const parent = await newTask(a, { list });
|
||||
const sibling = await newTask(a, { parentId: parent, list, position: 2 });
|
||||
|
||||
// Whatever list_id names: another list of the account, a list of another account, no list.
|
||||
const created: string[] = [];
|
||||
for (const [index, list_id] of [a.inbox, b.inbox, u(), undefined].entries()) {
|
||||
const args = { title: words('title'), parent_id: parent, ...(list_id === undefined ? {} : { list_id }) };
|
||||
const task = (await ok(a.token, 'create_task', args, { era: ERAS[index % 2] })).task as ShapedTask;
|
||||
expect(task).toMatchObject({ parent_id: parent, list_id: list, tags: [] });
|
||||
expect(task).not.toHaveProperty('subtasks');
|
||||
expect(await stored(task.id)).toMatchObject({ user_id: a.userId, list_id: list, parent_id: parent, position: 3 + index });
|
||||
created.push(task.id);
|
||||
}
|
||||
const read = (await ok(a.token, 'get_task', { task_id: parent })).task as ShapedTask;
|
||||
expect(read.subtasks?.map((subtask) => subtask.id)).toEqual([sibling, ...created]);
|
||||
expect((await journal(a.userId)).map((line) => line.entity_id).sort()).toEqual([...created].sort());
|
||||
});
|
||||
|
||||
it.each(ERAS)('refuses a list, a parent or a tag that is unknown, deleted or of another account, and writes nothing (%s)', async (era) => {
|
||||
const [a, b] = [await connected('write'), await connected('write')];
|
||||
const top = await newTask(a);
|
||||
const subtask = await newTask(a, { parentId: top });
|
||||
const own = await newTag(a);
|
||||
const cases: [Json, keyof typeof TOOL_ERROR_MESSAGES][] = [
|
||||
[{ list_id: u() }, 'list_not_found'],
|
||||
[{ list_id: await newList(a, { deletedAt: GONE }) }, 'list_not_found'],
|
||||
[{ list_id: b.inbox }, 'list_not_found'],
|
||||
[{ parent_id: u() }, 'parent_not_found'],
|
||||
[{ parent_id: await newTask(a, { deletedAt: GONE }) }, 'parent_not_found'],
|
||||
[{ parent_id: await newTask(b) }, 'parent_not_found'],
|
||||
[{ parent_id: subtask }, 'parent_is_subtask'],
|
||||
[{ tag_ids: [own, u()] }, 'tag_not_found'],
|
||||
[{ tag_ids: [await newTag(a, { deletedAt: GONE })] }, 'tag_not_found'],
|
||||
[{ tag_ids: [own, await newTag(b)] }, 'tag_not_found'],
|
||||
[{ parent_id: top, tag_ids: [await newTag(b)] }, 'tag_not_found'],
|
||||
];
|
||||
const before = await state(a, b);
|
||||
for (const [args, code] of cases) {
|
||||
// The code and its fixed message, nothing else: a row of another
|
||||
// account reads like a row that does not exist.
|
||||
expect(await refused(a.token, 'create_task', { title: words('title'), ...args }, code, { era }))
|
||||
.toStrictEqual({ error: code, message: TOOL_ERROR_MESSAGES[code] });
|
||||
}
|
||||
expect(await state(a, b)).toEqual(before);
|
||||
expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]);
|
||||
expect(logLines('mcp-tool').map((line) => line.outcome)).toEqual(cases.map(([, code]) => code));
|
||||
|
||||
// An account without a list: the Inbox created for the refused task is not kept.
|
||||
const c = await bare();
|
||||
await refused(c.token, 'create_task', { title: words('title'), tag_ids: [own] }, 'tag_not_found', { era });
|
||||
expect((await ok(c.token, 'list_lists', {}, { era })).lists).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['no title', {}, 'title'],
|
||||
['an empty title', { title: '' }, 'title'],
|
||||
['a title of 501 characters', { title: 'x'.repeat(501) }, 'title'],
|
||||
['notes of 5001 characters', { title: 'x', notes: 'x'.repeat(5001) }, 'notes'],
|
||||
['null notes', { title: 'x', notes: null }, 'notes'],
|
||||
['a priority of 4', { title: 'x', priority: 4 }, 'priority'],
|
||||
['a recurrence the app does not know', { title: 'x', recurrence: 'hourly' }, 'recurrence'],
|
||||
['21 tags', { title: 'x', tag_ids: Array.from({ length: 21 }, () => u()) }, 'tag_ids'],
|
||||
['a tag id that is not a uuid', { title: 'x', tag_ids: ['red'] }, 'tag_ids'],
|
||||
['a list id that is not a uuid', { title: 'x', list_id: 'inbox' }, 'list_id'],
|
||||
['a parent id that is not a uuid', { title: 'x', parent_id: 'first' }, 'parent_id'],
|
||||
['a date-time without an offset', { title: 'x', due_date: '2026-06-01T10:00:00' }, 'Invalid due date'],
|
||||
['a date that does not exist', { title: 'x', due_date: '2026-02-30' }, 'Invalid due date'],
|
||||
['an account', { title: 'x', user_id: 'someone-else' }, 'user_id'],
|
||||
['a completed flag', { title: 'x', completed: true }, 'completed'],
|
||||
['a position', { title: 'x', position: 0 }, 'position'],
|
||||
])('refuses %s before the tool runs', async (_label, args, named) => {
|
||||
const a = await connected('write');
|
||||
const before = await state(a);
|
||||
for (const era of ERAS) expect(await invalid(a.token, 'create_task', args, { era })).toContain(named);
|
||||
expect(await state(a)).toEqual(before);
|
||||
expect(notices(a.userId)).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts a title of 500 characters, notes of 5000 and 20 tags', async () => {
|
||||
const a = await connected('write');
|
||||
const tags: string[] = [];
|
||||
for (let i = 0; i < 20; i++) tags.push(await newTag(a));
|
||||
const task = (await ok(a.token, 'create_task', { title: 'x'.repeat(500), notes: 'y'.repeat(5000), tag_ids: tags })).task as ShapedTask;
|
||||
expect(task.title).toHaveLength(500);
|
||||
expect(task.notes).toHaveLength(5000);
|
||||
expect(task.tags.map((tag) => tag.id).sort()).toEqual([...tags].sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe('update_task', () => {
|
||||
it.each(ERAS)('changes the fields it receives, clears with null, and every call is a write (%s)', async (era) => {
|
||||
const a = await connected('write');
|
||||
const notes = words('notes');
|
||||
const id = await newTask(a, { notes, priority: 1, dueDate: '2026-06-01T12:00:00Z', recurrence: 'daily' });
|
||||
const title = words('title');
|
||||
|
||||
const renamed = await ok(a.token, 'update_task', { task_id: id, title, priority: 3 }, { era });
|
||||
expect(Object.keys(renamed)).toEqual(['task']);
|
||||
expect(Object.keys(renamed.task as ShapedTask)).toEqual(TASK_KEYS);
|
||||
expect(renamed.task).toMatchObject({ id, title, priority: 3, notes, due_date: '2026-06-01T12:00:00.000Z', recurrence: 'daily', completed: false });
|
||||
|
||||
const cleared = await ok(a.token, 'update_task', { task_id: id, notes: null, due_date: null, recurrence: null }, { era });
|
||||
expect(cleared.task).toMatchObject({ id, title, priority: 3, notes: null, due_date: null, recurrence: null });
|
||||
|
||||
const dated = await ok(a.token, 'update_task', { task_id: id, due_date: '2026-07-01', recurrence: 'monthly' }, { era });
|
||||
expect(dated.task).toMatchObject({ id, due_date: '2026-07-01T12:00:00.000Z', recurrence: 'monthly', notes: null });
|
||||
|
||||
// The value the task already has: a write all the same.
|
||||
const same = await ok(a.token, 'update_task', { task_id: id, title }, { era });
|
||||
expect(same.task).toMatchObject({ id, title, due_date: '2026-07-01T12:00:00.000Z' });
|
||||
expect(new Date((same.task as ShapedTask).updated_at).getTime())
|
||||
.toBeGreaterThan(new Date((same.task as ShapedTask).created_at).getTime());
|
||||
|
||||
expect(await journal(a.userId)).toEqual(Array(4).fill(lineOf('update_task', id, a)));
|
||||
expect(notices(a.userId)).toEqual([true, true, true, true]);
|
||||
});
|
||||
|
||||
it('moves a task to the end of another list, with its live subtasks', async () => {
|
||||
const a = await connected('write');
|
||||
const target = await newList(a);
|
||||
const other = await newTask(a, { list: target, position: 4 });
|
||||
const id = await newTask(a, { position: 1 });
|
||||
const [first, second] = [await newTask(a, { parentId: id, position: 1 }), await newTask(a, { parentId: id, position: 2 })];
|
||||
const deleted = await newTask(a, { parentId: id, position: 3, deletedAt: GONE });
|
||||
|
||||
const { task } = await ok(a.token, 'update_task', { task_id: id, list_id: target }) as { task: ShapedTask };
|
||||
expect(task).toMatchObject({ id, list_id: target, parent_id: null });
|
||||
expect(task.subtasks?.map((subtask) => [subtask.id, subtask.list_id])).toEqual([[first, target], [second, target]]);
|
||||
expect(await stored(id)).toMatchObject({ list_id: target, position: 5 });
|
||||
expect(await stored(deleted)).toMatchObject({ list_id: a.inbox, deleted_at: new Date(GONE) });
|
||||
expect(await taskIds(a.token, { list_id: a.inbox })).toEqual([]);
|
||||
expect(await taskIds(a.token, { list_id: target })).toEqual([other, id]);
|
||||
// One line, for the task: its subtasks have none.
|
||||
expect(await journal(a.userId)).toEqual([lineOf('update_task', id, a)]);
|
||||
expect(notices(a.userId)).toEqual([true]);
|
||||
});
|
||||
|
||||
it.each(ERAS)('refuses to move a subtask, and a list that is unknown, deleted or of another account (%s)', async (era) => {
|
||||
const [a, b] = [await connected('write'), await connected('write')];
|
||||
const id = await newTask(a);
|
||||
const sub = await newTask(a, { parentId: id });
|
||||
const target = await newList(a);
|
||||
const lists = [u(), await newList(a, { deletedAt: GONE }), b.inbox];
|
||||
const before = await state(a, b);
|
||||
|
||||
for (const list_id of lists) {
|
||||
// Nothing of the call is written, its other fields included.
|
||||
expect(await refused(a.token, 'update_task', { task_id: id, list_id, title: words('title') }, 'list_not_found', { era }))
|
||||
.toStrictEqual({ error: 'list_not_found', message: 'No list with this id exists in this account.' });
|
||||
}
|
||||
for (const list_id of [target, a.inbox]) {
|
||||
expect(await refused(a.token, 'update_task', { task_id: sub, list_id, title: words('title') }, 'subtask_not_movable', { era }))
|
||||
.toStrictEqual({ error: 'subtask_not_movable', message: 'A subtask stays in the list of its parent task: it cannot be moved to another list.' });
|
||||
}
|
||||
expect(await state(a, b)).toEqual(before);
|
||||
expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]);
|
||||
// The other fields of a subtask can be written.
|
||||
expect((await ok(a.token, 'update_task', { task_id: sub, priority: 2 }, { era })).task).toMatchObject({ id: sub, priority: 2, parent_id: id });
|
||||
});
|
||||
|
||||
it('refuses a call without a field to change, and a field it does not take, before the tool runs', async () => {
|
||||
const a = await connected('write');
|
||||
const id = await newTask(a);
|
||||
const before = await state(a);
|
||||
for (const era of ERAS) {
|
||||
expect(await invalid(a.token, 'update_task', { task_id: id }, { era }))
|
||||
.toContain('Nothing to change: pass at least one of title, notes, priority, due_date, recurrence, list_id.');
|
||||
}
|
||||
const cases: [Json, string][] = [
|
||||
[{ title: 'x' }, 'task_id'],
|
||||
[{ task_id: 'first', title: 'x' }, 'task_id'],
|
||||
[{ task_id: id, title: '' }, 'title'],
|
||||
[{ task_id: id, title: null }, 'title'],
|
||||
[{ task_id: id, priority: null }, 'priority'],
|
||||
[{ task_id: id, list_id: null }, 'list_id'],
|
||||
[{ task_id: id, notes: 'x'.repeat(5001) }, 'notes'],
|
||||
[{ task_id: id, due_date: 'tomorrow' }, 'Invalid due date'],
|
||||
[{ task_id: id, recurrence: 'hourly' }, 'recurrence'],
|
||||
// What the REST route takes and the tool does not.
|
||||
[{ task_id: id, completed: true }, 'completed'],
|
||||
[{ task_id: id, parent_id: u() }, 'parent_id'],
|
||||
[{ task_id: id, position: 0 }, 'position'],
|
||||
[{ task_id: id, title: 'x', user_id: 'someone-else' }, 'user_id'],
|
||||
];
|
||||
for (const [args, named] of cases) expect(await invalid(a.token, 'update_task', args), JSON.stringify(args)).toContain(named);
|
||||
expect(await state(a)).toEqual(before);
|
||||
expect(notices(a.userId)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('complete_task and reopen_task', () => {
|
||||
it.each(ERAS)('complete a recurring task once, with one next occurrence, and reopen it (%s)', async (era) => {
|
||||
const a = await connected('write');
|
||||
const title = words('title');
|
||||
const id = await newTask(a, { title, notes: words('notes'), dueDate: '2026-06-01T12:00:00Z', recurrence: 'weekly', priority: 2 });
|
||||
await tagTask(id, await newTag(a));
|
||||
|
||||
const done = await ok(a.token, 'complete_task', { task_id: id }, { era });
|
||||
expect(Object.keys(done)).toEqual(['task', 'next_occurrence', 'changed']);
|
||||
expect(done).toMatchObject({ changed: true, task: { id, completed: true, due_date: '2026-06-01T12:00:00.000Z' } });
|
||||
const completedAt = (done.task as ShapedTask).completed_at;
|
||||
expect(completedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
|
||||
// The next occurrence: a week later, same title, priority and list, without the tags.
|
||||
const next = done.next_occurrence as ShapedTask;
|
||||
expect(Object.keys(next)).toEqual(TASK_KEYS);
|
||||
expect(next).toMatchObject({
|
||||
title, completed: false, completed_at: null, priority: 2, due_date: '2026-06-08T12:00:00.000Z', recurrence: 'weekly',
|
||||
list_id: a.inbox, parent_id: null, tags: [], subtasks: [],
|
||||
});
|
||||
expect(next.id).not.toBe(id);
|
||||
|
||||
// Replayed: nothing happens, and there is still one occurrence.
|
||||
const replayed = await ok(a.token, 'complete_task', { task_id: id }, { era });
|
||||
expect(replayed).toMatchObject({ changed: false, next_occurrence: null, task: { id, completed: true, completed_at: completedAt } });
|
||||
expect(await taskIds(a.token, { status: 'all' })).toEqual([id, next.id]);
|
||||
// One line, for the task that was completed, and one notice.
|
||||
expect(await journal(a.userId)).toEqual([lineOf('complete_task', id, a)]);
|
||||
expect(notices(a.userId)).toEqual([true]);
|
||||
|
||||
const reopened = await ok(a.token, 'reopen_task', { task_id: id }, { era });
|
||||
expect(Object.keys(reopened)).toEqual(['task', 'changed']);
|
||||
expect(reopened).toMatchObject({ changed: true, task: { id, completed: false, completed_at: null } });
|
||||
// An open task: nothing happens. The occurrence stays.
|
||||
expect(await ok(a.token, 'reopen_task', { task_id: id }, { era })).toMatchObject({ changed: false, task: { id, completed: false } });
|
||||
expect(await ok(a.token, 'reopen_task', { task_id: next.id }, { era })).toMatchObject({ changed: false, task: { id: next.id } });
|
||||
expect(await taskIds(a.token, { status: 'all' })).toEqual([id, next.id]);
|
||||
|
||||
expect((await journal(a.userId)).map((line) => `${line.tool} ${line.entity_id}`).sort())
|
||||
.toEqual([`complete_task ${id}`, `reopen_task ${id}`]);
|
||||
expect(notices(a.userId)).toEqual([true, true]);
|
||||
// A call that changes nothing is still a call that succeeded.
|
||||
expect(logLines('mcp-tool').filter((line) => line.tool !== 'list_tasks').map((line) => `${line.tool} ${line.outcome}`)).toEqual([
|
||||
'complete_task ok', 'complete_task ok', 'reopen_task ok', 'reopen_task ok', 'reopen_task ok',
|
||||
]);
|
||||
});
|
||||
|
||||
it('complete a task without a recurrence or without a due date: no next occurrence', async () => {
|
||||
const a = await connected('write');
|
||||
const [plain, undated] = [await newTask(a), await newTask(a, { recurrence: 'daily' })];
|
||||
for (const id of [plain, undated]) {
|
||||
expect(await ok(a.token, 'complete_task', { task_id: id })).toMatchObject({ changed: true, next_occurrence: null, task: { id, completed: true } });
|
||||
}
|
||||
// A subtask is completed like a task, and comes back with its parent_id.
|
||||
const child = await newTask(a, { parentId: plain });
|
||||
const done = await ok(a.token, 'complete_task', { task_id: child });
|
||||
expect(done).toMatchObject({ changed: true, next_occurrence: null, task: { id: child, parent_id: plain, completed: true } });
|
||||
expect(done.task).not.toHaveProperty('subtasks');
|
||||
expect(await taskIds(a.token, { status: 'all' })).toEqual([plain, undated]);
|
||||
expect((await journal(a.userId)).map((line) => line.entity_id).sort()).toEqual([plain, undated, child].sort());
|
||||
});
|
||||
|
||||
it.each([
|
||||
['no id', {}],
|
||||
['an id that is not a uuid', { task_id: 'first' }],
|
||||
['an unknown key', { task_id: u(), user_id: 'someone-else' }],
|
||||
])('refuse %s before the tool runs', async (_label, args) => {
|
||||
const a = await connected('write');
|
||||
for (const name of ['complete_task', 'reopen_task']) await invalid(a.token, name, args);
|
||||
expect(notices(a.userId)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('set_task_tags', () => {
|
||||
it.each(ERAS)('replaces the tags of a task, and changes nothing for the set it already has (%s)', async (era) => {
|
||||
const a = await connected('write');
|
||||
const [red, blue, green] = [
|
||||
await newTag(a, { name: words('a-red') }), await newTag(a, { name: words('b-blue') }), await newTag(a, { name: words('c-green') }),
|
||||
];
|
||||
const id = await newTask(a);
|
||||
const sub = await newTask(a, { parentId: id });
|
||||
await tagTask(id, red);
|
||||
const tagsOf = (result: Json) => (result.task as ShapedTask).tags.map((tag) => tag.id);
|
||||
|
||||
const set = await ok(a.token, 'set_task_tags', { task_id: id, tag_ids: [green, blue] }, { era });
|
||||
expect(Object.keys(set)).toEqual(['task', 'changed']);
|
||||
expect(Object.keys(set.task as ShapedTask)).toEqual(TASK_KEYS);
|
||||
expect(set).toMatchObject({ changed: true, task: { id } });
|
||||
expect(tagsOf(set)).toEqual([blue, green]);
|
||||
|
||||
// The same set in another order, and twice the same id.
|
||||
const same = await ok(a.token, 'set_task_tags', { task_id: id, tag_ids: [blue, green, blue] }, { era });
|
||||
expect(same).toMatchObject({ changed: false, task: { id, updated_at: (set.task as ShapedTask).updated_at } });
|
||||
expect(tagsOf(same)).toEqual([blue, green]);
|
||||
|
||||
// A subtask has tags of its own.
|
||||
const onSub = await ok(a.token, 'set_task_tags', { task_id: sub, tag_ids: [red] }, { era });
|
||||
expect(onSub).toMatchObject({ changed: true, task: { id: sub, parent_id: id } });
|
||||
expect(tagsOf(onSub)).toEqual([red]);
|
||||
|
||||
// An empty list takes every tag off; a second time, there is nothing to take off.
|
||||
const emptied = await ok(a.token, 'set_task_tags', { task_id: id, tag_ids: [] }, { era });
|
||||
expect(emptied).toMatchObject({ changed: true });
|
||||
expect(tagsOf(emptied)).toEqual([]);
|
||||
expect(await ok(a.token, 'set_task_tags', { task_id: id, tag_ids: [] }, { era })).toMatchObject({ changed: false });
|
||||
|
||||
// Three writes out of five calls: three lines, three notices.
|
||||
expect((await journal(a.userId)).map((line) => `${line.tool} ${line.entity_id}`).sort())
|
||||
.toEqual([`set_task_tags ${id}`, `set_task_tags ${id}`, `set_task_tags ${sub}`].sort());
|
||||
expect(notices(a.userId)).toEqual([true, true, true]);
|
||||
// The tags themselves are still there.
|
||||
expect(((await ok(a.token, 'list_tags', {}, { era })).tags as ShapedTag[]).map((tag) => tag.id)).toEqual([red, blue, green]);
|
||||
});
|
||||
|
||||
it.each(ERAS)('refuses a tag that is unknown, deleted or of another account, and writes nothing (%s)', async (era) => {
|
||||
const [a, b] = [await connected('write'), await connected('write')];
|
||||
const own = await newTag(a);
|
||||
const id = await newTask(a);
|
||||
await tagTask(id, own);
|
||||
const tags = [u(), await newTag(a, { deletedAt: GONE }), await newTag(b)];
|
||||
const before = await state(a, b);
|
||||
for (const tag of tags) {
|
||||
for (const tag_ids of [[tag], [own, tag]]) {
|
||||
expect(await refused(a.token, 'set_task_tags', { task_id: id, tag_ids }, 'tag_not_found', { era }))
|
||||
.toStrictEqual({ error: 'tag_not_found', message: 'No tag with this id exists in this account.' });
|
||||
}
|
||||
}
|
||||
expect(await state(a, b)).toEqual(before);
|
||||
expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['no tag_ids', (id: string) => ({ task_id: id }), 'tag_ids'],
|
||||
['a null tag_ids', (id: string) => ({ task_id: id, tag_ids: null }), 'tag_ids'],
|
||||
['21 tags', (id: string) => ({ task_id: id, tag_ids: Array.from({ length: 21 }, () => u()) }), 'tag_ids'],
|
||||
['a tag id that is not a uuid', (id: string) => ({ task_id: id, tag_ids: ['red'] }), 'tag_ids'],
|
||||
['no task', () => ({ tag_ids: [] }), 'task_id'],
|
||||
['an unknown key', (id: string) => ({ task_id: id, tag_ids: [], user_id: 'someone-else' }), 'user_id'],
|
||||
])('refuses %s before the tool runs', async (_label, args, named) => {
|
||||
const a = await connected('write');
|
||||
const id = await newTask(a);
|
||||
await tagTask(id, await newTag(a));
|
||||
const before = await state(a);
|
||||
for (const era of ERAS) expect(await invalid(a.token, 'set_task_tags', args(id), { era })).toContain(named);
|
||||
expect(await state(a)).toEqual(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the write tools and the other accounts', () => {
|
||||
it.each(ERAS)('a task that is unknown, deleted or of another account answers not_found to every write tool (%s)', async (era) => {
|
||||
const [a, b] = [await connected('write'), await connected('write')];
|
||||
const tag = await newTag(a);
|
||||
const ids = [u(), await newTask(a, { deletedAt: GONE }), await newTask(b), await newTask(b, { parentId: await newTask(b) })];
|
||||
const before = await state(a, b);
|
||||
for (const task_id of ids) {
|
||||
for (const [name, args] of [
|
||||
['update_task', { title: words('title') }],
|
||||
['complete_task', {}],
|
||||
['reopen_task', {}],
|
||||
['set_task_tags', { tag_ids: [tag] }],
|
||||
] as const) {
|
||||
expect(await refused(a.token, name, { task_id, ...args }, 'not_found', { era }), `${name} ${task_id}`)
|
||||
.toStrictEqual({ error: 'not_found', message: 'No task with this id exists in this account.' });
|
||||
}
|
||||
}
|
||||
// Nothing of the refusals tells one case from another.
|
||||
expect(new Set(seen.answers.map((answered) => answered.text)).size).toBe(1);
|
||||
expect(await state(a, b)).toEqual(before);
|
||||
expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]);
|
||||
});
|
||||
|
||||
it.each(ERAS)('no write tool writes, moves or links a row of another account (%s)', async (era) => {
|
||||
const [a, b] = [await connected('write'), await connected('write')];
|
||||
const [titleB, notesB] = [words('title'), words('notes')];
|
||||
const taskB = await newTask(b, { title: titleB, notes: notesB, dueDate: '2026-06-01T12:00:00Z', recurrence: 'weekly' });
|
||||
const subB = await newTask(b, { parentId: taskB });
|
||||
const doneB = await newTask(b, { completed: true, completedAt: '2026-03-02T00:00:00Z' });
|
||||
const listB = await newList(b);
|
||||
const tagB = await newTag(b);
|
||||
await tagTask(taskB, tagB);
|
||||
const own = await newTask(a);
|
||||
const ownTag = await newTag(a);
|
||||
await tagTask(own, ownTag);
|
||||
|
||||
const attempts: [string, Json, keyof typeof TOOL_ERROR_MESSAGES][] = [
|
||||
// A task of the account in a list, under a task or with a tag of the other.
|
||||
['create_task', { title: words('title'), list_id: listB }, 'list_not_found'],
|
||||
['create_task', { title: words('title'), list_id: b.inbox }, 'list_not_found'],
|
||||
['create_task', { title: words('title'), parent_id: taskB }, 'parent_not_found'],
|
||||
['create_task', { title: words('title'), parent_id: subB }, 'parent_not_found'],
|
||||
['create_task', { title: words('title'), tag_ids: [tagB] }, 'tag_not_found'],
|
||||
['update_task', { task_id: own, list_id: listB }, 'list_not_found'],
|
||||
['set_task_tags', { task_id: own, tag_ids: [tagB] }, 'tag_not_found'],
|
||||
['set_task_tags', { task_id: own, tag_ids: [ownTag, tagB] }, 'tag_not_found'],
|
||||
// A task of the other account: renamed, taken into a list of the account, completed, reopened, tagged.
|
||||
['update_task', { task_id: taskB, title: words('title') }, 'not_found'],
|
||||
['update_task', { task_id: taskB, list_id: a.inbox }, 'not_found'],
|
||||
['update_task', { task_id: subB, notes: null }, 'not_found'],
|
||||
['complete_task', { task_id: taskB }, 'not_found'],
|
||||
['reopen_task', { task_id: doneB }, 'not_found'],
|
||||
['set_task_tags', { task_id: taskB, tag_ids: [] }, 'not_found'],
|
||||
['set_task_tags', { task_id: taskB, tag_ids: [ownTag] }, 'not_found'],
|
||||
['set_task_tags', { task_id: taskB, tag_ids: [tagB] }, 'not_found'],
|
||||
];
|
||||
const before = await state(a, b);
|
||||
for (const [name, args, code] of attempts) {
|
||||
expect(await refused(a.token, name, args, code, { era }), `${name} ${JSON.stringify(args)}`)
|
||||
.toStrictEqual({ error: code, message: TOOL_ERROR_MESSAGES[code] });
|
||||
}
|
||||
// Not a row of either account changed, no line was journaled, nobody was notified.
|
||||
expect(await state(a, b)).toEqual(before);
|
||||
expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]);
|
||||
// Nothing of the other account was read back either.
|
||||
const answered = seen.answers.map((x) => x.text).join('\n');
|
||||
for (const leak of [titleB, notesB, taskB, subB, listB, tagB]) expect(answered).not.toContain(leak);
|
||||
|
||||
// The other account does all of it on its own rows.
|
||||
expect(await ok(b.token, 'update_task', { task_id: taskB, list_id: listB }, { era })).toMatchObject({ task: { id: taskB, list_id: listB } });
|
||||
expect(await ok(b.token, 'set_task_tags', { task_id: taskB, tag_ids: [] }, { era })).toMatchObject({ changed: true });
|
||||
expect(await ok(b.token, 'complete_task', { task_id: taskB }, { era })).toMatchObject({ changed: true, next_occurrence: { list_id: listB } });
|
||||
expect(await ok(b.token, 'reopen_task', { task_id: doneB }, { era })).toMatchObject({ changed: true });
|
||||
expect(await ok(b.token, 'create_task', { title: words('title'), parent_id: taskB, tag_ids: [tagB] }, { era }))
|
||||
.toMatchObject({ task: { parent_id: taskB, list_id: listB, tags: [{ id: tagB }] } });
|
||||
expect((await journal(b.userId)).every((line) => line.token_id === b.id)).toBe(true);
|
||||
expect(await journal(a.userId)).toEqual([]);
|
||||
expect([notices(a.userId), notices(b.userId).length]).toEqual([[], 5]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the journal and the notice of a write', () => {
|
||||
// A token revoked while its request runs: the request was authenticated,
|
||||
// and the row its journal line points to is gone (#199).
|
||||
it('takes the write back when its journal line cannot be written, and answers internal_error', async () => {
|
||||
const a = await connected('write');
|
||||
const id = await newTask(a, { dueDate: '2026-06-01T12:00:00Z', recurrence: 'weekly' });
|
||||
const done = await newTask(a, { completed: true, completedAt: '2026-03-02T00:00:00Z' });
|
||||
const tag = await newTag(a);
|
||||
const target = await newList(a);
|
||||
const revoked = { userId: a.userId, scope: 'write', tokenId: u(), tokenName: 'Assistant' } as const;
|
||||
const writes: [string, Json][] = [
|
||||
['create_task', { title: words('title'), tag_ids: [tag] }],
|
||||
['update_task', { task_id: id, title: words('title'), list_id: target }],
|
||||
['complete_task', { task_id: id }],
|
||||
['reopen_task', { task_id: done }],
|
||||
['set_task_tags', { task_id: id, tag_ids: [tag] }],
|
||||
];
|
||||
const before = await state(a);
|
||||
for (const [name, args] of writes) {
|
||||
expect(await handled(revoked, name, args), name).toStrictEqual({
|
||||
isError: true,
|
||||
data: { error: 'internal_error', message: 'The server could not complete this call. Try again later.' },
|
||||
});
|
||||
}
|
||||
// Neither the task, nor the move, nor the completion and its next
|
||||
// occurrence, nor the link: nothing was kept, and nobody was notified.
|
||||
expect(await state(a)).toEqual(before);
|
||||
expect(notices(a.userId)).toEqual([]);
|
||||
const lines = logLines('mcp-tool');
|
||||
expect(lines.map((line) => `${line.tool} ${line.outcome}`)).toEqual(writes.map(([name]) => `${name} internal_error`));
|
||||
for (const line of lines) {
|
||||
expect(line.token).toBe(revoked.tokenId);
|
||||
// The class name of the database error, never its text.
|
||||
expect(line.error).toMatch(/^[A-Za-z]+$/);
|
||||
}
|
||||
|
||||
// A call that changes nothing writes no line: it is served.
|
||||
expect(await handled(revoked, 'reopen_task', { task_id: id })).toMatchObject({ isError: false, data: { changed: false } });
|
||||
// Control: the same writes with the token of the account are kept.
|
||||
for (const [name, args] of writes) await ok(a.token, name, args);
|
||||
expect((await journal(a.userId)).map((line) => line.tool).sort()).toEqual(writes.map(([name]) => name).sort());
|
||||
expect(notices(a.userId)).toEqual(Array(5).fill(true));
|
||||
});
|
||||
|
||||
it('journals a write of a caller without a token row under a null token', async () => {
|
||||
const a = await connected('write');
|
||||
const oauth = { userId: a.userId, scope: 'write', tokenId: null, tokenName: 'Connection' } as const;
|
||||
const { data } = await handled(oauth, 'create_task', { title: words('title') });
|
||||
const task = data.task as ShapedTask;
|
||||
expect(await journal(a.userId)).toEqual([
|
||||
{ tool: 'create_task', entity_type: 'task', entity_id: task.id, token_id: null, token_name: 'Connection' },
|
||||
]);
|
||||
expect(notices(a.userId)).toEqual([true]);
|
||||
});
|
||||
|
||||
it('keeps the lines of a token once it is revoked, and writes nothing more with it', async () => {
|
||||
const a = await connected('write');
|
||||
const title = words('title');
|
||||
const task = (await ok(a.token, 'create_task', { title })).task as ShapedTask;
|
||||
// What the page of the assistants reads: the line, with the title of the task as it is now.
|
||||
const line = { tool: 'create_task', entityType: 'task', entityId: task.id, entityName: title, tokenName: 'Assistant' };
|
||||
expect((await listActions(db, a.userId, { limit: 10 })).actions).toMatchObject([{ ...line, tokenId: a.id, tokenRevoked: false }]);
|
||||
|
||||
expect(await revokeAgentToken(a.userId, a.id)).toBe(true);
|
||||
expect((await listActions(db, a.userId, { limit: 10 })).actions).toMatchObject([{ ...line, tokenId: null, tokenRevoked: true }]);
|
||||
expect(await journal(a.userId)).toEqual([{ ...lineOf('create_task', task.id, a), token_id: null }]);
|
||||
expect(await rpc(a.token, 'tools/call', { name: 'complete_task', arguments: { task_id: task.id } })).toMatchObject(UNAUTHORIZED);
|
||||
expect((await stored(task.id)).completed).toBe(false);
|
||||
expect(notices(a.userId)).toEqual([true]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the write limit', () => {
|
||||
it('refuses the 31st write of a minute with rate_limited, all tokens and all write tools of the account together', async () => {
|
||||
const a = await connected('write');
|
||||
const second = await newToken(a, { scope: 'write' });
|
||||
const b = await connected('write');
|
||||
const id = await newTask(a);
|
||||
|
||||
await frozen(async (advance) => {
|
||||
// 30 calls over two tokens, the five tools and both generations: a call
|
||||
// that changes nothing and a call the tool refuses count like the others.
|
||||
const writes = [
|
||||
['create_task', { title: 'x' }], ['update_task', { task_id: id, priority: 1 }], ['complete_task', { task_id: id }],
|
||||
['reopen_task', { task_id: id }], ['set_task_tags', { task_id: id, tag_ids: [] }], ['complete_task', { task_id: u() }],
|
||||
] as const;
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const [name, args] = writes[i % writes.length];
|
||||
const r = await call(i % 2 === 0 ? a.token : second.token, name, args, { era: ERAS[(i >> 1) % 2] });
|
||||
expect(r.data.error === 'rate_limited', `write ${i + 1}: ${r.text}`).toBe(false);
|
||||
}
|
||||
const [before, transactions, sent] = [await state(a), h.transactions, notices(a.userId).length];
|
||||
|
||||
advance(20_000);
|
||||
for (const era of ERAS) {
|
||||
expect(await refused(a.token, 'create_task', { title: 'x' }, 'rate_limited', { era })).toStrictEqual({
|
||||
error: 'rate_limited',
|
||||
message: 'Too many calls for this account: wait retry_after_seconds seconds, then try again.',
|
||||
retry_after_seconds: 40,
|
||||
});
|
||||
}
|
||||
// The other token of the account, and every write tool.
|
||||
await refused(second.token, 'update_task', { task_id: id, priority: 2 }, 'rate_limited');
|
||||
await refused(second.token, 'complete_task', { task_id: id }, 'rate_limited');
|
||||
await refused(second.token, 'reopen_task', { task_id: id }, 'rate_limited');
|
||||
await refused(second.token, 'set_task_tags', { task_id: id, tag_ids: [] }, 'rate_limited');
|
||||
// Refused before the transaction: nothing written, nobody notified.
|
||||
expect(h.transactions).toBe(transactions);
|
||||
expect(await state(a)).toEqual(before);
|
||||
expect(notices(a.userId)).toHaveLength(sent);
|
||||
// An answer of the tool, not an HTTP error.
|
||||
expect(seen.answers.every((answered) => answered.status === 200)).toBe(true);
|
||||
expect(logLines('mcp-tool').slice(-6).map((line) => line.outcome)).toEqual(Array(6).fill('rate_limited'));
|
||||
|
||||
// The reads are counted apart, and another account is not slowed down.
|
||||
await ok(a.token, 'get_task', { task_id: id });
|
||||
await ok(b.token, 'create_task', { title: 'x' });
|
||||
|
||||
// A refused call is not counted: once the minute has passed, the account writes again.
|
||||
advance(39_999);
|
||||
expect(await refused(a.token, 'create_task', { title: 'x' }, 'rate_limited')).toMatchObject({ retry_after_seconds: 1 });
|
||||
advance(1);
|
||||
await ok(a.token, 'create_task', { title: 'x' });
|
||||
});
|
||||
});
|
||||
|
||||
it('counts every write of a JSON-RPC batch', async () => {
|
||||
const a = await connected('write');
|
||||
await frozen(async () => {
|
||||
for (let i = 0; i < 28; i++) expect(rateLimitDelay(a.userId, 'mcp-write')).toBeNull();
|
||||
const batch = [1, 2, 3].map((id) => ({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'create_task', arguments: { title: 'x' } } }));
|
||||
const answered = await post(a.token, JSON.stringify(batch), { headers: LEGACY_ACCEPT });
|
||||
expect(answered.status).toBe(200);
|
||||
// One HTTP request, three calls: two tasks are created, the third call is the 31st.
|
||||
expect(logLines('mcp-tool').map((line) => line.outcome).sort()).toEqual(['ok', 'ok', 'rate_limited']);
|
||||
expect(await journal(a.userId)).toHaveLength(2);
|
||||
// The calls of a batch may overlap: only their number is read here.
|
||||
expect(notices(a.userId)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('list_lists', () => {
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import type { AgentTokenContext, AgentTokenScope } from '@/lib/agentTokens';
|
|||
import { rateLimitDelay } from '@/lib/rateLimit';
|
||||
import { ToolRefusal, errorName, toolErrorBody, type ToolErrorCode } from './errors';
|
||||
import { registerReadTools } from './readTools';
|
||||
import { registerWriteTools } from './writeTools';
|
||||
|
||||
const SERVER_NAME = 'simpl-liste';
|
||||
const SERVER_VERSION = '1.0.0';
|
||||
|
|
@ -166,8 +167,10 @@ function buildServer(authInfo: AuthInfo | undefined): McpServer {
|
|||
};
|
||||
|
||||
// A read-only token sees the read tools and nothing else: a tool it may not
|
||||
// call does not exist for it.
|
||||
// call does not exist for it. The write tools (#203) are registered for a
|
||||
// read-write token only.
|
||||
registerReadTools(register);
|
||||
if (context.scope === 'write') registerWriteTools(register);
|
||||
return server;
|
||||
}
|
||||
|
||||
|
|
|
|||
245
web/src/lib/mcp/writeTools.ts
Normal file
245
web/src/lib/mcp/writeTools.ts
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
// The write tools of the MCP server (#203), registered for a read-write token
|
||||
// only. This module validates inputs and shapes outputs: every write is a
|
||||
// function of taskWrites.ts, scoped to the account of the token, and every
|
||||
// task leaves through renderTask (readTools.ts).
|
||||
//
|
||||
// No tool removes a task, a list or a tag (DECISIONS.md, 2026-11-14), and a
|
||||
// change cannot be undone: the journal (agentJournal.ts) is its only trace.
|
||||
// A task that was deleted, or that belongs to another account, answers like
|
||||
// one that never existed, and so do a list, a parent and a tag.
|
||||
|
||||
import { z } from 'zod';
|
||||
import { db } from '@/db/client';
|
||||
import { recordAction, type JournalEntityType } from '@/lib/agentJournal';
|
||||
import { RECURRENCES } from '@/lib/recurrence';
|
||||
import type { Tx } from '@/lib/taskDelete';
|
||||
import { completeTask, createTask, reopenTask, setTaskTags, updateTask, type TaskRow } from '@/lib/taskWrites';
|
||||
import { dueDateSchema } from '@/lib/validators';
|
||||
import { notifyUserChanged } from '@/lib/ws';
|
||||
import { ToolRefusal } from './errors';
|
||||
import { renderTask } from './readTools';
|
||||
import type { RegisterTool, ToolContext } from './server';
|
||||
|
||||
// The names of the write tools: what the journal holds in its `tool` column.
|
||||
// A tool registered through registerWriteTool has its name here.
|
||||
export const WRITE_TOOL_NAMES = [
|
||||
'create_task',
|
||||
'update_task',
|
||||
'complete_task',
|
||||
'reopen_task',
|
||||
'set_task_tags',
|
||||
] as const;
|
||||
|
||||
export type WriteToolName = (typeof WRITE_TOOL_NAMES)[number];
|
||||
|
||||
// What a write did: whether it wrote anything, the row it touched (for the
|
||||
// journal), and what the tool renders its answer from once the transaction
|
||||
// has committed.
|
||||
export type WriteOutcome<Value> = {
|
||||
changed: boolean;
|
||||
entityType: JournalEntityType;
|
||||
entityId: string;
|
||||
value: Value;
|
||||
};
|
||||
|
||||
// A write tool, as registerWriteTool takes it.
|
||||
export type WriteToolDefinition<Schema extends z.ZodType, Value> = {
|
||||
name: WriteToolName;
|
||||
description: string;
|
||||
inputSchema: Schema;
|
||||
// readOnlyHint and openWorldHint are the same for every write tool.
|
||||
annotations: { destructiveHint: boolean; idempotentHint?: boolean };
|
||||
// Runs in the transaction of the envelope, and queries through `tx` only.
|
||||
// It refuses by throwing (a WriteRefusal of taskWrites.ts, or a ToolRefusal):
|
||||
// the transaction is rolled back, and nothing is journaled nor notified.
|
||||
write: (tx: Tx, input: z.output<Schema>, context: ToolContext) => Promise<WriteOutcome<Value>>;
|
||||
// Runs after the commit, outside the transaction: the answer of the tool.
|
||||
render: (value: Value, context: ToolContext) => Promise<Record<string, unknown>>;
|
||||
};
|
||||
|
||||
// The envelope of every write tool, inside the envelope of every tool
|
||||
// (server.ts), which has already counted the call in `mcp-write`:
|
||||
// 1. one transaction: the write, then its journal line when it changed
|
||||
// something. The line and the write are committed together, or neither
|
||||
// is: a journal insert that fails takes the write back;
|
||||
// 2. after the commit, one notification, so that an open page or the app
|
||||
// that reloads on it finds what was written;
|
||||
// 3. the answer, read from the committed rows. A read that fails here
|
||||
// answers `internal_error` for a write that is kept, and that its
|
||||
// journal line shows.
|
||||
// A call that changes nothing (`changed: false`) writes no journal line and
|
||||
// notifies nobody.
|
||||
export function registerWriteTool<Schema extends z.ZodType, Value>(
|
||||
register: RegisterTool,
|
||||
tool: WriteToolDefinition<Schema, Value>,
|
||||
): void {
|
||||
register({
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema,
|
||||
annotations: { readOnlyHint: false, openWorldHint: false, ...tool.annotations },
|
||||
limit: 'mcp-write',
|
||||
run: async (input, context) => {
|
||||
const outcome = await db.transaction(async (tx) => {
|
||||
const written = await tool.write(tx, input, context);
|
||||
if (written.changed) {
|
||||
await recordAction(tx, {
|
||||
userId: context.userId,
|
||||
tokenId: context.tokenId,
|
||||
tokenName: context.tokenName,
|
||||
tool: tool.name,
|
||||
entityType: written.entityType,
|
||||
entityId: written.entityId,
|
||||
});
|
||||
}
|
||||
return written;
|
||||
});
|
||||
if (outcome.changed) notifyUserChanged(context.userId);
|
||||
return tool.render(outcome.value, context);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// What taskWrites.ts answers for a task that is unknown, deleted or of
|
||||
// another account: the three read the same.
|
||||
function found<Result>(result: Result | null): Result {
|
||||
if (result === null) throw new ToolRefusal('not_found');
|
||||
return result;
|
||||
}
|
||||
|
||||
// The journal line of a write on a task.
|
||||
function onTask<Value extends { changed: boolean; task: TaskRow }>(result: Value): WriteOutcome<Value> {
|
||||
return { changed: result.changed, entityType: 'task', entityId: result.task.id, value: result };
|
||||
}
|
||||
|
||||
// `tag_ids` holds at most 20 ids, as the tag filter of list_tasks. With the
|
||||
// other arguments, the largest call (create_task: 8 keys and 20 ids) stays
|
||||
// below `maxToolInputElements` (server.ts), which bounds a hostile array
|
||||
// before zod reads its elements.
|
||||
const TAG_IDS_MAX = 20;
|
||||
|
||||
const DUE_DATE_FORMATS = 'YYYY-MM-DD for a day (stored at 12:00 UTC of that day), or an ISO 8601 date-time with a UTC offset for a precise time';
|
||||
|
||||
const taskId = z.string().uuid().describe('Id of the task, top-level or subtask.');
|
||||
const title = z.string().min(1).max(500);
|
||||
// 5 000 characters, as the REST API; the app allows 10 000.
|
||||
const notes = z.string().max(5000);
|
||||
const priority = z.number().int().min(0).max(3);
|
||||
const recurrence = z.enum(RECURRENCES);
|
||||
const tagIds = z.array(z.string().uuid()).max(TAG_IDS_MAX);
|
||||
|
||||
const createTaskInput = z.object({
|
||||
title: title.describe('Title of the task, 1 to 500 characters.'),
|
||||
list_id: z.string().uuid().optional()
|
||||
.describe('List the task is created in. Without it, the task goes to the Inbox. Ignored when parent_id is given.'),
|
||||
parent_id: z.string().uuid().optional()
|
||||
.describe('Id of a top-level task: the new task becomes its subtask, in the list of that task. A subtask cannot have subtasks.'),
|
||||
notes: notes.optional().describe('Notes of the task, 5000 characters at most.'),
|
||||
priority: priority.optional().describe('0 none (default), 1 low, 2 medium, 3 high.'),
|
||||
due_date: dueDateSchema.optional().describe(`Due date: ${DUE_DATE_FORMATS}.`),
|
||||
recurrence: recurrence.optional()
|
||||
.describe('How often the task comes back. A recurring task that has a due date gets its next occurrence when it is completed.'),
|
||||
tag_ids: tagIds.optional().describe('Ids of the tags to put on the task, 20 at most.'),
|
||||
}).strict();
|
||||
|
||||
const UPDATE_FIELDS = ['title', 'notes', 'priority', 'due_date', 'recurrence', 'list_id'] as const;
|
||||
|
||||
const updateTaskInput = z.object({
|
||||
task_id: taskId,
|
||||
title: title.optional().describe('New title, 1 to 500 characters.'),
|
||||
notes: notes.nullable().optional().describe('New notes, 5000 characters at most; null removes them.'),
|
||||
priority: priority.optional().describe('New priority: 0 none, 1 low, 2 medium, 3 high.'),
|
||||
due_date: dueDateSchema.nullable().optional().describe(`New due date: ${DUE_DATE_FORMATS}; null removes it.`),
|
||||
recurrence: recurrence.nullable().optional().describe('New recurrence; null makes the task stop coming back.'),
|
||||
list_id: z.string().uuid().optional()
|
||||
.describe('List to move the task to: it goes to the end of that list, with its subtasks. A subtask cannot be moved.'),
|
||||
}).strict().refine(
|
||||
(input) => UPDATE_FIELDS.some((field) => input[field] !== undefined),
|
||||
{ message: `Nothing to change: pass at least one of ${UPDATE_FIELDS.join(', ')}.` },
|
||||
);
|
||||
|
||||
const taskInput = z.object({ task_id: taskId }).strict();
|
||||
|
||||
const setTaskTagsInput = z.object({
|
||||
task_id: taskId,
|
||||
tag_ids: tagIds.describe('Ids of the tags the task must have, 20 at most. An empty list removes every tag.'),
|
||||
}).strict();
|
||||
|
||||
export function registerWriteTools(register: RegisterTool): void {
|
||||
// Adds a task: nothing existing is changed.
|
||||
registerWriteTool(register, {
|
||||
name: 'create_task',
|
||||
description: 'Creates a task and returns it. Without list_id the task goes to the Inbox; with parent_id it becomes a subtask of that task. The task is placed at the end of its list, or of the subtasks of its parent.',
|
||||
inputSchema: createTaskInput,
|
||||
annotations: { destructiveHint: false },
|
||||
write: async (tx, input, { userId }) => onTask(await createTask(tx, userId, {
|
||||
title: input.title,
|
||||
listId: input.list_id,
|
||||
parentId: input.parent_id,
|
||||
notes: input.notes,
|
||||
priority: input.priority,
|
||||
dueDate: input.due_date,
|
||||
recurrence: input.recurrence,
|
||||
tagIds: input.tag_ids,
|
||||
})),
|
||||
render: async ({ task }, { userId }) => ({ task: await renderTask(userId, task) }),
|
||||
});
|
||||
|
||||
// Overwrites values: the previous ones are lost. Calling it again with the
|
||||
// same arguments leaves the task as it is.
|
||||
registerWriteTool(register, {
|
||||
name: 'update_task',
|
||||
description: 'Changes a task and returns it. Only the fields passed are changed; null removes the notes, the due date or the recurrence. list_id moves a top-level task to the end of another list, with its subtasks. The previous values are not kept: a change cannot be undone. To complete or reopen a task, use complete_task or reopen_task; to change its tags, set_task_tags.',
|
||||
inputSchema: updateTaskInput,
|
||||
annotations: { destructiveHint: true, idempotentHint: true },
|
||||
write: async (tx, input, { userId }) => onTask(found(await updateTask(tx, userId, input.task_id, {
|
||||
title: input.title,
|
||||
notes: input.notes,
|
||||
priority: input.priority,
|
||||
dueDate: input.due_date,
|
||||
recurrence: input.recurrence,
|
||||
listId: input.list_id,
|
||||
}))),
|
||||
render: async ({ task }, { userId }) => ({ task: await renderTask(userId, task) }),
|
||||
});
|
||||
|
||||
registerWriteTool(register, {
|
||||
name: 'complete_task',
|
||||
description: 'Marks a task as completed and returns it. A recurring task that has a due date gets its next occurrence, a new task returned in next_occurrence (null for any other task). When the task was already completed, nothing happens and changed is false.',
|
||||
inputSchema: taskInput,
|
||||
annotations: { destructiveHint: false, idempotentHint: true },
|
||||
// One journal line, for the task that was completed: its next occurrence
|
||||
// has none.
|
||||
write: async (tx, input, { userId }) => onTask(found(await completeTask(tx, userId, input.task_id))),
|
||||
render: async (result, { userId }) => ({
|
||||
task: await renderTask(userId, result.task),
|
||||
next_occurrence: result.changed && result.next ? await renderTask(userId, result.next) : null,
|
||||
changed: result.changed,
|
||||
}),
|
||||
});
|
||||
|
||||
registerWriteTool(register, {
|
||||
name: 'reopen_task',
|
||||
description: 'Marks a completed task as not completed and returns it. The next occurrence that completing a recurring task created stays. When the task was not completed, nothing happens and changed is false.',
|
||||
inputSchema: taskInput,
|
||||
annotations: { destructiveHint: false, idempotentHint: true },
|
||||
write: async (tx, input, { userId }) => onTask(found(await reopenTask(tx, userId, input.task_id))),
|
||||
render: async (result, { userId }) => ({
|
||||
task: await renderTask(userId, result.task),
|
||||
changed: result.changed,
|
||||
}),
|
||||
});
|
||||
|
||||
// Overwrites the set of tags: a tag that is not listed leaves the task.
|
||||
registerWriteTool(register, {
|
||||
name: 'set_task_tags',
|
||||
description: 'Replaces the tags of a task by the given ones and returns the task: a tag that is not in tag_ids is taken off the task (the tag itself stays), and an empty list takes them all off. When the task already has exactly these tags, nothing happens and changed is false.',
|
||||
inputSchema: setTaskTagsInput,
|
||||
annotations: { destructiveHint: true, idempotentHint: true },
|
||||
write: async (tx, input, { userId }) => onTask(found(await setTaskTags(tx, userId, input.task_id, input.tag_ids))),
|
||||
render: async (result, { userId }) => ({
|
||||
task: await renderTask(userId, result.task),
|
||||
changed: result.changed,
|
||||
}),
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue