catence 0.2.0-beta.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +38 -166
  2. package/config.example.json +5 -1
  3. package/dist/contracts/index.d.ts +1 -0
  4. package/dist/contracts/index.js +1 -0
  5. package/dist/contracts/progress.d.ts +23 -0
  6. package/dist/contracts/progress.js +49 -0
  7. package/dist/contracts/release.d.ts +1 -1
  8. package/dist/contracts/release.js +1 -1
  9. package/dist/core/logging.d.ts +16 -0
  10. package/dist/core/logging.js +68 -0
  11. package/dist/core/query/activity-discovery.d.ts +2 -0
  12. package/dist/core/query/activity-discovery.js +1 -1
  13. package/dist/core/query/analytics.d.ts +10 -0
  14. package/dist/core/query/analytics.js +494 -0
  15. package/dist/core/query/catalog.d.ts +1 -1
  16. package/dist/core/query/catalog.js +8 -4
  17. package/dist/core/query/events.d.ts +34 -0
  18. package/dist/core/query/events.js +121 -0
  19. package/dist/core/query/fitness.d.ts +4 -0
  20. package/dist/core/query/fitness.js +60 -0
  21. package/dist/core/query/repository.d.ts +2 -0
  22. package/dist/core/query/repository.js +48 -0
  23. package/dist/core/query/swimming.js +2 -2
  24. package/dist/core/runtime/configuration.d.ts +3 -1
  25. package/dist/core/runtime/configuration.js +5 -1
  26. package/dist/core/runtime/opencode-go.d.ts +58 -0
  27. package/dist/core/runtime/opencode-go.js +246 -0
  28. package/dist/core/runtime/secrets.js +51 -13
  29. package/dist/elt/application/detached-sync.d.ts +50 -0
  30. package/dist/elt/application/detached-sync.js +99 -0
  31. package/dist/elt/application/management.d.ts +15 -0
  32. package/dist/elt/application/management.js +435 -19
  33. package/dist/elt/ingestion/importer.d.ts +3 -2
  34. package/dist/elt/ingestion/importer.js +5 -4
  35. package/dist/elt/ingestion/providers/intervals.d.ts +12 -1
  36. package/dist/elt/ingestion/providers/intervals.js +37 -2
  37. package/dist/elt/ingestion/providers/registry.d.ts +13 -0
  38. package/dist/elt/ingestion/providers/registry.js +19 -1
  39. package/dist/elt/ingestion/providers/strava/service.js +7 -1
  40. package/dist/elt/normalization/normalizers.js +207 -15
  41. package/dist/elt/storage/database.d.ts +21 -2
  42. package/dist/elt/storage/database.js +184 -6
  43. package/dist/elt/storage/migrations.js +145 -1
  44. package/dist/elt/storage/progress-sidecar.d.ts +61 -0
  45. package/dist/elt/storage/progress-sidecar.js +200 -0
  46. package/dist/interfaces/cli/commands.js +94 -1
  47. package/dist/interfaces/http/generation-status.d.ts +19 -0
  48. package/dist/interfaces/http/generation-status.js +55 -0
  49. package/dist/interfaces/http/server.d.ts +7 -1
  50. package/dist/interfaces/http/server.js +184 -1
  51. package/dist/interfaces/mcp/main.js +33 -1
  52. package/dist/interfaces/mcp/server.d.ts +2 -1
  53. package/dist/interfaces/mcp/server.js +168 -45
  54. package/dist/runtime/index.d.ts +9 -2
  55. package/dist/runtime/index.js +6 -2
  56. package/docs/architecture.md +13 -2
  57. package/docs/assets/image.png +0 -0
  58. package/docs/configuration.md +243 -0
  59. package/docs/deployment/docker.md +528 -0
  60. package/docs/deployment/local-console.md +263 -0
  61. package/docs/deployment/local-mcp.md +329 -0
  62. package/docs/development.md +337 -0
  63. package/docs/distribution.md +45 -0
  64. package/docs/llm-providers.md +66 -1
  65. package/docs/mcp-activity-retrieval.md +90 -210
  66. package/package.json +1 -1
  67. package/pyproject.toml +1 -1
  68. package/python/catence/providers/garmin/cli.py +43 -9
  69. package/python/catence/providers/garmin/progress.py +85 -0
  70. package/python/catence/providers/garmin/registry.py +2 -0
  71. package/python/catence/providers/garmin/streams.py +38 -0
  72. package/python/catence/providers/garmin/swim_backfill.py +83 -0
  73. package/python/catence/providers/garmin/worker.py +415 -12
  74. package/scripts/discover-opencode-go.mjs +36 -144
  75. package/uv.lock +3 -3
  76. package/docs/deployment.md +0 -338
@@ -1,7 +1,7 @@
1
1
  import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
3
  import { z } from 'zod';
