オープンした時には、Agents SDK数週間前、あらゆる場所でデヴがヒップされた――そして正当な理由で! 最後に、事実上理屈を示すことができる、目標に基づくAIエージェントを構築する簡単な方法。仕事が出来上がる↓↓↓
ほぼ同じ呼吸で、MCP現場に爆発し、すぐにこの野生のAIの風景の次のホットトレンドとなったので、なぜこの2つのパワーハウスを一緒に打ち砕かないのか!? それはまさに我々がここでやろうとしていることです。
このガイドでは、we're going to forge a formidable AI agentOpenAI Agents SDK を活用し、MCP サーバーが提供するリアル ワールド ツールに直接接続します。
MCP + OpenAI エージェント SDK インテグレーション
OpenAI Agents SDKは、インテリジェントなAIエージェントを作成するための最も人気のあるPythonツールキットの1つで、彼らに理性と行動を与えますが、ここにキッカーがあります:外部の情報がなければ、彼らはしばしばトレーニングデータバブルに閉じ込められています。
MCP をあなたの AI のためのユニバーサル USB-C ポートとして考えて、それを接続する標準化された方法を提供します。どんな外部データ ソースまたはツール - ローカル ファイル、API、データベース、あなたが名前を付けます。
MCP を OpenAI エージェント SDK に統合すると、エージェントはリアルタイムでダイナミックなコンテキストを提供し、スマートで孤立したボットからパワーハウス データ エクスクリプターやアクション タッカーに変身します!
OpenAI Agents SDK を使用して MCP 統合による AI エージェントの構築
Okay, enough theory. You get it—MCP supercharges AI agents as they areアイアンマンアイコンの金属のコスチューム
この段階的なセクションでは、OpenAI Agents SDK - yep、OpenAIの新しいPython SDK - を使用して、MCP統合を搭載したAIエージェントを構築します。native MCP supportつまり、あなたのエージェントはスマートからスマートに移行することができます。スーパーパワー秒で
さて、小さな捕獲:OpenAIのAPIは無料ではありません。we’ll run it using Gemini as the LLM engine instead(心配しないでください、OpenAIや他のモデルでも交換する方法を示します。
では、どのMCPサーバーを使っているのか?
素晴らしい質問! 早く始めるには、私たちは接続します。MCP データサーバーウェブオートメーションおよびデータタスクのために構築されたMCPサーバーで、AIエージェントが検索、ブラウザ、アクションを行い、Webからリアルタイムのデータを抽出することができます。アンチボットトラップ.
具体的には、以下はBright Data MCP サーバ ️ によってサポートされるすべてのツールです。
Tool |
Description |
---|---|
|
Scrape SERP data (from Google, Bing, Yandex, and more) |
|
Scrape a URL and return content in clean Markdown |
|
Scrape a URL and return full HTML content |
|
View tool usage during the current session |
|
Get Amazon product info by URL |
|
Fetch Amazon reviews for a product |
|
Grab LinkedIn profile data |
|
Fetch LinkedIn company data |
|
Get ZoomInfo company profile |
|
Fetch Instagram profile details |
|
Get Instagram post data |
|
Grab Instagram reel data |
|
Fetch comments from an Instagram post |
|
Extract Facebook post info |
|
Get Facebook Marketplace listings |
|
Scrape Facebook business reviews |
|
Fetch data from X (formerly Twitter) posts |
|
Get Zillow property listings |
|
Fetch Booking.com hotel listings |
|
Extract YouTube video metadata |
|
Navigate to a new URL in a virtual browser |
|
Go back one page in the browser |
|
Go forward one page in the browser |
|
Click a page element (needs selector) |
|
Get all links and selectors on the page |
|
Type into a form or input |
|
Wait for an element to appear |
|
Capture a screenshot of the current page |
|
Get raw HTML from the page |
|
Extract text content from the page |
search_engine
SERPデータ(Google、Bing、Yandex、およびその他)の削除
scrape_as_markdown
Scrape a URL and return content in clean Markdown (URLをスクラップして、クリーンマークダウンでコンテンツを返します)
scrape_as_html
URLを削除し、完全なHTMLコンテンツを返します。
session_stats
現在のセッション中のツールの使用状況を表示
web_data_amazon_product
Amazonの製品情報はURLで入手できます。
web_data_amazon_product_reviews
Fetch Amazon 製品のレビュー
web_data_linkedin_person_profile
LinkedInプロフィールデータ
web_data_linkedin_company_profile
LinkedInの企業データ
web_data_zoominfo_company_profile
ZoomInfoのプロフィール
web_data_instagram_profiles
Instagramプロフィール詳細
web_data_instagram_posts
インスタグラムの投稿データ
web_data_instagram_reels
インスタグラム リアルデータ
web_data_instagram_comments
Fetch コメント from an Instagram post
web_data_facebook_posts
フェイスブックの投稿情報
web_data_facebook_marketplace_listings
Facebook Marketplaceの検索結果
web_data_facebook_company_reviews
Scrape Facebook ビジネスレビュー
web_data_x_posts
X (以前はTwitter) 投稿からのデータの回収
web_data_zillow_properties_listing
Zillow Property Listings の検索結果
web_data_booking_hotel_listings
Fetchボクシング.comホテルリスト
web_data_youtube_videos
YouTubeビデオメタデータ
scraping_browser_navigate
仮想ブラウザで新しいURLに移動する
scraping_browser_go_back
Go back one page in the browser (ブラウザに1ページ戻る)
scraping_browser_go_forward
Go forward one page in the browser (ブラウザで1ページ進む)
scraping_browser_click
ページの要素をクリックします(Needs Selector)
scraping_browser_links
Get all links and selectors on the page. ページ上のすべてのリンクと選択者を取得する
scraping_browser_type
Type into a form or input 形式または入力
scraping_browser_wait_for
要素が現れるのを待つ
scraping_browser_screenshot
現行ページのスクリーンショットを撮影
scraping_browser_get_html
ページから Raw HTML を取得する
scraping_browser_get_text
ページからテキストコンテンツを抽出
無制限のパワーを得るために、AIエージェントがMCPサーバーに話しかける方法をご覧ください!
ステップ #1:プロジェクト設定
このチュートリアルセクションに従うには、次の前提条件を持っていることを確認してください:
- Python 3.10+ ローカルにインストール
- Node.js をローカルにインストール
- OpenAI Agents SDK のサポートされている LLM プロバイダーからの API キー(この用に Gemini をお勧めします)
退屈なセットアップフラフを省略し、あなたがすでにこの構造を持つPythonプロジェクトを作成したと仮定します。
/openai-agents-mcp
├── venv/
├── .env
└── agent.py
仮想環境(仮想環境)venv/
)と必要なパッケージをインストールする:
pip install openai-agents python-dotenv
どこ:
- openai-agents は、OpenAI Agents Python SDK ── AI エージェントの魔法へのあなたのゲートウェイ
- python-dotenv は .env ファイルの値を読み取るためのものです。
次に、オープンagent.py
これらの環境変数を読み、エージェントのリリースに備える時間:
import asyncio
from dotenv import load_dotenv
import os
from agents import (
Runner,
Agent,
OpenAIChatCompletionsModel,
set_default_openai_client,
set_tracing_disabled
)
from openai import AsyncOpenAI
from agents.mcp import MCPServerStdio
# Load environment variables from the .env file
load_dotenv()
async def run():
# AI Agent logic goes here...
pass
if __name__ == "__main__":
asyncio.run(run())
ブーム!あなたは起きて、基本を駆け抜けています。
Step #2: Bright Data MCP Server で始める
だから、あなたあなたのAIエージェントがMCPサーバーと話したいですか?↓↓↓
では、まず、MCPサーバが必要になります(はい、明らかなキャプテン義務申告です!!
前述したように、我々は使用する。Bright Data MCP Serverこの部分は、まず、あなたのAPIキーをキャプチャし、公式のBright Data MCPサーバードキュメントに従ってサーバーを初期化します。.
準備が完了したら、以下のコマンドでサーバーを起動してください。
npx -y @brightdata/mcp
すべてが正しく設定されている場合は、次のような出力が表示されるはずです。
Checking for required zones...
Required zone "mcp_unlocker" already exists
Starting server...
イケメン!!
現在、エージェントがBright Data MCP サーバーに接続するために使用する環境変数を設定します。.env
ファイルを追加し、以下の2行を追加します。
BRIGHT_DATA_API_TOKEN="<YOUR_BRIGHT_DATA_API_TOKEN>"
BRIGHT_DATA_BROWSER_AUTH="<BRIGHT_DATA_BROWSER_AUTH>"
Bright Data MCP サーバー ドキュメントで説明したように、得た値で場所保持者を置き換えます。
戻る inagent.py
この2つのエントリーは、こんな感じで読んでください:
BRIGHT_DATA_API_TOKEN = os.getenv("BRIGHT_DATA_API_TOKEN")
BRIGHT_DATA_BROWSER_AUTH = os.getenv("BRIGHT_DATA_BROWSER_AUTH")
これらの値は、コードからMCP接続を初期化する際にすぐに使用します。
そして、それと同じように、あなたのMCPサーバは起動し、動作し、あなたのAIエージェントを忠実なサイデックとしてサービスする準備ができています。
STEP #3:あなたのAIエージェントを作成する
このセクションの入門で述べたように、我々はOpenAI Agents SDKと共にジェミニ(Yep、Googleの輝くLLM)を使用する予定です。
まずは外へ・・・あなたはそれさえできますか?二つ目は、なんでオープンだけ使わないの?↓↓
Responseええ、やれるんですよ!!Gemini exposes an OpenAI-compatible APIつまり、Drop-in 代替として OpenAI Agents SDK に直接接続できます。It’s free—OpenAIとは異なり、トークンであなたを請求するのが好きです。
したがって、OpenAIの代わりに双子座を使用する理由はこちらです! 💡
Chit-chat enough, let's wire things up. まずは、あなたを捕まえましょう。Google AI Studio の Gemini API キーand pop it into your.env
ファイル:
GEMINI_API_KEY="<YOUR_GEMINI_API_KEY>"
その後、Inagent.py
キーはこんな感じで読む:
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
今、すべてを結びつける機能を構築する──Gemini model, OpenAI SDK, and the MCP server(近いうちにコードで設定する予定です。
async def create_mcp_ai_agent(mcp_server):
# Initialize Gemini client using its OpenAI-compatible interface
gemini_client = AsyncOpenAI(
api_key=GEMINI_API_KEY,
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
# Set the default OpenAI client to Gemini
set_default_openai_client(gemini_client)
# Disable tracing to avoid tracing errors being logged in the terminal
set_tracing_disabled(True)
# Create an agent configured to use the MCP server and Gemini model
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant",
model=OpenAIChatCompletionsModel(
model="gemini-2.0-flash",
openai_client=gemini_client,
),
mcp_servers=[mcp_server]
)
return agent
別のサポートされているモデル(Claude、Mistral、またはその他のモデルなど)を使用したい場合は、単にbase_url
ちなみにモデル名は
↓↓↓Extra: 代わりにOpenAIを使用したいですか? 問題ありません。OPENAI_API_KEY
上記の論理を以下に置き換える:
async def create_mcp_ai_agent(mcp_server):
# Create an agent configured to use the MCP server and Gemini model
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant",
mcp_servers=[mcp_server]
)
return agent
シンプルな交換、同じインターフェイス――それがSDKの美しさです。
Oh, and if you're wondering where themcp_server
argument comes from - we will initialize it in the next step ( ↓ spoiler alert). 続きを読む!
ステップ #4: MCP サーバーの初期化
あなたの内側run()
async 関数、Bright Data MCP サーバをスピンアップnpx
こんな感じ:
async with MCPServerStdio(
name="Bright Data web data MCP server, via npx",
params={
"command": "npx",
"args": ["-y", "@brightdata/mcp"],
"env": {
"API_TOKEN": BRIGHT_DATA_API_TOKEN,
"BROWSER_AUTH": BRIGHT_DATA_BROWSER_AUTH,
}
},
client_session_timeout_seconds=180 # To avoid timeout errors
) as server:
# Create and initialize the AI agent with the running MCP server
agent = await create_mcp_ai_agent(server)
# AI agent loop logic...
ここで何が起きているのか? MCP サーバを起動するnpx -y @brightdata/mcp
, 環境変数を通じてあなたの認証を送信します。
タイトル: Don't Forget to Bumpclient_session_timeout_seconds
2位180
デフォルト(Default is5
(なぜなら)リアルタイムのスキャン、CAPTCHAの解決、および反ボット忍者の動きBright Data MCP サーバーによって実行される作業は時間が必要です. You don't want it timing out mid-mission.
✅甘い! 残っているのは、AIエージェントのループを切り落とすことだけ...それを巻き上げよう。
STEP #5: AI Agent Loop を定義する
MCP サーバーのアシンクブロック内では、REPL (Read-Eval-Print) ループを落とし、ユーザーがリクエストを入力し、MCP エージェントを介して送信し、魔法を取り戻すことができます。
while True:
# Read the user's request
request = input("Your request -> ")
# Exit condition
if request.lower() == "exit":
print("Exiting the agent...")
break
# Run the request through the agent
output = await Runner.run(agent, input=request)
# Print the result to the user
print(f"Output -> \n{output.final_output}\n\n")
この小さなPythonのスニップはあなたのAIエージェントのコマンドセンターです。それは継続的にあなたの要求をキャッチし、それをエージェントに供給し、そして最後の栄光ある結果を吐き出す。
あの「whoa」の瞬間を思い出したのだろうか。もしそうでないのなら、あなたのために書かせてください:you just wired up a full AI agent loop using the OpenAI Agents SDK + Bright Data’s MCP server + Gemini!
今、あなたは完全なコードを見る準備ができ、すべてが美しいフランケンシュタインのAI自動化のモンスターのようにまとめられています。
Step #6: Put It All Together
これは、OpenAI Agents SDK + MCP 統合のための最終的な Python スクリプトです(Gemini によって動作し、お金を節約します。
import asyncio
from dotenv import load_dotenv
import os
from agents import (
Runner,
Agent,
OpenAIChatCompletionsModel,
set_default_openai_client,
set_tracing_disabled
)
from openai import AsyncOpenAI
from agents.mcp import MCPServerStdio
# Load environment variables from the .env file
load_dotenv()
# Read the required secrets envs from environment variables
BRIGHT_DATA_API_TOKEN = os.getenv("BRIGHT_DATA_API_TOKEN")
BRIGHT_DATA_BROWSER_AUTH = os.getenv("BRIGHT_DATA_BROWSER_AUTH")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
async def create_mcp_ai_agent(mcp_server):
# Initialize Gemini client using its OpenAI-compatible interface
gemini_client = AsyncOpenAI(
api_key=GEMINI_API_KEY,
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
# Set the default OpenAI client to Gemini
set_default_openai_client(gemini_client)
# Disable tracing to avoid tracing errors being logged in the terminal
set_tracing_disabled(True)
# Create an agent configured to use the MCP server and Gemini model
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant",
model=OpenAIChatCompletionsModel(
model="gemini-2.0-flash",
openai_client=gemini_client,
),
mcp_servers=[mcp_server]
)
return agent
async def run():
# Start the Bright Data MCP server via npx
async with MCPServerStdio(
name="Bright Data web data MCP server, via npx",
params={
"command": "npx",
"args": ["-y", "@brightdata/mcp"],
"env": {
"API_TOKEN": BRIGHT_DATA_API_TOKEN,
"BROWSER_AUTH": BRIGHT_DATA_BROWSER_AUTH,
}
},
client_session_timeout_seconds=180 # To avoid timeout errors
) as server:
# Create and initialize the AI agent with the running MCP server
agent = await create_mcp_ai_agent(server)
# Main REPL loop to process user requests
while True:
# Read the user's request
request = input("Your request -> ")
# Exit condition
if request.lower() == "exit":
print("Exiting the agent...")
break
# Run the request through the agent
output = await Runner.run(agent, input=request)
# Print the result to the user
print(f"Output -> \n{output.final_output}\n\n")
if __name__ == "__main__":
asyncio.run(run())
たった81行のコードで、あなたは何を得ますか? ウェブをサーフィンできるAIエージェントは、アンチボットを回避し、リアルタイムのデータをキャッチし、それに戻って話す - まるでそれが大きな問題ではないかのように。
NEWのおかげプロトコルまた、OpenAI Agents SDKやBright Data MCPなどの先駆的なツールや、AI自動化は今では...あまりにも簡単です。
ステップ7: MCP パワート AI エージェントのテスト
AIエージェントをターミナルから実行する:
python agent.py
Linux/macOS について:
python3 agent.py
あなたは、以下のような友好的なプロンプトによって歓迎されます。
Your request ->
たとえば、エージェントに MCP ツールがどのようなものかを尋ねてみてください。
What tools are you linked to through MCP?
あなたは何かを返すでしょう:
あなたが見ることができるように、あなたのAIエージェントは、彼が接続できるすべてのBright Data MCPツールを知っており、それらを使用する準備ができています!
まあ、野獣を解放する時間だ!それらの明るいMCPツールを究極のテストに置こう:あなたのAIエージェントを指揮して、Amazon P5ページからいくつかのジュースなデータを掘り下げましょう。
それを実現するには、以下のようなスピードを与えてください。
From the Amazon product page "https://www.amazon.com/PlayStation%C2%AE5-console-slim-PlayStation-5/dp/B0CL61F39H/", extract the main info and return it in JSON format
それを実行し、結果は次のようになります。
特に、出力は以下のようになるはずです。
{
"title": "PlayStation®5 console (slim)",
"seller_name": "Amazon.com",
"brand": "Sony",
"description": "The PS5 console unleashes new gaming possibilities that you never anticipated. Experience lightning fast loading with an ultra-high speed SSD, deeper immersion with support for haptic feedback, adaptive triggers, and 3D Audio*, and an all-new generation of incredible PlayStation games. Lightning Speed - Harness the power of a custom CPU, GPU, and SSD with Integrated I/O that rewrite the rules of what a PlayStation console can do. Stunning Games - Marvel at incredible graphics and experience new PS5 features. Play a back catalog of supported PS4 games. Breathtaking Immersion - Discover a deeper gaming experience with support for haptic feedback, adaptive triggers, and 3D Audio technology. Vertical stand sold separately. *3D audio via built-in TV speakers or analog/USB stereo headphones. Set up and latest system software update required.",
"initial_price": 499,
"currency": "USD",
"availability": "In Stock",
"reviews_count": 6759,
"categories": [
"Video Games",
"PlayStation 5",
"Consoles"
],
"asin": "B0CL61F39H",
"buybox_seller": "Amazon.com",
"number_of_sellers": 1,
"root_bs_rank": 18,
"answered_questions": 0,
"domain": "https://www.amazon.com/",
"images_count": 5,
"url": "https://www.amazon.com/PlayStation%C2%AE5-console-slim-PlayStation-5/dp/B0CL61F39H?th=1&psc=1&language=en_US¤cy=USD",
"video_count": 6,
"image_url": "https://m.media-amazon.com/images/I/41ECK5cY-2L._SL1000_.jpg",
"item_weight": "10.6 pounds",
"rating": 4.7,
"product_dimensions": "14 x 17 x 7 inches; 10.6 Pounds",
"seller_id": "ATVPDKIKX0DER",
"date_first_available": "December 10, 2023",
"model_number": "CFI-2015",
"manufacturer": "Sony",
"department": "Video Games",
"plus_content": true,
"video": true,
"final_price": 499,
"delivery": [
"FREE delivery Monday, May 26",
"Or Prime members get FREE delivery Tomorrow, May 22. Order within 15 hrs 43 mins. Join Prime"
],
"features": [
"Model Number CFI-2000",
"Includes DualSense Wireless Controller, 1TB SSD, Disc Drive, 2 Horizontal Stand Feet, HDMI Cable, AC power cord, USB cable, printed materials, ASTRO’s PLAYROOM (Pre-installed game)",
"Vertical Stand sold separately"
],
"bought_past_month": 8000,
"is_available": true,
"root_bs_category": "Video Games",
"bs_category": "PlayStation Consoles",
"bs_rank": 15,
"badge": "Amazon's Choice",
"subcategory_rank": [
{
"subcategory_name": "PlayStation 5 Consoles",
"subcategory_rank": 1
}
],
"amazon_choice": true,
"product_details": [
{
"type": "ASIN",
"value": "B0CL61F39H"
},
{
"type": "Release date",
"value": "December 10, 2023"
},
{
"type": "Customer Reviews",
"value": "4.74.7 out of 5 stars6,759 ratings4.7 out of 5 stars"
},
{
"type": "Best Sellers Rank",
"value": "#18 in Video Games (See Top 100 in Video Games)#1 in PlayStation 5 Consoles"
},
{
"type": "Product Dimensions",
"value": "14 x 17 x 7 inches; 10.6 Pounds"
},
{
"type": "Type of item",
"value": "Video Game"
},
{
"type": "Item model number",
"value": "CFI-2015"
},
{
"type": "Item Weight",
"value": "10.6 pounds"
},
{
"type": "Manufacturer",
"value": "Sony"
},
{
"type": "Country of Origin",
"value": "China"
},
{
"type": "Batteries",
"value": "1 Lithium Ion batteries required. (included)"
},
{
"type": "Date First Available",
"value": "December 10, 2023"
}
],
"country_of_origin": "China",
"seller_url": "https://www.amazon.com/sp?ie=UTF8&seller=ATVPDKIKX0DER&asin=B0CL61F39H",
"customers_say": "Customers find the PlayStation 5 console runs well and performs mind-blowingly fast, with quick loading times and smooth game performance. The graphics quality receives positive feedback, with one customer highlighting its stunning 120Hz visuals, while the console is easy to set up with an intuitive user interface. Customers consider the price worth the investment and appreciate its pristine condition. The noise level receives mixed reviews, with some customers finding it super quiet while others report it being loud.",
"climate_pledge_friendly": false,
"sponsered": true,
"store_url": "https://www.amazon.com/stores/PlayStationPlayHasNoLimits/page/5AF5EF82-86EF-4699-B450-C232B3BD720E?lp_asin=B0CL61F39H&ref_=ast_bln&store_ref=bl_ast_dp_brandLogo_sto",
"ships_from": "Amazon.com",
"customers_say": {
"text": "Customers find the PlayStation 5 console runs well and performs mind-blowingly fast, with quick loading times and smooth game performance. The graphics quality receives positive feedback, with one customer highlighting its stunning 120Hz visuals, while the console is easy to set up with an intuitive user interface. Customers consider the price worth the investment and appreciate its pristine condition. The noise level receives mixed reviews, with some customers finding it super quiet while others report it being loud.",
"keywords": {
"positive": [
"Functionality",
"Gaming experience",
"Value for money",
"Graphics quality",
"Quality",
"Speed",
"Ease of setup"
],
"negative": null,
"mixed": [
"Noise level"
]
}
},
"max_quantity_available": 30,
"timestamp": "2025-05-21T10:46:13.487Z"
}
↓↓↓Wow! 🤯
One prompt, and you just scraped all the data from an Amazon product page.そして、どのサイトだけでなく、アマゾンは攻撃的なCAPTCHAと反ボット防御のおかげで、スキャンするのが有名です。
では、それはどうやって機能したのか? 舞台の裏で、AIエージェントが電話をかけた。web_data_amazon_product
MCP ツール—Bright Data MCP サーバが暴露する既製のパワー ツールの 1 つ. それは汚れた仕事を処理しました: CAPTCHA を解決し、ボット検出を回避し、商品を取得しました。
そしてそこで止まらない!
より複雑なプロンプトを作成することにより、AIエージェントにさらなる分析を依頼するために使用できます。結局のところ、AIエージェントはMCP駆動ツールキットからツールを自由に選択し、連鎖することができます。可能性は本当に無限️
このような強力な構造によって、世界はあなたのもの!トニー・モンタナ(Tony Montana)
最終思考
これで、OpenAI Agents SDKで構築されたAIエージェントを超過充電する方法がわかります - GPT、Gemini、または次に何が起動するか - をMCPサーバーに接続することによって。
細かいところで、我々は強力なBright Data MCP serverたった一つのThe私たちが実世界のAIワークフローを規模でサポートするために構築した多くのサービス.
Bright Dataでは、私たちの使命は単純です:誰にでも、どこにでも、AIにアクセスできるようにしますので、次回まで、好奇心を持って、勇気を持って、AIの未来を創造的に構築し続けてください。