Explorar el Código

feat(mcp): embedded read-only MCP server at /mcp (#1118)

feat(mcp): embedded read-only MCP server at /mcp (#1118)

Streamable-HTTP MCP server (mcp-go) with seven read-only tools fed from
the latest poller snapshot. Bearer-only API token auth, per-IP rate limit,
audit log, off by default (NETPULSE_MCP_ENABLED=1). First-class integration
in Settings with a restart-less toggle and the token manager in its dialog.

Closes #1114
Nacho hace 2 meses
padre
commit
786b38119d

+ 22 - 0
README.es.md

@@ -294,6 +294,28 @@ OpenWrt deberían funcionar, pero el tuyo sería el primero en contarlo.
 - **[Discusiones](https://github.com/gnacho/netpulse/discussions)**:
   preguntas, ideas y hablar del futuro.
 
+## Asistentes de IA (MCP)
+
+NetPulse lleva un servidor [MCP](https://modelcontextprotocol.io) embebido
+(streamable-HTTP) para que los asistentes de IA puedan consultar tu instancia
+con herramientas de solo lectura: estado de la flota, salud por router,
+dispositivos conocidos, peers WireGuard, estadísticas de AdGuard Home, el
+grafo de topología detectado y las alertas activas. Nada más: sin cambios de
+configuración ni reinicios.
+
+Está **desactivado por defecto**. Para activarlo:
+
+```bash
+NETPULSE_MCP_ENABLED=1
+```
+
+Después crea un token de API en Ajustes > Tokens de API y apunta tu cliente
+MCP a `http://<host-de-netpulse>:<puerto>/mcp` con ese token como Bearer. El
+endpoint solo acepta tokens de API (nunca la cookie de sesión), lleva rate
+limit y cada llamada a tool queda registrada en el log de auditoría. Mantén
+el puerto en tu LAN o detrás de un firewall: quien tenga el token puede leer
+el estado completo de tu red.
+
 ## Desarrollo
 
 ```bash

+ 21 - 0
README.md

@@ -284,6 +284,27 @@ first to tell.
 - **[Discussions](https://github.com/gnacho/netpulse/discussions)**: questions,
   ideas and shape-the-future talk.
 
+## AI assistants (MCP)
+
+NetPulse ships an embedded [MCP](https://modelcontextprotocol.io) server
+(streamable-HTTP) so AI assistants can query your instance with read-only
+tools: fleet status, per-router health, known devices, WireGuard peers,
+AdGuard Home stats, the detected topology graph and active alerts. Nothing
+else: no configuration changes, no restarts.
+
+It is **disabled by default**. To enable it:
+
+```bash
+NETPULSE_MCP_ENABLED=1
+```
+
+Then create an API token in Settings > API tokens and point your MCP client
+at `http://<your-netpulse-host>:<port>/mcp` with that token as the Bearer
+token. The endpoint only accepts API tokens (never the session cookie), is
+rate limited, and every tool call is logged for audit. Keep the port on your
+LAN or behind a firewall: anyone with the token can read your whole network
+state.
+
 ## Development
 
 ```bash

+ 12 - 0
app/public/locales/en/translation.json

@@ -1575,6 +1575,7 @@
       "integrationsGroup": "Integrations",
       "proxmoxCaption": "Cluster inventory (hypervisors and CTs)",
       "mqttCaption": "Fleet state published to the MQTT broker",
+      "mcpCaption": "Read-only queries for AI assistants",
       "configure": "Configure {{name}}"
     },
     "session": {
@@ -1798,6 +1799,17 @@
       "urgentOnly": "Urgent alerts only",
       "urgentOnlyHint": "On: the channel receives only urgent alerts (recommended, the usual behavior). Turn it off to receive everything that shows in the feed according to the level chosen in Alerts."
     },
+    "mcp": {
+      "title": "MCP — AI assistants",
+      "description": "Exposes an MCP server (streamable-HTTP) at /mcp so AI assistants can query your instance with read-only tools: fleet status, per-router health, devices, WireGuard, AdGuard, topology and alerts. No configuration changes, no restarts.",
+      "enabled": "Endpoint /mcp active",
+      "lockedHint": "The /mcp endpoint is not enabled on this server: add NETPULSE_MCP_ENABLED=1 to its environment (e.g. the .env next to the binary) and restart the service.",
+      "endpoint": "Endpoint",
+      "endpointHint": "Only accepts API tokens as Bearer (never the session cookie), is rate limited, and every call lands in the audit log. Keep it on your LAN or behind a firewall.",
+      "copy": "Copy endpoint",
+      "tokensTitle": "API tokens",
+      "tokensHint": "These tokens are the only credential for the /mcp endpoint: create one per assistant or integration and revoke it when no longer needed."
+    },
     "mqtt": {
       "title": "MQTT / Home Assistant",
       "description": "Publishes the fleet state to an MQTT broker for Home Assistant (automatic discovery) and pushes the configuration to NetGrip routers.",

+ 12 - 0
app/public/locales/es/translation.json

@@ -1575,6 +1575,7 @@
       "integrationsGroup": "Integraciones",
       "proxmoxCaption": "Inventario del cluster (hipervisores y CTs)",
       "mqttCaption": "Publicación del estado en el broker MQTT",
+      "mcpCaption": "Consultas de solo lectura para asistentes de IA",
       "configure": "Configurar {{name}}"
     },
     "session": {
@@ -1798,6 +1799,17 @@
       "urgentOnly": "Solo alertas urgentes",
       "urgentOnlyHint": "Activado: el canal recibe solo las alertas urgentes (recomendado, el comportamiento habitual). Desactívalo para que llegue todo lo que aparece en el feed según el nivel elegido en Alertas."
     },
+    "mcp": {
+      "title": "MCP — asistentes de IA",
+      "description": "Expone un servidor MCP (streamable-HTTP) en /mcp para que los asistentes de IA consulten tu instancia con herramientas de solo lectura: estado de la flota, salud por router, dispositivos, WireGuard, AdGuard, topología y alertas. Sin cambios de configuración ni reinicios.",
+      "enabled": "Endpoint /mcp activo",
+      "lockedHint": "El endpoint /mcp no está habilitado en este servidor: añade NETPULSE_MCP_ENABLED=1 a su entorno (p. ej. en el .env junto al binario) y reinicia el servicio.",
+      "endpoint": "Endpoint",
+      "endpointHint": "Solo acepta tokens de API como Bearer (nunca la cookie de sesión), lleva rate limit y cada llamada queda en el log de auditoría. Mantenlo en tu LAN o detrás de un firewall.",
+      "copy": "Copiar endpoint",
+      "tokensTitle": "Tokens de API",
+      "tokensHint": "Estos tokens son la única credencial del endpoint /mcp: crea uno por asistente o integración y revócalo cuando deje de usarse."
+    },
     "mqtt": {
       "title": "MQTT / Home Assistant",
       "description": "Publica el estado de la flota en un broker MQTT para Home Assistant (descubrimiento automático) y propaga la configuración a los routers NetGrip.",

+ 24 - 20
app/src/hooks/useIntegrations.ts

@@ -11,16 +11,32 @@ export interface IntegrationsState {
   telegram: boolean
   proxmox: boolean
   mqtt: boolean
+  mcp: boolean
 }
 
-const DEFAULTS: IntegrationsState = { ntfy: true, telegram: true, proxmox: true, mqtt: false }
+const DEFAULTS: IntegrationsState = { ntfy: true, telegram: true, proxmox: true, mqtt: false, mcp: false }
+
+// parseIntegrations: mapea la view del servidor (#968 + MCP #1114). mcp solo
+// es true si el despliegue lo habilitó por env (mcpLocked=false) y el toggle
+// está activo; mcpLocked=true (sin env) lo muestra apagado y bloqueado.
+function parseIntegrations(d: Record<string, unknown>): IntegrationsState {
+  return {
+    ntfy: d.ntfy !== false,
+    telegram: d.telegram !== false,
+    proxmox: d.proxmox !== false,
+    mqtt: d.mqtt === true,
+    mcp: d.mcp === true,
+  }
+}
 
 export function useIntegrations(enabled = true): {
   integrations: IntegrationsState
   loaded: boolean
+  mcpLocked: boolean
   setIntegration: (k: keyof IntegrationsState, v: boolean) => void
 } {
   const [integrations, setIntegrations] = useState<IntegrationsState>(DEFAULTS)
+  const [mcpLocked, setMcpLocked] = useState(true)
   const [loaded, setLoaded] = useState(false)
 
   useEffect(() => {
@@ -30,12 +46,8 @@ export function useIntegrations(enabled = true): {
       .then((r) => (r.ok ? r.json() : null))
       .then((d) => {
         if (!alive || !d) return
-        setIntegrations({
-          ntfy: d.ntfy !== false,
-          telegram: d.telegram !== false,
-          proxmox: d.proxmox !== false,
-          mqtt: d.mqtt === true,
-        })
+        setIntegrations(parseIntegrations(d))
+        setMcpLocked(d.mcpLocked === true)
         setLoaded(true)
       })
       .catch(() => undefined)
@@ -59,12 +71,8 @@ export function useIntegrations(enabled = true): {
       })
       .then((d) => {
         if (d) {
-          setIntegrations({
-            ntfy: d.ntfy !== false,
-            telegram: d.telegram !== false,
-            proxmox: d.proxmox !== false,
-            mqtt: d.mqtt === true,
-          })
+          setIntegrations(parseIntegrations(d))
+          setMcpLocked(d.mcpLocked === true)
         }
       })
       .catch(() => {
@@ -73,17 +81,13 @@ export function useIntegrations(enabled = true): {
           .then((r) => (r.ok ? r.json() : null))
           .then((d) => {
             if (d) {
-              setIntegrations({
-                ntfy: d.ntfy !== false,
-                telegram: d.telegram !== false,
-                proxmox: d.proxmox !== false,
-                mqtt: d.mqtt === true,
-              })
+              setIntegrations(parseIntegrations(d))
+              setMcpLocked(d.mcpLocked === true)
             }
           })
           .catch(() => undefined)
       })
   }, [])
 
-  return { integrations, loaded, setIntegration }
+  return { integrations, loaded, mcpLocked, setIntegration }
 }

+ 92 - 5
app/src/pages/Settings.tsx

@@ -3792,7 +3792,7 @@ function SpeedtestRecent({ disabled = false }: { disabled?: boolean }) {
 
 // Clave de integración configurable desde la tarjeta (icono Settings2 que
 // abre el Dialog con su manager, #968).
-type IntegrationDialogKey = 'adguard' | 'proxmox' | 'ntfy' | 'telegram' | 'mqtt'
+type IntegrationDialogKey = 'adguard' | 'proxmox' | 'ntfy' | 'telegram' | 'mqtt' | 'mcp'
 
 // Los diálogos de configuración van GRANDES (#968, #977): el manager
 // (formularios, tablas) necesita el ancho casi completo. Wrapper compartido
@@ -3816,6 +3816,82 @@ function ConfigGear({ label, onClick, disabled = false }: { label: string; onCli
   )
 }
 
+// ---------------------------------------------------------------------------
+// Integración MCP (#1114): endpoint /mcp para asistentes de IA. El toggle es
+// el server-side settings.integrations.mcp (aplica sin reinicio); sin
+// NETPULSE_MCP_ENABLED=1 en el servidor el endpoint no existe y el toggle
+// queda bloqueado. Los tokens de API son la ÚNICA auth del endpoint: se
+// gestionan aquí mismo (crear/revocar).
+// ---------------------------------------------------------------------------
+function McpIntegration({ onToggle }: { onToggle: () => void }) {
+  const { t } = useTranslation()
+  const { integrations, setIntegration, mcpLocked } = useIntegrations()
+  const [copied, setCopied] = useState(false)
+  const endpoint = `${window.location.origin}/mcp`
+
+  return (
+    <div>
+      <div className="flex items-center gap-2">
+        <KeyRound className="h-4 w-4 text-accent" strokeWidth={1.75} />
+        <h3 className="text-sm font-semibold text-text-primary">{t('settings.mcp.title')}</h3>
+      </div>
+      <p className="mt-1 text-caption text-text-muted">{t('settings.mcp.description')}</p>
+
+      {mcpLocked ? (
+        <div className="mt-3 flex items-start gap-2 rounded-lg border border-warning/30 bg-warning/5 px-3 py-2 text-caption text-text-secondary">
+          <CircleAlert className="mt-0.5 h-4 w-4 shrink-0 text-warning" strokeWidth={1.75} />
+          <span>{t('settings.mcp.lockedHint')}</span>
+        </div>
+      ) : (
+        <div className="mt-2 divide-y divide-border/60">
+          <SwitchRow
+            label={t('settings.mcp.enabled')}
+            checked={integrations.mcp}
+            disabled={mcpLocked}
+            onCheckedChange={(v) => {
+              setIntegration('mcp', v)
+              onToggle()
+            }}
+          />
+        </div>
+      )}
+
+      <div className="mt-3">
+        <div className="text-label uppercase text-text-muted">{t('settings.mcp.endpoint')}</div>
+        <div className="mt-1 flex items-center gap-2">
+          <code className="min-w-0 flex-1 truncate rounded-lg bg-elevated px-3 py-2 text-caption text-text-primary">{endpoint}</code>
+          <button
+            type="button"
+            onClick={() => {
+              void copyToClipboard(endpoint).then(() => {
+                setCopied(true)
+                setTimeout(() => setCopied(false), 1500)
+              })
+            }}
+            aria-label={t('settings.mcp.copy')}
+            title={t('settings.mcp.copy')}
+            className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent"
+          >
+            {copied ? <Check className="h-4 w-4 text-accent" strokeWidth={1.75} /> : <Copy className="h-4 w-4" strokeWidth={1.75} />}
+          </button>
+        </div>
+        <p className="mt-1.5 flex items-start gap-1.5 text-caption text-text-muted">
+          <ShieldCheck className="mt-0.5 h-3.5 w-3.5 shrink-0" strokeWidth={1.75} />
+          {t('settings.mcp.endpointHint')}
+        </p>
+      </div>
+
+      <div className="mt-5 border-t border-border pt-4">
+        <div className="text-label uppercase text-text-muted">{t('settings.mcp.tokensTitle')}</div>
+        <p className="mt-1 text-caption text-text-muted">{t('settings.mcp.tokensHint')}</p>
+        <div className="mt-2">
+          <TokensManager />
+        </div>
+      </div>
+    </div>
+  )
+}
+
 function ServicesCard({
   reduce,
   onSaved,
@@ -3834,8 +3910,10 @@ function ServicesCard({
   const { t } = useTranslation()
   const [services, setService] = useServicesVisibility()
   // Toggles server-side de integraciones (#968): se leen del servidor al
-  // montar (coherencia entre navegadores) y se escriben al cambiar.
-  const { integrations, setIntegration } = useIntegrations(!disabled)
+  // montar (coherencia entre navegadores) y se escriben al cambiar. mcpLocked
+  // (#1114): sin NETPULSE_MCP_ENABLED=1 el endpoint /mcp no existe y el
+  // toggle queda bloqueado con una explicación.
+  const { integrations, setIntegration, mcpLocked } = useIntegrations(!disabled)
   const [dialog, setDialog] = useState<IntegrationDialogKey | null>(null)
   const networkRows: { key: keyof ServicesVisibility; label: string; caption: string; dialogKey?: IntegrationDialogKey }[] = [
     { key: 'adguard', label: 'AdGuard Home', caption: t('settings.services.adguardCaption'), dialogKey: 'adguard' },
@@ -3845,9 +3923,10 @@ function ServicesCard({
   // #996: el grupo Integraciones se queda SOLO con MQTT y Proxmox (estado e
   // inventario); ntfy y Telegram son canales de aviso y viven en la tarjeta
   // de Notificaciones.
-  const integrationRows: { key: keyof IntegrationsState; label: string; caption: string; dialogKey: IntegrationDialogKey }[] = [
+  const integrationRows: { key: keyof IntegrationsState; label: string; caption: string; dialogKey: IntegrationDialogKey; locked?: boolean }[] = [
     { key: 'proxmox', label: 'Proxmox VE', caption: t('settings.services.proxmoxCaption'), dialogKey: 'proxmox' },
     { key: 'mqtt', label: 'MQTT', caption: t('settings.services.mqttCaption'), dialogKey: 'mqtt' },
+    { key: 'mcp', label: 'MCP', caption: t('settings.services.mcpCaption'), dialogKey: 'mcp', locked: mcpLocked },
   ]
 
   // AdGuard (#813): el toggle de Servicios también controla el sondeo y la
@@ -3956,7 +4035,7 @@ function ServicesCard({
               label={row.label}
               caption={row.caption}
               checked={integrations[row.key]}
-              disabled={disabled}
+              disabled={disabled || row.locked}
               trailing={gear(row.dialogKey, row.label)}
                 onCheckedChange={(v) => {
                   setIntegration(row.key, v)
@@ -3994,6 +4073,14 @@ function ServicesCard({
           <MqttCard onSaved={() => { onSaved(); setDialog(null) }} bare />
         </DialogContent>
       </Dialog>
+      <Dialog open={dialog === 'mcp'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
+        <DialogContent className={integrationDialogCls} aria-describedby={undefined}>
+          <DialogHeader>
+            <DialogTitle className="sr-only">{t('settings.mcp.title')}</DialogTitle>
+          </DialogHeader>
+          <McpIntegration onToggle={() => onSaved()} />
+        </DialogContent>
+      </Dialog>
     </Card>
   )
 }

+ 21 - 0
server-go/cmd/netpulse/main.go

@@ -45,6 +45,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 	"github.com/gnacho/netpulse/server-go/internal/firmware"
 	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/mcp"
 	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
 	"github.com/gnacho/netpulse/server-go/internal/ntfy"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
@@ -714,6 +715,25 @@ func run() error {
 
 	mqttMgr := mqttpub.NewManager(mqttpub.LoadConfig(mqttpub.SQLKV{DB: dbHandle.DB}), httpapi.Version, p.LastOverview, cfg.DemoMode)
 
+	// MCP (#1114): servidor MCP embebido (streamable-HTTP en /mcp), solo si
+	// NETPULSE_MCP_ENABLED=1. Sin token store NO se monta: el endpoint solo
+	// existe con su auth Bearer (fail-closed, también en mcp.Handler).
+	var mcpSrv *mcp.Server
+	if cfg.MCPEnabled && tokenStore != nil {
+		var engine *alerts.Engine
+		if adapter != nil {
+			engine = adapter.AlertsEngine()
+		}
+		mcpSrv = mcp.New(mcp.Deps{
+			LastOverview: p.LastOverview,
+			Engine:       engine,
+			Version:      httpapi.Version,
+		})
+		log.Printf("[netpulse] MCP server activo en /mcp (streamable-HTTP, auth: API token Bearer, LAN-only)")
+	} else if cfg.MCPEnabled {
+		log.Printf("[netpulse] aviso: NETPULSE_MCP_ENABLED=1 pero no hay token store; MCP desactivado")
+	}
+
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config:          cfg,
 		DB:              dbHandle,
@@ -740,6 +760,7 @@ func run() error {
 		Speedtest:       stScheduler,
 		AlertEmitter:    adapter.AlertsEngine(),
 		ChannelPlan:     chPlan,
+		MCP:             mcpSrv,
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},

+ 5 - 0
server-go/go.mod

@@ -8,6 +8,7 @@ require (
 	github.com/gonzalop/mq v0.9.10
 	github.com/gosnmp/gosnmp v1.44.0
 	github.com/m-lab/ndt7-client-go v0.10.1
+	github.com/mark3labs/mcp-go v1.1.1
 	github.com/showwin/speedtest-go v1.8.3
 	golang.org/x/crypto v0.55.0
 	golang.org/x/net v0.58.0
@@ -23,6 +24,7 @@ require (
 	github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de // indirect
 	github.com/dustin/go-humanize v1.0.1 // indirect
 	github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
+	github.com/google/jsonschema-go v0.4.2 // indirect
 	github.com/google/uuid v1.6.0 // indirect
 	github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect
 	github.com/m-lab/go v0.1.76 // indirect
@@ -32,6 +34,9 @@ require (
 	github.com/mattn/go-isatty v0.0.24 // indirect
 	github.com/ncruces/go-strftime v1.0.0 // indirect
 	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+	github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
+	github.com/spf13/cast v1.7.1 // indirect
+	github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
 	golang.org/x/sys v0.47.0 // indirect
 	modernc.org/libc v1.74.4 // indirect
 	modernc.org/mathutil v1.7.1 // indirect

+ 22 - 0
server-go/go.sum

@@ -38,6 +38,8 @@ github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/Buvy
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
 github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
 github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
 github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g=
@@ -46,6 +48,8 @@ github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg
 github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=
 github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
 github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
 github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
 github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
 github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
@@ -64,6 +68,10 @@ github.com/gomodule/redigo v1.9.3/go.mod h1:KsU3hiK/Ay8U42qpaJk+kuNa3C+spxapWpM+
 github.com/gonzalop/mq v0.9.10 h1:7uaSKq/m/n0ElV3SJtXQTZnI5HyHtgoNIL/ufsxFU+8=
 github.com/gonzalop/mq v0.9.10/go.mod h1:chaGtxnueekistsTKhDnLOoNdJPKEI6vadlUBRQS2ok=
 github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
+github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
 github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
 github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
 github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
@@ -92,6 +100,10 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
 github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
 github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
 github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
 github.com/m-lab/access v0.0.13 h1:ZCtOEZp2qmcp0CFUBP21r42miNqqWu7gQVa8GxzASts=
 github.com/m-lab/access v0.0.13/go.mod h1:V3hWcsesp1kDgIRQOUXRU8uDTfUhYv/D0SJ4g3WOUS8=
 github.com/m-lab/go v0.1.76 h1:zdxI5k0AIZaf99Cyh7zjNyNBBZxTlhIJvWg7AX710bU=
@@ -108,6 +120,8 @@ github.com/m-lab/uuid v1.0.2 h1:rlkqHQ0fXnj4VtqWElJkc3KgCvOYf3SSZgRRxbycHN8=
 github.com/m-lab/uuid v1.0.2/go.mod h1:SAjW6jto9p0Ms5ZCaTCVe2GTu1pvctlr6W/TEMQ1/vg=
 github.com/m-lab/uuid-annotator v0.5.10 h1:ZojVfeiFDdhtN/GqqxxRtBPVxSY4Focf6YRr7Om9XgM=
 github.com/m-lab/uuid-annotator v0.5.10/go.mod h1:djp2929KpTtHEJMVubnjniks5sEMVtyvDaBKR+8QVqQ=
+github.com/mark3labs/mcp-go v1.1.1 h1:PMZjyayCF01Y4R2kQXgDtsmxVLOdq1Mol4CnzzTYSEo=
+github.com/mark3labs/mcp-go v1.1.1/go.mod h1:r2fW4o3wsoJ7IMsx1Wuq5xeP8PRGXPDfNveoGAYbb/s=
 github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
 github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
 github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
@@ -142,17 +156,25 @@ github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05Zp
 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
 github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
 github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7PQSMz9NShzorzCiG2fk9+xuCgLkPeCvMHYR2OWg=
 github.com/showwin/speedtest-go v1.8.3 h1:x988hyZFsa5V1EEwox84niAji632uxBTk8Clsc1itF8=
 github.com/showwin/speedtest-go v1.8.3/go.mod h1:N4bn2lgNNWmfJyC1AIHD4T5wYhU+9D21OfacVhJsxiU=
 github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
 github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
+github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
+github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
 github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
 github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
 github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
 github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
 go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=
 go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=

+ 16 - 0
server-go/internal/config/config.go

@@ -69,6 +69,7 @@ type Config struct {
 	AgentAutoenroll  bool   // AGENT_AUTOENROLL=1: el responder UDP entrega token de alta y /pair lo acepta (#367)
 	Onbox            bool   // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS)
 	GhostPortEnabled bool   // GHOST_PORT_ENABLED=1: activa alertas de ghost port (#419); default false
+	MCPEnabled       bool   // NETPULSE_MCP_ENABLED=1: servidor MCP embebido en /mcp (#1114); default false
 	// NETPULSE_TLS_ENABLED=1: listener HTTPS adicional (puerto NETPULSE_TLS_PORT,
 	// default 443) junto al HTTP de PORT. Opt-in: sin la variable, arranque
 	// idéntico al actual. El modo on-box ya sirve HTTPS en PORT (Fase 9) y no
@@ -454,6 +455,20 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		}
 	}
 
+	// NETPULSE_MCP_ENABLED: '0'|'1', opcional (#1114) - default false. Activa
+	// el endpoint /mcp (streamable-HTTP) para asistentes AI; SOLO auth por API
+	// token Bearer, nunca cookie de sesión. El puerto debe quedar en LAN.
+	mcpEnabled := false
+	if v, ok := env["NETPULSE_MCP_ENABLED"]; ok && v != "" {
+		switch v {
+		case "0":
+		case "1":
+			mcpEnabled = true
+		default:
+			errs.issues = append(errs.issues, issue{"NETPULSE_MCP_ENABLED", "Invalid enum value. Expected '0' | '1'"})
+		}
+	}
+
 	// NETPULSE_RTL_PASS / NETPULSE_RTL_POLL_S: sondeo HTTP de la consola de
 	// switches RTLPlayground (KP-9000) para firmware + uptime (#639). La pass
 	// por defecto es la del firmware tras flasheo; la cadencia 300 s (5 min).
@@ -624,6 +639,7 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		AgentAutoenroll:   agentAutoenroll,
 		Onbox:             onbox,
 		GhostPortEnabled:  ghostPortEnabled,
+		MCPEnabled:        mcpEnabled,
 		RTLConsolePass:    rtlPass,
 		RTLConsolePollSec: rtlPollSec,
 		PollIntervalSec:   pollIntervalSec,

+ 158 - 0
server-go/internal/httpapi/mcp_gate_test.go

@@ -0,0 +1,158 @@
+// mcp_gate_test.go - /mcp como integración (#1114): el toggle
+// settings.integrations.mcp (default activo cuando el endpoint está montado
+// vía NETPULSE_MCP_ENABLED=1) apaga el endpoint con 404 sin reiniciar.
+package httpapi_test
+
+import (
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/apitoken"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/channelplan"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/configbackup"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/mcp"
+	"github.com/gnacho/netpulse/server-go/internal/orchestr"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+// makeMCPTestServer levanta la app real con NETPULSE_MCP_ENABLED=1 y el
+// servidor MCP montado (poller sin snapshot: los tools dan isError, el gate
+// no depende de ello).
+func makeMCPTestServer(t *testing.T) *testServer {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+		"NETPULSE_MCP_ENABLED": "1",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	if err := apitoken.EnsureSchema(d); err != nil {
+		t.Fatalf("api_tokens schema: %v", err)
+	}
+	tokenStore := apitoken.NewStore(d, secret)
+	configBackup, err := configbackup.NewStore(d)
+	if err != nil {
+		t.Fatalf("config backup store: %v", err)
+	}
+	mcpSrv := mcp.New(mcp.Deps{LastOverview: func() *adapters.Overview { return nil }, Version: "test"})
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
+		Secret: secret, Started: time.Now(), TokenStore: tokenStore,
+		ConfigBackup: configBackup, Orchestr: orchestr.New(d), Agents: adapters.NewAgentRegistry(0),
+		ChannelPlan: channelplan.NewStore(d.DB), MCP: mcpSrv,
+	})
+	srv := httptest.NewServer(handler)
+	t.Cleanup(func() { srv.Close(); d.Close() })
+	return &testServer{Server: srv, db: d, secret: secret}
+}
+
+func mcpPost(t *testing.T, url, cookie, body string) (int, string) {
+	t.Helper()
+	req, err := http.NewRequest("POST", url+"/mcp", strings.NewReader(body))
+	if err != nil {
+		t.Fatalf("NewRequest: %v", err)
+	}
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Accept", "application/json")
+	if cookie != "" {
+		req.Header.Set("Cookie", cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("Do: %v", err)
+	}
+	defer res.Body.Close()
+	buf := new(strings.Builder)
+	_, _ = io.Copy(buf, res.Body)
+	return res.StatusCode, buf.String()
+}
+
+func TestMCPGateDefaultOn(t *testing.T) {
+	srv := makeMCPTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	// View: mcp activo (montado + default on) y no bloqueado.
+	res, body := wanSpeedRequest(t, "GET", srv.URL, "/api/settings/integrations", cookie, "")
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("GET integrations: status %d", res.StatusCode)
+	}
+	if body["mcp"] != true || body["mcpLocked"] != false {
+		t.Fatalf("view mcp: %v / locked %v, esperado true/false", body["mcp"], body["mcpLocked"])
+	}
+
+	// /mcp responde (401 sin token Bearer: la auth propia sigue aplicando).
+	status, _ := mcpPost(t, srv.URL, "", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
+	if status != http.StatusUnauthorized {
+		t.Fatalf("/mcp sin token: status %d, esperado 401 (endpoint vivo)", status)
+	}
+}
+
+func TestMCPGateToggleOffHidesEndpoint(t *testing.T) {
+	srv := makeMCPTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	// Apagar la integración: sin reinicio el endpoint desaparece (404).
+	res, body := wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{"mcp":false}`)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT mcp=false: status %d (%v)", res.StatusCode, body)
+	}
+	if body["mcp"] != false {
+		t.Fatalf("echo mcp: %v, esperado false", body["mcp"])
+	}
+	status, _ := mcpPost(t, srv.URL, "", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
+	if status != http.StatusNotFound {
+		t.Fatalf("/mcp con integración off: status %d, esperado 404", status)
+	}
+
+	// Reactivar: vuelve a responder (401) sin reiniciar.
+	res, body = wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{"mcp":true}`)
+	if res.StatusCode != http.StatusOK || body["mcp"] != true {
+		t.Fatalf("PUT mcp=true: status %d (%v)", res.StatusCode, body)
+	}
+	status, _ = mcpPost(t, srv.URL, "", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
+	if status != http.StatusUnauthorized {
+		t.Fatalf("/mcp reactivado: status %d, esperado 401", status)
+	}
+}
+
+func TestMCPLockedWithoutEnv(t *testing.T) {
+	// Sin NETPULSE_MCP_ENABLED el endpoint no se monta: la view lo reporta
+	// bloqueado y /mcp es 404 aunque el toggle kv diga otra cosa.
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	res, body := wanSpeedRequest(t, "GET", srv.URL, "/api/settings/integrations", cookie, "")
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("GET integrations: status %d", res.StatusCode)
+	}
+	if body["mcp"] != false || body["mcpLocked"] != true {
+		t.Fatalf("view sin env: mcp %v / locked %v, esperado false/true", body["mcp"], body["mcpLocked"])
+	}
+	status, _ := mcpPost(t, srv.URL, "", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)
+	if status != http.StatusNotFound {
+		t.Fatalf("/mcp sin env: status %d, esperado 404 (no montado)", status)
+	}
+}

+ 38 - 1
server-go/internal/httpapi/server.go

@@ -39,6 +39,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/firmware"
 	"github.com/gnacho/netpulse/server-go/internal/internethealth"
+	"github.com/gnacho/netpulse/server-go/internal/mcp"
 	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/pathanalysis"
@@ -135,6 +136,10 @@ type Deps struct {
 	AlertEmitter interface {
 		Emit(ev alerts.AlertEvent) bool
 	}
+	// MCP: servidor MCP embebido (#1114). nil → sin endpoint /mcp. Cuando se
+	// monta, va FUERA de RequireAuth (auth Bearer propia por API token, nunca
+	// cookie) con rate limit y fail-closed sin TokenStore.
+	MCP *mcp.Server
 }
 
 type server struct {
@@ -213,6 +218,9 @@ type server struct {
 	// TokenStore: bearer tokens de API (#330). nil = sin tokens.
 	tokenStore *apitoken.Store
 
+	// MCP: servidor MCP embebido (#1114). nil = sin endpoint /mcp.
+	mcp *mcp.Server
+
 	// CollectorReader: lector read-only de metrics.db del sidecar (#328).
 	collectorReader *collectorreader.Reader
 
@@ -261,6 +269,7 @@ func NewHandler(d Deps) http.Handler {
 		ingestLimit:     newIPRateLimit(ingestRateLimit, ingestRateWindow),
 		upgrades:        newUpgradeTracker(),
 		tokenStore:      d.TokenStore,
+		mcp:             d.MCP,
 		collectorReader: d.CollectorReader,
 		baselines:       d.Baselines,
 		internetHealth:  d.InternetHealth,
@@ -565,7 +574,35 @@ func NewHandler(d Deps) http.Handler {
 		tv = s.tokenStore
 	}
 	s.registerHTTPS(mux)
-	return requestID(security.Middleware(s.hsts, auth.RequireSameOrigin(auth.RequireAuth(s.db, s.secret, tv, s.demoReadOnly(noStoreMux(mux))))))
+	// /mcp (#1114): streamable-HTTP MCP con auth Bearer propia (API token) y
+	// rate limit. Va en un mux EXTERNO al de sesión: RequireAuth queda fuera
+	// a propósito (nunca acepta cookie; spec fase 3.5) y security headers + HSTS
+	// siguen aplicando al envolver el mux externo completo.
+	var h http.Handler = auth.RequireSameOrigin(auth.RequireAuth(s.db, s.secret, tv, s.demoReadOnly(noStoreMux(mux))))
+	if d.MCP != nil {
+		outer := http.NewServeMux()
+		// Gate de integración (#1114): con el toggle apagado el endpoint
+		// DESAPARECE (404, no 403: no confirma su existencia a un escáner).
+		// Va antes de la auth Bearer propia del MCP.
+		outer.Handle("/mcp", s.mcpIntegrationGate(d.MCP.Handler(s.tokenStore)))
+		outer.Handle("/", h)
+		h = outer
+	}
+	return requestID(security.Middleware(s.hsts, h))
+}
+
+// mcpIntegrationGate deja pasar /mcp solo con la integración activada en
+// Ajustes (#1114). El gate lee la kv por petición: el toggle aplica sin
+// reiniciar. Default activo cuando el endpoint está montado (el opt-in fue
+// el env del despliegue); la UI puede apagarlo.
+func (s *server) mcpIntegrationGate(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if !kvGetDefaultOn(s.db.DB, integrationMCPKey) {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		next.ServeHTTP(w, r)
+	})
 }
 
 // requestID lee o genera un x-request-id para cada petición y lo expone en

+ 23 - 8
server-go/internal/httpapi/settings.go

@@ -26,6 +26,10 @@ const (
 	integrationNtfyKey     = "settings.integrations.ntfy"
 	integrationTelegramKey = "settings.integrations.telegram"
 	integrationProxmoxKey  = "settings.integrations.proxmox"
+	// integrationMCPKey: toggle del endpoint /mcp (#1114). El endpoint solo
+	// EXISTE si el env NETPULSE_MCP_ENABLED=1 (opt-in duro del despliegue);
+	// esta clave (default activa) permite apagarlo desde Ajustes sin reinicio.
+	integrationMCPKey = "settings.integrations.mcp"
 )
 
 // adguardServiceKey: si el usuario monitoriza AdGuard (#813). Ausente = SÍ
@@ -152,12 +156,13 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 			Telegram *bool `json:"telegram"`
 			Proxmox  *bool `json:"proxmox"`
 			MQTT     *bool `json:"mqtt"`
+			MCP      *bool `json:"mcp"`
 		}
 		if st := readJSONBody(w, r, &body); st != 0 {
 			writeBodyError(w, st, "invalid_body", "")
 			return
 		}
-		if body.Ntfy == nil && body.Telegram == nil && body.Proxmox == nil && body.MQTT == nil {
+		if body.Ntfy == nil && body.Telegram == nil && body.Proxmox == nil && body.MQTT == nil && body.MCP == nil {
 			writeError(w, http.StatusBadRequest, "invalid_input", "at least one integration key is required")
 			return
 		}
@@ -173,6 +178,7 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 			{body.Ntfy, integrationNtfyKey, "ntfy.enabled"},
 			{body.Telegram, integrationTelegramKey, "telegram.enabled"},
 			{body.Proxmox, integrationProxmoxKey, ""},
+			{body.MCP, integrationMCPKey, ""},
 		} {
 			if p.flag == nil {
 				continue
@@ -275,20 +281,29 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 
 // integrationsView: estado efectivo de los toggles server-side (#968).
 // Ausente = activo para ntfy/telegram/proxmox; MQTT refleja la config
-// efectiva del manager (env + kv).
-func (s *server) integrationsView() map[string]bool {
+// efectiva del manager (env + kv). MCP (#1114): false con mcpLocked=true
+// cuando el despliegue no lo habilitó por env (el endpoint no existe).
+func (s *server) integrationsView() map[string]any {
 	mqtt := kvGet(s.db.DB, "mqtt.enabled") == "true"
 	if s.mqtt != nil {
 		mqtt = s.mqtt.Config().Enabled
 	}
-	return map[string]bool{
-		"ntfy":     kvGetDefaultOn(s.db.DB, integrationNtfyKey),
-		"telegram": kvGetDefaultOn(s.db.DB, integrationTelegramKey),
-		"proxmox":  kvGetDefaultOn(s.db.DB, integrationProxmoxKey),
-		"mqtt":     mqtt,
+	return map[string]any{
+		"ntfy":      kvGetDefaultOn(s.db.DB, integrationNtfyKey),
+		"telegram":  kvGetDefaultOn(s.db.DB, integrationTelegramKey),
+		"proxmox":   kvGetDefaultOn(s.db.DB, integrationProxmoxKey),
+		"mqtt":      mqtt,
+		"mcp":       s.mcpMounted() && kvGetDefaultOn(s.db.DB, integrationMCPKey),
+		"mcpLocked": !s.mcpMounted(),
 	}
 }
 
+// mcpMounted: el endpoint /mcp existe en este proceso (opt-in duro por env,
+// #1114). El toggle de integración solo puede apagarlo, nunca montarlo.
+func (s *server) mcpMounted() bool {
+	return s.cfg != nil && s.cfg.MCPEnabled && s.mcp != nil
+}
+
 // setMQTTEnabled cambia SOLO el flag enabled del publisher MQTT (#968): carga
 // la config efectiva, conmuta y reaplica (sin tocar host/credenciales). Sin
 // manager (tests) cae a escribir la clave kv directamente.

+ 108 - 0
server-go/internal/mcp/auth.go

@@ -0,0 +1,108 @@
+package mcp
+
+import (
+	"encoding/json"
+	"net/http"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/apitoken"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+// Handler devuelve el handler HTTP de /mcp: rate limit por IP → auth Bearer
+// por API token → servidor MCP streamable-HTTP. La cadena va en este orden
+// para que el brute-force de tokens también quede limitado.
+//
+// SOLO acepta API tokens (internal/apitoken): nunca la cookie de sesión, para
+// no mezclar superficies CSRF con clientes AI (spec fase 3.5). Cualquier scope
+// válido (read/write/admin) basta: la primera tanda de tools es solo lectura.
+func (s *Server) Handler(tokens *apitoken.Store) http.Handler {
+	// Sin token store el endpoint NO se sirve sin auth: fail-closed (el MCP
+	// nunca debe quedar abierto; main solo lo construye con tokenStore, pero
+	// la defensa va aquí, en la última capa antes del handler).
+	if tokens == nil {
+		return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+			w.Header().Set("Content-Type", "application/json")
+			w.WriteHeader(http.StatusServiceUnavailable)
+			_, _ = w.Write([]byte(`{"error":"mcp_auth_unavailable"}`))
+		})
+	}
+	return rateLimit(s.ratePerMin, bearerOnly(tokens, http.Handler(s.http)))
+}
+
+// bearerOnly exige Authorization: Bearer <api token> válido. Sin token, con
+// token mal formado o inválido → 401 {error: unauthorized}.
+func bearerOnly(tokens *apitoken.Store, next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		raw := bearerToken(r)
+		if raw == "" || tokens.Validate(raw) == nil {
+			w.Header().Set("Content-Type", "application/json")
+			w.WriteHeader(http.StatusUnauthorized)
+			_, _ = w.Write([]byte(`{"error":"unauthorized"}`))
+			return
+		}
+		next.ServeHTTP(w, r)
+	})
+}
+
+func bearerToken(r *http.Request) string {
+	v := r.Header.Get("Authorization")
+	if !strings.HasPrefix(v, "Bearer ") {
+		return ""
+	}
+	return strings.TrimPrefix(v, "Bearer ")
+}
+
+// rlBucket es la ventana deslizante de un cliente (por IP).
+type rlBucket struct {
+	window time.Time
+	count  int
+}
+
+// rateLimit limita /mcp por IP (ventana fija de 1 minuto). Sin tokens ni
+// estado externo: brute-force de tokens queda acotado a ratePerMin intentos/min.
+func rateLimit(perMin int, next http.Handler) http.Handler {
+	var mu sync.Mutex
+	buckets := map[string]*rlBucket{}
+	window := time.Minute
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		ip := clientIP(r)
+		now := time.Now()
+		mu.Lock()
+		b := buckets[ip]
+		if b == nil || now.Sub(b.window) >= window {
+			b = &rlBucket{window: now}
+			buckets[ip] = b
+		}
+		b.count++
+		full := b.count > perMin
+		mu.Unlock()
+		if full {
+			w.Header().Set("Content-Type", "application/json")
+			w.WriteHeader(http.StatusTooManyRequests)
+			_ = json.NewEncoder(w).Encode(map[string]string{"error": "rate_limited"})
+			return
+		}
+		next.ServeHTTP(w, r)
+	})
+}
+
+// clientIP prefiere X-Forwarded-For solo si el proceso confía en proxy
+// (misma regla global que internal/auth: sin TRUST_PROXY el header no es
+// fiable y se usa RemoteAddr).
+func clientIP(r *http.Request) string {
+	if auth.TrustProxy() {
+		if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
+			if first := strings.TrimSpace(strings.Split(xff, ",")[0]); first != "" {
+				return first
+			}
+		}
+	}
+	host := r.RemoteAddr
+	if i := strings.LastIndex(host, ":"); i > 0 {
+		host = host[:i]
+	}
+	return host
+}

+ 342 - 0
server-go/internal/mcp/mcp.go

@@ -0,0 +1,342 @@
+// Package mcp expone un servidor MCP (Model Context Protocol) embebido en
+// NetPulse (#1114). Corre en el mismo binario y proceso, montado en /mcp
+// con transporte streamable-HTTP de mcp-go. Auth: SOLO API token Bearer
+// (internal/apitoken), nunca cookie de sesión. Activación: NETPULSE_MCP_ENABLED=1
+// (config.MCPEnabled); desactivado por defecto.
+//
+// Primera tanda de tools: SOLO LECTURA sobre el último snapshot en memoria del
+// poller (nunca sondean routers). Todos declaran readOnlyHint desde el día uno;
+// los writes futuros (fase 3.4 del spec) deberán declarar destructiveHint.
+package mcp
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"log"
+	"time"
+
+	"github.com/mark3labs/mcp-go/mcp"
+	"github.com/mark3labs/mcp-go/server"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// Deps son las fuentes de datos de los tools. Todo lectura, todo memoria:
+// el último snapshot del poller (LastOverview) y, opcionalmente, el motor de
+// alertas para el read-state server truth (igual que handleOverview).
+type Deps struct {
+	// LastOverview devuelve el último snapshot del poller (nil si aún no hay).
+	LastOverview func() *adapters.Overview
+	// Engine: motor de alertas (read-state server truth). nil → el tool de
+	// alertas cae al snapshot (sin read-state).
+	Engine *alerts.Engine
+	// Version del servidor (se expone en fleet_status).
+	Version string
+	// RatePerMin: límite de peticiones /mcp por IP y minuto (default 60).
+	RatePerMin int
+}
+
+// Server envuelve el MCPServer de mcp-go con nuestras fuentes y auditoría.
+type Server struct {
+	lastOverview func() *adapters.Overview
+	engine       *alerts.Engine
+	version      string
+	http         *server.StreamableHTTPServer
+	ratePerMin   int
+}
+
+// New construye el servidor MCP con la primera tanda de tools (read-only).
+func New(d Deps) *Server {
+	s := &Server{
+		lastOverview: d.LastOverview,
+		engine:       d.Engine,
+		version:      d.Version,
+		ratePerMin:   d.RatePerMin,
+	}
+	if s.ratePerMin <= 0 {
+		s.ratePerMin = 60
+	}
+	mcpServer := server.NewMCPServer(
+		"netpulse",
+		d.Version,
+		server.WithToolCapabilities(false),
+	)
+	s.addTools(mcpServer)
+	s.http = server.NewStreamableHTTPServer(mcpServer, server.WithStateLess(true))
+	return s
+}
+
+// readOnly es la anotación común de TODA la primera tanda: los clientes AI
+// pueden ejecutarlas libremente sin pedir confirmación al usuario. mcp-go
+// defaulta destructiveHint/openWorldHint a TRUE (asume tools genéricos), así
+// que hay que apagarlos explícitamente en los tools de solo lectura.
+var readOnly = []mcp.ToolOption{
+	mcp.WithReadOnlyHintAnnotation(true),
+	mcp.WithDestructiveHintAnnotation(false),
+	mcp.WithOpenWorldHintAnnotation(false),
+}
+
+// tool arma un tool con descripción + opciones propias + las anotaciones
+// read-only comunes. Helper porque Go no permite mezclar argumentos sueltos y
+// spread (s...) en una misma llamada variádica.
+func tool(name, description string, opts ...mcp.ToolOption) mcp.Tool {
+	all := make([]mcp.ToolOption, 0, len(opts)+len(readOnly)+1)
+	all = append(all, mcp.WithDescription(description))
+	all = append(all, opts...)
+	all = append(all, readOnly...)
+	return mcp.NewTool(name, all...)
+}
+
+// addTools registra los siete tools de solo lectura (spec fase 3.3, #1114).
+func (s *Server) addTools(mcpServer *server.MCPServer) {
+	mcpServer.AddTool(tool("fleet_status",
+		"Fleet-wide status from the latest poller snapshot: health score, WAN summary, per-router status, device totals and alert counts. Read-only.",
+	), s.run("fleet_status", s.toolFleetStatus))
+
+	mcpServer.AddTool(tool("router_health",
+		"Health of one monitored router: online status, health score, CPU/RAM/temperature vitals, uptime and client count from the latest snapshot. Read-only.",
+		mcp.WithString("router_id",
+			mcp.Required(),
+			mcp.Description("Router id as listed by fleet_status"),
+		),
+	), s.run("router_health", s.toolRouterHealth))
+
+	mcpServer.AddTool(tool("list_devices",
+		"Known devices (clients) from the latest snapshot, optionally filtered by router. Read-only.",
+		mcp.WithString("router_id",
+			mcp.Description("Optional router id to filter by"),
+		),
+	), s.run("list_devices", s.toolListDevices))
+
+	mcpServer.AddTool(tool("wireguard_peers",
+		"WireGuard peers with tunnel IPs, active state and last handshake, as polled on the gateway. Read-only.",
+	), s.run("wireguard_peers", s.toolWireGuardPeers))
+
+	mcpServer.AddTool(tool("adguard_stats",
+		"AdGuard Home stats: DNS queries and blocking rates over the last 24h, latency, top blocked domains. Read-only.",
+	), s.run("adguard_stats", s.toolAdGuardStats))
+
+	mcpServer.AddTool(tool("topology",
+		"Current network topology graph derived from FDB/LLDP/SNMP: links, per-router rings and inferred distribution nodes (switches, hypervisors). Read-only.",
+	), s.run("topology", s.toolTopology))
+
+	mcpServer.AddTool(tool("alerts",
+		"Active alerts from the alert engine (read-state aware). Pass active_only=true to list only unread alerts. Read-only.",
+		mcp.WithBoolean("active_only",
+			mcp.Description("Only return unread alerts (default false = all active alerts)"),
+		),
+	), s.run("alerts", s.toolAlerts))
+}
+
+// toolFunc produce el resultado de un tool a partir del snapshot actual y los
+// argumentos de la petición.
+type toolFunc func(ctx context.Context, req mcp.CallToolRequest, ov *adapters.Overview) (any, error)
+
+// run envuelve cada tool con snapshot-nil check y auditoría (qué AI tocó qué).
+// Los errores de negocio se devuelven como ToolResultError (isError), no como
+// error Go: el protocolo lo trata como resultado válido con error dentro.
+func (s *Server) run(name string, fn toolFunc) server.ToolHandlerFunc {
+	return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+		start := time.Now()
+		v, err := fn(ctx, req, s.lastOverview())
+		audit(name, req, err, time.Since(start))
+		if err != nil {
+			return mcp.NewToolResultError(err.Error()), nil
+		}
+		return mcp.NewToolResultJSON(v)
+	}
+}
+
+// audit registra cada invocación de tool: nombre, argumentos, éxito y duración.
+// Es la traza de auditoría del spec (fase 3.5): qué asistente tocó qué y cuándo.
+func audit(name string, req mcp.CallToolRequest, err error, dur time.Duration) {
+	args, _ := json.Marshal(req.GetArguments())
+	if err != nil {
+		log.Printf("[netpulse] mcp: tool=%s args=%s error=%q dur=%s", name, args, err.Error(), dur)
+		return
+	}
+	log.Printf("[netpulse] mcp: tool=%s args=%s ok dur=%s", name, args, dur)
+}
+
+// overviewOrErr devuelve el snapshot actual o el error de "aún no hay datos".
+func overviewOrErr(ov *adapters.Overview) (*adapters.Overview, error) {
+	if ov == nil {
+		return nil, fmt.Errorf("no poller snapshot available yet (the first poll has not finished)")
+	}
+	return ov, nil
+}
+
+// routerBrief es la forma resumida de un router para fleet_status (el tipo
+// completo Router se devuelve entero en router_health).
+type routerBrief struct {
+	ID      string `json:"id"`
+	Name    string `json:"name"`
+	Model   string `json:"model"`
+	Role    string `json:"role"`
+	Status  string `json:"status"`
+	Health  int    `json:"health"`
+	Clients int    `json:"clients"`
+}
+
+type fleetStatus struct {
+	Version         string                `json:"version"`
+	Ts              int64                 `json:"ts"`
+	Health          adapters.HealthScore  `json:"health"`
+	WAN             adapters.WAN          `json:"wan"`
+	Routers         []routerBrief         `json:"routers"`
+	DeviceTotals    adapters.DeviceTotals `json:"deviceTotals"`
+	AlertCount      int                   `json:"alertCount"`
+	UnreadAlerts    int                   `json:"unreadAlerts"`
+	ServerUptimeSec int64                 `json:"serverUptimeSec"`
+}
+
+func (s *Server) toolFleetStatus(_ context.Context, _ mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
+	ov, err := overviewOrErr(ov)
+	if err != nil {
+		return nil, err
+	}
+	out := fleetStatus{
+		Version:         s.version,
+		Ts:              ov.Ts,
+		Health:          ov.Health,
+		WAN:             ov.WAN,
+		DeviceTotals:    ov.DeviceTotals,
+		AlertCount:      len(ov.Alerts),
+		UnreadAlerts:    ov.UnreadAlerts,
+		ServerUptimeSec: ov.ServerUptimeSec,
+	}
+	out.Routers = make([]routerBrief, 0, len(ov.Routers))
+	for _, r := range ov.Routers {
+		out.Routers = append(out.Routers, routerBrief{
+			ID:      r.ID,
+			Name:    r.Name,
+			Model:   r.Model,
+			Role:    r.Role,
+			Status:  r.Status,
+			Health:  r.Health,
+			Clients: r.Clients,
+		})
+	}
+	return out, nil
+}
+
+func (s *Server) toolRouterHealth(_ context.Context, req mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
+	ov, err := overviewOrErr(ov)
+	if err != nil {
+		return nil, err
+	}
+	id, err := req.RequireString("router_id")
+	if err != nil {
+		return nil, err
+	}
+	for i := range ov.Routers {
+		if ov.Routers[i].ID == id {
+			return ov.Routers[i], nil
+		}
+	}
+	known := make([]string, 0, len(ov.Routers))
+	for _, r := range ov.Routers {
+		known = append(known, r.ID)
+	}
+	return nil, fmt.Errorf("router %q not found in the latest snapshot; known routers: %v", id, known)
+}
+
+func (s *Server) toolListDevices(_ context.Context, req mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
+	ov, err := overviewOrErr(ov)
+	if err != nil {
+		return nil, err
+	}
+	routerID := req.GetString("router_id", "")
+	out := make([]adapters.Device, 0, len(ov.Devices))
+	for _, d := range ov.Devices {
+		if routerID == "" || d.RouterID == routerID {
+			out = append(out, d)
+		}
+	}
+	return map[string]any{"total": len(out), "devices": out}, nil
+}
+
+func (s *Server) toolWireGuardPeers(_ context.Context, _ mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
+	ov, err := overviewOrErr(ov)
+	if err != nil {
+		return nil, err
+	}
+	// Wireguard/Adguard son VALORES en el snapshot (nunca null en live; el
+	// poller pone status "inactive" cuando no hay datos). Se reportan tal cual:
+	// el propio status comunica la disponibilidad.
+	if ov.Wireguard.Interface == "" && len(ov.Wireguard.Peers) == 0 {
+		return nil, fmt.Errorf("no WireGuard data in the latest snapshot (no gateway with WireGuard polled)")
+	}
+	return ov.Wireguard, nil
+}
+
+func (s *Server) toolAdGuardStats(_ context.Context, _ mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
+	ov, err := overviewOrErr(ov)
+	if err != nil {
+		return nil, err
+	}
+	if ov.Adguard.Host == "" {
+		return nil, fmt.Errorf("no AdGuard Home data in the latest snapshot (not configured or gateway offline)")
+	}
+	return ov.Adguard, nil
+}
+
+type topologyView struct {
+	Links             []adapters.TopoLink         `json:"links"`
+	Rings             map[string][]string         `json:"rings"`
+	HiddenPeers       map[string]int              `json:"hiddenPeers,omitempty"`
+	WanPeer           string                      `json:"wanPeer,omitempty"`
+	DistributionNodes []adapters.DistributionNode `json:"distributionNodes"`
+}
+
+func (s *Server) toolTopology(_ context.Context, _ mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
+	ov, err := overviewOrErr(ov)
+	if err != nil {
+		return nil, err
+	}
+	out := topologyView{
+		DistributionNodes: ov.DistributionNodes,
+	}
+	if ov.Topology != nil {
+		out.Links = ov.Topology.Links
+		out.Rings = ov.Topology.Rings
+		out.HiddenPeers = ov.Topology.HiddenPeers
+		out.WanPeer = ov.Topology.WanPeer
+	}
+	if out.Links == nil {
+		out.Links = []adapters.TopoLink{}
+	}
+	if out.Rings == nil {
+		out.Rings = map[string][]string{}
+	}
+	if out.DistributionNodes == nil {
+		out.DistributionNodes = []adapters.DistributionNode{}
+	}
+	return out, nil
+}
+
+func (s *Server) toolAlerts(_ context.Context, req mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
+	activeOnly := req.GetBool("active_only", false)
+	// Fuente canónica: el motor (read-state + dismissed/silence server truth,
+	// igual que GET /api/alerts). Fallback al snapshot si no hay motor.
+	var list []adapters.AlertEvent
+	if s.engine != nil {
+		list = s.engine.List()
+	} else {
+		ov, err := overviewOrErr(ov)
+		if err != nil {
+			return nil, err
+		}
+		list = ov.Alerts
+	}
+	out := make([]adapters.AlertEvent, 0, len(list))
+	for _, a := range list {
+		if activeOnly && a.Read {
+			continue
+		}
+		out = append(out, a)
+	}
+	return map[string]any{"total": len(out), "alerts": out}, nil
+}

+ 416 - 0
server-go/internal/mcp/mcp_test.go

@@ -0,0 +1,416 @@
+package mcp
+
+import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/apitoken"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// fakeOverview es el snapshot mínimo que cubre los siete tools.
+func fakeOverview() *adapters.Overview {
+	return &adapters.Overview{
+		Ts: 1750000000,
+		Routers: []adapters.Router{
+			{ID: "gateway", Name: "Gateway", Model: "GL.iNet Flint 2", Role: "gateway", Status: "online", Health: 98, Clients: 5},
+			{ID: "ap-living", Name: "AP Living", Model: "Redmi AX6", Role: "ap", Status: "offline", Health: 0, Clients: 0},
+		},
+		Devices: []adapters.Device{
+			{ID: "dev-1", Name: "laptop", RouterID: "gateway", Online: true},
+			{ID: "dev-2", Name: "phone", RouterID: "ap-living", Online: false},
+		},
+		DeviceTotals:    adapters.DeviceTotals{Total: 2, Online: 1},
+		UnreadAlerts:    1,
+		ServerUptimeSec: 3600,
+		Alerts: []adapters.AlertEvent{
+			{ID: "a1", Category: "router-offline", Severity: "critical", Ts: 1750000000},
+			{ID: "a2", Category: "weak-signal", Severity: "warn", Ts: 1749999000, Read: true},
+		},
+		Wireguard: adapters.WireGuardStats{
+			Interface: "wg0", Status: "active", Subnet: "10.0.0.0/24",
+			Peers: []adapters.WGPeer{{ID: "peer-1", Name: "oficina", Active: true}},
+		},
+		Adguard: adapters.AdGuardStats{
+			Host: "192.168.1.1", Status: "active", Queries24h: 12000, Blocked24h: 3000,
+		},
+		Topology: &adapters.TopoSemantics{
+			Links: []adapters.TopoLink{{From: "gateway", To: "dev-1", Kind: "wired"}},
+			Rings: map[string][]string{"gateway": {"dev-1"}},
+		},
+		DistributionNodes: []adapters.DistributionNode{{ID: "dist-1", Kind: "inferred", RouterID: "gateway"}},
+	}
+}
+
+// testEnv levanta el handler MCP completo (auth + rate limit) sobre un token
+// store real con un token válido. Devuelve la URL base y el token crudo.
+func testEnv(t *testing.T, ov *adapters.Overview, ratePerMin int) (string, string) {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	if err := apitoken.EnsureSchema(d); err != nil {
+		t.Fatalf("EnsureSchema: %v", err)
+	}
+	store := apitoken.NewStore(d, "test-secret")
+	_, raw, err := store.Create("mcp-test", apitoken.ScopeRead, 1, 0)
+	if err != nil {
+		t.Fatalf("Create token: %v", err)
+	}
+	srv := New(Deps{
+		LastOverview: func() *adapters.Overview { return ov },
+		Version:      "0.0.0-test",
+		RatePerMin:   ratePerMin,
+	})
+	// Montar como en producción: mux externo con /mcp (StreamableHTTPServer
+	// valida el path por defecto).
+	mux := http.NewServeMux()
+	mux.Handle("/mcp", srv.Handler(store))
+	ts := httptest.NewServer(mux)
+	t.Cleanup(ts.Close)
+	return ts.URL, raw
+}
+
+// rpc hace una llamada JSON-RPC 2.0 contra /mcp y devuelve el body parseado.
+// Acept JSON puro (sin SSE) para simplificar el parseo en tests.
+func rpc(t *testing.T, url, token, method string, id int, params any) (int, map[string]any) {
+	t.Helper()
+	body, _ := json.Marshal(map[string]any{
+		"jsonrpc": "2.0", "id": id, "method": method, "params": params,
+	})
+	req, err := http.NewRequest("POST", url+"/mcp", bytes.NewReader(body))
+	if err != nil {
+		t.Fatalf("NewRequest: %v", err)
+	}
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Accept", "application/json")
+	if token != "" {
+		req.Header.Set("Authorization", "Bearer "+token)
+	}
+	resp, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("Do: %v", err)
+	}
+	defer resp.Body.Close()
+	var out map[string]any
+	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
+		t.Fatalf("Decode (status %d): %v", resp.StatusCode, err)
+	}
+	return resp.StatusCode, out
+}
+
+func callTool(t *testing.T, url, token, name string, args map[string]any) map[string]any {
+	t.Helper()
+	_, out := rpc(t, url, token, "tools/call", 2, map[string]any{
+		"name":      name,
+		"arguments": args,
+	})
+	return out
+}
+
+// structured extrae el contenido de un CallToolResult: los tools devuelven
+// NewToolResultJSON → Content[0].Text es el JSON serializado (y además va en
+// structuredContent, pero el text basta y es version-proof).
+func structured(t *testing.T, out map[string]any) map[string]any {
+	t.Helper()
+	res, ok := out["result"].(map[string]any)
+	if !ok {
+		t.Fatalf("sin result en %v", out)
+	}
+	if res["isError"] == true {
+		t.Fatalf("tool error: %v", res)
+	}
+	content, ok := res["content"].([]any)
+	if !ok || len(content) == 0 {
+		t.Fatalf("sin content en %v", res)
+	}
+	first, ok := content[0].(map[string]any)
+	if !ok {
+		t.Fatalf("content[0] no es mapa: %v", content[0])
+	}
+	text, ok := first["text"].(string)
+	if !ok {
+		t.Fatalf("content[0].text no es string: %v", first)
+	}
+	var v map[string]any
+	if err := json.Unmarshal([]byte(text), &v); err != nil {
+		t.Fatalf("content[0].text no es JSON (%q): %v", text, err)
+	}
+	return v
+}
+
+func TestFleetStatus(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 60)
+
+	out := callTool(t, url, tok, "fleet_status", nil)
+	v := structured(t, out)
+	if v["version"] != "0.0.0-test" {
+		t.Errorf("version = %v", v["version"])
+	}
+	if v["ts"] != float64(1750000000) {
+		t.Errorf("ts = %v", v["ts"])
+	}
+	routers, ok := v["routers"].([]any)
+	if !ok || len(routers) != 2 {
+		t.Fatalf("routers = %v", v["routers"])
+	}
+	gw := routers[0].(map[string]any)
+	if gw["id"] != "gateway" || gw["status"] != "online" || gw["health"] != float64(98) {
+		t.Errorf("gateway brief = %v", gw)
+	}
+	if v["unreadAlerts"] != float64(1) || v["alertCount"] != float64(2) {
+		t.Errorf("alertas = %v / %v", v["unreadAlerts"], v["alertCount"])
+	}
+	totals, ok := v["deviceTotals"].(map[string]any)
+	if !ok || totals["total"] != float64(2) || totals["online"] != float64(1) {
+		t.Errorf("deviceTotals = %v", v["deviceTotals"])
+	}
+}
+
+func TestToolsListAllReadOnly(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 60)
+
+	_, out := rpc(t, url, tok, "tools/list", 1, nil)
+	res, ok := out["result"].(map[string]any)
+	if !ok {
+		t.Fatalf("sin result: %v", out)
+	}
+	tools, ok := res["tools"].([]any)
+	if !ok || len(tools) != 7 {
+		t.Fatalf("tools = %v", res["tools"])
+	}
+	want := map[string]bool{
+		"fleet_status": true, "router_health": true, "list_devices": true,
+		"wireguard_peers": true, "adguard_stats": true, "topology": true,
+		"alerts": true,
+	}
+	for _, raw := range tools {
+		tool := raw.(map[string]any)
+		name := tool["name"].(string)
+		if !want[name] {
+			t.Errorf("tool inesperada: %s", name)
+		}
+		delete(want, name)
+		ann, ok := tool["annotations"].(map[string]any)
+		if !ok {
+			t.Errorf("%s sin annotations", name)
+			continue
+		}
+		if ann["readOnlyHint"] != true {
+			t.Errorf("%s readOnlyHint != true: %v", name, ann)
+		}
+		for _, forbidden := range []string{"destructiveHint", "openWorldHint"} {
+			if ann[forbidden] == true {
+				t.Errorf("%s no debe declarar %s=true en la tanda read-only", name, forbidden)
+			}
+		}
+	}
+	if len(want) > 0 {
+		t.Errorf("tools sin registrar: %v", want)
+	}
+}
+
+func TestRouterHealth(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 60)
+
+	v := structured(t, callTool(t, url, tok, "router_health", map[string]any{"router_id": "ap-living"}))
+	if v["id"] != "ap-living" || v["status"] != "offline" {
+		t.Errorf("router = %v", v)
+	}
+
+	// Router desconocido: isError con los ids conocidos en el mensaje.
+	out := callTool(t, url, tok, "router_health", map[string]any{"router_id": "nope"})
+	res := out["result"].(map[string]any)
+	if res["isError"] != true {
+		t.Errorf("isError = %v", res)
+	}
+}
+
+func TestListDevices(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 60)
+
+	v := structured(t, callTool(t, url, tok, "list_devices", nil))
+	if v["total"] != float64(2) {
+		t.Errorf("total = %v", v["total"])
+	}
+	v = structured(t, callTool(t, url, tok, "list_devices", map[string]any{"router_id": "gateway"}))
+	if v["total"] != float64(1) {
+		t.Errorf("total filtrado = %v", v["total"])
+	}
+	devs := v["devices"].([]any)
+	if devs[0].(map[string]any)["id"] != "dev-1" {
+		t.Errorf("devices = %v", devs)
+	}
+}
+
+func TestWireGuardAndAdGuard(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 60)
+
+	wg := structured(t, callTool(t, url, tok, "wireguard_peers", nil))
+	if wg["interface"] != "wg0" {
+		t.Errorf("wg = %v", wg)
+	}
+	agh := structured(t, callTool(t, url, tok, "adguard_stats", nil))
+	if agh["queries24h"] != float64(12000) {
+		t.Errorf("agh = %v", agh)
+	}
+
+	// Sin datos: isError honesto, no un struct vacío.
+	empty := &adapters.Overview{Ts: 1}
+	url2, tok2 := testEnv(t, empty, 60)
+	out := callTool(t, url2, tok2, "wireguard_peers", nil)
+	if out["result"].(map[string]any)["isError"] != true {
+		t.Errorf("wireguard sin datos debería ser isError: %v", out)
+	}
+	out = callTool(t, url2, tok2, "adguard_stats", nil)
+	if out["result"].(map[string]any)["isError"] != true {
+		t.Errorf("adguard sin datos debería ser isError: %v", out)
+	}
+}
+
+func TestTopology(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 60)
+
+	v := structured(t, callTool(t, url, tok, "topology", nil))
+	links := v["links"].([]any)
+	if len(links) != 1 || links[0].(map[string]any)["kind"] != "wired" {
+		t.Errorf("links = %v", links)
+	}
+	rings := v["rings"].(map[string]any)
+	if len(rings["gateway"].([]any)) != 1 {
+		t.Errorf("rings = %v", rings)
+	}
+	dists := v["distributionNodes"].([]any)
+	if len(dists) != 1 || dists[0].(map[string]any)["kind"] != "inferred" {
+		t.Errorf("distributionNodes = %v", dists)
+	}
+}
+
+func TestAlertsActiveOnly(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 60)
+
+	v := structured(t, callTool(t, url, tok, "alerts", nil))
+	if v["total"] != float64(2) {
+		t.Errorf("total = %v", v["total"])
+	}
+	v = structured(t, callTool(t, url, tok, "alerts", map[string]any{"active_only": true}))
+	if v["total"] != float64(1) {
+		t.Errorf("total active_only = %v", v["total"])
+	}
+}
+
+func TestAuthBearerOnly(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 60)
+
+	// Sin token.
+	status, _ := rpc(t, url, "", "tools/list", 1, nil)
+	if status != http.StatusUnauthorized {
+		t.Errorf("sin token: status %d", status)
+	}
+	// Token inválido.
+	status, _ = rpc(t, url, "np_bogus000000000000000000000000", "tools/list", 1, nil)
+	if status != http.StatusUnauthorized {
+		t.Errorf("token inválido: status %d", status)
+	}
+	// Token válido.
+	status, _ = rpc(t, url, tok, "tools/list", 1, nil)
+	if status != http.StatusOK {
+		t.Errorf("token válido: status %d", status)
+	}
+}
+
+func TestRateLimit(t *testing.T) {
+	url, tok := testEnv(t, fakeOverview(), 2)
+
+	for i := 1; i <= 2; i++ {
+		status, _ := rpc(t, url, tok, "tools/list", i, nil)
+		if status != http.StatusOK {
+			t.Fatalf("petición %d: status %d", i, status)
+		}
+	}
+	status, body := rpc(t, url, tok, "tools/list", 3, nil)
+	if status != http.StatusTooManyRequests {
+		t.Errorf("petición 3: status %d body %v", status, body)
+	}
+}
+
+func TestHandlerNilTokensFailClosed(t *testing.T) {
+	srv := New(Deps{LastOverview: fakeOverview})
+	ts := httptest.NewServer(srv.Handler(nil))
+	t.Cleanup(ts.Close)
+
+	status, _ := rpc(t, ts.URL, "", "tools/list", 1, nil)
+	if status != http.StatusServiceUnavailable {
+		t.Errorf("sin token store debería ser 503 fail-closed, status %d", status)
+	}
+}
+
+func TestNilSnapshot(t *testing.T) {
+	url, tok := testEnv(t, nil, 60)
+
+	out := callTool(t, url, tok, "fleet_status", nil)
+	res := out["result"].(map[string]any)
+	if res["isError"] != true {
+		t.Errorf("snapshot nil debería ser isError: %v", out)
+	}
+}
+
+// TestAlertsWithEngine comprueba la fuente canónica (motor de alertas) cuando
+// está disponible: engine.List() manda sobre el snapshot.
+func TestAlertsWithEngine(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	engine := alerts.New(d, nil)
+	engine.Emit(alerts.AlertEvent{ID: "live-1", Category: "router-offline", Severity: "critical"})
+
+	if err := apitoken.EnsureSchema(d); err != nil {
+		t.Fatalf("EnsureSchema: %v", err)
+	}
+	store := apitoken.NewStore(d, "test-secret")
+	_, raw, err := store.Create("mcp-test", apitoken.ScopeRead, 1, 0)
+	if err != nil {
+		t.Fatalf("Create token: %v", err)
+	}
+	srv := New(Deps{
+		LastOverview: func() *adapters.Overview { return fakeOverview() },
+		Engine:       engine,
+		Version:      "0.0.0-test",
+	})
+	mux := http.NewServeMux()
+	mux.Handle("/mcp", srv.Handler(store))
+	ts := httptest.NewServer(mux)
+	t.Cleanup(ts.Close)
+
+	v := structured(t, callTool(t, ts.URL, raw, "alerts", nil))
+	found := false
+	for _, a := range v["alerts"].([]any) {
+		if a.(map[string]any)["id"] == "live-1" {
+			found = true
+		}
+	}
+	if !found {
+		t.Errorf("alerts del engine no presentes: %v", v["alerts"])
+	}
+}
+
+func Example() {
+	// Documentación viva del wiring mínimo.
+	srv := New(Deps{
+		LastOverview: func() *adapters.Overview { return nil },
+		Version:      "2.31.1",
+	})
+	_ = srv
+	fmt.Println("ok")
+	// Output: ok
+}