From 06ee5a850b24c3463c8225b715a79aee4db65941 Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 5 Dec 2026 12:29:48 +0100 Subject: [PATCH] feat(mcp): set bringers for a packing item Let packing editors replace the bringers on a Common item in one write. Use the existing trip roster, item visibility and packing edit policy, and leave the sharing tier and recipients alone. Closes #3313 --- .../PackingItemContributors.repository.ts | 41 ++++--- .../nest/packing/packing-writes.service.ts | 8 ++ server/src/nest/packing/packing.mcp.ts | 26 ++++ server/src/nest/packing/packing.service.ts | 21 ++++ server/tests/unit/mcp/tools-packing.test.ts | 116 +++++++++++++++++- wiki/MCP-Addon-Tools.md | 1 + 6 files changed, 193 insertions(+), 20 deletions(-) diff --git a/server/src/db/repositories/PackingItemContributors.repository.ts b/server/src/db/repositories/PackingItemContributors.repository.ts index ae47d011e..d59e433e7 100644 --- a/server/src/db/repositories/PackingItemContributors.repository.ts +++ b/server/src/db/repositories/PackingItemContributors.repository.ts @@ -23,11 +23,8 @@ type PackingItemContributorsKyselyDB = Pick { /** @@ -52,20 +49,28 @@ export class PackingItemContributorsRepository extends TrekRepository { - await this.upsert( - { item: item_id, user: user_id, status: 'accepted' }, - { onConflictFields: ['item', 'user'], onConflictAction: 'ignore' }, - ); + await this.insertManyIgnore(item_id, [user_id]); + } + + async insertManyIgnore(item_id: number, user_ids: number[]): Promise { + if (user_ids.length === 0) return; + await this.kysely() + .insertInto('packing_item_contributors') + .values(user_ids.map((user_id) => ({ item_id, user_id, status: 'accepted' }))) + .onConflict((conflict) => conflict.columns(['item_id', 'user_id']).doNothing()) + .execute(); + } + + /** Remove former bringers when an editor replaces the whole selection. */ + async deleteExcept(item_id: number, user_ids: number[]): Promise { + if (user_ids.length === 0) return this.deleteForItem(item_id); + await this.kysely() + .deleteFrom('packing_item_contributors') + .where('item_id', '=', item_id) + .where('user_id', 'not in', user_ids) + .execute(); } /** PK18 (`setItemSharing`'s leaving-Common cleanup) — `DELETE FROM packing_item_contributors WHERE item_id = ?`. */ diff --git a/server/src/nest/packing/packing-writes.service.ts b/server/src/nest/packing/packing-writes.service.ts index 65a7bcd68..fb8a46eb0 100644 --- a/server/src/nest/packing/packing-writes.service.ts +++ b/server/src/nest/packing/packing-writes.service.ts @@ -183,6 +183,14 @@ export class PackingWritesService { return item; } + async setBringers(tripId: number, itemId: number, userIds: number[], writer: TripWriter) { + await this.gate(tripId, writer); + const item = await this.packing.setBringers(tripId, itemId, userIds, writer.userId); + if (!item) throw itemNotFound(); + writer.events.emit('packing:updated', { item } as TrekWsPayload<'packing:updated'>); + return item; + } + /** The list's new order, for every other tab on both surfaces. */ async reorder(tripId: string | number, orderedIds: number[], writer: TripWriter) { await this.gate(tripId, writer); diff --git a/server/src/nest/packing/packing.mcp.ts b/server/src/nest/packing/packing.mcp.ts index 567e44e9f..b4a44724d 100644 --- a/server/src/nest/packing/packing.mcp.ts +++ b/server/src/nest/packing/packing.mcp.ts @@ -292,6 +292,32 @@ export class PackingMcp { return ok({ item }); } + @Tool({ + name: 'set_packing_item_bringers', + description: + 'Set who brings a Common packing item. Replaces the full selection, including the original bringer if omitted. Pass an empty list to clear it. To find the current selection, read owner_id and contributors in list_packing_items. Does not change sharing or recipients.', + inputSchema: { + tripId: idSchema, + itemId: idSchema, + user_ids: z.array(idSchema).describe('User IDs of the trip members who bring this item'), + }, + annotations: TOOL_ANNOTATIONS_WRITE, + when: packingAddonOn, + access: { group: 'packing', mode: 'write' }, + }) + async setPackingItemBringers( + { tripId, itemId, user_ids }: { tripId: number; itemId: number; user_ids: number[] }, + ctx: McpContext, + ) { + const item = await this.writes.setBringers( + tripId, + itemId, + user_ids, + await this.guards.tripWriter(tripId, ctx.userId), + ); + return ok({ item }); + } + // --- PACKING ADVANCED --- @Tool({ diff --git a/server/src/nest/packing/packing.service.ts b/server/src/nest/packing/packing.service.ts index 5c5e9561b..7eaa9f2e1 100644 --- a/server/src/nest/packing/packing.service.ts +++ b/server/src/nest/packing/packing.service.ts @@ -429,6 +429,27 @@ export class PackingService { return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0]; } + /** Replace the bringers of a Common item without changing who may see it. */ + async setBringers(tripId: string | number, itemId: number, userIds: number[], actingUserId: number) { + return this.uow.transactional(async () => { + const item = await this.itemsRepo.findVisibleInTrip(itemId, tripId, actingUserId); + if (!item || item.is_private !== 0) return null; + const roster = await this.tripRosterIds(tripId); + if (userIds.some((id) => !roster.has(id))) { + throw new DomainError(400, 'Every bringer must be a trip member'); + } + + // The Common item's owner is its first bringer in the UI. When omitted, + // release them the same way as the single-person removal on REST. + const selected = new Set(userIds); + const contributors = [...selected].filter((id) => id !== item.owner_id); + if (item.owner_id != null && !selected.has(item.owner_id)) await this.itemsRepo.clearOwner(itemId); + await this.contributorsRepo.deleteExcept(itemId, contributors); + await this.contributorsRepo.insertManyIgnore(itemId, contributors); + return (await this.enrichItems([await this.itemsRepo.findById(itemId)]))[0]; + }); + } + /** True when the bag exists AND belongs to the trip — the referenced-id rule * the FK cannot enforce (it only checks existence). */ private async bagInTrip(tripId: string | number, bagId: number): Promise { diff --git a/server/tests/unit/mcp/tools-packing.test.ts b/server/tests/unit/mcp/tools-packing.test.ts index c1788a04c..39ce8b1d3 100644 --- a/server/tests/unit/mcp/tools-packing.test.ts +++ b/server/tests/unit/mcp/tools-packing.test.ts @@ -14,6 +14,7 @@ import { ADDON_IDS } from '../../../src/addons'; import { PackingBags } from '../../../src/db/entities/PackingBags.entity'; import { PackingItems } from '../../../src/db/entities/PackingItems.entity'; +import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import { inContext } from '../../helpers/factories/context'; import { addPackingBagMembers, @@ -22,7 +23,7 @@ import { makePackingItem, } from '../../helpers/factories/packing'; import { countRows, findRow, insertRow, updateRows } from '../../helpers/factories/rows'; -import { setAddonEnabled } from '../../helpers/factories/settings'; +import { setAddonEnabled, setAppSetting, setTripAddon } from '../../helpers/factories/settings'; import { addTripMember, makeTrip } from '../../helpers/factories/trips'; import { makeUser } from '../../helpers/factories/users'; import { FakeRealtimeService } from '../../helpers/fake-realtime'; @@ -935,6 +936,116 @@ describe('Tool: list_packing_items', () => { }); }); +describe('Tool: set_packing_item_bringers', () => { + function setBringers(h: McpHarness, tripId: number, itemId: number, userIds: number[]) { + return h.client.callTool({ + name: 'set_packing_item_bringers', + arguments: { tripId, itemId, user_ids: userIds }, + }); + } + + it('replaces the full selection and keeps the Common item and its other fields', async () => { + const { user: owner } = await makeUser(orm); + const { user: member } = await makeUser(orm); + const trip = await makeTrip(orm, owner.id); + await addTripMember(orm, trip.id, member.id, owner.id); + const item = await makePackingItem(orm, trip.id, { owner: owner.id, name: 'Tent', quantity: 2 }); + + await withHarness(member.id, async (h) => { + const both = parseToolResult(await setBringers(h, trip.id, item.id, [owner.id, member.id, member.id])); + expect(both).toMatchObject({ + item: { owner_id: owner.id, contributors: [{ user_id: member.id }] }, + }); + expect(broadcastMock).toHaveBeenLastCalledWith( + trip.id, + 'packing:updated', + expect.objectContaining({ item: expect.objectContaining({ id: item.id }) }), + ); + + const one = parseToolResult(await setBringers(h, trip.id, item.id, [member.id])); + expect(one).toMatchObject({ + item: { + name: 'Tent', + quantity: 2, + is_private: 0, + owner_id: null, + contributors: [{ user_id: member.id }], + recipients: [], + }, + }); + + const none = parseToolResult(await setBringers(h, trip.id, item.id, [])); + expect(none).toMatchObject({ item: { owner_id: null, contributors: [] } }); + }); + }); + + it('validates every bringer before changing the current selection', async () => { + const { user: owner } = await makeUser(orm); + const { user: outsider } = await makeUser(orm); + const trip = await makeTrip(orm, owner.id); + const item = await makePackingItem(orm, trip.id, { owner: owner.id }); + + await withHarness(owner.id, async (h) => { + const result = await setBringers(h, trip.id, item.id, [outsider.id]); + expect(result.isError).toBe(true); + expect(errorText(result)).toContain('Every bringer must be a trip member'); + }); + expect((await itemRow(item.id)).owner_id).toBe(owner.id); + expect(broadcastMock).not.toHaveBeenCalled(); + }); + + it('refuses private items and items on a different trip', async () => { + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id); + const other = await makeTrip(orm, user.id); + const personal = await makePackingItem(orm, trip.id, { is_private: 1, owner: user.id }); + const outsideTrip = await makePackingItem(orm, other.id, { owner: user.id }); + + await withHarness(user.id, async (h) => { + expect((await setBringers(h, trip.id, personal.id, [])).isError).toBe(true); + expect((await setBringers(h, trip.id, outsideTrip.id, [])).isError).toBe(true); + }); + expect(broadcastMock).not.toHaveBeenCalled(); + }); + + it('requires the configured packing edit permission', async () => { + const { user: owner } = await makeUser(orm); + const { user: member } = await makeUser(orm); + const trip = await makeTrip(orm, owner.id); + await addTripMember(orm, trip.id, member.id, owner.id); + const item = await makePackingItem(orm, trip.id, { owner: owner.id }); + const permissions = (await bootTestApp(realtime)).get(PermissionsService); + await setAppSetting(orm, 'perm_packing_edit', 'trip_owner'); + await permissions.invalidatePermissionsCache(); + + try { + await withHarness(member.id, async (h) => { + const result = await setBringers(h, trip.id, item.id, [member.id]); + expect(result.isError).toBe(true); + expect(errorText(result)).toContain('You do not have permission'); + }); + expect(broadcastMock).not.toHaveBeenCalled(); + } finally { + await setAppSetting(orm, 'perm_packing_edit', 'trip_member'); + await permissions.invalidatePermissionsCache(); + } + }); + + it('respects the target trip addon switch', async () => { + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id); + const item = await makePackingItem(orm, trip.id, { owner: user.id }); + await setTripAddon(orm, trip.id, ADDON_IDS.PACKING, false); + + await withHarness(user.id, async (h) => { + const result = await setBringers(h, trip.id, item.id, []); + expect(result.isError).toBe(true); + expect(errorText(result)).toMatch(/Packing addon is not enabled/i); + }); + expect(broadcastMock).not.toHaveBeenCalled(); + }); +}); + // --------------------------------------------------------------------------- // Scope gating (packing read/write, registration-time) // --------------------------------------------------------------------------- @@ -962,6 +1073,7 @@ describe('Packing tools — scope gating', () => { 'delete_packing_template', 'bulk_import_packing', 'set_packing_item_sharing', + 'set_packing_item_bringers', ]; async function listToolNames(userId: number, scopes: string[] | null): Promise { @@ -973,7 +1085,7 @@ describe('Packing tools — scope gating', () => { } } - it('registers all nineteen tools with null scopes (full access)', async () => { + it('registers all packing tools with null scopes (full access)', async () => { const { user } = await makeUser(orm); const names = await listToolNames(user.id, null); for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool); diff --git a/wiki/MCP-Addon-Tools.md b/wiki/MCP-Addon-Tools.md index e6f09c097..1199d7b10 100644 --- a/wiki/MCP-Addon-Tools.md +++ b/wiki/MCP-Addon-Tools.md @@ -16,6 +16,7 @@ Requires `packing:read` or `packing:write` scope. The Packing addon is listed as | `create_packing_item` | Add an item to the packing checklist with optional category. | | `update_packing_item` | Rename an item, change its category, or count how many of it are already packed. | | `set_packing_item_sharing` | Move an item between the three sharing tiers: `common` puts it in the pool the whole trip packs from, `personal` keeps it to its owner, `shared` covers the trip members in `recipient_ids`. Only the item's owner may change this. | +| `set_packing_item_bringers` | Replace who brings a Common packing item with `user_ids`, including the original bringer in that list if they should stay. An empty list clears all bringers. Read the item's `owner_id` and `contributors` with `list_packing_items` for its current bringers. Sharing and recipients stay as they are. | | `toggle_packing_item` | Check or uncheck a packing item. | | `delete_packing_item` | Remove a packing item. | | `reorder_packing_items` | Set the display order of packing items within a trip. |