File size: 32,136 Bytes
e6c3213
 
6279b2d
e6c3213
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6279b2d
 
 
 
 
 
 
 
e6c3213
 
 
 
6279b2d
 
 
 
 
 
 
 
 
 
 
 
 
e6c3213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6279b2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c3213
6279b2d
e6c3213
 
 
6279b2d
 
e6c3213
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
6279b2d
e6c3213
 
 
 
 
6279b2d
e6c3213
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
6279b2d
 
 
 
 
 
 
 
 
e6c3213
 
 
 
 
6279b2d
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c3213
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
6279b2d
e6c3213
 
 
6279b2d
e6c3213
 
 
 
 
6279b2d
e6c3213
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
 
 
6279b2d
e6c3213
6279b2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c3213
6279b2d
e6c3213
 
 
 
6279b2d
 
e6c3213
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
 
 
 
 
 
6279b2d
e6c3213
 
 
6279b2d
e6c3213
 
 
 
 
6279b2d
e6c3213
 
 
 
6279b2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c3213
6279b2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e984de
6279b2d
 
 
 
 
 
4e984de
 
6279b2d
 
 
 
 
 
4e984de
6279b2d
 
4e984de
 
 
6279b2d
 
 
 
e6c3213
 
6279b2d
 
 
 
 
 
e6c3213
190b5c5
 
4e984de
eca2420
4e984de
 
 
 
 
 
 
 
eca2420
 
 
 
 
 
 
 
 
 
 
e6c3213
190b5c5
 
4e984de
190b5c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e984de
 
 
 
190b5c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e984de
 
190b5c5
4e984de
 
 
 
 
 
 
 
190b5c5
 
4e984de
 
 
 
 
 
 
 
 
 
 
190b5c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e984de
190b5c5
 
 
4e984de
190b5c5
 
 
 
 
 
 
 
 
 
 
 
4e984de
190b5c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c3213
 
 
 
 
6279b2d
e6c3213
 
6279b2d
e6c3213
 
 
6279b2d
 
 
 
e6c3213
 
 
6279b2d
e6c3213
 
 
 
 
 
6279b2d
 
e6c3213
 
6279b2d
e6c3213
 
6279b2d
e6c3213
 
 
6279b2d
 
 
 
e6c3213
 
 
6279b2d
e6c3213
6279b2d
e6c3213
6279b2d
e6c3213
 
6279b2d
 
e6c3213
 
 
 
6279b2d
e6c3213
 
 
6279b2d
 
 
e6c3213
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests
from typing import List, Dict
from huggingface_hub import HfApi
import os
from dotenv import load_dotenv
from pinecone import Pinecone
from openai import OpenAI
import re

# Load environment variables
load_dotenv()

# Initialize HF API with token if available
HF_TOKEN = os.getenv("HF_TOKEN")
api = HfApi(token=HF_TOKEN) if HF_TOKEN else HfApi()

def keyword_search_hf_spaces(query: str = "", limit: int = 3) -> Dict:
    """
    Search for MCPs in Hugging Face Spaces.
    
    Args:
        query: Search query string
        limit: Maximum number of results to return (default: 3)
        
    Returns:
        Dictionary containing search results with MCP information
    """
    try:
        # Use list_spaces API with mcp-server filter and sort by likes
        spaces = list(api.list_spaces(
            search=query,
            sort="likes",
            direction=-1,  # Descending order
            filter="mcp-server"
        ))
        
        results = []
        for space in spaces[:limit]:  # Process up to limit matches
            try:
                # Convert space ID to URL format - replace all special chars with hyphens
                space_id_lower = re.sub(r'[^a-z0-9]', '-', space.id.lower())
                # Remove consecutive hyphens
                space_id_lower = re.sub(r'-+', '-', space_id_lower)
                # Remove leading and trailing hyphens
                space_id_lower = space_id_lower.strip('-')
                sse_url = f"https://{space_id_lower}.hf.space/gradio_api/mcp/sse"
                
                space_info = {
                    "id": space.id,
                    "likes": space.likes,
                    "trending_score": space.trending_score,
                    "source": "huggingface",
                    "configuration": {
                                "gradio": {
                                    "command": "npx",  # Use npx to run MCP-Remote
                                    "args": [
                                        "mcp-remote",
                                        sse_url,
                                        "--transport",
                                        "sse-only"
                                    ]
                                }
                            }
                        }
                results.append(space_info)
            except Exception as e:
                continue
        
        return {
            "results": results,
            "total": len(results)
        }
    except Exception as e:
        return {
            "error": str(e),
            "results": [],
            "total": 0
        }

