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

# MCP レスポンス抽出

> MCP ツール結果から AdCP 成功レスポンスデータを抽出する方法: structuredContent、text フォールバック、クライアント実装要件。

このページは、MCP ツール結果から AdCP 成功レスポンスデータを抽出する規範的アルゴリズムを定義します。エラー抽出については [Transport Error Mapping](/docs/building/operating/transport-errors) を参照。

## 層の分離

| Path                                                                 | When                     | Data Source                                     |
| -------------------------------------------------------------------- | ------------------------ | ----------------------------------------------- |
| 成功抽出（このページ）                                                          | `isError` が欠如または `false` | `structuredContent` または `content[].text`        |
| エラー抽出（[transport-errors](/docs/building/operating/transport-errors)） | `isError: true`          | `structuredContent.adcp_error` または text フォールバック |

クライアントは、どの抽出パスを使うかを決める前に `isError` を確認しなければなりません（MUST）。`isError: true` のレスポンスは、非エラーデータを持つ `structuredContent` を含んでいても、成功レスポンスとして処理してはなりません（MUST NOT）。

## 抽出アルゴリズム

クライアントは、この順序で MCP ツール結果から AdCP データを抽出しなければなりません（MUST）:

1. **ガード: エラーレスポンスを拒否。** `isError` が truthy なら null を返す。エラー抽出は別のパス。
2. **`structuredContent`** — 存在し非配列オブジェクトなら、それを返す。唯一のキーが `adcp_error` なら null を返す（これは `isError` フラグを欠くエラーレスポンス）。
3. **Text フォールバック** — `content[]` アイテムを配列順で反復。`type === 'text'` の各アイテムについて、1MB サイズ制限を強制し、次に `JSON.parse` を試みる。結果が非配列オブジェクトなら、それを返す。パースに失敗する、非オブジェクトとしてパースされる、または `adcp_error` キーのみを含むアイテムはスキップ。
4. **構造化データが見つからない** — null を返す。レスポンスは機械可読な AdCP データのないプレーンテキスト。

<CodeGroup>
  ```javascript MCP Client theme={null}
  function extractAdcpResponseFromMcp(response) {
    // 1. Error responses go through transport-errors extraction
    if (response.isError) return null;

    // 2. structuredContent (preferred — MCP 2025-03-26+)
    if (response.structuredContent != null
        && typeof response.structuredContent === 'object'
        && !Array.isArray(response.structuredContent)) {
      const sc = response.structuredContent;
      // adcp_error-only structuredContent is an error missing isError flag
      const keys = Object.keys(sc);
      if (keys.length === 1 && keys[0] === 'adcp_error') return null;
      return sc;
    }

    // 3. Text fallback — JSON.parse content[].text
    if (response.content && Array.isArray(response.content)) {
      for (const item of response.content) {
        if (item.type === 'text' && item.text) {
          if (item.text.length > 1_048_576) continue; // 1MB size limit
          try {
            const parsed = JSON.parse(item.text);
            if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
              // Skip adcp_error-only payloads (error missing isError flag)
              const keys = Object.keys(parsed);
              if (keys.length === 1 && keys[0] === 'adcp_error') continue;
              return parsed;
            }
          } catch { /* not JSON */ }
        }
      }
    }

    return null;
  }
  ```
</CodeGroup>

## 抽出パス

### structuredContent（推奨）

MCP 2025-03-26 は型付きツール結果のため `structuredContent` を導入しました。AdCP サーバーは完全なレスポンスペイロードをここに返します:

```json theme={null}
{
  "content": [{"type": "text", "text": "Found 3 products matching your brief."}],
  "structuredContent": {
    "status": "completed",
    "message": "Found 3 products",
    "products": [
      {"product_id": "ctv_sports_premium", "name": "Premium Sports CTV"},
      {"product_id": "ctv_news_standard", "name": "Standard News CTV"}
    ]
  }
}
```

