> ## 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.

# 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="Sentry エラーの自動トリアージ" description="Sentry の Webhook を Devin API に接続して、新しい本番環境エラーを自動トリアージします。" prompt="Sentry から Devin への自動トリアージパイプラインの構築を手伝ってください。https://docs.devin.ai/use-cases/gallery/api-sentry-auto-triage のガイドに従い、Sentry MCP の有効化、内部インテグレーションの作成、Webhook ハンドラーのデプロイまで、各ステップを順番に案内してください。" category="インシデント対応" features="API, MCP" />

<div className="uc-detail-wrapper">
  <Tip>Sentry インテグレーションの詳細なガイドについては、[こちら](/ja/enterprise/integrations/sentry)をご覧ください。</Tip>

  <Steps>
    <Step title="Sentry MCP を有効にする">
      Devin がトリアージ中にスタックトレース、ブレッドクラム、イベントメタデータを取得できるようにするには、Sentry アカウントへのアクセス権が必要です。

      1. **Settings > Connections > MCPサーバー** に移動し、**Sentry** を探します
      2. **Enable** をクリックし、あなたのプロジェクトにアクセスできる Sentry アカウントで OAuth フローを完了します
      3. 接続をテストします — セッションを開始し、プロジェクトの 1 つについて最近の Issue を一覧表示するよう Devin に依頼します

      接続が完了すると、Devin はあなたのアカウントからアクセス可能な任意の Sentry プロジェクトに対してクエリを実行できます。Issue の詳細、完全なスタックトレース、イベントのブレッドクラム、リリースタグなどを取得できます。セットアップの詳細については、[MCP Marketplace ドキュメント](/ja/work-with-devin/mcp) を参照してください。
    </Step>

    <Step title="Sentry の内部インテグレーションを作成">
      Sentry は Internal Integrations を通じて webhook を配信します。Sentry ダッシュボードで **Settings > Developer Settings > Custom Integrations** に移動し、**Create New Integration > Internal Integration** をクリックします。

      次のように設定します:

      * **Name:** `Devin Auto-Triage`
      * **Webhook URL:** 次のステップでデプロイするサービス (例: `https://your-domain.com/sentry-webhook`)
      * **Alert Rule Action:** **on** に切り替え — このインテグレーションがアラートルール内のアクションとして利用可能になります
      * **Permissions:** **Issue & Event** と **Project** への読み取り権限

      インテグレーションを保存したら、アラートルールを作成します。プロジェクトで **Alerts > Create Alert Rule > Issue Alert** に移動します:

      * **When:** 新しい issue が作成されたとき
      * **If:** その issue に **1時間** で **50** 件を超える event がある場合 (トラフィックに応じて調整してください)
      * **Then:** **Devin Auto-Triage** 経由で通知を送信します
    </Step>

    <Step title="Webhook を Devin API に接続する">
      Sentry のアラートペイロードを受け取り、Devin セッションを開始する小さなハンドラを作成します。**Settings > Service Users** で `ManageOrgSessions` 権限を持つ[サービスユーザー](/ja/api-reference/v3/overview)を作成し、そのトークンをハンドラの環境変数 `DEVIN_API_KEY` に保存します。`DEVIN_ORG_ID` には組織 ID を設定します。組織 ID は、トークンを指定して `GET https://api.devin.ai/v3/enterprise/organizations` を呼び出すことで取得できます。

      ```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);
      ```

      HTTPS トラフィックを受信できる任意の場所 (Cloudflare Worker、AWS Lambda、または小さな VPS など) にデプロイします。Sentry の Internal Integration の webhook URL としてこのエンドポイントを指定してください。

      上記のコードは、各セッションに `sentry-auto-triage` と Sentry プロジェクト名のタグを付けます。これにより、Devin のダッシュボードでこれらのセッションをフィルタリングし、`tags` クエリパラメータを使って [API 経由で取得](/ja/api-reference/v3/sessions/get-organizations-sessions) できるようになります。プロジェクトごとに Devin がトリアージしたエラー数を追跡するのに便利です。

      パイプラインが動作していることを確認するには、Sentry でテストアラートをトリガーするか (一時的にしきい値を下げてから) 、[app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) を開き、新しく `sentry-auto-triage` がタグ付けされたセッションがあるかどうかを確認します。
    </Step>

    <Step title="各アラートに対してDevinが行う対応">
      新しいエラーがしきい値を超えて webhook が発火すると、Devin がセッションを開始し、次のように問題へ対処します。

      1. **MCP 経由で Sentry にクエリを送信** — フルスタックトレース、breadcrumb (クラッシュに至るまでのユーザー操作履歴) 、影響を受けたブラウザ / OS / リリースタグ、およびイベント頻度を取得します
      2. **根本原因を特定** — スタックトレースの該当行のソースファイルを読み、データフローを追って値が `undefined` や `null` になっている理由を把握します
      3. **的確な修正を作成** — 既存のコードベースのパターンに合わせたエラーハンドリング (オプショナルチェイニング、デフォルト値、入力バリデーション) を実装します
      4. **リグレッションテストを追加** — 元のクラッシュシナリオを再現するテストケースを作成し、その修正で再発が防げることを検証します
      5. **PR を作成** — PR の説明に Sentry の issue の URL を記載し、レビュアーが元のエラーコンテキストとイベントボリュームを突き合わせて確認できるようにします

      PR 説明の例:

      ```
      修正: user.profile が null の場合に UserProfile で発生する TypeError

      根本原因: /api/users/:id エンドポイントは、オンボーディングを完了していない
      ユーザーに対して { profile: null } を返す。UserProfile.tsx:47 では
      null チェックなしで user.profile から email を分割代入している。

      修正: オプショナルチェーンとフォールバック状態を追加。
      テスト: null プロファイルを持つユーザー向けのテストを追加 — コンポーネントが
      クラッシュする代わりに「プロフィールを完成させてください」と表示されることを確認。

      Sentry issue: FRONTEND-1892 (過去1時間で340件のイベント)
      ```
    </Step>

    <Step title="プレイブックと Knowledge でトリアージを強化">
      パイプラインが稼働し始めたら、自動トリアージをさらにスマートにしましょう。

      **トリアージ用のプレイブックを作成する。** まずは [`!triage` テンプレートプレイブック](https://app.devin.ai/settings/playbooks/14fed18b89d44713a26e673cf258f548?utm_source=docs\&utm_medium=use-case-gallery) から始め、複製したうえでチームのエラーハンドリング規約 (エラーバウンダリ、null チェックパターン、ログ形式) に合わせてカスタマイズします。その後、リクエストボディに `"playbook_id": "your-playbook-id"` を追加して、webhook ハンドラーからプレイブック ID を渡します。また、トリアージワークフローの説明からプレイブックを生成するよう Devin に依頼することもできます。

      **API コントラクトや既知のエッジケースに関する [Knowledge](/ja/product-guides/knowledge) を追加する。** 例: "`/api/users` からのレスポンスでは、オンボーディングを完了していないユーザーに対して `{ profile: null }` が返される場合があります。必ずこのケースを考慮してガードしてください。" 既存ドキュメントから Knowledge エントリを作成するのを Devin に支援させましょう。Devin がドメインについて持つコンテキストが多いほど、修正はより正確になります。

      **アラートのスコープを慎重に設定する。** Sentry のアラートルール条件を使って、どのエラーで Devin を起動するかを制限します — プロジェクト、環境 (`production` のみ) 、エラーの発生数などでフィルタします。よい出発点としては、インパクトの大きいエラーに集中できるよう、最初の 1 時間で 50 件以上のイベントが発生した課題のみを対象にトリガーする設定です。

      **週次レビューのスケジュールを設定する。** [スケジュール](https://app.devin.ai/settings/schedules/create?utm_source=docs\&utm_medium=use-case-gallery) を作成し、週に 1 回実行して自動トリアージセッションの結果をレビューし、その学びをプレイブックと Knowledge にフィードバックします：

      <PromptBlock type="schedule">
        ```txt Weekly Sentry auto-triage review theme={null}
        過去 1 週間に実行された、"sentry-auto-triage" タグ付きのすべての Devin セッションをレビューする。
        各セッションについて、次を確認する:

        1. PR の結果 — マージされたか、マージされずにクローズされたか、まだオープンか？
        2. Sentry 課題のステータス — resolved/fixed、ignored、dismissed のいずれかに設定されたか？
        3. PR に対するレビュアーのコメントや、変更リクエストがあったか？

        これらの指標に基づいて:
        - PR が一貫してクローズされていたり、毎回同じフィードバック（例: "ここでは optional chaining を使わず、明示的なガードを使うこと"）が付いていた場合は、
          その規約を !sentry-triage プレイブックに反映する
        - Devin がコンテキストを取り逃したことで誤った修正につながった場合は、
          そのドメイン領域（例: API コントラクト、サービス依存関係）をカバーする Knowledge エントリを追加する
        - 要約として、実行されたセッション数、マージされた PR とクローズされた PR の数、
          フィードバックに見られたパターンをまとめる

        サマリーを Slack の #engineering-ops に投稿する。
        ```
      </PromptBlock>
    </Step>
  </Steps>
</div>
