# AGENTS
Source: https://docs.emergedata.ai/AGENTS
# Emerge Documentation Agent Instructions
This file customizes how AI agents interact with and generate content for Emerge documentation.
## Code examples
* Always provide examples in both TypeScript and Python
* Use realistic parameter values (not foo/bar/example)
* Include proper error handling in all examples
* Show complete, runnable code snippets
* Use async/await patterns for API calls
## API documentation
Every endpoint must document:
* Required authentication method
* All parameters with types and descriptions
* Response format with example
* Possible error codes
* Rate limiting information (if applicable)
## Style guidelines
* Write for developers integrating data APIs
* Use second person ("you")
* Be concise - developers want answers, not prose
* Focus on privacy-first messaging
* Explain the "why" when it's not obvious
## Response format
When answering questions about Emerge:
1. Start with a direct answer
2. Provide relevant code example
3. Link to related documentation
4. Mention edge cases or gotchas
## Common patterns
### Creating consent links
* Always mention HMAC signing requirement
* Show state parameter for CSRF protection
* Include timestamp for link expiration
### Handling callbacks
* Emphasize state verification
* Show all possible status values
* Include error handling
### Querying data
* Explain sync vs async tradeoffs
* Show pagination handling
* Mention delta query patterns
## Do not
* Guess at API behavior not documented
* Provide outdated code patterns
* Skip error handling in examples
* Assume implementation details
## Terminology
* "Emerge Link" - The consent flow product
* "Control Room" - The dashboard at dashboard.emergedata.ai
* "consent" - User permission for data access
* "export" - Data transfer from provider to Emerge
* "query" - Retrieving user data via API
* "flow\_config" - Named configuration for custom branding
* "uid" or "partner\_uid" - Partner's user identifier
* "task\_id" - Async query job identifier
* "signing\_secret" - HMAC signing credential (not "client\_secret")
## API domains
* Link API: [https://link.emergedata.ai](https://link.emergedata.ai)
* Query API: [https://query.emergedata.ai](https://query.emergedata.ai)
* Dashboard: [https://dashboard.emergedata.ai](https://dashboard.emergedata.ai)
## Critical implementation details
* Link URL endpoint: `/link/start?` (not `/link?`)
* Timestamp format: ISO 8601 (`new Date().toISOString()`)
* Signature base: raw parameter values, not URL-encoded
* Async queries: `users` array (max 25), returns Parquet via S3 URL
* Sync queries: single `uid`, uses `ingested_begin`/`ingested_end` for delta queries
# CLAUDE
Source: https://docs.emergedata.ai/CLAUDE
# Emerge API Documentation
## Project overview
Documentation for Emerge API - a privacy-first API for accessing consented user data. The project includes Link API (consent collection) and Query API (data retrieval).
## Technical stack
* Format: MDX files with YAML frontmatter
* Build system: Mintlify (cloud-hosted, auto-deploys from GitHub)
* Config: docs.json (navigation, theme, branding)
* Theme: maple with Emerge brand colors (primary: #e36c35, light: #ff4f1a, dark: #2e1205)
* Branding: Mintlify footer branding hidden (`branding.hide: true` in docs.json + CSS selector in style.css)
* Custom styles: style.css - Logo sized to 32px height, Mintlify "Powered by" footer hidden via CSS
* OpenAPI specs: openapi/link.json and openapi/query.json (v0.0.11 spec changes as of 2026-02-12: webhook v2 payload, consent/export status updates, categories endpoint examples)
* AI integration: MCP (Model Context Protocol) enabled
* Local dev: `mint dev` (requires global CLI: `npm i -g mint`)
* Preview URL: [http://localhost:3000](http://localhost:3000)
* Logo: emerge-logo.svg (360x96px, text-based with system-ui fonts, 70px bold, used for both light and dark modes)
* Favicon: favicon.ico (MS Windows icon resource with 16x16 and 32x32 PNG icons)
* Navbar: Primary CTA button links to The Control Room (dashboard.emergedata.ai), support email link ([account@emergedata.ai](mailto:account@emergedata.ai)) in secondary navigation and global footer
* Global anchors: The Control Room (arrow-up-right-from-square icon, external link indicator), Support (envelope icon)
## Content structure
### Main sections (tabs in docs.json)
* **Guides** (`/`) - Getting started, quickstart, SDKs, changelog
* **Link** (`/link/`) - Consent flow integration (authentication, signed URLs, callbacks, webhooks)
* **Query** (`/query/`) - Data retrieval (sync/async patterns, pagination, categories, schema)
* **Ship with MCP** (`/ai/`) - MCP setup, contextual menu, examples, tool-specific guides
* **The Control Room** (`/control-room/overview`) - Dashboard configuration and operational workflows
* **Data Wallet** (`/data-wallet/overview`) - End-user revocation and transparency workflows
### Key files
* `index.mdx` - Homepage with product overview and navigation
* `quickstart.mdx` - Lightning-fast integration guide with upfront AI tool setup section (MCP integration for Cursor, Claude Code, VS Code) at the beginning before prerequisites
* `AGENTS.md` - AI-specific documentation guidelines (code examples, API patterns, terminology)
* `CLAUDE.md` - This file - project memory for AI agents
* `changelog.mdx` - Version history (current: v0.0.11 as of 2026-02-12)
* `docs.json` - Navigation structure, Mintlify configuration, theme colors (maple theme with Emerge branding), support email: [account@emergedata.ai](mailto:account@emergedata.ai)
* `openapi/link.json` - OpenAPI 3.1 spec for Link API reference, contact email: [account@emergedata.ai](mailto:account@emergedata.ai) (auto-synced from atlas; do not edit manually)
* `openapi/query.json` - OpenAPI 3.1 spec for Query API reference, contact email: [account@emergedata.ai](mailto:account@emergedata.ai) (auto-synced from atlas; do not edit manually)
* `README.md` - Documentation development guide
## Writing standards
### Voice and style
* Second-person ("you")
* Developer-focused, concise prose
* Privacy-first messaging
* Explain "why" when not obvious
### Code examples
* Provide both TypeScript AND Python for all API examples
* Use realistic parameter values (not foo/bar/example)
* Include proper error handling
* Show complete, runnable snippets
* Use async/await patterns for API calls
* All code blocks must have language tags
* Show only required fields in quickstart examples (optional fields can be documented separately)
### API documentation patterns
Every endpoint must document:
* Required authentication method
* All parameters with types and descriptions
* Response format with example
* Possible error codes
* Rate limiting (if applicable)
### Common integration patterns
**Creating consent links:**
* HMAC signing with sorted parameters using signing\_secret
* State parameter for CSRF protection
* Timestamp in ISO 8601 format (new Date().toISOString() or datetime.now(timezone.utc).isoformat()) for link expiration (30 days)
* Link URL endpoint: `/link/start?` (not `/link?`)
* Optional flow\_config parameter for custom branding (replaced deprecated flow\_version)
**Handling callbacks:**
* State verification against stored values
* Status values: success, reauthorized, failure
* Error code handling (data\_invalid, user\_failed, uid\_conflict, access\_denied, invalid\_scope, admin\_policy\_enforced)
* Callback parameters: status, state, uid, error\_code (no flow\_version)
**Querying data:**
* Sync vs async tradeoffs (30s timeout vs job-based polling)
* Sync: Single uid, pagination with cursor, delta queries with ingested\_begin/ingested\_end
* Async: Batch up to 25 users, date range with begin/end, results as Parquet file via S3 presigned URL
**Webhooks:**
* Event types: `consent.given`, `consent.revoked`, `consent.expiring`, `consent.reauthorized`, `data.ready`, `data.failed`
* HMAC-SHA256 signature verification (`X-Signature` header)
* Payload includes top-level `uid`, `client_id`, and provider-specific `sources[]`
## Content strategy
* Document just enough for user success
* Prioritize accuracy and usability
* Make content evergreen when possible
* Avoid duplication unless strategic
* Check existing patterns for consistency
* Start with smallest reasonable changes
## Frontmatter requirements
Every MDX file must include:
```yaml theme={null}
---
title: Clear, descriptive page title
description: Concise summary for SEO/navigation
---
```
## File organization
* `/link/*.mdx` - Link API guides (overview, authentication, create-link, callbacks, webhooks)
* `/query/*.mdx` - Query guides (overview, pagination, event-categories, data-schema)
* `/ai/*.mdx` - Ship with MCP docs (overview, mcp-docs-setup, mcp-query-setup, mcp-query-tools, contextual-menu, examples)
* `/ai-tools/*.mdx` - AI tool-specific setup guides (claude-code, cursor, windsurf) \[Note: Directory exists in git but not filesystem - may be template content]
* `/sdks/*.mdx` - SDK implementations (TypeScript, Python) - Copy-paste reference implementations
* `/api-reference/` - Legacy API reference pages (deprecated - use OpenAPI auto-generated pages)
* `/openapi/link.json` - OpenAPI 3.1 spec with Link API endpoints
* `/openapi/query.json` - OpenAPI 3.1 spec with Query API endpoints
* `/essentials/` - Template content (code, images, markdown, navigation, etc.)
* `/snippets/` - Reusable content snippets
* `/images/` - Documentation images and diagrams
* `/logo/` - Brand assets (emerge-logo.svg - 360x96px text-based logo)
* `favicon.ico` - Site favicon (16x16 and 32x32 icons)
* `style.css` - Custom styles (32px logo height, hide Mintlify footer)
## Build and development
### Local preview
```bash theme={null}
# Install docs CLI globally
npm i -g mint
# Run dev server (from docs root, where docs.json is located)
mint dev
# View at http://localhost:3000
```
### Common commands
```bash theme={null}
# Update CLI to latest version
mint update
# Validate docs.json and OpenAPI spec
mint validate
```
### Deployment
* Auto-deploys via GitHub integration
* Push to main branch → automatic production deployment
* No manual build step required
## Git workflow
* NEVER use --no-verify when committing
* Ask about uncommitted changes before starting
* Create new branch when no clear branch exists
* Commit frequently throughout development
* NEVER skip or disable pre-commit hooks
## Do not
* Skip frontmatter on any MDX file
* Use absolute URLs for internal links
* Include untested code examples
* Make assumptions - always ask for clarification
* Provide only one language example (need both TS and Python)
* Skip error handling in code examples
## Available data types
| Data Type | Sync Endpoint | Async Endpoint | Description |
| ---------------- | ----------------------- | -------------- | --------------------------------------- |
| Search History | `/v1/sync/get_search` | `/v1/search` | Google search queries with timestamps |
| Browsing History | `/v1/sync/get_browsing` | `/v1/browsing` | Chrome page visits with titles |
| YouTube History | `/v1/sync/get_youtube` | `/v1/youtube` | Watched videos with channels |
| Ad Interactions | `/v1/sync/get_ads` | `/v1/ads` | Ad clicks and views |
| Receipts | `/v1/sync/get_receipts` | `/v1/receipts` | Purchase receipts with items and brands |
### Link API endpoints
* `POST /configs` - Create/update consent flow configuration (required: config\_name, company\_name, logo\_url, privacy\_policy\_url, is\_default; optional: webhook\_url, flow\_config)
* `GET /consent/status/{uid}` - Returns `sub`, `client_id`, and provider-level `consents[]`
* `GET /export/status/{uid}` - Returns provider-level readiness in `sources[]`
* Link URL: `/link/start?` with parameters: client\_id, redirect\_uri, state, timestamp (ISO 8601), signature, optional: uid, flow\_config
### Query API endpoints
* Sync endpoints: 30s timeout, immediate JSON response, single uid parameter
* Async endpoints: Job-based polling via `/v1/job/{task_id}`, users array (max 25), begin/end date range, Parquet file result
* Job management: `GET /v1/jobs` lists all jobs
## Terminology
* "Emerge Link" - The consent flow product
* "The Control Room" - Dashboard at dashboard.emergedata.ai
* "consent" - User permission for data access
* "export" - Data transfer from provider to Emerge
* "query" - Retrieving user data via API
* "signing\_secret" - HMAC signing credential (not "client\_secret")
* "flow\_config" - Named configuration for custom branding (replaced deprecated "flow\_version")
* "uid" or "partner\_uid" - Partner's user identifier
* "task\_id" or "job\_id" - Async query job identifier
* "config\_name" - Named configuration for consent flow (supports multiple configs per client)
* "data\_ready" - Boolean indicating if exported data is available for querying
* "consents" - Array of provider-specific consent records with scopes and validity
* "begin/end" - Date range parameters for async queries (replaced ingested\_after/before)
* "event\_id" - Integer type in Query API responses (not string)
## API domains
* Link API: [https://link.emergedata.ai](https://link.emergedata.ai)
* Query API: [https://query.emergedata.ai](https://query.emergedata.ai)
* Dashboard: [https://dashboard.emergedata.ai](https://dashboard.emergedata.ai)
* MCP Server: [https://docs.emergedata.ai/mcp](https://docs.emergedata.ai/mcp) (AI tool integration - updated from emerge.mintlify.dev)
* Docs site: [https://docs.emergedata.ai](https://docs.emergedata.ai) (production URL)
## AI-native features
### MCP (Model Context Protocol)
* Mintlify auto-generates MCP server at `/mcp` endpoint
* AI tools can search and query documentation semantically
* Configuration examples in `/ai/mcp-docs-setup.mdx` for Claude, Cursor, VS Code, Claude Code
* Quickstart guide includes AI tool setup section with MCP instructions for Cursor (.cursor/mcp.json), Claude Code (claude mcp add), and VS Code (.vscode/mcp.json)
### Contextual menu
* Enabled via `docs.json` "contextual" section
* Options: copy, view, chatgpt, claude, perplexity, mcp, cursor, vscode
* Right-click any code block or text selection for AI-powered actions
* Examples documented in `/ai/contextual-menu.mdx`
### Interactive API playground
* OpenAPI playground mode set to "interactive"
* Allows testing API endpoints directly from documentation
* Configured via `api.playground.display` in docs.json
## Working relationship
* Push back on ideas with citations and reasoning
* ALWAYS ask for clarification vs assumptions
* NEVER lie, guess, or fabricate information
# Contextual Menu
Source: https://docs.emergedata.ai/ai/contextual-menu
One-click AI integrations on every documentation page
Every page in these docs includes a contextual menu with quick actions for AI tools. Look for the menu icon in the top-right corner of any page.
## Available options
| Option | Description |
| -------------- | ----------------------------------- |
| **Copy** | Copy page content as Markdown |
| **View** | View page source |
| **ChatGPT** | Open in ChatGPT with page context |
| **Claude** | Open in Claude with page context |
| **Perplexity** | Search Perplexity with page context |
| **MCP** | Copy MCP server URL |
| **Cursor** | Copy Cursor MCP config |
| **VS Code** | Copy VS Code MCP config |
## Using the menu
### Copy as Markdown
Click **Copy** to copy the page content as formatted Markdown. Paste directly into:
* AI chat interfaces (Claude, ChatGPT, etc.)
* Your own documentation
* Issue descriptions
* Slack/Discord messages
### Open in AI tools
Click **ChatGPT** or **Claude** to open a new conversation with the page content pre-loaded. This is useful for:
* Asking follow-up questions about the page
* Generating code based on the documentation
* Getting explanations of complex concepts
### MCP configurations
Click **Cursor** or **VS Code** to copy the MCP configuration snippet for that tool. Paste into your configuration file to enable doc search.
**Cursor config:**
```json theme={null}
{
"mcpServers": {
"Emerge": {
"type": "http",
"url": "https://docs.emergedata.ai/mcp"
}
}
}
```
**VS Code config:**
```json theme={null}
{
"mcpServers": {
"Emerge": {
"type": "http",
"url": "https://docs.emergedata.ai/mcp"
}
}
}
```
## Workflow examples
### Getting help with a specific topic
1. Navigate to the relevant page (e.g., [Webhooks](/link/webhooks))
2. Click the contextual menu
3. Select **Claude** or **ChatGPT**
4. Ask your question with full context
### Adding MCP to your IDE
1. Open any page
2. Click the contextual menu
3. Select **Cursor** or **VS Code**
4. Paste the config into your project
5. Restart your IDE
### Sharing documentation
1. Find the page you want to share
2. Click **Copy** to get Markdown
3. Paste into your communication channel
4. Team members get formatted content
## Tips
If you ask documentation questions regularly, set up the MCP connection once and your AI tool will always have access.
For prompts that need specific documentation context, use Copy to include exact content rather than relying on AI search.
Copy documentation, paste into your AI tool, then share your code. The AI has both the official docs and your implementation.
# AI Workflow Examples
Source: https://docs.emergedata.ai/ai/examples
Real-world examples of using AI tools with Emerge documentation
These examples show how AI tools can help you integrate with Emerge more efficiently using the MCP connection.
## Example 1: Generate integration code
**You ask:**
> "Generate TypeScript and Python code to create a signed Emerge link and handle the callback"
**AI response (with MCP connection):**
The AI searches the docs, finds the [Create Links](/link/create-link) and [Callbacks](/link/callbacks) pages, and generates code that keeps `uid` server-side (never user input):
```typescript TypeScript theme={null}
import express from 'express';
import crypto from 'crypto';
const app = express();
const CLIENT_ID = process.env.EMERGE_CLIENT_ID;
const SIGNING_SECRET = process.env.EMERGE_SIGNING_SECRET;
const REDIRECT_URI = process.env.EMERGE_REDIRECT_URI || 'https://yourapp.com/emerge/callback';
if (!CLIENT_ID || !SIGNING_SECRET) {
throw new Error('Missing EMERGE_CLIENT_ID or EMERGE_SIGNING_SECRET');
}
const stateStore = new Map();
const uidMap = new Map();
function createLinkUrl(internalUserId: string): { url: string; state: string } {
const timestamp = new Date().toISOString();
const state = crypto.randomBytes(16).toString('hex');
const params: Record = {
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
state,
timestamp
};
// Use your internal user id or omit uid entirely.
if (internalUserId) {
params.uid = internalUserId;
}
const signatureBase = Object.keys(params)
.sort()
.map(key => `${key}=${params[key]}`)
.join('&');
const signature = crypto
.createHmac('sha256', SIGNING_SECRET)
.update(signatureBase)
.digest('hex');
const finalParams = new URLSearchParams(params);
finalParams.append('signature', signature);
return { url: `https://link.emergedata.ai/link/start?${finalParams.toString()}`, state };
}
app.get('/emerge/link', (req, res) => {
try {
const internalUserId = String(req.query.user_id || '');
if (!internalUserId) {
return res.status(400).send('Missing user_id');
}
const { url, state } = createLinkUrl(internalUserId);
stateStore.set(state, { internalUserId, createdAt: Date.now() });
return res.redirect(url);
} catch (err) {
console.error('Failed to create link', err);
return res.status(500).send('Server error');
}
});
app.get('/emerge/callback', async (req, res) => {
try {
const { status, state, uid, error_code } = req.query as Record;
const record = stateStore.get(state);
if (!record) {
return res.status(400).send('Invalid state');
}
stateStore.delete(state);
if (status === 'success' || status === 'reauthorized') {
if (!uid) {
return res.status(400).send('Missing uid');
}
uidMap.set(record.internalUserId, uid);
return res.redirect('/dashboard?connected=true');
}
const errorMessage = encodeURIComponent(error_code || 'unknown_error');
return res.redirect(`/connect?error=${errorMessage}`);
} catch (err) {
console.error('Callback error', err);
return res.status(500).send('Server error');
}
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
```
```python Python theme={null}
import os
import hmac
import hashlib
import secrets
from datetime import datetime, timezone
from urllib.parse import urlencode
from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse
import uvicorn
CLIENT_ID = os.getenv('EMERGE_CLIENT_ID')
SIGNING_SECRET = os.getenv('EMERGE_SIGNING_SECRET')
REDIRECT_URI = os.getenv('EMERGE_REDIRECT_URI', 'https://yourapp.com/emerge/callback')
if not CLIENT_ID or not SIGNING_SECRET:
raise RuntimeError('Missing EMERGE_CLIENT_ID or EMERGE_SIGNING_SECRET')
app = FastAPI()
state_store: dict[str, dict] = {}
uid_map: dict[str, str] = {}
def create_link_url(internal_user_id: str) -> tuple[str, str]:
timestamp = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
state = secrets.token_hex(16)
params = {
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI,
'state': state,
'timestamp': timestamp
}
# Use your internal user id or omit uid entirely.
if internal_user_id:
params['uid'] = internal_user_id
signature_base = '&'.join(f'{k}={v}' for k, v in sorted(params.items()))
signature = hmac.new(
SIGNING_SECRET.encode(),
signature_base.encode(),
hashlib.sha256
).hexdigest()
params['signature'] = signature
return f"https://link.emergedata.ai/link/start?{urlencode(params)}", state
@app.get('/emerge/link')
async def emerge_link(user_id: str):
if not user_id:
raise HTTPException(status_code=400, detail='Missing user_id')
url, state = create_link_url(user_id)
state_store[state] = {
'internal_user_id': user_id,
'created_at': datetime.now(timezone.utc).timestamp()
}
return RedirectResponse(url)
@app.get('/emerge/callback')
async def emerge_callback(
status: str,
state: str,
uid: str = '',
error_code: str | None = None
):
record = state_store.pop(state, None)
if not record:
raise HTTPException(status_code=400, detail='Invalid state')
if status in ('success', 'reauthorized'):
if not uid:
raise HTTPException(status_code=400, detail='Missing uid')
uid_map[record['internal_user_id']] = uid
return RedirectResponse('/dashboard?connected=true')
return RedirectResponse(f"/connect?error={error_code or 'unknown_error'}")
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=3000)
```
## Example 2: Understand data availability
**You ask:**
> "What data can I get from Emerge and how soon after consent?"
**AI response:**
The AI finds the [Query Overview](/query/overview) and [Webhooks](/link/webhooks) pages:
* Data is available **after export completes**. Poll `GET /export/status/{uid}` and wait until the required provider in `sources[]` is `data_ready: true`.
* Until a provider is ready, sync queries may return empty results. Handle this gracefully and retry with backoff.
## Example 3: Debug a webhook signature issue
**You ask:**
> "My webhook signature verification is failing. What am I doing wrong?"
**AI response:**
The AI checks [Webhooks](/link/webhooks) and points out the most common issues:
1. **Raw body required** - sign the raw request body, not parsed JSON.
2. **Header name** - use the `x-signature` header.
3. **Comparison** - use constant-time comparison to avoid subtle mismatches.
```typescript TypeScript theme={null}
import express from 'express';
import crypto from 'crypto';
const app = express();
app.use(express.raw({ type: 'application/json' }));
const WEBHOOK_SECRET = process.env.EMERGE_WEBHOOK_SECRET;
if (!WEBHOOK_SECRET) {
throw new Error('Missing EMERGE_WEBHOOK_SECRET');
}
app.post('/webhooks/emerge', async (req, res) => {
try {
const signature = req.header('x-signature');
if (!signature) {
return res.status(401).send('Missing signature');
}
const expected = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
const signatureBuf = Buffer.from(signature, 'hex');
const expectedBuf = Buffer.from(expected, 'hex');
if (signatureBuf.length !== expectedBuf.length || !crypto.timingSafeEqual(signatureBuf, expectedBuf)) {
return res.status(401).send('Invalid signature');
}
const payload = JSON.parse(req.body.toString('utf8'));
const { event, uid } = payload;
console.log(`Received ${event} for uid ${uid}`);
return res.status(200).send('OK');
} catch (err) {
console.error('Webhook error', err);
return res.status(500).send('Server error');
}
});
app.listen(3001, () => {
console.log('Webhook listener running on http://localhost:3001');
});
```
```python Python theme={null}
import os
import hmac
import hashlib
import json
from fastapi import FastAPI, HTTPException, Request
import uvicorn
app = FastAPI()
WEBHOOK_SECRET = os.getenv('EMERGE_WEBHOOK_SECRET')
if not WEBHOOK_SECRET:
raise RuntimeError('Missing EMERGE_WEBHOOK_SECRET')
@app.post('/webhooks/emerge')
async def emerge_webhook(request: Request):
signature = request.headers.get('x-signature')
if not signature:
raise HTTPException(status_code=401, detail='Missing signature')
body = await request.body()
expected = hmac.new(
WEBHOOK_SECRET.encode(),
body,
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, expected):
raise HTTPException(status_code=401, detail='Invalid signature')
try:
payload = json.loads(body)
except json.JSONDecodeError as exc:
raise HTTPException(status_code=400, detail='Invalid JSON') from exc
event = payload.get('event')
uid = payload.get('uid')
print(f"Received {event} for uid {uid}")
return {'status': 'ok'}
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=3001)
```
## Example 4: Plan a nightly sync
**You ask:**
> "I want to sync Emerge data to my database nightly. What's the best approach?"
**AI response:**
The AI finds [Pagination](/query/pagination) and [Query Overview](/query/overview):
```mermaid theme={null}
graph LR
A[Cron Job] --> B[Delta Query]
B --> C[Process Records]
C --> D[Update Database]
D --> E[Store Sync State]
```
**Recommended approach:**
* Use **delta queries** with `ingested_begin` to fetch new data since the last run.
* Page with `cursor` until `has_more` is false.
* Store `applied_ingested_end` as your next `ingested_begin`.
```typescript TypeScript theme={null}
interface SyncState {
lastIngestedEnd: string;
}
async function deltaSync(uid: string, token: string, state: SyncState): Promise {
let cursor: string | undefined;
let appliedEnd = state.lastIngestedEnd;
const newData: unknown[] = [];
try {
do {
const params = new URLSearchParams({
uid,
ingested_begin: appliedEnd
});
if (cursor) {
params.set('cursor', cursor);
}
const response = await fetch(
`https://query.emergedata.ai/v1/sync/get_search?${params.toString()}`,
{ headers: { Authorization: `Bearer ${token}` } }
);
if (!response.ok) {
const body = await response.text();
throw new Error(`Query failed (${response.status}): ${body}`);
}
const result = await response.json();
newData.push(...(result.data || []));
appliedEnd = result.applied_ingested_end || appliedEnd;
cursor = result.has_more ? result.next_cursor : undefined;
} while (cursor);
await processNewData(newData);
return { lastIngestedEnd: appliedEnd };
} catch (err) {
console.error('Delta sync failed', err);
throw err;
}
}
async function processNewData(records: unknown[]) {
console.log(`Processing ${records.length} records`);
}
async function runDeltaSync() {
const token = process.env.EMERGE_API_TOKEN;
if (!token) {
throw new Error('Missing EMERGE_API_TOKEN');
}
const state = { lastIngestedEnd: '2024-01-01T00:00:00Z' };
await deltaSync('psub_d4e5f6789012345678901234abcdef01', token, state);
}
runDeltaSync().catch(err => {
console.error(err);
process.exit(1);
});
```
```python Python theme={null}
import asyncio
import httpx
from dataclasses import dataclass
from typing import Any
@dataclass
class SyncState:
last_ingested_end: str
async def delta_sync(uid: str, token: str, state: SyncState) -> SyncState:
cursor: str | None = None
applied_end = state.last_ingested_end
new_data: list[Any] = []
try:
async with httpx.AsyncClient(timeout=30) as client:
while True:
params = {
'uid': uid,
'ingested_begin': applied_end
}
if cursor:
params['cursor'] = cursor
response = await client.get(
'https://query.emergedata.ai/v1/sync/get_search',
params=params,
headers={'Authorization': f'Bearer {token}'}
)
response.raise_for_status()
result = response.json()
new_data.extend(result.get('data', []))
applied_end = result.get('applied_ingested_end', applied_end)
if not result.get('has_more'):
break
cursor = result.get('next_cursor')
await process_new_data(new_data)
return SyncState(last_ingested_end=applied_end)
except httpx.HTTPError as exc:
raise RuntimeError(f'Delta sync failed: {exc}') from exc
async def process_new_data(records: list[Any]):
print(f'Processing {len(records)} records')
if __name__ == '__main__':
async def main():
state = SyncState(last_ingested_end='2024-01-01T00:00:00Z')
await delta_sync('psub_d4e5f6789012345678901234abcdef01', 'your_api_token', state)
asyncio.run(main())
```
## Example 5: Choose sync vs async for mobile
**You ask:**
> "Should I use sync or async queries for my mobile app?"
**AI response:**
For mobile apps, **sync queries are recommended** because they return JSON immediately and are simpler to integrate. Your mobile app should call **your backend**, not the Query API directly.
```typescript TypeScript theme={null}
async function getSearchHistory(uid: string, token: string) {
try {
const response = await fetch(
`https://query.emergedata.ai/v1/sync/get_search?uid=${encodeURIComponent(uid)}`,
{ headers: { Authorization: `Bearer ${token}` } }
);
if (!response.ok) {
const body = await response.text();
throw new Error(`Query failed (${response.status}): ${body}`);
}
return await response.json();
} catch (err) {
console.error('Search history query failed', err);
throw err;
}
}
async function runQuery() {
const token = process.env.EMERGE_API_TOKEN;
if (!token) {
throw new Error('Missing EMERGE_API_TOKEN');
}
const data = await getSearchHistory('psub_d4e5f6789012345678901234abcdef01', token);
console.log(data);
}
runQuery().catch(err => {
console.error(err);
process.exit(1);
});
```
```python Python theme={null}
import asyncio
import httpx
async def get_search_history(uid: str, token: str) -> dict:
try:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(
'https://query.emergedata.ai/v1/sync/get_search',
params={'uid': uid},
headers={'Authorization': f'Bearer {token}'}
)
response.raise_for_status()
return response.json()
except httpx.HTTPError as exc:
raise RuntimeError(f'Search history query failed: {exc}') from exc
if __name__ == '__main__':
async def main():
data = await get_search_history('psub_d4e5f6789012345678901234abcdef01', 'your_api_token')
print(data)
asyncio.run(main())
```
## Example 6: Query user data via MCP
These examples show using the **Query API MCP server** to directly query consented user data from AI tools. This is different from the documentation MCP - it provides real data access.
**Setup required:** These examples require the [Query API MCP server](/ai/mcp-query-setup) with valid credentials (`auth_token` and `uid`).
Using Claude Code with Query API MCP configured:
```bash theme={null}
claude "Analyze search patterns for psub_c3d4e5f6789012345678901234abcdef from the last month and identify the top 3 interest categories"
```
**What happens:**
1. Claude calls `get_search_data` tool with date range filter
2. Receives search history data grouped by category
3. Analyzes query frequency and patterns
4. Returns insights with specific examples
**Example response:**
```text theme={null}
Based on search history analysis:
1. **Technology/Software** (42% of searches)
- Frequent queries about React, TypeScript, AWS
- Pattern: Learning new frameworks
2. **Shopping/Electronics** (28% of searches)
- Looking at laptop reviews, monitors, keyboards
- Pattern: Office equipment research
3. **Health/Fitness** (18% of searches)
- Running training plans, nutrition guides
- Pattern: Marathon preparation
```
Using Cursor AI chat with Query API MCP configured:
```text theme={null}
"Based on this user's YouTube watch history and browsing patterns from the last 2 weeks,
suggest 5 relevant blog topics for our content calendar"
```
**What happens:**
1. AI calls `get_youtube_data` and `get_browsing_data` tools
2. Identifies themes and recurring interests
3. Cross-references patterns across data sources
4. Generates topic suggestions with rationale
**Example response:**
```text theme={null}
Recommended blog topics based on user data:
1. "Getting Started with Docker in 2024"
- Watched 12 Docker tutorials, visited Docker docs 8 times
2. "Best Practices for React State Management"
- Heavy focus on Redux and Zustand content
3. "Home Office Setup Guide for Developers"
- Browsed ergonomic furniture, watched office tour videos
4. "Debugging Node.js Performance Issues"
- Searched for profiling tools, read performance articles
5. "AI Tools for Code Review"
- Interest in GitHub Copilot, Claude Code, and similar tools
```
Using Claude Desktop with Query API MCP:
```text theme={null}
"Create a user activity summary for the last 7 days showing:
- Most searched topics
- YouTube categories watched
- Top browsing domains
- Peak activity times"
```
**What happens:**
1. AI calls multiple MCP tools in parallel (`get_search_data`, `get_youtube_data`, `get_browsing_data`)
2. Aggregates and analyzes data across sources
3. Identifies patterns and trends
4. Formats results as structured summary
**Example response:**
```text theme={null}
User Activity Summary (Last 7 Days)
📊 Search Activity
- 127 total searches
- Top topics: Machine Learning (23), JavaScript (18), AWS (15)
- Peak search time: 10am-12pm EST
🎥 YouTube Activity
- 34 videos watched (8.2 hours)
- Top categories: Technology (41%), Education (32%), Entertainment (27%)
- Longest session: 2.5 hours on Sunday
🌐 Browsing Activity
- 412 page views
- Top domains: github.com (87), stackoverflow.com (64), docs.aws.amazon.com (42)
- Most active day: Wednesday (94 pages)
```
Using Claude Code to generate sync script:
```bash theme={null}
claude "Write a Python script that uses the MCP tools to sync all new search data since my last sync timestamp into my data warehouse, handling pagination automatically"
```
**What happens:**
1. Claude accesses Query API MCP tool documentation
2. Generates script using `get_search_data` with delta query parameters
3. Implements pagination with `cursor` and `has_more` handling
4. Uses `ingested_begin` for incremental updates
Claude will generate a complete script that:
* Loads last sync timestamp from state file
* Calls MCP tool with `ingested_begin` parameter
* Pages through all results
* Saves `applied_ingested_end` for next sync
## Try it yourself
### For documentation help (Docs MCP):
* "How do I implement retry logic for Emerge API calls?"
* "What happens if a user revokes consent?"
* "Generate a React component that shows a Connect Data button"
* "Show the correct way to handle uid without asking the user"
See [MCP Docs Setup](/ai/mcp-docs-setup) to connect your AI tool.
### For querying user data (Query API MCP):
* "Show me search patterns for the last week"
* "What categories is this user most interested in?"
* "Compare browsing and YouTube activity to find common interests"
* "Generate a weekly activity report"
See [Query API MCP Setup](/ai/mcp-query-setup) to connect with credentials.
# How to build an app with Emerge (Quickstart Masterprompt)
Source: https://docs.emergedata.ai/ai/how-to-build-an-app-with-emerge-quickstart-masterprompt
Hidden masterprompt for AI agents to build an end-to-end Emerge integration
Use the masterprompt below to guide AI agents through an end-to-end Emerge integration without hardcoding API specs. It keeps identifiers private and instructs the agent to read the live docs for exact endpoints, parameters, and response formats.
## Masterprompt (copy/paste)
```text theme={null}
You are building a full-stack app that integrates Emerge Link + Query end-to-end.
Rules:
- Do NOT hardcode Emerge endpoints or parameter lists. Always read the live docs via MCP for exact references.
- Keep Link (consent) and Query (data retrieval) separate.
- Before coding, ask the user for config fields and confirm any URLs/params against the docs. At minimum ask for: client_id, signing_secret, api_token, redirect_uri, flow_config name (if any), and the current Link start URL + Query endpoint URLs + export/consent status URLs from the docs.
- Generate signed links server-side. Never expose signing_secret or API tokens in the frontend.
- Generate a random state, store it server-side, and verify it on callback.
- Never ask end-users for uid. Use your internal user id (server-side) or omit uid and store the callback uid.
- Poll export readiness using the Link export status endpoint: https://link.emergedata.ai/export/status/{uid}.
- Provide TypeScript and Python examples with async/await and error handling.
- Use privacy-first messaging and explain why each step matters when it is not obvious.
Required references (read before coding):
- /link/create-link (signature rules + link parameters)
- /link/callbacks (status + error handling)
- Link API export status endpoint (GET /export/status/{uid})
- Link API consent status endpoint (GET /consent/status/{uid})
- /query/overview (sync vs async + auth)
- /query/pagination (cursor + delta sync)
Output requirements:
1) Direct answer
2) Code examples (TypeScript + Python)
3) Links to the docs pages you used
4) Edge cases/gotchas
```
## Flow summary (spec-free)
1. **Create a signed consent link** server-side and redirect the user.
2. **Handle the callback** by verifying `state` and storing the returned `uid`.
3. **Poll export status** via `https://link.emergedata.ai/export/status/{uid}` before querying.
4. **Query data** using the stored `uid`, with pagination and delta sync where needed.
5. **Check consent status** via `https://link.emergedata.ai/consent/status/{uid}` and stop processing if revoked.
Why this matters:
* The `uid` is the canonical user scope. Keeping it server-side prevents wrong-user data access.
* Polling export status avoids empty results and improves UX when data is not ready.
* Keeping secrets off the client prevents data leakage.
## Integration scaffold (server-side)
```typescript TypeScript theme={null}
import express from 'express';
import crypto from 'crypto';
const app = express();
const stateStore = new Map();
const uidMap = new Map();
function loadConfig() {
const linkStartUrl = process.env.EMERGE_LINK_START_URL;
const querySearchUrl = process.env.EMERGE_QUERY_SEARCH_URL;
const exportStatusUrl = process.env.EMERGE_EXPORT_STATUS_URL;
const consentStatusUrl = process.env.EMERGE_CONSENT_STATUS_URL;
const signingSecret = process.env.EMERGE_SIGNING_SECRET;
const linkParamsJson = process.env.EMERGE_LINK_PARAMS_JSON;
if (!linkStartUrl || !querySearchUrl || !exportStatusUrl || !consentStatusUrl || !signingSecret || !linkParamsJson) {
throw new Error('Missing EMERGE_LINK_START_URL, EMERGE_QUERY_SEARCH_URL, EMERGE_EXPORT_STATUS_URL, EMERGE_CONSENT_STATUS_URL, EMERGE_SIGNING_SECRET, or EMERGE_LINK_PARAMS_JSON');
}
return { linkStartUrl, querySearchUrl, exportStatusUrl, consentStatusUrl, signingSecret, linkParamsJson };
}
function signParams(params: Record, signingSecret: string): string {
const signatureBase = Object.keys(params)
.sort()
.map(key => `${key}=${params[key]}`)
.join('&');
return crypto
.createHmac('sha256', signingSecret)
.update(signatureBase)
.digest('hex');
}
function buildSignedLinkUrl(internalUserId: string): { url: string; state: string } {
const { linkStartUrl, signingSecret, linkParamsJson } = loadConfig();
const state = crypto.randomBytes(16).toString('hex');
const timestamp = new Date().toISOString();
const params: Record = JSON.parse(linkParamsJson);
params.state = state;
params.timestamp = timestamp;
params.uid = internalUserId;
const signature = signParams(params, signingSecret);
const finalParams = new URLSearchParams(params);
finalParams.append('signature', signature);
return { url: `${linkStartUrl}?${finalParams.toString()}`, state };
}
app.get('/connect-data', async (req, res) => {
try {
const internalUserId = String(req.query.user_id || '');
if (!internalUserId) {
return res.status(400).send('Missing user_id');
}
const { url, state } = buildSignedLinkUrl(internalUserId);
stateStore.set(state, { internalUserId, createdAt: Date.now() });
return res.redirect(url);
} catch (err) {
console.error('Failed to create link', err);
return res.status(500).send('Server error');
}
});
app.get('/emerge/callback', async (req, res) => {
try {
const { status, state, uid, error_code } = req.query as Record;
const record = stateStore.get(state);
if (!record) {
return res.status(400).send('Invalid state');
}
stateStore.delete(state);
if (status === 'success' || status === 'reauthorized') {
if (!uid) {
return res.status(400).send('Missing uid');
}
uidMap.set(record.internalUserId, uid);
return res.redirect('/dashboard?connected=true');
}
const errorMessage = encodeURIComponent(error_code || 'unknown_error');
return res.redirect(`/connect?error=${errorMessage}`);
} catch (err) {
console.error('Callback error', err);
return res.status(500).send('Server error');
}
});
function buildStatusUrl(template: string, uid: string): string {
if (template.includes('{uid}')) {
return template.replace('{uid}', encodeURIComponent(uid));
}
return template;
}
async function pollExportReady(uid: string, provider: 'google_data' | 'gmail' = 'google_data'): Promise {
const { exportStatusUrl } = loadConfig();
const token = process.env.EMERGE_API_TOKEN;
if (!token) {
throw new Error('Missing EMERGE_API_TOKEN');
}
const maxAttempts = 10;
const baseDelayMs = 1500;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
const url = buildStatusUrl(exportStatusUrl, uid);
const response = await fetch(url, {
headers: { Authorization: `Bearer ${token}` }
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Export status failed (${response.status}): ${body}`);
}
const status = await response.json() as {
sources?: Array<{ provider: string; data_ready: boolean }>;
};
const source = status.sources?.find((item) => item.provider === provider);
if (source?.data_ready === true) {
return;
}
const delay = baseDelayMs * attempt;
await new Promise(resolve => setTimeout(resolve, delay));
}
throw new Error('Export not ready after polling');
}
app.get('/query-search', async (req, res) => {
try {
const internalUserId = String(req.query.user_id || '');
const emergeUid = uidMap.get(internalUserId);
if (!emergeUid) {
return res.status(404).send('User not connected');
}
const exportProvider = (process.env.EMERGE_EXPORT_PROVIDER as 'google_data' | 'gmail' | undefined) || 'google_data';
await pollExportReady(emergeUid, exportProvider);
const { querySearchUrl } = loadConfig();
const url = new URL(querySearchUrl);
url.searchParams.set('uid', emergeUid);
const response = await fetch(url.toString(), {
headers: { Authorization: `Bearer ${process.env.EMERGE_API_TOKEN}` }
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Query failed (${response.status}): ${body}`);
}
const data = await response.json();
return res.json(data);
} catch (err) {
console.error('Query error', err);
return res.status(500).send('Server error');
}
});
app.get('/consent-status', async (req, res) => {
try {
const internalUserId = String(req.query.user_id || '');
const emergeUid = uidMap.get(internalUserId);
if (!emergeUid) {
return res.status(404).send('User not connected');
}
const { consentStatusUrl } = loadConfig();
const token = process.env.EMERGE_API_TOKEN;
if (!token) {
return res.status(500).send('Missing EMERGE_API_TOKEN');
}
const url = buildStatusUrl(consentStatusUrl, emergeUid);
const response = await fetch(url, {
headers: { Authorization: `Bearer ${token}` }
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Consent status failed (${response.status}): ${body}`);
}
const data = await response.json();
return res.json(data);
} catch (err) {
console.error('Consent status error', err);
return res.status(500).send('Server error');
}
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
```
```python Python theme={null}
import os
import json
import hmac
import hashlib
import secrets
import asyncio
from datetime import datetime, timezone
from urllib.parse import urlencode
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse
import uvicorn
app = FastAPI()
state_store: dict[str, dict] = {}
uid_map: dict[str, str] = {}
def load_config() -> dict:
link_start_url = os.getenv("EMERGE_LINK_START_URL")
query_search_url = os.getenv("EMERGE_QUERY_SEARCH_URL")
export_status_url = os.getenv("EMERGE_EXPORT_STATUS_URL")
consent_status_url = os.getenv("EMERGE_CONSENT_STATUS_URL")
signing_secret = os.getenv("EMERGE_SIGNING_SECRET")
link_params_json = os.getenv("EMERGE_LINK_PARAMS_JSON")
if not all([link_start_url, query_search_url, export_status_url, consent_status_url, signing_secret, link_params_json]):
raise RuntimeError(
"Missing EMERGE_LINK_START_URL, EMERGE_QUERY_SEARCH_URL, "
"EMERGE_EXPORT_STATUS_URL, EMERGE_CONSENT_STATUS_URL, "
"EMERGE_SIGNING_SECRET, or EMERGE_LINK_PARAMS_JSON"
)
return {
"link_start_url": link_start_url,
"query_search_url": query_search_url,
"export_status_url": export_status_url,
"consent_status_url": consent_status_url,
"signing_secret": signing_secret,
"link_params_json": link_params_json
}
def sign_params(params: dict, signing_secret: str) -> str:
signature_base = "&".join(f"{k}={v}" for k, v in sorted(params.items()))
return hmac.new(
signing_secret.encode(),
signature_base.encode(),
hashlib.sha256
).hexdigest()
def build_signed_link_url(internal_user_id: str) -> tuple[str, str]:
config = load_config()
state = secrets.token_hex(16)
timestamp = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
params = json.loads(config["link_params_json"])
params["state"] = state
params["timestamp"] = timestamp
params["uid"] = internal_user_id
signature = sign_params(params, config["signing_secret"])
params["signature"] = signature
url = f"{config['link_start_url']}?{urlencode(params)}"
return url, state
def build_status_url(template: str, uid: str) -> str:
if "{uid}" in template:
return template.replace("{uid}", uid)
return template
async def poll_export_ready(uid: str, provider: str = "google_data") -> None:
config = load_config()
token = os.getenv("EMERGE_API_TOKEN")
if not token:
raise HTTPException(status_code=500, detail="Missing EMERGE_API_TOKEN")
max_attempts = 10
base_delay = 1.5
async with httpx.AsyncClient(timeout=30) as client:
for attempt in range(1, max_attempts + 1):
url = build_status_url(config["export_status_url"], uid)
response = await client.get(
url,
headers={"Authorization": f"Bearer {token}"}
)
response.raise_for_status()
payload = response.json()
source = next(
(item for item in payload.get("sources", []) if item.get("provider") == provider),
None
)
if source and source.get("data_ready") is True:
return
await asyncio.sleep(base_delay * attempt)
raise HTTPException(status_code=504, detail="Export not ready after polling")
@app.get("/connect-data")
async def connect_data(user_id: str):
if not user_id:
raise HTTPException(status_code=400, detail="Missing user_id")
url, state = build_signed_link_url(user_id)
state_store[state] = {"internal_user_id": user_id, "created_at": datetime.now(timezone.utc).timestamp()}
return RedirectResponse(url)
@app.get("/emerge/callback")
async def emerge_callback(
status: str,
state: str,
uid: str = "",
error_code: str | None = None
):
record = state_store.pop(state, None)
if not record:
raise HTTPException(status_code=400, detail="Invalid state")
if status in ("success", "reauthorized"):
if not uid:
raise HTTPException(status_code=400, detail="Missing uid")
uid_map[record["internal_user_id"]] = uid
return RedirectResponse("/dashboard?connected=true")
return RedirectResponse(f"/connect?error={error_code or 'unknown_error'}")
@app.get("/query-search")
async def query_search(user_id: str):
emerge_uid = uid_map.get(user_id)
if not emerge_uid:
raise HTTPException(status_code=404, detail="User not connected")
config = load_config()
token = os.getenv("EMERGE_API_TOKEN")
if not token:
raise HTTPException(status_code=500, detail="Missing EMERGE_API_TOKEN")
try:
export_provider = os.getenv("EMERGE_EXPORT_PROVIDER", "google_data")
await poll_export_ready(emerge_uid, export_provider)
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(
config["query_search_url"],
params={"uid": emerge_uid},
headers={"Authorization": f"Bearer {token}"}
)
response.raise_for_status()
return response.json()
except httpx.HTTPError as exc:
raise HTTPException(status_code=502, detail=f"Query failed: {exc}") from exc
@app.get("/consent-status")
async def consent_status(user_id: str):
emerge_uid = uid_map.get(user_id)
if not emerge_uid:
raise HTTPException(status_code=404, detail="User not connected")
config = load_config()
token = os.getenv("EMERGE_API_TOKEN")
if not token:
raise HTTPException(status_code=500, detail="Missing EMERGE_API_TOKEN")
try:
async with httpx.AsyncClient(timeout=30) as client:
url = build_status_url(config["consent_status_url"], emerge_uid)
response = await client.get(
url,
headers={"Authorization": f"Bearer {token}"}
)
response.raise_for_status()
return response.json()
except httpx.HTTPError as exc:
raise HTTPException(status_code=502, detail=f"Consent status failed: {exc}") from exc
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=3000)
```
## Related documentation
* [Create Links](/link/create-link)
* [Callbacks](/link/callbacks)
* [Link Overview](/link/overview)
* [Query Overview](/query/overview)
* [Pagination & Delta Queries](/query/pagination)
## Edge cases / gotchas
* `state` must be verified on callback or you risk account linking attacks.
* Querying before export is ready can return empty results; poll export status and retry with backoff.
* If a user revokes consent, stop processing and delete data to stay privacy-first; use the consent status endpoint to detect changes.
* Never prompt the user to type a `uid` — it must stay server-side.
# MCP Docs Setup
Source: https://docs.emergedata.ai/ai/mcp-docs-setup
Connect AI tools to Emerge documentation via MCP
The Model Context Protocol (MCP) allows AI tools to search and query documentation directly. An MCP server is automatically generated for these docs.
**Looking for the Query API MCP server?** This page covers the **documentation MCP server**. For AI agent access to the Query API (data retrieval), see [Query API MCP Setup](/ai/mcp-query-setup).
## MCP Servers
Emerge provides two MCP servers:
| Server | Purpose | URL |
| ----------------- | --------------------------- | -------------------------------- |
| **Documentation** | Search and query these docs | `https://docs.emergedata.ai/mcp` |
| **Query API** | Retrieve user data | `https://mcp.emergedata.ai/mcp` |
This page covers the **Documentation MCP server** setup. For Query API MCP server setup, see [Query API MCP Setup](/ai/mcp-query-setup).
## Documentation MCP Server URL
```
https://docs.emergedata.ai/mcp
```
**Transport**: Streamable HTTP (`http`)
## Setup by tool
### Add MCP server
```bash theme={null}
claude mcp add --transport http emerge https://docs.emergedata.ai/mcp
```
### Verify connection
```bash theme={null}
claude mcp list
```
You should see:
```
emerge: https://docs.emergedata.ai/mcp (connected)
```
### Usage
Claude Code will automatically use the docs when relevant:
```bash theme={null}
claude "How do I implement delta queries in Emerge?"
```
### Configuration file
Update `claude_desktop_config.json`:
```json theme={null}
{
"mcpServers": {
"emerge": {
"command": "",
"url": "https://docs.emergedata.ai/mcp"
}
}
}
```
### Configuration file
Create or edit `.cursor/mcp.json` in your project root:
```json theme={null}
{
"mcpServers": {
"Emerge": {
"type": "http",
"url": "https://docs.emergedata.ai/mcp"
}
}
}
```
### Global configuration
For all projects, add to your global Cursor settings:
1. Open Cursor
2. Press `Cmd/Ctrl + ,` for settings
3. Search for "MCP"
4. Add the server configuration
### Usage
Once configured, Cursor can:
* Answer questions about Emerge API in chat
* Generate integration code with context
* Explain error messages and suggest fixes
### MCP configuration
Create `.vscode/mcp.json` in your workspace:
```json theme={null}
{
"mcpServers": {
"Emerge": {
"type": "http",
"url": "https://docs.emergedata.ai/mcp"
}
}
}
```
### With GitHub Copilot
If using Copilot Chat, the MCP connection provides:
* Accurate Emerge API suggestions
* Code completion with real examples
* Documentation-backed explanations
### With other AI extensions
Any VS Code AI extension supporting MCP can use this configuration.
### Add MCP server
```bash theme={null}
codex mcp add emerge --url https://docs.emergedata.ai/mcp
```
### Verify connection
```bash theme={null}
codex mcp list
```
### Configuration file
Update `mcp_config.json`:
```json theme={null}
{
"mcpServers": {
"emerge": {
"url": "https://docs.emergedata.ai/mcp",
"headers": {}
}
}
}
```
## Verifying the connection
After setup, test the connection by asking your AI tool:
> "Search the Emerge documentation for how to handle callbacks"
The AI should:
1. Query the MCP server
2. Find the callbacks documentation
3. Return a detailed answer with code examples
If the AI gives a generic response or says it can't find information, the MCP connection may not be configured correctly.
## Troubleshooting
Some AI tools require explicit activation:
* Restart the tool after adding configuration
* Check that the config file is in the correct location
* Verify the URL is exactly `https://docs.emergedata.ai/mcp`
* Verify transport is `http` (not `sse`)
The MCP server should respond within seconds. If timeouts occur:
* Check your internet connection
* Try accessing the URL in a browser
* Contact support if the issue persists
The MCP server reflects the current live documentation. If responses seem outdated:
* The AI may be using cached context
* Start a new conversation
* Explicitly ask it to search the docs again
## What the AI can access
The MCP server provides access to:
All guide pages (Link API, Query API, etc.)
API reference documentation
Code examples in TypeScript and Python
Troubleshooting and best practices
The AI cannot:
* Access your API credentials
* Make API calls on your behalf
* See your application's data
## Next steps
One-click AI integrations on every page
See AI workflow examples
# MCP Query Setup
Source: https://docs.emergedata.ai/ai/mcp-query-setup
Connect AI tools to query consented user data via MCP
The Query API MCP server gives AI agents (Claude, Cursor, VS Code) secure access to consented user data. Instead of making direct HTTP calls, AI tools use the Model Context Protocol with session-based credentials.
**Different from Docs MCP**: This server queries **user data**. For documentation search, see [Docs MCP Setup](/ai/mcp-docs-setup).
## Architecture
```mermaid theme={null}
graph LR
A[AI Agent
Claude Code, Cursor] -->|MCP Protocol
session credentials| B[MCP Server
NestJS
StreamableHTTP]
B -->|HTTP/JSON
Bearer token| C[Query API
FastAPI
ClickHouse]
```
The MCP server is a thin wrapper around Query API sync endpoints:
| Feature | MCP Server | Direct HTTP |
| ------------------ | ---------------------------- | ----------------------------- |
| **Protocol** | MCP (JSON-RPC over HTTP) | REST API |
| **Credentials** | Session-based (provide once) | Per-request (Bearer token) |
| **Tool Discovery** | Built-in (`tools/list`) | OpenAPI spec |
| **Ship with MCP** | Native support | Manual implementation |
| **Best For** | AI agents, IDE plugins | Server-to-server, custom apps |
## Prerequisites
The Control Room account with API credentials
At least one user with granted consent
Don't have credentials? [Sign up here](https://dashboard.emergedata.ai).
## MCP Server URL
```
https://mcp.emergedata.ai/mcp
```
**Authentication**: Session-based credentials passed via URL parameters during initialization.
## Setup by Tool
### Add MCP Server
```bash theme={null}
claude mcp add emerge-query "https://mcp.emergedata.ai/mcp?auth_token=YOUR_TOKEN&uid=YOUR_UID"
```
### Verify Connection
```bash theme={null}
claude mcp list
```
You should see:
```
emerge-query: https://mcp.emergedata.ai/mcp (connected)
```
### Usage
Now you can query user data:
```bash theme={null}
claude "Get search history for psub_c3d4e5f6789012345678901234abcdef from the last week"
```
Claude Code will:
1. Call the `get_search_data` tool
2. Apply date range filters
3. Return formatted results
### Add MCP Server
1. Open Claude desktop app
2. Go to **Settings** → **Connectors**
3. Click **Add custom connector**
4. Enter configuration:
* **Name**: Emerge Query API
* **URL**: `https://mcp.emergedata.ai/mcp`
5. Add connection parameters:
```
?auth_token=YOUR_API_TOKEN&uid=YOUR_USER_ID
```
6. Click **Save**
### Usage
Now you can ask Claude to query user data:
* "Get search history for the last week"
* "What YouTube videos has this user watched?"
* "Show me browsing history filtered by Shopping category"
Claude will automatically call the appropriate MCP tools and format the results.
### Configuration File
Create or edit `.cursor/mcp.json` in your project root:
```json theme={null}
{
"mcpServers": {
"Emerge Query": {
"url": "https://mcp.emergedata.ai/mcp?auth_token=YOUR_TOKEN&uid=YOUR_USER_ID"
}
}
}
```
**Security**: Never commit credentials to git. Use environment variables:
```json theme={null}
{
"mcpServers": {
"Emerge Query": {
"url": "https://mcp.emergedata.ai/mcp?auth_token=${EMERGE_TOKEN}&uid=${EMERGE_UID}"
}
}
}
```
### Usage
In Cursor's AI chat, ask questions about user data:
```
@Emerge Query Show me search patterns for the last month
```
Cursor will:
1. Query the MCP server
2. Receive structured data
3. Analyze and present insights
### MCP Configuration
Create `.vscode/mcp.json` in your workspace:
```json theme={null}
{
"servers": {
"Emerge Query": {
"type": "http",
"url": "https://mcp.emergedata.ai/mcp?auth_token=YOUR_TOKEN&uid=YOUR_UID"
}
}
}
```
### With GitHub Copilot
If using Copilot Chat, the MCP connection provides:
* Direct access to user data via natural language
* Structured queries with proper filtering
* Context-aware code generation
### With Other AI Extensions
Any VS Code AI extension supporting MCP can use this configuration.
### Verify Connection
After configuration, test the health endpoint:
```bash theme={null}
curl https://mcp.emergedata.ai/mcp/health
# Expected response
{
"status": "ok",
"service": "mcp-server",
"version": "1.0.0",
"protocol": "streamable-http"
}
```
## Session Credentials
The MCP server uses **session-based credentials** — provide them once on connection, and all tool calls use them automatically.
| Credential | What it is | Format | Example |
| ------------ | ----------------------------------------------- | ---------------------------------- | --------------------------------------- |
| `auth_token` | Base64-encoded JWT from The Control Room | Starts with `eyJ...` (long string) | `eyJhbGciOiJSUzI1NiIs...` |
| `uid` | Consented user identifier from consent callback | Typically starts with `psub_` | `psub_c3d4e5f6789012345678901234abcdef` |
**Don't mix these up!** A common mistake is swapping `auth_token` and `uid`. The `auth_token` is always a long JWT string starting with `eyJ`. The `uid` is a shorter identifier, typically starting with `psub_`.
You can override session credentials for individual tool calls by passing `auth_token` and `uid` as tool parameters.
### Security Best Practices
Never commit credentials to git repositories
Use environment variables in configuration files
Rotate API tokens regularly via The Control Room
Use unique `uid` per user (don't share across users)
## Available Tools
The MCP server exposes 5 tools that map 1:1 to Query API sync endpoints:
| MCP Tool | Query API Endpoint | Data Type |
| ------------------- | ----------------------- | --------------------- |
| `get_search_data` | `/v1/sync/get_search` | Search history |
| `get_youtube_data` | `/v1/sync/get_youtube` | YouTube watch history |
| `get_browsing_data` | `/v1/sync/get_browsing` | Web browsing |
| `get_ads_data` | `/v1/sync/get_ads` | Ad interactions |
| `get_receipts_data` | `/v1/sync/get_receipts` | Purchase receipts |
See [MCP Query Tools](/ai/mcp-query-tools) for detailed parameter and response documentation.
## Response Format
All tools return the same structure:
```json theme={null}
{
"success": true,
"count": 10,
"has_more": true,
"next_cursor": "eyJsYXN0X2V2ZW50X2lkIjoxMjM0NX0=",
"applied_ingested_end": "2024-01-15T10:30:00Z",
"data": [
// ... event objects
]
}
```
## Pagination
Use cursor-based pagination for large datasets:
```typescript theme={null}
let cursor = null;
let allData = [];
do {
const result = await use_mcp_tool({
tool: "get_search_data",
arguments: {
begin: "2024-01-01T00:00:00Z",
limit: 1000,
cursor: cursor
}
});
allData.push(...result.data);
cursor = result.next_cursor;
} while (result.has_more);
```
See [Pagination Guide](/query/pagination) for best practices.
## Error Handling
When a tool call fails, it returns:
```json theme={null}
{
"isError": true,
"content": [
{
"type": "text",
"text": "Detailed error message"
}
]
}
```
Common errors:
* **401 Unauthorized**: Invalid or missing credentials
* **400 Bad Request**: Invalid parameters (e.g., malformed timestamp)
* **500 Internal Server Error**: Query API or database error
## Example Queries
```text Claude theme={null}
"Get search history for psub_c3d4e5f6789012345678901234abcdef from the last 7 days filtered by Shopping category"
```
```text Cursor theme={null}
"Show me the most recent YouTube videos watched by this user, grouped by category"
```
```text Claude Code theme={null}
"Retrieve browsing history with pagination, starting from cursor abc123, limit 500"
```
The AI agent will:
1. Parse your natural language query
2. Select the appropriate MCP tool
3. Apply filters and parameters
4. Return formatted results
## Troubleshooting
**Cause**: Invalid or missing credentials
**Solutions**:
* Verify `auth_token` is correct from The Control Room
* Check that user has granted consent (callback `status=success`)
* Ensure credentials are in the connection URL
* Try refreshing/rotating your API token
**Cause**: No data available for query
**Solutions**:
* Data export may still be processing (watch for `data.ready`/`data.failed` webhooks or poll `GET /export/status/{uid}` until provider `data_ready: true`)
* User may not have data for the requested type
* Check time filters (`begin`/`end`) aren't excluding all data
* Verify `category` filter isn't too restrictive
**Cause**: Cannot reach MCP server
**Solutions**:
* Verify MCP server URL is exactly `https://mcp.emergedata.ai/mcp`
* Check firewall/network settings allow HTTPS outbound
* Test health endpoint: `curl https://mcp.emergedata.ai/mcp/health`
* Contact support if server appears down
**Cause**: MCP connection not established
**Solutions**:
* Restart your AI tool after adding configuration
* Verify config file is in the correct location
* Check file permissions (must be readable)
* Review AI tool logs for MCP connection errors
## Rate Limits
The MCP server inherits rate limits from the Query API:
* **Requests**: 100 requests per minute per auth token
* **Data**: 10,000 events per request (recommended: 1000)
* **Concurrent**: 10 simultaneous connections per organization
Exceeding limits returns HTTP 429 errors. Contact support for higher limits.
## Source Code
The MCP server is open-source:
* **Repository**: [github.com/emerge-protocol/emgcp](https://github.com/emerge-protocol/emgcp)
* **Issues**: [Report bugs or request features](https://github.com/emerge-protocol/emgcp/issues)
* **License**: MIT
## Next Steps
Detailed documentation for all 5 tools
Learn about sync vs async queries
See AI workflow examples
Track consent and data export lifecycle changes
# MCP Query Tools Reference
Source: https://docs.emergedata.ai/ai/mcp-query-tools
Detailed reference for all Query API MCP tools
The Query API MCP server provides 5 tools for querying consented user data. Each tool maps 1:1 to a Query API sync endpoint.
Tools use **session credentials** by default (provided during connection). You can override per-tool by passing `auth_token` and `uid` parameters.
## Tool: get\_search\_data
Retrieve user search history (Google searches).
### Parameters
| Parameter | Type | Required | Description |
| ---------------- | ------ | -------- | ---------------------------------------------------------------------- |
| `auth_token` | string | No\* | Base64-encoded JWT (starts with `eyJ...`). Not the user ID. |
| `uid` | string | No\* | Consented user ID (typically starts with `psub_`). Not the auth token. |
| `begin` | string | No | Start time filter (ISO 8601) |
| `end` | string | No | End time filter (ISO 8601) |
| `ingested_begin` | string | No | Ingestion start (for delta queries) |
| `ingested_end` | string | No | Ingestion end (for delta queries) |
| `category` | string | No | Filter by category (e.g., "/Shopping") |
| `cursor` | string | No | Pagination cursor from previous response |
| `limit` | number | No | Max results per request (default 100, max 1000) |
*Either provide in tool call or use session credentials from connection*
### Response Format
```json theme={null}
{
"success": true,
"count": 2,
"has_more": true,
"next_cursor": "eyJsYXN0X2V2ZW50X2lkIjoxMjM0NX0=",
"applied_ingested_end": "2024-01-15T10:30:00Z",
"data": [
{
"event_id": 12345,
"user_id": "psub_e5f6789012345678901234abcdef0123",
"query": "best restaurants nearby",
"title": "best restaurants nearby - Google Search",
"url": "https://www.google.com/search?q=best+restaurants+nearby",
"timestamp": "2024-01-15T10:30:00Z",
"category": "/Food/Restaurants",
"intent": "find",
"brands": ["Google"],
"ingested_at": "2024-01-15T11:00:00Z"
},
{
"event_id": 12346,
"user_id": "psub_e5f6789012345678901234abcdef0123",
"query": "laptop deals",
"title": "laptop deals - Google Search",
"url": "https://www.google.com/search?q=laptop+deals",
"timestamp": "2024-01-15T14:20:00Z",
"category": "/Shopping/Electronics",
"intent": "buy",
"brands": ["Google"],
"ingested_at": "2024-01-15T14:25:00Z"
}
]
}
```
### Example Usage
```text Claude theme={null}
"Get search history from January 1-15, 2024, filtered by Shopping category"
```
```text Cursor theme={null}
Agent uses: get_search_data({
"begin": "2024-01-01T00:00:00Z",
"end": "2024-01-15T23:59:59Z",
"category": "/Shopping",
"limit": 100
})
```
***
## Tool: get\_youtube\_data
Retrieve user YouTube watch history and interactions.
### Parameters
| Parameter | Type | Required | Description |
| ---------------- | ------ | -------- | ---------------------------------------------------------------------- |
| `auth_token` | string | No\* | Base64-encoded JWT (starts with `eyJ...`). Not the user ID. |
| `uid` | string | No\* | Consented user ID (typically starts with `psub_`). Not the auth token. |
| `begin` | string | No | Start time filter (ISO 8601) |
| `end` | string | No | End time filter (ISO 8601) |
| `ingested_begin` | string | No | Ingestion start (for delta queries) |
| `ingested_end` | string | No | Ingestion end (for delta queries) |
| `category` | string | No | Filter by category (e.g., "/Music") |
| `cursor` | string | No | Pagination cursor |
| `limit` | number | No | Max results per request |
*Either provide in tool call or use session credentials from connection*
### Response Format
```json theme={null}
{
"success": true,
"count": 1,
"has_more": false,
"next_cursor": null,
"applied_ingested_end": "2024-01-15T10:30:00Z",
"data": [
{
"event_id": 67890,
"user_id": "psub_e5f6789012345678901234abcdef0123",
"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"title": "Example Video Title",
"timestamp": "2024-01-15T10:30:00Z",
"category": "/Entertainment/Music",
"brands": ["YouTube"],
"ingested_at": "2024-01-15T11:00:00Z"
}
]
}
```
### Example Usage
```text Claude theme={null}
"Show me YouTube videos watched in the last 3 days"
```
```text Cursor theme={null}
Agent uses: get_youtube_data({
"begin": "2024-01-12T00:00:00Z",
"limit": 50
})
```
***
## Tool: get\_browsing\_data
Retrieve user web browsing history (Chrome).
### Parameters
| Parameter | Type | Required | Description |
| ---------------- | ------ | -------- | ---------------------------------------------------------------------- |
| `auth_token` | string | No\* | Base64-encoded JWT (starts with `eyJ...`). Not the user ID. |
| `uid` | string | No\* | Consented user ID (typically starts with `psub_`). Not the auth token. |
| `begin` | string | No | Start time filter (ISO 8601) |
| `end` | string | No | End time filter (ISO 8601) |
| `ingested_begin` | string | No | Ingestion start (for delta queries) |
| `ingested_end` | string | No | Ingestion end (for delta queries) |
| `category` | string | No | Filter by category (e.g., "/Shopping") |
| `cursor` | string | No | Pagination cursor |
| `limit` | number | No | Max results per request |
*Either provide in tool call or use session credentials from connection*
### Response Format
```json theme={null}
{
"success": true,
"count": 1,
"has_more": true,
"next_cursor": "eyJsYXN0X2lkIjogNjc4OX0=",
"applied_ingested_end": "2024-01-15T10:30:00Z",
"data": [
{
"event_id": 45678,
"user_id": "psub_e5f6789012345678901234abcdef0123",
"url": "https://example.com/product",
"title": "Product Page - Example Store",
"timestamp": "2024-01-15T10:30:00Z",
"category": "/Shopping",
"page_category": "/Shopping/Electronics",
"brands": ["Example Store"],
"ingested_at": "2024-01-15T11:00:00Z"
}
]
}
```
### Example Usage
```text Claude theme={null}
"Find browsing history related to cooking recipes from last month"
```
```text Cursor theme={null}
Agent uses: get_browsing_data({
"begin": "2023-12-15T00:00:00Z",
"end": "2024-01-15T23:59:59Z",
"category": "/Food/Recipes"
})
```
***
## Tool: get\_ads\_data
Retrieve user ad interactions (clicks and views).
### Parameters
| Parameter | Type | Required | Description |
| ---------------- | ------ | -------- | ---------------------------------------------------------------------- |
| `auth_token` | string | No\* | Base64-encoded JWT (starts with `eyJ...`). Not the user ID. |
| `uid` | string | No\* | Consented user ID (typically starts with `psub_`). Not the auth token. |
| `begin` | string | No | Start time filter (ISO 8601) |
| `end` | string | No | End time filter (ISO 8601) |
| `ingested_begin` | string | No | Ingestion start (for delta queries) |
| `ingested_end` | string | No | Ingestion end (for delta queries) |
| `category` | string | No | Filter by category |
| `cursor` | string | No | Pagination cursor |
| `limit` | number | No | Max results per request |
*Either provide in tool call or use session credentials from connection*
### Response Format
```json theme={null}
{
"success": true,
"count": 1,
"has_more": false,
"next_cursor": null,
"applied_ingested_end": "2024-01-15T10:30:00Z",
"data": [
{
"event_id": 23456,
"user_id": "psub_e5f6789012345678901234abcdef0123",
"url": "https://ads.example.com/click?id=abc123",
"title": "Shop Electronics - Example Brand",
"source_domain": "news.example.com",
"landing_domain": "shop.examplebrand.com",
"ad_network": "Google Ads",
"timestamp": "2024-01-15T10:30:00Z",
"category": "/Shopping/Electronics",
"brands": ["Example Brand"],
"ingested_at": "2024-01-15T11:00:00Z"
}
]
}
```
### Example Usage
```text Claude theme={null}
"Show me ad interactions from the last week"
```
```text Cursor theme={null}
Agent uses: get_ads_data({
"begin": "2024-01-08T00:00:00Z",
"limit": 100
})
```
***
## Tool: get\_receipts\_data
Retrieve user purchase receipts (email receipts).
### Parameters
| Parameter | Type | Required | Description |
| ---------------- | ------ | -------- | ---------------------------------------------------------------------- |
| `auth_token` | string | No\* | Base64-encoded JWT (starts with `eyJ...`). Not the user ID. |
| `uid` | string | No\* | Consented user ID (typically starts with `psub_`). Not the auth token. |
| `begin` | string | No | Start time filter (ISO 8601) |
| `end` | string | No | End time filter (ISO 8601) |
| `ingested_begin` | string | No | Ingestion start (for delta queries) |
| `ingested_end` | string | No | Ingestion end (for delta queries) |
| `category` | string | No | Filter by category |
| `cursor` | string | No | Pagination cursor |
| `limit` | number | No | Max results per request |
*Either provide in tool call or use session credentials from connection*
### Response Format
```json theme={null}
{
"success": true,
"count": 1,
"has_more": false,
"next_cursor": null,
"applied_ingested_end": "2024-01-15T10:30:00Z",
"data": [
{
"event_id": 98765,
"user_id": "psub_e5f6789012345678901234abcdef0123",
"retailer_name": "Example Store",
"total_value": 49.99,
"receipt_currency": "USD",
"subject": "Purchase Receipt - Example Store",
"timestamp": "2024-01-15T10:30:00Z",
"category": "/Shopping/Retail",
"brands": ["Example Store"],
"items": [],
"ingested_at": "2024-01-15T11:00:00Z"
}
]
}
```
### Example Usage
```text Claude theme={null}
"Find all purchases over $100 from the last month"
```
```text Cursor theme={null}
Agent uses: get_receipts_data({
"begin": "2023-12-15T00:00:00Z",
"end": "2024-01-15T23:59:59Z",
"limit": 1000
})
// Then filters results where amount > 100
```
***
## Common Patterns
### Pagination
All tools support cursor-based pagination for large datasets:
1. Make initial request (no `cursor` parameter)
2. Check response `has_more` field
3. If `true`, use `next_cursor` in next request
4. Repeat until `has_more = false`
```typescript TypeScript theme={null}
let allData = [];
let cursor = null;
do {
const result = await mcpTool.call('get_search_data', {
begin: '2024-01-01T00:00:00Z',
limit: 1000,
cursor: cursor
});
allData.push(...result.data);
cursor = result.next_cursor;
} while (result.has_more);
```
```python Python theme={null}
all_data = []
cursor = None
while True:
result = mcp_tool.call('get_search_data', {
'begin': '2024-01-01T00:00:00Z',
'limit': 1000,
'cursor': cursor
})
all_data.extend(result['data'])
if not result['has_more']:
break
cursor = result['next_cursor']
```
### Delta Queries
Use `ingested_begin`/`ingested_end` to fetch only new data since last sync:
1. Store `last_sync_time` after each sync
2. Next sync: set `ingested_begin = last_sync_time`
3. Update `last_sync_time` to response `applied_ingested_end`
4. Repeat on subsequent syncs
This avoids re-fetching unchanged data.
### Category Filtering
Categories use slash-delimited hierarchical paths:
* `/Shopping` - All shopping data
* `/Shopping/Electronics` - Electronics only
* `/Food/Restaurants` - Restaurant searches/visits
Categories are assigned by Emerge's classification system. Not all events have categories.
### Error Handling
When a tool call fails, it returns an error structure:
```json theme={null}
{
"isError": true,
"content": [
{
"type": "text",
"text": "Error: 401 Unauthorized - Invalid API token. Verify your auth_token is correct."
}
]
}
```
Common error codes:
* **401**: Invalid credentials
* **400**: Invalid parameters (e.g., malformed timestamp)
* **404**: User not found (no consent)
* **429**: Rate limit exceeded
* **500**: Server error (retry with exponential backoff)
## Best Practices
Use `limit: 1000` for balanced performance and memory
Always check `has_more` for complete dataset retrieval
Use `ingested_begin`/`end` for incremental syncs
Apply category filters to reduce data volume
Handle errors gracefully with retry logic
## Rate Limits
Per API token limits:
* **100 requests/minute**
* **1000 requests/hour**
Exceeding limits returns HTTP 429. Wait before retrying or contact support for higher limits.
## Next Steps
Configure AI tools to use these tools
HTTP API equivalents
See workflow examples
Architecture and configuration
# Ship with MCP
Source: https://docs.emergedata.ai/ai/overview
Connect AI tools to Emerge documentation and user data via MCP
Emerge provides two MCP (Model Context Protocol) servers for different purposes. Connect your AI tools to search documentation, query user data, or both.
## Two MCP Servers
**Search and query this documentation**
* Semantic documentation search
* API reference lookup
* Code example retrieval
* Best for: Learning the API, troubleshooting
**Query consented user data via AI tools**
* Search history, browsing, YouTube, ad interactions, receipts
* Session-based credentials
* Direct data access for AI agents
* Best for: Building AI applications with user data
| Server | Purpose | URL | Auth Required |
| ------------- | -------------------- | -------------------------------- | --------------------- |
| **Docs MCP** | Search documentation | `https://docs.emergedata.ai/mcp` | No |
| **Query MCP** | Query user data | `https://mcp.emergedata.ai/mcp` | Yes (API token + uid) |
Both use the same Model Context Protocol and work with Claude, Cursor, VS Code, and Claude Code.
## Quick setup
Add documentation search to your AI tool:
```bash theme={null}
# Claude Code
claude mcp add --transport http emerge https://docs.emergedata.ai/mcp
```
```json theme={null}
// Cursor (.cursor/mcp.json)
{
"mcpServers": {
"Emerge": {
"type": "http",
"url": "https://docs.emergedata.ai/mcp"
}
}
}
```
See [Docs MCP Setup](/ai/mcp-docs-setup) for all tools.
Add user data querying to your AI tool:
```bash theme={null}
# Claude Code
claude mcp add emerge-query "https://mcp.emergedata.ai/mcp?auth_token=YOUR_TOKEN&uid=YOUR_UID"
```
```json theme={null}
// Cursor (.cursor/mcp.json)
{
"mcpServers": {
"Emerge Query": {
"url": "https://mcp.emergedata.ai/mcp?auth_token=YOUR_TOKEN&uid=YOUR_UID"
}
}
}
```
See [MCP Query Setup](/ai/mcp-query-setup) for all tools.
## What you can do
"How do I query user search history?" — AI searches docs and returns the answer with code examples
"Generate Python code to create a signed link" — AI finds SDK page and provides working implementation
"Get search history for the last week" — AI calls the Query MCP tool and returns results
"Why is my webhook signature invalid?" — AI finds troubleshooting info and suggests fixes
## How it works
```mermaid theme={null}
sequenceDiagram
participant You
participant AI Tool
participant MCP Server
participant Emerge
You->>AI Tool: "How do I handle callbacks?"
AI Tool->>MCP Server: Search docs
MCP Server->>Emerge: Query content
Emerge->>MCP Server: Return relevant pages
MCP Server->>AI Tool: Structured context
AI Tool->>You: Answer with code examples
```
## Benefits over web search
| Web Search | MCP Connection |
| ----------------------------- | ------------------------------- |
| May find outdated content | Always current documentation |
| Results from multiple sources | Single source of truth |
| Generic code examples | Emerge-specific implementations |
| Manual copy/paste | Structured data for AI |
## One-shot prompt for app builders
Use this prompt in tools like Lovable, Cursor, or Claude Code after connecting MCP:
```text theme={null}
You are building a full-stack app that integrates Emerge Link + Query.
Requirements:
- Use https://link.emergedata.ai/link/start to start consent.
- Generate HMAC-SHA256 signature over sorted raw params (exclude signature).
- Use signing_secret for HMAC; never expose secrets in the frontend.
- timestamp must be ISO 8601 (new Date().toISOString()).
- Generate random state, store it server-side, verify on callback.
- redirect_uri must be pre-approved in the Control Room.
- Never ask end-users for uid. If you send uid, use your internal user id. Otherwise store the callback uid.
- Query sync endpoints with uid: https://query.emergedata.ai/v1/sync/get_*
- Poll `GET /export/status/{uid}` and query only when the provider in `sources[]` is `data_ready: true`.
Return TypeScript and Python examples with async/await and error handling.
```
## Contextual menu
Every page in these docs includes a contextual menu with one-click AI integrations. Look for the menu icon on any page to:
* Copy as Markdown for pasting into AI chats
* Open directly in Claude or ChatGPT
* Copy the MCP server URL
Learn more in [Contextual Menu](/ai/contextual-menu).
# Job
Source: https://docs.emergedata.ai/api-reference/jobs/job
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/job/{task_id}
# Jobs
Source: https://docs.emergedata.ai/api-reference/jobs/jobs
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/jobs
# Create Flow Config
Source: https://docs.emergedata.ai/api-reference/link/create-flow-config
/openapi/link.json post /configs
Create or update a flow configuration for the authenticated client.
This endpoint allows partners to programmatically create flow configurations
with custom branding. The logo is fetched from the provided URL, optimized
for display (resized to max 400x400 pixels), and stored in S3.
If config_name already exists, updates the existing configuration.
Args:
body: Flow configuration details including company name, logo URL, etc.
client_id: Authenticated client ID from JWT token
Returns:
Created or updated flow configuration with S3 logo URL and preview link
Raises:
400: Invalid request (bad config name, unreachable logo, unsupported image type)
500: S3 upload failure
# Get Consent Status
Source: https://docs.emergedata.ai/api-reference/link/get-consent-status
/openapi/link.json get /consent/status/{uid}
Get consent status per provider for a partner user (`uid`).
The response is reconstructed from partner mappings and consent webhook history.
# Get Export Status
Source: https://docs.emergedata.ai/api-reference/link/get-export-status
/openapi/link.json get /export/status/{uid}
Check export readiness per provider for a partner user (`uid`).
Use `sources[]` and wait for the provider you need to report `data_ready: true`.
# List Flow Configs
Source: https://docs.emergedata.ai/api-reference/link/list-flow-configs
/openapi/link.json get /configs
List all flow configurations for the authenticated client.
Returns all configs with their details including S3 logo URLs and preview links.
# Ads
Source: https://docs.emergedata.ai/api-reference/query-async/ads
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/ads
# Browsing
Source: https://docs.emergedata.ai/api-reference/query-async/browsing
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/browsing
# Receipts
Source: https://docs.emergedata.ai/api-reference/query-async/receipts
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/receipts
# Search
Source: https://docs.emergedata.ai/api-reference/query-async/search
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/search
# YouTube
Source: https://docs.emergedata.ai/api-reference/query-async/youtube
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/youtube
# Get ad impressions (synchronous)
Source: https://docs.emergedata.ai/api-reference/query-sync/get-ad-impressions-synchronous
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/sync/get_ads
Returns ad impression data immediately using the api_ads mart view.
# Get available categories
Source: https://docs.emergedata.ai/api-reference/query-sync/get-available-categories
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/sync/categories
Return distinct category paths available for a given table.
# Get browsing history (synchronous)
Source: https://docs.emergedata.ai/api-reference/query-sync/get-browsing-history-synchronous
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/sync/get_browsing
Returns browsing history data immediately using the api_browsing mart view.
# Get receipts (synchronous)
Source: https://docs.emergedata.ai/api-reference/query-sync/get-receipts-synchronous
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/sync/get_receipts
Returns receipt data immediately using the api_receipts mart view.
# Get search history (synchronous)
Source: https://docs.emergedata.ai/api-reference/query-sync/get-search-history-synchronous
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/sync/get_search
Returns search history data immediately using the api_search mart view.
# Get YouTube activity (synchronous)
Source: https://docs.emergedata.ai/api-reference/query-sync/get-youtube-activity-synchronous
https://emerge-openapi-specs.s3.eu-central-1.amazonaws.com/query/1.21.0/openapi.json get /v1/sync/get_youtube
Returns YouTube activity data immediately using the api_youtube mart view.
# Changelog
Source: https://docs.emergedata.ai/changelog
API updates and documentation changes
## v0.0.11 (2026-02-12)
**Link API:**
* Updated webhook payload contract to v2 (`sources[]` + `client_id` in payload)
* Updated webhook headers (`X-Signature`, `X-Webhook-Version: 2.0`, `X-Attempt-Number`, `Idempotency-Key`)
* Added `data.ready` and `data.failed` webhook event types for export lifecycle updates
* Added `client_id` to `GET /consent/status/{uid}` response
* Updated `GET /export/status/{uid}` to return provider-level `sources[]`
* Provider names standardized to `google_data` and `gmail`
**Query API Docs:**
* Added `GET /v1/sync/categories`
* Added Event Categories guide (first-level taxonomy list)
* Added Data Schema guide (field-level payload reference)
* Added response examples across endpoint docs
***
## v0.0.10 (2026-01-28)
**Link API:**
* Removed `flow_version` parameter (deprecated)
* Use `flow_config` for custom branding configurations
**Query API:**
* Fixed `event_id` type from string to integer
***
## v0.0.5
**Query API:**
* Added Receipts data type with sync (`/v1/sync/get_receipts`) and async (`/v1/receipts`) endpoints
* Purchase receipts include retailer name, total value, itemized products, and brand data
***
## v0.0.1
Initial release.
### Features
* **Emerge Link** - Consent flow for collecting user data permissions
* **Query API** - Sync and async endpoints for retrieving user data
* **Webhook notifications** - Real-time updates for consent and export events
* **SDK support** - TypeScript and Python reference implementations
### Data Types
* Search history
* Browsing history
* YouTube watch history
* Ad interactions
### Ship with MCP (formerly AI Integration)
* MCP server for AI tool integration
* Contextual menu for one-click AI actions
# The Control Room Overview
Source: https://docs.emergedata.ai/control-room/overview
Manage credentials, flow configs, and webhooks in the Control Room
Use the Control Room at [dashboard.emergedata.ai](https://dashboard.emergedata.ai) to manage your Link + Query integration lifecycle.
## What you manage in the Control Room
* API credentials (`client_id`, `signing_secret`, API token)
* Flow branding (`flow_config`, logo, privacy policy)
* Webhook destinations and event subscriptions
* Team/admin access
## Authentication context
Actions in The Control Room map to API-authenticated operations:
* Link API base: `https://link.emergedata.ai`
* Query API base: `https://query.emergedata.ai`
* Auth header: `Authorization: Bearer `
## Response example: flow configs
`GET /configs` response:
```json theme={null}
[
{
"config_id": "cfg_30bfe2ca",
"config_name": "default",
"company_name": "Wonderful AI",
"logo_url": "https://assets.emergedata.ai/logo/wonderful-ai.png",
"privacy_policy_url": "https://wonderful.ai/privacy",
"webhook_url": "https://api.wonderful.ai/webhooks/emerge",
"flow_version": "emerge",
"is_default": true,
"preview_url": "https://link.emergedata.ai/preview/ck_live_123?flow_config=default"
}
]
```
## API parity examples
```typescript TypeScript theme={null}
async function listFlowConfigs(apiToken: string) {
const response = await fetch("https://link.emergedata.ai/configs", {
headers: {
Authorization: `Bearer ${apiToken}`
}
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Failed to list configs (${response.status}): ${body}`);
}
return response.json();
}
```
```python Python theme={null}
import requests
def list_flow_configs(api_token: str) -> list[dict]:
response = requests.get(
"https://link.emergedata.ai/configs",
headers={"Authorization": f"Bearer {api_token}"},
timeout=30
)
response.raise_for_status()
return response.json()
```
## Gotchas
* Treat The Control Room credentials as production secrets. Never embed them in frontend code.
* Rotate credentials after team changes.
* Keep redirect URIs and webhook URLs environment-specific to avoid data leaks.
## Related docs
* [Create Signed Links](/link/create-link)
* [Webhooks](/link/webhooks)
* [Ship with MCP](/ai/overview)
# Data Wallet Overview
Source: https://docs.emergedata.ai/data-wallet/overview
End-user dashboard for transparency and consent revocation
Data Wallet at [wallet.emergedata.ai](https://wallet.emergedata.ai) gives your users direct control over consent.
## What your users can do
* View active connections by provider (`google_data`, `gmail`)
* Review connected companies
* Revoke consent per provider
* Reconnect when needed
## Integration impact
When users revoke consent in Data Wallet, you receive a `consent.revoked` webhook with `sources[]` for affected providers.
### Webhook response example
```json theme={null}
{
"event": "consent.revoked",
"timestamp": "2026-02-12T09:10:11Z",
"uid": "psub_d4e5f6789012345678901234abcdef01",
"client_id": "ck_live_123456789",
"sources": [
{
"provider": "google_data",
"revoked_at": "2026-02-12T09:10:11Z",
"reason": "user_revoked"
}
]
}
```
## Handle revocations safely
```typescript TypeScript theme={null}
import crypto from "crypto";
import express from "express";
const app = express();
app.use(express.raw({ type: "application/json" }));
const webhookSecret = process.env.EMERGE_WEBHOOK_SECRET;
if (!webhookSecret) {
throw new Error("Missing EMERGE_WEBHOOK_SECRET");
}
app.post("/webhooks/emerge", async (req, res) => {
try {
const signature = req.header("x-signature");
if (!signature) {
return res.status(401).send("Missing signature");
}
const expected = crypto
.createHmac("sha256", webhookSecret)
.update(req.body)
.digest("hex");
const matches =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature, "hex"), Buffer.from(expected, "hex"));
if (!matches) {
return res.status(401).send("Invalid signature");
}
const payload = JSON.parse(req.body.toString("utf8")) as {
event: string;
uid: string;
sources?: Array<{ provider: string; reason?: string }>;
};
if (payload.event === "consent.revoked") {
await revokeUserAccess(payload.uid, payload.sources ?? []);
}
return res.status(200).send("OK");
} catch (error) {
console.error("Webhook error", error);
return res.status(500).send("Server error");
}
});
async function revokeUserAccess(uid: string, sources: Array<{ provider: string }>) {
for (const source of sources) {
await deleteProviderData(uid, source.provider);
}
}
async function deleteProviderData(uid: string, provider: string) {
console.log(`Deleting ${provider} data for ${uid}`);
}
```
```python Python theme={null}
import hashlib
import hmac
import json
import os
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
webhook_secret = os.getenv("EMERGE_WEBHOOK_SECRET")
if not webhook_secret:
raise RuntimeError("Missing EMERGE_WEBHOOK_SECRET")
@app.post("/webhooks/emerge")
async def handle_webhook(request: Request):
body = await request.body()
signature = request.headers.get("x-signature")
if not signature:
raise HTTPException(status_code=401, detail="Missing signature")
expected = hmac.new(
webhook_secret.encode(),
body,
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, expected):
raise HTTPException(status_code=401, detail="Invalid signature")
payload = json.loads(body)
if payload.get("event") == "consent.revoked":
uid = payload.get("uid")
sources = payload.get("sources", [])
await revoke_user_access(uid, sources)
return {"status": "ok"}
async def revoke_user_access(uid: str, sources: list[dict]):
for source in sources:
provider = source.get("provider", "unknown")
await delete_provider_data(uid, provider)
async def delete_provider_data(uid: str, provider: str):
print(f"Deleting {provider} data for {uid}")
```
## Gotchas
* Revoke processing must be idempotent because webhooks can retry.
* Handle per-provider revocation in `sources[]`; do not assume full-account revocation.
* Keep deletion logs for compliance/audit trails.
## Related docs
* [Webhooks](/link/webhooks)
* [Callbacks](/link/callbacks)
* [Authentication & Status Endpoints](/link/authentication)
# Emerge API
Source: https://docs.emergedata.ai/index
Privacy-first access to consented user data for personalization and insights
Access user data with explicit consent. Emerge handles the complexity of consent collection, data portability compliance, and secure data transfer so you can focus on building great experiences.
Get your first integration running lightning-fast
Collect user consent with a hosted flow
Retrieve consented user data
Connect AI tools directly to these docs
Manage credentials, branding, and webhooks
Understand end-user revocation and transparency controls
## How it works
Embed Emerge Link in your app. Users authenticate with their data provider and grant consent in a compliant flow.
Emerge securely exports the user's data from their provider account. Use `GET /export/status/{uid}` and wait until your provider in `sources[]` has `data_ready: true`.
Use the Query API to retrieve search history, browsing data, YouTube history, ad interactions, and receipts.
## Available data types
| Data Type | Description | Use Cases |
| ---------------- | --------------------------------------- | ------------------------------------ |
| Search History | Google search queries with timestamps | Intent analysis, personalization |
| Browsing History | Page visits with titles and timestamps | Interest profiling, recommendations |
| YouTube History | Watched videos with channels | Content preferences, media planning |
| Ad Interactions | Ad clicks and views | Attribution, audience insights |
| Receipts | Purchase receipts with items and brands | Shopping behavior, brand preferences |
## AI-Native documentation
These docs are designed for AI-first workflows. Connect your AI tools directly to search and query this documentation.
Add as a connector
Configure MCP server
Add to MCP config
## Get started
Sign up for the Control Room to get your API credentials
# Authentication
Source: https://docs.emergedata.ai/link/authentication
API credentials and HMAC signing for Emerge Link
Emerge uses two authentication mechanisms:
1. **API Token** - Bearer token for API calls
2. **HMAC Signature** - Signed URLs for the consent flow
## API Token
Use your API token for server-to-server API calls. Include it in the `Authorization` header:
```bash theme={null}
curl -X GET 'https://link.emergedata.ai/consent/status/psub_c3d4e5f6789012345678901234abcdef' \
-H 'Authorization: Bearer your_api_token'
```
Never expose your API token in client-side code. All API calls should be made from your backend.
## HMAC Signing
Consent flow URLs are signed with HMAC-SHA256 to prevent tampering. The signature validates that:
* The URL parameters haven't been modified
* The request originated from your application
* The link hasn't expired (30-day validity)
### Signature algorithm
1. Collect all URL parameters (except `signature`)
2. Sort parameters alphabetically by key
3. Join as `key=value&key=value` (raw values, not URL-encoded)
4. Generate HMAC-SHA256 using your signing secret
5. Append signature as hex string
### Parameters to sign
| Parameter | Required | Description |
| -------------- | -------- | ----------------------------------------------------- |
| `client_id` | Yes | Your client identifier |
| `redirect_uri` | Yes | Callback URL |
| `state` | Yes | CSRF protection token |
| `timestamp` | Yes | ISO 8601 timestamp (e.g., `2024-01-15T10:30:00.000Z`) |
| `uid` | No | Your user identifier |
| `flow_config` | No | Named configuration for custom branding |
### Example signature generation
```typescript TypeScript theme={null}
import crypto from 'crypto';
function signParams(params: Record, signingSecret: string): string {
// Sort parameters alphabetically
const sortedKeys = Object.keys(params).sort();
// Join as raw key=value pairs (NOT URL-encoded)
const signatureBase = sortedKeys
.map(key => `${key}=${params[key]}`)
.join('&');
// Generate HMAC-SHA256
return crypto
.createHmac('sha256', signingSecret)
.update(signatureBase)
.digest('hex');
}
// Usage
const params = {
client_id: 'your_client_id',
redirect_uri: 'https://yourapp.com/callback',
state: 'random_state_value',
timestamp: new Date().toISOString(),
uid: 'psub_c3d4e5f6789012345678901234abcdef'
};
const signature = signParams(params, 'your_signing_secret');
```
```python Python theme={null}
import hmac
import hashlib
from datetime import datetime, timezone
def sign_params(params: dict, signing_secret: str) -> str:
# Sort parameters alphabetically
sorted_items = sorted(params.items())
# Join as raw key=value pairs (NOT URL-encoded)
signature_base = '&'.join(f'{k}={v}' for k, v in sorted_items)
# Generate HMAC-SHA256
return hmac.new(
signing_secret.encode(),
signature_base.encode(),
hashlib.sha256
).hexdigest()
# Usage
params = {
'client_id': 'your_client_id',
'redirect_uri': 'https://yourapp.com/callback',
'state': 'random_state_value',
'timestamp': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
'uid': 'psub_c3d4e5f6789012345678901234abcdef'
}
signature = sign_params(params, 'your_signing_secret')
```
The signature base uses **raw parameter values**, not URL-encoded values. URL encoding is only applied when constructing the final URL.
## Credential management
### Obtaining credentials
1. Sign in to [The Control Room](https://dashboard.emergedata.ai)
2. Navigate to **Settings** → **API Keys**
3. Generate or view your credentials
You'll receive:
* **Client ID** - Public identifier for your application
* **Signing Secret** - Private key for HMAC signatures (keep secure)
* **API Token** - Bearer token for API calls
### Rotating credentials
To rotate your credentials:
1. Go to **Settings** → **API Keys** in the Control Room
2. Click **Regenerate Keys**
3. A one-time retrieval link is emailed to the admin
4. The link expires after 60 minutes
After regeneration, existing signed links remain valid for their 30-day period. Only new links need the new secret.
## Security best practices
Use environment variables or a secrets manager (AWS Secrets Manager, HashiCorp Vault). Never commit secrets to version control.
Always verify the `state` parameter in callbacks matches what you sent. This prevents CSRF attacks.
Only HTTPS redirect URIs are allowed in production. This ensures the callback is encrypted.
API tokens don't expire, but rotate them periodically as a security practice.
# Callbacks
Source: https://docs.emergedata.ai/link/callbacks
Handle redirect callbacks from the consent flow
After a user completes (or exits) the consent flow, they're redirected to your `redirect_uri` with query parameters indicating the result.
## Callback parameters
| Parameter | Always Present | Description |
| ------------ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `status` | Yes | `success`, `reauthorized`, or `failure` |
| `state` | Yes | The state value you provided in the link |
| `uid` | Yes | The user identifier returned by Emerge. If you provided `uid`, you get the same value; if you omitted it, Emerge generates a pairwise `uid`. |
| `error_code` | Only on failure | Error code explaining the failure |
Do not ask end-users for `uid` or collect it in the frontend. Store the callback `uid` server-side and map it to your internal user record. This avoids wrong-user data access and keeps identifiers private.
## Status values
### `success`
First-time consent granted. This user has connected their data for the first time with your application.
```
https://yourapp.com/callback?status=success&state=abc123&uid=psub_d4e5f6789012345678901234abcdef01
```
### `reauthorized`
User re-linked an existing consent. This happens when:
* User clicks the link again after previously consenting
* User re-authenticates after token expiration
```
https://yourapp.com/callback?status=reauthorized&state=abc123&uid=psub_d4e5f6789012345678901234abcdef01
```
### `failure`
User cancelled or an error occurred during the flow.
```
https://yourapp.com/callback?status=failure&state=abc123&uid=psub_d4e5f6789012345678901234abcdef01&error_code=user_failed
```
## Error codes
| Error Code | Description | Suggested Action |
| ----------------------- | ------------------------------------------- | ---------------------------------- |
| `user_failed` | User cancelled or denied consent | Show retry option |
| `data_invalid` | Insufficient data in user's account | Explain data requirements |
| `access_denied` | User denied OAuth permissions | Explain why permissions are needed |
| `invalid_scope` | Required scopes not available | Contact support |
| `admin_policy_enforced` | Organization policy blocks access | User needs admin approval |
| `uid_conflict` | Different user already linked with this uid | Use a unique uid per user |
## Handling callbacks
```typescript TypeScript theme={null}
import express from 'express';
const app = express();
app.get('/emerge/callback', async (req, res) => {
const { status, state, uid, error_code } = req.query;
// 1. Verify state matches (CSRF protection)
const expectedState = req.session.emergeState;
if (state !== expectedState) {
console.error('State mismatch - possible CSRF attack');
return res.status(400).redirect('/error?reason=invalid_state');
}
// Clear stored state
delete req.session.emergeState;
// 2. Handle based on status
switch (status) {
case 'success':
// First-time consent - data export will start automatically
await saveUserConsent(uid as string, {
consentedAt: new Date()
});
// Redirect to success page
return res.redirect('/dashboard?connected=true');
case 'reauthorized':
// Existing consent refreshed
await updateUserConsent(uid as string, {
reauthorizedAt: new Date()
});
return res.redirect('/dashboard?reconnected=true');
case 'failure':
// Handle specific error codes
const errorMessage = getErrorMessage(error_code as string);
return res.redirect(`/connect?error=${encodeURIComponent(errorMessage)}`);
default:
return res.status(400).redirect('/error');
}
});
function getErrorMessage(errorCode: string): string {
const messages: Record = {
'user_failed': 'You cancelled the connection. Click below to try again.',
'data_invalid': 'Your account doesn\'t have enough data history yet.',
'access_denied': 'Permission was denied. We need access to provide this feature.',
'admin_policy_enforced': 'Your organization\'s policy prevents this connection.'
};
return messages[errorCode] || 'Something went wrong. Please try again.';
}
```
```python Python theme={null}
from datetime import datetime, timezone
from urllib.parse import quote
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get('/emerge/callback')
async def emerge_callback(
request: Request,
status: str,
state: str,
uid: str,
error_code: str | None = None
):
# 1. Verify state matches (CSRF protection)
expected_state = request.session.get('emerge_state')
if state != expected_state:
raise HTTPException(status_code=400, detail='Invalid state')
# Clear stored state
del request.session['emerge_state']
# 2. Handle based on status
if status == 'success':
# First-time consent - data export will start automatically
await save_user_consent(uid, {
'consented_at': datetime.now(timezone.utc)
})
return RedirectResponse('/dashboard?connected=true')
elif status == 'reauthorized':
# Existing consent refreshed
await update_user_consent(uid, {
'reauthorized_at': datetime.now(timezone.utc)
})
return RedirectResponse('/dashboard?reconnected=true')
elif status == 'failure':
error_message = get_error_message(error_code)
return RedirectResponse(f'/connect?error={quote(error_message)}')
else:
return RedirectResponse('/error')
def get_error_message(error_code: str | None) -> str:
messages = {
'user_failed': 'You cancelled the connection.',
'data_invalid': 'Your account doesn\'t have enough data history.',
'access_denied': 'Permission was denied.',
'admin_policy_enforced': 'Your organization\'s policy prevents this.'
}
return messages.get(error_code, 'Something went wrong.')
```
## State verification
Always verify the `state` parameter matches what you stored before the redirect. This prevents CSRF attacks where an attacker tricks a user into linking their account to the attacker's data.
### Recommended state storage
| Storage | Pros | Cons |
| ------------- | ------------------------- | --------------------------- |
| Session | Simple, automatic cleanup | Requires session middleware |
| Redis | Distributed, TTL support | Additional infrastructure |
| Database | Persistent, auditable | More complex queries |
| Signed cookie | Stateless | Size limitations |
## What happens after success
When you receive `success` or `reauthorized`:
1. **Data export starts automatically** - Emerge begins exporting the user's data from their provider
2. **Export takes 1-15 minutes** - Depending on data volume
3. **Webhook updates (optional)** - You may receive consent events plus `data.ready`/`data.failed` for provider-level export updates
4. **Poll export readiness (recommended fallback)** - Check `GET /export/status/{uid}` and query only when the provider in `sources[]` has `data_ready: true`
Use provider-level readiness from `sources[]` instead of assuming all providers are ready at once.
## Completed session handling
If a user clicks a consent link after they've already completed consent:
* They see a brief "already connected" message
* They're redirected to the [Data Wallet](/link/data-wallet) (not back to your `redirect_uri`)
* No new callback is triggered
This prevents confusion from re-processing completed flows.
# Create Signed Links
Source: https://docs.emergedata.ai/link/create-link
Generate HMAC-signed URLs for the consent flow
Generate signed URLs server-side to initiate the consent flow. Each link is unique to a user and includes an HMAC signature for security.
## URL structure
```
https://link.emergedata.ai/link/start?client_id=...&redirect_uri=...&state=...×tamp=...&signature=...
```
## Required parameters
| Parameter | Type | Description |
| -------------- | ------ | --------------------------------------------------------------- |
| `client_id` | string | Your client identifier from the Control Room |
| `redirect_uri` | string | URL to redirect after consent |
| `state` | string | Random string for CSRF protection (you verify this in callback) |
| `timestamp` | string | ISO 8601 timestamp (e.g., `2024-01-15T10:30:00.000Z`) |
| `signature` | string | HMAC-SHA256 signature of sorted parameters |
## Optional parameters
| Parameter | Type | Default | Description |
| ------------- | ------ | ------- | ------------------------------------------------------------------------------------------------------------------- |
| `uid` | string | - | Your internal user id (server-side only). If omitted, Emerge generates a pairwise `uid` and returns it on callback. |
| `flow_config` | string | - | Named configuration for custom branding |
## Complete implementation
Do not ask end-users for `uid` or collect it in the frontend. Use your internal user id server-side or omit `uid` and store the generated callback `uid`. This prevents wrong-user data access and keeps identifiers private.
```typescript TypeScript theme={null}
import crypto from 'crypto';
interface LinkParams {
clientId: string;
signingSecret: string;
redirectUri: string;
userId?: string;
}
function createLinkUrl(params: LinkParams): string {
const timestamp = new Date().toISOString();
const state = crypto.randomBytes(16).toString('hex');
// Build parameters object
const urlParams: Record = {
client_id: params.clientId,
redirect_uri: params.redirectUri,
state: state,
timestamp: timestamp
};
if (params.userId) {
urlParams.uid = params.userId;
}
// Sort and create signature base (raw values, not URL-encoded)
const sortedKeys = Object.keys(urlParams).sort();
const signatureBase = sortedKeys
.map(key => `${key}=${urlParams[key]}`)
.join('&');
// Generate signature
const signature = crypto
.createHmac('sha256', params.signingSecret)
.update(signatureBase)
.digest('hex');
// Build final URL (URLSearchParams handles encoding)
const finalParams = new URLSearchParams(urlParams);
finalParams.append('signature', signature);
return `https://link.emergedata.ai/link/start?${finalParams.toString()}`;
}
// Store state for verification in callback
const stateStore = new Map();
function createLinkWithStateTracking(params: LinkParams): {
url: string;
state: string;
} {
const timestamp = new Date().toISOString();
const state = crypto.randomBytes(16).toString('hex');
// Store state for later verification
stateStore.set(state, {
userId: params.userId || '',
createdAt: Date.now()
});
const urlParams: Record = {
client_id: params.clientId,
redirect_uri: params.redirectUri,
state: state,
timestamp: timestamp
};
if (params.userId) {
urlParams.uid = params.userId;
}
const sortedKeys = Object.keys(urlParams).sort();
const signatureBase = sortedKeys
.map(key => `${key}=${urlParams[key]}`)
.join('&');
const signature = crypto
.createHmac('sha256', params.signingSecret)
.update(signatureBase)
.digest('hex');
const finalParams = new URLSearchParams(urlParams);
finalParams.append('signature', signature);
return {
url: `https://link.emergedata.ai/link/start?${finalParams.toString()}`,
state: state
};
}
```
```python Python theme={null}
import hmac
import hashlib
import time
import secrets
from datetime import datetime, timezone
from urllib.parse import urlencode
from dataclasses import dataclass
from typing import Optional
@dataclass
class LinkParams:
client_id: str
signing_secret: str
redirect_uri: str
user_id: Optional[str] = None
def create_link_url(params: LinkParams) -> str:
timestamp = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
state = secrets.token_hex(16)
# Build parameters dict
url_params = {
'client_id': params.client_id,
'redirect_uri': params.redirect_uri,
'state': state,
'timestamp': timestamp
}
if params.user_id:
url_params['uid'] = params.user_id
# Sort and create signature base (raw values, not URL-encoded)
sorted_items = sorted(url_params.items())
signature_base = '&'.join(f'{k}={v}' for k, v in sorted_items)
# Generate signature
signature = hmac.new(
params.signing_secret.encode(),
signature_base.encode(),
hashlib.sha256
).hexdigest()
# Build final URL
url_params['signature'] = signature
return f'https://link.emergedata.ai/link/start?{urlencode(url_params)}'
# With state tracking for verification
state_store: dict[str, dict] = {}
def create_link_with_state_tracking(params: LinkParams) -> tuple[str, str]:
timestamp = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
state = secrets.token_hex(16)
# Store state for later verification
state_store[state] = {
'user_id': params.user_id or '',
'created_at': time.time()
}
url_params = {
'client_id': params.client_id,
'redirect_uri': params.redirect_uri,
'state': state,
'timestamp': timestamp
}
if params.user_id:
url_params['uid'] = params.user_id
sorted_items = sorted(url_params.items())
signature_base = '&'.join(f'{k}={v}' for k, v in sorted_items)
signature = hmac.new(
params.signing_secret.encode(),
signature_base.encode(),
hashlib.sha256
).hexdigest()
url_params['signature'] = signature
url = f'https://link.emergedata.ai/link/start?{urlencode(url_params)}'
return url, state
```
## Usage examples
### Basic link generation
```typescript theme={null}
const url = createLinkUrl({
clientId: process.env.EMERGE_CLIENT_ID!,
signingSecret: process.env.EMERGE_SIGNING_SECRET!,
redirectUri: 'https://yourapp.com/emerge/callback',
userId: 'psub_d4e5f6789012345678901234abcdef01'
});
// Redirect user to this URL or display as a button
console.log(url);
```
### Express.js endpoint
```typescript theme={null}
import express from 'express';
const app = express();
app.get('/connect-data', (req, res) => {
const userId = req.session.userId;
const { url, state } = createLinkWithStateTracking({
clientId: process.env.EMERGE_CLIENT_ID!,
signingSecret: process.env.EMERGE_SIGNING_SECRET!,
redirectUri: 'https://yourapp.com/emerge/callback',
userId: userId
});
// Store state in session for verification
req.session.emergeState = state;
res.redirect(url);
});
```
### FastAPI endpoint
```python theme={null}
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
import os
app = FastAPI()
@app.get('/connect-data')
async def connect_data(request: Request):
user_id = request.session.get('user_id')
url, state = create_link_with_state_tracking(LinkParams(
client_id=os.environ['EMERGE_CLIENT_ID'],
signing_secret=os.environ['EMERGE_SIGNING_SECRET'],
redirect_uri='https://yourapp.com/emerge/callback',
user_id=user_id
))
# Store state in session for verification
request.session['emerge_state'] = state
return RedirectResponse(url)
```
## Link validity
* Links are valid for **30 days** from the timestamp
* The same link parameters generate the same session (idempotent)
* Expired links show an error page to users
Generate links on-demand rather than storing them. This ensures the timestamp is always fresh.
## Signature algorithm
The signature ensures the link hasn't been tampered with:
1. Collect all URL parameters (except `signature`)
2. Sort parameters alphabetically by key
3. Join as `key=value&key=value` (raw values, not URL-encoded)
4. Generate HMAC-SHA256 using your signing secret
5. Append signature as hex string
The signature base uses **raw parameter values**, not URL-encoded values. URL encoding is only applied when constructing the final URL.
# Data Wallet
Source: https://docs.emergedata.ai/link/data-wallet
End-user dashboard for tracking access and revoking consent
Data Wallet is the end-user dashboard at [https://wallet.emergedata.ai](https://wallet.emergedata.ai) where your users can see which companies have access to their data and revoke consent at any time. This keeps consent transparent and user-controlled.
## When it appears
* It is created after a user completes their first successful Link consent flow.
* Your user receives an email notifying them they can track their data access and revoke consent for a specific company.
## What users can do
* Review all connected companies and data types
* See which connections are active vs revoked
* Revoke consent with a single toggle
## Screenshots
## Handle revocations in your app
When a user revokes consent in Data Wallet, you receive a `consent.revoked` webhook. Use it to stop processing and delete any stored data for that user.
```typescript TypeScript theme={null}
import express from 'express';
import crypto from 'crypto';
const app = express();
app.use(express.raw({ type: 'application/json' }));
const WEBHOOK_SECRET = process.env.EMERGE_WEBHOOK_SECRET;
if (!WEBHOOK_SECRET) {
throw new Error('Missing EMERGE_WEBHOOK_SECRET');
}
app.post('/webhooks/emerge', async (req, res) => {
try {
const signature = req.headers['x-signature'] as string | undefined;
if (!signature) {
return res.status(401).send('Missing signature');
}
const expected = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
const signatureBuf = Buffer.from(signature, 'hex');
const expectedBuf = Buffer.from(expected, 'hex');
const valid =
signatureBuf.length === expectedBuf.length &&
crypto.timingSafeEqual(signatureBuf, expectedBuf);
if (!valid) {
console.error('Invalid webhook signature');
return res.status(401).send('Invalid signature');
}
const payload = JSON.parse(req.body.toString('utf8')) as {
event?: string;
uid?: string;
sources?: Array<{ provider?: string }>;
};
if (payload.event === 'consent.revoked' && payload.uid) {
await revokeLocalAccess(payload.uid, payload.sources ?? []);
}
return res.status(200).send('OK');
} catch (err) {
console.error('Webhook error', err);
return res.status(500).send('Server error');
}
});
async function revokeLocalAccess(uid: string, sources: Array<{ provider?: string }>) {
for (const source of sources) {
if (source.provider) {
await deleteUserData(uid, source.provider);
}
}
}
async function deleteUserData(uid: string, provider: string) {
console.log(`Deleting ${provider} data for ${uid}`);
}
app.listen(3000, () => {
console.log('Webhook listener running on http://localhost:3000');
});
```
```python Python theme={null}
from fastapi import FastAPI, Request, HTTPException
import hmac
import hashlib
import json
import os
from typing import Optional
app = FastAPI()
WEBHOOK_SECRET = os.getenv('EMERGE_WEBHOOK_SECRET')
if not WEBHOOK_SECRET:
raise RuntimeError('Missing EMERGE_WEBHOOK_SECRET')
@app.post('/webhooks/emerge')
async def emerge_webhook(request: Request):
try:
signature = request.headers.get('x-signature')
if not signature:
raise HTTPException(status_code=401, detail='Missing signature')
payload = await request.body()
expected = hmac.new(
WEBHOOK_SECRET.encode(),
payload,
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, expected):
raise HTTPException(status_code=401, detail='Invalid signature')
body = json.loads(payload)
event = body.get('event')
uid = body.get('uid')
sources = body.get('sources', [])
if event == 'consent.revoked':
await revoke_local_access(uid, sources)
return {'status': 'ok'}
except HTTPException:
raise
except Exception as exc:
raise HTTPException(status_code=500, detail='Server error') from exc
async def revoke_local_access(uid: Optional[str], sources: list[dict]):
if not uid:
return
for source in sources:
provider = source.get('provider')
if provider:
await delete_user_data(uid, provider)
async def delete_user_data(uid: str, provider: str):
print(f'Deleting {provider} data for {uid}')
```
## Related documentation
Understand redirect behavior after consent
Receive consent changes like revocations
## Edge cases
* If a user opens a completed Link flow again, they are redirected to the Data Wallet instead of your `redirect_uri`.
* If you keep cached data, delete it when you receive `consent.revoked` to stay privacy-first.
# Link Overview
Source: https://docs.emergedata.ai/link/overview
Collect user consent with Emerge Link
Emerge Link is a hosted consent flow that handles user authentication, consent collection, and data portability compliance. Users authenticate with their data provider (Google) and grant your application access to their data.
## How Link works
```mermaid theme={null}
sequenceDiagram
participant User
participant Your App
participant Emerge Link
participant Google
Your App->>User: Show "Connect Data" button
User->>Emerge Link: Click signed link
Emerge Link->>Google: OAuth redirect
Google->>User: Authenticate & consent
User->>Emerge Link: Grant permissions
Emerge Link->>Your App: Redirect with status
Emerge Link-->>Your App: Webhook: consent/data lifecycle event
```
## Flow states
When a user completes (or exits) the consent flow, they're redirected to your `redirect_uri` with a `status` parameter:
| Status | Description |
| -------------- | ---------------------------------------- |
| `success` | First-time consent granted for this user |
| `reauthorized` | User re-linked an existing consent |
| `failure` | User cancelled or an error occurred |
## Try the demo
Preview the latest single-checkbox demo flow:
Endpoint coming next. This demo is configured for a single consent checkbox.
## Integration steps
Sign up for [The Control Room](https://dashboard.emergedata.ai) and create your client credentials.
Set your company name, logo, and redirect URIs via the API or The Control Room.
Create HMAC-signed URLs server-side to initiate the consent flow.
Process the redirect callback and verify the state parameter.
Receive consent and data export lifecycle events (for example revocations and `data.ready` updates).
If you update branding in The Control Room and want to remove a logo, clear the logo field. That sets `logo_url` to `null` and removes the stored logo.
## What users see
The consent flow presents users with:
1. **Partner context** - Your company name and logo
2. **Data explanation** - What data will be shared and why
3. **Google OAuth** - Standard Google authentication
4. **Consent confirmation** - Explicit consent checkbox
The flow is designed for compliance with GDPR, CCPA, and Google's data portability requirements.
## Next steps
Learn about API credentials and HMAC signing
Generate signed consent URLs
# Webhooks
Source: https://docs.emergedata.ai/link/webhooks
Receive consent and data lifecycle events from Emerge Link
Use Link webhooks to track consent changes and data export status per provider.
## Authentication
Webhook deliveries are signed with HMAC-SHA256. Verify every request before processing.
Headers sent by Emerge:
| Header | Description |
| ------------------- | --------------------------------------- |
| `X-Signature` | HMAC-SHA256 signature (hex) |
| `X-Webhook-Version` | Payload/header contract version (`2.0`) |
| `X-Attempt-Number` | Delivery attempt number (starts at `1`) |
| `Idempotency-Key` | Stable id for deduplication |
## Event types
| Event | Description |
| ---------------------- | ----------------------------------------------------------------- |
| `consent.given` | New consent granted |
| `consent.revoked` | Consent revoked |
| `consent.expiring` | Consent nearing expiry |
| `consent.reauthorized` | Previously revoked/expired consent granted again |
| `data.ready` | User's data has landed and is queryable via the Query API |
| `data.failed` | Data export failed — data will not be available via the Query API |
## Payload format (v2)
All webhook events use:
```json theme={null}
{
"event": "consent.given",
"timestamp": "2026-02-12T09:10:11.000000+00:00",
"uid": "psub_d4e5f6789012345678901234abcdef01",
"client_id": "ck_live_123456789",
"sources": []
}
```
`sources[]` is event-specific:
* `consent.given`:
* `provider`, `scopes[]`, `valid_until`, `is_reauthorized`
* `consent.revoked`:
* `provider`, `revoked_at`, `reason` (`user_revoked` | `account_deleted`)
* `consent.expiring`:
* `provider`, `valid_until`, `days_until_expiry`
* `consent.reauthorized`:
* `provider`, `scopes[]`, `valid_until`, `is_returning_user`
* `data.ready`:
* `provider`
* `data.failed`:
* `provider`, `error_code`, `error_message`
## Response examples
### `consent.given`
```json theme={null}
{
"event": "consent.given",
"timestamp": "2026-02-12T09:10:11.000000+00:00",
"uid": "psub_d4e5f6789012345678901234abcdef01",
"client_id": "ck_live_123456789",
"sources": [
{
"provider": "google_data",
"scopes": [
"https://www.googleapis.com/auth/dataportability.myactivity.search",
"https://www.googleapis.com/auth/dataportability.chrome.history"
],
"valid_until": "2026-08-11T09:10:11.000000+00:00",
"is_reauthorized": false
},
{
"provider": "gmail",
"scopes": [
"https://www.googleapis.com/auth/gmail.readonly"
],
"valid_until": "2026-08-11T09:10:11.000000+00:00",
"is_reauthorized": false
}
]
}
```
### `consent.revoked`
```json theme={null}
{
"event": "consent.revoked",
"timestamp": "2026-02-12T09:22:44.000000+00:00",
"uid": "psub_d4e5f6789012345678901234abcdef01",
"client_id": "ck_live_123456789",
"sources": [
{
"provider": "gmail",
"revoked_at": "2026-02-12T09:22:44.000000+00:00",
"reason": "user_revoked"
}
]
}
```
`reason` values:
* `user_revoked` — user manually revoked consent via the Data Wallet
* `account_deleted` — user deleted their account (GDPR right-to-erasure)
### `consent.expiring`
```json theme={null}
{
"event": "consent.expiring",
"timestamp": "2026-02-12T09:22:44.000000+00:00",
"uid": "psub_d4e5f6789012345678901234abcdef01",
"client_id": "ck_live_123456789",
"sources": [
{
"provider": "google_data",
"valid_until": "2026-02-15T09:22:44.000000+00:00",
"days_until_expiry": 3
}
]
}
```
### `consent.reauthorized`
```json theme={null}
{
"event": "consent.reauthorized",
"timestamp": "2026-02-12T09:22:44.000000+00:00",
"uid": "psub_d4e5f6789012345678901234abcdef01",
"client_id": "ck_live_123456789",
"sources": [
{
"provider": "google_data",
"scopes": [
"https://www.googleapis.com/auth/dataportability.myactivity.search"
],
"valid_until": "2026-08-11T09:22:44.000000+00:00",
"is_returning_user": true
}
]
}
```
### `data.ready`
```json theme={null}
{
"event": "data.ready",
"timestamp": "2026-02-12T09:34:10.000000+00:00",
"uid": "psub_d4e5f6789012345678901234abcdef01",
"client_id": "ck_live_123456789",
"sources": [
{
"provider": "google_data"
}
]
}
```
### `data.failed`
```json theme={null}
{
"event": "data.failed",
"timestamp": "2026-02-12T09:35:41.000000+00:00",
"uid": "psub_d4e5f6789012345678901234abcdef01",
"client_id": "ck_live_123456789",
"sources": [
{
"provider": "google_data",
"error_code": "export_provider_error",
"error_message": "Provider export request failed. Retry scheduled."
}
]
}
```
## Handling webhooks
```typescript TypeScript theme={null}
import crypto from "crypto";
import express from "express";
const app = express();
app.use(express.raw({ type: "application/json" }));
const secret = process.env.EMERGE_WEBHOOK_SECRET;
if (!secret) {
throw new Error("Missing EMERGE_WEBHOOK_SECRET");
}
app.post("/webhooks/emerge", async (req, res) => {
try {
const signature = req.header("x-signature");
const idempotencyKey = req.header("idempotency-key");
if (!signature || !idempotencyKey) {
return res.status(401).send("Missing signature or idempotency key");
}
const expected = crypto.createHmac("sha256", secret).update(req.body).digest("hex");
const valid =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature, "hex"), Buffer.from(expected, "hex"));
if (!valid) {
return res.status(401).send("Invalid signature");
}
// Idempotency guard (replace with DB/Redis in production)
if (seen(idempotencyKey)) {
return res.status(200).send("Duplicate ignored");
}
remember(idempotencyKey);
const payload = JSON.parse(req.body.toString("utf8")) as {
event: string;
uid: string;
sources: Array>;
};
if (payload.event === "consent.revoked") {
await handleRevocation(payload.uid, payload.sources);
} else if (payload.event === "data.ready") {
await handleDataReady(payload.uid, payload.sources);
} else if (payload.event === "data.failed") {
await handleDataFailed(payload.uid, payload.sources);
}
return res.status(200).send("OK");
} catch (error) {
console.error("Webhook processing failed", error);
return res.status(500).send("Server error");
}
});
const idempotencyStore = new Set();
function seen(key: string): boolean {
return idempotencyStore.has(key);
}
function remember(key: string): void {
idempotencyStore.add(key);
}
async function handleRevocation(uid: string, sources: Array>) {
for (const source of sources) {
const provider = String(source.provider ?? "");
if (provider) {
await purgeProviderData(uid, provider);
}
}
}
async function handleDataReady(uid: string, sources: Array>) {
for (const source of sources) {
const provider = String(source.provider ?? "");
if (provider) {
console.log(`Data ready for ${provider} and user ${uid}`);
await enqueueProviderQuery(uid, provider);
}
}
}
async function handleDataFailed(uid: string, sources: Array>) {
for (const source of sources) {
const provider = String(source.provider ?? "unknown_provider");
const errorCode = String(source.error_code ?? "unknown_error");
const errorMessage = String(source.error_message ?? "No details provided");
console.error(
`Data export failed for ${provider} and user ${uid}: ${errorCode} - ${errorMessage}`
);
await notifyOps(uid, provider, errorCode, errorMessage);
}
}
async function purgeProviderData(uid: string, provider: string) {
console.log(`Purging ${provider} data for ${uid}`);
}
async function enqueueProviderQuery(uid: string, provider: string) {
console.log(`Queueing query for ${provider} and user ${uid}`);
}
async function notifyOps(
uid: string,
provider: string,
errorCode: string,
errorMessage: string
) {
console.log(`Notify ops: ${uid} ${provider} ${errorCode} ${errorMessage}`);
}
```
```python Python theme={null}
import hashlib
import hmac
import json
import os
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
secret = os.getenv("EMERGE_WEBHOOK_SECRET")
if not secret:
raise RuntimeError("Missing EMERGE_WEBHOOK_SECRET")
_seen: set[str] = set()
@app.post("/webhooks/emerge")
async def receive_webhook(request: Request):
body = await request.body()
signature = request.headers.get("x-signature")
idem_key = request.headers.get("idempotency-key")
if not signature or not idem_key:
raise HTTPException(status_code=401, detail="Missing signature or idempotency key")
expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, expected):
raise HTTPException(status_code=401, detail="Invalid signature")
if idem_key in _seen:
return {"status": "duplicate_ignored"}
_seen.add(idem_key)
payload = json.loads(body)
event = payload.get("event")
if event == "consent.revoked":
uid = payload.get("uid", "")
for source in payload.get("sources", []):
provider = source.get("provider")
if provider:
await purge_provider_data(uid, provider)
elif event == "data.ready":
uid = payload.get("uid", "")
for source in payload.get("sources", []):
provider = source.get("provider")
if provider:
await enqueue_provider_query(uid, provider)
elif event == "data.failed":
uid = payload.get("uid", "")
for source in payload.get("sources", []):
provider = source.get("provider", "unknown_provider")
error_code = source.get("error_code", "unknown_error")
error_message = source.get("error_message", "No details provided")
await notify_ops(uid, provider, error_code, error_message)
return {"status": "ok"}
async def purge_provider_data(uid: str, provider: str):
print(f"Purging {provider} data for {uid}")
async def enqueue_provider_query(uid: str, provider: str):
print(f"Queueing query for {provider} and user {uid}")
async def notify_ops(uid: str, provider: str, error_code: str, error_message: str):
print(f"Data export failed for {provider} and user {uid}: {error_code} - {error_message}")
```
## Delivery and retries
* A non-2xx response triggers retries with exponential backoff.
* Current max attempts: `5`.
* Always design handlers to be idempotent using `Idempotency-Key`.
## Related docs
* [Callbacks](/link/callbacks)
* [Data Wallet](/data-wallet/overview)
* [Query Overview](/query/overview)
# Data Schema
Source: https://docs.emergedata.ai/query/data-schema
Field-level schema for Query API event records
Use this page as the canonical schema reference for Query API payloads.
## Event Types Overview
The Query API provides five types of enriched events:
| Event Type | Description |
| ------------------ | ------------------------------------------- |
| 🔍 Search Events | Search queries and results across platforms |
| 🌐 Browsing Events | Websites visited and page views |
| 📺 YouTube Events | YouTube videos watched and interactions |
| 📢 Ads Events | Advertisements seen across the web |
| 🧾 Receipts Events | Purchase receipts and transaction data |
## Sync response envelope
All sync endpoints return:
```json theme={null}
{
"data": [],
"count": 0,
"next_cursor": null,
"has_more": false,
"applied_ingested_end": "2026-02-12T09:10:11Z"
}
```
| Field | Type | Description |
| ---------------------- | ---------------- | ----------------------------------------- |
| `data` | array | Event records for the endpoint |
| `count` | integer | Number of records returned |
| `next_cursor` | string \| null | Cursor for next page |
| `has_more` | boolean | Whether more records exist |
| `applied_ingested_end` | ISO 8601 \| null | Effective ingestion cutoff used by server |
## Common event fields
Every event includes these standard fields:
| Data Point Name | Explanation | Example Value |
| --------------- | ------------------------------------------------------------ | ----------------------------------------- |
| `user_id` | Your unique identifier for this person | `"psub_d4e5f6789012345678901234abcdef01"` |
| `event_id` | Unique ID for this specific event (used to avoid duplicates) | `102938` |
| `timestamp` | When this event happened | `"2026-02-10T08:22:11Z"` |
| `ingested_at` | When Emerge received this event | `"2026-02-10T08:23:40Z"` |
| `category` | The topic category (from Google Topics taxonomy) | `"/Shopping/Apparel/Footwear"` |
## Event type schemas
### Search Events
Captures what people search for online.
**Endpoint:** `/v1/sync/get_search`
| Data Point Name | Explanation | Example Value |
| --------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `url` | The web address where the search happened | `"https://www.google.com/search?q=running+shoes"` |
| `title` | The page title shown in the browser tab | `"running shoes - Google Search"` |
| `query` | The exact words the person searched for | `"running shoes"` |
| `intent` | Why they searched: looking for info, ready to buy, or finding a specific site | `"transactional"` (options: `"informational"`, `"transactional"`, `"navigational"`) |
| `category` | The topic category this search relates to | `"/Shopping/Apparel/Footwear"` |
| `brands` | Brand names found in the search results | `["Nike", "Adidas"]` |
```json theme={null}
{
"data": [
{
"user_id": "psub_d4e5f6789012345678901234abcdef01",
"event_id": 102938,
"timestamp": "2026-02-10T08:22:11Z",
"ingested_at": "2026-02-10T08:23:40Z",
"url": "https://www.google.com/search?q=running+shoes",
"title": "running shoes - Google Search",
"query": "running shoes",
"intent": "transactional",
"category": "/Shopping/Apparel/Footwear",
"brands": ["Nike"]
}
],
"count": 1,
"next_cursor": null,
"has_more": false,
"applied_ingested_end": "2026-02-12T09:10:11Z"
}
```
### Browsing Events
Captures websites people visit.
**Endpoint:** `/v1/sync/get_browsing`
| Data Point Name | Explanation | Example Value |
| --------------- | --------------------------------------------------------------- | -------------------------------------- |
| `url` | The web address of the page visited | `"https://www.nike.com/running-shoes"` |
| `title` | The page title shown in the browser tab | `"Running Shoes - Nike.com"` |
| `page_category` | The type of page visited (like product page, article, homepage) | `"product"` |
| `category` | The topic category this page relates to | `"/Shopping/Apparel/Footwear"` |
| `brands` | Brand names detected on the page | `["Nike"]` |
```json theme={null}
{
"data": [
{
"user_id": "psub_d4e5f6789012345678901234abcdef01",
"event_id": 102940,
"timestamp": "2026-02-10T09:15:22Z",
"ingested_at": "2026-02-10T09:16:33Z",
"url": "https://www.nike.com/running-shoes",
"title": "Running Shoes - Nike.com",
"page_category": "product",
"category": "/Shopping/Apparel/Footwear",
"brands": ["Nike"]
}
],
"count": 1,
"next_cursor": null,
"has_more": false,
"applied_ingested_end": "2026-02-12T09:10:11Z"
}
```
### YouTube Events
Captures YouTube videos people watch.
**Endpoint:** `/v1/sync/get_youtube`
| Data Point Name | Explanation | Example Value |
| --------------- | ------------------------------------------- | ----------------------------------------------- |
| `url` | The YouTube video web address | `"https://www.youtube.com/watch?v=dQw4w9WgXcQ"` |
| `title` | The video title | `"Best Running Shoes for Beginners"` |
| `category` | The topic category this video relates to | `"/Sports/Running"` |
| `brands` | Brand names mentioned or shown in the video | `["Nike", "Adidas"]` |
```json theme={null}
{
"data": [
{
"user_id": "psub_d4e5f6789012345678901234abcdef01",
"event_id": 102942,
"timestamp": "2026-02-10T10:30:45Z",
"ingested_at": "2026-02-10T10:31:12Z",
"url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"title": "Best Running Shoes for Beginners",
"category": "/Sports/Running",
"brands": ["Nike", "Adidas"]
}
],
"count": 1,
"next_cursor": null,
"has_more": false,
"applied_ingested_end": "2026-02-12T09:10:11Z"
}
```
### Ads Events
Captures online ads people see and click.
**Endpoint:** `/v1/sync/get_ads`
| Data Point Name | Explanation | Example Value |
| ---------------- | ---------------------------------------------- | ------------------------------ |
| `source_domain` | The website where the ad was shown | `"cnn.com"` |
| `landing_domain` | The website the ad links to | `"nike.com"` |
| `url` | The full web address the ad links to | `"https://www.nike.com/sale"` |
| `title` | The headline or text shown in the ad | `"Nike Sale - Up to 50% Off"` |
| `category` | The topic category this ad relates to | `"/Shopping/Apparel/Footwear"` |
| `brands` | Brand names associated with the ad | `["Nike"]` |
| `ad_network` | The company serving the ad (like Google, Meta) | `"Google Ads"` |
```json theme={null}
{
"data": [
{
"user_id": "psub_d4e5f6789012345678901234abcdef01",
"event_id": 102945,
"timestamp": "2026-02-10T11:22:33Z",
"ingested_at": "2026-02-10T11:23:01Z",
"source_domain": "cnn.com",
"landing_domain": "nike.com",
"url": "https://www.nike.com/sale",
"title": "Nike Sale - Up to 50% Off",
"category": "/Shopping/Apparel/Footwear",
"brands": ["Nike"],
"ad_network": "Google Ads"
}
],
"count": 1,
"next_cursor": null,
"has_more": false,
"applied_ingested_end": "2026-02-12T09:10:11Z"
}
```
### Receipts Events
Captures purchases from email receipts.
**Endpoint:** `/v1/sync/get_receipts`
| Data Point Name | Explanation | Example Value |
| ------------------ | ------------------------------------------------ | ------------------------------------ |
| `subject` | The email subject line | `"Your Nike.com order confirmation"` |
| `retailer_name` | The store or website where the purchase was made | `"Nike.com"` |
| `receipt_currency` | The currency used for the purchase | `"USD"` |
| `total_value` | The total amount spent | `149.99` |
| `items` | List of items purchased (see item details below) | `[{...}, {...}]` |
| `brands` | Brand names from all items in the receipt | `["Nike"]` |
**Receipt item details:**
Each item in the `items` array includes:
| Data Point Name | Explanation | Example Value |
| --------------- | ------------------------------------ | ------------------------------ |
| `name` | The product name | `"Air Max 90"` |
| `quantity` | How many of this item were purchased | `1` |
| `unit_price` | The price for one item | `149.99` |
| `brand` | The brand of this specific item | `"Nike"` |
| `category` | The product category | `"/Shopping/Apparel/Footwear"` |
```json theme={null}
{
"data": [
{
"user_id": "psub_d4e5f6789012345678901234abcdef01",
"event_id": 102950,
"timestamp": "2026-02-10T14:45:22Z",
"ingested_at": "2026-02-10T14:46:11Z",
"subject": "Your Nike.com order confirmation",
"retailer_name": "Nike.com",
"receipt_currency": "USD",
"total_value": 149.99,
"items": [
{
"name": "Air Max 90",
"quantity": 1,
"unit_price": 149.99,
"brand": "Nike",
"category": "/Shopping/Apparel/Footwear"
}
],
"brands": ["Nike"]
}
],
"count": 1,
"next_cursor": null,
"has_more": false,
"applied_ingested_end": "2026-02-12T09:10:11Z"
}
```
## Type-safe parsing examples
```typescript TypeScript theme={null}
type SyncEnvelope = {
data: T[];
count: number;
next_cursor: string | null;
has_more: boolean;
applied_ingested_end: string | null;
};
type SearchEvent = {
user_id: string;
event_id: number;
timestamp: string;
ingested_at: string;
url: string | null;
title: string | null;
query: string | null;
intent: string | null;
category: string | null;
brands: string[];
};
async function fetchSearch(uid: string): Promise> {
const response = await fetch(
`https://query.emergedata.ai/v1/sync/get_search?uid=${encodeURIComponent(uid)}`,
{ headers: { Authorization: `Bearer ${process.env.EMERGE_API_TOKEN ?? ''}` } }
);
if (!response.ok) {
throw new Error(`Search request failed (${response.status})`);
}
const payload = (await response.json()) as SyncEnvelope;
return payload;
}
```
```python Python theme={null}
from typing import Any, TypedDict
import os
import requests
class SearchEvent(TypedDict):
user_id: str
event_id: int
timestamp: str
ingested_at: str
url: str | None
title: str | None
query: str | None
intent: str | None
category: str | None
brands: list[str]
def fetch_search(uid: str) -> dict[str, Any]:
response = requests.get(
"https://query.emergedata.ai/v1/sync/get_search",
params={"uid": uid},
headers={"Authorization": f"Bearer {os.environ['EMERGE_API_TOKEN']}"},
timeout=30
)
response.raise_for_status()
return response.json()
```
## Related docs
* [Query Overview](/query/overview)
* [Event Categories](/query/event-categories)
* [Pagination & Delta Queries](/query/pagination)
# Event Categories
Source: https://docs.emergedata.ai/query/event-categories
Category taxonomy used in Query API event data
Query events use Google Topics-style category paths like `/Shopping/Apparel/Footwear`.\
If you only need first-level categories, use the list below.
## Authentication
`GET /v1/sync/categories` requires:
* `Authorization: Bearer `
## First-level categories
| Category |
| ------------------------- |
| `Arts & Entertainment` |
| `Autos & Vehicles` |
| `Beauty & Fitness` |
| `Books & Literature` |
| `Business & Industrial` |
| `Computers & Electronics` |
| `Finance` |
| `Food & Drink` |
| `Games` |
| `Hobbies & Leisure` |
| `Home & Garden` |
| `Internet & Telecom` |
| `Jobs & Education` |
| `Law & Government` |
| `News` |
| `Online Communities` |
| `People & Society` |
| `Pets & Animals` |
| `Real Estate` |
| `Shopping` |
| `Sports` |
| `Travel & Transportation` |
## Endpoint
Use `GET /v1/sync/categories` with a `table` value:
* `searches`
* `browsing`
* `youtube`
* `ads`
* `receipts`
### Response example
```json theme={null}
{
"categories": [
"/Shopping/Apparel/Footwear",
"/Sports/Running & Walking",
"/Computers & Electronics/Software"
]
}
```
## Example implementation
```typescript TypeScript theme={null}
async function getFirstLevelCategories(table: 'searches' | 'browsing' | 'youtube' | 'ads' | 'receipts') {
const response = await fetch(
`https://query.emergedata.ai/v1/sync/categories?table=${table}`,
{
headers: {
Authorization: `Bearer ${process.env.EMERGE_API_TOKEN ?? ''}`
}
}
);
if (!response.ok) {
const body = await response.text();
throw new Error(`Categories request failed (${response.status}): ${body}`);
}
const payload: { categories: string[] } = await response.json();
const roots = Array.from(
new Set(
payload.categories
.map((path) => path.replace(/^\/+/, '').split('/')[0]?.trim())
.filter((value): value is string => Boolean(value))
)
);
return roots.sort();
}
```
```python Python theme={null}
import os
import requests
def get_first_level_categories(table: str) -> list[str]:
response = requests.get(
"https://query.emergedata.ai/v1/sync/categories",
params={"table": table},
headers={"Authorization": f"Bearer {os.environ['EMERGE_API_TOKEN']}"},
timeout=30
)
response.raise_for_status()
payload = response.json()
categories = payload.get("categories", [])
roots = sorted({
path.lstrip("/").split("/")[0].strip()
for path in categories
if isinstance(path, str) and path
})
return roots
```
## Gotchas
* Category filters are subtree matches. `/Shopping` includes `/Shopping/...`.
* `category` can be `null` on some records. Handle missing values in downstream logic.
* Keep filtering server-side where possible to reduce payload size.
## Related docs
* [Query Overview](/query/overview)
* [Data Schema](/query/data-schema)
* [Pagination & Delta Queries](/query/pagination)
# Query API Overview
Source: https://docs.emergedata.ai/query/overview
Retrieve consented user data with sync or async queries
The Query API retrieves user data after they've granted consent through Emerge Link. Choose between synchronous (immediate response) or asynchronous (job-based) queries depending on your use case.
## Available data types
| Data Type | Sync Endpoint | Async Endpoint | Description |
| ---------------- | ----------------------- | -------------- | --------------------------------------- |
| Search History | `/v1/sync/get_search` | `/v1/search` | Google search queries |
| Browsing History | `/v1/sync/get_browsing` | `/v1/browsing` | Chrome browser history |
| YouTube History | `/v1/sync/get_youtube` | `/v1/youtube` | Watched videos |
| Ad Interactions | `/v1/sync/get_ads` | `/v1/ads` | Ad clicks and views |
| Receipts | `/v1/sync/get_receipts` | `/v1/receipts` | Purchase receipts with items and brands |
## Sync vs Async
**Best for:** Real-time needs, single users, simple integrations
```typescript theme={null}
const response = await fetch(
`https://query.emergedata.ai/v1/sync/get_search?uid=${uid}`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
const data = await response.json();
// Data returned immediately in JSON format
```
**Characteristics:**
* Single `uid` parameter
* Response includes data directly as JSON
* 30-second timeout
* Supports pagination with `cursor`
* Supports delta queries with `ingested_begin`/`ingested_end`
**Best for:** Large datasets, multiple users, batch processing
```typescript theme={null}
// 1. Start the query (up to 25 users)
const params = new URLSearchParams([
['user_ids', 'psub_a1b2c3d4e5f6789012345678901234ab'],
['user_ids', 'psub_b2c3d4e5f6789012345678901234abcd'],
['begin', '2024-01-01T00:00:00Z'],
['end', '2024-01-31T23:59:59Z']
]);
const startResponse = await fetch(
`https://query.emergedata.ai/v1/search?${params.toString()}`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
const { job_id: taskId } = await startResponse.json();
// 2. Poll for results
const resultResponse = await fetch(
`https://query.emergedata.ai/v1/job/${taskId}`,
{ headers: { 'Authorization': `Bearer ${token}` } }
);
const result = await resultResponse.json();
if (result.status === 'COMPLETED' && result.url) {
// Download Parquet file from result.url
console.log(result.url);
}
```
**Characteristics:**
* `user_ids` query parameter (up to 25 users per request)
* `begin`/`end` date range parameters
* Returns `job_id` immediately
* Poll `/v1/job/{task_id}` using the returned `job_id`
* Completed jobs provide S3 presigned URL to Parquet file
* No timeout concerns
## When to use each
| Use Case | Recommendation |
| -------------------------- | ----------------------------------------- |
| User-facing dashboard | Sync - immediate JSON response |
| Background data processing | Async - batch multiple users |
| Real-time personalization | Sync - low latency |
| Batch analytics | Async - Parquet format for big data tools |
| Mobile app | Sync - simpler error handling |
| Multi-user reports | Async - query up to 25 users at once |
## Authentication
All Query API endpoints require a Bearer token:
```bash theme={null}
curl 'https://query.emergedata.ai/v1/sync/get_search?uid=psub_c3d4e5f6789012345678901234abcdef' \
-H 'Authorization: Bearer your_api_token'
```
Sync endpoints require `uid`. Use the callback `uid` you stored on your backend (or the same value you supplied in the Link URL). Never ask end-users for `uid`, and never call Query from the frontend since tokens and user mapping must stay server-side.
## Categories and schema
* Categories are Google Topics taxonomy paths (for example `/Shopping/Apparel/Footwear`).
* Use `GET /v1/sync/categories?table=searches` (or `browsing`, `youtube`, `ads`, `receipts`) to list available category paths.
Response example:
```json theme={null}
{
"categories": [
"/Shopping/Apparel/Footwear",
"/Sports/Running & Walking",
"/Computers & Electronics/Software"
]
}
```
See:
* [Event Categories](/query/event-categories)
* [Data Schema](/query/data-schema)
## Sync response format
Sync endpoints return JSON directly:
```json theme={null}
{
"data": [
{
"user_id": "psub_c3d4e5f6789012345678901234abcdef",
"event_id": 12345,
"query": "best restaurants nearby",
"timestamp": "2024-01-15T10:30:00Z",
"ingested_at": "2024-01-15T11:00:00Z"
}
],
"count": 1,
"has_more": true,
"next_cursor": "eyJsYXN0X2lkIjogMTIzNH0=",
"applied_ingested_end": "2024-01-15T12:00:00Z"
}
```
| Field | Description |
| ---------------------- | ------------------------------------- |
| `data` | Array of records |
| `event_id` | Unique identifier for deduplication |
| `ingested_at` | When record was added to Emerge |
| `count` | Number of records in this response |
| `has_more` | Whether more records exist |
| `next_cursor` | Pagination token for next page |
| `applied_ingested_end` | Actual end time used (for delta sync) |
## Async response format
Async endpoints return a job reference:
```json theme={null}
{
"job_id": "82f80278-5e76-4d01-8f1d-b55e08f12a52",
"status": "PENDING"
}
```
When completed, the job result includes a download URL:
```json theme={null}
{
"task_id": "82f80278-5e76-4d01-8f1d-b55e08f12a52",
"status": "COMPLETED",
"url": "https://query-results.s3.amazonaws.com/82f80278-5e76-4d01-8f1d-b55e08f12a52.parquet",
"created_at": "2026-02-12T09:10:11Z",
"expire_at": "2026-02-19T09:10:11Z"
}
```
The download URL points to a Parquet file containing all results.
## Error responses
| Status | Code | Description |
| ------ | ---------------- | --------------------------------- |
| 401 | `unauthorized` | Invalid or missing API token |
| 404 | `user_not_found` | No consent for this user |
| 429 | `rate_limited` | Too many requests |
| 500 | `internal_error` | Server error (retry with backoff) |
## Next steps
Handle large datasets with cursors and delta queries
First-level category list and filter patterns
Field-level schema for all Query event types
# Pagination & Delta Queries
Source: https://docs.emergedata.ai/query/pagination
Handle large datasets with cursors and incremental queries
Query API responses can contain thousands of records. Use pagination to retrieve data in manageable chunks, and delta queries to fetch only new data since your last sync.
## Cursor-based pagination
Every response includes a `next_cursor` for fetching the next page:
```json theme={null}
{
"data": [...],
"count": 100,
"has_more": true,
"next_cursor": "eyJsYXN0X2lkIjogMTIzNH0="
}
```
Pass the cursor to get the next page:
```typescript TypeScript theme={null}
async function fetchAllSearchHistory(uid: string) {
const allData: SearchEntry[] = [];
let cursor: string | undefined;
do {
const params = new URLSearchParams({ uid });
if (cursor) {
params.set('cursor', cursor);
}
const response = await fetch(
`https://query.emergedata.ai/v1/sync/get_search?${params}`,
{ headers: { 'Authorization': `Bearer ${API_TOKEN}` } }
);
const result = await response.json();
allData.push(...result.data);
cursor = result.has_more ? result.next_cursor : undefined;
} while (cursor);
return allData;
}
```
```python Python theme={null}
def fetch_all_search_history(uid: str) -> list[dict]:
all_data = []
cursor = None
while True:
params = {'uid': uid}
if cursor:
params['cursor'] = cursor
response = requests.get(
'https://query.emergedata.ai/v1/sync/get_search',
params=params,
headers={'Authorization': f'Bearer {API_TOKEN}'}
)
result = response.json()
all_data.extend(result['data'])
if not result.get('has_more'):
break
cursor = result['next_cursor']
return all_data
```
## Page size
Control the number of records per page with the `limit` parameter:
```bash theme={null}
curl 'https://query.emergedata.ai/v1/sync/get_search?uid=psub_c3d4e5f6789012345678901234abcdef&limit=500' \
-H 'Authorization: Bearer your_api_token'
```
| Parameter | Default | Maximum |
| --------- | ------- | ------- |
| `limit` | 100 | 1000 |
## Delta queries
Fetch only data that's been ingested since your last sync using `ingested_begin` and `ingested_end`:
```bash theme={null}
curl 'https://query.emergedata.ai/v1/sync/get_search?uid=psub_c3d4e5f6789012345678901234abcdef&ingested_begin=2024-01-15T00:00:00Z' \
-H 'Authorization: Bearer your_api_token'
```
### Time-based filtering
| Parameter | Description | Format |
| ---------------- | -------------------------------------- | -------- |
| `ingested_begin` | Records ingested at or after this time | ISO 8601 |
| `ingested_end` | Records ingested before this time | ISO 8601 |
`ingested_begin` and `ingested_end` filter by when data was added to Emerge, not when the user performed the action. This is useful for incremental syncs.
### Response fields for delta sync
The response includes additional fields to help with delta syncing:
```json theme={null}
{
"data": [...],
"count": 50,
"has_more": false,
"next_cursor": null,
"applied_ingested_end": "2024-01-15T12:00:00Z"
}
```
| Field | Description |
| ---------------------- | ------------------------------------------------------------------------------------------------------- |
| `applied_ingested_end` | The actual end time used for filtering. Use this as your next `ingested_begin` value to ensure no gaps. |
### Delta sync pattern
```typescript TypeScript theme={null}
interface SyncState {
lastIngestedEnd: string;
}
async function deltaSync(uid: string, state: SyncState): Promise {
const newData: SearchEntry[] = [];
let cursor: string | undefined;
do {
const params = new URLSearchParams({
uid,
ingested_begin: state.lastIngestedEnd
});
if (cursor) {
params.set('cursor', cursor);
}
const response = await fetch(
`https://query.emergedata.ai/v1/sync/get_search?${params}`,
{ headers: { 'Authorization': `Bearer ${API_TOKEN}` } }
);
const result = await response.json();
newData.push(...result.data);
// Use applied_ingested_end for next sync to avoid gaps
const appliedEnd = result.applied_ingested_end;
cursor = result.has_more ? result.next_cursor : undefined;
// After last page, update state
if (!cursor) {
return {
lastIngestedEnd: appliedEnd
};
}
} while (cursor);
// Process new data
await processNewData(newData);
return state;
}
// Usage
let syncState: SyncState = {
lastIngestedEnd: '2024-01-01T00:00:00Z'
};
// Run periodically
syncState = await deltaSync('psub_c3d4e5f6789012345678901234abcdef', syncState);
```
```python Python theme={null}
from dataclasses import dataclass
from typing import Optional
@dataclass
class SyncState:
last_ingested_end: str
def delta_sync(uid: str, state: SyncState) -> SyncState:
new_data = []
cursor = None
applied_end = None
while True:
params = {
'uid': uid,
'ingested_begin': state.last_ingested_end
}
if cursor:
params['cursor'] = cursor
response = requests.get(
'https://query.emergedata.ai/v1/sync/get_search',
params=params,
headers={'Authorization': f'Bearer {API_TOKEN}'}
)
result = response.json()
new_data.extend(result['data'])
# Track applied_ingested_end for next sync
applied_end = result.get('applied_ingested_end')
if not result.get('has_more'):
break
cursor = result['next_cursor']
# Process new data
process_new_data(new_data)
# Return new state with applied_ingested_end
return SyncState(last_ingested_end=applied_end or state.last_ingested_end)
# Usage
sync_state = SyncState(last_ingested_end='2024-01-01T00:00:00Z')
# Run periodically
sync_state = delta_sync('psub_c3d4e5f6789012345678901234abcdef', sync_state)
```
## Best practices
Always use the `applied_ingested_end` from the response as your next `ingested_begin` value. This ensures no gaps between syncs.
An empty `data` array with `has_more: false` means no new data since your last sync.
500 records per page balances throughput and memory usage for most applications.
If you hit rate limits or errors, back off exponentially before retrying.
Each record includes an `event_id` for deduplication. Use this to handle any potential duplicates across pagination boundaries.
## Async job pagination
For async queries, results are returned as a single Parquet file. The file contains all records for all users in the request.
If you need to paginate through very large async results, use the `begin` and `end` date parameters to narrow the time range:
```typescript theme={null}
// First batch: January 1-15
const firstWindow = new URLSearchParams({
user_ids: 'psub_a1b2c3d4e5f6789012345678901234ab',
begin: '2024-01-01T00:00:00Z',
end: '2024-01-15T23:59:59Z'
});
const job1 = await fetch(
`https://query.emergedata.ai/v1/search?${firstWindow.toString()}`,
{ headers: { 'Authorization': `Bearer ${API_TOKEN}` } }
).then(r => r.json());
// Second batch: January 16-31
const secondWindow = new URLSearchParams({
user_ids: 'psub_a1b2c3d4e5f6789012345678901234ab',
begin: '2024-01-16T00:00:00Z',
end: '2024-01-31T23:59:59Z'
});
const job2 = await fetch(
`https://query.emergedata.ai/v1/search?${secondWindow.toString()}`,
{ headers: { 'Authorization': `Bearer ${API_TOKEN}` } }
).then(r => r.json());
```
# Quickstart
Source: https://docs.emergedata.ai/quickstart
Integrate Emerge lightning-fast
This guide walks you through collecting your first user consent and querying their data.
## Connect your AI tools
Get AI-powered help while integrating by connecting these docs to your AI tools.
Add to `.cursor/mcp.json`:
```json theme={null}
{
"mcpServers": {
"Emerge": { "type": "http", "url": "https://docs.emergedata.ai/mcp" }
}
}
```
```bash theme={null}
claude mcp add --transport http emerge https://docs.emergedata.ai/mcp
```
Add to `.vscode/mcp.json`:
```json theme={null}
{
"mcpServers": {
"Emerge": { "type": "http", "url": "https://docs.emergedata.ai/mcp" }
}
}
```
## Prerequisites
The Control Room account with API credentials
Don't have an account? [Sign up here](https://dashboard.emergedata.ai).
## Step 1: Configure your flow
Set up your company branding for the consent flow.
```typescript TypeScript theme={null}
const response = await fetch('https://link.emergedata.ai/configs', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
config_name: 'default',
company_name: 'Your Company',
logo_url: 'https://yourcompany.com/logo.png',
privacy_policy_url: 'https://yourcompany.com/privacy',
is_default: true
})
});
```
```python Python theme={null}
import requests
response = requests.post(
'https://link.emergedata.ai/configs',
headers={
'Authorization': f'Bearer {API_TOKEN}',
'Content-Type': 'application/json'
},
json={
'config_name': 'default',
'company_name': 'Your Company',
'logo_url': 'https://yourcompany.com/logo.png',
'privacy_policy_url': 'https://yourcompany.com/privacy',
'is_default': True
}
)
```
`POST /configs` is an upsert. Reusing the same `config_name` updates the existing config instead of returning a conflict, which makes setup scripts idempotent. Use `GET /configs` to list your configs and preview URLs.
## Step 2: Generate a signed link
Create an HMAC-signed URL that users click to start the consent flow.
Do not ask end-users for `uid` or collect it in the frontend. Use your internal user id server-side or omit `uid` and store the generated callback `uid`. This keeps user scoping private and avoids wrong-user data access.
```typescript TypeScript theme={null}
import crypto from 'crypto';
function createLinkUrl(params: {
clientId: string;
signingSecret: string;
redirectUri: string;
userId: string;
}) {
const timestamp = new Date().toISOString();
const state = crypto.randomBytes(16).toString('hex');
// Build parameters object
const urlParams: Record = {
client_id: params.clientId,
redirect_uri: params.redirectUri,
state: state,
timestamp: timestamp,
uid: params.userId
};
// Sort parameters alphabetically for signature
const sortedKeys = Object.keys(urlParams).sort();
const signatureBase = sortedKeys
.map(key => `${key}=${urlParams[key]}`)
.join('&');
const signature = crypto
.createHmac('sha256', params.signingSecret)
.update(signatureBase)
.digest('hex');
// Build final URL with URL-encoded parameters
const finalParams = new URLSearchParams(urlParams);
finalParams.append('signature', signature);
return `https://link.emergedata.ai/link/start?${finalParams.toString()}`;
}
// Usage
const linkUrl = createLinkUrl({
clientId: 'your_client_id',
signingSecret: 'your_signing_secret',
redirectUri: 'https://yourcompany.com/callback',
userId: 'psub_d4e5f6789012345678901234abcdef01'
});
```
```python Python theme={null}
import hmac
import hashlib
from datetime import datetime, timezone
import secrets
from urllib.parse import urlencode
def create_link_url(
client_id: str,
signing_secret: str,
redirect_uri: str,
user_id: str
) -> str:
timestamp = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
state = secrets.token_hex(16)
params = {
'client_id': client_id,
'redirect_uri': redirect_uri,
'state': state,
'timestamp': timestamp,
'uid': user_id
}
# Sort parameters alphabetically for signature
sorted_params = sorted(params.items())
signature_base = '&'.join(f'{k}={v}' for k, v in sorted_params)
signature = hmac.new(
signing_secret.encode(),
signature_base.encode(),
hashlib.sha256
).hexdigest()
params['signature'] = signature
return f"https://link.emergedata.ai/link/start?{urlencode(params)}"
# Usage
link_url = create_link_url(
client_id='your_client_id',
signing_secret='your_signing_secret',
redirect_uri='https://yourcompany.com/callback',
user_id='psub_d4e5f6789012345678901234abcdef01'
)
```
## Step 3: Handle the callback
After the user completes the consent flow, they're redirected to your `redirect_uri` with these parameters:
| Parameter | Description |
| ------------ | ---------------------------------------------------------------------- |
| `status` | `success`, `reauthorized`, or `failure` |
| `state` | The state value you provided (verify this matches) |
| `uid` | The user identifier returned by Emerge (your value or a generated one) |
| `error_code` | Only present if `status=failure` |
```typescript TypeScript theme={null}
// Express.js example
app.get('/callback', (req, res) => {
const { status, state, uid, error_code } = req.query;
// Verify state matches what you stored
if (!verifyState(state)) {
return res.status(400).send('Invalid state');
}
if (status === 'success' || status === 'reauthorized') {
// Consent granted - data export will start automatically
// Next step: poll /export/status/{uid} and wait for provider-level readiness
console.log(`User ${uid} granted consent`);
res.redirect('/success');
} else {
console.log(`Consent failed: ${error_code}`);
res.redirect('/error');
}
});
```
```python Python theme={null}
# FastAPI example
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get('/callback')
async def callback(
status: str,
state: str,
uid: str,
error_code: str = None
):
# Verify state matches what you stored
if not verify_state(state):
return RedirectResponse('/error')
if status in ('success', 'reauthorized'):
# Consent granted - data export will start automatically
print(f'User {uid} granted consent')
return RedirectResponse('/success')
else:
print(f'Consent failed: {error_code}')
return RedirectResponse('/error')
```
## Step 4: Check export status
Before querying, poll `GET /export/status/{uid}` until the provider you need is ready.
```typescript TypeScript theme={null}
async function waitForProviderExport(uid: string, provider: 'google_data' | 'gmail') {
for (let attempt = 1; attempt <= 10; attempt += 1) {
const response = await fetch(
`https://link.emergedata.ai/export/status/${encodeURIComponent(uid)}`,
{
headers: {
Authorization: `Bearer ${API_TOKEN}`
}
}
);
if (!response.ok) {
const body = await response.text();
throw new Error(`Export status failed (${response.status}): ${body}`);
}
const payload = await response.json() as {
uid: string;
sources: Array<{ provider: string; data_ready: boolean }>;
};
const source = payload.sources.find((item) => item.provider === provider);
if (source?.data_ready) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 1500 * attempt));
}
throw new Error(`Export not ready for provider ${provider}`);
}
```
```python Python theme={null}
import time
import requests
def wait_for_provider_export(uid: str, provider: str) -> None:
for attempt in range(1, 11):
response = requests.get(
f'https://link.emergedata.ai/export/status/{uid}',
headers={'Authorization': f'Bearer {API_TOKEN}'}
)
response.raise_for_status()
payload = response.json()
source = next(
(item for item in payload.get('sources', []) if item.get('provider') == provider),
None
)
if source and source.get('data_ready') is True:
return
time.sleep(1.5 * attempt)
raise RuntimeError(f'Export not ready for provider {provider}')
```
### Response example
```json theme={null}
{
"uid": "psub_d4e5f6789012345678901234abcdef01",
"sources": [
{
"provider": "google_data",
"data_ready": true,
"data_landed_at": "2026-02-12T09:10:11Z",
"export_status": "completed",
"export_completed_at": "2026-02-12T09:10:11Z"
},
{
"provider": "gmail",
"data_ready": false,
"data_landed_at": null,
"export_status": "running",
"export_completed_at": null
}
]
}
```
You can also subscribe to `data.ready` and `data.failed` webhooks for near-real-time export updates. Keep polling `GET /export/status/{uid}` as a fallback for missed webhook deliveries.
## Step 5: Query user data
Once consent is granted and data is exported, query it using the sync endpoints.
```typescript TypeScript theme={null}
async function getUserSearchHistory(uid: string) {
const response = await fetch(
`https://query.emergedata.ai/v1/sync/get_search?uid=${uid}`,
{
headers: {
'Authorization': `Bearer ${API_TOKEN}`
}
}
);
const data = await response.json();
return data;
}
// Usage
const searchHistory = await getUserSearchHistory('psub_d4e5f6789012345678901234abcdef01');
console.log(searchHistory.data);
// [{ query: "best restaurants nearby", timestamp: "2024-01-15T10:30:00Z" }, ...]
```
```python Python theme={null}
import requests
def get_user_search_history(uid: str) -> dict:
response = requests.get(
f'https://query.emergedata.ai/v1/sync/get_search',
params={'uid': uid},
headers={'Authorization': f'Bearer {API_TOKEN}'}
)
return response.json()
# Usage
search_history = get_user_search_history('psub_d4e5f6789012345678901234abcdef01')
print(search_history['data'])
# [{'query': 'best restaurants nearby', 'timestamp': '2024-01-15T10:30:00Z'}, ...]
```
## Common mistakes to avoid
* Using `https://link.emergedata.ai/link` instead of `https://link.emergedata.ai/link/start`
* Signing URL parameters in the wrong order or signing URL-encoded values
* Treating `state` as a user identifier or skipping state verification
* Asking users to input `uid` or failing to store the callback `uid`
* Querying before `GET /export/status/{uid}` shows `data_ready: true` for your provider
* Exposing `signing_secret` or API tokens in client-side code
## Next steps
Deep dive into consent flow options
Learn about sync vs async queries
Track consent and data export lifecycle changes
Full SDK implementation examples
# Python SDK
Source: https://docs.emergedata.ai/sdks/python
Complete Python implementation for Emerge API
Full Python implementation for integrating with Emerge. Copy these utilities into your project or use as reference.
## Installation
```bash theme={null}
pip install requests
```
For async support:
```bash theme={null}
pip install httpx
```
## Link API Client
```python theme={null}
import hmac
import hashlib
import time
import secrets
from datetime import datetime, timezone
from dataclasses import dataclass
from typing import Optional
from urllib.parse import urlencode
import requests
@dataclass
class EmergeConfig:
client_id: str
signing_secret: str
api_token: str
redirect_uri: str
@dataclass
class LinkResult:
url: str
state: str
@dataclass
class CallbackParams:
status: str # 'success', 'reauthorized', 'failure'
state: str
uid: str
error_code: Optional[str] = None
class EmergeLinkClient:
def __init__(self, config: EmergeConfig):
self.config = config
self._state_store: dict[str, dict] = {}
def create_link_url(self, user_id: str) -> LinkResult:
"""Create a signed link URL for the consent flow."""
# Use ISO 8601 timestamp
timestamp = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
state = secrets.token_hex(16)
# Store state for verification
self._state_store[state] = {
'user_id': user_id,
'created_at': time.time()
}
params = {
'client_id': self.config.client_id,
'redirect_uri': self.config.redirect_uri,
'state': state,
'timestamp': timestamp,
'uid': user_id
}
# Sort and create signature (raw values, NOT URL-encoded)
sorted_items = sorted(params.items())
signature_base = '&'.join(f'{k}={v}' for k, v in sorted_items)
signature = hmac.new(
self.config.signing_secret.encode(),
signature_base.encode(),
hashlib.sha256
).hexdigest()
params['signature'] = signature
return LinkResult(
url=f'https://link.emergedata.ai/link/start?{urlencode(params)}',
state=state
)
def verify_state(self, state: str) -> tuple[bool, Optional[str]]:
"""Verify callback state parameter."""
stored = self._state_store.pop(state, None)
if not stored:
return False, None
# Check expiration (1 hour)
if time.time() - stored['created_at'] > 3600:
return False, None
return True, stored['user_id']
def parse_callback(self, query: dict) -> CallbackParams:
"""Parse callback parameters."""
return CallbackParams(
status=query.get('status', ''),
state=query.get('state', ''),
uid=query.get('uid', ''),
error_code=query.get('error_code')
)
def get_consent_status(self, uid: str) -> dict:
"""Get consent status for a user.
Returns:
dict with 'consents' array containing provider, scopes,
valid_until, status, issued_at for each consent
"""
response = requests.get(
f'https://link.emergedata.ai/consent/status/{uid}',
headers={'Authorization': f'Bearer {self.config.api_token}'}
)
response.raise_for_status()
return response.json()
def get_export_status(self, uid: str) -> dict:
"""Get export status for a user.
Returns:
dict with uid and sources[] where each source contains:
provider, data_ready, data_landed_at, export_status, export_completed_at
"""
response = requests.get(
f'https://link.emergedata.ai/export/status/{uid}',
headers={'Authorization': f'Bearer {self.config.api_token}'}
)
response.raise_for_status()
return response.json()
```
## Query API Client
```python theme={null}
from dataclasses import dataclass
from typing import Optional, Callable, Any
import requests
@dataclass
class QueryParams:
uid: str
ingested_begin: Optional[str] = None
ingested_end: Optional[str] = None
cursor: Optional[str] = None
limit: Optional[int] = None
@dataclass
class QueryResult:
data: list[dict]
count: int
has_more: bool
next_cursor: Optional[str]
applied_ingested_end: Optional[str]
class EmergeQueryClient:
def __init__(self, api_token: str):
self.api_token = api_token
self.base_url = 'https://query.emergedata.ai/v1'
def _request(self, endpoint: str, params: QueryParams) -> QueryResult:
url_params = {'uid': params.uid}
if params.ingested_begin:
url_params['ingested_begin'] = params.ingested_begin
if params.ingested_end:
url_params['ingested_end'] = params.ingested_end
if params.cursor:
url_params['cursor'] = params.cursor
if params.limit:
url_params['limit'] = str(params.limit)
response = requests.get(
f'{self.base_url}{endpoint}',
params=url_params,
headers={'Authorization': f'Bearer {self.api_token}'}
)
response.raise_for_status()
result = response.json()
return QueryResult(
data=result['data'],
count=result.get('count', len(result['data'])),
has_more=result.get('has_more', False),
next_cursor=result.get('next_cursor'),
applied_ingested_end=result.get('applied_ingested_end')
)
def get_search(self, params: QueryParams) -> QueryResult:
"""Get search history (sync)."""
return self._request('/sync/get_search', params)
def get_browsing(self, params: QueryParams) -> QueryResult:
"""Get browsing history (sync)."""
return self._request('/sync/get_browsing', params)
def get_youtube(self, params: QueryParams) -> QueryResult:
"""Get YouTube history (sync)."""
return self._request('/sync/get_youtube', params)
def get_ads(self, params: QueryParams) -> QueryResult:
"""Get ad interactions (sync)."""
return self._request('/sync/get_ads', params)
def get_receipts(self, params: QueryParams) -> QueryResult:
"""Get receipts (sync)."""
return self._request('/sync/get_receipts', params)
def fetch_all(
self,
fetcher: Callable[[QueryParams], QueryResult],
uid: str,
ingested_begin: Optional[str] = None,
ingested_end: Optional[str] = None
) -> tuple[list[dict], Optional[str]]:
"""Fetch all records with automatic pagination.
Returns:
Tuple of (all_data, applied_ingested_end)
"""
all_data = []
cursor = None
applied_end = None
while True:
params = QueryParams(
uid=uid,
ingested_begin=ingested_begin,
ingested_end=ingested_end,
cursor=cursor
)
result = fetcher(params)
all_data.extend(result.data)
applied_end = result.applied_ingested_end
if not result.has_more:
break
cursor = result.next_cursor
return all_data, applied_end
```
## Async Query Client
```python theme={null}
import httpx
from dataclasses import dataclass
from typing import Optional, Callable, Awaitable
class AsyncEmergeQueryClient:
def __init__(self, api_token: str):
self.api_token = api_token
self.base_url = 'https://query.emergedata.ai/v1'
async def _request(self, endpoint: str, params: QueryParams) -> QueryResult:
url_params = {'uid': params.uid}
if params.ingested_begin:
url_params['ingested_begin'] = params.ingested_begin
if params.ingested_end:
url_params['ingested_end'] = params.ingested_end
if params.cursor:
url_params['cursor'] = params.cursor
if params.limit:
url_params['limit'] = str(params.limit)
async with httpx.AsyncClient() as client:
response = await client.get(
f'{self.base_url}{endpoint}',
params=url_params,
headers={'Authorization': f'Bearer {self.api_token}'}
)
response.raise_for_status()
result = response.json()
return QueryResult(
data=result['data'],
count=result.get('count', len(result['data'])),
has_more=result.get('has_more', False),
next_cursor=result.get('next_cursor'),
applied_ingested_end=result.get('applied_ingested_end')
)
async def get_search(self, params: QueryParams) -> QueryResult:
return await self._request('/sync/get_search', params)
async def get_browsing(self, params: QueryParams) -> QueryResult:
return await self._request('/sync/get_browsing', params)
async def get_youtube(self, params: QueryParams) -> QueryResult:
return await self._request('/sync/get_youtube', params)
async def get_ads(self, params: QueryParams) -> QueryResult:
return await self._request('/sync/get_ads', params)
async def get_receipts(self, params: QueryParams) -> QueryResult:
return await self._request('/sync/get_receipts', params)
async def fetch_all(
self,
fetcher: Callable[[QueryParams], Awaitable[QueryResult]],
uid: str,
ingested_begin: Optional[str] = None
) -> tuple[list[dict], Optional[str]]:
all_data = []
cursor = None
applied_end = None
while True:
params = QueryParams(
uid=uid,
ingested_begin=ingested_begin,
cursor=cursor
)
result = await fetcher(params)
all_data.extend(result.data)
applied_end = result.applied_ingested_end
if not result.has_more:
break
cursor = result.next_cursor
return all_data, applied_end
```
## Webhook Handler
```python theme={null}
import hmac
import hashlib
import json
from dataclasses import dataclass
from typing import Literal
WebhookEvent = Literal[
'consent.given',
'consent.revoked',
'consent.expiring',
'consent.reauthorized',
'data.ready',
'data.failed'
]
@dataclass
class WebhookPayload:
event: WebhookEvent
timestamp: str
uid: str
client_id: str
sources: list[dict]
class EmergeWebhookHandler:
def __init__(self, webhook_secret: str):
self.secret = webhook_secret
def verify_signature(self, payload: bytes, signature: str) -> bool:
"""Verify webhook signature."""
expected = hmac.new(
self.secret.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected)
def parse_webhook(self, raw_body: bytes, signature: str) -> WebhookPayload:
"""Parse and verify webhook."""
if not self.verify_signature(raw_body, signature):
raise ValueError('Invalid webhook signature')
data = json.loads(raw_body)
return WebhookPayload(
event=data['event'],
timestamp=data['timestamp'],
uid=data['uid'],
client_id=data['client_id'],
sources=data.get('sources', [])
)
```
## Usage Example
```python theme={null}
import os
# Initialize clients
config = EmergeConfig(
client_id=os.environ['EMERGE_CLIENT_ID'],
signing_secret=os.environ['EMERGE_SIGNING_SECRET'],
api_token=os.environ['EMERGE_API_TOKEN'],
redirect_uri='https://yourapp.com/emerge/callback'
)
link_client = EmergeLinkClient(config)
query_client = EmergeQueryClient(os.environ['EMERGE_API_TOKEN'])
# Create consent link
result = link_client.create_link_url(user_id='psub_d4e5f6789012345678901234abcdef01')
print(f'Consent URL: {result.url}')
# After consent, query data
search_result = query_client.get_search(QueryParams(uid='psub_d4e5f6789012345678901234abcdef01'))
print(f'Search queries: {search_result.count}')
# Fetch all with pagination
all_browsing, applied_end = query_client.fetch_all(
query_client.get_browsing,
uid='psub_d4e5f6789012345678901234abcdef01'
)
print(f'Total browsing entries: {len(all_browsing)}')
# Delta sync - use applied_end for next sync
next_sync_start = applied_end
```
## FastAPI Integration
```python theme={null}
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
import os
app = FastAPI()
# Initialize clients
config = EmergeConfig(
client_id=os.environ['EMERGE_CLIENT_ID'],
signing_secret=os.environ['EMERGE_SIGNING_SECRET'],
api_token=os.environ['EMERGE_API_TOKEN'],
redirect_uri='https://yourapp.com/emerge/callback'
)
link_client = EmergeLinkClient(config)
webhook_handler = EmergeWebhookHandler(os.environ['EMERGE_WEBHOOK_SECRET'])
@app.get('/connect')
async def connect(request: Request):
user_id = request.session.get('user_id')
result = link_client.create_link_url(user_id=user_id)
# Store state in session
request.session['emerge_state'] = result.state
return RedirectResponse(result.url)
@app.get('/emerge/callback')
async def callback(request: Request):
params = link_client.parse_callback(dict(request.query_params))
# Verify state
valid, user_id = link_client.verify_state(params.state)
if not valid:
raise HTTPException(status_code=400, detail='Invalid state')
if params.status in ('success', 'reauthorized'):
return RedirectResponse('/dashboard?connected=true')
return RedirectResponse(f'/error?code={params.error_code}')
@app.post('/webhooks/emerge')
async def webhook(request: Request):
body = await request.body()
signature = request.headers.get('x-signature', '')
try:
payload = webhook_handler.parse_webhook(body, signature)
except ValueError:
raise HTTPException(status_code=401, detail='Invalid signature')
if payload.event == 'consent.given':
print(f"Consent granted for user {payload.uid}")
elif payload.event == 'consent.revoked':
print(f"Consent revoked for user {payload.uid}")
elif payload.event == 'consent.expiring':
print(f"Consent expiring for user {payload.uid}")
elif payload.event == 'data.ready':
print(f"Data ready for user {payload.uid}: {payload.sources}")
elif payload.event == 'data.failed':
print(f"Data export failed for user {payload.uid}: {payload.sources}")
return {'status': 'ok'}
```
# TypeScript SDK
Source: https://docs.emergedata.ai/sdks/typescript
Complete TypeScript implementation for Emerge API
Full TypeScript implementation for integrating with Emerge. Copy these utilities into your project or use as reference.
## Installation
No SDK package required. These examples use standard Node.js crypto and fetch APIs.
```bash theme={null}
# For Node.js < 18, install node-fetch
npm install node-fetch
```
## Link API Client
```typescript theme={null}
import crypto from 'crypto';
interface EmergeConfig {
clientId: string;
signingSecret: string;
apiToken: string;
redirectUri: string;
}
interface LinkParams {
userId: string;
}
interface CallbackParams {
status: 'success' | 'reauthorized' | 'failure';
state: string;
uid: string;
errorCode?: string;
}
class EmergeLinkClient {
private config: EmergeConfig;
private stateStore: Map;
constructor(config: EmergeConfig) {
this.config = config;
this.stateStore = new Map();
}
/**
* Create a signed link URL for the consent flow
*/
createLinkUrl(params: LinkParams): { url: string; state: string } {
// Use ISO 8601 timestamp
const timestamp = new Date().toISOString();
const state = crypto.randomBytes(16).toString('hex');
// Store state for verification
this.stateStore.set(state, {
userId: params.userId,
createdAt: Date.now()
});
const urlParams: Record = {
client_id: this.config.clientId,
redirect_uri: this.config.redirectUri,
state,
timestamp,
uid: params.userId
};
// Sort and create signature (raw values, NOT URL-encoded)
const sortedKeys = Object.keys(urlParams).sort();
const signatureBase = sortedKeys
.map(key => `${key}=${urlParams[key]}`)
.join('&');
const signature = crypto
.createHmac('sha256', this.config.signingSecret)
.update(signatureBase)
.digest('hex');
// Build final URL (URLSearchParams handles encoding)
const finalParams = new URLSearchParams(urlParams);
finalParams.append('signature', signature);
return {
url: `https://link.emergedata.ai/link/start?${finalParams.toString()}`,
state
};
}
/**
* Verify callback state parameter
*/
verifyState(state: string): { valid: boolean; userId?: string } {
const stored = this.stateStore.get(state);
if (!stored) {
return { valid: false };
}
// Clean up state after verification
this.stateStore.delete(state);
// Check expiration (1 hour)
if (Date.now() - stored.createdAt > 3600000) {
return { valid: false };
}
return { valid: true, userId: stored.userId };
}
/**
* Parse callback parameters
*/
parseCallback(query: Record): CallbackParams {
return {
status: query.status as CallbackParams['status'],
state: query.state,
uid: query.uid,
errorCode: query.error_code
};
}
/**
* Get consent status for a user
*/
async getConsentStatus(uid: string): Promise<{
consents: Array<{
provider: string;
scopes: string[];
valid_until: string;
status: string;
issued_at: string;
}>;
}> {
const response = await fetch(
`https://link.emergedata.ai/consent/status/${uid}`,
{
headers: {
'Authorization': `Bearer ${this.config.apiToken}`
}
}
);
if (!response.ok) {
throw new Error(`Consent status failed: ${response.status}`);
}
return response.json();
}
/**
* Get export status for a user
*/
async getExportStatus(uid: string): Promise<{
uid: string;
sources: Array<{
provider: string;
data_ready: boolean;
data_landed_at?: string | null;
export_status?: string | null;
export_completed_at?: string | null;
}>;
}> {
const response = await fetch(
`https://link.emergedata.ai/export/status/${uid}`,
{
headers: {
'Authorization': `Bearer ${this.config.apiToken}`
}
}
);
if (!response.ok) {
throw new Error(`Export status failed: ${response.status}`);
}
return response.json();
}
}
```
## Query API Client
```typescript theme={null}
interface QueryParams {
uid: string;
ingestedBegin?: string;
ingestedEnd?: string;
cursor?: string;
limit?: number;
}
interface QueryResult {
data: T[];
count: number;
hasMore: boolean;
nextCursor?: string;
appliedIngestedEnd?: string;
}
interface SearchEntry {
user_id: string;
event_id: number;
url: string | null;
title: string | null;
query: string | null;
intent: string | null;
category: string | null;
brands: string[];
timestamp: string;
ingested_at: string;
}
interface BrowsingEntry {
user_id: string;
event_id: number;
url: string | null;
title: string | null;
page_category: string | null;
category: string | null;
brands: string[];
timestamp: string;
ingested_at: string;
}
interface YoutubeEntry {
user_id: string;
event_id: number;
url: string | null;
title: string | null;
category: string | null;
brands: string[];
timestamp: string;
ingested_at: string;
}
interface AdsEntry {
user_id: string;
event_id: number;
source_domain: string | null;
landing_domain: string | null;
url: string | null;
title: string | null;
category: string | null;
brands: Array;
ad_network: string | null;
timestamp: string;
ingested_at: string;
}
interface ReceiptsEntry {
user_id: string;
event_id: number;
subject: string | null;
retailer_name: string | null;
receipt_currency: string | null;
total_value: number | null;
category: string | null;
brands: Array;
items: Array<{
name: string | null;
quantity: number | null;
unit_price: number | null;
brand: string | null;
category: string | null;
}>;
timestamp: string;
ingested_at: string;
}
class EmergeQueryClient {
private apiToken: string;
private baseUrl = 'https://query.emergedata.ai/v1';
constructor(apiToken: string) {
this.apiToken = apiToken;
}
private async request(endpoint: string, params: QueryParams): Promise> {
const url = new URL(`${this.baseUrl}${endpoint}`);
url.searchParams.set('uid', params.uid);
if (params.ingestedBegin) {
url.searchParams.set('ingested_begin', params.ingestedBegin);
}
if (params.ingestedEnd) {
url.searchParams.set('ingested_end', params.ingestedEnd);
}
if (params.cursor) {
url.searchParams.set('cursor', params.cursor);
}
if (params.limit) {
url.searchParams.set('limit', params.limit.toString());
}
const response = await fetch(url.toString(), {
headers: {
'Authorization': `Bearer ${this.apiToken}`
}
});
if (!response.ok) {
throw new Error(`Query failed: ${response.status}`);
}
const result = await response.json();
return {
data: result.data,
count: result.count,
hasMore: result.has_more,
nextCursor: result.next_cursor,
appliedIngestedEnd: result.applied_ingested_end
};
}
/**
* Get search history (sync)
*/
async getSearch(params: QueryParams): Promise> {
return this.request('/sync/get_search', params);
}
/**
* Get browsing history (sync)
*/
async getBrowsing(params: QueryParams): Promise> {
return this.request('/sync/get_browsing', params);
}
/**
* Get YouTube history (sync)
*/
async getYoutube(params: QueryParams): Promise> {
return this.request('/sync/get_youtube', params);
}
/**
* Get ad interactions (sync)
*/
async getAds(params: QueryParams): Promise> {
return this.request('/sync/get_ads', params);
}
/**
* Get receipts (sync)
*/
async getReceipts(params: QueryParams): Promise> {
return this.request('/sync/get_receipts', params);
}
/**
* Fetch all records with automatic pagination
*/
async fetchAll(
fetcher: (params: QueryParams) => Promise>,
params: Omit
): Promise<{ data: T[]; appliedIngestedEnd?: string }> {
const allData: T[] = [];
let cursor: string | undefined;
let appliedEnd: string | undefined;
do {
const result = await fetcher({ ...params, cursor });
allData.push(...result.data);
appliedEnd = result.appliedIngestedEnd;
cursor = result.hasMore ? result.nextCursor : undefined;
} while (cursor);
return { data: allData, appliedIngestedEnd: appliedEnd };
}
}
```
## Webhook Handler
```typescript theme={null}
import crypto from 'crypto';
type WebhookEvent =
| 'consent.given'
| 'consent.revoked'
| 'consent.expiring'
| 'consent.reauthorized'
| 'data.ready'
| 'data.failed';
interface WebhookPayload {
event: WebhookEvent;
timestamp: string;
uid: string;
client_id: string;
sources: Array>;
}
class EmergeWebhookHandler {
private secret: string;
constructor(webhookSecret: string) {
this.secret = webhookSecret;
}
/**
* Verify webhook signature
*/
verifySignature(payload: Buffer | string, signature: string): boolean {
const expected = crypto
.createHmac('sha256', this.secret)
.update(payload)
.digest('hex');
const signatureBuf = Buffer.from(signature, 'hex');
const expectedBuf = Buffer.from(expected, 'hex');
if (signatureBuf.length !== expectedBuf.length) {
return false;
}
return crypto.timingSafeEqual(signatureBuf, expectedBuf);
}
/**
* Parse and verify webhook
*/
parseWebhook(rawBody: Buffer, signature: string): WebhookPayload {
if (!this.verifySignature(rawBody, signature)) {
throw new Error('Invalid webhook signature');
}
return JSON.parse(rawBody.toString());
}
}
```
## Usage Example
```typescript theme={null}
// Initialize clients
const linkClient = new EmergeLinkClient({
clientId: process.env.EMERGE_CLIENT_ID!,
signingSecret: process.env.EMERGE_SIGNING_SECRET!,
apiToken: process.env.EMERGE_API_TOKEN!,
redirectUri: 'https://yourapp.com/emerge/callback'
});
const queryClient = new EmergeQueryClient(process.env.EMERGE_API_TOKEN!);
// Create consent link
const { url, state } = linkClient.createLinkUrl({
userId: 'psub_d4e5f6789012345678901234abcdef01'
});
// After consent, query data
const searchHistory = await queryClient.getSearch({
uid: 'psub_d4e5f6789012345678901234abcdef01'
});
// Fetch all with pagination
const { data: allBrowsing, appliedIngestedEnd } = await queryClient.fetchAll(
(params) => queryClient.getBrowsing(params),
{ uid: 'psub_d4e5f6789012345678901234abcdef01' }
);
// Delta sync - use appliedIngestedEnd for next sync
const nextSyncStart = appliedIngestedEnd;
```
## Express.js Integration
```typescript theme={null}
import express from 'express';
const app = express();
// Initialize clients
const linkClient = new EmergeLinkClient({
clientId: process.env.EMERGE_CLIENT_ID!,
signingSecret: process.env.EMERGE_SIGNING_SECRET!,
apiToken: process.env.EMERGE_API_TOKEN!,
redirectUri: 'https://yourapp.com/emerge/callback'
});
const webhookHandler = new EmergeWebhookHandler(
process.env.EMERGE_WEBHOOK_SECRET!
);
// Create consent link
app.get('/connect', (req, res) => {
const userId = req.session.userId;
const { url, state } = linkClient.createLinkUrl({ userId });
// Store state in session for verification
req.session.emergeState = state;
res.redirect(url);
});
// Handle callback
app.get('/emerge/callback', async (req, res) => {
const params = linkClient.parseCallback(req.query as Record);
// Verify state
const { valid } = linkClient.verifyState(params.state);
if (!valid) {
return res.status(400).send('Invalid state');
}
if (params.status === 'success' || params.status === 'reauthorized') {
res.redirect('/dashboard?connected=true');
} else {
res.redirect(`/error?code=${params.errorCode}`);
}
});
// Handle webhooks
app.post('/webhooks/emerge', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-signature'] as string;
try {
const payload = webhookHandler.parseWebhook(req.body, signature);
switch (payload.event) {
case 'consent.given':
console.log(`Consent granted for user ${payload.uid}`);
break;
case 'consent.revoked':
console.log(`Consent revoked for user ${payload.uid}`);
break;
case 'data.ready':
console.log(`Data ready for user ${payload.uid}`, payload.sources);
break;
case 'data.failed':
console.error(`Data export failed for user ${payload.uid}`, payload.sources);
break;
default:
console.log(`Unhandled webhook event: ${payload.event}`);
}
res.status(200).send('OK');
} catch (error) {
res.status(401).send('Invalid signature');
}
});
```