Blog / OAuth token expired

Guide · Webhooks · OAuth

OAuth token expired: catch dead AI agent connections with a webhook

An agent that works in Gmail, Sentry, or Linear holds an OAuth grant, and grants stop working. FlyMy.AI refreshes an expired access token in the background. When the refresh token itself has expired or been revoked, however, the provider returns invalid_grant and every call after that fails. That is the OAuth token expired error no retry can fix. FlyMy.AI now tells you the moment it happens: the owner gets an email with a Reconnect button, a scheduled run stops before any paid step, and your own systems get a signed connection.expired webhook. Here is why tokens die, what changes for your agents, and how to set up the webhook and verify its signature.

A cracked brushed-aluminum key with a violet glass bow lies next to an empty hourglass: the OAuth token expired. A violet envelope with a Reconnect button floats toward a small server, and a violet beam carries a signed message to a receiver box with a check mark.

Why an OAuth token expired error stops an agent

OAuth gives an app two tokens. The access token goes with every API call and lasts for minutes or hours. When it expires, the app sends the refresh token to the provider to get a new access token. FlyMy.AI handles that refresh for every connection, so an expired access token never reaches your agent.

The refresh token can stop working too, and then nothing automatic can fix it. Google's documentation lists the reasons a granted refresh token stops working: the user revoked the app's access, the token went unused for six months, the user changed passwords and the token carries Gmail scopes, the account exceeded the limit of live refresh tokens, time-based access ran out, or an admin restricted one of the services. An app with a consent screen still in Testing gets refresh tokens that expire in 7 days. Other providers set their own lifetimes and revocation rules.

For a person in a chat, this is a small annoyance: the app asks them to sign in again. For an agent, it is a silent failure. Agents run on a schedule, from an API call, or inside someone else's product, with nobody watching the screen. A daily digest that reads your error tracker goes out without the errors. A sales agent stops logging calls to the CRM. The first sign is a customer asking why.

Access tokenRefresh token
What it doesGoes with each API callGets a new access token
How long it livesMinutes to hoursUntil it expires or is revoked
When it endsFlyMy.AI refreshes it before the callThe provider returns invalid_grant; the owner signs in again
What your agent seesNothingA connection that needs reconnecting

What invalid_grant means

OAuth 2.0 (RFC 6749, section 5.2) defines invalid_grant as the error a token endpoint returns when the authorization grant or refresh token "is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client." A retry gets the same response because the refresh token is still dead. The fix is a new sign-in by the account owner.

On FlyMy.AI, that is the moment a connection turns reconnect_required: the provider rejects a token refresh or reports that access is no longer valid. A timeout or a rate limit does not count, and the connection stays as it is. Your assistant sees the status in list_configured_tools, and both the owner and the owner's systems hear about it right away.

What FlyMy.AI does when a connection dies

Three things happen at the same moment.

  1. An email to the owner. The subject reads "Reconnect Sentry to keep your agents working", using the name of the app that died. The email lists up to five agents that use the connection and includes a Reconnect button that opens the connection's page, where signing in again issues a fresh grant. FlyMy.AI sends one email a day per connection, however many calls find it dead. Your own MCP servers connected with OAuth get the same email.
  2. Runs stop before they spend. A scheduled or API run of a saved agent version refreshes the grants it needs before it starts. When one is dead, the run stops before any paid step and reports which connection to reconnect, while the owner's email has the Reconnect button.
  3. A connection.expired webhook. Every active webhook subscribed to connection.expired receives one signed POST with the connection, its reconnect_url, and the agents that use it, once a day per connection.
A conveyor of small aluminum boxes stops at a lowered violet glass gate before a coin slot, while a cracked key lies in a tray and a violet envelope flies to a mailbox.
A dead grant stops the run before any paid step; the owner gets an email and your server a webhook.

The connection.expired webhook

Every request body is one compact JSON object:

{
  "id": "4c1f9a52-7d0e-4b8a-9f3c-2a6e5d1b7c90",
  "type": "connection.expired",
  "created_at": "2026-11-17T08:00:02+00:00",
  "schema": "flymy.webhooks.v1",
  "data": {
    "connection": {
      "id": "9a8b7c6d-1111-4222-8333-444455556666",
      "kind": "connection",
      "toolkit": "sentry",
      "alias": "default",
      "name": "Sentry",
      "status": "reconnect_required"
    },
    "reconnect_url": "https://app.flymy.ai/mcp-configs#sentry?connection_id=9a8b7c6d-1111-4222-8333-444455556666",
    "agents": ["Daily error digest"]
  }
}
FieldWhat it holds
idThe delivery's id, matching the webhook-id header and staying the same on every retry
typeconnection.expired, or webhook.test for a test event
created_atWhen the event happened
schemaflymy.webhooks.v1
data.connectionid, kind (connection or custom_mcp_server), toolkit, alias, name, and status (reconnect_required)
data.reconnect_urlThe page where the owner signs in again
data.agentsUp to five names of agents that use the connection

