๐ Hugging Face MCP Hackathon Submission
Transform any Python function into an AI agent with visual tools and instant testing.
GitHub |
Documentation
""")
# Main tabs
with gr.Tabs() as main_tabs:
# Tab 1: AI Assistant Hub (Main Feature)
with gr.Tab("๐ AI Assistant", id="assistant"):
self.create_assistant_tab(session_id)
# Tab 2: Visual Agent Builder
with gr.Tab("๐๏ธ Server Builder", id="builder"):
self.create_builder_tab(session_id)
# Tab 3: MCP Connections
with gr.Tab("๐ MCP Connections", id="tools"):
self.create_tools_tab(session_id)
# Tab 4: My Agents
with gr.Tab("๐ฆ Server Management", id="agents"):
self.create_agents_tab(session_id)
# Tab 5: Help
with gr.Tab("๐ Help & Resources", id="help"):
self.create_help_tab()
# Footer
gr.Markdown("""
---
""")
return demo
def create_assistant_tab(self, session_id):
"""Multi-mode AI assistant interface"""
with gr.Row():
with gr.Column(scale=1):
assistant_mode = gr.Radio(
choices=[
"Adam (General)",
"Liam (MCP Agent)",
"Arthur (Agent Builder)"
],
value="Adam (General)",
label="Choose AI Assistant",
info="Each assistant specializes in different tasks"
)
gr.Markdown("""
### ๐ ๏ธ Available MCP Tools
**Connected:**
- ๐ **FileSystem**: Read/write files
- ๐ค๏ธ **Weather**: Real-time weather
- ๐ **Search**: Web search
**Available:**
- ๐ผ๏ธ Images
- ๐ Data Analysis
- ๐๏ธ Database
""")
clear_btn = gr.Button("Clear Chat", variant="secondary")
with gr.Column(scale=2):
chatbot = gr.Chatbot(
value=[
(None, "๐ Hi! I'm Adam, your AI assistant with MCP superpowers. I can help you build agents, test MCP tools, or answer questions. Try asking me to check the weather or create a calculator agent!")
],
height=400,
avatar_images=(None, "https://api.dicebear.com/7.x/bottts/svg?seed=adam")
)
with gr.Row():
msg_input = gr.Textbox(
label="Message",
placeholder="Try: 'What's the weather in Paris?' or 'Help me build a calculator agent'",
scale=4,
lines=1
)
send_btn = gr.Button("Send", variant="primary", scale=1)
# Tool execution display
with gr.Accordion("๐ง Tool Execution Log", open=False) as tool_log:
tool_display = gr.Markdown("*No tools executed yet*")
# Example prompts
gr.Examples(
examples=[
"What's the weather in San Francisco?",
"Help me create a calculator agent",
"Show me available MCP tools",
"How do I connect a new MCP server?",
"Build an agent that can search the web"
],
inputs=msg_input,
label="Quick Start Examples"
)
# Chat functionality
def respond(message: str, history: List, mode: str) -> Tuple[List, str, str]:
"""Process chat messages and simulate MCP tool execution"""
if not message.strip():
return history, "", tool_display.value
# Simulate different assistant personalities
assistant_name = mode.split(" ")[0]
# Simulate MCP tool execution for certain queries
tool_executed = None
if "weather" in message.lower():
# Simulate weather tool execution
location = "San Francisco" # Extract from message in real impl
if "paris" in message.lower():
location = "Paris"
tool_executed = f"""
### ๐ง Tool Execution
**Tool:** `weather.get_current`
**Parameters:** `{{"location": "{location}"}}`
**Response:**
```json
{{
"temperature": 72,
"condition": "Sunny",
"humidity": 65,
"wind_speed": 12
}}
```
**Status:** โ Success
"""
response = f"I've checked the weather using the MCP weather tool. In {location}, it's currently 72ยฐF and sunny with 65% humidity and winds at 12 mph. Perfect weather for a walk! โ๏ธ"
elif "create" in message.lower() and ("agent" in message.lower() or "calculator" in message.lower()):
response = """I'll help you create a calculator agent! Here's what I'll do:
1. **Choose a template**: I'll use the calculator template that includes basic math operations
2. **Configure the agent**: Set up addition, subtraction, multiplication, and division tools
3. **Generate MCP server code**: Create a Python-based MCP server
4. **Test the tools**: Verify each operation works correctly
Would you like me to walk you through the visual builder, or should I generate the code directly for you?"""
elif "mcp tools" in message.lower() or "available tools" in message.lower():
response = """Here are the currently available MCP tools:
๐ **FileSystem MCP** (Connected)
- `read_file`: Read file contents
- `write_file`: Write to files
- `list_directory`: List folder contents
๐ค๏ธ **Weather MCP** (Connected)
- `get_current`: Current weather
- `get_forecast`: 5-day forecast
๐ **Search MCP** (Available)
- `web_search`: Search the web
- `image_search`: Find images
Would you like to test any of these tools or learn how to create your own?"""
else:
# General responses based on assistant mode
if assistant_name == "Adam":
response = f"Great question! As a general assistant with MCP capabilities, I can help you with {message}. Would you like me to use any specific tools or create an agent for this task?"
elif assistant_name == "Liam":
response = f"As an MCP development specialist, I'll help you with {message}. I can show you how to implement this as an MCP tool or integrate it into an existing server. Which approach would you prefer?"
else: # Arthur
response = f"Let's architect a solution for {message}. I can help you design the agent structure, choose the right MCP tools, and create a scalable implementation. What's your main goal with this agent?"
# Add to history
history.append((message, response))
# Update tool display
tool_display_text = tool_executed if tool_executed else "*No tools executed*"
return history, "", tool_display_text
# Wire up events
msg_input.submit(respond, [msg_input, chatbot, assistant_mode], [chatbot, msg_input, tool_display])
send_btn.click(respond, [msg_input, chatbot, assistant_mode], [chatbot, msg_input, tool_display])
clear_btn.click(lambda: ([(None, "Chat cleared! How can I help you?")], ""), outputs=[chatbot, msg_input])
def create_builder_tab(self, session_id):
"""Visual agent builder interface"""
with gr.Row():
with gr.Column():
gr.Markdown("### ๐๏ธ Create Your Server")
agent_name = gr.Textbox(
label="Server Name",
placeholder="my-awesome-server",
info="Lowercase letters, numbers, and hyphens only"
)
agent_desc = gr.Textbox(
label="Description",
placeholder="What does your server do?",
lines=2
)
template = gr.Dropdown(
choices=[
("๐งฎ Calculator - Math operations", "calculator"),
("๐ค๏ธ Weather - Weather information", "weather"),
("๐ Search - Web search", "search"),
("๐ FileSystem - File operations", "filesystem"),
("โก Custom - Start from scratch", "custom")
],
label="Template",
value="calculator",
info="Choose a starting template"
)
with gr.Row():
create_btn = gr.Button("Create Server", variant="primary")
test_btn = gr.Button("Test Server", variant="secondary")
creation_status = gr.HTML()
# Templates gallery
gr.Markdown("### ๐ Template Gallery")
templates_html = gr.HTML(self.render_templates_gallery())
with gr.Column():
gr.Markdown("### ๐ Generated Code")
code_editor = gr.Code(
label="MCP Server Implementation",
language="python",
value=self.get_template_code("calculator"),
lines=20
)
with gr.Accordion("๐งช Test Console", open=False):
test_input = gr.Textbox(
label="Test Input",
placeholder='{"operation": "add", "a": 5, "b": 3}'
)
test_output = gr.JSON(label="Test Output")
# Template change handler
def update_template(template_choice):
return self.get_template_code(template_choice)
template.change(update_template, template, code_editor)
# Create agent handler
def create_agent(name, desc, template_choice, session_data):
if not name:
return '
Please enter a server name
'
# Add to session agents
new_agent = {
"id": str(uuid.uuid4()),
"name": name,
"description": desc,
"template": template_choice,
"status": "created",
"created": datetime.now().strftime("%Y-%m-%d %H:%M")
}
# In demo mode, just show success
return f'''
โ Server "{name}" created successfully!
Template: {template_choice}
Status: Ready to deploy
Note: In production, this would be saved to your account.
๐ Deployment Initiated!
Server: {agent_data.get('name', 'Unknown')}
Target: Hugging Face Spaces
Status: In Progress...
Note: In production, this would deploy to your HF Space.
'''
deploy_btn.click(deploy_agent, selected_agent, deployment_status)
def create_help_tab(self):
"""Help and resources tab"""
gr.Markdown("""
## ๐ Help & Resources
### ๐ Quick Start Guide
1. **Choose an AI Assistant** - Start with Adam for general help, Liam for MCP development, or Arthur for architecture
2. **Build Your First Agent** - Use the Server Builder tab to create an agent from templates
3. **Connect MCP Servers** - Use the MCP Connections tab to connect to available servers
4. **Test and Deploy** - Test your agents and deploy them to production
### ๐ง Available Templates
- **Calculator** - Basic math operations (add, subtract, multiply, divide)
- **Weather** - Get weather information for any location
- **Search** - Web search capabilities
- **FileSystem** - Read and write files (with safety checks)
- **Custom** - Start from scratch with your own implementation
### ๐ Documentation
- [Getting Started Guide](https://github.com/seanpoyner/gradio-mcp-playground/wiki/Getting-Started)
- [MCP Protocol Specification](https://github.com/anthropics/mcp)
- [Gradio Documentation](https://gradio.app/docs)
### ๐ก Tips
- Use the chat to ask for help building specific agents
- Templates are fully customizable - modify the generated code as needed
- Test your tools before deploying to ensure they work correctly
- Join our Discord for community support and sharing
### ๐ Known Limitations (Demo Mode)
- MCP servers are simulated in this demo
- File operations are limited to safe paths
- API integrations require your own keys
- Deployments are simulated (not real)
### ๐ Support
- [GitHub Issues](https://github.com/seanpoyner/gradio-mcp-playground/issues)
- [Discussions](https://huggingface.co/spaces/seanpoyner/gradio-mcp-playground/discussions)
- [Discord Community](#)
""")
def get_template_code(self, template: str) -> str:
"""Return template code for different agent types"""
templates = {
"calculator": '''"""
Calculator MCP Server
A simple calculator that performs basic math operations
"""
import json
from typing import Dict, Any
from mcp.server import Server, Tool
class CalculatorServer(Server):
def __init__(self):
super().__init__("calculator")
self.register_tools()
def register_tools(self):
self.add_tool(Tool(
name="calculate",
description="Perform a calculation",
input_schema={
"type": "object",
"properties": {
"operation": {
"type": "string",
"enum": ["add", "subtract", "multiply", "divide"]
},
"a": {"type": "number"},
"b": {"type": "number"}
},
"required": ["operation", "a", "b"]
},
handler=self.calculate
))
async def calculate(self, operation: str, a: float, b: float) -> Dict[str, Any]:
"""Execute calculation based on operation"""
operations = {
"add": lambda x, y: x + y,
"subtract": lambda x, y: x - y,
"multiply": lambda x, y: x * y,
"divide": lambda x, y: x / y if y != 0 else None
}
if operation in operations:
result = operations[operation](a, b)
if result is not None:
return {"result": result, "status": "success"}
else:
return {"error": "Division by zero", "status": "error"}
return {"error": "Unknown operation", "status": "error"}
if __name__ == "__main__":
server = CalculatorServer()
server.run()
''',
"weather": '''"""
Weather MCP Server
Provides weather information for any location
"""
import aiohttp
from mcp.server import Server, Tool
class WeatherServer(Server):
def __init__(self):
super().__init__("weather")
self.api_key = "YOUR_API_KEY" # Set via environment variable
self.register_tools()
def register_tools(self):
self.add_tool(Tool(
name="get_current_weather",
description="Get current weather for a location",
input_schema={
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
},
handler=self.get_weather
))
async def get_weather(self, location: str) -> dict:
"""Fetch current weather data"""
# Demo response
return {
"location": location,
"temperature": 72,
"condition": "Sunny",
"humidity": 65,
"wind_speed": 12,
"unit": "fahrenheit"
}
if __name__ == "__main__":
server = WeatherServer()
server.run()
''',
"filesystem": '''"""
FileSystem MCP Server
Safe file operations within allowed directories
"""
import os
import json
from pathlib import Path
from mcp.server import Server, Tool
class FileSystemServer(Server):
def __init__(self):
super().__init__("filesystem")
self.allowed_paths = ["/tmp", "/workspace"]
self.register_tools()
def register_tools(self):
tools = [
Tool(
name="read_file",
description="Read file contents",
input_schema={
"type": "object",
"properties": {
"path": {"type": "string"}
},
"required": ["path"]
},
handler=self.read_file
),
Tool(
name="write_file",
description="Write content to file",
input_schema={
"type": "object",
"properties": {
"path": {"type": "string"},
"content": {"type": "string"}
},
"required": ["path", "content"]
},
handler=self.write_file
)
]
for tool in tools:
self.add_tool(tool)
async def read_file(self, path: str) -> dict:
"""Read file with safety checks"""
try:
file_path = Path(path).resolve()
# Safety check
if not any(str(file_path).startswith(allowed)
for allowed in self.allowed_paths):
return {"error": "Path not allowed", "status": "error"}
if file_path.exists() and file_path.is_file():
content = file_path.read_text()
return {"content": content, "status": "success"}
return {"error": "File not found", "status": "error"}
except Exception as e:
return {"error": str(e), "status": "error"}
if __name__ == "__main__":
server = FileSystemServer()
server.run()
''',
"custom": '''"""
Custom MCP Server Template
Build your own MCP server with custom tools
"""
from mcp.server import Server, Tool
class CustomServer(Server):
def __init__(self):
super().__init__("custom-server")
self.register_tools()
def register_tools(self):
# Add your custom tools here
self.add_tool(Tool(
name="example_tool",
description="An example tool",
input_schema={
"type": "object",
"properties": {
"input": {"type": "string"}
},
"required": ["input"]
},
handler=self.example_handler
))
async def example_handler(self, input: str) -> dict:
"""Your tool implementation"""
return {
"result": f"Processed: {input}",
"status": "success"
}
if __name__ == "__main__":
server = CustomServer()
server.run()
'''
}
return templates.get(template, templates["custom"])
def render_templates_gallery(self) -> str:
"""Render template gallery as HTML"""
templates = [
{"name": "Calculator", "desc": "Math operations", "tools": 4, "icon": "๐งฎ"},
{"name": "Weather", "desc": "Weather data", "tools": 2, "icon": "๐ค๏ธ"},
{"name": "Search", "desc": "Web search", "tools": 2, "icon": "๐"},
{"name": "FileSystem", "desc": "File operations", "tools": 5, "icon": "๐"},
]
html = '
'
for tmpl in templates:
html += f'''
{tmpl["icon"]} {tmpl["name"]}
{tmpl["desc"]}
{tmpl["tools"]} tools included
'''
html += '
'
return html
def render_server_cards(self) -> str:
"""Render MCP server status cards"""
html = '
'
for server_id, server_info in self.mcp_servers.items():
status_color = "#28a745" if server_info["status"] == "connected" else "#ffc107"
status_icon = "๐ข" if server_info["status"] == "connected" else "๐ก"
html += f'''
{server_info["name"]}
{status_icon} {server_info["status"].title()}
{server_info["endpoint"]}
{len(server_info["tools"])} tools
'''
html += '
'
return html
def render_agent_gallery(self) -> str:
"""Render agent gallery cards"""
html = '
'
for agent in self.demo_agents:
status_color = {
"active": "#28a745",
"inactive": "#dc3545",
"beta": "#ffc107"
}.get(agent["status"], "#6c757d")
html += f'''