4
- import { ActivityDiscoveryService, AnalyticsService, loadCatalog, configuredMcpRateLimit, DataWriteBusyError, DATASET_CATALOG, demoStoreMetadata, FitnessService, getDataset, hydrateStravaActivity, hydrateStravaSegmentHistory, jsonSafe, loadCatenceConfig, openReadOnlyRepository, queryReadOnlyData, QueryValidationError, ReadOnlyDatabaseError, resolveAthlete, resolveCatalogPaths, searchContext, SlidingWindowLimiter, StravaEnrichmentError, StravaRateLimitError, SwimmingService, WELLNESS_METRICS, WellnessService, } from '../../runtime/index.js';
4
+ import { ActivityDiscoveryService, AnalyticsService, loadCatalog, configuredMcpRateLimit, DataWriteBusyError, DATASET_CATALOG, demoStoreMetadata, DetachedSyncBusyError, EventsService, FitnessService, getDataset, hydrateStravaActivity, hydrateStravaSegmentHistory, jsonSafe, loadCatenceConfig, openReadOnlyRepository, queryReadOnlyData, QueryValidationError, ReadOnlyDatabaseError, resolveAthlete, resolveCatalogPaths, searchContext, SlidingWindowLimiter, startDetachedSync, StravaEnrichmentError, StravaRateLimitError, SwimmingService, WELLNESS_METRICS, WellnessService, } from '../../runtime/index.js';
5
5
  const filterSchema = z.object({
6
6
  column: z.string().min(1),
7
7
  op: z.enum(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'in', 'between', 'contains']),
@@ -27,22 +27,30 @@ const MCP_INSTRUCTIONS = [
27
27
  'That tool performs the targeted Strava hydration itself. Do not say segment data is unavailable before it returns; if it reports not_found, ambiguous, authorization, throttling, or an error, report that exact outcome instead.',
28
28
  'For Garmin running VO₂max, call get_vo2max_history with sport: running. Garmin stores the source value as generic; returned rows preserve that source label.',
29
29
  'Aggregate elevation alone cannot support an individual-climb conclusion. Use source-specific facts and their stated coverage.',
30
+ 'For race-readiness / fitness-target questions, establish a trend-first baseline (readiness_baseline, analyze_series, aggregate_data time buckets) before comparing any single activity.',
31
+ 'Never conclude from VO2max alone; pull full indicator set (LT/FTP/power/race-prediction).',
32
+ 'When summary metric is NULL (e.g. avg_power), fall through to FIT-derived/samples layer before declaring absence.',
33
+ 'Before reusing any prior course/elevation profile, resolve event\'s courseId and diff it against past activity\'s course; different courseId => different profile.',
34
+ 'If a needed tool is not visible in your current tool list (the host may truncate it to a subset), read the catence://tools resource to discover all available tools before concluding a capability is absent.',
35
+ 'For swim analysis: use find_activities (sports: ["lap_swimming"] or sport: "lap_swimming") to list pool sessions. Use get_swim_laps for per-length data (pace from duration_s/pool_length_m, SPL from stroke_count, SWOLF from duration_s+stroke_count). Use swim_progress_report for session-level SWOLF, fastest-100, and stroke cadence. Per-length SWOLF is derived when the provider does not supply it. Per-length distance is typically null in Garmin FIT; use pool_length_m for pace calculations.',
30
36
  ].join(' ');
31
37
  function textResult(value) {
32
38
  return { content: [{ type: 'text', text: JSON.stringify(jsonSafe(value), null, 2) }] };
33
39
  }
34
40
  function errorResult(error) {
35
- const classified = error instanceof DataWriteBusyError
36
- ? { code: 'data_sync_in_progress', message: error.message, retryable: true }
37
- : error instanceof StravaRateLimitError
38
- ? { code: 'rate_limited', message: error.message, retryable: true, retryAfterSeconds: error.retryAfterSeconds ?? null }
39
- : error instanceof StravaEnrichmentError
40
- ? { code: 'strava_connection_error', message: error.message }
41
- : error instanceof ReadOnlyDatabaseError
42
- ? { code: error.code, message: error.message }
43
- : error instanceof QueryValidationError
44
- ? { code: 'invalid_request', message: error.message }
45
- : { code: 'data_unavailable', message: error instanceof Error ? error.message : String(error) };
41
+ const classified = error instanceof DetachedSyncBusyError
42
+ ? { code: 'sync_in_progress', message: error.message, retryable: true, runId: error.runId }
43
+ : error instanceof DataWriteBusyError
44
+ ? { code: 'data_sync_in_progress', message: error.message, retryable: true }
45
+ : error instanceof StravaRateLimitError
46
+ ? { code: 'rate_limited', message: error.message, retryable: true, retryAfterSeconds: error.retryAfterSeconds ?? null }
47
+ : error instanceof StravaEnrichmentError
48
+ ? { code: 'strava_connection_error', message: error.message }
49
+ : error instanceof ReadOnlyDatabaseError
50
+ ? { code: error.code, message: error.message }
51
+ : error instanceof QueryValidationError
52
+ ? { code: 'invalid_request', message: error.message }
53
+ : { code: 'data_unavailable', message: error instanceof Error ? error.message : String(error) };
46
54
  return { ...textResult({ data: null, provenance: {}, query: {}, caveats: [classified.message], error: classified }), isError: true };
47
55
  }
48
56
  function hydrationFailure(error) {
@@ -123,6 +131,7 @@ async function activitySegments(repository, activityId, hydratedStravaActivityId
123
131
  export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependencies = {}) {
124
132
  const server = new McpServer({ name: 'catence', version: '0.1.0' }, { instructions: MCP_INSTRUCTIONS });
125
133
  const hydrateActivity = dependencies.hydrateStravaActivity ?? hydrateStravaActivity;
134
+ const startSync = dependencies.startDetachedSync ?? startDetachedSync;
126
135
  const catalogPaths = isCatalogPaths(paths) ? paths : null;
127
136
  const staticPaths = isCatalogPaths(paths) ? null : paths;
128
137
  const scope = new AsyncLocalStorage();
@@ -130,9 +139,16 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
130
139
  const activeAthlete = () => scope.getStore()?.athlete;
131
140
  const limiter = new SlidingWindowLimiter();
132
141
  const athleteIdSchema = z.string().regex(/^[a-z][a-z0-9-]{0,62}$/);
142
+ // Discoverability: record every registered tool so the catence://tools resource can
143
+ // enumerate all tools even when the host harness truncates the visible tool list.
144
+ const TOOL_INDEX = [];
145
+ function registerTool(name, config, callback) {
146
+ TOOL_INDEX.push({ name, title: config.title ?? name, description: config.description ?? '' });
147
+ server.registerTool(name, config, callback);
148
+ }
133
149
  const promptAthleteSchema = catalogPaths ? { athleteId: athleteIdSchema } : {};
134
150
  if (catalogPaths) {
135
- server.registerTool('list_athletes', {
151
+ registerTool('list_athletes', {
136
152
  title: 'List configured athletes',
137
153
  description: 'List athlete IDs and labels available to this shared Catence agent. No personal metrics are returned.',
138
154
  }, async () => {
@@ -147,10 +163,29 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
147
163
  const originalRegister = server.registerTool.bind(server);
148
164
  server.registerTool = (name, configuration, handler) => {
149
165
  const originalInput = configuration.inputSchema;
166
+ let mergedInputSchema;
167
+ if (originalInput) {
168
+ const hasV4 = '_zod' in originalInput;
169
+ const hasV3 = '_def' in originalInput;
170
+ if (hasV4 || hasV3) {
171
+ // originalInput is already a Zod object schema; extract its shape and
172
+ // merge athleteId into a new object of the same Zod version.
173
+ const rawShape = originalInput.shape;
174
+ const shape = typeof rawShape === 'object' && rawShape !== null ? rawShape : {};
175
+ mergedInputSchema = z.object({ ...shape, athleteId: athleteIdSchema });
176
+ }
177
+ else {
178
+ // originalInput is a raw shape (plain object of Zod schemas).
179
+ mergedInputSchema = { athleteId: athleteIdSchema, ...originalInput };
180
+ }
181
+ }
182
+ else {
183
+ mergedInputSchema = { athleteId: athleteIdSchema };
184
+ }
150
185
  return originalRegister(name, {
151
186
  ...configuration,
152
187
  description: `${String(configuration.description ?? '')} Requires athleteId from list_athletes.`,
153
- inputSchema: { athleteId: athleteIdSchema, ...(originalInput ?? {}) },
188
+ inputSchema: mergedInputSchema,
154
189
  }, handler);
155
190
  };
156
191
  }
@@ -176,7 +211,12 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
176
211
  ...(demoStore ? { demoStore: { generated: true, seed: demoStore.seed, days: demoStore.days, startDate: demoStore.startDate, endDate: demoStore.endDate }, caveats: [...caveats, 'This response uses Catence generated demo data, not personal measurements.'] } : {}),
177
212
  });
178
213
  };
179
- return selected ? scope.run(selected, run) : run();
214
+ // `return await` matters here: a bare `return run()` would let a
215
+ // rejected promise escape the try block, bypassing the classified
216
+ // errorResult payload entirely.
217
+ if (selected)
218
+ return await scope.run(selected, run);
219
+ return await run();
180
220
  }
181
221
  catch (error) {
182
222
  return errorResult(error);
@@ -221,17 +261,46 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
221
261
  }, ({ activityId, ...input }) => ({
222
262
  messages: [{
223
263
  role: 'user',
224
- content: { type: 'text', text: `Run review_activity_deep_dive for ${activityId}${typeof input.athleteId === 'string' ? ` with athleteId ${input.athleteId}` : ''}. Use its source records and intervals first; load read_series only if a specific sampled metric is needed.` },
264
+ content: { type: 'text', text: `Run review_activity_deep_dive for ${activityId}${typeof input.athleteId === 'string' ? ` with athleteId ${input.athleteId}` : ''}. Use its source records and intervals first; load read_series only if a specific sampled metric is needed. Use as anchor for current form only after trend baseline exists.` },
225
265
  }],
226
266
  }));
227
- server.registerTool('catence_status', {
267
+ registerTool('catence_status', {
228
268
  title: 'Catence data status',
229
269
  description: 'Read sync state, data coverage, entity counts, stream availability, unresolved errors, and retrieval-index freshness. Read-only.',
230
270
  }, tool('catence_status', async () => useRepository(activePaths(), async (repository) => ({
231
271
  data: { ...(await repository.status()), ...(await repository.coverage()) },
232
272
  provenance: { database: 'read-only DuckDB snapshot' }, query: {}, caveats: [],
233
273
  }))));
234
- server.registerTool('review_daily_recovery_load', {
274
+ registerTool('catence_sync_progress', {
275
+ title: 'Catence sync progress',
276
+ description: 'Read live progress heartbeats for active sync runs, plus the most recent completed or interrupted runs. Read-only.',
277
+ }, tool('catence_sync_progress', async () => useRepository(activePaths(), async (repository) => ({
278
+ data: await repository.progress(),
279
+ provenance: { database: 'read-only DuckDB snapshot' }, query: {}, caveats: [],
280
+ }))));
281
+ registerTool('start_detached_sync', {
282
+ title: 'Start a detached data sync',
283
+ description: 'Write-only sync trigger, named like the other explicit lock-guarded write tools. Spawns one detached catence-data sync process for this athlete and returns immediately with the run handle and log file; it refuses while another sync run is active. Track the run with catence_sync_progress; this tool never waits for completion.',
284
+ inputSchema: {
285
+ provider: z.enum(['intervals', 'garmin', 'strava', 'all']).optional(),
286
+ from: z.string().date().optional(),
287
+ refresh: z.boolean().optional(),
288
+ },
289
+ }, tool('start_detached_sync', async (input) => {
290
+ const paths = activePaths();
291
+ const athleteId = activeAthlete()?.id ?? 'local';
292
+ const handle = await startSync({ paths, athleteId, provider: input.provider, from: input.from, refresh: input.refresh });
293
+ return {
294
+ data: { ...handle, progressTool: 'catence_sync_progress' },
295
+ provenance: { operation: 'detached_sync_spawn' },
296
+ query: { ...input },
297
+ caveats: [
298
+ 'The sync runs in its own process and keeps running if this session ends; its log file records the full worker output.',
299
+ 'Only one sync run may be active per athlete store.',
300
+ ],
301
+ };
302
+ }));
303
+ registerTool('review_daily_recovery_load', {
235
304
  title: 'Review daily recovery and training load',
236
305
  description: 'Return source-cited daily health, training, and nutrition facts for a recovery/load review. It does not prescribe a training plan.',
237
306
  inputSchema: { date: z.string().date().optional() },
@@ -247,7 +316,7 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
247
316
  ],
248
317
  }));
249
318
  }));
250
- server.registerTool('review_weekly_training', {
319
+ registerTool('review_weekly_training', {
251
320
  title: 'Review seven days of training',
252
321
  description: 'Return source-cited health, training, and nutrition facts for the seven-day period ending on an optional date. It does not prescribe a training plan.',
253
322
  inputSchema: { endDate: z.string().date().optional() },
@@ -264,7 +333,7 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
264
333
  ],
265
334
  }));
266
335
  }));
