How to integrate Launch darkly MCP with Pydantic AI

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Launch darkly logo
Pydantic AI logo
divider

Introduction

This guide walks you through connecting Launch darkly to Pydantic AI using the Composio tool router. By the end, you'll have a working Launch darkly agent that can list all environments for your project, retrieve all custom roles for audit, create a trigger workflow for a flag through natural language commands.

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

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

Also integrate Launch darkly 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 Launch darkly
  • 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 Launch darkly 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 Launch darkly MCP server, and what's possible with it?

The Launch darkly MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Launch darkly account. It provides structured and secure access to your feature management platform, so your agent can perform actions like managing feature flag workflows, listing projects, retrieving environments, and reviewing teams or custom roles.

  • Automated flag trigger workflows: Set up, modify, or delete flag trigger workflows so your agent can help automate feature releases and rollbacks in specific environments.
  • Comprehensive project and environment listing: Instantly retrieve all projects and their environments to help your agent audit, enumerate, or manage deployment contexts.
  • Team and role audits: List all teams and custom roles, making it easy for your agent to review permissions, conduct audits, or suggest configuration changes.
  • Code reference repository discovery: Pull complete lists of code reference repositories tied to your projects for better traceability and DevOps integration.
  • Effortless environment and project management: Quickly access and enumerate environments and projects to streamline workflows and improve operational oversight.

Supported Tools & Triggers

