How to integrate Gleap MCP with Pydantic AI

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Gleap logo
Pydantic AI logo
divider

Introduction

This guide walks you through connecting Gleap to Pydantic AI using the Composio tool router. By the end, you'll have a working Gleap agent that can archive resolved support tickets from last week, send a chat message to follow up on feedback, list all articles in the onboarding collection through natural language commands.

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

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

Also integrate Gleap with

TL;DR

Here's what you'll learn:
  • How to set up your Composio API key and User ID
  • How to create a Composio Tool Router session for Gleap
  • How to attach an MCP Server to a Pydantic AI agent
  • How to stream responses and maintain chat history
  • How to build a simple REPL-style chat interface to test your Gleap workflows

What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.

Key features include:

  • Type Safety: Built on Pydantic for automatic data validation
  • MCP Support: Native support for Model Context Protocol servers
  • Streaming: Built-in support for streaming responses
  • Async First: Designed for async/await patterns

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

The Gleap MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Gleap account. It provides structured and secure access to your customer feedback data, so your agent can perform actions like managing support tickets, communicating with users, organizing help center content, and handling team workflows on your behalf.

  • Ticket creation and management: Instantly create new support tickets, archive resolved issues, or retrieve existing tickets to streamline customer support workflows.
  • Chat and user communication: Allow your agent to send new chat messages or fetch entire chat histories, making it easy to keep conversations going with users.
  • Help center organization: Create collections or retrieve articles in your help center, enabling your agent to help manage and organize your knowledge base content efficiently.
  • Team and user administration: Add new teams for ticket assignment or remove users from projects, so you can stay on top of team management tasks without lifting a finger.
  • Checklist and engagement tracking: Fetch detailed checklists to monitor user engagement or onboarding progress, giving your agent context to provide personalized support.

Supported Tools & Triggers

