---
title: "Connect Heap to ChatGPT: Track Events and Map User Identities"
slug: connect-heap-to-chatgpt-track-events-and-map-user-identities
date: 2026-10-01
author: Nidhi KN
categories: ["AI & Agents"]
excerpt: "Learn how to connect Heap to ChatGPT using an auto-generated MCP server. Automate identity resolution, track custom events, and manage user deletions."
tldr: "Skip writing custom Heap integration code. Learn how to generate a secure MCP server via Truto, connect it natively to ChatGPT, and execute complex analytics workflows like identity stitching and async GDPR deletions using natural language."
canonical: https://truto.one/blog/connect-heap-to-chatgpt-track-events-and-map-user-identities/
---

# Connect Heap to ChatGPT: Track Events and Map User Identities

**Heap in ChatGPT, in about a minute.** The best way to connect Heap to ChatGPT is Elaichi: connect Heap to Elaichi once, then add Elaichi to ChatGPT as a connector. Two steps, about a minute, with a 14-day free trial and no credit card required.

1. **Start your free trial.** Create your Elaichi account. 14 days free, no credit card required.
2. **Connect Heap.** Connect Heap once in Elaichi. ChatGPT never gets more access than you have.
3. **Add Elaichi to ChatGPT.** In ChatGPT, open Plugins, press +, and paste https://api.elaichi.ai/mcp into Server URL. Sign in and approve.

