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

# Auto-Generate Incident Postmortems

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="Auto-Generate Incident Postmortems" description="When a PagerDuty incident resolves, Devin drafts a structured postmortem with timeline, root cause analysis, and action items." prompt="Help me set up a PagerDuty-to-Devin postmortem pipeline. Follow the guide at https://docs.devin.ai/use-cases/gallery/api-pagerduty-postmortem and walk me through each step: deploying the webhook bridge, configuring PagerDuty, and connecting observability MCPs." category="Incident Response" features="API, MCP" />

<div className="uc-detail-wrapper">
  <Tip>For a more detailed PagerDuty integration guide, [click here](/enterprise/integrations/pagerduty).</Tip>

  <Steps>
    <Step title="Deploy a webhook bridge">
      Create a small service that listens for PagerDuty `incident.resolved` events and starts a Devin session to write the postmortem. Deploy this as a serverless function (AWS Lambda, Cloudflare Worker) or a lightweight container:

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

      function verifySignature(req) {
        const secret = Buffer.from(req.headers['x-webhook-secret'] || '');
        const expected = Buffer.from(process.env.WEBHOOK_SECRET || '');
        if (!expected.length) throw new Error('WEBHOOK_SECRET environment variable is not set');
        if (secret.length !== expected.length) return false;
        return crypto.timingSafeEqual(secret, expected);
      }

      app.post('/pagerduty-resolved', async (req, res) => {
        if (!verifySignature(req)) return res.status(401).send('Bad signature');

        const event = req.body?.event;
        if (!event || event.event_type !== 'incident.resolved') {
          return res.sendStatus(200);
        }

        const incident = event.data;
        const title = incident.title || 'Unknown incident';
        const service = incident.service?.summary || 'unknown-service';
        const urgency = incident.urgency || 'high';
        const incidentUrl = incident.html_url || '';
        const createdAt = incident.created_at || '';
        const resolvedAt = incident.resolved_at || new Date().toISOString();

        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 PagerDuty incident has been resolved. Draft a postmortem.`,
              ``,
              `Incident: "${title}"`,
              `Service: ${service}`,
              `Urgency: ${urgency}`,
              `Created: ${createdAt}`,
              `Resolved: ${resolvedAt}`,
              `Incident URL: ${incidentUrl}`,
              ``,
              `Write a structured postmortem:`,
              `1. Use the Datadog MCP to pull logs and metrics for ${service} during the incident window`,
              `2. Identify the root cause — check for deploys, config changes, or upstream failures`,
              `3. Build a detailed timeline from first alert to resolution`,
              `4. List action items to prevent recurrence`,
              `5. Post the postmortem as a PR to our docs/postmortems/ directory`,
            ].join('\n'),
            tags: ['pagerduty-postmortem', `service:${service}`],
          }),
        });

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

      app.listen(3000);
      ```

      Create a [service user](/api-reference/v3/overview) in **Settings > Service Users** at [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) with `ManageOrgSessions` permission. Copy the API token shown after creation and store it as `DEVIN_API_KEY` on your bridge service. Set `DEVIN_ORG_ID` to your organization ID — get it by calling `GET https://api.devin.ai/v3/enterprise/organizations` with your token. Set `WEBHOOK_SECRET` to a shared secret you'll also configure in PagerDuty.
    </Step>

    <Step title="Configure PagerDuty">
      1. In PagerDuty, go to **Services > \[your service] > Integrations**
      2. Click **Add Integration** and select **Generic Webhooks (v3)**
      3. Set the **Webhook URL** to your bridge endpoint (e.g., `https://your-bridge.example.com/pagerduty-resolved`)
      4. Under **Custom Headers**, add `X-Webhook-Secret` with the same value you stored as `WEBHOOK_SECRET`
      5. Under **Event Subscription**, filter by event type `incident.resolved` so the postmortem triggers only after the incident is closed

      <Note>
        You can also subscribe to `incident.acknowledged` if you want Devin to start gathering data while the incident is still in progress, then finalize the postmortem on resolution.
      </Note>
    </Step>

    <Step title="Connect observability MCPs (optional)">
      Devin writes better postmortems when it can access your telemetry data. Enable one or more MCPs so Devin can pull real data for the incident window:

      **Datadog MCP** — Go to **Settings > Connections > MCP servers**, find **Datadog**, click **Enable**, and enter your API/Application keys. Devin will query logs, metrics, deploy events, and monitor history.

      **Sentry MCP** — Find **Sentry** in the MCP Marketplace, click **Enable**, and complete the OAuth flow. Devin will pull error details, stack traces, and release tags.

      Once connected, Devin automatically correlates telemetry with the incident timeline to build an evidence-backed postmortem. Learn more about [connecting MCP servers](/work-with-devin/mcp).
    </Step>

    <Step title="What Devin generates">
      When a PagerDuty incident resolves, Devin analyzes the incident window and drafts a structured postmortem:

      <PromptBlock>
        ```txt Generate incident postmortem theme={null}
        A PagerDuty incident has been resolved. Draft a postmortem.

        Incident: "Database connection pool exhaustion on orders-service"
        Service: orders-service
        Created: 2026-02-10T14:32:00Z
        Resolved: 2026-02-10T15:18:00Z

        Using Datadog and Sentry MCPs:
        1. Pull logs and metrics for orders-service between 14:00 and 15:30 UTC
        2. Check for deploys, config changes, or upstream failures in that window
        3. Build a detailed timeline from first alert to resolution
        4. Identify contributing factors and root cause
        5. Draft action items to prevent recurrence
        6. Commit the postmortem as a Markdown file to docs/postmortems/
        ```
      </PromptBlock>

      Example postmortem Devin produces:

      ```markdown theme={null}
      # Postmortem: Database Connection Pool Exhaustion — orders-service
      **Date:** 2026-02-10 | **Duration:** 46 minutes | **Severity:** P1

      ## Summary
      orders-service experienced connection pool exhaustion between
      14:32 and 15:18 UTC, causing 502 errors for ~12% of order
      placement requests.

      ## Timeline
      - 14:15 UTC — Deploy #387 released (commit e4f29a1)
      - 14:28 UTC — Connection pool usage climbed from 60% to 92%
      - 14:32 UTC — Pool exhausted; PagerDuty incident triggered
      - 14:38 UTC — On-call engineer acknowledged
      - 14:45 UTC — Identified Deploy #387 added a new inventory
                    check that opens a DB connection per line item
                    without releasing it in the finally block
      - 15:02 UTC — Rollback to Deploy #386 initiated
      - 15:18 UTC — Connection pool recovered; incident resolved

      ## Root Cause
      Deploy #387 introduced `checkInventoryAvailability()` in
      `src/services/orders.ts:142`. The function opens a new DB
      connection for each line item in an order but only releases
      it on the success path. When inventory checks fail (timeout
      or stock unavailable), connections leak.

      Orders with 5+ line items reliably exhausted the pool within
      15 minutes of the deploy.

      ## Action Items
      - [ ] Fix connection leak: add `finally` block to release
            connection (PR #388 opened)
      - [ ] Add connection pool usage monitor with alert at 80%
      - [ ] Add integration test for multi-item orders with
            simulated inventory failures
      - [ ] Review other DB access patterns for similar leak risks
      ```
    </Step>

    <Step title="Customize the postmortem">
      Tailor the pipeline to match your team's postmortem process:

      **Use a [Playbook](/product-guides/creating-playbooks)** to define your postmortem template — sections, severity classification, required fields, and where to store the output. Pass a `playbook_id` in the API request to standardize every postmortem.

      **Route by severity.** Add logic in your bridge to only generate postmortems for P1/P2 incidents. Lower-severity incidents might not need a full writeup.

      **Add [Knowledge](/product-guides/knowledge)** about your architecture, service ownership, and past incidents so Devin can connect the dots — e.g., "orders-service depends on inventory-service, which is known for timeout issues under load."

      **Post to your wiki.** Instead of committing to a repo, have Devin post the postmortem to Confluence, Notion, or your internal wiki via the session prompt.
    </Step>
  </Steps>
</div>
