---
title: Claude APIでOpenTelemetryを使用する
url: https://platform.claude.com/docs/ja/manage-claude/opentelemetry/api
description: Claude Consoleで宛先を追加して、Messages APIリクエストとManaged AgentsセッションのOpenTelemetryトレースをオブザーバビリティプラットフォームに送信します。
featureMetadata:
  topic:
    title: OpenTelemetry
    url: https://platform.claude.com/docs/en/manage-claude/opentelemetry
  status: beta
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). Messages API など、それ自体が ZDR の対象となる機能に限ります。Claude Managed Agents は ZDR の対象となりません。
  supportedPlatforms:
    Claude API: beta
    Claude Platform on AWS: beta
  rows:
    - label: 対応製品
      value: Messages API, Claude Managed Agents
  details:
    - 配信後、データはAnthropicの外部にある、お客様が選択したサービスによって、そのサービスの保持およびアクセス制御のもとで保持されます。
---

OpenTelemetryを使用すると、Claude APIは実行する各モデルリクエストと各ツール使用について「span」（スパン）を出力できます。コードを変更することなく、これらのスパンをオブザーバビリティプラットフォームで確認できます。

APIは、Messages APIリクエストとManaged Agentsセッションのスパンを出力します。それらを受け取るには、Claude Consoleで「*destination*」（宛先）を追加します。宛先は、オブザーバビリティプラットフォームのOTLPエンドポイントと、そのプラットフォームでの認証方法をAPIに伝えます。

## 必要なもの

