How to integrate Posthog MCP with Mastra AI

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Posthog logo
Mastra AI logo
divider

Introduction

This guide walks you through connecting Posthog to Mastra AI using the Composio tool router. By the end, you'll have a working Posthog agent that can add a new member to project with admin role, bulk invite multiple users to your organization, bookmark a recent project activity notification through natural language commands.

This guide will help you understand how to give your Mastra AI agent real control over a Posthog account through Composio's Posthog MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

Also integrate Posthog with

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 Posthog tools
  • Connect Mastra's MCP client to the Composio generated MCP URL
  • Fetch Posthog 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 Posthog 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 Posthog MCP server, and what's possible with it?

The Posthog MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Posthog account. It provides structured and secure access to your product analytics workspace, so your agent can perform actions like managing team permissions, updating feature flag access, handling project insights, and maintaining pipeline plugins on your behalf.

  • Role and team management: Seamlessly add members to organization roles, assign specific permissions, and manage dashboard collaborators for effective collaboration.
  • Feature flag access control: Let your agent assign role-based access to feature flags, ensuring precise rollout and permission management for new features.
  • Project insight handling: Cancel ongoing insights for a project or bookmark key activity notifications, helping your team stay focused on actionable analytics.
  • Pipeline plugin and app updates: Automate the process of checking for updates and statuses of pipeline destinations, import apps, and transformation plugins to keep your analytics infrastructure healthy.
  • Bulk organization invites: Efficiently send out and manage organization invitations in bulk, streamlining onboarding for new team members and stakeholders.

Supported Tools & Triggers