[Start free on Elaichi, 14 days, no credit card required](https://app.elaichi.ai/signup?utm_source=truto.one&utm_medium=referral&utm_campaign=launchpad&utm_content=post_markdown&utm_term=heap) · [Heap on Elaichi](https://elaichi.ai/connectors/heap/?utm_source=truto.one&utm_medium=referral&utm_campaign=launchpad&utm_content=post_markdown&utm_term=heap)

*Building Heap into your own product? The guide below is for you.*

---

If you want to connect Heap to ChatGPT so your AI agents can log server-side events, stitch anonymous sessions to known identities, and orchestrate GDPR deletion requests, you need a [Model Context Protocol (MCP) server](https://truto.one/blog/what-is-mcp-model-context-protocol-the-2026-guide-for-saas-pms/). 

If your team uses Claude, check out our guide on [connecting Heap to Claude](https://truto.one/blog/connect-heap-to-claude-enrich-user-profiles-and-govern-data/) or explore our broader architectural overview on [connecting Heap to AI Agents](https://truto.one/blog/connect-heap-to-ai-agents-automate-account-and-event-ingestion/).

Giving a Large Language Model (LLM) read and write access to a product analytics database is a serious engineering challenge. Analytics APIs behave differently than standard CRM or HRIS systems. They are append-only time-series ledgers with complex identity resolution rules and strict asynchronous processing limits. You either spend weeks building, hosting, and maintaining a custom integration layer to translate LLM JSON arguments into Heap's specific payload structures, or you use a managed infrastructure platform to generate a secure MCP server instantly.

This guide breaks down exactly how to use Truto to [generate a secure, managed MCP server for Heap](https://truto.one/blog/auto-generated-mcp-tools-for-ai-agents-a-2026-architecture-guide/), connect it natively to ChatGPT, and execute complex analytics workflows using natural language.

> Stop writing boilerplate API integration code. Let Truto generate secure, managed MCP servers for your AI agents in seconds.
>
> [Talk to us](https://truto.one/book-a-demo/)

## The Engineering Reality of the Heap API

A custom MCP server is a self-hosted integration layer. While the open MCP standard provides a predictable way for models to discover tools, implementing it against Heap's highly specific API is exceptionally painful. 

If you decide to build a custom MCP server for Heap, you own the entire API lifecycle. Here are the specific integration challenges that break standard CRUD assumptions when working with Heap:

### The Identity XOR Constraint
Most APIs let you update a user by passing an ID and a JSON body. Heap's data model revolves around the concept of known versus anonymous users. When logging server-side events, Heap enforces a strict XOR constraint: you must supply either `identity` (a known string like an email address) or `user_id` (a 16-character anonymous string generated by the SDK), but never both. If your LLM attempts to pass a payload containing both fields, the Heap API rejects it. Your MCP schemas must enforce this mutual exclusivity using JSON Schema `oneOf` directives, or ChatGPT will constantly hallucinate invalid requests.

### Strict Identity Stitching Limits
Mapping an anonymous `user_id` to a known `identity` is how you merge pre-login browsing behavior with post-login product usage. However, Heap places aggressive architectural limits on this endpoint. Heap allows only 1 identity per `user_id` and at most 10 `user_ids` per identity within a one-month window. Any extra calls beyond this limit fail silently or are ignored by the API. If your agent is running bulk identity stitching loops, you must engineer strict logic to handle these invisible boundaries.

### Asynchronous GDPR Deletions
Deleting a user in Heap is not a synchronous `DELETE /users/:id` call. Because analytics platforms store immutable event streams, scrubbing a user requires dropping events across distributed datastores. Heap's deletion API requires you to submit an array of users, which returns a `deletion_request_id`. Your MCP server must then expose a separate polling endpoint for the LLM to check the status of that specific job. 

### Factual Note on Rate Limits
When operating agents against high-volume analytics APIs, rate limiting is inevitable. Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Heap API returns HTTP 429, Truto passes that error directly to the caller. Truto normalizes upstream rate limit information into standardized headers (`ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`) per the IETF spec. The caller - in this case, the framework executing the ChatGPT agent - is entirely responsible for interpreting these headers and executing retry and backoff logic. Do not expect the MCP server to absorb rate limits for you.

## How to Generate a Heap MCP Server

Truto derives MCP tools dynamically from the integration's resource definitions and documentation records. When you connect a Heap account to Truto, the system automatically generates JSON Schema definitions for every supported Heap API method and exposes them via a JSON-RPC 2.0 endpoint.

Each MCP server is scoped to a single integrated account. The server URL contains a cryptographic token that encodes the account, what tools are exposed, and when the server expires. You can create this server using either the Truto UI or the API.

### Method 1: Generating the MCP Server via the Truto UI

If you are setting this up manually for an internal ChatGPT workspace, the UI is the fastest path.

1. Log into your Truto dashboard and navigate to your **Integrated Accounts** list.
2. Select your connected Heap account to open the detail page.
3. Click the **MCP Servers** tab.
4. Click **Create MCP Server**.
5. Select your desired configuration. For example, you can name it "Heap Analytics Agent" and filter by specific methods (like `write`) or tags (like `users`, `events`).
6. Click Save and **copy the generated MCP server URL**. It will look something like `https://api.truto.one/mcp/a1b2c3d4e5f6...`.

### Method 2: Generating the MCP Server via the API

If you are provisioning ChatGPT custom connectors programmatically for your end-users, you can generate the MCP server via a simple POST request. The API validates the configuration, hashes the secure token, and returns a ready-to-use URL.

**Endpoint:** `POST /integrated-account/:id/mcp`

```bash
curl -X POST https://api.truto.one/integrated-account/$INTEGRATED_ACCOUNT_ID/mcp \
  -H "Authorization: Bearer $TRUTO_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Heap Identity and Event Agent",
    "config": {
      "methods": ["read", "write"],
      "tags": ["users", "events", "identity"]
    }
  }'
```

**Example Response:**
```json
{
  "id": "mcp_token_9x8y7z",
  "name": "Heap Identity and Event Agent",
  "config": { 
    "methods": ["read", "write"], 
    "tags": ["users", "events", "identity"] 
  },
  "expires_at": null,
  "url": "https://api.truto.one/mcp/a1b2c3d4e5f67890"
}
```

That URL is a fully self-contained JSON-RPC 2.0 endpoint. It handles routing and authentication natively - treat it like a secret.

## Connecting the Heap MCP Server to ChatGPT

Once you have your tokenized URL, you need to register it with your LLM client. Truto MCP servers support CORS, allowing browser-based AI tools and chat interfaces to connect directly without a backend proxy.

### Method A: Via the ChatGPT UI (Custom Connectors)

If you are on a ChatGPT Pro, Plus, Business, Enterprise, or Education account, you can add custom connectors directly in the web interface.

1. In ChatGPT, navigate to **Settings -> Apps -> Advanced settings**.
2. Ensure **Developer mode** is toggled on.
3. Under the MCP servers or Custom connectors section, click **Add new server**.
4. **Name:** Enter a recognizable label (e.g., "Heap Analytics by Truto").
5. **Server URL:** Paste the `url` you generated in the previous step.
6. Click **Save**.

ChatGPT will immediately ping the endpoint, execute an `initialize` handshake, request `tools/list`, and surface the available Heap API operations to the agent.

### Method B: Via Manual Config File (SSE Transport)

If you are orchestrating ChatGPT models via desktop clients, local agents, or custom Node.js wrappers, you can connect using standard Server-Sent Events (SSE) configuration.

Create an `mcp_config.json` file:

```json
{
  "mcpServers": {
    "heap-analytics": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-sse",
        "--url",
        "https://api.truto.one/mcp/a1b2c3d4e5f67890"
      ]
    }
  }
}
```

When your agent boots, it will connect to Truto's MCP router, which splits flat argument objects into the correct query and body parameters based on the integration's underlying schema.

## Hero Tools for Heap Analytics

Truto automatically generates descriptive snake_case tool names based on the integration label and resource name. The query and body schemas are explicitly structured to guide ChatGPT away from hallucinating payload structures.

Here are the highest-leverage tools available for Heap operations.

### create_a_heap_event

This tool sends a custom server-side event to Heap. It is primarily used to log backend transaction data, webhooks, or revenue events that cannot be reliably captured via client-side JavaScript. The tool enforces the XOR rule: the LLM must supply either `identity` or `user_id`, along with the `app_id` and the `event` name. It returns an empty JSON object on success.

> "Log a server-side event in Heap for app_id '11223344'. The event is named 'Subscription Upgraded', and the identity is 'enterprise_admin@example.com'. Include custom properties for 'mrr_increase': 500 and 'tier': 'pro'."

### update_a_heap_identity_by_id

This is the core tool for identity stitching. It maps an anonymous SDK `user_id` to a known `identity` (usually an email address or internal UUID). When this tool fires, Heap migrates all historical events associated with that anonymous session to the known identity. The agent must respect Heap's strict limits of 1 identity per `user_id`.

> "We just saw a successful login webhook for 'sarah@example.com'. Map her known identity to the anonymous SDK user_id '8374928374823948' in Heap for app_id '11223344'."

### update_a_heap_user_by_id

This tool attaches custom key-value properties to an identified Heap user. It is highly effective for data enrichment workflows. If the identity does not exist in Heap, this tool creates a new user. If properties already exist with the same name, they are overwritten with the new values.

> "Update the Heap user profile for 'sarah@example.com' in app_id '11223344'. Set her 'account_status' to 'active', 'lifetime_value' to 1250, and 'last_login_region' to 'us-east-1'."

### update_a_heap_account_by_id

Heap supports B2B analytics via account-level properties. This tool attaches or updates custom properties for one or more accounts. It returns a plain-text 'OK' success acknowledgment from the API. The agent must supply the `app_id`, plus either a single `account_id` and `properties` object, or an `accounts` array for bulk updates.

> "Update the Heap account properties for account_id 'acct_998877'. Add a property for 'churn_risk' set to 'low' and 'total_seats' set to 45."

### create_a_heap_user_deletion

This tool initiates an asynchronous GDPR/CCPA user deletion job. You can submit up to 10,000 users in a single payload. Each entry in the `users` array requires either a `user_id` or an `identity`. The tool does not return a simple success confirmation; it returns a `deletion_request_id` which the agent must track.

> "We received a GDPR Right to be Forgotten request. Submit a deletion request to Heap for the identity 'data_subject_99@example.com'. Save the deletion_request_id so we can check on it later."

### get_single_heap_user_deletion_by_id

Because deletions are asynchronous, this tool allows the agent to poll the status of a previously submitted deletion job. It requires the `id` (the `deletion_request_id` from the creation tool). The agent will check this endpoint to confirm if the status has changed from 'pending' to 'completed'.

> "Check the status of the Heap user deletion job with id 'del_req_abc123'. Let me know if the records have been fully purged yet."

To view the complete schema definitions and remaining API operations available for this integration, visit the [Heap integration page](https://truto.one/integrations/detail/heap).

## Workflows in Action

Connecting tools to ChatGPT isn't just about reading isolated records; it enables multi-step autonomous data orchestration. Here are two real-world examples of how an AI agent uses the Heap MCP server.

### Workflow 1: Automated Identity Stitching and Enrichment

When a new user signs up in a SaaS product, they transition from an anonymous prospect to a known user. You want the agent to orchestrate this transition in Heap automatically.

> "A user just completed onboarding. Their anonymous user_id is '9876543210', and their new email is 'founder@startup.io'. Map their identity in Heap, then update their user profile with 'role': 'admin' and 'plan': 'startup'. Finally, log a 'Signup Complete' event under their new identity."

**Step-by-step execution:**
1. **`update_a_heap_identity_by_id`**: The agent calls this tool to link `9876543210` to `founder@startup.io`. This stitches all their pre-signup web traffic to the new email.
2. **`update_a_heap_user_by_id`**: The agent updates the known user (`founder@startup.io`), attaching the custom properties for role and plan.
3. **`create_a_heap_event`**: The agent logs the `Signup Complete` event, passing the `identity` explicitly and leaving the `user_id` blank to satisfy Heap's XOR constraint.

```mermaid
sequenceDiagram
    participant User as User
    participant ChatGPT as ChatGPT
    participant TrutoMCP as Truto MCP Server
    participant HeapAPI as Heap API
    
    User->>ChatGPT: "A user just completed onboarding..."
    
    ChatGPT->>TrutoMCP: Call update_a_heap_identity_by_id
    TrutoMCP->>HeapAPI: POST /api/identity<br>{"identity": "founder@...", "user_id": "98765..."}
    HeapAPI-->>TrutoMCP: 200 OK
    TrutoMCP-->>ChatGPT: Tool Success
    
    ChatGPT->>TrutoMCP: Call update_a_heap_user_by_id
    TrutoMCP->>HeapAPI: POST /api/add_user_properties<br>{"identity": "founder@...", "properties": {...}}
    HeapAPI-->>TrutoMCP: 200 OK
    TrutoMCP-->>ChatGPT: Tool Success
    
    ChatGPT->>TrutoMCP: Call create_a_heap_event
    TrutoMCP->>HeapAPI: POST /api/track<br>{"identity": "founder@...", "event": "Signup Complete"}
    HeapAPI-->>TrutoMCP: 200 OK
    TrutoMCP-->>ChatGPT: Tool Success
    
    ChatGPT-->>User: "Identity stitched, profile enriched, and event logged."
```

### Workflow 2: Asynchronous GDPR Deletion Orchestration

Handling compliance requests manually is tedious. You can hand this off entirely to an agent.

> "We received a formal data deletion request from 'old_client@corp.com'. Execute the deletion in Heap and verify when it is actually complete."

**Step-by-step execution:**
1. **`create_a_heap_user_deletion`**: The agent submits the email to the deletion endpoint. Heap responds with a payload containing `deletion_request_id: 'req_887766'`. 
2. **Wait State**: The agent understands from the tool description that this is asynchronous and will decide to wait.
3. **`get_single_heap_user_deletion_by_id`**: The agent polls the endpoint using the ID it saved. If the status is 'pending', it waits again.
4. **Final Verification**: Once the status returns as 'completed', the agent replies to the user confirming that the data has been scrubbed from the analytics datastore.

## [Security and Access Control](https://truto.one/blog/mcp-server-security-zero-data-retention-2026-implementation-guide/)

Exposing an enterprise analytics platform to an autonomous agent requires strict boundaries. Truto provides several configuration layers at the MCP token level to constrain what the LLM can do:

* **Method Filtering**: You can restrict an MCP server to read-only operations by passing `config: { methods: ["read"] }` during creation. If your agent should never mutate user records, this guarantees safety at the protocol level.
* **Tag Filtering**: You can scope the server to specific operational domains by passing `config: { tags: ["events"] }`. The generated MCP server will completely omit tools for identity mapping or user deletions.
* **API Token Auth**: By default, possession of the MCP URL grants access. For higher security, setting `require_api_token_auth: true` forces the client to also provide a valid Truto API token in the Authorization header.
* **Expiration (`expires_at`)**: You can assign an ISO datetime to the token. Once expired, a Durable Object alarm automatically tears down the KV entries and the database record, immediately severing the LLM's access to Heap.

## Automate Analytics Operations Safely

Connecting ChatGPT to Heap through a managed MCP server removes the friction of parsing XOR payload constraints, building long-running polling architecture, and managing OAuth lifecycles. By exposing properly typed JSON-RPC tools with auto-injected schema hints, your agents can focus on orchestrating complex data workflows instead of guessing endpoint paths. Whether you are stitching identities or purging compliance records, a unified proxy layer ensures your analytics data remains accurate and secure.
