How to integrate Brightdata MCP with Pydantic AI

Connect Pydantic AI to Brightdata MCP. Download all product listings from this ecommerce site, check crawl status for your recent job, and more using natural language, with authentication handled for you.

Brightdata logoBrightdata
Api Key

Brightdata is a leading web data platform offering advanced scraping, SERP APIs, and anti-bot tools. It lets you collect public web data at scale, bypassing blocks and friction.

167 Tools

Introduction

This guide walks you through connecting Brightdata to Pydantic AI using the Composio tool router. By the end, you'll have a working Brightdata agent that can scrape e-commerce and social media sites, run SERP searches, crawl websites, unlock protected pages, and filter ready-made datasets through natural language commands.

This guide will help you understand how to give your Pydantic AI agent real control over a Brightdata account through Composio's Brightdata MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

For exact tool slugs and parameter tables, see the tool catalog in the Composio docs.

Also integrate Brightdata with

TL;DR

Here's what you'll learn:
  • How to set up your Composio API key and User ID
  • How to create a Composio Tool Router session for Brightdata
  • How to attach an MCP Server to a Pydantic AI agent
  • How to stream responses and maintain chat history
  • How to build a simple REPL-style chat interface to test your Brightdata workflows

What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.

Key features include:

  • Type Safety: Built on Pydantic for automatic data validation
  • MCP Support: Native support for Model Context Protocol servers
  • Streaming: Built-in support for streaming responses
  • Async First: Designed for async/await patterns

What is the Brightdata MCP server, and what's possible with it?

The Brightdata MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Brightdata account. It provides structured and secure access to Brightdata’s web data platform, so your agent can trigger site crawls, run SERP searches, filter and download datasets, and manage proxy endpoints on your behalf.

  • Automated site crawling and extraction: Start large-scale crawl jobs across multiple web pages or entire domains, letting your agent collect structured data from the internet with just a prompt.
  • Access to pre-made marketplace scrapers: Browse and select from Brightdata’s collection of pre-built scrapers for popular websites, making it easy to gather structured data without building your own scrapers from scratch.
  • Filtered dataset generation and download: Apply custom filters to datasets, check crawl job status, and retrieve the exact data you need by downloading processed results once ready.
  • Powerful SERP and web unlocker tools: Perform real-time SERP searches across various engines and leverage web unlocker zones to bypass anti-bot protections and scrape challenging websites.
  • Proxy zone and location management: List available proxy zones, cities, and countries to configure how and where your data collection jobs run, optimizing for speed and success.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Step by step09 STEPS
1

Prerequisites

Before starting, make sure you have:
  • Python 3.9 or higher
  • A Composio account with an active API key
  • Basic familiarity with Python and async programming
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
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.
3

Install dependencies

bash
pip install composio pydantic-ai python-dotenv

Install the required libraries.

What's happening:

  • composio connects your agent to external SaaS tools like Brightdata
  • pydantic-ai lets you create structured AI agents with tool support
  • python-dotenv loads your environment variables securely from a .env file
4

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your agent to Composio's API
  • USER_ID associates your session with your account for secure tool access
  • OPENAI_API_KEY to access OpenAI LLMs
5

Import dependencies

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
What's happening:
  • We load environment variables and import required modules
  • Composio manages connections to Brightdata
  • MCPServerStreamableHTTP connects to the Brightdata MCP server endpoint
  • Agent from Pydantic AI lets you define and run the AI assistant
6

Create a Tool Router Session

