This page describes the OAuth 2.0 authorization code flow with PKCE used by both Madgicx MCP servers (Facebook Ads and Google Ads). The flow is identical for both, because they share the same authorization server.
Discover endpoints automatically
The canonical OAuth endpoint URLs are published at https://app.madgicx.com/.well-known/oauth-authorization-server. Whenever possible, configure your client to read this discovery document instead of hardcoding URLs. That way, changes on the server side won't break your integration.
Flow Overview
Step 1: Client Initialization
The AI client generates PKCE parameters:
// Generate code verifier (43-128 characters)
const codeVerifier = generateRandomString(64);
// Create code challenge (SHA-256 hash, base64url encoded)
const codeChallenge = base64url(sha256(codeVerifier));
Step 2: Authorization Request
Client redirects user to the authorization endpoint:
https://app.madgicx.com/o/authorize/?
response_type=code&
client_id=CLIENT_ID&
redirect_uri=CALLBACK_URL&
scope=openid%20profile%20email%20mcp:read%20mcp:write&
state=RANDOM_STATE&
code_challenge=CODE_CHALLENGE&
code_challenge_method=S256
Step 3: User Authentication
User logs in to Madgicx and selects their team:
- Enter Madgicx credentials (or SSO)
- Select team from dropdown
- Review requested permissions
- Click "Authorize"
Step 4: Authorization Code
After approval, user is redirected back with an authorization code:
CALLBACK_URL?code=AUTH_CODE&state=RANDOM_STATE
Step 5: Token Exchange
Client exchanges the code for tokens:
POST https://app.madgicx.com/o/token/
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&
code=AUTH_CODE&
redirect_uri=CALLBACK_URL&
client_id=CLIENT_ID&
code_verifier=CODE_VERIFIER
Step 6: Token Response
Server returns access and refresh tokens:
{
"access_token": "eyJhbGciOiJSUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "dGhpcyBpcyBhIHJlZn...",
"scope": "openid profile email mcp:read mcp:write"
}
Team Selection
During authorization, users select which Madgicx team to connect. The selected team is encoded in the issued tokens and cannot be changed without re-authorization.
Token Refresh
When the access token expires, use the refresh token:
POST https://app.madgicx.com/o/token/
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&
refresh_token=REFRESH_TOKEN&
client_id=CLIENT_ID
Each refresh token can only be used once. Store the new refresh token from the response.
Security Considerations
- State Parameter: Always validate the
stateparameter to prevent CSRF attacks - PKCE: Use S256 code challenge method (SHA-256)
- Token Storage: Store tokens securely; never expose in URLs or logs
- HTTPS: All OAuth endpoints require HTTPS