@thebriangao/totem 1.4.4

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 (405) hide show
  1. package/.dockerignore +23 -0
  2. package/.env.example +66 -0
  3. package/CHANGELOG.md +283 -0
  4. package/CONTRIBUTING.md +149 -0
  5. package/Dockerfile +53 -0
  6. package/LICENSE +37 -0
  7. package/README.md +587 -0
  8. package/SECURITY.md +79 -0
  9. package/TOOLS.md +429 -0
  10. package/WHOOP.md +2673 -0
  11. package/assets/banner.svg +38 -0
  12. package/dist/cli/index.js +589 -0
  13. package/dist/cli/index.js.map +1 -0
  14. package/dist/cli/setup.js +1127 -0
  15. package/dist/cli/setup.js.map +1 -0
  16. package/dist/cli/ui.js +512 -0
  17. package/dist/cli/ui.js.map +1 -0
  18. package/dist/cli/update.js +465 -0
  19. package/dist/cli/update.js.map +1 -0
  20. package/dist/data/behaviors.js +2777 -0
  21. package/dist/data/behaviors.js.map +1 -0
  22. package/dist/data/endpoints.js +320 -0
  23. package/dist/data/endpoints.js.map +1 -0
  24. package/dist/data/exercises.js +4863 -0
  25. package/dist/data/exercises.js.map +1 -0
  26. package/dist/data/sports.js +212 -0
  27. package/dist/data/sports.js.map +1 -0
  28. package/dist/lib/concurrency.js +27 -0
  29. package/dist/lib/concurrency.js.map +1 -0
  30. package/dist/lib/dates.js +29 -0
  31. package/dist/lib/dates.js.map +1 -0
  32. package/dist/lib/format.js +22 -0
  33. package/dist/lib/format.js.map +1 -0
  34. package/dist/lib/stats.js +32 -0
  35. package/dist/lib/stats.js.map +1 -0
  36. package/dist/lib/timezone.js +249 -0
  37. package/dist/lib/timezone.js.map +1 -0
  38. package/dist/lib/walk.js +396 -0
  39. package/dist/lib/walk.js.map +1 -0
  40. package/dist/projections/behavior_impact.js +96 -0
  41. package/dist/projections/behavior_impact.js.map +1 -0
  42. package/dist/projections/calendar.js +33 -0
  43. package/dist/projections/calendar.js.map +1 -0
  44. package/dist/projections/communities.js +105 -0
  45. package/dist/projections/communities.js.map +1 -0
  46. package/dist/projections/cycle.js +81 -0
  47. package/dist/projections/cycle.js.map +1 -0
  48. package/dist/projections/hr_zones.js +35 -0
  49. package/dist/projections/hr_zones.js.map +1 -0
  50. package/dist/projections/journal.js +56 -0
  51. package/dist/projections/journal.js.map +1 -0
  52. package/dist/projections/leaderboard.js +37 -0
  53. package/dist/projections/leaderboard.js.map +1 -0
  54. package/dist/projections/lift_exercise.js +22 -0
  55. package/dist/projections/lift_exercise.js.map +1 -0
  56. package/dist/projections/lift_history.js +133 -0
  57. package/dist/projections/lift_history.js.map +1 -0
  58. package/dist/projections/lift_library.js +71 -0
  59. package/dist/projections/lift_library.js.map +1 -0
  60. package/dist/projections/lift_progression.js +138 -0
  61. package/dist/projections/lift_progression.js.map +1 -0
  62. package/dist/projections/lift_prs.js +20 -0
  63. package/dist/projections/lift_prs.js.map +1 -0
  64. package/dist/projections/live_hr.js +19 -0
  65. package/dist/projections/live_hr.js.map +1 -0
  66. package/dist/projections/live_state.js +23 -0
  67. package/dist/projections/live_state.js.map +1 -0
  68. package/dist/projections/live_stress.js +11 -0
  69. package/dist/projections/live_stress.js.map +1 -0
  70. package/dist/projections/performance_assessment.js +15 -0
  71. package/dist/projections/performance_assessment.js.map +1 -0
  72. package/dist/projections/profile.js +59 -0
  73. package/dist/projections/profile.js.map +1 -0
  74. package/dist/projections/recovery.js +131 -0
  75. package/dist/projections/recovery.js.map +1 -0
  76. package/dist/projections/sleep.js +256 -0
  77. package/dist/projections/sleep.js.map +1 -0
  78. package/dist/projections/sleep_need.js +32 -0
  79. package/dist/projections/sleep_need.js.map +1 -0
  80. package/dist/projections/smart_alarm.js +45 -0
  81. package/dist/projections/smart_alarm.js.map +1 -0
  82. package/dist/projections/strain.js +128 -0
  83. package/dist/projections/strain.js.map +1 -0
  84. package/dist/projections/stress.js +86 -0
  85. package/dist/projections/stress.js.map +1 -0
  86. package/dist/projections/today.js +129 -0
  87. package/dist/projections/today.js.map +1 -0
  88. package/dist/projections/trend.js +149 -0
  89. package/dist/projections/trend.js.map +1 -0
  90. package/dist/projections/workout.js +161 -0
  91. package/dist/projections/workout.js.map +1 -0
  92. package/dist/projections/workouts.js +37 -0
  93. package/dist/projections/workouts.js.map +1 -0
  94. package/dist/schemas/calendar.js +12 -0
  95. package/dist/schemas/calendar.js.map +1 -0
  96. package/dist/schemas/coach.js +11 -0
  97. package/dist/schemas/coach.js.map +1 -0
  98. package/dist/schemas/communities.js +51 -0
  99. package/dist/schemas/communities.js.map +1 -0
  100. package/dist/schemas/compare.js +15 -0
  101. package/dist/schemas/compare.js.map +1 -0
  102. package/dist/schemas/escape.js +18 -0
  103. package/dist/schemas/escape.js.map +1 -0
  104. package/dist/schemas/journal.js +69 -0
  105. package/dist/schemas/journal.js.map +1 -0
  106. package/dist/schemas/leaderboard.js +25 -0
  107. package/dist/schemas/leaderboard.js.map +1 -0
  108. package/dist/schemas/live.js +26 -0
  109. package/dist/schemas/live.js.map +1 -0
  110. package/dist/schemas/performance.js +12 -0
  111. package/dist/schemas/performance.js.map +1 -0
  112. package/dist/schemas/primitives.js +29 -0
  113. package/dist/schemas/primitives.js.map +1 -0
  114. package/dist/schemas/profile.js +39 -0
  115. package/dist/schemas/profile.js.map +1 -0
  116. package/dist/schemas/recovery.js +27 -0
  117. package/dist/schemas/recovery.js.map +1 -0
  118. package/dist/schemas/settings.js +26 -0
  119. package/dist/schemas/settings.js.map +1 -0
  120. package/dist/schemas/sleep.js +38 -0
  121. package/dist/schemas/sleep.js.map +1 -0
  122. package/dist/schemas/sleep_need.js +15 -0
  123. package/dist/schemas/sleep_need.js.map +1 -0
  124. package/dist/schemas/smart_alarm.js +36 -0
  125. package/dist/schemas/smart_alarm.js.map +1 -0
  126. package/dist/schemas/strain.js +24 -0
  127. package/dist/schemas/strain.js.map +1 -0
  128. package/dist/schemas/strength.js +170 -0
  129. package/dist/schemas/strength.js.map +1 -0
  130. package/dist/schemas/stress.js +16 -0
  131. package/dist/schemas/stress.js.map +1 -0
  132. package/dist/schemas/today.js +38 -0
  133. package/dist/schemas/today.js.map +1 -0
  134. package/dist/schemas/trend.js +50 -0
  135. package/dist/schemas/trend.js.map +1 -0
  136. package/dist/schemas/womens_health.js +23 -0
  137. package/dist/schemas/womens_health.js.map +1 -0
  138. package/dist/schemas/workouts.js +50 -0
  139. package/dist/schemas/workouts.js.map +1 -0
  140. package/dist/scripts/cognito_bootstrap.js +278 -0
  141. package/dist/scripts/cognito_bootstrap.js.map +1 -0
  142. package/dist/server-http.js +221 -0
  143. package/dist/server-http.js.map +1 -0
  144. package/dist/server.js +74 -0
  145. package/dist/server.js.map +1 -0
  146. package/dist/tools/register.js +117 -0
  147. package/dist/tools/register.js.map +1 -0
  148. package/dist/tools/v2/activity_create.js +64 -0
  149. package/dist/tools/v2/activity_create.js.map +1 -0
  150. package/dist/tools/v2/activity_delete.js +26 -0
  151. package/dist/tools/v2/activity_delete.js.map +1 -0
  152. package/dist/tools/v2/behavior_impact.js +36 -0
  153. package/dist/tools/v2/behavior_impact.js.map +1 -0
  154. package/dist/tools/v2/calendar.js +28 -0
  155. package/dist/tools/v2/calendar.js.map +1 -0
  156. package/dist/tools/v2/coach_ask.js +117 -0
  157. package/dist/tools/v2/coach_ask.js.map +1 -0
  158. package/dist/tools/v2/communities.js +60 -0
  159. package/dist/tools/v2/communities.js.map +1 -0
  160. package/dist/tools/v2/compare.js +67 -0
  161. package/dist/tools/v2/compare.js.map +1 -0
  162. package/dist/tools/v2/cycle.js +23 -0
  163. package/dist/tools/v2/cycle.js.map +1 -0
  164. package/dist/tools/v2/cycle_log.js +43 -0
  165. package/dist/tools/v2/cycle_log.js.map +1 -0
  166. package/dist/tools/v2/day.js +32 -0
  167. package/dist/tools/v2/day.js.map +1 -0
  168. package/dist/tools/v2/endpoints.js +28 -0
  169. package/dist/tools/v2/endpoints.js.map +1 -0
  170. package/dist/tools/v2/hidden_metric.js +28 -0
  171. package/dist/tools/v2/hidden_metric.js.map +1 -0
  172. package/dist/tools/v2/hr_zones.js +24 -0
  173. package/dist/tools/v2/hr_zones.js.map +1 -0
  174. package/dist/tools/v2/hr_zones_set.js +51 -0
  175. package/dist/tools/v2/hr_zones_set.js.map +1 -0
  176. package/dist/tools/v2/journal.js +26 -0
  177. package/dist/tools/v2/journal.js.map +1 -0
  178. package/dist/tools/v2/journal_autopop.js +19 -0
  179. package/dist/tools/v2/journal_autopop.js.map +1 -0
  180. package/dist/tools/v2/journal_catalog.js +44 -0
  181. package/dist/tools/v2/journal_catalog.js.map +1 -0
  182. package/dist/tools/v2/journal_log.js +78 -0
  183. package/dist/tools/v2/journal_log.js.map +1 -0
  184. package/dist/tools/v2/leaderboard.js +79 -0
  185. package/dist/tools/v2/leaderboard.js.map +1 -0
  186. package/dist/tools/v2/lift_catalog.js +47 -0
  187. package/dist/tools/v2/lift_catalog.js.map +1 -0
  188. package/dist/tools/v2/lift_custom_exercise.js +108 -0
  189. package/dist/tools/v2/lift_custom_exercise.js.map +1 -0
  190. package/dist/tools/v2/lift_exercise.js +31 -0
  191. package/dist/tools/v2/lift_exercise.js.map +1 -0
  192. package/dist/tools/v2/lift_history.js +39 -0
  193. package/dist/tools/v2/lift_history.js.map +1 -0
  194. package/dist/tools/v2/lift_library.js +22 -0
  195. package/dist/tools/v2/lift_library.js.map +1 -0
  196. package/dist/tools/v2/lift_log.js +95 -0
  197. package/dist/tools/v2/lift_log.js.map +1 -0
  198. package/dist/tools/v2/lift_progression.js +30 -0
  199. package/dist/tools/v2/lift_progression.js.map +1 -0
  200. package/dist/tools/v2/lift_prs.js +21 -0
  201. package/dist/tools/v2/lift_prs.js.map +1 -0
  202. package/dist/tools/v2/lift_template_save.js +83 -0
  203. package/dist/tools/v2/lift_template_save.js.map +1 -0
  204. package/dist/tools/v2/live_hr.js +21 -0
  205. package/dist/tools/v2/live_hr.js.map +1 -0
  206. package/dist/tools/v2/live_state.js +21 -0
  207. package/dist/tools/v2/live_state.js.map +1 -0
  208. package/dist/tools/v2/live_stress.js +22 -0
  209. package/dist/tools/v2/live_stress.js.map +1 -0
  210. package/dist/tools/v2/performance_assessment.js +38 -0
  211. package/dist/tools/v2/performance_assessment.js.map +1 -0
  212. package/dist/tools/v2/profile.js +28 -0
  213. package/dist/tools/v2/profile.js.map +1 -0
  214. package/dist/tools/v2/profile_update.js +66 -0
  215. package/dist/tools/v2/profile_update.js.map +1 -0
  216. package/dist/tools/v2/raw.js +43 -0
  217. package/dist/tools/v2/raw.js.map +1 -0
  218. package/dist/tools/v2/recovery.js +31 -0
  219. package/dist/tools/v2/recovery.js.map +1 -0
  220. package/dist/tools/v2/sleep.js +23 -0
  221. package/dist/tools/v2/sleep.js.map +1 -0
  222. package/dist/tools/v2/sleep_need.js +21 -0
  223. package/dist/tools/v2/sleep_need.js.map +1 -0
  224. package/dist/tools/v2/smart_alarm.js +24 -0
  225. package/dist/tools/v2/smart_alarm.js.map +1 -0
  226. package/dist/tools/v2/smart_alarm_set.js +94 -0
  227. package/dist/tools/v2/smart_alarm_set.js.map +1 -0
  228. package/dist/tools/v2/sports_catalog.js +26 -0
  229. package/dist/tools/v2/sports_catalog.js.map +1 -0
  230. package/dist/tools/v2/strain.js +23 -0
  231. package/dist/tools/v2/strain.js.map +1 -0
  232. package/dist/tools/v2/stress.js +23 -0
  233. package/dist/tools/v2/stress.js.map +1 -0
  234. package/dist/tools/v2/symptom_log.js +72 -0
  235. package/dist/tools/v2/symptom_log.js.map +1 -0
  236. package/dist/tools/v2/today.js +30 -0
  237. package/dist/tools/v2/today.js.map +1 -0
  238. package/dist/tools/v2/trend.js +26 -0
  239. package/dist/tools/v2/trend.js.map +1 -0
  240. package/dist/tools/v2/workout.js +23 -0
  241. package/dist/tools/v2/workout.js.map +1 -0
  242. package/dist/tools/v2/workouts.js +32 -0
  243. package/dist/tools/v2/workouts.js.map +1 -0
  244. package/dist/whoop/build_lift_body.js +67 -0
  245. package/dist/whoop/build_lift_body.js.map +1 -0
  246. package/dist/whoop/client.js +84 -0
  247. package/dist/whoop/client.js.map +1 -0
  248. package/dist/whoop/cognito.js +110 -0
  249. package/dist/whoop/cognito.js.map +1 -0
  250. package/dist/whoop/constants.js +4 -0
  251. package/dist/whoop/constants.js.map +1 -0
  252. package/dist/whoop/device.js +103 -0
  253. package/dist/whoop/device.js.map +1 -0
  254. package/dist/whoop/errors.js +42 -0
  255. package/dist/whoop/errors.js.map +1 -0
  256. package/dist/whoop/init_timezone.js +62 -0
  257. package/dist/whoop/init_timezone.js.map +1 -0
  258. package/dist/whoop/installation.js +62 -0
  259. package/dist/whoop/installation.js.map +1 -0
  260. package/dist/whoop/json_out.js +9 -0
  261. package/dist/whoop/json_out.js.map +1 -0
  262. package/dist/whoop/oauth_provider.js +297 -0
  263. package/dist/whoop/oauth_provider.js.map +1 -0
  264. package/dist/whoop/session_state.js +34 -0
  265. package/dist/whoop/session_state.js.map +1 -0
  266. package/dist/whoop/token_manager.js +60 -0
  267. package/dist/whoop/token_manager.js.map +1 -0
  268. package/dist/whoop/token_store.js +47 -0
  269. package/dist/whoop/token_store.js.map +1 -0
  270. package/dist/whoop/types.js +82 -0
  271. package/dist/whoop/types.js.map +1 -0
  272. package/dist/whoop/write_safety.js +23 -0
  273. package/dist/whoop/write_safety.js.map +1 -0
  274. package/package.json +66 -0
  275. package/src/cli/index.ts +597 -0
  276. package/src/cli/setup.ts +1106 -0
  277. package/src/cli/ui.ts +505 -0
  278. package/src/cli/update.ts +442 -0
  279. package/src/data/behaviors.ts +2784 -0
  280. package/src/data/endpoints.ts +319 -0
  281. package/src/data/exercises.ts +4868 -0
  282. package/src/data/sports.ts +218 -0
  283. package/src/lib/concurrency.ts +28 -0
  284. package/src/lib/dates.ts +35 -0
  285. package/src/lib/format.ts +27 -0
  286. package/src/lib/stats.ts +35 -0
  287. package/src/lib/timezone.ts +269 -0
  288. package/src/lib/walk.ts +418 -0
  289. package/src/projections/behavior_impact.ts +98 -0
  290. package/src/projections/calendar.ts +46 -0
  291. package/src/projections/communities.ts +135 -0
  292. package/src/projections/cycle.ts +85 -0
  293. package/src/projections/hr_zones.ts +43 -0
  294. package/src/projections/journal.ts +55 -0
  295. package/src/projections/leaderboard.ts +49 -0
  296. package/src/projections/lift_exercise.ts +29 -0
  297. package/src/projections/lift_history.ts +140 -0
  298. package/src/projections/lift_library.ts +70 -0
  299. package/src/projections/lift_progression.ts +138 -0
  300. package/src/projections/lift_prs.ts +23 -0
  301. package/src/projections/live_hr.ts +21 -0
  302. package/src/projections/live_state.ts +28 -0
  303. package/src/projections/live_stress.ts +13 -0
  304. package/src/projections/performance_assessment.ts +19 -0
  305. package/src/projections/profile.ts +71 -0
  306. package/src/projections/recovery.ts +133 -0
  307. package/src/projections/sleep.ts +276 -0
  308. package/src/projections/sleep_need.ts +36 -0
  309. package/src/projections/smart_alarm.ts +70 -0
  310. package/src/projections/strain.ts +131 -0
  311. package/src/projections/stress.ts +95 -0
  312. package/src/projections/today.ts +166 -0
  313. package/src/projections/trend.ts +149 -0
  314. package/src/projections/workout.ts +168 -0
  315. package/src/projections/workouts.ts +36 -0
  316. package/src/schemas/calendar.ts +13 -0
  317. package/src/schemas/coach.ts +11 -0
  318. package/src/schemas/communities.ts +56 -0
  319. package/src/schemas/compare.ts +17 -0
  320. package/src/schemas/escape.ts +21 -0
  321. package/src/schemas/journal.ts +80 -0
  322. package/src/schemas/leaderboard.ts +26 -0
  323. package/src/schemas/live.ts +31 -0
  324. package/src/schemas/performance.ts +13 -0
  325. package/src/schemas/primitives.ts +35 -0
  326. package/src/schemas/profile.ts +40 -0
  327. package/src/schemas/recovery.ts +28 -0
  328. package/src/schemas/settings.ts +30 -0
  329. package/src/schemas/sleep.ts +40 -0
  330. package/src/schemas/sleep_need.ts +16 -0
  331. package/src/schemas/smart_alarm.ts +40 -0
  332. package/src/schemas/strain.ts +25 -0
  333. package/src/schemas/strength.ts +189 -0
  334. package/src/schemas/stress.ts +17 -0
  335. package/src/schemas/today.ts +39 -0
  336. package/src/schemas/trend.ts +53 -0
  337. package/src/schemas/womens_health.ts +26 -0
  338. package/src/schemas/workouts.ts +55 -0
  339. package/src/scripts/cognito_bootstrap.ts +249 -0
  340. package/src/server-http.ts +241 -0
  341. package/src/server.ts +85 -0
  342. package/src/tools/register.ts +120 -0
  343. package/src/tools/v2/activity_create.ts +74 -0
  344. package/src/tools/v2/activity_delete.ts +33 -0
  345. package/src/tools/v2/behavior_impact.ts +39 -0
  346. package/src/tools/v2/calendar.ts +33 -0
  347. package/src/tools/v2/coach_ask.ts +131 -0
  348. package/src/tools/v2/communities.ts +65 -0
  349. package/src/tools/v2/compare.ts +83 -0
  350. package/src/tools/v2/cycle.ts +28 -0
  351. package/src/tools/v2/cycle_log.ts +51 -0
  352. package/src/tools/v2/day.ts +37 -0
  353. package/src/tools/v2/endpoints.ts +32 -0
  354. package/src/tools/v2/hidden_metric.ts +33 -0
  355. package/src/tools/v2/hr_zones.ts +29 -0
  356. package/src/tools/v2/hr_zones_set.ts +57 -0
  357. package/src/tools/v2/journal.ts +31 -0
  358. package/src/tools/v2/journal_autopop.ts +26 -0
  359. package/src/tools/v2/journal_catalog.ts +48 -0
  360. package/src/tools/v2/journal_log.ts +84 -0
  361. package/src/tools/v2/leaderboard.ts +92 -0
  362. package/src/tools/v2/lift_catalog.ts +48 -0
  363. package/src/tools/v2/lift_custom_exercise.ts +117 -0
  364. package/src/tools/v2/lift_exercise.ts +35 -0
  365. package/src/tools/v2/lift_history.ts +52 -0
  366. package/src/tools/v2/lift_library.ts +28 -0
  367. package/src/tools/v2/lift_log.ts +102 -0
  368. package/src/tools/v2/lift_progression.ts +34 -0
  369. package/src/tools/v2/lift_prs.ts +26 -0
  370. package/src/tools/v2/lift_template_save.ts +89 -0
  371. package/src/tools/v2/live_hr.ts +26 -0
  372. package/src/tools/v2/live_state.ts +26 -0
  373. package/src/tools/v2/live_stress.ts +27 -0
  374. package/src/tools/v2/performance_assessment.ts +44 -0
  375. package/src/tools/v2/profile.ts +33 -0
  376. package/src/tools/v2/profile_update.ts +76 -0
  377. package/src/tools/v2/raw.ts +50 -0
  378. package/src/tools/v2/recovery.ts +36 -0
  379. package/src/tools/v2/sleep.ts +28 -0
  380. package/src/tools/v2/sleep_need.ts +26 -0
  381. package/src/tools/v2/smart_alarm.ts +29 -0
  382. package/src/tools/v2/smart_alarm_set.ts +103 -0
  383. package/src/tools/v2/sports_catalog.ts +32 -0
  384. package/src/tools/v2/strain.ts +28 -0
  385. package/src/tools/v2/stress.ts +28 -0
  386. package/src/tools/v2/symptom_log.ts +78 -0
  387. package/src/tools/v2/today.ts +35 -0
  388. package/src/tools/v2/trend.ts +31 -0
  389. package/src/tools/v2/workout.ts +28 -0
  390. package/src/tools/v2/workouts.ts +37 -0
  391. package/src/whoop/build_lift_body.ts +84 -0
  392. package/src/whoop/client.ts +118 -0
  393. package/src/whoop/cognito.ts +150 -0
  394. package/src/whoop/constants.ts +3 -0
  395. package/src/whoop/device.ts +106 -0
  396. package/src/whoop/errors.ts +41 -0
  397. package/src/whoop/init_timezone.ts +64 -0
  398. package/src/whoop/installation.ts +58 -0
  399. package/src/whoop/json_out.ts +9 -0
  400. package/src/whoop/oauth_provider.ts +377 -0
  401. package/src/whoop/session_state.ts +41 -0
  402. package/src/whoop/token_manager.ts +76 -0
  403. package/src/whoop/token_store.ts +45 -0
  404. package/src/whoop/types.ts +89 -0
  405. package/src/whoop/write_safety.ts +30 -0