def keyword_search_smithery(query: str = "", limit: int = 3, os_type: str = "Mac/Linux") -> Dict:
    """
    Search for MCPs in Smithery Registry.
    
    Args:
        query: Search query string
        limit: Maximum number of results to return (default: 3)
        os_type: Operating system type ("Mac/Linux", "Windows", "WSL")
        
    Returns:
        Dictionary containing search results with MCP information
    """
    try:
        # Get Smithery token from environment
        SMITHERY_TOKEN = os.getenv("SMITHERY_TOKEN")
        if not SMITHERY_TOKEN:
            return {
                "error": "SMITHERY_TOKEN not found",
                "results": [],
                "total": 0
            }
        
        # Prepare headers and query parameters
        headers = {
            'Authorization': f'Bearer {SMITHERY_TOKEN}'
        }
        
        # Add filters for deployed and verified servers
        search_query = f"{query} is:deployed"
        
        params = {
            'q': search_query,
            'page': 1,
            'pageSize': 100  # Get maximum results
        }
        
        # Make API request
        response = requests.get(
            'https://registry.smithery.ai/servers',
            headers=headers,
            params=params
        )
        
        if response.status_code != 200:
            return {
                "error": f"Smithery API error: {response.status_code}",
                "results": [],
                "total": 0
            }
        
        # Parse response
        data = response.json()
        results = []
        
        # Sort servers by useCount and take top results up to limit
        servers = sorted(data.get('servers', []), key=lambda x: x.get('useCount', 0), reverse=True)[:limit]
        
        for server in servers:
            server_id = server.get('qualifiedName')
            # Extract server ID without @author/ prefix for configuration
            config_server_id = server_id.split('/')[-1] if '/' in server_id else server_id
            
            # Create configuration based on OS type
            if os_type == "Mac/Linux":
                configuration = {
                        f"{config_server_id}": {
                            "command": "npx",
                            "args": [
                                "-y",
                                "@smithery/cli@latest",
                                "run",
                                f"{server_id}",
                                "--key",
                                "YOUR_SMITHERY_KEY"
                            ]
                        }
                    }
            elif os_type == "Windows":
                configuration = {
                        f"{config_server_id}": {
                            "command": "cmd",
                            "args": [
                                "/c",
                                "npx",
                                "-y",
                                "@smithery/cli@latest",
                                "run",
                                f"{server_id}",
                                "--key",
                                "YOUR_SMITHERY_KEY"
                            ]
                        }
                    }
            elif os_type == "WSL":
                configuration = {
                        f"{config_server_id}": {
                            "command": "wsl",
                            "args": [
                                "npx",
                                "-y",
                                "@smithery/cli@latest",
                                "run",
                                f"{server_id}",
                                "--key",
                                "YOUR_SMITHERY_KEY"
                            ]
                        }
                    }
            
            server_info = {
                "id": server_id,
                "name": server.get('displayName'),
                "description": server.get('description'),
                "likes": server.get('useCount', 0),
                "source": "smithery",
                "configuration": configuration
            }
            
            results.append(server_info)
        
        return {
            "results": results,
            "total": len(results)
        }
        
    except Exception as e:
        return {
            "error": str(e),
            "results": [],
            "total": 0
        }

def keyword_search(query: str, sources: List[str], limit: int = 3, os_type: str = "Mac/Linux") -> Dict:
    """
    Search for MCPs using keyword matching.
    
    Args:
        query: Keyword search query
        sources: List of sources to search from ('huggingface', 'smithery')
        limit: Maximum number of results to return (default: 3)
        os_type: Operating system type ("Mac/Linux", "Windows", "WSL")
        
    Returns:
        Dictionary containing combined search results
    """
    all_results = []
    
    if "huggingface" in sources:
        hf_results = keyword_search_hf_spaces(query, limit)
        all_results.extend(hf_results.get("results", []))
    
    if "smithery" in sources:
        smithery_results = keyword_search_smithery(query, limit, os_type)
        all_results.extend(smithery_results.get("results", []))
    
    return {
        "results": all_results,
        "total": len(all_results),
        "search_type": "keyword"
    }

