feat(assistant): expenses, shares, wind, journey tracks and Dawarich checks as MCP tools

- list_budget_items lists a trip's expenses with their ids, payers and
  splits, page by page so no page is cut down on its way to a model;
  get_budget_per_person answers who paid and owes what. Both in a new
  budget-items.mcp.ts, checked like their REST twins.
- get_wind_forecast reads the hourly wind, gusts and direction of a day.
- get_journey_tracks lists a journey's GPX tracks; the line for drawing
  rides under a key the provider never receives.
- The Dawarich wishlist scan and the countries the recordings suggest
  become tools, with their confirming writes, in DawarichAtlasMcp in the
  Atlas group; the shared time window check refuses alike on REST and
  MCP, and the model never sees when the user was last seen in a city.
- The journal's map, tracks and recorded days load with the journey
  group instead of riding in the core of every step.
- The prompt points at list_budget_items for expense ids (the trip
  summary never carried them) and names the shares and the wind tools;
  each new read has its own live step.
This commit is contained in:
Maurice
2026-10-22 00:03:19 +00:00
parent 3c0f324266
commit 6d6efddc4e
63 changed files with 2418 additions and 51 deletions
+77
View File
@@ -13,10 +13,13 @@ import { BudgetSettlements } from '../../src/db/entities/BudgetSettlements.entit
import { Reservations } from '../../src/db/entities/Reservations.entity';
import { TripMembers } from '../../src/db/entities/TripMembers.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
import type { McpContext } from '../../src/nest-mcp';
import { BudgetItemsMcp } from '../../src/nest/budget/budget-items.mcp';
import { BudgetModule } from '../../src/nest/budget/budget.module';
import { ExchangeRatesService } from '../../src/nest/budget/exchange-rates.service';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { withRequestContext } from '../../src/nest/database/request-context';
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
@@ -29,6 +32,7 @@ import { makeUser } from '../helpers/factories/users';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
@@ -861,4 +865,77 @@ describe('Budget e2e (real auth guard + temp SQLite, real budget SQL)', () => {
expect(balances.find((b) => b.user_id === 3)?.balance).toBe(0);
});
});
describe('the read tools over MCP', () => {
let mcpTripId: number;
const asUser = (userId: number) => ({ userId }) as McpContext;
const call = <T>(fn: () => Promise<T>) => withRequestContext(app.get(MikroORM), fn);
const text = (result: { content: { text: string }[] }) => JSON.parse(result.content[0]?.text ?? '');
beforeAll(async () => {
mcpTripId = (await makeTrip(orm, 1, { title: 'MCP Trip', currency: 'EUR' })).id;
await addTripMember(orm, mcpTripId, 2);
await makeUser(orm, {
id: 6,
username: 'e2e-mcp-outsider',
email: 'mcp-outsider@example.test',
password_version: 0,
});
});
it('BUDGET-E2E-001: list_budget_items answers the expenses REST lists, in its order, with the trip totals', async () => {
const create = (body: object) =>
request(server).post(`/api/trips/${mcpTripId}/budget`).set('Cookie', sessionCookie(1)).send(body);
// One after the other, so the list order is the order they were made in.
const ferry = await create({ name: 'Ferry', category: 'transport', total_price: 60, member_ids: [1, 2] });
const diner = await create({
name: 'Diner',
category: 'food',
currency: 'USD',
exchange_rate: 1.2,
payers: [{ user_id: 2, amount: 36 }],
});
expect([ferry.status, diner.status]).toEqual([201, 201]);
const rest = await request(server).get(`/api/trips/${mcpTripId}/budget`).set('Cookie', sessionCookie(1));
expect(rest.status).toBe(200);
const tool = text(await call(() => app.get(BudgetItemsMcp).listBudgetItems({ tripId: mcpTripId }, asUser(2))));
type RestItem = { id: number; name: string; total_price: number; currency: string | null; members: unknown[] };
expect(tool.items.map((item: { id: number }) => item.id)).toEqual(rest.body.items.map((i: RestItem) => i.id));
expect(tool.items.map((item: { name: string; total_price: number }) => [item.name, item.total_price])).toEqual(
rest.body.items.map((i: RestItem) => [i.name, i.total_price]),
);
// 60 EUR and 36 USD at 1.2: 30 EUR.
expect(tool).toMatchObject({ currency: 'EUR', total: 90, item_count: 2, next_offset: null });
});
it('BUDGET-E2E-002: get_budget_per_person answers exactly what the per-person route answers', async () => {
const rest = await request(server)
.get(`/api/trips/${mcpTripId}/budget/summary/per-person`)
.set('Cookie', sessionCookie(1));
expect(rest.status).toBe(200);
const tool = text(await call(() => app.get(BudgetItemsMcp).getBudgetPerPerson({ tripId: mcpTripId }, asUser(1))));
expect(tool).toEqual(rest.body);
expect(tool.summary.length).toBeGreaterThan(0);
});
it('BUDGET-E2E-003: someone off the trip gets the REST 404 and the MCP trip refusal from both tools', async () => {
const rest = await request(server).get(`/api/trips/${mcpTripId}/budget`).set('Cookie', sessionCookie(6));
expect(rest.status).toBe(404);
const mcp = app.get(BudgetItemsMcp);
for (const result of [
await call(() => mcp.listBudgetItems({ tripId: mcpTripId }, asUser(6))),
await call(() => mcp.getBudgetPerPerson({ tripId: mcpTripId }, asUser(6))),
]) {
expect(result).toEqual({
content: [{ type: 'text', text: 'Trip not found or access denied.' }],
isError: true,
});
}
});
});
});
+134 -2
View File
@@ -15,21 +15,31 @@
* 401, the shape of a connection nobody has configured, the two URL rejections
* that need no DNS, the suggestions envelope's `connected: false`, and the
* cross-user isolation — someone else's suggestion is invisible and untouchable
* through your own session, and answers the same 404 a missing one does.
* through your own session, and answers the same 404 a missing one does. The
* bucket-list and Atlas tools of DawarichAtlasMcp run next to their routes on
* the same container, so the two channels are held to the same answers.
*/
import { db } from '../../src/db/database';
import { BucketList } from '../../src/db/entities/BucketList.entity';
import { DawarichConnections } from '../../src/db/entities/DawarichConnections.entity';
import { DawarichVisitSuggestions } from '../../src/db/entities/DawarichVisitSuggestions.entity';
import { VisitedCountries } from '../../src/db/entities/VisitedCountries.entity';
import { trekMcpErrorMapper } from '../../src/mcp/nest-mcp-policy';
import type { McpContext, McpTextResult } from '../../src/nest-mcp';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { DawarichClient } from '../../src/nest/integrations/dawarich.client';
import { withRequestContext } from '../../src/nest/database/request-context';
import { DawarichAtlasMcp } from '../../src/nest/integrations/dawarich-atlas.mcp';
import { DawarichClient, DawarichError } from '../../src/nest/integrations/dawarich.client';
import { DawarichModule } from '../../src/nest/integrations/dawarich.module';
import { createUser } from '../helpers/factories';
import { makeBucketListItem } from '../helpers/factories/atlas';
import { countRows, deleteRows, findRow, insertRow } from '../helpers/factories/rows';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
@@ -377,4 +387,126 @@ describe('Dawarich e2e (real addon gate + real auth guard + real services + temp
expect(res.body.state).toBe('dismissed');
expect((await findRow(orm, DawarichVisitSuggestions, { id: mine }))?.state).toBe('dismissed');
});
// ── Bucket list and Atlas over MCP: the same services, the same answers ──
const asUser = (userId: number) => ({ userId, scopes: null, isStaticToken: false }) as McpContext;
const viaMcp = <T>(fn: (mcp: DawarichAtlasMcp) => Promise<T>) =>
withRequestContext(app.get(MikroORM), () => fn(app.get(DawarichAtlasMcp)));
const answerOf = (result: McpTextResult) => JSON.parse(result.content[0]?.text ?? '');
it('DAWARICH-E2E-040: a wish ticked off over MCP is ticked off for REST, and only its owner can clear it', async () => {
const wish = await makeBucketListItem(orm, ownerId, { name: 'Alhambra', lat: 37.176, lng: -3.588 });
const confirmed = await viaMcp((mcp) =>
mcp.confirmBucketVisits({ itemIds: [wish.id], visitedAt: '2024-04-02T10:00:00Z' }, asUser(ownerId)),
);
expect(answerOf(confirmed)).toEqual({ updated: 1 });
const again = await request(server)
.post('/api/integrations/dawarich/bucket-list/confirm')
.set('Cookie', sessionCookie(ownerId))
.send({ itemIds: [wish.id] });
expect(again.status).toBe(200);
expect(again.body).toEqual({ updated: 0 });
expect(await findRow(orm, BucketList, { id: wish.id })).toMatchObject({
visited_at: '2024-04-02T10:00:00Z',
visited_source: 'dawarich',
});
const foreign = await viaMcp((mcp) => mcp.clearBucketVisit({ itemId: wish.id }, asUser(strangerId)));
expect(foreign).toEqual({ content: [{ type: 'text', text: 'Bucket-list entry not found' }], isError: true });
const foreignRest = await request(server)
.delete(`/api/integrations/dawarich/bucket-list/${wish.id}/visit`)
.set('Cookie', sessionCookie(strangerId));
expect(foreignRest.status).toBe(404);
expect(foreignRest.body).toEqual({ error: 'Bucket-list entry not found' });
expect(answerOf(await viaMcp((mcp) => mcp.clearBucketVisit({ itemId: wish.id }, asUser(ownerId))))).toEqual({
success: true,
});
expect(await findRow(orm, BucketList, { id: wish.id })).toMatchObject({ visited_at: null, visited_source: null });
});
it('DAWARICH-E2E-041: countries accepted over MCP land in the Atlas once, as REST then finds them', async () => {
const marked = await viaMcp((mcp) => mcp.acceptAtlasCountries({ countryCodes: ['PT', 'es'] }, asUser(ownerId)));
expect(answerOf(marked)).toEqual({ marked: 2 });
const again = await request(server)
.post('/api/integrations/dawarich/atlas/accept')
.set('Cookie', sessionCookie(ownerId))
.send({ countryCodes: ['PT', 'ES'] });
expect(again.status).toBe(200);
expect(again.body).toEqual({ marked: 0 });
expect(await countRows(orm, VisitedCountries, { user: ownerId, source: 'dawarich' })).toBe(2);
});
it('DAWARICH-E2E-042: without a connection both reads refuse alike, and a backwards window is the route 400 before anything is asked', async () => {
const scan = await request(server)
.post('/api/integrations/dawarich/bucket-list/scan')
.set('Cookie', sessionCookie(ownerId));
expect(scan.status).toBe(400);
expect(scan.body).toEqual({ error: 'Dawarich is not connected', code: 'not_connected' });
expect(await viaMcp((mcp) => mcp.scanBucketList({}, asUser(ownerId)))).toEqual({
content: [{ type: 'text', text: 'Dawarich is not connected' }],
isError: true,
});
const window = { from: '2026-01-01T00:00:00Z', to: '2026-03-01T00:00:00Z' };
const suggestions = await request(server)
.get('/api/integrations/dawarich/atlas/suggestions')
.query(window)
.set('Cookie', sessionCookie(ownerId));
expect(suggestions.status).toBe(400);
expect(suggestions.body).toEqual({ error: 'Dawarich is not connected', code: 'not_connected' });
expect(await viaMcp((mcp) => mcp.suggestAtlasCountries(window, asUser(ownerId)))).toEqual({
content: [{ type: 'text', text: 'Dawarich is not connected' }],
isError: true,
});
const backwards = { from: window.to, to: window.from };
const refused = await request(server)
.get('/api/integrations/dawarich/atlas/suggestions')
.query(backwards)
.set('Cookie', sessionCookie(ownerId));
expect(refused.status).toBe(400);
expect(refused.body).toEqual({ error: 'to must be after from' });
const thrown = await viaMcp((mcp) => mcp.suggestAtlasCountries(backwards, asUser(ownerId))).then(
() => undefined,
(err: unknown) => err,
);
expect(thrown).toMatchObject({ status: 400, publicMessage: 'to must be after from' });
// The tool call answers with the route's sentence: the registry maps the refusal to an error result.
expect(trekMcpErrorMapper(thrown)).toEqual({
content: [{ type: 'text', text: 'to must be after from' }],
isError: true,
});
});
it('DAWARICH-E2E-043: an instance that does not answer ends a scan after one lookup: the route 502 and the same sentence over MCP', async () => {
await insertRow(orm, DawarichConnections, {
user: ownerId,
url: 'https://dawarich.example',
api_key: 'plain-legacy-key',
});
await Promise.all(
['Alhambra', 'Petra'].map((name) => makeBucketListItem(orm, ownerId, { name, lat: 37.176, lng: -3.588 })),
);
const findVisitsNear = vi.mocked(app.get(DawarichClient).findVisitsNear);
findVisitsNear.mockClear();
const down = () => new DawarichError('unreachable', 'Could not reach Dawarich', undefined, 'ETIMEDOUT');
findVisitsNear.mockRejectedValueOnce(down()).mockRejectedValueOnce(down());
const scan = await request(server)
.post('/api/integrations/dawarich/bucket-list/scan')
.set('Cookie', sessionCookie(ownerId));
expect(scan.status).toBe(502);
expect(scan.body).toEqual({ error: 'Could not reach Dawarich', code: 'unreachable', detail: 'ETIMEDOUT' });
expect(await viaMcp((mcp) => mcp.scanBucketList({}, asUser(ownerId)))).toEqual({
content: [{ type: 'text', text: 'Could not reach Dawarich' }],
isError: true,
});
// One lookup per channel, not one per wish.
expect(findVisitsNear).toHaveBeenCalledTimes(2);
await deleteRows(orm, BucketList, { user: ownerId });
});
});
+58
View File
@@ -5,6 +5,7 @@
* ordering (404 wins over 401), auth, the service-owned 403/404 mapping, status
* codes and the unguarded public route.
*/
import type { McpContext } from '../../src/nest-mcp';
import { AddonsService } from '../../src/nest/addons/addons.service';
import { notFound } from '../../src/nest/common/domain-error';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
@@ -13,6 +14,7 @@ import { JourneyBookService } from '../../src/nest/journey/journey-book.service'
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
import { JourneyMapService } from '../../src/nest/journey/journey-map.service';
import { JourneyShareService } from '../../src/nest/journey/journey-share.service';
import { JourneyTracksMcp } from '../../src/nest/journey/journey-tracks.mcp';
import { JourneyModule } from '../../src/nest/journey/journey.module';
import { PhotoCaptureBackfillService } from '../../src/nest/memories/photo-capture-backfill.service';
import { StorageService } from '../../src/nest/storage/storage.service';
@@ -102,6 +104,7 @@ const { jsvc } = vi.hoisted(() => ({
uploadGalleryPhotos: vi.fn(),
broadcastJourneyEvent: vi.fn(),
journeyIdOfEntry: vi.fn(),
journeyTracks: vi.fn(),
},
}));
@@ -616,4 +619,59 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
expect(missing.status).toBe(404);
expect(missing.body).toEqual({ error: 'Not found' });
});
// ── GPX tracks: the route and get_journey_tracks read the same service ────
const TRACK = {
place_id: 4,
trip_id: 2,
name: 'Lagoon loop',
color: '#1971c2',
points: [
[45.43, 12.33],
[45.44, 12.34],
] as [number, number][],
};
const asMcp = { userId: 1 } as McpContext;
it('JOURNEY-E2E-001: the tracks route and get_journey_tracks answer the same tracks, the tool by size with a thinned line', async () => {
jsvc.journeyTracks.mockReset();
jsvc.journeyTracks.mockResolvedValue([TRACK]);
const res = await request(server).get('/api/journeys/9/tracks').set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ tracks: [TRACK] });
const tool = await app.get(JourneyTracksMcp).getJourneyTracks({ journeyId: 9 }, asMcp);
expect(JSON.parse(tool.content[0]?.text ?? '')).toEqual({
tracks: [
{
place_id: 4,
trip_id: 2,
name: 'Lagoon loop',
kind: 'trip_gpx',
color: '#1971c2',
point_count: 2,
distance_km: 1.4,
display_geometry: TRACK.points,
},
],
});
expect(jsvc.journeyTracks.mock.calls).toEqual([
[9, 1],
[9, 1],
]);
});
it('JOURNEY-E2E-002: a journey out of reach is a 404 on the route and the journey refusal over MCP', async () => {
jsvc.journeyTracks.mockReset();
jsvc.journeyTracks.mockResolvedValue(null);
const res = await request(server).get('/api/journeys/9/tracks').set('Cookie', sessionCookie(1));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Journey not found' });
const tool = await app.get(JourneyTracksMcp).getJourneyTracks({ journeyId: 9 }, asMcp);
expect(tool).toEqual({ content: [{ type: 'text', text: 'Journey not found or access denied.' }], isError: true });
});
});
+61
View File
@@ -3,8 +3,13 @@
* real JwtAuthGuard against a temp SQLite db (seeded via the shared harness).
* The weather service is mocked so no real Open-Meteo calls happen.
*/
import type { McpContext } from '../../src/nest-mcp';
import { DomainError } from '../../src/nest/common/domain-error';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { WeatherMcp } from '../../src/nest/weather/weather.mcp';
import { WeatherModule } from '../../src/nest/weather/weather.module';
import { WIND_UNAVAILABLE_MESSAGE, WindService } from '../../src/nest/weather/wind.service';
import { createTestMikroOrmModule } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { createTempDb, seedUser, sessionCookie } from './harness';
@@ -49,6 +54,8 @@ describe('Weather e2e (real auth guard + temp SQLite)', () => {
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalFilters(new TrekExceptionFilter());
// Mirror the production APP_PIPE: the wind route's DTO query is coerced as under buildApp().
nest.useGlobalPipes(new ZodValidationPipe());
await nest.init();
return nest;
}
@@ -103,4 +110,58 @@ describe('Weather e2e (real auth guard + temp SQLite)', () => {
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ type: 'forecast' });
});
// ── Wind: GET /wind and get_wind_forecast ask the one service alike ───────
const WIND = {
status: 'forecast' as const,
date: '2026-07-01',
lat: 38.7,
lng: -9.1,
timezone: 'Europe/Lisbon',
source: 'Open-Meteo' as const,
fetched_at: '2026-06-30T08:00:00.000Z',
horizon_days: 16,
hours: [{ hour: 14, speed_kmh: 22, gusts_kmh: 38, direction_deg: 320 }],
day: { speed_max_kmh: 22, gusts_max_kmh: 38, direction_dominant_deg: 320 },
};
const asMcp = { userId: 1 } as McpContext;
it('WEATHER-E2E-001: the wind route and get_wind_forecast answer the same forecast for the same query', async () => {
const forecast = vi.spyOn(app.get(WindService), 'forecast').mockResolvedValue(WIND);
const res = await request(server)
.get('/api/weather/wind')
.set('Cookie', sessionCookie(1))
.query({ lat: '38.7', lng: '-9.1', date: '2026-07-01' });
expect(res.status).toBe(200);
expect(res.body).toEqual(WIND);
const tool = await app.get(WeatherMcp).getWindForecast({ lat: 38.7, lng: -9.1, date: '2026-07-01' }, asMcp);
expect(JSON.parse(tool.content[0]?.text ?? '')).toEqual({ wind: WIND });
expect(forecast.mock.calls).toEqual([
[{ lat: 38.7, lng: -9.1, date: '2026-07-01' }],
[{ lat: 38.7, lng: -9.1, date: '2026-07-01' }],
]);
forecast.mockRestore();
});
it('WEATHER-E2E-002: a failed source is the 502 sentence on the route and the same sentence as a refusal over MCP', async () => {
const failure = new DomainError(502, WIND_UNAVAILABLE_MESSAGE, {
code: 'wind_unavailable',
details: { code: 'wind_unavailable' },
});
const forecast = vi.spyOn(app.get(WindService), 'forecast').mockRejectedValue(failure);
const res = await request(server)
.get('/api/weather/wind')
.set('Cookie', sessionCookie(1))
.query({ lat: '38.7', lng: '-9.1', date: '2026-07-01' });
expect(res.status).toBe(502);
expect(res.body).toEqual({ error: WIND_UNAVAILABLE_MESSAGE, code: 'wind_unavailable' });
const tool = await app.get(WeatherMcp).getWindForecast({ lat: 38.7, lng: -9.1, date: '2026-07-01' }, asMcp);
expect(tool).toEqual({ content: [{ type: 'text', text: WIND_UNAVAILABLE_MESSAGE }], isError: true });
forecast.mockRestore();
});
});