File size: 56,594 Bytes
642907a
 
 
262aca8
 
be9d670
262aca8
 
 
 
 
 
 
 
 
642907a
 
 
be9d670
642907a
f219f0a
 
 
 
 
be9d670
 
 
 
 
642907a
 
262aca8
 
 
 
642907a
 
 
 
f219f0a
 
 
 
 
 
 
be9d670
 
 
 
642907a
f219f0a
 
 
 
 
b935477
 
f219f0a
 
642907a
 
 
f219f0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4eb0a2
 
 
 
 
 
 
 
f219f0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be9d670
 
 
 
 
00ab4f8
 
 
be9d670
 
 
 
 
00ab4f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be9d670
 
 
 
 
b935477
 
 
 
 
00ab4f8
b935477
00ab4f8
 
bfcd620
 
c3e313a
 
f219f0a
c3e313a
 
 
 
 
 
f219f0a
 
c3e313a
 
f219f0a
c3e313a
 
f219f0a
 
 
c3e313a
f219f0a
c3e313a
 
f219f0a
 
 
 
 
 
 
 
 
 
 
 
c3e313a
 
f219f0a
c3e313a
f219f0a
c3e313a
f219f0a
c3e313a
f219f0a
c3e313a
 
f219f0a
 
c3e313a
f219f0a
 
 
 
 
 
 
 
 
c3e313a
f219f0a
 
c3e313a
 
 
 
bfcd620
be9d670
bfcd620
 
 
 
 
 
 
 
 
be9d670
 
 
bfcd620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642907a
 
be9d670
 
 
 
 
 
 
c3e313a
be9d670
 
 
 
c3e313a
 
 
 
 
 
 
f219f0a
 
c3e313a
 
f219f0a
c3e313a
 
be9d670
 
 
 
 
 
 
 
 
 
 
 
 
 
f219f0a
 
 
be9d670
 
00ab4f8
be9d670
 
f219f0a
 
be9d670
 
b935477
be9d670
 
b935477
 
 
 
 
 
 
 
 
 
 
 
00ab4f8
b935477
 
 
 
 
 
 
 
 
 
 
00ab4f8
b935477
 
 
 
 
be9d670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00ab4f8
 
 
be9d670
 
 
 
 
00ab4f8
be9d670
 
00ab4f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be9d670
 
 
c3e313a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f219f0a
 
 
 
 
 
 
be9d670
 
 
 
 
 
f219f0a
 
be9d670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f219f0a
be9d670
c3e313a
 
 
 
 
 
 
 
 
f219f0a
 
 
 
 
 
 
 
 
be9d670
 
 
 
 
f219f0a
be9d670
c3e313a
 
 
 
 
 
 
 
 
f219f0a
 
 
 
 
 
 
 
 
be9d670
 
 
 
 
f219f0a
c3e313a
 
 
 
 
 
 
 
 
 
f219f0a
 
 
 
 
 
 
 
 
c3e313a
f219f0a
be9d670
 
 
 
 
f219f0a
 
 
 
 
 
 
be9d670
 
 
 
 
 
 
 
 
 
 
f219f0a
 
be9d670
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f219f0a
642907a
 
 
 
f219f0a
 
 
 
 
642907a
262aca8
f219f0a
 
 
b935477
642907a
 
262aca8
f219f0a
 
 
 
 
642907a
262aca8
 
 
642907a
262aca8
bfcd620
be9d670
642907a
bfcd620
 
 
 
 
 
 
 
 
 
642907a
 
 
 
 
f219f0a
642907a
 
 
 
f219f0a
 
 
 
 
 
642907a
262aca8
f219f0a
 
 
 
642907a
 
262aca8
f219f0a
642907a
 
 
 
 
057e151
be9d670
 
642907a
 
 
 
 
 
f219f0a
642907a
 
 
 
f219f0a
 
 
 
 
642907a
262aca8
f219f0a
 
 
 
642907a
 
262aca8
f219f0a
642907a
 
 
 
 
057e151
be9d670
 
642907a
 
 
 
 
 
 
 
 
 
 
262aca8
642907a
 
262aca8
642907a
 
 
 
 
057e151
be9d670
 
642907a
 
 
 
 
 
f219f0a
262aca8
642907a
 
 
f219f0a
 
 
 
 
 
 
 
 
642907a
262aca8
f219f0a
 
 
 
642907a
 
262aca8
642907a
262aca8
642907a
 
 
be9d670
642907a
 
 
 
 
 
 
bfcd620
 
 
 
 
 
 
262aca8
bfcd620
 
262aca8
bfcd620
 
 
 
 
057e151
be9d670
 
bfcd620
 
 
 
 
 
 
 
 
 
 
262aca8
bfcd620
 
262aca8
bfcd620
 
 
 
 
057e151
be9d670
 
bfcd620
 
 
 
 
 
 
 
 
 
 
262aca8
bfcd620
 
262aca8
bfcd620
 
 
 
 
057e151
be9d670
 
bfcd620
 
 
 
 
 
 
 
 
 
 
262aca8
bfcd620
 
262aca8
bfcd620
 
 
 
 
057e151
be9d670
 
bfcd620
 
 
 
 
 
 
 
 
 
 
262aca8
bfcd620
 
262aca8
bfcd620
 
 
 
 
057e151
be9d670
 
bfcd620
 
 
 
 
 
00ab4f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f219f0a
bfcd620
 
 
00ab4f8
f219f0a
 
 
 
 
 
 
 
bfcd620
 
262aca8
bfcd620
 
be9d670
bfcd620
262aca8
f219f0a
262aca8
bfcd620
262aca8
f219f0a
bfcd620
f219f0a
bfcd620
 
 
 
 
 
 
 
 
 
 
 
c3e313a
bfcd620
 
00ab4f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f219f0a
00ab4f8
 
 
 
f219f0a
 
00ab4f8
 
f219f0a
 
 
 
 
00ab4f8
f219f0a
 
 
 
 
00ab4f8
f219f0a
 
 
 
00ab4f8
 
 
f219f0a
 
00ab4f8
 
 
f219f0a
 
00ab4f8
 
 
f219f0a
 
 
00ab4f8
f219f0a
 
 
 
 
 
 
 
 
bfcd620
 
 
 
 
 
f219f0a
bfcd620
 
c3e313a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262aca8
f219f0a
262aca8
f219f0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262aca8
 
c3e313a
 
 
b935477
c3e313a
f219f0a
b935477
c3e313a
f219f0a
 
c3e313a
 
 
 
 
 
 
 
 
 
 
b18cfa8
 
c3e313a
 
b18cfa8
c3e313a
 
 
a544d54
c3e313a
 
 
 
 
 
 
 
 
 
a544d54
 
 
 
 
 
b18cfa8
a544d54
 
 
 
 
 
 
 
 
 
 
 
c3e313a
 
 
 
 
 
 
 
 
 
 
262aca8
 
 
 
 
 
 
 
 
 
 
 
