Spaces:
Sleeping
Sleeping
File size: 35,635 Bytes
29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 aab630b 518eab8 29c4a42 518eab8 29c4a42 aab630b 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 aab630b 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 2ae13c5 aab630b 29c4a42 aab630b 29c4a42 aab630b 2ae13c5 aab630b 2ae13c5 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 29c4a42 aab630b 518eab8 29c4a42 aab630b 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 aab630b 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 aab630b 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 518eab8 29c4a42 aab630b 518eab8 29c4a42 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 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 |
# 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", "seanpoyner/gradio-mcp-playground")
GITHUB_REPO = "https://github.com/seanpoyner/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 = {}
self.demo_chat_history = []
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:
# Banner directing to GitHub
gr.HTML(f"""
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 10px; margin-bottom: 20px; text-align: center; color: white;">
<h2 style="margin: 0 0 10px 0; color: white;">π― Demo Version - Limited Functionality</h2>
<p style="margin: 0 0 15px 0; font-size: 16px;">
This is a demonstration of the Gradio MCP Playground with limited features.
For full functionality including AI assistants, agent building, and live MCP connections:
</p>
<a href="{GITHUB_REPO}" target="_blank" style="background: white; color: #667eea; padding: 12px 30px; border-radius: 25px; text-decoration: none; font-weight: bold; display: inline-block; transition: transform 0.2s;">
π Get Full Version on GitHub
</a>
</div>
""")
# Header
gr.Markdown("""
# π Gradio MCP Playground
Build, test, and deploy Model Context Protocol (MCP) servers directly in your browser.
This demo showcases core MCP capabilities with functional examples.
""")
# Session state
session_id = gr.State(value=lambda: str(uuid.uuid4()))
with gr.Tabs() as tabs:
# Tab 1: AI Assistant (Demo)
with gr.Tab("π AI Assistant"):
gr.Markdown("## AI Assistant Hub [DEMO]")
with gr.Row():
assistant_mode = gr.Radio(
choices=["General Assistant", "MCP Development", "Agent Builder"],
value="General Assistant",
label="Assistant Mode",
info="Choose your assistant type"
)
# 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, "π I'm Liam, your MCP development specialist. In the full version, I can help you build, test, and deploy MCP servers!"]
]
)
# 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, "π I'm Arthur, your agent creation specialist. In the full version, I can help you create custom agents for data analysis, creative writing, code review, and more!"]
]
)
# Tab 2: Server Builder
with gr.Tab("π§ Server Builder"):
gr.Markdown("### Build MCP Servers")
with gr.Tabs():
# Quick Create
with gr.Tab("β‘ Quick Create"):
with gr.Row():
with gr.Column(scale=1):
template_gallery = gr.Radio(
choices=[t["name"] for t in self.templates],
label="Available Templates",
value="Calculator"
)
template_info = gr.JSON(
value=self.templates[0],
label="Template Details"
)
with gr.Column(scale=2):
server_name = gr.Textbox(
label="Server Name",
placeholder="my-calculator-server"
)
server_code = gr.Code(
value=self.templates[0]["code"],
language="python",
label="Server Code",
lines=20
)
with gr.Row():
create_btn = gr.Button("β¨ Create Server", variant="primary")
test_btn = gr.Button("π§ͺ Test Server")
creation_output = gr.JSON(label="Server Status")
# Pipeline Builder
with gr.Tab("π Pipeline Builder"):
gr.Markdown("### Visual Pipeline Builder [DEMO]")
gr.Markdown(
"The full version includes a visual pipeline builder for creating complex workflows. "
"This feature requires the agent components from the GitHub repository."
)
gr.Image(
value=None,
label="Pipeline Builder Preview [DEMO]"
)
# Templates Gallery
with gr.Tab("π Templates"):
gr.Markdown("## π¨ Server Template Gallery")
gr.Markdown(
"Choose from our collection of pre-built MCP server templates. "
"Full versions include AI/ML templates, database connectors, and more!"
)
with gr.Row():
for template in self.templates:
with gr.Column():
gr.Markdown(f"### {template['name']}")
gr.Markdown(f"_{template['description']}_")
gr.Button(f"Use {template['name']} Template", variant="secondary")
# Tab 3: Server Management
with gr.Tab("π₯οΈ Server Management"):
with gr.Tabs():
# Active Servers
with gr.Tab("π’ Active Servers"):
gr.Markdown("### Currently Running Servers")
with gr.Row():
server_status = gr.JSON(
value={"message": "Demo mode - showing simulated servers", "count": 2},
label="Server Status"
)
refresh_btn = gr.Button("π Refresh", scale=0)
# Simulated active servers
with gr.Row():
with gr.Column():
gr.Markdown("**Calculator Server** π’")
gr.Markdown("Port: 8080 | Status: Running")
with gr.Column():
gr.Markdown("**Text Processor** π’")
gr.Markdown("Port: 8081 | Status: Running")
# Browse Registry
with gr.Tab("π¦ Browse Registry"):
gr.Markdown("### MCP Server Registry [DEMO]")
gr.Markdown(
"The full version includes access to a registry of community MCP servers. "
"Install servers from npm, PyPI, or custom sources!"
)
# Tab 4: Agent Control Panel
with gr.Tab("π€ Agent Control Panel"):
gr.Markdown("## Agent Control Panel [DEMO]")
gr.Markdown(
"In the full version, this panel allows you to:\n"
"- Create and manage custom agents\n"
"- Configure agent behaviors and tools\n"
"- Monitor agent performance\n"
"- Export and share agent configurations"
)
with gr.Row():
with gr.Column():
gr.Markdown("### Available Agents [DEMO]")
gr.Markdown("- π€ Data Analysis Agent\n- βοΈ Creative Writing Agent\n- π Code Review Agent")
with gr.Column():
gr.Markdown("### Agent Status [DEMO]")
gr.JSON(value={"status": "demo", "agents": 3})
# Tab 5: MCP Connections
with gr.Tab("π MCP Connections"):
with gr.Tabs():
# Quick Connect
with gr.Tab("β‘ Quick Connect"):
gr.Markdown("### Quick Connect to MCP Servers [DEMO]")
gr.Markdown(
"The full version allows instant connection to MCP servers via stdio, HTTP, or WebSocket."
)
with gr.Row():
connection_type = gr.Radio(
choices=["stdio", "http", "websocket"],
label="Connection Type [DEMO]",
value="stdio"
)
connect_btn = gr.Button("Connect [DEMO]", variant="primary")
# Active Connections
with gr.Tab("π Active Connections"):
gr.Markdown("### Currently Connected Servers [DEMO]")
gr.Markdown("No active connections in demo mode")
# Custom Connection
with gr.Tab("β Custom Connection"):
gr.Markdown("### Add Custom MCP Connection [DEMO]")
gr.Textbox(label="Server Command [DEMO]", placeholder="python my_server.py")
gr.Textbox(label="Arguments [DEMO]", placeholder="--port 8080")
# Tab 6: Help & Resources
with gr.Tab("π Help & Resources"):
with gr.Tabs():
# User Guides
with gr.Tab("π User Guides"):
gr.Markdown("""
## User Guides
### Getting Started
1. **Install the full version** from [GitHub]({GITHUB_REPO})
2. **Set up your environment** with required dependencies
3. **Launch the playground** and start building!
### Key Features
- π€ **AI Assistants** - Three specialized assistants for different tasks
- π§ **Server Builder** - Create MCP servers from templates
- π **Live Connections** - Connect to any MCP server
- π **Visual Pipeline Builder** - Create complex workflows
""".replace("{GITHUB_REPO}", GITHUB_REPO))
# Configuration
with gr.Tab("βοΈ Configuration"):
gr.Markdown("### Configuration Guide [DEMO]")
gr.Code(
value='{\n "servers": [\n {\n "name": "example-server",\n "command": "python",\n "args": ["server.py"]\n }\n ]\n}',
language="json",
label="Example Configuration"
)
# Quick Start
with gr.Tab("π Quick Start"):
gr.Markdown(f"""
## Quick Start Guide
### 1. Get the Full Version
```bash
git clone {GITHUB_REPO}
cd gradio-mcp-playground
```
### 2. Install Dependencies
```bash
pip install -e ".[all]"
```
### 3. Launch the Playground
```bash
gmp --help # See all options
gmp ui # Launch the full UI
```
""")
# Tutorials
with gr.Tab("π‘ Tutorials"):
gr.Markdown("### Available Tutorials [DEMO]")
gr.Markdown(
"- Building Your First MCP Server\n"
"- Connecting Multiple Servers\n"
"- Creating Custom Agents\n"
"- Advanced Pipeline Workflows"
)
# API Reference
with gr.Tab("π§ API Reference"):
gr.Markdown("### MCP API Reference [DEMO]")
gr.Markdown("Full API documentation available in the GitHub repository.")
# Troubleshooting
with gr.Tab("π οΈ Troubleshooting"):
gr.Markdown("### Common Issues [DEMO]")
gr.Markdown(
"- **Connection Issues**: Check server logs and ports\n"
"- **Performance**: Optimize server code and connections\n"
"- **Compatibility**: Ensure MCP protocol version match"
)
# Event handlers
# 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]
)
# Demo chat handlers
def demo_chat_response(message, history):
"""Simulate chat responses for demo"""
history = history or []
history.append({"role": "user", "content": message})
# Simple demo responses
if "screenshot" in message.lower():
response = "In the full version, I would capture a screenshot using the MCP screenshot tool. This demo doesn't have live MCP connections, but you can get the full functionality on GitHub!"
elif "file" in message.lower():
response = "In the full version, I can read, write, and manipulate files using MCP file tools. Check out the GitHub repository for the complete experience!"
elif "search" in message.lower():
response = "In the full version, I can search the web using MCP search tools. This demo shows what's possible - get the full version for actual functionality!"
else:
response = f"This is a demo response. In the full version, I would process your request: '{message}' using connected MCP tools. Visit our GitHub repository for the complete Gradio MCP Playground!"
history.append({"role": "assistant", "content": response})
return "", history
demo_send_btn.click(
demo_chat_response,
inputs=[demo_input, demo_chatbot],
outputs=[demo_input, demo_chatbot]
)
# Server management handlers
refresh_btn.click(
self.refresh_status,
inputs=[session_id],
outputs=[server_status]
)
template_gallery.change(
self.update_template_view,
inputs=[template_gallery],
outputs=[template_info, server_code]
)
create_btn.click(
self.create_server,
inputs=[server_name, server_code, session_id],
outputs=[creation_output]
)
test_btn.click(
self.test_server,
inputs=[server_code],
outputs=[creation_output]
)
return demo
def get_custom_css(self) -> str:
"""Custom CSS for the interface"""
return """
.gradio-container {
max-width: 1400px !important;
}
/* Banner styling */
.banner a:hover {
transform: scale(1.05);
}
/* Demo labels */
button:has-text("[DEMO]"),
.label:has-text("[DEMO]") {
position: relative;
}
button:has-text("[DEMO]")::after,
.label:has-text("[DEMO]")::after {
content: "DEMO";
position: absolute;
top: -8px;
right: -8px;
background: #ff6b6b;
color: white;
padding: 2px 6px;
border-radius: 4px;
font-size: 10px;
font-weight: bold;
}
/* 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);
}
.server-status {
padding: 12px;
border-radius: 8px;
margin: 8px 0;
}
.status-active {
background: #10b981;
color: white;
}
.status-inactive {
background: #ef4444;
color: white;
}
/* Tab styling */
.tabs {
margin-top: 20px;
}
/* Demo mode indicators */
.demo-indicator {
background: #ff6b6b;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
display: inline-block;
margin-left: 8px;
}
"""
def refresh_status(self, session_id: str) -> Dict:
"""Refresh server status"""
session = self.sessions.get(session_id, {})
servers = session.get("servers", [])
return {
"message": f"Active servers: {len(servers)}",
"count": len(servers),
"servers": servers,
"timestamp": datetime.now().isoformat()
}
def quick_deploy(self, template_name: str, session_id: str) -> Tuple[Dict, Dict]:
"""Quick deploy a template"""
template = next((t for t in self.templates if t["name"] == template_name), None)
if not template:
return {"error": "Template not found"}, self.refresh_status(session_id)
# Initialize session
if session_id not in self.sessions:
self.sessions[session_id] = {"servers": []}
# Add server to session
server_id = f"{template['id']}-{int(time.time())}"
server_info = {
"id": server_id,
"name": template_name,
"status": "active",
"created": datetime.now().isoformat()
}
self.sessions[session_id]["servers"].append(server_info)
return {
"success": True,
"message": f"Deployed {template_name}",
"server_id": server_id
}, self.refresh_status(session_id)
def update_template_view(self, template_name: str) -> Tuple[Dict, str]:
"""Update template view when selection changes"""
template = next((t for t in self.templates if t["name"] == template_name), None)
if template:
return template, template["code"]
return {"error": "Template not found"}, ""
def create_server(self, name: str, code: str, session_id: str) -> Dict:
"""Create a new server"""
if not name:
return {"error": "Server name is required"}
# Save server code temporarily
temp_dir = tempfile.mkdtemp()
server_file = Path(temp_dir) / f"{name}.py"
try:
server_file.write_text(code)
# Test if code is valid Python
result = subprocess.run(
[sys.executable, "-m", "py_compile", str(server_file)],
capture_output=True,
text=True
)
if result.returncode != 0:
return {"error": f"Invalid Python code: {result.stderr}"}
return {
"success": True,
"message": f"Server '{name}' created successfully",
"path": str(server_file)
}
except Exception as e:
return {"error": f"Failed to create server: {str(e)}"}
finally:
# Cleanup
shutil.rmtree(temp_dir, ignore_errors=True)
def test_server(self, code: str) -> Dict:
"""Test server code"""
try:
# Basic syntax check
compile(code, '<string>', 'exec')
return {
"success": True,
"message": "Code syntax is valid",
"timestamp": datetime.now().isoformat()
}
except SyntaxError as e:
return {
"error": f"Syntax error at line {e.lineno}: {e.msg}",
"line": e.lineno
}
except Exception as e:
return {"error": f"Validation error: {str(e)}"}
def update_tool_methods(self, server: str) -> Tuple[gr.Dropdown, Dict]:
"""Update available methods based on selected server"""
methods_map = {
"calculator": {
"methods": ["add", "subtract", "multiply", "divide"],
"default_params": {"a": 10, "b": 5}
},
"text_processor": {
"methods": ["count_words", "reverse", "uppercase", "lowercase"],
"default_params": {"text": "Hello, World!"}
},
"echo": {
"methods": ["echo"],
"default_params": {"message": "Test message"}
}
}
server_info = methods_map.get(server, {"methods": [], "default_params": {}})
return gr.Dropdown(
choices=server_info["methods"],
value=server_info["methods"][0] if server_info["methods"] else None
), server_info["default_params"]
def execute_tool(self, server: str, method: str, params: Dict, session_id: str) -> Tuple[Dict, str]:
"""Execute a tool method"""
log_lines = []
log_lines.append(f"[{datetime.now().strftime('%H:%M:%S')}] Executing {server}.{method}")
log_lines.append(f"Parameters: {json.dumps(params, indent=2)}")
try:
# Simulate execution based on server type
if server == "calculator":
if method == "add":
result = {"result": params.get("a", 0) + params.get("b", 0)}
elif method == "subtract":
result = {"result": params.get("a", 0) - params.get("b", 0)}
elif method == "multiply":
result = {"result": params.get("a", 0) * params.get("b", 0)}
elif method == "divide":
b = params.get("b", 1)
if b == 0:
result = {"error": "Division by zero"}
else:
result = {"result": params.get("a", 0) / b}
else:
result = {"error": f"Unknown method: {method}"}
elif server == "text_processor":
text = params.get("text", "")
if method == "count_words":
result = {"count": len(text.split())}
elif method == "reverse":
result = {"reversed": text[::-1]}
elif method == "uppercase":
result = {"uppercase": text.upper()}
elif method == "lowercase":
result = {"lowercase": text.lower()}
else:
result = {"error": f"Unknown method: {method}"}
elif server == "echo":
result = {
"echo": params,
"timestamp": datetime.now().isoformat(),
"server": server
}
else:
result = {"error": f"Unknown server: {server}"}
log_lines.append(f"Result: {json.dumps(result, indent=2)}")
log_lines.append(f"[{datetime.now().strftime('%H:%M:%S')}] Execution completed")
return result, "\n".join(log_lines)
except Exception as e:
error_result = {"error": str(e), "type": type(e).__name__}
log_lines.append(f"Error: {str(e)}")
return error_result, "\n".join(log_lines)
def demo_notification(self, action: str) -> str:
"""Return a demo notification message"""
return f"[DEMO MODE] {action} - This feature requires the full version. Visit {GITHUB_REPO} for complete functionality!"
# Create and launch the app
app = MCPPlaygroundApp()
demo = app.create_interface()
if __name__ == "__main__":
demo.queue(api_open=False).launch(
server_name="0.0.0.0",
server_port=7860,
favicon_path="π",
show_api=False
) |