Skip to main content
Glama
driosalido
by driosalido

create_silence

Create a silence to mute a specific alert in a Kubernetes cluster. Specify the cluster, alert name, duration (e.g., '2h'), and a comment. Optionally add matchers to target specific alerts. Returns a silence ID.

Instructions

Create a new silence for specific alerts

Args: cluster: Target cluster name (e.g., 'teddy-prod') alertname: Name of the alert to silence duration: Duration of silence (e.g., '2h', '30m', '1d') comment: Comment explaining why the alert is being silenced matchers: Additional matchers in format 'key=value,key2=value2' (optional)

Returns: Silence creation result with silence ID

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
clusterYes
alertnameYes
durationNo2h
commentNoSilenced via MCP
matchersNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main tool implementation: `create_silence` MCP tool decorated with @mcp.tool(). Fetches cluster info from Karma API, parses duration, builds silence matchers, and returns a prepared silence creation request (placeholder awaiting direct Alertmanager API integration).
    @mcp.tool()
    async def create_silence(
        cluster: str,
        alertname: str,
        duration: str = "2h",
        comment: str = "Silenced via MCP",
        matchers: str = "",
    ) -> str:
        """Create a new silence for specific alerts
    
        Args:
            cluster: Target cluster name (e.g., 'teddy-prod')
            alertname: Name of the alert to silence
            duration: Duration of silence (e.g., '2h', '30m', '1d')
            comment: Comment explaining why the alert is being silenced
            matchers: Additional matchers in format 'key=value,key2=value2' (optional)
    
        Returns:
            Silence creation result with silence ID
        """
        try:
            # First, get the Alertmanager URL for this cluster
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    f"{KARMA_URL}/alerts.json",
                    json={},
                    headers={"Content-Type": "application/json"},
                    timeout=10.0,
                )
    
                if response.status_code != 200:
                    return (
                        f"Error fetching cluster information: code {response.status_code}"
                    )
    
                data = response.json()
                upstreams = data.get("upstreams", {}).get("instances", [])
    
                # Find the Alertmanager for this cluster
                alertmanager_url = None
                for upstream in upstreams:
                    if cluster.lower() in upstream.get("cluster", "").lower():
                        # For now, we'll need to use the publicURI
                        # In production, you might need to handle authentication
                        alertmanager_url = upstream.get("publicURI")
                        break
    
                if not alertmanager_url:
                    return f"Could not find Alertmanager for cluster: {cluster}"
    
                # Parse duration
                import re
                from datetime import datetime, timedelta
    
                # Parse duration string (e.g., '2h', '30m', '1d')
                duration_match = re.match(r"(\d+)([hdm])", duration.lower())
                if not duration_match:
                    return "Invalid duration format. Use format like '2h', '30m', or '1d'"
    
                amount = int(duration_match.group(1))
                unit = duration_match.group(2)
    
                if unit == "h":
                    delta = timedelta(hours=amount)
                elif unit == "m":
                    delta = timedelta(minutes=amount)
                elif unit == "d":
                    delta = timedelta(days=amount)
                else:
                    return f"Unsupported time unit: {unit}"
    
                starts_at = datetime.utcnow()
                ends_at = starts_at + delta
    
                # Build matchers
                silence_matchers = [
                    {
                        "name": "alertname",
                        "value": alertname,
                        "isRegex": False,
                        "isEqual": True,
                    }
                ]
    
                # Add additional matchers if provided
                if matchers:
                    for matcher_str in matchers.split(","):
                        if "=" in matcher_str:
                            key, value = matcher_str.split("=", 1)
                            silence_matchers.append(
                                {
                                    "name": key.strip(),
                                    "value": value.strip(),
                                    "isRegex": False,
                                    "isEqual": True,
                                }
                            )
    
                # Create silence request
                {
                    "matchers": silence_matchers,
                    "startsAt": starts_at.isoformat() + "Z",
                    "endsAt": ends_at.isoformat() + "Z",
                    "createdBy": "karma-mcp",
                    "comment": comment,
                }
    
                # Note: Actually creating the silence requires direct Alertmanager API access
                # which may need authentication. This is a placeholder for the actual implementation
                return f"""
    ⚠️ Silence Creation Request Prepared:
    
    📍 Cluster: {cluster}
    🔕 Alert: {alertname}
    ⏱️ Duration: {duration} (until {ends_at.strftime("%Y-%m-%d %H:%M UTC")})
    💬 Comment: {comment}
    🏷️ Matchers: {len(silence_matchers)} configured
    
    Note: Direct Alertmanager API integration is required to complete this action.
    The Alertmanager endpoint would be: {alertmanager_url}/api/v2/silences
    
    To manually create this silence, you can use the Karma UI or Alertmanager API directly.
    """
    
        except Exception as e:
            return f"Error creating silence: {str(e)}"
  • The @mcp.tool() decorator registers `create_silence` as an MCP tool on the FastMCP server instance.
    @mcp.tool()
  • Input parameters/schema for create_silence: cluster (str), alertname (str), duration (str, default '2h'), comment (str, default 'Silenced via MCP'), matchers (str, default '').
        cluster: str,
        alertname: str,
        duration: str = "2h",
        comment: str = "Silenced via MCP",
        matchers: str = "",
    ) -> str:
        """Create a new silence for specific alerts
    
        Args:
            cluster: Target cluster name (e.g., 'teddy-prod')
            alertname: Name of the alert to silence
            duration: Duration of silence (e.g., '2h', '30m', '1d')
            comment: Comment explaining why the alert is being silenced
            matchers: Additional matchers in format 'key=value,key2=value2' (optional)
    
        Returns:
            Silence creation result with silence ID
        """
  • Import of create_silence from .server into the HTTP server module for REST endpoint exposure.
    from .server import (
        check_karma,
        create_silence,
  • HTTP REST endpoint wrapper: POST /silences that calls the create_silence MCP tool via the create_silence_endpoint function.
    @app.post("/silences", response_model=MCPResponse)
    async def create_silence_endpoint(request: SilenceRequest):
        """Create a new silence for specific alerts"""
        try:
            result = await create_silence(
                cluster=request.cluster,
                alertname=request.alertname,
                duration=request.duration,
                comment=request.comment,
                matchers=request.matchers,
            )
            return MCPResponse(success=True, data=result)
        except Exception as e:
            logger.error(f"Error creating silence: {e}")
            return MCPResponse(success=False, data="", error=str(e))
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It explains the creation behavior and return value (silence ID), but does not disclose side effects (e.g., duplicate handling) or permission requirements.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a well-structured docstring with Args and Returns sections. It is concise, front-loaded with the purpose, and every sentence contributes value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 5 parameters and an output schema, the description covers parameter explanations and return value. It lacks edge cases and error handling, but is sufficient for basic usage given the output schema exists.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, but the description adds meaning for all five parameters, including examples for duration and format for matchers. This goes beyond the bare schema, though it could provide more detail on allowed values.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action 'Create a new silence for specific alerts', using a specific verb and resource. It distinguishes from sibling tools like delete_silence and list_silences.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description does not explicitly state when to use this tool versus alternatives. It implies usage by its name but lacks guidance on prerequisites or when not to use it, e.g., checking existing silences with list_silences.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/driosalido/mcp-karma'

If you have feedback or need assistance with the MCP directory API, please join our Discord server