Skip to main content
meta-agent-bridge

meta-agent-bridge

Agentic-first omnichannel Meta messaging SDK — one canonical schema across WhatsApp Cloud API, Messenger, and Instagram.

PyPI Python 3.12+ License: MIT mypy: strict Ruff

Architecture • Installation • Quickstart • Capabilities • Resumable Sends • Error Handling • Testing • Roadmap


Why meta-agent-bridge

Single-tenant bot wrappers couple your agent to one Meta surface, leak HTTP clients onto message objects, or force you through paid SaaS middlemen. meta-agent-bridge gives AI agents direct, zero-markup control over Meta's APIs:

  • One Canonical Schema (AgentEvent / AgentResponse): Write your LangGraph, PydanticAI, or plain Python agent once against AgentEvent and AgentResponse — never branch on Meta payload dialects.
  • 4 Official Meta Surfaces (Graph API v27.0): Supports WhatsApp Cloud API, Facebook Messenger, Instagram (Facebook Login), and Instagram (Instagram Direct Login) out of the box.
  • Pure Sync Sans-I/O core/: parse_webhook() and compile() run synchronously with zero httpx or driver imports in core/, making them safe for FastAPI, Celery, or unit tests.
  • JSON-Serializable Events: Every AgentEvent carries schema_version: str = "1.0", a deterministic event_id: str for deduplication, and raw: dict[str, Any] — with zero bound HTTP clients or .reply() methods.
  • Multi-Tenant Connection Pooling: Share one httpx.AsyncClient across thousands of tenants; GraphTransport binds Authorization: Bearer ... and base_url strictly per request.
  • UnknownEvent Resilience: Unrecognized webhook payloads, echo events, or future Meta fields never raise ValidationError — they safely yield UnknownEvent.

Architecture

flowchart LR
    Agent["AI Agent / Queue Worker"] --> Bridge["bridge.py (SocialBridge)"]
    Webhook["FastAPI / Webhook Route"] --> Bridge
    Bridge --> Drivers["drivers/ (whatsapp.py, meta_messaging.py)"]
    Bridge --> Transport["transport/ (GraphTransport, MediaDownloader)"]
    Drivers --> Core["core/ (Pure Sync Sans-I/O: models, compiler, crypto, capabilities, errors)"]
    Transport --> Core
    Transport --> WA["graph.facebook.com (WhatsApp Cloud API)"]
    Transport --> FB["graph.facebook.com (Messenger & IG FB Login)"]
    Transport --> IG["graph.instagram.com (IG Direct Login)"]

Strict Dependency Direction: bridge.py → drivers/ & transport/ → core/. core/ never imports from drivers/, transport/, or httpx. SocialBridge is lazily exported at the package root so importing meta_agent_bridge.core stays completely sans-I/O.

Package Layout
src/meta_agent_bridge/
├── core/                  # Pure sync sans-I/O (zero httpx or driver imports)
│   ├── enums.py           # Channel, Surface
│   ├── models.py          # AgentEvent union, TenantTarget, AgentResponse, CompiledPlan, RequestSpec
│   ├── credentials.py     # Typed per-surface credentials with SecretStr redaction
│   ├── capabilities.py    # Declarative CapabilityProfile limits + verified_on date
│   ├── compiler.py        # Pure compile_response(response, profile, target) -> CompiledPlan
│   ├── crypto.py          # Constant-time X-Hub-Signature-256 & hub.challenge helpers
│   └── errors.py          # Flat MetaError, ErrorCategory, declarative ERROR_MAP
├── transport/             # Async httpx execution layer
│   ├── http.py            # GraphTransport (injected/managed AsyncClient, per-call Bearer auth)
│   └── media.py           # SSRF-safe MediaDownloader (WA 2-step media_id & CDN URLs)
├── drivers/               # Depends ONLY on core/
│   ├── base.py            # ChannelDriver protocol
│   ├── whatsapp.py        # WhatsApp Cloud API parser & RequestSpec renderer
│   └── meta_messaging.py  # Shared Messenger / IG-FB / IG-Direct parser & renderer
├── bridge.py              # SocialBridge public facade
└── testing/               # FakeMetaTransport & signed webhook payload factories

Installation

uv add meta-agent-bridge

Or with pip:

pip install meta-agent-bridge

Requires Python 3.12+. Core runtime dependencies are strictly httpx and pydantic>=2.0.


Quickstart

Step 1: Webhook Ingestion (FastAPI)

Verify X-Hub-Signature-256 (enabled by default), parse batched entry[] payloads synchronously, and push serialized JSON events to your background queue:

from fastapi import FastAPI, Header, HTTPException, Request, Response

from meta_agent_bridge import SignatureVerificationError, SocialBridge

