Spaces:
Sleeping
Sleeping
File size: 28,599 Bytes
29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 82ae865 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 82ae865 aab630b 518eab8 29c4a42 518eab8 82ae865 29c4a42 82ae865 29c4a42 518eab8 29c4a42 518eab8 82ae865 aab630b 82ae865 29c4a42 82ae865 29c4a42 aab630b 2ae13c5 aab630b 29c4a42 aab630b 29c4a42 aab630b 82ae865 aab630b 82ae865 aab630b 82ae865 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 82ae865 aab630b 82ae865 29c4a42 82ae865 655a6c3 29c4a42 82ae865 29c4a42 82ae865 761f837 82ae865 aab630b 82ae865 29c4a42 655a6c3 82ae865 29c4a42 aab630b 82ae865 aab630b 82ae865 29c4a42 aab630b 82ae865 29c4a42 82ae865 aab630b 82ae865 29c4a42 aab630b 82ae865 655a6c3 82ae865 655a6c3 82ae865 aab630b 82ae865 655a6c3 82ae865 aab630b 82ae865 aab630b 82ae865 aab630b 82ae865 29c4a42 82ae865 29c4a42 82ae865 29c4a42 82ae865 aab630b 82ae865 aab630b 82ae865 aab630b 29c4a42 82ae865 aab630b 82ae865 aab630b 82ae865 aab630b 82ae865 aab630b 29c4a42 aab630b 82ae865 aab630b 82ae865 aab630b 82ae865 aab630b 82ae865 aab630b 82ae865 29c4a42 82ae865 29c4a42 518eab8 82ae865 29c4a42 518eab8 82ae865 655a6c3 82ae865 29c4a42 518eab8 82ae865 29c4a42 518eab8 29c4a42 518eab8 29c4a42 82ae865 aab630b 82ae865 aab630b 82ae865 aab630b 82ae865 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 82ae865 aab630b 82ae865 aab630b 29c4a42 82ae865 29c4a42 82ae865 655a6c3 82ae865 29c4a42 82ae865 29c4a42 518eab8 29c4a42 518eab8 655a6c3 29c4a42 82ae865 518eab8 655a6c3 518eab8 655a6c3 82ae865 518eab8 655a6c3 82ae865 655a6c3 518eab8 29c4a42 82ae865 29c4a42 518eab8 82ae865 518eab8 9dc9aa6 518eab8 9dc9aa6 518eab8 |
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 |
# app.py - Gradio MCP Playground for HF Spaces
import gradio as gr
import json
import os
from datetime import datetime
from typing import Dict, List, Optional, Tuple, Any
import uuid
import asyncio
import time
import subprocess
import sys
from pathlib import Path
import tempfile
import shutil
# Configuration
HF_SPACE_MODE = True
HF_SPACE_ID = os.getenv("SPACE_ID", "Agents-MCP-Hackathon/gradio-mcp-playground")
class MCPPlaygroundApp:
"""Gradio MCP Playground - Functional demo for HF Spaces"""
def __init__(self):
self.sessions = {}
self.templates = self.load_templates()
self.active_servers = {}
def load_templates(self) -> List[Dict]:
"""Load available MCP server templates"""
return [
{
"name": "Calculator",
"id": "calculator",
"description": "Basic arithmetic operations server",
"code": '''import json
import sys
class CalculatorServer:
def handle_add(self, a, b):
return {"result": a + b}
def handle_subtract(self, a, b):
return {"result": a - b}
def handle_multiply(self, a, b):
return {"result": a * b}
def handle_divide(self, a, b):
if b == 0:
return {"error": "Division by zero"}
return {"result": a / b}
# Simple stdin/stdout handler
server = CalculatorServer()
while True:
try:
line = sys.stdin.readline()
if not line:
break
request = json.loads(line)
method = request.get("method", "")
params = request.get("params", {})
if method == "add":
result = server.handle_add(params.get("a", 0), params.get("b", 0))
elif method == "subtract":
result = server.handle_subtract(params.get("a", 0), params.get("b", 0))
elif method == "multiply":
result = server.handle_multiply(params.get("a", 0), params.get("b", 0))
elif method == "divide":
result = server.handle_divide(params.get("a", 0), params.get("b", 1))
else:
result = {"error": f"Unknown method: {method}"}
response = {"id": request.get("id"), "result": result}
print(json.dumps(response))
sys.stdout.flush()
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.stdout.flush()
'''
},
{
"name": "Text Processor",
"id": "text_processor",
"description": "Text manipulation and analysis",
"code": '''import json
import sys
class TextProcessor:
def count_words(self, text):
return {"count": len(text.split())}
def reverse_text(self, text):
return {"reversed": text[::-1]}
def to_uppercase(self, text):
return {"uppercase": text.upper()}
def to_lowercase(self, text):
return {"lowercase": text.lower()}
# Simple stdin/stdout handler
processor = TextProcessor()
while True:
try:
line = sys.stdin.readline()
if not line:
break
request = json.loads(line)
method = request.get("method", "")
params = request.get("params", {})
text = params.get("text", "")
if method == "count_words":
result = processor.count_words(text)
elif method == "reverse":
result = processor.reverse_text(text)
elif method == "uppercase":
result = processor.to_uppercase(text)
elif method == "lowercase":
result = processor.to_lowercase(text)
else:
result = {"error": f"Unknown method: {method}"}
response = {"id": request.get("id"), "result": result}
print(json.dumps(response))
sys.stdout.flush()
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.stdout.flush()
'''
},
{
"name": "Echo Server",
"id": "echo",
"description": "Simple echo server for testing",
"code": '''import json
import sys
import datetime
# Simple echo server
while True:
try:
line = sys.stdin.readline()
if not line:
break
request = json.loads(line)
response = {
"id": request.get("id"),
"result": {
"echo": request,
"timestamp": datetime.datetime.now().isoformat(),
"server": "echo-server-v1"
}
}
print(json.dumps(response))
sys.stdout.flush()
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.stdout.flush()
'''
}
]
def create_interface(self) -> gr.Blocks:
"""Create the Gradio interface"""
with gr.Blocks(
title="π Gradio MCP Playground",
theme=gr.themes.Soft(
primary_hue="blue",
secondary_hue="gray",
font=["Inter", "system-ui", "sans-serif"]
),
css=self.get_custom_css()
) as demo:
# Header with GitHub banner
gr.HTML("""
<div class="github-banner">
<a href="https://github.com/seanpoyner/gradio-mcp-playground" target="_blank">
π¦ For full functionality, install from GitHub - Free & Open Source!
</a>
</div>
""")
gr.Markdown("""
# π Gradio MCP Playground
**Open-source access to MCP tools without expensive LLM subscriptions**
Build, test, and deploy Model Context Protocol (MCP) servers directly in your browser.
This demo showcases the core features - install locally for full functionality.
""")
# Session state
session_id = gr.State(value=lambda: str(uuid.uuid4()))
with gr.Tabs() as main_tabs:
# Tab 1: AI Assistant
with gr.Tab("π AI Assistant"):
gr.Markdown("### Choose Your AI Assistant")
assistant_mode = gr.Radio(
choices=["General Assistant", "MCP Development", "Agent Builder"],
value="General Assistant",
label="Select Mode"
)
# General Assistant Mode
with gr.Group(visible=True) as general_assistant_group:
gr.Markdown("### Adam - General Assistant [DEMO]")
gr.Markdown(
"In the full version, Adam has access to all connected MCP tools and can help with any task. "
"This demo shows a simulated conversation."
)
# Demo chat interface
demo_chatbot = gr.Chatbot(
label="Chat with Adam [DEMO]",
height=500,
value=[
[None, "π Hello! I'm Adam, your general-purpose assistant. In the full version, I have access to MCP tools like screenshot capture, web search, file operations, and more!"],
["Can you take a screenshot of a website?", None],
[None, "In the full version, I would use the MCP screenshot tool to capture any website. This demo version doesn't have live MCP connections, but you can see how it would work in the full GitHub version!"]
]
)
with gr.Row():
demo_input = gr.Textbox(
label="Message [DEMO]",
placeholder="This is a demo - messages won't be processed. Get the full version on GitHub!",
scale=4
)
demo_send_btn = gr.Button("Send [DEMO]", variant="primary", scale=1)
# MCP Agent Mode
with gr.Group(visible=False) as mcp_agent_group:
gr.Markdown("### Liam - MCP Development Specialist [DEMO]")
gr.Markdown(
"In the full version, Liam helps with MCP server development, best practices, and troubleshooting."
)
mcp_demo_chatbot = gr.Chatbot(
label="Chat with Liam [DEMO]",
height=500,
value=[
[None, "ποΈ Hello! I'm Liam, specialized in MCP pipeline creation. Let me show you what I can do in the full version!"],
["I need a pipeline for web scraping and analysis.", None],
[None, "Great choice! Here's what I would build for you:\n\n1. **Web Scraper MCP** β Extract data from websites\n2. **Data Processor MCP** β Clean and structure the data\n3. **Analysis MCP** β Generate insights and reports\n\nEach component would be a separate MCP server that communicates through the pipeline. Install the full version to build this!"]
]
)
# Agent Builder Mode
with gr.Group(visible=False) as agent_builder_group:
gr.Markdown("### Arthur - Agent Builder [DEMO]")
gr.Markdown(
"In the full version, Arthur helps create custom Gradio agents using system prompts from top AI assistants."
)
agent_demo_chatbot = gr.Chatbot(
label="Agent Builder Assistant [DEMO]",
height=500,
value=[
[None, "π§ββοΈ Greetings! I'm Arthur, your advanced MCP developer. In the full version, I can create sophisticated autonomous agents!"],
["Can you build a Twitter monitoring agent?", None],
[None, "Absolutely! Here's the architecture I'd create:\n\n```python\n# Twitter Monitor Agent\nclass TwitterAgent:\n tools = [\n 'twitter_stream',\n 'sentiment_analysis',\n 'alert_system',\n 'data_storage'\n ]\n```\n\nThis agent would:\nβ Monitor keywords in real-time\nβ Analyze sentiment and trends\nβ Send alerts on important events\nβ Store data for analysis\n\nGet the full version to build this!"]
]
)
# Add event handler for assistant mode switching
def switch_assistant_mode(mode):
return (
gr.update(visible=mode == "General Assistant"),
gr.update(visible=mode == "MCP Development"),
gr.update(visible=mode == "Agent Builder")
)
assistant_mode.change(
switch_assistant_mode,
inputs=[assistant_mode],
outputs=[general_assistant_group, mcp_agent_group, agent_builder_group]
)
# Tab 2: Server Builder
with gr.Tab("π§ Server Builder"):
gr.Markdown("### Build MCP Servers")
with gr.Tabs():
# Quick Create Tab
with gr.Tab("Quick Create"):
gr.Markdown("#### Create from Templates")
with gr.Row():
template_select = gr.Dropdown(
choices=[t["name"] for t in self.templates],
label="Select Template",
value="Calculator"
)
create_btn = gr.Button("Create Server", variant="primary")
template_code = gr.Code(
value=self.templates[0]["code"],
language="python",
label="Template Code"
)
creation_result = gr.Textbox(
label="Creation Result",
lines=5,
interactive=False
)
# Pipeline Builder Tab
with gr.Tab("Pipeline Builder [DEMO]"):
gr.Markdown("""
#### Visual Pipeline Builder
In the full version, you can:
- Drag and drop MCP servers to create pipelines
- Connect servers with data flow arrows
- Configure server parameters visually
- Test pipelines in real-time
- Export pipeline configurations
**[Install from GitHub for this feature]**
""")
# Demo pipeline visualization
gr.HTML("""
<div style="border: 2px dashed #ccc; padding: 40px; text-align: center; border-radius: 8px;">
<p style="color: #666;">π Web Scraper β π Data Processor β π Analyzer β π§ Report Generator</p>
<p style="color: #999; font-size: 14px;">Visual pipeline builder available in full version</p>
</div>
""")
# Templates Gallery Tab
with gr.Tab("Templates Gallery"):
gr.Markdown("#### Available Templates")
for template in self.templates:
with gr.Group():
gr.Markdown(f"**{template['name']}**")
gr.Markdown(f"*{template['description']}*")
gr.Code(
value=template['code'][:200] + "...",
language="python",
label="Preview"
)
# Tab 3: Server Management
with gr.Tab("π₯οΈ Server Management"):
with gr.Tabs():
with gr.Tab("Active Servers"):
gr.Markdown("### Running MCP Servers")
server_list = gr.Textbox(
value='{"servers": [], "message": "No active servers"}',
label="Server Status",
lines=5,
interactive=False
)
with gr.Row():
refresh_servers_btn = gr.Button("π Refresh", scale=1)
stop_all_btn = gr.Button("βΉοΈ Stop All [DEMO]", scale=1)
with gr.Tab("Browse Registry [DEMO]"):
gr.Markdown("""
### MCP Server Registry
In the full version, browse and install community servers:
- π Search thousands of MCP servers
- β Filter by ratings and popularity
- π¦ One-click installation
- π Security verification
""")
# Tab 4: Agent Control Panel
with gr.Tab("π€ Agent Control Panel [DEMO]"):
gr.Markdown("""
### Agent Management Dashboard
The full version includes:
- **Agent Creation Wizard** - Step-by-step agent building
- **Agent Templates** - Pre-built agent architectures
- **Performance Monitoring** - Real-time agent metrics
- **Agent Marketplace** - Share and discover agents
**[Get the full version on GitHub]**
""")
# Tab 5: MCP Connections
with gr.Tab("π MCP Connections"):
with gr.Tabs():
with gr.Tab("Quick Connect"):
gr.Markdown("### Connect to Popular MCP Servers")
with gr.Row():
with gr.Column():
server_type = gr.Dropdown(
choices=["Filesystem", "Memory", "GitHub", "Brave Search"],
label="Server Type",
value="Filesystem"
)
connect_params = gr.Textbox(
value='{"path": "/workspace"}',
label="Connection Parameters (JSON)",
lines=3
)
connect_btn = gr.Button("π Connect [DEMO]", variant="primary")
with gr.Column():
connection_status = gr.Textbox(
value='{"status": "Not connected"}',
label="Connection Status",
lines=3,
interactive=False
)
with gr.Tab("Active Connections [DEMO]"):
gr.Markdown("### Currently Connected Servers")
gr.Textbox(
value='{"connections": [], "message": "No active connections in demo"}',
label="Active Connections",
lines=5,
interactive=False
)
with gr.Tab("Custom Connection [DEMO]"):
gr.Markdown("""
### Connect to Custom MCP Server
In the full version:
- Connect via stdio or SSE
- Custom authentication
- Advanced configuration
""")
# Tab 6: Help & Resources
with gr.Tab("π Help & Resources"):
with gr.Tabs():
with gr.Tab("Getting Started"):
gr.Markdown("""
### Welcome to Gradio MCP Playground!
This demo showcases what's possible with the full version.
**To get started with full features:**
1. **Install from GitHub:**
```bash
git clone https://github.com/seanpoyner/gradio-mcp-playground
cd gradio-mcp-playground
pip install -e ".[all]"
```
2. **Launch the dashboard:**
```bash
gmp dashboard
```
3. **Create your first server:**
```bash
gmp create calculator my-calc-server
```
""")
with gr.Tab("Features Overview"):
gr.Markdown("""
### What You Can Do
**In This Demo:**
- β
Explore the interface
- β
View server templates
- β
Test calculator functionality
- β
See AI assistant examples
**In Full Version:**
- β
Create real MCP servers
- β
Connect to any MCP server
- β
Build complex pipelines
- β
Deploy to production
- β
Use AI assistants with real tools
- β
Access CLI tools
- β
Much more!
""")
with gr.Tab("About"):
gr.Markdown(f"""
### About Gradio MCP Playground
**Our Mission:** Democratize access to MCP technology by providing free, open-source tools
that don't require expensive LLM subscriptions.
**Created by:**
- Sean Poyner - Project Lead
- Ranadeep Laskar ([@flickinshots](https://github.com/flickinshots)) - Project Member & Collaborator
**Version:** 1.0.0
**License:** MIT
**Space ID:** {HF_SPACE_ID}
**Links:**
- [GitHub Repository](https://github.com/seanpoyner/gradio-mcp-playground)
- [Documentation](https://github.com/seanpoyner/gradio-mcp-playground)
- [Report Issues](https://github.com/seanpoyner/gradio-mcp-playground/issues)
""")
# Event handlers for templates
template_select.change(
self.update_template_view,
inputs=[template_select],
outputs=[template_code]
)
create_btn.click(
self.create_server,
inputs=[template_select, session_id],
outputs=[creation_result]
)
refresh_servers_btn.click(
self.refresh_status,
inputs=[session_id],
outputs=[server_list]
)
# Demo button handlers
demo_send_btn.click(
lambda: gr.Info("This is a demo - install the full version from GitHub for real chat functionality!"),
inputs=[],
outputs=[]
)
connect_btn.click(
lambda: '{"status": "Demo mode - install full version to connect to real MCP servers"}',
inputs=[],
outputs=[connection_status]
)
stop_all_btn.click(
lambda: gr.Info("This is a demo feature - install full version from GitHub!"),
inputs=[],
outputs=[]
)
return demo
def get_custom_css(self) -> str:
"""Custom CSS for the interface"""
return """
.gradio-container {
max-width: 1200px !important;
}
/* GitHub Banner */
.github-banner {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 12px;
text-align: center;
margin-bottom: 20px;
border-radius: 8px;
animation: pulse 2s ease-in-out infinite;
}
.github-banner a {
color: white !important;
text-decoration: none;
font-weight: bold;
font-size: 16px;
}
.github-banner:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
@keyframes pulse {
0% { opacity: 0.9; }
50% { opacity: 1; }
100% { opacity: 0.9; }
}
/* Dark mode friendly styles */
.template-card {
background: #374151;
border: 2px solid #4b5563;
border-radius: 8px;
padding: 16px;
margin: 8px 0;
transition: all 0.3s ease;
}
.template-card:hover {
border-color: #60a5fa;
transform: translateY(-2px);
}
/* Demo labels */
button:has-text("[DEMO]") {
opacity: 0.8;
}
/* Make JSON components more readable */
.block.json-block {
font-family: 'Monaco', 'Consolas', monospace;
}
"""
def update_template_view(self, template_name: str) -> str:
"""Update template code view"""
template = next((t for t in self.templates if t["name"] == template_name), None)
return template["code"] if template else ""
def create_server(self, template_name: str, session_id: str) -> str:
"""Create a demo server"""
# Initialize session
if session_id not in self.sessions:
self.sessions[session_id] = {"servers": []}
# Add server to session
server_info = {
"name": f"{template_name.lower()}-{int(time.time())}",
"template": template_name,
"status": "active",
"created": datetime.now().isoformat()
}
self.sessions[session_id]["servers"].append(server_info)
result = {
"success": True,
"message": f"Server created from {template_name} template",
"server": server_info,
"note": "This is a demo - install full version for real server creation"
}
return json.dumps(result, indent=2)
def refresh_status(self, session_id: str) -> str:
"""Refresh server status"""
session = self.sessions.get(session_id, {})
servers = session.get("servers", [])
result = {
"servers": servers,
"count": len(servers),
"message": f"{len(servers)} active server(s)" if servers else "No active servers",
"timestamp": datetime.now().isoformat()
}
return json.dumps(result, indent=2)
# Create and launch the app
print("π Starting Gradio MCP Playground...")
app = MCPPlaygroundApp()
demo = app.create_interface()
# Launch with API disabled to avoid schema errors
if __name__ == "__main__":
demo.queue(api_open=False).launch(
server_name="0.0.0.0",
server_port=7860,
favicon_path="π",
show_api=False
) |