Meta Ads MCP Server
> Self-hosted Model Context Protocol (MCP) server that gives Claude, ChatGPT and other AI agents secure, multi-tenant access to the Meta Marketing API for Facebook Ads and Instagram Ads. Built for advertising agencies managing many client ad accounts from a single AI assistant — with OAuth login, encrypted-at-rest tokens, rate-limit compliance and circuit breakers baked in.
>
> v4.0.0 (2026-09-18) — Node.js 22.13+ is now the minimum, the published tool schemas are generated by zod 4, and tool results over stdio are budgeted to fit the MCP SDK's read buffer. Nothing about tool names, parameters, authentication or transports changes. Since 3.6.0 the server also gained a hardened video pipeline (ads_get_video_media), Ad Library media, server-side video analysis with Gemini (ads_analyze_video), a one-call ad dossier (ads_get_ad_dossier) and four skills published as MCP resources and prompts. See docs/migration-v4.md and the CHANGELOG.
Table of contents
- What is Meta Ads MCP?
- Who is this for?
- Aligned with Meta's official MCP
- Features
- Tools (162 total)
- Quick start
- Authentication — three modes
- Setting up Sign in with Meta
- Registering System User tokens (no expiry)
- Connecting AI clients
- Common workflows
- Architecture overview
- Meta API compliance
- Deployment
- Local development
- Security
- FAQ / troubleshooting
- Contributing
- Resources
- License
What is Meta Ads MCP?
Meta Ads MCP Server is an open-source Model Context Protocol server that exposes the Meta Marketing API — the API behind Facebook Ads and Instagram Ads — as a set of well-typed tools that any MCP-compatible AI agent can call. Drop it in front of Claude, ChatGPT, Cline, Continue or any other MCP client and your assistant can manage campaigns, ad sets, creatives, audiences, insights, leads, comments and pixels across an unlimited number of ad accounts.
It is multi-tenant by design. Each user signs in with Facebook Login on a consent page, their long-lived (60-day) Meta token is encrypted with AES-256-GCM and stored in Firestore, and every MCP request automatically picks up the right token. There is no shared PIN, no token pasting, no plaintext at rest.
It is compliance-first. Every Meta throttling header (X-App-Usage, X-Business-Use-Case-Usage, x-fb-ads-insights-throttle, x-ad-account-usage, reach throttle) is parsed and respected per (token, account, use-case) bucket. A circuit breaker stops all calls for an account on abuse signal 1996 or repeated throttles. Insights guardrails reject dangerous parameter combinations before they hit Graph API.
It is deploy-ready. Stateless Streamable HTTP transport, Docker image, GitHub Actions workflow that ships to Google Cloud Run with Workload Identity Federation, gitleaks-scanned on every push, masked health checks. Or run it via stdio for single-tenant local use with Claude Desktop.
Who is this for?
- Marketing agencies that manage many client ad accounts and want one AI assistant that can act across all of them.
- In-house marketing teams with multiple users who need their own Meta token but a shared MCP endpoint.
- Developers building AI-powered tools, copilots or autonomous agents on top of Meta Ads.
- Solo operators who want to drive their own Meta account from Claude Desktop with zero infrastructure (
stdiomode).
Aligned with Meta's official MCP
On 2026-04-29 Meta launched a first-party remote MCP server at
mcp.facebook.com/ads (the "Ads AI Connectors" umbrella) with native support
for ChatGPT, Claude, and Perplexity. v3.0.0 of this project aligns its
vocabulary so the same prompts and agent patterns transfer cleanly between
both servers.
Meta's official MCP (mcp.facebook.com/ads) |
This project | |
|---|---|---|
| Auth model | Per-user OAuth in your AI client | Multi-tenant: agency operator handles N client accounts from one server |
| Tool surface | 29 tools (campaigns, ads, catalogs, 5 insight views, opportunity_score, dataset, errors, help) | 162 tools including the official 29-equivalent + audiences, lookalikes, lead forms, automated rules, A/B studies, async reports, billing invoices, custom conversions, asset uploads, comment moderation, cross-account macros, and full WhatsApp Business management (templates, phone numbers, flows, QR codes) |
| Hosting | Hosted by Meta | Self-hosted on Cloud Run / your infra; tokens encrypted at rest in Firestore |
| Cross-account | Per-user, single Meta login | Yes — ads_portfolio_summary aggregates across N accounts |
| Token control | Lives in your AI client | Server-side System User token registry per agency operator |
| Naming | ads_create_campaign, ads_update_entity, ads_insights_* |
Same naming, plus all the tools the official MCP doesn't ship |
When to use which:
- Single advertiser running their own ads from Claude/ChatGPT → Meta's
official MCP. Zero setup, first-party. - Agency operating across many client accounts, internal staff that should
not have direct Facebook login to every client, custom workflow / governance
needs, integration with internal stack → this project.
Features
- 162 tools covering campaign management, creatives, targeting, audiences, reporting, comments, billing, invoices, tokens, Instagram workflows, WhatsApp Business management, rate-limit observability, semantic insight views, diagnostics, help-center search, competitor research via the public Meta Ad Library (full ad cards with their images and videos), video analysis (keyframes or the MP4 itself for video-capable models), and agency-tier cross-account macros.
- Aligned vocabulary with Meta's official MCP server so agents transfer cleanly between both.
- Sign in with Meta (Facebook Login) — replaces shared PINs. Each user lands their own long-lived (60-day) Meta token.
- System User token registry — for tokens that don't expire, register them per user from the consent UI.
- Encrypted persistence — Meta tokens stored AES-256-GCM in Firestore; survive restarts so connections never drop.
- Email / domain / FB-id allowlist — public repo, private deployment: only listed identities can sign in.
- Multi-account support — each request carries its own Meta access token via
AsyncLocalStoragerequest context. - Cloud-ready — Streamable HTTP transport, stateless, Docker-ready, Google Cloud Run reference deploy.
- Stdio support — for local development with MCP clients like Claude Desktop.
- Compliance-first rate limiting — per-
(token, ad-account, use-case)bucketing of every throttle signal Meta publishes; reacts toestimated_time_to_regain_accessinstead of blind backoff. - Circuit breaker — abuse-signal (subcode 1996), temporary-block and repeated-throttle events stop all calls for the affected account, following Meta's explicit "stop making API calls" rule.
- Preventive write pacing — Ads Management
POST/DELETEare paced against the hourly BUC quota so bursts from agents never blow the limit. - Insights guardrails — dangerous parameter combinations (account-level + high-cardinality breakdowns, lifetime + breakdowns in sync,
time_range> 37 months) are rejected before hitting Meta. - Async reports with safe polling —
ads_run_report_and_waitone-shot with 5 s-min / 60 s-max backoff, properJob Failed/Job Skippedhandling. - Retry logic — exponential backoff on truly transient errors only (never on throttled requests).
Tools (162 total)
Ads tools use the ads_* naming convention, aligned with Meta's official MCP server; WhatsApp Business tools use whatsapp_*. Read tools declare readOnlyHint: true; mutating tools declare destructiveHint / idempotentHint and prefix descriptions with a ⚠️ warning.
| Category | Tools | Description |
|---|---|---|
| Accounts | 5 | ads_get_ad_accounts, ads_get_account_info, ads_get_pages_for_business (a Business Manager's own Pages), ads_get_ad_account_pages (Pages used for ads on an account), ads_get_user_pages (Pages the person can advertise with) |
| Business Manager access | 4 | ads_get_business_users, ads_get_asset_users, ads_assign_user_to_asset, ads_remove_user_from_asset — who is in a Business Manager and who can use each ad account, Page and pixel; give, change or take away that access by role (admin, advertiser, analyst; Pages also editor and moderator), each change read back from Meta |
| Campaigns | 5 | CRUD + status management |
| Ad Sets | 6 | CRUD + clone bundle (native ad-copy, 100% creative-type coverage incl. dynamic/Advantage+) |
| Ads | 6 | CRUD with creative assignment, UTM (url_tags) editing |
| Creatives | 10 | List, details, create/update, image/video library and uploads, ads_get_creative_ads (the ads that use a creative) |
| Creative media | 1 | ads_get_creative_media — downloads an ad's images (incl. carousel cards and video thumbnails) and returns them as inline MCP image blocks for visual analysis; video_delivery=frames adds real keyframes |
| Video media | 1 | ads_get_video_media — delivers an ad video so a model can analyze it: ffmpeg keyframes as image blocks (any multimodal model), the MP4 embedded as a resource blob (video-capable models such as Gemini, no intermediary), signed CDN links, or the thumbnail |
| Generic entity helpers | 4 | ads_get_ad_entities (with Meta filters), ads_update_entity, ads_activate_entity (mirror official MCP), ads_get_field_context (fields, filters, values and units per level, measured) |
| Activity log | 1 | ads_account_get_activity_logs — the account's change history: who changed what and when, with old and new values |
| Insights — power tool | 1 | ads_get_insights — full control over breakdowns, attribution, time series |
| Insights views | 5 | performance_trend, anomaly_signal, auction_ranking_benchmarks, industry_benchmark, advertiser_context |
| Targeting | 8 | Interest / behavior / demographic / geo / locale search, audience estimation, targeting description |
| Budget | 1 | Budget schedule management |
| Leads | 4 | Lead forms and lead retrieval |
| Audiences | 11 | Custom audiences, lookalikes, cross-account sharing, customer-list members (hashed on the server) and the ad sets that use an audience |
| Previews | 2 | Ad previews before launch |
| Pixels | 5 | Pixel details, events, custom conversions |
| Comments | 4 | Ad comment moderation |
| Rules | 5 | Automated rules and rule details |
| A/B tests and lift studies | 5 | List an account's studies (through its campaigns and ad sets), check a planned test before creating it, create an A/B test or a lift study on the account's Business Manager, read one study with its cells and objectives, edit or cancel a test (ads_experiment_check_eligibility, ads_experiment_abtest_update_test) |
| Reports | 4 | Async report creation, status, retrieval, and one-shot run+wait |
| Billing | 4 | Billing info, spend limits, and invoices (ads_get_invoices) |
| Diagnostics | 3 | ads_get_opportunity_score, ads_get_dataset_quality, ads_get_errors |
| Help search | 1 | ads_get_help_article — curated Meta Business Help Center search |
| Agency macros | 2 | ads_diagnose_underperformance, ads_portfolio_summary (cross-account) |
| Bulk ad creation | 1 | ads_bulk_create_video_ads — video URLs → upload, processing wait, auto-thumbnail, creative and ad in one call |
| Ad content editing | 1 | ads_update_ad_content — add, remove or replace the primary texts, headlines and descriptions of live ads, or change link, button or media; keeps the Facebook post when only primary texts change, or edits the post itself for one-text ads (allow_post_edit); dry run by default |
| Social proof | 2 | ads_duplicate_ad — copy an ad into other ad sets on the same creative, so the copies share its Facebook post, Instagram media and text options, and with them the likes, comments and shares (creating copies needs the Firestore store); ads_get_ad_social_proof — those counts per post, each ad's own engagement, and every ad of the account showing the same post |
| 3 | IG account and media lookup, ads_boost_ig_post (an organic post into a paused ad) |
|
| Ad Library search | 1 | ads_library_search — Meta's own Ad Library API, free: ads by keyword or Page in the countries they reached, with text, dates, platforms and public link |
| Ad Library (Apify) | 9 | Competitor ad research: ads_library_scrape the public Meta Ad Library by keyword or Facebook page, poll run status, page through results (each with a media summary and its offset), abort runs, ads_library_get_ad_details for the full card of one scraped ad with its images inline and its videos as thumbnails / keyframes / links, plus per-user Apify token register/status/delete |
| Ad dossier | 1 | ads_get_ad_dossier — one ad in full: ad, ad set, campaign, creative with copy and effective landing URL, targeting, performance with the video retention funnel and auction rankings, plus the media itself |
| Gemini video analysis | 4 | ads_analyze_video — the server watches the video with Gemini and returns hook, transcript, on-screen text, scenes, format, compliance flags and ideas to test; plus per-user Gemini key register/status/delete |
| Tokens | 4 | List / set-active / register / delete |
| Rate Status | 1 | Live view of quota usage, open circuits and write-pacer state |
| WhatsApp — WABAs & phones | 8 | whatsapp_get_business_accounts, phone number list/register/deregister/verify, business profile get/update |
| WhatsApp — Templates & analytics | 6 | Message template CRUD (whatsapp_create_template, edit, delete), WABA analytics (messaging/conversation/pricing), per-template analytics |
| WhatsApp — Flows | 6 | Flow list/create/update (incl. Flow JSON upload), publish, deprecate, delete |
| WhatsApp — QR & webhooks | 7 | QR deep-link CRUD (message_qrdls), webhook subscription get/subscribe/unsubscribe |
The ads_library_* tools read the public Meta Ad Library through the
curious_coder/facebook-ads-library-scraper
Apify actor, so they need no Meta permissions — but they do need an Apify token
and they cost money (about $0.75 per 1,000 ads). Each user registers their
own token with ads_library_register_apify_token; it is validated against the
Apify API and then stored encrypted with AES-256-GCM in Firestore, scoped to
that user, exactly like Meta tokens. Every scrape sends Apify a hard
maxTotalChargeUsd cap derived from the requested count, so a single run
cannot bill past it (the cap is per run, not a per-tenant budget).
Registering the token does not require going through an assistant: the
server serves an authenticated /auth/connections page that lists your
stored Meta tokens and your Apify connection, and lets you register, replace or
disconnect the Apify token at any time. The consent screen shown during OAuth
approval carries the same Apify section for first-time setup, plus a link to
that page. The ads_library_register_apify_token tool still works for agents
and headless setups.
Credential resolution fails closed: in multi-tenant mode a caller with no
OAuth identity is refused rather than falling back to a shared credential. The
APIFY_TOKEN environment variable is honoured only in single-tenant mode
(stdio transport, or no Meta OAuth app configured), so one advertiser's scrapes
can never be billed to the operator's Apify account.
Two operational caveats worth knowing: runs execute against the actor's
latest build, so an upstream change to its input schema or pricing can alter
behaviour without a change in this repo; and a scrape start that times out is
indeterminate rather than failed — Apify may have accepted it — so check
ads_library_list_runs before starting another.
Once a run has finished, ads_library_get_results lists each ad with a media
summary (display format, image and video counts, has_video, the CDN expiry)
and its absolute offset. ads_library_get_ad_details then returns the full
card of one ad — page, dates, platforms, delivery data, the copy per card
(DCO/DPA template copy is flagged and the real creative read from the cards),
links and any transparency blocks — with its images attached inline behind the
Meta CDN host allowlist and its videos delivered as thumbnails, ffmpeg keyframes
or signed links; ads_get_video_media takes the same dataset_id +
ad_archive_id to embed the MP4 for a video-capable model. Reading a dataset
is free on Apify. Media URLs are signed and expire roughly four days after the
scrape (the exact moment is reported as expires_at), so download promptly or
re-scrape.
Video analysis
ads_get_video_media lets an agent actually look at an ad video instead of
just its poster frame. The server downloads the video from Meta's CDN behind the
same SSRF guard as images (pinned DNS, every redirect re-validated, a host
allowlist limited to .fbcdn.net / .facebook.com / .cdninstagram.com),
validates it with ffprobe before any decode (container, stream count,
dimensions, duration), and then delivers it in the mode the calling model can
consume:
delivery |
What comes back | For |
|---|---|---|
frames (default) |
Evenly spaced keyframes as MCP image blocks — one contact sheet by default, frame_layout=individual for one image per frame, include_audio for an audio/aac block |
Claude, GPT and any image-capable model |
inline |
The MP4 itself as an MCP resource blob (video/mp4), transcoded to a compact 480p rendition that fits max_inline_bytes (20 MiB cap over HTTP; 6 MiB over stdio, shared with the poster and any images in the same result, because MCP SDK clients since 1.30 close the transport on any message above 10 MiB unless they raise the buffer) |
Video-capable clients such as Gemini CLI or agents on the Gemini API — no intermediary needed |
url |
Signed CDN links as resource_link blocks, with their expiry |
Clients that fetch media themselves |
thumbnail |
Poster image only | Cheap previews |
Sources can be a video_id, an ad_id or creative_id (every video in the
creative, capped by max_videos), or a scraped dataset_id + ad_archive_id
from the Ad Library (pass hint_offset from ads_library_get_results to skip
the dataset scan). ads_get_creative_media accepts the
same video_delivery for frames and url.
Operational guardrails, all configurable through the VIDEO_* variables in
.env.example: ffmpeg runs with no shell, a protocol and
format whitelist, single-threaded, with output size caps and a hard kill on
timeout; at most two jobs per instance with a bounded queue; a per-tenant
hourly limit; a per-call time budget under the Cloud Run request timeout
(videos that do not fit are reported as skipped rather than failing the call);
one scratch directory per video on tmpfs, removed before the next one starts;
and a 30 MB response budget shared with the images. Without ffmpeg on the
server the tool degrades to thumbnails and says so. The production image
installs ffmpeg and Cloud Run runs with 2 GiB / 2 vCPU and a size-limited
in-memory /tmp; /health reports ffmpeg: true|false once a probe has
been conclusive and omits the key until then. That deployment is pinned to
the second generation execution environment. Leaving the generation for
the platform to choose has already cost three deploys: with the in-memory
/tmp volume mounted the container never opened its port and logged nothing
at all.
Server-side analysis with Gemini
ads_analyze_video covers the remaining case: an agent whose own model cannot
ingest video at all. The server downloads the video through the same hardened
pipeline, sends it to Google Gemini with the user's own API key, and returns
a structured analysis — hook (with a 1-5 score and the reasoning), verbatim
transcript, on-screen text, scene list, audio, format (aspect ratio, pacing,
sound-off friendliness), branding, claims a reviewer might question, strengths,
weaknesses and concrete ideas to test. A focus question is answered directly.
It is the last resort by design, and the tool description says so: if your model
can watch video, delivery=inline is free and better; if it can see images,
delivery=frames is free and usually enough.
The key belongs to the user, not to the server. Each one registers their own on
/auth/connections or with ads_register_gemini_key, and it is validated
against the API and then stored encrypted (AES-256-GCM, its own AAD namespace)
exactly like the Meta and Apify credentials. GEMINI_API_KEY is honoured only
in stdio / single-operator mode: sharing one key across OAuth tenants would bill
everyone's analyses to the operator. Create a key at
aistudio.google.com/apikey.
Full operational detail is in docs/gemini-video-analysis.md.
What it costs and where the video goes, both stated in the tool description:
roughly USD 0.02 per ad against your own quota, and the video is sent to
Google. One at or below GEMINI_INLINE_MAX_BYTES (12 MB) is embedded in the
request and stored nowhere; a larger one goes through the Files API and is
deleted as soon as the analysis returns, with Google removing leftovers within
48 hours. Use a paid-tier key for client creatives: Google may use free-tier
inputs to improve its models.
Guardrails: a per-tenant hourly cap (GEMINI_ANALYSES_PER_TENANT_PER_HOUR,
default 20) that is refunded when nothing was billed, a short-lived result cache
keyed by tenant, video and options so a retry costs nothing, and the same job
runner, byte caps and time budget as the rest of the video pipeline. Everything
the model writes is delimited as untrusted content and flattened to single
lines, so an analysis cannot forge the structure around it.
Skills and MCP protocol surface
An agent connecting to this server does not have to work out which of 162 tools
answers a question. The server ships four skills and exposes them three
ways.
As MCP resources, under meta-ads://skills/. A client can list and read
them without any local installation:
| Resource | What it covers |
|---|---|
meta-ads://skills/meta-ads-mcp-guide |
Which tool answers which question, what writes cost, the ID and permission rules that make calls fail |
meta-ads://skills/meta-ads-creative-analysis |
How to look at a creative and the rubric to judge it by |
meta-ads://skills/meta-ads-video-analysis |
Which video delivery your model can ingest, how to read a hook and a retention curve |
meta-ads://skills/meta-ads-competitor-research |
The Ad Library scrape-poll-read sequence, its cost, and how to read a scraped record |
The guide carries three references of its own: a map of all 162 tools by intent
with the write tools marked, the call sequences for the recurring jobs, and a
safety-and-costs page.
As MCP prompts, which start a job with the right skill already in hand:
analyze_ad, analyze_ad_video, competitor_creative_research,
ad_library_ad_deep_dive, creative_performance_review and
account_health_check. In Claude Code they appear as
/mcp__meta-ads-mcp__analyze_ad and friends.
As instructions in the initialize response, so a client sees the rules
that matter — reads are free, writes are not, untrusted content is fenced —
before its first call.
To install them locally for Claude Code, Codex or Cursor, copy the directories:```bash
cp -r skills/* ~/.claude/skills/
A test keeps the tool map in step with the code: every registered tool must
appear in it, nothing that is not registered may, and the `⚠️` marks must agree
with each tool's own annotations.
WhatsApp tools require the `whatsapp_business_management` permission. Tokens issued before this scope was added must be re-authorized (sign in again through the OAuth flow) before the `whatsapp_*` tools will work, and the Meta App must have the **WhatsApp product** added in the developer dashboard.
Tool definitions live under src/tools/, wired together in src/tools/index.ts.
## Quick start
### Prerequisites
- **Node.js 22.13+** (the project uses Import Attributes for JSON imports). The Docker image runs the same major.
- **ffmpeg** (optional) — used by `delivery=frames`, by the compact `inline` transcode and by the compaction before a Gemini upload. Without it, `frames` falls back to thumbnails with a warning, `inline` only delivers an original that already fits the cap, and `ads_analyze_video` cannot shrink a video over its upload limit. The Docker image installs it.
- A **Meta access token** with `ads_management` and `ads_read` permissions, *or* a Meta App configured for Facebook Login (see below).
### Install & run
**Option A — from source (contributors, self-hosters):**```bash
git clone https://github.com/byadsco/meta-ads-mcp.git
cd meta-ads-mcp
npm install
npm run build
npm start
Option B — from GitHub Packages (npm): scoped to @byadsco, hosted on npm.pkg.github.com. Requires a GitHub Personal Access Token with read:packages scope.```bash
tell npm where the @byadsco scope lives
echo "@byadsco:registry=https://npm.pkg.github.com" >> .npmrc
echo "//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}" >> .npmrc
npm install @byadsco/meta-ads-mcp
npx meta-ads-mcp # HTTP transport, port 3000
npx meta-ads-mcp --transport stdio
**Option C — from GitHub Container Registry (Docker):**```bash
docker pull ghcr.io/byadsco/meta-ads-mcp:latest
docker run --rm -p 3000:3000 --env-file .env ghcr.io/byadsco/meta-ads-mcp:latest
The server starts on http://localhost:3000 with the /mcp endpoint and a health check at /health. New versions are published on every GitHub Release (releases).
Environment variables
See .env.example for the full list. The minimum to run an HTTP deployment with Meta OAuth login:```bash
SERVER_URL=https://your-host.com # required for OAuth redirect URIs
META_APP_ID=... # your Meta app
META_APP_SECRET=...
AUTH_ALLOWED_EMAILS=you@x.com # at least one allowlist source required
TOKEN_ENCRYPTION_KEY=$(openssl rand -hex 32)
SESSION_COOKIE_SECRET=$(openssl rand -base64 32)
OAUTH_SECRET=$(openssl rand -hex 32)
FIRESTORE_PROJECT_ID=my-gcp-project
Permissions that need Meta App Review are asked for only when `META_OAUTH_EXTRA_SCOPES` lists them. For example, editing an ad's post (`ads_update_ad_content` with `allow_post_edit`) needs `pages_manage_posts`. Set it once Meta approved the permission; people with a role on the app can use it before. People then sign in again to grant it.
For local development with `stdio` (no OAuth, no Firestore needed):```bash
META_ACCESS_TOKEN=EAA... # the only required value in stdio mode
Authentication — three modes
| Mode | Activated by | Used for |
|---|---|---|
| Sign in with Meta (recommended) | META_APP_ID + META_APP_SECRET + TOKEN_ENCRYPTION_KEY + allowlist |
Each user signs in with Facebook Login on /authorize. Their long-lived (60-day) token is encrypted in Firestore and auto-refreshed. |
| API key (service-to-service) | MCP_API_KEY=... |
Server-to-server clients pass X-API-Key and X-Meta-Token headers; bypasses the human OAuth flow. |
| Stdio / single-tenant | META_ACCESS_TOKEN=... |
Local development, single user; no HTTP server required. |
The repo is public but the deployment is private: nothing sensitive lives in the code. All secrets, allowlists, and tokens are runtime-only and never checked in. See SECURITY.md for the full security policy.
Setting up Sign in with Meta
-
Create a Meta App at :
- Add the Facebook Login product.
- In Facebook Login → Settings, set the Valid OAuth Redirect URI to/auth/meta/callback.
- In App Review → Permissions and Features, requestads_management,ads_read,pages_show_list,pages_read_engagement,business_management,whatsapp_business_management,email. While the app is in Development mode, only people listed under Roles can sign in. For thewhatsapp_*tools, also add the WhatsApp product to the app. -
Provision Firestore in your GCP project:
- In the Cloud Console: Firestore → Create database → Native mode → pick a region.
- Grant the Cloud Run runtime service accountroles/datastore.user. -
Generate the encryption key and secrets:
bash echo "TOKEN_ENCRYPTION_KEY=$(openssl rand -hex 32)" echo "SESSION_COOKIE_SECRET=$(openssl rand -base64 32)" echo "OAUTH_SECRET=$(openssl rand -hex 32)"
Store them as Cloud Run env vars (or in Secret Manager).
-
Configure the allowlist: at least one of
AUTH_ALLOWED_EMAILS,AUTH_ALLOWED_DOMAINS,AUTH_ALLOWED_FB_USER_IDSmust be set when Meta OAuth is enabled — otherwise startup fails. -
Connect Claude: point Claude (Desktop or Web) to
https:///mcp. On the first tool call Claude will open the/authorizepage in your browser, kick off Facebook Login, and you'll land on a consent screen with your token already provisioned. Approve once and Claude is connected.
For the full end-to-end flow with sequence diagram, cURL examples for /.well-known, /register, /authorize, /token, multi-tenant token resolution via AsyncLocalStorage, troubleshooting and verification steps, see docs/oauth-multi-tenant.md.
Registering System User tokens (no expiry)
Long-lived user tokens last 60 days and are auto-refreshed. If you prefer a token that does not expire (typical for agency System Users), open the /authorize consent page and use "Registrar System User token" — paste the System User access token, it is validated against Graph API /me, encrypted, and saved alongside your personal token. Switch the active token from the same UI.
Connecting AI clients
Claude Desktop (stdio)
Add to claude_desktop_config.json:```json
{
"mcpServers": {
"meta-ads": {
"command": "node",
…(正文过长,页面只展示前面部分,完整内容见仓库)
```
