Last updated: 16 November 2026. Meta, Anthropic and OpenAI documentation checked that day.
Not every team wants a chat window. If you are building an internal tool, a reporting bot or a SaaS feature, you’ll connect Claude to Facebook ads server-side: your backend holds a Meta system user token and calls the Claude API. This guide covers the token and the three patterns that work. For the chat setup, see how to connect Claude to Facebook Ads step by step.
Three patterns
| Pattern | How Claude reaches Meta | Token | Best for |
|---|---|---|---|
| MCP connector (Messages API, beta) | Anthropic calls mcp.facebook.com/ads for you | Employee system user, in authorization_token | Quick server-side agents |
| Tool use (your own functions) | Your code calls the Marketing API | Any system user token you control | Strict, narrow integrations |
| Agent SDK | The SDK connects to the MCP server | Employee system user, in headers | Multi-step agents with approvals |

Step 1: create the system user token
- In Meta Business Suite settings, open Users › System users and add a system user. For the ads MCP server it must be an Employee system user; Admin-role tokens can’t access it (
- ads MCP get started
- ).
- Assign only the ad accounts (and Pages) this integration needs.
- Click Generate new token, pick your app, and grant
ads_mcp_managementplusads_read(reporting) orads_management(drafting). - Copy the token once into your secret manager. You can’t view it again.
Your app also needs the “Create & manage ads with ads MCP server” use case, and agencies need Advanced Access on ads_mcp_management (Meta developer blog). For plain Marketing API calls, see Marketing API authentication.
# .env (add .env to .gitignore; never commit or paste tokens into a prompt)
META_API_VERSION=v27.0
META_AD_ACCOUNT_ID=act_<AD_ACCOUNT_ID>
META_PAGE_ID=<PAGE_ID>
META_SYSTEM_USER_TOKEN=<SYSTEM_USER_ACCESS_TOKEN>Pattern 1: Messages API MCP connector
The MCP connector lets the Messages API connect to a remote MCP server without your own MCP client. It’s in beta, supports only the tools part of MCP, and isn’t eligible for zero data retention (MCP connector). Deny tools by default and enable just the ones you need:
# Messages API + MCP connector (beta). pip install anthropic
import os, anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
resp = client.beta.messages.create(
model=os.environ.get("CLAUDE_MODEL", "claude-sonnet-5-5"),
max_tokens=2000,
betas=["mcp-client-2025-11-20"],
mcp_servers=[{"type": "url", "name": "meta-ads",
"url": "https://mcp.facebook.com/ads",
"authorization_token": os.environ["META_ADS_MCP_TOKEN"]}],
tools=[{"type": "mcp_toolset", "mcp_server_name": "meta-ads",
"default_config": {"enabled": False}, # deny by default
"configs": {"ads_get_ad_entities": {"enabled": True},
"ads_insights_performance_trend": {"enabled": True}}}],
messages=[{"role": "user", "content":
"Which campaigns in act_<AD_ACCOUNT_ID> had rising CPC over the last 7 days?"}],
)
print(resp.content)The token travels to Anthropic in the request, so give this integration its own read-only token where you can.
Pattern 2: Claude tool use with your own functions
If you’d rather your server be the only thing that talks to Meta, define a narrow tool and run the call yourself (tool use). Claude only sees the data you return:
# meta_api.py - minimal Marketing API client (Python 3.10+, pip install requests)
import os, time, json, uuid, requests
API = "https://graph.facebook.com/" + os.environ.get("META_API_VERSION", "v27.0")
TOKEN = os.environ["META_SYSTEM_USER_TOKEN"] # from env / secret manager only
ACT = os.environ["META_AD_ACCOUNT_ID"] # e.g. act_1234567890
THROTTLE = {4, 17, 613, 80000, 80003, 80004, 80014} # rate-limit codes in Meta's docs
def call(method, path, params=None, data=None, idem_key=None, tries=5):
headers = {"X-Client-Idempotent-Key": idem_key} if idem_key else {}
for attempt in range(tries):
r = requests.request(method, f"{API}/{path}", headers=headers, timeout=60,
params={**(params or {}), "access_token": TOKEN} if method == "GET" else None,
data={**(data or {}), "access_token": TOKEN} if method != "GET" else None)
for h in ("X-Business-Use-Case-Usage", "X-Ad-Account-Usage", "X-FB-Ads-Insights-Throttle"):
if h in r.headers:
print(h, r.headers[h]) # log usage, back off early
body = r.json()
err = body.get("error")
if not err:
return body
if err.get("code") in THROTTLE or r.status_code >= 500:
time.sleep(min(60 * 2 ** attempt, 900)) # exponential backoff
continue # same idem_key -> no duplicates
raise RuntimeError(json.dumps(err))
raise RuntimeError("rate limited: giving up, try later")
def key(run_id, name):
"""Stable idempotency key per object, so a retry never creates a duplicate."""
return str(uuid.uuid5(uuid.NAMESPACE_URL, f"{ACT}/{run_id}/{name}"))# Claude tool use with your own Marketing API function (no MCP). pip install anthropic requests
import os, json, anthropic
from meta_api import call, ACT
tools = [{
"name": "get_campaign_insights",
"description": "Read-only. Campaign-level spend, clicks, CTR, CPC and actions for a date preset.",
"input_schema": {"type": "object",
"properties": {"date_preset": {"type": "string",
"enum": ["yesterday", "last_7d", "last_30d"]}},
"required": ["date_preset"]}}]
client = anthropic.Anthropic()
msgs = [{"role": "user", "content": "Compare yesterday with the last 7 days and list 3 issues."}]
while True:
r = client.messages.create(model=os.environ.get("CLAUDE_MODEL", "claude-sonnet-5-5"),
max_tokens=1500, tools=tools, messages=msgs)
msgs.append({"role": "assistant", "content": r.content})
if r.stop_reason != "tool_use":
print(r.content[-1].text); break
results = []
for block in r.content:
if block.type == "tool_use":
data = call("GET", f"{ACT}/insights", params={
"level": "campaign", "date_preset": block.input["date_preset"],
"fields": "campaign_name,spend,clicks,ctr,cpc,actions"})
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": json.dumps(data.get("data", []))[:20000]})
msgs.append({"role": "user", "content": results})| Decision | MCP connector | Tool use |
|---|---|---|
| Who calls Meta | Anthropic’s infrastructure | Your server |
| Tool surface | Meta’s ads MCP tools, filtered by mcp_toolset | Only the functions you define |
| Token handling | Sent to Anthropic in the request | Stays on your server |
| Zero data retention | Not eligible | Depends on your setup |
| Effort | Low | Medium |

