# How to integrate Amplitude MCP with Mastra AI

```json
{
  "title": "How to integrate Amplitude MCP with Mastra AI",
  "toolkit": "Amplitude",
  "toolkit_slug": "amplitude",
  "framework": "Mastra AI",
  "framework_slug": "mastra-ai",
  "url": "https://composio.dev/toolkits/amplitude/framework/mastra-ai",
  "markdown_url": "https://composio.dev/toolkits/amplitude/framework/mastra-ai.md",
  "updated_at": "2026-05-12T10:01:10.106Z"
}
```

## Introduction

This guide walks you through connecting Amplitude to Mastra AI using the Composio tool router. By the end, you'll have a working Amplitude agent that can get daily active users for last month, generate funnel analysis for onboarding flow, list top events for premium users through natural language commands.
This guide will help you understand how to give your Mastra AI agent real control over a Amplitude account through Composio's Amplitude MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Amplitude with

- [OpenAI Agents SDK](https://composio.dev/toolkits/amplitude/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/amplitude/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/amplitude/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/amplitude/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/amplitude/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/amplitude/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/amplitude/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/amplitude/framework/cli)
- [Google ADK](https://composio.dev/toolkits/amplitude/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/amplitude/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/amplitude/framework/ai-sdk)
- [LlamaIndex](https://composio.dev/toolkits/amplitude/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/amplitude/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- Set up your environment so Mastra, OpenAI, and Composio work together
- Create a Tool Router session in Composio that exposes Amplitude tools
- Connect Mastra's MCP client to the Composio generated MCP URL
- Fetch Amplitude tool definitions and attach them as a toolset
- Build a Mastra agent that can reason, call tools, and return structured results
- Run an interactive CLI where you can chat with your Amplitude agent

## What is Mastra AI?

Mastra AI is a TypeScript framework for building AI agents with tool support. It provides a clean API for creating agents that can use external services through MCP.
Key features include:
- MCP Client: Built-in support for Model Context Protocol servers
- Toolsets: Organize tools into logical groups
- Step Callbacks: Monitor and debug agent execution
- OpenAI Integration: Works with OpenAI models via @ai-sdk/openai

## What is the Amplitude MCP server, and what's possible with it?

The Amplitude MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Amplitude account. It provides structured and secure access to your analytics platform, so your agent can perform actions like managing event types, organizing cohorts, updating user properties, and tracking event categories on your behalf.
- Cohort and user management: Ask your agent to request, download, and check the status of specific user cohorts for advanced segmentation or analysis.
- Event type and category administration: Effortlessly create, update, or delete event types and categories, keeping your analytics taxonomy organized and up to date.
- User property updates: Direct your agent to set or modify user properties—like device information or location—without sending new events, making user profile management a breeze.
- Comprehensive analytics lookup: Retrieve detailed information about event types and categories, enabling your agent to provide insights or answer analytics questions in real time.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `AMPLITUDE_ASSIGN_ANNOTATIONS_TO_CATEGORY` | Bulk Assign Annotations to Category | Tool to bulk assign multiple annotations to a category in Amplitude. Use when you need to organize annotations by assigning them to a specific category. |
| `AMPLITUDE_CANCEL_DELETION` | Cancel User Deletion | Cancel a pending user deletion request in Amplitude. Use this to remove a user from a scheduled deletion job before it completes. Only works on deletion jobs in 'Staging' status (not yet submitted). |
| `AMPLITUDE_CHECK_COHORT_STATUS` | Check Amplitude Cohort Status | Check the status of a cohort export request. This action allows you to: - Poll the status of an in-progress cohort download request - Determine if a cohort is ready for download |
| `AMPLITUDE_CREATE_ANNOTATION` | Create Chart Annotation in Amplitude | Create a chart annotation in Amplitude to mark important dates. Use to highlight key events like feature releases, marketing campaigns, or product updates on analytics charts. |
| `AMPLITUDE_CREATE_ANNOTATION_CATEGORY` | Create Annotation Category | Tool to create an annotation category in Amplitude to organize annotations. Use when you need to create a new category for grouping related annotations. |
| `AMPLITUDE_CREATE_EVENT_CATEGORY` | Create Amplitude Event Category | Create a new event category in Amplitude. This action allows you to: - Create a new event category to organize event types - Validate category name before creation Key features: - Creates event categories for organizing events - Returns success/failure status |
| `AMPLITUDE_CREATE_EVENT_TYPE` | Create Amplitude Event Type | Create a new event type in Amplitude. This action allows you to: - Define a new event type with various properties - Associate the event with a category - Add metadata like description, tags, and owner Key features: - Creates trackable events in your Amplitude project - Supports full event type configuration |
| `AMPLITUDE_CREATE_RELEASE` | Create Amplitude Release | Create a release to document product changes. Use when you want to track app version releases and their impact on metrics. Can be integrated into deployment workflows to automatically log releases in Amplitude. |
| `AMPLITUDE_DELETE_ANNOTATION` | Delete Amplitude Chart Annotation | Delete a chart annotation from Amplitude. Use to remove existing annotations from charts. |
| `AMPLITUDE_DELETE_ANNOTATION_CATEGORY` | Delete Amplitude Annotation Category | Delete an annotation category from Amplitude. Use when you need to remove an annotation category that is no longer needed. |
| `AMPLITUDE_DELETE_EVENT_CATEGORY` | Delete Amplitude Event Category | Delete an event category from Amplitude. This action allows you to: - Delete an existing event category - Remove category organization from events Key features: - Permanently removes event categories - Returns success/failure status |
| `AMPLITUDE_DELETE_EVENT_TYPE` | Delete Amplitude Event Type | Delete an event type from Amplitude. This action allows you to: - Remove an event type from your project - Mark live events as deleted - Remove planned events from the tracking plan Key features: - Different behavior based on event status (live, planned, etc.) - Returns success/failure status |
| `AMPLITUDE_DELETE_USERS` | Delete Amplitude Users | Submit user deletion requests for GDPR/CCPA compliance. Supports up to 100 users per request. Use when you need to delete user data from Amplitude in compliance with privacy regulations. Either amplitude_ids or user_ids must be provided. |
| `AMPLITUDE_DOWNLOAD_COHORT_FILE` | Download Amplitude Cohort File | Download the cohort file after request is complete. Use this action after checking that the cohort status is 'JOB COMPLETED'. The download link is valid for 7 days, but the S3 link is valid for only 1 minute. |
| `AMPLITUDE_FIND_USER` | Search Amplitude User | Search for users in Amplitude by canonical identifier (Amplitude ID, device ID, user ID, or user ID prefix). Use this to find matching Amplitude IDs for deterministic user mapping. Important: This searches only canonical identifiers (Amplitude ID, device_id, user_id), NOT arbitrary user properties like email unless email is your actual user_id. |
| `AMPLITUDE_GET_ACTIVE_USERS` | Get Active or New Users | Get the number of active or new users for a date range with optional segmentation. Use when you need user count metrics aggregated by day, week, or month, optionally grouped by user properties. |
| `AMPLITUDE_GET_ANNOTATION` | Get Amplitude Annotation | Get a single chart annotation by ID from Amplitude. Use when you need to retrieve detailed information about a specific annotation including its label, timestamps, category, and associated chart. |
| `AMPLITUDE_GET_ANNOTATION_CATEGORY` | Get Amplitude Annotation Category | Get a single annotation category by ID from Amplitude. Use when you need to retrieve details about a specific annotation category. |
| `AMPLITUDE_GET_COHORT` | Request Amplitude Cohort | Get a single cohort by ID and initiate download. This action allows you to: - Request a specific cohort from Amplitude - Optionally include user properties in the response - Start the asynchronous download process Key features: - Supports filtering by specific user properties - Returns a request ID used for polling status and downloading - Supports EU data residency |
| `AMPLITUDE_GET_DELETION_REQUESTS` | Get User Deletion Requests | Get the status of user deletion requests within a date range. Use this to track GDPR/CCPA deletion compliance and monitor deletion job progress. |
| `AMPLITUDE_GET_EVENT_CATEGORIES` | Get Amplitude Event Categories | Get event categories from Amplitude. This action allows you to: - Get all event categories in your project - Get a specific category by name |
| `AMPLITUDE_GET_EVENT_PROPERTY` | Get Amplitude Event Property | Get a specific event property from Amplitude taxonomy. Use when you need to retrieve details about a specific event property including its type, validation rules, and metadata. |
| `AMPLITUDE_GET_EVENT_SEGMENTATION` | Get Event Segmentation Data | Get event segmentation data from Amplitude Analytics API. Use this to analyze event metrics over time with optional grouping by properties. Supports multiple metrics (uniques, totals, percentage of DAU, averages) and time intervals (realtime, hourly, daily, weekly). |
| `AMPLITUDE_GET_EVENT_TYPE` | Get Amplitude Event Type | Get a specific event type from Amplitude by name. This action allows you to: - Retrieve detailed information about a single event type - Get all properties and metadata for the event Key features: - Retrieves comprehensive event type details - Returns metadata like category, description, and settings - Supports lookup by exact event name |
| `AMPLITUDE_GET_EVENT_TYPES` | Get Amplitude Event Types | Get all event types from Amplitude. This action allows you to: - Retrieve all event types in your project - Optionally include deleted events |
| `AMPLITUDE_GET_FUNNEL_DATA` | Get Funnel Analysis Data | Get funnel analysis data showing user conversion through a sequence of events. Use this to analyze user drop-off rates and conversion times across multiple steps in a user journey. |
| `AMPLITUDE_GET_REALTIME_ACTIVE_USERS` | Get Real-time Active Users | Get real-time active users count from Amplitude. Returns active user counts with 5-minute granularity (configurable) for today and yesterday. Use this to monitor current user activity and compare with historical data. |
| `AMPLITUDE_GET_RETENTION` | Get User Retention Analysis | Get user retention analysis showing how users return over time after a starting action. Use when analyzing user engagement patterns, measuring feature stickiness, or understanding long-term user behavior across cohorts. |
| `AMPLITUDE_GET_REVENUE_LTV` | Get Revenue LTV Metrics | Get revenue lifetime value (LTV) metrics including ARPU, ARPPU, and total revenue. Use when you need to analyze revenue trends over time for user cohorts. |
| `AMPLITUDE_GET_SESSION_AVERAGE` | Get Session Average Length | Get average session length (in seconds) for a specified date range from Amplitude. Use when you need to analyze user engagement patterns and session duration trends over time. |
| `AMPLITUDE_GET_SESSION_LENGTH` | Get Session Length Distribution | Tool to retrieve session length distribution data for a specified date range from Amplitude. Use when you need to analyze how long users' sessions typically last or visualize session duration patterns across time buckets. |
| `AMPLITUDE_GET_SESSIONS_PER_USER` | Get Sessions Per User from Amplitude | Tool to get average number of sessions per user for each day in a date range from Amplitude. Use when analyzing user engagement patterns or session frequency over time. |
| `AMPLITUDE_GET_USER_ACTIVITY` | Get User Activity from Amplitude | Fetch a single user's profile summary and event stream by Amplitude ID. Use when you need to extract attribution data (UTM parameters, referrers) from early events or user properties, or when analyzing user behavior patterns. |
| `AMPLITUDE_GET_USER_COMPOSITION` | Get User Composition by Property | Tool to get user composition breakdown by property (platform, version, country, etc.). Use when analyzing user distribution across property values during a date range. |
| `AMPLITUDE_GET_USER_MAPPINGS` | Get User Mappings | Get the list of user mappings for provided user IDs. Use when you need to retrieve aliasing relationships between user identifiers in Amplitude. Returns mapping data showing which users map into and out of the requested user IDs. |
| `AMPLITUDE_GET_USER_PROPERTY` | Get Amplitude User Property | Get a specific user property from Amplitude taxonomy. Use when you need to retrieve details about a specific user property including its type, validation rules, and classifications. |
| `AMPLITUDE_IDENTIFY` | Update User Properties in Amplitude | Update user properties using Amplitude's Identify API. This action allows you to: - Set or update the User ID for a Device ID - Update user properties without sending an event - Perform operations on user properties (set, append, etc.) - Update user attributes like device info and location |
| `AMPLITUDE_LIST_ANNOTATION_CATEGORIES` | List Amplitude Annotation Categories | List all annotation categories from Amplitude. Use to retrieve available categories for chart annotations. |
| `AMPLITUDE_LIST_ANNOTATIONS` | List Chart Annotations | Tool to get all chart annotations with optional filtering by category, chart, and date range. Use when you need to retrieve annotations that mark important events or milestones on Amplitude charts. |
| `AMPLITUDE_LIST_COHORTS` | List Amplitude Cohorts | List all discoverable cohorts for an Amplitude project. This action allows you to: - Get a list of all cohorts in your Amplitude project - Optionally include sync information for each cohort Key features: - Returns cohort details including ID, name, size, and definition - Optionally includes sync metadata for integration with other tools - Supports EU data residency. An empty result may indicate insufficient permissions to view cohorts rather than an absence of cohorts in the project. |
| `AMPLITUDE_LIST_EVENT_PROPERTIES` | List Amplitude Event Properties | Get all event properties from Amplitude, optionally filtered by event type or property name. Use when you need to retrieve property definitions, data types, or validation rules for events. |
| `AMPLITUDE_LIST_EVENTS` | List Amplitude Events | Tool to get a list of all event types in your Amplitude project with current week's statistics. Use when you need to see all events and their recent activity metrics including totals, uniques, and DAU percentages. |
| `AMPLITUDE_LIST_USER_PROPERTIES` | List Amplitude User Properties | Tool to get all user properties in your Amplitude project. Use when you need to retrieve the complete list of user properties including both default and custom properties. |
| `AMPLITUDE_MAP_USER` | Map Users in Amplitude | Map users with different user IDs together (alias/merge users) in Amplitude. Use this to merge user identities across different identifiers or unmap previously merged users. Supports up to 2000 mappings per request with 1MB size limit. |
| `AMPLITUDE_RESTORE_EVENT_TYPE` | Restore Amplitude Event Type | Restore a deleted event type in Amplitude. This action allows you to: - Restore a previously deleted event type - Make the event available again in the UI and API Key features: - Undoes the deletion of an event type - Returns success/failure status |
| `AMPLITUDE_SEND_EVENTS` | Send Events to Amplitude | Send events to Amplitude using the HTTP V2 API. This action allows you to send events to Amplitude for tracking user behavior and analytics. It supports all Amplitude event fields, handles proper validation, and includes comprehensive error handling. |
| `AMPLITUDE_SET_GROUP_PROPERTIES` | Set Group Properties in Amplitude | Set group properties for account-level reporting without sending an event. Use this action to update group attributes like company name, industry, or plan type. Requires Enterprise plan with Accounts add-on. |
| `AMPLITUDE_UPDATE_ANNOTATION` | Update Amplitude Chart Annotation | Tool to update an existing chart annotation in Amplitude. Use when you need to modify annotation properties such as label, timestamps, category, or chart association. Supports partial updates - only include fields you want to change. |
| `AMPLITUDE_UPDATE_ANNOTATION_CATEGORY` | Update Amplitude Annotation Category | Tool to update an annotation category in Amplitude. Use when you need to rename or modify an existing annotation category for organizing chart annotations. |
| `AMPLITUDE_UPDATE_COHORT_MEMBERSHIP` | Update Amplitude Cohort Membership | Incrementally update cohort membership by adding or removing IDs. This action allows you to: - Add new IDs to an existing cohort - Remove IDs from an existing cohort - Perform multiple operations in a single request |
| `AMPLITUDE_UPDATE_EVENT_CATEGORY` | Update Amplitude Event Category | Update an existing event category in Amplitude. This action allows you to: - Update the name of an existing event category - Validate the new category name Key features: - Updates category names - Returns success/failure status |
| `AMPLITUDE_UPDATE_EVENT_TYPE` | Update Amplitude Event Type | Update an existing event type in Amplitude. This action allows you to: - Change event type properties - Update event name, category, metadata, and settings - Modify display name for ingested events Key features: - Updates event type configuration - Supports partial updates (only specified fields are changed) |
| `AMPLITUDE_UPLOAD_BATCH_EVENTS` | Batch Upload Events to Amplitude | Bulk upload events to Amplitude using the Batch Event Upload API. Supports larger payloads (20MB) and higher throttling limits than HTTP V2 API. Use when you need to send large batches of events efficiently. |
| `AMPLITUDE_UPLOAD_COHORT` | Upload Amplitude Cohort | Generate a new cohort or update an existing cohort by uploading user IDs or Amplitude IDs. Use when you need to create cohorts from a specific list of users. |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Amplitude MCP server is an implementation of the Model Context Protocol that connects your AI agent to Amplitude. It provides structured and secure access so your agent can perform Amplitude operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Node.js 18 or higher
- A Composio account with an active API key
- An OpenAI API key
- Basic familiarity with TypeScript

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key.
- You need credits or a connected billing setup to use the models.
- Store the key somewhere safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Go to Settings and copy your API key.
- This key lets your Mastra agent talk to Composio and reach Amplitude through MCP.

### 2. Install dependencies

Install the required packages.
What's happening:
- @composio/core is the Composio SDK for creating MCP sessions
- @mastra/core provides the Agent class
- @mastra/mcp is Mastra's MCP client
- @ai-sdk/openai is the model wrapper for OpenAI
- dotenv loads environment variables from .env
```bash
npm install @composio/core @mastra/core @mastra/mcp @ai-sdk/openai dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates your requests to Composio
- COMPOSIO_USER_ID tells Composio which user this session belongs to
- OPENAI_API_KEY lets the Mastra agent call OpenAI models
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here
```

### 4. Import libraries and validate environment

What's happening:
- dotenv/config auto loads your .env so process.env.* is available
- openai gives you a Mastra compatible model wrapper
- Agent is the Mastra agent that will call tools and produce answers
- MCPClient connects Mastra to your Composio MCP server
- Composio is used to create a Tool Router session
```typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey as string,
});
```

### 5. Create a Tool Router session for Amplitude

What's happening:
- create spins up a short-lived MCP HTTP endpoint for this user
- The toolkits array contains "amplitude" for Amplitude access
- session.mcp.url is the MCP URL that Mastra's MCPClient will connect to
```typescript
async function main() {
  const session = await composio.create(
    composioUserID as string,
    {
      toolkits: ["amplitude"],
    },
  );

  const composioMCPUrl = session.mcp.url;
  console.log("Amplitude MCP URL:", composioMCPUrl);
```

### 6. Configure Mastra MCP client and fetch tools

What's happening:
- MCPClient takes an id for this client and a list of MCP servers
- The headers property includes the x-api-key for authentication
- getTools fetches the tool definitions exposed by the Amplitude toolkit
```typescript
const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      nasdaq: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

console.log("Fetching MCP tools from Composio...");
const composioTools = await mcpClient.getTools();
console.log("Number of tools:", Object.keys(composioTools).length);
```

### 7. Create the Mastra agent

What's happening:
- Agent is the core Mastra agent
- name is just an identifier for logging and debugging
- instructions guide the agent to use tools instead of only answering in natural language
- model uses openai("gpt-5") to configure the underlying LLM
```typescript
const agent = new Agent({
    name: "amplitude-mastra-agent",
    instructions: "You are an AI agent with Amplitude tools via Composio.",
    model: "openai/gpt-5",
  });
```

### 8. Set up interactive chat interface

What's happening:
- messages keeps the full conversation history in Mastra's expected format
- agent.generate runs the agent with conversation history and Amplitude toolsets
- maxSteps limits how many tool calls the agent can take in a single run
- onStepFinish is a hook that prints intermediate steps for debugging
```typescript
let messages: AiMessageType[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end.\n");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();

rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

  if (!trimmedInput) {
    rl.prompt();
    return;
  }

  messages.push({
    id: crypto.randomUUID(),
    role: "user",
    content: trimmedInput,
  });

  console.log("\nAgent is thinking...\n");

  try {
    const response = await agent.generate(messages, {
      toolsets: {
        amplitude: composioTools,
      },
      maxSteps: 8,
    });

    const { text } = response;

    if (text && text.trim().length > 0) {
      console.log(`Agent: ${text}\n`);
        messages.push({
          id: crypto.randomUUID(),
          role: "assistant",
          content: text,
        });
      }
    } catch (error) {
      console.error("\nError:", error);
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    console.log("\nSession ended.");
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
```

## Complete Code

```typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({ apiKey: composioAPIKey as string });

async function main() {
  const session = await composio.create(composioUserID as string, {
    toolkits: ["amplitude"],
  });

  const composioMCPUrl = session.mcp.url;

  const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      amplitude: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "amplitude-mastra-agent",
    instructions: "You are an AI agent with Amplitude tools via Composio.",
    model: "openai/gpt-5",
  });

  let messages: AiMessageType[] = [];

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (input: string) => {
    const trimmed = input.trim();
    if (["exit", "quit"].includes(trimmed.toLowerCase())) {
      rl.close();
      return;
    }

    messages.push({ id: crypto.randomUUID(), role: "user", content: trimmed });

    const { text } = await agent.generate(messages, {
      toolsets: { amplitude: composioTools },
      maxSteps: 8,
    });

    if (text) {
      console.log(`Agent: ${text}\n`);
      messages.push({ id: crypto.randomUUID(), role: "assistant", content: text });
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main();
```

## Conclusion

You've built a Mastra AI agent that can interact with Amplitude through Composio's Tool Router.
You can extend this further by:
- Adding other toolkits like Gmail, Slack, or GitHub
- Building a web-based chat interface around this agent
- Using multiple MCP endpoints to enable cross-app workflows

## How to build Amplitude MCP Agent with another framework

- [OpenAI Agents SDK](https://composio.dev/toolkits/amplitude/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/amplitude/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/amplitude/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/amplitude/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/amplitude/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/amplitude/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/amplitude/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/amplitude/framework/cli)
- [Google ADK](https://composio.dev/toolkits/amplitude/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/amplitude/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/amplitude/framework/ai-sdk)
- [LlamaIndex](https://composio.dev/toolkits/amplitude/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/amplitude/framework/crew-ai)

## Related Toolkits

- [Firecrawl](https://composio.dev/toolkits/firecrawl) - Firecrawl automates large-scale web crawling and data extraction. It helps organizations efficiently gather, index, and analyze content from online sources.
- [Tavily](https://composio.dev/toolkits/tavily) - Tavily offers powerful search and data retrieval from documents, databases, and the web. It helps teams locate and filter information instantly, saving hours on research.
- [Exa](https://composio.dev/toolkits/exa) - Exa is a data extraction and search platform for gathering and analyzing information from websites, APIs, or databases. It helps teams quickly surface insights and automate data-driven workflows.
- [Serpapi](https://composio.dev/toolkits/serpapi) - SerpApi is a real-time API for structured search engine results. It lets you automate SERP data collection, parsing, and analysis for SEO and research.
- [Peopledatalabs](https://composio.dev/toolkits/peopledatalabs) - Peopledatalabs delivers B2B data enrichment and identity resolution APIs. Supercharge your apps with accurate, up-to-date business and contact data.
- [Snowflake](https://composio.dev/toolkits/snowflake) - Snowflake is a cloud data warehouse built for elastic scaling, secure data sharing, and fast SQL analytics across major clouds.
- [Posthog](https://composio.dev/toolkits/posthog) - PostHog is an open-source analytics platform for tracking user interactions and product metrics. It helps teams refine features, analyze funnels, and reduce churn with actionable insights.
- [Bright Data MCP](https://composio.dev/toolkits/brightdata_mcp) - Bright Data MCP is an AI-powered web scraping and data collection platform. Instantly access public web data in real time with advanced scraping tools.
- [Browseai](https://composio.dev/toolkits/browseai) - Browseai is a web automation and data extraction platform that turns any website into an API. It's perfect for monitoring websites and retrieving structured data without manual scraping.
- [ClickHouse](https://composio.dev/toolkits/clickhouse) - ClickHouse is an open-source, column-oriented database for real-time analytics and big data processing using SQL. Its lightning-fast query performance makes it ideal for handling large datasets and delivering instant insights.
- [Coinmarketcal](https://composio.dev/toolkits/coinmarketcal) - CoinMarketCal is a community-powered crypto calendar for upcoming events, announcements, and releases. It helps traders track market-moving developments and stay ahead in the crypto space.
- [Control d](https://composio.dev/toolkits/control_d) - Control d is a customizable DNS filtering and traffic redirection platform. It helps you manage internet access, enforce policies, and monitor usage across devices and networks.
- [Databox](https://composio.dev/toolkits/databox) - Databox is a business analytics platform that connects your data from any tool and device. It helps you track KPIs, build dashboards, and discover actionable insights.
- [Databricks](https://composio.dev/toolkits/databricks) - Databricks is a unified analytics platform for big data and AI on the lakehouse architecture. It empowers data teams to collaborate, analyze, and build scalable solutions efficiently.
- [Datagma](https://composio.dev/toolkits/datagma) - Datagma delivers data intelligence and analytics for business growth and market discovery. Get actionable market insights and track competitors to inform your strategy.
- [Delighted](https://composio.dev/toolkits/delighted) - Delighted is a customer feedback platform based on the Net Promoter System®. It helps you quickly gather, track, and act on customer sentiment.
- [Dovetail](https://composio.dev/toolkits/dovetail) - Dovetail is a research analysis platform for transcript review and insight generation. It helps teams code interviews, analyze feedback, and create actionable research summaries.
- [Dub](https://composio.dev/toolkits/dub) - Dub is a short link management platform with analytics and API access. Use it to easily create, manage, and track branded short links for your business.
- [Elasticsearch](https://composio.dev/toolkits/elasticsearch) - Elasticsearch is a distributed, RESTful search and analytics engine for all types of data. It delivers fast, scalable search and powerful analytics across massive datasets.
- [Fireflies](https://composio.dev/toolkits/fireflies) - Fireflies.ai is an AI-powered meeting assistant that records, transcribes, and analyzes voice conversations. It helps teams capture call notes automatically and search or summarize meetings effortlessly.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Amplitude MCP?

With a standalone Amplitude MCP server, the agents and LLMs can only access a fixed set of Amplitude tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Amplitude and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with Mastra AI?

Yes, you can. Mastra AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Amplitude tools.

### Can I manage the permissions and scopes for Amplitude while using Tool Router?

Yes, absolutely. You can configure which Amplitude scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

### How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Amplitude data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
