bamy commited on
Commit
bc85648
·
1 Parent(s): d5e4861

feat(activities): add analysis, search, and interval-editing tools

Browse files

New tool modules:
- activity_analysis: curves, best efforts, segments, interval stats, map,
power-vs-hr, HR load and power spike models, time-at-HR, weather summary
- activity_search: search_activities, interval_search, get_activities_around,
get_activities_by_ids, get_activity_tags
- activity_intervals: update/delete/split activity intervals

Also extend activities with update/delete/create/bulk manual activities and
a "gap" histogram type, fix activity streams and power-curves to use the
spec-required .json extension and f1/f2/f3 filters, and allow list bodies in
make_intervals_request for bulk endpoints.

Ignore the local api/ OpenAPI reference spec.

.gitignore CHANGED
@@ -182,3 +182,6 @@ TODO
182
  .gitconfig
183
  .claude/
184
  .DS_Store
 
 
 
 
182
  .gitconfig
183
  .claude/
184
  .DS_Store
185
+
186
+ # Local OpenAPI reference spec (not versioned)
187
+ /api/
src/intervals_mcp_server/api/client.py CHANGED
@@ -154,7 +154,7 @@ async def make_intervals_request(
154
  api_key: str | None = None,
155
  params: dict[str, Any] | None = None,
156
  method: str = "GET",
157
- data: dict[str, Any] | None = None,
158
  ) -> dict[str, Any] | list[dict[str, Any]]:
159
  """
160
  Make a request to the Intervals.icu API with proper error handling.
 
154
  api_key: str | None = None,
155
  params: dict[str, Any] | None = None,
156
  method: str = "GET",
157
+ data: dict[str, Any] | list[Any] | None = None,
158
  ) -> dict[str, Any] | list[dict[str, Any]]:
159
  """
160
  Make a request to the Intervals.icu API with proper error handling.
src/intervals_mcp_server/tools/__init__.py CHANGED
@@ -10,10 +10,42 @@ from mcp.server.fastmcp import FastMCP # pylint: disable=import-error
10
  # Note: Tools register themselves via @mcp.tool() decorators when imported
11
  from intervals_mcp_server.tools.training_summary import get_training_summary # noqa: F401
12
  from intervals_mcp_server.tools.activities import ( # noqa: F401
 
 
 
 
13
  get_activities,
14
  get_activity_details,
 
15
  get_activity_intervals,
 
16
  get_activity_streams,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  )