Tools
Add dashboard collaborators with access levelAdd collaborators to a specific project dashboard.
Add member to organization roleAdd a member to an organization role by submitting their details and UUID in JSON/form, using organization and role IDs.
Add persons to static cohortAdd persons to a static cohort by their UUIDs.
Add product intent to projectTool to add a product intent to a PostHog project.
Add project specific member rolesAdd members with specific roles to a project by providing their user_uuid and level (member or admin).
Add session recording to playlistAdd an existing session recording to a playlist.
Append Desktop Recording SegmentsAppend transcript segments to an existing desktop recording for real-time streaming support.
Archive survey responseTool to archive a single survey response.
Assign feature flag role based accessSet up role-based access for a feature flag using `project_id` and `feature_flag_id`.
Bulk create organization invitesPOST /api/organizations/{organization_id}/invites/bulk/: Bulk-create organization invites with customizable levels, sender details, and validation checks.
Bulk delete feature flagsBulk delete feature flags by filter criteria or explicit IDs.
Create Persons Bulk DeleteTool to bulk delete persons by PostHog person IDs or distinct IDs.
Cancel insights for a projectThe "/api/projects/{project_id}/insights/cancel/" endpoint allows users to cancel insights for a project by providing a project ID and insight details in JSON or CSV, and confirms cancellation in the response.
Capture EventCapture (ingest) a single analytics event into PostHog using the public ingestion API and a project API key.
Check pipeline destination updatesCheck for available updates to a pipeline destination plugin by comparing the currently installed version (tag) with the latest version available in the plugin's repository.
Check pipeline import app updatesRetrieve the latest update information for a specific pipeline import app by its ID within an organization.
Check pipeline plugin update statusGet update status for a specific pipeline transformation plugin by its unique ID within an organization.
Check project's demo data generation statusCheck if a project is currently generating demo data.
Create Max AI insight and queryTool to create and query insights using PostHog's Max AI assistant.
Create alertTool to create a new alert configuration in PostHog.
Create BatchCapture a batch of analytics events to PostHog using the public batch ingestion API.
Create batch exportCreate a new batch export to automatically export PostHog data to external destinations like S3, BigQuery, or Snowflake.
Create batch exports backfillsTool to create a new backfill for a BatchExport.
Create batch exports run test stepTool to run a test step for a batch export configuration in PostHog.
Create customer profile configCreate a customer profile configuration for a PostHog project.
Create project insights with customizable parametersCreate custom analytics insights for a PostHog project.
Create data color themeTool to create a new data color theme in a PostHog project.
Create DatasetTool to create a new dataset in a PostHog project.
Create Dataset ItemsTool to create a new dataset item in a PostHog project dataset.
Create desktop recordingCreate a new desktop recording and get Recall.
Create endpointTool to create a new endpoint for a PostHog project.
Create error tracking autocapture controlsTool to create a new error tracking autocapture control configuration for a PostHog project.
Create error tracking releaseCreate a new error tracking release in PostHog.
Create error tracking suppression ruleTool to create a new error tracking suppression rule for a project.
Create EvaluationCreate a new evaluation for a PostHog project to assess AI-generated content or responses.
Create evaluation runTool to create a new evaluation run and enqueue a Temporal workflow to asynchronously execute the evaluation.
Create event definitionsCreate a new event definition in a PostHog project.
Create experiment exposure cohortCreate a new exposure cohort for an experiment in a project by sending a POST request with experiment details and feature flag data.
Create experiment holdoutTool to create a new experiment holdout group in PostHog.
Create experiment saved metricTool to create a new experiment saved metric in a PostHog project.
Create Feature FlagTool to create a new feature flag in a PostHog project.
Create static cohort for feature flagManage feature flags for apps with create, read, update, and delete operations using PostHog's JavaScript Library or dedicated endpoint.
Create feature flag dashboardManage feature flags by creating, reading, updating, and deleting them.
Create file systemTool to create a new file system resource in PostHog with specified metadata and hierarchy.
Create file system shortcutCreate a new file system shortcut in a PostHog project.
Create groups types metricsTool to create a new metric for a specific group type in a PostHog project.
Create hog functionCreate a new hog function in PostHog.
Create insight variableCreate a new insight variable for a PostHog project.
Create live debugger breakpointTool to create a new live debugger breakpoint in a PostHog project.
Create LLM Analytics SummarizationGenerate an AI-powered summary of an LLM trace or event.
Create LLM Analytics Text RepresentationTool to generate human-readable text representations of LLM trace events for display, logging, or analysis.
Create Logs ExportTool to create a logs export job using HogQL queries in PostHog.
Create new organization with configurable accessCreate a new PostHog organization with configurable security and notification settings.
Create organization invite with role and emailCreate and send an organization invitation to a user via email.
Create organization proxy record for custom domainCreate a managed reverse proxy record for an organization to enable custom domain routing for PostHog analytics events.
Create organization role with feature flag levelsCreate a new custom role within a PostHog organization with optional feature flag access permissions.
Create domain with saml for organizationCreate and configure an authentication domain with SAML SSO for a PostHog organization.
Create persisted folderTool to create a new persisted folder in a PostHog project.
Create person path with format optionRetrieve path analytics for a specific person within a PostHog project.
Create product tourTool to create a new product tour in a PostHog project.
Create project action with formatThis POST endpoint creates actions for a project, accepts various data types, requires project_id and action data, optionally outputs in CSV/JSON, and needs PersonalAPIKeyAuth, returning a 201 with action details.
Create project cohortsCreate cohorts for a specified project by POSTing JSON-form data to "/api/projects/{project_id}/cohorts/".
Create project dashboardThe POST endpoint creates a dashboard within a project using a `project_id`, accepting details in JSON/form formats.
Create new project experimentCreate a new experiment in a specific project using JSON, form, or multipart data.
Create project insights with format optionCreate a new analytics insight in a PostHog project.
Create a notebook in a projectThe API for interacting with Notebooks.
Create project pipeline frontend app jobCreate a job for a pipeline frontend app config in a project.
Create Retrieve Retention Insights For ProjectCreate and retrieve retention insights for a project using PostHog's Query API.
Create project subscription with delivery optionsCreate a subscription for a given project by providing required details such as delivery method, frequency, and starting date.
Create project surveys with questions and targetsCreate surveys in a project by providing a project ID and details like type, questions, and targets in JSON, form-data, or urlencoded format.
Create query in project by idThe `/api/projects/{project_id}/query/` POST endpoint allows users to submit queries for a specific project by providing the project ID in the URL and the query details in JSON or form data.
Create session recording playlistsCreate playlists of session recordings for a specified project.
Generate AI summary for session recordingGenerate an AI-powered summary for a session recording.
Create Surveys Summary HeadlineTool to create or regenerate a summary headline for a survey.
Create warehouse saved queryCreate a new warehouse saved query in PostHog for data warehouse operations.
Create Web ExperimentCreate a new web experiment in a PostHog project.
Delete alertDelete an alert configuration by providing its UUID and the associated project ID.
Delete Customer Profile ConfigTool to delete a customer profile configuration by ID in a PostHog project.
Delete desktop recordingTool to delete a desktop meeting recording by its UUID and project ID.
Delete endpointDelete an endpoint and clean up materialized query.
Delete error tracking autocapture controlsDelete an error tracking autocapture control configuration by UUID and project ID.
Delete error tracking grouping ruleDelete a specific error tracking grouping rule by ID.
Delete error tracking releaseDelete an error tracking release by its UUID and project ID.
Delete Error Tracking Suppression RuleTool to delete an error tracking suppression rule by its UUID.
Delete experiment holdoutDelete an experiment holdout by providing its ID and the associated project ID.
Delete experiment saved metricTool to delete an experiment saved metric by ID from a PostHog project.
Remove feature flag role access by idDELETE /api/projects/{project_id}/feature_flags/{feature_flag_id}/role_access/{id}: Remove role access from a feature flag in a project by ID, requiring authorization.
Delete file systemTool to delete a file system resource in PostHog by UUID.
Delete Groups Types MetricsTool to delete a group usage metric by its UUID within a specific project and group type.
Delete insight variablesDelete an insight variable by its UUID from a specified project.
Delete live debugger breakpointDelete a live debugger breakpoint by providing its UUID and project ID.
Delete organization by uuidDelete an organization by its UUID.
Remove organization batch export by uuidDelete a specific batch export by its UUID in an organization.
Remove domain by uuid from organizationDelete a specific domain by its UUID within an organization, given valid organization and domain IDs.
Remove member from organization by uuidRemove a member from a PostHog organization by their user UUID.
Remove organization pipeline destinationDelete a specific pipeline destination in an organization by ID.
Remove org pipeline import app by idDelete a specific pipeline import app plugin associated with an organization by ID.
Remove organization pipeline transformationDelete a specific pipeline transformation plugin for an organization by ID.
Remove organization plugin by idDelete a specific plugin (by its integer ID) from the organization (identified by UUID) with no response body on success.
Delete organization projectProjects for the current organization.
Remove organization proxy recordDelete a proxy record by ID for a specific organization.
Remove organization role by idDelete a role with a specific UUID in an organization.
Delete persisted folderDelete a persisted folder by providing its UUID and the associated project ID.
Delete person and optionally associated eventsThis endpoint is used to read and delete user data.
Delete person propertyDelete specific properties from a person record using the $unset operation.
Delete product toursDelete a product tour by providing its UUID and the associated project ID.
Remove specific project batch exportDelete a specific batch export by providing the UUID and project ID.
Remove project dashboard collaboratorRemove a collaborator from a project dashboard.
Remove early access feature from projectDelete an early access feature by ID from a specified project.
Remove project event definitionDelete an event definition by providing its UUID and the associated project ID.
Remove project experiment by idSoft-delete a specific experiment by its unique integer ID within a project.
Remove explicit project member by uuidDelete a specific user (by UUID) from the explicit members of a given project.
Remove project plugin configurationDELETE /api/projects/{project_id}/plugin_configs/{id}/: Removes a specific plugin configuration by ID from a given project.
Remove specific project query(Experimental)
Remove property definition by uuidDelete a property definition by providing its UUID and the associated project ID.
Remove rolemembership by uuidRemove a user from a custom organization role by deleting their role membership.
Delete session recording by uuidDelete a session recording by providing the session's UUID and the associated project ID.
Remove session recording from playlistRemove a session recording from a playlist in a PostHog project.
Delete survey by idDelete a survey by providing its UUID and the associated project ID.
Delete warehouse saved queryTool to delete a warehouse saved query from PostHog.
Delete web experimentDelete a web experiment by its ID from a specific project.
Cohort duplication to staticThis endpoint duplicates a specified cohort as a static one within a project.
Duplicate experimentTool to duplicate an existing experiment in PostHog.
Duplicate survey to projectsDuplicate a survey to multiple projects in a single transaction.
Enable project early access featureEnables a new early access feature for a project using project ID, payload with details, and PersonalAPIKeyAuth.
Finish symbol sets bulk uploadTool to finalize bulk upload of error tracking symbol sets for a PostHog project.
Flag annotation as deletedSoft delete an annotation by setting 'deleted' to true via PATCH request.
Generate Insight NameTool to generate an AI-suggested name for a PostHog insight based on its query configuration.
Generate project funnel correlation insightThe /api/projects/{project_id}/insights/funnel/correlation endpoint generates a correlation insight for funnel analysis in a project, accepting JSON/CSV and needing 'project_id' and insight details.
Retrieve app metrics by idsRetrieve performance and error metrics for a specific plugin configuration (app) in a PostHog project.
Retrieve app metrics error detailsRetrieves detailed error information for a specific app metric (plugin config) within a project.
Retrieve batch export detailsRetrieve details of a specific batch export by its UUID in a project.
Get batch exports backfillsTool to retrieve backfills for a specific batch export within a project.
Retrieve cohort activity detailsRetrieve activity details for a specific cohort within a project.
Retrieve cohort person detailsRetrieve details of persons within a cohort by its unique ID in the specified project.
Get cohort calculation historyTool to retrieve the calculation history for a specific cohort.
Get conversationTool to retrieve a specific conversation by UUID and project ID.
Get conversationsTool to retrieve conversations for a specific PostHog project with pagination support.
Get Customer Profile ConfigRetrieve a specific customer profile configuration by its ID for a given project.
Get customer profile configsTool to retrieve customer profile configurations for a project with pagination support.
Retrieve dashboard template details by uuidFetch specific dashboard template details by UUID in a project with 'dashboard_template:read' rights using a PersonalAPIKeyAuth.
Retrieve dashboard template schemaRetrieve the JSON schema for dashboard templates of a specific project.
Get data color themeTool to retrieve a specific data color theme by ID from a PostHog project.
Get Data Color ThemesTool to retrieve data color themes for a specific project.
Get dataset detailsRetrieve detailed information about a specific dataset within a project.
Get Dataset ItemTool to retrieve a specific dataset item by its ID from a PostHog project.
Get dataset itemsTool to retrieve paginated dataset items for a specific project in PostHog.
Get DatasetsTool to retrieve datasets for a PostHog project.
Get desktop recordingsTool to retrieve desktop meeting recordings for a specific project.
Get Endpoint OpenAPI SpecificationGet OpenAPI 3.
Get error tracking assignment rulesTool to retrieve error tracking assignment rules for a project.
Get error tracking autocapture controlRetrieve a specific error tracking autocapture control configuration by its ID.
Get error tracking fingerprintsTool to retrieve error tracking fingerprints for a project.
Get error tracking grouping rulesTool to retrieve error tracking grouping rules for a project.
Get error tracking releaseRetrieve details of a specific error tracking release by its UUID and project ID.
Get error tracking release by hashTool to retrieve an error tracking release by its hash identifier.
Get error tracking releasesTool to retrieve paginated error tracking releases for a specific project in PostHog.
Get error tracking suppression rulesTool to retrieve error tracking suppression rules for a project.
Get error tracking symbol setsTool to retrieve error tracking symbol sets for a PostHog project.
Get EvaluationRetrieve details of a specific evaluation by its UUID and project ID.
Get evaluations for projectTool to retrieve evaluations configured for a specific PostHog environment/project.
Retrieve event definition by uuidRetrieve an event definition by its UUID within a specified project.
Get event definition by nameTool to retrieve an event definition by its exact name for a specific project.
Retrieve event definitions by project idRetrieve definitions for events within a specified project by providing the unique project_id.
Get event definitions in Golang formatTool to retrieve event definitions in Golang format for a specific PostHog project.
Get event definitions in Python formatTool to retrieve Python-formatted event definitions for a specific project.
Get event definitions TypeScriptTool to retrieve TypeScript event definitions for a specific project.
Retrieve experiment details by idsAccess detailed experiment info within a project using unique `experiment ID` & `project ID`, with 'experiment:read' rights.
Get experiment holdout detailsRetrieve details of a specific experiment holdout by ID within a project.
Get experiment holdoutsTool to retrieve experiment holdouts for a specific PostHog project.
Get experiment saved metricTool to retrieve a specific experiment saved metric by ID from a PostHog project.
Get eligible feature flags for experimentsTool to retrieve feature flags eligible for use in experiments.
Retrieve experiments requiring flag implementationRetrieve details for experiments that require feature flag implementation in a specific project.
Get experiments statsTool to retrieve experimentation velocity statistics for a PostHog project.
Retrieve export unsubscribe configsRetrieves export unsubscribe configurations for pipeline import apps in an organization.
Fetch export unsubscribe settingsRetrieves export unsubscribe configurations for pipeline transformations in an organization.
Get external data sourceTool to retrieve details of a specific external data source by its UUID and project ID.
Get external data sourcesTool to retrieve external data sources for a PostHog project with pagination support.
Retrieve feature flag activity detailsManage feature flags (creation, reading, updating, and deleting) using PostHog's guides or via JavaScript Library/endpoint for user-specific flag status.
Retrieve feature flag detailsRetrieve detailed information about a specific feature flag in a PostHog project.
Retrieve feature flag role access detailsRetrieve details for a specific role's access to a feature flag within a project.
Retrieve feature flags activity logLearn to manage feature flags by creating, reading, updating, and deleting them.
Get feature flags dependent flagsRetrieve all active feature flags that depend on a specified flag.
Retrieve feature flags evaluation reasonsManage feature flags—create, read, update, delete—using the PostHog JavaScript Library or endpoint for user-specific flag status.
Get feature flags matching IDsTool to get IDs of all feature flags matching the current filters.
Get feature flag statusTool to retrieve the status of a specific feature flag in a PostHog project.
Get file systemTool to retrieve a specific file system resource by UUID and project ID.
Get file system shortcutRetrieve a specific file system shortcut by UUID from a project.
Retrieve filtered project property definitionsGet property definitions for a project using project_id, with filters for event names, property types, exclusions, and numerical or feature flags.
Retrieve funnel insights in projectExecute a funnel analysis for a specific project.
Retrieve group property definitions by project idRetrieve property definitions for a group within a project by providing the project ID.
Retrieve group property values by index and keyRetrieve property values by 'group_type_index' and 'key' within a 'project_id'.
Get group type metric by IDTool to retrieve detailed information about a specific group usage metric by its ID.
Get groups types metricsTool to retrieve metrics for a specific group type in a PostHog project.
Retrieve hedgehog configuration by uuidRetrieve user's hedgehog configuration details by their UUID.
Retrieve historical app metrics exportRetrieve historical export data for app metrics by supplying the `project_id` and `plugin_config_id`.
Get hog functionTool to retrieve a specific hog function by UUID and project ID.
Get hog functionsTool to retrieve hog functions for a specific PostHog project.
Retrieve important project activity logRetrieve a log of important activities and changes for a specified project.
Retrieve insight sharing configurationsRetrieve sharing configurations for a specific insight within a project, requiring project and insight IDs.
Get insight thresholdsTool to retrieve thresholds configured for a specific insight within a project.
Get insight thresholdTool to retrieve a specific insight threshold by ID for a PostHog project.
Get insight variableTool to retrieve a specific insight variable by UUID and project ID.
Get insight variablesTool to retrieve paginated list of insight variables for a project.
Get live debugger breakpointTool to retrieve a specific live debugger breakpoint by UUID and project ID.
Get live debugger breakpointsTool to retrieve live debugger breakpoints for a project.
Get LLM Analytics Evaluation ConfigTool to retrieve the LLM analytics evaluation configuration for a specific PostHog project.
Get LLM Analytics ModelsTool to list available LLM models for a specific provider in PostHog LLM Analytics.
Get LLM Analytics Provider KeysTool to retrieve LLM analytics provider keys for a project.
Get logs attributesTool to retrieve available log attributes for a PostHog project.
Get logs availability statusTool to check if a project has logs available.
Get log field valuesTool to retrieve unique values for a specific log field key in a PostHog project.
Fetch organization details by uuidRetrieve organization details by UUID.
Fetch organization pipeline app repositoriesRetrieve details of pipeline import app repositories for a specific organization by its UUID.
Get persisted foldersTool to list persisted folders for a PostHog project with pagination support.
Fetch pipeline destination activityRetrieve activity logs and metadata for a specific pipeline destination configuration.
Fetch pipeline transformation detailsRetrieve available pipeline transformation plugins from the organization's plugin repository.
Get product tourTool to retrieve a specific product tour by UUID from a PostHog project.
Retrieve and delete project person trendsThis endpoint is for reading and deleting persons.
Fetch project survey activity logRetrieve the activity log of surveys within a specific project by using the project ID.
Get Role MembershipRetrieve details of a specific role membership within an organization by its UUID.
Get session group summariesTool to retrieve stored group session summaries for a project.
Fetch session recording playlist detailsRetrieve session recording playlist details for a specific project by project_id and playlist short_id.
Get survey response statisticsGet survey response statistics for a specific survey.
Get surveys archived response UUIDsTool to get list of archived response UUIDs for HogQL filtering.
Get surveys statsTool to get aggregated response statistics across all surveys for a project.
Retrieve unused organization pipeline frontend appsRetrieve a list of pipeline frontend apps that are available but not currently in use within a specific organization.
Get user home settingsTool to retrieve user home settings including homepage and tab configurations.
Get user interviewsTool to retrieve paginated list of user interviews for a specific project.
Get warehouse saved queries activityTool to retrieve activity details for a specific warehouse saved query in PostHog.
Get warehouse saved queryTool to retrieve a warehouse saved query from PostHog data warehouse.
Get warehouse tableRetrieve details of a specific data warehouse table by its UUID.
Get Warehouse TablesTool to retrieve a paginated list of warehouse tables for a specific project.
Get web experimentTool to retrieve a specific web experiment by ID from a PostHog project.
Get web vitalsTool to retrieve web vitals metrics for a specific pathname in a PostHog project.
Initiate domain verification with saml configInitiates domain verification for SAML SSO authentication.
List alerts for projectTool to retrieve all alerts configured for a specific PostHog project.
List all projects across organizationsTool to list all projects the authenticated user can access by enumerating organizations and aggregating each organization's projects.
List and manage project annotationsCreate, Read, Update and Delete annotations.
List and manage project feature flagsList all feature flags for a specific project with pagination support.
List Batch Export RunsList runs for a batch export by `batch_export_id` within a project.
List conversations ticketsTool to list tickets with person data attached for a project.
List dashboard sharing configsRetrieve a list of dashboard sharing configurations for a specified project and dashboard.
List endpoints for projectTool to list all endpoints for the team.
List endpoint versionsTool to list all versions for a specific endpoint in PostHog.
List error tracking autocapture controlsTool to list error tracking autocapture controls for a PostHog project.
List experiment saved metricsTool to list experiment saved metrics for a project with pagination support.
List feature flag role access detailsThis GET endpoint returns role access details for a feature flag in a project, needs 'project_id' & 'feature_flag_id', and offers optional 'limit' & 'offset' for pagination.
List file system resourcesTool to list file system resources for a PostHog project with pagination support.
List specific type groups with paginationList all groups of a specific group type.
List live debugger breakpoint hitsTool to retrieve breakpoint hit events from ClickHouse with optional filtering and pagination.
List active live debugger breakpointsTool to fetch active live debugger breakpoints for external client applications using Project API key.
List notebooks with filters and paginationThe API for interacting with Notebooks.
List or delete persons with optional filtersThis endpoint is for reading/deleting persons.
List organization s batch exports with paginationRetrieve paginated batch exports for an organization, with filters and optional limits.
List organization domains with paginationFetch a list of an organization's domains with pagination using `limit` and `offset`.
List organization integrationsTool to list organization-level integrations with read-only access.
List organization invites with paginationRetrieve a paginated list of all pending and active invites for an organization.
List organization members with paginationList all members of a specific organization with pagination support.
List organization s pipeline destinationsRetrieve a paginated list of an organization's pipeline destinations by ID, with optional count and offset parameters.
List Organization's Pipeline Frontend AppsRetrieve a paginated list of available pipeline frontend apps for a specific organization.
List organization s pipeline import appsRetrieve a paginated list of pipeline import applications for a specified organization by ID.
List organization s pipeline transformationsRetrieve paginated pipeline transformation lists for an organization using `limit` and `offset`, requiring a UUID and PersonalAPIKeyAuth.
List Organization Plugins with PaginationRetrieve the list of plugins for a specified organization.
List projects in organization with paginationProjects for the current organization.
List organization proxy recordsRetrieve a paginated list of custom domain proxy records for an organization.
List organization roles with paginationList all roles in an organization with pagination support.
List pipeline destination configs with paginationList pipeline destination configurations for a given project by ID, with optional pagination through 'limit' and 'offset' query parameters.
List pipeline frontend app configsList all pipeline frontend app configurations for a project.
List product toursTool to retrieve a paginated list of product tours for a specific project.
List project actions with pagination and filtersGet paginated project actions with filters by format.
List project batch exports with paginationRetrieve an indexed list of batch exports for a specified project with optional pagination.
List project configuration plugin logsRetrieve logs for a specific plugin configuration within a project.
List project dashboard collaboratorsRetrieve the list of collaborators for a specific dashboard within a project.
List project dashboards with paginationGet paginated dashboards for a project by ID, using 'limit' and 'offset'.
List project dashboard templatesRetrieve available dashboard templates for a PostHog project.
List project early access featuresRetrieve a paginated list of a project's early access features by ID with 'limit' and 'offset' parameters.
List project experiments with paginationGet a paginated list of experiments within a project using 'limit' and 'offset' parameters.
List project export items with paginationRetrieve a paginated list of export items for a specific project by ID with optional 'limit' and 'offset' query parameters.
List project group types by idList all group types configured for a PostHog project.
List project membership detailsRetrieve a list of project membership details for a specified project by ID.
List project pipeline configurationsList all pipeline transformation configurations for a specific project.
ListprojectpipelineimportconfigsList pipeline import app configurations for a specified project, with pagination options 'limit' and 'offset'.
List project plugin configurationsList all plugin configurations for a specific project.
List project session recordingsRetrieve a paginated list of session recordings for a specific project, including viewing times and user interactions.
List project subscriptions with paginationRetrieve a paginated list of subscriptions for a given project by its ID.
List paginated surveys for a projectGet paginated surveys for a project with its ID, using 'limit' and 'offset'.
List Role Memberships PaginatedList all users assigned to a specific role within an organization.
List of project s session recording playlistsList all session recording playlists for a PostHog project, including both user-created playlists and system-generated synthetic playlists (like "Watch history", "Recordings with comments", etc.
List session recording sharing configsRetrieve a list of sharing configurations for a specific session recording in a project, including creation timestamps and access tokens.
List unused organization pipeline transformationsRetrieve a list of unused pipeline transformations for a specified organization, identified by UUID.
List users with staff filter and paginationAPI endpoint fetches a user list with staff filter, pagination (limit, offset), and requires a personal API key.
List warehouse saved queriesTool to retrieve warehouse saved queries for a project.
List web experimentsTool to retrieve a paginated list of web experiments for a specific project.
Manage feature flag enrichment for usage dashboardLearn to manage feature flags (creation, access, modification, removal) using PostHog's docs, with options to use a JavaScript Library or a dedicated endpoint for user-specific flag status.
Crud operations for project annotationsCreate, Read, Update and Delete annotations.
Manage project feature flags for local evaluationRetrieve all feature flag definitions for a project to enable local evaluation.
Mark dashboard template as deletedHard delete of this model is not allowed.
Mark insight as viewed with configurable formatMarks one or more insights as viewed by the current user for a specified project.
Create project timing insightsRecord insights as viewed by updating their last_viewed_at timestamps.
Prevent hard delete notebook by flaggingHard delete of this model is not allowed.
Move dashboard tileEndpoint to move a tile from one dashboard to another.
Update alert configurationTool to update an existing alert configuration in PostHog.
Patch Batch ExportUpdate an existing batch export configuration in PostHog by partially modifying fields like name, paused status, destination, or schedule.
Mark product onboarding completeTool to mark a specific product onboarding as complete for a PostHog project.
Patch Customer Profile ConfigUpdate a customer profile configuration by partially modifying fields like content, scope, or sidebar.
Patch DatasetTool to partially update a dataset in a PostHog project.
Patch Dataset ItemTool to partially update a dataset item by its ID in a PostHog project.
Patch endpointTool to partially update an endpoint for a project.
Patch error tracking autocapture controlsPartially update an error tracking autocapture control configuration.
Patch EvaluationUpdate an evaluation by patching specific fields.
Partial experiment update in projectEndpoint enables partial updates to an experiment in a project using PATCH, needing `project_id`, `experiment_id`, and various payload types.
Patch experiment saved metricTool to partially update an experiment saved metric by ID in a PostHog project.
Patch External Data SourceTool to update an external data source in PostHog by patching specific fields like description or configuration.
Patch file systemTool to partially update a file system resource by UUID and project ID.
Patch file system shortcutTool to partially update a file system shortcut in PostHog by its UUID.
Update group usage metricTool to update a group usage metric configuration in PostHog.
Patch hog functionTool to partially update a hog function by UUID and project ID.
Patch Insight VariableUpdate an insight variable by partially modifying its properties (name, type, default value, etc.
Patch live debugger breakpointTool to update a live debugger breakpoint by UUID and project ID.
Update organization domain propertiesUpdates selected properties of a domain in an organization via PATCH request, supports various data formats but SAML fields are immutable.
Update partial role details in organizationPATCH /api/organizations/{organization_id}/roles/{id}/: Update partial details of a role by ID within an organization, including name and feature flag access level.
Patch persisted folderTool to partially update a persisted folder by ID for a PostHog project.
Person partial update via project idThis endpoint allows reading and deleting individuals.
Patch product tourTool to partially update a product tour in PostHog.
Update project action with partial dataUpdate an action within a project with a specified ID.
Partial update project annotationCreate, Read, Update and Delete annotations.
Update partial project cohort detailsUpdate partial cohort details for a specific project.
Partial update of a project s dashboardEndpoint PATCH /api/projects/{project_id}/dashboards/{id}: Allows partial update of a project's dashboard with specified ID.
Partial update of a project s feature flagLearn to manage feature flags (create, read, update, delete) using PostHog's docs, with options for JavaScript Library use or dedicated endpoints for user flag status.
Partial update of a project insightThe PATCH endpoint supports partial insight updates in a project, allows format specification (CSV/JSON), and requires `PersonalAPIKeyAuth` and `insight:write` scope for access.
Update project member role by uuidUpdate a project member's role using their UUID in a specific project.
Partial update of project notebookThe API for interacting with Notebooks.
Partially update project property definitionPATCH /api/projects/{project_id}/property_definitions/{id}/: Partially update a specific property definition by UUID in a project.
Update partial subscription detailsPATCH /api/projects/{project_id}/subscriptions/{id}/: Update partial details of a specific project subscription by ID.
Update partial survey detailsUpdate partial survey details by PATCH to /api/projects/{project_id}/surveys/{id}/ with UUID.
Update session recording playlist partiallyUpdate session recording playlists using PATCH on the endpoint with `project_id` and `short_id`.
Update user profileTool to update user profile settings in PostHog.
Patch warehouse saved queryTool to partially update a warehouse saved query in PostHog.
Patch warehouse tablesTool to partially update a warehouse table by patching specific fields like name, format, or schema.
Patch web experimentTool to partially update a web experiment in PostHog.
Pause Batch ExportPause a batch export in PostHog to temporarily stop scheduled data exports.
Pause Organization Batch ExportPause an organization-level batch export in PostHog.
Project Funnel Advanced AnalyticsCreate comprehensive funnel analysis for a PostHog project with advanced configuration options.
Post Project Trends With FiltersThe `/api/projects/{project_id}/insights/trend/` endpoint provides project trends in CSV/JSON, requires `project_id` and optional parameters, and needs 'PersonalAPIKeyAuth'.
Rearrange frontend app pipeline configsRearrange (reorder) the configuration of frontend apps in a project's data pipeline.
Rearrange pipeline transformation configsRearrange the execution order of pipeline transformation configurations for a project.
Rearrange project import app configurationsRearrange app import settings in a project using PATCH /api/projects/{project_id}/.
Rearrange project pipeline destination configsRearrange the execution order of pipeline destination configurations for a project.
Create experiment timeseries recalculationTool to create a recalculation request for experiment timeseries data.
Reconfigure plugin order and status in projectReconfigure the execution order and status of plugin configurations within a project.
Replace Desktop RecordingReplace a desktop meeting recording in PostHog using PUT.
Reset person distinct IDReset a distinct_id for a deleted person.
Retrieve async query status by id(Experimental)
Retrieve last viewed insights for userReturns basic details about the last 5 insights viewed by this user.
Retrieve matching events for session recordingRetrieves event IDs matching a filter with one session ID and at least one event/action criterion.
Retrieve notebook activity for projectThe API for interacting with Notebooks.
Retrieve notebook activity logThe API for interacting with Notebooks.
Retrieve notebook detailsThe API for interacting with Notebooks.
Retrieve or delete person retention dataThis endpoint is for reading and deleting person data; use the capture API, `$set`/`$unset` properties, or SDKs for creation and updates.
Retrieve or delete project persons funnel dataRetrieves persons who entered or progressed through a funnel in the specified project.
Retrieve organization pipeline frontend app detailsRetrieve pipeline frontend app details for an organization using its 'organization_id' (UUID).
Retrieve Org Pipeline Repo DetailsRetrieve details for repository pipeline destinations within a specific organization by its UUID.
Retrieve org pipeline transformation activityRetrieve org pipeline transformation activity
Retrieve organization pipeline unsubscribe configsRetrieve export unsubscribe configurations for an organization's pipeline frontend apps.
Retrieve organization plugin activityRetrieve activity details for plugins in a specified organization by ID.
Retrieve organization plugin detailsRetrieve a specific plugin's details for an organization.
Retrieve organization plugin repository detailsRetrieve plugin repository details for a specific organization by its UUID, including plugin type, name, URL, and more.
Retrieve organization plugin unsubscribe configsRetrieve export unsubscribe configurations for plugins in an organization.
Retrieve organization project detailsProjects for the current organization.
Retrieve organization role detailsRetrieve the details of a specific role within an organization using its UUID.
Retrieve organization s unused pipeline appsRetrieve unused pipeline import apps for a specified organization.
Retrieve paginated organization listRetrieve a paginated list of organizations with optional 'limit' and 'offset' query parameters.
Retrieve persisted folderTool to retrieve a specific persisted folder by its UUID and project ID.
Retrieve person s activity and delete optionsThis endpoint is for reading and deleting persons; for creating/updating, use the capture API, `$set`/`$unset` properties, or SDKs.
Retrieve person details by idThis endpoint is used to read and delete persons.
Retrieve person property valuesRetrieve unique values for a specific person property across all persons in a project.
Retrieve pipeline destination activityRetrieve activity details for pipeline destinations within an organization.
Retrieve pipeline destination config detailsRetrieve details of a specific pipeline destination config for a project by its ID.
Retrieve pipeline destination detailsFetch a pipeline destination's details by ID and organization UUID, using a PersonalAPIKeyAuth with read access to plugins.
Retrieve pipeline destination plugin detailsRetrieve details of a specific pipeline destination plugin within an organization by its unique ID.
Retrieve pipeline frontend app activityRetrieve activity details for pipeline front-end apps within a specified organization by organization ID.
Retrieve pipeline frontend app detailsRetrieve detailed information about a specific pipeline frontend app within an organization.
Retrieve pipeline frontend app source detailsRetrieve details for a specific pipeline frontend app's source by its ID within an organization.
Retrieve pipeline frontend plugin configRetrieve the frontend-specific configuration for a pipeline frontend app by its config ID and project ID.
Retrieve pipeline import apps activityRetrieve activity details of pipeline import apps for a given organization.
Retrieve pipeline plugin details by idRetrieve detailed information about a specific pipeline transformation plugin by ID.
Retrieve Pipeline Plugin SourceRetrieve the source details of a pipeline transformation for a specific plugin by ID within an organization.
Retrieve pipeline transformation frontend configRetrieve the frontend configuration details for a specific pipeline transformation by ID within a given project.
Retrieve plugin source detailsRetrieve plugin source details by organization and plugin ID.
Retrieve plugin update infoThis endpoint retrieves update information for a specific plugin within an organization's pipeline frontend app by its integer ID and the organization's UUID.
Retrieve plugin update statusRetrieve the latest update status for a specific plugin, identified by its integer ID, within an organization specified by UUID.
Retrieve project action details by idGet details on a project action by ID.
Retrieve project activity detailsRetrieve the activity log for a specified project, showing recent changes and events.
Retrieve project activity insightsRetrieve the activity log history for insights in a specific project.
Retrieve project activity log with paginationRetrieve a project's activity log with cursor-based pagination.
Retrieve project annotation detailsCreate, Read, Update and Delete annotations.
Retrieve project cohort detailsRetrieve detailed information about a specific cohort within a project using its ID.
Retrieve project cohorts activity logRetrieve activity log for a specific project's cohorts.
Retrieve project cohorts with paginationRetrieve a paginated list of cohorts for a specific project using `project_id`.
Retrieve project early access feature detailsRetrieve details of a specific early access feature in a project by ID.
Retrieve project event details by idRetrieve details for a specific event by ID within a project.
Retrieve project event valuesRetrieve event values for a specific project by ID.
Retrieve project experiment resultsRetrieve experiment timeseries results within a project by project and experiment ID.
Retrieve project export detailsRetrieve detailed info on a specific export of a project using its unique ID.
Retrieve project funnel correlation insightsRetrieve funnel correlation insights for a specific project.
Retrieve project group details by key and typeRetrieves specified group details within a project by group key and type index.
Retrieve project insight activity dataRetrieve insights activity for a specific project and insight ID, offering data in JSON or CSV format.
Retrieve project insight detailsRetrieve details for a specific project insight by ID, with options to format as JSON/CSV, request refresh, and specify dashboard context.
Retrieve project insights with paginationThe GET `/api/projects/{project_id}/insights/` endpoint retrieves a paginated list of insights for a specified project.
Retrieve project member details by uuidRetrieve detailed information about a specific user's membership level and status within a project by their UUID.
Retrieve project person activityThis endpoint allows reading and deleting individuals.
Retrieve project session valuesRetrieve session values for a specified project.
Retrieve project subscription detailsRetrieve a specific subscription for a project, identified by 'project_id' and 'id'.
Retrieve project trend insightsRetrieves saved trend insights from a PostHog project.
Retrieve properties and events associationAllows a caller to provide a list of event names and a single property name Returns a map of the event names to a boolean representing whether that property has ever been seen with that event_name
Retrieve property definition detailsRetrieve details of a specific property definition by UUID within a project.
Retrieve related project groupsRetrieve related groups for a specific project and user.
Retrieve session property definitionsRetrieve property definitions for a specific project by providing the project's ID.
Retrieve session recording detailsRetrieve detailed information about a specific session recording by providing the session's UUID and associated project ID.
Retrieve session recording error clustersRetrieve error clusters from session recordings for a specified project.
Retrieve recordings from playlistRetrieve the list of session recordings within a playlist.
Retrieve session recording propertiesRetrieve properties of session recordings for a given project by ID, including activity metrics, timestamps, and participant details.
Retrieve session recording snapshotsSnapshots for a session can be loaded from S3 (if old) or Redis (if recent).
Retrieve specific batch export detailsRetrieve details of a specific batch export for an organization by its UUID.
Retrieve specific batch export run detailsRetrieve details for a specific batch export run within a project by ID.
Retrieve specific domain detailsRetrieve complete details of a specific authentication domain within an organization by its UUID.
Retrieve specific exported asset contentRetrieve the content of a specific exported asset by ID within a project.
Retrieve specific historical plugin exportRetrieve historical export data for a specific plugin configuration within a project.
Retrieve specific pipeline frontend app configRetrieve the configuration details of a specific pipeline frontend app by providing its unique ID and the associated project ID.
Retrieve specific project dashboard detailsRetrieve details of a specific dashboard within a project.
Retrieve survey activity logsRetrieve activity logs for specific survey in a project, identified by UUIDs.
Retrieve survey details with uuid and project idRetrieve survey details using survey UUID and associated project ID.
Retrieve survey responses count by project idRetrieve the count of survey responses for a specific project by its ID.
Retrieve unsubscribed pipeline configsRetrieve export unsubscribe configurations for an organization's pipeline destinations.
Retrieve user profile and team detailsFetch user profile info including team, organization, and notifications.
Retry batch export runTool to retry a failed or incomplete batch export run.
Revoke organization inviteDelete an organization invite by its UUID.
Run endpointTool to execute a PostHog endpoint with optional materialization and filtering.
Split person entities in projectThis endpoint allows reading and deleting persons; for creation or updates, use the capture API, `$set`/`$unset` properties, or SDKs.
Create error tracking symbol sets bulk start uploadTool to initiate bulk upload of error tracking symbol sets for a PostHog project.
Create error tracking symbol sets start uploadTool to initiate symbol set upload session for error tracking in PostHog.
Summarize survey responsesTool to generate an AI-powered summary of survey responses for a specific question.
Translate textTool to translate text to a target language using PostHog's LLM analytics translation endpoint.
Trigger project export with format optionThe `/api/projects/{project_id}/exports/` endpoint triggers a project export, requiring `project_id` and `export_format`.
Unarchive survey responseTool to unarchive a single survey response.
Unpause Batch ExportTool to unpause a paused batch export in PostHog.
Unpause Organization Batch ExportTool to unpause a paused batch export at the organization level.
Update alert (full replacement)Tool to fully update an existing alert configuration in PostHog using PUT method.
Update annotation detailsCreate, Read, Update and Delete annotations.
Update batch exportTool to update an existing batch export configuration in PostHog.
Update Customer Profile ConfigUpdate a customer profile configuration by completely replacing it with new data via PUT request.
Update DatasetsTool to update a dataset in PostHog by its ID and project ID.
Update Dataset ItemsTool to fully update a dataset item by its ID in a PostHog project using PUT method.
Update Desktop RecordingUpdate desktop meeting recording details via PATCH.
Update early access project featureThis PATCH endpoint updates a specific early access project feature.
Update endpointTool to update an existing endpoint for a PostHog project.
Update error tracking autocapture controlsTool to fully update an error tracking autocapture control configuration for a PostHog project.
Update evaluationTool to update an existing evaluation in PostHog using PUT request.
Update event definition by uuidUpdate an event definition by sending a PUT request to '/api/projects/{project_id}/event_definitions/{id}/' using the UUID and project ID, provided you have 'event_definition:write' authorization.
Update experiment detailsUpdate an experiment by sending a PUT request with `project_id` and `id`, including new details as JSON/form data.
Update experiment holdoutTool to partially update an experiment holdout in a PostHog project.
Update experiment holdout (full)Tool to fully update an experiment holdout in PostHog using PUT method.
Update experiment saved metricsTool to update an existing experiment saved metric in PostHog.
Update External Data SourcesTool to update an existing external data source in PostHog (e.
Update feature flag configurationManage feature flags for your app with creation, reading, updating, and deletion options.
Update file systemTool to update a file system resource in PostHog by UUID and project ID.
Update group type metricTool to update a specific group usage metric by its ID.
Update hog functionTool to update a hog function by UUID and project ID using PUT method.
Update Insight VariableUpdate an insight variable by replacing all its properties.
Update live debugger breakpointTool to update a live debugger breakpoint for a project.
Update organization details by uuidUpdate specific details of an organization using its UUID.
Update organization batch exportTool to update an existing organization-level batch export configuration in PostHog.
Modify org info via uuidPUT /api/organizations/{id}/: Update organization details by providing a UUID as 'id'.
Update organization domain info and saml configUpdate an organization's authentication domain settings, including SAML SSO configuration and user provisioning policies.
Update organization member by uuidsUpdate an organization member's access level and permissions.
Update organization member detailsUpdate member details in an organization by ID and user UUID.
Update organization proxy recordUpdate an organization's proxy record configuration.
Update role details in organizationUpdate an organization role by submitting its UUID and organization_id in UUID format.
Update persisted folderTool to update an existing persisted folder in PostHog.
Update person propertiesRequest data's "properties" will be updated on a person using "$set" event, affecting only listed properties without deletion or other changes.
Update person property endpointThis endpoint allows for reading and deleting individuals.
Update product tourUpdate an existing product tour in PostHog.
Update project action by idPUT endpoint '/api/projects/{project_id}/actions/{id}/' updates actions in a project by ID, accepts JSON/form data, supports 'format' query, and needs 'action:write' authentication.
Update project batch exportTool to update a batch export configuration within a project using PUT method.
Update project cohort detailsUpdate cohort details of a specific project by ID.
Update project dashboard detailsEndpoint to update an existing dashboard within a project.
Update project early access featureUpdate a specific early access feature of a project by providing the `project_id` and feature `id` (UUID).
Update project event definitionUpdate an existing event definition for a specified project using its UUID.
Update project group type metadataPATCH /api/projects/{project_id}/groups_types/update_metadata: Update group type metadata for a specific project using its project_id.
Update project insight detailsEndpoint "/api/projects/{project_id}/insights/{id}/" allows for updating an insight's details for a given project and insight ID, supporting JSON and CSV formats, with fields like name, query, and various timestamps.
Update project member s role by uuidUpdate explicit project membership using UUIDs.
Update project notebook detailsThe API for interacting with Notebooks.
Update project property definitionUpdate a property definition in a project by its UUID.
Update project session recording playlistUpdate an existing session recording playlist for a project with the specified project_id and playlist short_id.
Update project settingsTool to update project settings and configuration within a PostHog organization.
Update project subscription detailsUpdate a subscription for a specific project.
Update project survey detailsThe `/api/projects/{project_id}/surveys/{id}/` PUT endpoint updates survey details in a project using survey UUID and project ID, accepts JSON/form/multipart data, needs `survey:write` permission, and returns the updated survey.
Update user home settingsTool to update user home settings including homepage and tab configurations.
Update warehouse saved queryUpdate a warehouse saved query in PostHog by completely replacing it with new data.
Update web experimentTool to completely update a web experiment in PostHog using PUT method.
Validate LLM Provider API KeyTool to validate LLM provider API keys without persisting them to PostHog.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

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

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard 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.
  • Go to Settings and copy your API key.
  • This key lets your Mastra agent talk to Composio and reach Posthog through MCP.

Install dependencies

bash
npm install @composio/core @mastra/core @mastra/mcp @ai-sdk/openai dotenv

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

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

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

Import libraries and validate environment

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,
});
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

Create a Tool Router session for Posthog

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

  const composioMCPUrl = session.mcp.url;
  console.log("Posthog MCP URL:", composioMCPUrl);
What's happening:
  • create spins up a short-lived MCP HTTP endpoint for this user
  • The toolkits array contains "posthog" for Posthog access
  • session.mcp.url is the MCP URL that Mastra's MCPClient will connect to

Configure Mastra MCP client and fetch tools

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);
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 Posthog toolkit

Create the Mastra agent

typescript
const agent = new Agent({
    name: "posthog-mastra-agent",
    instructions: "You are an AI agent with Posthog tools via Composio.",
    model: "openai/gpt-5",
  });
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

Set up interactive chat interface

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: {
        posthog: 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);
});
What's happening:
  • messages keeps the full conversation history in Mastra's expected format
  • agent.generate runs the agent with conversation history and Posthog 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

Complete Code

Here's the complete code to get you started with Posthog and Mastra AI:

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: ["posthog"],
  });

  const composioMCPUrl = session.mcp.url;

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

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "posthog-mastra-agent",
    instructions: "You are an AI agent with Posthog 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: { posthog: 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 Posthog 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 Posthog MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Posthog MCP?

With a standalone Posthog MCP server, the agents and LLMs can only access a fixed set of Posthog tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Posthog 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 Posthog tools.

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

Yes, absolutely. You can configure which Posthog 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 Posthog data and credentials are handled as safely as possible.

Used by agents from

Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.