import gradio as gr import os import asyncio import json import httpx from openai import OpenAI from typing import List, Dict, Any import logging import markdown # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Initialize OpenAI client client = OpenAI( api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_API_BASE", "https://api.openai.com/v1") ) class MCPServerDemo: def __init__(self): self.servers = { "Microsoft Learn Docs": { "url": "https://learn.microsoft.com/api/mcp", "description": "Search official Microsoft Learn documentation", "tools": ["microsoft_docs_search"] }, "Azure MCP": { "description": "Manage Azure resources and services", "tools": ["azure_resource_list", "azure_monitor_query"] }, "GitHub MCP": { "description": "Interact with GitHub repositories", "tools": ["github_search_repos", "github_create_issue"] }, "Azure DevOps MCP": { "description": "Manage Azure DevOps work items", "tools": ["devops_create_workitem", "devops_query_workitems"] }, "MarkItDown MCP": { "description": "Convert documents to Markdown format", "tools": ["convert_to_markdown"] }, "SQL Server MCP": { "description": "Query SQL Server databases", "tools": ["sql_query", "sql_schema"] }, "Playwright MCP": { "description": "Web automation and testing", "tools": ["playwright_navigate", "playwright_screenshot"] } } async def search_microsoft_docs(self, query: str) -> str: """Search Microsoft Learn documentation""" try: async with httpx.AsyncClient() as client: response = await client.post( "https://learn.microsoft.com/api/mcp", json={ "method": "tools/call", "params": { "name": "microsoft_docs_search", "arguments": {"query": query} } }, headers={"Content-Type": "application/json"} ) if response.status_code == 200: result = response.json() return f"Search results for '{query}':\n\n{json.dumps(result, indent=2, ensure_ascii=False)}" else: return f"Search error: {response.status_code}" except Exception as e: logger.error(f"Error searching Microsoft docs: {e}") return f"Error: {str(e)}" def simulate_mcp_call(self, server_name: str, tool_name: str, query: str) -> str: """Simulate MCP server call with markdown formatting""" if server_name not in self.servers: return "❌ **Server not found**" server_info = self.servers[server_name] # Simulate results based on server and tool with actual query if server_name == "Microsoft Learn Docs" and tool_name == "microsoft_docs_search": # Generate different results based on query keywords results = [] query_lower = query.lower() if "auth" in query_lower or "security" in query_lower: results = [ ("ASP.NET Core Authentication", "https://learn.microsoft.com/aspnet/core/security/authentication/", "Complete guide to authentication in ASP.NET Core"), ("Azure Active Directory", "https://learn.microsoft.com/azure/active-directory/", "Enterprise identity and access management"), ("Identity Framework", "https://learn.microsoft.com/aspnet/core/security/authentication/identity", "ASP.NET Core Identity framework documentation") ] elif "azure" in query_lower: results = [ ("Azure Documentation", "https://learn.microsoft.com/azure/", "Official Azure documentation and tutorials"), ("Azure Functions", "https://learn.microsoft.com/azure/azure-functions/", "Serverless compute service documentation"), ("Azure Storage", "https://learn.microsoft.com/azure/storage/", "Cloud storage solutions and best practices") ] elif "c#" in query_lower or "csharp" in query_lower: results = [ ("C# Programming Guide", "https://learn.microsoft.com/dotnet/csharp/", "Complete C# language reference and examples"), (".NET Documentation", "https://learn.microsoft.com/dotnet/", "Official .NET platform documentation"), ("C# Language Features", "https://learn.microsoft.com/dotnet/csharp/whats-new/", "Latest C# features and improvements") ] else: results = [ ("ASP.NET Core Documentation", "https://learn.microsoft.com/aspnet/core/", "Comprehensive guide for ASP.NET Core development"), ("Azure Documentation", "https://learn.microsoft.com/azure/", "Official Azure documentation and tutorials"), ("C# Programming Guide", "https://learn.microsoft.com/dotnet/csharp/", "Complete C# language reference and examples") ] result_md = f""" ## 🔍 **Microsoft Learn Docs Search** **Query:** `{query}` ### 📚 **Search Results for "{query}":** """ for i, (title, url, desc) in enumerate(results, 1): result_md += f"""#### {i}. {title} - **URL:** [{url}]({url}) - **Description:** {desc} - **Relevance:** {'⭐' * (6-i)} """ result_md += """### ✅ **Real Features:** - 🔍 Semantic search across all Microsoft Learn content - 🔄 Real-time access to latest documentation - 🔗 Contextual results with source links - 📊 Up to 10 high-quality content chunks returned """ return result_md elif server_name == "Azure MCP": # Generate different results based on query query_lower = query.lower() if "vm" in query_lower or "virtual" in query_lower: resource_focus = "Virtual Machines" vm_count = 8 storage_count = 15 elif "storage" in query_lower: resource_focus = "Storage Accounts" vm_count = 3 storage_count = 25 else: resource_focus = "All Resources" vm_count = 5 storage_count = 12 return f""" ## ☁️ **Azure MCP Server** **Action:** `{tool_name}` **Query:** `{query}` ### 🔧 **Results for "{query}":** | Resource Type | Count | Status | |---------------|-------|--------| | Resource Groups | 5 | ✅ Active | | Storage Accounts | {storage_count} | ✅ Running | | Virtual Machines | {vm_count} | ✅ Running | | App Services | 8 | ✅ Deployed | ### 📊 **Resource Health:** - 🟢 **Healthy:** {28 + vm_count} resources - 🟡 **Warning:** 2 resources - 🔴 **Critical:** 0 resources **Focus Area:** {resource_focus} ### ✅ **Real Features:** - 🛠️ **15+ Azure service connectors** - 📊 **Azure Monitor log analysis with KQL** - 🗄️ **Database connectivity** (PostgreSQL, SQL Server) - 🌐 **Cosmos DB integration** - 📈 **Resource management and monitoring** """ elif server_name == "GitHub MCP": # Generate different results based on query query_lower = query.lower() if "microsoft" in query_lower: repo_count = 50 top_repos = [ ("microsoft/vscode", "162k", "Visual Studio Code editor"), ("microsoft/TypeScript", "100k", "TypeScript language"), ("microsoft/PowerToys", "110k", "Windows system utilities") ] elif "python" in query_lower: repo_count = 35 top_repos = [ ("python/cpython", "62k", "Python programming language"), ("psf/requests", "52k", "HTTP library for Python"), ("pallets/flask", "67k", "Micro web framework") ] else: repo_count = 25 top_repos = [ ("facebook/react", "228k", "JavaScript library for UIs"), ("vuejs/vue", "207k", "Progressive JavaScript framework"), ("angular/angular", "96k", "Platform for mobile and desktop") ] repo_list = "" for i, (repo, stars, desc) in enumerate(top_repos, 1): repo_list += f"{i}. **{repo}** - ⭐ {stars} stars\n - {desc}\n\n" return f""" ## 🐙 **GitHub MCP Server** **Action:** `{tool_name}` **Query:** `{query}` ### 📊 **Search Results for "{query}":** #### Repository Statistics ```json {{ "repositories_found": {repo_count}, "open_issues": {repo_count // 2}, "pull_requests": {repo_count // 3}, "recent_commits": {repo_count * 2}, "contributors": {repo_count // 2} }} ``` #### Top Repositories {repo_list} ### ✅ **Real Features:** - 📝 **Create and manage GitHub issues** - 🔍 **Search repositories and code** - 🔄 **Manage pull requests** - 📊 **Repository analytics and insights** - 👥 **Team collaboration tools** """ else: return f""" ## 🛠️ **{server_name}** **Tool:** `{tool_name}` **Query:** `{query}` ### 📋 **Results for "{query}":** > **{server_info['description']}** This is a **demo simulation** for your query: **"{query}"** ### ✅ **Capabilities:** - 🔗 Connect directly to the service - ⚡ Perform real-time operations - 📊 Return accurate data from APIs - 🔄 Execute live commands and queries ### 🚀 **Integration Benefits:** - **Stay in flow** - No context switching - **AI-powered** - Natural language queries - **Chainable** - Combine multiple servers - **Extensible** - Build custom integrations """ def format_markdown_response(self, content: str) -> str: """Format response with proper markdown rendering""" # Convert markdown to HTML for better rendering html_content = markdown.markdown(content, extensions=['tables', 'fenced_code']) return html_content def create_demo_interface(): demo_instance = MCPServerDemo() def process_mcp_request(server_name: str, tool_name: str, query: str) -> str: if not query.strip(): return "❌ **Please enter a query to test the MCP server**" return demo_instance.simulate_mcp_call(server_name, tool_name, query) def get_tools_for_server(server_name: str) -> gr.Dropdown: if server_name in demo_instance.servers: tools = demo_instance.servers[server_name]["tools"] return gr.Dropdown(choices=tools, value=tools[0] if tools else None) return gr.Dropdown(choices=[], value=None) # Dark theme optimized CSS dark_theme_css = """ .gradio-container { max-width: 1400px !important; background: #0d1117 !important; } .server-header { background: linear-gradient(135deg, #1f6feb 0%, #8b5cf6 100%); color: white; padding: 24px; border-radius: 12px; margin: 16px 0; box-shadow: 0 8px 32px rgba(31, 111, 235, 0.2); } .server-info-grid { background: #161b22; padding: 24px; border-radius: 12px; margin: 20px 0; border: 1px solid #30363d; } .server-card { background: #21262d; padding: 20px; border-radius: 10px; border-left: 4px solid #1f6feb; margin: 12px 0; transition: all 0.3s ease; } .server-card:hover { background: #262c36; transform: translateY(-2px); box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3); } .markdown-content { background: #0d1117; color: #e6edf3; font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace; } .markdown-content h2 { color: #1f6feb; border-bottom: 2px solid #21262d; padding-bottom: 8px; } .markdown-content h3 { color: #7c3aed; } .markdown-content code { background: #161b22; color: #79c0ff; padding: 2px 6px; border-radius: 4px; border: 1px solid #30363d; } .markdown-content pre { background: #161b22 !important; border: 1px solid #30363d; border-radius: 8px; padding: 16px; } .markdown-content table { border-collapse: collapse; width: 100%; margin: 16px 0; } .markdown-content th, .markdown-content td { border: 1px solid #30363d; padding: 12px; text-align: left; } .markdown-content th { background: #21262d; color: #1f6feb; font-weight: 600; } .markdown-content blockquote { border-left: 4px solid #1f6feb; background: #161b22; padding: 16px; margin: 16px 0; border-radius: 0 8px 8px 0; } /* Gradio component styling for dark theme */ .gr-textbox, .gr-dropdown { background: #21262d !important; border: 1px solid #30363d !important; color: #e6edf3 !important; } .gr-button { background: linear-gradient(135deg, #1f6feb 0%, #8b5cf6 100%) !important; border: none !important; color: white !important; font-weight: 600 !important; transition: all 0.3s ease !important; } .gr-button:hover { transform: translateY(-2px) !important; box-shadow: 0 4px 16px rgba(31, 111, 235, 0.4) !important; } """ with gr.Blocks( title="Microsoft MCP Servers Demo", theme=gr.themes.Base().set( body_background_fill="#0d1117", body_text_color="#e6edf3", background_fill_primary="#161b22", background_fill_secondary="#21262d", border_color_primary="#30363d", color_accent="#1f6feb", color_accent_soft="#1f6feb20" ), css=dark_theme_css ) as demo: gr.HTML("""

