mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
feat(mcp): list_collection_places pages a long list compactly (#2647)
A read tool that answers one list a page at a time (100 by default, up to 500) as compact one-line JSON rows, filtered by status, label or "no label", with the list's labels, the matching total and a cursor. The cursor is the last place's position (sort_order, created_at, id), so labelling a page while paging through unlabelled places skips none. getCollection orders by the same keys, id last, so both tools agree on ties.
This commit is contained in:
@@ -84,6 +84,42 @@ type CollectionPlacesWriteKyselyDB = Pick<DB, 'collection_places'>;
|
||||
|
||||
type CollectionPlaceLabelsKyselyDB = Pick<DB, 'collection_place_labels'>;
|
||||
|
||||
type CollectionPlacesPageKyselyDB = Pick<DB, 'collection_places' | 'collection_place_labels'>;
|
||||
|
||||
/** Which of a list's places a page holds (list_collection_places, #2647); every filter left out matches all. */
|
||||
interface CollectionPlacePageFilter {
|
||||
status?: string;
|
||||
labelId?: number;
|
||||
unlabeled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A place's position in its list: the keys both a page and getCollection order
|
||||
* by, in that order. A missing sort_order reads as the column default and a
|
||||
* missing created_at as the earliest, so the order is total on every engine and
|
||||
* a page can go on after any place.
|
||||
*/
|
||||
export interface CollectionPlacePosition {
|
||||
sortOrder: number;
|
||||
createdAt: string;
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** A saved place as a page names it: the fields an agent finds it by, plus its position. */
|
||||
export interface CollectionPlacePageRow {
|
||||
id: number;
|
||||
name: string;
|
||||
status: string;
|
||||
address: string | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
google_place_id: string | null;
|
||||
website: string | null;
|
||||
phone: string | null;
|
||||
sort_key: number;
|
||||
created_key: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* `collections` — the root of the collections cluster (Plan 3h Task 1, part
|
||||
* A). Owns every CL1-CL36 statement not moved to `CollectionMembersRepository`/
|
||||
@@ -344,7 +380,9 @@ export class CollectionsRepository extends TrekRepository<Collections> {
|
||||
* CL16/CL17 (`getCollection`/`exportCollection`'s dup-text pair, collapsed
|
||||
* onto ONE repository method as the brief directs) — the same
|
||||
* `cp.*`/category-alias select as {@link findPlaceRowById}, scoped by
|
||||
* `cp.collection_id` and ordered by `cp.sort_order, cp.created_at`.
|
||||
* `cp.collection_id` and ordered by the place's position: `sort_order`,
|
||||
* `created_at`, then `id`, so two places saved in the same second keep one
|
||||
* order, the one list_collection_places pages through (#2647).
|
||||
*/
|
||||
async listPlaceRows(collectionId: number): Promise<CollectionPlaceRow[]> {
|
||||
return await this.placesReadDb()
|
||||
@@ -382,8 +420,99 @@ export class CollectionsRepository extends TrekRepository<Collections> {
|
||||
'c.icon as category_icon',
|
||||
])
|
||||
.where('cp.collection_id', '=', collectionId)
|
||||
.orderBy('cp.sort_order')
|
||||
.orderBy('cp.created_at')
|
||||
.orderBy((eb) => eb.fn.coalesce('cp.sort_order', eb.val(0)))
|
||||
.orderBy((eb) => eb.fn.coalesce('cp.created_at', eb.val('')))
|
||||
.orderBy('cp.id')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The places of a list the filter matches, before any paging. */
|
||||
private filteredPlaces(collectionId: number, filter: CollectionPlacePageFilter) {
|
||||
const { status, labelId, unlabeled } = filter;
|
||||
let query = this.kysely<CollectionPlacesPageKyselyDB>()
|
||||
.selectFrom('collection_places as cp')
|
||||
.where('cp.collection_id', '=', collectionId);
|
||||
if (status !== undefined) query = query.where('cp.status', '=', status);
|
||||
if (labelId !== undefined) {
|
||||
query = query.where((eb) =>
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom('collection_place_labels as cpl')
|
||||
.select('cpl.label_id')
|
||||
.whereRef('cpl.collection_place_id', '=', 'cp.id')
|
||||
.where('cpl.label_id', '=', labelId),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (unlabeled) {
|
||||
query = query.where((eb) =>
|
||||
eb.not(
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom('collection_place_labels as cpl')
|
||||
.select('cpl.label_id')
|
||||
.whereRef('cpl.collection_place_id', '=', 'cp.id'),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
/** How many places of a list the filter matches (list_collection_places' total). */
|
||||
async countPlacePage(collectionId: number, filter: CollectionPlacePageFilter): Promise<number> {
|
||||
const row = await this.filteredPlaces(collectionId, filter)
|
||||
.select((eb) => eb.fn.countAll<number>().as('n'))
|
||||
.executeTakeFirstOrThrow();
|
||||
return Number(row.n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Up to `limit` places of a list the filter matches, in the list's order
|
||||
* (listPlaceRows'), starting after the position `after` names: a keyset, so
|
||||
* a place that stops matching between two pages moves none of the others.
|
||||
*/
|
||||
async listPlacePage(
|
||||
collectionId: number,
|
||||
filter: CollectionPlacePageFilter,
|
||||
after: CollectionPlacePosition | null,
|
||||
limit: number,
|
||||
): Promise<CollectionPlacePageRow[]> {
|
||||
let query = this.filteredPlaces(collectionId, filter);
|
||||
if (after) {
|
||||
query = query.where((eb) => {
|
||||
const sortKey = eb.fn.coalesce('cp.sort_order', eb.val(0));
|
||||
const createdKey = eb.fn.coalesce('cp.created_at', eb.val(''));
|
||||
return eb.or([
|
||||
eb(sortKey, '>', after.sortOrder),
|
||||
eb.and([
|
||||
eb(sortKey, '=', after.sortOrder),
|
||||
eb.or([
|
||||
eb(createdKey, '>', after.createdAt),
|
||||
eb.and([eb(createdKey, '=', after.createdAt), eb('cp.id', '>', after.id)]),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
});
|
||||
}
|
||||
return await query
|
||||
.select((eb) => [
|
||||
'cp.id',
|
||||
'cp.name',
|
||||
'cp.status',
|
||||
'cp.address',
|
||||
'cp.lat',
|
||||
'cp.lng',
|
||||
'cp.google_place_id',
|
||||
'cp.website',
|
||||
'cp.phone',
|
||||
eb.fn.coalesce('cp.sort_order', eb.val(0)).as('sort_key'),
|
||||
eb.fn.coalesce('cp.created_at', eb.val('')).as('created_key'),
|
||||
])
|
||||
.orderBy('sort_key')
|
||||
.orderBy('created_key')
|
||||
.orderBy('cp.id')
|
||||
.limit(limit)
|
||||
.execute();
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@ export function ok(data: unknown): McpTextResult {
|
||||
return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] };
|
||||
}
|
||||
|
||||
/** Success result: `data` as one line of JSON, for an answer whose size matters more than how it reads (a page of a long list). */
|
||||
export function okCompact(data: unknown): McpTextResult {
|
||||
return { content: [{ type: 'text' as const, text: JSON.stringify(data) }] };
|
||||
}
|
||||
|
||||
/** Error result with a verbatim message (no formatting, no prefix). */
|
||||
export function errorResult(text: string): McpTextResult {
|
||||
return { content: [{ type: 'text' as const, text }], isError: true };
|
||||
|
||||
@@ -3,6 +3,7 @@ export {
|
||||
demoDenied,
|
||||
errorResult,
|
||||
ok,
|
||||
okCompact,
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
TOOL_ANNOTATIONS_OPEN_WORLD_NON_IDEMPOTENT,
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { CollectionLabels } from '../../db/entities/CollectionLabels.entity';
|
||||
import { Collections } from '../../db/entities/Collections.entity';
|
||||
import { CollectionLabelsRepository } from '../../db/repositories/CollectionLabels.repository';
|
||||
import {
|
||||
CollectionsRepository,
|
||||
type CollectionPlacePageRow,
|
||||
type CollectionPlacePosition,
|
||||
} from '../../db/repositories/Collections.repository';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { decodePlacesCursor, encodePlacesCursor } from './collections.helpers';
|
||||
import { CollectionsService } from './collections.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { COLLECTION_PLACES_PAGE_DEFAULT, type CollectionPlacesPageRequest } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* How long the places of one page may run as JSON. The in-app assistant cuts a
|
||||
* tool answer at 40,000 characters, and a page cut there would leave its last
|
||||
* places unread while next_cursor goes on after them. So a page ends early,
|
||||
* before that cut, and next_cursor goes on after the last place it holds.
|
||||
*/
|
||||
const PAGE_CHARS = 30_000;
|
||||
|
||||
/** The fields a page carries only where a place has them, so an empty one costs nothing. */
|
||||
const FIELDS_WHEN_SET = ['address', 'lat', 'lng', 'google_place_id', 'website', 'phone'] as const;
|
||||
|
||||
/** A saved place as a page lists it: id, name, status, its labels and the fields it has. */
|
||||
type CompactPlace = Record<string, unknown>;
|
||||
|
||||
/** One page of a list's places, next to what the list is and how far the filter reaches. */
|
||||
interface CollectionPlacesPage {
|
||||
collection: { id: number; name: string };
|
||||
labels: Array<{ id: number; name: string; color: string | null }>;
|
||||
/** Places of the list the filter matches, on every page. */
|
||||
total: number;
|
||||
places: CompactPlace[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
function compactPlace(row: CollectionPlacePageRow, labelIds: number[]): CompactPlace {
|
||||
const place: CompactPlace = { id: row.id, name: row.name, status: row.status };
|
||||
if (labelIds.length > 0) place.label_ids = labelIds;
|
||||
for (const field of FIELDS_WHEN_SET) {
|
||||
const value = row[field];
|
||||
if (value !== null && value !== '') place[field] = value;
|
||||
}
|
||||
return place;
|
||||
}
|
||||
|
||||
/** The places of a page in order until their JSON would pass PAGE_CHARS; always at least one. */
|
||||
function fillPage(rows: CollectionPlacePageRow[], labelIds: Map<number, number[]>): CompactPlace[] {
|
||||
const page: CompactPlace[] = [];
|
||||
let chars = 0;
|
||||
for (const row of rows) {
|
||||
const place = compactPlace(row, labelIds.get(row.id) ?? []);
|
||||
chars += JSON.stringify(place).length + 1;
|
||||
if (page.length > 0 && chars > PAGE_CHARS) break;
|
||||
page.push(place);
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
function positionOf(row: CollectionPlacePageRow): CollectionPlacePosition {
|
||||
return { sortOrder: row.sort_key, createdAt: row.created_key, id: row.id };
|
||||
}
|
||||
|
||||
/**
|
||||
* A long list a page at a time (the list_collection_places tool, #2647).
|
||||
* get_collection answers a list whole, every place with its full row, tags and
|
||||
* every member's vote, which an MCP client cuts down to its first and last
|
||||
* places on a long list. A page is the list's own order, compact, and goes on
|
||||
* from a cursor: the position of its last place, so places that stop matching
|
||||
* the filter in between (labelled while paging through the unlabelled ones)
|
||||
* move none of the others. Read through the collections service's own access
|
||||
* check, like get_collection.
|
||||
*/
|
||||
@Injectable()
|
||||
export class CollectionsPlacesPageService {
|
||||
constructor(
|
||||
private readonly collections: CollectionsService,
|
||||
@InjectRepository(Collections) private readonly collectionsRepo: CollectionsRepository,
|
||||
@InjectRepository(CollectionLabels) private readonly labels: CollectionLabelsRepository,
|
||||
) {}
|
||||
|
||||
async listPlaces(userId: number, request: CollectionPlacesPageRequest): Promise<CollectionPlacesPage> {
|
||||
const { collectionId, status, labelId, unlabeled } = request;
|
||||
await this.collections.assertAccess(userId, collectionId);
|
||||
if (labelId !== undefined && unlabeled) {
|
||||
throw new DomainError(400, 'Pass either labelId or unlabeled, not both');
|
||||
}
|
||||
const after = this.positionAfter(request.cursor);
|
||||
const labels = await this.labels.listByCollection(collectionId);
|
||||
if (labelId !== undefined && !labels.some((label) => label.id === labelId)) {
|
||||
throw new DomainError(404, 'Label not found in this list');
|
||||
}
|
||||
|
||||
const filter = { status, labelId, unlabeled };
|
||||
const limit = request.limit ?? COLLECTION_PLACES_PAGE_DEFAULT;
|
||||
const total = await this.collectionsRepo.countPlacePage(collectionId, filter);
|
||||
// One place more than the page holds says whether another page follows.
|
||||
const rows = await this.collectionsRepo.listPlacePage(collectionId, filter, after, limit + 1);
|
||||
const candidates = rows.slice(0, limit);
|
||||
const places = fillPage(candidates, await this.labelIdsOf(candidates.map((row) => row.id)));
|
||||
const last = rows[places.length - 1];
|
||||
const collection = await this.collectionsRepo.findRow(collectionId);
|
||||
return {
|
||||
collection: { id: collectionId, name: collection?.name ?? '' },
|
||||
labels: labels.map(({ id, name, color }) => ({ id, name, color })),
|
||||
total,
|
||||
places,
|
||||
next_cursor: places.length < rows.length && last ? encodePlacesCursor(positionOf(last)) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Where a page starts: after the place the cursor names, or at the top without one. */
|
||||
private positionAfter(cursor: string | undefined): CollectionPlacePosition | null {
|
||||
if (cursor === undefined) return null;
|
||||
const position = decodePlacesCursor(cursor);
|
||||
if (!position) throw new DomainError(400, 'Invalid cursor: pass the next_cursor of the page before');
|
||||
return position;
|
||||
}
|
||||
|
||||
/** Each place's label ids, in one read for the whole page. */
|
||||
private async labelIdsOf(placeIds: number[]): Promise<Map<number, number[]>> {
|
||||
const byPlace = new Map<number, number[]>();
|
||||
for (const { pid, label_id } of await this.collectionsRepo.loadLabelIdsByPlaceIds(placeIds)) {
|
||||
byPlace.set(pid, [...(byPlace.get(pid) ?? []), label_id]);
|
||||
}
|
||||
return byPlace;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { CollectionPlacePosition } from '../../db/repositories/Collections.repository';
|
||||
import type { CollectionLink, CollectionPlaceUpdateRequest } from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Pure helpers of the collections domain, moved verbatim out of
|
||||
* collections.service.ts. Nothing here touches the DB, so they stay plain
|
||||
@@ -48,3 +51,29 @@ export function listingWriteOf(body: CollectionPlaceUpdateRequest): ListingWrite
|
||||
if (body.currency !== undefined) write.currency = body.currency ?? null;
|
||||
return write;
|
||||
}
|
||||
|
||||
/** A cursor as list_collection_places hands it out: the position of the last place of a page. */
|
||||
const placesCursorSchema = z.tuple([z.number().int(), z.string().max(40), z.number().int().positive()]);
|
||||
|
||||
/**
|
||||
* The cursor of the page after a place (#2647): its position in the list, so
|
||||
* the next page starts right after it whatever changed in between. Opaque to
|
||||
* the client, which passes it back as it came.
|
||||
*/
|
||||
export function encodePlacesCursor(position: CollectionPlacePosition): string {
|
||||
return Buffer.from(JSON.stringify([position.sortOrder, position.createdAt, position.id])).toString('base64url');
|
||||
}
|
||||
|
||||
/** The position a cursor names; null for anything encodePlacesCursor did not write. */
|
||||
export function decodePlacesCursor(cursor: string): CollectionPlacePosition | null {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const parsed = placesCursorSchema.safeParse(value);
|
||||
if (!parsed.success) return null;
|
||||
const [sortOrder, createdAt, id] = parsed.data;
|
||||
return { sortOrder, createdAt, id };
|
||||
}
|
||||
|
||||
@@ -10,11 +10,13 @@ import {
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
ok,
|
||||
okCompact,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { CollectionsItemsService } from './collections-items.service';
|
||||
import { CollectionsPlacesPageService } from './collections-places-page.service';
|
||||
import { CollectionsService } from './collections.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import {
|
||||
@@ -29,7 +31,10 @@ import {
|
||||
collectionInviteRequestSchema,
|
||||
collectionSetStatusFromTripRequestSchema,
|
||||
collectionItemsRequestSchema,
|
||||
collectionPlacesPageRequestSchema,
|
||||
collectionLinkSchema,
|
||||
COLLECTION_PLACES_PAGE_DEFAULT,
|
||||
COLLECTION_PLACES_PAGE_MAX,
|
||||
COLLECTION_STATUSES,
|
||||
COLLECTION_ROLES,
|
||||
idSchema,
|
||||
@@ -46,6 +51,7 @@ import type {
|
||||
CollectionLabelAssignRequest,
|
||||
CollectionSetStatusFromTripRequest,
|
||||
CollectionItemsRequest,
|
||||
CollectionPlacesPageRequest,
|
||||
CollectionStatus,
|
||||
CollectionRole,
|
||||
} from '@trek/shared';
|
||||
@@ -90,6 +96,7 @@ export class CollectionsMcp {
|
||||
readonly addons: AddonsService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
private readonly items: CollectionsItemsService,
|
||||
private readonly placesPage: CollectionsPlacesPageService,
|
||||
) {}
|
||||
|
||||
// ── Read ──────────────────────────────────────────────────────────────
|
||||
@@ -114,7 +121,7 @@ export class CollectionsMcp {
|
||||
@Tool({
|
||||
name: 'get_collection',
|
||||
description:
|
||||
'Get one collection with its members, labels, and all saved places. Each place includes rating_avg / rating_count and the per-member ratings (#1435) so you can plan around highly-rated spots.',
|
||||
'Get one collection with its members, labels, and all saved places. Each place includes rating_avg / rating_count and the per-member ratings (#1435) so you can plan around highly-rated spots. For a long list, page through it with list_collection_places instead.',
|
||||
inputSchema: { collectionId: idSchema },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: collectionsAddonOn,
|
||||
@@ -128,6 +135,23 @@ export class CollectionsMcp {
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_collection_places',
|
||||
description: `Page through one list's saved places in the list's own order (the order get_collection uses), ${COLLECTION_PLACES_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${COLLECTION_PLACES_PAGE_MAX}). Each place as a compact row: id, name, status and label_ids, plus address, lat, lng, google_place_id, website and phone, every one left out when empty. Filter by status, by labelId (a label of this list) or with unlabeled: true for the places without any label. Next to the page: the list's labels, total (the places the filter matches) and next_cursor; pass it back as cursor for the next page, null on the last. A page of long rows can end before limit, so always go on at next_cursor. Labelling the places of a page while paging through unlabeled ones skips none. Pairs with assign_collection_labels and update_collection_place; get_collection_items reads a place in full.`,
|
||||
inputSchema: collectionPlacesPageRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: collectionsAddonOn,
|
||||
access: { group: 'collections', mode: 'read' },
|
||||
})
|
||||
async listCollectionPlaces(request: CollectionPlacesPageRequest, ctx: McpContext) {
|
||||
try {
|
||||
// One line of JSON: the size of a long list is what this tool exists for (#2647).
|
||||
return okCompact(await this.placesPage.listPlaces(ctx.userId, request));
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'available_collection_users',
|
||||
description:
|
||||
|
||||
@@ -22,6 +22,7 @@ import { buildStorageUploadOptions } from '../storage/storage-upload.factory';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { CollectionsItemsService } from './collections-items.service';
|
||||
import { CollectionsPlacesPageService } from './collections-places-page.service';
|
||||
import { CollectionsStorageRefsService } from './collections-storage-refs.service';
|
||||
import { CollectionsController } from './collections.controller';
|
||||
import { MAX_COVER_SIZE } from './collections.controller';
|
||||
@@ -81,6 +82,7 @@ import { MulterModule } from '@nestjs/platform-express';
|
||||
providers: [
|
||||
CollectionsService,
|
||||
CollectionsItemsService,
|
||||
CollectionsPlacesPageService,
|
||||
CollectionsMcp,
|
||||
CollectionsRpc,
|
||||
CollectionsStorageRefsService,
|
||||
|
||||
Reference in New Issue
Block a user