chore: move atlas backend to proper DI

Fold the 1612-line services/atlasService.ts into the DI-native AtlasService:
the stats aggregation, visited countries/regions with the #1490 tombstone and
cascade logic, and the bucket-list CRUD become methods over the injected
DatabaseService. The ~750-line pure-geo half — the bundled admin0/admin1
boundary stores with their #1576 streaming builders, the point-in-polygon
indexes, Nominatim geocoding with its shared throttle, and every module-scoped
cache including the import-time unref'd cleanup interval — moves verbatim to
the plain module atlas-geo.ts so the caches stay process-global across the
container instance, the bridge instance and test helpers (assetPath
re-anchored one directory deeper, the only non-verbatim line).

The 10-tool mcp/tools/atlas.ts registrar plus all four atlas resources in
mcp/resources.ts move onto the decorator registry as atlas.mcp.ts — the when:
atlas-addon gate is parity here (legacy tools and resources both gated; the
REST controller deliberately does not). resources.test.ts retires with its
last two cases, which move to tools-atlas-expanded.test.ts. The plugin RPC
host swaps its 9 atlas imports for the injected AtlasService (23rd constructor
dep); a minimal 2-export atlas.bridge.ts serves the one legacy consumer,
authService.getTravelStats, and dies when authService migrates.

Adopts atlas.dto.ts over the existing shared schemas and clears all three
AtlasController entries from body-contract-allow-list.ts: the hand-rolled
'name and country_code are required' 400 becomes the ZodValidationPipe
envelope (todo/places trade) while the whitespace-only bucket name keeps its
legacy 'Name is required' trim guard.

Fixes the verified defects the relocation had faithfully carried, each with a
regression test (ATLAS-SVC-031..036 plus two MCP casing cases): the four
multi-statement mark/unmark writes now run in db.transaction() (the region
cascade nests as a savepoint), the trip-less countryPlaces early return
honours manually_marked, the '|| null' bindings that dropped lat/lng 0 and
empty-string notes on bucket update become '?? null', the mutating bucket SQL
is user-scoped, and the MCP region/country-places tools uppercase their codes
to match REST.

Quirks deliberately preserved: the detached GET-path place_regions backfill
writes, getStats' two divergent return shapes, the import-time cache-cleanup
interval, getCountryFromAddress's unvalidated bare 2-letter codes, and the
whitespace-only-name silent no-op on bucket update.

