> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devinenterprise.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Triage automatico degli errori Sentry

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="Triage automatico degli errori Sentry" description="Collega i webhook di Sentry all'API di Devin per eseguire il triage automatico di ogni nuovo errore in produzione." prompt="Aiutami a configurare una pipeline di triage automatico da Sentry a Devin. Segui la guida all'indirizzo https://docs.devin.ai/use-cases/gallery/api-sentry-auto-triage e accompagnami in ogni passaggio: abilitare il Sentry MCP, creare l'integrazione interna e distribuire il gestore del webhook." category="Risposta agli incidenti" features="API, MCP" />

<div className="uc-detail-wrapper">
  <Tip>Per una guida più dettagliata sull'integrazione con Sentry, [clicca qui](/it/enterprise/integrations/sentry).</Tip>

  <Steps>
    <Step title="Abilita MCP Sentry">
      Devin ha bisogno di accedere al tuo account Sentry per poter recuperare stack trace, breadcrumb e metadati degli eventi durante il triage.

      1. Vai su **Settings > Connessioni > server MCP** e trova **Sentry**
      2. Clicca su **Enable** e completa il flusso OAuth con l'account Sentry che ha accesso ai tuoi progetti
      3. Verifica la connessione — avvia una sessione e chiedi a Devin di elencare le issue recenti in uno dei tuoi progetti

      Una volta connesso, Devin può interrogare qualsiasi progetto Sentry a cui il tuo account ha accesso: dettagli delle issue, stack trace completi, breadcrumb degli eventi, tag di release e altro ancora. Consulta la [documentazione di MCP Marketplace](/it/work-with-devin/mcp) per i dettagli sulla configurazione.
    </Step>

    <Step title="Crea un'integrazione interna di Sentry">
      Sentry invia i webhook tramite le Internal Integrations. Nel dashboard di Sentry, vai su **Settings > Developer Settings > Custom Integrations** e fai clic su **Create New Integration > Internal Integration**.

      Configura l'integrazione:

      * **Name:** `Devin Auto-Triage`
      * **Webhook URL:** Un servizio di cui effettuerai il deploy nel prossimo passaggio (ad esempio, `https://your-domain.com/sentry-webhook`)
      * **Alert Rule Action:** Impostala su **on** — in questo modo l'integrazione sarà disponibile come azione nelle alert rule
      * **Permissions:** Accesso in lettura a **Issue & Event** e **Project**

      Salva l'integrazione, quindi crea una alert rule. Vai su **Alerts > Create Alert Rule > Issue Alert** per il tuo progetto:

      * **When:** Viene creata una nuova issue
      * **If:** L'issue ha più di **50** eventi in **1 ora** (modifica in base al tuo traffico)
      * **Then:** Invia una notifica tramite **Devin Auto-Triage**
    </Step>

    <Step title="Collega il webhook all'API di Devin">
      Crea un piccolo handler che riceve il payload di alert di Sentry e avvia una sessione Devin. Crea un [service user](/it/api-reference/v3/overview) in **Settings > Service Users** con il permesso `ManageOrgSessions` e salva il suo token come `DEVIN_API_KEY` nell'ambiente del tuo handler. Imposta `DEVIN_ORG_ID` sull'ID della tua organizzazione — ottienilo effettuando una chiamata GET a `https://api.devin.ai/v3/enterprise/organizations` con il tuo token.

      ```javascript theme={null}
      const express = require('express');
      const app = express();
      app.use(express.json());

      app.post('/sentry-webhook', async (req, res) => {
        const event = req.body.data?.event;
        if (!event) return res.sendStatus(200);

        const orgId = process.env.DEVIN_ORG_ID;
        const response = await fetch(
          `https://api.devin.ai/v3/organizations/${orgId}/sessions`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${process.env.DEVIN_API_KEY}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            prompt: [
              `A Sentry alert fired for a new issue: "${event.title}"`,
              `Culprit: ${event.culprit}`,
              `Sentry URL: ${event.web_url}`,
              ``,
              `Use the Sentry MCP to pull the full stack trace and breadcrumbs.`,
              `Identify the root cause, fix the issue, and open a PR with a`,
              `regression test.`,
            ].join('\n'),
            tags: ['sentry-auto-triage', `project:${event.project}`],
          }),
        });

        const { session_id } = await response.json();
        console.log(`Started Devin session ${session_id} for: ${event.title}`);
        res.sendStatus(200);
      });

      app.listen(3000);
      ```

      Distribuisci questo ovunque sia in grado di ricevere traffico HTTPS — ad esempio su un Cloudflare Worker, AWS Lambda o una piccola VPS. Imposta l'URL del webhook della tua Sentry Internal Integration su questo endpoint.

      Il codice sopra etichetta ogni sessione con `sentry-auto-triage` e il nome del progetto Sentry. Questo ti permette di filtrare queste sessioni nella dashboard di Devin e di [recuperarle tramite l'API](/it/api-reference/v3/sessions/get-organizations-sessions) usando il parametro di query `tags`, utile per monitorare quanti errori Devin gestisce in triage per progetto.

      Per verificare che la pipeline funzioni, attiva un alert di test in Sentry (oppure abbassa temporaneamente la soglia), quindi controlla [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) per una nuova sessione etichettata `sentry-auto-triage`.
    </Step>

    <Step title="Come Devin gestisce ogni avviso">
      Quando un nuovo errore supera la tua soglia e il webhook viene attivato, Devin avvia una sessione e lavora sul problema:

      1. **Interroga Sentry tramite MCP** — recupera l'intero stack trace, i breadcrumbs (azioni dell'utente che hanno portato al crash), i tag relativi al browser/sistema operativo/release interessati e la frequenza degli eventi
      2. **Individua la causa principale** — legge il file sorgente alla riga esatta indicata nello stack trace, segue il flusso dei dati per capire perché il valore è `undefined` o `null`
      3. **Scrive una correzione mirata** — implementa la gestione degli errori (optional chaining, valori predefiniti, validazione degli input) in linea con i pattern esistenti nella tua base di codice
      4. **Aggiunge un test di regressione** — crea un caso di test che riproduce lo scenario del crash originale e verifica che la correzione impedisca che si ripeta
      5. **Apre una PR** — inserisce l'URL della issue Sentry nella descrizione della PR in modo che i revisori possano mettere a confronto il contesto dell'errore originale e il volume degli eventi

      Esempio di descrizione PR:

      ```
      Fix: TypeError in UserProfile quando user.profile è null

      Causa principale: l'endpoint /api/users/:id restituisce { profile: null }
      per gli utenti che non hanno completato l'onboarding. UserProfile.tsx:47
      destruttura email da user.profile senza un controllo null.

      Fix: aggiunto optional chaining e uno stato di fallback.
      Test: aggiunto test per utenti con profilo null — verifica che
      il componente mostri "Complete your profile" invece di andare in crash.

      Sentry issue: FRONTEND-1892 (340 eventi nell'ultima ora)
      ```
    </Step>

    <Step title="Migliora il triage con i playbook e Knowledge">
      Una volta che la pipeline è in esecuzione, rendi l’auto-triage più intelligente:

      **Crea un playbook di triage.** Parti dal playbook di esempio [`!triage`](https://app.devin.ai/settings/playbooks/14fed18b89d44713a26e673cf258f548?utm_source=docs\&utm_medium=use-case-gallery) — duplicalo e personalizzalo con le convenzioni di gestione degli errori del tuo team (error boundaries, pattern di controllo dei valori null, formato dei log). Poi passa l'ID del playbook nel tuo webhook handler aggiungendo `"playbook_id": "your-playbook-id"` al body della richiesta. Puoi anche chiedere a Devin di generare un playbook a partire da una descrizione del tuo workflow di triage.

      **Aggiungi [Knowledge](/it/product-guides/knowledge)** sui tuoi contratti API e sui casi limite noti — ad esempio, "Le risposte da `/api/users` possono restituire `{ profile: null }` per gli utenti che non hanno completato l'onboarding. Gestisci sempre questo caso." Chiedi a Devin di aiutarti a scrivere le voci di Knowledge partendo dalla tua documentazione esistente. Più contesto ha Devin sul tuo dominio, più accurate saranno le sue correzioni.

      **Definisci con attenzione l'ambito degli alert.** Usa le condizioni delle regole di alert di Sentry per limitare quali errori attivano Devin — filtra per progetto, ambiente (solo `production`) o volume di errori. Un buon punto di partenza è attivare solo per i problemi con oltre 50 eventi nella prima ora, per concentrarti sugli errori ad alto impatto.

      **Imposta una revisione settimanale.** Crea una [schedule](https://app.devin.ai/settings/schedules/create?utm_source=docs\&utm_medium=use-case-gallery) che venga eseguita una volta a settimana per rivedere gli esiti delle tue sessioni di auto-triage e riversare gli apprendimenti nel tuo playbook e in Knowledge:

      <PromptBlock type="schedule">
        ```txt Weekly Sentry auto-triage review theme={null}
        Review all Devin sessions tagged "sentry-auto-triage" from the past week.
        For each session, check:

        1. PR outcome — was it merged, closed without merging, or still open?
        2. Sentry issue status — was it marked as resolved/fixed, ignored, or dismissed?
        3. Any reviewer comments or requested changes on the PR

        Based on these signals:
        - If PRs were consistently closed or had the same feedback (e.g., "don't use
          optional chaining here, use an explicit guard"), update the !sentry-triage
          playbook with that convention
        - If Devin missed context that led to a bad fix, add a Knowledge entry
          covering that domain area (e.g., API contracts, service dependencies)
        - Summarize: how many sessions ran, how many PRs merged vs closed, and
          any patterns in the feedback

        Post the summary to #engineering-ops on Slack.
        ```
      </PromptBlock>
    </Step>
  </Steps>
</div>
