Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(error-tracking): link issues to existing external issues via the API (#79954)

Catalin8b76c0333fdb
diff --git a/products/error_tracking/backend/facade/__init__.py b/products/error_tracking/backend/facade/__init__.py
index 0776128a3261..69c09c656fc2 100644
--- a/products/error_tracking/backend/facade/__init__.py
+++ b/products/error_tracking/backend/facade/__init__.py
@@ -58,6 +58,7 @@ from .api import (
reorder_assignment_rules,
reorder_grouping_rules,
reorder_suppression_rules,
+ search_external_issues,
sync_issues_to_clickhouse,
update_assignment_rule,
update_grouping_rule,
@@ -127,6 +128,7 @@ __all__ = [
"reorder_assignment_rules",
"reorder_grouping_rules",
"reorder_suppression_rules",
+ "search_external_issues",
"sync_issues_to_clickhouse",
"update_assignment_rule",
"update_grouping_rule",
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 21eeb73bec17..b39c2b81f658 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -590,29 +590,50 @@ def create_external_reference(
team_id: int,
issue_id: UUID,
integration_id: int,
- config: dict[str, Any],
+ config: dict[str, Any] | None = None,
+ external_context: dict[str, Any] | None = None,
distinct_id: int | str,
) -> contracts.ErrorTrackingExternalReference:
- reference = logic.create_external_reference(
+ reference, created = logic.create_external_reference(
team_id=team_id,
issue_id=issue_id,
integration_id=integration_id,
config=config,
+ external_context=external_context,
)
- posthoganalytics.capture(
- "error_tracking_external_issue_created",
- distinct_id=distinct_id,
- groups=groups(reference.issue.team.organization, reference.issue.team),
- properties={
- "issue_id": reference.issue_id,
- "integration_kind": reference.integration.kind,
- },
- )
+ # Idempotent re-links return an existing reference; counting those would inflate the metric.
+ if created:
+ posthoganalytics.capture(
+ "error_tracking_external_issue_created",
+ distinct_id=distinct_id,
+ groups=groups(reference.issue.team.organization, reference.issue.team),
+ properties={
+ "issue_id": reference.issue_id,
+ "integration_kind": reference.integration.kind,
+ # Distinguish linking an existing issue from creating a brand-new one.
+ "linked_existing": external_context is not None,
+ },
+ )
return _to_external_reference(reference)
+def search_external_issues(
+ *,
+ team_id: int,
+ integration_id: int,
+ search: str,
+ repository: str | None = None,
+) -> list[dict[str, Any]]:
+ return logic.search_external_issues(
+ team_id=team_id,
+ integration_id=integration_id,
+ search=search,
+ repository=repository,
+ )
+
+
def is_supported_external_issue_provider(kind: str) -> bool:
return logic.is_supported_external_issue_provider(kind=kind)
diff --git a/products/error_tracking/backend/logic/__init__.py b/products/error_tracking/backend/logic/__init__.py
index fc63dacccbf4..d907ce7a0332 100644
--- a/products/error_tracking/backend/logic/__init__.py
+++ b/products/error_tracking/backend/logic/__init__.py
@@ -1,3 +1,4 @@
+import re
from datetime import datetime
from typing import Any, TypeVar, cast
from urllib.parse import quote
@@ -6,9 +7,13 @@ from uuid import UUID
from django.conf import settings
from django.db.models import Count, Q, QuerySet
+import requests
+
from posthog.models.integration import (
GitHubIntegration,
+ GitHubIntegrationError,
GitLabIntegration,
+ GitLabIntegrationError,
Integration,
JiraIntegration,
LinearIntegration,
@@ -100,6 +105,17 @@ EXTERNAL_REFERENCE_NON_BLANK_CONFIG_FIELDS = {
Integration.IntegrationKind.JIRA.value: ("project_key", "title"),
}
+# Keys build_external_issue_url reads per provider, with the identifier type each expects —
+# the minimal external_context we need to persist when linking an issue that already exists
+# rather than creating a new one. References cannot be deleted, so a malformed identifier
+# would persist a permanently broken link.
+LINK_EXISTING_REQUIRED_CONTEXT_FIELDS: dict[str, dict[str, type]] = {
+ Integration.IntegrationKind.GITHUB.value: {"repository": str, "number": int},
+ Integration.IntegrationKind.GITLAB.value: {"issue_id": int},
+ Integration.IntegrationKind.LINEAR.value: {"id": str},
+ Integration.IntegrationKind.JIRA.value: {"key": str},
+}
+
def is_supported_external_issue_provider(kind: str) -> bool:
return kind in SUPPORTED_EXTERNAL_ISSUE_PROVIDERS
@@ -143,6 +159,47 @@ def _validate_external_reference_config(integration: Integration, config: Any) -
)
+def _clean_existing_external_context(integration: Integration, external_context: Any) -> dict[str, Any]:
+ """Validate and normalize the external_context for linking an already-existing issue.
+
+ Keeps only the provider keys build_external_issue_url reads, so we never persist arbitrary
+ client-supplied data on the reference.
+ """
+ if not isinstance(external_context, dict):
+ raise ErrorTrackingExternalReferenceValidationError("External context must be an object.")
+
+ required_fields = LINK_EXISTING_REQUIRED_CONTEXT_FIELDS.get(integration.kind)
+ if required_fields is None:
+ raise ErrorTrackingExternalReferenceValidationError("Provider not supported")
+
+ error = ErrorTrackingExternalReferenceValidationError(
+ f"Missing required external context fields for {integration.kind}: {', '.join(required_fields)}."
+ )
+
+ cleaned: dict[str, Any] = {}
+ for field, expected_type in required_fields.items():
+ value = external_context.get(field)
+ # build_external_issue_url interpolates these into URLs, so enforce the identifier
+ # type each provider expects (digit strings are accepted for numeric identifiers),
+ # and restrict strings to URL-path-safe characters so a crafted value (e.g. a
+ # "repository" of "../../settings") cannot redirect the stored link.
+ if isinstance(value, str):
+ value = value.strip()
+ if expected_type is int:
+ # Explicit ASCII-digit check: str.isdigit() accepts values int() rejects (e.g. "²"),
+ # and the length bound avoids Python's large-int conversion limit.
+ if isinstance(value, str) and re.fullmatch(r"[0-9]{1,10}", value):
+ value = int(value)
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ raise error
+ elif not isinstance(value, str) or not re.fullmatch(r"(?!\.+$)[A-Za-z0-9._-]+", value):
+ # The lookahead rejects all-dot values ("." / ".."), which are URL path
+ # segments with traversal semantics.
+ raise error
+ cleaned[field] = value
+ return cleaned
+
+
def get_issue_list_queryset(team_id: int) -> QuerySet[ErrorTrackingIssue]:
return ErrorTrackingIssue.objects.with_first_seen().select_related("assignment").filter(team_id=team_id)
@@ -256,13 +313,9 @@ def get_external_reference(reference_id: UUID, team_id: int) -> ErrorTrackingExt
return list_external_references(team_id=team_id).filter(id=reference_id).first()
-def create_external_reference(
- *,
- team_id: int,
- issue_id: UUID,
- integration_id: int,
- config: dict[str, Any],
-) -> ErrorTrackingExternalReference:
+def _get_issue_and_integration(
+ team_id: int, issue_id: UUID, integration_id: int
+) -> tuple[ErrorTrackingIssue, Integration]:
issue = ErrorTrackingIssue.objects.filter(id=issue_id, team_id=team_id).first()
if issue is None:
raise ErrorTrackingExternalReferenceValidationError("Issue does not belong to this team.")
@@ -271,26 +324,116 @@ def create_external_reference(
if integration is None:
raise ErrorTrackingExternalReferenceValidationError("Integration does not belong to this team.")
+ return issue, integration
+
+
+def create_external_reference(
+ *,
+ team_id: int,
+ issue_id: UUID,
+ integration_id: int,
+ config: dict[str, Any] | None = None,
+ external_context: dict[str, Any] | None = None,
+) -> tuple[ErrorTrackingExternalReference, bool]:
+ """Link an error tracking issue to an external provider issue.
+
+ Pass ``config`` to create a brand-new provider issue, or ``external_context`` to link an
+ existing one that the user picked. Exactly one of the two must be supplied.
+ Returns the reference and whether it was newly created (idempotent re-links return False).
+ """
+ if (config is None) == (external_context is None):
+ raise ErrorTrackingExternalReferenceValidationError(
+ "Provide either config (to create a new issue) or external_context (to link an existing one)."
+ )
+
+ issue, integration = _get_issue_and_integration(team_id, issue_id, integration_id)
+
+ if external_context is not None:
+ if not is_supported_external_issue_provider(integration.kind):
+ raise ErrorTrackingExternalReferenceValidationError("Provider not supported")
+ stored_context = _clean_existing_external_context(integration, external_context)
+ # Linking is idempotent: retries and double-clicks must not duplicate the
+ # reference (references cannot be deleted) or re-attach in the provider.
+ # Containment (not equality) also matches references the create flow stored
+ # with extra provider keys alongside the identifier.
+ existing = ErrorTrackingExternalReference.objects.filter(
+ issue=issue, integration=integration, external_context__contains=stored_context
+ ).first()
+ if existing is not None:
+ return existing, False
+ if integration.kind == Integration.IntegrationKind.LINEAR:
+ # Linked issues get the same PostHog back-link attachment as created ones.
+ attachment_url = get_issue_permalink_by_fingerprint(team_id=team_id, issue_id=issue.id)
+ LinearIntegration(integration).create_attachment(stored_context["id"], attachment_url)
+ return ErrorTrackingExternalReference.objects.create(
+ issue=issue,
+ integration=integration,
+ external_context=stored_context,
+ ), True
+
_validate_external_reference_config(integration, config)
- provider_config = dict(config)
+ provider_config = dict(config or {})
if integration.kind == Integration.IntegrationKind.GITHUB:
- external_context = GitHubIntegration(integration).create_issue(provider_config)
+ created_context = GitHubIntegration(integration).create_issue(provider_config)
elif integration.kind == Integration.IntegrationKind.GITLAB:
- external_context = GitLabIntegration(integration).create_issue(provider_config)
+ created_context = GitLabIntegration(integration).create_issue(provider_config)
elif integration.kind == Integration.IntegrationKind.LINEAR:
attachment_url = get_issue_permalink_by_fingerprint(team_id=team_id, issue_id=issue.id)
- external_context = LinearIntegration(integration).create_issue(attachment_url, provider_config)
+ created_context = LinearIntegration(integration).create_issue(attachment_url, provider_config)
elif integration.kind == Integration.IntegrationKind.JIRA:
- external_context = JiraIntegration(integration).create_issue(provider_config)
+ created_context = JiraIntegration(integration).create_issue(provider_config)
else:
raise ErrorTrackingExternalReferenceValidationError("Provider not supported")
return ErrorTrackingExternalReference.objects.create(
issue=issue,
integration=integration,
- external_context=external_context,
- )
+ external_context=created_context,
+ ), True
+
+
+def search_external_issues(
+ *,
+ team_id: int,
+ integration_id: int,
+ search: str,
+ repository: str | None = None,
+) -> list[dict[str, Any]]:
+ """Search a provider for existing issues to link, returning normalized picker results.
+
+ Each result is ``{id, title, url, external_context}`` where ``external_context`` is the
+ exact payload to persist when the user selects it.
+ """
+ integration = Integration.objects.filter(id=integration_id, team_id=team_id).first()
+ if integration is None:
+ raise ErrorTrackingExternalReferenceValidationError("Integration does not belong to this team.")
+
+ # Provider failures (expired tokens, rate limits) surface as validation errors so the
+ # endpoint returns an actionable 400 instead of a 500.
+ try:
+ if integration.kind == Integration.IntegrationKind.GITHUB:
+ if not repository:
+ raise ErrorTrackingExternalReferenceValidationError("A repository is required to search GitHub issues.")
+ # Bare names only, matching what create/link store: an owner-qualified path can
+ # search another account's repository, whose issues would link to wrong URLs.
+ if "/" in repository:
+ raise ErrorTrackingExternalReferenceValidationError(
+ "Pass the repository name without an owner; only the integration's account can be searched."
+ )
+ return GitHubIntegration(integration).search_issues(repository, search)
+ elif integration.kind == Integration.IntegrationKind.GITLAB:
+ return GitLabIntegration(integration).search_issues(search)
+ elif integration.kind == Integration.IntegrationKind.LINEAR:
+ return LinearIntegration(integration).search_issues(search)
+ elif integration.kind == Integration.IntegrationKind.JIRA:
+ return JiraIntegration(integration).search_issues(search)
+ except (GitHubIntegrationError, GitLabIntegrationError, requests.RequestException, ValueError) as error:
+ # RequestException and ValueError (JSON decoding) cover provider timeouts,
+ # connection failures, and malformed bodies from any provider.
+ raise ErrorTrackingExternalReferenceValidationError(f"Failed to search {integration.kind} issues.") from error
+
+ raise ErrorTrackingExternalReferenceValidationError("Provider not supported")
def get_issue_assignment(assignment_id: UUID | str) -> ErrorTrackingIssueAssignment:
diff --git a/products/error_tracking/backend/presentation/views/external_references.py b/products/error_tracking/backend/presentation/views/external_references.py
index cd40e483bc4d..22da12cda956 100644
--- a/products/error_tracking/backend/presentation/views/external_references.py
+++ b/products/error_tracking/backend/presentation/views/external_references.py
@@ -1,13 +1,19 @@
import logging
+from typing import cast
from uuid import UUID
-from drf_spectacular.utils import extend_schema_field, extend_schema_serializer
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_serializer
from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, ValidationError
+from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.forbid_destroy_model import ForbidDestroyModel
+from posthog.api.integration import github_rate_limited_response
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.egress.github.transport import GitHubRateLimitError
from products.error_tracking.backend.facade import contracts
from products.error_tracking.backend.facade.api import (
@@ -16,6 +22,7 @@ from products.error_tracking.backend.facade.api import (
get_external_reference,
is_supported_external_issue_provider,
list_external_references,
+ search_external_issues,
)
logger = logging.getLogger(__name__)
@@ -35,12 +42,38 @@ class ExternalReferenceConfigField(serializers.JSONField):
pass
+@extend_schema_field({"type": "object", "additionalProperties": True})
+class ExternalReferenceContextField(serializers.JSONField):
+ pass
+
+
@extend_schema_serializer(component_name="ErrorTrackingExternalReferenceResult")
-class ErrorTrackingExternalReferenceSerializer(serializers.Serializer):
+class ErrorTrackingExternalReferenceResultSerializer(serializers.Serializer):
+ """Read-only shape of an external reference, shared by every response."""
+
id = serializers.UUIDField(read_only=True, help_text="Unique ID of the external reference.")
integration = ErrorTrackingExternalReferenceIntegrationSerializer(
read_only=True, help_text="The connected integration this reference was created through."
)
+ external_url = serializers.SerializerMethodField(
+ help_text="URL of the linked external issue in the provider's system."
+ )
+
+ @extend_schema_field(serializers.CharField())
+ def get_external_url(self, reference: contracts.ErrorTrackingExternalReference) -> str:
+ if reference.external_url:
+ return reference.external_url
+
+ if is_supported_external_issue_provider(reference.integration.kind):
+ raise ValidationError("Missing required external context fields")
+
+ raise ValidationError("Provider not supported")
+
+
+@extend_schema_serializer(component_name="ErrorTrackingExternalReferenceCreate")
+class ErrorTrackingExternalReferenceSerializer(ErrorTrackingExternalReferenceResultSerializer):
+ """Payload for creating a new provider issue and linking it to an error tracking issue."""
+
integration_id = serializers.IntegerField(
write_only=True,
help_text="ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira').",
@@ -57,24 +90,68 @@ class ErrorTrackingExternalReferenceSerializer(serializers.Serializer):
),
)
issue = serializers.UUIDField(write_only=True, help_text="ID of the error tracking issue to link the reference to.")
- external_url = serializers.SerializerMethodField(
- help_text="URL of the linked external issue in the provider's system."
+
+
+@extend_schema_serializer(component_name="ErrorTrackingExternalReferenceLink")
+class ErrorTrackingExternalReferenceLinkSerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(
+ write_only=True,
+ help_text="ID of the connected integration the existing issue lives in (one of 'github', 'gitlab', 'linear', 'jira').",
+ )
+ issue = serializers.UUIDField(write_only=True, help_text="ID of the error tracking issue to link the reference to.")
+ external_context = ExternalReferenceContextField(
+ write_only=True,
+ help_text=(
+ "Identifier of the existing external issue to link, as returned by the search-issues endpoint. "
+ "Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; "
+ "linear -> {id}; jira -> {key}."
+ ),
)
- @extend_schema_field(serializers.CharField())
- def get_external_url(self, reference: contracts.ErrorTrackingExternalReference) -> str:
- if reference.external_url:
- return reference.external_url
- if is_supported_external_issue_provider(reference.integration.kind):
- raise ValidationError("Missing required external context fields")
+class ErrorTrackingExternalIssueSearchQuerySerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(
+ help_text="ID of the connected integration to search issues in.",
+ )
+ search = serializers.CharField(
+ help_text="Text to match against existing issue titles / keys in the provider.",
+ )
+ repository = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Repository to search within. Required for GitHub, ignored by other providers.",
+ )
- raise ValidationError("Provider not supported")
+
+@extend_schema_serializer(component_name="ErrorTrackingExternalIssueResult")
+class ErrorTrackingExternalIssueResultSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Provider-native identifier of the issue (e.g. issue key or number).")
+ title = serializers.CharField(help_text="Human-readable issue title, for display in the picker.")
+ url = serializers.CharField(help_text="Link to the issue in the provider's system.")
+ external_context = ExternalReferenceContextField(
+ help_text="Payload to send back as external_context when creating a reference to this issue.",
+ )
+
+
+@extend_schema_serializer(component_name="ErrorTrackingExternalIssueSearchResult")
+class ErrorTrackingExternalIssueSearchResponseSerializer(serializers.Serializer):
+ issues = ErrorTrackingExternalIssueResultSerializer(many=True, help_text="Matching existing issues.")
class ErrorTrackingExternalReferenceViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.GenericViewSet):
scope_object = "error_tracking"
- serializer_class = ErrorTrackingExternalReferenceSerializer
+ # Custom actions aren't in the default action->scope mapping, so API keys would be
+ # rejected outright without these. search_issues declares its own scopes on the action.
+ scope_object_read_actions = ["list", "retrieve"]
+ scope_object_write_actions = ["create", "link_issue"]
+ serializer_class = ErrorTrackingExternalReferenceResultSerializer
+
+ def handle_exception(self, exc: Exception) -> Response:
+ # Provider searches hit GitHub directly; map its rate limits to the shared
+ # 429 + Retry-After response instead of a 500.
+ if isinstance(exc, GitHubRateLimitError):
+ return github_rate_limited_response(exc)
+ return super().handle_exception(exc)
def list(self, request, *args, **kwargs):
references = list_external_references(team_id=self.team.id)
@@ -100,8 +177,12 @@ class ErrorTrackingExternalReferenceViewSet(TeamAndOrgViewSetMixin, ForbidDestro
serializer = self.get_serializer(reference)
return Response(serializer.data)
+ @extend_schema(
+ request=ErrorTrackingExternalReferenceSerializer,
+ responses={201: ErrorTrackingExternalReferenceResultSerializer},
+ )
def create(self, request, *args, **kwargs):
- serializer = self.get_serializer(data=request.data)
+ serializer = ErrorTrackingExternalReferenceSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
issue_id = serializer.validated_data["issue"]
@@ -122,3 +203,60 @@ class ErrorTrackingExternalReferenceViewSet(TeamAndOrgViewSetMixin, ForbidDestro
response_serializer = self.get_serializer(reference)
return Response(response_serializer.data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ request=ErrorTrackingExternalReferenceLinkSerializer,
+ responses={201: ErrorTrackingExternalReferenceResultSerializer},
+ )
+ @action(methods=["POST"], detail=False, url_path="link_issue")
+ def link_issue(self, request: Request, *args, **kwargs) -> Response:
+ """Link an error to an issue that already exists in the connected provider."""
+ serializer = ErrorTrackingExternalReferenceLinkSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ issue_id = serializer.validated_data["issue"]
+ if not isinstance(issue_id, UUID):
+ issue_id = UUID(str(issue_id))
+
+ try:
+ reference = create_external_reference(
+ team_id=self.team.id,
+ issue_id=issue_id,
+ integration_id=serializer.validated_data["integration_id"],
+ external_context=serializer.validated_data["external_context"],
+ distinct_id=cast(int, request.user.pk),
+ )
+ except ExternalReferenceValidationError as error:
+ logger.warning("Failed to link external reference", exc_info=error)
+ raise ValidationError(str(error)) from error
+
+ response_serializer = self.get_serializer(reference)
+ return Response(response_serializer.data, status=status.HTTP_201_CREATED)
+
+ @validated_request(
+ query_serializer=ErrorTrackingExternalIssueSearchQuerySerializer,
+ responses={200: OpenApiResponse(response=ErrorTrackingExternalIssueSearchResponseSerializer)},
+ )
+ @action(
+ methods=["GET"],
+ detail=False,
+ url_path="search_issues",
+ pagination_class=None,
+ # Searching exposes provider data well beyond error tracking, so a token also
+ # needs read access to integrations.
+ required_scopes=["error_tracking:read", "integration:read"],
+ )
+ def search_issues(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ """Search a connected provider for existing issues to link an error to."""
+ try:
+ issues = search_external_issues(
+ team_id=self.team.id,
+ integration_id=request.validated_query_data["integration_id"],
+ search=request.validated_query_data["search"],
+ repository=request.validated_query_data.get("repository") or None,
+ )
+ except ExternalReferenceValidationError as error:
+ raise ValidationError(str(error)) from error
+
+ response_serializer = ErrorTrackingExternalIssueSearchResponseSerializer({"issues": issues})
+ return Response(response_serializer.data)
diff --git a/products/error_tracking/backend/presentation/views/issues.py b/products/error_tracking/backend/presentation/views/issues.py
index c5acea45b917..caafac2eddd5 100644
--- a/products/error_tracking/backend/presentation/views/issues.py
+++ b/products/error_tracking/backend/presentation/views/issues.py
@@ -25,7 +25,7 @@ from products.error_tracking.backend.facade import (
)
from products.error_tracking.backend.presentation.pagination import paginate_via_facade
from products.error_tracking.backend.presentation.views.external_references import (
- ErrorTrackingExternalReferenceSerializer,
+ ErrorTrackingExternalReferenceResultSerializer,
)
IssueNotFoundError = facade_api.IssueNotFoundError
@@ -76,7 +76,7 @@ class ErrorTrackingIssueReadSerializer(serializers.Serializer):
description = serializers.CharField(allow_null=True)
first_seen = serializers.DateTimeField(allow_null=True)
assignee = ErrorTrackingIssueAssigneeReadSerializer(allow_null=True)
- external_issues = ErrorTrackingExternalReferenceSerializer(many=True)
+ external_issues = ErrorTrackingExternalReferenceResultSerializer(many=True)
cohort = ErrorTrackingIssueCohortReadSerializer(allow_null=True)
diff --git a/products/error_tracking/backend/test/test_facade_api.py b/products/error_tracking/backend/test/test_facade_api.py
index e8643cc9f592..33bb511477d8 100644
--- a/products/error_tracking/backend/test/test_facade_api.py
+++ b/products/error_tracking/backend/test/test_facade_api.py
@@ -6,13 +6,16 @@ from unittest.mock import patch
from django.test import override_settings
from django.utils.timezone import now
+import requests
from parameterized import parameterized
+from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.models import Team
-from posthog.models.integration import Integration
+from posthog.models.integration import GitLabIntegrationError, Integration
from products.error_tracking.backend.facade import api, contracts
from products.error_tracking.backend.models import (
+ ErrorTrackingExternalReference,
ErrorTrackingIssue,
ErrorTrackingIssueAssignment,
ErrorTrackingIssueFingerprintV2,
@@ -144,6 +147,217 @@ class TestErrorTrackingFacadeAPI(BaseTest):
attachment_url = mock_create_issue.call_args.args[0]
assert attachment_url.endswith(f"/project/{self.team.id}/error_tracking/{issue.id}")
+ @override_settings(ATLASSIAN_APP_CLIENT_ID="atlassian-client-id", ATLASSIAN_APP_CLIENT_SECRET="atlassian-secret")
+ @patch("products.error_tracking.backend.logic.JiraIntegration.create_issue")
+ def test_create_external_reference_links_existing_issue_without_creating(self, mock_create_issue):
+ issue = self._create_issue(team=self.team, name="Checkout TypeError")
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.JIRA.value,
+ config={"site_url": "https://acme.atlassian.net", "site_name": "acme"},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ reference = api.create_external_reference(
+ team_id=self.team.id,
+ issue_id=issue.id,
+ integration_id=integration.id,
+ external_context={"key": "ENG-42", "id": "10042"},
+ distinct_id=self.user.id,
+ )
+
+ mock_create_issue.assert_not_called()
+ assert reference.external_url == "https://acme.atlassian.net/browse/ENG-42"
+
+ @override_settings(LINEAR_APP_CLIENT_ID="linear-client-id", LINEAR_APP_CLIENT_SECRET="linear-client-secret")
+ @patch("products.error_tracking.backend.facade.api.posthoganalytics.capture")
+ @patch("products.error_tracking.backend.logic.LinearIntegration.create_attachment")
+ @patch("products.error_tracking.backend.logic.LinearIntegration.create_issue")
+ def test_link_existing_linear_issue_creates_attachment(
+ self, mock_create_issue, mock_create_attachment, mock_capture
+ ):
+ issue = self._create_issue(team=self.team, name="Checkout TypeError")
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.LINEAR.value,
+ config={"data": {"viewer": {"organization": {"urlKey": "acme", "name": "Acme"}}}},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ reference = api.create_external_reference(
+ team_id=self.team.id,
+ issue_id=issue.id,
+ integration_id=integration.id,
+ external_context={"id": "ENG-42"},
+ distinct_id=self.user.id,
+ )
+
+ mock_create_issue.assert_not_called()
+ linked_issue_id, attachment_url = mock_create_attachment.call_args.args
+ assert linked_issue_id == "ENG-42"
+ assert f"/project/{self.team.id}/error_tracking/" in attachment_url
+ assert reference.external_url == "https://linear.app/acme/issue/ENG-42"
+
+ # Linking the same issue again returns the existing reference without re-attaching.
+ duplicate = api.create_external_reference(
+ team_id=self.team.id,
+ issue_id=issue.id,
+ integration_id=integration.id,
+ external_context={"id": "ENG-42"},
+ distinct_id=self.user.id,
+ )
+ assert duplicate.id == reference.id
+ assert mock_create_attachment.call_count == 1
+ created_events = [
+ call
+ for call in mock_capture.call_args_list
+ if call.args and call.args[0] == "error_tracking_external_issue_created"
+ ]
+ assert len(created_events) == 1
+
+ @override_settings(LINEAR_APP_CLIENT_ID="linear-client-id", LINEAR_APP_CLIENT_SECRET="linear-client-secret")
+ @patch("products.error_tracking.backend.logic.LinearIntegration.create_attachment")
+ def test_link_existing_linear_issue_aborts_when_attachment_fails(self, mock_create_attachment):
+ # A failed attachment (invalid issue id, forbidden, rate limit) must not persist a
+ # reference that promises a back-link Linear never created.
+ mock_create_attachment.side_effect = DRFValidationError("Failed to attach")
+ issue = self._create_issue(team=self.team, name="Checkout TypeError")
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.LINEAR.value,
+ config={"data": {"viewer": {"organization": {"urlKey": "acme", "name": "Acme"}}}},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ with self.assertRaises(DRFValidationError):
+ api.create_external_reference(
+ team_id=self.team.id,
+ issue_id=issue.id,
+ integration_id=integration.id,
+ external_context={"id": "ENG-42"},
+ distinct_id=self.user.id,
+ )
+
+ assert not ErrorTrackingExternalReference.objects.exists()
+
+ @parameterized.expand(
+ [
+ ("both", {"title": "x"}, {"key": "ENG-1"}),
+ ("neither", None, None),
+ ]
+ )
+ def test_create_external_reference_requires_exactly_one_source(self, _name, config, external_context):
+ issue = self._create_issue(team=self.team, name="Checkout TypeError")
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.JIRA.value,
+ config={"site_url": "https://acme.atlassian.net"},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ with self.assertRaises(api.ExternalReferenceValidationError):
+ api.create_external_reference(
+ team_id=self.team.id,
+ issue_id=issue.id,
+ integration_id=integration.id,
+ config=config,
+ external_context=external_context,
+ distinct_id=self.user.id,
+ )
+
+ @parameterized.expand(
+ [
+ ("missing_number", {"repository": "posthog"}),
+ ("boolean_number", {"repository": "posthog", "number": False}),
+ ("zero_number", {"repository": "posthog", "number": 0}),
+ ("list_number", {"repository": "posthog", "number": [42]}),
+ ("non_numeric_number", {"repository": "posthog", "number": "not-an-issue"}),
+ ("unicode_digit_number", {"repository": "posthog", "number": "²"}),
+ ("integer_repository", {"repository": 42, "number": 42}),
+ ("blank_repository", {"repository": " ", "number": 42}),
+ ("path_traversal_repository", {"repository": "../../settings", "number": 42}),
+ ("dot_segment_repository", {"repository": "..", "number": 42}),
+ ]
+ )
+ def test_link_existing_issue_rejects_invalid_external_context(self, _name, external_context):
+ issue = self._create_issue(team=self.team, name="Checkout TypeError")
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.GITHUB.value,
+ config={"account": {"name": "acme"}},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ # Identifiers must be non-blank strings or ints; anything else would persist a broken URL.
+ with self.assertRaises(api.ExternalReferenceValidationError):
+ api.create_external_reference(
+ team_id=self.team.id,
+ issue_id=issue.id,
+ integration_id=integration.id,
+ external_context=external_context,
+ distinct_id=self.user.id,
+ )
+
+ def test_search_external_issues_requires_repository_for_github(self):
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.GITHUB.value,
+ config={"account": {"name": "acme"}},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ with self.assertRaises(api.ExternalReferenceValidationError):
+ api.search_external_issues(team_id=self.team.id, integration_id=integration.id, search="boom")
+
+ def test_search_external_issues_rejects_owner_qualified_github_repository(self):
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.GITHUB.value,
+ config={"account": {"name": "acme"}},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ with self.assertRaises(api.ExternalReferenceValidationError):
+ api.search_external_issues(
+ team_id=self.team.id, integration_id=integration.id, search="boom", repository="other-org/repo"
+ )
+
+ @parameterized.expand(
+ [
+ ("application_error", GitLabIntegrationError("rate limited")),
+ ("transport_error", requests.Timeout("timed out")),
+ ("malformed_body", ValueError("invalid json")),
+ ]
+ )
+ @patch("products.error_tracking.backend.logic.GitLabIntegration.search_issues")
+ def test_search_external_issues_maps_provider_failures_to_validation_errors(
+ self, _name, side_effect, mock_search_issues
+ ):
+ mock_search_issues.side_effect = side_effect
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.GITLAB.value,
+ config={"hostname": "https://gitlab.example.com", "project_id": 1},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ with self.assertRaises(api.ExternalReferenceValidationError):
+ api.search_external_issues(team_id=self.team.id, integration_id=integration.id, search="boom")
+
+ @patch("products.error_tracking.backend.logic.LinearIntegration.search_issues")
+ def test_search_external_issues_dispatches_to_provider(self, mock_search_issues):
+ results = [{"id": "ENG-1", "title": "Boom", "url": "https://linear.app/x", "external_context": {"id": "ENG-1"}}]
+ mock_search_issues.return_value = results
+ integration = Integration.objects.create(
+ team=self.team,
+ kind=Integration.IntegrationKind.LINEAR.value,
+ config={"data": {"viewer": {"organization": {"urlKey": "acme"}}}},
+ sensitive_config={"access_token": "access-token"},
+ )
+
+ assert api.search_external_issues(team_id=self.team.id, integration_id=integration.id, search="boom") == results
+ mock_search_issues.assert_called_once_with("boom")
+
def test_issue_exists(self):
assert api.issue_exists(team_id=self.team.id) is False
diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.ts
index 2f9920321c79..04243e5d7f92 100644
--- a/products/error_tracking/frontend/generated/api.schemas.ts
+++ b/products/error_tracking/frontend/generated/api.schemas.ts
@@ -469,21 +469,13 @@ export interface ErrorTrackingExternalReferenceIntegrationResultApi {
}
/**
- * Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}.
+ * Read-only shape of an external reference, shared by every response.
*/
-export type ErrorTrackingExternalReferenceResultApiConfig = { [key: string]: string }
-
export interface ErrorTrackingExternalReferenceResultApi {
/** Unique ID of the external reference. */
readonly id: string
/** The connected integration this reference was created through. */
readonly integration: ErrorTrackingExternalReferenceIntegrationResultApi
- /** ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira'). */
- integration_id: number
- /** Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}. */
- config: ErrorTrackingExternalReferenceResultApiConfig
- /** ID of the error tracking issue to link the reference to. */
- issue: string
/** URL of the linked external issue in the provider's system. */
readonly external_url: string
}
@@ -497,6 +489,64 @@ export interface PaginatedErrorTrackingExternalReferenceResultListApi {
results: ErrorTrackingExternalReferenceResultApi[]
}
+/**
+ * Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}.
+ */
+export type ErrorTrackingExternalReferenceCreateApiConfig = { [key: string]: string }
+
+/**
+ * Payload for creating a new provider issue and linking it to an error tracking issue.
+ */
+export interface ErrorTrackingExternalReferenceCreateApi {
+ /** Unique ID of the external reference. */
+ readonly id: string
+ /** The connected integration this reference was created through. */
+ readonly integration: ErrorTrackingExternalReferenceIntegrationResultApi
+ /** URL of the linked external issue in the provider's system. */
+ readonly external_url: string
+ /** ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira'). */
+ integration_id: number
+ /** Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}. */
+ config: ErrorTrackingExternalReferenceCreateApiConfig
+ /** ID of the error tracking issue to link the reference to. */
+ issue: string
+}
+
+/**
+ * Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.
+ */
+export type ErrorTrackingExternalReferenceLinkApiExternalContext = { [key: string]: unknown }
+
+export interface ErrorTrackingExternalReferenceLinkApi {
+ /** ID of the connected integration the existing issue lives in (one of 'github', 'gitlab', 'linear', 'jira'). */
+ integration_id: number
+ /** ID of the error tracking issue to link the reference to. */
+ issue: string
+ /** Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}. */
+ external_context: ErrorTrackingExternalReferenceLinkApiExternalContext
+}
+
+/**
+ * Payload to send back as external_context when creating a reference to this issue.
+ */
+export type ErrorTrackingExternalIssueResultApiExternalContext = { [key: string]: unknown }
+
+export interface ErrorTrackingExternalIssueResultApi {
+ /** Provider-native identifier of the issue (e.g. issue key or number). */
+ id: string
+ /** Human-readable issue title, for display in the picker. */
+ title: string
+ /** Link to the issue in the provider's system. */
+ url: string
+ /** Payload to send back as external_context when creating a reference to this issue. */
+ external_context: ErrorTrackingExternalIssueResultApiExternalContext
+}
+
+export interface ErrorTrackingExternalIssueSearchResultApi {
+ /** Matching existing issues. */
+ issues: ErrorTrackingExternalIssueResultApi[]
+}
+
export interface ErrorTrackingFingerprintApi {
/** Unique ID of the fingerprint record. */
readonly id: string
@@ -1822,6 +1872,22 @@ export type ErrorTrackingExternalReferencesListParams = {
offset?: number
}
+export type ErrorTrackingExternalReferencesSearchIssuesRetrieveParams = {
+ /**
+ * ID of the connected integration to search issues in.
+ */
+ integration_id: number
+ /**
+ * Repository to search within. Required for GitHub, ignored by other providers.
+ */
+ repository?: string
+ /**
+ * Text to match against existing issue titles / keys in the provider.
+ * @minLength 1
+ */
+ search: string
+}
+
export type ErrorTrackingFingerprintsListParams = {
/**
* Number of results to return per page.
diff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.ts
index 927285553696..f6a5624c599e 100644
--- a/products/error_tracking/frontend/generated/api.ts
+++ b/products/error_tracking/frontend/generated/api.ts
@@ -17,8 +17,12 @@ import type {
ErrorTrackingBypassRuleCreateRequestApi,
ErrorTrackingBypassRuleUpdateRequestApi,
ErrorTrackingBypassRulesListParams,
+ ErrorTrackingExternalIssueSearchResultApi,
+ ErrorTrackingExternalReferenceCreateApi,
+ ErrorTrackingExternalReferenceLinkApi,
ErrorTrackingExternalReferenceResultApi,
ErrorTrackingExternalReferencesListParams,
+ ErrorTrackingExternalReferencesSearchIssuesRetrieveParams,
ErrorTrackingFingerprintApi,
ErrorTrackingFingerprintsListParams,
ErrorTrackingFingerprintsResolveRetrieveParams,
@@ -408,14 +412,14 @@ export const getErrorTrackingExternalReferencesCreateUrl = (projectId: string) =
export const errorTrackingExternalReferencesCreate = async (
projectId: string,
- errorTrackingExternalReferenceResultApi: NonReadonly<ErrorTrackingExternalReferenceResultApi>,
+ errorTrackingExternalReferenceCreateApi: NonReadonly<ErrorTrackingExternalReferenceCreateApi>,
options?: RequestInit
): Promise<ErrorTrackingExternalReferenceResultApi> => {
return apiMutator<ErrorTrackingExternalReferenceResultApi>(getErrorTrackingExternalReferencesCreateUrl(projectId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(errorTrackingExternalReferenceResultApi),
+ body: JSON.stringify(errorTrackingExternalReferenceCreateApi),
})
}
@@ -455,6 +459,65 @@ export const errorTrackingExternalReferencesDestroy = async (
})
}
+export const getErrorTrackingExternalReferencesLinkIssueCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/error_tracking/external_references/link_issue/`
+}
+
+/**
+ * Link an error to an issue that already exists in the connected provider.
+ */
+export const errorTrackingExternalReferencesLinkIssueCreate = async (
+ projectId: string,
+ errorTrackingExternalReferenceLinkApi: ErrorTrackingExternalReferenceLinkApi,
+ options?: RequestInit
+): Promise<ErrorTrackingExternalReferenceResultApi> => {
+ return apiMutator<ErrorTrackingExternalReferenceResultApi>(
+ getErrorTrackingExternalReferencesLinkIssueCreateUrl(projectId),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(errorTrackingExternalReferenceLinkApi),
+ }
+ )
+}
+
+export const getErrorTrackingExternalReferencesSearchIssuesRetrieveUrl = (
+ projectId: string,
+ params: ErrorTrackingExternalReferencesSearchIssuesRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/error_tracking/external_references/search_issues/?${stringifiedParams}`
+ : `/api/projects/${projectId}/error_tracking/external_references/search_issues/`
+}
+
+/**
+ * Search a connected provider for existing issues to link an error to.
+ */
+export const errorTrackingExternalReferencesSearchIssuesRetrieve = async (
+ projectId: string,
+ params: ErrorTrackingExternalReferencesSearchIssuesRetrieveParams,
+ options?: RequestInit
+): Promise<ErrorTrackingExternalIssueSearchResultApi> => {
+ return apiMutator<ErrorTrackingExternalIssueSearchResultApi>(
+ getErrorTrackingExternalReferencesSearchIssuesRetrieveUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getErrorTrackingFingerprintsListUrl = (
projectId: string,
params?: ErrorTrackingFingerprintsListParams
diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.ts
index 36f7202f41e3..d30e8dddcc73 100644
--- a/products/error_tracking/frontend/generated/api.zod.ts
+++ b/products/error_tracking/frontend/generated/api.zod.ts
@@ -147,18 +147,37 @@ export const ErrorTrackingBypassRulesReorderPartialUpdateBody = /* @__PURE__ */
),
})
-export const ErrorTrackingExternalReferencesCreateBody = /* @__PURE__ */ zod.object({
+export const ErrorTrackingExternalReferencesCreateBody = /* @__PURE__ */ zod
+ .object({
+ integration_id: zod
+ .number()
+ .describe(
+ "ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira')."
+ ),
+ config: zod
+ .record(zod.string(), zod.string())
+ .describe(
+ 'Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {\"repository\":\"posthog\",\"title\":\"Checkout TypeError\",\"body\":\"Stack trace\"}; linear {\"team_id\":\"team-id\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}; jira {\"project_key\":\"ENG\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}.'
+ ),
+ issue: zod.uuid().describe('ID of the error tracking issue to link the reference to.'),
+ })
+ .describe('Payload for creating a new provider issue and linking it to an error tracking issue.')
+
+/**
+ * Link an error to an issue that already exists in the connected provider.
+ */
+export const ErrorTrackingExternalReferencesLinkIssueCreateBody = /* @__PURE__ */ zod.object({
integration_id: zod
.number()
.describe(
- "ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira')."
+ "ID of the connected integration the existing issue lives in (one of 'github', 'gitlab', 'linear', 'jira')."
),
- config: zod
- .record(zod.string(), zod.string())
+ issue: zod.uuid().describe('ID of the error tracking issue to link the reference to.'),
+ external_context: zod
+ .record(zod.string(), zod.unknown())
.describe(
- 'Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {\"repository\":\"posthog\",\"title\":\"Checkout TypeError\",\"body\":\"Stack trace\"}; linear {\"team_id\":\"team-id\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}; jira {\"project_key\":\"ENG\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}.'
+ 'Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.'
),
- issue: zod.uuid().describe('ID of the error tracking issue to link the reference to.'),
})
export const ErrorTrackingGroupingRulesCreateBody = /* @__PURE__ */ zod.object({
@@ -278,30 +297,25 @@ export const ErrorTrackingIssuesAssignPartialUpdateBody = /* @__PURE__ */ zod
.optional(),
external_issues: zod
.array(
- zod.object({
- id: zod.uuid().describe('Unique ID of the external reference.'),
- integration: zod
- .object({
- id: zod.number().describe('ID of the integration backing this external reference.'),
- kind: zod
- .string()
- .describe("Integration provider, e.g. 'github', 'gitlab', 'linear', or 'jira'."),
- display_name: zod.string().describe('Human-readable name of the connected integration.'),
- })
- .describe('The connected integration this reference was created through.'),
- integration_id: zod
- .number()
- .describe(
- "ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira')."
- ),
- config: zod
- .record(zod.string(), zod.string())
- .describe(
- 'Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {\"repository\":\"posthog\",\"title\":\"Checkout TypeError\",\"body\":\"Stack trace\"}; linear {\"team_id\":\"team-id\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}; jira {\"project_key\":\"ENG\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}.'
- ),
- issue: zod.uuid().describe('ID of the error tracking issue to link the reference to.'),
- external_url: zod.string().describe("URL of the linked external issue in the provider's system."),
- })
+ zod
+ .object({
+ id: zod.uuid().describe('Unique ID of the external reference.'),
+ integration: zod
+ .object({
+ id: zod.number().describe('ID of the integration backing this external reference.'),
+ kind: zod
+ .string()
+ .describe("Integration provider, e.g. 'github', 'gitlab', 'linear', or 'jira'."),
+ display_name: zod
+ .string()
+ .describe('Human-readable name of the connected integration.'),
+ })
+ .describe('The connected integration this reference was created through.'),
+ external_url: zod
+ .string()
+ .describe("URL of the linked external issue in the provider's system."),
+ })
+ .describe('Read-only shape of an external reference, shared by every response.')
)
.optional(),
cohort: zod
@@ -334,30 +348,21 @@ export const ErrorTrackingIssuesCohortUpdateBody = /* @__PURE__ */ zod
zod.null(),
]),
external_issues: zod.array(
- zod.object({
- id: zod.uuid().describe('Unique ID of the external reference.'),
- integration: zod
- .object({
- id: zod.number().describe('ID of the integration backing this external reference.'),
- kind: zod
- .string()
- .describe("Integration provider, e.g. 'github', 'gitlab', 'linear', or 'jira'."),
- display_name: zod.string().describe('Human-readable name of the connected integration.'),
- })
- .describe('The connected integration this reference was created through.'),
- integration_id: zod
- .number()
- .describe(
- "ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira')."
- ),
- config: zod
- .record(zod.string(), zod.string())
- .describe(
- 'Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {\"repository\":\"posthog\",\"title\":\"Checkout TypeError\",\"body\":\"Stack trace\"}; linear {\"team_id\":\"team-id\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}; jira {\"project_key\":\"ENG\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}.'
- ),
- issue: zod.uuid().describe('ID of the error tracking issue to link the reference to.'),
- external_url: zod.string().describe("URL of the linked external issue in the provider's system."),
- })
+ zod
+ .object({
+ id: zod.uuid().describe('Unique ID of the external reference.'),
+ integration: zod
+ .object({
+ id: zod.number().describe('ID of the integration backing this external reference.'),
+ kind: zod
+ .string()
+ .describe("Integration provider, e.g. 'github', 'gitlab', 'linear', or 'jira'."),
+ display_name: zod.string().describe('Human-readable name of the connected integration.'),
+ })
+ .describe('The connected integration this reference was created through.'),
+ external_url: zod.string().describe("URL of the linked external issue in the provider's system."),
+ })
+ .describe('Read-only shape of an external reference, shared by every response.')
),
cohort: zod.union([
zod.object({
@@ -410,30 +415,21 @@ export const ErrorTrackingIssuesBulkCreateBody = /* @__PURE__ */ zod
zod.null(),
]),
external_issues: zod.array(
- zod.object({
- id: zod.uuid().describe('Unique ID of the external reference.'),
- integration: zod
- .object({
- id: zod.number().describe('ID of the integration backing this external reference.'),
- kind: zod
- .string()
- .describe("Integration provider, e.g. 'github', 'gitlab', 'linear', or 'jira'."),
- display_name: zod.string().describe('Human-readable name of the connected integration.'),
- })
- .describe('The connected integration this reference was created through.'),
- integration_id: zod
- .number()
- .describe(
- "ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira')."
- ),
- config: zod
- .record(zod.string(), zod.string())
- .describe(
- 'Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {\"repository\":\"posthog\",\"title\":\"Checkout TypeError\",\"body\":\"Stack trace\"}; linear {\"team_id\":\"team-id\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}; jira {\"project_key\":\"ENG\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}.'
- ),
- issue: zod.uuid().describe('ID of the error tracking issue to link the reference to.'),
- external_url: zod.string().describe("URL of the linked external issue in the provider's system."),
- })
+ zod
+ .object({
+ id: zod.uuid().describe('Unique ID of the external reference.'),
+ integration: zod
+ .object({
+ id: zod.number().describe('ID of the integration backing this external reference.'),
+ kind: zod
+ .string()
+ .describe("Integration provider, e.g. 'github', 'gitlab', 'linear', or 'jira'."),
+ display_name: zod.string().describe('Human-readable name of the connected integration.'),
+ })
+ .describe('The connected integration this reference was created through.'),
+ external_url: zod.string().describe("URL of the linked external issue in the provider's system."),
+ })
+ .describe('Read-only shape of an external reference, shared by every response.')
),
cohort: zod.union([
zod.object({
diff --git a/products/error_tracking/mcp/tools.yaml b/products/error_tracking/mcp/tools.yaml
index 202b95cdc1ad..9b0546ea23f1 100644
--- a/products/error_tracking/mcp/tools.yaml
+++ b/products/error_tracking/mcp/tools.yaml
@@ -146,12 +146,18 @@ tools:
error-tracking-external-references-destroy:
operation: error_tracking_external_references_destroy
enabled: false
+ error-tracking-external-references-link-issue-create:
+ operation: error_tracking_external_references_link_issue_create
+ enabled: false
error-tracking-external-references-list:
operation: error_tracking_external_references_list
enabled: false
error-tracking-external-references-retrieve:
operation: error_tracking_external_references_retrieve
enabled: false
+ error-tracking-external-references-search-issues-retrieve:
+ operation: error_tracking_external_references_search_issues_retrieve
+ enabled: false
error-tracking-fingerprints-destroy:
operation: error_tracking_fingerprints_destroy
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 04bd7f8ec436..b6bccfb263c7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29704,6 +29704,32 @@ export namespace Schemas {
properties?: ErrorTrackingEventProperties;
}
+ /**
+ * Payload to send back as external_context when creating a reference to this issue.
+ */
+ export type ErrorTrackingExternalIssueResultExternalContext = { [key: string]: unknown };
+
+ export interface ErrorTrackingExternalIssueResult {
+ /** Provider-native identifier of the issue (e.g. issue key or number). */
+ id: string;
+ /** Human-readable issue title, for display in the picker. */
+ title: string;
+ /** Link to the issue in the provider's system. */
+ url: string;
+ /** Payload to send back as external_context when creating a reference to this issue. */
+ external_context: ErrorTrackingExternalIssueResultExternalContext;
+ }
+
+ export interface ErrorTrackingExternalIssueSearchResult {
+ /** Matching existing issues. */
+ issues: ErrorTrackingExternalIssueResult[];
+ }
+
+ /**
+ * Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}.
+ */
+ export type ErrorTrackingExternalReferenceCreateConfig = {[key: string]: string};
+
export interface ErrorTrackingExternalReferenceIntegrationResult {
/** ID of the integration backing this external reference. */
readonly id: number;
@@ -29714,21 +29740,45 @@ export namespace Schemas {
}
/**
- * Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}.
+ * Payload for creating a new provider issue and linking it to an error tracking issue.
*/
- export type ErrorTrackingExternalReferenceResultConfig = {[key: string]: string};
-
- export interface ErrorTrackingExternalReferenceResult {
+ export interface ErrorTrackingExternalReferenceCreate {
/** Unique ID of the external reference. */
readonly id: string;
/** The connected integration this reference was created through. */
readonly integration: ErrorTrackingExternalReferenceIntegrationResult;
+ /** URL of the linked external issue in the provider's system. */
+ readonly external_url: string;
/** ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira'). */
integration_id: number;
/** Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {"repository":"posthog","title":"Checkout TypeError","body":"Stack trace"}; linear {"team_id":"team-id","title":"Checkout TypeError","description":"Stack trace"}; jira {"project_key":"ENG","title":"Checkout TypeError","description":"Stack trace"}. */
- config: ErrorTrackingExternalReferenceResultConfig;
+ config: ErrorTrackingExternalReferenceCreateConfig;
+ /** ID of the error tracking issue to link the reference to. */
+ issue: string;
+ }
+
+ /**
+ * Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}.
+ */
+ export type ErrorTrackingExternalReferenceLinkExternalContext = { [key: string]: unknown };
+
+ export interface ErrorTrackingExternalReferenceLink {
+ /** ID of the connected integration the existing issue lives in (one of 'github', 'gitlab', 'linear', 'jira'). */
+ integration_id: number;
/** ID of the error tracking issue to link the reference to. */
issue: string;
+ /** Identifier of the existing external issue to link, as returned by the search-issues endpoint. Required keys depend on the integration kind: github -> {repository, number}; gitlab -> {issue_id}; linear -> {id}; jira -> {key}. */
+ external_context: ErrorTrackingExternalReferenceLinkExternalContext;
+ }
+
+ /**
+ * Read-only shape of an external reference, shared by every response.
+ */
+ export interface ErrorTrackingExternalReferenceResult {
+ /** Unique ID of the external reference. */
+ readonly id: string;
+ /** The connected integration this reference was created through. */
+ readonly integration: ErrorTrackingExternalReferenceIntegrationResult;
/** URL of the linked external issue in the provider's system. */
readonly external_url: string;
}
@@ -87199,6 +87249,22 @@ export namespace Schemas {
offset?: number;
};
+ export type ErrorTrackingExternalReferencesSearchIssuesRetrieveParams = {
+ /**
+ * ID of the connected integration to search issues in.
+ */
+ integration_id: number;
+ /**
+ * Repository to search within. Required for GitHub, ignored by other providers.
+ */
+ repository?: string;
+ /**
+ * Text to match against existing issue titles / keys in the provider.
+ * @minLength 1
+ */
+ search: string;
+ };
+
export type ErrorTrackingFingerprintsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.ts
index 075ee6631e66..642d2ff003cd 100644
--- a/services/mcp/src/generated/error_tracking/api.ts
+++ b/services/mcp/src/generated/error_tracking/api.ts
@@ -3707,19 +3707,21 @@ export const ErrorTrackingExternalReferencesCreateParams = /* @__PURE__ */ zod.o
),
})
-export const ErrorTrackingExternalReferencesCreateBody = /* @__PURE__ */ zod.object({
- integration_id: zod
- .number()
- .describe(
- "ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira')."
- ),
- config: zod
- .record(zod.string(), zod.string())
- .describe(
- 'Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {\"repository\":\"posthog\",\"title\":\"Checkout TypeError\",\"body\":\"Stack trace\"}; linear {\"team_id\":\"team-id\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}; jira {\"project_key\":\"ENG\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}.'
- ),
- issue: zod.string().describe('ID of the error tracking issue to link the reference to.'),
-})
+export const ErrorTrackingExternalReferencesCreateBody = /* @__PURE__ */ zod
+ .object({
+ integration_id: zod
+ .number()
+ .describe(
+ "ID of the connected integration to create the external issue with. List the project's integrations to find the right ID and its kind (one of 'github', 'gitlab', 'linear', 'jira')."
+ ),
+ config: zod
+ .record(zod.string(), zod.string())
+ .describe(
+ 'Provider-specific fields describing the external issue to create. Required keys depend on the integration kind: github -> {repository, title, body}; gitlab -> {title, body}; linear -> {team_id, title, description}; jira -> {project_key, title, description}. Examples: github {\"repository\":\"posthog\",\"title\":\"Checkout TypeError\",\"body\":\"Stack trace\"}; linear {\"team_id\":\"team-id\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}; jira {\"project_key\":\"ENG\",\"title\":\"Checkout TypeError\",\"description\":\"Stack trace\"}.'
+ ),
+ issue: zod.string().describe('ID of the error tracking issue to link the reference to.'),
+ })
+ .describe('Payload for creating a new provider issue and linking it to an error tracking issue.')
export const ErrorTrackingGroupingRulesListParams = /* @__PURE__ */ zod.object({
project_id: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-external-references-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-external-references-create.json
index de5d7cfea432..540d486e89f1 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-external-references-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-external-references-create.json
@@ -1,5 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
+ "description": "Payload for creating a new provider issue and linking it to an error tracking issue.",
"properties": {
"config": {
"additionalProperties": {