talkops-alertmanager-mcp-server 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. alertmanager_mcp_server/__init__.py +3 -0
  2. alertmanager_mcp_server/config.py +103 -0
  3. alertmanager_mcp_server/exceptions/__init__.py +33 -0
  4. alertmanager_mcp_server/main.py +35 -0
  5. alertmanager_mcp_server/models/__init__.py +24 -0
  6. alertmanager_mcp_server/models/alert.py +32 -0
  7. alertmanager_mcp_server/models/audit.py +12 -0
  8. alertmanager_mcp_server/models/backend.py +17 -0
  9. alertmanager_mcp_server/models/config.py +68 -0
  10. alertmanager_mcp_server/models/silence.py +29 -0
  11. alertmanager_mcp_server/prompts/__init__.py +37 -0
  12. alertmanager_mcp_server/prompts/onboarding_prompts.py +40 -0
  13. alertmanager_mcp_server/prompts/silence_prompts.py +44 -0
  14. alertmanager_mcp_server/prompts/triage_prompts.py +38 -0
  15. alertmanager_mcp_server/resources/__init__.py +37 -0
  16. alertmanager_mcp_server/resources/alert_resources.py +28 -0
  17. alertmanager_mcp_server/resources/audit_resources.py +17 -0
  18. alertmanager_mcp_server/resources/backend_resources.py +49 -0
  19. alertmanager_mcp_server/resources/base.py +16 -0
  20. alertmanager_mcp_server/resources/config_resources.py +28 -0
  21. alertmanager_mcp_server/resources/silence_resources.py +16 -0
  22. alertmanager_mcp_server/resources/static_resources.py +24 -0
  23. alertmanager_mcp_server/resources/status_resources.py +25 -0
  24. alertmanager_mcp_server/server/__init__.py +3 -0
  25. alertmanager_mcp_server/server/bootstrap.py +26 -0
  26. alertmanager_mcp_server/server/core.py +17 -0
  27. alertmanager_mcp_server/services/__init__.py +658 -0
  28. alertmanager_mcp_server/static/ALERTMANAGER_BEST_PRACTICES.md +34 -0
  29. alertmanager_mcp_server/static/ALERTMANAGER_MCP_INSTRUCTIONS.md +79 -0
  30. alertmanager_mcp_server/static/ALERTMANAGER_ONBOARDING_GUIDE.md +44 -0
  31. alertmanager_mcp_server/static/__init__.py +1 -0
  32. alertmanager_mcp_server/tools/__init__.py +43 -0
  33. alertmanager_mcp_server/tools/alert_tools.py +205 -0
  34. alertmanager_mcp_server/tools/base.py +19 -0
  35. alertmanager_mcp_server/tools/discovery_tools.py +8 -0
  36. alertmanager_mcp_server/tools/governance_tools.py +153 -0
  37. alertmanager_mcp_server/tools/helper_tools.py +183 -0
  38. alertmanager_mcp_server/tools/routing_tools.py +109 -0
  39. alertmanager_mcp_server/tools/silence_tools.py +228 -0
  40. alertmanager_mcp_server/tools/triage_tools.py +123 -0
  41. alertmanager_mcp_server/utils/__init__.py +67 -0
  42. alertmanager_mcp_server/utils/audit.py +41 -0
  43. talkops_alertmanager_mcp_server-0.1.0.dist-info/METADATA +578 -0
  44. talkops_alertmanager_mcp_server-0.1.0.dist-info/RECORD +46 -0
  45. talkops_alertmanager_mcp_server-0.1.0.dist-info/WHEEL +4 -0
  46. talkops_alertmanager_mcp_server-0.1.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,3 @@
