首页 AI Connect the Claude API to the Facebook Marketing API with a System User Token (2026): MCP Connector, Tool Use and Agent SDK

Connect the Claude API to the Facebook Marketing API with a System User Token (2026): MCP Connector, Tool Use and Agent SDK

Connect the Claude API to Facebook ads server-side: Employee system user token, Messages API MCP connector, Claude tool use on the Marketing API, and the Agent SDK.

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

PatternHow Claude reaches MetaTokenBest for
MCP connector (Messages API, beta)Anthropic calls mcp.facebook.com/ads for youEmployee system user, in authorization_tokenQuick server-side agents
Tool use (your own functions)Your code calls the Marketing APIAny system user token you controlStrict, narrow integrations
Agent SDKThe SDK connects to the MCP serverEmployee system user, in headersMulti-step agents with approvals
Three ways to connect the Claude API to the Facebook Marketing API

Step 1: create the system user token

  1. 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 (
  2. ads MCP get started
  3. ).
  4. Assign only the ad accounts (and Pages) this integration needs.
  5. Click Generate new token, pick your app, and grant ads_mcp_management plus ads_read (reporting) or ads_management (drafting).
  6. 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})
DecisionMCP connectorTool use
Who calls MetaAnthropic’s infrastructureYour server
Tool surfaceMeta’s ads MCP tools, filtered by mcp_toolsetOnly the functions you define
Token handlingSent to Anthropic in the requestStays on your server
Zero data retentionNot eligibleDepends on your setup
EffortLowMedium
Claude MCP connector versus tool use for Facebook ads integrations

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

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

PandaWM WeChat QR code szcwh99

Official sources

All official pages checked on 2026-11-16. API versions, tool names and permission requirements change; the official pages prevail.

本文来自网络,不代表熊猫出海立场。转载请注明出处: https://www.pandawm.com/blog/connect-claude-api-facebook-marketing-api-system-user-token-en.html
上一篇
下一篇

作者: 熊猫出海编辑团队

熊猫出海(PandaWM)编辑团队,来自香港出海服务商熊猫出海,专注 Facebook、TikTok、Google 等海外广告开户与代投,以及 GEO/AI 搜索优化、多语言独立站建设。有Facebook白名单牌照户、TikTok加白户、Google G2认证户等核心资源 。

为您推荐

发表回复

联系我们

联系我们

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部