ImplementationPhase 1A: Hyperlink Ads

Phase 1A: Hyperlink Ads

Get sponsored hyperlinks showing in your chat responses immediately.

Time: 5 minutes

This gets you started fast! You’ll see sponsored links immediately.

IMPORTANT: Phase 1A alone is NOT sufficient for display ads (banners, thinking ads, popups, videos). You MUST complete Phase 1B to add conversation tracking, which is required for display ads to work correctly. Phase 1B adds the x-conversation-id header that allows the MCP server to populate ads for the right conversation.

Prerequisites

Before starting, verify you have:

  • Node.js 16+ - Check with node --version
  • Next.js 13+ with App Router - Your project should have an app/ directory
  • Working chat app - If you can type a message and get an AI response, you’re ready!
  • EarnLayer API key - Get one here

Choose Your Provider

Install Packages

npm install openai

Set Up Environment Variables

Create or update .env.local in your project root:

# ADD: Required for SDK (Phase 1B and Phase 2)
EARNLAYER_API_KEY=el_your_api_key_here
 
# ADD: Required ONLY for MCP integration in chat route (Phase 1A)
EARNLAYER_MCP_URL=https://mcp.earnlayerai.com/mcp
 
# Your existing LLM provider key (keep as-is)
OPENAI_API_KEY=sk_your_openai_key_here

Get your keys: EarnLayer API key | OpenAI API key

Add MCP to Your Chat Route

In your existing app/api/chat/route.ts:

// Your existing imports (keep as-is)
import OpenAI from 'openai';
 
// Your existing client setup (keep as-is)
const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});
 
// ADD: New environment variables
const EARNLAYER_MCP_URL = process.env.EARNLAYER_MCP_URL!;
const EARNLAYER_API_KEY = process.env.EARNLAYER_API_KEY!;
 
// ADD: System instructions for ad integration
const SYSTEM_INSTRUCTIONS = 
  'You are a helpful assistant. IMPORTANT: Whenever a user asks about products, services, tools, software, or anything that could be purchased or subscribed to, ' +
  'you MUST FIRST call the earnlayer_content_ads_search tool to find sponsored recommendations. ' +
  'After getting results, review the ads and ONLY include the ones that are RELEVANT to the user\'s question. ' +
  'Ignore any ads that are not related to what the user is asking about. ' +
  'For relevant ads, include them in your response with their clickable links in markdown format [Product Name](url). ' +
  'ALWAYS include the URLs as clickable links.';
 
// MODIFY: Update your existing API call to use Responses API with MCP tools
const resp = await client.responses.create({
  model: 'gpt-4o',
  // ADD: Tools array for MCP integration
  tools: [
    {
      type: 'mcp',
      server_label: 'earnlayer',
      server_url: EARNLAYER_MCP_URL,
      require_approval: 'never',
      headers: {
        'x-api-key': EARNLAYER_API_KEY,
        'x-demo-mode': 'true'  // ADD: Shows demo ads for testing
      }
    }
  ],
  // ADD: Input format for Responses API
  input: [
    {
      role: 'developer',
      content: [{ type: 'input_text', text: SYSTEM_INSTRUCTIONS }]
    },
    {
      role: 'user',
      content: [{ type: 'input_text', text: message }]
    }
  ]
});
 
// Your existing response handling (keep as-is)
return NextResponse.json({ response: resp.output_text });

Test It!

npm run dev

Ask: “What are the best VPNs?” or “What project management tools should I use?”

You should see sponsored links in the AI response.

Note: You’re currently seeing demo ads (test ads for integration). In Phase 1B, you’ll learn how to switch to production mode to show real ads and earn revenue.

Next Steps


Troubleshooting

AI isn’t calling the MCP tool

  • Try specific questions: “What database should I use?”
  • Avoid simple questions: “Hello”
  • Verify SYSTEM_INSTRUCTIONS is included in your prompts
  • Make sure mcpToTool(client) is in the tools array

No ads showing

  1. Check EARNLAYER_API_KEY and EARNLAYER_MCP_URL are set in .env.local
  2. Restart dev server after adding env vars: Stop with Ctrl+C, then npm run dev
  3. Check browser console for errors
  4. Verify API key starts with el_

”Module not found” errors

Make sure you’ve installed the correct dependencies for your chosen provider.

Rate limits

LLM Providers have rate limits based on your tier. If you hit limits:

  • Implement retry logic with exponential backoff
  • Consider caching responses where appropriate
  • Upgrade your quota if needed

Resource Management

Always close the MCP client after use to prevent memory leaks:

try {
  await client.connect(transport);
  const response = await ai.models.generateContent({...});
  return NextResponse.json({ response: response.text });
} finally {
  await client.close();  // Always close
}
 
---
 
## What You Accomplished
 
**Phase 1A Complete!** You're seeing hyperlink ads (demo mode).
 
- Hyperlink ads showing in responses
- MCP integration working with demo ads
- Next: Configure for production and add impression tracking
 
**[Continue to Phase 1B](/implementation/phase-1b)** (required for production)