18
  from intervals_mcp_server.tools.events import ( # noqa: F401
19
  add_or_update_event,
@@ -53,19 +85,52 @@ def register_tools(mcp_instance: FastMCP) -> None:
53
 
54
  __all__ = [
55
  "register_tools",
 
56
  "get_activities",
57
  "get_activity_details",
 
58
  "get_activity_intervals",
 
59
  "get_activity_streams",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  "get_events",
61
  "get_races",
62
  "get_event_by_id",
63
  "delete_event",
64
  "delete_events_by_date_range",
65
  "add_or_update_event",
 
66
  "get_wellness_data",
67
  "get_athlete_zones",
68
  "get_training_summary",
 
69
  "get_workout_folders",
70
  "list_workouts",
71
  "get_workout",
 
10
  # Note: Tools register themselves via @mcp.tool() decorators when imported
11
  from intervals_mcp_server.tools.training_summary import get_training_summary # noqa: F401
12
  from intervals_mcp_server.tools.activities import ( # noqa: F401
13
+ add_activity_message,
14
+ bulk_create_manual_activities,
15
+ create_manual_activity,
16
+ delete_activity,
17
  get_activities,
18
  get_activity_details,
19
+ get_activity_histogram,
20
  get_activity_intervals,
21
+ get_activity_messages,
22
  get_activity_streams,
23
+ update_activity,
24
+ )
25
+ from intervals_mcp_server.tools.activity_analysis import ( # noqa: F401
26
+ get_activity_best_efforts,
27
+ get_activity_curve,
28
+ get_activity_hr_load_model,
29
+ get_activity_interval_stats,
30
+ get_activity_map,
31
+ get_activity_power_spike_model,
32
+ get_activity_power_vs_hr,
33
+ get_activity_segments,
34
+ get_activity_time_at_hr,
35
+ get_activity_weather_summary,
36
+ )
37
+ from intervals_mcp_server.tools.activity_intervals import ( # noqa: F401
38
+ delete_activity_intervals,
39
+ split_activity_interval,
40
+ update_activity_interval,
41
+ update_activity_intervals,
42
+ )
43
+ from intervals_mcp_server.tools.activity_search import ( # noqa: F401
44
+ get_activities_around,
45
+ get_activities_by_ids,
46
+ get_activity_tags,
47
+ interval_search,
48
+ search_activities,
49
  )
50
  from intervals_mcp_server.tools.events import ( # noqa: F401
51
  add_or_update_event,
 
85
 
86
  __all__ = [
87
  "register_tools",
88
+ # Activities (read + CRUD)
89
  "get_activities",
90
  "get_activity_details",
91
+ "get_activity_histogram",
92
  "get_activity_intervals",
93
+ "get_activity_messages",
94
  "get_activity_streams",
95
+ "add_activity_message",
96
+ "update_activity",
97
+ "delete_activity",
98
+ "create_manual_activity",
99
+ "bulk_create_manual_activities",
100
+ # Activity search/discovery
101
+ "search_activities",
102
+ "interval_search",
103
+ "get_activities_around",
104
+ "get_activities_by_ids",
105
+ "get_activity_tags",
106
+ # Activity analysis
107
+ "get_activity_curve",
108
+ "get_activity_best_efforts",
109
+ "get_activity_segments",
110
+ "get_activity_time_at_hr",
111
+ "get_activity_weather_summary",
112
+ "get_activity_interval_stats",
113
+ "get_activity_map",
114
+ "get_activity_power_vs_hr",
115
+ "get_activity_hr_load_model",
116
+ "get_activity_power_spike_model",
117
+ # Activity interval editing
118
+ "update_activity_intervals",
119
+ "update_activity_interval",
120
+ "delete_activity_intervals",
121
+ "split_activity_interval",
122
+ # Events
123
  "get_events",
124
  "get_races",
125
  "get_event_by_id",
126
  "delete_event",
127
  "delete_events_by_date_range",
128
  "add_or_update_event",
129
+ # Other
130
  "get_wellness_data",
131
  "get_athlete_zones",
132
  "get_training_summary",
133
+ # Workout library
134
  "get_workout_folders",
135
  "list_workouts",
136
  "get_workout",
src/intervals_mcp_server/tools/activities.py CHANGED
@@ -273,12 +273,13 @@ async def get_activity_histogram(
273
 
274
  Args:
275
  activity_id: The Intervals.icu activity ID
276
- histogram_type: Type of histogram to retrieve. One of: "power", "hr", "pace"
 
277
  bucket_size: Width of each bucket (optional). For power: watts (defaults to 10),
278
- for hr: bpm (defaults to 5). Not used for pace.
279
  api_key: The Intervals.icu API key (optional, will use API_KEY from .env if not provided)
280
  """
281
- valid_types = {"power", "hr", "pace"}
282
  if histogram_type not in valid_types:
283
  return f"Invalid histogram_type '{histogram_type}'. Must be one of: {', '.join(sorted(valid_types))}."
284
 
@@ -286,13 +287,14 @@ async def get_activity_histogram(
286
  "power": "power-histogram",
287
  "hr": "hr-histogram",
288
  "pace": "pace-histogram",
 
289
  }
290
  default_bucket_sizes = {"power": 10, "hr": 5}
291
 
292
  url = f"/activity/{activity_id}/{endpoint_map[histogram_type]}"
293
 
294
  params: dict[str, Any] | None = None
295
- if histogram_type != "pace":
296
  bucket = bucket_size if bucket_size is not None else default_bucket_sizes[histogram_type]
297
  params = {"bucketSize": bucket}
298
 
@@ -334,9 +336,10 @@ async def get_activity_streams(
334
  # Default to common stream types if none specified
335
  params["types"] = "time,watts,heartrate,cadence,altitude,distance,velocity_smooth"
336
 
337
- # Call the Intervals.icu API
 
338
  result = await make_intervals_request(
339
- url=f"/activity/{activity_id}/streams",
340
  api_key=api_key,
341
  params=params,
342
  )
@@ -449,3 +452,135 @@ async def add_activity_message(
449
  if msg_id is not None:
450
  return f"Successfully added message (ID: {msg_id}) to activity {activity_id}."
451
  return f"Message appears to have been added to activity {activity_id}, but no ID was returned. Please verify manually."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
274
  Args:
275
  activity_id: The Intervals.icu activity ID
276
+ histogram_type: Type of histogram to retrieve. One of: "power", "hr", "pace", "gap"
277
+ ("gap" = gradient-adjusted pace).
278
  bucket_size: Width of each bucket (optional). For power: watts (defaults to 10),
279
+ for hr: bpm (defaults to 5). Ignored for pace and gap.
280
  api_key: The Intervals.icu API key (optional, will use API_KEY from .env if not provided)
281
  """
282
+ valid_types = {"power", "hr", "pace", "gap"}
283
  if histogram_type not in valid_types:
284
  return f"Invalid histogram_type '{histogram_type}'. Must be one of: {', '.join(sorted(valid_types))}."
285
 
 
287
  "power": "power-histogram",
288
  "hr": "hr-histogram",
289
  "pace": "pace-histogram",
290
+ "gap": "gap-histogram",
291
  }
292
  default_bucket_sizes = {"power": 10, "hr": 5}
293
 
294
  url = f"/activity/{activity_id}/{endpoint_map[histogram_type]}"
295
 
296
  params: dict[str, Any] | None = None
297
+ if histogram_type in default_bucket_sizes:
298
  bucket = bucket_size if bucket_size is not None else default_bucket_sizes[histogram_type]
299
  params = {"bucketSize": bucket}
300
 
 
336
  # Default to common stream types if none specified
337
  params["types"] = "time,watts,heartrate,cadence,altitude,distance,velocity_smooth"
338
 
339
+ # Call the Intervals.icu API. The spec defines the path as /streams{ext}
340
+ # where ext is required; use ".json" for JSON output.
341
  result = await make_intervals_request(
342
+ url=f"/activity/{activity_id}/streams.json",
343
  api_key=api_key,
344
  params=params,
345
  )
 
452
  if msg_id is not None:
453
  return f"Successfully added message (ID: {msg_id}) to activity {activity_id}."
454
  return f"Message appears to have been added to activity {activity_id}, but no ID was returned. Please verify manually."
455
+
456
+
457
+ @mcp.tool(annotations=ToolAnnotations(title="Update Activity", readOnlyHint=False, destructiveHint=False))
458
+ async def update_activity(
459
+ activity_id: str,
460
+ fields: dict[str, Any],
461
+ api_key: str = "",
462
+ ) -> str:
463
+ """Update metadata on an existing activity.
464
+
465
+ Args:
466
+ activity_id: The Intervals.icu activity ID
467
+ fields: Dictionary of activity fields to update. Common fields include:
468
+ name (str), description (str), type (str), trainer (bool), commute (bool),
469
+ tags (list[str]), gear_id (str), start_date_local (ISO datetime str).
470
+ Only the provided fields are updated.
471
+ api_key: The Intervals.icu API key (optional, will use API_KEY from .env if not provided)
472
+ """
473
+ if not fields:
474
+ return "Error: At least one field must be provided to update."
475
+
476
+ result = await make_intervals_request(
477
+ url=f"/activity/{activity_id}",
478
+ api_key=api_key,
479
+ method="PUT",
480
+ data=fields,
481
+ )
482
+
483
+ if isinstance(result, dict) and "error" in result:
484
+ return f"Error updating activity: {result.get('message', 'Unknown error')}"
485
+
486
+ return f"Successfully updated activity {activity_id}."
487
+
488
+
489
+ @mcp.tool(annotations=ToolAnnotations(title="Delete Activity", readOnlyHint=False, destructiveHint=True))
490
+ async def delete_activity(activity_id: str, api_key: str = "") -> str:
491
+ """Permanently delete an activity from Intervals.icu.
492
+
493
+ Args:
494
+ activity_id: The Intervals.icu activity ID
495
+ api_key: The Intervals.icu API key (optional, will use API_KEY from .env if not provided)
496
+ """
497
+ if not activity_id:
498
+ return "Error: No activity ID provided."
499
+
500
+ result = await make_intervals_request(
501
+ url=f"/activity/{activity_id}",
502
+ api_key=api_key,
503
+ method="DELETE",
504
+ )
505
+
506
+ if isinstance(result, dict) and "error" in result:
507
+ return f"Error deleting activity: {result.get('message', 'Unknown error')}"
508
+
509
+ return f"Successfully deleted activity {activity_id}."
510
+
511
+
512
+ @mcp.tool(annotations=ToolAnnotations(title="Create Manual Activity", readOnlyHint=False, destructiveHint=False))
513
+ async def create_manual_activity(
514
+ activity: dict[str, Any],
515
+ athlete_id: str = "",
516
+ api_key: str = "",
517
+ ) -> str:
518
+ """Create a manual (no file) activity for an athlete.
519
+
520
+ Args:
521
+ activity: Activity payload. Typical fields: name (str), type (str, e.g. "Ride"),
522
+ start_date_local (ISO datetime str), moving_time (int, seconds),
523
+ distance (float, meters), description (str), trainer (bool).
524
+ athlete_id: The Intervals.icu athlete ID (optional, will use ATHLETE_ID from .env if not provided)
525
+ api_key: The Intervals.icu API key (optional, will use API_KEY from .env if not provided)
526
+ """
527
+ athlete_id_to_use, error_msg = resolve_athlete_id(athlete_id, config.athlete_id)
528
+ if error_msg:
529
+ return error_msg
530
+
531
+ if not isinstance(activity, dict) or not activity:
532
+ return "Error: 'activity' must be a non-empty dictionary."
533
+
534
+ result = await make_intervals_request(
535
+ url=f"/athlete/{athlete_id_to_use}/activities/manual",
536
+ api_key=api_key,
537
+ method="POST",
538
+ data=activity,
539
+ )
540
+
541
+ if isinstance(result, dict) and "error" in result:
542
+ return f"Error creating manual activity: {result.get('message', 'Unknown error')}"
543
+
544
+ if isinstance(result, dict):
545
+ act_id = result.get("id")
546
+ return f"Successfully created manual activity (ID: {act_id})."
547
+ return "Manual activity created."
548
+
549
+
550
+ @mcp.tool(annotations=ToolAnnotations(title="Bulk Create Manual Activities", readOnlyHint=False, destructiveHint=False))
551
+ async def bulk_create_manual_activities(
552
+ activities: list[dict[str, Any]],
553
+ athlete_id: str = "",
554
+ api_key: str = "",
555
+ ) -> str:
556
+ """Create or upsert multiple manual activities in a single request.
557
+
558
+ Existing activities are matched on ``external_id`` and updated; new ones are created.
559
+
560
+ Args:
561
+ activities: List of activity payloads. Each item is a dict (see create_manual_activity
562
+ for typical fields). Including ``external_id`` enables upsert behaviour.
563
+ athlete_id: The Intervals.icu athlete ID (optional, will use ATHLETE_ID from .env if not provided)
564
+ api_key: The Intervals.icu API key (optional, will use API_KEY from .env if not provided)
565
+ """
566
+ athlete_id_to_use, error_msg = resolve_athlete_id(athlete_id, config.athlete_id)
567
+ if error_msg:
568
+ return error_msg
569
+
570
+ if not isinstance(activities, list) or not activities:
571
+ return "Error: 'activities' must be a non-empty list of activity dictionaries."
572
+
573
+ result = await make_intervals_request(
574
+ url=f"/athlete/{athlete_id_to_use}/activities/manual/bulk",
575
+ api_key=api_key,
576
+ method="POST",
577
+ data=activities,
578
+ )
579
+
580
+ if isinstance(result, dict) and "error" in result:
581
+ return f"Error bulk-creating activities: {result.get('message', 'Unknown error')}"
582
+
583
+ count = len(result) if isinstance(result, list) else None
584
+ if count is not None:
585
+ return f"Successfully created/updated {count} activities for athlete {athlete_id_to_use}."
586
+ return f"Bulk operation completed for athlete {athlete_id_to_use}."
src/intervals_mcp_server/tools/activity_analysis.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Activity analysis MCP tools for Intervals.icu.
3
+
4
+ These tools cover analytical endpoints for a single activity: curves
5
+ (HR/pace/power), segments, time-at-HR, weather, interval-stats, map,
6
+ power-vs-HR, training-load models, and best efforts.
7
+
8
+ Most tools return raw JSON because the response shapes vary widely and are
9
+ typically consumed by downstream callers for further analysis.
10
+ """
11
+
12
+ import json
13
+ from typing import Any
14
+
15
+ from mcp.types import ToolAnnotations
16
+
17
+ from intervals_mcp_server.api.client import make_intervals_request
18
+ from intervals_mcp_server.mcp_instance import mcp # noqa: F401
19
+
20
+
21
+ CURVE_TYPES = {"hr", "pace", "power", "power-multi"}
22
+
23
+
24
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Curve", readOnlyHint=True, destructiveHint=False))
25
+ async def get_activity_curve( # pylint: disable=too-many-arguments,too-many-positional-arguments
26
+ activity_id: str,
27
+ curve_type: str,
28
+ api_key: str = "",
29
+ gap: bool = False,
30
+ fatigue: str = "",
31
+ streams: str = "",
32
+ ) -> str:
33
+ """Get a single-activity best-effort curve (HR, pace, power, or multi-stream power).
34
+
35
+ Args:
36
+ activity_id: The Intervals.icu activity ID.
37
+ curve_type: One of "hr", "pace", "power", "power-multi". "power-multi" returns
38
+ curves for multiple streams via the /power-curves endpoint.
39
+ api_key: Optional API key.
40
+ gap: For pace curves only. If True, returns gradient-adjusted pace curve.
41
+ fatigue: For "power": one of "kj0", "kj1" to request a fatigued-curve variant.
42
+ For "power-multi": comma-separated list of "normal", "kj0", "kj1".
43
+ streams: For "power-multi" only. Comma-separated list of stream names (default "watts").
44
+ """
45
+ if curve_type not in CURVE_TYPES:
46
+ return f"Invalid curve_type '{curve_type}'. Must be one of: {', '.join(sorted(CURVE_TYPES))}."
47
+
48
+ endpoint_map = {
49
+ "hr": "hr-curve.json",
50
+ "pace": "pace-curve.json",
51
+ "power": "power-curve.json",
52
+ "power-multi": "power-curves.json",
53
+ }
54
+ url = f"/activity/{activity_id}/{endpoint_map[curve_type]}"
55
+
56
+ params: dict[str, Any] = {}
57
+ if curve_type == "pace" and gap:
58
+ params["gap"] = True
59
+ if curve_type == "power" and fatigue:
60
+ params["fatigue"] = fatigue
61
+ if curve_type == "power-multi":
62
+ if streams:
63
+ params["types"] = streams
64
+ if fatigue:
65
+ params["fatigue"] = fatigue
66
+
67
+ result = await make_intervals_request(url=url, api_key=api_key, params=params or None)
68
+
69
+ if isinstance(result, dict) and "error" in result:
70
+ return f"Error fetching {curve_type} curve: {result.get('message', 'Unknown error')}"
71
+
72
+ return json.dumps(result, default=str)
73
+
74
+
75
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Best Efforts", readOnlyHint=True, destructiveHint=False))
76
+ async def get_activity_best_efforts( # pylint: disable=too-many-arguments,too-many-positional-arguments
77
+ activity_id: str,
78
+ stream: str,
79
+ api_key: str = "",
80
+ duration: int = 0,
81
+ distance: float = 0.0,
82
+ count: int = 0,
83
+ min_value: float = 0.0,
84
+ exclude_intervals: bool = False,
85
+ start_index: int = 0,
86
+ end_index: int = 0,
87
+ ) -> str:
88
+ """Find the best efforts (peak segments) within an activity's stream.
89
+
90
+ Args:
91
+ activity_id: The Intervals.icu activity ID.
92
+ stream: Stream name to search (e.g. "watts", "heartrate", "velocity_smooth").
93
+ api_key: Optional API key.
94
+ duration: Duration of each effort in seconds (use 0 to omit).
95
+ distance: Distance of each effort in meters (use 0 to omit).
96
+ count: Maximum number of efforts to return (use 0 to omit).
97
+ min_value: Minimum average value; intervals expand if specified (use 0 to omit).
98
+ exclude_intervals: If True, ignore stream portions inside existing work intervals.
99
+ start_index: First stream index to consider (0 = start).
100
+ end_index: Last stream index to consider, exclusive (0 = end of stream).
101
+ """
102
+ if not stream:
103
+ return "Error: stream is required."
104
+
105
+ params: dict[str, Any] = {"stream": stream}
106
+ if duration:
107
+ params["duration"] = duration
108
+ if distance:
109
+ params["distance"] = distance
110
+ if count:
111
+ params["count"] = count
112
+ if min_value:
113
+ params["minValue"] = min_value
114
+ if exclude_intervals:
115
+ params["excludeIntervals"] = True
116
+ if start_index:
117
+ params["startIndex"] = start_index
118
+ if end_index:
119
+ params["endIndex"] = end_index
120
+
121
+ result = await make_intervals_request(
122
+ url=f"/activity/{activity_id}/best-efforts",
123
+ api_key=api_key,
124
+ params=params,
125
+ )
126
+
127
+ if isinstance(result, dict) and "error" in result:
128
+ return f"Error fetching best efforts: {result.get('message', 'Unknown error')}"
129
+
130
+ return json.dumps(result, default=str)
131
+
132
+
133
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Segments", readOnlyHint=True, destructiveHint=False))
134
+ async def get_activity_segments(activity_id: str, api_key: str = "") -> str:
135
+ """Get segments (e.g. Strava segments) detected within an activity."""
136
+ result = await make_intervals_request(
137
+ url=f"/activity/{activity_id}/segments",
138
+ api_key=api_key,
139
+ )
140
+ if isinstance(result, dict) and "error" in result:
141
+ return f"Error fetching segments: {result.get('message', 'Unknown error')}"
142
+ return json.dumps(result, default=str)
143
+
144
+
145
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Time at HR", readOnlyHint=True, destructiveHint=False))
146
+ async def get_activity_time_at_hr(activity_id: str, api_key: str = "") -> str:
147
+ """Get the per-bpm time-at-heart-rate distribution for an activity."""
148
+ result = await make_intervals_request(
149
+ url=f"/activity/{activity_id}/time-at-hr",
150
+ api_key=api_key,
151
+ )
152
+ if isinstance(result, dict) and "error" in result:
153
+ return f"Error fetching time-at-HR: {result.get('message', 'Unknown error')}"
154
+ return json.dumps(result, default=str)
155
+
156
+
157
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Weather Summary", readOnlyHint=True, destructiveHint=False))
158
+ async def get_activity_weather_summary(
159
+ activity_id: str,
160
+ api_key: str = "",
161
+ start_index: int = 0,
162
+ end_index: int = 0,
163
+ ) -> str:
164
+ """Get weather conditions summary for an activity (or a slice of it).
165
+
166
+ Args:
167
+ activity_id: The Intervals.icu activity ID.
168
+ api_key: Optional API key.
169
+ start_index: First stream index to include (0 = start).
170
+ end_index: Last stream index, exclusive (0 = end).
171
+ """
172
+ params: dict[str, Any] = {}
173
+ if start_index:
174
+ params["start_index"] = start_index
175
+ if end_index:
176
+ params["end_index"] = end_index
177
+
178
+ result = await make_intervals_request(
179
+ url=f"/activity/{activity_id}/weather-summary",
180
+ api_key=api_key,
181
+ params=params or None,
182
+ )
183
+ if isinstance(result, dict) and "error" in result:
184
+ return f"Error fetching weather summary: {result.get('message', 'Unknown error')}"
185
+ return json.dumps(result, default=str)
186
+
187
+
188
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Interval Stats", readOnlyHint=True, destructiveHint=False))
189
+ async def get_activity_interval_stats(
190
+ activity_id: str,
191
+ start_index: int,
192
+ end_index: int,
193
+ api_key: str = "",
194
+ ) -> str:
195
+ """Compute interval-style stats (avg power, HR, etc.) for a sub-section of an activity.
196
+
197
+ Args:
198
+ activity_id: The Intervals.icu activity ID.
199
+ start_index: First stream index of the section.
200
+ end_index: Last stream index of the section (exclusive).
201
+ api_key: Optional API key.
202
+ """
203
+ params = {"start_index": start_index, "end_index": end_index}
204
+ result = await make_intervals_request(
205
+ url=f"/activity/{activity_id}/interval-stats",
206
+ api_key=api_key,
207
+ params=params,
208
+ )
209
+ if isinstance(result, dict) and "error" in result:
210
+ return f"Error fetching interval stats: {result.get('message', 'Unknown error')}"
211
+ return json.dumps(result, default=str)
212
+
213
+
214
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Map", readOnlyHint=True, destructiveHint=False))
215
+ async def get_activity_map(
216
+ activity_id: str,
217
+ api_key: str = "",
218
+ bounds: str = "",
219
+ bounds_only: bool = False,
220
+ weather: bool = False,
221
+ ) -> str:
222
+ """Get activity map data (latlngs and/or bounds, optionally with weather points).
223
+
224
+ Args:
225
+ activity_id: The Intervals.icu activity ID.
226
+ api_key: Optional API key.
227
+ bounds: Comma-separated bounding box "left,top,right,bottom" to clip points to.
228
+ bounds_only: If True, return only the map bounds, no latlngs.
229
+ weather: If True, include weather points if available.
230
+ """
231
+ params: dict[str, Any] = {}
232
+ if bounds:
233
+ params["bounds"] = bounds
234
+ if bounds_only:
235
+ params["boundsOnly"] = True
236
+ if weather:
237
+ params["weather"] = True
238
+
239
+ result = await make_intervals_request(
240
+ url=f"/activity/{activity_id}/map",
241
+ api_key=api_key,
242
+ params=params or None,
243
+ )
244
+ if isinstance(result, dict) and "error" in result:
245
+ return f"Error fetching activity map: {result.get('message', 'Unknown error')}"
246
+ return json.dumps(result, default=str)
247
+
248
+
249
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Power vs HR", readOnlyHint=True, destructiveHint=False))
250
+ async def get_activity_power_vs_hr(activity_id: str, api_key: str = "") -> str:
251
+ """Get the power-vs-heart-rate scatter data for an activity."""
252
+ result = await make_intervals_request(
253
+ url=f"/activity/{activity_id}/power-vs-hr.json",
254
+ api_key=api_key,
255
+ )
256
+ if isinstance(result, dict) and "error" in result:
257
+ return f"Error fetching power-vs-HR: {result.get('message', 'Unknown error')}"
258
+ return json.dumps(result, default=str)
259
+
260
+
261
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity HR Load Model", readOnlyHint=True, destructiveHint=False))
262
+ async def get_activity_hr_load_model(activity_id: str, api_key: str = "") -> str:
263
+ """Get the heart-rate-based training-load model for an activity."""
264
+ result = await make_intervals_request(
265
+ url=f"/activity/{activity_id}/hr-load-model",
266
+ api_key=api_key,
267
+ )
268
+ if isinstance(result, dict) and "error" in result:
269
+ return f"Error fetching HR load model: {result.get('message', 'Unknown error')}"
270
+ return json.dumps(result, default=str)
271
+
272
+
273
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Power Spike Model", readOnlyHint=True, destructiveHint=False))
274
+ async def get_activity_power_spike_model(activity_id: str, api_key: str = "") -> str:
275
+ """Get the power-spike-detection model for an activity."""
276
+ result = await make_intervals_request(
277
+ url=f"/activity/{activity_id}/power-spike-model",
278
+ api_key=api_key,
279
+ )
280
+ if isinstance(result, dict) and "error" in result:
281
+ return f"Error fetching power spike model: {result.get('message', 'Unknown error')}"
282
+ return json.dumps(result, default=str)
src/intervals_mcp_server/tools/activity_intervals.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Activity interval editing MCP tools for Intervals.icu.
3
+
4
+ These tools mutate the icu_intervals on an existing activity: bulk update,
5
+ single interval upsert, delete, and split.
6
+ """
7
+
8
+ from typing import Any
9
+
10
+ from mcp.types import ToolAnnotations
11
+
12
+ from intervals_mcp_server.api.client import make_intervals_request
13
+ from intervals_mcp_server.mcp_instance import mcp # noqa: F401
14
+
15
+
16
+ @mcp.tool(annotations=ToolAnnotations(title="Update Activity Intervals", readOnlyHint=False, destructiveHint=True))
17
+ async def update_activity_intervals(
18
+ activity_id: str,
19
+ intervals: list[dict[str, Any]],
20
+ api_key: str = "",
21
+ replace_all: bool = False,
22
+ ) -> str:
23
+ """Update intervals on an activity in bulk.
24
+
25
+ Args:
26
+ activity_id: The Intervals.icu activity ID.
27
+ intervals: List of interval objects. See the Interval schema; common fields include
28
+ start_index, type ("WORK"/"REST"), label, moving_time, distance.
29
+ api_key: Optional API key.
30
+ replace_all: If True, replaces existing intervals; otherwise merges.
31
+ """
32
+ if not isinstance(intervals, list) or not intervals:
33
+ return "Error: 'intervals' must be a non-empty list."
34
+
35
+ params = {"all": True} if replace_all else None
36
+ result = await make_intervals_request(
37
+ url=f"/activity/{activity_id}/intervals",
38
+ api_key=api_key,
39
+ method="PUT",
40
+ params=params,
41
+ data=intervals,
42
+ )
43
+
44
+ if isinstance(result, dict) and "error" in result:
45
+ return f"Error updating intervals: {result.get('message', 'Unknown error')}"
46
+
47
+ return f"Successfully updated {len(intervals)} interval(s) on activity {activity_id}."
48
+
49
+
50
+ @mcp.tool(annotations=ToolAnnotations(title="Update Activity Interval", readOnlyHint=False, destructiveHint=False))
51
+ async def update_activity_interval(
52
+ activity_id: str,
53
+ interval_id: int,
54
+ interval: dict[str, Any],
55
+ api_key: str = "",
56
+ ) -> str:
57
+ """Update or create a single interval on an activity.
58
+
59
+ Args:
60
+ activity_id: The Intervals.icu activity ID.
61
+ interval_id: Numeric interval ID. Use a new ID to create.
62
+ interval: Interval payload (Interval schema).
63
+ api_key: Optional API key.
64
+ """
65
+ if not isinstance(interval, dict) or not interval:
66
+ return "Error: 'interval' must be a non-empty dictionary."
67
+
68
+ result = await make_intervals_request(
69
+ url=f"/activity/{activity_id}/intervals/{interval_id}",
70
+ api_key=api_key,
71
+ method="PUT",
72
+ data=interval,
73
+ )
74
+
75
+ if isinstance(result, dict) and "error" in result:
76
+ return f"Error updating interval: {result.get('message', 'Unknown error')}"
77
+
78
+ return f"Successfully upserted interval {interval_id} on activity {activity_id}."
79
+
80
+
81
+ @mcp.tool(annotations=ToolAnnotations(title="Delete Activity Intervals", readOnlyHint=False, destructiveHint=True))
82
+ async def delete_activity_intervals(
83
+ activity_id: str,
84
+ interval_ids: list[int],
85
+ api_key: str = "",
86
+ ) -> str:
87
+ """Delete one or more intervals from an activity.
88
+
89
+ Args:
90
+ activity_id: The Intervals.icu activity ID.
91
+ interval_ids: List of interval IDs to remove.
92
+ api_key: Optional API key.
93
+ """
94
+ if not isinstance(interval_ids, list) or not interval_ids:
95
+ return "Error: 'interval_ids' must be a non-empty list."
96
+
97
+ result = await make_intervals_request(
98
+ url=f"/activity/{activity_id}/delete-intervals",
99
+ api_key=api_key,
100
+ method="PUT",
101
+ data=interval_ids,
102
+ )
103
+
104
+ if isinstance(result, dict) and "error" in result:
105
+ return f"Error deleting intervals: {result.get('message', 'Unknown error')}"
106
+
107
+ return f"Successfully deleted {len(interval_ids)} interval(s) from activity {activity_id}."
108
+
109
+
110
+ @mcp.tool(annotations=ToolAnnotations(title="Split Activity Interval", readOnlyHint=False, destructiveHint=False))
111
+ async def split_activity_interval(
112
+ activity_id: str,
113
+ split_at: int,
114
+ api_key: str = "",
115
+ ) -> str:
116
+ """Split an interval into two at the given stream index.
117
+
118
+ Args:
119
+ activity_id: The Intervals.icu activity ID.
120
+ split_at: Stream index at which to split the interval.
121
+ api_key: Optional API key.
122
+ """
123
+ result = await make_intervals_request(
124
+ url=f"/activity/{activity_id}/split-interval",
125
+ api_key=api_key,
126
+ method="PUT",
127
+ params={"splitAt": split_at},
128
+ )
129
+
130
+ if isinstance(result, dict) and "error" in result:
131
+ return f"Error splitting interval: {result.get('message', 'Unknown error')}"
132
+
133
+ return f"Successfully split interval at index {split_at} on activity {activity_id}."
src/intervals_mcp_server/tools/activity_search.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Activity search and discovery tools for Intervals.icu.
3
+
4
+ These tools cover lookup operations beyond simple date-range listing:
5
+ text/tag search, interval search, neighbour activities, multi-fetch by ID,
6
+ and tag enumeration.
7
+ """
8
+
9
+ import json
10
+ from typing import Any
11
+
12
+ from mcp.types import ToolAnnotations
13
+
14
+ from intervals_mcp_server.api.client import make_intervals_request
15
+ from intervals_mcp_server.config import get_config
16
+ from intervals_mcp_server.utils.formatting import format_activity_compact
17
+ from intervals_mcp_server.utils.validation import resolve_athlete_id
18
+
19
+ from intervals_mcp_server.mcp_instance import mcp # noqa: F401
20
+
21
+ config = get_config()
22
+
23
+
24
+ def _format_activity_list(activities: list[dict[str, Any]], header: str) -> str:
25
+ if not activities:
26
+ return f"{header}\n(no results)"
27
+ out = f"{header}\n\n"
28
+ for activity in activities:
29
+ if isinstance(activity, dict):
30
+ out += format_activity_compact(activity) + "\n"
31
+ return out
32
+
33
+
34
+ @mcp.tool(annotations=ToolAnnotations(title="Search Activities", readOnlyHint=True, destructiveHint=False))
35
+ async def search_activities(
36
+ query: str,
37
+ athlete_id: str = "",
38
+ api_key: str = "",
39
+ limit: int = 25,
40
+ full: bool = False,
41
+ ) -> str:
42
+ """Search activities by name (case-insensitive) or by exact tag (prefix with ``#``).
43
+
44
+ Args:
45
+ query: Search query. Plain text searches activity names; prefix with ``#`` to match a tag exactly.
46
+ athlete_id: The Intervals.icu athlete ID (optional, defaults to env)
47
+ api_key: The Intervals.icu API key (optional, defaults to env)
48
+ limit: Maximum number of results (default 25)
49
+ full: If True, fetch full activity objects via /search-full; otherwise summary info.
50
+ """
51
+ athlete_id_to_use, error_msg = resolve_athlete_id(athlete_id, config.athlete_id)
52
+ if error_msg:
53
+ return error_msg
54
+ if not query:
55
+ return "Error: query is required."
56
+
57
+ endpoint = "search-full" if full else "search"
58
+ params: dict[str, Any] = {"q": query, "limit": limit}
59
+
60
+ result = await make_intervals_request(
61
+ url=f"/athlete/{athlete_id_to_use}/activities/{endpoint}",
62
+ api_key=api_key,
63
+ params=params,
64
+ )
65
+
66
+ if isinstance(result, dict) and "error" in result:
67
+ return f"Error searching activities: {result.get('message', 'Unknown error')}"
68
+
69
+ activities = result if isinstance(result, list) else []
70
+ return _format_activity_list(activities, f"Activity search results for '{query}':")
71
+
72
+
73
+ @mcp.tool(annotations=ToolAnnotations(title="Interval Search", readOnlyHint=True, destructiveHint=False))
74
+ async def interval_search( # pylint: disable=too-many-arguments,too-many-positional-arguments
75
+ min_secs: int,
76
+ max_secs: int,
77
+ min_intensity: int,
78
+ max_intensity: int,
79
+ athlete_id: str = "",
80
+ api_key: str = "",
81
+ interval_type: str = "",
82
+ min_reps: int = 0,
83
+ max_reps: int = 0,
84
+ limit: int = 25,
85
+ ) -> str:
86
+ """Find activities containing intervals matching a duration and intensity window.
87
+
88
+ Args:
89
+ min_secs: Minimum interval duration in seconds.
90
+ max_secs: Maximum interval duration in seconds.
91
+ min_intensity: Minimum intensity percentage (e.g. 90 for 90% FTP).
92
+ max_intensity: Maximum intensity percentage.
93
+ athlete_id: The Intervals.icu athlete ID (optional, defaults to env)
94
+ api_key: The Intervals.icu API key (optional, defaults to env)
95
+ interval_type: Optional interval type filter (e.g. "WORK", "REST").
96
+ min_reps: Minimum matching intervals required per activity (0 = no minimum).
97
+ max_reps: Maximum matching intervals per activity (0 = no maximum).
98
+ limit: Maximum number of activities to return.
99
+ """
100
+ athlete_id_to_use, error_msg = resolve_athlete_id(athlete_id, config.athlete_id)
101
+ if error_msg:
102
+ return error_msg
103
+
104
+ params: dict[str, Any] = {
105
+ "minSecs": min_secs,
106
+ "maxSecs": max_secs,
107
+ "minIntensity": min_intensity,
108
+ "maxIntensity": max_intensity,
109
+ "limit": limit,
110
+ }
111
+ if interval_type:
112
+ params["type"] = interval_type
113
+ if min_reps:
114
+ params["minReps"] = min_reps
115
+ if max_reps:
116
+ params["maxReps"] = max_reps
117
+
118
+ result = await make_intervals_request(
119
+ url=f"/athlete/{athlete_id_to_use}/activities/interval-search",
120
+ api_key=api_key,
121
+ params=params,
122
+ )
123
+
124
+ if isinstance(result, dict) and "error" in result:
125
+ return f"Error in interval search: {result.get('message', 'Unknown error')}"
126
+
127
+ activities = result if isinstance(result, list) else []
128
+ header = (
129
+ f"Activities with intervals matching {min_secs}-{max_secs}s @ "
130
+ f"{min_intensity}-{max_intensity}%:"
131
+ )
132
+ return _format_activity_list(activities, header)
133
+
134
+
135
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activities Around", readOnlyHint=True, destructiveHint=False))
136
+ async def get_activities_around(
137
+ activity_id: str,
138
+ athlete_id: str = "",
139
+ api_key: str = "",
140
+ route_id: int = 0,
141
+ limit: int = 30,
142
+ ) -> str:
143
+ """List activities before and after a given activity, closest first.
144
+
145
+ Args:
146
+ activity_id: The reference activity ID (not returned in the result set).
147
+ athlete_id: The Intervals.icu athlete ID (optional, defaults to env)
148
+ api_key: The Intervals.icu API key (optional, defaults to env)
149
+ route_id: Only return activities sharing this route (0 = no filter).
150
+ limit: Maximum number of activities to return (default 30).
151
+ """
152
+ athlete_id_to_use, error_msg = resolve_athlete_id(athlete_id, config.athlete_id)
153
+ if error_msg:
154
+ return error_msg
155
+ if not activity_id:
156
+ return "Error: activity_id is required."
157
+
158
+ params: dict[str, Any] = {"activity_id": activity_id, "limit": limit}
159
+ if route_id:
160
+ params["route_id"] = route_id
161
+
162
+ result = await make_intervals_request(
163
+ url=f"/athlete/{athlete_id_to_use}/activities-around",
164
+ api_key=api_key,
165
+ params=params,
166
+ )
167
+
168
+ if isinstance(result, dict) and "error" in result:
169
+ return f"Error fetching neighbour activities: {result.get('message', 'Unknown error')}"
170
+
171
+ activities = result if isinstance(result, list) else []
172
+ return _format_activity_list(activities, f"Activities around {activity_id}:")
173
+
174
+
175
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activities by IDs", readOnlyHint=True, destructiveHint=False))
176
+ async def get_activities_by_ids(
177
+ activity_ids: list[str],
178
+ athlete_id: str = "",
179
+ api_key: str = "",
180
+ include_intervals: bool = False,
181
+ ) -> str:
182
+ """Fetch multiple activities by ID in a single call. Missing IDs are ignored.
183
+
184
+ Args:
185
+ activity_ids: List of Intervals.icu activity IDs.
186
+ athlete_id: The Intervals.icu athlete ID (optional, defaults to env)
187
+ api_key: The Intervals.icu API key (optional, defaults to env)
188
+ include_intervals: If True, include icu_intervals/icu_groups in each activity.
189
+ """
190
+ athlete_id_to_use, error_msg = resolve_athlete_id(athlete_id, config.athlete_id)
191
+ if error_msg:
192
+ return error_msg
193
+ if not activity_ids:
194
+ return "Error: activity_ids must be a non-empty list."
195
+
196
+ ids_path = ",".join(activity_ids)
197
+ params: dict[str, Any] = {}
198
+ if include_intervals:
199
+ params["intervals"] = True
200
+
201
+ result = await make_intervals_request(
202
+ url=f"/athlete/{athlete_id_to_use}/activities/{ids_path}",
203
+ api_key=api_key,
204
+ params=params or None,
205
+ )
206
+
207
+ if isinstance(result, dict) and "error" in result:
208
+ return f"Error fetching activities: {result.get('message', 'Unknown error')}"
209
+
210
+ # Multi-fetch responses are richer than simple summaries; return JSON so callers
211
+ # can inspect any field they need.
212
+ return json.dumps(result, indent=2, default=str)
213
+
214
+
215
+ @mcp.tool(annotations=ToolAnnotations(title="Get Activity Tags", readOnlyHint=True, destructiveHint=False))
216
+ async def get_activity_tags(
217
+ athlete_id: str = "",
218
+ api_key: str = "",
219
+ ) -> str:
220
+ """List all tags that have been applied to the athlete's activities."""
221
+ athlete_id_to_use, error_msg = resolve_athlete_id(athlete_id, config.athlete_id)
222
+ if error_msg:
223
+ return error_msg
224
+
225
+ result = await make_intervals_request(
226
+ url=f"/athlete/{athlete_id_to_use}/activity-tags",
227
+ api_key=api_key,
228
+ )
229
+
230
+ if isinstance(result, dict) and "error" in result:
231
+ return f"Error fetching activity tags: {result.get('message', 'Unknown error')}"
232
+
233
+ tags = result if isinstance(result, list) else []
234
+ if not tags:
235
+ return f"No activity tags found for athlete {athlete_id_to_use}."
236
+ return "Activity tags:\n" + "\n".join(f"- {t}" for t in tags)
src/intervals_mcp_server/tools/power_curves.py CHANGED
@@ -165,10 +165,15 @@ async def get_athlete_power_curves(
165
  if not curves:
166
  return "Error: At least one curve must be selected (this_season, last_season, or a date range)."
167
 
 
 
168
  params: dict[str, Any] = {
169
  "curves": curves,
170
  "type": activity_type,
171
  "includeRanks": False,
 
 
 
172
  }
173
  if indoor_outdoor:
174
  params["filters"] = json.dumps(
@@ -176,7 +181,7 @@ async def get_athlete_power_curves(
176
  )
177
 
178
  result = await make_intervals_request(
179
- url=f"/athlete/{athlete_id_to_use}/power-curves",
180
  params=params,
181
  )
182
 
 
165
  if not curves:
166
  return "Error: At least one curve must be selected (this_season, last_season, or a date range)."
167
 
168
+ # f1, f2, f3 are marked required in the spec (comparison-curve filters);
169
+ # send empty JSON arrays so the request is spec-compliant.
170
  params: dict[str, Any] = {
171
  "curves": curves,
172
  "type": activity_type,
173
  "includeRanks": False,
174
+ "f1": json.dumps([]),
175
+ "f2": json.dumps([]),
176
+ "f3": json.dumps([]),
177
  }
178
  if indoor_outdoor:
179
  params["filters"] = json.dumps(
 
181
  )
182
 
183
  result = await make_intervals_request(
184
+ url=f"/athlete/{athlete_id_to_use}/power-curves.json",
185
  params=params,
186
  )
187
 
tests/test_activity_tools.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lightweight sanity tests for the activity analysis, search, and interval tools.
3
+
4
+ Verifies URL routing, HTTP method, and body / query-parameter shape per the
5
+ OpenAPI spec. Network calls are mocked via monkeypatching
6
+ ``make_intervals_request`` on each tool module.
7
+ """
8
+
9
+ import asyncio
10
+ import json
11
+ import os
12
+ import pathlib
13
+ import sys
14
+ from typing import Any
15
+
16
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "src"))
17
+ os.environ.setdefault("API_KEY", "test")
18
+ os.environ.setdefault("ATHLETE_ID", "i1")
19
+
20
+ from intervals_mcp_server.tools.activities import ( # noqa: E402
21
+ bulk_create_manual_activities,
22
+ create_manual_activity,
23
+ delete_activity,
24
+ update_activity,
25
+ )
26
+ from intervals_mcp_server.tools.activity_analysis import ( # noqa: E402
27
+ get_activity_best_efforts,
28
+ get_activity_curve,
29
+ get_activity_interval_stats,
30
+ get_activity_map,
31
+ )
32
+ from intervals_mcp_server.tools.activity_intervals import ( # noqa: E402
33
+ delete_activity_intervals,
34
+ split_activity_interval,
35
+ update_activity_interval,
36
+ update_activity_intervals,
37
+ )
38
+ from intervals_mcp_server.tools.activity_search import ( # noqa: E402
39
+ get_activities_around,
40
+ get_activity_tags,
41
+ interval_search,
42
+ search_activities,
43
+ )
44
+
45
+
46
+ class FakeRequest:
47
+ """Records every call and returns a configurable response."""
48
+
49
+ def __init__(self, response: Any = None):
50
+ self.calls: list[dict[str, Any]] = []
51
+ self.response: Any = response if response is not None else {"id": 1}
52
+
53
+ async def __call__(self, *args: Any, **kwargs: Any) -> Any:
54
+ self.calls.append(kwargs)
55
+ return self.response
56
+
57
+ @property
58
+ def last(self) -> dict[str, Any]:
59
+ return self.calls[-1]
60
+
61
+
62
+ def _patch(monkeypatch, module_path: str, fake: FakeRequest) -> None:
63
+ monkeypatch.setattr(f"intervals_mcp_server.tools.{module_path}.make_intervals_request", fake)
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Activities — CRUD
68
+ # ---------------------------------------------------------------------------
69
+
70
+
71
+ def test_update_activity_puts_to_activity(monkeypatch):
72
+ fake = FakeRequest()
73
+ _patch(monkeypatch, "activities", fake)
74
+ result = asyncio.run(update_activity("a1", {"name": "Morning Ride"}))
75
+ assert fake.last["url"] == "/activity/a1"
76
+ assert fake.last["method"] == "PUT"
77
+ assert fake.last["data"] == {"name": "Morning Ride"}
78
+ assert "Successfully updated" in result
79
+
80
+
81
+ def test_update_activity_requires_fields():
82
+ result = asyncio.run(update_activity("a1", {}))
83
+ assert "Error" in result
84
+
85
+
86
+ def test_delete_activity(monkeypatch):
87
+ fake = FakeRequest(response={})
88
+ _patch(monkeypatch, "activities", fake)
89
+ result = asyncio.run(delete_activity("a1"))
90
+ assert fake.last["url"] == "/activity/a1"
91
+ assert fake.last["method"] == "DELETE"
92
+ assert "Successfully deleted" in result
93
+
94
+
95
+ def test_create_manual_activity(monkeypatch):
96
+ fake = FakeRequest(response={"id": "a42"})
97
+ _patch(monkeypatch, "activities", fake)
98
+ payload = {"name": "Run", "type": "Run", "moving_time": 1800}
99
+ result = asyncio.run(create_manual_activity(payload, athlete_id="i1"))
100
+ assert fake.last["url"] == "/athlete/i1/activities/manual"
101
+ assert fake.last["method"] == "POST"
102
+ assert fake.last["data"] == payload
103
+ assert "a42" in result
104
+
105
+
106
+ def test_bulk_create_manual_activities(monkeypatch):
107
+ fake = FakeRequest(response=[{"id": "a1"}, {"id": "a2"}])
108
+ _patch(monkeypatch, "activities", fake)
109
+ items = [{"name": "A", "external_id": "x1"}, {"name": "B", "external_id": "x2"}]
110
+ result = asyncio.run(bulk_create_manual_activities(items, athlete_id="i1"))
111
+ assert fake.last["url"] == "/athlete/i1/activities/manual/bulk"
112
+ assert fake.last["method"] == "POST"
113
+ assert fake.last["data"] == items
114
+ assert "2 activities" in result
115
+
116
+
117
+ # ---------------------------------------------------------------------------
118
+ # Activity search
119
+ # ---------------------------------------------------------------------------
120
+
121
+
122
+ def test_search_activities_summary(monkeypatch):
123
+ fake = FakeRequest(response=[])
124
+ _patch(monkeypatch, "activity_search", fake)
125
+ asyncio.run(search_activities("vo2", athlete_id="i1", limit=5))
126
+ assert fake.last["url"] == "/athlete/i1/activities/search"
127
+ assert fake.last["params"] == {"q": "vo2", "limit": 5}
128
+
129
+
130
+ def test_search_activities_full_uses_search_full(monkeypatch):
131
+ fake = FakeRequest(response=[])
132
+ _patch(monkeypatch, "activity_search", fake)
133
+ asyncio.run(search_activities("#race", athlete_id="i1", full=True))
134
+ assert fake.last["url"] == "/athlete/i1/activities/search-full"
135
+
136
+
137
+ def test_interval_search_sends_required_params(monkeypatch):
138
+ fake = FakeRequest(response=[])
139
+ _patch(monkeypatch, "activity_search", fake)
140
+ asyncio.run(
141
+ interval_search(
142
+ min_secs=60,
143
+ max_secs=300,
144
+ min_intensity=95,
145
+ max_intensity=120,
146
+ athlete_id="i1",
147
+ min_reps=3,
148
+ )
149
+ )
150
+ p = fake.last["params"]
151
+ assert p["minSecs"] == 60
152
+ assert p["maxSecs"] == 300
153
+ assert p["minIntensity"] == 95
154
+ assert p["maxIntensity"] == 120
155
+ assert p["minReps"] == 3
156
+
157
+
158
+ def test_get_activities_around(monkeypatch):
159
+ fake = FakeRequest(response=[])
160
+ _patch(monkeypatch, "activity_search", fake)
161
+ asyncio.run(get_activities_around("a1", athlete_id="i1", limit=10))
162
+ assert fake.last["url"] == "/athlete/i1/activities-around"
163
+ assert fake.last["params"]["activity_id"] == "a1"
164
+ assert fake.last["params"]["limit"] == 10
165
+
166
+
167
+ def test_get_activity_tags(monkeypatch):
168
+ fake = FakeRequest(response=["climbing", "race"])
169
+ _patch(monkeypatch, "activity_search", fake)
170
+ result = asyncio.run(get_activity_tags(athlete_id="i1"))
171
+ assert fake.last["url"] == "/athlete/i1/activity-tags"
172
+ assert "climbing" in result
173
+
174
+
175
+ # ---------------------------------------------------------------------------
176
+ # Activity analysis
177
+ # ---------------------------------------------------------------------------
178
+
179
+
180
+ def test_get_activity_curve_hr(monkeypatch):
181
+ fake = FakeRequest(response={"curve": []})
182
+ _patch(monkeypatch, "activity_analysis", fake)
183
+ asyncio.run(get_activity_curve("a1", curve_type="hr"))
184
+ assert fake.last["url"] == "/activity/a1/hr-curve.json"
185
+
186
+
187
+ def test_get_activity_curve_pace_with_gap(monkeypatch):
188
+ fake = FakeRequest(response={"curve": []})
189
+ _patch(monkeypatch, "activity_analysis", fake)
190
+ asyncio.run(get_activity_curve("a1", curve_type="pace", gap=True))
191
+ assert fake.last["url"] == "/activity/a1/pace-curve.json"
192
+ assert fake.last["params"] == {"gap": True}
193
+
194
+
195
+ def test_get_activity_curve_power_multi(monkeypatch):
196
+ fake = FakeRequest(response={"curves": []})
197
+ _patch(monkeypatch, "activity_analysis", fake)
198
+ asyncio.run(
199
+ get_activity_curve(
200
+ "a1",
201
+ curve_type="power-multi",
202
+ streams="watts,watts_alt",
203
+ fatigue="normal,kj1",
204
+ )
205
+ )
206
+ assert fake.last["url"] == "/activity/a1/power-curves.json"
207
+ assert fake.last["params"]["types"] == "watts,watts_alt"
208
+ assert fake.last["params"]["fatigue"] == "normal,kj1"
209
+
210
+
211
+ def test_get_activity_curve_invalid_type():
212
+ result = asyncio.run(get_activity_curve("a1", curve_type="bogus"))
213
+ assert "Invalid curve_type" in result
214
+
215
+
216
+ def test_get_activity_best_efforts(monkeypatch):
217
+ fake = FakeRequest(response=[])
218
+ _patch(monkeypatch, "activity_analysis", fake)
219
+ asyncio.run(
220
+ get_activity_best_efforts(
221
+ "a1", stream="watts", duration=300, count=5, exclude_intervals=True
222
+ )
223
+ )
224
+ assert fake.last["url"] == "/activity/a1/best-efforts"
225
+ p = fake.last["params"]
226
+ assert p["stream"] == "watts"
227
+ assert p["duration"] == 300
228
+ assert p["count"] == 5
229
+ assert p["excludeIntervals"] is True
230
+
231
+
232
+ def test_get_activity_interval_stats(monkeypatch):
233
+ fake = FakeRequest(response={})
234
+ _patch(monkeypatch, "activity_analysis", fake)
235
+ asyncio.run(get_activity_interval_stats("a1", start_index=0, end_index=500))
236
+ assert fake.last["url"] == "/activity/a1/interval-stats"
237
+ assert fake.last["params"] == {"start_index": 0, "end_index": 500}
238
+
239
+
240
+ def test_get_activity_map(monkeypatch):
241
+ fake = FakeRequest(response={})
242
+ _patch(monkeypatch, "activity_analysis", fake)
243
+ asyncio.run(get_activity_map("a1", bounds_only=True, weather=True))
244
+ assert fake.last["url"] == "/activity/a1/map"
245
+ assert fake.last["params"] == {"boundsOnly": True, "weather": True}
246
+
247
+
248
+ # ---------------------------------------------------------------------------
249
+ # Activity interval editing
250
+ # ---------------------------------------------------------------------------
251
+
252
+
253
+ def test_update_activity_intervals_replace_all(monkeypatch):
254
+ fake = FakeRequest(response={})
255
+ _patch(monkeypatch, "activity_intervals", fake)
256
+ items = [{"start_index": 0, "type": "WORK"}]
257
+ asyncio.run(update_activity_intervals("a1", items, replace_all=True))
258
+ assert fake.last["url"] == "/activity/a1/intervals"
259
+ assert fake.last["method"] == "PUT"
260
+ assert fake.last["params"] == {"all": True}
261
+ assert fake.last["data"] == items
262
+
263
+
264
+ def test_update_activity_interval_single(monkeypatch):
265
+ fake = FakeRequest(response={})
266
+ _patch(monkeypatch, "activity_intervals", fake)
267
+ asyncio.run(update_activity_interval("a1", 7, {"label": "Tempo"}))
268
+ assert fake.last["url"] == "/activity/a1/intervals/7"
269
+ assert fake.last["method"] == "PUT"
270
+ assert fake.last["data"] == {"label": "Tempo"}
271
+
272
+
273
+ def test_delete_activity_intervals(monkeypatch):
274
+ fake = FakeRequest(response={})
275
+ _patch(monkeypatch, "activity_intervals", fake)
276
+ asyncio.run(delete_activity_intervals("a1", [1, 2, 3]))
277
+ assert fake.last["url"] == "/activity/a1/delete-intervals"
278
+ assert fake.last["method"] == "PUT"
279
+ assert fake.last["data"] == [1, 2, 3]
280
+
281
+
282
+ def test_split_activity_interval(monkeypatch):
283
+ fake = FakeRequest(response={})
284
+ _patch(monkeypatch, "activity_intervals", fake)
285
+ asyncio.run(split_activity_interval("a1", split_at=120))
286
+ assert fake.last["url"] == "/activity/a1/split-interval"
287
+ assert fake.last["method"] == "PUT"
288
+ assert fake.last["params"] == {"splitAt": 120}
289
+
290
+
291
+ # ---------------------------------------------------------------------------
292
+ # Power curves fix verification (uses athlete tool, not module above)
293
+ # ---------------------------------------------------------------------------
294
+
295
+
296
+ def test_power_curves_sends_required_filters_and_json_ext(monkeypatch):
297
+ from intervals_mcp_server.tools import power_curves as pc_mod
298
+
299
+ fake = FakeRequest(response={"list": []})
300
+ monkeypatch.setattr(
301
+ "intervals_mcp_server.tools.power_curves.make_intervals_request", fake
302
+ )
303
+ asyncio.run(pc_mod.get_athlete_power_curves(activity_type="Ride", athlete_id="i1"))
304
+ assert fake.last["url"] == "/athlete/i1/power-curves.json"
305
+ p = fake.last["params"]
306
+ assert p["f1"] == json.dumps([])
307
+ assert p["f2"] == json.dumps([])
308
+ assert p["f3"] == json.dumps([])
309
+
310
+
311
+ def test_activity_streams_uses_json_ext(monkeypatch):
312
+ from intervals_mcp_server.tools import activities as act_mod
313
+
314
+ fake = FakeRequest(response=[])
315
+ monkeypatch.setattr(
316
+ "intervals_mcp_server.tools.activities.make_intervals_request", fake
317
+ )
318
+ asyncio.run(act_mod.get_activity_streams("a1"))
319
+ assert fake.last["url"] == "/activity/a1/streams.json"