|
1 | | -from __future__ import annotations |
| 1 | +"""keep-mcp — Model Context Protocol server for Keep.""" |
2 | 2 |
|
3 | 3 | import logging |
| 4 | +import os |
4 | 5 | import sys |
5 | | -from typing import Any |
6 | 6 |
|
7 | 7 | import httpx |
8 | 8 | from mcp.server.fastmcp import FastMCP |
9 | | -from starlette.requests import Request |
10 | | -from starlette.responses import JSONResponse, PlainTextResponse |
| 9 | +from starlette.responses import PlainTextResponse |
| 10 | + |
| 11 | +API_URL = os.environ.get("KEEP_MCP_KEEP_API_URL", "http://keep-backend:8080").rstrip("/") |
| 12 | +API_KEY = os.environ.get("KEEP_MCP_KEEP_API_KEY", "") |
| 13 | +TRANSPORT = os.environ.get("KEEP_MCP_TRANSPORT", "stdio") |
| 14 | +HTTP_HOST = os.environ.get("KEEP_MCP_HTTP_HOST", "0.0.0.0") |
| 15 | +HTTP_PORT = int(os.environ.get("KEEP_MCP_HTTP_PORT", "8090")) |
| 16 | + |
| 17 | +http = httpx.AsyncClient( |
| 18 | + base_url=API_URL, |
| 19 | + timeout=30.0, |
| 20 | + headers={"X-API-KEY": API_KEY, "User-Agent": "keep-mcp/0.1"}, |
| 21 | +) |
| 22 | + |
| 23 | +mcp = FastMCP( |
| 24 | + name="keep", |
| 25 | + instructions=( |
| 26 | + "Read-only access to a Keep AIOps deployment. Use search_alerts and " |
| 27 | + "list_incidents to see what is firing, then get_incident + " |
| 28 | + "list_incident_alerts to drill in. CEL is the query language for " |
| 29 | + "search_alerts — see docs.keephq.dev." |
| 30 | + ), |
| 31 | +) |
| 32 | + |
| 33 | + |
| 34 | +async def _json(method: str, path: str, **kw): |
| 35 | + r = await http.request(method, path, **kw) |
| 36 | + r.raise_for_status() |
| 37 | + return r.json() if r.content else None |
| 38 | + |
| 39 | + |
| 40 | +@mcp.tool() |
| 41 | +async def search_alerts(cel: str = "", limit: int = 25, offset: int = 0) -> dict: |
| 42 | + """Query Keep alerts. `cel` is a CEL filter like `severity == "critical"`; empty returns most recent.""" |
| 43 | + return await _json("POST", "/alerts/query", json={"cel": cel, "limit": limit, "offset": offset}) |
| 44 | + |
| 45 | + |
| 46 | +@mcp.tool() |
| 47 | +async def list_incidents( |
| 48 | + status: list[str] | None = None, |
| 49 | + severity: list[str] | None = None, |
| 50 | + limit: int = 25, |
| 51 | + offset: int = 0, |
| 52 | + cel: str | None = None, |
| 53 | +) -> dict: |
| 54 | + """List Keep incidents. status ⊆ {firing, resolved, acknowledged, merged, deleted}; severity ⊆ {critical, high, warning, info, low}.""" |
| 55 | + params: list[tuple[str, str | int]] = [("limit", limit), ("offset", offset)] |
| 56 | + params += [("status", s) for s in status or []] |
| 57 | + params += [("severity", s) for s in severity or []] |
| 58 | + if cel: |
| 59 | + params.append(("cel", cel)) |
| 60 | + return await _json("GET", "/incidents", params=params) |
| 61 | + |
| 62 | + |
| 63 | +@mcp.tool() |
| 64 | +async def get_incident(incident_id: str) -> dict: |
| 65 | + return await _json("GET", f"/incidents/{incident_id}") |
| 66 | + |
| 67 | + |
| 68 | +@mcp.tool() |
| 69 | +async def list_incident_alerts(incident_id: str, limit: int = 25, offset: int = 0) -> dict: |
| 70 | + return await _json( |
| 71 | + "GET", f"/incidents/{incident_id}/alerts", params={"limit": limit, "offset": offset} |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +@mcp.tool() |
| 76 | +async def get_topology(service: str | None = None) -> list[dict]: |
| 77 | + return await _json("GET", "/topology", params={"service": service} if service else None) |
11 | 78 |
|
12 | | -from .client import KeepClient |
13 | | -from .config import load_settings |
14 | 79 |
|
15 | | -log = logging.getLogger("keep_mcp") |
| 80 | +@mcp.custom_route("/healthz", methods=["GET"]) |
| 81 | +async def healthz(_): |
| 82 | + return PlainTextResponse("ok") |
16 | 83 |
|
17 | 84 |
|
18 | 85 | def main() -> None: |
19 | | - settings = load_settings() |
20 | 86 | logging.basicConfig( |
21 | | - level=settings.log_level.upper(), |
| 87 | + level=logging.INFO, |
22 | 88 | format="%(asctime)s %(levelname)s %(name)s: %(message)s", |
23 | 89 | stream=sys.stderr, |
24 | 90 | ) |
25 | | - |
26 | | - if not settings.keep_api_key: |
27 | | - log.error("KEEP_MCP_KEEP_API_KEY is not set; refusing to start") |
| 91 | + if not API_KEY: |
| 92 | + logging.error("KEEP_MCP_KEEP_API_KEY is not set; refusing to start") |
28 | 93 | sys.exit(2) |
29 | | - |
30 | | - log.info( |
31 | | - "starting keep-mcp transport=%s keep_api_url=%s", |
32 | | - settings.transport, |
33 | | - settings.keep_api_url, |
34 | | - ) |
35 | | - |
36 | | - client = KeepClient(settings.keep_api_url, settings.keep_api_key, settings.http_timeout) |
37 | | - mcp = FastMCP( |
38 | | - name="keep", |
39 | | - instructions=( |
40 | | - "Read-only access to a Keep AIOps deployment. Use search_alerts and " |
41 | | - "list_incidents to see what is firing, then get_incident + " |
42 | | - "list_incident_alerts to drill in. CEL is the query language for " |
43 | | - "search_alerts — see docs.keephq.dev." |
44 | | - ), |
45 | | - ) |
46 | | - |
47 | | - @mcp.tool() |
48 | | - async def search_alerts(cel: str = "", limit: int = 25, offset: int = 0) -> dict[str, Any]: |
49 | | - """Query Keep alerts. `cel` is a CEL expression like `severity == "critical"`; empty returns most recent.""" |
50 | | - return await client.query_alerts(cel=cel, limit=max(1, min(limit, 1000)), offset=offset) |
51 | | - |
52 | | - @mcp.tool() |
53 | | - async def list_incidents( |
54 | | - status: list[str] | None = None, |
55 | | - severity: list[str] | None = None, |
56 | | - limit: int = 25, |
57 | | - offset: int = 0, |
58 | | - cel: str | None = None, |
59 | | - ) -> dict[str, Any]: |
60 | | - """List Keep incidents. Defaults to active incidents (firing + acknowledged) when status is omitted.""" |
61 | | - if status is None: |
62 | | - status = ["firing", "acknowledged"] |
63 | | - return await client.list_incidents( |
64 | | - status=status, |
65 | | - severity=severity, |
66 | | - limit=max(1, min(limit, 500)), |
67 | | - offset=offset, |
68 | | - cel=cel, |
69 | | - ) |
70 | | - |
71 | | - @mcp.tool() |
72 | | - async def get_incident(incident_id: str) -> dict[str, Any]: |
73 | | - """Fetch a single incident by UUID.""" |
74 | | - return await client.get_incident(incident_id) |
75 | | - |
76 | | - @mcp.tool() |
77 | | - async def list_incident_alerts( |
78 | | - incident_id: str, limit: int = 25, offset: int = 0 |
79 | | - ) -> dict[str, Any]: |
80 | | - """List alerts linked to an incident.""" |
81 | | - return await client.get_incident_alerts( |
82 | | - incident_id, limit=max(1, min(limit, 200)), offset=offset |
83 | | - ) |
84 | | - |
85 | | - @mcp.tool() |
86 | | - async def get_topology(service: str | None = None) -> list[dict[str, Any]]: |
87 | | - """Return the service dependency graph, optionally scoped to one service.""" |
88 | | - return await client.get_topology(service=service) |
89 | | - |
90 | | - @mcp.custom_route("/healthz", methods=["GET"]) |
91 | | - async def healthz(_: Request) -> PlainTextResponse: |
92 | | - return PlainTextResponse("ok") |
93 | | - |
94 | | - @mcp.custom_route("/readyz", methods=["GET"]) |
95 | | - async def readyz(_: Request) -> JSONResponse: |
96 | | - try: |
97 | | - resp = await client.get("/healthcheck") |
98 | | - ready = resp.status_code < 500 |
99 | | - except httpx.HTTPError: |
100 | | - ready = False |
101 | | - return JSONResponse( |
102 | | - {"ready": ready, "keep_api_url": settings.keep_api_url}, |
103 | | - status_code=200 if ready else 503, |
104 | | - ) |
105 | | - |
106 | | - if settings.transport == "stdio": |
| 94 | + logging.info("starting keep-mcp transport=%s keep_api_url=%s", TRANSPORT, API_URL) |
| 95 | + if TRANSPORT == "stdio": |
107 | 96 | mcp.run(transport="stdio") |
108 | 97 | else: |
109 | | - mcp.settings.host = settings.http_host |
110 | | - mcp.settings.port = settings.http_port |
| 98 | + mcp.settings.host = HTTP_HOST |
| 99 | + mcp.settings.port = HTTP_PORT |
111 | 100 | mcp.run(transport="streamable-http") |
112 | 101 |
|
113 | 102 |
|
|
0 commit comments