mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
feat(mcp): place pictures, POI search, GPX export and a biased place search
image_url was in no places tool although the service persists it and the picker in the UI sets a URL, which is not a file transport question. search_place passed two of the service's four arguments, so an unbiased query resolved to the wrong continent. get_place_details gained expand for reviews and the editorial summary. It defaults to off because that field mask bills as a Google Enterprise SKU, and it now honours the admin kill switch the REST route checks: an instance owner who turns Place Details off to stop the billing was still billable through this one surface.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type McpContext } from '../../nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { POI_CATEGORY_KEYS } from './maps.helpers';
|
||||
import { MapsService } from './maps.service';
|
||||
|
||||
/**
|
||||
@@ -16,16 +17,38 @@ export class MapsMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'get_place_details',
|
||||
description: 'Fetch detailed information about a place by its Google Place ID.',
|
||||
description: 'Fetch detailed information about a place by its Google Place ID. The plain lookup returns name, address, coordinates, rating, opening hours, phone and website, and always answers with an empty review list. Set expand only when visitor reviews or the editorial summary are what was actually asked for: that field mask bills as a Google Enterprise SKU and costs the instance owner several times a plain lookup.',
|
||||
inputSchema: {
|
||||
placeId: z.string().describe('Google Place ID'),
|
||||
lang: z.string().optional().default('en'),
|
||||
expand: z.boolean().optional().default(false).describe('Also fetch up to five visitor reviews and the editorial summary. Billed as an Enterprise SKU, so leave it off unless the answer needs them'),
|
||||
refresh: z.boolean().optional().default(false).describe('Bypass the cached expanded payload and re-fetch from the provider. Only does anything together with expand, and pays the expanded price again'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'geo', mode: 'read' },
|
||||
})
|
||||
async getPlaceDetails({ placeId, lang }: { placeId: string; lang?: string }, ctx: McpContext) {
|
||||
const details = await this.maps.getPlaceDetails(ctx.userId, placeId, lang ?? 'en');
|
||||
async getPlaceDetails(
|
||||
{ placeId, lang, expand, refresh }: { placeId: string; lang?: string; expand?: boolean; refresh?: boolean },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
// The admin kill switch, checked before either path. An instance owner who
|
||||
// turns Place Details off does it to stop Google billing them, and an
|
||||
// assistant reaching the provider anyway would bill them from the one
|
||||
// surface the switch does not cover. REST answers { place: null, disabled }
|
||||
// rather than an error, so this does too, with a line the model can act on.
|
||||
if (this.maps.detailsDisabled()) {
|
||||
return ok({
|
||||
details: null,
|
||||
disabled: true,
|
||||
note: 'Place Details is turned off on this instance by an administrator. Nothing was fetched.',
|
||||
});
|
||||
}
|
||||
|
||||
// Same split the REST route makes, and for the same reason: the expanded
|
||||
// field mask is the expensive one, so nothing reaches it unless it was asked for.
|
||||
const details = expand
|
||||
? await this.maps.getPlaceDetailsExpanded(ctx.userId, placeId, lang ?? 'en', refresh ?? false)
|
||||
: await this.maps.getPlaceDetails(ctx.userId, placeId, lang ?? 'en');
|
||||
return ok({ details });
|
||||
}
|
||||
|
||||
@@ -58,4 +81,41 @@ export class MapsMcp {
|
||||
const result = await this.maps.resolveGoogleMapsUrl(url);
|
||||
return ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* The MCP side of GET /api/maps/pois, the "explore" pill on the trip map. Not
|
||||
* part of the 1:1 move above: the route had no tool at all, which left the
|
||||
* whole discover-what-is-here half of the map unreachable from a conversation.
|
||||
*/
|
||||
@Tool({
|
||||
name: 'search_pois',
|
||||
description: 'List OpenStreetMap points of interest of one category inside a map rectangle, with address, opening hours, website, phone and cuisine wherever OSM carries them. This is the discovery tool: use it to answer "what is around here" for a neighbourhood or a whole city district. Prefer search_place when the user already named the place they mean. Never calls Google, so it costs nothing and works on an instance with no Places key.',
|
||||
inputSchema: {
|
||||
category: z.enum(POI_CATEGORY_KEYS).describe('Which kind of place to look for'),
|
||||
bbox: z.object({
|
||||
south: z.number().min(-90).max(90).describe('Southern edge, latitude'),
|
||||
west: z.number().min(-180).max(180).describe('Western edge, longitude'),
|
||||
north: z.number().min(-90).max(90).describe('Northern edge, latitude'),
|
||||
east: z.number().min(-180).max(180).describe('Eastern edge, longitude'),
|
||||
}).describe('The rectangle to search. Anything wider than 0.5 degrees is narrowed to a centred window so the query stays fast; the answer reports that as `clamped`'),
|
||||
lang: z.string().max(35).optional().describe('Language for the POI names, e.g. "de" or "ja". Falls back to the OSM international name and then the local one'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'geo', mode: 'read' },
|
||||
})
|
||||
async searchPois(
|
||||
{ category, bbox, lang }: {
|
||||
category: string;
|
||||
bbox: { south: number; west: number; north: number; east: number };
|
||||
lang?: string;
|
||||
},
|
||||
_ctx: McpContext,
|
||||
) {
|
||||
try {
|
||||
return ok(await this.maps.pois(category, bbox, lang));
|
||||
} catch {
|
||||
// Overpass is a set of public mirrors; an outage there is not a bad request.
|
||||
return errorResult('POI search failed.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,15 @@ import {
|
||||
McpController, Tool, ResourceTemplate, type McpContext,
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
|
||||
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
demoDenied, ok,
|
||||
demoDenied, errorResult, ok,
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { placeWebsiteSchema } from '@trek/shared';
|
||||
import {
|
||||
mapsSearchRequestSchema,
|
||||
placeImageUrlSchema,
|
||||
placeImportListRequestSchema,
|
||||
placeWebsiteSchema,
|
||||
} from '@trek/shared';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { AssignmentsService } from '../assignments/assignments.service';
|
||||
@@ -66,6 +71,7 @@ export class PlacesMcp {
|
||||
notes: z.string().max(2000).optional(),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
image_url: placeImageUrlSchema.optional().describe('Thumbnail for the place: an /uploads/ path, an /api/maps/place-photo/ path, an inline data: image, or an https URL'),
|
||||
price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
|
||||
currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
|
||||
},
|
||||
@@ -73,17 +79,17 @@ export class PlacesMcp {
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async createPlace(
|
||||
{ tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes, website, phone, price, currency }: {
|
||||
{ tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes, website, phone, image_url, price, currency }: {
|
||||
tripId: number; name: string; description?: string; lat?: number; lng?: number; address?: string;
|
||||
category_id?: number; google_place_id?: string; google_ftid?: string; osm_id?: string;
|
||||
notes?: string; website?: string; phone?: string; price?: number; currency?: string;
|
||||
notes?: string; website?: string; phone?: string; image_url?: string; price?: number; currency?: string;
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('place_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
const place = this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes, website, phone, price, currency });
|
||||
const place = this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes, website, phone, image_url, price, currency });
|
||||
this.guards.safeBroadcast(tripId, 'place:created', { place });
|
||||
return ok({ place });
|
||||
}
|
||||
@@ -106,6 +112,7 @@ export class PlacesMcp {
|
||||
place_notes: z.string().max(2000).optional().describe('Notes for the place'),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
image_url: placeImageUrlSchema.optional().describe('Thumbnail for the place: an /uploads/ path, an /api/maps/place-photo/ path, an inline data: image, or an https URL'),
|
||||
assignment_notes: z.string().max(500).optional().describe('Notes for this day assignment'),
|
||||
price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
|
||||
currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
|
||||
@@ -114,10 +121,10 @@ export class PlacesMcp {
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async createAndAssignPlace(
|
||||
{ tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, place_notes, website, phone, assignment_notes, price, currency }: {
|
||||
{ tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, place_notes, website, phone, image_url, assignment_notes, price, currency }: {
|
||||
tripId: number; dayId: number; name: string; description?: string; lat?: number; lng?: number; address?: string;
|
||||
category_id?: number; google_place_id?: string; google_ftid?: string; osm_id?: string;
|
||||
place_notes?: string; website?: string; phone?: string; assignment_notes?: string;
|
||||
place_notes?: string; website?: string; phone?: string; image_url?: string; assignment_notes?: string;
|
||||
price?: number; currency?: string;
|
||||
},
|
||||
ctx: McpContext,
|
||||
@@ -128,7 +135,7 @@ export class PlacesMcp {
|
||||
if (!this.assignments.dayExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
|
||||
try {
|
||||
const result = this.db.transaction(() => {
|
||||
const place = this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes: place_notes, website, phone, price, currency });
|
||||
const place = this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, notes: place_notes, website, phone, image_url, price, currency });
|
||||
const assignment = this.assignments.createAssignment(dayId, place.id, assignment_notes ?? null);
|
||||
return { place, assignment };
|
||||
});
|
||||
@@ -161,6 +168,7 @@ export class PlacesMcp {
|
||||
notes: z.string().max(2000).optional(),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
image_url: placeImageUrlSchema.nullable().optional().describe('Thumbnail for the place: an /uploads/ path, an /api/maps/place-photo/ path, an inline data: image, or an https URL. Pass null to remove the current picture'),
|
||||
transport_mode: z.enum(['walking', 'driving', 'cycling', 'transit', 'flight']).optional(),
|
||||
osm_id: z.string().optional().describe('OpenStreetMap ID (e.g. "way:12345")'),
|
||||
google_place_id: z.string().optional().describe('Google Place ID (e.g. "ChIJd8BlQ2BZwokRAFUEcm_qrcA")'),
|
||||
@@ -170,10 +178,11 @@ export class PlacesMcp {
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async updatePlace(
|
||||
{ tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, transport_mode, osm_id, google_place_id, google_ftid }: {
|
||||
{ tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, image_url, transport_mode, osm_id, google_place_id, google_ftid }: {
|
||||
tripId: number; placeId: number; name?: string; description?: string; lat?: number; lng?: number;
|
||||
address?: string; category_id?: number; price?: number; currency?: string; place_time?: string;
|
||||
end_time?: string; duration_minutes?: number; notes?: string; website?: string; phone?: string;
|
||||
image_url?: string | null;
|
||||
transport_mode?: 'walking' | 'driving' | 'cycling' | 'transit' | 'flight'; osm_id?: string;
|
||||
google_place_id?: string; google_ftid?: string;
|
||||
},
|
||||
@@ -182,7 +191,7 @@ export class PlacesMcp {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('place_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, transport_mode, osm_id, google_place_id, google_ftid });
|
||||
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, image_url, transport_mode, osm_id, google_place_id, google_ftid });
|
||||
if (!place) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
|
||||
this.guards.safeBroadcast(tripId, 'place:updated', { place });
|
||||
return ok({ place });
|
||||
@@ -274,19 +283,26 @@ export class PlacesMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'search_place',
|
||||
description: 'Search for a real-world place by name or address. Returns results with osm_id (and google_place_id/google_ftid if configured). Use these IDs when calling create_place so the app can display opening hours, ratings, and map links.',
|
||||
description: 'Search for a real-world place by name or address. Returns results with osm_id (and google_place_id/google_ftid if configured). Use these IDs when calling create_place so the app can display opening hours, ratings, and map links. Pass locationBias whenever the trip has a destination: a bare name like "Central Station" or "Museum of Modern Art" otherwise resolves wherever the provider guesses, which is regularly the wrong continent.',
|
||||
inputSchema: {
|
||||
query: z.string().min(1).max(500).describe('Place name or address to search for'),
|
||||
locationBias: mapsSearchRequestSchema.shape.locationBias.describe('Centre the search on a coordinate: { lat, lng, radius? } with radius in metres (default 50000). Only the Google provider honours it; the OpenStreetMap fallback ignores it'),
|
||||
lang: z.string().max(35).optional().describe('BCP 47 language for the result names, e.g. "de" or "ja". Defaults to English'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'places', mode: 'read' },
|
||||
})
|
||||
async searchPlace({ query }: { query: string }, ctx: McpContext) {
|
||||
async searchPlace(
|
||||
{ query, locationBias, lang }: {
|
||||
query: string; locationBias?: { lat: number; lng: number; radius?: number }; lang?: string;
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
try {
|
||||
const result = await this.maps.searchPlaces(ctx.userId, query);
|
||||
const result = await this.maps.searchPlaces(ctx.userId, query, lang, locationBias);
|
||||
return ok(result);
|
||||
} catch {
|
||||
return { content: [{ type: 'text' as const, text: 'Place search failed.' }], isError: true };
|
||||
return errorResult('Place search failed.');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,21 +313,25 @@ export class PlacesMcp {
|
||||
tripId: z.number().int().positive(),
|
||||
url: z.string().url().describe('Publicly shared Google Maps list URL (maps.app.goo.gl/...) or Naver Maps list URL'),
|
||||
source: z.enum(['google-list', 'naver-list']).describe('List source: "google-list" for Google Maps saved places, "naver-list" for Naver Maps'),
|
||||
enrich: placeImportListRequestSchema.shape.enrich.describe('Re-resolve every imported place through the Places API afterwards to fill in photo, address, website and phone (#886). Needs a Google Maps key on the instance, costs a lookup per place, and runs in the background: the tool returns the bare import and the places fill in over the websocket. Off by default'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async importPlacesFromUrl(
|
||||
{ tripId, url, source }: { tripId: number; url: string; source: 'google-list' | 'naver-list' },
|
||||
{ tripId, url, source, enrich }: { tripId: number; url: string; source: 'google-list' | 'naver-list'; enrich?: boolean },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('place_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
|
||||
// Same opts the REST route builds: the enrichment pass is keyed on the calling
|
||||
// user because it spends that user's Places credential.
|
||||
const opts = { enrich: enrich ?? false, userId: ctx.userId };
|
||||
const result = source === 'google-list'
|
||||
? await this.places.importGoogleList(String(tripId), url)
|
||||
: await this.places.importNaverList(String(tripId), url);
|
||||
? await this.places.importGoogleList(String(tripId), url, opts)
|
||||
: await this.places.importNaverList(String(tripId), url, opts);
|
||||
|
||||
if ('error' in result) {
|
||||
return { content: [{ type: 'text' as const, text: result.error }], isError: true };
|
||||
@@ -323,6 +343,32 @@ export class PlacesMcp {
|
||||
return ok({ places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'export_trip_gpx',
|
||||
description: 'Export a trip as GPX text: its places as waypoints, any imported routes as tracks, and each planned day as a route in visiting order. This is the format handhelds and offline map apps (Organic Maps, OsmAnd, Garmin) read. Prefer export_trip_ics when the user wants the itinerary in a calendar instead.',
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
waypoints: z.boolean().optional().default(true).describe('Write every place with coordinates as a <wpt>'),
|
||||
tracks: z.boolean().optional().default(true).describe('Write places that carry an imported route geometry as a <trk>'),
|
||||
dayRoutes: z.boolean().optional().default(true).describe('Write each planned day as a <rte> through its stops in order'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'places', mode: 'read' },
|
||||
})
|
||||
async exportTripGpx(
|
||||
{ tripId, waypoints, tracks, dayRoutes }: {
|
||||
tripId: number; waypoints?: boolean; tracks?: boolean; dayRoutes?: boolean;
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
// A read, like the REST route: seeing the trip is enough, no place_edit.
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
if (!waypoints && !tracks && !dayRoutes) return errorResult('No export types selected.');
|
||||
const result = this.places.exportGpx(String(tripId), { waypoints, tracks, dayRoutes });
|
||||
if (!result) return errorResult('Nothing to export.');
|
||||
return ok({ gpx: result.gpx, filename: result.filename });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'bulk_delete_places',
|
||||
description: 'Delete multiple places from a trip at once. Removes all day assignments for each place as well. Warn the user before calling this — it cannot be undone.',
|
||||
@@ -369,17 +415,18 @@ export class PlacesMcp {
|
||||
notes: z.string().max(2000).optional(),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
image_url: placeImageUrlSchema.nullable().optional().describe('Thumbnail for every listed place: an /uploads/ path, an /api/maps/place-photo/ path, an inline data: image, or an https URL. Pass null to strip the pictures off a batch at once'),
|
||||
description: z.string().max(2000).optional(),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async bulkUpdatePlaces(
|
||||
{ tripId, placeIds, category_id, price, currency, transport_mode, place_time, end_time, duration_minutes, notes, website, phone, description }: {
|
||||
{ tripId, placeIds, category_id, price, currency, transport_mode, place_time, end_time, duration_minutes, notes, website, phone, image_url, description }: {
|
||||
tripId: number; placeIds: number[]; category_id?: number; price?: number; currency?: string;
|
||||
transport_mode?: 'walking' | 'driving' | 'cycling' | 'transit' | 'flight'; place_time?: string;
|
||||
end_time?: string; duration_minutes?: number; notes?: string; website?: string; phone?: string;
|
||||
description?: string;
|
||||
image_url?: string | null; description?: string;
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
@@ -387,7 +434,7 @@ export class PlacesMcp {
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('place_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
|
||||
const fields = { category_id, price, currency, transport_mode, place_time, end_time, duration_minutes, notes, website, phone, description };
|
||||
const fields = { category_id, price, currency, transport_mode, place_time, end_time, duration_minutes, notes, website, phone, image_url, description };
|
||||
if (Object.values(fields).every(v => v === undefined)) {
|
||||
return { content: [{ type: 'text' as const, text: 'Provide at least one field to update.' }], isError: true };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user