@trainheroic-unofficial/coach-mcp 3.2.0 → 3.3.1

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 (2) hide show
  1. package/dist/server.mjs +552 -149
  2. package/package.json +4 -4
package/dist/server.mjs CHANGED
@@ -27,12 +27,14 @@ const numLikeOrNull = z.union([
27
27
  z.string(),
28
28
  z.null()
29
29
  ]);
30
- z.looseObject({
30
+ /** `/user/simple` — the identity + tenant key (numeric `id`) for any logged-in account. */
31
+ const userSimpleSchema = z.looseObject({
31
32
  id: intLike$1,
32
33
  roles: z.array(z.string()).optional(),
33
34
  org_id: intLikeOrNull$1.optional()
34
35
  });
35
- z.looseObject({
36
+ /** `/v5/athleteProfile/summary` — lifetime training totals. Needs `use_metric` in the query. */
37
+ const athleteProfileSummarySchema = z.looseObject({
36
38
  reps_sum: z.number().optional(),
37
39
  volume_sum: z.number().optional(),
38
40
  sessions_count: z.number().optional(),
@@ -40,7 +42,8 @@ z.looseObject({
40
42
  last_logged_date: z.string().optional(),
41
43
  duration_hours: z.number().optional()
42
44
  });
43
- z.looseObject({
45
+ /** `/v5/users/{id}` — the detailed athlete profile (only the fields we surface). */
46
+ const athleteUserSchema = z.looseObject({
44
47
  id: intLike$1,
45
48
  email: z.string().optional(),
46
49
  name_first: z.string().optional(),
@@ -110,7 +113,8 @@ const liftPRSchema = z.looseObject({
110
113
  isMetric: z.boolean().optional(),
111
114
  description: z.string().optional()
112
115
  });
113
- z.looseObject({
116
+ /** `/v5/exercises/{id}/history` — the per-exercise PRs + session history. */
117
+ const exerciseHistoryDetailSchema = z.looseObject({
114
118
  liftPRs: z.array(liftPRSchema).optional(),
115
119
  singleParamPRs: z.array(z.unknown()).optional(),
116
120
  history: z.array(historyEntrySchema).optional()
@@ -147,7 +151,7 @@ const programWorkoutSchema = z.looseObject({
147
151
  team_title: z.string().optional(),
148
152
  summarizedSavedWorkout: z.unknown().optional()
149
153
  });
150
- z.array(programWorkoutSchema);
154
+ const programWorkoutListSchema = z.array(programWorkoutSchema);
151
155
  /** A `YYYY-MM-DD` date argument. The single definition reused across athlete tool inputs. */
152
156
  const dateString = z.string().regex(/^\d{4}-\d{2}-\d{2}$/u, "expected YYYY-MM-DD");
153
157
  z.object({
@@ -234,8 +238,168 @@ z.object({
234
238
  programWorkoutId: idArgSchema,
235
239
  date: dateString
236
240
  });
241
+ const presentedNullNumber = z.number().nullable();
242
+ const presentedNullString = z.string().nullable();
243
+ /** Flattened exercise within a presented workout: prescriptions, logged results, units. */
244
+ const athleteWorkoutExerciseSchema = z.object({
245
+ exerciseId: presentedNullNumber,
246
+ title: z.string(),
247
+ instruction: presentedNullString,
248
+ units: z.array(presentedNullString),
249
+ prescribed: z.array(z.string()),
250
+ performed: z.array(z.string())
251
+ });
252
+ const athleteWorkoutBlockSchema = z.object({
253
+ order: z.number(),
254
+ title: presentedNullString,
255
+ instruction: presentedNullString,
256
+ isTest: z.boolean(),
257
+ exercises: z.array(athleteWorkoutExerciseSchema)
258
+ });
259
+ const athleteWorkoutViewSchema = z.object({
260
+ id: presentedNullNumber,
261
+ date: z.string(),
262
+ title: z.string(),
263
+ program: presentedNullString,
264
+ team: presentedNullString,
265
+ instruction: presentedNullString,
266
+ logged: z.boolean(),
267
+ personal: z.boolean(),
268
+ blocks: z.array(athleteWorkoutBlockSchema)
269
+ });
270
+ const athleteWorkoutSummarySchema = z.object({
271
+ id: presentedNullNumber,
272
+ date: z.string(),
273
+ title: z.string(),
274
+ program: presentedNullString,
275
+ team: presentedNullString,
276
+ logged: z.boolean(),
277
+ personal: z.boolean(),
278
+ exerciseCount: z.number().int().nonnegative(),
279
+ performedCount: z.number().int().nonnegative()
280
+ });
281
+ z.union([
282
+ z.array(athleteWorkoutSummarySchema),
283
+ z.array(athleteWorkoutViewSchema),
284
+ programWorkoutListSchema
285
+ ]);
286
+ z.looseObject({
287
+ summary: athleteProfileSummarySchema,
288
+ user: athleteUserSchema
289
+ });
290
+ z.array(z.object({
291
+ id: z.union([z.number(), z.string()]),
292
+ title: z.string(),
293
+ isCircuit: z.boolean(),
294
+ units: z.array(presentedNullString)
295
+ }));
296
+ const coachAthleteExerciseSchema = z.object({
297
+ exerciseId: presentedNullNumber,
298
+ title: z.string(),
299
+ summary: presentedNullString,
300
+ completed: z.boolean()
301
+ });
302
+ const coachAthleteSessionSchema = z.object({
303
+ workoutId: presentedNullNumber,
304
+ savedWorkoutId: presentedNullNumber,
305
+ title: z.string(),
306
+ logged: z.boolean(),
307
+ completed: z.boolean(),
308
+ rpe: presentedNullNumber,
309
+ durationMin: presentedNullNumber,
310
+ notes: presentedNullString,
311
+ exercises: z.array(coachAthleteExerciseSchema)
312
+ });
313
+ const coachAthleteTrainingOutputSchema = z.object({
314
+ athleteId: presentedNullNumber,
315
+ athleteName: presentedNullString,
316
+ year: z.number().int(),
317
+ month: z.number().int(),
318
+ sessions: z.array(coachAthleteSessionSchema)
319
+ });
320
+ const rosterActivityRowSchema = z.object({
321
+ athleteId: z.number(),
322
+ sessionsCount: presentedNullNumber,
323
+ firstLoggedDate: presentedNullString,
324
+ lastLoggedDate: presentedNullString,
325
+ totalReps: presentedNullNumber,
326
+ totalVolume: presentedNullNumber
327
+ });
328
+ const teamVolumeAthleteSchema = z.object({
329
+ athleteId: z.number(),
330
+ name: presentedNullString,
331
+ sessions: z.number(),
332
+ reps: z.number(),
333
+ volume: z.number(),
334
+ firstLoggedDate: presentedNullString,
335
+ lastLoggedDate: presentedNullString
336
+ });
337
+ const teamVolumeOutputSchema = z.object({
338
+ window: z.object({
339
+ start: z.string(),
340
+ end: z.string()
341
+ }),
342
+ athletes: z.array(teamVolumeAthleteSchema),
343
+ totals: z.object({
344
+ athletes: z.number(),
345
+ sessions: z.number(),
346
+ reps: z.number(),
347
+ volume: z.number()
348
+ })
349
+ });
350
+ const rosterActivityOutputSchema = z.array(rosterActivityRowSchema);
351
+ const presentedExerciseSessionSchema = z.object({
352
+ date: z.string(),
353
+ abr: presentedNullString,
354
+ estimated1RM: presentedNullNumber,
355
+ sets: z.array(z.object({
356
+ setNumber: z.number(),
357
+ value: presentedNullString
358
+ }))
359
+ });
360
+ const presentedExerciseHistorySchema = z.object({
361
+ liftPRs: z.array(z.object({
362
+ description: presentedNullString,
363
+ reps: presentedNullNumber,
364
+ weight: presentedNullNumber,
365
+ units: presentedNullString,
366
+ date: presentedNullString
367
+ })),
368
+ sessions: z.array(presentedExerciseSessionSchema)
369
+ });
370
+ /** Presented history first so the loose raw detail schema cannot swallow it. */
371
+ const exerciseHistoryOutputSchema = z.union([presentedExerciseHistorySchema, exerciseHistoryDetailSchema]);
237
372
  //#endregion
238
373
  //#region ../dto/src/exercise.ts
374
+ /**
375
+ * A row presented for display. The raw param-type codes are dropped and the fixed
376
+ * measurement units are surfaced positionally in `units`, ordered by entry slot
377
+ * (param 1, then param 2). Positional, not semantic: param 2 is not always the load
378
+ * — some exercises reverse the slots — so the units are not labelled by role.
379
+ */
380
+ const exerciseViewSchema = z.object({
381
+ id: z.number(),
382
+ title: z.string(),
383
+ can_edit: z.number(),
384
+ user_id: z.number().nullable(),
385
+ use_count: z.number(),
386
+ units: z.array(z.string().nullable())
387
+ });
388
+ /**
389
+ * Full library object from `exercise_get`: the stored row with param-type codes
390
+ * replaced by positional `units`. Extra API fields are preserved. Search/resolve
391
+ * use the strict `exerciseViewSchema` projection instead.
392
+ */
393
+ const exerciseGetOutputSchema = z.looseObject({
394
+ id: idSchema,
395
+ title: z.string(),
396
+ units: z.array(z.string().nullable())
397
+ });
398
+ /** The outcome of resolving a name: a single match (or null) plus ranked candidates. */
399
+ const exerciseResolveOutputSchema = z.object({
400
+ match: exerciseViewSchema.nullable(),
401
+ candidates: z.array(exerciseViewSchema)
402
+ });
239
403
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
240
404
  const exerciseCreateSchema = z.looseObject({
241
405
  title: z.string().min(1),
@@ -302,6 +466,199 @@ const teamPublishPatchObject = z.object({
302
466
  });
303
467
  const teamPublishPatchSchema = teamPublishPatchObject.refine((v) => v.pub_enabled !== void 0 || v.pub_days !== void 0 || v.pub_time !== void 0 || v.pub_timezone !== void 0, { message: "Provide at least one pub_* field" });
304
468
  //#endregion
469
+ //#region ../dto/src/tool-output.ts
470
+ const nullableNumber = z.number().nullable();
471
+ const nullableString = z.string().nullable();
472
+ const truncationMarkerSchema = z.looseObject({
473
+ field: z.string().optional(),
474
+ returned: z.number().int().nonnegative().optional(),
475
+ total: z.number().int().nonnegative(),
476
+ omitted: z.number().int().nonnegative(),
477
+ hint: z.string()
478
+ });
479
+ /** Dedicated budget-fallback envelope. Never the natural tool shape. */
480
+ const truncatedOutputSchema = z.looseObject({
481
+ preview: z.string().optional(),
482
+ items: z.array(z.json()).optional(),
483
+ __truncated: truncationMarkerSchema
484
+ });
485
+ /**
486
+ * Add the shared size-budget fallback to a tool's natural result shape.
487
+ * Truncation is a dedicated `{ items|preview, __truncated }` envelope, so it cannot
488
+ * validate as the natural object and drop the marker.
489
+ */
490
+ function toolOutputSchema(schema) {
491
+ return z.union([truncatedOutputSchema, schema]);
492
+ }
493
+ /** Explicit passthrough for tools whose live API payload is not yet contracted. */
494
+ const opaqueOutputSchema = toolOutputSchema(z.json());
495
+ const logSetTargetOutputSchema = z.object({
496
+ date: z.string(),
497
+ workoutTitle: z.string(),
498
+ program: nullableString,
499
+ programId: nullableNumber,
500
+ team: nullableString,
501
+ teamId: nullableNumber,
502
+ savedWorkoutSetId: z.number(),
503
+ setTitle: nullableString,
504
+ exercises: z.array(z.object({
505
+ savedWorkoutSetExerciseId: z.number(),
506
+ title: z.string(),
507
+ units: z.array(nullableString),
508
+ prescribed: z.array(z.string()),
509
+ performed: z.array(z.string())
510
+ }))
511
+ });
512
+ const logTargetsOutputSchema = z.union([z.array(logSetTargetOutputSchema), programWorkoutListSchema]);
513
+ const messageDraftOutputSchema = z.object({
514
+ draft: z.literal(true),
515
+ note: z.string(),
516
+ would_POST: z.string(),
517
+ payload: z.json()
518
+ });
519
+ z.looseObject({
520
+ status: z.enum(["sent", "logged"]),
521
+ reference: z.string().optional(),
522
+ note: z.string()
523
+ });
524
+ const removedSessionOutputSchema = z.looseObject({ removed: z.union([z.boolean(), z.number()]) });
525
+ z.object({
526
+ removed: z.literal(true),
527
+ programWorkoutId: z.number(),
528
+ date: z.string()
529
+ });
530
+ const athleteInviteOutputSchema = z.object({
531
+ invited: z.literal(true),
532
+ teamId: z.number(),
533
+ result: z.json().optional()
534
+ });
535
+ const setLogOutputSchema = z.object({
536
+ savedWorkoutSetId: z.number(),
537
+ exercisesLogged: z.number().int().nonnegative(),
538
+ setCompleted: z.boolean()
539
+ });
540
+ const setPrescriptionOutputSchema = z.object({
541
+ savedWorkoutSetId: z.number(),
542
+ exercisesPrescribed: z.number().int().nonnegative()
543
+ });
544
+ const exerciseSwapOutputSchema = z.object({
545
+ savedWorkoutSetExerciseId: z.number(),
546
+ athleteId: nullableNumber,
547
+ newExerciseId: z.number(),
548
+ newExerciseTitle: nullableString,
549
+ originalTeamExerciseId: nullableNumber
550
+ });
551
+ const sessionLogSetOutputSchema = z.object({
552
+ savedWorkoutSetId: z.number(),
553
+ exercisesLogged: z.number().int().nonnegative()
554
+ });
555
+ const sessionLogOutputSchema = z.object({
556
+ date: z.string(),
557
+ created: z.boolean(),
558
+ sets: z.array(sessionLogSetOutputSchema),
559
+ scheduledAlternatives: z.array(z.object({
560
+ exerciseId: z.number(),
561
+ title: z.string(),
562
+ program: nullableString,
563
+ workoutTitle: z.string(),
564
+ savedWorkoutSetId: z.number(),
565
+ savedWorkoutSetExerciseId: z.number()
566
+ })).optional()
567
+ });
568
+ z.object({
569
+ programWorkoutId: z.number(),
570
+ workoutId: z.number(),
571
+ savedWorkoutId: z.number(),
572
+ groupId: z.number(),
573
+ date: z.string()
574
+ });
575
+ const workoutReadExerciseOutputSchema = z.object({
576
+ order: z.number(),
577
+ title: z.string(),
578
+ reps: z.array(z.string()),
579
+ primaryUnit: nullableString,
580
+ load: z.array(z.string()),
581
+ loadUnit: nullableString,
582
+ instruction: z.string()
583
+ });
584
+ const workoutReadBlockOutputSchema = z.object({
585
+ order: z.number(),
586
+ title: z.string(),
587
+ instruction: z.string(),
588
+ leaderboard: nullableString,
589
+ exercises: z.array(workoutReadExerciseOutputSchema)
590
+ });
591
+ const workoutReadOutputSchema = z.object({
592
+ pwId: z.number(),
593
+ date: z.string(),
594
+ published: z.json().optional(),
595
+ instruction: z.string(),
596
+ blocks: z.array(workoutReadBlockOutputSchema)
597
+ });
598
+ const workoutBuildOutputSchema = z.object({
599
+ pwId: z.number(),
600
+ workoutId: z.number(),
601
+ programId: z.number(),
602
+ published: z.literal(false),
603
+ advisories: z.object({
604
+ notes: z.array(z.string()),
605
+ warnings: z.array(z.string())
606
+ }),
607
+ readback: workoutReadOutputSchema.nullable(),
608
+ note: z.string()
609
+ });
610
+ const workoutPublishOutputSchema = z.object({
611
+ published: z.number(),
612
+ readback: workoutReadOutputSchema,
613
+ note: z.string()
614
+ });
615
+ const messageSentOutputSchema = z.object({
616
+ sent: z.literal(true),
617
+ comment: z.json()
618
+ });
619
+ const messageDeletedOutputSchema = z.object({
620
+ deleted: z.literal(true),
621
+ response: z.json().optional()
622
+ });
623
+ const exerciseDeletedOutputSchema = z.object({ deleted: z.number() });
624
+ const exerciseForgottenOutputSchema = z.object({ forgotten: z.number() });
625
+ const exerciseCreatedOutputSchema = exerciseResponseSchema;
626
+ const sessionTemplateCreatedOutputSchema = z.looseObject({ id: z.union([z.number(), z.string()]) });
627
+ const mainLiftPrOutputSchema = z.object({
628
+ family: z.enum([
629
+ "cleanjerk",
630
+ "snatch",
631
+ "deadlift",
632
+ "squat",
633
+ "bench",
634
+ "overhead"
635
+ ]),
636
+ label: z.string(),
637
+ exerciseId: nullableNumber,
638
+ title: nullableString,
639
+ weight: nullableNumber,
640
+ reps: nullableNumber,
641
+ units: nullableString,
642
+ date: nullableString
643
+ });
644
+ const athleteMainLiftPrsOutputSchema = z.object({
645
+ athleteId: z.number(),
646
+ athleteName: nullableString,
647
+ prs: z.array(mainLiftPrOutputSchema)
648
+ });
649
+ const programCreatedOutputSchema = z.object({
650
+ containerId: z.number(),
651
+ programId: z.number(),
652
+ title: z.string(),
653
+ kind: z.enum(["calendar", "fixed"]),
654
+ requestedName: z.string(),
655
+ nameApplied: z.boolean()
656
+ });
657
+ const programDeletedOutputSchema = z.object({
658
+ programId: z.number(),
659
+ containerId: nullableNumber
660
+ });
661
+ //#endregion
305
662
  //#region ../dto/src/workout.ts
306
663
  /** A single exercise prescription inside a block. */
307
664
  const exerciseSpecSchema = z.object({
@@ -381,6 +738,12 @@ function toId(value) {
381
738
  }
382
739
  const READ = {
383
740
  readOnlyHint: true,
741
+ destructiveHint: false,
742
+ openWorldHint: true
743
+ };
744
+ const ADDITIVE = {
745
+ readOnlyHint: false,
746
+ destructiveHint: false,
384
747
  openWorldHint: true
385
748
  };
386
749
  const SYNC = {
@@ -408,32 +771,36 @@ async function attempt(fn) {
408
771
  }
409
772
  /** Conservative per-result character cap, below the smallest host cap. */
410
773
  const DEFAULT_RESULT_BUDGET = 6e4;
774
+ /** Smallest cap that can still carry a useful structured truncation envelope. */
775
+ const MIN_RESULT_BUDGET = 256;
411
776
  /** Reserve for the `__truncated` marker so wrapping cannot push back over budget. */
412
777
  const MARKER_RESERVE = 300;
413
778
  const DEFAULT_ARRAY_HINT = "Result was truncated to fit the size budget. Narrow it with a filter/search argument or paginate to see the rest.";
414
779
  const DEFAULT_OBJECT_HINT = "Result was truncated to fit the size budget. Request a more specific id or sub-resource.";
415
780
  /**
416
781
  * Clip an array to its first `keep` items and attach the `__truncated` marker describing what was
417
- * dropped. The marker is model-facing (tools instruct the model to key off `__truncated`), so its
418
- * shape has exactly one definition here: the size-budget path (`boundedSerialize`) and any tool
419
- * that deliberately caps a list (e.g. `athlete_exercises`) emit the same thing.
782
+ * dropped. Every budget fallback that trims a list uses this envelope (`{ items, __truncated }`),
783
+ * including in-place object-array truncation (the sliced array becomes `items` and `field` names
784
+ * the original key). `athlete_exercises` uses the same helper for a client-side catalog cap.
420
785
  */
421
- function clipArray(items, keep, hint) {
786
+ function clipArray(items, keep, hint, field) {
787
+ const marker = {
788
+ returned: keep,
789
+ total: items.length,
790
+ omitted: items.length - keep,
791
+ hint: hint ?? DEFAULT_ARRAY_HINT
792
+ };
793
+ if (field !== void 0) marker.field = field;
422
794
  return {
423
795
  items: items.slice(0, keep),
424
- __truncated: {
425
- returned: keep,
426
- total: items.length,
427
- omitted: items.length - keep,
428
- hint: hint ?? DEFAULT_ARRAY_HINT
429
- }
796
+ __truncated: marker
430
797
  };
431
798
  }
432
799
  /** Active budget. Overridable via TH_MCP_RESULT_BUDGET on Node; the default on workerd. */
433
800
  function resultBudget() {
434
801
  const raw = (globalThis.process?.env)?.TH_MCP_RESULT_BUDGET;
435
802
  const n = raw ? Number(raw) : NaN;
436
- return Number.isFinite(n) && n > 0 ? n : DEFAULT_RESULT_BUDGET;
803
+ return Number.isFinite(n) && n >= MIN_RESULT_BUDGET ? n : DEFAULT_RESULT_BUDGET;
437
804
  }
438
805
  function isPlainObject(value) {
439
806
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -450,7 +817,7 @@ function largestPrefixCount(pieces, charBudget) {
450
817
  }
451
818
  return k;
452
819
  }
453
- /** Last resort: cap a string at the budget and label it as truncated, non-JSON output. */
820
+ /** Cap diagnostic text. Tool errors are text-only and are not output-schema validated. */
454
821
  function hardCap(text, budget, hint) {
455
822
  if (text.length <= budget) return text;
456
823
  const note = `\n\n[TRUNCATED: output exceeded ${budget} chars and is NOT valid JSON. ${hint ?? "Narrow the query (filter, paginate, or fetch a specific id)."}]`;
@@ -470,56 +837,79 @@ function largestArrayValuedKey(obj) {
470
837
  }
471
838
  return best;
472
839
  }
473
- /**
474
- * Serialize `data` as JSON within `budget` characters. Small results are pretty-printed.
475
- * Oversized results degrade in order: trim a top-level array (wrapping it as
476
- * `{ items, __truncated }`), then a top-level object's largest array property (annotated
477
- * with `__truncated`), then a last-resort hard character cap. Pure and side-effect free.
478
- */
479
- function boundedSerialize(data, budget, hint) {
480
- if (typeof data === "string") return hardCap(data, budget, hint);
481
- const compact = JSON.stringify(data) ?? "null";
840
+ function jsonValue(data) {
841
+ return JSON.parse(JSON.stringify(data) ?? "null");
842
+ }
843
+ function previewEnvelope(source, budget, hint) {
844
+ const total = source.length;
845
+ const makeValue = (preview, markerHint) => ({
846
+ preview,
847
+ __truncated: {
848
+ total,
849
+ omitted: total - preview.length,
850
+ hint: markerHint
851
+ }
852
+ });
853
+ let markerHint = hint ?? "Narrow the query (filter, paginate, or fetch a specific id).";
854
+ while (JSON.stringify(makeValue("", markerHint)).length > budget && markerHint.length > 0) markerHint = markerHint.slice(0, -1);
855
+ if (JSON.stringify(makeValue("", markerHint)).length > budget) throw new RangeError("Result budget is too small for a structured truncation envelope.");
856
+ let keep = Math.max(0, budget - JSON.stringify(makeValue("", markerHint)).length);
857
+ let value = makeValue(source.slice(0, keep), markerHint);
858
+ while (JSON.stringify(value).length > budget && keep > 0) {
859
+ keep = Math.max(0, keep - (JSON.stringify(value).length - budget));
860
+ value = makeValue(source.slice(0, keep), markerHint);
861
+ }
862
+ return value;
863
+ }
864
+ function boundedResult(data, budget, hint) {
865
+ if (typeof data === "string" && data.length <= budget) return {
866
+ text: data,
867
+ value: data
868
+ };
869
+ const value = jsonValue(data);
870
+ const compact = JSON.stringify(value);
482
871
  if (compact.length <= budget) {
483
- const pretty = JSON.stringify(data, null, 2) ?? "null";
484
- return pretty.length <= budget ? pretty : compact;
872
+ const pretty = JSON.stringify(value, null, 2);
873
+ return {
874
+ text: pretty.length <= budget ? pretty : compact,
875
+ value
876
+ };
485
877
  }
486
- if (Array.isArray(data)) {
487
- const k = largestPrefixCount(data.map((el) => JSON.stringify(el) ?? "null"), budget - MARKER_RESERVE);
488
- const out = JSON.stringify(clipArray(data, k, hint));
489
- if (out.length <= budget) return out;
490
- } else if (isPlainObject(data)) {
491
- const key = largestArrayValuedKey(data);
878
+ if (Array.isArray(value)) {
879
+ const truncated = clipArray(value, largestPrefixCount(value.map((element) => JSON.stringify(element)), budget - MARKER_RESERVE), hint);
880
+ const text = JSON.stringify(truncated);
881
+ if (text.length <= budget) return {
882
+ text,
883
+ value: truncated
884
+ };
885
+ } else if (isPlainObject(value)) {
886
+ const key = largestArrayValuedKey(value);
492
887
  if (key !== null) {
493
- const arr = data[key];
494
- const pieces = arr.map((el) => JSON.stringify(el) ?? "null");
495
- const restLen = (JSON.stringify({
496
- ...data,
497
- [key]: []
498
- }) ?? "{}").length;
499
- const k = largestPrefixCount(pieces, Math.max(0, budget - MARKER_RESERVE - restLen));
500
- const clone = {
501
- ...data,
502
- [key]: arr.slice(0, k),
503
- __truncated: {
504
- field: key,
505
- returned: k,
506
- total: arr.length,
507
- omitted: arr.length - k,
508
- hint: hint ?? DEFAULT_OBJECT_HINT
509
- }
888
+ const array = value[key];
889
+ const truncated = clipArray(array, largestPrefixCount(array.map((element) => JSON.stringify(element)), budget - MARKER_RESERVE), hint ?? DEFAULT_OBJECT_HINT, key);
890
+ const text = JSON.stringify(truncated);
891
+ if (text.length <= budget) return {
892
+ text,
893
+ value: truncated
510
894
  };
511
- const out = JSON.stringify(clone);
512
- if (out.length <= budget) return out;
513
895
  }
514
896
  }
515
- return hardCap(compact, budget, hint);
897
+ const truncated = previewEnvelope(typeof data === "string" ? data : compact, budget, hint);
898
+ return {
899
+ text: JSON.stringify(truncated),
900
+ value: truncated
901
+ };
516
902
  }
517
903
  /** A successful tool result carrying JSON (or text) for the model, size-bounded. */
518
904
  function jsonResult(data, opts) {
519
- return { content: [{
520
- type: "text",
521
- text: boundedSerialize(data, resultBudget(), opts?.hint)
522
- }] };
905
+ const { text, value } = boundedResult(data, resultBudget(), opts?.hint);
906
+ return {
907
+ content: [{
908
+ type: "text",
909
+ text
910
+ }],
911
+ structuredContent: value
912
+ };
523
913
  }
524
914
  /** A tool-level error: returned in-band (isError) so the model can self-correct. */
525
915
  function errorResult(message) {
@@ -3234,12 +3624,6 @@ function enc(value) {
3234
3624
  }
3235
3625
  /** No-argument GET endpoints, registered from a table to keep the wiring compact. */
3236
3626
  const SIMPLE_GETS = [
3237
- {
3238
- name: "whoami",
3239
- title: "Who am I",
3240
- description: "The authenticated TrainHeroic coach profile (id, org_id, name, roles, trial days).",
3241
- path: "/user/simple"
3242
- },
3243
3627
  {
3244
3628
  name: "head_coach",
3245
3629
  title: "Head coach / org",
@@ -3291,10 +3675,18 @@ const SIMPLE_GETS = [
3291
3675
  ];
3292
3676
  /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
3293
3677
  function registerRosterReads(server, ctx) {
3678
+ server.registerTool("whoami", {
3679
+ title: "Who am I",
3680
+ description: "The authenticated TrainHeroic coach profile (id, org_id, name, roles, trial days).",
3681
+ inputSchema: {},
3682
+ outputSchema: toolOutputSchema(userSimpleSchema),
3683
+ annotations: READ
3684
+ }, () => apiCall(ctx, "GET", "/user/simple"));
3294
3685
  for (const t of SIMPLE_GETS) server.registerTool(t.name, {
3295
3686
  title: t.title,
3296
3687
  description: t.description,
3297
3688
  inputSchema: {},
3689
+ outputSchema: opaqueOutputSchema,
3298
3690
  annotations: READ
3299
3691
  }, () => apiCall(ctx, "GET", t.path));
3300
3692
  server.registerTool("list_athletes", {
@@ -3304,6 +3696,7 @@ function registerRosterReads(server, ctx) {
3304
3696
  q: z.string().optional(),
3305
3697
  limit: z.number().int().positive().max(500).optional()
3306
3698
  },
3699
+ outputSchema: toolOutputSchema(z.array(z.json())),
3307
3700
  annotations: READ
3308
3701
  }, ({ q, limit }) => attempt(async () => {
3309
3702
  const res = await ctx.client.request("GET", "/v5/athletes");
@@ -3320,13 +3713,7 @@ function registerRosterReads(server, ctx) {
3320
3713
  return needles.every((n) => hay.includes(n));
3321
3714
  });
3322
3715
  }
3323
- const total = rows.length;
3324
- if (limit !== void 0 && rows.length > limit) return jsonResult({
3325
- items: rows.slice(0, limit),
3326
- returned: limit,
3327
- total,
3328
- note: "Limited client-side. Raise limit or narrow with q for the rest."
3329
- });
3716
+ if (limit !== void 0 && rows.length > limit) return jsonResult(clipArray(rows, limit, "Limited client-side. Raise limit or narrow with q for the rest."));
3330
3717
  return jsonResult(rows, { hint: "Filter with q (name/email substring) or cap with limit to shrink this list." });
3331
3718
  }));
3332
3719
  server.registerTool("list_teams", {
@@ -3337,6 +3724,7 @@ function registerRosterReads(server, ctx) {
3337
3724
  pageSize: z.number().int().positive().optional(),
3338
3725
  q: z.string().optional()
3339
3726
  },
3727
+ outputSchema: opaqueOutputSchema,
3340
3728
  annotations: READ
3341
3729
  }, ({ page, pageSize, q }) => {
3342
3730
  const qs = new URLSearchParams();
@@ -3353,12 +3741,14 @@ function registerEntityReads(server, ctx) {
3353
3741
  title: "Get team",
3354
3742
  description: "Full team object by team id.",
3355
3743
  inputSchema: { teamId: idParam },
3744
+ outputSchema: opaqueOutputSchema,
3356
3745
  annotations: READ
3357
3746
  }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}`));
3358
3747
  server.registerTool("list_team_codes", {
3359
3748
  title: "List team access codes",
3360
3749
  description: "Join/access codes for a team.",
3361
3750
  inputSchema: { teamId: idParam },
3751
+ outputSchema: opaqueOutputSchema,
3362
3752
  annotations: READ
3363
3753
  }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}/teamCodes`));
3364
3754
  server.registerTool("athlete_lift_history", {
@@ -3371,6 +3761,7 @@ function registerEntityReads(server, ctx) {
3371
3761
  since: dateString.optional(),
3372
3762
  until: dateString.optional()
3373
3763
  },
3764
+ outputSchema: toolOutputSchema(exerciseHistoryOutputSchema),
3374
3765
  annotations: READ
3375
3766
  }, ({ athleteId, exerciseId, raw, since, until }) => attempt(async () => {
3376
3767
  const detail = await fetchExerciseHistoryDetail(ctx.client, toId(exerciseId), toId(athleteId));
@@ -3384,6 +3775,7 @@ function registerEntityReads(server, ctx) {
3384
3775
  athleteIds: z.array(idParam).min(1),
3385
3776
  useMetric: z.boolean().optional()
3386
3777
  },
3778
+ outputSchema: toolOutputSchema(rosterActivityOutputSchema),
3387
3779
  annotations: READ
3388
3780
  }, ({ athleteIds, useMetric }) => attempt(async () => jsonResult(await fetchRosterActivity(ctx.client, athleteIds.map(toId), useMetric ?? false), { hint: "Sorted most-recently-active first; lastLoggedDate null = never logged. The top row is the most recently active athlete." })));
3389
3781
  server.registerTool("athlete_training", {
@@ -3394,6 +3786,7 @@ function registerEntityReads(server, ctx) {
3394
3786
  year: z.number().int(),
3395
3787
  month: z.number().int().min(1).max(12)
3396
3788
  },
3789
+ outputSchema: toolOutputSchema(coachAthleteTrainingOutputSchema),
3397
3790
  annotations: READ
3398
3791
  }, ({ athleteId, year, month }) => attempt(async () => {
3399
3792
  return jsonResult(presentCoachAthleteTraining(await fetchCoachAthleteCalendarSummary(ctx.client, toId(athleteId), year, month), toId(athleteId), year, month), { hint: "One session per row for the month. Use the exercise titles to pick lifts, then athlete_lift_history for their PRs." });
@@ -3402,6 +3795,7 @@ function registerEntityReads(server, ctx) {
3402
3795
  title: "Get program detail",
3403
3796
  description: "Program detail live from the API, by program id. Works for team calendars and athlete coach calendars (type 5 from /v5/calendars/athletes/{id}). For standalone rows from list_programs, accepts either id (the container id) or group_program (the underlying program id); container ids are resolved automatically. If neither detail endpoint is available, returns calendar metadata and next-step guidance instead.",
3404
3797
  inputSchema: { programId: idParam },
3798
+ outputSchema: opaqueOutputSchema,
3405
3799
  annotations: READ
3406
3800
  }, ({ programId }) => getProgram(ctx, toId(programId)));
3407
3801
  }
@@ -3436,6 +3830,7 @@ function registerTeamVolume(server, ctx) {
3436
3830
  dateStart: dateString,
3437
3831
  dateEnd: dateString
3438
3832
  },
3833
+ outputSchema: toolOutputSchema(teamVolumeOutputSchema),
3439
3834
  annotations: READ
3440
3835
  }, ({ teamId, athleteIds, dateStart, dateEnd }) => attempt(async () => {
3441
3836
  const ids = athleteIds !== void 0 && athleteIds.length > 0 ? athleteIds.map(toId) : teamId !== void 0 ? await fetchTeamAthleteIds(ctx.client, toId(teamId)) : [];
@@ -3458,6 +3853,7 @@ function registerCoachAthleteTeamCalendar(server, ctx) {
3458
3853
  title: "Coach-athlete team calendar",
3459
3854
  description: "Companion calendar for a roster athlete (GET /v5/calendars/athletes/{id}/coachAthleteTeam). Distinct from workout_build's type-5 individual calendar. Returns title, logo, id, athlete_id, owner_user_id.",
3460
3855
  inputSchema: { athleteId: idParam },
3856
+ outputSchema: opaqueOutputSchema,
3461
3857
  annotations: READ
3462
3858
  }, ({ athleteId }) => apiCall(ctx, "GET", `/v5/calendars/athletes/${toId(athleteId)}/coachAthleteTeam`));
3463
3859
  }
@@ -3475,6 +3871,7 @@ function registerMainLiftTools(server, ctx) {
3475
3871
  athleteId: idParam,
3476
3872
  months: monthsParam
3477
3873
  },
3874
+ outputSchema: toolOutputSchema(athleteMainLiftPrsOutputSchema),
3478
3875
  annotations: READ
3479
3876
  }, ({ athleteId, months }) => attempt(async () => jsonResult(await fetchAthleteMainLiftPRs(ctx.client, toId(athleteId), months !== void 0 ? { months } : {}))));
3480
3877
  server.registerTool("roster_main_lift_prs", {
@@ -3484,6 +3881,7 @@ function registerMainLiftTools(server, ctx) {
3484
3881
  months: monthsParam,
3485
3882
  athleteIds: z.array(idParam).optional()
3486
3883
  },
3884
+ outputSchema: toolOutputSchema(z.array(athleteMainLiftPrsOutputSchema)),
3487
3885
  annotations: READ
3488
3886
  }, ({ months, athleteIds }) => attempt(async () => {
3489
3887
  return jsonResult(await fetchRosterMainLiftPRs(ctx.client, {
@@ -3534,6 +3932,7 @@ function registerAthleteTools(server, ctx) {
3534
3932
  message: z.string().optional(),
3535
3933
  confirm: z.boolean().optional()
3536
3934
  },
3935
+ outputSchema: toolOutputSchema(athleteInviteOutputSchema),
3537
3936
  annotations: DESTRUCTIVE
3538
3937
  }, ({ teamId, emails, message, confirm }, extra) => attempt(async () => {
3539
3938
  const list = asEmailList(emails);
@@ -3558,6 +3957,7 @@ function registerAthleteTools(server, ctx) {
3558
3957
  athleteIds: z.array(idParam).min(1),
3559
3958
  confirm: z.boolean().optional()
3560
3959
  },
3960
+ outputSchema: opaqueOutputSchema,
3561
3961
  annotations: DESTRUCTIVE
3562
3962
  }, ({ athleteIds, confirm }, extra) => attempt(async () => {
3563
3963
  const ids = athleteIds.map(toId);
@@ -3569,6 +3969,7 @@ function registerAthleteTools(server, ctx) {
3569
3969
  title: "Restore athletes",
3570
3970
  description: "Restore previously archived athletes to the active roster (PUT /v5/athletes/restore).",
3571
3971
  inputSchema: { athleteIds: z.array(idParam).min(1) },
3972
+ outputSchema: opaqueOutputSchema,
3572
3973
  annotations: {
3573
3974
  readOnlyHint: false,
3574
3975
  idempotentHint: true,
@@ -3599,6 +4000,7 @@ function registerAthleteSavedWorkouts(server, ctx) {
3599
4000
  teamId: idParam.optional(),
3600
4001
  raw: z.boolean().optional()
3601
4002
  },
4003
+ outputSchema: toolOutputSchema(logTargetsOutputSchema),
3602
4004
  annotations: READ
3603
4005
  }, ({ athleteId, startDate, endDate, program, programId, teamId, raw }) => attempt(async () => {
3604
4006
  const workouts = selectWorkoutsByProgram(await fetchCoachAthleteWorkouts(ctx.client, toId(athleteId), startDate, endDate), definedProps({
@@ -3619,6 +4021,7 @@ function registerAthleteLogTools(server, ctx) {
3619
4021
  ...coachLogSetArgsSchema.shape,
3620
4022
  confirm: z.boolean().optional()
3621
4023
  },
4024
+ outputSchema: toolOutputSchema(setLogOutputSchema),
3622
4025
  annotations: DESTRUCTIVE
3623
4026
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
3624
4027
  const aId = toId(athleteId);
@@ -3638,6 +4041,7 @@ function registerAthleteLogTools(server, ctx) {
3638
4041
  ...coachLogSessionArgsSchema.shape,
3639
4042
  confirm: z.boolean().optional()
3640
4043
  },
4044
+ outputSchema: toolOutputSchema(sessionLogOutputSchema),
3641
4045
  annotations: DESTRUCTIVE
3642
4046
  }, ({ athleteId, date, exercises, confirm }, extra) => attempt(async () => {
3643
4047
  const aId = toId(athleteId);
@@ -3662,6 +4066,7 @@ function registerAthleteSwapTool(server, ctx) {
3662
4066
  ...swapAthleteExerciseArgsSchema.shape,
3663
4067
  confirm: z.boolean().optional()
3664
4068
  },
4069
+ outputSchema: toolOutputSchema(exerciseSwapOutputSchema),
3665
4070
  annotations: DESTRUCTIVE
3666
4071
  }, ({ savedWorkoutSetExerciseId, exerciseId, confirm }, extra) => attempt(async () => {
3667
4072
  const sweId = toId(savedWorkoutSetExerciseId);
@@ -3687,6 +4092,7 @@ function registerAthletePrescribeTool(server, ctx) {
3687
4092
  ...coachPrescribeSetArgsSchema.shape,
3688
4093
  confirm: z.boolean().optional()
3689
4094
  },
4095
+ outputSchema: toolOutputSchema(setPrescriptionOutputSchema),
3690
4096
  annotations: DESTRUCTIVE
3691
4097
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
3692
4098
  const aId = toId(athleteId);
@@ -3702,11 +4108,6 @@ function registerAthletePrescribeTool(server, ctx) {
3702
4108
  }
3703
4109
  //#endregion
3704
4110
  //#region ../core/src/tools/teams.ts
3705
- const ADDITIVE$1 = {
3706
- readOnlyHint: false,
3707
- destructiveHint: false,
3708
- openWorldHint: true
3709
- };
3710
4111
  /**
3711
4112
  * Team write tools. The team reads (list_teams, get_team, list_team_codes) live in
3712
4113
  * reads.ts; this module covers create/rename/delete plus the join-code lifecycle.
@@ -3716,19 +4117,25 @@ function registerTeamTools(server, ctx) {
3716
4117
  title: "Create a team",
3717
4118
  description: "Create a team (POST /1.0/coach/team/createWithTitleAndCode). Also creates the team's calendar/program. Returns the new team including its calendar id. Use the team id with athlete_invite. To point a new team at an existing calendar instead of its auto-created one, follow up with team_update groupProgram.",
3718
4119
  inputSchema: { title: z.string().min(1) },
3719
- annotations: ADDITIVE$1
4120
+ outputSchema: opaqueOutputSchema,
4121
+ annotations: ADDITIVE
3720
4122
  }, ({ title }) => apiCall(ctx, "POST", "/1.0/coach/team/createWithTitleAndCode", { body: { title } }));
3721
4123
  server.registerTool("team_update", {
3722
4124
  title: "Update a team",
3723
- description: "Update a team's title and/or reassign its calendar (PUT /v5/teams/{teamId}). Pass groupProgram (a program/calendar id — typically another team's group_program from list_teams, or get_team) to point this team at an existing parent program. At least one of title or groupProgram is required; when only groupProgram is set the current title is preserved.",
4125
+ description: "Update a team's title and/or reassign its calendar (PUT /v5/teams/{teamId}). Pass groupProgram (a program/calendar id — typically another team's group_program from list_teams, or get_team) to point this team at an existing parent program. At least one of title or groupProgram is required; when only groupProgram is set the current title is preserved. Requires confirmation (elicitation, or confirm:true).",
3724
4126
  inputSchema: {
3725
4127
  teamId: idParam,
3726
4128
  title: z.string().min(1).optional(),
3727
- groupProgram: idParam.optional()
4129
+ groupProgram: idParam.optional(),
4130
+ confirm: z.boolean().optional()
3728
4131
  },
3729
- annotations: ADDITIVE$1
3730
- }, ({ teamId, title, groupProgram }) => attempt(async () => {
3731
- const args = { teamId: toId(teamId) };
4132
+ outputSchema: opaqueOutputSchema,
4133
+ annotations: DESTRUCTIVE
4134
+ }, ({ teamId, title, groupProgram, confirm }, extra) => attempt(async () => {
4135
+ const id = toId(teamId);
4136
+ const blocked = confirmGate(extra, `Update team ${id}? This overwrites its live title and/or calendar assignment.`, confirm);
4137
+ if (blocked) return blocked;
4138
+ const args = { teamId: id };
3732
4139
  if (title !== void 0) args.title = title;
3733
4140
  if (groupProgram !== void 0) args.groupProgram = toId(groupProgram);
3734
4141
  return jsonResult(await updateTeam(ctx.client, args));
@@ -3740,6 +4147,7 @@ function registerTeamTools(server, ctx) {
3740
4147
  teamId: idParam,
3741
4148
  confirm: z.boolean().optional()
3742
4149
  },
4150
+ outputSchema: opaqueOutputSchema,
3743
4151
  annotations: DESTRUCTIVE
3744
4152
  }, ({ teamId, confirm }, extra) => attempt(async () => {
3745
4153
  const id = toId(teamId);
@@ -3754,7 +4162,8 @@ function registerTeamTools(server, ctx) {
3754
4162
  teamId: idParam,
3755
4163
  type: z.number().int().optional()
3756
4164
  },
3757
- annotations: ADDITIVE$1
4165
+ outputSchema: opaqueOutputSchema,
4166
+ annotations: ADDITIVE
3758
4167
  }, ({ teamId, type }) => apiCall(ctx, "POST", `/v5/teams/${toId(teamId)}/teamCodes`, { body: { type: type ?? 2 } }));
3759
4168
  server.registerTool("team_code_delete", {
3760
4169
  title: "Delete a team join code",
@@ -3763,6 +4172,7 @@ function registerTeamTools(server, ctx) {
3763
4172
  codeId: idParam,
3764
4173
  confirm: z.boolean().optional()
3765
4174
  },
4175
+ outputSchema: opaqueOutputSchema,
3766
4176
  annotations: DESTRUCTIVE
3767
4177
  }, ({ codeId, confirm }, extra) => attempt(async () => {
3768
4178
  const id = toId(codeId);
@@ -3782,6 +4192,7 @@ function registerTeamPublishSettings(server, ctx) {
3782
4192
  ...teamPublishPatchObject.shape,
3783
4193
  confirm: z.boolean().optional()
3784
4194
  },
4195
+ outputSchema: opaqueOutputSchema,
3785
4196
  annotations: DESTRUCTIVE
3786
4197
  }, ({ teamId, programId, pub_enabled, pub_days, pub_time, pub_timezone, confirm }, extra) => attempt(async () => {
3787
4198
  const blocked = confirmGate(extra, "Change auto-publish settings? This controls when athletes see programmed sessions.", confirm);
@@ -3804,11 +4215,6 @@ function registerTeamPublishSettings(server, ctx) {
3804
4215
  }
3805
4216
  //#endregion
3806
4217
  //#region ../core/src/tools/programs.ts
3807
- const ADDITIVE = {
3808
- readOnlyHint: false,
3809
- destructiveHint: false,
3810
- openWorldHint: true
3811
- };
3812
4218
  /** Standalone program writes. Program reads live in reads.ts. */
3813
4219
  function registerProgramTools(server, ctx) {
3814
4220
  server.registerTool("program_create", {
@@ -3818,6 +4224,7 @@ function registerProgramTools(server, ctx) {
3818
4224
  kind: z.enum(PROGRAM_KINDS),
3819
4225
  name: z.string().trim().min(1)
3820
4226
  },
4227
+ outputSchema: toolOutputSchema(programCreatedOutputSchema),
3821
4228
  annotations: ADDITIVE
3822
4229
  }, ({ kind, name }) => attempt(async () => jsonResult(await createProgram(ctx.client, {
3823
4230
  kind,
@@ -3830,6 +4237,7 @@ function registerProgramTools(server, ctx) {
3830
4237
  programId: idParam,
3831
4238
  confirm: z.boolean().optional()
3832
4239
  },
4240
+ outputSchema: toolOutputSchema(programDeletedOutputSchema),
3833
4241
  annotations: DESTRUCTIVE
3834
4242
  }, ({ programId, confirm }, extra) => attempt(async () => {
3835
4243
  const id = toId(programId);
@@ -3856,6 +4264,7 @@ function registerAnalyticsTools(server, ctx) {
3856
4264
  dateEnd: z.string().optional(),
3857
4265
  useMetric: z.boolean().optional()
3858
4266
  },
4267
+ outputSchema: opaqueOutputSchema,
3859
4268
  annotations: READ
3860
4269
  }, ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => attempt(async () => jsonResult(await queryAnalytics(ctx.client, definedProps({
3861
4270
  metric,
@@ -3873,17 +4282,20 @@ function registerAnalyticsTools(server, ctx) {
3873
4282
  function registerExerciseUpdate(server, index) {
3874
4283
  server.registerTool("exercise_update", {
3875
4284
  title: "Update custom exercise",
3876
- description: "Update a custom exercise (POST /2.0/coach/exercise/update/{id}) and write it through to the mirror. Same body as exercise_create. Only works for exercises with can_edit:1.",
4285
+ description: "Update a custom exercise (POST /2.0/coach/exercise/update/{id}) and write it through to the mirror. Same body as exercise_create. Only works for exercises with can_edit:1. Requires confirmation (elicitation, or confirm:true).",
3877
4286
  inputSchema: {
3878
4287
  id: idParam,
3879
- exercise: exerciseCreateSchema
4288
+ exercise: exerciseCreateSchema,
4289
+ confirm: z.boolean().optional()
3880
4290
  },
3881
- annotations: {
3882
- readOnlyHint: false,
3883
- destructiveHint: false,
3884
- openWorldHint: true
3885
- }
3886
- }, ({ id, exercise }) => attempt(async () => jsonResult(await index.update(toId(id), exercise))));
4291
+ outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
4292
+ annotations: DESTRUCTIVE
4293
+ }, ({ id, exercise, confirm }, extra) => attempt(async () => {
4294
+ const exerciseId = toId(id);
4295
+ const blocked = confirmGate(extra, `Update custom exercise ${exerciseId}? This overwrites its live TrainHeroic definition.`, confirm);
4296
+ if (blocked) return blocked;
4297
+ return jsonResult(await index.update(exerciseId, exercise));
4298
+ }));
3887
4299
  }
3888
4300
  function registerExerciseDelete(server, index) {
3889
4301
  server.registerTool("exercise_delete", {
@@ -3893,6 +4305,7 @@ function registerExerciseDelete(server, index) {
3893
4305
  id: idParam,
3894
4306
  confirm: z.boolean().optional()
3895
4307
  },
4308
+ outputSchema: toolOutputSchema(exerciseDeletedOutputSchema),
3896
4309
  annotations: DESTRUCTIVE
3897
4310
  }, ({ id, confirm }, extra) => attempt(async () => {
3898
4311
  const exerciseId = toId(id);
@@ -3902,17 +4315,12 @@ function registerExerciseDelete(server, index) {
3902
4315
  return jsonResult({ deleted: exerciseId });
3903
4316
  }));
3904
4317
  }
3905
- /**
3906
- * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
3907
- * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
3908
- * read correctly on both backends.
3909
- */
3910
- function registerExerciseTools(server, ctx) {
3911
- const index = ctx.index;
4318
+ function registerExerciseReads(server, index) {
3912
4319
  server.registerTool("exercise_resolve", {
3913
4320
  title: "Resolve exercise name",
3914
4321
  description: "Map a name to an exercise id via the local mirror. Prefer this over exercise_search when you want a single authoritative id for a known name. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Each result's `units` array lists the fixed measurement units by entry slot; they are fixed per exercise — check them before prescribing. `can_edit` is 1 only for the coach's own custom exercises and 0 for built-in library exercises.",
3915
4322
  inputSchema: { name: z.string().min(1) },
4323
+ outputSchema: toolOutputSchema(exerciseResolveOutputSchema),
3916
4324
  annotations: READ
3917
4325
  }, ({ name }) => attempt(async () => jsonResult(await index.resolve(name))));
3918
4326
  server.registerTool("exercise_search", {
@@ -3922,12 +4330,14 @@ function registerExerciseTools(server, ctx) {
3922
4330
  query: z.string().min(1),
3923
4331
  limit: z.number().int().positive().max(100).optional()
3924
4332
  },
4333
+ outputSchema: toolOutputSchema(z.array(exerciseViewSchema)),
3925
4334
  annotations: READ
3926
4335
  }, ({ query, limit }) => attempt(async () => jsonResult(await index.search(query, limit ?? 20))));
3927
4336
  server.registerTool("exercise_get", {
3928
4337
  title: "Get exercise",
3929
4338
  description: "Full exercise object (with units) by id.",
3930
4339
  inputSchema: { id: idParam },
4340
+ outputSchema: toolOutputSchema(exerciseGetOutputSchema),
3931
4341
  annotations: READ
3932
4342
  }, ({ id }) => attempt(async () => {
3933
4343
  const ex = await index.get(toId(id));
@@ -3937,21 +4347,28 @@ function registerExerciseTools(server, ctx) {
3937
4347
  title: "Sync exercise library",
3938
4348
  description: "Refresh the cached exercise index from TrainHeroic.",
3939
4349
  inputSchema: { force: z.boolean().optional() },
4350
+ outputSchema: opaqueOutputSchema,
3940
4351
  annotations: SYNC
3941
4352
  }, ({ force }) => attempt(async () => {
3942
4353
  if (force ?? false) return jsonResult(await index.refresh());
3943
4354
  await index.ensureFresh();
3944
4355
  return jsonResult(await index.stats());
3945
4356
  }));
4357
+ }
4358
+ /**
4359
+ * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
4360
+ * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
4361
+ * read correctly on both backends.
4362
+ */
4363
+ function registerExerciseTools(server, ctx) {
4364
+ const index = ctx.index;
4365
+ registerExerciseReads(server, index);
3946
4366
  server.registerTool("exercise_create", {
3947
4367
  title: "Create custom exercise",
3948
4368
  description: "Create a custom exercise (POST /2.0/coach/exercise/create) and write it through to the mirror. Body example: {\"title\":\"Sandbag Clean\",\"param_1_type\":3,\"param_2_type\":1}.",
3949
4369
  inputSchema: { exercise: exerciseCreateSchema },
3950
- annotations: {
3951
- readOnlyHint: false,
3952
- destructiveHint: false,
3953
- openWorldHint: true
3954
- }
4370
+ outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
4371
+ annotations: ADDITIVE
3955
4372
  }, ({ exercise }) => attempt(async () => jsonResult(await index.create(exercise))));
3956
4373
  registerExerciseUpdate(server, index);
3957
4374
  registerExerciseDelete(server, index);
@@ -3959,9 +4376,11 @@ function registerExerciseTools(server, ctx) {
3959
4376
  title: "Forget exercise (cache only)",
3960
4377
  description: "Remove an exercise from the local mirror only. Does not call TrainHeroic — use exercise_delete to delete the live custom exercise.",
3961
4378
  inputSchema: { id: idParam },
4379
+ outputSchema: toolOutputSchema(exerciseForgottenOutputSchema),
3962
4380
  annotations: {
3963
4381
  readOnlyHint: false,
3964
4382
  idempotentHint: true,
4383
+ destructiveHint: false,
3965
4384
  openWorldHint: false
3966
4385
  }
3967
4386
  }, ({ id }) => attempt(async () => {
@@ -3972,6 +4391,7 @@ function registerExerciseTools(server, ctx) {
3972
4391
  title: "Exercise index stats",
3973
4392
  description: "Row counts and sync state for the cached exercise index.",
3974
4393
  inputSchema: {},
4394
+ outputSchema: opaqueOutputSchema,
3975
4395
  annotations: READ
3976
4396
  }, () => attempt(async () => jsonResult(await index.stats())));
3977
4397
  }
@@ -3990,11 +4410,8 @@ function registerBuild(server, ctx) {
3990
4410
  blocks: z.array(blockSpecSchema),
3991
4411
  instruction: z.string().optional()
3992
4412
  },
3993
- annotations: {
3994
- readOnlyHint: false,
3995
- destructiveHint: false,
3996
- openWorldHint: true
3997
- }
4413
+ outputSchema: toolOutputSchema(workoutBuildOutputSchema),
4414
+ annotations: ADDITIVE
3998
4415
  }, ({ programId, athleteId, date, timelineDay, blocks, instruction }) => attempt(async () => {
3999
4416
  if (date === void 0 && timelineDay === void 0) return errorResult("Provide either date (YYYY-M-D) or timelineDay.");
4000
4417
  const resolveArgs = {};
@@ -4034,10 +4451,8 @@ function registerReadPublish(server, ctx) {
4034
4451
  date: z.string(),
4035
4452
  pwId: z.number()
4036
4453
  },
4037
- annotations: {
4038
- readOnlyHint: true,
4039
- openWorldHint: true
4040
- }
4454
+ outputSchema: toolOutputSchema(workoutReadOutputSchema),
4455
+ annotations: READ
4041
4456
  }, ({ programId, date, pwId }) => attempt(async () => jsonResult(await readSession(ctx.client, programId, parseWorkoutDate(date), pwId))));
4042
4457
  server.registerTool("workout_publish", {
4043
4458
  title: "Publish a session",
@@ -4048,11 +4463,8 @@ function registerReadPublish(server, ctx) {
4048
4463
  pwId: z.number(),
4049
4464
  confirm: z.boolean().optional()
4050
4465
  },
4051
- annotations: {
4052
- readOnlyHint: false,
4053
- destructiveHint: true,
4054
- openWorldHint: true
4055
- }
4466
+ outputSchema: toolOutputSchema(workoutPublishOutputSchema),
4467
+ annotations: DESTRUCTIVE
4056
4468
  }, ({ programId, date, pwId, confirm }, extra) => attempt(async () => {
4057
4469
  const blocked = confirmGate(extra, `Publish session ${pwId} on ${date}? This is athlete-facing and immediate.`, confirm);
4058
4470
  if (blocked) return blocked;
@@ -4074,11 +4486,8 @@ function registerLifecycle(server, ctx) {
4074
4486
  pwId: z.number(),
4075
4487
  confirm: z.boolean().optional()
4076
4488
  },
4077
- annotations: {
4078
- readOnlyHint: false,
4079
- destructiveHint: true,
4080
- openWorldHint: true
4081
- }
4489
+ outputSchema: toolOutputSchema(removedSessionOutputSchema),
4490
+ annotations: DESTRUCTIVE
4082
4491
  }, ({ programId, pwId, confirm }, extra) => attempt(async () => {
4083
4492
  const blocked = confirmGate(extra, `Delete session ${pwId}? This removes it from the live calendar and is hard to undo.`, confirm);
4084
4493
  if (blocked) return blocked;
@@ -4092,11 +4501,8 @@ function registerLifecycle(server, ctx) {
4092
4501
  pwId: z.number(),
4093
4502
  confirm: z.boolean().optional()
4094
4503
  },
4095
- annotations: {
4096
- readOnlyHint: false,
4097
- destructiveHint: true,
4098
- openWorldHint: true
4099
- }
4504
+ outputSchema: opaqueOutputSchema,
4505
+ annotations: DESTRUCTIVE
4100
4506
  }, ({ pwId, confirm }, extra) => attempt(async () => {
4101
4507
  const blocked = confirmGate(extra, `Unpublish session ${pwId}? Athletes will no longer see it.`, confirm);
4102
4508
  if (blocked) return blocked;
@@ -4110,11 +4516,8 @@ function registerLifecycle(server, ctx) {
4110
4516
  pwId: z.number(),
4111
4517
  toDate: z.string()
4112
4518
  },
4113
- annotations: {
4114
- readOnlyHint: false,
4115
- destructiveHint: false,
4116
- openWorldHint: true
4117
- }
4519
+ outputSchema: opaqueOutputSchema,
4520
+ annotations: ADDITIVE
4118
4521
  }, ({ toProgramId, pwId, toDate }) => attempt(async () => jsonResult(await copySession(ctx.client, {
4119
4522
  toProgramId,
4120
4523
  pwId,
@@ -4124,23 +4527,17 @@ function registerLifecycle(server, ctx) {
4124
4527
  title: "Save a session to the library",
4125
4528
  description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
4126
4529
  inputSchema: { workoutId: z.number() },
4127
- annotations: {
4128
- readOnlyHint: false,
4129
- destructiveHint: false,
4130
- openWorldHint: true
4131
- }
4530
+ outputSchema: opaqueOutputSchema,
4531
+ annotations: ADDITIVE
4132
4532
  }, ({ workoutId }) => apiCall(ctx, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${workoutId}`));
4133
4533
  }
4134
4534
  function registerTemplateLibrary(server, ctx) {
4135
4535
  server.registerTool("session_template_create", {
4136
4536
  title: "Create a session template",
4137
4537
  description: "Create an empty reusable session template in the library (POST /v5/sessions/template). Distinct from session_save_as_template, which copies an existing session. Pass title and optional instruction.",
4138
- inputSchema: sessionTemplateCreateSchema,
4139
- annotations: {
4140
- readOnlyHint: false,
4141
- destructiveHint: false,
4142
- openWorldHint: true
4143
- }
4538
+ inputSchema: sessionTemplateCreateSchema.shape,
4539
+ outputSchema: toolOutputSchema(sessionTemplateCreatedOutputSchema),
4540
+ annotations: ADDITIVE
4144
4541
  }, ({ title, instruction }) => attempt(async () => jsonResult(await createSessionTemplate(ctx.client, definedProps({
4145
4542
  title,
4146
4543
  instruction
@@ -4152,6 +4549,7 @@ function registerTemplateLibrary(server, ctx) {
4152
4549
  id: idParam,
4153
4550
  confirm: z.boolean().optional()
4154
4551
  },
4552
+ outputSchema: opaqueOutputSchema,
4155
4553
  annotations: DESTRUCTIVE
4156
4554
  }, ({ id, confirm }, extra) => attempt(async () => {
4157
4555
  const templateId = toId(id);
@@ -4174,6 +4572,7 @@ function registerReads(server, ctx) {
4174
4572
  title: "List conversations (live)",
4175
4573
  description: "List chat streams (id, kind, title) live from the API; no setup needed. Use the id to read/draft/send.",
4176
4574
  inputSchema: {},
4575
+ outputSchema: opaqueOutputSchema,
4177
4576
  annotations: READ
4178
4577
  }, () => attempt(async () => {
4179
4578
  return jsonResult((await fetchStreams(ctx.client)).map(({ stream, kind }) => ({
@@ -4192,12 +4591,14 @@ function registerReads(server, ctx) {
4192
4591
  limit: z.number().int().positive().max(200).optional(),
4193
4592
  afterCommentId: idParam.optional()
4194
4593
  },
4594
+ outputSchema: opaqueOutputSchema,
4195
4595
  annotations: READ
4196
4596
  }, ({ streamId, limit, afterCommentId }) => attempt(async () => jsonResult(await readLive(ctx.client, toId(streamId), limit ?? 20, afterCommentId === void 0 ? void 0 : toId(afterCommentId)))));
4197
4597
  server.registerTool("message_draft", {
4198
4598
  title: "Draft a message (preview only)",
4199
4599
  description: "Preview the exact payload and target WITHOUT sending. Always safe.",
4200
4600
  inputSchema: commentDraftSchema.shape,
4601
+ outputSchema: toolOutputSchema(messageDraftOutputSchema),
4201
4602
  annotations: READ
4202
4603
  }, ({ streamId, text, replyTo }) => attempt(async () => {
4203
4604
  const id = toId(streamId);
@@ -4217,6 +4618,7 @@ function registerWrites(server, ctx) {
4217
4618
  ...commentDraftSchema.shape,
4218
4619
  confirm: z.boolean().optional()
4219
4620
  },
4621
+ outputSchema: toolOutputSchema(messageSentOutputSchema),
4220
4622
  annotations: DESTRUCTIVE
4221
4623
  }, ({ streamId, text, replyTo, confirm }, extra) => attempt(async () => {
4222
4624
  const id = toId(streamId);
@@ -4235,6 +4637,7 @@ function registerWrites(server, ctx) {
4235
4637
  commentId: idParam,
4236
4638
  confirm: z.boolean().optional()
4237
4639
  },
4640
+ outputSchema: toolOutputSchema(messageDeletedOutputSchema),
4238
4641
  annotations: DESTRUCTIVE
4239
4642
  }, ({ streamId, commentId, confirm }, extra) => attempt(async () => {
4240
4643
  const blocked = confirmGate(extra, `Delete comment ${toId(commentId)} from stream ${toId(streamId)}? Acts on the live account.`, confirm);
@@ -4290,7 +4693,7 @@ var JsonFileLibraryCache = class {
4290
4693
  };
4291
4694
  //#endregion
4292
4695
  //#region package.json
4293
- var version = "3.2.0";
4696
+ var version = "3.3.1";
4294
4697
  //#endregion
4295
4698
  //#region src/server.ts
4296
4699
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "3.2.0",
3
+ "version": "3.3.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,13 +21,13 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/server": "2.0.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/core": "3.2.0",
25
- "@trainheroic-unofficial/js": "3.2.0"
24
+ "@trainheroic-unofficial/core": "3.3.1",
25
+ "@trainheroic-unofficial/js": "3.3.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.2.0",
29
29
  "tsdown": "^0.22.14",
30
- "tsx": "^4.23.11",
30
+ "tsx": "^4.23.12",
31
31
  "typescript": "^7.0.2",
32
32
  "vitest": "^4.1.10"
33
33
  },