Tools
Archive All TicketsTool to archive all tickets matching specific type and status criteria.
Archive a TicketTool to archive a ticket.
Clone EngagementTool to clone an existing engagement.
Create a CollectionTool to create a help center collection.
Create AI ContentTool to create or update AI content in Gleap's knowledge base.
Create a new chat messageCreates a new chat message in a Gleap chat session.
Create a new sessionCreate a new user session in Gleap and associate it with a project.
Create a new teamTool to create a new team.
Create a new ticketCreate a new support ticket in Gleap with detailed information including title, description, type, priority, status, tags, and attachments.
Create Engagement BannerTool to create a new engagement banner in Gleap.
Create Engagement ChecklistTool to create a new engagement checklist.
Create Engagement CobrowseTool to create a new cobrowse product tour.
Create Engagement EmailTool to create a new engagement email in Gleap.
Create Engagement ModalTool to create a new engagement modal in Gleap.
Create Engagement Product TourTool to create a new product tour in Gleap.
Create Engagement Push NotificationTool to create a new push notification in Gleap.
Create Engagement TooltipTool to create a new engagement tooltip in Gleap.
Create feedback itemTool to manually create a feedback item (bug) in a Gleap project.
Create Help Center RedirectTool to create a new redirect for help center URLs.
Create Message TemplateTool to create a new message template in Gleap.
Create new conversation with sessionCreate a new conversation with a session in Gleap.
Create QA SnippetTool to create a QA snippet (question-answer pair) in Gleap.
Create Tracker TicketTool to create a tracker ticket in Gleap.
Delete AI ContentTool to delete AI content by content ID.
Delete AI Content BatchTool to delete all AI content by batchId.
Delete a User from a ProjectRemoves a user (team member) from a Gleap project, revoking their access.
Delete BugsTool to delete a bug/ticket by ID.
Delete Engagement BannerTool to delete an engagement banner.
Delete Engagement Chat MessageDeletes an engagement chat message from Gleap by its ID.
Delete Engagement ChecklistTool to delete an engagement checklist by its ID.
Delete Engagement CobrowseTool to delete a cobrowse product tour by its ID.
Delete Engagement EmailTool to delete an engagement email by its ID.
Delete Engagement ModalTool to delete an engagement modal from a Gleap project.
Delete Engagement NewsTool to delete an engagement news article.
Delete Engagement Product TourTool to delete an engagement product tour by its ID.
Delete Engagement Push NotificationTool to delete an engagement push notification by its ID.
Delete Engagement SurveysTool to delete an engagement survey.
Delete Engagement TooltipsTool to delete an engagement tooltip.
Delete Engagement WhatsApp MessageTool to delete an engagement WhatsApp message by its ID.
Delete Help Center CollectionTool to delete a help center collection by ID.
Delete Help Center RedirectTool to delete a help center redirect.
Delete MessageTool to delete a message (comment) from a bug or ticket.
Delete Message TemplateTool to delete a message template.
Delete Old AI Content BatchesDelete all AI content batches except the current batch.
Delete QA AnswerTool to delete a QA answer (snippet) from a Gleap project.
Delete project sessionTool to delete a session from a Gleap project.
Delete sessionTool to delete a session by ID.
Delete TeamTool to delete a team by ID.
Delete TicketTool to delete a ticket by ID.
Export sessionsTool to export sessions for the authenticated project in CSV format.
Export Statistics ListsTool to export statistics list data as CSV from Gleap.
Generate ticket draft replyTool to generate an AI-powered draft reply for a ticket.
Generate tracker ticket dataTool to generate AI-powered tracker ticket data from an existing ticket.
Get a ChecklistTool to retrieve a specific engagement checklist by its ID.
Get a CollectionTool to retrieve a help center collection by ID.
Get AI contentTool to retrieve AI content by its content ID.
Get all articlesTool to retrieve articles in a help center collection.
Get all chat messagesRetrieves all engagement chat messages from the current Gleap project.
Get All CollectionsRetrieves all help center collections for the authenticated project.
Get All Invitations for a ProjectRetrieves all pending invitations for a project.
Get all sessionsRetrieves all user sessions for the authenticated project.
Get All TeamsTool to retrieve all teams.
Get All TicketsRetrieve tickets from a Gleap project with optional filtering, sorting, and pagination.
Get All Users for a ProjectTool to retrieve all users for a project.
Get a ticketRetrieves complete details for a specific ticket by its ID.
Get current userRetrieves the authenticated user's profile including email, name, user type, availability status, notification preferences, and 2FA settings.
Get engagement activities countTool to retrieve the count of activities for a specific engagement.
Get engagement bannerTool to retrieve an engagement banner by its ID.
Get Engagement BannersTool to retrieve all engagement banners from a Gleap project.
Get engagement chat messageRetrieves a specific engagement chat message by its ID.
Get Engagement ChecklistsTool to retrieve all engagement checklists for a project.
Get Engagement CobrowseRetrieves all cobrowse product tours for the authenticated project.
Get engagement cobrowse by IDTool to retrieve a specific cobrowse product tour by its ID.
Get engagement emailRetrieves a specific engagement email by its ID.
Get Engagement EmailsTool to retrieve all engagement emails from a Gleap project.
Get engagement modalTool to retrieve an engagement modal by its ID.
Get Engagement ModalsTool to retrieve all engagement modals from a Gleap project.
Get Engagement NewsTool to retrieve all engagement news articles from a Gleap project.
Get engagement news articleRetrieves a specific engagement news article by its ID.
Get a Product TourTool to retrieve a specific engagement product tour by its ID.
Get Engagement Product ToursTool to retrieve all engagement product tours for a project.
Get engagement push notificationRetrieves a specific engagement push notification by its ID.
Get Engagement Push NotificationsTool to retrieve all engagement push notifications from a Gleap project.
Get Engagements ActivitiesTool to retrieve all activities for a specific engagement.
Get engagement recipientsTool to find and retrieve recipients for a specific engagement.
Get engagement statisticsTool to retrieve statistics for a specific engagement.
Get Engagement SurveyTool to retrieve a survey by its ID.
Get Engagement SurveysTool to retrieve all engagement surveys from a Gleap project.
Get Survey ResponsesTool to retrieve all survey responses for a specific survey.
Get Engagement Survey Response SamplesTool to retrieve survey response samples for a specific engagement survey.
Summarize Survey ResponsesTool to retrieve an AI-generated summary of survey responses.
Get Engagement Tooltip by IDTool to retrieve a specific engagement tooltip by its ID.
Get Engagement TooltipsTool to retrieve all engagement tooltips for the authenticated project.
Get engagement WhatsApp messageRetrieves a specific engagement WhatsApp message by its ID.
Get Help Center SourcesRetrieves all configured help center sources (knowledge base content sources) for the project.
Get InvitationsRetrieves all invitations for the authenticated user.
Get message templateRetrieves a specific message template by its ID from a Gleap project.
Get Message TemplatesRetrieve all message templates for the authenticated project.
Get notification ticketRetrieves detailed information about a Gleap ticket using its notification share token.
Get projectRetrieves complete details for a specific project by its ID.
Get ProjectsRetrieves all projects accessible to the authenticated user.
Get archived bugsTool to retrieve archived bugs for a specific project.
Get Projects Help Center CollectionsTool to get all help center collections for a project.
Get project sessionsTool to retrieve all sessions for a specific project.
Get Projects TicketsTool to retrieve all tickets from a specific Gleap project.
Get project usersTool to get project users by project ID.
Get a sessionRetrieves detailed information for a specific session by its ID.
Get session activitiesRetrieves all activities for a specific session by session ID.
Get session Chargebee infoTool to retrieve Chargebee billing information for a specific session.
Get Session ChecklistsRetrieve all engagement checklists associated with a user session in Gleap.
Get session events by IDTool to retrieve all streamed events for a specific session by its ID.
Get session LemonSqueezy infoTool to retrieve LemonSqueezy subscription and payment information for a specific session.
Get Session Shopify InfoRetrieve Shopify information associated with a user session in Gleap.
Get Shared Help Center AnswerRetrieves an answer to a question from the shared help center knowledge base.
Get email client bounce statisticsTool to retrieve email client bounce statistics from Gleap.
Get Email Client Usage StatisticsTool to retrieve email client usage statistics from Gleap.
Get email overview statisticsTool to retrieve email overview statistics from Gleap.
Get statistics factsTool to retrieve fact data for various statistics from Gleap.
Get Statistics HeatmapRetrieve heatmap data for activity patterns in Gleap.
Get Statistics ListsTool to retrieve statistics list data from Gleap.
Get Statistics Raw DataTool to retrieve raw statistics data from Gleap.
Get Tickets By Session QueryFind tickets by session query parameters such as email, userId, phone, or custom data.
Get Tickets ExportExport tickets from Gleap project with optional filtering and sorting.
Get Tickets Export FieldsRetrieve available fields for ticket export from Gleap.
Search Tickets by TermSearch for tickets using a text search term in Gleap.
Get Tickets CountTool to get the total count of tickets in a Gleap project.
Get current user's permissionsTool to retrieve the current user's role permissions.
Get users unified inboxRetrieves tickets from the unified inbox for the authenticated user.
Get users unified inbox ticketRetrieves complete details for a specific ticket from the unified inbox by its ID.
Identify or update userIdentify or update a user's information in Gleap.
Import sessionImport user sessions into Gleap for tracking and analytics.
Import sessions from IntercomImport user sessions from Intercom into Gleap.
Indicate user typingTool to indicate that a user is typing in a ticket conversation.
Indicate user viewingTool to indicate that a user is viewing a ticket.
Link a TicketTool to link a ticket.
Mark Survey Responses as ReadTool to mark all survey responses as read for a given survey.
Merge ticketsTool to merge multiple tickets into a single target ticket in Gleap.
Post a comment on a bugTool to post a comment/message on a bug or ticket in Gleap.
Create Engagement News ArticleTool to create a new engagement news article in Gleap.
Create Engagement SurveyTool to create a new survey in Gleap.
Create WhatsApp Engagement MessageTool to create a new WhatsApp message in Gleap for user engagement.
Reassign all tickets to userTool to reassign all tickets to the authenticated user.
Resubscribe a SessionTool to resubscribe a session.
Search for sessionsSearch for sessions in Gleap using various filter criteria.
Search messagesSearch messages in Gleap by search term.
Search sessions by indexSearch for sessions in a project using the session search index.
Send Engagement Email PreviewTool to send a preview of an engagement email to specified email addresses.
Send ticket transcriptTool to send ticket conversation transcript to multiple email addresses.
Snooze a TicketTool to snooze a ticket for a specified duration.
Suggest FAQ from messageTool to suggest a FAQ from a message.
Toggle Collection Publish StatusTool to toggle the publish status of a help center collection.
Track eventsTrack custom user events in Gleap for analytics and user behavior monitoring.
Unarchive a TicketTool to unarchive a ticket.
Unlink a TicketTool to unlink a ticket.
Unsubscribe sessionsTool to unsubscribe one or more user sessions from communications.
Update AI Content by Content IDTool to update AI content by content ID.
Update a teamTool to update an existing team.
Update a ticketTool to update an existing ticket/bug in Gleap.
Update a User for a ProjectTool to update a user’s role in a project.
Update Chat MessageUpdates an existing chat message in Gleap by its ID.
Update a ChecklistTool to update an engagement checklist by its ID.
Update Engagement BannerTool to update an engagement banner.
Update Engagement CobrowseTool to update an existing cobrowse product tour.
Update Engagement EmailTool to update an existing engagement email.
Update Engagement ModalTool to update an existing engagement modal.
Update Engagement NewsTool to update an engagement news article.
Update Engagement Product TourTool to update an existing product tour.
Update Engagement Push NotificationTool to update an existing push notification.
Update Engagement SurveyTool to update an existing engagement survey in Gleap.
Update Engagement TooltipsTool to update an engagement tooltip.
Update Engagement WhatsApp MessageTool to update an existing engagement WhatsApp message.
Update Helpcenter CollectionTool to update a help center collection.
Update help center redirectTool to update an existing help center redirect.
Update message templateTool to update an existing message template in Gleap.
Update projectTool to update a Gleap project's configuration including name, description, notification settings, and feedback tags.
Update QA AnswerUpdates an existing QA answer/snippet in Gleap.
Update a sessionTool to update an existing session in Gleap.
Update userTool to update a user's profile information including name, availability, profile image, onboarding status, and notification settings.
Vote for ticketTool to vote for a ticket in Gleap.

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:
  • Python 3.9 or higher
  • A Composio account with an active API key
  • Basic familiarity with Python and async programming

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.