app = FastAPI()
bridge = SocialBridge()

APP_SECRETS = ["meta-app-secret", "instagram-app-secret"]  # single str or candidate sequence
VERIFY_TOKEN = "my-webhook-verify-token"


@app.get("/webhook")
def verify_webhook(request: Request) -> Response:
    try:
        challenge = bridge.verify_challenge(request.query_params, VERIFY_TOKEN)
        return Response(content=challenge, media_type="text/plain")
    except SignatureVerificationError as exc:
        raise HTTPException(status_code=403, detail=exc.message) from exc


@app.post("/webhook")
async def ingest_webhook(
    request: Request,
    x_hub_signature_256: str | None = Header(default=None),
) -> dict[str, int]:
    raw_body = await request.body()
    try:
        events = bridge.parse_webhook(
            raw_body,
            signature=x_hub_signature_256,
            app_secret=APP_SECRETS,
        )
    except SignatureVerificationError as exc:
        raise HTTPException(status_code=401, detail=exc.message) from exc

    for event in events:
        payload_json = event.model_dump_json()
        # Enqueue payload_json into Redis / Celery / SQS here
        _ = payload_json

    return {"accepted": len(events)}

Step 2: Agent Worker Reply

Deserialize an AgentEvent in your worker, build a channel-neutral AgentResponse, and dispatch with await bridge.send(...):

from pydantic import SecretStr

from meta_agent_bridge import (
    AgentEventAdapter,
    AgentMessageEvent,
    AgentResponse,
    Choice,
    MediaType,
    OutboundMedia,
    SenderAction,
    SocialBridge,
    WhatsAppCredentials,
)


async def handle_queued_event(raw_event_json: str) -> None:
    event = AgentEventAdapter.validate_json(raw_event_json)
    if not isinstance(event, AgentMessageEvent):
        return

    creds = WhatsAppCredentials(
        access_token=SecretStr("EAAG..."),
        phone_number_id=event.target.tenant_id or "109876543210",
    )

    response = AgentResponse(
        text="Here is your invoice. Would you like to pay now?",
        media=(
            OutboundMedia(
                media_type=MediaType.IMAGE,
                url="https://lookaside.fbsbx.com/example/invoice.png",
            ),
        ),
        choices=(
            Choice(id="pay_now", title="Pay Now"),
            Choice(id="remind_later", title="Remind Later"),
        ),
        actions=(SenderAction.MARK_READ, SenderAction.TYPING_ON),
        reply_to_message_id=event.message_id,
    )

    async with SocialBridge() as bridge:
        result = await bridge.send(response, event.target, creds)
        if not result.succeeded:
            print("Failed step:", result.failed_step_id)

Step 3: Multi-Tenant Credentials

Pass the credential model matching each tenant's channel and auth flavor — GraphTransport routes to the right Meta host and binds the token per call:

from pydantic import SecretStr

from meta_agent_bridge import (
    InstagramDirectCredentials,
    InstagramFacebookCredentials,
    MessengerCredentials,
    WhatsAppCredentials,
)

wa_creds = WhatsAppCredentials(
    access_token=SecretStr("EAAG..."),
    phone_number_id="109876543210",
)
ms_creds = MessengerCredentials(
    access_token=SecretStr("EAAG..."),
    page_id="page_90001",
)
ig_fb_creds = InstagramFacebookCredentials(
    access_token=SecretStr("EAAG..."),
    page_id="page_90001",
    ig_account_id="ig_acct_777",
)
ig_direct_creds = InstagramDirectCredentials(
    access_token=SecretStr("IGA..."),
    ig_account_id="ig_acct_777",
)

Capabilities

Verified against Meta Graph API v27.0 (CapabilityProfile.verified_on = 2026-12-01) in v0.1.0:

Capability WhatsApp Cloud API Messenger Instagram (FB Login) Instagram (IG Direct)
Base Host graph.facebook.com graph.facebook.com graph.facebook.com graph.instagram.com
Max Text Length 4096 (auto-chunked) 2000 (auto-chunked) 1000 (auto-chunked) 1000 (auto-chunked)
Interactive Choices 1–3 reply buttons · 4–10 list rows 1–13 quick replies 1–13 quick replies 1–13 quick replies
Recipient Routing Phone (to) & BSUID (recipient) PSID (recipient.id) IGSID (recipient.id) IGSID (recipient.id)
Typing & Read Receipts Coupled status="read" + typing_indicator Separate sender_action Separate sender_action Separate sender_action
Media + Choices Split Emits MediaStep then interactive Allowed together / sequential Enforced split (MediaStep → ButtonsStep) Enforced split (MediaStep → ButtonsStep)
Media (URL / media_id) Supported (inbound & outbound) Supported (inbound & outbound) Supported (inbound & outbound) Supported (inbound & outbound)
Inbound Location (Maps) Supported (LocationData) Supported (LocationData) Supported (LocationData) Supported (LocationData)
Templates Planned v0.2.0 Planned v0.2.0 Planned v0.2.0 Planned v0.2.0
Link / URL Buttons Planned v0.2.0 Planned v0.2.0 Planned v0.2.0 Planned v0.2.0
Emoji Reactions Planned v0.2.0 Planned v0.2.0 Planned v0.2.0 Planned v0.2.0
Multipart Binary Upload Planned v0.2.0 Planned v0.2.0 — (hosted URL) — (hosted URL)