1
+ """Alertmanager MCP Server package."""
2
+
3
+ __version__ = '0.1.0'
@@ -0,0 +1,103 @@
1
+ """Application configuration management for Alertmanager MCP server."""
2
+
3
+ import json
4
+ import os
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict, List, Optional
7
+
8
+ from dotenv import load_dotenv
9
+
10
+ load_dotenv()
11
+
12
+
13
+ @dataclass
14
+ class BackendConfig:
15
+ """Configuration for a single Alertmanager backend."""
16
+ id: str = "default"
17
+ base_url: str = "http://localhost:9093"
18
+ display_name: Optional[str] = None
19
+ labels: Dict[str, str] = field(default_factory=dict)
20
+ auth_header: Optional[str] = None
21
+ verify_ssl: bool = True
22
+ timeout: int = 30
23
+ is_default: bool = True
24
+
25
+
26
+ @dataclass
27
+ class LoggingConfig:
28
+ """Logging configuration."""
29
+ level: str = 'INFO'
30
+ format: str = 'json'
31
+
32
+
33
+ @dataclass
34
+ class ServerConfig:
35
+ """MCP server configuration."""
36
+ name: str = 'alertmanager-mcp-server'
37
+ version: str = '0.1.0'
38
+ transport: str = 'stdio'
39
+ host: str = '0.0.0.0'
40
+ port: int = 8768
41
+ path: str = '/mcp'
42
+
43
+ backends: List[BackendConfig] = field(default_factory=lambda: [BackendConfig()])
44
+ logging: LoggingConfig = field(default_factory=LoggingConfig)
45
+
46
+ # Silence safety defaults
47
+ max_silence_duration_minutes: int = 1440 # 24h cap
48
+ silence_warning_threshold: int = 50 # warn if silence affects >= N alerts
49
+
50
+
51
+ class Config:
52
+ """Configuration loader."""
53
+
54
+ @staticmethod
55
+ def from_env() -> ServerConfig:
56
+ """Load configuration from environment variables."""
57
+ backends_json = os.getenv('ALERTMANAGER_BACKENDS')
58
+ if backends_json:
59
+ try:
60
+ raw_backends = json.loads(backends_json)
61
+ backends = [
62
+ BackendConfig(
63
+ id=b.get('id', f'backend-{i}'),
64
+ base_url=b.get('base_url', 'http://localhost:9093'),
65
+ display_name=b.get('display_name'),
66
+ labels=b.get('labels', {}),
67
+ auth_header=b.get('auth_header'),
68
+ verify_ssl=b.get('verify_ssl', True),
69
+ timeout=b.get('timeout', 30),
70
+ is_default=b.get('is_default', i == 0),
71
+ )
72
+ for i, b in enumerate(raw_backends)
73
+ ]
74
+ except (json.JSONDecodeError, TypeError):
75
+ backends = [BackendConfig()]
76
+ else:
77
+ backends = [
78
+ BackendConfig(
79
+ id=os.getenv('ALERTMANAGER_BACKEND_ID', 'default'),
80
+ base_url=os.getenv('ALERTMANAGER_BASE_URL', 'http://localhost:9093'),
81
+ display_name=os.getenv('ALERTMANAGER_DISPLAY_NAME'),
82
+ auth_header=os.getenv('ALERTMANAGER_AUTH_HEADER'),
83
+ verify_ssl=os.getenv('ALERTMANAGER_VERIFY_SSL', 'true').lower() == 'true',
84
+ timeout=int(os.getenv('ALERTMANAGER_TIMEOUT', '30')),
85
+ is_default=True,
86
+ )
87
+ ]
88
+
89
+ return ServerConfig(
90
+ name=os.getenv('MCP_SERVER_NAME', 'alertmanager-mcp-server'),
91
+ version=os.getenv('MCP_SERVER_VERSION', '0.1.0'),
92
+ transport=os.getenv('MCP_TRANSPORT', 'stdio'),
93
+ host=os.getenv('MCP_HOST', '0.0.0.0'),
94
+ port=int(os.getenv('MCP_PORT', '8768')),
95
+ path=os.getenv('MCP_PATH', '/mcp'),
96
+ backends=backends,
97
+ logging=LoggingConfig(
98
+ level=os.getenv('MCP_LOG_LEVEL', 'INFO'),
99
+ format=os.getenv('MCP_LOG_FORMAT', 'json'),
100
+ ),
101
+ max_silence_duration_minutes=int(os.getenv('AM_MAX_SILENCE_MINUTES', '1440')),
102
+ silence_warning_threshold=int(os.getenv('AM_SILENCE_WARNING_THRESHOLD', '50')),
103
+ )
@@ -0,0 +1,33 @@
1
+ """Custom exceptions for Alertmanager MCP server."""
2
+
3
+ from fastmcp.exceptions import NotFoundError, ResourceError, ToolError, ValidationError
4
+
5
+
6
+ class AlertmanagerOperationError(ToolError):
7
+ """Error during Alertmanager tool operations."""
8
+ pass
9
+
10
+
11
+ class AlertmanagerResourceError(ResourceError):
12
+ """Error during Alertmanager resource operations."""
13
+ pass
14
+
15
+
16
+ class AlertmanagerNotFoundError(NotFoundError):
17
+ """Error when an Alertmanager resource is not found."""
18
+ pass
19
+
20
+
21
+ class AlertmanagerValidationError(ValidationError):
22
+ """Error validating Alertmanager parameters."""
23
+ pass
24
+
25
+
26
+ class AlertmanagerConnectionError(ToolError):
27
+ """Error connecting to an Alertmanager backend."""
28
+ pass
29
+
30
+
31
+ class SilenceSafetyError(ToolError):
32
+ """Error when a silence operation violates safety guardrails."""
33
+ pass
@@ -0,0 +1,35 @@
1
+ """Application entry point."""
2
+ import asyncio
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ project_root = Path(__file__).parent.parent
7
+ if str(project_root) not in sys.path:
8
+ sys.path.insert(0, str(project_root))
9
+
10
+ from alertmanager_mcp_server.server.bootstrap import ServerBootstrap
11
+
12
+
13
+ def main():
14
+ service = None
15
+ try:
16
+ mcp, config, service = ServerBootstrap.initialize()
17
+ # Run FastMCP server with the configured transport
18
+ if config.transport in ('http', 'sse', 'streamable-http'):
19
+ mcp.run(transport=config.transport, host=config.host, port=config.port, path=config.path)
20
+ else:
21
+ mcp.run()
22
+ except KeyboardInterrupt:
23
+ pass
24
+ finally:
25
+ # Graceful shutdown: close all HTTP clients
26
+ if service is not None:
27
+ asyncio.get_event_loop().run_until_complete(service.close())
28
+
29
+
30
+ def cli():
31
+ main()
32
+
33
+
34
+ if __name__ == '__main__':
35
+ cli()
@@ -0,0 +1,24 @@
1
+ """Alertmanager data models package."""
2
+
3
+ from alertmanager_mcp_server.models.backend import BackendDescriptor, BackendsSummary
4
+ from alertmanager_mcp_server.models.alert import (
5
+ AlertMatcher, AlertStatus, GettableAlert, AlertGroup,
6
+ )
7
+ from alertmanager_mcp_server.models.silence import (
8
+ SilenceStatus, PostableSilence, GettableSilence,
9
+ SilenceEffectPreview,
10
+ )
11
+ from alertmanager_mcp_server.models.config import (
12
+ ReceiverConfig, RoutingRoute, InhibitionRule,
13
+ AlertmanagerConfigSnapshot, RoutingSimulationResult,
14
+ )
15
+ from alertmanager_mcp_server.models.audit import AuditLogEntry
16
+
17
+ __all__ = [
18
+ 'BackendDescriptor', 'BackendsSummary',
19
+ 'AlertMatcher', 'AlertStatus', 'GettableAlert', 'AlertGroup',
20
+ 'SilenceStatus', 'PostableSilence', 'GettableSilence', 'SilenceEffectPreview',
21
+ 'ReceiverConfig', 'RoutingRoute', 'InhibitionRule',
22
+ 'AlertmanagerConfigSnapshot', 'RoutingSimulationResult',
23
+ 'AuditLogEntry',
24
+ ]
@@ -0,0 +1,32 @@
1
+ """Alert and alert group models aligned with Alertmanager API v2."""
2
+ from datetime import datetime
3
+ from typing import Any, Dict, List, Optional
4
+ from pydantic import BaseModel, Field
5
+
6
+
7
+ class AlertMatcher(BaseModel):
8
+ name: str = Field(..., description="Label name")
9
+ value: str = Field(..., description="Label value or regex pattern")
10
+ isRegex: bool = Field(False, description="Whether value is a regex")
11
+ isEqual: bool = Field(True, description="False for negative matching")
12
+
13
+
14
+ class AlertStatus(BaseModel):
15
+ state: str = Field("active", description="active, suppressed, unprocessed")
16
+ silencedBy: List[str] = Field(default_factory=list)
17
+ inhibitedBy: List[str] = Field(default_factory=list)
18
+
19
+
20
+ class GettableAlert(BaseModel):
21
+ fingerprint: str
22
+ labels: Dict[str, str] = Field(default_factory=dict)
23
+ annotations: Dict[str, str] = Field(default_factory=dict)
24
+ startsAt: datetime
25
+ endsAt: Optional[datetime] = None
26
+ generatorURL: Optional[str] = None
27
+ status: Dict[str, Any] = Field(default_factory=dict)
28
+
29
+
30
+ class AlertGroup(BaseModel):
31
+ labels: Dict[str, str] = Field(default_factory=dict)
32
+ alerts: List[GettableAlert] = Field(default_factory=list)
@@ -0,0 +1,12 @@
1
+ """Audit log models."""
2
+ from datetime import datetime
3
+ from typing import List
4
+ from pydantic import BaseModel, Field
5
+
6
+
7
+ class AuditLogEntry(BaseModel):
8
+ timestamp: datetime
9
+ backend_id: str
10
+ operation: str
11
+ principal: str
12
+ summary: str
@@ -0,0 +1,17 @@
1
+ """Alertmanager backend models."""
2
+ from typing import Dict, List, Literal, Optional
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class BackendDescriptor(BaseModel):
7
+ id: str
8
+ display_name: Optional[str] = None
9
+ base_url: str
10
+ labels: Dict[str, str] = Field(default_factory=dict)
11
+ health: Literal["unknown", "healthy", "degraded", "unhealthy"] = "unknown"
12
+ version: Optional[str] = None
13
+ is_default: bool = False
14
+
15
+
16
+ class BackendsSummary(BaseModel):
17
+ backends: List[BackendDescriptor]
@@ -0,0 +1,68 @@
1
+ """Configuration, receiver, and routing models."""
2
+ from datetime import datetime
3
+ from typing import Any, Dict, List, Optional
4
+ from pydantic import BaseModel, Field
5
+ from alertmanager_mcp_server.models.alert import AlertMatcher
6
+
7
+
8
+ class ReceiverConfig(BaseModel):
9
+ name: str
10
+ type: Optional[str] = None
11
+ details: Dict[str, Any] = Field(default_factory=dict)
12
+
13
+
14
+ class RoutingRoute(BaseModel):
15
+ matchers: List[AlertMatcher] = Field(default_factory=list)
16
+ receiver: Optional[str] = None
17
+ group_by: List[str] = Field(default_factory=list)
18
+ group_wait: Optional[str] = None
19
+ group_interval: Optional[str] = None
20
+ repeat_interval: Optional[str] = None
21
+
22
+
23
+ class RoutingTreeNode(BaseModel):
24
+ """Nested routing tree node preserving the full tree structure."""
25
+ receiver: Optional[str] = None
26
+ matchers: List[AlertMatcher] = Field(default_factory=list)
27
+ group_by: List[str] = Field(default_factory=list)
28
+ group_wait: Optional[str] = None
29
+ group_interval: Optional[str] = None
30
+ repeat_interval: Optional[str] = None
31
+ continue_routing: bool = False
32
+ routes: List["RoutingTreeNode"] = Field(default_factory=list)
33
+
34
+
35
+ class InhibitionRule(BaseModel):
36
+ source_matchers: List[AlertMatcher] = Field(default_factory=list)
37
+ target_matchers: List[AlertMatcher] = Field(default_factory=list)
38
+ equal: List[str] = Field(default_factory=list)
39
+
40
+
41
+ class AlertmanagerConfigSnapshot(BaseModel):
42
+ routes: List[RoutingRoute] = Field(default_factory=list)
43
+ inhibitions: List[InhibitionRule] = Field(default_factory=list)
44
+
45
+
46
+ class RoutingSimulationResult(BaseModel):
47
+ receivers: List[str] = Field(default_factory=list)
48
+ route_path: str = ""
49
+ inhibited_by: List[str] = Field(default_factory=list)
50
+
51
+
52
+ class RoutingExplanation(BaseModel):
53
+ """Rich routing explanation with human-readable reasoning."""
54
+ matched_route: str = ""
55
+ receivers: List[str] = Field(default_factory=list)
56
+ group_labels: List[str] = Field(default_factory=list)
57
+ inhibited_by: List[str] = Field(default_factory=list)
58
+ explanation: str = ""
59
+
60
+
61
+ class SilenceChange(BaseModel):
62
+ """A silence change event for governance audit."""
63
+ silence_id: str
64
+ action: str # "created", "expired", "updated"
65
+ matchers_summary: str = ""
66
+ created_by: str = ""
67
+ comment: str = ""
68
+ timestamp: datetime
@@ -0,0 +1,29 @@
1
+ """Silence models aligned with Alertmanager API v2."""
2
+ from datetime import datetime
3
+ from typing import List, Optional
4
+ from pydantic import BaseModel, Field
5
+ from alertmanager_mcp_server.models.alert import AlertMatcher, GettableAlert
6
+
7
+
8
+ class SilenceStatus(BaseModel):
9
+ state: str = Field(..., description="active, pending, or expired")
10
+
11
+
12
+ class PostableSilence(BaseModel):
13
+ matchers: List[AlertMatcher]
14
+ startsAt: datetime
15
+ endsAt: datetime
16
+ createdBy: str
17
+ comment: str
18
+
19
+
20
+ class GettableSilence(PostableSilence):
21
+ id: str
22
+ status: SilenceStatus
23
+ updatedAt: Optional[datetime] = None
24
+
25
+
26
+ class SilenceEffectPreview(BaseModel):
27
+ affected_alert_count: int = 0
28
+ affected_alerts_preview: List[GettableAlert] = Field(default_factory=list)
29
+ warning_flag: bool = False
@@ -0,0 +1,37 @@
1
+ """Prompts module for Alertmanager MCP server."""
2
+ from typing import Any, Dict, List
3
+ from abc import ABC, abstractmethod
4
+
5
+
6
+ class BasePrompt(ABC):
7
+ def __init__(self, service_locator: Dict[str, Any]):
8
+ self.alertmanager_service = service_locator.get('alertmanager_service')
9
+
10
+ @abstractmethod
11
+ def register(self, mcp_instance) -> None:
12
+ pass
13
+
14
+
15
+ class PromptRegistry:
16
+ def __init__(self):
17
+ self.prompts: List[BasePrompt] = []
18
+
19
+ def register_prompt(self, prompt: BasePrompt) -> None:
20
+ self.prompts.append(prompt)
21
+
22
+ def register_all_prompts(self, mcp_instance) -> None:
23
+ for prompt in self.prompts:
24
+ prompt.register(mcp_instance)
25
+
26
+
27
+ from alertmanager_mcp_server.prompts.triage_prompts import TriagePrompts
28
+ from alertmanager_mcp_server.prompts.silence_prompts import SilencePrompts
29
+ from alertmanager_mcp_server.prompts.onboarding_prompts import OnboardingPrompts
30
+
31
+
32
+ def initialize_prompts(service_locator: Dict[str, Any]) -> PromptRegistry:
33
+ registry = PromptRegistry()
34
+ registry.register_prompt(TriagePrompts(service_locator))
35
+ registry.register_prompt(SilencePrompts(service_locator))
36
+ registry.register_prompt(OnboardingPrompts(service_locator))
37
+ return registry
@@ -0,0 +1,40 @@
1
+ """Onboarding and pipeline validation prompts."""
2
+ from mcp.types import PromptMessage, TextContent
3
+ from alertmanager_mcp_server.prompts import BasePrompt
4
+
5
+
6
+ class OnboardingPrompts(BasePrompt):
7
+ def register(self, mcp_instance) -> None:
8
+ @mcp_instance.prompt(name="am-integration-test-guided",
9
+ description="Guided workflow for testing notification integrations (Slack, PagerDuty)")
10
+ def am_integration_test(backend_id: str, team: str = "sre", receiver: str = "slack-sre") -> list[PromptMessage]:
11
+ return [PromptMessage(role="user", content=TextContent(type="text", text=f"""# 🧪 Integration Test Guide
12
+
13
+ ## Context
14
+ - **Backend**: {backend_id}
15
+ - **Team**: {team}
16
+ - **Target Receiver**: {receiver}
17
+
18
+ ## Phase 1: Check Receivers
19
+ ```
20
+ Resource: am://system/receivers
21
+ ```
22
+ Verify that receiver '{receiver}' is configured.
23
+
24
+ ## Phase 2: Simulate Routing
25
+ ```
26
+ Tool: am_alert_mgmt(action="simulate_routing", backend_id="{backend_id}", alert_labels={{"alertname": "MCPIntegrationTest", "team": "{team}", "env": "staging"}})
27
+ ```
28
+
29
+ ## Phase 3: Push Test Alert
30
+ ```
31
+ Tool: am_alert_mgmt(action="push_test", backend_id="{backend_id}", alert_labels={{"alertname": "MCPIntegrationTest", "team": "{team}", "env": "staging", "severity": "warning"}}, annotations={{"summary": "Test alert from Alertmanager MCP"}})
32
+ ```
33
+
34
+ ## Phase 4: Verify Receipt
35
+ Ask the user to confirm the test alert arrived in {receiver}.
36
+ If not received, check routing config:
37
+ ```
38
+ Resource: am://system/config
39
+ ```
40
+ """))]
@@ -0,0 +1,44 @@
1
+ """Silence management guided workflow prompts."""
2
+ from mcp.types import PromptMessage, TextContent
3
+ from alertmanager_mcp_server.prompts import BasePrompt
4
+
5
+
6
+ class SilencePrompts(BasePrompt):
7
+ def register(self, mcp_instance) -> None:
8
+ @mcp_instance.prompt(name="am-maintenance-silence-guided",
9
+ description="Guided workflow for creating a maintenance silence")
10
+ def am_maintenance_silence(backend_id: str, service: str = "checkout", env: str = "prod", duration: int = 60) -> list[PromptMessage]:
11
+ return [PromptMessage(role="user", content=TextContent(type="text", text=f"""# 🔇 Maintenance Silence Guide
12
+
13
+ ## Context
14
+ - **Backend**: {backend_id}
15
+ - **Service**: {service}
16
+ - **Environment**: {env}
17
+ - **Duration**: {duration} minutes
18
+
19
+ ## Phase 1: Preview Impact (MANDATORY)
20
+ ```
21
+ Tool: am_helper_mgmt(action="preview_silence", backend_id="{backend_id}", matchers=[{{"name": "service", "value": "{service}", "isRegex": false, "isEqual": true}}, {{"name": "env", "value": "{env}", "isRegex": false, "isEqual": true}}])
22
+ ```
23
+ ⚠️ If warning_flag is true, narrow your matchers before proceeding.
24
+
25
+ ## Phase 2: Create Silence
26
+ ```
27
+ Tool: am_silence_mgmt(action="create", backend_id="{backend_id}", matchers=[{{"name": "service", "value": "{service}", "isRegex": false, "isEqual": true}}, {{"name": "env", "value": "{env}", "isRegex": false, "isEqual": true}}], duration_minutes={duration}, comment="Planned maintenance for {service}")
28
+ ```
29
+
30
+ ## Phase 3: Confirm
31
+ ```
32
+ Tool: am_silence_mgmt(action="list", backend_id="{backend_id}", state="active")
33
+ ```
34
+
35
+ ## Phase 4: Extend if Needed
36
+ ```
37
+ Tool: am_silence_mgmt(action="extend", backend_id="{backend_id}", silence_id="<from step 2>", add_minutes=30)
38
+ ```
39
+
40
+ ## Phase 5: Clean Up
41
+ ```
42
+ Tool: am_silence_mgmt(action="expire", backend_id="{backend_id}", silence_id="<from step 2>")
43
+ ```
44
+ """))]
@@ -0,0 +1,38 @@
1
+ """Alert triage guided workflow prompts."""
2
+ from mcp.types import PromptMessage, TextContent
3
+ from alertmanager_mcp_server.prompts import BasePrompt
4
+
5
+
6
+ class TriagePrompts(BasePrompt):
7
+ def register(self, mcp_instance) -> None:
8
+ @mcp_instance.prompt(name="am-alert-triage-guided",
9
+ description="Guided workflow for triaging active alerts")
10
+ def am_alert_triage(backend_id: str, service: str = "checkout", env: str = "prod") -> list[PromptMessage]:
11
+ return [PromptMessage(role="user", content=TextContent(type="text", text=f"""# 🚨 Alert Triage Guide
12
+
13
+ ## Context
14
+ - **Backend**: {backend_id}
15
+ - **Service**: {service}
16
+ - **Environment**: {env}
17
+
18
+ ## Phase 1: See What's Firing
19
+ ```
20
+ Tool: am_alert_mgmt(action="list", backend_id="{backend_id}", label_filters={{"service": "{service}", "env": "{env}"}})
21
+ ```
22
+
23
+ ## Phase 2: Group Related Alerts
24
+ ```
25
+ Tool: am_alert_mgmt(action="list_groups", backend_id="{backend_id}")
26
+ ```
27
+
28
+ ## Phase 3: Check Routing
29
+ ```
30
+ Tool: am_alert_mgmt(action="simulate_routing", backend_id="{backend_id}", alert_labels={{"alertname": "<from step 1>", "service": "{service}", "env": "{env}"}})
31
+ ```
32
+
33
+ ## Phase 4: Investigate with Prometheus MCP
34
+ Use the Prometheus MCP server for metric-level diagnostics:
35
+ ```
36
+ prom_query_mgmt(action="instant", query="up{{service='{service}'}}")
37
+ ```
38
+ """))]
@@ -0,0 +1,37 @@
1
+ """Resources module for Alertmanager MCP server."""
2
+ from typing import Any, Dict, List
3
+ from alertmanager_mcp_server.resources.base import BaseResource
4
+
5
+
6
+ class ResourceRegistry:
7
+ def __init__(self, service_locator: Dict[str, Any]):
8
+ self.service_locator = service_locator
9
+ self.resources: List[BaseResource] = []
10
+
11
+ def register_resource(self, resource: BaseResource) -> None:
12
+ self.resources.append(resource)
13
+
14
+ def register_all_resources(self, mcp_instance) -> None:
15
+ for resource in self.resources:
16
+ resource.register(mcp_instance)
17
+
18
+
19
+ from alertmanager_mcp_server.resources.backend_resources import BackendResources
20
+ from alertmanager_mcp_server.resources.alert_resources import AlertResources
21
+ from alertmanager_mcp_server.resources.silence_resources import SilenceResources
22
+ from alertmanager_mcp_server.resources.config_resources import ConfigResources
23
+ from alertmanager_mcp_server.resources.static_resources import StaticResources
24
+ from alertmanager_mcp_server.resources.audit_resources import AuditResources
25
+ from alertmanager_mcp_server.resources.status_resources import StatusResources
26
+
27
+
28
+ def initialize_resources(service_locator: Dict[str, Any]) -> ResourceRegistry:
29
+ registry = ResourceRegistry(service_locator)
30
+ registry.register_resource(BackendResources(service_locator))
31
+ registry.register_resource(AlertResources(service_locator))
32
+ registry.register_resource(SilenceResources(service_locator))
33
+ registry.register_resource(ConfigResources(service_locator))
34
+ registry.register_resource(StaticResources(service_locator))
35
+ registry.register_resource(AuditResources(service_locator))
36
+ registry.register_resource(StatusResources(service_locator))
37
+ return registry
@@ -0,0 +1,28 @@
1
+ """Alert resources."""
2
+ import json
3
+ from alertmanager_mcp_server.resources.base import BaseResource
4
+
5
+
6
+ class AlertResources(BaseResource):
7
+ def register(self, mcp_instance) -> None:
8
+ @mcp_instance.resource("am://alerts/active", name="am_active_alerts",
9
+ description="Bounded snapshot of active alerts for default backend", mime_type="application/json")
10
+ async def active_alerts_resource() -> str:
11
+ backends = self.alertmanager_service.list_backends()
12
+ default = next((b for b in backends if b.is_default), backends[0] if backends else None)
13
+ if not default:
14
+ return json.dumps({"alerts": [], "error": "No backends configured"})
15
+ alerts, _, _ = await self.alertmanager_service.list_alerts(
16
+ default.id, active=True, silenced=False, inhibited=False, limit=50, offset=0,
17
+ )
18
+ return json.dumps({"alerts": [a.model_dump(mode="json") for a in alerts]}, default=str, indent=2)
19
+
20
+ @mcp_instance.resource("am://alerts/groups", name="am_alert_groups",
21
+ description="Snapshot of alert groups as computed by Alertmanager", mime_type="application/json")
22
+ async def alert_groups_resource() -> str:
23
+ backends = self.alertmanager_service.list_backends()
24
+ default = next((b for b in backends if b.is_default), backends[0] if backends else None)
25
+ if not default:
26
+ return json.dumps({"groups": [], "error": "No backends configured"})
27
+ groups = await self.alertmanager_service.list_alert_groups(default.id)
28
+ return json.dumps({"groups": [g.model_dump(mode="json") for g in groups]}, default=str, indent=2)
@@ -0,0 +1,17 @@
1
+ """Audit log resources."""
2
+ import json
3
+ from alertmanager_mcp_server.resources.base import BaseResource
4
+ from alertmanager_mcp_server.utils.audit import get_audit_entries
5
+
6
+
7
+ class AuditResources(BaseResource):
8
+ def register(self, mcp_instance) -> None:
9
+ @mcp_instance.resource("am://system/audit-log", name="am_audit_log",
10
+ description="Recent MCP-initiated operations (create/expire/extend silence, push test alert)",
11
+ mime_type="application/json")
12
+ async def audit_log_resource() -> str:
13
+ entries = get_audit_entries()
14
+ return json.dumps(
15
+ {"entries": [e.model_dump(mode="json") for e in entries]},
16
+ default=str, indent=2,
17
+ )
@@ -0,0 +1,49 @@
1
+ """Backend resources."""
2
+ import json
3
+ from alertmanager_mcp_server.models.backend import BackendDescriptor
4
+ from alertmanager_mcp_server.resources.base import BaseResource
5
+
6
+
7
+ class BackendResources(BaseResource):
8
+ def register(self, mcp_instance) -> None:
9
+ @mcp_instance.resource("am://system/backends", name="am_backends",
10
+ description="All Alertmanager backends with health status", mime_type="application/json")
11
+ async def list_backends_resource() -> str:
12
+ backends = self.alertmanager_service.list_backends()
13
+ result = []
14
+ for b in backends:
15
+ health = await self.alertmanager_service.check_health(b.id)
16
+ updated = BackendDescriptor(
17
+ id=b.id, display_name=b.display_name,
18
+ base_url=b.base_url, labels=b.labels,
19
+ health=health, version=b.version, is_default=b.is_default,
20
+ )
21
+ result.append(updated.model_dump())
22
+ return json.dumps({"backends": result}, default=str, indent=2)
23
+
24
+ @mcp_instance.resource("am://system/backends/{backend_id}", name="am_backend_detail",
25
+ description="Detailed status, version, cluster info, and health for one backend",
26
+ mime_type="application/json")
27
+ async def get_backend_detail_resource(backend_id: str) -> str:
28
+ health = await self.alertmanager_service.check_health(backend_id)
29
+ status = await self.alertmanager_service.get_status(backend_id)
30
+ backends = self.alertmanager_service.list_backends()
31
+ backend = next((b for b in backends if b.id == backend_id), None)
32
+ if not backend:
33
+ return json.dumps({"error": f"Unknown backend_id '{backend_id}'"})
34
+ version_info = status.get("versionInfo", {})
35
+ return json.dumps({
36
+ "backend": {
37
+ "id": backend.id,
38
+ "display_name": backend.display_name,
39
+ "base_url": backend.base_url,
40
+ "labels": backend.labels,
41
+ "health": health,
42
+ "is_default": backend.is_default,
43
+ "version": version_info.get("version"),
44
+ "revision": version_info.get("revision"),
45
+ "build_date": version_info.get("buildDate"),
46
+ },
47
+ "cluster": status.get("cluster", {}),
48
+ "uptime": status.get("uptime"),
49
+ }, default=str, indent=2)