`structuredContent` オブジェクトが AdCP レスポンスそのものです — タスク固有のフィールド（`products`、`media_buy_id`、`status` など）はネストではなくトップレベルにあります。

### Text フォールバック

古い MCP サーバー（2025-03-26 以前）はレスポンスを `content[].text` に JSON としてシリアライズします:

```json theme={null}
{
  "content": [
    {"type": "text", "text": "{\"status\":\"completed\",\"products\":[{\"product_id\":\"ctv_premium\"}]}"}
  ]
}
```

クライアントは JSON オブジェクトを生成する最初のテキストアイテムをパースします。`structuredContent` とテキスト JSON の両方が存在するとき、`structuredContent` が優先します。

## エラー抽出との関係

成功とエラーの抽出は補完的です:

```javascript theme={null}
function handleMcpResponse(response) {
  // Try error extraction first (only runs if isError is true)
  const error = extractAdcpErrorFromMcp(response);
  if (error) return handleError(error);

  // Then try success extraction
  const data = extractAdcpResponseFromMcp(response);
  if (data) return handleSuccess(data);

  // Plain text response — no structured data
  return handlePlainText(response.content);
}
```

## セキュリティ考慮事項

### セラー制御データ

`structuredContent` と `content[].text` のすべてのデータはセラー制御です。[Transport Error Mapping](/docs/building/operating/transport-errors#security-considerations) の同じプロンプトインジェクションとデータ境界要件が適用されます。

### サイズ制限

クライアントは処理前に最大ペイロードサイズを強制すべきです（SHOULD）。推奨制限は `structuredContent` に 1MB。text フォールバックについては、過大なペイロードからのメモリ枯渇を防ぐため `JSON.parse` の前に制限を適用します。

### プロトタイプ汚染

クライアントは、キーをフィルターせずに抽出されたレスポンスオブジェクトを `Object.assign` やスプレッド経由でアプリケーション状態にマージしてはなりません（MUST NOT）。`__proto__` や `constructor` のようなセラー制御のキーはプロトタイプ汚染をトリガーできます。マージ前に期待されるタスクレスポンススキーマに対して検証してください。

### 型混乱

クライアントは成功抽出の前に `isError` を確認しなければなりません（MUST）。このガードなしでは、クライアントはエラーレスポンスを成功データとして処理し、誤ったビジネスロジック（例: `RATE_LIMITED` エラーをプロダクトデータとして扱う）につながる可能性があります。

## クライアントライブラリ要件

この仕様を実装するクライアントライブラリは次をしなければなりません（MUST）:

1. **抽出前に `isError` を確認。** エラーレスポンスに null を返す。
2. **`structuredContent` を優先。** `structuredContent` が欠如するときのみテキストパースにフォールバック。
3. **パースされたテキストを検証。** `JSON.parse` から非配列オブジェクトのみを受け入れる。配列、文字列、数値、boolean、null を拒否。
4. **`adcp_error` のみの `structuredContent` を扱う。** `structuredContent` が `adcp_error` キーのみを含むとき、null を返す — これは `isError` フラグを欠くかもしれないエラーレスポンス。

## テストベクター

機械可読なテストベクターは [`/static/test-vectors/mcp-response-extraction.json`](https://adcontextprotocol.org/test-vectors/mcp-response-extraction.json) で利用可能です。各ベクターは次を含みます:

* `path`: 抽出パス（`structuredContent` または `text_fallback`）
* `response`: MCP ツール結果エンベロープ
* `expected_data`: 抽出されるべき AdCP データ（または `null`）

クライアントライブラリはこれらのベクターに対して抽出ロジックを検証すべきです（SHOULD）。

## 関連項目

* [Transport Error Mapping](/docs/building/operating/transport-errors) — MCP と A2A からのエラー抽出
* [A2A Response Extraction](/docs/building/by-layer/L0/a2a-response-extraction) — A2A の同等仕様
* [MCP Guide](/docs/building/by-layer/L0/mcp-guide) — MCP トランスポート統合