642907a
 
 
262aca8
c3e313a
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
"""
Research Tracker MCP Server

A clean, simple MCP server that provides research inference utilities.
Exposes functions to infer research metadata from paper URLs, repository links,
or research names using embedded inference logic.

Key Features:
- Author inference from papers and repositories
- Cross-platform resource discovery (papers, code, models, datasets)
- Research metadata extraction (names, dates, licenses, organizations)
- URL classification and relationship mapping
- Comprehensive research ecosystem analysis

All functions are optimized for MCP usage with clear type hints and docstrings.
"""

import os
import re
import logging
import time
from urllib.parse import urlparse, quote
from typing import List, Dict, Any, Optional, Union
from functools import wraps
from datetime import datetime, timedelta

import gradio as gr
import requests
import feedparser
from bs4 import BeautifulSoup

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Configuration
REQUEST_TIMEOUT = 30
MAX_RETRIES = 3
RETRY_DELAY = 1  # seconds
CACHE_TTL = 3600  # 1 hour cache TTL
MAX_URL_LENGTH = 2048
RATE_LIMIT_WINDOW = 60  # seconds
RATE_LIMIT_CALLS = 30  # max calls per window

ARXIV_API_BASE = "http://export.arxiv.org/api/query"
HUGGINGFACE_API_BASE = "https://huggingface.co/api"
HF_TOKEN = os.environ.get("HF_TOKEN")
GITHUB_AUTH = os.environ.get("GITHUB_AUTH")

# Allowed domains for security
ALLOWED_DOMAINS = {
    "arxiv.org",
    "huggingface.co",
    "github.com",
    "github.io",
    "raw.githubusercontent.com"
}

if not HF_TOKEN:
    logger.warning("HF_TOKEN not found in environment variables")

# Enhanced cache with TTL for scraping results
_scrape_cache = {}  # {url: {"data": ..., "timestamp": ...}}
_rate_limit_tracker = {}  # {key: [timestamps]}


class MCPError(Exception):
    """Base exception for MCP-related errors"""
    pass


class ValidationError(MCPError):
    """Input validation error"""
    pass


class ExternalAPIError(MCPError):
    """External API call error"""
    pass


def validate_url(url: str) -> bool:
    """Validate URL for security and correctness"""
    if not url or len(url) > MAX_URL_LENGTH:
        return False
    
    try:
        parsed = urlparse(url)
        if not parsed.scheme or not parsed.netloc:
            return False
        
        # Extract domain
        domain = parsed.netloc.lower()
        if ":" in domain:
            domain = domain.split(":")[0]
        
        # Check against allowed domains
        return any(domain.endswith(allowed) for allowed in ALLOWED_DOMAINS)
    except Exception:
        return False


