mcp.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // Package mcp expone un servidor MCP (Model Context Protocol) embebido en
  2. // NetPulse (#1114). Corre en el mismo binario y proceso, montado en /mcp
  3. // con transporte streamable-HTTP de mcp-go. Auth: SOLO API token Bearer
  4. // (internal/apitoken), nunca cookie de sesión. Activación: NETPULSE_MCP_ENABLED=1
  5. // (config.MCPEnabled); desactivado por defecto.
  6. //
  7. // Primera tanda de tools: SOLO LECTURA sobre el último snapshot en memoria del
  8. // poller (nunca sondean routers). Todos declaran readOnlyHint desde el día uno;
  9. // los writes futuros (fase 3.4 del spec) deberán declarar destructiveHint.
  10. package mcp
  11. import (
  12. "context"
  13. "encoding/json"
  14. "fmt"
  15. "log"
  16. "time"
  17. "github.com/mark3labs/mcp-go/mcp"
  18. "github.com/mark3labs/mcp-go/server"
  19. "github.com/gnacho/netpulse/server-go/internal/adapters"
  20. "github.com/gnacho/netpulse/server-go/internal/alerts"
  21. )
  22. // Deps son las fuentes de datos de los tools. Todo lectura, todo memoria:
  23. // el último snapshot del poller (LastOverview) y, opcionalmente, el motor de
  24. // alertas para el read-state server truth (igual que handleOverview).
  25. type Deps struct {
  26. // LastOverview devuelve el último snapshot del poller (nil si aún no hay).
  27. LastOverview func() *adapters.Overview
  28. // Engine: motor de alertas (read-state server truth). nil → el tool de
  29. // alertas cae al snapshot (sin read-state).
  30. Engine *alerts.Engine
  31. // Version del servidor (se expone en fleet_status).
  32. Version string
  33. // RatePerMin: límite de peticiones /mcp por IP y minuto (default 60).
  34. RatePerMin int
  35. }
  36. // Server envuelve el MCPServer de mcp-go con nuestras fuentes y auditoría.
  37. type Server struct {
  38. lastOverview func() *adapters.Overview
  39. engine *alerts.Engine
  40. version string
  41. http *server.StreamableHTTPServer
  42. ratePerMin int
  43. }
  44. // New construye el servidor MCP con la primera tanda de tools (read-only).
  45. func New(d Deps) *Server {
  46. s := &Server{
  47. lastOverview: d.LastOverview,
  48. engine: d.Engine,
  49. version: d.Version,
  50. ratePerMin: d.RatePerMin,
  51. }
  52. if s.ratePerMin <= 0 {
  53. s.ratePerMin = 60
  54. }
  55. mcpServer := server.NewMCPServer(
  56. "netpulse",
  57. d.Version,
  58. server.WithToolCapabilities(false),
  59. )
  60. s.addTools(mcpServer)
  61. s.http = server.NewStreamableHTTPServer(mcpServer, server.WithStateLess(true))
  62. return s
  63. }
  64. // readOnly es la anotación común de TODA la primera tanda: los clientes AI
  65. // pueden ejecutarlas libremente sin pedir confirmación al usuario. mcp-go
  66. // defaulta destructiveHint/openWorldHint a TRUE (asume tools genéricos), así
  67. // que hay que apagarlos explícitamente en los tools de solo lectura.
  68. var readOnly = []mcp.ToolOption{
  69. mcp.WithReadOnlyHintAnnotation(true),
  70. mcp.WithDestructiveHintAnnotation(false),
  71. mcp.WithOpenWorldHintAnnotation(false),
  72. }
  73. // tool arma un tool con descripción + opciones propias + las anotaciones
  74. // read-only comunes. Helper porque Go no permite mezclar argumentos sueltos y
  75. // spread (s...) en una misma llamada variádica.
  76. func tool(name, description string, opts ...mcp.ToolOption) mcp.Tool {
  77. all := make([]mcp.ToolOption, 0, len(opts)+len(readOnly)+1)
  78. all = append(all, mcp.WithDescription(description))
  79. all = append(all, opts...)
  80. all = append(all, readOnly...)
  81. return mcp.NewTool(name, all...)
  82. }
  83. // addTools registra los siete tools de solo lectura (spec fase 3.3, #1114).
  84. func (s *Server) addTools(mcpServer *server.MCPServer) {
  85. mcpServer.AddTool(tool("fleet_status",
  86. "Fleet-wide status from the latest poller snapshot: health score, WAN summary, per-router status, device totals and alert counts. Read-only.",
  87. ), s.run("fleet_status", s.toolFleetStatus))
  88. mcpServer.AddTool(tool("router_health",
  89. "Health of one monitored router: online status, health score, CPU/RAM/temperature vitals, uptime and client count from the latest snapshot. Read-only.",
  90. mcp.WithString("router_id",
  91. mcp.Required(),
  92. mcp.Description("Router id as listed by fleet_status"),
  93. ),
  94. ), s.run("router_health", s.toolRouterHealth))
  95. mcpServer.AddTool(tool("list_devices",
  96. "Known devices (clients) from the latest snapshot, optionally filtered by router. Read-only.",
  97. mcp.WithString("router_id",
  98. mcp.Description("Optional router id to filter by"),
  99. ),
  100. ), s.run("list_devices", s.toolListDevices))
  101. mcpServer.AddTool(tool("wireguard_peers",
  102. "WireGuard peers with tunnel IPs, active state and last handshake, as polled on the gateway. Read-only.",
  103. ), s.run("wireguard_peers", s.toolWireGuardPeers))
  104. mcpServer.AddTool(tool("adguard_stats",
  105. "AdGuard Home stats: DNS queries and blocking rates over the last 24h, latency, top blocked domains. Read-only.",
  106. ), s.run("adguard_stats", s.toolAdGuardStats))
  107. mcpServer.AddTool(tool("topology",
  108. "Current network topology graph derived from FDB/LLDP/SNMP: links, per-router rings and inferred distribution nodes (switches, hypervisors). Read-only.",
  109. ), s.run("topology", s.toolTopology))
  110. mcpServer.AddTool(tool("alerts",
  111. "Active alerts from the alert engine (read-state aware). Pass active_only=true to list only unread alerts. Read-only.",
  112. mcp.WithBoolean("active_only",
  113. mcp.Description("Only return unread alerts (default false = all active alerts)"),
  114. ),
  115. ), s.run("alerts", s.toolAlerts))
  116. }
  117. // toolFunc produce el resultado de un tool a partir del snapshot actual y los
  118. // argumentos de la petición.
  119. type toolFunc func(ctx context.Context, req mcp.CallToolRequest, ov *adapters.Overview) (any, error)
  120. // run envuelve cada tool con snapshot-nil check y auditoría (qué AI tocó qué).
  121. // Los errores de negocio se devuelven como ToolResultError (isError), no como
  122. // error Go: el protocolo lo trata como resultado válido con error dentro.
  123. func (s *Server) run(name string, fn toolFunc) server.ToolHandlerFunc {
  124. return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
  125. start := time.Now()
  126. v, err := fn(ctx, req, s.lastOverview())
  127. audit(name, req, err, time.Since(start))
  128. if err != nil {
  129. return mcp.NewToolResultError(err.Error()), nil
  130. }
  131. return mcp.NewToolResultJSON(v)
  132. }
  133. }
  134. // audit registra cada invocación de tool: nombre, argumentos, éxito y duración.
  135. // Es la traza de auditoría del spec (fase 3.5): qué asistente tocó qué y cuándo.
  136. func audit(name string, req mcp.CallToolRequest, err error, dur time.Duration) {
  137. args, _ := json.Marshal(req.GetArguments())
  138. if err != nil {
  139. log.Printf("[netpulse] mcp: tool=%s args=%s error=%q dur=%s", name, args, err.Error(), dur)
  140. return
  141. }
  142. log.Printf("[netpulse] mcp: tool=%s args=%s ok dur=%s", name, args, dur)
  143. }
  144. // overviewOrErr devuelve el snapshot actual o el error de "aún no hay datos".
  145. func overviewOrErr(ov *adapters.Overview) (*adapters.Overview, error) {
  146. if ov == nil {
  147. return nil, fmt.Errorf("no poller snapshot available yet (the first poll has not finished)")
  148. }
  149. return ov, nil
  150. }
  151. // routerBrief es la forma resumida de un router para fleet_status (el tipo
  152. // completo Router se devuelve entero en router_health).
  153. type routerBrief struct {
  154. ID string `json:"id"`
  155. Name string `json:"name"`
  156. Model string `json:"model"`
  157. Role string `json:"role"`
  158. Status string `json:"status"`
  159. Health int `json:"health"`
  160. Clients int `json:"clients"`
  161. }
  162. type fleetStatus struct {
  163. Version string `json:"version"`
  164. Ts int64 `json:"ts"`
  165. Health adapters.HealthScore `json:"health"`
  166. WAN adapters.WAN `json:"wan"`
  167. Routers []routerBrief `json:"routers"`
  168. DeviceTotals adapters.DeviceTotals `json:"deviceTotals"`
  169. AlertCount int `json:"alertCount"`
  170. UnreadAlerts int `json:"unreadAlerts"`
  171. ServerUptimeSec int64 `json:"serverUptimeSec"`
  172. }
  173. func (s *Server) toolFleetStatus(_ context.Context, _ mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
  174. ov, err := overviewOrErr(ov)
  175. if err != nil {
  176. return nil, err
  177. }
  178. out := fleetStatus{
  179. Version: s.version,
  180. Ts: ov.Ts,
  181. Health: ov.Health,
  182. WAN: ov.WAN,
  183. DeviceTotals: ov.DeviceTotals,
  184. AlertCount: len(ov.Alerts),
  185. UnreadAlerts: ov.UnreadAlerts,
  186. ServerUptimeSec: ov.ServerUptimeSec,
  187. }
  188. out.Routers = make([]routerBrief, 0, len(ov.Routers))
  189. for _, r := range ov.Routers {
  190. out.Routers = append(out.Routers, routerBrief{
  191. ID: r.ID,
  192. Name: r.Name,
  193. Model: r.Model,
  194. Role: r.Role,
  195. Status: r.Status,
  196. Health: r.Health,
  197. Clients: r.Clients,
  198. })
  199. }
  200. return out, nil
  201. }
  202. func (s *Server) toolRouterHealth(_ context.Context, req mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
  203. ov, err := overviewOrErr(ov)
  204. if err != nil {
  205. return nil, err
  206. }
  207. id, err := req.RequireString("router_id")
  208. if err != nil {
  209. return nil, err
  210. }
  211. for i := range ov.Routers {
  212. if ov.Routers[i].ID == id {
  213. return ov.Routers[i], nil
  214. }
  215. }
  216. known := make([]string, 0, len(ov.Routers))
  217. for _, r := range ov.Routers {
  218. known = append(known, r.ID)
  219. }
  220. return nil, fmt.Errorf("router %q not found in the latest snapshot; known routers: %v", id, known)
  221. }
  222. func (s *Server) toolListDevices(_ context.Context, req mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
  223. ov, err := overviewOrErr(ov)
  224. if err != nil {
  225. return nil, err
  226. }
  227. routerID := req.GetString("router_id", "")
  228. out := make([]adapters.Device, 0, len(ov.Devices))
  229. for _, d := range ov.Devices {
  230. if routerID == "" || d.RouterID == routerID {
  231. out = append(out, d)
  232. }
  233. }
  234. return map[string]any{"total": len(out), "devices": out}, nil
  235. }
  236. func (s *Server) toolWireGuardPeers(_ context.Context, _ mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
  237. ov, err := overviewOrErr(ov)
  238. if err != nil {
  239. return nil, err
  240. }
  241. // Wireguard/Adguard son VALORES en el snapshot (nunca null en live; el
  242. // poller pone status "inactive" cuando no hay datos). Se reportan tal cual:
  243. // el propio status comunica la disponibilidad.
  244. if ov.Wireguard.Interface == "" && len(ov.Wireguard.Peers) == 0 {
  245. return nil, fmt.Errorf("no WireGuard data in the latest snapshot (no gateway with WireGuard polled)")
  246. }
  247. return ov.Wireguard, nil
  248. }
  249. func (s *Server) toolAdGuardStats(_ context.Context, _ mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
  250. ov, err := overviewOrErr(ov)
  251. if err != nil {
  252. return nil, err
  253. }
  254. if ov.Adguard.Host == "" {
  255. return nil, fmt.Errorf("no AdGuard Home data in the latest snapshot (not configured or gateway offline)")
  256. }
  257. return ov.Adguard, nil
  258. }
  259. type topologyView struct {
  260. Links []adapters.TopoLink `json:"links"`
  261. Rings map[string][]string `json:"rings"`
  262. HiddenPeers map[string]int `json:"hiddenPeers,omitempty"`
  263. WanPeer string `json:"wanPeer,omitempty"`
  264. DistributionNodes []adapters.DistributionNode `json:"distributionNodes"`
  265. }
  266. func (s *Server) toolTopology(_ context.Context, _ mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
  267. ov, err := overviewOrErr(ov)
  268. if err != nil {
  269. return nil, err
  270. }
  271. out := topologyView{
  272. DistributionNodes: ov.DistributionNodes,
  273. }
  274. if ov.Topology != nil {
  275. out.Links = ov.Topology.Links
  276. out.Rings = ov.Topology.Rings
  277. out.HiddenPeers = ov.Topology.HiddenPeers
  278. out.WanPeer = ov.Topology.WanPeer
  279. }
  280. if out.Links == nil {
  281. out.Links = []adapters.TopoLink{}
  282. }
  283. if out.Rings == nil {
  284. out.Rings = map[string][]string{}
  285. }
  286. if out.DistributionNodes == nil {
  287. out.DistributionNodes = []adapters.DistributionNode{}
  288. }
  289. return out, nil
  290. }
  291. func (s *Server) toolAlerts(_ context.Context, req mcp.CallToolRequest, ov *adapters.Overview) (any, error) {
  292. activeOnly := req.GetBool("active_only", false)
  293. // Fuente canónica: el motor (read-state + dismissed/silence server truth,
  294. // igual que GET /api/alerts). Fallback al snapshot si no hay motor.
  295. var list []adapters.AlertEvent
  296. if s.engine != nil {
  297. list = s.engine.List()
  298. } else {
  299. ov, err := overviewOrErr(ov)
  300. if err != nil {
  301. return nil, err
  302. }
  303. list = ov.Alerts
  304. }
  305. out := make([]adapters.AlertEvent, 0, len(list))
  306. for _, a := range list {
  307. if activeOnly && a.Read {
  308. continue
  309. }
  310. out = append(out, a)
  311. }
  312. return map[string]any{"total": len(out), "alerts": out}, nil
  313. }