-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfirstcycling.py
2651 lines (2128 loc) · 113 KB
/
firstcycling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Any
import sys
import os
from mcp.server.fastmcp import FastMCP
import requests
from bs4 import BeautifulSoup
from typing import Dict, List, Optional, Union
from datetime import datetime
from FirstCyclingAPI.first_cycling_api.rider.rider import Rider
from FirstCyclingAPI.first_cycling_api.race.race import Race
from FirstCyclingAPI.first_cycling_api.api import FirstCyclingAPI
import re
# Add the FirstCyclingAPI directory to the Python path
sys.path.append(os.path.join(os.path.dirname(__file__), "FirstCyclingAPI"))
# Import from the FirstCycling API
from first_cycling_api.rider.rider import Rider
from first_cycling_api.race.race import RaceEdition
# Initialize FastMCP server
mcp = FastMCP("firstcycling")
@mcp.tool(
name="get_rider_year_results",
description="""Retrieve detailed results for a professional cyclist for a specific year.
This tool provides comprehensive information about a rider's performance in all races during a given calendar year.
It includes positions achieved, race categories, dates, and additional details.
Note: If you don't know the rider's ID, use the search_rider tool first to find it by name.
Example usage:
- Get 2023 results for Tadej Pogačar (ID: 16973)
- Get 2022 results for Jonas Vingegaard (ID: 16974)
Returns a formatted string with:
- Complete results for the specified year
- Position and time for each race
- Race category and details
- Chronological organization by date"""
)
async def get_rider_year_results(rider_id: int, year: int) -> str:
"""Get detailed results for a professional cyclist for a specific year.
Args:
rider_id: The FirstCycling rider ID (e.g., 16973 for Tadej Pogačar)
year: The year to get results for (e.g., 2023)
"""
try:
# Create a rider instance
rider = Rider(rider_id)
# Get year results
year_results = rider.year_results(year)
# Build information string
info = ""
# Get rider name
rider_name = None
if hasattr(year_results, 'header_details') and year_results.header_details:
if 'name' in year_results.header_details:
rider_name = year_results.header_details['name']
else:
# Try to find name in soup
if hasattr(year_results, 'soup') and year_results.soup:
name_element = year_results.soup.find('h1')
if name_element:
rider_name = name_element.text.strip()
# Format title
if rider_name:
info += f"{year} Results for {rider_name}:\n\n"
else:
info += f"{year} Results for Rider ID {rider_id}:\n\n"
# Check if we need to use standard parsing or direct HTML parsing
if hasattr(year_results, 'results_df') and not (year_results.results_df is None or year_results.results_df.empty):
# Use standard parsing
results_df = year_results.results_df
# Sort by date
if 'Date' in results_df.columns:
results_df = results_df.sort_values('Date')
for _, row in results_df.iterrows():
date = row.get('Date', 'N/A')
race = row.get('Race', 'N/A')
pos = row.get('Pos', 'N/A')
category = row.get('CAT', 'N/A')
result_line = f"{date} - {race}"
if category and category != 'N/A':
result_line += f" ({category})"
result_line += f": {pos}"
info += result_line + "\n"
else:
# Direct HTML parsing
if not hasattr(year_results, 'soup') or not year_results.soup:
return f"No results found for rider ID {rider_id} in year {year}. This rider ID may not exist or the rider didn't compete this year."
soup = year_results.soup
# Find results table
results_table = None
tables = soup.find_all('table')
# Look for the appropriate table that contains race results
for table in tables:
headers = [th.text.strip() for th in table.find_all('th')]
if len(headers) >= 3 and any(keyword in ' '.join(headers).lower()
for keyword in ['date', 'race', 'result', 'position']):
results_table = table
break
if not results_table:
return f"No results table found for rider ID {rider_id} in year {year}. The rider may not have competed this year."
# Parse results data
rows = results_table.find_all('tr')
if len(rows) <= 1: # Only header row, no data
return f"No race results found for rider ID {rider_id} in year {year}."
# Skip header row
for row in rows[1:]:
cols = row.find_all('td')
if len(cols) < 3: # Ensure it's a data row
continue
# Extract data (positions may vary depending on table structure)
date = cols[0].text.strip() if len(cols) > 0 else "N/A"
race = cols[1].text.strip() if len(cols) > 1 else "N/A"
pos = cols[2].text.strip() if len(cols) > 2 else "N/A"
# Try to find category if available
category = "N/A"
for i in range(3, min(6, len(cols))): # Check a few columns for possible category
col_text = cols[i].text.strip()
if col_text and len(col_text) <= 5 and any(c in col_text for c in [".", "WT", "1", "2"]):
category = col_text
break
result_line = f"{date} - {race}"
if category and category != 'N/A':
result_line += f" ({category})"
result_line += f": {pos}"
info += result_line + "\n"
if not info.endswith("\n\n"):
info += "\n"
return info
except Exception as e:
return f"Error retrieving {year} results for rider ID {rider_id}: {str(e)}"
@mcp.tool(
name="get_rider_victories",
description="""Get a comprehensive list of a rider's UCI victories.
This tool retrieves detailed information about all UCI-registered race victories achieved by the cyclist
throughout their career. Victories can be filtered to show only WorldTour wins if desired.
Note: If you don't know the rider's ID, use the search_rider tool first to find it by name.
Example usage:
- Get all UCI victories for Tadej Pogačar (ID: 16973)
- Get WorldTour victories for Jonas Vingegaard (ID: 16974)
Returns a formatted string with:
- Complete list of victories
- Race details including category
- Date and year of each victory
- Option to filter by WorldTour races only"""
)
async def get_rider_victories(rider_id: int, world_tour_only: bool = False) -> str:
"""Get a comprehensive list of a rider's UCI victories.
Args:
rider_id: The FirstCycling rider ID (e.g., 16973 for Tadej Pogačar)
world_tour_only: If True, only shows WorldTour victories
"""
try:
# Create a rider instance
rider = Rider(rider_id)
# Get victories (UCI victories by default)
victories = rider.victories(world_tour=world_tour_only, uci=True)
# Build information string
info = ""
# Get rider name
rider_name = None
if hasattr(victories, 'header_details') and victories.header_details:
if 'name' in victories.header_details:
rider_name = victories.header_details['name']
else:
# Try to find name in soup
if hasattr(victories, 'soup') and victories.soup:
name_element = victories.soup.find('h1')
if name_element:
rider_name = name_element.text.strip()
# Format title based on filter
if rider_name:
if world_tour_only:
info += f"WorldTour Victories for {rider_name}:\n\n"
else:
info += f"UCI Victories for {rider_name}:\n\n"
else:
if world_tour_only:
info += f"WorldTour Victories for Rider ID {rider_id}:\n\n"
else:
info += f"UCI Victories for Rider ID {rider_id}:\n\n"
# Check if we need to use standard parsing or direct HTML parsing
if hasattr(victories, 'results_df') and not (victories.results_df is None or victories.results_df.empty):
# Use standard parsing
results_df = victories.results_df
# Group by year
results_df = results_df.sort_values('Year', ascending=False)
for year in results_df['Year'].unique():
year_data = results_df[results_df['Year'] == year]
info += f"{year}:\n"
for _, row in year_data.iterrows():
date = row.get('Date', 'N/A')
race = row.get('Race', 'N/A')
category = row.get('CAT', 'N/A')
result_line = f" {date} - {race}"
if category and category != 'N/A':
result_line += f" ({category})"
info += result_line + "\n"
info += "\n"
else:
# Direct HTML parsing
if not hasattr(victories, 'soup') or not victories.soup:
return f"No victories data found for rider ID {rider_id}. This rider ID may not exist or has no recorded victories."
soup = victories.soup
# Find victories table
victories_table = None
tables = soup.find_all('table')
# Look for the appropriate table that contains victories
for table in tables:
headers = [th.text.strip() for th in table.find_all('th')] if table.find_all('th') else []
if len(headers) >= 3 and any(keyword in ' '.join(headers).lower()
for keyword in ['date', 'race', 'year']):
victories_table = table
break
if not victories_table:
return f"No victories table found for rider ID {rider_id}. The rider may not have any recorded victories."
# Parse victories data
rows = victories_table.find_all('tr')
if len(rows) <= 1: # Only header row, no data
return f"No victories found for rider ID {rider_id}."
# Get headers to determine column positions
headers = [th.text.strip() for th in rows[0].find_all('th')] if rows[0].find_all('th') else []
# Find column indices
year_idx = next((i for i, h in enumerate(headers) if "Year" in h), None)
date_idx = next((i for i, h in enumerate(headers) if "Date" in h), None)
race_idx = next((i for i, h in enumerate(headers) if "Race" in h), 1) # Default to second column
cat_idx = next((i for i, h in enumerate(headers) if "CAT" in h), None)
# Extract and organize victories by year
victories_by_year = {}
# Skip header row
for row in rows[1:]:
cols = row.find_all('td')
if len(cols) < 3: # Ensure it's a data row
continue
# Extract data
year = cols[year_idx].text.strip() if year_idx is not None and year_idx < len(cols) else "Unknown"
date = cols[date_idx].text.strip() if date_idx is not None and date_idx < len(cols) else "N/A"
race = cols[race_idx].text.strip() if race_idx is not None and race_idx < len(cols) else cols[1].text.strip()
category = cols[cat_idx].text.strip() if cat_idx is not None and cat_idx < len(cols) else "N/A"
# If year not found in date column, try to extract from date
if year == "Unknown" and date != "N/A":
year_match = re.search(r'(\d{4})', date)
if year_match:
year = year_match.group(1)
if year not in victories_by_year:
victories_by_year[year] = []
victories_by_year[year].append({
'date': date,
'race': race,
'category': category
})
# Sort years in descending order and format output
for year in sorted(victories_by_year.keys(), reverse=True):
info += f"{year}:\n"
for victory in victories_by_year[year]:
result_line = f" {victory['date']} - {victory['race']}"
if victory['category'] and victory['category'] != 'N/A':
result_line += f" ({victory['category']})"
info += result_line + "\n"
info += "\n"
if not victories_by_year:
info += "No victories found.\n"
return info
except Exception as e:
return f"Error retrieving victories for rider ID {rider_id}: {str(e)}"
@mcp.tool(
name="get_rider_teams",
description="""Get a detailed history of a professional cyclist's team affiliations throughout their career.
This tool provides a chronological list of all teams the rider has been part of, including years and team details.
Note: If you don't know the rider's ID, use the search_rider tool first to find it by name.
Example usage:
- Get team history for Peter Sagan (ID: 12345)
- Get career team changes for Chris Froome (ID: 67890)
Returns a formatted string with:
- Complete team history
- Years with each team
- Team names and details
- Chronological organization"""
)
async def get_rider_teams(rider_id: int) -> str:
"""Get a detailed history of a professional cyclist's team affiliations throughout their career.
Args:
rider_id: The FirstCycling rider ID (e.g., 12345 for Peter Sagan)
"""
try:
# Create a rider instance
rider = Rider(rider_id)
# Get teams history
teams_history = rider.teams()
# Build information string
info = ""
# Get rider name
rider_name = None
if hasattr(teams_history, 'header_details') and teams_history.header_details:
if 'name' in teams_history.header_details:
rider_name = teams_history.header_details['name']
else:
# Try to find name in soup
if hasattr(teams_history, 'soup') and teams_history.soup:
name_element = teams_history.soup.find('h1')
if name_element:
rider_name = name_element.text.strip()
# Format title
if rider_name:
info += f"Team History for {rider_name}:\n\n"
else:
info += f"Team History for Rider ID {rider_id}:\n\n"
# Check if we need to use standard parsing or direct HTML parsing
if hasattr(teams_history, 'results_df') and not (teams_history.results_df is None or teams_history.results_df.empty):
# Use standard parsing
results_df = teams_history.results_df
# Sort by year (most recent first)
results_df = results_df.sort_values('Year', ascending=False)
for _, row in results_df.iterrows():
year = row.get('Year', 'N/A')
team = row.get('Team', 'N/A')
info += f"{year}: {team}\n"
else:
# Direct HTML parsing
if not hasattr(teams_history, 'soup') or not teams_history.soup:
return f"No team history found for rider ID {rider_id}. This rider ID may not exist."
soup = teams_history.soup
# Find teams table
teams_table = None
tables = soup.find_all('table')
# Look for the appropriate table that contains team history
for table in tables:
headers = [th.text.strip() for th in table.find_all('th')] if table.find_all('th') else []
if len(headers) >= 2 and any(keyword in ' '.join(headers).lower()
for keyword in ['year', 'team', 'season']):
teams_table = table
break
if not teams_table:
# Try to find any table that might contain years and teams
for table in tables:
rows = table.find_all('tr')
if len(rows) >= 2: # At least a header and one data row
# Check first data row for year-like and team-like content
cols = rows[1].find_all('td')
if len(cols) >= 2:
# Check if first column contains a year
if re.match(r'\d{4}', cols[0].text.strip()):
teams_table = table
break
if not teams_table:
return f"No team history table found for rider ID {rider_id}."
# Parse teams data
rows = teams_table.find_all('tr')
if len(rows) <= 1: # Only header row, no data
return f"No team history found for rider ID {rider_id}."
# Get headers to determine column positions
headers = [th.text.strip() for th in rows[0].find_all('th')] if rows[0].find_all('th') else []
# Find column indices
year_idx = next((i for i, h in enumerate(headers) if "Year" in h), 0) # Default to first column
team_idx = next((i for i, h in enumerate(headers) if "Team" in h), 1) # Default to second column
# Extract teams by year
teams_by_year = []
# Skip header row
for row in rows[1:]:
cols = row.find_all('td')
if len(cols) < 2: # Ensure it's a data row
continue
# Extract data
year = cols[year_idx].text.strip() if year_idx < len(cols) else "Unknown"
team = cols[team_idx].text.strip() if team_idx < len(cols) else cols[1].text.strip()
# Sanitize data
if year and team:
teams_by_year.append({
'year': year,
'team': team
})
# Sort years in descending order and format output
teams_by_year.sort(key=lambda x: x['year'], reverse=True)
for team_entry in teams_by_year:
info += f"{team_entry['year']}: {team_entry['team']}\n"
if not teams_by_year:
info += "No team history found.\n"
return info
except Exception as e:
return f"Error retrieving team history for rider ID {rider_id}: {str(e)}"
@mcp.tool(
name="search_rider",
description="""Search for professional cyclists by name. This tool helps find riders by their name,
returning a list of matching riders with their IDs and basic information. This is useful when you need
a rider's ID for other operations but only know their name.
Example usage:
- Search for "Tadej Pogacar" to find Tadej Pogačar's ID
- Search for "Van Aert" to find Wout van Aert's ID
Returns a formatted string with:
- List of matching riders
- Each rider's ID, name, nationality, and current team
- Number of matches found"""
)
async def search_rider(query: str) -> str:
"""Search for riders by name.
Args:
query (str): The search query string to find riders by name.
Returns:
str: A formatted string containing matching riders with their details:
- Rider ID
- Rider name
- Nationality
- Current team
"""
try:
# Search for riders using the Rider.search method
riders = Rider.search(query)
if not riders:
return f"No riders found matching the query '{query}'."
# Build results string
info = f"Found {len(riders)} riders matching '{query}':\n\n"
for rider in riders:
info += f"ID: {rider['id']}\n"
info += f"Name: {rider['name']}\n"
if rider.get('nationality'):
info += f"Nationality: {rider['nationality'].upper()}\n"
if rider.get('team'):
info += f"Team: {rider['team']}\n"
info += "\n"
return info
except Exception as e:
return f"Error searching for riders: {str(e)}"
@mcp.tool(
name="get_rider_info",
description="""Get comprehensive information about a professional cyclist including their current team, nationality, date of birth, and recent race results.
This tool provides a detailed overview of a rider's current status and recent performance in professional cycling races.
The information includes their current team affiliation, nationality, age, and their most recent race results with positions and times.
Note: If you don't know the rider's ID, use the search_rider tool first to find it by name.
Example usage:
- Get basic info for Tadej Pogačar (ID: 16973)
- Get basic info for Jonas Vingegaard (ID: 16974)
Returns a formatted string with:
- Full name and current team
- Nationality and date of birth
- UCI ID and social media handles
- Last 5 race results with positions and times
- Total number of UCI victories"""
)
async def get_rider_info(rider_id: int) -> str:
"""Get basic information about a rider.
Args:
rider_id (int): The unique identifier for the rider. This ID can be found on FirstCycling.com
in the rider's profile URL (e.g., for rider 12345, the URL would be firstcycling.com/rider/12345).
Returns:
str: A formatted string containing the rider's information including:
- Full name
- Current team (if available)
- Nationality
- Date of birth
- Recent race results (last 5 races) with positions and times
Raises:
Exception: If the rider is not found or if there are connection issues.
"""
try:
# Create a rider instance
rider = Rider(rider_id)
# Use direct HTML parsing approach to handle cases where the regular parsing fails
try:
# Try to get rider year results using standard method
year_results = rider.year_results()
# Check if results exist
if year_results is None or not hasattr(year_results, 'results_df') or year_results.results_df.empty:
raise Exception("No results found using standard method")
# Extract details from the response
header_details = year_results.header_details
sidebar_details = year_results.sidebar_details
# Build rider information string
info = ""
# Add name from header details
if header_details and 'name' in header_details:
info += f"Name: {header_details['name']}\n"
else:
info += f"Rider ID: {rider_id}\n"
# Add team if available
if header_details and 'current_team' in header_details:
info += f"Team: {header_details['current_team']}\n"
# Add Twitter/social media if available
if header_details and 'twitter_handle' in header_details:
info += f"Twitter: @{header_details['twitter_handle']}\n"
# Add information from sidebar details
if sidebar_details:
if 'Nationality' in sidebar_details:
info += f"Nationality: {sidebar_details['Nationality']}\n"
if 'Date of Birth' in sidebar_details:
info += f"Date of Birth: {sidebar_details['Date of Birth']}\n"
if 'UCI ID' in sidebar_details:
info += f"UCI ID: {sidebar_details['UCI ID']}\n"
# Get results for current year
if hasattr(year_results, 'results_df') and not year_results.results_df.empty:
info += "\nRecent Results:\n"
results_count = min(5, len(year_results.results_df))
for i in range(results_count):
row = year_results.results_df.iloc[i]
date = row.get('Date', 'N/A')
race = row.get('Race', 'N/A')
pos = row.get('Pos', 'N/A')
info += f"{i+1}. {date} - {race}: {pos}\n"
# Add victories if available (just a count)
try:
victories = rider.victories(uci=True)
if hasattr(victories, 'results_df') and not victories.results_df.empty:
info += f"\nUCI Victories: {len(victories.results_df)}\n"
except:
pass
return info
except Exception as parsing_error:
# If standard parsing method fails, use direct HTML parsing
# Get raw HTML for the rider page
url = f"https://firstcycling.com/rider.php?r={rider_id}"
response = requests.get(url)
if response.status_code != 200:
return f"Failed to retrieve data for rider ID {rider_id}. Status code: {response.status_code}"
# Parse the HTML
soup = BeautifulSoup(response.text, 'html.parser')
# Check if the page indicates the rider doesn't exist
if "not found" in soup.text.lower() or "no results found" in soup.text.lower():
return f"Rider ID {rider_id} does not exist on FirstCycling.com."
# Build rider information string
info = ""
# Get rider name from the heading
name_element = soup.find('h1')
if name_element:
rider_name = name_element.text.strip()
info += f"Name: {rider_name}\n"
else:
info += f"Rider ID: {rider_id}\n"
# Get current team - typically in a div after the rider name
team_element = soup.find('span', class_='blue')
if team_element:
team_name = team_element.text.strip()
info += f"Team: {team_name}\n"
# Try to find the sidebar details (nationality, birth date, etc.)
sidebar = soup.find('div', class_='rp-info')
if sidebar:
detail_rows = sidebar.find_all('tr')
for row in detail_rows:
cells = row.find_all('td')
if len(cells) >= 2:
key = cells[0].text.strip().rstrip(':')
value = cells[1].text.strip()
if key and value:
info += f"{key}: {value}\n"
# Try to find recent results
tables = soup.find_all('table')
results_table = None
# Look for a table that has race results
for table in tables:
headers = [th.text.strip() for th in table.find_all('th')]
if len(headers) >= 3 and ('Date' in headers or 'Race' in headers):
results_table = table
break
if results_table:
# Get the headers to identify column positions
headers = [th.text.strip() for th in results_table.find_all('th')]
date_idx = headers.index('Date') if 'Date' in headers else None
race_idx = headers.index('Race') if 'Race' in headers else None
pos_idx = headers.index('Pos') if 'Pos' in headers else None
if date_idx is not None and race_idx is not None and pos_idx is not None:
# Extract up to 5 recent results
rows = results_table.find_all('tr')[1:6] # Skip header row, take up to 5 rows
if rows:
info += "\nRecent Results:\n"
for i, row in enumerate(rows):
cells = row.find_all('td')
if len(cells) > max(date_idx, race_idx, pos_idx):
date = cells[date_idx].text.strip()
race = cells[race_idx].text.strip()
pos = cells[pos_idx].text.strip()
info += f"{i+1}. {date} - {race}: {pos}\n"
# Try to find victories count
# This can be tricky with direct parsing, often in a different section
victories_section = soup.find(text=lambda text: text and 'victories' in text.lower())
if victories_section:
# Try to extract the number from text like "X UCI victories"
victory_text = victories_section.strip()
victory_match = re.search(r'(\d+)\s+UCI\s+victories', victory_text, re.IGNORECASE)
if victory_match:
victories_count = victory_match.group(1)
info += f"\nUCI Victories: {victories_count}\n"
return info
except Exception as e:
return f"Error retrieving rider information for ID {rider_id}: {str(e)}. The rider ID may not exist or there might be a connection issue."
@mcp.tool(
name="get_rider_best_results",
description="""Retrieve the best career results of a professional cyclist, including their top finishes in various races.
This tool provides a comprehensive overview of a rider's most significant achievements throughout their career,
including their highest positions in major races, stage wins, and overall classifications.
Results are sorted by importance and include detailed information about each race.
Note: If you don't know the rider's ID, use the search_rider tool first to find it by name.
Example usage:
- Get top 10 best results for Tadej Pogačar (ID: 16973)
- Get top 5 best results for Jonas Vingegaard (ID: 16974)
Returns a formatted string with:
- Rider's name and career highlights
- Top results sorted by importance
- Race details including category and country
- Date and position for each result"""
)
async def get_rider_best_results(rider_id: int, limit: int = 10) -> str:
"""Get the best results of a rider throughout their career.
Args:
rider_id (int): The unique identifier for the rider. This ID can be found on FirstCycling.com
in the rider's profile URL (e.g., for rider 12345, the URL would be firstcycling.com/rider/12345).
limit (int, optional): The maximum number of results to return. Defaults to 10.
This parameter helps control the amount of data returned and can be adjusted
based on the level of detail needed. Maximum recommended value is 20.
Returns:
str: A formatted string containing the rider's best results, including:
- Race name and edition
- Date of the race
- Position achieved
- Time or gap to winner (if applicable)
- Race category and type
- Any special achievements (e.g., stage wins, points classification)
Raises:
Exception: If the rider is not found or if there are connection issues.
"""
try:
# Create a rider instance
rider = Rider(rider_id)
# Get best results
best_results = rider.best_results()
# Check if results exist
if best_results is None or not hasattr(best_results, 'results_df') or best_results.results_df.empty:
return f"No best results found for rider ID {rider_id}. Check if this rider has results on FirstCycling.com."
# Build results information string
info = ""
# Add rider name if available from header details
if hasattr(best_results, 'header_details') and best_results.header_details and best_results.header_details.get('current_team'):
rider_name = best_results.soup.find('h1').text.strip() if best_results.soup.find('h1') else f"Rider ID {rider_id}"
info += f"Best Results for {rider_name}:\n\n"
else:
info += f"Best Results for Rider ID {rider_id}:\n\n"
# Get top results
results_df = best_results.results_df.head(limit)
for _, row in results_df.iterrows():
pos = row.get('Pos', 'N/A')
race = row.get('Race', 'N/A')
editions = row.get('Editions', 'N/A')
category = row.get('CAT', '')
country = row.get('Race_Country', '')
result_line = f"{pos}. {race}"
if category:
result_line += f" ({category})"
if editions != 'N/A':
result_line += f" - {editions}"
if country:
result_line += f" - {country}"
info += result_line + "\n"
return info
except Exception as e:
return f"Error retrieving best results for rider ID {rider_id}: {str(e)}. The rider ID may not exist or there might be a connection issue."
@mcp.tool(
name="get_rider_grand_tour_results",
description="""Get comprehensive results for a rider in Grand Tours (Tour de France, Giro d'Italia, and Vuelta a España).
This tool provides detailed information about a rider's performance in cycling's most prestigious three-week races,
including their overall classification positions, stage wins, and special classification results.
The data is organized chronologically and includes all relevant race details.
Note: If you don't know the rider's ID, use the search_rider tool first to find it by name.
Example usage:
- Get Grand Tour results for Tadej Pogačar (ID: 16973)
- Get Grand Tour results for Jonas Vingegaard (ID: 16974)
Returns a formatted string with:
- Results for each Grand Tour (Tour de France, Giro, Vuelta)
- Overall classification positions
- Stage wins and special classification results
- Time gaps and race details"""
)
async def get_rider_grand_tour_results(rider_id: int) -> str:
"""Get results for a rider in Grand Tours.
Args:
rider_id (int): The unique identifier for the rider. This ID can be found on FirstCycling.com
in the rider's profile URL (e.g., for rider 12345, the URL would be firstcycling.com/rider/12345).
Returns:
str: A formatted string containing the rider's Grand Tour results, including:
- Race name and year
- Overall classification position
- Time or gap to winner
- Stage wins (if any)
- Points classification results
- Mountains classification results
- Young rider classification results (if applicable)
- Team classification results
Raises:
Exception: If the rider is not found or if there are connection issues.
"""
try:
# Create a rider instance
rider = Rider(rider_id)
# Get grand tour results
grand_tour_results = rider.grand_tour_results()
# Build information string
info = ""
# Get rider name
rider_name = None
if hasattr(grand_tour_results, 'header_details') and grand_tour_results.header_details and 'name' in grand_tour_results.header_details:
rider_name = grand_tour_results.header_details['name']
else:
# Try to extract rider name from page title
if hasattr(grand_tour_results, 'soup') and grand_tour_results.soup:
title = grand_tour_results.soup.find('title')
if title and '|' in title.text:
rider_name = title.text.split('|')[0].strip()
# Format title
if rider_name:
info += f"Grand Tour Results for {rider_name}:\n\n"
else:
info += f"Grand Tour Results for Rider ID {rider_id}:\n\n"
# Check if we need to use standard parsing or direct HTML parsing
if hasattr(grand_tour_results, 'results_df') and not (grand_tour_results.results_df is None or grand_tour_results.results_df.empty):
# Use standard parsing
results_df = grand_tour_results.results_df
# Group results by race
for race in results_df['Race'].unique():
race_results = results_df[results_df['Race'] == race]
info += f"{race}:\n"
# Sort by year (most recent first)
race_results = race_results.sort_values('Year', ascending=False)
for _, row in race_results.iterrows():
year = row.get('Year', 'N/A')
pos = row.get('Pos', 'N/A')
time = row.get('Time', '')
result_line = f" {year}: {pos}"
if time:
result_line += f" - {time}"
info += result_line + "\n"
info += "\n"
else:
# Direct HTML parsing
if not hasattr(grand_tour_results, 'soup') or not grand_tour_results.soup:
return f"No Grand Tour results found for rider ID {rider_id}. This rider ID may not exist."
soup = grand_tour_results.soup
# Find Grand Tour results table
tables = soup.find_all('table')
gt_table = None
# Look for the appropriate table that contains Grand Tour results
# Usually it's a table with "Tour de France", "Giro d'Italia", or "Vuelta a España" mentioned
grand_tours = ["Tour de France", "Giro d'Italia", "Vuelta a España"]
for table in tables:
for gt in grand_tours:
if gt in table.text:
gt_table = table
break
if gt_table:
break
# If not found by name, look for a table with "Race" and "Year" columns
headers = [th.text.strip() for th in table.find_all('th')]
if len(headers) >= 3 and "Race" in headers and "Year" in headers:
gt_table = table
break
if not gt_table:
return f"Could not find Grand Tour results table for rider ID {rider_id}."
# Parse Grand Tour data
rows = gt_table.find_all('tr')
gt_data = []
# Get column indices from header row
headers = [th.text.strip() for th in rows[0].find_all('th')]
race_idx = next((i for i, h in enumerate(headers) if "Race" in h), None)
year_idx = next((i for i, h in enumerate(headers) if "Year" in h), None)
pos_idx = next((i for i, h in enumerate(headers) if "Pos" in h), None)
time_idx = next((i for i, h in enumerate(headers) if "Time" in h), None)
# Skip header row
for row in rows[1:]:
cols = row.find_all('td')
if len(cols) < 3: # Ensure it's a data row
continue
# Extract data
race_text = cols[race_idx].text.strip() if race_idx is not None and race_idx < len(cols) else "N/A"
year_text = cols[year_idx].text.strip() if year_idx is not None and year_idx < len(cols) else "N/A"
pos_text = cols[pos_idx].text.strip() if pos_idx is not None and pos_idx < len(cols) else "N/A"
time_text = cols[time_idx].text.strip() if time_idx is not None and time_idx < len(cols) else ""
# Only include if it's a Grand Tour
if any(gt in race_text for gt in grand_tours):
gt_data.append({
'Race': race_text,
'Year': year_text,
'Pos': pos_text,
'Time': time_text
})
# Group by race
race_grouped = {}
for result in gt_data:
race = result['Race']
if race not in race_grouped:
race_grouped[race] = []
race_grouped[race].append(result)
# Format output by race
for race, results in race_grouped.items():
info += f"{race}:\n"
# Sort by year (most recent first)
results.sort(key=lambda x: x['Year'], reverse=True)
for result in results:
result_line = f" {result['Year']}: {result['Pos']}"
if result['Time']:
result_line += f" - {result['Time']}"
info += result_line + "\n"
info += "\n"
if not gt_data:
info += "No Grand Tour results found for this rider.\n"
return info
except Exception as e:
return f"Error retrieving Grand Tour results for rider ID {rider_id}: {str(e)}. The rider ID may not exist or there might be a connection issue."
@mcp.tool(
name="get_rider_monument_results",
description="""Retrieve detailed results for a rider in cycling's five Monument races (Milan-San Remo, Tour of Flanders,
Paris-Roubaix, Liège-Bastogne-Liège, and Il Lombardia). These are the most prestigious one-day races in professional cycling.
The tool provides comprehensive information about a rider's performance in these historic races, including their positions,
times, and any special achievements.
Note: If you don't know the rider's ID, use the search_rider tool first to find it by name.
Example usage:
- Get Monument results for Tadej Pogačar (ID: 16973)
- Get Monument results for Mathieu van der Poel (ID: 16975)
Returns a formatted string with:
- Results for each Monument race