@adcp/client API Reference - v3.3.3
    Preparing search index...

    Class SingleAgentClient

    Internal single-agent client implementation

    This is an internal implementation detail used by AgentClient and ADCPMultiAgentClient. External users should use AdCPClient (alias for ADCPMultiAgentClient) instead.

    Key features:

    • 🔒 Full type safety for all ADCP tasks
    • 💬 Conversation management with context preservation
    • 🔄 Input handler pattern for clarifications
    • ⏱️ Timeout and retry support
    • 🐛 Debug logging and observability
    • 🎯 Works with both MCP and A2A protocols
    Index

    Constructors

    Methods

    • Handle webhook from agent (async task completion)

      Accepts either:

      1. Standard WebhookPayload format (operation_id, task_type, result, etc.)
      2. Raw A2A task payload (artifacts, status, contextId, etc.) - will be transformed

      For A2A payloads, extracts the ADCP response from artifacts[0].parts[].data so handlers receive the unwrapped response, not the raw protocol structure.

      Parameters

      • payload: any

        Webhook payload from agent (WebhookPayload or raw A2A task)

      • Optionalsignature: string

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

      • Optionaltimestamp: string | number

        X-ADCP-Timestamp header (Unix timestamp)

      • OptionaltaskType: string

        Task type override (useful when not in payload, e.g., from URL path)

      Returns Promise<boolean>

      Whether webhook was handled successfully

      app.post('/webhook/:taskType', async (req, res) => {
      const signature = req.headers['x-adcp-signature'];
      const timestamp = req.headers['x-adcp-timestamp'];

      try {
      const handled = await client.handleWebhook(req.body, signature, timestamp, req.params.taskType);
      res.status(200).json({ received: handled });
      } catch (error) {
      res.status(401).json({ error: error.message });
      }
      });
    • Generate webhook URL using macro substitution

      Parameters

      • taskType: string

        Type of task (e.g., 'get_products', 'media_buy_delivery')

      • operationId: string

        Operation ID for this request

      Returns string

      Full webhook URL with macros replaced

      // With template: "https://myapp.com/webhook/{task_type}/{agent_id}/{operation_id}"
      const webhookUrl = client.getWebhookUrl('sync_creatives', 'op_123');
      // Returns: https://myapp.com/webhook/sync_creatives/agent_x/op_123

      // With template: "https://myapp.com/webhook?agent={agent_id}&op={operation_id}"
      const webhookUrl = client.getWebhookUrl('sync_creatives', 'op_123');
      // Returns: https://myapp.com/webhook?agent=agent_x&op=op_123
    • Create an HTTP webhook handler that automatically verifies signatures

      This helper creates a standard HTTP handler (Express/Next.js/etc.) that:

      • Extracts X-ADCP-Signature and X-ADCP-Timestamp headers
      • Verifies HMAC signature (if webhookSecret configured)
      • Validates timestamp freshness
      • Calls handleWebhook() with proper error handling

      Returns (req: any, res: any) => Promise<void>

      HTTP handler function compatible with Express, Next.js, etc.

      const client = new ADCPClient(agent, {
      webhookSecret: 'your-secret-key',
      handlers: {
      onSyncCreativesStatusChange: async (result) => {
      console.log('Creative synced:', result);
      }
      }
      });

      app.post('/webhook', client.createWebhookHandler());
      export default client.createWebhookHandler();
      
    • Verify webhook signature using HMAC-SHA256 per AdCP PR #86 spec

      Signature format: sha256={hex_signature} Message format: {timestamp}.{json_payload}

      Parameters

      • payload: any

        Webhook payload object

      • signature: string

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

      • timestamp: string | number

        X-ADCP-Timestamp header value (Unix timestamp)

      Returns boolean

      true if signature is valid

    • Execute any task by name with type safety

      Type Parameters

      • T = any

      Parameters

      • taskName: string

        Name of the task to execute

      • params: any

        Task parameters

      • OptionalinputHandler: InputHandler

        Handler for clarification requests

      • Optionaloptions: TaskOptions

        Task execution options

      Returns Promise<TaskResult<T>>

      const result = await client.executeTask(
      'get_products',
      { brief: 'Coffee brands' },
      handler
      );
    • Resume a deferred task using its token

      Type Parameters

      • T = any

      Parameters

      • token: string

        Deferred task token

      • inputHandler: InputHandler

        Handler to provide the missing input

      Returns Promise<TaskResult<T>>

      try {
      await client.createMediaBuy(params, handler);
      } catch (error) {
      if (error instanceof DeferredTaskError) {
      // Get human input and resume
      const result = await client.resumeDeferredTask(
      error.token,
      (context) => humanProvidedValue
      );
      }
      }
    • Continue an existing conversation with the agent

      Type Parameters

      • T = any

      Parameters

      • message: string

        Message to send to the agent

      • contextId: string

        Conversation context ID to continue

      • OptionalinputHandler: InputHandler

        Handler for any clarification requests

      Returns Promise<TaskResult<T>>

      const agent = new ADCPClient(config);
      const initial = await agent.getProducts({ brief: 'Tech products' });

      // Continue the conversation
      const refined = await agent.continueConversation(
      'Focus only on laptops under $1000',
      initial.metadata.taskId
      );
    • List all tasks for this agent with detailed information

      Returns Promise<TaskInfo[]>

      Promise resolving to array of task information

      const tasks = await client.listTasks();
      tasks.forEach(task => {
      console.log(`${task.taskName}: ${task.status}`);
      });
    • Get detailed information about a specific task

      Parameters

      • taskId: string

        ID of the task to get information for

      Returns Promise<null | TaskInfo>

      Promise resolving to task information

    • Subscribe to task notifications for this agent

      Parameters

      • callback: (task: TaskInfo) => void

        Function to call when task status changes

      Returns () => void

      Unsubscribe function

      const unsubscribe = client.onTaskUpdate((task) => {
      console.log(`Task ${task.taskName} is now ${task.status}`);
      if (task.status === 'completed') {
      // Handle completion
      }
      });

      // Later, stop listening
      unsubscribe();
    • Subscribe to all task events (create, update, complete, error)

      Parameters

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

        Event callbacks for different task events

      Returns () => void

      Unsubscribe function

    • Register webhook URL for receiving task notifications

      Parameters

      • webhookUrl: string

        URL to receive webhook notifications

      • OptionaltaskTypes: string[]

        Optional array of task types to watch (defaults to all)

      Returns Promise<void>

      await client.registerWebhook('https://myapp.com/webhook', ['create_media_buy']);
      
    • Get comprehensive agent information including name, description, and available tools/skills

      Works with both MCP (tools) and A2A (skills) protocols to discover what the agent can do.

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

      Promise resolving to agent information including tools

      const client = new ADCPClient(agentConfig);
      const info = await client.getAgentInfo();

      console.log(`${info.name}: ${info.description}`);
      console.log(`Supports ${info.tools.length} tools`);

      info.tools.forEach(tool => {
      console.log(` - ${tool.name}: ${tool.description}`);
      });
    • Query a creative agent to discover available creative formats

      This is a static utility method that allows you to query any creative agent (like creative.adcontextprotocol.org) to discover what formats are available before creating a media buy.

      Parameters

      Returns Promise<Format[]>

      Promise resolving to the list of available formats

      // Discover formats from the standard creative agent
      const formats = await SingleAgentClient.discoverCreativeFormats(
      'https://creative.adcontextprotocol.org/mcp'
      );

      // Find a specific format
      const banner = formats.find(f => f.format_id.id === 'display_300x250_image');

      // Use the format in a media buy
      await salesAgent.createMediaBuy({
      packages: [{
      format_ids: [{
      agent_url: banner.format_id.agent_url,
      id: banner.format_id.id
      }]
      }]
      });