def semantic_search_hf_spaces(query: str = "", limit: int = 3) -> Dict:
    """
    Search for MCPs in Hugging Face Spaces using semantic embedding matching.
    
    Args:
        query: Natural language search query
        limit: Maximum number of results to return (default: 3)
        
    Returns:
        Dictionary containing search results with MCP information
    """
    try:
        pinecone_api_key = os.getenv('PINECONE_API_KEY')
        openai_api_key = os.getenv('OPENAI_API_KEY')
        if not pinecone_api_key or not openai_api_key:
            return {
                "error": "API keys not found",
                "results": [],
                "total": 0
            }
        
        pc = Pinecone(api_key=pinecone_api_key)
        index = pc.Index("hf-mcp")
        client = OpenAI(api_key=openai_api_key)
        
        response = client.embeddings.create(
            input=query,
            model="text-embedding-3-large"
        )
        query_embedding = response.data[0].embedding
        
        results = index.query(
            namespace="",
            vector=query_embedding,
            top_k=limit
        )
        
        space_results = []
        if not results.matches:
            return {
                "results": [],
                "total": 0
            }
            
        for match in results.matches:
            space_id = match.id
            try:
                repo_id = space_id.replace('spaces/', '')
                space = api.space_info(repo_id)
                
                # Convert space ID to URL format - replace all special chars with hyphens
                space_id_lower = re.sub(r'[^a-z0-9]', '-', space.id.lower())
                # Remove consecutive hyphens
                space_id_lower = re.sub(r'-+', '-', space_id_lower)
                # Remove leading and trailing hyphens
                space_id_lower = space_id_lower.strip('-')
                sse_url = f"https://{space_id_lower}.hf.space/gradio_api/mcp/sse"
                
                space_info = {
                    "id": space.id,
                    "likes": space.likes,
                    "trending_score": space.trending_score,
                    "source": "huggingface",
                    "score": match.score,
                    "configuration": {
                        "mcpServers": {
                            "gradio": {
                                "command": "npx",
                                "args": [
                                    "mcp-remote",
                                    sse_url,
                                    "--transport",
                                    "sse-only"
                                ]
                            }
                        }
                    }
                }
                space_results.append(space_info)
            except Exception as e:
                continue
                
        return {
            "results": space_results,
            "total": len(space_results)
        }
    except Exception as e:
        return {
            "error": str(e),
            "results": [],
            "total": 0
        }

def semantic_search_smithery(query: str = "", limit: int = 3, os_type: str = "Mac/Linux") -> Dict:
    """
    Search for MCPs in Smithery Registry using semantic embedding matching.
    
    Args:
        query: Natural language search query
        limit: Maximum number of results to return (default: 3)
        os_type: Operating system type ("Mac/Linux", "Windows", "WSL")
        
    Returns:
        Dictionary containing search results with MCP information
    """
    try:
        from pinecone import Pinecone
        from openai import OpenAI
        import os
        
        pinecone_api_key = os.getenv('PINECONE_API_KEY')
        openai_api_key = os.getenv('OPENAI_API_KEY')
        smithery_token = os.getenv('SMITHERY_TOKEN')
        
        if not pinecone_api_key or not openai_api_key or not smithery_token:
            return {
                "error": "API keys not found",
                "results": [],
                "total": 0
            }
            
        pc = Pinecone(api_key=pinecone_api_key)
        index = pc.Index("smithery-mcp")
        client = OpenAI(api_key=openai_api_key)
        
        response = client.embeddings.create(
            input=query,
            model="text-embedding-3-large"
        )
        query_embedding = response.data[0].embedding
        
        results = index.query(
            namespace="",
            vector=query_embedding,
            top_k=limit
        )
        
        server_results = []
        if not results.matches:
            return {
                "results": [],
                "total": 0
            }
            
        headers = {
            'Authorization': f'Bearer {smithery_token}'
        }
        
        for match in results.matches:
            server_id = match.id
            try:
                response = requests.get(
                    f'https://registry.smithery.ai/servers/{server_id}',
                    headers=headers
                )
                if response.status_code != 200:
                    continue
                    
                server = response.json()
                
                # Extract server ID without @author/ prefix for configuration
                config_server_id = server_id.split('/')[-1] if '/' in server_id else server_id
                
                # Create configuration based on OS type
                if os_type == "Mac/Linux":
                    configuration = {
                            f"{config_server_id}": {
                                "command": "npx",
                                "args": [
                                    "-y",
                                    "@smithery/cli@latest",
                                    "run",
                                    f"{server_id}",
                                    "--key",
                                    "YOUR_SMITHERY_KEY"
                                ]
                            }
                        }
                elif os_type == "Windows":
                    configuration = {
                            f"{config_server_id}": {
                                "command": "cmd",
                                "args": [
                                    "/c",
                                    "npx",
                                    "-y",
                                    "@smithery/cli@latest",
                                    "run",
                                    f"{server_id}",
                                    "--key",
                                    "YOUR_SMITHERY_KEY"
                                ]
                            }
                        }
                elif os_type == "WSL":
                    configuration = {
                            f"{config_server_id}": {
                                "command": "wsl",
                                "args": [
                                    "npx",
                                    "-y",
                                    "@smithery/cli@latest",
                                    "run",
                                    f"{server_id}",
                                    "--key",
                                    "YOUR_SMITHERY_KEY"
                                ]
                            }
                        }
                
                server_info = {
                    "id": server_id,
                    "name": server.get('displayName'),
                    "description": server.get('description'),
                    "likes": server.get('useCount', 0),
                    "source": "smithery",
                    "score": match.score,
                    "configuration": configuration
                }
                server_results.append(server_info)
            except Exception as e:
                continue
                
        return {
            "results": server_results,
            "total": len(server_results)
        }
    except Exception as e:
        return {
            "error": str(e),
            "results": [],
            "total": 0
        }

