@adcp/sdk API Reference - v10.0.1
    Preparing search index...

    Class AgentClient

    Index

    Constructors

    Methods

    • Create an AgentClient backed by a pre-connected MCP Client instead of an HTTP endpoint. Useful for in-process compliance testing without spinning up a loopback HTTP server.

      MCP only. This factory wraps an MCP Client from @modelcontextprotocol/sdk. There is no equivalent in-process bridge for A2A today — for A2A agents, run them on a loopback HTTP server and use the standard AgentClient constructor with the agent's agent_uri.

      What this gives you over dispatchTestRequest: All client-side pipeline stages still apply — idempotency key auto-injection, request/response schema validation hooks, governance middleware, and the typed TaskResult<T> discriminated-union response shape. None of these apply when calling dispatchTestRequest() directly.

      Usage:

      import { Client } from '@modelcontextprotocol/sdk/client/index.js';
      import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
      import { AgentClient } from '@adcp/sdk';

      const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
      const mcpClient = new Client({ name: 'test', version: '1.0.0' });
      await Promise.all([
      mcpClient.connect(clientTransport),
      adcpServer.connect(serverTransport),
      ]);

      const agent = AgentClient.fromMCPClient(mcpClient, {
      validation: { requests: 'strict' },
      });
      const result = await agent.createMediaBuy({ ... });

      Unsupported methods on in-process instances: resolveCanonicalUrl, getWebhookUrl, registerWebhook, unregisterWebhook — these require HTTP and will throw Error with a descriptive message. Use getAgentId() / getAgentName() for identification instead.

      Parameters

      • mcpClient: Client

        An already-connected MCP Client (see example above).

      • config: InProcessAgentClientConfig = {}

        Optional narrowed config. HTTP-only fields are excluded.

      Returns AgentClient

    • Handle webhook from agent (async task completion or notifications)

      Parameters

      • payload: MCPWebhookPayload | Task | TaskStatusUpdateEvent

        Webhook payload from agent

      • taskType: string

        Task type (e.g create_media_buy) from url param or url part of the webhook delivery

      • operationId: string

        Operation id (e.g used for client app to track the operation) from the param or url part of the webhook delivery

      • Optionalsignature: WebhookHeaderValue

        Optional signature for verification (X-ADCP-Signature)

      • Optionaltimestamp: WebhookHeaderValue

        Optional timestamp for verification (X-ADCP-Timestamp)

      • OptionalrawBody: string | Uint8Array<ArrayBufferLike> | Buffer<ArrayBufferLike>

      Returns Promise<boolean>

      Whether webhook was handled successfully

    • Verify webhook signature using HMAC-SHA256 per AdCP spec.

      Prefer passing the raw HTTP body string for correct cross-language interop. Passing a parsed object still works but re-serializes with JSON.stringify, which may not match the sender's byte representation.

      Parameters

      • rawBodyOrPayload: unknown

        Raw HTTP body string (preferred) or parsed payload object (deprecated)

      • signature: WebhookHeaderValue

        X-ADCP-Signature header value (format: "sha256=...")

      • timestamp: WebhookHeaderValue

        X-ADCP-Timestamp header value (Unix timestamp)

      Returns boolean

      true if signature is valid

    • Discover available advertising products.

      By default, response products are augmented with the AdCP 3.1 format_options[] declaration (the V2 mental model). When the seller emitted v1 format_ids[], the SDK projects them via the AAO canonical-formats catalog so buyers always read the same V2 shape regardless of wire version. The original format_ids[] is preserved alongside format_options[] (additive — 7.x callers reading format_ids keep working).

      Projection diagnostics surface on result.data.projection.diagnostics (structured source: 'sdk' markers; codes mirror the spec's error-code vocabulary plus three SDK-local codes — see the projection module's ProjectionDiagnostic type for the full set).

      Pass { project: false } to opt out and receive the raw wire response unmodified — useful for storyboard / compliance harnesses asserting exact seller emission. The opt-out narrows the return type back to GetProductsResponse (no projection envelope, no guaranteed format_options[]).

      The 8.0 release narrows further by removing format_ids[] from the public Product type entirely.

      Parameters

      Returns Promise<TaskResult<V2AugmentedGetProductsResponse>>

    • Discover available advertising products.

      By default, response products are augmented with the AdCP 3.1 format_options[] declaration (the V2 mental model). When the seller emitted v1 format_ids[], the SDK projects them via the AAO canonical-formats catalog so buyers always read the same V2 shape regardless of wire version. The original format_ids[] is preserved alongside format_options[] (additive — 7.x callers reading format_ids keep working).

      Projection diagnostics surface on result.data.projection.diagnostics (structured source: 'sdk' markers; codes mirror the spec's error-code vocabulary plus three SDK-local codes — see the projection module's ProjectionDiagnostic type for the full set).

      Pass { project: false } to opt out and receive the raw wire response unmodified — useful for storyboard / compliance harnesses asserting exact seller emission. The opt-out narrows the return type back to GetProductsResponse (no projection envelope, no guaranteed format_options[]).

      The 8.0 release narrows further by removing format_ids[] from the public Product type entirely.

      Parameters

      Returns Promise<TaskResult<GetProductsResponse>>

    • Create a new media buy.

      3.1+ format-option write flow (preferred at 3.1.0-beta.5+). After getProducts() returns the V2-augmented response (format_options[] auto-populated), pick declarations by format_option_id and use packageRefsForFormatOptions to author the package. The helper emits BOTH format_option_refs[] (the 3.1+ path) AND format_ids[] (legacy named-format dual emission) so a single request works against both format-option-aware and legacy sellers.

      import { packageRefsForFormatOptions } from '@adcp/sdk/v2/projection';

      const { data: { products } } = await agent.getProducts({ brief: '...' });
      const product = products[0];

      await agent.createMediaBuy({
      packages: [{
      package_id: 'pkg-1',
      product_id: product.product_id,
      pricing_option_id: product.pricing_options[0].pricing_option_id,
      ...packageRefsForFormatOptions(product, ['nytimes_mrec', 'nytimes_video_30s']),
      // ↑ spreads `{ format_option_refs, format_ids? }`
      budget: { currency: 'USD', total: 5000 },
      }],
      // ...
      });

      The resulting wire payload for the package looks like:

      {
      "package_id": "pkg-1",
      "product_id": "...",
      "pricing_option_id": "...",
      "format_option_refs": [
      {"scope": "product", "format_option_id": "nytimes_mrec"},
      {"scope": "product", "format_option_id": "nytimes_video_30s"}
      ],
      "format_ids": [
      {"agent_url": "https://creative.adcontextprotocol.org/", "id": "display_300x250_image"},
      {"agent_url": "https://creative.adcontextprotocol.org/", "id": "video_standard_30s"}
      ],
      "budget": {"currency": "USD", "total": 5000}
      }

      format_ids is omitted entirely when every chosen format option is V2-only (the spec's "neither present" fallback fires for v1 sellers in that case).

      Inline creative fallback. Sellers that do not advertise a creative library (supportsSyncCreatives(await agent.getCapabilities()) === false) can still accept package-scoped creative uploads when they advertise caps.features.inlineCreativeManagement. Use inlineCreativesForPackages(packages, creatives, { assignments }) to project sync_creatives-style creative assets into create-media-buy package payloads without rewriting a raw sync_creatives call. If using assignments for create payloads, give each package a stable key such as context.buyer_ref, or pass a custom packageId resolver.

      For adopters writing strictly to v1 sellers — or for products whose format_options[] entries don't publish format_option_id — see the legacyFormatIdsFromOptions / tryLegacyFormatIdsFromOptions / legacyFormatIdsForFormatOption helpers in @adcp/sdk/v2/projection.

      packageRefsForFormatOptions throws FormatOptionRefsLookupError with a normalized .code in { 'unknown_format_option_id' | 'format_option_refs_not_published' | 'empty_input' | 'invalid_product' } — branch on .code to fall back to the legacy* helpers when the product is V1-shape only. See the helper JSDoc for the full recovery example.

      Parameters

      Returns Promise<TaskResult<CreateMediaBuyResponse>>

    • Return the seller's declared adcp.idempotency.replay_ttl_seconds, or throw when a v3 seller omits the (required) declaration.

      Returns undefined for v2 agents — v2 pre-dates the idempotency envelope.

      Returns Promise<number | undefined>

    • Assert that the seller's capabilities corroborate this client's pinned AdCP major (per getAdcpVersion()). Throws VersionUnsupportedError otherwise. Set ADCP_ALLOW_V2=1 to bypass.

      Parameters

      • taskType: string = 'request'

      Returns Promise<void>

    • Continue the conversation with a natural language message

      Type Parameters

      • T = any

      Parameters

      • message: string

        Natural language message to send to the agent

      • OptionalinputHandler: InputHandler

        Handler for any clarification requests

      • Optionaloptions: TaskOptions

      Returns Promise<TaskResult<T>>

      const agent = multiClient.agent('my-agent');
      await agent.getProducts({ brief: 'Tech products' });

      // Continue the conversation
      const refined = await agent.continueConversation(
      'Focus only on laptops under $1000'
      );
    • Clear the conversation context (start fresh).

      Equivalent to resetContext() — clears both the retained contextId and any pending server-side taskId, and drops cached history.

      Returns void

    • Reset conversation state. Call with no args to start a fresh conversation; pass a seed to rehydrate a persisted session id (e.g., across a process restart).

      Always clears the retained pending-task handle — a persisted contextId places the next send into the same server-side session, but any old taskId is stale.

      Parameters

      • Optionalseed: string

      Returns void

    • Get the pending server-side taskId from the last non-terminal response, if any. Populated when the server returned input-required / working / submitted / auth-required; cleared when the task reaches a terminal state.

      Persist this alongside getContextId() if you need to resume a specific task (not just a conversation) across a process restart.

      Returns string | undefined

    • Get the canonical base URL for this agent

      Returns the canonical URL if already resolved, or computes it synchronously. For guaranteed canonical URL (especially for A2A), use resolveCanonicalUrl() first.

      Returns string

    • Resolve and return the canonical base URL for this agent

      For A2A: Fetches the agent card and uses its 'url' field For MCP: Performs endpoint discovery and strips /mcp suffix

      Not supported on in-process instances (created via fromMCPClient). Use getAgentId() / getAgentName() for identification instead.

      Returns Promise<string>

    • Get agent information including capabilities

      Parameters

      • Optionaloptions: Pick<TaskOptions, "signal" | "transport">

      Returns Promise<
          {
              name: string;
              description?: string;
              protocol: "mcp"
              | "a2a";
              url: string;
              tools: {
                  name: string;
                  description?: string;
                  inputSchema?: Record<string, unknown>;
                  parameters?: string[];
              }[];
          },
      >

    • Get detailed information about a specific task

      Parameters

      • taskId: string

      Returns Promise<TaskInfo | null>

    • Subscribe to task notifications for this agent

      Parameters

      • callback: (task: TaskInfo) => void

      Returns () => void

    • Subscribe to all task events

      Parameters

      • callbacks: {
            onTaskCreated?: (task: TaskInfo) => void;
            onTaskUpdated?: (task: TaskInfo) => void;
            onTaskCompleted?: (task: TaskInfo) => void;
            onTaskFailed?: (task: TaskInfo, error: string) => void;
        }

      Returns () => void

    • Generate webhook URL for a specific task and operation.

      Not supported on in-process instances (created via fromMCPClient). In-process clients have no HTTP listener to receive webhook callbacks.

      Parameters

      • taskType: string
      • operationId: string

      Returns string

    • Register webhook for task notifications.

      Not supported on in-process instances (created via fromMCPClient).

      Parameters

      • webhookUrl: string
      • OptionaltaskTypes: string[]

      Returns Promise<void>

    • Unregister webhook notifications.

      Not supported on in-process instances (created via fromMCPClient).

      Returns Promise<void>