Python + LangChain + OpenAI with Meta Ads MCP
Run a minimal Python script to connect to the Pipeboard Meta Ads MCP and get instant campaign insights with AI.
Stop wasting time on manual campaign analysis. This guide shows you how to build an AI agent that reads your Meta Ads data and gives you actionable recommendations—all in about 30 lines of Python.
You'll create a script that finds your most active account, identifies top-spending campaigns, and delivers optimization insights. No API wrestling, no data formatting—just results.
Takes 5 minutes to set up.
- Python 3.10+
- OpenAI API key
- Pipeboard account and token
pip install --upgrade langchain-mcp-adapters langgraph mcp langchain langchain-openai pydantic
OPENAI_API_KEYPIPEBOARD_API_TOKENCreate pipeboard_analysis.py:
import asyncio, os, sys
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
def env(k):
v=os.getenv(k)
if not v:
print(f"{k} is required")
sys.exit(1)
return v
def to_text(r):
try:
if isinstance(r,dict) and "messages" in r:
m=r["messages"]
if isinstance(m,list) and m:
last=m[-1]
if isinstance(last,dict): return str(last.get("content", last))
c=getattr(last,"content",None); return str(c if c is not None else last)
return str(r)
except Exception:
return str(r)
async def run():
t=env("PIPEBOARD_API_TOKEN")
model=os.getenv("OPENAI_MODEL","openai:gpt-4.1")
url=os.getenv("MCP_META_ADS_URL","https://mcp.pipeboard.co/meta-ads-mcp")
# Note: You can also use query parameter auth by adding f"?token={t}" to the URL
# but header auth (shown below) is more secure and recommended
client=MultiServerMCPClient({"meta-ads":{"transport":"streamable_http","url":url,"headers":{"Authorization":f"Bearer {t}","X-Pipeboard-Token":t}}})
tools=await client.get_tools()
agent=create_react_agent(model,tools)
prompt = """You are a Meta Ads optimization assistant.
1) Find the most active ad account in the last 7 days.
2) In that account, find the top-spend campaign last 7 days.
3) Analyze performance and give 3–5 recommendations. Include names, IDs, spend, impressions, clicks, conversions, CTR, CPC, CPA/ROAS if available."""
resp=await agent.ainvoke({"messages":prompt})
print(to_text(resp))
if __name__=="__main__":
try: asyncio.run(run())
except KeyboardInterrupt: pass
Run it:
python pipeboard_analysis.py
- Find the ad account with the most activity in the last 7 days - Within that account, find the single campaign with the highest spend last week - Analyze performance and provide prioritized recommendations
- If you see an authentication error, confirm
PIPEBOARD_API_TOKENis set. - If the model fails, confirm
OPENAI_API_KEYis set and your plan supports the selected model. - If you see
ImportError: Unable to import langchain_openai, install the OpenAI integration for LangChain:pip install -U langchain-openai
With this script, you can analyze campaigns across all your ad accounts in seconds. No more switching between dashboards or exporting CSVs—your AI agent handles it all.
What you can do next:
- Ask the agent to compare performance across multiple campaigns
- Request budget optimization suggestions for underperforming ad sets
- Schedule this script to run daily and send reports via email or Slack
- Explore the full MCP API reference for advanced automation
Pro tip: Save hours every week by building custom reporting workflows that fit your exact needs.