def semantic_search(query: str, sources: List[str], limit: int = 3, os_type: str = "Mac/Linux") -> Dict:
    """
    Search for MCPs using semantic embedding matching.
    
    Args:
        query: Natural language search query
        sources: List of sources to search from ('huggingface', 'smithery')
        limit: Maximum number of results to return (default: 3)
        os_type: Operating system type ("Mac/Linux", "Windows", "WSL")
        
    Returns:
        Dictionary containing combined search results
    """
    all_results = []
    
    if "huggingface" in sources:
        try:
            hf_results = semantic_search_hf_spaces(query, limit)
            all_results.extend(hf_results.get("results", []))
        except Exception as e:
            # Fallback to keyword search if vector search fails
            hf_results = keyword_search_hf_spaces(query, limit)
            all_results.extend(hf_results.get("results", []))
    
    if "smithery" in sources:
        try:
            smithery_results = semantic_search_smithery(query, limit, os_type)
            all_results.extend(smithery_results.get("results", []))
        except Exception as e:
            # Fallback to keyword search if vector search fails
            smithery_results = keyword_search_smithery(query, limit, os_type)
            all_results.extend(smithery_results.get("results", []))
    
    return {
        "results": all_results,
        "total": len(all_results),
        "search_type": "semantic"
    }