Tools
Add Member to TeamsTool to add a LaunchDarkly member to one or more teams.
Apply Approval RequestTool to apply an approved approval request in LaunchDarkly.
Apply Approval Request for FlagTool to apply an approved approval request for a feature flag in LaunchDarkly.
Copy Feature FlagTool to copy a feature flag's configuration from one environment to another within the same project.
Create AnnouncementTool to create a public announcement in LaunchDarkly.
Create Approval RequestTool to create an approval request in LaunchDarkly.
Create Approval Request for FlagTool to create an approval request for a feature flag in LaunchDarkly.
Create Approval Request ReviewTool to review an approval request by approving, declining, or commenting on changes.
Create Approval Request Review for FlagTool to review an approval request for a feature flag by approving, declining, or commenting on the changes.
Create Big Segment ExportTool to create an export for a big segment in LaunchDarkly.
Create Big Segment Store IntegrationTool to create a persistent store integration for big segments in LaunchDarkly.
Create Custom RoleTool to create a new custom role in LaunchDarkly.
Create Data Export DestinationTool to create a new Data Export destination for exporting LaunchDarkly event data to external services.
Create EnvironmentTool to create a new environment within a LaunchDarkly project.
Create ExperimentTool to create a new experiment in LaunchDarkly.
Create Extinction EventsTool to create new extinction events for feature flags in LaunchDarkly.
Create Feature FlagTool to create a new feature flag in LaunchDarkly.
Create Flag Scheduled ChangesTool to create a scheduled changes workflow for a feature flag in LaunchDarkly.
Create Flag Copy Config Approval RequestTool to create an approval request for copying a feature flag's configuration from one environment to another.
Create Flag Import ConfigurationTool to create a new flag import configuration for importing feature flags from external feature management systems like Split or Unleash.
Create Flag LinkTool to create a new flag link in LaunchDarkly.
Create HoldoutTool to create a new holdout in LaunchDarkly for experiment control groups.
Create Integration ConfigurationTool to create a new integration configuration in LaunchDarkly.
Create Experiment IterationTool to create a new iteration for an experiment in LaunchDarkly.
Create LayerTool to create a new layer in a LaunchDarkly project.
Create MembersTool to invite one or more new members to join a LaunchDarkly account.
Create MetricTool to create a new metric in LaunchDarkly.
Create Metric GroupTool to create a new metric group in LaunchDarkly.
Create Migration Safety IssuesTool to check migration safety issues for a feature flag patch.
Create OAuth 2.0 ClientTool to create (register) a LaunchDarkly OAuth 2.
Create ProjectTool to create a new project with the given key and name.
Create Relay Proxy Auto ConfigurationTool to create a new Relay Proxy configuration in LaunchDarkly.
Create Release for FlagTool to create a release by adding a flag to a release pipeline in LaunchDarkly.
Create Release PipelineTool to create a release pipeline in LaunchDarkly.
Create Release PolicyTool to create a new release policy for a specified project.
Create RepositoryTool to create a code reference repository with the specified name.
Create SegmentTool to create a new segment in LaunchDarkly.
Create Audit Log SubscriptionTool to create a new audit log subscription for forwarding LaunchDarkly audit events to external services.
Create TeamTool to create a new team in LaunchDarkly.
Create Flag Trigger WorkflowCreates a flag trigger workflow in LaunchDarkly.
Create WebhookTool to create a new webhook in LaunchDarkly.
Create WorkflowTool to create a workflow in LaunchDarkly for automating flag changes.
Create Workflow TemplateTool to create a workflow template in LaunchDarkly.
Delete AnnouncementTool to permanently delete an announcement from LaunchDarkly.
Delete Approval RequestTool to delete an approval request in LaunchDarkly.
Delete Approval Request for FlagPermanently deletes an approval request for a feature flag in LaunchDarkly.
Delete Big Segment Store IntegrationTool to permanently delete a persistent store integration for big segments.
Delete Branches from Code Reference RepositoryAsynchronously deletes multiple branches from a LaunchDarkly code reference repository.
Delete Custom RolePermanently deletes a custom role from LaunchDarkly.
Delete Data Export DestinationPermanently deletes a Data Export destination from LaunchDarkly.
Delete EnvironmentTool to permanently delete an environment from a LaunchDarkly project.
Delete Feature FlagTool to permanently delete a feature flag from LaunchDarkly.
Delete Flag Scheduled ChangesTool to delete scheduled changes workflow for a feature flag in LaunchDarkly.
Delete Flag Import ConfigurationTool to delete a flag import configuration by ID.
Delete Flag LinkPermanently deletes a flag link from LaunchDarkly.
Delete Integration ConfigurationPermanently deletes an integration configuration from LaunchDarkly.
Delete Account MemberTool to permanently delete an account member from LaunchDarkly.
Delete MetricTool to permanently delete a metric from LaunchDarkly.
Delete Metric GroupTool to permanently delete a metric group from LaunchDarkly.
Delete OAuth 2.0 ClientPermanently deletes an OAuth 2.
Delete ProjectTool to permanently delete a project from LaunchDarkly.
Delete Relay Proxy Auto ConfigurationTool to delete a Relay Proxy auto configuration by ID.
Delete Release by Flag KeyTool to delete a release from a feature flag.
Delete Release PipelineTool to permanently delete a release pipeline from LaunchDarkly.
Delete Release PolicyTool to permanently delete a release policy from a LaunchDarkly project.
Delete RepositoryTool to delete a code reference repository with the specified name.
Delete SegmentPermanently deletes a segment from LaunchDarkly.
Delete Audit Log SubscriptionTool to permanently delete an audit log subscription in LaunchDarkly.
Delete TeamPermanently deletes a team from LaunchDarkly organization.
Delete Access TokenTool to permanently delete an access token from LaunchDarkly.
Delete Flag Trigger WorkflowPermanently deletes a flag trigger workflow from LaunchDarkly.
Delete WebhookTool to delete a webhook from LaunchDarkly.
Delete WorkflowPermanently deletes a workflow from LaunchDarkly.
Delete Workflow TemplatePermanently deletes a workflow template from LaunchDarkly.
Evaluate Context InstanceTool to evaluate flags for a context instance to determine expected flag variations.
Generate Trust Policy for Data ExportTool to generate an AWS trust policy for Data Export destinations.
Get All HoldoutsTool to retrieve all holdouts for a specific project and environment.
Get All Integration ConfigurationsTool to retrieve all integration configurations for a specific integration key.
Get All Release PipelinesTool to retrieve all release pipelines for a project.
Get All WebhooksTool to retrieve all webhooks configured in the LaunchDarkly account.
Get Announcements PublicTool to retrieve public announcements from LaunchDarkly.
Get ApplicationsTool to retrieve a list of applications in LaunchDarkly.
Get Application VersionsTool to retrieve all versions for a specific application in LaunchDarkly.
Get Approval for FlagTool to get a single approval request for a feature flag in LaunchDarkly.
Get Approval RequestTool to get a specific approval request by ID from LaunchDarkly.
Get Approval RequestsTool to retrieve all approval requests from LaunchDarkly.
Get Approval Request SettingsTool to retrieve approval request settings for a project.
Get Approvals for FlagTool to retrieve all approval requests for a specific feature flag in an environment.
Get Audit Log EntriesTool to get a list of all audit log entries.
Get Audit Log EntryTool to retrieve a single audit log entry by ID.
Get Big Segment ExportTool to retrieve a specific big segment export by its ID.
Get Big Segment ImportTool to retrieve the status and details of a big segment import by its ID.
Get Big Segment Store IntegrationTool to retrieve a specific persistent store integration for big segments by its ID.
Get Big Segment Store IntegrationsTool to retrieve all persistent store integrations for big segments.
Get BranchTool to retrieve branch information from a LaunchDarkly code reference repository.
Get Caller IdentityTool to retrieve basic information about the identity used to authenticate API calls.
Get Context Attribute NamesTool to retrieve context attribute names for a project and environment.
Get Context Attribute ValuesTool to retrieve unique values for a specific context attribute within a project environment.
Get Context InstancesTool to get context instances for a specific context ID within a project and environment.
Get Context Kinds By Project KeyTool to retrieve all context kinds for a given project.
Get ContextsTool to retrieve context instances from a LaunchDarkly environment by kind and key.
Get Contexts Clientside UsageTool to get a detailed time series of context key usages observed by LaunchDarkly in your account, including non-primary context kinds.
Get Contexts Serverside UsageTool to get detailed time series of context key usages observed by LaunchDarkly in your account, including non-primary context kinds.
Get Contexts Total UsageTool to get a detailed time series of the number of context key usages observed by LaunchDarkly in your account, including non-primary context kinds.
Get Context Instance Segments Membership By EnvironmentTool to get segment membership details for a given context instance with attributes.
Get Custom RoleTool to retrieve a single custom role by key or ID.
Get Custom RolesTool to retrieve a list of all custom roles.
Get Custom WorkflowTool to retrieve details of a specific custom workflow by ID.
Get Data Export Events UsageTool to retrieve a time series array showing the number of data export events from your account.
Get Dependent FlagsTool to list dependent feature flags for a specific flag.
Get Dependent Flags By EnvironmentTool to list dependent flags across all environments for a specified flag.
Get Data Export DestinationTool to retrieve a specific Data Export destination by ID.
Get Data Export DestinationsTool to retrieve all Data Export destinations configured across all projects and environments.
Get EnvironmentTool to retrieve a specific environment by project key and environment key.
Get EnvironmentsTool to retrieve a list of all environments within a project.
Get Evaluations UsageTool to get time-series arrays of flag evaluation counts, broken down by variation.
Get Events UsageTool to get time-series arrays of flag evaluation events.
Get ExperimentTool to retrieve a specific experiment by project key, environment key, and experiment key.
Get Experimentation Events UsageTool to retrieve a time series array showing the number of experimentation events from your account.
Get Experimentation Keys UsageTool to get a time series showing the number of experimentation keys from your account.
Get Experimentation SettingsTool to retrieve experimentation settings for a project.
Get ExperimentsTool to retrieve experiments from a project and environment.
Get Expiring Context TargetsTool to retrieve context targets scheduled for removal from a feature flag.
Get Expiring Targets For SegmentTool to retrieve context targets scheduled for removal from a segment.
Get ExtinctionsTool to get a list of all extinctions.
Get Feature FlagTool to retrieve a specific feature flag by project key and flag key.
Get Feature FlagsTool to retrieve a list of all feature flags in a project.
Get Feature Flag Scheduled ChangeTool to retrieve a specific scheduled change for a feature flag.
Get Feature Flag StatusTool to retrieve the status of a feature flag.
Get Feature Flag Status Across EnvironmentsTool to retrieve the status of a feature flag across all environments in a project.
Get Feature Flag StatusesTool to retrieve status information for all feature flags in a project environment.
Get Flag Scheduled ChangesTool to retrieve scheduled changes for a feature flag.
Get Flag Defaults by ProjectTool to retrieve flag defaults for a specific project.
Get Flag FollowersTool to retrieve followers of a flag in a project and environment.
Get Flag Import ConfigurationTool to retrieve a single flag import configuration by project key, integration key, and integration ID.
Get Flag Import ConfigurationsTool to list all flag import configurations.
Get Flag LinksTool to retrieve all flag links for a specific feature flag.
Get Followers By Project and EnvironmentTool to retrieve followers of all flags in a given project and environment.
Get HoldoutTool to retrieve a specific holdout experiment by project key, environment key, and holdout key.
Get Integration ConfigurationTool to retrieve a specific integration configuration by ID.
Get Integration Delivery Configuration by EnvironmentTool to get delivery configurations by environment for feature store integrations.
Get IPsTool to retrieve the list of IP ranges used by the LaunchDarkly service.
Get LayersTool to retrieve layers for a project.
Get MAU Clientside UsageTool to get a time series of context key usages observed by LaunchDarkly client-side SDKs for the primary context kind.
Get MAU Total UsageTool to get a time series of the number of context key usages observed by LaunchDarkly in your account, for the primary context kind only.
Get MAU UsageTool to get a time-series array of monthly active users (MAU) seen by LaunchDarkly from your account.
Get MAU Usage By CategoryTool to get time-series arrays of monthly active users (MAU) by category (browser, mobile, or backend).
Get Account MemberTool to retrieve detailed information about a specific LaunchDarkly account member.
Get MembersTool to retrieve a list of account members.
Get MetricTool to retrieve a specific metric by project key and metric key.
Get Metric GroupTool to retrieve a specific metric group by project key and metric group key.
Get OAuth 2.0 Client by IDTool to retrieve a registered OAuth 2.
Get OAuth 2.0 ClientsTool to retrieve all OAuth 2.
Get Observability Errors UsageTool to get time-series arrays of the number of observability errors.
Get Observability Logs UsageTool to retrieve time-series arrays of observability logs usage data.
Get Observability Sessions UsageTool to get time-series arrays of the number of observability sessions.
Get Observability Traces UsageTool to retrieve time-series arrays of observability traces usage data.
Get OpenAPI SpecTool to retrieve the latest OpenAPI specification for LaunchDarkly's API in JSON format.
Get ProjectTool to retrieve a specific project by project key.
Get Relay Proxy ConfigTool to retrieve a single Relay Proxy auto configuration by ID.
Get Relay Proxy ConfigsTool to retrieve all Relay Proxy configurations in the LaunchDarkly account.
Get Release by Flag KeyTool to retrieve the currently active release for a feature flag.
Get Release Pipeline by KeyTool to retrieve a release pipeline by its key.
Get Release PoliciesTool to retrieve a list of release policies for a specified project.
Get Release PolicyTool to retrieve a single release policy by its key for a specified project.
Get All Release Progressions for Release PipelineTool to retrieve details on the progression of all releases, across all flags, for a release pipeline.
Get RepositoryTool to get a single code reference repository by name.
Get RootTool to retrieve the LaunchDarkly API root resource.
Get Root Code Reference StatisticTool to get links to code reference repositories for each project.
Get SegmentTool to retrieve a specific segment by segment key.
Get Segment Membership For ContextTool to get big segment membership status for a specific context.
Get SegmentsTool to retrieve a list of all segments in a project and environment.
Get Service Connections UsageTool to get a time series array showing the number of service connection minutes from your account.
Get Code References StatisticsTool to retrieve code references statistics for feature flags.
Get Stream UsageTool to get time-series data of streaming connections to LaunchDarkly.
Get Stream Usage By SDK VersionTool to get time-series data of streaming connections to LaunchDarkly, separated by SDK type and version.
Get Stream Usage SDK VersionsTool to get a list of SDK version objects from LaunchDarkly.
Get Audit Log Subscription by IDTool to retrieve a specific audit log subscription by ID.
Get Audit Log Subscriptions by IntegrationTool to retrieve all audit log subscriptions for a given integration.
Get TagsTool to retrieve a list of tags from LaunchDarkly.
Get TeamTool to fetch a specific team by key.
Get Team MaintainersTool to retrieve the list of maintainers for a specific LaunchDarkly team.
Get Team RolesTool to fetch the custom roles that have been assigned to a team.
Get Access TokenTool to retrieve detailed information about a specific LaunchDarkly access token by its ID.
Get TokensTool to fetch a list of all access tokens.
Get Flag Trigger by IDTool to retrieve details of a specific flag trigger by ID.
Get Flag Trigger WorkflowsTool to retrieve all flag triggers for a specific feature flag in an environment.
Get VersionsTool to retrieve LaunchDarkly API version information.
Get WebhookTool to retrieve a specific webhook by ID.
Get WorkflowsTool to retrieve workflows for a specific feature flag in an environment.
Get Workflow TemplatesTool to retrieve workflow templates belonging to an account.
List Branches in Code Reference RepositoryTool to list branches in a LaunchDarkly code reference repository.
List Code Reference RepositoriesLists all code reference repositories configured in LaunchDarkly.
List Integration Delivery ConfigurationsTool to list all integration delivery configurations.
List Metric GroupsTool to retrieve a list of all metric groups in a project.
List MetricsTool to retrieve a list of all metrics in a project.
List ProjectsTool to retrieve a list of all projects.
List TeamsFetches one page of teams from LaunchDarkly.
Patch Approval Request SettingsTool to perform a partial update to approval request settings for a project.
Patch Big Segment Store IntegrationTool to update a persistent store integration for big segments using JSON Patch operations.
Patch Custom RoleTool to update a custom role's settings using JSON Patch operations.
Update Data Export DestinationTool to update a Data Export destination using JSON Patch operations.
Patch EnvironmentTool to update an environment's settings using JSON Patch operations.
Patch ExperimentTool to update an experiment using semantic patch format.
Patch Expiring TargetsTool to update expiring context targets on a feature flag.
Patch Feature FlagTool to update a feature flag's settings using JSON Patch operations.
Patch Flag Config Approval RequestTool to perform a partial update to a flag config approval request using semantic patch format.
Patch Flag Scheduled ChangeTool to update a scheduled change workflow for a feature flag.
Patch Flag Defaults By ProjectTool to update flag defaults for a project using JSON Patch operations.
Patch Flag Import ConfigurationTool to update a flag import configuration using JSON Patch operations.
Patch HoldoutTool to update a LaunchDarkly holdout using semantic patch operations.
Patch Account MemberTool to modify an account member's information using JSON Patch operations.
Patch MembersTool to perform partial updates to multiple LaunchDarkly account members using semantic patch format.
Patch MetricTool to update a metric's settings using JSON Patch operations.
Patch Metric GroupTool to update a metric group's settings using JSON Patch operations.
Patch OAuth 2.0 ClientTool to update an existing OAuth 2.
Update ProjectTool to update a LaunchDarkly project using JSON Patch operations (RFC 6902).
Update Relay Proxy ConfigTool to update a Relay Proxy auto configuration using JSON Patch operations (RFC 6902).
Patch RepositoryTool to update a code reference repository's settings using JSON Patch operations.
Patch SegmentTool to update a segment's settings using JSON Patch operations.
Patch TeamTool to perform partial updates to a LaunchDarkly team using semantic patch format.
Patch TeamsTool to perform partial updates to multiple LaunchDarkly teams using semantic patch format.
Patch Access TokenTool to update an access token's settings using JSON Patch operations.
Update Flag TriggerTool to update a flag trigger using semantic patch operations.
Update WebhookTool to update a LaunchDarkly webhook using JSON Patch operations (RFC 6902).
Create or Update Flag Defaults by ProjectTool to create or update flag defaults for a specific project.
Reset Environment Mobile KeyTool to reset the mobile SDK key for a specific environment.
Reset Environment SDK KeyTool to reset the SDK key for a specific environment.
Reset Relay Proxy Configuration KeyTool to reset the Relay Proxy configuration key.
Reset Access TokenTool to reset a LaunchDarkly access token, generating a new token value.
Search Audit Log EntriesSearch audit log entries in LaunchDarkly.
Search Context InstancesTool to search for context instances within a project and environment.
Search ContextsTool to search for contexts in a LaunchDarkly environment with flexible filtering and sorting.
Trigger Flag Import JobTool to trigger a single flag import run for an existing flag import configuration.
Update AnnouncementTool to update an existing announcement in LaunchDarkly using JSON Patch operations.
Update Big Segment Context TargetsTool to update context targets included or excluded in a big segment.
Update Context Flag SettingTool to enable or disable a feature flag for a specific context based on its context kind and key.
Create or Update Context KindTool to create or update a context kind in a LaunchDarkly project.
Update Experimentation SettingsTool to update experimentation settings for a project.
Update Flag LinkTool to update an existing flag link in LaunchDarkly using JSON Patch operations.
Update Integration ConfigurationTool to update an existing integration configuration in LaunchDarkly using JSON Patch operations.
Update LayerTool to update a layer using semantic patch instructions.
Update Phase StatusTool to update the execution status of a phase in a feature flag release.
Update Release PipelineTool to update an existing release pipeline in LaunchDarkly.
Update Release Policies OrderTool to update the order of existing release policies for a project.
Update Release PolicyTool to update an existing release policy for a specified project.
Update Audit Log SubscriptionTool to update an audit log subscription configuration using JSON Patch operations.
Upsert Branch in Code Reference RepositoryTool to upsert (create or update) a branch in a LaunchDarkly code reference repository.

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 Launch darkly
  • 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 Launch darkly
  • MCPServerStreamableHTTP connects to the Launch darkly 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 Launch darkly
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["launch_darkly"],
    )
    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 Launch darkly 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
launch_darkly_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[launch_darkly_mcp],
    instructions=(
        "You are a Launch darkly assistant. Use Launch darkly tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
What's happening:
  • The MCP client connects to the Launch darkly endpoint
  • The agent uses GPT-5 to interpret user commands and perform Launch darkly 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 Launch darkly.\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
  • Launch darkly 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 Launch darkly 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 Launch darkly
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["launch_darkly"],
    )
    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
    launch_darkly_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[launch_darkly_mcp],
        instructions=(
            "You are a Launch darkly assistant. Use Launch darkly 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 Launch darkly.\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 Launch darkly through Composio's Tool Router. With this setup, your agent can perform real Launch darkly 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 + Launch darkly 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 Launch darkly MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Launch darkly MCP?

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

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

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