# 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"""
๐ฏ Demo Version - Limited Functionality
This is a demonstration of the Gradio MCP Playground with limited features.
For full functionality including AI assistants, agent building, and live MCP connections:
๐ Get Full Version on GitHub
""")
# 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, '', '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
)