Send your user to reconnect_url. Signing in there again issues a fresh grant, and the agents that use the connection work again. New event types use the same flymy.webhooks.v1 schema, and an existing data shape does not change within v1.

Set up a webhook in three steps

1. Add FlyMy.AI to your assistant

The FlyMy.AI MCP uses one URL, https://mcp-agents.flymy.ai/mcp. Add it to your client and sign in.

  • Claude Code: run claude mcp add --transport http flymyai https://mcp-agents.flymy.ai/mcp, then /mcp to sign in.
  • Codex: run codex mcp add flymy --url https://mcp-agents.flymy.ai/mcp, then codex mcp login flymy.
  • claude.ai, Claude Desktop, and ChatGPT: open Settings, Connectors, Add custom connector, then paste the URL and sign in.
  • Cursor and other MCP clients: add the same URL as a remote MCP server.

2. Ask for the webhook

Your assistant calls create_webhook with your URL and events. The response includes the signing secret (whsec_...) once. Store it where your receiver reads it, for example as FLYMYAI_WEBHOOK_SECRET.

Try it
Send a webhook to https://example.com/flymyai/events when one of my connections stops working. Give me the signing secret once and do not save it anywhere else.

3. Send a test event and check the delivery

test_webhook queues one webhook.test event, and list_webhook_deliveries shows its status, attempts, and the HTTP code your receiver returned.

Try it
Send a test event to my webhook and show me its delivery status and HTTP code.

More requests to paste:

Try it
Check which of my connections need to be reconnected.
Try it
List my webhooks with their last delivery status and how many deliveries failed in a row.
Try it
Pause my webhook while I redeploy the receiver, then resume it when I say so.
Try it
Rotate the signing secret of my webhook and give me the new one once.

The Agents MCP has seven webhook tools: list_webhooks, create_webhook, update_webhook, delete_webhook, test_webhook, rotate_webhook_secret, and list_webhook_deliveries. Write calls take an operation key, so a retried call does not create a second webhook.

You can also do all of this by hand in the FlyMy.AI app: open Developers > Webhooks to add a webhook, copy its signing secret once, send a test event and watch its deliveries, pause it, rotate its secret or delete it.

Create a webhook from code

With the Python SDK (python -m pip install 'flymyai>=1.2.0rc29'):

import os
from flymyai import AgentClient

client = AgentClient(api_key=os.environ["FLYMYAI_API_KEY"])
created = client.webhooks.create(
    "https://example.com/flymyai/events",
    events=["connection.expired"],
    description="Reconnect alerts",
    idempotency_key="webhook-reconnect-alerts",
)
signing_secret = created.secret  # whsec_..., shown once: store it for your receiver
client.webhooks.send_test(created.webhook.id)  # one webhook.test event
for delivery in client.webhooks.list_deliveries(created.webhook.id):
    print(delivery.event_type, delivery.status, delivery.last_status_code)

The async client provides the same methods with await. update changes the URL, events, or description, or pauses a webhook with is_active=False. delete removes it, and rotate_secret replaces the signing secret right away.

With the REST API:

curl -X POST https://backend.flymy.ai/api/v1/agents/webhooks/ \
  -H "X-API-KEY: $FLYMYAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: webhook-reconnect-alerts" \
  -d '{"url": "https://example.com/flymyai/events", "events": ["connection.expired"], "description": "Reconnect alerts"}'

The endpoint returns 201 with the webhook and its signing secret. The same routes list webhooks (GET /api/v1/agents/webhooks/), update (PATCH .../{id}/), delete, test (POST .../{id}/test/), rotate the secret (POST .../{id}/rotate-secret/), and list the 50 newest deliveries from the last 30 days (GET .../{id}/deliveries/). A retry with the same Idempotency-Key does not apply a change twice, and a replayed create request returns secret: null.

Webhook signature verification in Python and Node

