@adcp/client API Reference - v3.11.2
    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 status updates and completions)

      Accepts webhook payloads from both MCP and A2A protocols:

      1. MCP: MCPWebhookPayload envelope with AdCP data in .result field
      2. A2A: Native Task/TaskStatusUpdateEvent with AdCP data in either:
        • status.message.parts[].data (for status updates)
        • artifacts (for task completion, per A2A spec)

      The method normalizes both formats so handlers receive the unwrapped AdCP response data (AdCPAsyncResponseData), not the raw protocol structure.

      Parameters

      • payload: MCPWebhookPayload | Task | TaskStatusUpdateEvent

        Protocol-specific webhook payload (MCPWebhookPayload | Task | TaskStatusUpdateEvent)

      • 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: string

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

      • Optionaltimestamp: string | number

        X-ADCP-Timestamp header (Unix timestamp)

      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
      );
    • Get the agent configuration with normalized protocol

      Returns the agent config with:

      • Protocol normalized (e.g., .well-known URLs switch to A2A)
      • If canonical URL has been resolved, agent_uri will be the canonical URL

      For guaranteed canonical URL, use getResolvedAgent() instead.

      Returns AgentConfig

    • Get the fully resolved agent configuration

      This async method ensures the agent config has the canonical URL resolved:

      • For A2A: Fetches the agent card and uses its 'url' field
      • For MCP: Performs endpoint discovery

      Returns Promise<AgentConfig>

      Promise resolving to agent config with canonical URL

    • Get the canonical base URL for this agent

      Returns the canonical URL if already resolved, or computes it synchronously from the configured URL. For the most accurate canonical URL (especially for A2A where the agent card contains the authoritative URL), use resolveCanonicalUrl() first.

      The canonical URL is:

      • For A2A: The 'url' field from the agent card (if resolved), or base URL with /.well-known/agent-card.json stripped
      • For MCP: The discovered endpoint with /mcp stripped

      Returns string

      The canonical base URL (synchronous, may not be fully resolved)

    • Resolve and return the canonical base URL for this agent

      This async method ensures the canonical URL is properly resolved:

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

      The result is cached, so subsequent calls are fast.

      Returns Promise<string>

      Promise resolving to the canonical base URL

    • Check if this agent is the same as another agent

      Compares agents by their canonical base URLs. Two agents are considered the same if they have the same canonical URL, regardless of:

      • Protocol (MCP vs A2A)
      • URL format (with/without /mcp, with/without /.well-known/agent-card.json)
      • Trailing slashes

      Parameters

      Returns boolean

      true if agents have the same canonical URL

    • Async version of isSameAgent that resolves canonical URLs first

      This provides more accurate comparison for A2A agents since it fetches the agent card to get the authoritative canonical URL.

      Parameters

      Returns Promise<boolean>

      Promise resolving to true if agents have the same canonical URL

    • 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}`);
      });
    • Get agent capabilities, including AdCP version support

      For v3 servers, calls get_adcp_capabilities tool. For v2 servers, builds synthetic capabilities from available tools.

      Returns Promise<AdcpCapabilities>

      Promise resolving to normalized capabilities object

      const capabilities = await client.getCapabilities();

      console.log(`Server version: ${capabilities.version}`);
      console.log(`Protocols: ${capabilities.protocols.join(', ')}`);

      if (capabilities.features.propertyListFiltering) {
      // Use v3 property list features
      }
    • Check if server supports a specific AdCP major version

      Parameters

      • version: 2 | 3

      Returns Promise<boolean>

    • 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
      }]
      }]
      });