def rate_limit(key: str):
    """Simple rate limiting decorator"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            now = time.time()
            
            # Clean old timestamps
            if key in _rate_limit_tracker:
                _rate_limit_tracker[key] = [
                    ts for ts in _rate_limit_tracker[key]
                    if now - ts < RATE_LIMIT_WINDOW
                ]
            else:
                _rate_limit_tracker[key] = []
            
            # Check rate limit
            if len(_rate_limit_tracker[key]) >= RATE_LIMIT_CALLS:
                raise MCPError(f"Rate limit exceeded. Max {RATE_LIMIT_CALLS} calls per {RATE_LIMIT_WINDOW} seconds.")
            
            _rate_limit_tracker[key].append(now)
            return func(*args, **kwargs)
        return wrapper
    return decorator


def make_github_request(endpoint: str, headers: Optional[Dict] = None) -> Optional[requests.Response]:
    """Make GitHub API request with proper authentication and error handling"""
    if not GITHUB_AUTH:
        return None
        
    url = f"https://api.github.com{endpoint}" if endpoint.startswith("/") else endpoint
    
    if not headers:
        headers = {}
    headers["Authorization"] = f"Bearer {GITHUB_AUTH}"
    
    try:
        response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT)
        if response.status_code == 200:
            return response
        elif response.status_code == 404:
            return None
        else:
            logger.warning(f"GitHub API returned {response.status_code} for {url}")
            return None
    except requests.exceptions.RequestException as e:
        logger.warning(f"GitHub API request failed: {e}")
        return None


def cached_request(url: str, timeout: int = REQUEST_TIMEOUT) -> Optional[requests.Response]:
    """Make HTTP request with caching, retries, and validation"""
    if not validate_url(url):
        raise ValidationError(f"Invalid or disallowed URL: {url}")
    
    # Check cache
    if url in _scrape_cache:
        cache_entry = _scrape_cache[url]
        # Handle both old and new cache formats
        if isinstance(cache_entry, dict) and "timestamp" in cache_entry:
            if time.time() - cache_entry["timestamp"] < CACHE_TTL:
                logger.debug(f"Cache hit for {url}")
                return cache_entry["data"]
        else:
            # Old cache format, clear it
            del _scrape_cache[url]
    
    # Make request with retries
    for attempt in range(MAX_RETRIES):
        try:
            response = requests.get(url, timeout=timeout)
            if response.status_code == 200:
                # Cache successful response
                _scrape_cache[url] = {
                    "data": response,
                    "timestamp": time.time()
                }
                return response
            elif response.status_code == 404:
                return None
            else:
                logger.warning(f"HTTP {response.status_code} for {url}")
        except requests.exceptions.Timeout:
            logger.warning(f"Timeout on attempt {attempt + 1} for {url}")
        except requests.exceptions.RequestException as e:
            logger.warning(f"Request error on attempt {attempt + 1}: {e}")
        
        if attempt < MAX_RETRIES - 1:
            time.sleep(RETRY_DELAY * (attempt + 1))  # Exponential backoff
    
    raise ExternalAPIError(f"Failed to fetch {url} after {MAX_RETRIES} attempts")


# Utility functions
def get_arxiv_id(paper_url: str) -> Optional[str]:
    """Extract arXiv ID from paper URL"""
    if "arxiv.org/abs/" in paper_url:
        return paper_url.split("arxiv.org/abs/")[1].split('.pdf')[0]
    elif "arxiv.org/pdf/" in paper_url:
        return paper_url.split("arxiv.org/pdf/")[1].split('.pdf')[0]
    elif "huggingface.co/papers" in paper_url:
        return paper_url.split("huggingface.co/papers/")[1]
    return None


def clean_url(url):
    """Clean malformed URLs by removing trailing HTML fragments and invalid characters"""
    if not url:
        return url
    
    # Remove HTML closing tags and attributes that often get attached
    import re
    
    # Remove anything after quote marks followed by HTML-like content
    url = re.sub(r'["\']\s*>.*$', '', url)
    
    # Remove trailing HTML fragments
    url = re.sub(r'["\']?\s*</.*$', '', url)
    
    # Remove trailing punctuation and whitespace
    url = url.rstrip('",;\'"()<>[] \t\n\r')
    
    # Basic URL validation - should start with http/https and contain valid characters
    if not re.match(r'^https?://[^\s<>"\'\[\]{}|\\^`]+$', url):
        return None
    
    return url


def is_valid_paper_url(url):
    """Check if a URL is a valid paper URL, excluding badges and non-paper content"""
    if not url:
        return False
    
    url_lower = url.lower()
    
    # Exclude badges, shields, and other non-paper URLs
    if any(pattern in url_lower for pattern in [
        'img.shields.io', 'badge', 'logo', 'icon', 'button',
        'github.com/microsoft/trellis/issues', '/releases/', '/actions/',
        '/wiki/', '/tree/', '/blob/', '.svg', '.png', '.jpg', '.gif'
    ]):
        return False
    
    # Valid paper URL patterns
    if any(pattern in url_lower for pattern in [
        'arxiv.org/abs/', 'arxiv.org/pdf/', 'huggingface.co/papers/'
    ]):
        return True
    
    return False


def select_best_github_repo(github_links, context_keywords=None):
    """Select the best GitHub repository from a list of GitHub URLs"""
    if not github_links:
        return None
    
    if context_keywords is None:
        context_keywords = []
    
    # Score repositories based on various factors
    scored_repos = []
    
    for link in github_links:
        if not link:
            continue
            
        score = 0
        link_lower = link.lower()
        
        # Skip user profiles (github.com/username without repo)
        path_parts = link.split('github.com/')[-1].split('/')
        if len(path_parts) < 2 or not path_parts[1]:
            continue  # Skip user profiles
        
        # Skip issue/PR/wiki pages - prefer main repo
        if any(x in link_lower for x in ['/issues', '/pull', '/wiki', '/releases', '/actions']):
            score -= 10
        
        # Prefer repositories that match context keywords
        for keyword in context_keywords:
            if keyword.lower() in link_lower:
                score += 20
        
        # Prefer Microsoft/official org repos if in a Microsoft context
        if 'microsoft' in link_lower and any(k.lower() in link_lower for k in context_keywords):
            score += 15
        
        # Prefer main branch/root repo URLs
        if link_lower.endswith('.git') or '/tree/' not in link_lower:
            score += 5
        
        scored_repos.append((score, link))
    
    if scored_repos:
        # Return the highest scored repository
        scored_repos.sort(key=lambda x: x[0], reverse=True)
        return scored_repos[0][1]
    
    return None


def extract_links_from_soup(soup, text):
    """Extract both HTML and markdown links from soup and text"""
    html_links = [link.get("href") for link in soup.find_all("a") if link.get("href")]
    link_pattern = re.compile(r"\[.*?\]\((.*?)\)")
    markdown_links = link_pattern.findall(text)
    
    # Also extract direct URLs that aren't in markdown format
    url_pattern = re.compile(r'https?://[^\s\)]+')
    direct_urls = url_pattern.findall(text)
    
    # Combine all links, clean them, and remove duplicates
    all_links = html_links + markdown_links + direct_urls
    cleaned_links = [clean_url(link) for link in all_links if link]
    return list(set([link for link in cleaned_links if link]))


def scrape_huggingface_paper_page(paper_url: str) -> Dict[str, Any]:
    """
    Scrape HuggingFace paper page to find associated resources with caching
    
    Returns:
        Dict containing found resources: {
            "models": [], "datasets": [], "spaces": [], "code": []
        }
    """
    # Default empty resources
    empty_resources = {"models": [], "datasets": [], "spaces": [], "code": []}
    
    if not paper_url or "huggingface.co/papers" not in paper_url:
        return empty_resources
    
    try:
        response = cached_request(paper_url)
        if not response:
            return empty_resources
            
        soup = BeautifulSoup(response.text, "html.parser")
        
        # Find all links on the page
        links = set()  # Use set to avoid duplicates
        for link in soup.find_all("a", href=True):
            href = link["href"]
            # Convert relative URLs to absolute
            if href.startswith("/"):
                href = "https://huggingface.co" + href
            elif href.startswith("huggingface.co"):
                href = "https://" + href
            links.add(href)
        
        # Categorize links efficiently
        resources = {"models": [], "datasets": [], "spaces": [], "code": []}
        for link in links:
            if "huggingface.co/" in link:
                if "/models/" in link:
                    resources["models"].append(link)
                elif "/datasets/" in link:
                    resources["datasets"].append(link)
                elif "/spaces/" in link:
                    resources["spaces"].append(link)
            elif "github.com" in link:
                resources["code"].append(link)
        
        # Cache the result
        _scrape_cache[paper_url] = resources
        
        logger.info(f"Scraped {len(resources['models'])} models, {len(resources['datasets'])} datasets, "
                   f"{len(resources['spaces'])} spaces, {len(resources['code'])} code repos from {paper_url}")
        
    except ValidationError as e:
        logger.error(f"Validation error scraping HF paper page: {e}")
        return empty_resources
    except ExternalAPIError as e:
        logger.error(f"External API error scraping HF paper page: {e}")
        return empty_resources
    except Exception as e:
        logger.error(f"Unexpected error scraping HF paper page: {e}")
        return empty_resources
    
    return resources


def create_row_data(input_data: str) -> Dict[str, Any]:
    """Create standardized row data structure from input."""
    row_data = {
        "Name": None,
        "Authors": [],
        "Paper": None,
        "Code": None,
        "Project": None,
        "Space": None,
        "Model": None,
        "Dataset": None,
        "Orgs": [],
        "License": None,
        "Date": None,
    }
    
    # Classify input based on URL patterns
    if input_data.startswith(("http://", "https://")):
        if "arxiv.org" in input_data or "huggingface.co/papers" in input_data:
            row_data["Paper"] = input_data
        elif "github.com" in input_data:
            row_data["Code"] = input_data
        elif "github.io" in input_data:
            row_data["Project"] = input_data
        elif "huggingface.co/spaces" in input_data:
            row_data["Space"] = input_data
        elif "huggingface.co/datasets" in input_data:
            row_data["Dataset"] = input_data
        elif "huggingface.co/" in input_data:
            row_data["Model"] = input_data
        else:
            row_data["Paper"] = input_data
    else:
        row_data["Name"] = input_data
    
    return row_data


# Core inference functions
def infer_paper_from_row(row_data: Dict[str, Any]) -> Optional[str]:
    """Infer paper URL from row data"""
    if row_data.get("Paper") is not None:
        try:
            url = urlparse(row_data["Paper"])
            if url.scheme in ["http", "https"]:
                # Convert arXiv PDF to abs format
                if "arxiv.org/pdf/" in row_data["Paper"]:
                    new_url = row_data["Paper"].replace("/pdf/", "/abs/").replace(".pdf", "")
                    logger.info(f"Paper {new_url} inferred from {row_data['Paper']}")
                    return new_url
                
                # If this is an arXiv URL, try HuggingFace papers first for better resource discovery
                if "arxiv.org/abs/" in row_data["Paper"]:
                    arxiv_id = row_data["Paper"].split("arxiv.org/abs/")[1]
                    hf_paper_url = f"https://huggingface.co/papers/{arxiv_id}"
                    try:
                        # Test if HuggingFace paper page exists and has content
                        response = cached_request(hf_paper_url)
                        if response and len(response.text) > 1000:  # Basic check for content
                            logger.info(f"Paper {hf_paper_url} inferred from arXiv (HuggingFace preferred)")
                            return hf_paper_url
                    except (ValidationError, ExternalAPIError):
                        pass  # Fall back to original arXiv URL
                
                return row_data["Paper"]
        except Exception:
            pass

    # Check if paper is in other fields
    for field in ["Project", "Code", "Model", "Space", "Dataset", "Name"]:
        if row_data.get(field) is not None:
            if "arxiv" in row_data[field] or "huggingface.co/papers" in row_data[field]:
                logger.info(f"Paper {row_data[field]} inferred from {field}")
                return row_data[field]

    # Try following project link and look for paper
    if row_data.get("Project") is not None:
        try:
            response = cached_request(row_data["Project"])
            if response:
                soup = BeautifulSoup(response.text, "html.parser")
            for link in soup.find_all("a"):
                href = link.get("href")
                if href and is_valid_paper_url(href):
                    logger.info(f"Paper {href} inferred from Project")
                    return href
        except (ValidationError, ExternalAPIError) as e:
            logger.debug(f"Failed to scrape project page: {e}")

    # Try GitHub README parsing
    if row_data.get("Code") is not None and "github.com" in row_data["Code"]:
        try:
            repo = row_data["Code"].split("github.com/")[1]
            
            # First try with GitHub API if available
            if GITHUB_AUTH:
                readme_response = make_github_request(f"/repos/{repo}/readme")
                if readme_response:
                    readme = readme_response.json()
                    if readme.get("type") == "file" and readme.get("download_url"):
                        response = cached_request(readme["download_url"])
                        if response:
                            soup = BeautifulSoup(response.text, "html.parser")
                            links = extract_links_from_soup(soup, response.text)
                            for link in links:
                                if link and is_valid_paper_url(link):
                                    logger.info(f"Paper {link} inferred from Code (via GitHub API)")
                                    return link
            
            # Fallback: try scraping the GitHub page directly
            try:
                github_url = row_data["Code"]
                response = cached_request(github_url)
                if response:
                    soup = BeautifulSoup(response.text, "html.parser")
                    links = extract_links_from_soup(soup, response.text)
                    for link in links:
                        if link and is_valid_paper_url(link):
                            logger.info(f"Paper {link} inferred from Code (via GitHub scraping)")
                            return link
            except (ValidationError, ExternalAPIError):
                pass
                
        except Exception:
            pass
    
    return None


def infer_name_from_row(row_data: Dict[str, Any]) -> Optional[str]:
    """Infer research name from row data"""
    if row_data.get("Name") is not None:
        return row_data["Name"]

    # Try to get name using arxiv api
    if row_data.get("Paper") is not None:
        arxiv_id = get_arxiv_id(row_data["Paper"])
        if arxiv_id is not None:
            try:
                search_params = "id_list=" + arxiv_id
                response = feedparser.parse(f"{ARXIV_API_BASE}?" + search_params)
                if response.entries and len(response.entries) > 0:
                    entry = response.entries[0]
                    if hasattr(entry, "title"):
                        name = entry.title.strip()
                        logger.info(f"Name {name} inferred from Paper")
                        return name
            except Exception:
                pass

    # Try to get from code repo
    if row_data.get("Code") is not None and "github.com" in row_data["Code"]:
        try:
            repo = row_data["Code"].split("github.com/")[1]
            name = repo.split("/")[1]
            logger.info(f"Name {name} inferred from Code")
            return name
        except Exception:
            pass

    # Try to get from project page
    if row_data.get("Project") is not None:
        try:
            r = requests.get(row_data["Project"], timeout=REQUEST_TIMEOUT)
            soup = BeautifulSoup(r.text, "html.parser")
            if soup.title is not None:
                name = soup.title.string.strip()
                logger.info(f"Name {name} inferred from Project")
                return name
        except Exception:
            pass
    
    return None


def infer_code_from_row(row_data: Dict[str, Any]) -> Optional[str]:
    """Infer code repository URL from row data"""
    if row_data.get("Code") is not None:
        try:
            url = urlparse(row_data["Code"])
            if url.scheme in ["http", "https"] and "github" in url.netloc:
                return row_data["Code"]
        except Exception:
            pass

    # Check if code is in other fields
    for field in ["Project", "Paper", "Model", "Space", "Dataset", "Name"]:
        if row_data.get(field) is not None:
            try:
                url = urlparse(row_data[field])
                if url.scheme in ["http", "https"] and "github.com" in url.netloc:
                    logger.info(f"Code {row_data[field]} inferred from {field}")
                    return row_data[field]
            except Exception:
                pass

    # Try to infer code from project page
    if row_data.get("Project") is not None:
        try:
            r = requests.get(row_data["Project"], timeout=REQUEST_TIMEOUT)
            soup = BeautifulSoup(r.text, "html.parser")
            links = extract_links_from_soup(soup, r.text)
            
            # Filter GitHub links
            github_links = []
            for link in links:
                if link:
                    try:
                        url = urlparse(link)
                        if url.scheme in ["http", "https"] and "github.com" in url.netloc:
                            github_links.append(link)
                    except Exception:
                        pass
            
            if github_links:
                # Extract context keywords from the project page
                context_keywords = []
                if soup.title:
                    context_keywords.extend(soup.title.get_text().split())
                
                # Use URL parts as context
                project_url_parts = row_data["Project"].split('/')
                context_keywords.extend([part for part in project_url_parts if part and len(part) > 2])
                
                best_repo = select_best_github_repo(github_links, context_keywords)
                if best_repo:
                    logger.info(f"Code {best_repo} inferred from Project")
                    return best_repo
        except Exception:
            pass

    # Try scraping HuggingFace paper page for code links
    if row_data.get("Paper") is not None:
        arxiv_id = get_arxiv_id(row_data["Paper"])
        
        # Try scraping HuggingFace paper page
        if "huggingface.co/papers" in row_data["Paper"]:
            resources = scrape_huggingface_paper_page(row_data["Paper"])
            if resources["code"]:
                code_url = resources["code"][0]  # Take first code repo found
                logger.info(f"Code {code_url} inferred from HuggingFace paper page")
                return code_url
        
        # If we have arXiv URL, try the HuggingFace version first
        elif "arxiv.org/abs/" in row_data["Paper"] and arxiv_id:
            hf_paper_url = f"https://huggingface.co/papers/{arxiv_id}"
            resources = scrape_huggingface_paper_page(hf_paper_url)
            if resources["code"]:
                code_url = resources["code"][0]
                logger.info(f"Code {code_url} inferred from HuggingFace paper page (via arXiv)")
                return code_url

    # Fallback: Try GitHub search for papers
    if row_data.get("Paper") is not None and GITHUB_AUTH:
        arxiv_id = get_arxiv_id(row_data["Paper"])
        if arxiv_id:
            try:
                search_endpoint = f"/search/repositories?q={arxiv_id}&sort=stars&order=desc"
                search_response = make_github_request(search_endpoint)
                if search_response:
                    search_results = search_response.json()
                    if "items" in search_results and len(search_results["items"]) > 0:
                        repo = search_results["items"][0]
                        repo_url = repo["html_url"]
                        logger.info(f"Code {repo_url} inferred from Paper (GitHub search)")
                        return repo_url
            except Exception as e:
                logger.warning(f"Failed to infer code from paper: {e}")
    
    return None


def infer_authors_from_row(row_data: Dict[str, Any]) -> List[str]:
    """Infer authors from row data"""
    authors = row_data.get("Authors", [])
    if not isinstance(authors, list):
        authors = []
        
    if row_data.get("Paper") is not None:
        arxiv_id = get_arxiv_id(row_data["Paper"])
        if arxiv_id is not None:
            try:
                search_params = "id_list=" + arxiv_id
                response = feedparser.parse(f"{ARXIV_API_BASE}?" + search_params)
                if response.entries and len(response.entries) > 0:
                    entry = response.entries[0]
                    if hasattr(entry, 'authors'):
                        api_authors = entry.authors
                        for author in api_authors:
                            if author is None or not hasattr(author, "name"):
                                continue
                            if author.name not in authors and author.name != "arXiv api core":
                                authors.append(author.name)
                                logger.info(f"Author {author.name} inferred from Paper")
            except Exception as e:
                logger.warning(f"Failed to fetch authors from arXiv: {e}")

    return authors


def infer_date_from_row(row_data: Dict[str, Any]) -> Optional[str]:
    """Infer publication date from row data"""
    if row_data.get("Paper") is not None:
        arxiv_id = get_arxiv_id(row_data["Paper"])
        if arxiv_id is not None:
            try:
                search_params = "id_list=" + arxiv_id
                response = feedparser.parse(f"{ARXIV_API_BASE}?" + search_params)
                if response.entries and len(response.entries) > 0:
                    entry = response.entries[0]
                    date = getattr(entry, "published", None) or getattr(entry, "updated", None)
                    if date is not None:
                        logger.info(f"Date {date} inferred from Paper")
                        return date
            except Exception as e:
                logger.warning(f"Failed to fetch date from arXiv: {e}")
    
    return None


def infer_model_from_row(row_data: Dict[str, Any]) -> Optional[str]:
    """Infer HuggingFace model from row data by scraping paper page"""
    if row_data.get("Paper") is not None:
        # Try scraping HuggingFace paper page
        if "huggingface.co/papers" in row_data["Paper"]:
            resources = scrape_huggingface_paper_page(row_data["Paper"])
            if resources["models"]:
                model_url = resources["models"][0]  # Take first model found
                logger.info(f"Model {model_url} inferred from HuggingFace paper page")
                return model_url
        
        # If we have arXiv URL, try the HuggingFace version
        elif "arxiv.org/abs/" in row_data["Paper"]:
            arxiv_id = get_arxiv_id(row_data["Paper"])
            if arxiv_id:
                hf_paper_url = f"https://huggingface.co/papers/{arxiv_id}"
                resources = scrape_huggingface_paper_page(hf_paper_url)
                if resources["models"]:
                    model_url = resources["models"][0]
                    logger.info(f"Model {model_url} inferred from HuggingFace paper page (via arXiv)")
                    return model_url
    
    return None


def infer_dataset_from_row(row_data: Dict[str, Any]) -> Optional[str]:
    """Infer HuggingFace dataset from row data by scraping paper page"""
    if row_data.get("Paper") is not None:
        # Try scraping HuggingFace paper page
        if "huggingface.co/papers" in row_data["Paper"]:
            resources = scrape_huggingface_paper_page(row_data["Paper"])
            if resources["datasets"]:
                dataset_url = resources["datasets"][0]  # Take first dataset found
                logger.info(f"Dataset {dataset_url} inferred from HuggingFace paper page")
                return dataset_url
        
        # If we have arXiv URL, try the HuggingFace version
        elif "arxiv.org/abs/" in row_data["Paper"]:
            arxiv_id = get_arxiv_id(row_data["Paper"])
            if arxiv_id:
                hf_paper_url = f"https://huggingface.co/papers/{arxiv_id}"
                resources = scrape_huggingface_paper_page(hf_paper_url)
                if resources["datasets"]:
                    dataset_url = resources["datasets"][0]
                    logger.info(f"Dataset {dataset_url} inferred from HuggingFace paper page (via arXiv)")
                    return dataset_url
    
    return None


def infer_space_from_row(row_data: Dict[str, Any]) -> Optional[str]:
    """Infer HuggingFace space from row data by scraping paper page"""
    if row_data.get("Paper") is not None:
        # Try scraping HuggingFace paper page
        if "huggingface.co/papers" in row_data["Paper"]:
            resources = scrape_huggingface_paper_page(row_data["Paper"])
            if resources["spaces"]:
                space_url = resources["spaces"][0]  # Take first space found
                logger.info(f"Space {space_url} inferred from HuggingFace paper page")
                return space_url
        
        # If we have arXiv URL, try the HuggingFace version
        elif "arxiv.org/abs/" in row_data["Paper"]:
            arxiv_id = get_arxiv_id(row_data["Paper"])
            if arxiv_id:
                hf_paper_url = f"https://huggingface.co/papers/{arxiv_id}"
                resources = scrape_huggingface_paper_page(hf_paper_url)
                if resources["spaces"]:
                    space_url = resources["spaces"][0]
                    logger.info(f"Space {space_url} inferred from HuggingFace paper page (via arXiv)")
                    return space_url
    
    # Fallback: try to infer from model using HF API
    if row_data.get("Model") is not None:
        try:
            model_id = row_data["Model"].split("huggingface.co/")[1]
            url = f"{HUGGINGFACE_API_BASE}/spaces?models=" + model_id
            r = requests.get(url, timeout=REQUEST_TIMEOUT)
            if r.status_code == 200:
                spaces = r.json()
                if len(spaces) > 0:
                    space = spaces[0]["id"]
                    space_url = "https://huggingface.co/spaces/" + space
                    logger.info(f"Space {space} inferred from Model")
                    return space_url
        except Exception as e:
            logger.warning(f"Failed to infer space from model: {e}")
    
    return None


def infer_license_from_row(row_data: Dict[str, Any]) -> Optional[str]:
    """Infer license information from row data"""
    if row_data.get("Code") is not None and GITHUB_AUTH and "github.com" in row_data["Code"]:
        try:
            repo = row_data["Code"].split("github.com/")[1]
            r = make_github_request(f"/repos/{repo}/license")
            if r:
                license_data = r.json()
                if "license" in license_data and license_data["license"] is not None:
                    license_name = license_data["license"]["name"]
                    logger.info(f"License {license_name} inferred from Code")
                    return license_name
        except Exception as e:
            logger.warning(f"Failed to infer license from code: {e}")
    
    return None




def infer_field_type(value: str) -> str:
    """Classify the type of research-related URL or input"""
    if value is None:
        return "Unknown"
    if "arxiv.org/" in value or "huggingface.co/papers" in value or ".pdf" in value:
        return "Paper"
    if "github.com" in value:
        return "Code"
    if "huggingface.co/spaces" in value:
        return "Space"
    if "huggingface.co/datasets" in value:
        return "Dataset"
    if "github.io" in value:
        return "Project"
    if "huggingface.co/" in value:
        try:
            path = value.split("huggingface.co/")[1]
            path_parts = path.strip("/").split("/")
            if len(path_parts) >= 2 and not path.startswith(("spaces/", "datasets/", "papers/")):
                return "Model"
        except (IndexError, AttributeError):
            pass
    return "Unknown"


# MCP tool functions
@rate_limit("mcp_tools")
def infer_authors(input_data: str) -> List[str]:
    """
    Infer authors from research paper or project information.
    
    This tool extracts author names from:
    - arXiv papers (via API)
    - HuggingFace paper pages (via scraping)
    - GitHub repositories (via API when GITHUB_AUTH is set)
    
    Args:
        input_data (str): A URL, paper title, or other research-related input.
                         Examples:
                         - "https://arxiv.org/abs/2103.00020"
                         - "https://huggingface.co/papers/2103.00020"
                         - "https://github.com/openai/CLIP"
        
    Returns:
        List[str]: A list of author names as strings, or empty list if no authors found.
                  Example: ["Alec Radford", "Jong Wook Kim", "Chris Hallacy"]
        
    Raises:
        ValidationError: If input_data is invalid or malformed
        ExternalAPIError: If external API calls fail after retries
    """
    if not input_data or not input_data.strip():
        return []
    
    try:
        cleaned_input = input_data.strip()
        row_data = create_row_data(cleaned_input)
        authors = infer_authors_from_row(row_data)
        
        valid_authors = []
        for author in authors:
            if isinstance(author, str) and len(author.strip()) > 0:
                cleaned_author = author.strip()
                if 2 <= len(cleaned_author) <= 100:
                    valid_authors.append(cleaned_author)
        
        logger.info(f"Successfully inferred {len(valid_authors)} authors from input")
        return valid_authors
        
    except Exception as e:
        logger.error(f"Error inferring authors: {e}")
        return []


@rate_limit("mcp_tools")
def infer_paper_url(input_data: str) -> str:
    """
    Infer the paper URL from various research-related inputs.
    
    This tool finds paper URLs by:
    - Validating existing paper URLs
    - Searching GitHub repositories for paper links
    - Converting between arXiv and HuggingFace paper formats
    - Searching by paper title when provided
    
    Args:
        input_data (str): A URL, repository link, or other research-related input
                         Examples:
                         - "https://github.com/openai/CLIP"
                         - "Vision Transformer"
                         - "https://huggingface.co/spaces/example"
        
    Returns:
        str: The paper URL (typically arXiv or Hugging Face papers), or empty string if not found
             Example: "https://huggingface.co/papers/2103.00020"
    """
    if not input_data or not input_data.strip():
        return ""
    
    try:
        row_data = create_row_data(input_data.strip())
        result = infer_paper_from_row(row_data)
        return result or ""
        
    except Exception as e:
        logger.error(f"Error inferring paper: {e}")
        return ""


@rate_limit("mcp_tools")
def infer_code_repository(input_data: str) -> str:
    """
    Infer the code repository URL from research-related inputs.
    
    This tool discovers code repositories by:
    - Scraping HuggingFace paper pages for GitHub links
    - Searching GitHub for repositories by paper title
    - Extracting repository links from project pages
    
    Args:
        input_data (str): A URL, paper link, or other research-related input
                         Examples:
                         - "https://arxiv.org/abs/2010.11929"
                         - "https://huggingface.co/papers/2010.11929"
                         - "Vision Transformer"
        
    Returns:
        str: The code repository URL (typically GitHub), or empty string if not found
             Example: "https://github.com/google-research/vision_transformer"
    """
    if not input_data or not input_data.strip():
        return ""
    
    try:
        row_data = create_row_data(input_data.strip())
        result = infer_code_from_row(row_data)
        return result or ""
        
    except Exception as e:
        logger.error(f"Error inferring code: {e}")
        return ""


def infer_research_name(input_data: str) -> str:
    """
    Infer the research paper or project name from various inputs.
    
    Args:
        input_data (str): A URL, repository link, or other research-related input
        
    Returns:
        str: The research name/title, or empty string if not found
    """
    if not input_data or not input_data.strip():
        return ""
    
    try:
        row_data = create_row_data(input_data.strip())
        result = infer_name_from_row(row_data)
        return result or ""
        
    except Exception as e:
        logger.error(f"Error inferring name: {e}")
        return ""


@rate_limit("mcp_tools")
def classify_research_url(input_data: str) -> str:
    """
    Classify the type of research-related URL or input.
    
    This tool identifies resource types based on URL patterns:
    - Paper: arXiv, HuggingFace papers, PDF files
    - Code: GitHub repositories
    - Model: HuggingFace model pages
    - Dataset: HuggingFace dataset pages
    - Space: HuggingFace space/demo pages
    - Project: GitHub.io pages
    - Unknown: Unrecognized patterns
    
    Args:
        input_data (str): The URL or input to classify
                         Examples:
                         - "https://arxiv.org/abs/2103.00020" -> "Paper"
                         - "https://github.com/openai/CLIP" -> "Code"
                         - "https://huggingface.co/openai/clip-vit-base-patch32" -> "Model"
        
    Returns:
        str: The field type: "Paper", "Code", "Space", "Model", "Dataset", "Project", or "Unknown"
    """
    if not input_data or not input_data.strip():
        return "Unknown"
    
    try:
        field = infer_field_type(input_data)
        return field if field else "Unknown"
        
    except Exception as e:
        logger.error(f"Error classifying URL: {e}")
        return "Unknown"




def infer_publication_date(input_data: str) -> str:
    """
    Infer publication date from research paper or project information.
    
    Args:
        input_data (str): A URL, paper title, or other research-related input
        
    Returns:
        str: Publication date as string (YYYY-MM-DD format), or empty string if not found
    """
    if not input_data or not input_data.strip():
        return ""
    
    try:
        row_data = create_row_data(input_data.strip())
        result = infer_date_from_row(row_data)
        return result or ""
        
    except Exception as e:
        logger.error(f"Error inferring publication date: {e}")
        return ""


def infer_model(input_data: str) -> str:
    """
    Infer associated HuggingFace model from research paper or project information.
    
    Args:
        input_data (str): A URL, paper title, or other research-related input
        
    Returns:
        str: HuggingFace model URL, or empty string if no model found
    """
    if not input_data or not input_data.strip():
        return ""
    
    try:
        row_data = create_row_data(input_data.strip())
        result = infer_model_from_row(row_data)
        return result or ""
        
    except Exception as e:
        logger.error(f"Error inferring model: {e}")
        return ""


def infer_dataset(input_data: str) -> str:
    """
    Infer associated HuggingFace dataset from research paper or project information.
    
    Args:
        input_data (str): A URL, paper title, or other research-related input
        
    Returns:
        str: HuggingFace dataset URL, or empty string if no dataset found
    """
    if not input_data or not input_data.strip():
        return ""
    
    try:
        row_data = create_row_data(input_data.strip())
        result = infer_dataset_from_row(row_data)
        return result or ""
        
    except Exception as e:
        logger.error(f"Error inferring dataset: {e}")
        return ""


def infer_space(input_data: str) -> str:
    """
    Infer associated HuggingFace space from research paper or project information.
    
    Args:
        input_data (str): A URL, paper title, or other research-related input
        
    Returns:
        str: HuggingFace space URL, or empty string if no space found
    """
    if not input_data or not input_data.strip():
        return ""
    
    try:
        row_data = create_row_data(input_data.strip())
        result = infer_space_from_row(row_data)
        return result or ""
        
    except Exception as e:
        logger.error(f"Error inferring space: {e}")
        return ""


def infer_license(input_data: str) -> str:
    """
    Infer license information from research repository or project.
    
    Args:
        input_data (str): A URL, repository link, or other research-related input
        
    Returns:
        str: License name/type, or empty string if no license found
    """
    if not input_data or not input_data.strip():
        return ""
    
    try:
        row_data = create_row_data(input_data.strip())
        result = infer_license_from_row(row_data)
        return result or ""
        
    except Exception as e:
        logger.error(f"Error inferring license: {e}")
        return ""


def discover_all_urls(input_data: str) -> Dict[str, Any]:
    """
    Discover ALL related URLs from the input by building a complete resource graph.
    This performs multiple rounds of discovery to find all interconnected resources.
    """
    discovered = {
        "paper": None,
        "code": None, 
        "project": None,
        "model": None,
        "dataset": None,
        "space": None,
        "hf_resources": None
    }
    
    # Initialize with input
    row_data = create_row_data(input_data.strip())
    
    # Round 1: Direct inferences from input
    if row_data.get("Paper"):
        discovered["paper"] = row_data["Paper"]
    if row_data.get("Code"):
        discovered["code"] = row_data["Code"]
    if row_data.get("Project"):
        discovered["project"] = row_data["Project"]
    if row_data.get("Model"):
        discovered["model"] = row_data["Model"]
    if row_data.get("Dataset"):
        discovered["dataset"] = row_data["Dataset"]
    if row_data.get("Space"):
        discovered["space"] = row_data["Space"]
    
    # Round 2: Cross-inferences - keep discovering until no new URLs found
    max_rounds = 3
    for round_num in range(max_rounds):
        found_new = False
        
        # Try to find paper from code if we have code but no paper
        if discovered["code"] and not discovered["paper"]:
            temp_row = {"Code": discovered["code"], "Paper": None, "Project": discovered["project"]}
            paper = infer_paper_from_row(temp_row)
            if paper and paper != discovered["paper"]:
                discovered["paper"] = paper
                found_new = True
        
        # Try to find code from paper if we have paper but no code
        if discovered["paper"] and not discovered["code"]:
            temp_row = {"Paper": discovered["paper"], "Code": None, "Project": discovered["project"]}
            code = infer_code_from_row(temp_row)
            if code and code != discovered["code"]:
                discovered["code"] = code
                found_new = True
        
        # Try to find code from project if we have project but no code
        if discovered["project"] and not discovered["code"]:
            temp_row = {"Project": discovered["project"], "Code": None, "Paper": discovered["paper"]}
            code = infer_code_from_row(temp_row)
            if code and code != discovered["code"]:
                discovered["code"] = code
                found_new = True
        
        # Scrape HuggingFace paper page for additional resources
        if discovered["paper"] and not discovered["hf_resources"]:
            arxiv_id = get_arxiv_id(discovered["paper"])
            if "huggingface.co/papers" in discovered["paper"]:
                discovered["hf_resources"] = scrape_huggingface_paper_page(discovered["paper"])
                found_new = True
            elif arxiv_id:
                hf_paper_url = f"https://huggingface.co/papers/{arxiv_id}"
                discovered["hf_resources"] = scrape_huggingface_paper_page(hf_paper_url)
                if discovered["hf_resources"] and any(discovered["hf_resources"].values()):
                    found_new = True
        
        # Extract additional resources from HF scraping
        if discovered["hf_resources"]:
            if not discovered["model"] and discovered["hf_resources"]["models"]:
                discovered["model"] = discovered["hf_resources"]["models"][0]
                found_new = True
            if not discovered["dataset"] and discovered["hf_resources"]["datasets"]:
                discovered["dataset"] = discovered["hf_resources"]["datasets"][0]
                found_new = True
            if not discovered["space"] and discovered["hf_resources"]["spaces"]:
                discovered["space"] = discovered["hf_resources"]["spaces"][0]
                found_new = True
            if not discovered["code"] and discovered["hf_resources"]["code"]:
                discovered["code"] = discovered["hf_resources"]["code"][0]
                found_new = True
        
        if not found_new:
            break
    
    return discovered


@rate_limit("mcp_tools")
def find_research_relationships(input_data: str) -> Dict[str, Any]:
    """
    Find ALL related research resources across platforms for comprehensive analysis.
    Uses a multi-round discovery approach to build a complete resource graph.
    
    This is a comprehensive tool that combines all individual inference tools to provide
    a complete picture of a research project's ecosystem. It discovers:
    - Paper URLs (arXiv, HuggingFace)
    - Code repositories (GitHub)
    - Models, datasets, and demo spaces (HuggingFace)
    - Author information and publication dates
    - License information
    
    Args:
        input_data (str): A URL, paper title, or other research-related input
        
    Returns:
        Dict[str, Any]: Dictionary containing all discovered related resources
    """
    if not input_data or not input_data.strip():
        return {"error": "Input data cannot be empty", "success_count": 0, "total_inferences": 10}
    
    try:
        cleaned_input = input_data.strip()
        logger.info(f"Finding research relationships for: {cleaned_input}")
        
        # Initialize results
        relationships = {
            "paper": None,
            "code": None,
            "name": None,
            "authors": [],
            "date": None,
            "model": None,
            "dataset": None,
            "space": None,
            "license": None,
            "field_type": None,
            "success_count": 0,
            "total_inferences": 10
        }
        
        # Phase 1: Discover all URLs by building complete resource graph
        discovered_urls = discover_all_urls(cleaned_input)
        
        # Phase 2: Create comprehensive row data with all discovered URLs
        complete_row_data = {
            "Name": None,
            "Authors": [],
            "Paper": discovered_urls["paper"],
            "Code": discovered_urls["code"],
            "Project": discovered_urls["project"],
            "Space": discovered_urls["space"],
            "Model": discovered_urls["model"],
            "Dataset": discovered_urls["dataset"],
            "Orgs": [],
            "License": None,
            "Date": None,
        }
        
        # Phase 3: Perform all inferences using complete information
        # Paper
        if complete_row_data["Paper"]:
            relationships["paper"] = complete_row_data["Paper"]
            relationships["success_count"] += 1
        
        # Code
        if complete_row_data["Code"]:
            relationships["code"] = complete_row_data["Code"]
            relationships["success_count"] += 1
        
        # Name inference (try all available sources)
        name = infer_name_from_row(complete_row_data)
        if name:
            relationships["name"] = name
            relationships["success_count"] += 1
        
        # Authors inference
        authors = infer_authors_from_row(complete_row_data)
        if authors:
            relationships["authors"] = authors
            relationships["success_count"] += 1
        
        # Date inference
        date = infer_date_from_row(complete_row_data)
        if date:
            relationships["date"] = date
            relationships["success_count"] += 1
        
        # Model
        if complete_row_data["Model"]:
            relationships["model"] = complete_row_data["Model"]
            relationships["success_count"] += 1
        
        # Dataset
        if complete_row_data["Dataset"]:
            relationships["dataset"] = complete_row_data["Dataset"]
            relationships["success_count"] += 1
        
        # Space
        if complete_row_data["Space"]:
            relationships["space"] = complete_row_data["Space"]
            relationships["success_count"] += 1
        
        # License inference
        license_info = infer_license_from_row(complete_row_data)
        if license_info:
            relationships["license"] = license_info
            relationships["success_count"] += 1
        
        # Field type inference
        field_type = infer_field_type(cleaned_input)
        if field_type and field_type != "Unknown":
            relationships["field_type"] = field_type
            relationships["success_count"] += 1
        
        logger.info(f"Research relationship analysis completed: {relationships['success_count']}/{relationships['total_inferences']} successful")
        return relationships
        
    except Exception as e:
        logger.error(f"Error finding research relationships: {e}")
        return {"error": str(e), "success_count": 0, "total_inferences": 10}


def format_list_output(items):
    """Format list items for display"""
    if not items or not isinstance(items, list):
        return "None"
    return "\n".join([f"β€’ {item}" for item in items])

def process_research_relationships(input_data):
    """Process research input and return formatted results"""
    if not input_data or not input_data.strip():
        return "Please enter a valid URL or research name", "", "", "", "", "", "", "", "", ""
    
    try:
        result = find_research_relationships(input_data.strip())
        
        # Extract individual fields with fallback to empty string
        paper = result.get("paper", "") or ""
        code = result.get("code", "") or ""
        name = result.get("name", "") or ""
        authors = format_list_output(result.get("authors", []))
        date = result.get("date", "") or ""
        model = result.get("model", "") or ""
        dataset = result.get("dataset", "") or ""
        space = result.get("space", "") or ""
        license_info = result.get("license", "") or ""
        field_type = result.get("field_type", "") or ""
        
        return paper, code, name, authors, date, model, dataset, space, license_info, field_type
        
    except Exception as e:
        error_msg = f"Error processing input: {str(e)}"
        return error_msg, "", "", "", "", "", "", "", "", ""

# Create Gradio interface with both UI and MCP tool exposure
with gr.Blocks(title="Research Tracker MCP Server") as demo:
    gr.Markdown("# πŸ”¬ Research Tracker MCP Server")
    gr.Markdown("""
    **MCP Server for AI Research Intelligence** - This interface demonstrates the `find_research_relationships` tool, which combines all available MCP inference tools into a comprehensive analysis.
    
    ## Individual MCP Tools Available:
    Each output field below represents a separate MCP tool that can be used independently:
    - `infer_paper_url` β†’ Paper URL
    - `infer_code_repository` β†’ Code Repository  
    - `infer_research_name` β†’ Research Name
    - `infer_authors` β†’ Authors
    - `infer_publication_date` β†’ Publication Date
    - `infer_model` β†’ HuggingFace Model
    - `infer_dataset` β†’ HuggingFace Dataset
    - `infer_space` β†’ HuggingFace Space
    - `infer_license` β†’ License
    - `classify_research_url` β†’ Field Type
    
    πŸ’‘ **For programmatic access**: Use the "Use via API or MCP" button below to integrate these tools with Claude or other AI assistants.
    """)
    
    with gr.Row():
        with gr.Column():
            input_text = gr.Textbox(
                label="Demo Input",
                placeholder="https://arxiv.org/abs/2506.18787",
                lines=2,
                info="Paper URL, repository URL, or project page"
            )
            submit_btn = gr.Button("πŸ” Demonstrate find_research_relationships", variant="primary")
    
    gr.Markdown("## Research Relationships")
    
    with gr.Row():
        with gr.Column():
            paper_output = gr.Textbox(label="Paper URL", interactive=False)
            code_output = gr.Textbox(label="Code Repository", interactive=False)
            name_output = gr.Textbox(label="Research Name", interactive=False)
            authors_output = gr.Textbox(label="Authors", lines=3, interactive=False)
            
        with gr.Column():
            date_output = gr.Textbox(label="Publication Date", interactive=False)
            model_output = gr.Textbox(label="Hugging Face Model", interactive=False)
            dataset_output = gr.Textbox(label="Hugging Face Dataset", interactive=False)
            
        with gr.Column():
            space_output = gr.Textbox(label="Hugging Face Space", interactive=False)
            license_output = gr.Textbox(label="License", interactive=False)
            field_type_output = gr.Textbox(label="Field Type", interactive=False)
    
    # Connect the interface with examples
    submit_btn.click(
        fn=process_research_relationships,
        inputs=[input_text],
        outputs=[
            paper_output, code_output, name_output, authors_output, 
            date_output, model_output, dataset_output,
            space_output, license_output, field_type_output
        ]
    )
    
    # Add examples using Gradio's built-in system
    gr.Examples(
        examples=[
            ["https://arxiv.org/abs/2506.18787"],
            ["https://huggingface.co/papers/2010.11929"],
            ["https://github.com/facebookresearch/segment-anything"],
            ["https://microsoft.github.io/TRELLIS/"]
        ],
        inputs=[input_text],
        outputs=[
            paper_output, code_output, name_output, authors_output, 
            date_output, model_output, dataset_output,
            space_output, license_output, field_type_output
        ],
        fn=process_research_relationships,
        cache_examples=False,
        label="Example Inputs"
    )
    
    # Also trigger on Enter key
    input_text.submit(
        fn=process_research_relationships,
        inputs=[input_text],
        outputs=[
            paper_output, code_output, name_output, authors_output, 
            date_output, model_output, dataset_output,
            space_output, license_output, field_type_output
        ]
    )
    
    # Expose all core functions as MCP tools
    gr.api(infer_authors)
    gr.api(infer_paper_url)
    gr.api(infer_code_repository)
    gr.api(infer_research_name)
    gr.api(classify_research_url)
    gr.api(infer_publication_date)
    gr.api(infer_model)
    gr.api(infer_dataset)
    gr.api(infer_space)
    gr.api(infer_license)
    gr.api(find_research_relationships)


if __name__ == "__main__":
    logger.info("Starting Research Tracker MCP Server")
    demo.launch(mcp_server=True, share=False)