Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ The GitGuardian MCP server connects any MCP client to GitGuardian's secrets dete
hours, or leave it at zero for the workspace's default sharing duration. Revoke the link
with `revoke_public_incident_share_link` to end that access.
- **Close the loop.** Resolve, ignore or reopen incidents, revoke exposed secrets,
and deploy honeytokens.
and deploy honeytokens. `resolve_internal_incident` and `ignore_internal_incident`
accept either `incident_id` or `incident_ids` (1–50 distinct IDs), with one shared,
user-provided revocation answer or ignore reason. Batches return an outcome per ID,
continue after individual failures, and stop on rate limiting with the remaining IDs
marked as skipped. Each incident still uses its own API request.

### Developers: fix incidents in the repository you work on

Expand Down
11 changes: 10 additions & 1 deletion src/gg_api_core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,7 @@ async def _request(
*,
privacy_mode: bool = True,
return_response: bool = False,
retry_on_rate_limit: bool = True,
**kwargs: Any,
) -> Any:
"""Make a request to the GitGuardian API (generic method).
Expand All @@ -631,6 +632,8 @@ async def _request(
Opt-out requests do not follow redirects or log response bodies.
return_response: Return the successful httpx.Response instead of its parsed
body, for callers that also need the headers.
retry_on_rate_limit: Retry rate-limited reads. Batch write read-backs disable
this so a 429 stops the batch immediately.
**kwargs: Additional arguments to pass to requests

Returns:
Expand Down Expand Up @@ -689,6 +692,7 @@ async def _request(
if (
method.upper() == "GET"
and response.status_code in _RETRYABLE_READ_STATUSES
and (response.status_code != 429 or retry_on_rate_limit)
and retry_count < max_retries
and (wait_time := _retry_delay_seconds(response, retry_count + 1)) is not None
):
Expand Down Expand Up @@ -1037,12 +1041,15 @@ async def get_incident(
self,
incident_id: int,
with_occurrences: int = 20,
*,
retry_on_rate_limit: bool = True,
) -> dict[str, Any]:
"""Get detailed information about a specific incident.

Args:
incident_id: ID of the incident to retrieve
with_occurrences: Number of occurrences to retrieve (0-100, default: 20)
retry_on_rate_limit: Whether to wait and retry a 429 response (default: True)

