mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
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:
@@ -0,0 +1,130 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
type McpContext,
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
errorResult,
|
||||
ok,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { DawarichSuggestionsService } from './dawarich-suggestions.service';
|
||||
import { parseTimeWindow } from './dawarich.helpers';
|
||||
import { dawarichToolResult } from './dawarich.mcp';
|
||||
import {
|
||||
DAWARICH_BUCKET_MATCH_MIN_MINUTES,
|
||||
DAWARICH_BUCKET_MATCH_RADIUS_M,
|
||||
DAWARICH_BUCKET_SCAN_LIMIT,
|
||||
DAWARICH_WINDOW_MAX_DAYS,
|
||||
dawarichAtlasAcceptSchema,
|
||||
dawarichBucketConfirmSchema,
|
||||
dawarichTimeWindowSchema,
|
||||
idSchema,
|
||||
type DawarichAtlasAccept,
|
||||
type DawarichBucketConfirm,
|
||||
type DawarichTimeWindow,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Same gate as the controller's @RequireAddon(ADDON_IDS.DAWARICH): no addon, no tool. */
|
||||
const dawarichAddonOn = addonGate(ADDON_IDS.DAWARICH);
|
||||
|
||||
/**
|
||||
* The bucket list and the Atlas checked against the Dawarich recordings: the
|
||||
* twins of `/api/integrations/dawarich/bucket-list/*` and `/atlas/*`, on the
|
||||
* same service calls.
|
||||
*
|
||||
* Their own class rather than a part of DawarichMcp, because what they read
|
||||
* and write is the Atlas: the assistant loads them with the atlas tools, where
|
||||
* a question about the bucket list or the visited countries goes, while the
|
||||
* stays and the recorded route stay with the journal.
|
||||
*
|
||||
* Reading the recordings to offer wishes and countries is `atlas:read`, as the
|
||||
* answer is about the Atlas; ticking off and marking write it, `atlas:write`.
|
||||
* Like the routes the tools work on the caller's own data and take no trip,
|
||||
* and a refusal reads as the route's error sentence.
|
||||
*/
|
||||
@McpController()
|
||||
export class DawarichAtlasMcp {
|
||||
constructor(
|
||||
private readonly suggestions: DawarichSuggestionsService,
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'scan_bucket_list_visits',
|
||||
description: `Ask the caller's Dawarich recordings, wish by wish, whether they ever reached the places on their bucket list. A wish counts as reached by a stay of at least ${DAWARICH_BUCKET_MATCH_MIN_MINUTES} minutes within ${DAWARICH_BUCKET_MATCH_RADIUS_M} m; each entry carries that stay (start, minutes, distance, recorded points) or null, and whether the wish was ticked off already. At most ${DAWARICH_BUCKET_SCAN_LIMIT} wishes per scan (truncated says more are left); wishes without coordinates are only counted. An instance that cannot be reached ends the scan with an error rather than a list of misses. Nothing is ticked off here: confirm_bucket_list_visits does that once the user agrees.`,
|
||||
inputSchema: {},
|
||||
// Asks the caller's Dawarich instance once per wish and writes nothing.
|
||||
annotations: TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
|
||||
access: { group: 'atlas', mode: 'read' },
|
||||
when: dawarichAddonOn,
|
||||
})
|
||||
async scanBucketList(_args: unknown, ctx: McpContext) {
|
||||
return dawarichToolResult(() => this.suggestions.scanBucketList(ctx.userId));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'confirm_bucket_list_visits',
|
||||
description:
|
||||
"Tick off the caller's bucket-list wishes the user confirmed after scan_bucket_list_visits (1 to 200 ids). Each is dated with visitedAt (ISO 8601) when given, otherwise with the start of the stay it was matched to, otherwise today. A wish ticked off already keeps its date. Answers how many were ticked off now (updated).",
|
||||
inputSchema: dawarichBucketConfirmSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'atlas', mode: 'write' },
|
||||
when: dawarichAddonOn,
|
||||
})
|
||||
async confirmBucketVisits({ itemIds, visitedAt }: DawarichBucketConfirm, ctx: McpContext) {
|
||||
return dawarichToolResult(async () => ({
|
||||
updated: await this.suggestions.confirmBucketVisits(ctx.userId, itemIds, visitedAt),
|
||||
}));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'clear_bucket_list_visit',
|
||||
description:
|
||||
"Take the visited mark off one of the caller's bucket-list wishes, with its date and where it came from, so the wish reads as not reached yet. The undo of confirm_bucket_list_visits and mark_bucket_list_item_visited_from_dawarich.",
|
||||
inputSchema: { itemId: idSchema.describe('The bucket-list entry') },
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
access: { group: 'atlas', mode: 'write' },
|
||||
when: dawarichAddonOn,
|
||||
})
|
||||
async clearBucketVisit({ itemId }: { itemId: number }, ctx: McpContext) {
|
||||
// Someone else's wish answers like a missing one, as the route's 404 does.
|
||||
if (!(await this.suggestions.clearBucketVisit(ctx.userId, itemId))) {
|
||||
return errorResult('Bucket-list entry not found');
|
||||
}
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'suggest_atlas_countries',
|
||||
description: `List the countries the caller's Dawarich recordings put them in between from and to (at most ${DAWARICH_WINDOW_MAX_DAYS} days), each with its cities, the minutes spent there and whether the Atlas counts the country as visited already. Country names TREK could not match to a code are listed under unresolved. Nothing is marked here: accept_atlas_countries does that for the codes the user confirms.`,
|
||||
inputSchema: dawarichTimeWindowSchema.shape,
|
||||
// Reads the caller's Dawarich instance live and writes nothing.
|
||||
annotations: TOOL_ANNOTATIONS_OPEN_WORLD_READONLY,
|
||||
access: { group: 'atlas', mode: 'read' },
|
||||
when: dawarichAddonOn,
|
||||
})
|
||||
async suggestAtlasCountries({ from, to }: DawarichTimeWindow, ctx: McpContext) {
|
||||
// The route's window check, refused before the instance is asked.
|
||||
const window = parseTimeWindow(from, to);
|
||||
return dawarichToolResult(() => this.suggestions.atlasSuggestions(ctx.userId, window.from, window.to));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'accept_atlas_countries',
|
||||
description:
|
||||
"Mark countries the user confirmed from suggest_atlas_countries as visited in the caller's Atlas, by ISO 3166-1 alpha-2 code (1 to 300 at once). A country taken off the Atlas before comes back; one marked already keeps where it came from. Answers how many were added now (marked).",
|
||||
inputSchema: dawarichAtlasAcceptSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'atlas', mode: 'write' },
|
||||
when: dawarichAddonOn,
|
||||
})
|
||||
async acceptAtlasCountries({ countryCodes }: DawarichAtlasAccept, ctx: McpContext) {
|
||||
return dawarichToolResult(async () => ({
|
||||
marked: await this.suggestions.acceptAtlasCountries(ctx.userId, countryCodes),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import { JourneyDomainService } from '../journey/journey-domain.service';
|
||||
import { JourneyEntryStaysService } from '../journey/journey-entry-stays.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { DawarichClient, type DawarichCreds } from './dawarich.client';
|
||||
import { DawarichClient, DawarichError, type DawarichCreds } from './dawarich.client';
|
||||
import { minutesBetween, toNumber } from './dawarich.helpers';
|
||||
import { DawarichService } from './dawarich.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
@@ -37,8 +37,21 @@ import {
|
||||
type DawarichBucketScan,
|
||||
type DawarichSuggestion,
|
||||
type DawarichSuggestionList,
|
||||
type DawarichErrorCode,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The failures that are the instance's rather than one request's: it cannot
|
||||
* be reached (a timeout included), it turns the key away, or it asks TREK to
|
||||
* slow down. A bucket-list scan stops at the first of them.
|
||||
*/
|
||||
const INSTANCE_FAILURES: ReadonlySet<DawarichErrorCode> = new Set<DawarichErrorCode>([
|
||||
'unreachable',
|
||||
'unauthorized',
|
||||
'forbidden',
|
||||
'rate_limited',
|
||||
]);
|
||||
|
||||
/**
|
||||
* What a user does with the stays a sync brought in.
|
||||
*
|
||||
@@ -408,6 +421,11 @@ export class DawarichSuggestionsService {
|
||||
* One upstream request per wish, so it is capped and explicitly triggered
|
||||
* rather than run on a timer. The cap is reported, never silent: a user with
|
||||
* eighty wishes must not be told their other thirty had no match.
|
||||
*
|
||||
* For the same reason an instance that cannot answer at all ends the scan
|
||||
* with its error instead of reporting every wish as unmatched: one that does
|
||||
* not answer would otherwise hold the request for a timeout per wish, and
|
||||
* one that refuses the key would read as "you never got anywhere".
|
||||
*/
|
||||
async scanBucketList(userId: number): Promise<DawarichBucketScan> {
|
||||
const creds = await this.dawarich.getCredentials(userId);
|
||||
@@ -447,7 +465,10 @@ export class DawarichSuggestionsService {
|
||||
let stays;
|
||||
try {
|
||||
stays = await this.client.findVisitsNear(creds, lat, lng, DAWARICH_BUCKET_MATCH_RADIUS_M, 20);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// The instance itself is down or turns the key away: every later wish
|
||||
// would fail the same way, so the scan ends here with that error.
|
||||
if (err instanceof DawarichError && INSTANCE_FAILURES.has(err.code)) throw err;
|
||||
// One wish that could not be checked is not a failed scan; it reports as
|
||||
// "no match found" and the user can run it again.
|
||||
return null;
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
DawarichSettingsDto,
|
||||
DawarichSuggestionStateDto,
|
||||
} from './dawarich.dto';
|
||||
import { parseTimeWindow } from './dawarich.helpers';
|
||||
import { DawarichService } from './dawarich.service';
|
||||
import {
|
||||
Body,
|
||||
@@ -176,7 +177,7 @@ export class DawarichController {
|
||||
|
||||
@Get('atlas/suggestions')
|
||||
async atlasSuggestions(@CurrentUser() user: User, @Query('from') from?: string, @Query('to') to?: string) {
|
||||
const window = parseWindow(from, to);
|
||||
const window = parseTimeWindow(from, to);
|
||||
return this.guardAsync(() => this.suggestions.atlasSuggestions(user.id, window.from, window.to));
|
||||
}
|
||||
|
||||
@@ -215,7 +216,7 @@ export class DawarichController {
|
||||
@Query('to') to?: string,
|
||||
@Query('offset') offset?: string,
|
||||
) {
|
||||
const window = parseWindow(from, to);
|
||||
const window = parseTimeWindow(from, to);
|
||||
return this.guardAsync(() =>
|
||||
this.tracks.forWindow(user.id, window.from.toISOString(), window.to.toISOString(), parseOffset(offset)),
|
||||
);
|
||||
@@ -310,25 +311,6 @@ function parseDate(raw: string | undefined): string | undefined {
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* An explicit instant window. Both ends are required together: a half-open
|
||||
* range would silently become "everything since the epoch" on one side, which
|
||||
* is the request that makes an instance time out.
|
||||
*/
|
||||
function parseWindow(from: string | undefined, to: string | undefined): { from: Date; to: Date } {
|
||||
const start = from ? new Date(from) : null;
|
||||
const end = to ? new Date(to) : null;
|
||||
if (!start || !end || !Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime())) {
|
||||
throw new HttpException({ error: 'from and to are required ISO timestamps' }, 400);
|
||||
}
|
||||
if (end <= start) throw new HttpException({ error: 'to must be after from' }, 400);
|
||||
const MAX_DAYS = 400;
|
||||
if (end.getTime() - start.getTime() > MAX_DAYS * 86_400_000) {
|
||||
throw new HttpException({ error: `Window must be ${MAX_DAYS} days or less` }, 400);
|
||||
}
|
||||
return { from: start, to: end };
|
||||
}
|
||||
|
||||
/** The originating client's socket id, so a broadcast does not echo back to it. */
|
||||
function socketId(req: Request): string | undefined {
|
||||
const header = req.headers['x-socket-id'];
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import type {
|
||||
DawarichSlimPoint,
|
||||
DawarichTrackFeature,
|
||||
DawarichVisitRaw,
|
||||
DawarichVisitedCountry,
|
||||
} from './dawarich.client';
|
||||
import { RECORDING_GAP_METERS, type DawarichTrackDay, type DawarichTrackSegment } from '@trek/shared';
|
||||
import {
|
||||
DAWARICH_WINDOW_MAX_DAYS,
|
||||
RECORDING_GAP_METERS,
|
||||
type DawarichTrackDay,
|
||||
type DawarichTrackSegment,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
@@ -690,3 +696,25 @@ function sumOf(a: unknown, b: unknown): number | undefined {
|
||||
if (left === null && right === null) return undefined;
|
||||
return (left ?? 0) + (right ?? 0);
|
||||
}
|
||||
|
||||
// ── Windows ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* An explicit instant window, read the one way for the REST routes and the
|
||||
* MCP tools that take one. Both ends are required together: a half-open range
|
||||
* would silently become "everything since the epoch" on one side, which is the
|
||||
* request that makes an instance time out. A refusal is a 400 that REST and
|
||||
* MCP answer with the same sentence.
|
||||
*/
|
||||
export function parseTimeWindow(from: string | undefined, to: string | undefined): { from: Date; to: Date } {
|
||||
const start = from ? new Date(from) : null;
|
||||
const end = to ? new Date(to) : null;
|
||||
if (!start || !end || !Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime())) {
|
||||
throw new DomainError(400, 'from and to are required ISO timestamps');
|
||||
}
|
||||
if (end <= start) throw new DomainError(400, 'to must be after from');
|
||||
if (end.getTime() - start.getTime() > DAWARICH_WINDOW_MAX_DAYS * 86_400_000) {
|
||||
throw new DomainError(400, `Window must be ${DAWARICH_WINDOW_MAX_DAYS} days or less`);
|
||||
}
|
||||
return { from: start, to: end };
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { AcceptError, DawarichSuggestionsService } from './dawarich-suggestions.service';
|
||||
import { DawarichTracksService } from './dawarich-tracks.service';
|
||||
import { DawarichError } from './dawarich.client';
|
||||
import { idSchema } from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
@@ -48,6 +49,9 @@ const MAX_LIMIT = 200;
|
||||
* The connection routes (settings, test, disconnect) are deliberately absent:
|
||||
* they take an API key for somebody's complete location history, and that is
|
||||
* exactly what no assistant scope should be able to read or replace.
|
||||
*
|
||||
* The bucket-list and Atlas twins of `/bucket-list/*` and `/atlas/*` are
|
||||
* DawarichAtlasMcp, which the assistant loads with the Atlas.
|
||||
*/
|
||||
@McpController()
|
||||
export class DawarichMcp {
|
||||
@@ -251,11 +255,22 @@ export class DawarichMcp {
|
||||
|
||||
/** The MCP echo of the controller's error shaping: a refusal, not an exception. */
|
||||
private async run<T>(action: () => Promise<T>) {
|
||||
try {
|
||||
return ok((await action()) as object);
|
||||
} catch (err) {
|
||||
if (err instanceof AcceptError) return errorResult(err.message);
|
||||
throw err;
|
||||
}
|
||||
return dawarichToolResult(action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A Dawarich tool's answer: the action's result, or a refusal in its words
|
||||
* when it fails as the routes refuse. An instance that cannot be read is a
|
||||
* refusal too, with TREK's own sentence for it (the upstream text stays in
|
||||
* the error's detail, as on the route). Anything else propagates. Shared with
|
||||
* DawarichAtlasMcp.
|
||||
*/
|
||||
export async function dawarichToolResult<T>(action: () => Promise<T>) {
|
||||
try {
|
||||
return ok((await action()) as object);
|
||||
} catch (err) {
|
||||
if (err instanceof AcceptError || err instanceof DawarichError) return errorResult(err.message);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { PlacesModule } from '../places/places.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { DawarichAtlasMcp } from './dawarich-atlas.mcp';
|
||||
import { DawarichDayStaysService } from './dawarich-day-stays.service';
|
||||
import { DawarichSuggestionsService } from './dawarich-suggestions.service';
|
||||
import { DawarichSyncJob } from './dawarich-sync.job';
|
||||
@@ -90,6 +91,7 @@ import { Module } from '@nestjs/common';
|
||||
DawarichDayStaysService,
|
||||
DawarichSyncJob,
|
||||
DawarichMcp,
|
||||
DawarichAtlasMcp,
|
||||
],
|
||||
exports: [DawarichService, DawarichSuggestionsService, DawarichTracksService, DawarichDayStaysService],
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user