> ## Documentation Index
> Fetch the complete documentation index at: https://adcp-docs-ja.pier1.co.jp/llms.txt
> Use this file to discover all available pages before exploring further.

# sync_event_sources

> sync_event_sources タスク — コンバージョントラッキングとアトリビューションのために、AdCP セラーアカウントにウェブサイトピクセル、モバイル SDK、サーバー間連携、およびセラーやプラットフォームネイティブのイベントソースを設定します。

コンバージョントラッキングのためにセラーアカウントにイベントソースを設定します。ソースは、ウェブサイトピクセル、モバイル SDK、サーバー間フィード、CRM インポートのようなバイヤー管理の連携でも、チャンネル、プロフィール、フィード、ポッドキャスト、ニュースレターリストのようなセラーやプラットフォームネイティブの自社プロパティでもかまいません。アップサートセマンティクス、セラー管理ソース、セットアップ手順をサポートします。

**レスポンス時間**: 約1秒（同期設定）

**リクエストスキーマ**: [`/schemas/v3/media-buy/sync-event-sources-request.json`](https://adcontextprotocol.org/schemas/v3/media-buy/sync-event-sources-request.json)
**レスポンススキーマ**: [`/schemas/v3/media-buy/sync-event-sources-response.json`](https://adcontextprotocol.org/schemas/v3/media-buy/sync-event-sources-response.json)

## クイックスタート

購入トラッキング用のイベントソースを設定します：

<CodeGroup>
  ```javascript JavaScript theme={null}
  import { testAgent } from "@adcp/sdk/testing";
  import { SyncEventSourcesResponseSchema } from "@adcp/sdk";

  const result = await testAgent.syncEventSources({
    account: { account_id: "acct_12345" },
    event_sources: [
      {
        event_source_id: "website_pixel",
        name: "Main Website Pixel",
        event_types: ["purchase", "lead", "add_to_cart"],
        allowed_domains: ["www.example.com", "shop.example.com"],
      },
    ],
  });

  if (!result.success) {
    throw new Error(`Request failed: ${result.error}`);
  }

  // レスポンスをスキーマに対して検証する
  const validated = SyncEventSourcesResponseSchema.parse(result.data);

  // まず操作レベルのエラーを確認する（判別共用体）
  if ("errors" in validated && validated.errors) {
    throw new Error(`Operation failed: ${JSON.stringify(validated.errors)}`);
  }

  if ("event_sources" in validated) {
    for (const source of validated.event_sources) {
      console.log(`${source.event_source_id}: ${source.action}`);
      if (source.setup?.snippet) {
        console.log(`  Install: ${source.setup.snippet_type}`);
      }
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from adcp.testing import test_agent

  async def main():
      result = await test_agent.simple.sync_event_sources(
          account={'account_id': 'acct_12345'},
          event_sources=[{
              'event_source_id': 'website_pixel',
              'name': 'Main Website Pixel',
              'event_types': ['purchase', 'lead', 'add_to_cart'],
              'allowed_domains': ['www.example.com', 'shop.example.com']
          }]
      )

      # まず操作レベルのエラーを確認する
      if hasattr(result, 'errors') and result.errors:
          raise Exception(f"Operation failed: {result.errors}")

      for source in result.event_sources:
          print(f"{source.event_source_id}: {source.action}")
          if source.setup and source.setup.snippet:
              print(f"  Install: {source.setup.snippet_type}")

  asyncio.run(main())
  ```
</CodeGroup>

## リクエストパラメータ

| パラメータ            | 型                                                                                | 必須  | 説明                                                                                                           |
| ---------------- | -------------------------------------------------------------------------------- | --- | ------------------------------------------------------------------------------------------------------------ |
| `account`        | [account-ref](/docs/building/by-layer/L2/accounts-and-agents#account-references) | はい  | アカウント参照。`{ "account_id": "..." }` を渡すか、セラーが暗黙的な解決をサポートしている場合は `{ "brand": {...}, "operator": "..." }` を渡します。 |
| `event_sources`  | [EventSource](/docs/media-buy/conversion-tracking/#event-source)\[]              | いいえ | 同期するイベントソース。省略した場合、呼び出しはディスカバリーのみとなり、変更なしに既存のすべてのイベントソースを返します。                                               |
| `delete_missing` | boolean                                                                          | いいえ | true の場合、このリクエストに含まれていないアカウント上のバイヤー管理イベントソースが削除されます（デフォルト: false）。                                           |

### イベントソースオブジェクト

| フィールド             | 型                                                                   | 必須  | 説明                                                                                           |
| ----------------- | ------------------------------------------------------------------- | --- | -------------------------------------------------------------------------------------------- |
| `event_source_id` | string                                                              | はい  | このイベントソースの一意の識別子                                                                             |
| `name`            | string                                                              | いいえ | 人が読める名前                                                                                      |
| `event_types`     | [EventType](/docs/media-buy/conversion-tracking/#event-types)\[]    | いいえ | このソースが処理するイベントタイプ。省略した場合、すべてのイベントタイプを受け入れる。                                                  |
| `action_source`   | [ActionSource](/docs/media-buy/conversion-tracking/#action-sources) | いいえ | 互換性のためのフラットなソースカテゴリ（`website`、`app`、`system_generated` など）。フラット値が粗すぎる場合は `surface` と組み合わせます。 |
| `allowed_domains` | string\[]                                                           | いいえ | このソースへのイベント送信が許可されたドメイン                                                                      |
| `surface`         | [EventSurface](/docs/media-buy/conversion-tracking/#event-surfaces) | いいえ | このソースが表す構造化されたサーフェス（自社チャンネル、プロフィール、フィード、ポッドキャスト、ニュースレターリスト、ウェブサイト、アプリ、店舗など）                  |

## レスポンス

**成功レスポンス:**

* `event_sources` - 同期済みのソースとアカウント上のセラー管理ソースの両方を含む、各イベントソースの結果

**エラーレスポンス:**

* `errors` - 操作レベルのエラーの配列（認証失敗、アカウントが見つからないなど）

**注意:** レスポンスは判別共用体を使用しており、成功フィールドまたはエラーのいずれかが返され、両方が同時に返されることはない。

**成功レスポンス内の各イベントソースには以下が含まれます:**

* すべてのリクエストフィールド
* `seller_id` - このイベントソースのセラー割り当て識別子
* `action` - 実行された操作: `created`、`updated`、`unchanged`、`deleted`、`failed`
* `action_source` - イベントソースの種別（ウェブサイトピクセル、アプリ SDK など）
* `surface` - フラットな `action_source` が粗すぎる場合に、このソースが表す構造化されたサーフェス
* `managed_by` - このソースの管理者: `buyer` または `seller`
* `setup` - 実装の詳細（スニペット、手順）
* `health` - イベントソースの健全性評価（セラーが健全性スコアリングをサポートする場合）
* `errors` - ソースごとのエラー（`action: "failed"` の場合のみ）
* `ext` - ソースごとの拡張メタデータ（プラットフォームネイティブのコンバージョン ID、アトリビューションウィンドウのハンドル、生の起点文字列など）

**完全なフィールド一覧はスキーマを参照**: [sync-event-sources-response.json](https://adcontextprotocol.org/schemas/v3/media-buy/sync-event-sources-response.json)

### イベントソースの健全性

イベントソースの品質を評価するセラーは、レスポンスの各ソースに `health` オブジェクトを含めます。これは Snap の Event Quality Score や Meta の Event Match Quality に相当します——バイヤーのイベント連携が最適化に十分な程度に機能しているかを伝えます。

| フィールド                 | 型         | 説明                                                                                   |
| --------------------- | --------- | ------------------------------------------------------------------------------------ |
| `status`              | string    | AdCP 標準の健全性レベル: `insufficient`、`minimum`、`good`、`excellent`。セラー横断の判断に使用します。          |
| `detail`              | object    | セラー固有のスコアリング（任意）。`score`、`max_score`、任意の `label` を含みます。セラーがネイティブな品質スコアを持つ場合にのみ存在します。 |
| `match_rate`          | number    | 広告インタラクションに一致したイベントの割合（0.0〜1.0）。                                                     |
| `last_event_at`       | date-time | 受信した最新イベントのタイムスタンプ。                                                                  |
| `evaluated_at`        | date-time | この健全性評価が計算された時刻。レポートデータから計算するセラーでは古くなります。                                            |
| `events_received_24h` | integer   | 過去 24 時間に受信したイベント数（0 = 発火していない）。                                                     |
| `issues`              | array     | severity（`error`、`warning`、`info`）とメッセージを持つ実行可能な問題。severity でソートすること——配列の位置に頼らないこと。  |

```json test=false theme={null}
{
  "event_sources": [
    {
      "event_source_id": "web_pixel",
      "action": "unchanged",
      "managed_by": "buyer",
      "health": {
        "status": "good",
        "detail": { "score": 7.2, "max_score": 10, "label": "Event Match Quality" },
        "match_rate": 0.72,
        "last_event_at": "2026-03-23T14:22:00Z",
        "evaluated_at": "2026-03-23T14:30:00Z",
        "events_received_24h": 14200,
        "issues": [
          {
            "severity": "warning",
            "message": "Missing hashed_email parameter on 38% of purchase events. Adding this improves match rate for cross-device attribution."
          }
        ]
      }
    }
  ]
}
```

バイヤーエージェントは、`detail.score` ではなく `status` を判断の基準にすべきです。四段階のステータスはすべてのセラー間で比較可能です——バイヤーエージェントは、どこでも機能する一つのルール（「DR プロダクトには `good` 以上を要求する」）を書きます。`detail` オブジェクトは人間向けダッシュボードや高度な診断のためのものです。

バイヤーエージェントは健全性データを次のように活用できます:

* イベント品質でプロダクト選択をゲートする（例: DR プロダクトには `good` 以上を要求）
* キャンペーンのローンチ前にセットアップの問題をバイヤーに提示する
* どのイベントソースを最初に修正すべきか優先順位付けする

## よくある使用例

### ディスカバリーのみ

変更を加えずにアカウント上のすべてのイベントソース（セラー管理ソースを含む）を検出します。セラーが常時オンのアトリビューションを提供するプラットフォーム管理のコンバージョントラッキングに便利：

<CodeGroup>
  ```javascript JavaScript theme={null}
  import { testAgent } from "@adcp/sdk/testing";
  import { SyncEventSourcesResponseSchema } from "@adcp/sdk";

  const result = await testAgent.syncEventSources({
    account: { account_id: "acct_12345" },
  });

  if (!result.success) {
    throw new Error(`Request failed: ${result.error}`);
  }

  const validated = SyncEventSourcesResponseSchema.parse(result.data);

  if ("errors" in validated && validated.errors) {
    throw new Error(`Operation failed: ${JSON.stringify(validated.errors)}`);
  }

  if ("event_sources" in validated) {
    for (const source of validated.event_sources) {
      console.log(`${source.event_source_id} (${source.managed_by}): ${source.name}`);
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from adcp.testing import test_agent

  async def main():
      result = await test_agent.simple.sync_event_sources(
          account={'account_id': 'acct_12345'}
      )

      if hasattr(result, 'errors') and result.errors:
          raise Exception(f"Operation failed: {result.errors}")

      for source in result.event_sources:
          print(f"{source.event_source_id} ({source.managed_by}): {source.name}")

  asyncio.run(main())
  ```
</CodeGroup>

### 複数のイベントソース

ウェブサイトとアプリ用に個別のソースを設定します：

<CodeGroup>
  ```javascript JavaScript theme={null}
  import { testAgent } from "@adcp/sdk/testing";
  import { SyncEventSourcesResponseSchema } from "@adcp/sdk";

  const result = await testAgent.syncEventSources({
    account: { account_id: "acct_12345" },
    event_sources: [
      {
        event_source_id: "web_pixel",
        name: "Website Pixel",
        event_types: ["purchase", "lead", "add_to_cart", "view_content"],
        allowed_domains: ["www.example.com"],
      },
      {
        event_source_id: "app_sdk",
        name: "Mobile App SDK",
        event_types: ["purchase", "app_install", "app_launch"],
      },
    ],
  });

  if (!result.success) {
    throw new Error(`Request failed: ${result.error}`);
  }

  const validated = SyncEventSourcesResponseSchema.parse(result.data);

  if ("errors" in validated && validated.errors) {
    throw new Error(`Operation failed: ${JSON.stringify(validated.errors)}`);
  }

  if ("event_sources" in validated) {
    for (const source of validated.event_sources) {
      console.log(`${source.event_source_id} (${source.managed_by}): ${source.action}`);
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from adcp.testing import test_agent

  async def main():
      result = await test_agent.simple.sync_event_sources(
          account={'account_id': 'acct_12345'},
          event_sources=[
              {
                  'event_source_id': 'web_pixel',
                  'name': 'Website Pixel',
                  'event_types': ['purchase', 'lead', 'add_to_cart', 'view_content'],
                  'allowed_domains': ['www.example.com']
              },
              {
                  'event_source_id': 'app_sdk',
                  'name': 'Mobile App SDK',
                  'event_types': ['purchase', 'app_install', 'app_launch']
              }
          ]
      )

      if hasattr(result, 'errors') and result.errors:
          raise Exception(f"Operation failed: {result.errors}")

      for source in result.event_sources:
          print(f"{source.event_source_id} ({source.managed_by}): {source.action}")

  asyncio.run(main())
  ```
</CodeGroup>

### セラー管理ソースの検出

セラーは常時オンのイベントソース（例: Amazon 売上アトリビューション）を提供する場合があります。これらはバイヤー管理ソースと並んで `managed_by: "seller"` としてレスポンスに表示されます：

```json test=false theme={null}
{
  "event_sources": [
    {
      "event_source_id": "web_pixel",
      "name": "Website Pixel",
      "seller_id": "px_abc123",
      "action": "created",
      "managed_by": "buyer",
      "setup": {
        "snippet": "<script src=\"https://seller.example/pixel/px_abc123.js\"></script>",
        "snippet_type": "javascript",
        "instructions": "Place this tag in the <head> of all pages where you want to track events."
      }
    },
    {
      "event_source_id": "seller_sales_attribution",
      "name": "Sales Attribution",
      "seller_id": "internal_attr",
      "action": "unchanged",
      "managed_by": "seller",
      "action_source": "in_store"
    }
  ]
}
```

`conversion_tracking.platform_managed: true` を持つプロダクトは、セラーがこれらのソースを提供していることを示しています。

### クリエイターおよび自社プロパティのソース

セラー管理のクリエイターまたは自社プロパティのソースは、互換性のためのフラットな `action_source` と構造化されたコンテキストのための `surface` を伴って、同じ `event_sources` 配列を使います:

```json test=false theme={null}
{
  "event_sources": [
    {
      "event_source_id": "creator_channel",
      "name": "Creator Channel Events",
      "seller_id": "creator_attr_001",
      "event_types": ["follow", "content_view", "watch_milestone"],
      "action_source": "system_generated",
      "surface": {
        "category": "owned_property",
        "property_type": "channel",
        "namespace": "video_platform",
        "property_id": "channel_123"
      },
      "managed_by": "seller",
      "action": "unchanged",
      "ext": {
        "video_platform": {
          "native_origin": "owned_channel"
        }
      }
    }
  ]
}
```

チャンネル、プロフィール、フィード、リスト、ポッドキャストへの無料で継続的なオプトインには `follow` を使います。有料の購読または有料のメンバーシップにのみ `subscribe` を使います。

### delete\_missing によるクリーン同期

アカウント上のすべてのバイヤー管理イベントソースを置き換える：

<CodeGroup>
  ```javascript JavaScript theme={null}
  import { testAgent } from "@adcp/sdk/testing";
  import { SyncEventSourcesResponseSchema } from "@adcp/sdk";

  const result = await testAgent.syncEventSources({
    account: { account_id: "acct_12345" },
    delete_missing: true,
    event_sources: [
      {
        event_source_id: "unified_pixel",
        name: "Unified Tracking Pixel",
      },
    ],
  });

  if (!result.success) {
    throw new Error(`Request failed: ${result.error}`);
  }

  const validated = SyncEventSourcesResponseSchema.parse(result.data);

  if ("errors" in validated && validated.errors) {
    throw new Error(`Operation failed: ${JSON.stringify(validated.errors)}`);
  }

  if ("event_sources" in validated) {
    for (const source of validated.event_sources) {
      if (source.action === "deleted") {
        console.log(`Removed: ${source.event_source_id}`);
      } else {
        console.log(`Active: ${source.event_source_id} (${source.action})`);
      }
    }
  }
  ```

  ```python Python theme={null}
  import asyncio
  from adcp.testing import test_agent

  async def main():
      result = await test_agent.simple.sync_event_sources(
          account={'account_id': 'acct_12345'},
          delete_missing=True,
          event_sources=[{
              'event_source_id': 'unified_pixel',
              'name': 'Unified Tracking Pixel'
          }]
      )

      if hasattr(result, 'errors') and result.errors:
          raise Exception(f"Operation failed: {result.errors}")

      for source in result.event_sources:
          if source.action == 'deleted':
              print(f"Removed: {source.event_source_id}")
          else:
              print(f"Active: {source.event_source_id} ({source.action})")

  asyncio.run(main())
  ```
</CodeGroup>

## セットアップ手順

レスポンスには各イベントソースのセットアップ詳細が含まれます。`setup` オブジェクトはソースのアクティベート方法を示しています：

| `snippet_type` | 説明                        | 必要なアクション                     |
| -------------- | ------------------------- | ---------------------------- |
| `javascript`   | ウェブサイトページ用の JavaScript タグ | トラッキング対象ページの `<head>` 内に配置する |
| `html`         | HTML ピクセル / iframe        | `</body>` の直前に配置する           |
| `pixel_url`    | イベント発生時に呼び出す URL          | 各イベント時に GET リクエストを送信する       |
| `server_only`  | クライアントサイドのタグ不要            | `log_event` API を直接使用する      |

## エラーハンドリング

| エラーコード                      | 説明                        | 対処方法                                                        |
| --------------------------- | ------------------------- | ----------------------------------------------------------- |
| `ACCOUNT_NOT_FOUND`         | アカウントが存在しない               | アカウント設定の `account_id` を確認する                                 |
| `INVALID_EVENT_TYPE`        | 認識できないイベントタイプ             | `get_adcp_capabilities` でセラーの `supported_event_types` を確認する |
| `DUPLICATE_EVENT_SOURCE_ID` | リクエスト内に同じ ID を持つ複数のソースがある | 一意の `event_source_id` 値を使用する                                |
| `RATE_LIMITED`              | 同期リクエストが多すぎる              | 指数バックオフで待機してリトライする                                          |

## ベストプラクティス

1. **ログ送信前に同期する** — `log_event` でイベントを送信する前に、必ずイベントソースを設定しなければなりません。未設定のソースへのイベント送信は拒否されます。

2. **わかりやすい ID を使用する** — 不明瞭な識別子ではなく、意味のある `event_source_id` 値（例: `web_pixel`、`app_sdk`、`crm_import`）を選ぶべきです。

3. **event\_types を指定する** — より良いバリデーションとデバッグのために、各ソースを関連するイベントタイプに限定すべきです。

4. **セラーの機能を確認する** — イベントソースを設定する前に、`get_adcp_capabilities` を使用してサポートされているイベントタイプ、UID タイプ、アクションソースを確認すべきです。

5. **セットアップスニペットをインストールする** — レスポンスに `setup` 手順が含まれている場合、イベントをログに記録する前に提供されたスニペットをインストールしなければなりません。サーバーオンリーソース（`snippet_type: "server_only"`）はこの手順をスキップしてよいです。

6. **セラー管理ソースを処理する** — レスポンスには自分が設定していない `managed_by: "seller"` のソースが含まれる場合があります。これらは常時オンであり、追加のアトリビューションデータを提供します。

## 次のステップ

* [コンバージョントラッキング](/docs/media-buy/conversion-tracking/) — データモデル、最適化目標、エンドツーエンドのフロー
* [log\_event](/docs/media-buy/task-reference/log_event) — 設定済みイベントソースにマーケティングイベントを送信します
* [create\_media\_buy](/docs/media-buy/task-reference/create_media_buy#campaign-with-conversion-optimization) — イベントソースを参照するパッケージに最適化目標を設定します
* [get\_media\_buy\_delivery](/docs/media-buy/task-reference/get_media_buy_delivery) — デリバリーレポートでコンバージョン指標を監視します