🚀 Microsoft MCP Servers Demo

Explore 10 Microsoft MCP Servers to accelerate your development workflow!

Model Context Protocol (MCP) enables AI assistants to connect with external tools and data sources.

""") with gr.Row(): with gr.Column(scale=1): gr.HTML("

🛠️ Select MCP Server

") server_dropdown = gr.Dropdown( choices=list(demo_instance.servers.keys()), value="Microsoft Learn Docs", label="MCP Server", info="Choose a server to test", elem_classes=["gr-dropdown"] ) tool_dropdown = gr.Dropdown( choices=demo_instance.servers["Microsoft Learn Docs"]["tools"], value="microsoft_docs_search", label="Tool/Function", info="Select function to call", elem_classes=["gr-dropdown"] ) query_input = gr.Textbox( label="Query/Input", placeholder="Enter your query to test the MCP server...", lines=3, value="ASP.NET Core authentication", elem_classes=["gr-textbox"] ) submit_btn = gr.Button( "🔍 Test MCP Server", variant="primary", elem_classes=["gr-button"] ) with gr.Column(scale=2): gr.HTML("

📊 Results

") output_text = gr.Markdown( label="MCP Server Response", value="", elem_classes=["markdown-content"], show_copy_button=True, line_breaks=True, sanitize_html=False ) # Server info section with improved styling with gr.Row(): gr.HTML("""