Install dependencies

bash
pip install composio pydantic-ai python-dotenv

Install the required libraries.

What's happening:

  • composio connects your agent to external SaaS tools like Gleap
  • pydantic-ai lets you create structured AI agents with tool support
  • python-dotenv loads your environment variables securely from a .env file

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your agent to Composio's API
  • USER_ID associates your session with your account for secure tool access
  • OPENAI_API_KEY to access OpenAI LLMs

Import dependencies

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
What's happening:
  • We load environment variables and import required modules
  • Composio manages connections to Gleap
  • MCPServerStreamableHTTP connects to the Gleap MCP server endpoint
  • Agent from Pydantic AI lets you define and run the AI assistant

Create a Tool Router Session

python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Gleap
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["gleap"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
What's happening:
  • We're creating a Tool Router session that gives your agent access to Gleap tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use

Initialize the Pydantic AI Agent

python
# Attach the MCP server to a Pydantic AI Agent
gleap_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[gleap_mcp],
    instructions=(
        "You are a Gleap assistant. Use Gleap tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
What's happening:
  • The MCP client connects to the Gleap endpoint
  • The agent uses GPT-5 to interpret user commands and perform Gleap operations
  • The instructions field defines the agent's role and behavior

Build the chat interface

python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Gleap.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
What's happening:
  • The agent reads input from the terminal and streams its response
  • Gleap API calls happen automatically under the hood
  • The model keeps conversation history to maintain context across turns

Run the application

python
if __name__ == "__main__":
    asyncio.run(main())
What's happening:
  • The asyncio loop launches the agent and keeps it running until you exit

Complete Code

Here's the complete code to get you started with Gleap and Pydantic AI:

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Gleap
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["gleap"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    gleap_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[gleap_mcp],
        instructions=(
            "You are a Gleap assistant. Use Gleap tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Gleap.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())

Conclusion

You've built a Pydantic AI agent that can interact with Gleap through Composio's Tool Router. With this setup, your agent can perform real Gleap actions through natural language. You can extend this further by:
  • Adding other toolkits like Gmail, HubSpot, or Salesforce
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Gleap for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.

How to build Gleap MCP Agent with another framework

FAQ

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

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

Can I use Tool Router MCP with Pydantic AI?

Yes, you can. Pydantic 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 Gleap tools.

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

Yes, absolutely. You can configure which Gleap 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 Gleap 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.