@gravity-ai/react
React components for rendering Gravity ads with automatic impression and click tracking.
For composer insertion with host consent, see Prompt action ads.
Installation
npm install @gravity-ai/react
Peer dependency: React 17+
Quick Start
import { GravityAd } from '@gravity-ai/react';
function ChatResponse({ ads }) {
return ads.map((ad, i) => <GravityAd key={i} ad={ad} />);
}
That's it. When the response contains a server-delivered renderer_spec, the component validates and renders that placement design. Otherwise it falls back to its bundled card. It automatically fires the impression pixel when the ad scrolls into view.
API Response Shape
The components expect the objects returned by the Gravity API:
interface AdResponse {
adText: string;
title?: string;
cta?: string;
brandName?: string;
url?: string;
favicon?: string;
impUrl?: string; // impression tracking pixel
clickUrl?: string; // tracked click-through URL
renderer_spec?: RendererSpec | string; // optional server-delivered placement design
}
Components
<GravityAd />
Full-featured ad renderer with automatic impression/click tracking. Bundled variants use inline styles; server-delivered designs use validated inline declarations plus optional semantic CSS variables. No CSS-in-JS runtime is required.
<GravityAd
ad={ad}
// Leave `variant` unset to accept the placement's server-delivered design.
showLabel={true}
labelText="Sponsored"
openInNewTab={true}
onImpression={() => console.log('seen')}
onClickTracked={() => console.log('clicked')}
/>
Variants:
| Variant | Description |
|---|---|
card | Default. Vertical card with border, shadow, and padding. |
inline | Horizontal layout for sidebars or toolbars. |
minimal | No border, shadow, or background. Blends with host content. |
Passing variant deliberately pins one of these bundled looks and ignores renderer_spec. Use that only when the publisher must own the layout locally.
MCP connect ads
Pass onConnect when your app has an MCP client. An ad that carries a valid connect payload (type: 'mcp', an https serverUrl, a name, an optional https iconUrl) and button copy in cta then renders as a connect card: brand, title, body and one button labelled with cta. The card adds no text of its own.
<GravityAd
ad={ad}
onConnect={(request) => connectMcpServer(request.serverUrl, request.name)}
/>
onConnect receives { id, serverUrl, name, iconUrl? } and returns { status: 'connected' | 'declined' | 'failed' }, directly or as a promise. It runs synchronously inside the click, so open your OAuth popup before any await. The tracked click fires in the background on every connect click. There is no website fallback: when the result is declined or failed, or the callback throws, nothing opens and the card stays as it is, so the user can try again. Repeated clicks while a connect is pending reuse the pending call. Without onConnect, or with an invalid payload, the ad renders as an ordinary ad. When an ad carries both a usable prompt action and a usable connect, the connect card wins only when onConnect is set.
This component only renders: declare supportsMcpConnect: true on the matching placement of your ad request (@gravity-ai/ui's self-fetching GravityAd does this for you when onConnect is set).
Let the SDK run the sign-in
createMcpConnectHandler builds an onConnect handler that runs the whole MCP authorization in the browser and hands you the connection to add to your own MCP client. It opens a popup inside the click, discovers the server's authorization server (RFC 9728 protected-resource metadata, then RFC 8414 authorization-server metadata), registers your app by dynamic client registration under clientName, sends the user to the advertiser's consent screen with PKCE (S256), a random state and the RFC 8707 resource, and exchanges the returned code for tokens.
import { GravityAd, createMcpConnectHandler, type McpConnection } from '@gravity-ai/react';
const onConnect = createMcpConnectHandler({
clientName: 'Acme Chat',
redirectUri: `${window.location.origin}/mcp/callback`,
attribution: () => ({ utm_source: 'acme-chat', utm_medium: 'chat' }),
onConnected: async (connection: McpConnection) => {
await mcpHub.add({
name: connection.name,
url: connection.serverUrl,
headers: connection.headers,
oauth: connection.oauth,
});
},
});
<GravityAd ad={ad} onConnect={onConnect} />
Each connect runs in its own popup and only accepts the callback from that popup. The protected-resource metadata must name the MCP server itself (the same origin, with the server's path equal to or under the metadata's resource path), so a server cannot have a token issued for another server's resource. Each request gives up after 15 seconds.
The result is connected once onConnected resolves, declined when the user closes the popup (at any point before the callback, which also cancels requests still running) or denies consent, and failed otherwise (no OAuth metadata, a resource that does not match the server, a blocked popup, a refused registration or token exchange, a state mismatch, or onConnected throwing). The connection is:
{
serverUrl: string;
name: string;
headers: { Authorization: 'Bearer …' };
oauth: { tokenEndpoint: string; clientId: string; refreshToken?: string; expiresAt?: number; resource: string };
}
Options:
| Option | Purpose |
|---|---|
clientName | Your app's name, shown on the advertiser's consent screen. |
redirectUri | A page on your own origin that calls completeMcpConnectCallback(). |
clientId | A client id you registered with the advertiser; skips dynamic client registration. |
attribution | Returns tracking parameters for the authorize URL. Only utm_source, utm_medium, utm_campaign, utm_content, utm_term and grclid are kept, so it can never override an OAuth parameter. |
fetch | Replaces fetch for discovery, registration and token calls (see CORS below). |
onConnected | Receives the connection and the original request. |
The redirect page only needs to call completeMcpConnectCallback() once it loads. It posts the code, state and any error to the opener at the same origin, removes them from the address bar and closes the popup:
// app/mcp/callback/page.tsx
'use client';
import { useEffect } from 'react';
import { completeMcpConnectCallback } from '@gravity-ai/react';
export default function McpCallback() {
useEffect(() => { completeMcpConnectCallback(); }, []);
return <p>Connecting…</p>;
}
Refresh the access token before oauth.expiresAt with refreshMcpConnection, which uses the refresh-token grant and returns an updated connection (it rejects when there is no refresh token or the server refuses):
import { refreshMcpConnection } from '@gravity-ai/react';
if (connection.oauth.expiresAt && connection.oauth.expiresAt - Date.now() < 60_000) {
connection = await refreshMcpConnection(connection);
await mcpHub.update(connection);
}
The handler never logs tokens, codes or URLs that carry them. Store headers and oauth the way you store any other credential.
CORS. The browser calls the MCP server's metadata, the registration endpoint and the token endpoint directly, so they must allow cross-origin requests. Many do (the MCP reference server and Exa's token endpoint do), but some do not: Exa's registration endpoint (https://auth.exa.ai/api/oauth/register) sends no CORS headers, so registering from the browser fails there. For such servers, pass a clientId you registered ahead of time, or pass a fetch that relays the calls through your own server:
const relayFetch: typeof fetch = (input, init) =>
fetch('/api/mcp-oauth-relay', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
url: String(input),
method: init?.method ?? 'GET',
headers: init?.headers,
body: init?.body,
}),
});
const onConnect = createMcpConnectHandler({ clientName: 'Acme Chat', redirectUri, fetch: relayFetch, onConnected });
const refreshed = await refreshMcpConnection(connection, { fetch: relayFetch });
The relay forwards the request to url and returns the upstream status, WWW-Authenticate header and body. The URLs come from the advertiser's metadata, so let the relay reach only public https hosts and never forward your own cookies or credentials.
Server-delivered placement designs
Gravity can attach a versioned renderer_spec to an ad response. When variant is unset, <GravityAd>:
- Parses and structurally validates the spec.
- Resolves its content bindings (
title,adText,cta,brandName,favicon,url). - Applies the publisher's semantic theme variables.
- Renders through a safe node whitelist (
box,text,image,link). - Falls back to the bundled
cardrenderer if the spec is malformed or resolves to no content.
The standard card spec uses one root link bound to url, so the whole visible ad routes through clickUrl; it never nests anchors. Specs must include a visible disclosure such as AD, Sponsored, Promoted, or Paid. If disclosure is missing, the SDK overlays its built-in ad badge.
Web ad requests should send specCapabilities: "web1" (and must not send supportsSpec: false). Existing integrations that send neither field remain backward-compatible and are treated as web-capable for publisher placement defaults.
Server designs adopt these optional host variables, falling back to the SDK palette:
| Variable | Purpose |
|---|---|
--gravity-bg | Card/background surface |
--gravity-text | Primary text |
--gravity-text-muted | Secondary text |
--gravity-accent | CTA/accent |
--gravity-accent-foreground | Text on the accent |
--gravity-muted | Muted surface |
--gravity-border | Borders |
--gravity-radius | Card radius |
When a --gravity-* variable is absent, the renderer uses the matching host variable (--card, --foreground, --primary, etc.) before its literal fallback.
Data-drawn units
When an ad carries a unit and variant is unset, <GravityAd> draws it with the layout that fits the container's live width, and re-flows when the width crosses a layout boundary. The unit picks up the host page's light or dark surface, text colour and font; --gravity-accent and --gravity-radius set its button colour and corner radius. rich_frame units render in the frame host, an action_card button runs onPrompt, and a connect_card button runs onConnect. A unit type or version the SDK doesn't know draws as a plain text card. Impression and click tracking work as for every other ad, and ads without unit render as before.
If you fetch ads yourself, add what the component needs to fit a unit to each placement of the request with getPlacementContext:
import { getPlacementContext } from '@gravity-ai/react';
const placements = [{
placement: 'below_response',
placement_id: 'main',
...getPlacementContext(slotRef.current, { promptAction: !!onPrompt, mcpConnect: !!onConnect }),
}];
It returns the slot width, the host font and theme, and the capabilities <GravityAd> draws (frames defaults to true, matching enableFrames). It never throws; on the server it returns only capabilities.
Styling with style and slotProps
Override the outer container with the style prop:
<GravityAd ad={ad} style={{ maxWidth: 400, borderRadius: 16 }} />
Override any inner element with slotProps:
<GravityAd
ad={ad}
slotProps={{
cta: { style: { background: '#E11D48', borderRadius: 999 } },
label: { style: { display: 'none' } },
title: { style: { fontSize: 16 } },
}}
/>
Each slotProps key maps to a DOM element:
| Key | Element | What it controls |
|---|---|---|
container | Outer <a> | Same as top-level style prop |
inner | Padding wrapper <div> | Layout, padding, gap |
header | Header row <div> | Favicon + brand + label row |
favicon | Favicon <img> | Size, border-radius |
brand | Brand name <span> | Font, color |
label | "Sponsored" <span> | Pill styling, visibility |
body | Body wrapper <div> | Title + text layout |
title | Title <p> | Font, color |
text | Ad text <p> | Font, color |
cta | CTA button <span> | Background, border-radius, padding |
Each slot accepts { style?: CSSProperties; className?: string }.
For the full styling guide with DOM structure and common recipes, see STYLING.md.
<GravityLeadFormAd /> (deprecated)
Lead forms are retired. The server no longer returns leadForm on ads, and
<GravityLeadFormAd /> renders nothing. Use <GravityAd /> instead.
<AdText />
Unstyled text-only renderer. Use when you want full control over presentation.
<AdText
ad={ad}
className="my-custom-style"
style={{ fontSize: 14 }}
/>
Renders ad.adText as a link (if clickUrl exists) or a span. No built-in styles beyond text-decoration: none; color: inherit.
Impression Tracking
Both components use IntersectionObserver to fire the impression pixel only when the ad is actually visible to the user (50% of the element in the viewport). This is a significant improvement over fire-on-mount — publishers won't report impressions for ads rendered below the fold that were never seen.
The impression fires exactly once per ad. If the ad object changes (different impUrl), the tracking resets for the new ad.
Billing is unchanged: the impression pixel (impUrl) fires exactly as before. The pixel still fires the instant 50% of the ad enters the viewport (or on mount where IntersectionObserver is unavailable). Separately, the SDK sends a shadow viewability beacon to the same URL with ev=measured, sdk and sv query parameters when the pixel fires, and ev=viewable once at least 50% of the ad has been in view for 1 continuous second (MRC viewable impression). The beacons are measurement only and never affect billing. Dropping below 50% or hiding the tab restarts the 1 second; no beacon is sent where IntersectionObserver is unavailable.
To disable automatic tracking:
<GravityAd ad={ad} disableImpressionTracking />
Hooks
useAdTracking
Low-level hook for building fully custom ad components:
import { useAdTracking } from '@gravity-ai/react';
function CustomAd({ ad }) {
const { containerRef, handleClick } = useAdTracking({
ad,
onImpression: () => console.log('impression fired'),
onClickTracked: () => console.log('click tracked'),
});
return (
<a ref={containerRef} href={ad.clickUrl} onClick={handleClick}>
{ad.adText}
</a>
);
}
The hook returns:
containerRef— attach to the DOM element for IntersectionObserver-based impression trackinghandleClick— call on click to fire the click tracking callbackimpressionFired— boolean indicating whether the impression has already been fired
License
MIT