← Back to Guides

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.

Prerequisites
What you need before you start
Install dependencies
One-time setup
pip install --upgrade langchain-mcp-adapters langgraph mcp langchain langchain-openai pydantic
Set environment variables
Minimal configuration
OPENAI_API_KEY
PIPEBOARD_API_TOKEN
Create and run the script
Finds the most active account last week, top-spend campaign, and provides recommendations

Create pipeboard_analysis.py:

@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")
    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
What the agent asks
Prompt summary
- 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
Troubleshooting
Common issues
  • If you see an authentication error, confirm PIPEBOARD_API_TOKEN is set.
  • If the model fails, confirm OPENAI_API_KEY is 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