Returns:
Detailed incident data including occurrences
Expand All @@ -1051,7 +1058,9 @@ async def get_incident(
params: dict[str, Any] = {}
if with_occurrences != 20:
params["with_occurrences"] = with_occurrences
return await self._request_get(f"/incidents/secrets/{incident_id}", params=params)
return await self._request_get(
f"/incidents/secrets/{incident_id}", params=params, retry_on_rate_limit=retry_on_rate_limit
)

async def get_current_token_info(self) -> dict[str, Any]:
"""Get information about the current API token.
Expand Down
139 changes: 120 additions & 19 deletions src/gg_api_core/tools/incident_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import logging
from collections.abc import Awaitable
from typing import Any, Literal
from typing import Annotated, Any, Literal, Self

from pydantic import BaseModel, Field
import httpx
from fastmcp.exceptions import ToolError
from pydantic import BaseModel, Field, model_validator

from gg_api_core.client import GitGuardianClient
from gg_api_core.client import GitGuardianClient, caused_by_downstream_401
from gg_api_core.tools.ids import NumericId
from gg_api_core.tools.incident_writes import (
CHANGED_DESCRIPTION,
Expand All @@ -24,19 +26,40 @@
_STATUSES_AFTER = {"resolve": {"RESOLVED"}, "ignore": {"IGNORED"}, "reopen": {"TRIGGERED", "ASSIGNED"}}


class ResolveInternalIncidentParams(BaseModel):
"""Parameters for resolving an internal incident."""
MAX_BULK_INCIDENTS = 50


class InternalIncidentSelection(BaseModel):
"""Select one incident or a bounded batch, with each ID processed once."""

incident_id: NumericId | None = Field(default=None, description="One internal incident ID; omit incident_ids")
incident_ids: list[NumericId] | None = Field(
default=None,
min_length=1,
max_length=MAX_BULK_INCIDENTS,
description=f"1–{MAX_BULK_INCIDENTS} distinct internal incident IDs; omit incident_id",
)

@model_validator(mode="after")
def check_selection(self) -> Self:
if (self.incident_id is None) == (self.incident_ids is None):
raise ValueError("Provide exactly one of incident_id or incident_ids")
if self.incident_ids is not None and len(set(self.incident_ids)) != len(self.incident_ids):
raise ValueError("incident_ids must contain distinct IDs")
return self


class ResolveInternalIncidentParams(InternalIncidentSelection):
"""Parameters for resolving internal incidents with one shared revocation answer."""

incident_id: NumericId = Field(description="ID of the internal secret incident")
secret_revoked: bool = Field(
description="Whether the secret was revoked or rotated. Must come from the user: ask, do not assume."
)


class IgnoreInternalIncidentParams(BaseModel):
"""Parameters for ignoring an internal incident."""
class IgnoreInternalIncidentParams(InternalIncidentSelection):
"""Parameters for ignoring internal incidents with one shared reason."""

incident_id: NumericId = Field(description="ID of the internal secret incident")
ignore_reason: Literal["test_credential", "false_positive", "low_risk", "invalid"] = Field(
description="Why the incident is ignored. Must come from the user: ask, do not choose. 'test_credential' "
"(a secret used for testing), 'false_positive' (not a real secret), 'low_risk' (the secret poses little "
Expand Down Expand Up @@ -97,11 +120,13 @@ async def _apply(
incident_id: int,
action: StatusChange,
call: Awaitable[dict[str, Any]],
*,
retry_on_rate_limit: bool = True,
) -> IncidentStatusResult:
"""Make the change, and describe the incident it leaves."""
incident, changed = await apply_or_confirm(
call,
incident_reader(client, kind, incident_id),
incident_reader(client, kind, incident_id, retry_on_rate_limit=retry_on_rate_limit),
lambda current: current.get("status") in _STATUSES_AFTER[action],
check_advice(kind),
)
Expand All @@ -115,18 +140,94 @@ async def _apply(
)


async def resolve_internal_incident(params: ResolveInternalIncidentParams) -> IncidentStatusResult:
"""Resolve an internal secret incident."""
client = await get_client()
call = client.resolve_incident(str(params.incident_id), secret_revoked=params.secret_revoked)
return await _apply(client, "internal", params.incident_id, "resolve", call)
class IncidentStatusError(BaseModel):
"""An unsuccessful batch item; changed is unknown for an uncertain write."""

incident_id: int
changed: None = None
error: str = Field(description="Why the change failed, is uncertain, or was skipped")
skipped: bool = Field(default=False, description="True when this incident was never attempted")


class BulkIncidentStatusResult(BaseModel):
"""One outcome per requested ID, in input order. Errors remain visible in a successful tool response."""

results: list[IncidentStatusResult | IncidentStatusError]


# Both shapes are JSON objects. Mark the union as an object so FastMCP keeps
# structuredContent flat, preserving the legacy single-ID wire format.
InternalIncidentStatusResult = Annotated[
IncidentStatusResult | BulkIncidentStatusResult, Field(json_schema_extra={"type": "object"})
]


def _http_error(error: BaseException) -> httpx.HTTPStatusError | None:
"""Find the API response through the ToolError wrappers used for incident writes."""
current: BaseException | None = error
seen: set[int] = set()
while current is not None and id(current) not in seen:
if isinstance(current, httpx.HTTPStatusError):
return current
seen.add(id(current))
current = current.__cause__ or current.__context__
return None


async def ignore_internal_incident(params: IgnoreInternalIncidentParams) -> IncidentStatusResult:
"""Ignore an internal secret incident."""
async def _change_internal_incidents(
params: ResolveInternalIncidentParams | IgnoreInternalIncidentParams,
) -> InternalIncidentStatusResult:
client = await get_client()
call = client.ignore_incident(str(params.incident_id), ignore_reason=params.ignore_reason)
return await _apply(client, "internal", params.incident_id, "ignore", call)
action: StatusChange = "resolve" if isinstance(params, ResolveInternalIncidentParams) else "ignore"

async def change(incident_id: int) -> IncidentStatusResult:
if isinstance(params, ResolveInternalIncidentParams):
call = client.resolve_incident(str(incident_id), secret_revoked=params.secret_revoked)
else:
call = client.ignore_incident(str(incident_id), ignore_reason=params.ignore_reason)
return await _apply(
client, "internal", incident_id, action, call, retry_on_rate_limit=params.incident_ids is None
)

# Keep the existing single-ID result and error/authentication behavior.
if params.incident_id is not None:
return await change(params.incident_id)

results: list[IncidentStatusResult | IncidentStatusError] = []
stopped: str | None = None
for incident_id in params.incident_ids or []:
if stopped is not None:
results.append(IncidentStatusError(incident_id=incident_id, error=stopped, skipped=True))
continue
try:
results.append(await change(incident_id))
except ToolError as error:
# Preserve the HTTP 401 challenge that lets MCP clients reauthenticate.
if caused_by_downstream_401(error):
raise
message = str(error)
api_error = _http_error(error)
if api_error is not None and api_error.response.status_code == 429:
retry_after = api_error.response.headers.get("retry-after")
if retry_after:
message += f" Retry-After: {retry_after}."
stopped = f"Skipped because the API rate limit stopped this batch. {message}"
results.append(IncidentStatusError(incident_id=incident_id, error=message))
return BulkIncidentStatusResult(results=results)


async def resolve_internal_incident(
params: ResolveInternalIncidentParams,
) -> InternalIncidentStatusResult:
"""Resolve one internal incident or a bounded batch."""
return await _change_internal_incidents(params)


async def ignore_internal_incident(
params: IgnoreInternalIncidentParams,
) -> InternalIncidentStatusResult:
"""Ignore one internal incident or a bounded batch."""
return await _change_internal_incidents(params)


async def reopen_internal_incident(params: ReopenInternalIncidentParams) -> IncidentStatusResult:
Expand Down
6 changes: 4 additions & 2 deletions src/gg_api_core/tools/incident_writes.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,14 @@ def check_advice(kind: IncidentKind) -> str:


def incident_reader(
client: GitGuardianClient, kind: IncidentKind, incident_id: int
client: GitGuardianClient, kind: IncidentKind, incident_id: int, *, retry_on_rate_limit: bool = True
) -> Callable[[], Awaitable[dict[str, Any]]]:
"""A call that reads the incident as it is now."""
if kind == "public":
return lambda: client.get_public_incident(incident_id)
return lambda: client.get_incident(incident_id=incident_id, with_occurrences=0)
return lambda: client.get_incident(
incident_id=incident_id, with_occurrences=0, retry_on_rate_limit=retry_on_rate_limit
)


async def apply_or_confirm(
Expand Down
23 changes: 17 additions & 6 deletions src/gg_mcp_server/register_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
)
from gg_api_core.tools.incident_severity import set_internal_incident_severity, set_public_incident_severity
from gg_api_core.tools.incident_status import (
MAX_BULK_INCIDENTS,
ignore_internal_incident,
ignore_public_incident,
reopen_internal_incident,
Expand Down Expand Up @@ -310,18 +311,28 @@ def register_tools(mcp: AbstractGitGuardianFastMCP) -> None:

mcp.tool(
resolve_internal_incident,
description="(Internal incidents only; for Public Monitoring use resolve_public_incident) Resolve an internal secret incident. "
"secret_revoked must come from the user: ask whether the secret was revoked or rotated. Returns the "
"incident's new status and the incident.",
description="(Internal incidents only; for Public Monitoring use resolve_public_incident) Resolve internal secret incidents. "
f"Provide incident_id or incident_ids (1–{MAX_BULK_INCIDENTS} distinct IDs). "
"secret_revoked applies to every selected incident and must come from the user: ask whether the secrets "
"were revoked or rotated. A single-ID call returns the incident and new status. A batch returns results "
"per ID, including changed=false for already resolved incidents and errors for failures or uncertain writes. "
"Partial failures continue; a 429 stops the batch and marks remaining IDs skipped. "
"A rejected token asks the client to reauthenticate. "
"Each incident uses its own API request; writes are never retried.",
required_scopes=["incidents:write"],
annotations=CHANGES_INCIDENT_STATE,
)

mcp.tool(
ignore_internal_incident,
description="(Internal incidents only; for Public Monitoring use ignore_public_incident) Ignore an internal secret incident. "
"The ignore_reason must come from the user: ask, do not choose. Returns the incident's new status and the "
"incident.",
description="(Internal incidents only; for Public Monitoring use ignore_public_incident) Ignore internal secret incidents. "
f"Provide incident_id or incident_ids (1–{MAX_BULK_INCIDENTS} distinct IDs). "
"The ignore_reason applies to every selected incident and must come from the user: ask, do not choose. "
"A single-ID call returns the incident and new status. A batch returns results per ID, including "
"changed=false for already ignored incidents and errors for failures or uncertain writes. "
"Partial failures continue; a 429 stops the batch and marks remaining IDs skipped. "
"A rejected token asks the client to reauthenticate. "
"Each incident uses its own API request; writes are never retried.",
required_scopes=["incidents:write"],
annotations=CHANGES_INCIDENT_STATE,
)
Expand Down
Loading
Loading