Resumable Sends

Meta's Send APIs do not support request idempotency keys. If a multi-step response (for example, mark_read → MediaStep → ButtonsStep) experiences a post-dispatch ReadTimeout, blindly retrying from step 1 can duplicate messages already delivered to the user.

meta-agent-bridge compiles every response into a deterministic CompiledPlan and returns a DispatchResult where each StepResult has a 3-state status: "sent", "failed", or "unknown" (ambiguous network failure after dispatch):

from meta_agent_bridge import (
    AgentResponse,
    Choice,
    Credentials,
    MediaType,
    OutboundMedia,
    SenderAction,
    SocialBridge,
    TenantTarget,
)


async def send_resumable(
    bridge: SocialBridge,
    target: TenantTarget,
    creds: Credentials,
) -> None:
    response = AgentResponse(
        text="Confirm your booking?",
        media=(
            OutboundMedia(
                media_type=MediaType.IMAGE,
                url="https://scontent.cdninstagram.com/booking.png",
            ),
        ),
        choices=(Choice(id="yes", title="Confirm"), Choice(id="no", title="Cancel")),
        actions=(SenderAction.MARK_READ,),
    )

    # Compile once into deterministic, JSON-serializable steps
    plan = bridge.compile(response, target, creds)
    result = await bridge.send_plan(plan, creds)

    if not result.succeeded and result.failed_step_id is not None:
        failed = next(r for r in result.results if r.step_id == result.failed_step_id)
        if failed.status == "failed" and failed.error is not None and failed.error.retryable:
            # Resume strictly from the failed step without duplicating prior "sent" steps
            await bridge.send_plan(plan, creds, resume_from=result.failed_step_id)
        elif failed.status == "unknown":
            # Delivery is ambiguous (e.g., ReadTimeout); inspect or prompt before retrying
            print("Ambiguous delivery at step:", failed.step_id)

Error Handling

All Graph API, transport, compilation, and verification failures raise or return a single flat MetaError carrying normalized metadata (category, channel, code, subcode, http_status, fbtrace_id, retryable, retry_after, delivery_ambiguous), plus four convenience subclasses for common except blocks:

from meta_agent_bridge import (
    AgentResponse,
    AuthError,
    MetaError,
    RateLimitError,
    SignatureVerificationError,
    SocialBridge,
    TenantTarget,
    WhatsAppCredentials,
    WindowExpiredError,
)


async def dispatch_with_handling(
    bridge: SocialBridge,
    response: AgentResponse,
    target: TenantTarget,
    creds: WhatsAppCredentials,
) -> None:
    plan = bridge.compile(response, target, creds)
    result = await bridge.send_plan(plan, creds)
    if result.succeeded:
        return

    err = result.results[-1].error
    if err is None:
        return

    try:
        raise err
    except SignatureVerificationError:
        print("Webhook HMAC or hub.verify_token invalid")
    except AuthError as exc:
        print(f"Token invalid/expired (code={exc.code}, fbtrace_id={exc.fbtrace_id})")
    except RateLimitError as exc:
        print(f"Rate limited; retry after {exc.retry_after}s (retryable={exc.retryable})")
    except WindowExpiredError:
        print("24h customer service window closed")
    except MetaError as exc:
        print(f"[{exc.category.value}] code={exc.code} subcode={exc.subcode}: {exc.message}")

Testing

Use meta_agent_bridge.testing (FakeMetaTransport, make_whatsapp_text_webhook, make_messenger_text_webhook, make_instagram_text_webhook, sign_webhook_payload) to test your agent end-to-end in pytest with zero live network calls or Meta App Review:

import pytest
from pydantic import SecretStr

from meta_agent_bridge import AgentMessageEvent, AgentResponse, SocialBridge, WhatsAppCredentials
from meta_agent_bridge.testing import (
    FakeMetaTransport,
    make_whatsapp_text_webhook,
    sign_webhook_payload,
)