Each request carries three headers, as in Standard Webhooks:

  • webhook-id: the delivery's id. It stays the same on every retry, so use it to skip a repeat.
  • webhook-timestamp: the Unix timestamp in seconds for this attempt.
  • webhook-signature: v1, followed by the Base64 HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<raw body>, keyed with the Base64-decoded part of the secret after whsec_. Several space-separated signatures may appear; one match is enough.

Verify the raw body before you parse it, reject a timestamp more than five minutes from now, and compare signatures in constant time. Return 400 when a request fails verification.

A level balance scale: an envelope with a violet wax seal on one pan and the matching seal on the other, with a violet magnifying glass at its base.
A delivery is genuine when your signature over the same id, timestamp and body matches the one sent.

With the Python SDK:

import os
from flymyai import WebhookSignatureError, verify_webhook

def receive(body: bytes, headers) -> int:
    try:
        secret = os.environ["FLYMYAI_WEBHOOK_SECRET"]
        event = verify_webhook(body, headers, secret)
    except WebhookSignatureError:
        return 400
    if event.type == "connection.expired":
        notify(event.data["connection"]["name"], event.data["reconnect_url"])
    return 204

With the Python standard library:

import base64
import hashlib
import hmac
import json
import time

def verify(body: bytes, headers, secret: str) -> dict:
    message_id = headers["webhook-id"]
    timestamp = headers["webhook-timestamp"]
    if abs(time.time() - int(timestamp)) > 300:
        raise ValueError("stale delivery")
    key = base64.b64decode(secret.split("_", 1)[1])
    signed = f"{message_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    given = [s.split(",", 1)[1] for s in headers["webhook-signature"].split() if s.startswith("v1,")]
    if not any(hmac.compare_digest(expected, signature) for signature in given):
        raise ValueError("bad signature")
    return json.loads(body)

With Node.js (read the raw body, for example with express.raw({type: 'application/json'})):

import crypto from 'node:crypto';

export function verify(rawBody, headers, secret) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new Error('stale delivery');
  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto.createHmac('sha256', key).update(`${id}.${timestamp}.`).update(rawBody).digest();
  const ok = headers['webhook-signature'].split(' ').some((entry) => {
    const [version, value] = entry.split(',');
    if (version !== 'v1' || !value) return false;
    const given = Buffer.from(value, 'base64');
    return given.length === expected.length && crypto.timingSafeEqual(given, expected);
  });
  if (!ok) throw new Error('bad signature');
  return JSON.parse(rawBody.toString('utf8'));
}

Standard Webhooks libraries can also verify these deliveries with the whsec_ secret.

Webhook retries, timeouts and duplicates

  • Return any 2xx within 30 seconds, and run slow work after you respond.
  • FlyMy.AI retries network errors, 408, 429, and 5xx responses. The delay doubles from 30 seconds up to an hour: eight retries over about two hours. Any other response, including a redirect, ends the delivery as failed.
  • A delivery can arrive more than once. Skip any webhook-id you have already handled.
  • Each webhook tracks last_delivery_at, last_delivery_status, and consecutive_failures, and FlyMy.AI keeps its deliveries for 30 days.
  • A paused webhook (is_active: false) receives nothing until you resume it. Events in between are not replayed.

A webhook security checklist

Good webhook security comes from a few checks, and FlyMy.AI does its half of each:

  • Only public https:// addresses receive events, and FlyMy.AI does not follow redirects.
  • Every request is signed, and the signature covers the timestamp, so a receiver that checks it rejects an old request replayed later.
  • The signing secret is shown once, in the response when you create or rotate it. A replayed response has secret: null. Rotate the secret if it leaks; the old one stops verifying right away.
  • Your receiver keeps its half: verify the raw body before you parse, check the timestamp, and skip any webhook-id you have already seen.

FlyMy.AI vs Composio webhooks for expired connections

Composio's documentation says it "automatically refreshes OAuth tokens before they expire. But when a refresh token is revoked or expires, the connection enters an EXPIRED state and the user must re-authenticate", and recommends subscribing to composio.connected_account.expired "to detect this proactively, instead of waiting for a tool execution to fail" (Composio: webhook subscriptions). FlyMy.AI sends the same kind of event, and two more things happen at that moment: FlyMy.AI emails the owner and stops runs before any paid step.

