How to connect Ahrefs to OpenAI Agents SDK in 2 mins: No API key needed

You can see which keywords bring a competitor traffic, find your real search competitors and check volume and difficulty for your keyword list from OpenAI Agents SDK. Composio runs each call on its own Ahrefs account, so you don't need a Ahrefs API key, and your first $2 is free.

AhrefsInstant · No API key

OpenAI Agents SDK runs Ahrefs through Composio, and the cost comes out of your free $2.

  • A site's top 20 keywords with traffic$0.28
  • Volume and difficulty for 10 keywords$0.19
  • A site's top 10 search competitors$0.084

$2 ≈ 7 reports or 10 reports

Composio Instant

What you can do with your free $2

What your free $2 gets you with Ahrefs
When you ask OpenAI Agents SDK forOpenAI Agents SDK uses this toolCostWhat $2 gets you
A site's top 20 keywords with trafficRetrieve organic keywords$0.28 per reportAbout 7 reports
Volume and difficulty for 10 keywordsExplore keywords overview$0.19 per reportAbout 10 reports
A site's top 10 search competitorsRetrieve organic competitors$0.084 per reportAbout 20 reports
20 question keywords for a topicExplore matching terms for keywords$0.25 per reportAbout 8 reports
Backlink and referring domain totals for a siteBacklinks stats retrieval$0.030 per lookupAbout 65 lookups

You pay Ahrefs' price for each call with 0% markup, plus the regular Composio tool call charge. There's no Ahrefs subscription, and you only pay for what you use.

42 of 46 Ahrefs tools work without a key. For Fetch competitors overview, Fetch rank tracker overview, Get site audit projects and Retrieve subscription limits and usage, connect your own Ahrefs key. Read how Instant works.

How it works

How to connect Ahrefs to OpenAI Agents SDK

Composio adds Ahrefs to OpenAI Agents SDK as an Instant toolkit. You connect Composio to OpenAI Agents SDK once, and then OpenAI Agents SDK can use Ahrefs right away. There are two ways to do this:

  • Bring your own key

    You bring your own Ahrefs API key, set it up, and use it.

  • Use the Composio wallet

    Instant

    Composio runs each call on its own Ahrefs account, so you don't have to set anything up at Ahrefs, and your first $2 is free.

You do the setup one time and it takes about a minute. If you build Ahrefs into your own product, turn on Instant toolkits in your project settings so your agent can call Ahrefs for each of your users without a Ahrefs API key, and read Instant tools in the Composio docs for the setup steps and code examples.

Get started

Start to use Ahrefs in OpenAI Agents SDK in 3 steps

  1. Turn on Instant

    Open your Composio wallet and turn on Instant. Your free $2 shows up there.

  2. Add Composio to OpenAI Agents SDK

    Follow the setup below. You only do this once.

  3. Ask OpenAI Agents SDK for something

    Try a Ahrefs prompt. The cost comes out of your $2.

Setup

Step-by-step Guide

Step by step09 STEPS
1

Prerequisites

Before starting, make sure you have:
  • Composio API Key and OpenAI API Key
  • Primary know-how of OpenAI Agents SDK
  • A live Ahrefs project
  • Some knowledge of Python or Typescript
2

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
3

Install dependencies

npm install @composio/openai-agents @openai/agents dotenv

Install the Composio SDK and the OpenAI Agents SDK.

4

Set up environment variables

bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com

Create a .env file and add your OpenAI and Composio API keys.

5

Import dependencies

import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
What's happening:
  • You're importing all necessary libraries.
  • The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Ahrefs.
6

Set up the Composio instance

dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
What's happening:
  • dotenv.config() loads your .env file so COMPOSIO_API_KEY and USER_ID are available as environment variables.
  • Creating a Composio instance using the API Key and OpenAIAgentsProvider class.
7

Create a Tool Router session

// Create Tool Router session for Ahrefs
const session = await composio.create(userId as string, {
  toolkits: ['ahrefs'],
});
const mcpUrl = session.mcp.url;

What is happening:

  • You give the Tool Router the user id and the toolkits you want available. Here, it is only ahrefs.
  • The router checks the user's Ahrefs connection and prepares the MCP endpoint.
  • The returned session.mcp.url is the MCP URL that your agent will use to access Ahrefs.
  • This approach keeps things lightweight and lets the agent request Ahrefs tools only when needed during the conversation.
8

Configure the agent

// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Ahrefs. Help users perform Ahrefs operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
What's happening:
  • We're creating an Agent instance with a name, model (gpt-5), and clear instructions about its purpose.
  • The agent's instructions tell it that it can access Ahrefs and help with queries, inserts, updates, authentication, and fetching database information.
  • The tools array includes a hostedMcpTool that connects to the MCP server URL we created earlier.
  • The headers object includes the Composio API key for secure authentication with the MCP server.
  • requireApproval: 'never' means the agent can execute Ahrefs operations without asking for permission each time, making interactions smoother.
9

Start chat loop and handle conversation

// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
What's happening:
  • The program prints a session URL that you visit to authorize Ahrefs.
  • After authorization, the chat begins.
  • Each message you type is processed by the agent using run().
  • The responses are printed to the console.
  • Typing exit, quit, or q cleanly ends the chat.

Complete Code

Here's the complete code to get you started with Ahrefs and OpenAI Agents SDK:

import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['ahrefs'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Ahrefs. Help users perform Ahrefs operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
Try it

Ask OpenAI Agents SDK for something with Ahrefs

Start a new chat and try this prompt:

Using Ahrefs, show me the top 20 keywords [competitor domain] gets the most US organic traffic from. Give me a table with the keyword, monthly volume, their position, estimated traffic and the ranking URL.

OpenAI Agents SDK runs it on Instant and shows you the result. It doesn't ask you for a Ahrefs key, and the cost comes out of your $2. You can see each call in your wallet.

Optional: connect your own Ahrefs key

If you want Fetch competitors overview, Fetch rank tracker overview, Get site audit projects and Retrieve subscription limits and usage, you need your own key. Ask OpenAI Agents SDK to connect your Ahrefs account, and it gives you a Composio link:

Connect my Ahrefs account using Composio.

Open the link, paste your Ahrefs API key and click Connect Account. You can get a key from Ahrefs API keys page. After that, Composio uses your key first and doesn't charge Instant for those calls.

Starter prompts

Use your first $2: copy a prompt into OpenAI Agents SDK

Each prompt runs on Instant, and the cost next to it is about what it takes from your $2.

  • See which keywords bring a competitor traffic

    About $0.28

    Lists the 20 keywords that send a site the most search traffic, with volume, position and the page that ranks.

    Using Ahrefs, show me the top 20 keywords [competitor domain] gets the most US organic traffic from. Give me a table with the keyword, monthly volume, their position, estimated traffic and the ranking URL.

  • Find your real search competitors

    About $0.08

    Finds the sites that compete with you for the same keywords in search, with how much you overlap.

    Using Ahrefs, find the top 10 organic search competitors for [your domain] in the US. Show each competitor's domain, Domain Rating, the number of keywords we both rank for and their estimated organic traffic.

  • Check volume and difficulty for your keyword list

    About $0.19

    Gets search volume, difficulty, CPC and traffic potential for your keywords so you can pick which ones to target.

    Using Ahrefs, get US search volume, keyword difficulty, CPC and traffic potential for these keywords, then sort them so the best mix of high volume and low difficulty is at the top: [paste up to 10 keywords].

  • Find questions people search about a topic

    About $0.25

    Lists the question keywords people search around a topic, with volume and difficulty, so you can plan articles or FAQs.

    Using Ahrefs, find the 20 highest-volume question keywords in the US that contain "[topic]". Show the volume and keyword difficulty for each one and group them into article ideas.

  • Find broken links you can win back

    About $0.06

    Finds sites that link to pages on your domain that no longer work, so you can fix or redirect them.

    Using Ahrefs, find 20 broken backlinks pointing to [your domain], sorted by the linking site's Domain Rating. Show the linking page, the broken URL on my site, the anchor text and the HTTP status.

  • Vet link prospects by Domain Rating

    Free

    Checks the Domain Rating of a list of sites in one go so you can drop weak link prospects early.

    Using Ahrefs, get the Domain Rating for each of these sites and sort them from highest to lowest so I can see which ones are worth pitching: [paste up to 100 domains].

  • Compare search demand across countries

    About $0.03

    See where a keyword has the most monthly search volume.

    I want to compare demand for [keyword] across countries. Using Ahrefs, get the top 5 countries by monthly search volume and show each country and its volume. Tell me which country has the highest demand.

  • See which sites a competitor links to

    About $0.03

    Find external domains linked from a competitor site.

    I want you to do this: Using Ahrefs, list up to 10 external domains that [competitor domain] links to. Show the linked domain and a source page when returned, then group the domains by likely purpose based on their names and pages.

What it can do

What OpenAI Agents SDK can do with Ahrefs

Works without a key

  • A site's top 20 keywords with traffic
  • Volume and difficulty for 10 keywords
  • A site's top 10 search competitors
  • 20 question keywords for a topic
  • Backlink and referring domain totals for a site

Needs your own Ahrefs key

  • Fetch competitors overview
  • Fetch rank tracker overview
  • Get site audit projects
  • Retrieve subscription limits and usage
Tools and prices

Supported tools (46)

Ahrefs tools and their Instant prices
ToolWhat it doesWorks without a keyCost on Instant
Backlinks stats retrievalRetrieves comprehensive backlink statistics for a specified website or URL using Ahrefs' Site Explorer tool.Yes$0.006 per 10 API units used
Batch Url AnalysisPerforms a batch analysis on multiple URLs or domains using Ahrefs' powerful SEO metrics.Yes$0.006 per 10 API units used
Domain rating for site explorerRetrieves Ahrefs Domain Rating and Ahrefs Rank for a specified domain or URL on a requested date.Yes$0.006 per 10 API units used
Domain rating historyRetrieves the historical Domain Rating (DR) data for a specified domain over time.Yes$0.006 per 10 API units used
Explore keywords overviewRetrieves keyword-level overview metrics from Ahrefs' Keywords Explorer for specified keywords or an existing keyword list in a country.Yes$0.006 per 10 API units used
Explore keyword volume by countryRetrieves monthly search volume data across countries for a specified keyword using Ahrefs' Keywords Explorer.Yes$0.006 per 10 API units used
Explore linked domains of a siteRetrieves a list of external domains that the specified target website or URL links to, using Ahrefs' Site Explorer functionality.Yes$0.006 per 10 API units used
Explore matching terms for keywordsThe keywords_explorer_matching_terms endpoint retrieves a list of keyword phrases that match or contain the specified keyword from Ahrefs' vast database.Yes$0.006 per 10 API units used
Fetch all backlinksRetrieves a comprehensive list of backlinks for a specified website or URL using Ahrefs' Site Explorer tool.Yes$0.006 per 10 API units used
Fetch broken backlinks dataRetrieves a list of broken backlinks for a specified website using Ahrefs' Site Explorer tool.Yes$0.006 per 10 API units used
Fetch site explorer referring domainsRetrieves a list of domains that have backlinks pointing to a specified target website.Yes$0.006 per 10 API units used
Fetch total search volume historyRetrieves historical total search volume for keywords associated with a target domain or URL using Ahrefs Site Explorer.Yes$0.006 per 10 API units used
Get content helper topicsRetrieve topics covered by top-ranking pages for a keyword.Yes$0.006 per 10 API units used
Get domain rating freeRetrieve the free Ahrefs Domain Rating for a domain or URL.Yes$0 per request
Get domain rating top domainsRetrieves domains ordered by Ahrefs Domain Rating.Yes$0 per request
Get serp overviewRetrieves a SERP overview for one keyword in a specified country, optionally at a historical date.Yes$0.006 per 10 API units used
Get site explorer AI responses countRetrieve AI response citation and page counts for a site.Yes$0.006 per 10 API units used
Get site explorer country metricsRetrieves country-specific Site Explorer metrics for a target website or URL, including organic traffic and keyword metrics.Yes$0.006 per 10 API units used
Get site explorer crawled pagesRetrieve crawled pages and crawl metadata for a target URL.Yes$0.006 per 10 API units used
Get site explorer linked anchors externalRetrieves anchor text data for external links going out from a target website using Ahrefs Site Explorer.Yes$0.006 per 10 API units used
Show all 46 tools
More Ahrefs tools and their Instant prices
ToolWhat it doesWorks without a keyCost on Instant
Get url rating historyRetrieves the historical URL Rating data for a specified URL over time.Yes$0.006 per 10 API units used
Linked anchors explorerRetrieves information about internal linked anchors for a specified website using the Ahrefs API.Yes$0.006 per 10 API units used
List best by external linksRetrieves pages from a specified website using Ahrefs' Site Explorer best-by-external-links report.Yes$0.006 per 10 API units used
Pages by traffic overviewRetrieves a list of pages from a specified website, ordered by their estimated organic search traffic.Yes$0.006 per 10 API units used
Post Domain Rating FreeRetrieve Domain Rating scores for up to 1,000 target URLs.Yes$0 per request
Retrieve anchor dataRetrieves anchor text data for a specified website or URL using Ahrefs' Site Explorer tool.Yes$0.006 per 10 API units used
Retrieve best by internal linksRetrieves pages ranked by internal links for a specified website using Ahrefs' Site Explorer.Yes$0.006 per 10 API units used
Retrieve crawler ip rangesRetrieves the list of IP address ranges used by Ahrefs' web crawler (AhrefsBot).Yes$0 per request
Retrieve organic competitorsRetrieves organic search competitors for a target domain or URL, with keyword overlap and performance metrics.Yes$0.006 per 10 API units used
Retrieve organic keywordsRetrieves organic keywords data for a specified website using Ahrefs' Site Explorer tool.Yes$0.006 per 10 API units used
Retrieve outlinks statsRetrieves outgoing-link statistics for a specified website or URL using Ahrefs Site Explorer.Yes$0.006 per 10 API units used
Retrieve paid pages dataRetrieves information about paid pages (PPC advertising) for a specified website using Ahrefs' Site Explorer tool.Yes$0.006 per 10 API units used
Retrieve public crawler ipsRetrieves a list of IP addresses currently used by AhrefsBot, Ahrefs' web crawler.Yes$0 per request
Retrieve related termsRetrieves related keyword ideas for a given keyword or keyword list in a specified country.Yes$0.006 per 10 API units used
Retrieve site explorer keywords historyRetrieves historical keyword performance data for a specified website or domain using Ahrefs' Site Explorer.Yes$0.006 per 10 API units used
Retrieve site explorer metricsRetrieves Site Explorer SEO metrics for a target domain or URL on a specified date, including backlink, referring-page and crawled-page counts.Yes$0.006 per 10 API units used
Retrieve site explorer metrics historyRetrieves historical Site Explorer traffic metrics for a target website or URL over a specified period, including estimated organic and paid traffic and cost.Yes$0.006 per 10 API units used
Retrieve site explorer pages historyRetrieves historical page counts for a target domain or URL from Ahrefs Site Explorer over a specified period.Yes$0.006 per 10 API units used
Retrieve site explorer referring domains historyRetrieves the historical data of referring domains for a specified website or URL over time.Yes$0.006 per 10 API units used
Retrieve top pages from site explorerRetrieves data about the top-performing pages of a specified website using Ahrefs' Site Explorer tool.Yes$0.006 per 10 API units used
Retrieve volume historyRetrieves the historical search volume data for a specified keyword using Ahrefs' Keywords Explorer tool.Yes$0.006 per 10 API units used
Search suggestions explorerRetrieves search suggestions for keywords or an existing keyword list using Ahrefs Keywords Explorer.Yes$0.006 per 10 API units used
Fetch competitors overviewRetrieves a Rank Tracker competitor overview for a project, including comparative keyword ranking and organic search performance data.Needs your own keyBilled to your own Ahrefs key
Fetch rank tracker overviewRetrieves an Ahrefs Rank Tracker overview for a project, date and device, with ranking and search-performance metrics.Needs your own keyBilled to your own Ahrefs key
Get site audit projectsLists Site Audit projects associated with the authenticated Ahrefs account, with project and crawl status details.Needs your own keyBilled to your own Ahrefs key
Retrieve subscription limits and usageRetrieves an Ahrefs account's subscription limits and remaining API usage allowance.Needs your own keyBilled to your own Ahrefs key
Pricing

How you pay for Ahrefs

  • Your first $2 is freeIt's added to your Composio wallet when you turn on Instant.
  • You pay for each callYou pay Ahrefs' price with 0% markup, plus the regular Composio tool call charge.
  • Your own key comes firstIf you connect your own Ahrefs key, Composio uses it and doesn't charge Instant for those calls.
  • You control the costYou can ask your agent to check with you before each paid call, and you can turn Instant off at any time.
  • You can see each callYour wallet shows each call and what it cost.
  • When your balance runs outYou can add funds to your wallet on a Pro plan or connect your own key.
Help

Troubleshooting

  1. 1. OpenAI Agents SDK asks me for a Ahrefs API key

    You may have asked for something that needs your own key, like Fetch competitors overview, Fetch rank tracker overview, Get site audit projects and Retrieve subscription limits and usage. Those tools don't run on Instant. For everything else, check that Instant is turned on in your Composio wallet, then ask again.

  2. 2. I can't see my free $2

    Open your wallet in the Composio dashboard and check that Instant is turned on. If the $2 still isn't there, email support@composio.dev from the address you signed up with.

  3. 3. A Ahrefs call failed with a balance error

    Your balance is empty. Add funds to your wallet on a Pro plan, or connect your own Ahrefs key, then try again.

FAQ

Frequently asked questions

Start with Ahrefs.It takes 30 seconds.

New accounts get a one-time $2 starter credit for Instant calls.Run Ahrefs from your agent with no Ahrefs key.

Get $2 starter credit