package/src/server.ts ADDED
@@ -0,0 +1,85 @@
1
+ // Entry point. Boots an MCP server over either:
2
+ // - stdio (default, for local Claude Desktop / Claude Code)
3
+ // - HTTP/Streamable (for remote hosting; set MCP_TRANSPORT=http)
4
+ //
5
+ // Switch with MCP_TRANSPORT. See README → "Remote hosting" for the HTTP path.
6
+ import { config as loadEnv } from "dotenv";
7
+ import { fileURLToPath } from "node:url";
8
+ import { dirname, resolve } from "node:path";
9
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
+ import { WhoopClient } from "./whoop/client.js";
12
+ import { TokenManager } from "./whoop/token_manager.js";
13
+ import { EnvFileTokenStore, MemoryTokenStore, type TokenStore } from "./whoop/token_store.js";
14
+ import { registerTools } from "./tools/register.js";
15
+ import { startTimezoneAutoDetect } from "./whoop/init_timezone.js";
16
+ import { resolveInstallationId } from "./whoop/installation.js";
17
+ import { versionStaleWarning } from "./whoop/device.js";
18
+
19
+ const __dirname = dirname(fileURLToPath(import.meta.url));
20
+ const ENV_PATH = resolve(__dirname, "../.env");
21
+ loadEnv({ path: ENV_PATH, quiet: true });
22
+
23
+ function requireEnv(key: string): string {
24
+ const v = process.env[key];
25
+ if (!v) throw new Error(`Missing ${key} in environment. Run \`totem auth\` to set up auto-refresh.`);
26
+ return v;
27
+ }
28
+
29
+ function chooseStore(): TokenStore {
30
+ const mode = (process.env.WHOOP_TOKEN_STORE ?? "envfile").toLowerCase();
31
+ if (mode === "memory") {
32
+ console.error(
33
+ "[totem] WHOOP_TOKEN_STORE=memory: rotated tokens are NOT persisted. If Cognito rotates your refresh token, a restart will need a fresh `totem auth`.",
34
+ );
35
+ return new MemoryTokenStore();
36
+ }
37
+ return new EnvFileTokenStore(ENV_PATH);
38
+ }
39
+
40
+ async function main(): Promise<void> {
41
+ // Generate + persist a stable per-install identifier before any request goes
42
+ // out, so every data request carries the same `x-whoop-installation-identifier`
43
+ // the iOS app sends. Persisted to the env file like the tokens.
44
+ resolveInstallationId(ENV_PATH);
45
+
46
+ // Warn (once, at boot) if the bundled iOS app version has gone stale enough to
47
+ // become a fingerprintable cohort. No-op until ~6 months past the capture date.
48
+ const stale = versionStaleWarning();
49
+ if (stale) console.error(stale);
50
+
51
+ const tokenManager = new TokenManager({
52
+ email: requireEnv("WHOOP_EMAIL"),
53
+ accessToken: requireEnv("WHOOP_IOS_BEARER_TOKEN"),
54
+ refreshToken: requireEnv("WHOOP_COGNITO_REFRESH_TOKEN"),
55
+ store: chooseStore(),
56
+ });
57
+
58
+ const client = new WhoopClient({ getToken: () => tokenManager.getToken() });
59
+
60
+ // Tier 2 of the timezone resolution chain: auto-detect from Whoop's profile
61
+ // so responses come back in the user's local TZ without manual config.
62
+ // No-op if WHOOP_TIMEZONE is set (env var wins). Fires async — does not
63
+ // block server startup.
64
+ startTimezoneAutoDetect(client);
65
+
66
+ const transport = (process.env.MCP_TRANSPORT ?? "stdio").toLowerCase();
67
+
68
+ if (transport === "http") {
69
+ const { startHttpServer } = await import("./server-http.js");
70
+ await startHttpServer(client, {
71
+ authToken: requireEnv("MCP_AUTH_TOKEN"),
72
+ });
73
+ return;
74
+ }
75
+
76
+ // stdio (default — local Claude Desktop / Claude Code)
77
+ const server = new McpServer({ name: "totem", version: "1.4.4" });
78
+ registerTools(server, client);
79
+ await server.connect(new StdioServerTransport());
80
+ }
81
+
82
+ main().catch((err) => {
83
+ console.error("[totem] fatal:", err);
84
+ process.exit(1);
85
+ });
@@ -0,0 +1,120 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { WhoopClient } from "../whoop/client.js";
3
+
4
+ // Snapshots
5
+ import { registerToday } from "./v2/today.js";
6
+ import { registerDay } from "./v2/day.js";
7
+ import { registerProfile } from "./v2/profile.js";
8
+ import { registerCalendar } from "./v2/calendar.js";
9
+ // Deep dives
10
+ import { registerRecovery } from "./v2/recovery.js";
11
+ import { registerSleep } from "./v2/sleep.js";
12
+ import { registerStrain } from "./v2/strain.js";
13
+ // Trends + compare
14
+ import { registerTrend } from "./v2/trend.js";
15
+ import { registerCompare } from "./v2/compare.js";
16
+ // Stress + sleep_need
17
+ import { registerStress } from "./v2/stress.js";
18
+ import { registerSleepNeed } from "./v2/sleep_need.js";
19
+ // Live
20
+ import { registerLiveHr } from "./v2/live_hr.js";
21
+ import { registerLiveState } from "./v2/live_state.js";
22
+ import { registerLiveStress } from "./v2/live_stress.js";
23
+ // Activities
24
+ import { registerWorkouts } from "./v2/workouts.js";
25
+ import { registerWorkout } from "./v2/workout.js";
26
+ import { registerActivityCreate } from "./v2/activity_create.js";
27
+ import { registerActivityDelete } from "./v2/activity_delete.js";
28
+ import { registerSportsCatalog } from "./v2/sports_catalog.js";
29
+ // Strength reads
30
+ import { registerLiftPrs } from "./v2/lift_prs.js";
31
+ import { registerLiftExercise } from "./v2/lift_exercise.js";
32
+ import { registerLiftProgression } from "./v2/lift_progression.js";
33
+ import { registerLiftHistory } from "./v2/lift_history.js";
34
+ import { registerLiftLibrary } from "./v2/lift_library.js";
35
+ import { registerLiftCatalog } from "./v2/lift_catalog.js";
36
+ // Strength writes
37
+ import { registerLiftLog } from "./v2/lift_log.js";
38
+ import { registerLiftTemplateSave } from "./v2/lift_template_save.js";
39
+ import { registerLiftCustomExercise } from "./v2/lift_custom_exercise.js";
40
+ // Journal
41
+ import { registerJournal } from "./v2/journal.js";
42
+ import { registerJournalCatalog } from "./v2/journal_catalog.js";
43
+ import { registerBehaviorImpact } from "./v2/behavior_impact.js";
44
+ import { registerJournalLog } from "./v2/journal_log.js";
45
+ import { registerJournalAutopop } from "./v2/journal_autopop.js";
46
+ // Women's health
47
+ import { registerCycle } from "./v2/cycle.js";
48
+ import { registerCycleLog } from "./v2/cycle_log.js";
49
+ import { registerSymptomLog } from "./v2/symptom_log.js";
50
+ // Coach + performance
51
+ import { registerCoachAsk } from "./v2/coach_ask.js";
52
+ import { registerPerformanceAssessment } from "./v2/performance_assessment.js";
53
+ // Smart alarm
54
+ import { registerSmartAlarm } from "./v2/smart_alarm.js";
55
+ import { registerSmartAlarmSet } from "./v2/smart_alarm_set.js";
56
+ // Social
57
+ import { registerLeaderboard } from "./v2/leaderboard.js";
58
+ import { registerCommunities } from "./v2/communities.js";
59
+ // Settings
60
+ import { registerHrZones } from "./v2/hr_zones.js";
61
+ import { registerHrZonesSet } from "./v2/hr_zones_set.js";
62
+ import { registerProfileUpdate } from "./v2/profile_update.js";
63
+ import { registerHiddenMetric } from "./v2/hidden_metric.js";
64
+ // Escape
65
+ import { registerRaw } from "./v2/raw.js";
66
+ import { registerEndpoints } from "./v2/endpoints.js";
67
+
68
+ export function registerTools(server: McpServer, client: WhoopClient): void {
69
+ // Reads (32)
70
+ registerToday(server, client);
71
+ registerDay(server, client);
72
+ registerProfile(server, client);
73
+ registerCalendar(server, client);
74
+ registerRecovery(server, client);
75
+ registerSleep(server, client);
76
+ registerStrain(server, client);
77
+ registerTrend(server, client);
78
+ registerCompare(server, client);
79
+ registerStress(server, client);
80
+ registerSleepNeed(server, client);
81
+ registerLiveHr(server, client);
82
+ registerLiveState(server, client);
83
+ registerLiveStress(server, client);
84
+ registerWorkouts(server, client);
85
+ registerWorkout(server, client);
86
+ registerSportsCatalog(server, client);
87
+ registerLiftPrs(server, client);
88
+ registerLiftExercise(server, client);
89
+ registerLiftProgression(server, client);
90
+ registerLiftHistory(server, client);
91
+ registerLiftLibrary(server, client);
92
+ registerLiftCatalog(server, client);
93
+ registerJournal(server, client);
94
+ registerJournalCatalog(server, client);
95
+ registerBehaviorImpact(server, client);
96
+ registerCycle(server, client);
97
+ registerPerformanceAssessment(server, client);
98
+ registerSmartAlarm(server, client);
99
+ registerLeaderboard(server, client);
100
+ registerCommunities(server, client);
101
+ registerHrZones(server, client);
102
+ // Writes (14: 13 + coach_ask)
103
+ registerActivityCreate(server, client);
104
+ registerActivityDelete(server, client);
105
+ registerLiftLog(server, client);
106
+ registerLiftTemplateSave(server, client);
107
+ registerLiftCustomExercise(server, client);
108
+ registerJournalLog(server, client);
109
+ registerJournalAutopop(server, client);
110
+ registerCycleLog(server, client);
111
+ registerSymptomLog(server, client);
112
+ registerSmartAlarmSet(server, client);
113
+ registerHrZonesSet(server, client);
114
+ registerProfileUpdate(server, client);
115
+ registerHiddenMetric(server, client);
116
+ registerCoachAsk(server, client);
117
+ // Escape (2)
118
+ registerRaw(server, client);
119
+ registerEndpoints(server, client);
120
+ }
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { ActivityCreateOut } from "../../schemas/workouts.js";
5
+ import { preview } from "../../whoop/write_safety.js";
6
+ import { WhoopProjectionError } from "../../whoop/errors.js";
7
+ import { jsonOut } from "../../whoop/json_out.js";
8
+ import { SPORTS_BY_ID } from "../../data/sports.js";
9
+ import { gateError } from "../../whoop/session_state.js";
10
+
11
+ const PATH = "/core-details-bff/v0/create-activity";
12
+
13
+ export function registerActivityCreate(server: McpServer, client: WhoopClient): void {
14
+ server.tool(
15
+ "whoop_activity_create",
16
+ "WRITE: log a generic off-strap activity for a sport_id (call whoop_sports_catalog first to get one) over a start–end window of at least 1 minute. Preview unless confirm:true.",
17
+ {
18
+ sport_id: z.number().int().describe("Numeric sport_id from whoop_sports_catalog. Must call that tool first; this tool rejects calls otherwise."),
19
+ start: z.iso.datetime({ offset: true }),
20
+ end: z.iso.datetime({ offset: true }),
21
+ gps_enabled: z.boolean().default(false),
22
+ confirm: z.boolean().default(false),
23
+ },
24
+ async ({ sport_id, start, end, gps_enabled, confirm }) => {
25
+ const gate = gateError("sports", "whoop_sports_catalog");
26
+ if (gate) return { content: [{ type: "text", text: JSON.stringify(gate, null, 2) }], isError: true };
27
+ const sport = SPORTS_BY_ID.get(sport_id);
28
+ if (!sport) {
29
+ return {
30
+ content: [{ type: "text", text: jsonOut({ error: `Unknown sport_id ${sport_id}. Use whoop_sports_catalog to look up valid IDs.` }) }],
31
+ isError: true,
32
+ };
33
+ }
34
+ const body = { sport_id, start_time: start, end_time: end, gps_enabled };
35
+ if (!confirm) {
36
+ return {
37
+ content: [
38
+ {
39
+ type: "text",
40
+ text: jsonOut(
41
+ preview("POST", PATH, {
42
+ sport_id,
43
+ sport_name: sport.name,
44
+ start,
45
+ end,
46
+ duration_ms: new Date(end).getTime() - new Date(start).getTime(),
47
+ }),
48
+ ),
49
+ },
50
+ ],
51
+ };
52
+ }
53
+ const receipt = await client.post<{ id: string; cycle_id: number; sport_id?: number; start?: string; end?: string }>(
54
+ PATH,
55
+ body,
56
+ );
57
+ const projected = {
58
+ created: true as const,
59
+ activity_id: receipt.id,
60
+ cycle_id: receipt.cycle_id,
61
+ start: receipt.start ?? start,
62
+ end: receipt.end ?? end,
63
+ sport_id: receipt.sport_id ?? sport_id,
64
+ };
65
+ try {
66
+ const out = ActivityCreateOut.parse(projected);
67
+ return { content: [{ type: "text", text: jsonOut(out) }] };
68
+ } catch (e) {
69
+ if (e instanceof z.ZodError) throw new WhoopProjectionError("whoop_activity_create", e);
70
+ throw e;
71
+ }
72
+ },
73
+ );
74
+ }
@@ -0,0 +1,33 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { ActivityDeleteOut } from "../../schemas/workouts.js";
5
+ import { preview } from "../../whoop/write_safety.js";
6
+ import { jsonOut } from "../../whoop/json_out.js";
7
+
8
+ export function registerActivityDelete(server: McpServer, client: WhoopClient): void {
9
+ server.tool(
10
+ "whoop_activity_delete",
11
+ "WRITE / DESTRUCTIVE: delete a workout/activity. Preview unless confirm:true.",
12
+ {
13
+ activity_id: z.string(),
14
+ confirm: z.boolean().default(false),
15
+ },
16
+ async ({ activity_id, confirm }) => {
17
+ const path = "/core-details-bff/v1/cardio-details";
18
+ if (!confirm) {
19
+ return {
20
+ content: [
21
+ {
22
+ type: "text",
23
+ text: jsonOut(preview("DELETE", `${path}?activityId=${activity_id}`, { activity_id })),
24
+ },
25
+ ],
26
+ };
27
+ }
28
+ await client.delete(path, { activityId: activity_id });
29
+ const out = ActivityDeleteOut.parse({ deleted: true as const, activity_id });
30
+ return { content: [{ type: "text", text: jsonOut(out) }] };
31
+ },
32
+ );
33
+ }
@@ -0,0 +1,39 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { BehaviorImpactOut, BehaviorImpactListOut } from "../../schemas/journal.js";
5
+ import { projectBehaviorImpact, projectBehaviorImpactList } from "../../projections/behavior_impact.js";
6
+ import { WhoopProjectionError } from "../../whoop/errors.js";
7
+ import { jsonOut } from "../../whoop/json_out.js";
8
+
9
+ export function registerBehaviorImpact(server: McpServer, client: WhoopClient): void {
10
+ server.tool(
11
+ "whoop_behavior_impact",
12
+ "How much your tracked behaviors have historically moved recovery/HRV/sleep. Call with NO behavior_id to list every behavior with its impact_uuid + headline effect; then call again with behavior_id set to that impact_uuid (the long UUID, not a numeric id) for the full breakdown.",
13
+ {
14
+ behavior_id: z.string().optional().describe("An impact_uuid from the no-argument list. Omit to get that list."),
15
+ },
16
+ async ({ behavior_id }) => {
17
+ // No id → return the discovery list (the only place impact_uuids are exposed).
18
+ if (!behavior_id) {
19
+ const raw = await client.get("/behavior-impact-service/v1/impact");
20
+ try {
21
+ const out = BehaviorImpactListOut.parse(projectBehaviorImpactList(raw));
22
+ return { content: [{ type: "text", text: jsonOut(out) }] };
23
+ } catch (e) {
24
+ if (e instanceof z.ZodError) throw new WhoopProjectionError("whoop_behavior_impact", e);
25
+ throw e;
26
+ }
27
+ }
28
+ const raw = await client.get(`/behavior-impact-service/v2/impact/details/${behavior_id}`);
29
+ const projected = projectBehaviorImpact(raw, behavior_id);
30
+ try {
31
+ const out = BehaviorImpactOut.parse(projected);
32
+ return { content: [{ type: "text", text: jsonOut(out) }] };
33
+ } catch (e) {
34
+ if (e instanceof z.ZodError) throw new WhoopProjectionError("whoop_behavior_impact", e);
35
+ throw e;
36
+ }
37
+ },
38
+ );
39
+ }
@@ -0,0 +1,33 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { CalendarOut } from "../../schemas/calendar.js";
5
+ import { projectCalendar } from "../../projections/calendar.js";
6
+ import { WhoopProjectionError } from "../../whoop/errors.js";
7
+ import { jsonOut } from "../../whoop/json_out.js";
8
+ import { todayIso } from "../../lib/dates.js";
9
+
10
+ export function registerCalendar(server: McpServer, client: WhoopClient): void {
11
+ server.tool(
12
+ "whoop_calendar",
13
+ "Month-at-a-glance calendar grid for the month containing the given date: each day's recovery STATE — GREEN (high), YELLOW (medium), or RED (low). The grid only exposes the state, not numeric recovery/sleep/strain scores; for a specific day's numbers use whoop_day.",
14
+ {
15
+ date: z.iso.date().optional().describe("Any date in the target month. Defaults to today."),
16
+ },
17
+ async ({ date }) => {
18
+ const d = date ?? todayIso();
19
+ const [overview, recovery] = await Promise.all([
20
+ client.get("/home-service/v1/calendar/overview", { date: d }),
21
+ client.get("/home-service/v1/calendar/recovery", { date: d }).catch(() => null),
22
+ ]);
23
+ const projected = projectCalendar({ overview, recovery, date: d });
24
+ try {
25
+ const out = CalendarOut.parse(projected);
26
+ return { content: [{ type: "text", text: jsonOut(out) }] };
27
+ } catch (e) {
28
+ if (e instanceof z.ZodError) throw new WhoopProjectionError("whoop_calendar", e);
29
+ throw e;
30
+ }
31
+ },
32
+ );
33
+ }
@@ -0,0 +1,131 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { CoachAskOut } from "../../schemas/coach.js";
5
+ import { preview } from "../../whoop/write_safety.js";
6
+ import { jsonOut } from "../../whoop/json_out.js";
7
+ import { randomInt } from "node:crypto";
8
+
9
+ export function registerCoachAsk(server: McpServer, client: WhoopClient): void {
10
+ server.tool(
11
+ "whoop_coach_ask",
12
+ "WRITE (creates a coach conversation): ask Whoop Coach a question and poll up to 30s for the reply. context tells the coach which screen you're asking about — one of HOME, RECOVERY, STRAIN, SLEEP, STRESS, CARDIO_DETAILS, WAKE_UP_REPORT (default HOME). Preview unless confirm:true.",
13
+ {
14
+ message: z.string(),
15
+ context: z
16
+ .enum(["HOME", "RECOVERY", "STRAIN", "SLEEP", "STRESS", "CARDIO_DETAILS", "WAKE_UP_REPORT"])
17
+ .default("HOME"),
18
+ confirm: z.boolean().default(false).describe("Set true to actually send. Default returns a preview."),
19
+ },
20
+ async ({ message, context, confirm }) => {
21
+ if (!confirm) {
22
+ return {
23
+ content: [
24
+ {
25
+ type: "text",
26
+ text: jsonOut(
27
+ preview("POST", "/ai-conversation-bff/v1/conversation + /turn", {
28
+ message: message.slice(0, 100),
29
+ context,
30
+ }),
31
+ ),
32
+ },
33
+ ],
34
+ };
35
+ }
36
+ // Conversation creation response: { metadata: { id, ... }, turns: [...], tag }
37
+ const conv = await client.post<{
38
+ metadata?: { id?: string };
39
+ conversation_id?: string;
40
+ id?: string;
41
+ }>("/ai-conversation-bff/v1/conversation", {
42
+ context,
43
+ fingerprint: `CHAT_WITH_AGENT${context}_${new Date().toISOString().slice(0, 10)}`,
44
+ source_type: "CHAT_WITH_AGENT",
45
+ chat_entrypoint_experience: "STANDARD",
46
+ tracking_capabilities: {
47
+ is_dismiss_tracking_enabled: false,
48
+ is_seen_tracking_enabled: true,
49
+ },
50
+ });
51
+ const conversationId = conv.metadata?.id ?? conv.conversation_id ?? conv.id ?? "";
52
+
53
+ // Turn response: { id, turn_status, messages, turn_number, feedback }
54
+ const turn = await client.post<{ id?: string; turn_id?: string }>(
55
+ `/ai-conversation-bff/v1/conversation/${conversationId}/turn`,
56
+ {
57
+ role: "user",
58
+ content: message,
59
+ is_suggestion: false,
60
+ tracking_capabilities: {
61
+ is_dismiss_tracking_enabled: false,
62
+ is_seen_tracking_enabled: true,
63
+ },
64
+ },
65
+ );
66
+ const turnId = turn.id ?? turn.turn_id ?? "";
67
+
68
+ // Response text lives at messages[].items[].content.text (BFF rich-content
69
+ // shape); fall back to messages[].content for older shapes. Only the
70
+ // ASSISTANT's reply counts — the turn echoes the user's message first, so
71
+ // breaking on "any message present" returns before the coach has answered.
72
+ function extractText(msgs: unknown[]): string | null {
73
+ for (const m of msgs) {
74
+ if (typeof m !== "object" || m === null) continue;
75
+ const msg = m as Record<string, unknown>;
76
+ if (msg.role && msg.role !== "assistant") continue;
77
+ if (typeof msg.content === "string") return msg.content;
78
+ if (Array.isArray(msg.items)) {
79
+ for (const item of msg.items) {
80
+ if (typeof item !== "object" || item === null) continue;
81
+ const it = item as Record<string, unknown>;
82
+ const itemContent = it.content;
83
+ if (typeof itemContent === "object" && itemContent !== null) {
84
+ const t = (itemContent as Record<string, unknown>).text;
85
+ if (typeof t === "string") return t;
86
+ }
87
+ }
88
+ }
89
+ }
90
+ return null;
91
+ }
92
+
93
+ // The assistant reply streams token-by-token, so the FIRST non-empty read
94
+ // is almost always a partial chunk (e.g. just "56"). Breaking on first text
95
+ // returns a truncated answer. Instead keep the latest text each poll and
96
+ // stop only once the turn is terminal (server says it's done) or the text
97
+ // has stopped growing for two polls (the stream has settled). The 30s cap
98
+ // is the backstop.
99
+ const TERMINAL = ["COMPLETE", "COMPLETED", "DONE", "FINISHED"];
100
+ let polled = 0;
101
+ let status = "PENDING";
102
+ let responseText: string | null = null;
103
+ let stableFor = 0;
104
+ for (; polled < 30; polled++) {
105
+ // Jittered, not a fixed 1.000s metronome — a perfectly periodic poll is
106
+ // a scripted-client tell. ~0.85–1.4s keeps the 30s budget intact.
107
+ await new Promise((r) => setTimeout(r, randomInt(850, 1400)));
108
+ const r = await client.get<Record<string, unknown>>(
109
+ `/ai-conversation-bff/v1/conversation/${conversationId}/turn/${turnId}`,
110
+ );
111
+ status = typeof r.turn_status === "string" ? r.turn_status.toUpperCase() : status;
112
+ const latest = extractText(Array.isArray(r.messages) ? r.messages : []);
113
+ if (latest !== null) {
114
+ stableFor = latest === responseText ? stableFor + 1 : 0;
115
+ responseText = latest;
116
+ }
117
+ if (TERMINAL.includes(status)) break; // server marked the turn done
118
+ if (responseText !== null && stableFor >= 2) break; // stream settled
119
+ }
120
+ const out = CoachAskOut.parse({
121
+ conversation_id: conversationId,
122
+ turn_id: turnId,
123
+ response_text: responseText,
124
+ turn_status: status,
125
+ polled_iterations: polled,
126
+ timed_out: polled === 30,
127
+ });
128
+ return { content: [{ type: "text", text: jsonOut(out) }] };
129
+ },
130
+ );
131
+ }
@@ -0,0 +1,65 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { CommunitiesOut } from "../../schemas/communities.js";
5
+ import { projectCommunities } from "../../projections/communities.js";
6
+ import { WhoopProjectionError } from "../../whoop/errors.js";
7
+ import { jsonOut } from "../../whoop/json_out.js";
8
+
9
+ // Compute the date range for the given period, ending today. Used for the
10
+ // leaderboard segment of the memberships query.
11
+ function dateRange(period: "day" | "week" | "month"): { startDate: string; endDate: string } {
12
+ const today = new Date();
13
+ const end = today.toISOString().slice(0, 10);
14
+ const start = new Date(today);
15
+ if (period === "week") start.setUTCDate(today.getUTCDate() - 6);
16
+ else if (period === "month") start.setUTCDate(today.getUTCDate() - 29);
17
+ return { startDate: start.toISOString().slice(0, 10), endDate: end };
18
+ }
19
+
20
+ export function registerCommunities(server: McpServer, client: WhoopClient): void {
21
+ server.tool(
22
+ "whoop_communities",
23
+ "Lists the communities you belong to (teams, friend groups) with member count and optionally your rank, controlled by team_type (ALL, COMMUNITY, TEAM, BUSINESS), metric (strain, sleep, recovery), and period (day, week, month). Use this to discover community IDs, then whoop_leaderboard to drill into one.",
24
+ {
25
+ team_type: z.enum(["ALL", "COMMUNITY", "TEAM", "BUSINESS"]).default("ALL").describe("Filter by community type. ALL returns everything."),
26
+ metric: z.enum(["strain", "sleep", "recovery"]).default("strain").describe("Which leaderboard ranking to fetch your rank against."),
27
+ period: z.enum(["day", "week", "month"]).default("week").describe("Rolling window for the rank lookup."),
28
+ include_rank: z.boolean().default(true).describe("If false, skip fetching your rank in each community (faster, fewer fields)."),
29
+ limit: z.number().int().min(1).max(100).default(50),
30
+ offset: z.number().int().min(0).default(0),
31
+ },
32
+ async ({ team_type, metric, period, include_rank, limit, offset }) => {
33
+ const userId = process.env.WHOOP_USER_ID;
34
+ const { startDate, endDate } = dateRange(period);
35
+ const params: Record<string, string> = {
36
+ teamType: team_type,
37
+ includeOwnerDetails: "true",
38
+ includeUserRank: include_rank ? "true" : "false",
39
+ leaderboardType: metric,
40
+ period,
41
+ startDate,
42
+ endDate,
43
+ offset: String(offset),
44
+ limit: String(limit),
45
+ };
46
+ if (userId) params.userId = userId;
47
+
48
+ const raw = await client.get("/community-service/v1/communities/memberships", params);
49
+ const projected = projectCommunities({
50
+ raw,
51
+ team_type,
52
+ leaderboard_metric: metric,
53
+ period,
54
+ });
55
+
56
+ try {
57
+ const out = CommunitiesOut.parse(projected);
58
+ return { content: [{ type: "text", text: jsonOut(out) }] };
59
+ } catch (e) {
60
+ if (e instanceof z.ZodError) throw new WhoopProjectionError("whoop_communities", e);
61
+ throw e;
62
+ }
63
+ },
64
+ );
65
+ }
@@ -0,0 +1,83 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import type { WhoopClient } from "../../whoop/client.js";
4
+ import { CompareOut, type CompareMetricRow } from "../../schemas/compare.js";
5
+ import { projectTrend } from "../../projections/trend.js";
6
+ import { METRICS } from "../../schemas/trend.js";
7
+ import { WhoopProjectionError } from "../../whoop/errors.js";
8
+ import { jsonOut } from "../../whoop/json_out.js";
9
+ import { todayIso } from "../../lib/dates.js";
10
+ import { runPaced } from "../../lib/concurrency.js";
11
+
12
+ const COMPARE_METRICS = ["RECOVERY", "SLEEP_PERFORMANCE", "DAY_STRAIN", "HRV", "RHR"] as const;
13
+ type CompareMetric = typeof COMPARE_METRICS[number];
14
+
15
+ function dateBefore(end: string, days: number): string {
16
+ return new Date(new Date(end).getTime() - days * 86400000).toISOString().slice(0, 10);
17
+ }
18
+
19
+ export function registerCompare(server: McpServer, client: WhoopClient): void {
20
+ server.tool(
21
+ "whoop_compare",
22
+ "Compare two date windows side by side (e.g. 'this week vs last week') — each metric's average in window A vs window B plus the delta. window: week or month. metrics: any of RECOVERY, SLEEP_PERFORMANCE, DAY_STRAIN, HRV, RHR (defaults to all five).",
23
+ {
24
+ window: z.enum(["week", "month"]).default("week"),
25
+ end_a: z.iso.date().optional(),
26
+ end_b: z.iso.date().optional(),
27
+ metrics: z.array(z.enum(COMPARE_METRICS)).default([...COMPARE_METRICS]),
28
+ },
29
+ async ({ window, end_a, end_b, metrics }) => {
30
+ const a = end_a ?? todayIso();
31
+ const offsetDays = window === "week" ? 7 : 30;
32
+ const b = end_b ?? dateBefore(a, offsetDays);
33
+
34
+ // Up to 10 trend calls — paced (≤3 at a time, small jitter) rather than
35
+ // fired as one simultaneous burst, which no real app screen produces.
36
+ const flatResults = await runPaced(
37
+ metrics.flatMap((m: CompareMetric) => [
38
+ () => client.get(`/progression-service/v3/trends/${m}`, { endDate: a }).then((r) => ({ m, end: a, r })),
39
+ () => client.get(`/progression-service/v3/trends/${m}`, { endDate: b }).then((r) => ({ m, end: b, r })),
40
+ ]),
41
+ { concurrency: 3, jitterMaxMs: 150 },
42
+ );
43
+
44
+ const projected: CompareMetricRow[] = metrics.map((m: CompareMetric) => {
45
+ const aRes = flatResults.find((x) => x.m === m && x.end === a);
46
+ const bRes = flatResults.find((x) => x.m === m && x.end === b);
47
+ const aTrend = aRes ? projectTrend(aRes.r, m as typeof METRICS[number], a) : null;
48
+ const bTrend = bRes ? projectTrend(bRes.r, m as typeof METRICS[number], b) : null;
49
+ const aSeg = aTrend?.segments.find((s) => s.label === window) ?? null;
50
+ const bSeg = bTrend?.segments.find((s) => s.label === window) ?? null;
51
+ const aAvg = aSeg?.avg ?? null;
52
+ const bAvg = bSeg?.avg ?? null;
53
+ const deltaAbs = aAvg !== null && bAvg !== null ? aAvg - bAvg : null;
54
+ const deltaPct =
55
+ deltaAbs !== null && bAvg !== null && bAvg !== 0
56
+ ? Math.round((deltaAbs / bAvg) * 1000) / 10
57
+ : null;
58
+ return {
59
+ metric: m,
60
+ a_avg: aAvg,
61
+ b_avg: bAvg,
62
+ delta_abs: deltaAbs,
63
+ delta_pct: deltaPct,
64
+ unit: aSeg?.unit ?? bSeg?.unit ?? null,
65
+ };
66
+ });
67
+
68
+ const out = {
69
+ window,
70
+ a: { start_date: dateBefore(a, offsetDays), end_date: a },
71
+ b: { start_date: dateBefore(b, offsetDays), end_date: b },
72
+ metrics: projected,
73
+ };
74
+ try {
75
+ const parsed = CompareOut.parse(out);
76
+ return { content: [{ type: "text", text: jsonOut(parsed) }] };
77
+ } catch (e) {
78
+ if (e instanceof z.ZodError) throw new WhoopProjectionError("whoop_compare", e);
79
+ throw e;
80
+ }
81
+ },
82
+ );
83
+ }