* Claude Console組織における**管理者ロール**。宛先の追加と変更に必要です。開発者ロールでは、宛先を表示できます。組織がClaude Platform on AWSを利用している場合は、[サインイン](https://platform.claude.com/docs/ja/build-with-claude/claude-platform-on-aws#signing-in)の説明に従って、AWS Console経由でConsoleにサインインしてください。
* ポート443のHTTPS URLでprotobufエンコーディングを受け付ける**OTLP/HTTPエンドポイント**。独自の[OpenTelemetry Collector](https://opentelemetry.io/docs/collector/)を実行している場合、そのOTLP/HTTPレシーバーはデフォルトでポート4318をリッスンします。ポート443でHTTPSを受け付けるようにレシーバーを設定するか、Collectorの前にロードバランサーまたはリバースプロキシを配置してください。
* APIキーなどの**エンドポイントの認証情報**。

## 1. 宛先を追加する

<Info>
  テレメトリの送信先を追加すると、Anthropicは、お客様のプロバイダー規約およびアクセス制御に従い、組織内のClaude Platformアクティビティのトレースを、お客様が指定したサードパーティプロバイダーのOTLP/HTTPエンドポイントに送信します。配信後、データはAnthropicの外部にある、お客様が選択したサービスによって、そのサービスの保持およびアクセス制御のもとで保持されます。
</Info>

1. Consoleで、組織の[OpenTelemetry設定ページ](https://platform.claude.com/settings/telemetry-destinations)を開き、**Add destination**をクリックします。

2. 宛先を設定します：

   | フィールド                          | 入力内容                                                                                                                                                                                                                                                                                                    |
   | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
   | **Provider**                   | お使いのオブザーバビリティプラットフォーム。一覧にない場合は**Custom**。一覧にあるプラットフォームを選択した場合、Consoleでは**OTLP endpoint URL**、**Request headers**、**OTLP traces endpoint URL**の代わりに、APIキーなどのプラットフォームの詳細の入力を求められます。                                                                                                                       |
   | **Name**                       | 任意。たとえば「Acmeのオブザーバビリティプラットフォーム」。                                                                                                                                                                                                                                                                        |
   | **OTLP endpoint URL**          | オブザーバビリティプラットフォームのOTLP/HTTPエンドポイントのベースHTTPS URL。IPアドレスではなくホスト名を使用します。`https://gateway.example.com/otlp`のようにパスプレフィックスを含めることができます。`/v1/traces`はAPIが追加するため、追加しないでください。**OTLP traces endpoint URL**を設定した場合、APIは代わりにそのURLを使用します。                                                                             |
   | **Request headers**            | APIが各リクエストとともに送信するヘッダー。たとえばオブザーバビリティプラットフォームのAPIキーヘッダーです。認証情報はヘッダー値にのみ入力してください。保存後、Consoleは値を再表示しません。                                                                                                                                                                                                   |
   | **Content mode**               | **Metadata only**または**Full content**。[コンテンツモードの違い](https://platform.claude.com/docs/ja/manage-claude/opentelemetry#choose-a-content-mode)を参照してください。                                                                                                                                                     |
   | **Workspaces**                 | 宛先がスパンを受け取るワークスペース：**All**、**Selected**、または**All except**。[宛先のワークスペースを選択する](https://platform.claude.com/docs/ja/manage-claude/opentelemetry/api#choose-workspaces-for-a-destination)を参照してください。                                                                                                          |
   | **OTLP traces endpoint URL**   | 任意。**Advanced settings**の下にあります。オブザーバビリティプラットフォームのトレースエンドポイントの完全なURL。たとえば`https://gateway.example.com/custom/traces`。プラットフォームが、OTLP endpoint URLに`/v1/traces`を付けたもの以外のURLでトレースを受け取る場合に設定します。OTLP endpoint URLと同じホストである必要があります。                                                                          |
   | **Maximum content size in MB** | 任意。コンテンツモードが**Full content**の場合、**Advanced settings**の下にあります。APIが各スパンで送信するコンテンツの最大量。選択した**Provider**に応じて、Consoleが自動的に入力します。オブザーバビリティプラットフォームが受け付けるサイズに合わせて変更してください。APIが許容する最大量まで送信するには、空のままにしてください。[コンテンツの制限](https://platform.claude.com/docs/ja/manage-claude/opentelemetry#content-limits)を参照してください。 |

3. **Add destination**をクリックして保存します。

4. 宛先の**More actions**メニューで**Test**をクリックします。テストスパンがコレクターに配信されたことを示すメッセージ、または配信がどのように失敗したかを示すメッセージが表示されます（[配信エラー](https://platform.claude.com/docs/ja/manage-claude/opentelemetry/api#delivery-errors)を参照）。

5. `anthropic.test`スパンがオブザーバビリティプラットフォームに届いたことを確認します。

### Admin APIとCLI

Consoleの代わりに[Admin API](https://platform.claude.com/docs/ja/manage-claude/admin-api)を通じて宛先を追加することもできます。管理者としてCLIにサインインするか、`ANTHROPIC_API_KEY`に[Admin APIキー](https://platform.claude.com/docs/ja/manage-claude/admin-api-keys)を使用してください。Claude Platform on AWSでは、代わりに`https://aws-external-anthropic.{region}.api.aws`にリクエストを送信し、[リクエストの送信](https://platform.claude.com/docs/ja/build-with-claude/claude-platform-on-aws#making-requests)と同様にAWS認証情報で署名してください。その場合、宛先を管理できるユーザーは[IAMポリシー](https://platform.claude.com/docs/ja/api/claude-platform-on-aws-iam-actions)によって決まります。リクエストに含めることができるのは、そのリージョンにあるお客様のAWSアカウントのワークスペースのみです。

<CodeGroup>
  ```bash CLI
  # Sign in once as an admin, which opens a browser. Leave ANTHROPIC_API_KEY unset, because it overrides the profile.
  ant auth login --profile admin --scope "org:admin"
  ant --profile admin beta:organization:telemetry-destinations create \
    --endpoint-url https://gateway.example.com/otlp \
    --headers '{authorization: "Bearer YOUR_OBSERVABILITY_API_KEY"}' \
    --traces.content-mode metadata_only \
    --workspaces.type all
  ```

  ```bash cURL
  curl --fail-with-body -sS "https://api.anthropic.com/v1/organizations/telemetry_destinations" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: telemetry-destinations-2026-08-11" \
    -H "content-type: application/json" \
    -d '{
      "endpoint_url": "https://gateway.example.com/otlp",
      "headers": {"authorization": "Bearer YOUR_OBSERVABILITY_API_KEY"},
      "traces": {"content_mode": "metadata_only"},
      "workspaces": {"type": "all"}
    }'
  ```

  ```python Python
  client = anthropic.Anthropic()

  destination = client.beta.organization.telemetry_destinations.create(
      endpoint_url="https://gateway.example.com/otlp",
      headers={"authorization": "Bearer YOUR_OBSERVABILITY_API_KEY"},
      traces={"content_mode": "metadata_only"},
      workspaces={"type": "all"},
  )

  print(destination.id)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const destination = await client.beta.organization.telemetryDestinations.create({
    endpoint_url: "https://gateway.example.com/otlp",
    headers: { authorization: "Bearer YOUR_OBSERVABILITY_API_KEY" },
    traces: { content_mode: "metadata_only" },
    workspaces: { type: "all" }
  });

  console.log(destination.id);
  ```

  ```csharp C#
  using Anthropic.Models.Beta.Organization.TelemetryDestinations;

  AnthropicClient client = new();

  var destination = await client.Beta.Organization.TelemetryDestinations.Create(
      new()
      {
          EndpointUrl = "https://gateway.example.com/otlp",
          Headers = new Dictionary<string, string>
          {
              ["authorization"] = "Bearer YOUR_OBSERVABILITY_API_KEY",
          },
          Traces = new() { ContentMode = BetaTelemetryDestinationContentMode.MetadataOnly },
          Workspaces = new BetaTelemetryDestinationWorkspacesAllParams(),
      }
  );

  Console.WriteLine(destination.ID);
  ```

  ```go Go
  client := anthropic.NewClient()

  destination, err := client.Beta.Organization.TelemetryDestinations.New(
  	context.Background(),
  	anthropic.BetaOrganizationTelemetryDestinationNewParams{
  		EndpointURL: "https://gateway.example.com/otlp",
  		Headers: map[string]string{
  			"authorization": "Bearer YOUR_OBSERVABILITY_API_KEY",
  		},
  		Traces: anthropic.BetaTelemetryDestinationTracesParams{
  			ContentMode: anthropic.BetaTelemetryDestinationContentModeMetadataOnly,
  		},
  		Workspaces: anthropic.BetaTelemetryDestinationWorkspacesParamsUnion{
  			OfAll: &anthropic.BetaTelemetryDestinationWorkspacesAllParams{},
  		},
  	},
  )
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(destination.ID)
  ```

  ```java Java
  import com.anthropic.core.JsonValue;
  import com.anthropic.models.beta.organization.telemetrydestinations.BetaTelemetryDestinationContentMode;
  import com.anthropic.models.beta.organization.telemetrydestinations.BetaTelemetryDestinationTracesParams;
  import com.anthropic.models.beta.organization.telemetrydestinations.BetaTelemetryDestinationWorkspacesAllParams;
  import com.anthropic.models.beta.organization.telemetrydestinations.TelemetryDestinationCreateParams;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      var params = TelemetryDestinationCreateParams.builder()
          .endpointUrl("https://gateway.example.com/otlp")
          .headers(TelemetryDestinationCreateParams.Headers.builder()
              .putAdditionalProperty("authorization", JsonValue.from("Bearer YOUR_OBSERVABILITY_API_KEY"))
              .build())
          .traces(BetaTelemetryDestinationTracesParams.builder()
              .contentMode(BetaTelemetryDestinationContentMode.METADATA_ONLY)
              .build())
          .workspaces(BetaTelemetryDestinationWorkspacesAllParams.builder().build())
          .build();
      var destination = client.beta().organization().telemetryDestinations().create(params);

      IO.println(destination.id());
  }
  ```

  ```php PHP
  $client = new Client();

  $destination = $client->beta->organization->telemetryDestinations->create(
      endpointURL: 'https://gateway.example.com/otlp',
      headers: ['authorization' => 'Bearer YOUR_OBSERVABILITY_API_KEY'],
      traces: ['contentMode' => 'metadata_only'],
      workspaces: ['type' => 'all'],
  );

  echo "{$destination->id}\n";
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  destination = client.beta.organization.telemetry_destinations.create(
    endpoint_url: "https://gateway.example.com/otlp",
    headers: {authorization: "Bearer YOUR_OBSERVABILITY_API_KEY"},
    traces: {content_mode: :metadata_only},
    workspaces: {type: :all}
  )

  puts destination.id
  ```
</CodeGroup>

作成リクエストは**Provider**を除くConsoleの設定を受け取るため、オブザーバビリティプラットフォームのエンドポイントURLとヘッダーはご自身で入力してください。オブザーバビリティプラットフォームが受け付ける量に合わせて、`traces.max_content_bytes` (csharp, go: `Traces.MaxContentBytes`; java, php: `traces.maxContentBytes`)をバイト単位で設定します（[コンテンツの制限](https://platform.claude.com/docs/ja/manage-claude/opentelemetry#content-limits)を参照）。宛先の一覧表示、変更、削除、またはワークスペースを1つ追加または削除するには、テレメトリ宛先APIのその他のメソッドを使用します。

## 2. 宛先のワークスペースを選択する

宛先は、対象とするワークスペースのスパンを受け取ります。ワークスペースは宛先を追加するときに選択します。**Workspaces**で、次のいずれかを選択します。

* **All：** [Default Workspace](https://platform.claude.com/docs/ja/manage-claude/workspaces#how-workspaces-work)や後から作成されるワークスペースを含む、組織内のすべてのワークスペース。
* **Selected：** 選択したワークスペースのみ。
* **All except：** **All**と同様ですが、選択したワークスペースを除きます。

**Selected**または**All except**の場合は、オプションの下に表示される検索ボックスでワークスペースを選択します。後から宛先のワークスペースを変更するには、**Workspace**フィルターが**All**を表示している状態で、[OpenTelemetry設定ページ](https://platform.claude.com/settings/telemetry-destinations)でその宛先の**More actions**メニューを開きます。**Edit**をクリックし、別の**Workspaces**オプションを選択するか、検索ボックスでワークスペースを変更します。

組織で開発者ロールを持ち、あるワークスペースでWorkspace Adminロールを持っている場合は、**Selected**の宛先にそのワークスペースを追加したり、宛先から削除したりできます。**Workspace**フィルターをそのワークスペースに設定してから、宛先の**More actions**メニューを開きます。Claude Platform on AWSでは、ConsoleにWorkspace Adminロールはありません。その場合は、[IAMポリシー](https://platform.claude.com/docs/ja/api/claude-platform-on-aws-iam-actions)によって、宛先にワークスペースを追加したり、宛先から削除したりできるユーザーが決まります。

APIは、[リクエストまたはセッションが実行されるワークスペース](https://platform.claude.com/docs/ja/manage-claude/workspaces#api-keys-and-resource-scoping)を対象とする有効なすべての宛先にスパンを送信します。

## 3. スパンが届いていることを確認する

1. Consoleで、その宛先の対象となるワークスペースを選択し、[playground](https://platform.claude.com/playground)でMessages APIリクエストを送信します。アプリケーションからMessages APIリクエストを送信するか、そのワークスペースでManaged Agentsセッションを開始することもできます。セッションを開始するには、[Claude Managed Agentsを始める](https://platform.claude.com/docs/ja/managed-agents/quickstart)の手順に従ってください。
2. Consoleの[OpenTelemetry設定ページ](https://platform.claude.com/settings/telemetry-destinations)で、宛先の**Delivery**列に**Healthy**と表示されていることを確認します。これには1分ほどかかる場合があります。
3. オブザーバビリティプラットフォームで`service.name` = `claude-platform`でフィルタリングし、リクエストのスパンを見つけます。

列に**Failing**と表示されている場合は、ポインターを合わせると最後のエラーが表示されます。考えられる原因については、[配信エラー](https://platform.claude.com/docs/ja/manage-claude/opentelemetry/api#delivery-errors)を参照してください。

## 4. APIスパンを独自のトレースに接続する

デフォルトでは、Messages APIリクエストまたはManaged AgentsセッションのAPIスパンは、それぞれ独立したトレースに含まれます。これらをアプリケーションのトレースに接続すると、独自のスパンの下にネストされます。

APIは、各リクエストのトレースコンテキストをW3Cの[`traceparent`ヘッダー](https://www.w3.org/TR/trace-context/)から読み取ります。ヘッダー内のsampledフラグがオフの場合、APIはそのリクエストのスパンおよびその下のスパンを出力しません。Claude Platform on AWSはまだこのヘッダーをサポートしていません。Claude Platform on AWSに送信するリクエストのスパンは、sampledフラグがオフの場合でも、常に独自のトレースを開始します。

<Tabs>
  <Tab title="Claude SDKを使用する場合">
    APIスパンを接続するには、アプリケーションで[SDKトレースを設定](https://platform.claude.com/docs/ja/manage-claude/opentelemetry/sdk)し、独自のスパンの内側からSDKを呼び出します。すると、独自のスパンにSDKスパンが含まれ、SDKスパンにAPIスパンが含まれます。これらのスパンをすべて同じオブザーバビリティプラットフォームに送信すると、プラットフォームはそれらを1つのトレースとして表示できます。[Messages APIリクエスト](https://platform.claude.com/docs/ja/manage-claude/opentelemetry#a-messages-api-request)と[Managed Agentsセッション](https://platform.claude.com/docs/ja/manage-claude/opentelemetry#a-managed-agents-session)のトレース例を参照してください。

    次の例では、独自のスパンの内側でセッションにユーザーメッセージを送信します：

    <CodeGroup exclude="shell">
      ```python Python
      from opentelemetry import trace

      tracer = trace.get_tracer("my-service")

      with tracer.start_as_current_span("summarize_issues"):
          client.beta.sessions.events.send(
              session.id,
              events=[
                  {
                      "type": "user.message",
                      "content": [{"type": "text", "text": "Summarize the open issues"}],
                  },
              ],
          )
      ```

      ```typescript TypeScript
      import { trace } from "@opentelemetry/api";

      const tracer = trace.getTracer("my-service");

      await tracer.startActiveSpan("summarize_issues", async (span) => {
        try {
          await client.beta.sessions.events.send(session.id, {
            events: [
              {
                type: "user.message",
                content: [{ type: "text", text: "Summarize the open issues" }]
              }
            ]
          });
        } finally {
          span.end();
        }
      });
      ```

      ```csharp C#
      using System.Diagnostics;

      // このソースを、com.anthropic.sdk.csharp と並べて tracer provider に追加します。
      var source = new ActivitySource("MyService");

      using (source.StartActivity("summarize_issues"))
      {
          // parameters には user.message イベントが格納されます。
          await client.Beta.Sessions.Events.Send(session.ID, parameters);
      }
      ```

      ```go Go
      // span を含むコンテキストを渡します。
      ctx, span := otel.Tracer("my-service").Start(ctx, "summarize_issues")
      defer span.End()

      // params には user.message イベントが格納されています。
      _, err := client.Beta.Sessions.Events.Send(ctx, session.ID, params)
      ```

      ```java Java
      Tracer tracer = GlobalOpenTelemetry.getTracer("my-service");
      Span span = tracer.spanBuilder("summarize_issues").startSpan();

      try (Scope scope = span.makeCurrent()) {
          // params には user.message イベントが格納されます。
          client.beta().sessions().events().send(session.id(), params);
      } finally {
          span.end();
      }
      ```

      ```php PHP
      use OpenTelemetry\API\Globals;

      $tracer = Globals::tracerProvider()->getTracer('my-service');
      $span = $tracer->spanBuilder('summarize_issues')->startSpan();
      $scope = $span->activate();

      try {
          $client->beta->sessions->events->send(
              $session->id,
              events: [
                  [
                      'type' => 'user.message',
                      'content' => [
                          ['type' => 'text', 'text' => 'Summarize the open issues'],
                      ],
                  ],
              ],
          );
      } finally {
          $scope->detach();
          $span->end();
      }
      ```

      ```ruby Ruby
      tracer = OpenTelemetry.tracer_provider.tracer("my-service")

      tracer.in_span("summarize_issues") do
        client.beta.sessions.events.send_(
          session.id,
          events: [
            {
              type: "user.message",
              content: [{type: "text", text: "Summarize the open issues"}]
            }
          ]
        )
      end
      ```
    </CodeGroup>

    SDKはアプリケーションのプロパゲーターを使用して`traceparent`ヘッダーを書き込み、その中のsampledフラグはサンプラーに従います。アプリケーションがB3など、W3Cトレースコンテキスト以外のプロパゲーターを使用している場合は、W3Cトレースコンテキストのプロパゲーターも追加してください。
  </Tab>

  <Tab title="その他のクライアントを使用する場合">
    たとえばManaged Agentsセッションを作成するときやユーザーメッセージを送信するときに、現在のスパンのトレースコンテキストをリクエストヘッダーにコピーします：

    <CodeGroup exclude="shell:CLI">
      ```bash cURL
      # TRACEPARENT は、ご自身のサービス内でアクティブなスパンの traceparent です。
      # 例: 00-<trace-id>-<span-id>-01。
      curl -fsSL "https://api.anthropic.com/v1/sessions/$SESSION_ID/events" \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -H "anthropic-version: 2023-06-01" \
        -H "anthropic-beta: managed-agents-2026-04-01" \
        -H "content-type: application/json" \
        -H "traceparent: $TRACEPARENT" \
        -d '{
          "events": [
            {
              "type": "user.message",
              "content": [{"type": "text", "text": "Summarize the open issues"}]
            }
          ]
        }'
      ```

      ```python Python
      import os
      import httpx2
      from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator

      headers = {
          "x-api-key": os.environ["ANTHROPIC_API_KEY"],
          "anthropic-version": "2023-06-01",
          "anthropic-beta": "managed-agents-2026-04-01",
          "content-type": "application/json",
      }
      # アクティブなスパンのトレースコンテキストをリクエストヘッダーにコピーします。
      TraceContextTextMapPropagator().inject(headers)

      httpx2.post(
          f"https://api.anthropic.com/v1/sessions/{os.environ['SESSION_ID']}/events",
          headers=headers,
          json={
              "events": [
                  {
                      "type": "user.message",
                      "content": [{"type": "text", "text": "Summarize the open issues"}],
                  },
              ],
          },
      )
      ```

      ```typescript TypeScript
      import { context, defaultTextMapSetter } from "@opentelemetry/api";
      import { W3CTraceContextPropagator } from "@opentelemetry/core";

      const headers: Record<string, string> = {
        "x-api-key": process.env.ANTHROPIC_API_KEY!,
        "anthropic-version": "2023-06-01",
        "anthropic-beta": "managed-agents-2026-04-01",
        "content-type": "application/json"
      };
      // アクティブな span のトレースコンテキストをリクエストヘッダーにコピーします。
      new W3CTraceContextPropagator().inject(context.active(), headers, defaultTextMapSetter);

      await fetch(`https://api.anthropic.com/v1/sessions/${process.env.SESSION_ID}/events`, {
        method: "POST",
        headers,
        body: JSON.stringify({
          events: [
            {
              type: "user.message",
              content: [{ type: "text", text: "Summarize the open issues" }]
            }
          ]
        })
      });
      ```

      ```csharp C#
      using System.Diagnostics;
      using System.Net.Http.Json;
      using OpenTelemetry;
      using OpenTelemetry.Context.Propagation;

      using var httpClient = new HttpClient();
      using var request = new HttpRequestMessage(
          HttpMethod.Post,
          $"https://api.anthropic.com/v1/sessions/{Environment.GetEnvironmentVariable("SESSION_ID")}/events")
      {
          // JsonContent は content-type ヘッダーを設定します。
          Content = JsonContent.Create(new
          {
              events = new[]
              {
                  new
                  {
                      type = "user.message",
                      content = new[] { new { type = "text", text = "Summarize the open issues" } },
                  },
              },
          }),
      };
      request.Headers.Add("x-api-key", Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY"));
      request.Headers.Add("anthropic-version", "2023-06-01");
      request.Headers.Add("anthropic-beta", "managed-agents-2026-04-01");

      // アクティブなスパンのトレースコンテキストをリクエストヘッダーにコピーします。
      new TraceContextPropagator().Inject(
          new PropagationContext(Activity.Current?.Context ?? default, Baggage.Current),
          request,
          (carrier, key, value) => carrier.Headers.Add(key, value));

      await httpClient.SendAsync(request);
      ```

      ```go Go
      import (
      	"context"
      	"net/http"
      	"os"
      	"strings"

      	"go.opentelemetry.io/otel/propagation"
      )

      func sendMessage(ctx context.Context) error {
      	body := strings.NewReader(`{
      		"events": [
      			{
      				"type": "user.message",
      				"content": [{"type": "text", "text": "Summarize the open issues"}]
      			}
      		]
      	}`)
      	req, err := http.NewRequestWithContext(ctx, http.MethodPost,
      		"https://api.anthropic.com/v1/sessions/"+os.Getenv("SESSION_ID")+"/events", body)
      	if err != nil {
      		return err
      	}
      	req.Header.Set("x-api-key", os.Getenv("ANTHROPIC_API_KEY"))
      	req.Header.Set("anthropic-version", "2023-06-01")
      	req.Header.Set("anthropic-beta", "managed-agents-2026-04-01")
      	req.Header.Set("content-type", "application/json")

      	// アクティブな span のトレースコンテキストをリクエストヘッダーにコピーします。
      	propagation.TraceContext{}.Inject(ctx, propagation.HeaderCarrier(req.Header))

      	resp, err := http.DefaultClient.Do(req)
      	if err != nil {
      		return err
      	}
      	return resp.Body.Close()
      }
      ```

      ```java Java
      import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
      import io.opentelemetry.context.Context;
      import java.net.URI;
      import java.net.http.HttpClient;
      import java.net.http.HttpRequest;
      import java.net.http.HttpResponse;

      void main() throws Exception {
          var request = HttpRequest.newBuilder(URI.create(
                  "https://api.anthropic.com/v1/sessions/" + System.getenv("SESSION_ID") + "/events"))
              .header("x-api-key", System.getenv("ANTHROPIC_API_KEY"))
              .header("anthropic-version", "2023-06-01")
              .header("anthropic-beta", "managed-agents-2026-04-01")
              .header("content-type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString("""
                  {
                    "events": [
                      {
                        "type": "user.message",
                        "content": [{"type": "text", "text": "Summarize the open issues"}]
                      }
                    ]
                  }
                  """));

          // アクティブな span のトレースコンテキストをリクエストヘッダーにコピーします。
          W3CTraceContextPropagator.getInstance()
              .inject(Context.current(), request, HttpRequest.Builder::header);

          HttpClient.newHttpClient().send(request.build(), HttpResponse.BodyHandlers.ofString());
      }
      ```

      ```php PHP
      use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;

      $headers = [
          'x-api-key' => getenv('ANTHROPIC_API_KEY'),
          'anthropic-version' => '2023-06-01',
          'anthropic-beta' => 'managed-agents-2026-04-01',
          'content-type' => 'application/json',
      ];
      // アクティブなスパンのトレースコンテキストをリクエストヘッダーにコピーします。
      TraceContextPropagator::getInstance()->inject($headers);

      $ch = curl_init('https://api.anthropic.com/v1/sessions/' . getenv('SESSION_ID') . '/events');
      curl_setopt_array($ch, [
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_HTTPHEADER => array_map(
              static fn ($name, $value) => "$name: $value",
              array_keys($headers),
              $headers,
          ),
          CURLOPT_POSTFIELDS => json_encode([
              'events' => [
                  [
                      'type' => 'user.message',
                      'content' => [
                          ['type' => 'text', 'text' => 'Summarize the open issues'],
                      ],
                  ],
              ],
          ]),
      ]);
      curl_exec($ch);
      ```

      ```ruby Ruby
      require "json"
      require "net/http"
      require "opentelemetry"

      headers = {
        "x-api-key" => ENV.fetch("ANTHROPIC_API_KEY"),
        "anthropic-version" => "2023-06-01",
        "anthropic-beta" => "managed-agents-2026-04-01",
        "content-type" => "application/json"
      }
      # アクティブなスパンのトレースコンテキストをリクエストヘッダーにコピーします。
      OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator.inject(headers)

      Net::HTTP.post(
        URI("https://api.anthropic.com/v1/sessions/#{ENV.fetch("SESSION_ID")}/events"),
        {
          events: [
            {
              type: "user.message",
              content: [{type: "text", text: "Summarize the open issues"}]
            }
          ]
        }.to_json,
        headers
      )
      ```
    </CodeGroup>
  </Tab>
</Tabs>

Messages APIは、[MCPコネクター](https://platform.claude.com/docs/ja/agents-and-tools/mcp-connector)でMCPサーバーを接続した場合、そのMCPサーバーにもトレースを引き継ぐため、MCPサーバーは独自のスパンをAPIスパンの下に配置できます。APIがMCPサーバーに送信する各リクエストと通知には、`params._meta`にW3Cの`traceparent`が含まれます。`tools/call`リクエストでは、そのツール使用の[`anthropic.mcp_tool_use`](https://platform.claude.com/docs/ja/api/opentelemetry/spans#anthropic-tool-use-anthropic-mcp-tool-use-and-anthropic-custom-tool-use)スパンを参照します。その他のメッセージでは[`anthropic.messages.create`](https://platform.claude.com/docs/ja/api/opentelemetry/spans#anthropic-messages-create)スパンを参照します。`traceparent`ヘッダーのsampledフラグがオフのリクエストなど、APIがトレースしないリクエストについては、APIは`traceparent`を送信しません。

## 次のステップ

<CardGroup cols={2}>
  <Card title="SDKトレースを設定する" icon="code-brackets" href="https://platform.claude.com/docs/ja/manage-claude/opentelemetry/sdk">
    クライアントのオブザーバビリティを得られます。
  </Card>

  <Card title="トレースの例を見る" icon="sitemap" href="https://platform.claude.com/docs/ja/manage-claude/opentelemetry#example-traces-and-how-to-read-them">
    クライアントからClaude APIへのリクエストを追跡します。
  </Card>
</CardGroup>

## 配信とヘルス

APIが宛先に送信するスパンには、次のルールが適用されます。

* **少なくとも1回：** 宛先は同じスパンを複数回受け取る場合があります。重複を除去するには、トレースIDとスパンIDを使用してください。
* **ベストエフォート：** スパンは配信前に失われる場合があります。APIは失われたスパンを再送することはできません。
* **圧縮：** APIは各配信の最初のリクエストをgzipで圧縮し、ヘッダー`Content-Encoding: gzip`を設定します。エンドポイントがそのリクエストに`400`または`415`レスポンスを返した場合、APIは同じスパンを圧縮せずにすぐに再送します。
* **再試行：** タイムアウト、接続・TLS・DNSの失敗、または`408`、`429`、`5xx`レスポンスの後、APIは限られた回数だけ後で配信を再試行します。その他の失敗については再試行しません。
* **タイムアウト：** 各リクエストについて、エンドポイントは5秒以内にTLSハンドシェイクを完了し、5秒以内にレスポンスヘッダーを送信する必要があります。各配信は、圧縮なしでの再送信を含めて合計10秒でタイムアウトします。
* **ユーザーエージェント：** 各リクエストにはヘッダー`User-Agent: Claude-Platform`が含まれます。

**Delivery**列には各宛先の状態が表示されます。状態の反映は最大1分遅れる場合があります。

| 配信状態         | 意味                                                 |
| ------------ | -------------------------------------------------- |
| **Healthy**  | 最後の配信が成功しました。                                      |
| **Failing**  | 最後の配信が失敗しました。エラーを確認するには、**Failing**にポインターを合わせます。   |
| **No data**  | APIはまだ配信を試行していません。                                 |
| **Disabled** | 宛先はスパンを受け取りません。理由を確認するには、**Disabled**にポインターを合わせます。 |

APIは次の場合に宛先を無効にします：

* エンドポイントが`3xx`リダイレクトを送信した場合。
* エンドポイントのホスト名がパブリックではないIPアドレスに解決された場合。
* 24時間にわたってすべての配信が失敗した場合。

APIは無効化された宛先にスパンを送信しません。エクスポートを再開するには、原因を修正してください。その後、[OpenTelemetry設定ページ](https://platform.claude.com/settings/telemetry-destinations)の**Workspace**フィルターが**All**を表示している状態で、宛先の**More actions**メニューから**Enable**をクリックします。エクスポートは約1分以内に再開されます。

宛先を変更するには、**Workspace**フィルターが**All**を表示している状態で、その**More actions**メニューを開きます。次に、**Edit**、**Disable**、**Enable**、または**Delete**をクリックします。**OTLP endpoint URL**のホストを変更した場合は、ヘッダーの値を再入力してください。宛先に**OTLP traces endpoint URL**がある場合は、同じ新しいホストを指定するか、クリアしてください。

## 制限

| 制限                     | 値         |
| ---------------------- | --------- |
| 組織あたりの送信先（無効化されたものを含む） | 10        |
| 送信先に選択するワークスペース数       | 1,000     |
| 送信先あたりのリクエストヘッダー       | 20        |
| ヘッダー名の長さ               | 128バイト    |
| ヘッダー値の長さ               | 4,096バイト  |
| すべてのヘッダー名と値の合計の長さ      | 16,384バイト |
| エンドポイントURLの長さ          | 2,048文字   |

## トラブルシューティング

| 問題                                                   | 確認事項                                                                                                                                                                                                                               |
| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| APIスパンがない                                            | ワークスペースには、そのワークスペースを対象とする有効な送信先が必要です。[宛先のワークスペースを選択する](https://platform.claude.com/docs/ja/manage-claude/opentelemetry/api#choose-workspaces-for-a-destination)を参照してください。送信先がワークスペースを対象にし始めた後、そのワークスペースからのスパンが届くまでに最大1分かかる場合があります。 |
| **Delivery**列に**Failing**と表示される                      | ポインターを合わせると、最後のエラーが表示されます。考えられる原因を確認するには、[配信エラー](https://platform.claude.com/docs/ja/manage-claude/opentelemetry/api#delivery-errors)を参照してください。                                                                                    |
| **Delivery**列に**Disabled**と表示される                     | ポインターを合わせると、その理由が表示されます。理由については、[APIが送信先を無効にする場合](https://platform.claude.com/docs/ja/manage-claude/opentelemetry/api#delivery-and-health)を参照してください。                                                                               |
| 送信先が**Full content**に設定されているのに、スパンにプロンプトやレスポンスが含まれない | 組織がAnthropicとの間でHIPAA、FERPA、またはK-12のデータ取り扱い制限を設けている可能性があります。[コンテンツモード](https://platform.claude.com/docs/ja/manage-claude/opentelemetry#choose-a-content-mode)を参照してください。                                                            |

### 配信エラー

配信が失敗すると、**Delivery**列に**Failing**が表示されます。ポインターを合わせてエラーを確認し、考えられる原因を特定します。

| エラー                                                 | 考えられる原因                                                                                                                          |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| HTTP error (status 401) または HTTP error (status 403) | 認証ヘッダーが間違っている                                                                                                                    |
| HTTP error (status 404)                             | **OTLP endpoint URL**または**OTLP traces endpoint URL**のパスが間違っている                                                                   |
| DNS resolution failure                              | エンドポイントのホスト名を解決できない                                                                                                              |
| TLS failure                                         | エンドポイントの証明書などに関するTLSの問題                                                                                                          |
| Timeout                                             | エンドポイントが時間内に応答しなかった。[配信タイムアウト](https://platform.claude.com/docs/ja/manage-claude/opentelemetry/api#delivery-and-health)を参照してください |
| Connection failure                                  | APIがエンドポイントに接続できなかった                                                                                                             |
