#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utilidad para interactuar con el servidor MCP de Infraestructura de Telcotronics (SSE en http://192.168.10.160:3006/sse). Permite: - Consultar herramientas y recursos del MCP de infraestructura. - Buscar hardware, servicios, aplicaciones de IA y servicios externos. - Documentar y registrar servicios del ecosistema de acuerdo con la especificación central. """ import urllib.request import urllib.parse import json import threading import time import sys BASE_URL = "http://192.168.10.160:3006" class McpClient: def __init__(self, base_url=BASE_URL): self.base_url = base_url self.sse_url = f"{base_url}/sse" self.endpoint_path = None self.responses = {} self.stop_event = threading.Event() self.msg_counter = 1 def _sse_listener(self): req = urllib.request.Request(self.sse_url, headers={"Accept": "text/event-stream"}) try: with urllib.request.urlopen(req, timeout=30) as resp: current_event = None for line in resp: if self.stop_event.is_set(): break line_str = line.decode('utf-8').strip() if not line_str: continue if line_str.startswith("event:"): current_event = line_str.split(":", 1)[1].strip() elif line_str.startswith("data:"): data_str = line_str.split(":", 1)[1].strip() if current_event == "endpoint": self.endpoint_path = data_str elif current_event == "message": try: msg = json.loads(data_str) if msg.get("id") is not None: self.responses[msg["id"]] = msg except Exception: pass except Exception as e: pass def connect(self): t = threading.Thread(target=self._sse_listener, daemon=True) t.start() for _ in range(50): if self.endpoint_path: break time.sleep(0.1) if not self.endpoint_path: raise ConnectionError("No se pudo obtener el endpoint SSE del servidor MCP.") self.post_url = urllib.parse.urljoin(self.base_url, self.endpoint_path) # Inicializar sesión MCP self._send_rpc(self.msg_counter, "initialize", { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "agente-app-sentinel-one", "version": "1.0"} }) self._wait_response(self.msg_counter) self.msg_counter += 1 self._send_rpc(None, "notifications/initialized", {}) def _send_rpc(self, msg_id, method, params=None): payload = {"jsonrpc": "2.0", "method": method} if msg_id is not None: payload["id"] = msg_id if params is not None: payload["params"] = params req = urllib.request.Request( self.post_url, data=json.dumps(payload).encode('utf-8'), headers={"Content-Type": "application/json"} ) with urllib.request.urlopen(req, timeout=15) as r: return r.read().decode('utf-8') def _wait_response(self, msg_id, timeout_sec=6.0): start = time.time() while time.time() - start < timeout_sec: if msg_id in self.responses: return self.responses[msg_id] time.sleep(0.08) return self.responses.get(msg_id, {}) def call_tool(self, tool_name, arguments): cid = self.msg_counter self.msg_counter += 1 self._send_rpc(cid, "tools/call", {"name": tool_name, "arguments": arguments}) res = self._wait_response(cid) return res.get("result", {}) def list_tools(self): cid = self.msg_counter self.msg_counter += 1 self._send_rpc(cid, "tools/list", {}) res = self._wait_response(cid) return res.get("result", {}).get("tools", []) def close(self): self.stop_event.set() if __name__ == "__main__": client = McpClient() try: client.connect() if len(sys.argv) > 1 and sys.argv[1] == "tools": tools = client.list_tools() for t in tools: print(f"- {t['name']}: {t.get('description', '')}") elif len(sys.argv) > 2 and sys.argv[1] == "buscar": res = client.call_tool("buscar_infraestructura", {"query": sys.argv[2]}) for c in res.get("content", []): print(c.get("text", "")) else: print("Uso: python3 scripts/mcp_infra.py [tools|buscar ]") finally: client.close()