@pytest.mark.asyncio
async def test_agent_handles_bsuid_message() -> None:
    fake = FakeMetaTransport()
    bridge = SocialBridge(transport=fake)
    creds = WhatsAppCredentials(access_token=SecretStr("test-token"), phone_number_id="109876543210")

    raw_body, signature = sign_webhook_payload(
        make_whatsapp_text_webhook(
            sender_id="US.13491208655302741918",
            text="Where is my order?",
            use_bsuid=True,
        ),
        "test-app-secret",
    )

    events = bridge.parse_webhook(raw_body, signature=signature, app_secret="test-app-secret")
    assert len(events) == 1
    inbound = events[0]
    assert isinstance(inbound, AgentMessageEvent)

    result = await bridge.send(AgentResponse(text="On its way!"), inbound.target, creds)
    assert result.succeeded is True
    assert fake.calls[0].json_body is not None
    assert fake.calls[0].json_body["recipient"] == "US.13491208655302741918"

Roadmap

Coming in v0.2.0

  • WhatsApp Template Sending (TemplateStep): Structured outbound template messages (name, language_code, components) for re-engaging users outside the 24-hour customer service window, with compile-time surface validation and BSUID support.
  • URL / CTA Buttons (LinkButton & UrlButtonsStep): Native WhatsApp cta_url buttons (max_url_buttons = 1) and Messenger/Instagram Button Templates (max_url_buttons = 3), automatically degrading excess links into formatted TextSteps.
  • Multipart Media Upload (upload_media): Upload in-memory bytes directly to WhatsApp (/{phone_number_id}/media) and Messenger (/{page_id}/message_attachments), returning UploadedMedia(media_id, channel) while guarding Instagram (INVALID_PARAM) where hosted URLs are required.
  • Instagram Story Mentions, Story Replies & Post/Reel Shares (StoryContext): Normalize story_mention, reply_to.story, and share attachments into AgentMessageEvent with cacheable=False policy compliance (never auto-downloading ephemeral story media).
  • Explicit Quoted Replies on Messenger & Instagram (quote_message_id): Decouple WhatsApp's coupled typing/read target_message_id from explicit message quoting (reply_to.mid on Messenger/IG, context.message_id on WhatsApp).
  • Emoji Reactions (AgentReactionEvent & ReactionStep): Bidirectional react and unreact support across WhatsApp, Messenger, and Instagram.
  • Quick Wins: WhatsApp preview_url: bool toggle on TextStep and Messenger/Instagram sticker_id detection mapped to MediaType.STICKER.

Planned for v0.3.0

  • Outbound Maps / Location (LocationStep) and WhatsApp location_request_message
  • WhatsApp Contacts (vCard) inbound and outbound support
  • Exponential backoff / retry helper and optional [redis] / [auth] extras

Support the Project

If meta-agent-bridge saves you time building omnichannel Meta agents, consider supporting its development:

Buy Me A Coffee


Disclaimer & License

Disclaimer: meta-agent-bridge is an unofficial, independent open-source library and is not affiliated with, endorsed by, or sponsored by Meta Platforms, Inc. "WhatsApp", "Facebook", "Messenger", and "Instagram" are trademarks of Meta Platforms, Inc.

Licensed under the MIT License.

Metadata

Release files for meta-agent-bridge 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for meta-agent-bridge 0.1.0
File Size Uploaded Provenance Actions
meta_agent_bridge-0.1.0.tar.gz 89.7 kB With provenance Details for meta_agent_bridge-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for meta-agent-bridge 0.1.0
File Interpreter ABI Platform Actions
meta_agent_bridge-0.1.0-py3-none-any.whl Python 3 none any Details for meta_agent_bridge-0.1.0-py3-none-any.whl

Total release size: 136.3 kB

Release files / meta_agent_bridge-0.1.0.tar.gz

Download URL meta_agent_bridge-0.1.0.tar.gz
Size 89.7 kB
Tags Source
SHA-256 checksum
How to use checksums
28a7e4b78077acaff251367986f713807d8e80cbb9afb66c02dc6c39d6c8aca1
BLAKE2b-256 checksum
How to use checksums
988d4349e807b60c39e56b2c2248dc08d1889f1d8ef8b5486c4ef29f9dd09d82
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / meta_agent_bridge-0.1.0-py3-none-any.whl

Download URL meta_agent_bridge-0.1.0-py3-none-any.whl
Size 46.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c2f406a782d25e9046d4fc47c2d2ed7d3bc3439a5d3ed6550805a8801b2032e4
BLAKE2b-256 checksum
How to use checksums
249a904c4ddb928a98f33e86c6cb413e765e97e9958759d023d574a031754c9a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for meta-agent-bridge 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for meta_agent_bridge-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page