Pattern 3: Agent SDK for multi-step work
For agents that plan and draft campaigns, the Claude Agent SDK connects to the MCP server and lets you approve each write in a callback (Agent SDK Python). Use API-key authentication; Anthropic doesn’t allow third-party products to use claude.ai login.
# agent.py - Claude Agent SDK (pip install claude-agent-sdk), API-key auth
import asyncio, os
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
from claude_agent_sdk.types import PermissionResultAllow, PermissionResultDeny
READ_ONLY = {"mcp__meta-ads__ads_get_ad_accounts", "mcp__meta-ads__ads_get_ad_entities",
"mcp__meta-ads__ads_get_ad_preview", "mcp__meta-ads__ads_get_creatives"}
async def gate(tool_name, tool_input, context):
if tool_name in READ_ONLY:
return PermissionResultAllow(updated_input=tool_input)
if tool_name == "mcp__meta-ads__ads_activate_entity":
return PermissionResultDeny(message="Activation is done by a human in Ads Manager", interrupt=True)
if tool_name.startswith("mcp__meta-ads__"):
print("\nAgent wants:", tool_name, tool_input)
if input("Approve? [y/N] ").strip().lower() == "y":
return PermissionResultAllow(updated_input=tool_input)
return PermissionResultDeny(message="Not approved")
options = ClaudeAgentOptions(
mcp_servers={"meta-ads": {"type": "http", "url": "https://mcp.facebook.com/ads",
"headers": {"Authorization": "Bearer " + os.environ["META_ADS_MCP_TOKEN"]}}},
can_use_tool=gate, # do not also list gated tools in allowed_tools
strict_mcp_config=True,
)
async def main():
async with ClaudeSDKClient(options=options) as client:
await client.query("Draft (paused) a traffic campaign for act_<AD_ACCOUNT_ID> "
"from brief.md, then list what you created.")
async for msg in client.receive_response():
print(msg)
asyncio.run(main())Production checklist
- Separate tokens for reporting (ads_read) and drafting (ads_management).
- Log every tool call: input, approver, resulting object ID.
- Respect Marketing API limits and back off on 613 and 80000-series errors (
- rate limiting
- ).
- Keep model IDs in config and check Anthropic’s models page (
- models
- ).
- Rotate tokens and revoke them when people leave.
Guardrail details: Claude Agent SDK guardrails. Reporting automation: Claude reporting and budget rules.
How PandaWM uses Claude, Codex and Facebook ad accounts to speed up client ad delivery
This guide focuses on Claude, but in day-to-day client work PandaWM combines Claude, Codex and Facebook business ad accounts to help companies going global move faster through the repetitive loop of account setup → campaign structure → creatives → reporting → budget changes, so media buyers spend their time on strategy and creative judgement.
- Ad accounts: the client’s own Facebook ad account, or a business ad account opened compliantly through PandaWM’s account-opening service. The account belongs to the client and is never rented or shared.
- Claude: reading long docs and reports, drafting media plans and ad copy, drafting campaign structures in a paused state through Meta’s ads MCP server, and rule-based anomaly checks.
- Codex: writing and maintaining automation scripts (Marketing API, Insights reports, bulk uploads, budget rules) that run in a sandbox, on a schedule or in CI.
- Human sign-off: anything that spends money (activating ads, raising budgets) is approved by a media buyer, and a person makes the final call on Meta policy and creative compliance.
This describes a service capability only. There are no prices or rebates here, and PandaWM is not an official partner of Meta, Anthropic or OpenAI. See Facebook ads account opening & management (PandaWM service page) for account opening and management.
FAQ
Can I use the same token for the MCP server and the Marketing API?
Yes if it has the needed permissions, but separate tokens limit the damage if one leaks.
Does the MCP connector work on cloud platforms?
Anthropic lists it as beta on the Claude API and several cloud platforms; check the docs for your provider.
Which beta header should I use?
The docs list mcp-client-2026-09-15 and mcp-client-2025-11-20. Our example uses the latter.
Is tool use safer than MCP?
It’s narrower: Claude can only call what you define, and the Meta token never leaves your server.
Can the integration activate ads?
Technically yes. We recommend denying activation and keeping it in Ads Manager.
Compliance note: Use every workflow in this guide only on ad accounts, Pages and pixels that your company owns or is formally authorised to manage, through Meta’s official Marketing API, the ads MCP server or Ads CLI, with Business Manager system users and least-privilege permissions. Respect Meta’s rate limits and Advertising Standards, and keep a human review step before anything that can spend money. PandaWM does not sell, rent, share or transfer ad accounts, Business Managers or API keys, does not help anyone bypass ad review, regional restrictions, KYC, business verification or payment controls, and is not an official partner of Meta, Anthropic or OpenAI. Claude and OpenAI services are only offered to customers in their supported countries and regions; the account holder should be an entity legitimately established and operating in a supported region.
Related guides
- Facebook ads account opening & management (PandaWM service page)
- Overseas AI Token service: account setup + API access (PandaWM)
- How to connect Claude to Facebook Ads (step by step)
- Claude Agent SDK guardrails for Meta ads automation
- Claude Facebook ads reporting and budget-rule automation
- Meta ads MCP server: let AI agents manage your ads
- How to get a Claude (Anthropic) API key
- Claude API pricing
Talk to PandaWM: Facebook ad accounts + AI-assisted delivery
Tell us where your company is registered, your industry, target countries, landing page and expected monthly budget, and which part you want to automate first (account structure, creatives, reporting or budget rules). We pre-check eligibility and creatives, help you open a compliant Facebook business ad account, and build Claude or Codex workflows that run on your own accounts. We never sell, rent or share ad accounts.
WhatsApp: +852 5904 8602Telegram: @PANDA0134WeChat: szcwh99

Official sources
- Meta: Ads MCP server – get started
- Meta for Developers blog: ads MCP server available for developers (2026-07-16)
- Meta: Marketing API authentication
- Anthropic: MCP connector (Messages API)
- Anthropic: Tool use with Claude
- Anthropic: Agent SDK Python reference
- Meta: Marketing API rate limiting
- Anthropic: Models overview
All official pages checked on 2026-11-16. API versions, tool names and permission requirements change; the official pages prevail.

微信扫一扫打赏
支付宝扫一扫打赏