📚 Microsoft MCP Servers Overview

📚 Microsoft Learn Docs

Semantic search across official Microsoft documentation

microsoft_docs_search

☁️ Azure MCP

Manage 15+ Azure services and resources

azure_resource_list, azure_monitor_query

🐙 GitHub MCP

Interact with GitHub repos, issues, PRs

github_search_repos, github_create_issue

🔄 Azure DevOps

Manage work items, builds, releases

devops_create_workitem, devops_query_workitems

📝 MarkItDown

Convert documents to Markdown format

convert_to_markdown

🗃️ SQL Server

Query SQL Server databases

sql_query, sql_schema

🎭 Playwright

Web automation and testing

playwright_navigate, playwright_screenshot

🚀 Key Benefits

""") # Event handlers server_dropdown.change( fn=lambda server: gr.Dropdown( choices=demo_instance.servers[server]["tools"] if server in demo_instance.servers else [], value=demo_instance.servers[server]["tools"][0] if server in demo_instance.servers and demo_instance.servers[server]["tools"] else None ), inputs=[server_dropdown], outputs=[tool_dropdown] ) submit_btn.click( fn=process_mcp_request, inputs=[server_dropdown, tool_dropdown, query_input], outputs=[output_text] ) # Load initial result with dynamic query def load_initial_result(): return demo_instance.simulate_mcp_call("Microsoft Learn Docs", "microsoft_docs_search", "ASP.NET Core authentication") demo.load( fn=load_initial_result, outputs=[output_text] ) return demo if __name__ == "__main__": demo = create_demo_interface() demo.launch( server_name="0.0.0.0", server_port=int(os.getenv("GRADIO_SERVER_PORT", 7860)), share=False, show_error=True )