Spaces:
Sleeping
Sleeping
File size: 26,400 Bytes
f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 2dc1766 f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 f6d0308 3968b69 f6d0308 | 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 | #!/usr/bin/env python3
"""
Universal MCP Toolkit with Tiny-Agents LLM Integration
A comprehensive MCP client with embedded lightweight AI for server automation
"""
import gradio as gr
import asyncio
import json
import logging
import os
import sys
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, asdict
from datetime import datetime
import httpx
import websockets
from pathlib import Path
import logging
# ΠΠ°ΡΡΡΠΎΠΉΠΊΠ° Π΄Π΅ΡΠ°Π»ΡΠ½ΠΎΠ³ΠΎ Π»ΠΎΠ³ΠΈΡΠΎΠ²Π°Π½ΠΈΡ
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('mcp_debug.log'),
logging.StreamHandler()
]
)
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class MCPServer:
"""MCP Server configuration"""
name: str
endpoint: str
protocol: str = "http" # http, websocket, stdio
auth_token: Optional[str] = None
capabilities: List[str] = None
status: str = "disconnected"
@dataclass
class MCPMessage:
"""MCP Protocol message structure"""
jsonrpc: str = "2.0"
id: Optional[str] = None
method: Optional[str] = None
params: Optional[Dict[str, Any]] = None
result: Optional[Any] = None
error: Optional[Dict[str, Any]] = None
class TinyAgent:
"""Lightweight AI agent for technical task execution"""
def __init__(self):
self.system_prompt = """You are a tiny technical agent designed for server automation and MCP operations.
You excel at:
- Analyzing server responses and data
- Generating appropriate MCP commands
- Troubleshooting technical issues
- Providing concise, actionable recommendations
Always respond with practical, executable solutions. Be direct and technical."""
# Simple rule-based responses for common patterns
self.patterns = {
"list": ["show", "list", "get all", "enumerate"],
"execute": ["run", "execute", "start", "launch"],
"status": ["status", "health", "check", "info"],
"config": ["config", "settings", "configure", "setup"],
"debug": ["error", "debug", "troubleshoot", "fix", "issue"],
"stop": ["stop", "kill", "terminate", "shutdown"],
"restart": ["restart", "reload", "refresh"]
}
def analyze_command(self, user_input: str) -> Dict[str, Any]:
"""Analyze user input and suggest MCP actions"""
user_lower = user_input.lower()
suggestions = {
"intent": "unknown",
"mcp_method": None,
"parameters": {},
"explanation": ""
}
# Pattern matching for common intents
for intent, keywords in self.patterns.items():
if any(keyword in user_lower for keyword in keywords):
suggestions["intent"] = intent
break
# Generate MCP method suggestions based on intent
if suggestions["intent"] == "list":
suggestions["mcp_method"] = "tools/list"
suggestions["explanation"] = "Listing available tools/resources"
elif suggestions["intent"] == "execute":
suggestions["mcp_method"] = "tools/call"
suggestions["explanation"] = "Executing a tool or command"
elif suggestions["intent"] == "status":
suggestions["mcp_method"] = "server/info"
suggestions["explanation"] = "Getting server status information"
return suggestions
def process_response(self, mcp_response: Any) -> str:
"""Process MCP response and provide human-readable analysis"""
if isinstance(mcp_response, dict):
if "error" in mcp_response:
return f"β Error: {mcp_response['error'].get('message', 'Unknown error')}"
elif "result" in mcp_response:
result = mcp_response["result"]
if isinstance(result, list):
return f"β
Found {len(result)} items:\n" + "\n".join([f"- {item}" for item in result[:5]])
elif isinstance(result, dict):
return f"β
Response received:\n" + json.dumps(result, indent=2)[:500]
else:
return f"β
Result: {str(result)[:200]}"
return f"π Raw response: {str(mcp_response)[:300]}"
class MCPClient:
"""Universal MCP Protocol Client"""
def __init__(self):
self.servers: Dict[str, MCPServer] = {}
self.connections: Dict[str, Any] = {}
self.message_id_counter = 0
def add_server(self, server: MCPServer) -> str:
"""Add a new MCP server configuration"""
self.servers[server.name] = server
return f"β
Server '{server.name}' added successfully"
def remove_server(self, server_name: str) -> str:
"""Remove MCP server configuration"""
if server_name in self.servers:
# Disconnect if connected
if server_name in self.connections:
asyncio.create_task(self.disconnect_server(server_name))
del self.servers[server_name]
return f"β
Server '{server_name}' removed"
return f"β Server '{server_name}' not found"
def get_next_message_id(self) -> str:
"""Generate unique message ID"""
self.message_id_counter += 1
return str(self.message_id_counter)
async def connect_server(self, server_name: str) -> str:
"""Connect to MCP server"""
if server_name not in self.servers:
return f"β Server '{server_name}' not configured"
server = self.servers[server_name]
try:
if server.protocol == "http":
# HTTP connection test
async with httpx.AsyncClient() as client:
response = await client.get(f"{server.endpoint}/health", timeout=5.0)
if response.status_code == 200:
self.connections[server_name] = client
server.status = "connected"
return f"β
Connected to {server_name} via HTTP"
elif server.protocol == "websocket":
# WebSocket connection
connection = await websockets.connect(server.endpoint)
self.connections[server_name] = connection
server.status = "connected"
return f"β
Connected to {server_name} via WebSocket"
else:
return f"β Unsupported protocol: {server.protocol}"
except Exception as e:
server.status = "error"
return f"β Failed to connect to {server_name}: {str(e)}"
async def disconnect_server(self, server_name: str) -> str:
"""Disconnect from MCP server"""
if server_name in self.connections:
connection = self.connections[server_name]
try:
if hasattr(connection, 'close'):
await connection.close()
del self.connections[server_name]
if server_name in self.servers:
self.servers[server_name].status = "disconnected"
return f"β
Disconnected from {server_name}"
except Exception as e:
return f"β Error disconnecting from {server_name}: {str(e)}"
return f"βΉοΈ {server_name} was not connected"
async def send_mcp_request(self, server_name: str, method: str, params: Dict[str, Any] = None) -> Any:
"""Send MCP request to server"""
if server_name not in self.connections:
raise Exception(f"Not connected to server '{server_name}'")
message = MCPMessage(
id=self.get_next_message_id(),
method=method,
params=params or {}
)
server = self.servers[server_name]
connection = self.connections[server_name]
try:
if server.protocol == "http":
# HTTP request
async with httpx.AsyncClient() as client:
response = await client.post(
f"{server.endpoint}/mcp",
json=asdict(message),
headers={"Authorization": f"Bearer {server.auth_token}"} if server.auth_token else {},
timeout=10.0
)
return response.json()
elif server.protocol == "websocket":
# WebSocket request
await connection.send(json.dumps(asdict(message)))
response = await connection.recv()
return json.loads(response)
except Exception as e:
raise Exception(f"MCP request failed: {str(e)}")
def list_servers(self) -> List[Dict[str, Any]]:
"""Get list of all configured servers"""
return [
{
"name": name,
"endpoint": server.endpoint,
"protocol": server.protocol,
"status": server.status,
"capabilities": server.capabilities or []
}
for name, server in self.servers.items()
]
# Global instances
mcp_client = MCPClient()
tiny_agent = TinyAgent()
# Gradio Interface Functions
def format_server_list() -> str:
"""Format server list for display"""
servers = mcp_client.list_servers()
if not servers:
return "No servers configured"
output = "## π₯οΈ MCP Servers\n\n"
for server in servers:
status_emoji = "π’" if server["status"] == "connected" else "π΄" if server["status"] == "error" else "βͺ"
output += f"**{status_emoji} {server['name']}**\n"
output += f"- Endpoint: `{server['endpoint']}`\n"
output += f"- Protocol: `{server['protocol']}`\n"
output += f"- Status: `{server['status']}`\n"
if server['capabilities']:
output += f"- Capabilities: {', '.join(server['capabilities'])}\n"
output += "\n"
return output
def add_server_config(name: str, endpoint: str, protocol: str, auth_token: str = "") -> Tuple[str, str]:
"""Add new server configuration"""
if not name or not endpoint:
return "β Name and endpoint are required", format_server_list()
server = MCPServer(
name=name,
endpoint=endpoint,
protocol=protocol,
auth_token=auth_token if auth_token else None
)
result = mcp_client.add_server(server)
return result, format_server_list()
async def connect_to_server(server_name: str) -> Tuple[str, str]:
"""Connect to selected server"""
if not server_name:
return "β Please select a server", format_server_list()
result = await mcp_client.connect_server(server_name)
return result, format_server_list()
async def disconnect_from_server(server_name: str) -> Tuple[str, str]:
"""Disconnect from selected server"""
if not server_name:
return "β Please select a server", format_server_list()
result = await mcp_client.disconnect_server(server_name)
return result, format_server_list()
def remove_server_config(server_name: str) -> Tuple[str, str]:
"""Remove server configuration"""
if not server_name:
return "β Please select a server", format_server_list()
result = mcp_client.remove_server(server_name)
return result, format_server_list()
async def execute_mcp_command(server_name: str, method: str, params_json: str) -> str:
"""Execute MCP command on selected server"""
if not server_name:
return "β Please select a server"
if not method:
return "β Please specify an MCP method"
# Parse parameters
try:
params = json.loads(params_json) if params_json.strip() else {}
except json.JSONDecodeError as e:
return f"β Invalid JSON parameters: {str(e)}"
try:
response = await mcp_client.send_mcp_request(server_name, method, params)
formatted_response = tiny_agent.process_response(response)
# Also show raw response
raw_response = f"\n\n**Raw Response:**\n```json\n{json.dumps(response, indent=2)}\n```"
return formatted_response + raw_response
except Exception as e:
return f"β Command execution failed: {str(e)}"
def analyze_user_input(user_message: str) -> str:
"""Analyze user input with tiny agent"""
if not user_message.strip():
return "Please enter a command or question."
analysis = tiny_agent.analyze_command(user_message)
output = f"## π€ AI Analysis\n\n"
output += f"**Intent Detected:** `{analysis['intent']}`\n"
if analysis['mcp_method']:
output += f"**Suggested MCP Method:** `{analysis['mcp_method']}`\n"
output += f"**Explanation:** {analysis['explanation']}\n"
if analysis['intent'] != "unknown":
output += f"\n**π‘ Suggestion:** Try using the suggested MCP method with an appropriate server."
return output
def chat_interface(message: str, history: List[List[str]]) -> Tuple[str, List[List[str]]]:
"""Main chat interface for MCP toolkit"""
if not message.strip():
return "", history
# Add user message to history
history.append([message, None])
# Analyze message with tiny agent
analysis = tiny_agent.analyze_command(message)
if analysis['intent'] == "unknown":
response = "I'm a technical MCP assistant. I can help you with:\n"
response += "- Managing MCP server connections\n"
response += "- Executing MCP commands\n"
response += "- Analyzing server responses\n"
response += "- Troubleshooting technical issues\n\n"
response += "Try commands like: 'list tools', 'check server status', 'execute command'"
else:
response = f"Intent: {analysis['intent']}\n"
if analysis['mcp_method']:
response += f"Suggested MCP method: {analysis['mcp_method']}\n"
response += f"Explanation: {analysis['explanation']}\n\n"
response += "Use the MCP Commands tab to execute this action on a connected server."
# Update history with response
history[-1][1] = response
return "", history
# Build Gradio Interface
def create_interface():
"""Create the main Gradio interface"""
with gr.Blocks(
title="Universal MCP Toolkit",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 1200px !important;
}
.server-status {
font-family: monospace;
background: #f5f5f5;
padding: 10px;
border-radius: 5px;
margin: 10px 0;
}
"""
) as interface:
gr.Markdown("""
# π§ Universal MCP Toolkit
### Model Context Protocol Client with Tiny-Agents AI
Connect to MCP servers, execute commands, and automate your infrastructure with AI assistance.
""")
with gr.Tabs():
# Chat Interface Tab
with gr.Tab("π¬ AI Assistant"):
gr.Markdown("Chat with the AI assistant for MCP guidance and automation help.")
chatbot = gr.Chatbot(
height=400,
label="MCP Assistant",
placeholder="Ask me about MCP operations, server management, or technical automation..."
)
chat_input = gr.Textbox(
placeholder="Type your message here...",
label="Message",
lines=2
)
chat_input.submit(
chat_interface,
inputs=[chat_input, chatbot],
outputs=[chat_input, chatbot]
)
# Server Management Tab
with gr.Tab("π₯οΈ Server Management"):
gr.Markdown("Configure and manage MCP server connections.")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### Add New Server")
server_name_input = gr.Textbox(
label="Server Name",
placeholder="my-server"
)
server_endpoint_input = gr.Textbox(
label="Endpoint URL",
placeholder="http://localhost:8080"
)
server_protocol_input = gr.Dropdown(
choices=["http", "websocket", "stdio"],
value="http",
label="Protocol"
)
server_auth_input = gr.Textbox(
label="Auth Token (optional)",
placeholder="Bearer token...",
type="password"
)
add_server_btn = gr.Button("Add Server", variant="primary")
add_server_output = gr.Textbox(label="Result", lines=2)
with gr.Column(scale=2):
gr.Markdown("### Server Status")
server_list_display = gr.Markdown(
format_server_list(),
elem_classes=["server-status"]
)
with gr.Row():
server_selector = gr.Dropdown(
choices=[],
label="Select Server",
interactive=True
)
connect_btn = gr.Button("Connect", variant="secondary")
disconnect_btn = gr.Button("Disconnect", variant="secondary")
remove_btn = gr.Button("Remove", variant="stop")
server_action_output = gr.Textbox(label="Action Result", lines=2)
# Event handlers
add_server_btn.click(
add_server_config,
inputs=[server_name_input, server_endpoint_input, server_protocol_input, server_auth_input],
outputs=[add_server_output, server_list_display]
).then(
lambda: [s["name"] for s in mcp_client.list_servers()],
outputs=[server_selector]
)
connect_btn.click(
connect_to_server,
inputs=[server_selector],
outputs=[server_action_output, server_list_display]
)
disconnect_btn.click(
disconnect_from_server,
inputs=[server_selector],
outputs=[server_action_output, server_list_display]
)
remove_btn.click(
remove_server_config,
inputs=[server_selector],
outputs=[server_action_output, server_list_display]
).then(
lambda: [s["name"] for s in mcp_client.list_servers()],
outputs=[server_selector]
)
# MCP Commands Tab
with gr.Tab("β‘ MCP Commands"):
gr.Markdown("Execute MCP protocol commands on connected servers.")
with gr.Row():
with gr.Column():
command_server_selector = gr.Dropdown(
choices=[],
label="Target Server",
interactive=True
)
mcp_method_input = gr.Textbox(
label="MCP Method",
placeholder="tools/list",
value="tools/list"
)
mcp_params_input = gr.Textbox(
label="Parameters (JSON)",
placeholder='{"arg1": "value1"}',
lines=3
)
execute_btn = gr.Button("Execute Command", variant="primary")
with gr.Column():
gr.Markdown("### Common MCP Methods:")
gr.Markdown("""
- `tools/list` - List available tools
- `tools/call` - Execute a tool
- `resources/list` - List resources
- `resources/read` - Read resource content
- `prompts/list` - List available prompts
- `server/info` - Get server information
""")
command_output = gr.Textbox(
label="Command Output",
lines=15,
max_lines=20,
interactive=False
)
execute_btn.click(
execute_mcp_command,
inputs=[command_server_selector, mcp_method_input, mcp_params_input],
outputs=[command_output]
)
# AI Analysis Tab
with gr.Tab("π€ AI Analysis"):
gr.Markdown("Get AI-powered analysis and recommendations for your commands.")
analysis_input = gr.Textbox(
label="Describe what you want to do",
placeholder="List all running processes on the server",
lines=3
)
analyze_btn = gr.Button("Analyze", variant="primary")
analysis_output = gr.Markdown(
label="AI Analysis",
value="Enter a command or question above for AI analysis."
)
analyze_btn.click(
analyze_user_input,
inputs=[analysis_input],
outputs=[analysis_output]
)
# Documentation Tab
with gr.Tab("π Documentation"):
gr.Markdown("""
## Universal MCP Toolkit Documentation
### Overview
This toolkit provides a comprehensive interface for interacting with Model Context Protocol (MCP) servers.
It includes an AI assistant powered by tiny-agents for automated analysis and command generation.
### Features
- **Multi-protocol support**: HTTP, WebSocket, and stdio connections
- **AI-powered analysis**: Intelligent command interpretation and suggestions
- **Real-time server management**: Connect, disconnect, and monitor MCP servers
- **Command execution**: Direct MCP protocol command execution
- **Response analysis**: AI-powered interpretation of server responses
### Getting Started
1. **Add Servers**: Configure your MCP servers in the Server Management tab
2. **Connect**: Establish connections to your servers
3. **Execute Commands**: Use the MCP Commands tab to interact with servers
4. **Get AI Help**: Use the AI Assistant for guidance and automation
### MCP Protocol
The Model Context Protocol enables secure, standardized communication between AI systems and external resources.
Common operations include:
- Tool execution
- Resource access
- Prompt management
- Server introspection
### Security
- Use authentication tokens for secure connections
- Validate all server endpoints before connecting
- Monitor connection status and error logs
### Troubleshooting
- Check server status in the Server Management tab
- Verify endpoint URLs and authentication
- Use the AI Assistant for diagnostic help
- Check the console for detailed error logs
""")
# Auto-refresh server list
interface.load(
lambda: [s["name"] for s in mcp_client.list_servers()],
outputs=[server_selector, command_server_selector]
)
return interface
# Main application
if __name__ == "__main__":
# Create and launch the interface
app = create_interface()
# Add some example servers for demonstration
example_servers = [
MCPServer(
name="local-demo",
endpoint="http://localhost:8080",
protocol="http",
capabilities=["tools", "resources"]
),
MCPServer(
name="websocket-demo",
endpoint="ws://localhost:8081/mcp",
protocol="websocket",
capabilities=["tools", "prompts"]
)
]
for server in example_servers:
mcp_client.add_server(server)
# Launch the application
app.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
inbrowser=True,
show_error=True
) |