267
- server.registerTool('review_activity_deep_dive', {
336
+ registerTool('review_activity_deep_dive', {
268
337
  title: 'Review one activity in depth',
269
338
  description: 'Return canonical activity identity, source summaries, and structured intervals. Call read_series separately only when a specific sampled metric is required.',
270
339
  inputSchema: { activityId: z.string().min(1) },
@@ -279,14 +348,14 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
279
348
  : ['No canonical activity matched this activityId. Use find_activities before drawing conclusions.'],
280
349
  };
281
350
  })));
282
- server.registerTool('describe_data', {
351
+ registerTool('describe_data', {
283
352
  title: 'Describe available Catence datasets',
284
353
  description: 'List cataloged datasets, fields, units, permitted filters/groupings, providers, and time coverage. Read-only.',
285
354
  }, tool('describe_data', async () => useRepository(activePaths(), async (repository) => ({
286
355
  data: { datasets: repository.catalog(), ...(await repository.coverage()) },
287
356
  provenance: { catalog: 'Catence catalog, restricted to analytical views' }, query: {}, caveats: ['activity_samples is available only through read_series or aggregate_data and only reads registered Parquet stream manifests.'],
288
357
  }))));
289
- server.registerTool('describe_dataset', {
358
+ registerTool('describe_dataset', {
290
359
  title: 'Describe one Catence dataset',
291
360
  description: 'Read a compact schema, permitted filters/groupings, provenance fields, and coverage for one cataloged dataset. Read-only.',
292
361
  inputSchema: { dataset: z.string().min(1) },
@@ -309,10 +378,10 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
309
378
  provenance: { catalog: 'Catence catalog', database: 'read-only DuckDB snapshot' }, query: input, caveats: [],
310
379
  };
311
380
  })));
312
- server.registerTool('read_series', {
381
+ registerTool('read_series', {
313
382
  title: 'Read a bounded time series', description: 'Read cataloged numeric series with deterministic cursor pagination and automatic stream downsampling. metrics must be numeric catalog columns; place identifiers and other strings in filters. Call describe_dataset first if the fields are uncertain.', inputSchema: seriesInput,
314
383
  }, tool('read_series', async (input) => useRepository(activePaths(), (repository) => new AnalyticsService(repository).readSeries({ ...input, filters: input.filters }))));
315
- server.registerTool('aggregate_data', {
384
+ registerTool('aggregate_data', {
316
385
  title: 'Aggregate cataloged data', description: 'Declarative aggregation over one cataloged dataset. A timeBucket adds a time_bucket field, which can be used in orderBy. No joins, arbitrary expressions, or file paths.',
317
386
  inputSchema: {
318
387
  dataset: z.string().min(1),
@@ -320,15 +389,42 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
320
389
  dimensions: z.array(z.string().min(1)).max(8).optional(), filters: z.array(filterSchema).max(50).optional(), startDate: z.string().date().optional(), endDate: z.string().date().optional(), timeBucket: z.enum(['day', 'week', 'month']).optional(), orderBy: z.object({ column: z.string().min(1), direction: z.enum(['asc', 'desc']).optional() }).optional(), limit: z.number().int().min(1).max(500).optional(),
321
390
  },
322
391
  }, tool('aggregate_data', async (input) => useRepository(activePaths(), (repository) => new AnalyticsService(repository).aggregate({ ...input, filters: input.filters }))));
323
- server.registerTool('analyze_series', {
392
+ registerTool('analyze_series', {
324
393
  title: 'Analyze a descriptive series', description: 'Run deterministic rolling statistics, baselines, correlations, seasonal comparisons, or trends on a cataloged series.',
325
394
  inputSchema: { ...seriesInput, analysis: z.enum(['rolling_mean', 'rolling_median', 'baseline_change', 'z_score', 'pearson', 'spearman', 'seasonal_comparison', 'linear_trend', 'theil_sen_trend']), compareMetric: z.string().min(1).optional(), window: z.number().int().min(2).max(100).optional() },
326
395
  }, tool('analyze_series', async (input) => useRepository(activePaths(), (repository) => new AnalyticsService(repository).analyzeSeries({ ...input, filters: input.filters }))));
327
- server.registerTool('fit_series_model', {
396
+ registerTool('fit_series_model', {
328
397
  title: 'Fit a descriptive series model', description: 'Fit a bounded OLS, Theil–Sen, quadratic, or cubic descriptive model. Not a sport-performance model.',
329
398
  inputSchema: { ...seriesInput, model: z.enum(['ols_linear', 'theil_sen_linear', 'polynomial_2', 'polynomial_3']), xMetric: z.string().min(1).optional(), yMetric: z.string().min(1).optional() },
330
399
  }, tool('fit_series_model', async (input) => useRepository(activePaths(), (repository) => new AnalyticsService(repository).fitSeriesModel({ ...input, filters: input.filters }))));
331
- server.registerTool('wellness_correlate', {
400
+ registerTool('activity_decoupling', {
401
+ title: 'Derive aerobic decoupling and GAP for one activity',
402
+ description: 'Derive aerobic decoupling (Pa:Hr for running using speed/HR, Pw:Hr for cycling using power/HR — drift across steady first/second halves) and grade-adjusted pace (GAP, Minetti 2002 cost model) from stored activity_samples for one activity. Returns null with explanatory caveats when samples are insufficient, walk-heavy, or stop-heavy. Derived values are descriptive only and never overwrite provider-supplied decoupling/GAP. Read-only.',
403
+ inputSchema: { activityId: z.string().min(1), includeGap: z.boolean().optional() },
404
+ }, tool('activity_decoupling', async (input) => useRepository(activePaths(), async (repository) => {
405
+ const analytics = new AnalyticsService(repository);
406
+ const decoupling = await analytics.deriveDecoupling({ activityId: input.activityId });
407
+ const gap = input.includeGap === false ? null : await analytics.deriveGap({ activityId: input.activityId });
408
+ const decouplingData = decoupling;
409
+ const gapData = gap;
410
+ const combinedCaveats = [
411
+ ...(decouplingData.caveats ?? []),
412
+ ...(gapData?.caveats ?? []),
413
+ ];
414
+ return jsonSafe({
415
+ data: { decoupling: decouplingData.data ?? null, gap: gapData?.data ?? null, decouplingRaw: decouplingData, gapRaw: gapData },
416
+ provenance: {
417
+ decoupling: decouplingData.provenance,
418
+ gap: gapData?.provenance ?? null,
419
+ derivation: 'derived',
420
+ note: 'Both metrics are derived from activity_samples (Parquet lake) when provider summaries do not supply them; provider values remain authoritative.',
421
+ },
422
+ query: { activityId: input.activityId, includeGap: input.includeGap ?? true, decouplingQuery: decouplingData.query, gapQuery: gapData?.query ?? null },
423
+ caveats: combinedCaveats.length ? combinedCaveats : ['Derived metrics are descriptive only; not a physiological performance model.'],
424
+ inputs: { decouplingInput: decouplingData.input, gapInput: gapData?.input ?? null },
425
+ });
426
+ })));
427
+ registerTool('wellness_correlate', {
332
428
  title: 'Correlate recovery and training metrics',
333
429
  description: 'Calculate a compact daily Pearson or Spearman correlation between curated wellness and training metrics, with an optional -7 through +7 day lag scan. Descriptive only.',
334
430
  inputSchema: {
@@ -336,35 +432,55 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
336
432
  method: z.enum(['pearson', 'spearman']).optional(), lagDays: z.number().int().min(-30).max(30).optional(), scanLags: z.boolean().optional(),
337
433
  },
338
434
  }, tool('wellness_correlate', async (input) => useRepository(activePaths(), (repository) => new WellnessService(repository).correlate(input))));
339
- server.registerTool('wellness_baselines', {
435
+ registerTool('wellness_baselines', {
340
436
  title: 'Read personal wellness baselines',
341
437
  description: 'Return trailing means, standard-deviation bands, latest values, and latest z-scores for common recovery and training metrics. Missing values remain missing.',
342
438
  inputSchema: { metrics: z.array(z.enum(WELLNESS_METRICS)).min(1).max(12).optional(), endDate: z.string().date().optional(), windowDays: z.number().int().min(7).max(365).optional() },
343
439
  }, tool('wellness_baselines', async (input) => useRepository(activePaths(), (repository) => new WellnessService(repository).baselines(input))));
344
- server.registerTool('wellness_anomalies', {
440
+ registerTool('wellness_anomalies', {
345
441
  title: 'Find statistical wellness anomalies',
346
442
  description: 'Find daily recovery and wellness outliers by z-score and group dates with anomalies across multiple signals. This does not diagnose or prescribe.',
347
443
  inputSchema: { metrics: z.array(z.enum(WELLNESS_METRICS)).min(1).max(12).optional(), startDate: z.string().date().optional(), endDate: z.string().date().optional(), zThreshold: z.number().min(1).max(5).optional() },
348
444
  }, tool('wellness_anomalies', async (input) => useRepository(activePaths(), (repository) => new WellnessService(repository).anomalies(input))));
349
- server.registerTool('wellness_coverage', {
445
+ registerTool('wellness_coverage', {
350
446
  title: 'Inspect wellness data coverage',
351
447
  description: 'Report present and missing dates for curated wellness/training metrics, plus unresolved extraction errors. Missing data is never interpreted as rest or a health outcome.',
352
448
  inputSchema: { metrics: z.array(z.enum(WELLNESS_METRICS)).min(1).max(12).optional(), startDate: z.string().date().optional(), endDate: z.string().date().optional() },
353
449
  }, tool('wellness_coverage', async (input) => useRepository(activePaths(), (repository) => new WellnessService(repository).coverage(input))));
354
- server.registerTool('get_ftp_history', {
450
+ registerTool('get_ftp_history', {
355
451
  title: 'Get dated FTP history',
356
452
  description: 'Return normalized cycling FTP settings and activity-summary observations with source-aware preferred daily values. Read-only.',
357
453
  inputSchema: { sport: z.string().min(1).optional(), startDate: z.string().date().optional(), endDate: z.string().date().optional(), sourcePreference: z.enum(['settings', 'settings_then_activity', 'all']).optional() },
358
454
  }, tool('get_ftp_history', async (input) => useRepository(activePaths(), (repository) => new FitnessService(repository).ftpHistory(input))));
359
- server.registerTool('get_vo2max_history', {
455
+ registerTool('readiness_baseline', {
456
+ title: 'Read a running/race readiness baseline',
457
+ description: 'Combine the full performance-indicator set — running lactate threshold (pace/power/HR), VO₂max, race predictions, fitness trend, endurance score, and FIT-derived power bests/coverage — as trends in one call. Use this before any single-activity comparison for race-readiness or fitness-target questions.',
458
+ inputSchema: { sport: z.string().min(1).optional(), startDate: z.string().date().optional(), endDate: z.string().date().optional() },
459
+ }, tool('readiness_baseline', async (input) => useRepository(activePaths(), (repository) => new FitnessService(repository).readinessBaseline(input))));
460
+ registerTool('resolve_event_course', {
461
+ title: 'Resolve a race event course and its synced geometry',
462
+ description: 'Given a Garmin/Intervals eventId, return the courseId it references and whether that course geometry has been synced. When geometry is absent, the result carries an explicit caveat so a prior course profile is never reused. Optionally pass pastActivityId to diff the event course against that activity\'s course.',
463
+ inputSchema: { eventId: z.string().min(1), pastActivityId: z.string().min(1).optional() },
464
+ }, tool('resolve_event_course', async (input) => useRepository(activePaths(), async (repository) => {
465
+ const events = new EventsService(repository);
466
+ const resolved = await events.resolveEventCourse(input.eventId);
467
+ const diff = input.pastActivityId ? await events.diffCourseProfiles(resolved.courseId, input.pastActivityId) : null;
468
+ return {
469
+ data: { event: resolved, courseDiff: diff },
470
+ provenance: { relation: 'source_entities' },
471
+ caveats: [...resolved.caveats, ...(diff?.caveats ?? [])],
472
+ };
473
+ })));
474
+ registerTool('get_vo2max_history', {
360
475
  title: 'Get sport-specific VO₂max history',
361
476
  description: 'Return normalized Garmin VO₂max observations for exactly one sport. For running, pass sport: running (or run): Garmin supplies that series with raw sport generic, which is preserved in each row. Cycling remains separate. Omit sport only to inspect available source labels. Read-only.',
362
477
  inputSchema: { sport: z.string().min(1).optional(), startDate: z.string().date().optional(), endDate: z.string().date().optional() },
363
478
  }, tool('get_vo2max_history', async (input) => useRepository(activePaths(), (repository) => new FitnessService(repository).vo2MaxHistory(input))));
364
- server.registerTool('find_activities', {
479
+ registerTool('find_activities', {
365
480
  title: 'Find activities and likely races',
366
481
  description: 'Find canonical activities by sport, distance, name, and date. Results are paginated and transparently flag likely-race signals without claiming provider-confirmed race metadata. Read-only.',
367
482
  inputSchema: {
483
+ sport: z.string().min(1).optional(),
368
484
  sports: z.array(z.string().min(1)).min(1).max(12).optional(),
369
485
  distanceKm: z.tuple([z.number().min(0), z.number().min(0)]).optional(),
370
486
  nameContains: z.array(z.string().min(1)).min(1).max(12).optional(),
@@ -372,17 +488,17 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
372
488
  sort: z.enum(['date_desc', 'date_asc']).optional(), limit: z.number().int().min(1).max(100).optional(), cursor: z.string().min(1).optional(),
373
489
  },
374
490
  }, tool('find_activities', async (input) => useRepository(activePaths(), (repository) => new ActivityDiscoveryService(repository).findActivities(input))));
375
- server.registerTool('get_swim_laps', {
491
+ registerTool('get_swim_laps', {
376
492
  title: 'Read explicit swim lengths and grouped sets',
377
493
  description: 'Return source-aware swim lengths when a provider actually supplied them, plus Garmin detected and Intervals.icu auto-detected sets. A missing length list is reported as unavailable; laps are never reconstructed from samples.',
378
494
  inputSchema: { activityId: z.string().min(1), provider: z.enum(['garmin', 'intervals']).optional() },
379
495
  }, tool('get_swim_laps', async (input) => useRepository(activePaths(), (repository) => new SwimmingService(repository).swimLaps(input))));
380
- server.registerTool('swim_progress_report', {
496
+ registerTool('swim_progress_report', {
381
497
  title: 'Build a source-aware swim progress report',
382
498
  description: 'Compare Garmin swimming summaries and data completeness over a date range, optionally within one pool length. It does not derive pace trends from moving time divided by distance.',
383
499
  inputSchema: { startDate: z.string().date().optional(), endDate: z.string().date().optional(), poolLengthM: z.number().positive().max(200).optional() },
384
500
  }, tool('swim_progress_report', async (input) => useRepository(activePaths(), (repository) => new SwimmingService(repository).swimProgressReport(input))));
385
- server.registerTool('get_activity_segments', {
501
+ registerTool('get_activity_segments', {
386
502
  title: 'Hydrate and read an activity’s Strava segments',
387
503
  description: 'For a selected activity’s segments, climbs, KOM/PRs, or per-segment analysis: automatically hydrate the matching Strava activity before returning its persisted segment efforts. Use this before saying segment data is unavailable.',
388
504
  inputSchema: { activityId: z.string().min(1), refresh: z.boolean().optional(), limit: z.number().int().min(1).max(500).optional() },
@@ -400,35 +516,35 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
400
516
  ],
401
517
  };
402
518
  }));
403
- server.registerTool('power_curve_trend', {
519
+ registerTool('power_curve_trend', {
404
520
  title: 'Read labelled power-curve trends',
405
521
  description: 'Return monthly bests for selected power durations from an explicit sport or sport family, including the supporting activity and source type. Read-only.',
406
522
  inputSchema: { sport: z.string().min(1).optional(), sportFamily: z.enum(['cycling', 'running']).optional(), durations: z.array(z.number().int().min(1).max(86_400)).min(1).max(12).optional(), startDate: z.string().date().optional(), endDate: z.string().date().optional(), sourceQuality: z.enum(['all', 'garmin_fit_derived']).optional() },
407
523
  }, tool('power_curve_trend', async (input) => useRepository(activePaths(), (repository) => new FitnessService(repository).powerCurveTrend(input))));
408
- server.registerTool('power_coverage_report', {
524
+ registerTool('power_coverage_report', {
409
525
  title: 'Inspect FIT-derived power coverage',
410
526
  description: 'Report powered activities and the complete duration-best inventory for an explicit sport or sport family. Uses Garmin FIT-derived power, not sparse activity summaries. Read-only.',
411
527
  inputSchema: { sport: z.string().min(1).optional(), sportFamily: z.enum(['cycling', 'running']).optional(), startDate: z.string().date().optional(), endDate: z.string().date().optional(), sourceQuality: z.enum(['all', 'garmin_fit_derived']).optional() },
412
528
  }, tool('power_coverage_report', async (input) => useRepository(activePaths(), (repository) => new FitnessService(repository).powerCoverageReport(input))));
413
- server.registerTool('latest_cycling_activities', {
529
+ registerTool('latest_cycling_activities', {
414
530
  title: 'List latest cycling activities',
415
531
  description: 'List Garmin cycling source records without duplicate Intervals summaries, optionally flagging multisport parent records. Read-only.',
416
532
  inputSchema: { startDate: z.string().date().optional(), endDate: z.string().date().optional(), includeMultisport: z.boolean().optional(), limit: z.number().int().min(1).max(100).optional() },
417
533
  }, tool('latest_cycling_activities', async (input) => useRepository(activePaths(), (repository) => new FitnessService(repository).latestCyclingActivities(input))));
418
- server.registerTool('cycling_progress_report', {
534
+ registerTool('cycling_progress_report', {
419
535
  title: 'Build a cycling progress report',
420
536
  description: 'Combine source-aware FTP and VO₂max histories with monthly canonical volume/load and labelled power-curve trends. Read-only and descriptive.',
421
537
  inputSchema: { startDate: z.string().date().optional(), endDate: z.string().date().optional() },
422
538
  }, tool('cycling_progress_report', async (input) => useRepository(activePaths(), (repository) => new FitnessService(repository).cyclingProgressReport(input))));
423
- server.registerTool('query_read_only_data', {
539
+ registerTool('query_read_only_data', {
424
540
  title: 'Query cataloged read-only data', description: 'Advanced fallback after describe_data/describe_dataset: one parameterized SELECT or WITH … SELECT over cataloged views only. Do not query information_schema, DuckDB system tables, or uncataloged physical relations. Results use deterministic cursor pagination and always report whether they are incomplete. Filesystem access, extensions, DDL, and mutation are rejected.',
425
541
  inputSchema: { sql: z.string().min(1).max(20_000), values: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])).refine((value) => Object.keys(value).length <= 100, 'At most 100 bind values are allowed.').optional(), cursor: z.string().min(1).optional(), pageSize: z.number().int().min(1).max(500).optional() },
426
542
  }, tool('query_read_only_data', async (input) => useRepository(activePaths(), (repository) => queryReadOnlyData(repository, input))));
427
- server.registerTool('search_context', {
543
+ registerTool('search_context', {
428
544
  title: 'Search generated context', description: 'Search compact generated activity, plan, nutrition, and message context. Results identify authoritative follow-up tools rather than making numerical claims.',
429
545
  inputSchema: { query: z.string().min(2).max(500), filters: z.array(z.object({ column: z.enum(['provider', 'entity_type', 'occurred_on']), op: z.enum(['eq', 'in', 'between']), value: z.unknown() })).max(20).optional(), limit: z.number().int().min(1).max(50).optional() },
430
546
  }, tool('search_context', async (input) => useRepository(activePaths(), (repository) => searchContext(repository, input))));
431
- server.registerTool('hydrate_strava_activity', {
547
+ registerTool('hydrate_strava_activity', {
432
548
  title: 'Hydrate one activity from Strava',
433
549
  description: 'Write-only targeted enrichment. Safely matches exactly one Catence activity/source to Strava, then archives and persists its activity detail, gear assignment, and segment efforts. For a segment/climb request, prefer get_activity_segments, which invokes this prerequisite automatically.',
434
550
  inputSchema: { activityId: z.string().min(1), refresh: z.boolean().optional() },
@@ -436,7 +552,7 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
436
552
  const data = await hydrateActivity(activePaths(), input.activityId, input.refresh ?? false);
437
553
  return { data, coverage: await useRepository(activePaths(), (repository) => repository.coverage()), provenance: { provider: 'strava', operation: 'activity_detail', archivedBeforeNormalization: true }, caveats: ['Segment verification is unavailable from Strava public segment data and is never inferred.'] };
438
554
  }));
439
- server.registerTool('hydrate_recent_strava_activities', {
555
+ registerTool('hydrate_recent_strava_activities', {
440
556
  title: 'Hydrate several recent Strava activities',
441
557
  description: 'Write-only targeted batch enrichment. Select an explicit list or a bounded date/sport window; Catence hydrates one activity at a time and reports every outcome.',
442
558
  inputSchema: z.object({
@@ -504,7 +620,7 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
504
620
  caveats: ['Each write is intentionally awaited before the next one, preventing data-directory lock contention.', 'not_found and ambiguous results include match diagnostics when Strava supplied them.'],
505
621
  };
506
622
  }));
507
- server.registerTool('hydrate_strava_segment_history', {
623
+ registerTool('hydrate_strava_segment_history', {
508
624
  title: 'Hydrate one Strava segment history',
509
625
  description: 'Write-only targeted enrichment. Fetches a persisted Strava segment and the authenticated athlete’s paged historic efforts; interrupted or throttled work is resumable.',
510
626
  inputSchema: { segmentId: z.string().min(1), refresh: z.boolean().optional() },
@@ -560,6 +676,13 @@ export function createCatenceMcpServer(paths = resolveCatalogPaths(), dependenci
560
676
  }
561
677
  });
562
678
  }
679
+ server.registerResource('tools', 'catence://tools', { title: 'Catence tool index', mimeType: 'application/json' }, async (uri) => {
680
+ return resource(uri, {
681
+ count: TOOL_INDEX.length,
682
+ note: 'If a needed tool is not visible in your current tool list (the host may truncate it), use this index to discover all available tools before concluding a capability is absent. SQL-only tables training_metric_observations and source_entities are reachable via query_read_only_data / describe_data.',
683
+ tools: TOOL_INDEX.map((tool) => ({ name: tool.name, purpose: tool.title, description: tool.description })),
684
+ });
685
+ });
563
686
  return server;
564
687
  }
565
688
  function variable(value) {
@@ -23,13 +23,20 @@ export type { DataFilter } from '../core/query/analytics.js';
23
23
  export { ActivityDiscoveryService } from '../core/query/activity-discovery.js';
24
24
  export { DATASET_CATALOG, getDataset, QueryValidationError } from '../core/query/catalog.js';
25
25
  export { FitnessService } from '../core/query/fitness.js';
26
+ export { EventsService, extractCourseId } from '../core/query/events.js';
26
27
  export { SwimmingService } from '../core/query/swimming.js';
27
28
  export { WELLNESS_METRICS, WellnessService } from '../core/query/wellness.js';
28
29
  export { jsonSafe, ReadOnlyRepository } from '../core/query/repository.js';
29
30
  export { queryReadOnlyData } from '../core/query/sql-guard.js';
30
31
  export { createDemoStore, demoStoreMetadata } from '../elt/application/demo.js';
31
- export { connectStrava, connectStravaWithCallback, dataStatus, disconnectStravaAccount, initializeDataStore, linkActivity, rebuildRetrievalIndex, retryDataSync, syncData, unlinkActivity, } from '../elt/application/management.js';
32
+ export { connectStrava, connectStravaWithCallback, dataStatus, disconnectStravaAccount, initializeDataStore, importStagedFile, linkActivity, rebuildRetrievalIndex, reimportNutrition, resolveExtractionErrors, retryDataSync, syncData, syncProgress, unlinkActivity, } from '../elt/application/management.js';
32
33
  export type { ProviderChoice } from '../elt/application/management.js';
33
- export { openReadOnlyRepository, ReadOnlyDatabaseError } from '../elt/storage/database.js';
34
+ export { DETACHED_SYNC_PROVIDERS, DetachedSyncBusyError, startDetachedSync, } from '../elt/application/detached-sync.js';
35
+ export type { DetachedSyncHandle, DetachedSyncProvider, DetachedSyncRequest, DetachedSyncSpawner } from '../elt/application/detached-sync.js';
36
+ export { buildOpenCodeGoConsoleProfiles, classifyOpenCodeGoModel, fetchOpenCodeGoModelIds, mergeOpenCodeGoConsoleProfiles, OPENCODE_GO_API_BASE_ENV, OPENCODE_GO_API_KEY_ENV, OPENCODE_GO_DEFAULT_BASE_URL, OPENCODE_GO_MESSAGES_API_BASE_ENV, } from '../core/runtime/opencode-go.js';
37
+ export type { OpenCodeGoConsoleProfiles, OpenCodeGoMergeResult, OpenCodeGoRoute } from '../core/runtime/opencode-go.js';
38
+ export type { InterruptedRuns, SyncProgressSnapshot, SyncProgressState } from '../contracts/progress.js';
39
+ export { CatenceDatabase, openReadOnlyRepository, ReadOnlyDatabaseError } from '../elt/storage/database.js';
34
40
  export { DataWriteBusyError } from '../elt/storage/write-lock.js';
41
+ export { migrations } from '../elt/storage/migrations.js';
35
42
  export { hydrateStravaActivity, hydrateStravaSegmentHistory, StravaEnrichmentError, StravaRateLimitError, } from '../elt/ingestion/providers/strava/service.js';
@@ -10,13 +10,17 @@ export { AnalyticsService } from '../core/query/analytics.js';
10
10
  export { ActivityDiscoveryService } from '../core/query/activity-discovery.js';
11
11
  export { DATASET_CATALOG, getDataset, QueryValidationError } from '../core/query/catalog.js';
12
12
  export { FitnessService } from '../core/query/fitness.js';
13
+ export { EventsService, extractCourseId } from '../core/query/events.js';
13
14
  export { SwimmingService } from '../core/query/swimming.js';
14
15
  export { WELLNESS_METRICS, WellnessService } from '../core/query/wellness.js';
15
16
  export { jsonSafe, ReadOnlyRepository } from '../core/query/repository.js';
16
17
  export { queryReadOnlyData } from '../core/query/sql-guard.js';
17
18
  export { createDemoStore, demoStoreMetadata } from '../elt/application/demo.js';
18
- export { connectStrava, connectStravaWithCallback, dataStatus, disconnectStravaAccount, initializeDataStore, linkActivity, rebuildRetrievalIndex, retryDataSync, syncData, unlinkActivity, } from '../elt/application/management.js';
19
- export { openReadOnlyRepository, ReadOnlyDatabaseError } from '../elt/storage/database.js';
19
+ export { connectStrava, connectStravaWithCallback, dataStatus, disconnectStravaAccount, initializeDataStore, importStagedFile, linkActivity, rebuildRetrievalIndex, reimportNutrition, resolveExtractionErrors, retryDataSync, syncData, syncProgress, unlinkActivity, } from '../elt/application/management.js';
20
+ export { DETACHED_SYNC_PROVIDERS, DetachedSyncBusyError, startDetachedSync, } from '../elt/application/detached-sync.js';
21
+ export { buildOpenCodeGoConsoleProfiles, classifyOpenCodeGoModel, fetchOpenCodeGoModelIds, mergeOpenCodeGoConsoleProfiles, OPENCODE_GO_API_BASE_ENV, OPENCODE_GO_API_KEY_ENV, OPENCODE_GO_DEFAULT_BASE_URL, OPENCODE_GO_MESSAGES_API_BASE_ENV, } from '../core/runtime/opencode-go.js';
22
+ export { CatenceDatabase, openReadOnlyRepository, ReadOnlyDatabaseError } from '../elt/storage/database.js';
20
23
  export { DataWriteBusyError } from '../elt/storage/write-lock.js';
24
+ export { migrations } from '../elt/storage/migrations.js';
21
25
  export { hydrateStravaActivity, hydrateStravaSegmentHistory, StravaEnrichmentError, StravaRateLimitError, } from '../elt/ingestion/providers/strava/service.js';
22
26
  //# sourceMappingURL=index.js.map
@@ -74,7 +74,7 @@ Normalized tables preserve provenance rather than force an early merge:
74
74
 
75
75
  ### 3. Queries, tools and methods
76
76
 
77
- The MCP process is a separate stdio consumer. Ordinary tools and resources open DuckDB `READ_ONLY` snapshots. The only write capabilities are the explicit `hydrate_strava_activity`, serial `hydrate_recent_strava_activities`, and `hydrate_strava_segment_history` tools: each acquires the shared data-directory lock, calls only the Strava GET allowlist, archives responses before normalization, commits, and releases the lock. If another writer owns it, the result is retryable `data_sync_in_progress`.
77
+ The MCP process is a separate stdio consumer. Ordinary tools and resources open DuckDB `READ_ONLY` snapshots. The only direct database writers are the explicit `hydrate_strava_activity`, serial `hydrate_recent_strava_activities`, and `hydrate_strava_segment_history` tools: each acquires the shared data-directory lock, calls only the Strava GET allowlist, archives responses before normalization, commits, and releases the lock. If another writer owns it, the result is retryable `data_sync_in_progress`. `start_detached_sync` is also a write tool: it spawns a detached `catence-data sync` child process (which acquires the lock itself) and returns immediately with the run handle.
78
78
 
79
79
  The query layer has four shared pieces:
80
80
 
@@ -87,7 +87,18 @@ The query layer has four shared pieces:
87
87
 
88
88
  ### 4. Serving and retrieval
89
89
 
90
- The server exposes `catence_status`, `describe_data`, `describe_dataset`, `read_series`, `aggregate_data`, `analyze_series`, `fit_series_model`, `query_read_only_data`, `find_activities`, `get_ftp_history`, `get_vo2max_history`, `power_curve_trend`, `power_coverage_report`, `latest_cycling_activities`, `cycling_progress_report`, `review_daily_recovery_load`, `review_weekly_training`, `review_activity_deep_dive`, `search_context`, `hydrate_strava_activity`, `hydrate_recent_strava_activities`, and `hydrate_strava_segment_history`, plus resources for status, catalog, a single activity, and a date-range summary.
90
+ The server exposes these tools, grouped by purpose:
91
+
92
+ - Catalog and status: `list_athletes`, `catence_status`, `catence_sync_progress`.
93
+ - Review workflows: `review_daily_recovery_load`, `review_weekly_training`, `review_activity_deep_dive`, plus the matching `daily_recovery_load_review`, `weekly_training_review`, and `activity_deep_dive` prompts.
94
+ - General data and analytics: `describe_data`, `describe_dataset`, `read_series`, `aggregate_data`, `analyze_series`, `fit_series_model`, `query_read_only_data`, `search_context`.
95
+ - Wellness: `wellness_correlate`, `wellness_baselines`, `wellness_anomalies`, `wellness_coverage`.
96
+ - Fitness, readiness, and progress: `get_ftp_history`, `get_vo2max_history`, `readiness_baseline`, `power_curve_trend`, `power_coverage_report`, `activity_decoupling`, `latest_cycling_activities`, `cycling_progress_report`, `get_swim_laps`, `swim_progress_report`.
97
+ - Activity detail and segments: `find_activities`, `get_activity_segments`, `resolve_event_course`.
98
+ - Background sync (write): `start_detached_sync` — spawns a detached `catence-data sync` child process and returns immediately; track progress with `catence_sync_progress`.
99
+ - Strava hydration (the only direct database writers): `hydrate_strava_activity`, `hydrate_recent_strava_activities`, `hydrate_strava_segment_history`.
100
+
101
+ Resources are mode-dependent. In catalog mode the server registers only `athletes` (`catence://athletes`), the machine-readable roster of configured athlete IDs and labels; in a single-store (non-catalog) deployment it registers resources for status, catalog, a single activity template (`catence://activity/{activityId}`), and a date-range summary template (`catence://summary/{startDate}/{endDate}`). Both modes also register `tools` (`catence://tools`), a machine-readable index of all registered tools — useful when a host truncates the tool list.
91
102
 
92
103
  `catence serve` is a loopback-only-by-default Streamable HTTP adapter. It creates a stateless MCP server and transport for each `/mcp` request, so the HTTP and stdio surfaces use the same tool implementation. `GET /health` is a versioned client handshake with runtime version, protocol version, and capabilities; distributed Console builds reject an incompatible protocol before starting a chat. The same listener serves a small read-only `/api/v1/dashboard` snapshot for the local Console: canonical daily-health rows, weekly canonical activity aggregates, recent canonical activities, status, coverage, and explicit missing-data caveats.
93
104
 
Binary file