FlyMy.AIComposio (from its docs)
Eventconnection.expiredcomposio.connected_account.expired, with V3 webhook payloads
Signaturewebhook-id, webhook-timestamp, webhook-signature; HMAC-SHA256 of id.timestamp.bodyThe same headers; HMAC-SHA256 over {webhook-id}.{webhook-timestamp}.{rawBody} (verifying signatures)
Replay windowThe SDK's verify_webhook rejects a timestamp more than 5 minutes awayThe SDK's parse() and verifyWebhook() enforce 300 seconds by default
SubscriptionsUp to 10 per account, each with its own eventsOne per project: a second create returns 409, so you update it instead
Reconnectreconnect_url in the event opens the connection's pageCreate a new auth link session for the user (connected accounts)
DuplicatesThe same webhook-id on every retryHandlers should be idempotent (triggers)

If you already handle Composio webhooks, your receiver changes little: both send the webhook-id, webhook-timestamp and webhook-signature headers with an HMAC-SHA256 signature over id.timestamp.body, and you route on type.

Troubleshooting

The signature does not match. Verify the raw body exactly as received, before any JSON parser touches it. After rotate_secret, the old secret stops verifying. In Node, req.headers names are lowercase.

400 invalid_webhook with field: url. The URL must be a public https:// address. field: events means an event type is not in event_types.

409 webhook_limit. An account can have at most 10 webhooks. Delete one first.

A delivery fails with Refused: OutboundRedirectError. FlyMy.AI does not follow redirects. Use the final URL.

"webhook-timestamp is too far from now". Your server's clock is off. Sync it with NTP.

No events arrive. Check that the webhook is active and subscribed to connection.expired, then send a test event.

FAQ

What does "token expired" mean?

The token an app sends with its API calls is past its lifetime. For an access token, expiration is normal and the app refreshes it. When the refresh token expired or was revoked too, the provider returns invalid_grant and the user must sign in again.

Do OAuth tokens expire?

Yes. Access tokens last for minutes or hours. Refresh tokens last longer, but they can expire or be revoked. Google's documentation lists six months without use, a password change for Gmail scopes, a revoked grant, and seven days for apps still in Testing, among other reasons.

What if a refresh token expired?

Nothing automatic can fix it. The account owner must sign in again. On FlyMy.AI, they get an email with a Reconnect button, and your systems get a connection.expired webhook with the reconnect_url.

What is invalid_grant?

invalid_grant is the OAuth 2.0 error a token endpoint returns when the grant or refresh token is invalid, expired, revoked, or issued to another client (RFC 6749, section 5.2). Retrying the same refresh token does not help.

How do I verify a webhook signature?

Compute the Base64 HMAC-SHA256 of webhook-id, webhook-timestamp, and the raw body joined by dots, using the key after whsec_, and compare it in constant time with the v1, value in webhook-signature. The Python SDK does this in one call: verify_webhook(body, headers, secret).

What are Standard Webhooks?

Standard Webhooks is an open specification for sending webhooks using the webhook-id, webhook-timestamp, and webhook-signature headers, HMAC-SHA256 signatures, and whsec_ secrets. FlyMy.AI signs its webhooks this way, so any Standard Webhooks library can verify them.

How do webhook retries work on FlyMy.AI?

FlyMy.AI retries network errors, 408, 429, and 5xx responses with a delay that doubles from 30 seconds to an hour: eight retries over about two hours. Any other response ends the delivery as failed.

What makes a webhook secure?

An HTTPS endpoint, a signature over the body and a timestamp, a check that the timestamp is recent, a secret only your receiver knows, and idempotent handling of repeats. Webhook security is the sum of those checks on both sides.

How is this different from Composio webhooks?

Both send a signed event when a connection expires, with the same webhook-id, webhook-timestamp and webhook-signature headers. On FlyMy.AI, the owner also gets an email with a Reconnect button at the same moment, and a saved agent's run stops before any paid step. An account can also have up to 10 webhooks, whereas Composio has one subscription per project.

How does MCP OAuth work with FlyMy.AI?

You sign in to the FlyMy.AI MCP once from Claude, ChatGPT, Codex, or Cursor. FlyMy.AI stores and refreshes the OAuth grants for the apps you connect through it, so no token passes through a chat. When a grant dies, you get the email and the webhook.

What is the FlyMy.AI MCP server URL?

https://mcp-agents.flymy.ai/mcp. It is the same URL for Claude, ChatGPT, Codex, Cursor, and every other MCP client.

Know the moment a connection dies

One webhook, one signed POST per event, and an email to the owner with a Reconnect button.

Keep reading