import React, { useState, useEffect, useRef } from 'react'; import { Cpu, Copy, Check, Terminal, Play, Send, Radio, Eye, FileText, Zap, Activity, Layers, Sparkles, Server, ArrowRight, RefreshCw, Sliders, CheckCircle2, AlertCircle, HelpCircle, Code, FileCode, HardDrive } from 'lucide-react'; import { MCPRequest, MCPResponse } from '../types'; export const MCPGuideTab: React.FC = () => { const [activeMainSection, setActiveMainSection] = useState<'sse-hub' | 'ollama-gpu' | 'inspector' | 'client-configs'>('sse-hub'); const [activeGuide, setActiveGuide] = useState<'claude' | 'cursor' | 'openwebui' | 'python' | 'ts' | 'curl'>('claude'); const [copiedKey, setCopiedKey] = useState(null); // SSE Live Stream Inspector State const [sseConnected, setSseConnected] = useState(false); const [sseLogs, setSseLogs] = useState>([]); const [ssePingCount, setSsePingCount] = useState(0); const sseEventSourceRef = useRef(null); // Local Ollama / GPU Probe State const [ollamaEndpoint, setOllamaEndpoint] = useState('http://localhost:11434'); const [probingOllama, setProbingOllama] = useState(false); const [probeResult, setProbeResult] = useState(null); // Local Model Interactive Playground State const [activeModelTool, setActiveModelTool] = useState<'prompt' | 'vision' | 'embed' | 'manager' | 'nvidia'>('prompt'); const [promptInput, setPromptInput] = useState('Explain how Model Context Protocol routes tool calls to local sub-models.'); const [selectedSubModel, setSelectedSubModel] = useState('llama3.2:1b'); const [visionImageInput, setVisionImageInput] = useState('https://images.unsplash.com/photo-1550751827-4bd374c3f58b?w=600'); const [visionPrompt, setVisionPrompt] = useState('Examine this image and detect key visual elements, text, and scene composition.'); const [embedTextInput, setEmbedTextInput] = useState('Model Context Protocol enables universal tool calling and structured knowledge sharing.'); const [embedCompareInput, setEmbedCompareInput] = useState('MCP standardizes agent tool invocation and context synchronization across AI clients.'); const [selectedEmbedModel, setSelectedEmbedModel] = useState('nomic-embed-text'); const [managerAction, setManagerAction] = useState('list_models'); const [toolExecuting, setToolExecuting] = useState(false); const [toolExecutionOutput, setToolExecutionOutput] = useState(null); // JSON-RPC Inspector State const [inspectorMethod, setInspectorMethod] = useState('tools/list'); const [inspectorParams, setInspectorParams] = useState('{}'); const [inspectorResponse, setInspectorResponse] = useState(null); const [inspectorLoading, setInspectorLoading] = useState(false); const baseUrl = window.location.origin; const localSseUrl = `http://localhost:3000/mcp/sse`; const publicSseUrl = `${baseUrl}/mcp/sse`; const directRpcUrl = `${baseUrl}/mcp`; const messagesPostUrl = `${baseUrl}/mcp/messages`; const copyCode = (code: string, key: string) => { navigator.clipboard.writeText(code); setCopiedKey(key); setTimeout(() => setCopiedKey(null), 2000); }; // Connect / Disconnect to live SSE stream const toggleSSEStream = () => { if (sseConnected) { if (sseEventSourceRef.current) { sseEventSourceRef.current.close(); sseEventSourceRef.current = null; } setSseConnected(false); setSseLogs(prev => [{ id: Math.random().toString(36), time: new Date().toLocaleTimeString(), event: 'client_disconnected', data: 'Disconnected from SSE stream endpoint.', }, ...prev]); } else { try { const es = new EventSource('/mcp/sse'); sseEventSourceRef.current = es; es.onopen = () => { setSseConnected(true); setSseLogs(prev => [{ id: Math.random().toString(36), time: new Date().toLocaleTimeString(), event: 'open', data: 'Connected to MCP SSE stream channel.', }, ...prev]); }; es.addEventListener('endpoint', (e: MessageEvent) => { setSseLogs(prev => [{ id: Math.random().toString(36), time: new Date().toLocaleTimeString(), event: 'endpoint', data: e.data, }, ...prev]); }); es.addEventListener('message', (e: MessageEvent) => { setSseLogs(prev => [{ id: Math.random().toString(36), time: new Date().toLocaleTimeString(), event: 'message', data: e.data, }, ...prev]); }); es.onerror = () => { // Keep-alive or reconnection setSsePingCount(p => p + 1); }; } catch (err: any) { console.error('Failed to connect to SSE stream:', err); } } }; useEffect(() => { return () => { if (sseEventSourceRef.current) { sseEventSourceRef.current.close(); } }; }, []); // Probe local Ollama instance const handleProbeOllama = async () => { setProbingOllama(true); try { const res = await fetch('/api/v1/ollama/probe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ endpoint: ollamaEndpoint }), }); const data = await res.json(); setProbeResult(data); } catch (err: any) { setProbeResult({ connected: false, error: err.message, message: 'Could not connect to Ollama probe endpoint.', }); } finally { setProbingOllama(false); } }; // Run local model tool const handleExecuteModelTool = async () => { setToolExecuting(true); try { let toolName = 'ollama_delegate_prompt'; let payload: any = {}; if (activeModelTool === 'prompt') { toolName = 'ollama_delegate_prompt'; payload = { prompt: promptInput, model: selectedSubModel, endpoint: ollamaEndpoint, }; } else if (activeModelTool === 'vision') { toolName = 'ollama_vision_inspect'; payload = { imageUrlOrBase64: visionImageInput, prompt: visionPrompt, model: 'llama3.2-vision', endpoint: ollamaEndpoint, }; } else if (activeModelTool === 'embed') { toolName = 'ollama_embed_document'; payload = { text: embedTextInput, compareText: embedCompareInput, model: selectedEmbedModel, endpoint: ollamaEndpoint, }; } else if (activeModelTool === 'manager') { toolName = 'ollama_gpu_model_manager'; payload = { action: managerAction, endpoint: ollamaEndpoint, }; } else if (activeModelTool === 'nvidia') { toolName = 'nvidia_nim_delegate'; payload = { prompt: promptInput, model: 'meta/llama-3.1-8b-instruct', endpoint: 'http://localhost:8888/v1', }; } const res = await fetch(`/api/v1/tools/${toolName}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }); const data = await res.json(); setToolExecutionOutput(data); } catch (err: any) { setToolExecutionOutput({ error: err.message || 'Execution failed' }); } finally { setToolExecuting(false); } }; // Run JSON-RPC Inspector const runInspectorRPC = async () => { setInspectorLoading(true); try { let parsedParams = {}; try { parsedParams = JSON.parse(inspectorParams); } catch { // use empty object if invalid } const reqPayload: MCPRequest = { jsonrpc: '2.0', id: Math.floor(Math.random() * 1000), method: inspectorMethod, params: parsedParams, }; const res = await fetch('/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(reqPayload), }); const data = await res.json(); setInspectorResponse(data); } catch (err: any) { setInspectorResponse({ jsonrpc: '2.0', error: { code: -32603, message: err.message || 'Failed to send request' }, }); } finally { setInspectorLoading(false); } }; const presetInspector = (method: string, paramsObj: any) => { setInspectorMethod(method); setInspectorParams(JSON.stringify(paramsObj, null, 2)); }; // Client Configs const claudeConfig = JSON.stringify( { mcpServers: { "do-everything-mcp-hub": { url: `${baseUrl}/mcp/sse` } } }, null, 2 ); const cursorConfig = JSON.stringify( { mcpServers: { "local-mcp-hub": { url: `${baseUrl}/mcp/sse`, transport: "sse" } } }, null, 2 ); const openwebuiConfig = `// OpenWebUI / AnythingLLM / LibreChat MCP SSE Connection Endpoint URL: ${baseUrl}/mcp/sse Messages POST: ${baseUrl}/mcp/messages Protocol: MCP JSON-RPC 2.0 (2024-11-05) System Prompt Injection: "You are connected to the universal Do Everything MCP Hub. You have access to local GPU sub-models via Ollama (ollama_delegate_prompt, ollama_vision_inspect, ollama_embed_document), web scraping, code execution, and persistent memory. Call tools whenever user requests tasks matching registered schemas." `; const pythonCode = `import asyncio import httpx async def call_mcp_sse_or_rpc(tool_name: str, arguments: dict): mcp_url = "${baseUrl}/mcp" payload = { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool_name, "arguments": arguments } } async with httpx.AsyncClient(timeout=30.0) as client: response = await client.post(mcp_url, json=payload) return response.json() # Example: Delegate sub-task to local Ollama model (llama3.2:1b) result = asyncio.run(call_mcp_sse_or_rpc("ollama_delegate_prompt", { "prompt": "Summarize this log text in 2 concise bullets", "model": "llama3.2:1b" })) print(result) `; const tsCode = `// Connect to Do Everything MCP Server via SSE or HTTP JSON-RPC import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; async function main() { const transport = new SSEClientTransport(new URL("${baseUrl}/mcp/sse")); const client = new Client({ name: "my-model-agent", version: "1.0.0" }, { capabilities: {} }); await client.connect(transport); // List all available tools including local GPU delegates const tools = await client.listTools(); console.log("Connected tools:", tools); // Call Ollama document embedder const embedRes = await client.callTool({ name: "ollama_embed_document", arguments: { text: "Self-hosted Model Context Protocol server" } }); console.log("Embedding vector:", embedRes); } main(); `; const curlCmd = `curl -X POST ${baseUrl}/mcp \\ -H "Content-Type: application/json" \\ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "ollama_delegate_prompt", "arguments": { "prompt": "Analyze code architecture", "model": "llama3.2:1b" } } }'`; return (
{/* Top Banner */}
Universal MCP SSE Endpoint & Local GPU Power-Up Hub

Direct SSE Model Pointer & Local GPU Delegation Hub

Point any external or local host model (Claude Desktop, Cursor, OpenWebUI, LlamaIndex, Ollama) directly at this server’s SSE address. Empower your main host model to dispatch vision inspection, document vector embeddings, fast sub-model reasoning, and GPU VRAM management to your local hardware.

{/* SECTION 1: SSE ENDPOINT HUB */} {activeMainSection === 'sse-hub' && (
{/* Left 2 Cols: Endpoint Addresses */}

Local & Public SSE Stream Addresses

MCP 2024-11-05 Compliant
{/* Local Address */}
Local SSE Endpoint (For local clients & containers): GET /mcp/sse
{/* Public App URL Address */}
Public / Deployed Web Endpoint: GET /mcp/sse
{/* POST Messages Address */}
Direct JSON-RPC / Messages POST Endpoint: POST /mcp
{/* Right Col: Live SSE Inspector */}
Live SSE Stream Monitor

Subscribes to /mcp/sse in real time to capture protocol handshakes, endpoint discovery events, and keep-alive frames.

{sseLogs.length === 0 ? (
Click "Connect Test" above to stream live SSE packets.
) : ( sseLogs.map((log) => (
event: {log.event} {log.time}
{log.data}
)) )}
Heartbeat: Active (10s) Active Listeners: {sseConnected ? '1 Connected' : '0'}
)} {/* SECTION 2: NVIDIA & OLLAMA LOCAL GPU DELEGATION HUB */} {activeMainSection === 'ollama-gpu' && (
{/* Header & Probe Bar */}

Local GPU Model Delegation & Worker Pool

Your host main model can call on small, specialized local models running on your GPU (Ollama, vLLM, llama.cpp, NVIDIA NIM) for sub-tasks, saving cloud API tokens and enabling zero-latency local vision & embeddings.

{/* Endpoint probe */}
setOllamaEndpoint(e.target.value)} placeholder="http://localhost:11434" className="px-3 py-2 bg-slate-50 border border-slate-300 rounded-xl text-xs font-mono text-slate-800 w-48 sm:w-60 focus:outline-none focus:ring-2 focus:ring-emerald-500" />
{/* Probe Results Banner */} {probeResult && (
{probeResult.connected ? : } {probeResult.connected ? 'Local Ollama Connected & Ready' : 'Local Ollama Offline (Using Smart Simulation Fallback)'}

{probeResult.message}

{probeResult.models && probeResult.models.length > 0 && (
{probeResult.models.map((m: any, i: number) => ( {m.name || m} ))}
)}
)} {/* 4 Specialized Delegation Roles */}
{/* Interactive Test Console */}
{/* Input Form */}
{activeModelTool === 'prompt' && '1. ollama_delegate_prompt'} {activeModelTool === 'vision' && '2. ollama_vision_inspect'} {activeModelTool === 'embed' && '3. ollama_embed_document'} {activeModelTool === 'manager' && '4. ollama_gpu_model_manager'} {activeModelTool === 'nvidia' && '5. nvidia_nim_delegate'} MCP Tool Execution
{/* Sub-tool inputs */} {activeModelTool === 'prompt' && (