python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Brightdata
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["brightdata"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
What's happening:
  • We're creating a Tool Router session that gives your agent access to Brightdata tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use
7

Initialize the Pydantic AI Agent

python
# Attach the MCP server to a Pydantic AI Agent
brightdata_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[brightdata_mcp],
    instructions=(
        "You are a Brightdata assistant. Use Brightdata tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
What's happening:
  • The MCP client connects to the Brightdata endpoint
  • The agent uses GPT-5 to interpret user commands and perform Brightdata operations
  • The instructions field defines the agent's role and behavior
8

Build the chat interface

python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Brightdata.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
What's happening:
  • The agent reads input from the terminal and streams its response
  • Brightdata API calls happen automatically under the hood
  • The model keeps conversation history to maintain context across turns
9

Run the application

python
if __name__ == "__main__":
    asyncio.run(main())
What's happening:
  • The asyncio loop launches the agent and keeps it running until you exit

Complete Code

Here's the complete code to get you started with Brightdata and Pydantic AI:

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Brightdata
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["brightdata"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    brightdata_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[brightdata_mcp],
        instructions=(
            "You are a Brightdata assistant. Use Brightdata tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Brightdata.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())

Conclusion

You've built a Pydantic AI agent that can interact with Brightdata through Composio's Tool Router. With this setup, your agent can perform real Brightdata actions through natural language. You can extend this further by:
  • Adding other toolkits like Gmail, HubSpot, or Salesforce
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Brightdata for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.
TOOLS

Supported Tools

Every Brightdata action and event your agent gets out of the box.

Start Site Crawl

Start an asynchronous dataset or site crawl.

Create Safe Zone

Create a durable SERP API or Scraping Browser zone using a fixed safe plan.

List Marketplace Datasets

List pre-built datasets in Bright Data's marketplace for structured scraping.

Filter Dataset

Create a billable filtered marketplace-dataset snapshot.

Get Customer Balance

Get current and pending Bright Data account balances.

Get Dataset Metadata

Retrieve field definitions for a Bright Data marketplace dataset.

Get Deep Lookup Results

Retrieve enriched records plus available progress, cost, and provider metadata for a completed Deep Lookup request.

Get Deep Lookup Status

Check a Deep Lookup request's status, progress, cost, and provider metadata.

Get Destination Type Schema

Retrieve the fields required to configure a Bright Data delivery destination.

List Available Cities

List static-network cities available for a country and proxy pool type.

List Available Countries

List country codes available for each static proxy zone type.

Get SERP Results

Retrieve JSON or raw results for an asynchronous BRIGHTDATA_SERP_SEARCH request.

Download Snapshot Results

Download a completed dataset snapshot.

Check Snapshot Status

Check whether a dataset snapshot is running, ready, or failed before downloading it.

Get Web Archive Search

Get a Web Archive search's status and its matching-file, dump-size-in-bytes, and dump-cost-in-USD estimates.

Get Zone Bandwidth

Get uploaded, downloaded, and total byte usage for one zone and date range.

Get Zone Cost

Get invoice-aligned billed cost and bandwidth for one zone and date range.

Get Country Cities

List cities in a country for account-level geographic selection.

Get Dataset Delivery Options

List settings supported when configuring Bright Data dataset delivery.

List Scraper Studio Scrapers

List account-owned Scraper Studio scrapers and discover collector IDs.

List Unlocker Zones

List configured Web Unlocker zones and their types for protected-URL scraping.

Scrape AE.com - Complete Products

Collect AE.

Scrape Agoda Listings Search

Collect Agoda Listings Search.

Scrape Agoda Properties Listings

Collect Agoda Properties Listings.

Scrape Agoda Properties Listings with Pricing

Collect Agoda Properties Listings with Pricing.

Scrape Agoda Reviews

Collect Agoda Reviews.

Amazon products

Collect Amazon products by URL with optional ASIN metadata, or discover them by best-seller/category URL, keyword, or UPC, returning product and price data.

Amazon products search

Collect structured Amazon products search data from amazon.

Amazon products global dataset

Collect global Amazon products by URL or discover them by best-seller, brand, category, keyword/domain, or seller, returning product and price data.

Amazon Reviews

Collect structured Amazon Reviews data from amazon.

Amazon sellers info

Collect structured Amazon sellers info data from amazon.

American Eagle Products - Unified Schema

Collect American Eagle.

Scrape Apple App Store

Collect Apple App Store.

Scrape Apple App Store reviews

Collect Apple App Store reviews .

Ashley Furniture Products

Collect Ashleyfurniture - Products.

Ashley Furniture Products - Unified Schema

Collect Ashley Furniture.

Scrape Best Buy products

Collect Best Buy products.

Scrape Best Buy Reviews

Collect Best Buy Reviews.

Scrape Booking Hotel Listings

Collect Booking Hotel Listings .

Scrape Booking Hotel Listings with Pricing

Collect Booking Hotel Listings with Pricing.

Scrape Booking Listings Search

Collect Booking Listings Search.

Scrape Booking Reviews

Collect Booking Reviews.

Scrape ChatGPT Search

Collect ChatGPT Search.

Scrape Costco products

Collect Costco products.

Scrape Costco Reviews

Collect Costco Reviews.

Crate & Barrel Products

Collect Crateandbarrel - Products.

Crate & Barrel Products - Unified Schema

Collect Crateandbarrel - Products.

Creative Commons 3D Models

Collect Creative Commons 3D Models.

Scrape Creative Commons Images

Collect Creative Commons Images.

Scrape Data Synchronously

Scrape up to 20 input objects synchronously.

Scrape Dior - Products

Collect Dior - Products.

Scrape Dior Products Unified Schema

Collect Dior Products Unified Schema.

Facebook - Comments

Collect structured Facebook - Comments data from facebook.

Scrape Facebook Company Reviews

Collect Facebook Company Reviews.

Scrape Facebook Events

Collect Facebook Events.

Facebook - Posts by group URL

Collect structured Facebook - Posts by group URL data from facebook.

Scrape Facebook Marketplace

Collect Facebook Marketplace.

Facebook - Pages Posts by Profile URL

Collect structured Facebook - Pages Posts by Profile URL data from facebook.

Facebook - Pages and Profiles

Collect Facebook pages and public profiles with the combined page/profile dataset, including entity type and page-oriented fields.

Scrape Facebook - Posts by post URL

Collect Facebook - Posts by post URL.

Scrape Facebook - Profiles

Collect Facebook profile URLs with the profile-only dataset.

Scrape Facebook - Reels by profile URL

Collect Facebook - Reels by profile URL.

Scrape Falabella.com - Reviews

Collect Falabella.

Scrape Falabella.com - Search

Collect Falabella.

Falabella Products

Collect Falabella.

Scrape Flipkart.com - Search

Collect Flipkart.

Flipkart Products

Collect Flipkart.

Scrape Flipkart Products unified schema

Collect Flipkart Products unified schema.

Scrape Flipkart - Reviews

Collect Flipkart - Reviews.

Scrape Glassdoor companies overview information

Collect Glassdoor companies overview information.

Scrape Glassdoor companies reviews

Collect Glassdoor companies reviews.

Glassdoor Jobs

Collect Glassdoor job listings information.

Scrape Google AI Mode Search

Collect Google AI Mode Search.

Scrape Google Flights

Collect Google Flights.

Scrape Google Hotels

Collect Google Hotels.

Scrape Google Images

Collect Google Images.

Scrape Google Maps Images

Collect Google Maps place images.

Google Maps Places

Collect Google Maps place URLs or discover places by keyword and location.

Scrape Google maps reviews

Collect Google Maps place reviews or discover reviews from place URLs.

Scrape Google Play Store

Collect Google Play Store.

Scrape Google Play Store reviews

Collect Google Play Store reviews.

Google SERP 100 Results

Collect Google SERP - 100 Results.

Scrape Google Shopping

Collect Google Shopping product pages or discover products by keyword with the general Google Shopping dataset.

Scrape Google Shopping products search US

Collect US Google Shopping search-result URLs with the US search schema.

H&M Products

Collect H&M - Products.

H&M Products - Unified Schema

Collect H&M products.

Scrape Ikea - Products

Collect Ikea - Products.

Scrape Ikea products unified schema

Collect Ikea products unified schema.

Scrape Indeed companies info

Collect Indeed companies info.

Indeed Jobs

Collect Indeed job listings information.

Scrape Instacart products

Collect Instacart products.

Scrape Instacart Products unified schema

Collect Instacart Products unified schema.

Scrape Instagram Comments

Collect Instagram comments with commenter, text, date, likes, replies, hashtags, tagged users, and source-post details.

Scrape Instagram Posts

Collect Instagram posts or discover posts from a profile, returning captions, hashtags, media, engagement, dates, location, and comments.

Scrape Instagram Profiles

Collect Instagram profiles by URL or discover them by username, returning biography, audience, verification, links, posts, and profile image.

Scrape Instagram Reels

Collect Instagram reels or discover reels from profiles, returning captions, hashtags, media, dates, engagement, play counts, and comments.

Scrape Kohls.com - Reviews

Collect Kohls.

Kohl's Products

Collect Kohls.

Scrape Kohl's Products unified schema

Collect Kohl's Products unified schema.

Scrape Kroger.com - Search

Collect Kroger.

Kroger Products

Collect Kroger.

Scrape LinkedIn Companies

Collect structured LinkedIn company details, including size, industry, locations, followers, specialties, and website.

Scrape LinkedIn Jobs

Collect LinkedIn job listings or discover jobs by keyword, location, and search URL, returning role, employer, location, summary, and pay data.

Scrape LinkedIn People Search

Search LinkedIn people and return matching profile URLs, names, subtitles, locations, experience, education, and avatars.

Scrape LinkedIn Posts

Collect LinkedIn posts directly or discover posts from company, profile, and article-feed URLs, returning text, media, dates, and engagement.

Scrape LinkedIn Profiles

Collect structured LinkedIn person profiles, including identity, location, company, follower, education, and public career data.

L.L.Bean Products

Collect llbean.

L.L.Bean Products - Unified Schema

Collect LLBean.

Scrape Macys.com - Reviews

Collect Macys.

Macy's Products

Collect Macys.

Scrape Macys Products unified schema

Collect Macys Products unified schema.

Scrape Massimo Dutti - Products

Collect Massimo Dutti - Products .

Massimo Dutti Products - Unified Schema

Collect Massimodutti.

Scrape Meta - Ad Library

Collect Meta - Ad Library .

Scrape Overstock.com - Reviews

Collect Overstock.

Overstock Products

Collect Overstock.

Scrape Overstock Products unified schema

Collect Overstock Products unified schema.

Scrape Pinterest - Posts

Collect Pinterest - Posts .

Scrape Pinterest - Profiles

Collect Pinterest - Profiles.

Poshmark Products

Collect Poshmark.

Scrape Poshmark Products unified schema

Collect Poshmark Products unified schema.

Scrape Reddit - Comments

Collect Reddit - Comments.

Scrape Reddit- Posts

Collect Reddit- Posts.

Scrape Reddit - Profiles

Collect Reddit - Profiles.

Scrape Snapchat posts

Collect Snapchat posts.

Scrape Snapchat profile

Collect Snapchat profile.

Scrape Threads - Posts

Collect Threads - Posts.

Scrape Threads - Profiles

Collect Threads - Profiles.

Scrape TikTok Comments

Collect TikTok comments with text, dates, likes, replies, commenter identity, and source-post details.

Scrape TikTok Posts

Collect TikTok posts with the full post dataset.

TikTok - Posts by URL Fast API

Collect individual TikTok post URLs with the fast dataset.

Scrape TikTok Profile Posts Fast

Discover TikTok posts from profile URLs with the fast profile-post dataset.

TikTok - Profiles

Collect structured TikTok - Profiles data from tiktok.

Scrape TikTok Search Posts Fast

Discover TikTok posts from search or discovery URLs with the fast search-post dataset.

TikTok Shop

Collect structured TikTok Shop data from tiktok.

TikTok Shop Category Products

Collect structured TikTok Shop Category Products data from tiktok.

Scrape Trip.com - Flights (mobile-app)

Collect Trip.

Trip.com Hotel Listings

Collect Trip Hotel Listings.

Scrape Trip.com - Hotels (mobile-app)

Collect Trip.

Trip.com Listings Search

Collect Trip Listings Search.

Scrape Walmart - products

Collect Walmart - products .

Scrape Walmart products search

Collect Walmart products search.

Scrape Walmart - products zipcodes

Collect Walmart product URLs with zipcode-specific availability and pricing.

Scrape Walmart Reviews

Collect Walmart Reviews.

Scrape Walmart sellers info

Collect Walmart sellers info.

X Posts

Collect X (formerly Twitter) - Posts.

X Profiles

Collect X (formerly Twitter) - Profiles.

Scrape Yelp businesses overview

Collect Yelp businesses overview.

Scrape Yelp businesses reviews

Collect Yelp businesses reviews.

Scrape YouTube - Channels

Collect YouTube - Channels.

Scrape Youtube - Comments

Collect Youtube - Comments.

YouTube Videos

Collect Youtube - Videos posts.

Scrape Zara Home Products

Collect Zara Home Products.

Scrape Zara Home products

Collect Zara Home products.

Scrape Zara - Products

Collect Zara - Products .

Zara Products - Unified Schema

Collect Zara.

Zillow Properties

Collect full property details for Zillow property URLs.

Zillow Property Listings

Collect Zillow listing URLs or discover property listings from filters or search URLs.

Zillow Property Price History

Collect the price-history timeline for Zillow property URLs.

Zillow Property Search Results

Collect Zillow search-page URLs into search-result property records.

Search Business Records

Search public company or professional-profile records synchronously using structured queries in Ludicrous mode or natural language in Instant/Smart mode.

Search Dataset Synchronously

Search a supported LinkedIn profiles, contact-enriched profiles, or companies Marketplace dataset and return matching records synchronously.

Search SERP Synchronously

Search Google, Bing, DuckDuckGo or Yandex synchronously for standard text results.

Search Web Archive

Search Bright Data's Web Archive and estimate matching files, dump size in bytes, and dump cost in USD.

Search SERP

Submit an asynchronous SERP search and return its response_id.

Start Deep Lookup

Start an asynchronous Deep Lookup research request and return its request_id.

Scrape Protected URL

Scrape a public URL through Web Unlocker when ordinary requests are blocked or require JavaScript rendering.

FAQ

Frequently asked questions

Start with Brightdata.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Brightdata tool your agent needs.Free to start.

Start building