Tests move with their case IDs: atlasService.test.ts becomes
unit/nest/atlas.service.test.ts (pure-geo imports from atlas-geo, DB calls
through the constructed service, plus bridge-delegation cases), the atlas e2e
converts to the DI-native pattern (real SQL against the full temp-db schema),
and the plugin-host path mock becomes a constructor stub.
This commit is contained in:
jubnl
2026-08-01 15:50:36 +02:00
parent c78134831f
commit ae3ba18b9e
25 changed files with 1511 additions and 1261 deletions
+6 -44
View File
@@ -1,5 +1,4 @@
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp';
import { listBucketList, listVisitedCountries, getStats as getAtlasStats, listManuallyVisitedRegions } from '../services/atlasService';
import { getNotifications } from '../services/inAppNotifications';
import { isAddonEnabled } from '../nest/addons/addons.bridge';
import { ADDON_IDS } from '../addons';
@@ -82,27 +81,9 @@ export function registerResources(server: McpServer, userId: number, scopes: str
// src/nest/categories/categories.mcp.ts (@Resource, attached via the
// nest-mcp registry in registerTools).
// User's bucket list
if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) server.registerResource(
'bucket-list',
'trek://bucket-list',
{ description: 'Your personal travel bucket list', mimeType: 'application/json' },
async (uri) => {
const items = listBucketList(userId);
return jsonContent(uri.href, items);
}
);
// User's visited countries
if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) server.registerResource(
'visited-countries',
'trek://visited-countries',
{ description: 'Countries you have marked as visited in Atlas', mimeType: 'application/json' },
async (uri) => {
const countries = listVisitedCountries(userId);
return jsonContent(uri.href, countries);
}
);
// The bucket-list and visited-countries resources moved to the DI-discovered
// src/nest/atlas/atlas.mcp.ts (@Resource, attached via the nest-mcp registry
// in registerTools).
// The trip-budget-per-person and trip-budget-settlement resources moved to
// the DI-discovered src/nest/budget/budget.mcp.ts (@ResourceTemplate).
@@ -121,28 +102,9 @@ export function registerResources(server: McpServer, userId: number, scopes: str
}
);
// Atlas stats and regions (addon-gated)
if (isAddonEnabled(ADDON_IDS.ATLAS) && canRead(scopes, 'atlas')) {
server.registerResource(
'atlas-stats',
'trek://atlas/stats',
{ description: "User's atlas statistics — visited country counts and breakdown", mimeType: 'application/json' },
async (uri) => {
const stats = await getAtlasStats(userId);
return jsonContent(uri.href, stats);
}
);
server.registerResource(
'atlas-regions',
'trek://atlas/regions',
{ description: 'List of manually visited regions for the current user', mimeType: 'application/json' },
async (uri) => {
const regions = listManuallyVisitedRegions(userId);
return jsonContent(uri.href, regions);
}
);
}
// The atlas-stats and atlas-regions resources moved to the DI-discovered
// src/nest/atlas/atlas.mcp.ts (@Resource, attached via the nest-mcp registry
// in registerTools).
// The vacay resources moved to the DI-discovered src/nest/vacay/vacay.mcp.ts
// (@McpController, attached via the nest-mcp registry in tools.ts).
+2 -2
View File
@@ -2,7 +2,6 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { registerJourneyTools } from './tools/journey';
import { registerMapsWeatherTools } from './tools/mapsWeather';
import { registerNotificationTools } from './tools/notifications';
import { registerAtlasTools } from './tools/atlas';
import { registerTransportTools } from './tools/transports';
import { registerMcpPrompts } from './tools/prompts';
import { getMcpRegistry } from './registry-handoff';
@@ -38,7 +37,8 @@ export function registerTools(server: McpServer, userId: number, scopes: string[
registerNotificationTools(server, userId, scopes);
registerAtlasTools(server, userId, scopes);
// The atlas tools moved to the DI-discovered src/nest/atlas/atlas.mcp.ts
// (@McpController, attached via the nest-mcp registry below).
// The collab tools moved to the DI-discovered src/nest/collab/collab.mcp.ts
// (@McpController, attached via the nest-mcp registry below).
-201
View File
@@ -1,201 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { isDemoUser } from '../../services/authService';
import {
markCountryVisited, unmarkCountryVisited, createBucketItem, deleteBucketItem,
getStats as getAtlasStats, listManuallyVisitedRegions,
markRegionVisited, unmarkRegionVisited, getCountryPlaces, updateBucketItem,
} from '../../services/atlasService';
import { isAddonEnabled } from '../../nest/addons/addons.bridge';
import { ADDON_IDS } from '../../addons';
import {
TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_READONLY,
demoDenied, ok,
} from './_shared';
import { canRead, canWrite } from '../scopes';
export function registerAtlasTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'atlas');
const W = canWrite(scopes, 'atlas');
if (!isAddonEnabled(ADDON_IDS.ATLAS)) return;
// --- BUCKET LIST ---
if (W) server.registerTool(
'create_bucket_list_item',
{
description: 'Add a destination to your personal travel bucket list.',
inputSchema: {
name: z.string().min(1).max(200).describe('Destination or experience name'),
lat: z.number().optional(),
lng: z.number().optional(),
country_code: z.string().length(2).toUpperCase().optional().describe('ISO 3166-1 alpha-2 country code'),
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ name, lat, lng, country_code, notes }) => {
if (isDemoUser(userId)) return demoDenied();
const item = createBucketItem(userId, { name, lat, lng, country_code, notes });
return ok({ item });
}
);
if (W) server.registerTool(
'delete_bucket_list_item',
{
description: 'Remove an item from your travel bucket list.',
inputSchema: {
itemId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ itemId }) => {
if (isDemoUser(userId)) return demoDenied();
const deleted = deleteBucketItem(userId, itemId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
return ok({ success: true });
}
);
// --- ATLAS ---
if (W) server.registerTool(
'mark_country_visited',
{
description: 'Mark a country as visited in your Atlas.',
inputSchema: {
country_code: z.string().length(2).toUpperCase().describe('ISO 3166-1 alpha-2 country code (e.g. "FR", "JP")'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ country_code }) => {
if (isDemoUser(userId)) return demoDenied();
markCountryVisited(userId, country_code.toUpperCase());
return ok({ success: true, country_code: country_code.toUpperCase() });
}
);
if (W) server.registerTool(
'unmark_country_visited',
{
description: 'Remove a country from your visited countries in Atlas.',
inputSchema: {
country_code: z.string().length(2).toUpperCase().describe('ISO 3166-1 alpha-2 country code'),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ country_code }) => {
if (isDemoUser(userId)) return demoDenied();
unmarkCountryVisited(userId, country_code.toUpperCase());
return ok({ success: true, country_code: country_code.toUpperCase() });
}
);
// --- ATLAS EXPANDED ---
if (R) server.registerTool(
'get_atlas_stats',
{
description: 'Get atlas statistics — total visited countries, region counts, continent breakdown.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const stats = await getAtlasStats(userId);
return ok({ stats });
}
);
if (R) server.registerTool(
'list_visited_regions',
{
description: 'List all manually visited sub-country regions for the current user.',
inputSchema: {},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async () => {
const regions = listManuallyVisitedRegions(userId);
return ok({ regions });
}
);
if (W) server.registerTool(
'mark_region_visited',
{
description: 'Mark a sub-country region as visited.',
inputSchema: {
regionCode: z.string().describe('ISO region code e.g. US-CA'),
regionName: z.string(),
countryCode: z.string().describe('ISO 3166-1 alpha-2 country code'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ regionCode, regionName, countryCode }) => {
if (isDemoUser(userId)) return demoDenied();
markRegionVisited(userId, regionCode, regionName, countryCode);
const row = listManuallyVisitedRegions(userId).find(r => r.region_code === regionCode);
// Echo in the client-facing shape ({ code, name, ... }) rather than raw DB columns.
const region = row
? { code: row.region_code, name: row.region_name, country_code: row.country_code, manuallyMarked: true }
: undefined;
return ok({ region });
}
);
if (W) server.registerTool(
'unmark_region_visited',
{
description: 'Remove a region from the visited list.',
inputSchema: {
regionCode: z.string(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ regionCode }) => {
if (isDemoUser(userId)) return demoDenied();
unmarkRegionVisited(userId, regionCode);
return ok({ success: true });
}
);
if (R) server.registerTool(
'get_country_atlas_places',
{
description: 'Get places saved in the user\'s atlas for a specific country.',
inputSchema: {
countryCode: z.string().describe('ISO 3166-1 alpha-2 country code'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ countryCode }) => {
const result = getCountryPlaces(userId, countryCode);
return ok(result);
}
);
if (W) server.registerTool(
'update_bucket_list_item',
{
description: 'Update a bucket list item (notes, name, target date, location).',
inputSchema: {
itemId: z.number().int().positive(),
name: z.string().optional(),
notes: z.string().optional(),
lat: z.number().nullable().optional(),
lng: z.number().nullable().optional(),
country_code: z.string().optional(),
target_date: z.string().nullable().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ itemId, name, notes, lat, lng, country_code, target_date }) => {
if (isDemoUser(userId)) return demoDenied();
const item = updateBucketItem(userId, itemId, { name, notes, lat, lng, country_code, target_date });
if (!item) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
return ok({ item });
}
);
}