# Create the Gradio interface
with gr.Blocks(title="🚦 Router MCP", css="""
    /* Make JSON output expanded by default */
    .json-viewer-container {
        display: block !important;
    }
    .json-viewer-container > .json-viewer-header {
        display: none !important;
    }
    .json-viewer-container > .json-viewer-content {
        display: block !important;
        max-height: none !important;
    }
    .json-viewer-container .json-viewer-item {
        display: block !important;
    }
    .json-viewer-container .json-viewer-item > .json-viewer-header {
        display: none !important;
    }
    .json-viewer-container .json-viewer-item > .json-viewer-content {
        display: block !important;
        max-height: none !important;
    }
    /* Additional selectors for nested items */
    .json-viewer-container .json-viewer-item .json-viewer-item {
        display: block !important;
    }
    .json-viewer-container .json-viewer-item .json-viewer-item > .json-viewer-header {
        display: none !important;
    }
    .json-viewer-container .json-viewer-item .json-viewer-item > .json-viewer-content {
        display: block !important;
        max-height: none !important;
    }
    /* Title styling */
    .title-container {
        text-align: center;
        margin: 0.5rem 0;
        position: relative;
        padding: 0.5rem 0;
        overflow: hidden;
    }
    .title-container h1 {
        display: inline-block;
        position: relative;
        z-index: 1;
        font-size: 1.8rem;
        margin: 0;
        line-height: 1.2;
        color: var(--body-text-color);
    }
    .title-container p {
        position: relative;
        z-index: 1;
        font-size: 1rem;
        margin: 0.5rem 0 0 0;
        color: var(--body-text-color);
        opacity: 0.8;
    }
    .traffic-light {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 500px;
        height: 40px;
        background: linear-gradient(90deg, 
            rgba(255, 0, 0, 0.2) 0%,
            rgba(255, 165, 0, 0.2) 50%,
            rgba(0, 255, 0, 0.2) 100%
        );
        border-radius: 20px;
        z-index: 0;
        filter: blur(20px);
    }
""") as demo:
    with gr.Column(elem_classes=["title-container"]):
        gr.HTML('''
            <div class="traffic-light"></div>
            <h1>🚦 Router MCP</h1>
            <p>Your Gateway to Optimal MCP Servers in Seconds</p>
        ''')
    
    with gr.Tabs() as tabs:
        with gr.Tab("Overview"):
            gr.Markdown("""
            <span style="font-size: 1.15em"> Router MCP is a powerful tool that helps you discover and connect to MCP servers.
            Whether you're looking for specific functionality or exploring new possibilities, 
            Router MCP makes it easy to find the perfect MCP server for your needs.</span>
            """)
            
            gr.Markdown("""
            ## πŸŽ₯ Video Demo
            """)
            
            with gr.Row():
                with gr.Column():
                    gr.Video(
                        value="demo.mp4",
                        label="Router MCP Demo Video",
                        interactive=False,
                        width=640
                    )
                with gr.Column():
                    pass
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("""
                    ## 🎯 How to Use Router MCP

                    1. **Enter Your Query**
                       - Type a natural language description of the MCP Server you're looking for
                       - Be as specific or general as you need

                    2. **Select Search Sources**
                       - Choose where to search for MCP Servers
                       - Currently supports Hugging Face Spaces and Smithery
                       - Note: Anthropic's Registry is under development and not yet available

                    3. **Choose Your OS**
                       - Select your operating system (Mac/Linux, Windows, or WSL)
                       - This ensures you get the correct configuration format for your system

                    4. **Choose Search Type**
                       - **Keyword Search**: Use when you have specific terms or names in mind
                       - **Semantic Search**: Use when you want to find servers based on meaning and intent
                       - Both methods will return ready-to-use MCP configurations
                    """)
                with gr.Column():
                    gr.Markdown("""
                    ## πŸ“Š Understanding Search Results

                    The search results will show MCP Servers from different sources, each with their own format:

                    #### Hugging Face Spaces Results
                    - **id**: The Space's unique identifier
                    - **likes**: Number of likes the Space has received
                    - **trending_score**: The Space's popularity score
                    - **source**: Always "huggingface"
                    - **configuration**: Ready-to-use MCP configuration for SSE connection

                    #### Smithery Results
                    - **id**: The server's qualified name (e.g., "author/server-name")
                    - **name**: Display name of the server
                    - **description**: Detailed description of the server's capabilities
                    - **likes**: Number of times the server has been used
                    - **source**: Always "smithery"
                    - **configuration**: OS-specific MCP configuration (requires your Smithery key)

                    > Note: For Smithery servers, you'll need to replace "YOUR_SMITHERY_KEY" in the configuration with your actual Smithery API key.

                    > Note: When using Semantic Search, each result includes a similarity score (0-1) that indicates how well the server matches your query's meaning. Higher scores (closer to 1) indicate better semantic matches.
                    """)
            
            gr.Markdown("""
            ## πŸš€ Upcoming Features

            We're constantly working to improve Router MCP. Here's what's coming soon:
            """)
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("""
                    #### πŸ”„ Enhanced Integration
                    - Integration with Anthropic's Registry for comprehensive MCP server discovery
                    - Complete support for Smithery search capabilities
                    - Enhanced server discovery with improved filtering and sorting options
                    """)
                with gr.Column():
                    gr.Markdown("""
                    #### ⚑️ Automated Setup
                    - One-click MCP server addition to your client
                    - Automatic configuration generation and validation
                    - Seamless integration with popular MCP clients
                    """)

        with gr.Tab("Try Router MCP"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Search MCP servers using natural language query")
                    query_input = gr.Textbox(
                        label="Describe the MCP Server you're looking for",
                        placeholder="e.g., 'I need an MCP Server that can generate images'"
                    )
                    
                    gr.Markdown("### Select sources to search")
                    hf_checkbox = gr.Checkbox(label="Hugging Face Spaces", value=True)
                    smithery_checkbox = gr.Checkbox(label="Smithery", value=False)
                    registry_checkbox = gr.Checkbox(label="Registry (Coming Soon)", value=False, interactive=False)
                    
                    result_limit = gr.Number(
                        label="Maximum number of results for each source",
                        value=3,
                        minimum=1,
                        maximum=20,
                        step=1
                    )
                    
                    gr.Markdown("### Select your OS")
                    client_radio = gr.Radio(
                        choices=["Mac/Linux", "Windows", "WSL"],
                        label="Choose your operating system to get the appropriate command format",
                        value="Mac/Linux",
                        interactive=True,
                        elem_id="client_radio"
                    )
                    
                    with gr.Row():
                        keyword_search_button = gr.Button("Keyword Search")
                        semantic_search_button = gr.Button("Semantic Search")
                
                with gr.Column():
                    results_output = gr.JSON(
                        label="Search Results",
                        elem_id="results_output"
                    )

        with gr.Tab("How to Integrate"):
            gr.Markdown("""
            ## Integration Guide

            To integrate Router MCP with your preferred client, follow these instructions:

            ### For SSE-Supported Clients
            For clients that support SSE (e.g., Cursor, Windsurf, Cline), add this configuration to your MCP config:

            ```json
            {
              "mcpServers": {
                "gradio": {
                  "url": "https://agents-mcp-hackathon-router-mcp.hf.space/gradio_api/mcp/sse"
                }
              }
            }
            ```

            ### For stdio-Only Clients
            For clients that only support stdio (e.g., Claude Desktop):
            1. First, install Node.js
            2. Add this configuration to your MCP config:

            ```json
            {
              "mcpServers": {
                "gradio": {
                  "command": "npx",
                  "args": [
                    "mcp-remote",
                    "https://agents-mcp-hackathon-router-mcp.hf.space/gradio_api/mcp/sse",
                    "--transport",
                    "sse-only"
                  ]
                }
              }
            }
            ```

            For more information about MCP, check out the [Gradio documentation](https://gradio.app/docs/mcp).
            """)
    
    # Set up event handlers
    def get_sources():
        return ["huggingface" if hf_checkbox.value else "", "smithery" if smithery_checkbox.value else ""]
    
    def handle_keyword_mcp_search(query: str, hf: bool, sm: bool, limit: int, os_type: str) -> Dict:
        """
        Handle keyword-based search for MCP servers across selected sources. If the client (such as Cursor or Claude) encounters a task it cannot handle, it can use MCP to search for other tools that can.
        Use this search when you know the specific name or keywords of the MCP Server you're looking for.

        Args:
            query (str): The search query string to find matching MCP servers
            hf (bool): Whether to include Hugging Face Spaces in the search
            sm (bool): Whether to include Smithery in the search
            limit (int): Maximum number of results to return per source
            os_type (str): Operating system type ("Mac/Linux", "Windows", "WSL")

        Returns:
            Dict: A dictionary containing the search results with the following keys:
                - results: List of found MCP servers with their configurations. Each configuration can be added to the MCP Client's config file to register the server.
                - total: Total number of results
                - search_type: Type of search performed ("keyword")
        """
        return keyword_search(
            query,
            ["huggingface" if hf else "", "smithery" if sm else ""],
            int(limit),
            os_type
        )
    
    def handle_semantic_mcp_search(query: str, hf: bool, sm: bool, limit: int, os_type: str) -> Dict:
        """
        Handle semantic embedding-based search for MCP servers across selected sources. If the client (such as Cursor or Claude) encounters a task it cannot handle, it can use MCP to search for other tools that can.
        Use this search when your query is more abstract or conceptual, as it can understand the meaning and context of your request.

        Args:
            query (str): The natural language search query to find semantically similar MCP servers
            hf (bool): Whether to include Hugging Face Spaces in the search
            sm (bool): Whether to include Smithery in the search
            limit (int): Maximum number of results to return per source
            os_type (str): Operating system type ("Mac/Linux", "Windows", "WSL")

        Returns:
            Dict: A dictionary containing the search results with the following keys:
                - results: List of found MCP servers with their configurations and similarity scores. Each configuration can be added to the MCP Client's config file to register the server.
                - total: Total number of results
                - search_type: Type of search performed ("semantic")
        """
        return semantic_search(
            query,
            ["huggingface" if hf else "", "smithery" if sm else ""],
            int(limit),
            os_type
        )
    
    keyword_search_button.click(
        fn=handle_keyword_mcp_search,
        inputs=[query_input, hf_checkbox, smithery_checkbox, result_limit, client_radio],
        outputs=results_output
    )
    
    semantic_search_button.click(
        fn=handle_semantic_mcp_search,
        inputs=[query_input, hf_checkbox, smithery_checkbox, result_limit, client_radio],
        outputs=results_output
    )
    
    # query_input.submit(
    #     fn=handle_embedding_search,
    #     inputs=[query_input, hf_checkbox, smithery_checkbox, result_limit],
    #     outputs=results_output
    # )

if __name__ == "__main__":
    demo.launch(mcp_server=True)