Skip to main content
Glama
Facebook Pages MCP Server

Facebook Pages MCP Server

by asrrin29
README.md
# Facebook Pages MCP Server

An [MCP](https://modelcontextprotocol.io) (Model Context Protocol) server that lets AI
agents work with Facebook Pages through the [Graph API](https://developers.facebook.com/docs/graph-api).

An agent can list the Pages a person manages, read Page details, posts, comments,
photos, videos, events, Messenger conversations and Page Insights. If you allow
it, it can also publish posts, comment, upload media, and delete content.

Built on the [MCP Python SDK](https://py.sdk.modelcontextprotocol.io) (v2, `MCPServer`).
Targets Graph API `v27.0`, the current version; any version can be selected with
`FB_GRAPH_VERSION`.

## Disclaimer

This is an **unofficial, fan-made contribution**. It is **not** associated with,
endorsed by, or affiliated with Meta Platforms, Inc. or Facebook in any way.

This project was written **with the assistance of a large language model (LLM)**. Please
review the code before relying on it, especially for anything security-sensitive.

## Graph API coverage

Tools are grouped by what the underlying Graph API call does. The group decides
whether a tool is registered at all. See [Tool permissions](#tool-permissions).

| Tool | Graph API | Group |
|---|---|---|
| `pages_list` | `GET /me/accounts` | read |
| `pages_find` | `GET /me/accounts` (filtered locally) | read |
| `page_get` | `GET /{page-id}` | read |
| `page_posts_list` | `GET /{page-id}/posts` | read |
| `post_get` | `GET /{post-id}` | read |
| `post_comments_list` | `GET /{post-id}/comments` | read |
| `page_insights` | `GET /{page-id}/insights` | read |
| `post_insights` | `GET /{post-id}/insights` | read |
| `page_insights_metrics` | (metric name reference) | read |
| `page_photos_list` | `GET /{page-id}/photos` | read |
| `page_videos_list` | `GET /{page-id}/videos` | read |
| `page_albums_list` | `GET /{page-id}/albums` | read |
| `page_events_list` | `GET /{page-id}/events` | read |
| `page_conversations_list` | `GET /{page-id}/conversations` | read |
| `conversation_messages_list` | `GET /{conversation-id}/messages` | read |
| `token_debug` | `GET /debug_token` | read |
| `graph_batch` | `POST /{version}` with a `batch` parameter | read (POST/DELETE entries need write/delete) |
| `graph_follow` | `GET <next_url>` | read |
| `page_publish` | `POST /{page-id}/feed` | write |
| `post_comment_create` | `POST /{post-id}/comments` | write |
| `page_photo_publish` | `POST /{page-id}/photos` | write |
| `page_video_publish` | `POST /{page-id}/videos` | write |
| `graph_write` | `POST <path>` | write |
| `comment_delete` | `DELETE /{comment-id}` | delete |
| `post_delete` | `DELETE /{post-id}` | delete |

Four tools are always available. They describe this server, and only
`facebook_pages_status`, `token_debug`, and `facebook_pages_refresh_token` touch
Facebook data:

- `facebook_pages_status`: configuration, readiness, and the token's expiry.
- `facebook_pages_set_token`: use a pasted access token for the rest of the
  session, which is how an expired token is replaced without a restart.
- `facebook_pages_refresh_token`: mint a Page token that does not expire, using
  the app credentials. See
  [A Page token that never expires](#a-page-token-that-never-expires).
- `facebook_pages_list_tools`: the tools currently enabled.

### Reading Page Insights

Insights need explicit metric names, and Meta deprecates them by API version.
Call `page_insights_metrics` to get a grouped list of names worth trying
(`audience`, `engagement`, `followers`, `posts`, `reactions`, `video`, `media`,
`monetization`), then pass them to `page_insights` with a `period` or
`date_preset`. When a metric is unavailable the Graph error names it.

Meta deprecated a large group of Page Insights metrics for every API version, in
waves dated 2025-06-15 and 2025-11-15, and states a further wave for 2026-06-15.
Two families matter here:

- Reach: `page_impressions`, `post_impressions` and their paid, organic, viral,
  fan and non-viral breakdowns. Use `page_media_view` and `post_media_view` for
  impressions, or the `*_total_media_view_unique` metrics for unique reach. The
  paid breakdown is available as a breakdown on the media-view metrics.
- Page likes: `page_fans`, `page_fans_city`, `page_fans_country` and
  `page_fan_adds`. Use the follower metrics instead: `page_follows`,
  `page_follows_city`, `page_follows_country`, `page_daily_follows` and
  `page_daily_unfollows_unique`.

The reference tables still print the deprecated names, so they are not a reliable
guide. The list the API enforces is
[Deprecated Facebook Page Insights Metrics](https://developers.facebook.com/documentation/pages-api/platforminsights/page/deprecated-metrics).
One rejected metric fails the whole Insights request with error 100, which is why
the tools never offer them. `page_insights_metrics` lists every name the API
refuses under `retired_metrics`, with the replacement, and an Insights request
that names one is answered with that replacement instead of being sent to the
API. That list is Meta's published list plus names a live Page has been seen
rejecting: `page_post_engagements` is absent from Meta's page, yet v27.0 answers
it as invalid, so it is treated the same way. A metric outside both is still sent
to the API and reported as Graph states it.

Three constraints worth knowing before you build a report: Page Insights are only
available for Pages with 100 or more likes, most metrics update once per day, and
a `since`/`until` range covers at most 90 days.

### Choosing fields

The Graph API returns only the `id` of a node unless you ask for fields. Each
read tool therefore ships a default field set taken from the current reference.
Pass `fields` to replace that set outright, or `extra_fields` to add to it.

Two behaviours to plan around:

- A field the API does not recognise fails the whole request with error 100
  rather than returning nothing. The error names the field, so drop it and retry.
- Some fields are accepted on one endpoint and rejected on another. The Post
  field `link` fails any post request with error 12 and a message about
  `deprecate_post_aggregated_fields_for_attachement`. The message names
  attachments, which are accepted; `link` is the field at fault. Use
  `permalink_url`, which answers the same need, and the defaults omit `link`.
  `attachments` is accepted on a post node and on the `/{page-id}/posts` edge, so
  it is included for `post_get` and left out of list responses to keep them
  small.

The tools never send one field name twice. Graph reports a syntax error (2500)
when `fields` and `extra_fields` name the same field, so a name already present
is not repeated.

### Pagination

Read tools that return an edge add `more_available` and `next_url` to the
response. Pass that URL to `graph_follow` to get the next page; Graph pagination
links already carry the cursor and token. `limit` and `after` work too.

## Tool permissions

`MCP_TOOL_PERMISSIONS` decides which tools the AI can see and call. It is
grouped by what the underlying call does to Facebook data:

| Level | What it allows | Effect |
|---|---|---|
| `read` | list and fetch data | Nothing changes. Safe. |
| `write` | `page_publish`, `post_comment_create`, `page_photo_publish`, `page_video_publish`, `graph_write` | The AI publishes publicly under your Page name. |
| `delete` | `post_delete`, `comment_delete` | Content is removed for good. |

Levels do not imply one another. List everything you want:

```bash
MCP_TOOL_PERMISSIONS=read                # AI can only look at data
MCP_TOOL_PERMISSIONS=read,write          # AI can look at AND publish
MCP_TOOL_PERMISSIONS=read,write,delete   # AI has full control (dangerous)
```

Unset means read-only. An unknown value makes the server refuse to start, so a
typo can never silently widen access. A disabled tool is not registered, so it
never appears in `tools/list` and cannot be called.

## Quick start

### 1. Get a Page access token

1. Create (or open) an app in the [Meta for Developers](https://developers.facebook.com/apps/) dashboard.
2. Open the **Graph API Explorer**, pick your app, and request the Pages
   permissions you need:
   - read tools: `pages_show_list`, `pages_read_engagement`, `read_insights`
   - write tools: `pages_manage_posts`, `pages_manage_engagement`
3. Pick the Page and copy the token.
4. Exchange it for a **long-lived** user token (60 days), then call
   `GET /me/accounts?fields=id,name,access_token` with it and copy the
   `access_token` returned for your Page. Short-lived tokens expire in about two
   hours, and a Page token taken from a short-lived user token expires within a
   day. **A Page token taken from a long-lived user token has no expiry.** That
   is the value `FB_PAGE_TOKEN` should hold. The
   [access token debugging tool](https://developers.facebook.com/tools/debug/accesstoken/)
   shows what you have and when it expires.

`check` reports the same thing before you start the server:

```bash
facebook-pages-mcp-server check
#   OK: type=PAGE app='1234567890' scopes=4
#   Expiry: none (this token does not expire)
```

### Using a token for one call

Every tool also accepts an `access_token` argument that applies to that call
alone. Use it when the token you hold was never put in the server's environment,
or when the configured token has expired and nothing has been restarted:

```json
{"tool": "page_posts_list", "arguments": {"page_id": "846466585206528", "access_token": "EAAG..."}}
```

The configured token is a default, not the only credential a request may use. A
token given with a request is used for that request's `Authorization` header and
is never forwarded to Graph as a parameter. Nothing in the server changes: the
next call without one goes back to the configured value. `token_debug` and
`facebook_pages_status` inspect the token given with the call, so a token can be
checked before anything else is attempted.

### Replacing an expired token without a restart

A token can expire while the server runs. Rather than editing `.env` and
restarting, pass the new token to `facebook_pages_set_token`:

```json
{"tool": "facebook_pages_set_token", "arguments": {"access_token": "EAAG..."}}
```

The token is checked with `debug_token` first. A token that Graph rejects, or
that is already expired, is not applied, so a typo cannot leave every later call
failing. A token that is accepted is used by every later call in that process.
It is not written to the environment, so a restart goes back to the configured
value; set `FB_PAGE_TOKEN` to keep it permanently.

The same tool replaces the optional `FB_USER_TOKEN` when called with
`"scope": "user"`.

The parameter may also be named `token`, `page_token`, `accessToken`, or
`fb_access_token`, and a value may carry a `Bearer ` prefix or surrounding
quotes. An AI client often writes the call that way, and a request naming an
unrecognised parameter is rejected before any handler runs, which looks exactly
like a bad token. A token copied from an HTTP header or a config file is used as
written.

### A Page token that never expires

A Page token inherits the lifetime of the user token it was read with. Read with
a short-lived user token, it dies within a day. Read with a long-lived user
token, it has no expiry at all. The difference is one extra call, and doing it
once ends the cycle of minting tokens.

Set the app credentials once, then call `facebook_pages_refresh_token`:

```json
{"tool": "facebook_pages_refresh_token", "arguments": {"user_token": "EAAG..."}}
```

It performs the three steps in order: exchange the user token for a long-lived
one with `GET /oauth/access_token?grant_type=fb_exchange_token`, read
`me/accounts?fields=id,name,category,access_token` with that result, and use the
Page token that returns. The response includes `page_token`, so the value can be
stored as `FB_PAGE_TOKEN` and survive a restart. `never_expires: true` confirms
the result is the permanent kind.

What it needs:

- `FB_APP_ID` and `FB_APP_SECRET`, or `app_id` and `app_secret` with the call.
  The exchange authenticates as the app, so no access token can stand in for
  them. They are in the app dashboard under Settings > Basic.
- A user token that has not expired, passed as `user_token` or held in
  `FB_USER_TOKEN`. A Page token cannot be exchanged: with one, `me` is the Page,
  and a Page has no `accounts` edge. Graph also refuses an exchange for a token
  that has already expired, so an expired user token must be re-issued first.
- `page_id` when the user token manages more than one Page. The tool names the
  Pages it can see rather than guessing.

Nothing is applied until every step has succeeded. A Page token that
`debug_token` rejects, or that is already past its expiry, is not installed, so a
failed refresh leaves the working token in place.

The same flow is available before the server runs:

```bash
facebook-pages-mcp-server refresh-token --page 846466585206528
# Page:          846466585206528 (Prime Time It)
# Expiry:        none (this token does not expire)
#
# Set this as FB_PAGE_TOKEN:
#
# EAQ...long value...
```

The App Secret is sent only to the token exchange. No Page call carries it.

An app in *Development Mode* can only reach test users and Pages you own. That
is fine for trying this out; it is the safest way to run it.

A new app is created on the current Graph API version, and Meta issues its
access tokens for that version. The default `FB_GRAPH_VERSION` matches it. If you
pin an older version, set it to the one your app was created on; an app cannot
issue tokens for a version older than itself.

### 2. Install

```bash
cd facebook-pages-mcp-server
pip install -e .
```

### 3. Configure

```bash
cp .env.example .env
# edit .env:
#   FB_PAGE_TOKEN=...      (required)
#   FB_USER_TOKEN=...      (optional, only for pages_list / pages_find)
#   FB_APP_ID=...          (optional, only to mint a token that never expires)
#   FB_APP_SECRET=...      (optional, same)
#   MCP_API_KEY=...        (only needed for serve-http)
```

Generate the MCP server's own Bearer token:

```bash
facebook-pages-mcp-server gen-key
```

Verify the configuration and the token:

```bash
facebook-pages-mcp-server check
```

That runs one live `debug_token` call and prints the issuing app, the granted
scopes and the expiry.

### 4. Run

**stdio** (the default, for local MCP clients):

```bash
facebook-pages-mcp-server
# or: facebook-pages-mcp-server serve
```

**streamable HTTP** (for remote access, protected by a Bearer token):

```bash
facebook-pages-mcp-server serve-http
# → http://127.0.0.1:8900/mcp   (clients send: Authorization: Bearer <MCP_API_KEY>)
#   http://127.0.0.1:8900/health (unauthenticated liveness probe)
```

## Environment variables

| Variable | Required | Description |
|---|---|---|
| `FB_PAGE_TOKEN` | yes | Facebook Page access token. Every Page tool acts with it. Never a tool parameter. |
| `FB_USER_TOKEN` | no | User access token for `me/accounts` (`pages_list`, `pages_find`). Unset means those calls use `FB_PAGE_TOKEN`. |
| `FB_APP_ID` | no | Meta app ID. Used only by `facebook_pages_refresh_token` and `refresh-token` to exchange a user token. Set both or neither. |
| `FB_APP_SECRET` | no | Meta app secret. Sent only to the token exchange, never with a Page call. |
| `FB_GRAPH_VERSION` | no | Graph API version (default `v27.0`). Accepts `v27.0` or `27.0`; a bare major such as `v27` is rejected by the API. Set it to the version your app was created on. |
| `FB_GRAPH_BASE_URL` | no | Graph API base URL (default `https://graph.facebook.com`). Change only for a test double or proxy. |
| `MCP_API_KEY` | for `serve-http` | Bearer token(s) clients must present to use *this* MCP server. Comma-separated list supported. |
| `MCP_HTTP_HOST` | no | Bind host for `serve-http` (default `127.0.0.1`). |
| `MCP_HTTP_PORT` | no | Bind port for `serve-http` (default `8900`). |
| `MCP_ALLOWED_HOSTS` | no | Comma-separated `Host` allowlist for the HTTP transport (see note below). |
| `MCP_ALLOWED_ORIGINS` | no | Comma-separated browser `Origin` allowlist for the HTTP transport. |
| `MCP_TOOL_PERMISSIONS` | no | `read`, `write`, `delete`, comma-separated. Default (unset): `read`. See [Tool permissions](#tool-permissions). |
| `FB_VERIFY_SSL` | no | `true` (default) or `false`. Set `false` only for a local test double with a self-signed certificate. |
| `FB_TIMEOUT` | no | HTTP timeout in seconds (default `30`). |
| `FB_MAX_RETRIES` | no | Extra retries on transient Graph failures (default `2`). |
| `MCP_LOG_LEVEL` | no | `DEBUG`, `INFO`, `WARNING`, `ERROR` (default `INFO`). Logs go to stderr. |

A `.env` file in the working directory (or the project root) is loaded
automatically if `python-dotenv` is installed; real environment variables always
win.

**DNS rebinding protection:** when `serve-http` binds to a loopback host the SDK
enables DNS-rebinding protection and only allows `127.0.0.1`/`localhost` Host
headers. Serving from a real hostname? Bind to that interface (e.g.
`MCP_HTTP_HOST=0.0.0.0`) and set `MCP_ALLOWED_HOSTS`/`MCP_ALLOWED_ORIGINS`.

## MCP client configuration

### Claude Desktop / any stdio client

```json
{
  "mcpServers": {
    "facebook-pages": {
      "command": "facebook-pages-mcp-server",
      "env": {
        "FB_PAGE_TOKEN": "your-page-access-token",
        "MCP_TOOL_PERMISSIONS": "read"
      }
    }
  }
}
```

(Or point `command` at `python` with `args: ["-m", "facebook_pages_mcp_server"]`
and put the config in a `.env` file.)

### Streamable HTTP client

- URL: `http://<host>:8900/mcp`
- Header: `Authorization: Bearer <MCP_API_KEY>`

## Docker

A production `Dockerfile` (multi-stage, non-root, slim) and `docker-compose.yml`
are included. The container serves streamable HTTP on port `8900` by default.

```bash
# 1. configure
cp .env.example .env   # fill in FB_PAGE_TOKEN and MCP_API_KEY

# 2. build and run
docker compose up -d --build

# 3. verify
curl http://localhost:8900/health
# → {"status": "ok", "server": "facebook-pages-mcp-server", "version": "1.6.1"}
```

MCP clients connect to `http://<host>:8900/mcp` with
`Authorization: Bearer <MCP_API_KEY>`.

`docker-compose.yml` passes every environment variable through from `.env`
(required ones fail fast with a clear message if unset) and applies container
hardening: non-root user, `cap_drop: ALL`, `no-new-privileges`, read-only root
filesystem, bounded log files, and a `/health`-based healthcheck.

Running without compose:

```bash
docker build -t facebook-pages-mcp-server .
docker run --rm -d --name fb-pages-mcp -p 8900:8900 --env-file .env \
  -e MCP_HTTP_HOST=0.0.0.0 facebook-pages-mcp-server
```

**Serving behind a real hostname:** DNS-rebinding protection auto-enables for
loopback binds. For a public hostname, set `MCP_ALLOWED_HOSTS` (and
`MCP_ALLOWED_ORIGINS` for browser clients) in `.env`. Terminate TLS at a reverse
proxy (Caddy/Traefik/nginx) in front of the container; the server itself speaks
plain HTTP.

**stdio in a container** (for MCP clients that spawn processes):

```bash
docker run --rm -i --env-file .env facebook-pages-mcp-server serve
```

## Troubleshooting

**The server reports an unexpected Graph API version.** A process keeps the
configuration it read at start, so a server that is still running after you
changed `.env` or reinstalled the package keeps answering with the old values.
Restart it. The startup line and `facebook_pages_status` both name the version in
use, so compare them with `FB_GRAPH_VERSION`. If you installed with `pip install .`
rather than `pip install -e .`, a later source edit is not picked up until you
install again.

**A tool you added is missing, or behaves as it did before the change.** The
process you are calling is not the build you edited. A rebuild on disk changes
nothing until the running process is replaced, and an MCP client can stay attached
to an older process across a rebuild. `facebook_pages_list_tools` lists the tools
the serving process registered, so a tool that is absent there is not in that
process regardless of what the source says. Confirm the version the same way:
`curl http://<host>:<port>/health` prints the `version` the process was built
from. Compare it with `--version` for the package you intend to run.

**The token exchange answers `Error validating client secret` (code 1).** The App
ID was accepted and the secret was not, which is what a half-set pair looks like:
Graph receives an empty `client_secret` and reports it as invalid rather than as
missing. `check` and `facebook_pages_status` name the variable that is unset as
`missing_app_credential`. Set both `FB_APP_ID` and `FB_APP_SECRET`, or neither.

**Insights return an invalid-metric error (code 100).** One unsupported metric
fails the whole request. A metric the server knows the API refuses is caught
before the request and answered with its replacement, so this error now means a
name that is not on that list. Call `page_insights_metrics` and read
`retired_metrics` for the replacement. The list Meta enforces is linked under
"Reading Page Insights" above; the reference tables still print deprecated
names.

**A read fails on a field you did not ask for.** Drop the field named in the
error, or pass your own `fields`. Some fields are valid on one endpoint and not
another, as described under "Choosing fields".

**`pages_list` answers `(#100) Tried accessing nonexisting field (accounts)`.**
The token in use is a Page token. With one, `me` is the Page itself, and a Page
has no `accounts` edge. That tool needs a user token, which is what lists the
Pages a person manages. A token supplied with a call is used exactly as given, so
this error is Graph naming the token's kind rather than a fault in the request.

**Every call fails with code 190.** The Facebook token is the problem, not the
code. An expired token says so and quotes the date Graph gave, for example
`Session has expired on Friday, 13-Nov-26 14:00:00 PST`. Pass a new one to
`facebook_pages_set_token` to use it from now on, or name it as `access_token`
with a single call to use it once. `facebook_pages_status` reports the expiry of
the token in use, and `check` prints it before the server starts.

A token that dies on a schedule is not fixed by replacing it again. Set
`FB_APP_ID` and `FB_APP_SECRET` and call `facebook_pages_refresh_token`: it
mints a Page token with no expiry. See
[A Page token that never expires](#a-page-token-that-never-expires).

## Development

```bash
pip install -e ".[dev]"
pytest            # unit tests (mocked Graph API) + end-to-end tests
```

The end-to-end suite starts the real server (stdio and streamable HTTP) against a
bundled mock Graph API (`tests/mock_graph.py`) that implements the documented
request and response shapes, so no live Facebook token is needed. The mock also
records the requests the server made, so the tests assert on the paths and
parameters, not only on the results.

## Project layout

```
facebook_pages_mcp_server/
├── __init__.py      # package metadata
├── __main__.py      # CLI: serve, serve-http, gen-key, check, refresh-token
├── config.py        # environment variable handling
├── graph.py         # async Graph API client (httpx) + error handling
├── refresh.py       # minting a Page token that does not expire
├── server.py        # MCPServer + tool registration + HTTP auth
├── specs.py         # catalog of every tool: tier, description, endpoint
└── tokens.py        # token expiry and token-failure messages
tests/
├── mock_graph.py    # mock Graph API for tests
├── test_graph.py    # client and configuration unit tests
├── test_tokens.py   # token diagnostics unit tests
└── test_e2e.py      # full server tests (stdio + HTTP)
```

## Security notes

- The MCP Bearer token is read only from the environment and is never logged.
- The Facebook token is read from the environment, except when you pass a
  replacement to `facebook_pages_set_token`. It is never logged, never written to
  the environment by the server, and never included in a tool response. Only the
  token's type, scopes and expiry are reported.
- The Facebook token is sent in the `Authorization: Bearer` header, so it never
  appears in a URL, an access log, or a Graph pagination link.
- `MCP_API_KEY` comparison is constant-time (`hmac.compare_digest`).
- Facebook access tokens expire. `facebook_pages_status` reports the type,
  scopes and expiry of the token in use, and an expired token makes it report
  `ready: false`. A Page token from a long-lived user token has no expiry, which
  is the state to aim for; `facebook_pages_set_token` replaces a dead token
  without a restart.
- Use HTTPS for anything beyond localhost, and rotate the MCP token regularly.
- Keep the app in Development Mode, or scope the token to one test Page, before
  enabling `write` or `delete`.
- `MCP_TOOL_PERMISSIONS` is the first line of defense: the AI only ever sees the
  tools you allow (read-only by default). It complements, not replaces, the
  scopes on the Facebook token. Use both.

## License

Distributed under the [MIT License](LICENSE). See the `LICENSE` file for full
terms.

TDQS

B3.4/5.0

Scored across 22 tools

Disambiguation4/5

Most tools map to a single resource+action (page_get, post_get, page_photos_list), so an agent can pick correctly. A few pairs overlap: pages_list vs pages_find, page_insights vs page_insights_metrics, and token_debug vs facebook_pages_status all answer similar questions, and set_token vs refresh_token both change the session token, but descriptions distinguish them.

Naming Consistency4/5

All names are snake_case and follow a resource-first pattern (page_*, post_*, graph_*), which is readable and predictable. Minor deviations: the collection prefix is plural 'pages_' for two tools, admin/utility tools use a different 'facebook_pages_' prefix, and page_insights_metrics lacks an action verb.

Tool Count4/5

22 tools is on the heavy side but each maps to a distinct Graph API edge or utility (posts, comments, insights, photos, videos, albums, events, messaging, auth, pagination, batch). Some listing tools could be collapsed into a generic edge reader, but nothing is clearly redundant.

Completeness3/5

The surface is almost entirely read-only: there are no direct tools to publish a post, reply to or moderate a comment, send a Messenger message, upload media, or create an event, which are core Facebook Pages workflows. graph_batch is an escape hatch for writes, but only if the agent already knows the raw Graph paths and has the write permission.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues