diff --git a/server/scripts/mcp-inline-zod-baseline.json b/server/scripts/mcp-inline-zod-baseline.json index b750f2f1c..f8bbe3893 100644 --- a/server/scripts/mcp-inline-zod-baseline.json +++ b/server/scripts/mcp-inline-zod-baseline.json @@ -22,7 +22,7 @@ "src/nest/places/places.mcp.ts": 68, "src/nest/plugins/contributions/plugin-pois.mcp.ts": 4, "src/nest/plugins/contributions/plugin-search.mcp.ts": 5, - "src/nest/reservations/reservations.mcp.ts": 64, + "src/nest/reservations/reservations.mcp.ts": 60, "src/nest/roadtrip/day-boundaries.mcp.ts": 1, "src/nest/roadtrip/google-route.mcp.ts": 2, "src/nest/roadtrip/roadtrip.mcp.ts": 16, diff --git a/server/src/nest/budget/budget.mcp.ts b/server/src/nest/budget/budget.mcp.ts index 64a72f340..a8f8cefa6 100644 --- a/server/src/nest/budget/budget.mcp.ts +++ b/server/src/nest/budget/budget.mcp.ts @@ -230,6 +230,11 @@ export class BudgetMcp { .describe( 'Place on this trip the expense belongs to (the museum ticket for that museum), linking it in the planner', ), + reservation_id: idSchema + .optional() + .describe( + 'Booking or transport on this trip the expense belongs to (a booking can carry several), linking it in the planner', + ), note: z.string().max(500).optional(), }, annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, @@ -248,6 +253,7 @@ export class BudgetMcp { payers, expense_date, place_id, + reservation_id, note, }: { tripId: number; @@ -260,6 +266,7 @@ export class BudgetMcp { payers?: { user_id: number; amount: number }[]; expense_date?: string | null; place_id?: number; + reservation_id?: number; note?: string; }, ctx: McpContext, @@ -270,6 +277,8 @@ export class BudgetMcp { return errorResult('Pass either members (uneven split) or member_ids (equal split), not both.'); if (place_id != null && !(await this.placeOnTrip(tripId, place_id))) return errorResult('place_id does not belong to this trip.'); + const linkRefusal = await this.budget.linkRefusal(tripId, { reservation_id }); + if (linkRefusal) return errorResult(linkRefusal); if (members !== undefined) { const refusal = await this.splitRefusal( tripId, @@ -293,13 +302,12 @@ export class BudgetMcp { payers, expense_date, place_id, + reservation_id, note, }; - // Freeze the live FX rate at entry time so a settled position isn't re-opened - // when live rates drift (#1445) — same as the REST create path. - await this.budget.freezeForeignRate(tripId, itemData); - const item = await this.budget.createBudgetItem(tripId, itemData); - this.guards.safeBroadcast(tripId, 'budget:created', { item }); + // The REST create's use case: it freezes the live FX rate at entry time + // (#1445), works out a linked booking's price again and sends budget:created. + const item = await this.writes.createItem(tripId, itemData, await this.guards.tripWriter(tripId, ctx.userId)); return ok({ item }); } @@ -486,6 +494,11 @@ export class BudgetMcp { .describe( 'Place on this trip the expense belongs to (the museum ticket for that museum), linking it in the planner', ), + reservation_id: idSchema + .optional() + .describe( + 'Booking or transport on this trip the expense belongs to (a booking can carry several), linking it in the planner', + ), }, annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, when: budgetAddonOn, @@ -500,6 +513,7 @@ export class BudgetMcp { note, userIds, place_id, + reservation_id, }: { tripId: number; name: string; @@ -508,6 +522,7 @@ export class BudgetMcp { note?: string; userIds?: number[]; place_id?: number; + reservation_id?: number; }, ctx: McpContext, ) { @@ -520,7 +535,7 @@ export class BudgetMcp { try { // The REST create's use case: the trip gate, the place check (#2084) and // budget:created alone, since the item it sends already carries its members. - const data = { category, name, total_price, note, member_ids: members, place_id }; + const data = { category, name, total_price, note, member_ids: members, place_id, reservation_id }; return ok({ item: await this.writes.createItem(tripId, data, writer) }); } catch (err) { if (err instanceof DomainError) throw err; diff --git a/server/src/nest/reservations/reservations.mcp.ts b/server/src/nest/reservations/reservations.mcp.ts index 43f258ae9..4594397d5 100644 --- a/server/src/nest/reservations/reservations.mcp.ts +++ b/server/src/nest/reservations/reservations.mcp.ts @@ -15,7 +15,7 @@ import { findByIata } from '../airports/airports.data'; import type { EndpointInput } from './reservations.service'; import { AssignmentsService } from '../assignments/assignments.service'; import { - idSchema, transportLegInputSchema, reservationUrlSchema, type TransportLegInput, + idSchema, transportLegInputSchema, reservationUrlSchema, type TransportLegInput, bookingPriceSchema, bookingBudgetCategorySchema, TRANSPORT_RESERVATION_TYPES, MCP_CREATABLE_TRANSPORT_TYPES, LEG_RESERVATION_TYPES, BOOKING_RESERVATION_TYPES, RESERVATION_STATUSES, type ReservationStatus, } from '@trek/shared'; @@ -366,8 +366,8 @@ export class ReservationsMcp { check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00", hotel type only)'), check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00", hotel type only)'), assignment_id: idSchema.optional().describe('Link to a day assignment (restaurant, train, car, cruise, event, tour, activity, other)'), - price: z.number().nonnegative().optional().describe(PRICE_FIELD), - budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to reservation type)'), + price: bookingPriceSchema.optional().describe(PRICE_FIELD), + budget_category: bookingBudgetCategorySchema.optional().describe('Budget category for the price entry (defaults to reservation type)'), }, annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, access: { group: 'reservations', mode: 'write' }, @@ -673,8 +673,8 @@ export class ReservationsMcp { endpoints: endpointSchema, legs: legsSchema, needs_review: z.boolean().optional(), - price: z.number().nonnegative().optional().describe(PRICE_FIELD), - budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to transport type)'), + price: bookingPriceSchema.optional().describe(PRICE_FIELD), + budget_category: bookingBudgetCategorySchema.optional().describe('Budget category for the price entry (defaults to transport type)'), }, annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, access: { group: 'reservations', mode: 'write' }, diff --git a/server/src/nest/reservations/reservations.module.ts b/server/src/nest/reservations/reservations.module.ts index 385e49c30..9a4207e79 100644 --- a/server/src/nest/reservations/reservations.module.ts +++ b/server/src/nest/reservations/reservations.module.ts @@ -84,7 +84,8 @@ import { Module } from '@nestjs/common'; // ReservationWritesService: the booking use cases the controller and the MCP tools share. // ReservationsReadMcp: the assistant's read of the bookings with their readable details. providers: [ReservationsService, ReservationWritesService, ReservationsMcp, ReservationsReadMcp, ReservationsRpc], - // For in-container consumers (ReservationsRpc, TripsService, BookingImportService). - exports: [ReservationsService], + // For in-container consumers (ReservationsRpc, TripsService, BookingImportService); + // ReservationWritesService for TransitMcp's create_transit_journey. + exports: [ReservationsService, ReservationWritesService], }) export class ReservationsModule {} diff --git a/server/src/nest/transit/transit.mcp.ts b/server/src/nest/transit/transit.mcp.ts index 537fe103b..f102be81c 100644 --- a/server/src/nest/transit/transit.mcp.ts +++ b/server/src/nest/transit/transit.mcp.ts @@ -10,7 +10,7 @@ import { import { RateLimitService } from '../common/rate-limit.service'; import { DaysService } from '../days/days.service'; import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; -import { ReservationsService } from '../reservations/reservations.service'; +import { ReservationWritesService } from '../reservations/reservation-writes.service'; import { TripAccessService } from '../trip-membership/trip-access.service'; import { buildTransitReservationParts, @@ -22,7 +22,13 @@ import { } from './transit-itinerary.helpers'; import { SCHEDULED_TRANSIT_MODES, type TransitItinerary } from './transit.helpers'; import { TransitService } from './transit.service'; -import { adminTransitProviderRequestSchema, idSchema, type TransitProvider } from '@trek/shared'; +import { + adminTransitProviderRequestSchema, + bookingBudgetCategorySchema, + bookingPriceSchema, + idSchema, + type TransitProvider, +} from '@trek/shared'; import { z } from 'zod'; @@ -66,7 +72,7 @@ export class TransitMcp { constructor( private readonly transit: TransitService, private readonly days: DaysService, - private readonly reservations: ReservationsService, + private readonly writes: ReservationWritesService, // Plan 4 Task 2 — canAccessTrip's own DatabaseService delegation is gone: // this injects TripAccessService (trip-membership) (same constructor slot) and // calls findAccessible. @@ -178,7 +184,7 @@ export class TransitMcp { @Tool({ name: 'create_transit_journey', description: - 'Add one itinerary returned by search_transit_routes to a trip day as a first-class automated public-transit journey. Pass the search response provider unchanged so fallback routes retain their source.', + 'Add one itinerary returned by search_transit_routes to a trip day as a first-class automated public-transit journey. Pass the search response provider unchanged so fallback routes retain their source. Set price to record the fare; it will appear on the journey and in the Budget tab.', inputSchema: { tripId: idSchema, dayId: idSchema.describe('Trip day on which the journey departs'), @@ -189,6 +195,10 @@ export class TransitMcp { .optional() .describe('Provider returned by search_transit_routes'), notes: z.string().max(1000).optional(), + price: bookingPriceSchema.optional().describe('Fare — shown on the journey and linked in the Budget tab'), + budget_category: bookingBudgetCategorySchema + .optional() + .describe('Budget category for the fare entry (defaults to transit)'), }, annotations: TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT, access: { group: 'reservations', mode: 'write' }, @@ -202,6 +212,8 @@ export class TransitMcp { itinerary, provider, notes, + price, + budget_category, }: { tripId: number; dayId: number; @@ -212,6 +224,8 @@ export class TransitMcp { itinerary: TransitItinerary; provider?: TransitProvider; notes?: string; + price?: number; + budget_category?: string; }, ctx: McpContext, ) { @@ -268,21 +282,28 @@ export class TransitMcp { isError: true, }; } - const { reservation } = await this.reservations.create(tripId, { - title: `${from.name} → ${to.name}`, - type: 'transit', - status: 'confirmed', - day_id: dayId, - end_day_id: endDay.id, - reservation_time: `${departure.local_date}T${departure.local_time}`, - reservation_end_time: `${arrival.local_date}T${arrival.local_time}`, - notes, - metadata, - endpoints, - needs_review: false, - }); - this.guards.safeBroadcast(tripId, 'reservation:created', { reservation }); - await this.reservations.notifyBookingChange(tripId, ctx.userId, reservation.title, reservation.type || ''); + // The fare files the linked expense in the booking's own transaction and + // rides along in the metadata, as create_transport's price does. + const linkedCost = + price != null && price > 0 ? { total_price: price, category: budget_category || 'transit' } : undefined; + const { reservation } = await this.writes.createBooking( + String(tripId), + { + title: `${from.name} → ${to.name}`, + type: 'transit', + status: 'confirmed', + day_id: dayId, + end_day_id: endDay.id, + reservation_time: `${departure.local_date}T${departure.local_time}`, + reservation_end_time: `${arrival.local_date}T${arrival.local_time}`, + notes, + metadata: price != null ? { ...metadata, price: String(price) } : metadata, + endpoints, + needs_review: false, + }, + linkedCost, + await this.guards.tripWriter(tripId, ctx.userId), + ); return ok({ reservation }); } } diff --git a/server/tests/unit/mcp/tools-budget.test.ts b/server/tests/unit/mcp/tools-budget.test.ts index 554c5a811..c1f5f3970 100644 --- a/server/tests/unit/mcp/tools-budget.test.ts +++ b/server/tests/unit/mcp/tools-budget.test.ts @@ -893,6 +893,104 @@ describe('Budget tools: place link', () => { }); }); +// --------------------------------------------------------------------------- +// A new expense linked to a booking, the MCP twin of POST /budget with +// reservation_id +// --------------------------------------------------------------------------- + +describe('Budget tools: booking link on create', () => { + async function metadataOf(reservationId: number): Promise> { + const row = await findRow(orm, Reservations, { id: reservationId }); + if (!row) throw new Error(`no reservation ${reservationId}`); + return row.metadata ? JSON.parse(row.metadata) : {}; + } + + it('create_budget_item links the expense to a booking, which mirrors its total', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const booking = createReservation(testDb, trip.id, { title: 'Flight' }); + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'create_budget_item', + arguments: { tripId: trip.id, name: 'Fare', total_price: 180, reservation_id: booking.id }, + }); + const data = parseToolResult(result) as { item: { id: number } }; + expect((await itemRow(data.item.id)).reservation_id).toBe(booking.id); + expect(await metadataOf(booking.id)).toEqual({ price: '180' }); + expect(broadcastMock.mock.calls.some((c) => c[1] === 'budget:created')).toBe(true); + expect(broadcastMock.mock.calls.some((c) => c[1] === 'reservation:updated')).toBe(true); + }); + }); + + it('create_budget_item adds a second expense to a booking, which then mirrors their sum', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const booking = createReservation(testDb, trip.id, { title: 'Flight' }); + await withHarness(user.id, async (h) => { + const add = (name: string, total_price: number) => + h.client.callTool({ + name: 'create_budget_item', + arguments: { tripId: trip.id, name, total_price, reservation_id: booking.id }, + }); + await add('Fare', 180); + await add('Seat upgrade', 35.5); + expect(await metadataOf(booking.id)).toEqual({ price: '215.5' }); + }); + }); + + it('create_budget_item refuses a booking from another trip and writes nothing', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const elsewhere = createTrip(testDb, user.id); + const foreign = createReservation(testDb, elsewhere.id); + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'create_budget_item', + arguments: { tripId: trip.id, name: 'Fare', total_price: 180, reservation_id: foreign.id }, + }); + expect(result.isError).toBe(true); + expect(errorText(result)).toBe('reservation_id does not belong to this trip.'); + expect(await itemCount(trip.id)).toBe(0); + }); + expect(await metadataOf(foreign.id)).toEqual({}); + }); + + it('create_budget_item_with_members links the expense to a booking', async () => { + const { user, other, trip } = tripWithTwo(); + const booking = createReservation(testDb, trip.id, { title: 'Train' }); + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'create_budget_item_with_members', + arguments: { + tripId: trip.id, + name: 'Tickets', + total_price: 68, + userIds: [user.id, other.id], + reservation_id: booking.id, + }, + }); + const data = parseToolResult(result) as { item: { id: number } }; + expect((await itemRow(data.item.id)).reservation_id).toBe(booking.id); + expect(await metadataOf(booking.id)).toEqual({ price: '68' }); + }); + }); + + it('create_budget_item_with_members refuses a booking from another trip', async () => { + const { user, trip } = tripWithTwo(); + const elsewhere = createTrip(testDb, user.id); + const foreign = createReservation(testDb, elsewhere.id); + await withHarness(user.id, async (h) => { + const result = await h.client.callTool({ + name: 'create_budget_item_with_members', + arguments: { tripId: trip.id, name: 'Tickets', total_price: 68, reservation_id: foreign.id }, + }); + expect(result.isError).toBe(true); + expect(errorText(result)).toBe('reservation_id does not belong to this trip.'); + expect(await itemCount(trip.id)).toBe(0); + }); + }); +}); + // --------------------------------------------------------------------------- // Linking an existing expense to a booking or a place (#2084), the MCP twin of // PUT /budget/:id with reservation_id / place_id diff --git a/server/tests/unit/mcp/tools-transit.test.ts b/server/tests/unit/mcp/tools-transit.test.ts index de7e8eacf..78fba5acb 100644 --- a/server/tests/unit/mcp/tools-transit.test.ts +++ b/server/tests/unit/mcp/tools-transit.test.ts @@ -1,4 +1,5 @@ import { db as testDb } from '../../../src/db/database'; +import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity'; import { Days } from '../../../src/db/entities/Days.entity'; import { Reservations } from '../../../src/db/entities/Reservations.entity'; import { invalidatePermissionsCache } from '../../../src/nest/permissions/permissions-cache'; @@ -256,7 +257,49 @@ describe('MCP transit tools', () => { expect(metadata.transit.walk_seconds).toBe(300); expect(metadata.transit.legs[1].line_color).toBe('#E5171F'); expect(broadcastMock).toHaveBeenCalledWith(trip.id, 'reservation:created', expect.anything()); - expect(notifyBookingChangeMock).toHaveBeenCalledWith(trip.id, user.id, 'Namba → Umeda', 'transit'); + expect(notifyBookingChangeMock).toHaveBeenCalledWith(String(trip.id), user.id, 'Namba → Umeda', 'transit'); + }); + }); + + it('files the fare as a linked expense and mirrors it in the metadata', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const day = await dayOf(trip.id, '2026-12-03'); + await withHarness(user.id, ['reservations:write'], async (harness) => { + const result = parseToolResult( + await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary, price: 240 }, + }), + ) as { reservation: { id: number; metadata: string } }; + const item = await findRow(orm, BudgetItems, { reservation: result.reservation.id }); + expect(item).toMatchObject({ name: 'Namba → Umeda', category: 'transit', total_price: 240 }); + expect(JSON.parse(result.reservation.metadata).price).toBe('240'); + expect(broadcastMock.mock.calls.some((c) => c[1] === 'budget:created')).toBe(true); + expect(broadcastMock.mock.calls.some((c) => c[1] === 'reservation:created')).toBe(true); + }); + }); + + it('files the fare under the given budget category, and records none for a free journey', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id, { start_date: '2026-12-03', end_date: '2026-12-04' }); + const day = await dayOf(trip.id, '2026-12-03'); + await withHarness(user.id, ['reservations:write'], async (harness) => { + const paid = parseToolResult( + await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary, price: 230, budget_category: 'Transport' }, + }), + ) as { reservation: { id: number; metadata: string } }; + expect((await findRow(orm, BudgetItems, { reservation: paid.reservation.id }))?.category).toBe('Transport'); + + const free = parseToolResult( + await harness.client.callTool({ + name: 'create_transit_journey', + arguments: { tripId: trip.id, dayId: day.id, from, to, itinerary, price: 0 }, + }), + ) as { reservation: { id: number; metadata: string } }; + expect(await findRow(orm, BudgetItems, { reservation: free.reservation.id })).toBeNull(); }); }); diff --git a/shared/src/reservation/reservation.schema.ts b/shared/src/reservation/reservation.schema.ts index a0a3b47bf..56c64bb8c 100644 --- a/shared/src/reservation/reservation.schema.ts +++ b/shared/src/reservation/reservation.schema.ts @@ -245,6 +245,14 @@ export const reservationUrlSchema = z.string().refine( { message: 'must not be a javascript:, data: or vbscript: URL' }, ); +/** + * The price an MCP booking tool takes and files as the booking's linked expense + * (create_reservation, create_transport, create_transit_journey), and the budget + * category of that expense. + */ +export const bookingPriceSchema = z.number().nonnegative(); +export const bookingBudgetCategorySchema = z.string().max(100); + /** Reservation create: title is required; the many optional fields stay open. */ export const reservationCreateRequestSchema = open.and( z.object({ diff --git a/wiki/MCP-Tools-and-Resources.md b/wiki/MCP-Tools-and-Resources.md index f17121b65..788aadbf2 100644 --- a/wiki/MCP-Tools-and-Resources.md +++ b/wiki/MCP-Tools-and-Resources.md @@ -24,7 +24,7 @@ Compound tools collapse multi-step workflows into a single atomic transaction. I |---|---|---| | `create_and_assign_place` | `create_place` + `assign_place_to_day` | Create a place and assign it to a day. Takes the same place fields as `create_place`, `stop_type` included. Returns `{ place, assignment }`. Requires `places:write`. | | `create_place_accommodation` | `create_place` + `create_accommodation` | Create a place and book it as an accommodation. Returns `{ place, accommodation }`. Requires `trips:write`. | -| `create_budget_item_with_members` | `create_budget_item` + `set_budget_item_members` | Create a budget item and set splitting members. If `userIds` is omitted or empty, the cost is split across all trip members, like `create_budget_item` without `member_ids`. Returns `{ item }`. Requires `budget:write`. | +| `create_budget_item_with_members` | `create_budget_item` + `set_budget_item_members` | Create a budget item and set splitting members. If `userIds` is omitted or empty, the cost is split across all trip members, like `create_budget_item` without `member_ids`. Takes the same `reservation_id` / `place_id` links. Returns `{ item }`. Requires `budget:write`. | ### Trips @@ -134,7 +134,7 @@ Transit search is powered by the configured transit provider (Transitous by defa |---|---|---| | `search_transit_stops` | `geo:read` | Search real public-transit stops and stations, optionally biased around coordinates. | | `search_transit_routes` | `geo:read` | Search scheduled routes between two coordinates with time, mode, and transfer filters. Also returns `provider` (`transitous` or `google`, the backend that answered) and `dropped`, the number of provider itineraries that failed validation and are absent from the results. | -| `create_transit_journey` | `reservations:write` | Save a selected route as a first-class automated transit journey on a trip day. Pass `provider` from `search_transit_routes` to preserve the actual source, including fallback results. Older callers that omit it retain the configured-provider behavior. | +| `create_transit_journey` | `reservations:write` | Save a selected route as a first-class automated transit journey on a trip day. Pass `provider` from `search_transit_routes` to preserve the actual source, including fallback results. Older callers that omit it retain the configured-provider behavior. `price` records the fare as an expense linked to the journey (`budget_category`, `transit` by default). | ### Reservations @@ -159,7 +159,7 @@ Requires `budget:read` or `budget:write` scope. The Budget addon must be enabled |---|---| | `list_budget_items` | The trip's expenses with their ids, a page at a time (`offset`, `limit` up to 100, 50 by default). A page of long expenses ends earlier, so a client goes on at `next_offset` until it is `null`. Per expense: name, category, price and currency, date, the start of its note, the linked place or booking, who paid how much and who shares it, what a foreign expense comes to in the trip currency (`trip_amount`) and how many receipts it has (`receipt_count`). Next to the page the trip currency, the total and the totals per category over all expenses, and `unconverted_item_ids` for foreign expenses no rate converts. | | `get_budget_per_person` | What each person's shares of the expenses add up to and how much of that they paid, in the trip currency, as the per-person summary in the app shows it. | -| `create_budget_item` | Add an expense with name, category, and price. | +| `create_budget_item` | Add an expense with name, category, and price. `reservation_id` / `place_id` link it to a booking or place of the same trip. | | `update_budget_item` | Update an expense's details, split (persons/days), or notes. `reservation_id` / `place_id` link it to a booking or place of the same trip; `null` unlinks it. | | `delete_budget_item` | Remove a budget item. | | `set_budget_item_members` | Set which members are splitting a budget item (replaces current list). |