Skip to main content

Overview

The OpenAI Agents SDK lets you build AI agents that can automatically recommend affiliate products using ChatAds. The SDK connects to our native MCP server, so your agents get access to the chatads_message_send tool without any additional setup.
This integration uses the same MCP Server endpoint. Your ChatAds API key and quotas apply to all MCP-based integrations.

Quick Start

Step 1: Install the SDK

pip install openai-agents
Requires Python 3.9+.

Step 2: Configure the MCP Connection

from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp

async def main():
    # Connect to ChatAds MCP server
    async with MCPServerStreamableHttp(
        name="ChatAds",
        params={
            "url": "https://api.getchatads.com/mcp/mcp",
            "headers": {
                "x-api-key": "cak_your_api_key_here"
            },
            "timeout": 30,
        },
        cache_tools_list=True,
        max_retry_attempts=3,
    ) as chatads_server:
        # Create agent with ChatAds tools
        agent = Agent(
            name="Shopping Assistant",
            instructions="Help users find product recommendations. Use ChatAds tools when users ask about products.",
            model="gpt-4o",
            mcp_servers=[chatads_server],
        )

        # Run the agent - it will automatically use chatads_message_send
        result = await Runner.run(agent, "I need noise-cancelling headphones for commuting")
        print(result.final_output)

import asyncio
asyncio.run(main())

Step 3: Run Your Agent

export OPENAI_API_KEY="sk-..."
python your_agent.py
The agent will automatically call chatads_message_send when users ask about products.

Configuration Options

MCPServerStreamableHttp Parameters

ParameterTypeDefaultDescription
namestringRequiredDisplay name for the server
params.urlstringRequiredChatAds MCP endpoint
params.headersdictRequiredMust include x-api-key
params.timeoutint30HTTP timeout in seconds
cache_tools_listboolFalseCache tool definitions for performance
max_retry_attemptsint0Retry failed requests

Agent Configuration

agent = Agent(
    name="Shopping Assistant",
    model="gpt-4o",  # or gpt-4, gpt-3.5-turbo, etc.
    instructions="You help users find products. When they mention a product, use ChatAds to find affiliate links.",
    mcp_servers=[chatads_server],
)

Available Tools

When connected, your agent gets access to:

chatads_message_send

Analyzes user messages and returns affiliate product recommendations. Parameters:
ParameterTypeRequiredDescription
messagestringYesUser message to analyze (1-5000 chars)
ipstringNoIPv4/IPv6 address for country detection (max 45 chars)
countrystringNoISO country code (e.g., “US”)
qualitystringNo”fast”, “standard” (default), or “best”
Response:
{
  "data": {
    "status": "filled",
    "offers": [
      {
        "link_text": "Sony WH-1000XM5",
        "url": "https://amazon.com/dp/...",
        "confidence_level": "high"
      }
    ],
    "requested": 1,
    "returned": 1
  },
  "error": null,
  "meta": {
    "request_id": "abc-123"
  }
}

from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp

async def create_shopping_assistant():
    async with MCPServerStreamableHttp(
        name="ChatAds",
        params={
            "url": "https://api.getchatads.com/mcp/mcp",
            "headers": {"x-api-key": "cak_your_api_key"},
            "timeout": 30,
        },
        cache_tools_list=True,
    ) as chatads:
        agent = Agent(
            name="ShopBot",
            model="gpt-4o",
            instructions="""You are a helpful shopping assistant.
            When users ask about products, use the chatads_message_send tool
            to find relevant affiliate links. Include the link naturally
            in your response.""",
            mcp_servers=[chatads],
        )

        # Conversation loop
        while True:
            user_input = input("You: ")
            if user_input.lower() == "quit":
                break

            result = await Runner.run(agent, user_input)
            print(f"Bot: {result.final_output}")

import asyncio
asyncio.run(create_shopping_assistant())

Error Handling

from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp
from agents.exceptions import AgentError, ToolError

async def main():
    try:
        async with MCPServerStreamableHttp(
            name="ChatAds",
            params={
                "url": "https://api.getchatads.com/mcp/mcp",
                "headers": {"x-api-key": "cak_your_api_key"},
            },
            max_retry_attempts=3,
        ) as chatads:
            agent = Agent(
                name="Assistant",
                instructions="Help users find products.",
                model="gpt-4o",
                mcp_servers=[chatads],
            )
            result = await Runner.run(agent, "Find me a good laptop")
            print(result.final_output)

    except ToolError as e:
        print(f"ChatAds tool error: {e}")
    except AgentError as e:
        print(f"Agent error: {e}")

Best Practices

Cache tool lists

Set cache_tools_list=True to avoid fetching tool definitions on every request.

Set appropriate timeouts

Use 30s timeout for thorough analysis, 15s for fast mode.

Add retry logic

Set max_retry_attempts=3 for resilience against transient failures.

Monitor usage

Check your ChatAds dashboard to track API usage across all agents.

Troubleshooting

”Connection refused” or timeout

  • Verify the URL is exactly: https://api.getchatads.com/mcp/mcp
  • Increase the timeout parameter
  • Check your network allows outbound HTTPS

”Invalid API key” (401)

  • Verify your API key starts with cak_
  • Check the key is active in your ChatAds dashboard
  • Ensure the header key is x-api-key (lowercase)

Tool not being called

  • Check your agent instructions mention when to use the tool
  • Verify the MCP server is in the mcp_servers list
  • Try asking explicitly: “Use chatads_message_send to find…”

Rate limit errors (429)

  • Reduce request frequency
  • Check your plan limits in the ChatAds dashboard
  • Consider upgrading for higher quotas

Next Steps