### MCP Signal Server Setup and SDK Integration
Source: https://developer.zeroclick.ai/docs/signal-collection/setup
This section details how to set up and connect to the MCP Signal Server using the official SDK. It covers prerequisites, the server URL, and provides a TypeScript example for SDK integration.
```APIDOC
## MCP Signal Server Setup and SDK Integration
### Description
Configure and connect to the MCP Signal Server. This guide walks you through integrating the MCP Signal Server into your AI agent.
### Prerequisites
* A [ZeroClick API key](https://developer.zeroclick.ai/apikeys) (contact [developers@zeroclick.ai](mailto:developers@zeroclick.ai) for access)
* An AI agent that supports the Model Context Protocol (MCP)
### Server URL
`https://zeroclick.dev/mcp/v2`
The server uses MCP over HTTP with Server-Sent Events (SSE) for streaming responses.
### SDK Integration (TypeScript / JavaScript)
Use the official MCP SDK with the remote transport:
```bash
npm install @modelcontextprotocol/sdk
```
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
// Create the transport with your headers
const transport = new StreamableHTTPClientTransport(
new URL("https://zeroclick.dev/mcp/v2"),
{
requestInit: {
headers: {
"x-zc-api-key": process.env.ZEROCLICK_API_KEY
}
}
}
);
// Create and connect the client
const client = new Client({
name: "your-agent",
version: "1.0.0"
});
await client.connect(transport);
// List available tools to pass to your LLM
const { tools } = await client.listTools();
console.log("Available tools:", tools);
```
See the [Headers Reference](/signal-collection/headers) for the complete list of available headers.
```
--------------------------------
### Fetch Offers API
Source: https://developer.zeroclick.ai/docs/quickstart
Make a POST request to /api/v2/offers to fetch personalized offers based on your query. Supports both server-side and client-side methods.
```APIDOC
## POST /api/v2/offers
### Description
Fetches personalized offers based on a query. Can be used for server-side or client-side integrations.
### Method
POST
### Endpoint
https://zeroclick.dev/api/v2/offers
### Parameters
#### Query Parameters
None
#### Request Body
- **method** (string) - Required - Specifies the integration method ('server' or 'client').
- **ipAddress** (string) - Required for 'server' method - The IP address of the client.
- **userAgent** (string) - Optional but recommended - The User-Agent string of the client.
- **query** (string) - Required - The search query for offers.
- **limit** (integer) - Optional - The maximum number of offers to return.
### Request Example
```json
{
"method": "server",
"ipAddress": "clientIpAddress",
"userAgent": "clientUserAgent",
"query": "best running shoes",
"limit": 3
}
```
### Response
#### Success Response (200)
- **offers** (array) - An array of offer objects.
- **id** (string) - Unique identifier for the offer.
- **title** (string) - The title of the offer.
- **subtitle** (string) - A brief subtitle for the offer.
- **content** (string) - Detailed content of the offer.
- **cta** (string) - Call to action text.
- **clickUrl** (string) - The URL to redirect to when the offer is clicked.
- **imageUrl** (string) - URL of the offer's image.
- **brand** (object) - Information about the brand.
- **name** (string) - Brand name.
- **url** (string) - Brand website URL.
- **price** (object) - Pricing information.
- **amount** (string) - The price amount.
- **currency** (string) - The currency code (e.g., USD).
#### Response Example
```json
[
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Nike Air Zoom Pegasus 40",
"subtitle": "Premium running shoe for daily training",
"content": "Responsive cushioning and breathable mesh upper...",
"cta": "Shop Now",
"clickUrl": "https://zero.click/1234...",
"imageUrl": "https://example.com/pegasus40.jpg",
"brand": {
"name": "Nike",
"url": "https://nike.com"
},
"price": {
"amount": "129.99",
"currency": "USD"
}
}
]
```
When calling from the browser, use `method: "client"`. IP and User-Agent are extracted automatically from request headers. Requires a public API key.
```javascript
const response = await fetch("https://zeroclick.dev/api/v2/offers", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-zc-api-key": "your-public-api-key"
},
body: JSON.stringify({
method: "client",
query: "best running shoes",
limit: 3
})
});
```
```
--------------------------------
### Install MCP SDK for TypeScript/JavaScript
Source: https://developer.zeroclick.ai/docs/signal-collection/setup
Installs the official MCP SDK using npm. This is a prerequisite for integrating the MCP Signal Server into your AI agent using TypeScript or JavaScript.
```bash
npm install @modelcontextprotocol/sdk
```
--------------------------------
### Fetch Offers using JavaScript (Server-side)
Source: https://developer.zeroclick.ai/docs/quickstart
Fetches personalized offers by making a POST request to the /api/v2/offers endpoint. Requires a server-side API key and client's IP address and user agent. Returns a JSON array of offer objects.
```javascript
const response = await fetch("https://zeroclick.dev/api/v2/offers", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-zc-api-key": "your-api-key" // Get from developer dashboard
},
body: JSON.stringify({
method: "server",
ipAddress: clientIpAddress, // required for server method
userAgent: clientUserAgent, // optional but recommended
query: "best running shoes",
limit: 3
})
});
const offers = await response.json();
console.log(offers);
```
--------------------------------
### Track Impressions API
Source: https://developer.zeroclick.ai/docs/quickstart
Make a POST request to /api/v2/impressions to track when offers are displayed to users. This endpoint must be called from client devices.
```APIDOC
## POST /api/v2/impressions
### Description
Tracks the impressions of offers when they are displayed to users. This request must originate from the end user's device.
### Method
POST
### Endpoint
https://zeroclick.dev/api/v2/impressions
### Parameters
#### Query Parameters
None
#### Request Body
- **ids** (array of strings) - Required - A list of offer IDs that have been displayed.
### Request Example
```json
{
"ids": [
"a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"f0e9d8c7-b6a5-4321-fedc-ba9876543210"
]
}
```
### Response
#### Success Response (200)
Typically returns an empty response or a success confirmation.
#### Response Example
```json
{}
```
Impression requests must originate from the end user's device, not your server. Requests will be [rate limited per IP](/rate-limiting#ip-based-rate-limiting).
```
--------------------------------
### Fetch Offers using JavaScript (Client-side)
Source: https://developer.zeroclick.ai/docs/quickstart
Fetches personalized offers by making a POST request to the /api/v2/offers endpoint using a public API key. Suitable for client-side integration where IP address and user agent are automatically handled. Returns a JSON array of offer objects.
```javascript
const response = await fetch("https://zeroclick.dev/api/v2/offers", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-zc-api-key": "your-public-api-key"
},
body: JSON.stringify({
method: "client",
query: "best running shoes",
limit: 3
})
});
```
--------------------------------
### Track Impressions using JavaScript
Source: https://developer.zeroclick.ai/docs/quickstart
Sends impression data to the /api/v2/impressions endpoint. This is crucial for tracking when offers are displayed to users and must be called from client devices. It takes an array of offer IDs as input.
```javascript
// Track all displayed offers
await fetch("https://zeroclick.dev/api/v2/impressions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
ids: offers.map(offer => offer.id)
})
});
```
--------------------------------
### Render Offers using JavaScript
Source: https://developer.zeroclick.ai/docs/quickstart
Renders fetched offer data into HTML elements within the UI. It iterates through the offers array and dynamically creates 'offer-card' divs, populating them with offer details like image, title, content, call-to-action, and price.
```javascript
offers.forEach(offer => {
const card = `
${offer.title}
${offer.content}
${offer.cta}
${offer.price.currency} ${offer.price.amount}
`;
document.querySelector('#offers').innerHTML += card;
});
```
--------------------------------
### ZeroClick API Offer Response Example
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
This is an example of a successful response (HTTP 200) from the /api/v2/offers endpoint. It returns an array of offer objects, each containing details like title, description, call-to-action, click URL, image, brand information, product details, and pricing with potential discounts.
```json
[
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Nike Air Zoom Pegasus 40",
"subtitle": "Premium running shoe for daily training",
"content": ">- Responsive cushioning and breathable mesh upper for comfortable miles.",
"cta": "Shop Now",
"clickUrl": "https://https://zeroclick.dev/api/v2/clicks?id=a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"imageUrl": "https://example.com/pegasus40.jpg",
"brand": {
"name": "Nike",
"description": "Global sports and athletic footwear brand",
"url": "https://nike.com",
"iconUrl": "https://example.com/nike-logo.png"
},
"product": {
"productId": "nike-pegasus-40",
"title": "Air Zoom Pegasus 40",
"category": "Running Shoes",
"availability": "in_stock"
},
"price": {
"amount": "129.99",
"currency": "USD",
"originalPrice": "139.99",
"discount": "7%"
}
}
]
```
--------------------------------
### Example Full Header Set (TypeScript)
Source: https://developer.zeroclick.ai/docs/signal-collection/headers
An example demonstrating how to construct a complete set of headers for the MCP Signal Server in TypeScript, including required, user context, application context, and privacy-safe PII headers.
```typescript
const headers = {
// Required
"x-zc-api-key": "your-api-key",
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
// User context
"x-zc-user-id": "user-12345",
"x-zc-user-session-id": "session-abc-789",
"x-zc-user-locale": "en-US",
"x-zc-grouping-id": "campaign-summer-2024",
"x-zc-user-ip": clientIp,
"x-zc-user-agent": req.headers["user-agent"],
// Application context
"x-zc-llm-model": "openai/gpt-4o",
// Privacy-safe PII (hashed)
"x-zc-user-email-sha256": sha256(email.toLowerCase().trim()),
"x-zc-user-phone-sha256": sha256(phone)
};
```
--------------------------------
### Connection Lifecycle Management
Source: https://developer.zeroclick.ai/docs/signal-collection/setup
Understand how to manage the MCP client's connection lifecycle, including best practices for production environments and graceful shutdown.
```APIDOC
## Connection Lifecycle Management
### Description
The MCP client maintains a persistent connection. For production use, follow these guidelines for managing the connection lifecycle.
### Best Practices
1. **Create one client per user session**: Do not share clients across different users.
2. **Handle reconnection**: Implement retry logic to manage network failures.
3. **Close connections**: Ensure you call `client.close()` when a user session ends.
### Graceful Shutdown Example
```typescript
// Graceful shutdown
process.on("SIGTERM", async () => {
await client.close();
process.exit(0);
});
```
### Next Steps
* [Headers Reference](/signal-collection/headers) - Configure context headers
* [Tool Reference](/signal-collection/tools) - Understand the broadcast_signal tool
* [Testing](/signal-collection/testing) - Verify your integration
```
--------------------------------
### Example Simple Interest Signal (JSON)
Source: https://developer.zeroclick.ai/docs/signal-collection/tools
An example demonstrating a simple signal object for the broadcast_signal tool, indicating user interest in 'wireless headphones' with a confidence score.
```json
{
"signals": [{
"category": "interest",
"confidence": 0.75,
"subject": "wireless headphones"
}]
}
```
--------------------------------
### IAB Content Taxonomy Example (JSON)
Source: https://developer.zeroclick.ai/docs/signal-collection/tools
This JSON example demonstrates how to include IAB Content Taxonomy classifications within a signal. It specifies the type, version, and an array of relevant IAB category IDs.
```json
{
"userId": "user-12345",
"ipAddress": "your-user-ip-address",
"signals": [{
"category": "interest",
"confidence": 0.85,
"subject": "Running & Jogging",
"relatedSubjects": ["Athletic Shoes", "Sportswear"],
"iab": {
"type": "content",
"version": "2.2",
"ids": ["607", "606", "123"]
}
}]
}
```
--------------------------------
### Connect to MCP Signal Server with TypeScript/JavaScript
Source: https://developer.zeroclick.ai/docs/signal-collection/setup
Establishes a connection to the MCP Signal Server using the SDK. It configures the transport with the server URL and API key, creates a client instance, connects to the server, and lists available tools.
```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
// Create the transport with your headers
const transport = new StreamableHTTPClientTransport(
new URL("https://zeroclick.dev/mcp/v2"),
{
requestInit: {
headers: {
"x-zc-api-key": process.env.ZEROCLICK_API_KEY
}
}
}
);
// Create and connect the client
const client = new Client({
name: "your-agent",
version: "1.0.0"
});
await client.connect(transport);
// List available tools to pass to your LLM
const { tools } = await client.listTools();
console.log("Available tools:", tools);
```
--------------------------------
### Get ZeroClick Offers
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
Returns an array of offers based on the provided query and user context. Supports both client-side and server-side requests.
```APIDOC
## GET /offers
### Description
Returns an array of offers based on the provided query and user context. Each offer includes an `id` that must be used for impression tracking.
### Method
GET
### Endpoint
/offers
### Query Parameters
- **method** (string) - Required - Specifies the request method. Use `client` for browser-based requests (IP/UA extracted from headers) or `server` for backend requests.
- **ipAddress** (string) - Optional - Required if `method` is `server`. The IP address of the user.
### Response
#### Success Response (200)
- **offers** (array) - An array of offer objects. Each offer object contains:
- **id** (string) - The unique identifier for the offer, used for impression tracking.
- [Other offer-specific fields]
#### Response Example
```json
{
"offers": [
{
"id": "offer_123",
"title": "Example Offer",
"description": "This is a sample offer."
}
]
}
```
```
--------------------------------
### ZeroClick API Error Response Example (400 Bad Request)
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
This example shows a typical error response (HTTP 400 Bad Request) from the ZeroClick API. It indicates that the input parameters were invalid. The response body contains an error object with a message explaining the specific issue, such as a missing required field for a particular method.
```json
{
"error": {
"message": ">- client ipAddress is required to be forwarded for server method"
}
}
```
--------------------------------
### IAB Audience Taxonomy Example (JSON)
Source: https://developer.zeroclick.ai/docs/signal-collection/tools
This JSON example illustrates the inclusion of IAB Audience Taxonomy classifications. It uses `category: "user_context"` and specifies the type, version, and an array of audience segment IDs.
```json
{
"userId": "user-12345",
"ipAddress": "your-user-ip-address",
"signals": [{
"category": "user_context",
"confidence": 0.9,
"subject": "Fitness Enthusiasts",
"relatedSubjects": ["Outdoor Adventurers", "Marathon Runners"],
"iab": {
"type": "audience",
"version": "1.1",
"ids": ["1234", "1235", "1236"]
}
}]
}
```
--------------------------------
### Server-Side Offer Fetching and Impression Tracking (JavaScript)
Source: https://developer.zeroclick.ai/docs/offers/rest-api
Provides a JavaScript example for server-side integration. It demonstrates fetching offers using a POST request with specific headers and body parameters, then logging the offer details. Finally, it shows how to track impressions from the client device.
```javascript
// 1. Fetch offers
const response = await fetch("https://zeroclick.dev/api/v2/offers", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-zc-api-key": "your-api-key"
},
body: JSON.stringify({
method: "server",
ipAddress: clientIpAddress, // required
userAgent: clientUserAgent, // recommended
query: "best running shoes",
limit: 3
})
});
const offers = await response.json();
// 2. Render offers in your UI
offers.forEach(offer => {
console.log(offer.title, offer.clickUrl, offer.price);
});
// 3. Track impressions (must be called from the client device)
await fetch("https://zeroclick.dev/api/v2/impressions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
ids: offers.map(offer => offer.id)
})
});
```
--------------------------------
### Improving Offer Relevance with Query Parameter
Source: https://developer.zeroclick.ai/docs/offers/rest-api
Demonstrates how to use the 'query' parameter to enhance the relevance of fetched offers. It shows examples using keywords, a full message, and a null value for broader targeting.
```javascript
query: "running shoes marathon training"
```
```javascript
query: "I'm running a marathon this fall and looking for new training shoes."
```
```javascript
query: null
```
--------------------------------
### Get ZeroClick Offers (Request with Identity)
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
This snippet illustrates how to request offers by including hashed user identity information (email or phone) for improved personalization. The `method` is set to `client`, and the API will use the provided `userEmailSha256` or `userPhoneSha256` for matching. The response is an array of offer objects.
```json
{
"method": "client",
"query": "project management software",
"userEmailSha256": "a1b2c3d4e5f6...",
"limit": 3
}
```
--------------------------------
### Get Offers API
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
Retrieves a list of offers based on the provided query and user context. Supports client-side and server-side sourcing of user information.
```APIDOC
## POST /websites/developer_zeroclick_ai/offers
### Description
Retrieves a list of offers based on the provided query and user context. Supports client-side and server-side sourcing of user information.
### Method
POST
### Endpoint
/websites/developer_zeroclick_ai/offers
### Parameters
#### Query Parameters
- **query** (string) - Required - Search query for offers. Example: "best running shoes", "cloud hosting solutions"
- **limit** (integer) - Optional - Maximum number of offers to return. Defaults to tenant settings or 1. Max value is 8.
#### Request Body
- **method** (string) - Required - Enum: "client", "server". Determines how IP address and User-Agent are sourced. Use "client" when making requests directly from the browser (IP/UA extracted from request headers). Use "server" when making requests from your backend (must provide ipAddress in body).
- **ipAddress** (string) - Required (if method is "server") - Client IP address. Ignored when method is "client".
- **userAgent** (string) - Optional - Client User-Agent string. Ignored when method is "client".
- **origin** (string) - Optional - Request origin/referer URL. Ignored when method is "client".
- **userEmailSha256** (string) - Optional - SHA-256 hash of user email address for identity matching (lowercase, trimmed before hashing).
- **userPhoneNumberSha256** (string) - Optional - SHA-256 hash of user phone number for identity matching (E.164 format before hashing).
- **groupingId** (string) - Optional - Tenant-defined grouping ID for analytics segmentation.
- **userId** (string) - Optional - Tenant-defined user ID for analytics and personalization.
- **userSessionId** (string) - Optional - Tenant-defined session ID for session-level tracking.
- **userLocale** (string) - Optional - User locale/language code (e.g., "en-US", "es-MX").
### Request Example
```json
{
"method": "client",
"query": "best running shoes",
"limit": 5,
"userLocale": "en-US"
}
```
### Response
#### Success Response (200)
- **offers** (array) - List of Offer objects.
- **title** (string) - Optional - Title of the offer.
- **subtitle** (string) - Optional - Optional subtitle or brief description of the offer.
- **content** (string) - Optional - Detailed content or description of the offer.
- **cta** (string) - Optional - Call to action text for the offer, to be used for links or buttons.
- **clickUrl** (string) - URL to navigate to when the offer is clicked.
- **imageUrl** (string) - Optional - Optional image URL representing the offer.
- **metadata** (object) - Optional - Any additional metadata specific to the offer.
- **context** (string) - Optional - Any additional context about the offer such as "great for gifts", "popular", etc.
- **brand** (object) - Optional - Brand information for the offer.
- **name** (string) - Name of the brand.
- **description** (string) - Optional - Description of the brand.
- **url** (string) - Optional - URL of the brand.
#### Response Example
```json
{
"offers": [
{
"title": "Premium Running Shoes",
"subtitle": "Lightweight and comfortable",
"content": "Experience unparalleled comfort and performance with our latest running shoes. Designed for marathon runners and everyday athletes.",
"cta": "Shop Now",
"clickUrl": "https://example.com/products/running-shoes",
"imageUrl": "https://example.com/images/running-shoes.jpg",
"metadata": {
"color": "blue",
"size": "10"
},
"context": "popular",
"brand": {
"name": "SpeedyFeet",
"description": "High-performance athletic footwear.",
"url": "https://example.com/brands/speedyfeet"
}
}
]
}
```
#### Error Responses
- **401 Unauthorized**: Missing or invalid API key.
- **429 Too Many Requests**: Rate limit exceeded. The `retry-after` header indicates how many seconds to wait before retrying.
- **500 Internal Server Error**: An unexpected error occurred on the server.
```
--------------------------------
### Get ZeroClick Offers (Server-Side Request)
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
This snippet shows a server-side request to the ZeroClick API for offers. It requires explicit `ipAddress` and `userAgent` to be provided in the request body. Optional parameters like `userId` and `groupingId` can be included for enhanced personalization. The response is an array of offer objects.
```json
{
"method": "server",
"ipAddress": "203.0.113.42",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"query": "cloud hosting solutions",
"limit": 5,
"userId": "user-12345",
"groupingId": "premium-tier"
}
```
--------------------------------
### Get ZeroClick Offers (Client-Side Request)
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
This snippet demonstrates how to request offers from the ZeroClick API using the client-side method. It automatically extracts the IP address and User-Agent from the request headers. The response is an array of offer objects, each with an ID for impression tracking.
```json
{
"method": "client",
"query": "best running shoes",
"limit": 3
}
```
--------------------------------
### Get Developer Analytics Metrics
Source: https://developer.zeroclick.ai/docs/api-reference/analytics/get-developer-analytics-metrics
Returns aggregated ad performance metrics for your tenant over a time range. You can group results by client/grouping and optionally by time granularity (daily or hourly).
```APIDOC
## GET /analytics/metrics
### Description
Fetches aggregated ad performance metrics for your tenant over a specified time range. Metrics can be grouped by client or grouping, and optionally by time granularity (daily or hourly).
### Method
GET
### Endpoint
/analytics/metrics
### Parameters
#### Query Parameters
- **startDate** (string) - Required - The start date for the metrics range (YYYY-MM-DD).
- **endDate** (string) - Required - The end date for the metrics range (YYYY-MM-DD).
- **timeGranularity** (string) - Optional - The granularity for time-based grouping. Accepts `HOURLY` or `DAILY`. Mutually exclusive.
- **tenantClientIds** (array) - Optional - An array of tenant client IDs to filter metrics by. Maximum 100 items.
- **tenantGroupingIds** (array) - Optional - An array of tenant grouping IDs to filter metrics by. Maximum 100 items.
### Request Example
```json
{
"startDate": "2023-01-01",
"endDate": "2023-01-31",
"timeGranularity": "DAILY",
"tenantClientIds": ["client_123", "client_456"]
}
```
### Response
#### Success Response (200)
- **date** (string) - The date or timestamp for the metric entry.
- **impressions** (integer) - The number of ad impressions.
- **eligible_prompts** (integer) - The number of prompts that were eligible for ad matching.
- **ad_matches** (integer) - The number of eligible prompts that resulted in an ad match.
- **prompts** (integer) - The total number of prompts received.
#### Response Example
```json
{
"data": [
{
"date": "2023-01-01T00:00:00Z",
"impressions": 1500,
"eligible_prompts": 1200,
"ad_matches": 800,
"prompts": 1300
},
{
"date": "2023-01-02T00:00:00Z",
"impressions": 1650,
"eligible_prompts": 1350,
"ad_matches": 950,
"prompts": 1450
}
]
}
```
### Error Handling
- **400 Bad Request**: Invalid date range, invalid granularity, or exceeding array limits.
- **401 Unauthorized**: Authentication failed.
- **500 Internal Server Error**: Server encountered an unexpected condition.
```
--------------------------------
### Pass Signals in ZeroClick Offers API Request
Source: https://developer.zeroclick.ai/docs/signal-collection/rest-api
This example shows how to include signals directly within a POST request to the ZeroClick Offers API. This is useful for sending contextual signals at the same time as fetching offers. The signals are structured similarly to those sent to the signals endpoint.
```javascript
const response = await fetch("https://zeroclick.dev/api/v2/offers", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-zc-api-key": "your-api-key"
},
body: JSON.stringify({
method: "server",
ipAddress: clientIpAddress,
query: "best running shoes",
limit: 3,
signals: [
{
category: "purchase_intent",
confidence: 0.9,
subject: "running shoes",
sentiment: "positive"
}
]
})
});
```
--------------------------------
### GET /websites/developer_zeroclick_ai
Source: https://developer.zeroclick.ai/docs/api-reference/analytics/get-developer-analytics-metrics
Retrieves developer analytics metrics for a given website. The response includes time series data and aggregated totals for metrics such as prompts, impressions, clicks, and estimated earnings.
```APIDOC
## GET /websites/developer_zeroclick_ai
### Description
Retrieves developer analytics metrics for a given website. The response includes time series data and aggregated totals for metrics such as prompts, impressions, clicks, and estimated earnings.
### Method
GET
### Endpoint
/websites/developer_zeroclick_ai
### Parameters
#### Query Parameters
- **startDate** (string) - Required - The start date for the analytics data in YYYY-MM-DD format.
- **endDate** (string) - Required - The end date for the analytics data in YYYY-MM-DD format.
- **dimensions** (string) - Optional - Comma-separated list of dimensions to group the data by (e.g., 'day', 'week', 'month').
### Request Example
```
GET /websites/developer_zeroclick_ai?startDate=2023-01-01&endDate=2023-01-31&dimensions=day
```
### Response
#### Success Response (200)
- **data** (array) - An array of group objects, each containing dimension values, time series data, and totals.
- **dimensions** (object) - Key-value pairs representing the dimensions for this group.
- **metadata** (object) - Metadata associated with the analytics data.
- **timeSeries** (array) - Array of time series data points.
- **date** (string) - The date of the data point.
- **prompts** (number) - Number of prompts.
- **eligiblePrompts** (number) - Number of eligible prompts.
- **promptsWithMatchedAds** (number) - Number of prompts with matched ads.
- **responsesWithImpressions** (number) - Number of responses with impressions.
- **impressions** (number) - Number of ad impression events.
- **clicks** (number) - Number of ad click events.
- **estimatedEarnings** (number) - Estimated earnings during the time range.
- **totals** (object) - Aggregated totals for this group.
- **prompts** (number) - Total number of prompts.
- **eligiblePrompts** (number) - Total number of eligible prompts.
- **promptsWithMatchedAds** (number) - Total number of prompts with matched ads.
- **responsesWithImpressions** (number) - Total number of responses with impressions.
- **impressions** (number) - Total number of ad impression events.
- **clicks** (number) - Total number of ad click events.
- **estimatedEarnings** (number) - Estimated earnings during the time range.
#### Response Example
```json
{
"data": [
{
"dimensions": {
"day": "2023-01-01"
},
"metadata": {
"currency": "USD"
},
"timeSeries": [
{
"date": "2023-01-01",
"prompts": 1000,
"eligiblePrompts": 950,
"promptsWithMatchedAds": 800,
"responsesWithImpressions": 750,
"impressions": 1500,
"clicks": 50,
"estimatedEarnings": 10.50
}
],
"totals": {
"prompts": 1000,
"eligiblePrompts": 950,
"promptsWithMatchedAds": 800,
"responsesWithImpressions": 750,
"impressions": 1500,
"clicks": 50,
"estimatedEarnings": 10.50
}
}
]
}
```
#### Error Response (400 or 500)
- **error** (object) - Contains error details.
- **message** (string) - A message describing the error.
#### Error Response Example
```json
{
"error": {
"message": "Invalid date format. Please use YYYY-MM-DD."
}
}
```
```
--------------------------------
### Product Information Schema
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
Defines the structure for product information, including ID, SKU, title, description, category, image, availability, and metadata.
```APIDOC
## Product Information Schema
### Description
This schema defines the structure for product information, encompassing details like product ID, SKU, title, description, category, image URL, availability status, and additional metadata.
### Method
N/A (Schema Definition)
### Endpoint
N/A (Schema Definition)
### Parameters
#### Request Body
- **productId** (string) - Required - Unique identifier for the product.
- **sku** (string) - Required - Stock keeping unit for the product, if available.
- **title** (string) - Required - Name or title of the product.
- **description** (string) - Optional - Description of the product.
- **category** (string) - Required - Category of the product.
- **subcategory** (string) - Required - Subcategory of the product.
- **image** (string) - Required - Image URL of the product.
- **availability** (string) - Required - Availability status of the product (enum: in_stock, limited, out_of_stock).
- **metadata** (object) - Optional - Any additional metadata specific to the product.
### Request Example
```json
{
"productId": "prod123",
"sku": "SKU456",
"title": "Awesome Gadget",
"description": "A must-have gadget for tech enthusiasts.",
"category": "Electronics",
"subcategory": "Gadgets",
"image": "https://example.com/gadget.jpg",
"availability": "in_stock",
"metadata": {"color": "blue", "weight": "100g"}
}
```
### Response
#### Success Response (200)
- **productId** (string) - Unique identifier for the product.
- **sku** (string) - Stock keeping unit for the product, if available.
- **title** (string) - Name or title of the product.
- **description** (string) - Description of the product.
- **category** (string) - Category of the product.
- **subcategory** (string) - Subcategory of the product.
- **image** (string) - Image URL of the product.
- **availability** (string) - Availability status of the product.
- **metadata** (object) - Any additional metadata specific to the product.
#### Response Example
```json
{
"productId": "prod123",
"sku": "SKU456",
"title": "Awesome Gadget",
"description": "A must-have gadget for tech enthusiasts.",
"category": "Electronics",
"subcategory": "Gadgets",
"image": "https://example.com/gadget.jpg",
"availability": "in_stock",
"metadata": {"color": "blue", "weight": "100g"}
}
```
```
--------------------------------
### Handle SIGTERM for Graceful Shutdown in TypeScript/JavaScript
Source: https://developer.zeroclick.ai/docs/signal-collection/setup
Implements a SIGTERM signal handler to gracefully close the MCP client connection before exiting the process. This ensures a clean shutdown of the AI agent's connection to the MCP Signal Server.
```typescript
// Graceful shutdown
process.on("SIGTERM", async () => {
await client.close();
process.exit(0);
});
```
--------------------------------
### Enable SDK Logging in TypeScript
Source: https://developer.zeroclick.ai/docs/signal-collection/testing
Demonstrates how to enable debug logging for the ZeroClick AI client in a TypeScript application. This is useful for troubleshooting issues by providing detailed logs of client operations. It requires initializing the client with a logger option.
```typescript
const client = new Client({
name: "your-agent",
version: "1.0.0"
}, {
// Enable debug logging
logger: console
});
```
--------------------------------
### POST /api/v2/impressions
Source: https://developer.zeroclick.ai/docs/integration-guide
Track offer impressions. This endpoint is required for analytics and revenue attribution after displaying offers to users.
```APIDOC
## POST /api/v2/impressions
### Description
After displaying offers to users, call the impressions endpoint to record what was shown. This is required for analytics and revenue attribution.
### Method
POST
### Endpoint
/api/v2/impressions
### Parameters
#### Request Body
- **ids** (array of strings) - Required - An array of offer IDs that were displayed.
### Request Example
```json
{
"ids": ["offer123", "offer456"]
}
```
### Response
#### Success Response (200)
- **message** (string) - A confirmation message indicating the impressions were tracked.
#### Response Example
```json
{
"message": "Impressions tracked successfully."
}
```
### Warning
Impression tracking must be called from client devices. Requests will be rate limited per IP.
```
--------------------------------
### POST /api/v2/offers
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
Retrieves an array of personalized offers based on the provided query and user context. Supports both client-side and server-side integration methods.
```APIDOC
## POST /api/v2/offers
### Description
Retrieves an array of offers based on the provided query and user context. Supports both client-side (browser) and server-side (backend) integrations.
### Method
POST
### Endpoint
/api/v2/offers
### Parameters
#### Query Parameters
None
#### Request Body
- **method** (string) - Required - Specifies the integration method. Use `client` for browser-based requests or `server` for backend requests.
- **query** (string) - Required - The search query for offers.
- **limit** (integer) - Optional - The maximum number of offers to return.
- **ipAddress** (string) - Required if `method` is `server` - The IP address of the client.
- **userAgent** (string) - Optional - The User-Agent string of the client (recommended for server-side).
- **userId** (string) - Optional - A unique identifier for the user.
- **groupingId** (string) - Optional - An identifier for grouping offers.
- **userEmailSha256** (string) - Optional - Hashed user email for identity matching.
- **userPhoneSha256** (string) - Optional - Hashed user phone number for identity matching.
### Request Example
```json
{
"method": "client",
"query": "best running shoes",
"limit": 3
}
```
```json
{
"method": "server",
"ipAddress": "203.0.113.42",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"query": "cloud hosting solutions",
"limit": 5,
"userId": "user-12345",
"groupingId": "premium-tier"
}
```
```json
{
"method": "client",
"query": "project management software",
"userEmailSha256": "a1b2c3d4e5f6...",
"limit": 3
}
```
### Response
#### Success Response (200)
- **Array of Offer objects** - Each offer object contains details like `id`, `title`, `subtitle`, `content`, `cta`, `clickUrl`, `imageUrl`, `brand`, `product`, and `price`.
#### Response Example
```json
[
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"title": "Nike Air Zoom Pegasus 40",
"subtitle": "Premium running shoe for daily training",
"content": "Responsive cushioning and breathable mesh upper for comfortable miles.",
"cta": "Shop Now",
"clickUrl": "https://https://zeroclick.dev/api/v2/clicks?id=a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"imageUrl": "https://example.com/pegasus40.jpg",
"brand": {
"name": "Nike",
"description": "Global sports and athletic footwear brand",
"url": "https://nike.com",
"iconUrl": "https://example.com/nike-logo.png"
},
"product": {
"productId": "nike-pegasus-40",
"title": "Air Zoom Pegasus 40",
"category": "Running Shoes",
"availability": "in_stock"
},
"price": {
"amount": "129.99",
"currency": "USD",
"originalPrice": "139.99",
"discount": "7%"
}
}
]
```
#### Error Response (400)
- **Error object** - Contains an `error` field with a `message` describing the bad request.
#### Error Response Example (400)
```json
{
"error": {
"message": "client ipAddress is required to be forwarded for server method"
}
}
```
#### Error Response (401)
- **Error object** - Contains an `error` field with a `message` describing the unauthorized request.
#### Error Response Example (401)
```json
{
"error": {
"message": "Invalid API key"
}
}
```
```
--------------------------------
### Send IAB Audience Segments to ZeroClick AI API
Source: https://developer.zeroclick.ai/docs/signal-collection/rest-api
This code example shows how to send IAB Audience Taxonomy segments to the ZeroClick API. It uses the 'user_context' category and requires user ID, IP address, and API key. The IAB data includes type, version, and IDs representing audience segments.
```javascript
await fetch("https://zeroclick.dev/api/v2/signals", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-zc-api-key": "your-api-key"
},
body: JSON.stringify({
userId: "user-12345",
ipAddress: "your-user-ip-address",
signals: [
{
category: "user_context",
confidence: 0.9,
subject: "Fitness Enthusiasts",
relatedSubjects: [
"Outdoor Adventurers",
"Marathon Runners"
],
iab: {
type: "audience",
version: "1.1",
ids: ["1234", "1235", "1236"]
}
}
]
})
});
```
--------------------------------
### API Authentication
Source: https://developer.zeroclick.ai/docs/api-reference/offers/get-zeroclick-offers
Details on how to authenticate API requests using an API key.
```APIDOC
## API Authentication
### Description
All API requests must be authenticated using an API key provided by ZeroClick AI. This key should be included in the request headers.
### Method
Header-based authentication
### Header Parameter
- **x-zc-api-key** (string) - Required - Your tenant API key. Obtain this from the ZeroClick AI developer portal.
```
--------------------------------
### Fetch Personalized Offers via REST API (JavaScript)
Source: https://developer.zeroclick.ai/docs/offers/overview
This snippet demonstrates how to fetch personalized offers from the ZeroClick AI API using a POST request. It requires an API key and sends user-specific information in the request body. The response contains the offers to be rendered in the UI.
```javascript
const response = await fetch("https://zeroclick.dev/api/v2/offers", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-zc-api-key": "your-api-key"
},
body: JSON.stringify({
method: "server",
ipAddress: clientIpAddress,
query: "best running shoes"
})
});
const offers = await response.json();
// Render offers in your UI
```