How to integrate Bunnycdn MCP with LangChain

This guide walks you through connecting Bunnycdn to LangChain using the Composio tool router. By the end, you'll have a working Bunnycdn agent that can create a new pull zone for static assets, list all dns zones in your bunnycdn account, delete a storage zone by its id through natural language commands. This guide will help you understand how to give your LangChain agent real control over a Bunnycdn account through Composio's Bunnycdn MCP server. Before we dive in, let's take a quick look at the key ideas and tools involved.

Bunnycdn logoBunnycdn
Api Key

BunnyCDN is a global content delivery network offering easy API-based content management. It accelerates your site and app performance by distributing files closer to your users.

126 Tools

Introduction

This guide walks you through connecting Bunnycdn to LangChain using the Composio tool router. By the end, you'll have a working Bunnycdn agent that can create a new pull zone for static assets, list all dns zones in your bunnycdn account, delete a storage zone by its id through natural language commands.

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

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

Also integrate Bunnycdn with

TL;DR

Here's what you'll learn:
  • Get and set up your OpenAI and Composio API keys
  • Connect your Bunnycdn project to Composio
  • Create a Tool Router MCP session for Bunnycdn
  • Initialize an MCP client and retrieve Bunnycdn tools
  • Build a LangChain agent that can interact with Bunnycdn
  • Set up an interactive chat interface for testing

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides tools and abstractions for building agents that can reason, use tools, and maintain conversation context.

Key features include:

  • Agent Framework: Build agents that can use tools and make decisions
  • MCP Integration: Connect to external services through Model Context Protocol adapters
  • Memory Management: Maintain conversation history across interactions
  • Multi-Provider Support: Works with OpenAI, Anthropic, and other LLM providers

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

The Bunnycdn MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Bunnycdn account. It provides structured and secure access to your CDN resources, so your agent can perform actions like managing storage zones, configuring DNS records, creating pull zones, and retrieving zone details on your behalf.

  • Effortless storage zone management: Instantly add or delete storage zones in specific regions, letting your agent optimize file storage based on your needs.
  • Automated DNS configuration: Direct your agent to create, update, or remove DNS records and zones, helping you keep your domain setup fast and flexible.
  • Pull zone creation and removal: Have your agent set up new pull zones or clean up unused ones, streamlining your content delivery workflows with minimal manual intervention.
  • Detailed configuration and status retrieval: Ask your agent to fetch comprehensive details for any DNS or pull zone, ensuring you always have up-to-date insights into your CDN setup.
  • Full account overview and auditing: Let the agent list all your DNS zones and pull critical stats, making it easy to audit or review your Bunnycdn resources on demand.

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

Step by step10 STEPS
1

Prerequisites

Before starting this tutorial, make sure you have:
  • Python 3.10 or higher installed on your system
  • A Composio account with an API key
  • An OpenAI API key
  • Basic familiarity with Python and async programming
2

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.
3

Install dependencies

npm install @composio/langchain @langchain/core @langchain/openai @langchain/mcp-adapters dotenv

Install the required packages for LangChain with MCP support.

What's happening:

  • @composio/langchain provides Composio integration for LangChain
  • @langchain/mcp-adapters enables MCP client connections
  • @langchain/core is the core agent framework
  • dotenv/config loads environment variables
4

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_composio_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's API
  • COMPOSIO_USER_ID identifies the user for session management
  • OPENAI_API_KEY enables access to OpenAI's language models
5

Import dependencies

import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

dotenv.config();
What's happening:
  • We're importing LangChain's MCP adapter and Composio SDK
  • The dotenv/config import loads environment variables from your .env file
  • This setup prepares the foundation for connecting LangChain with Bunnycdn functionality through MCP
6

Initialize Composio client

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });
What's happening:
  • We're loading the COMPOSIO_API_KEY from environment variables and validating it exists
  • Creating a Composio instance that will manage our connection to Bunnycdn tools
  • Validating that COMPOSIO_USER_ID is also set before proceeding
7

Create a Tool Router session

const session = await composio.create(
    userId as string,
    {
        toolkits: ['bunnycdn']
    }
);

const url = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Bunnycdn 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
  • This approach allows the agent to dynamically load and use Bunnycdn tools as needed
8

Configure the agent with the MCP URL

const client = new MultiServerMCPClient({
    "bunnycdn-agent": {
        transport: "http",
        url: url,
        headers: {
            "x-api-key": process.env.COMPOSIO_API_KEY
        }
    }
});

const tools = await client.getTools();

const agent = createAgent({ model: "gpt-5", tools });
What's happening:
  • We're creating a MultiServerMCPClient that connects to our Bunnycdn MCP server via HTTP
  • The client is configured with a name and the URL from our Tool Router session
  • getTools() retrieves all available Bunnycdn tools that the agent can use
  • We're creating a LangChain agent using the GPT-5 model
9

Set up interactive chat interface

let conversationHistory: any[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log("Ask any Bunnycdn related question or task to the agent.\n");

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

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

    conversationHistory.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    const response = await agent.invoke({ messages: conversationHistory });
    conversationHistory = response.messages;

    const finalResponse = response.messages[response.messages.length - 1]?.content;
    console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

    rl.on('close', () => {
        console.log('\n👋 Session ended.');
        process.exit(0);
    });
What's happening:
  • We initialize an empty conversationHistory list to maintain context across interactions
  • A readline interface is used to continuously accept user input from the command line
  • When a user types a message, it's added to the conversation history and sent to the agent
  • The agent processes the request using the invoke() method with the full conversation history
  • Users can type 'exit', 'quit', or 'bye' to end the chat session gracefully
10

Run the application

main().catch((err) => {
    console.error('Fatal error:', err);
    process.exit(1);
});
What's happening:
  • We call the main() function to start the application

Complete Code

Here's the complete code to get you started with Bunnycdn and LangChain:

import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";  
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });

    const session = await composio.create(
        userId as string,
        {
            toolkits: ['bunnycdn']
        }
    );

    const url = session.mcp.url;
    
    const client = new MultiServerMCPClient({
        "bunnycdn-agent": {
            transport: "http",
            url: url,
            headers: {
                "x-api-key": process.env.COMPOSIO_API_KEY
            }
        }
    });
    
    const tools = await client.getTools();
  
    const agent = createAgent({ model: "gpt-5", tools });
    
    let conversationHistory: any[] = [];
    
    console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
    console.log("Ask any Bunnycdn related question or task to the agent.\n");
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        prompt: 'You: '
    });

    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;
        }
        
        conversationHistory.push({ role: "user", content: trimmedInput });
        console.log("\nAgent is thinking...\n");
        
        const response = await agent.invoke({ messages: conversationHistory });
        conversationHistory = response.messages;
        
        const finalResponse = response.messages[response.messages.length - 1]?.content;
        console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

    rl.on('close', () => {
        console.log('\nSession ended.');
        process.exit(0);
    });
}

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

Conclusion

You've successfully built a LangChain agent that can interact with Bunnycdn through Composio's Tool Router.

Key features of this implementation:

  • Dynamic tool loading through Composio's Tool Router
  • Conversation history maintenance for context-aware responses
  • Async Python provides clean, efficient execution of agent workflows
You can extend this further by adding error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.
TOOLS

Supported Tools

Every Bunnycdn action and event your agent gets out of the box.

Add Allowed Referer

Adds a hostname to the allowed referer list for a pull zone.

Add Blocked IP

Tool to add an IP address to the blocked list of a pull zone.

Add Blocked Referer

Tool to add a blocked referer to a pull zone.

Add Storage Zone

Tool to add a new storage zone.

Add/Update Edge Rule

Tool to add or update edge rules in a BunnyCDN pull zone for advanced traffic control.

Check DNS Zone Availability

Tool to check if a DNS zone name is available for registration.

Check Pull Zone Availability

Tool to check if a pull zone name is available for registration.

Check Storage Zone Availability

Tool to check if a storage zone name is available.

Create Database

Creates a new Bunny Database (SQLite-compatible edge database).

Create DNS Record

Tool to create a new DNS record in a specific DNS zone.

Create Live Live 2

Tool to retrieve live metrics data for database groups.

Create Pull Zone

Creates a new CDN pull zone in BunnyCDN for content delivery acceleration.

Create Shield Rate Limit

Tool to create a new Shield rate limit rule for protecting against excessive requests.

Create Shield Zone Access List

Tool to create a new custom access list in a Shield Zone.

Delete Container Registry

Tool to delete a container registry from Magic Containers.

Delete Database

Tool to delete a BunnyCDN database by its ID.

Delete DNS Record

Tool to delete a specific DNS record by its ID.

Delete DNS Zone

Tool to delete a specific DNS zone by its ID.

Delete Edge Rule

Tool to delete an Edge Rule from a Pull Zone by its ID.

Delete Database Group

Tool to delete a specific database group by its ID.

Delete Pull Zone

Tool to delete a specific pull zone by its ID.

Delete Shield Zone Access List

Tool to delete a custom access list from a Shield Zone.

Delete Storage Zone

Tool to delete a storage zone.

Generate 2FA Verification

Tool to generate 2FA verification details for account security setup.

Generate Database Auth Token

Tool to generate an authentication token for a BunnyCDN database.

Get Billing Summary

Tool to retrieve billing summary with data report for each Pull Zone.

Get Container Config Suggestions

Tool to get AI-powered configuration suggestions for deploying a container image on BunnyCDN's Magic Containers platform.

Get Container Image Digest

Tool to retrieve the digest of a container image from a registry.

Get Database

Tool to retrieve details of a specific database by its ID.

Get Database Statistics

Tool to retrieve time-series statistics for a Bunny Database instance.

Get DNS Zone Details

Tool to retrieve details of a specific DNS zone by its ID.

Get DNS Zone List

Tool to list all DNS zones in your Bunny CDN account.

Get Database Group

Tool to retrieve details of a specific database group by its ID.

Get Languages

Tool to retrieve the list of languages supported by BunnyCDN's video library.

Get Database Limits

Tool to retrieve current database limits for the authenticated BunnyCDN account.

Get oEmbed

Tool to retrieve oEmbed metadata for BunnyCDN video embeds.

Get Optimal Base Region

Tool to get the optimal base region for Magic Containers.

Get Optimizer Statistics

Retrieve optimizer statistics for a Pull Zone to understand optimization performance.

Get Origin Shield Queue Statistics

Tool to retrieve Origin Shield Queue Statistics for a specific Pull Zone.

Get Pull Zone

Tool to retrieve details of a specific Pull Zone.

Get Pull Zone List

Retrieve a paginated list of all Pull Zones in your BunnyCDN account.

Get SafeHop Statistics

Tool to retrieve SafeHop statistics for a specific Pull Zone.

Get Shield Bot Detection Configuration

Tool to retrieve bot detection configuration for a specific Shield Zone.

Get Shield DDoS Enums

Tool to retrieve available enums for Shield DDoS configuration.

Get Shield Event Logs

Tool to retrieve Shield Event Logs for a specific Shield Zone and date.

Get Shield Metrics Bot Detection

Tool to retrieve bot detection metrics for a specific Shield Zone.

Get Shield Metrics Overview

Tool to retrieve comprehensive security metrics overview for a Shield Zone.

Get Shield Metrics Overview Detailed

Tool to retrieve detailed Shield zone metrics overview including DDoS protection, WAF, bot detection, rate limiting, access lists, and upload scanning statistics.

Get Shield Metrics Rate Limit by ID

Tool to retrieve shield metrics for a specific rate limit by ID.

Get Shield Metrics Rate Limits

Tool to retrieve rate limit metrics for a Shield Zone.

Get Shield Metrics Upload Scanning

Tool to retrieve upload scanning metrics for a specific Shield Zone.

Get Shield Metrics WAF Rule

Tool to retrieve shield metrics for a specific WAF rule.

Get Shield Promo State

Tool to retrieve a breakdown of Shield promotional data.

Get Shield Rate Limit by ID

Tool to retrieve a specific rate limit configuration by its ID.

Get Shield Rate Limits

Tool to retrieve Shield Rate Limits for a specific Shield Zone.

Get Shield Shield Zones

Tool to retrieve a list of all Shield Zones with their configurations.

Get Shield Upload Scanning Configuration

Tool to retrieve upload scanning configuration for a Shield Zone.

Get Shield WAF Custom Rule by ID

Tool to retrieve details of a specific Shield WAF custom rule by its ID.

Get Shield WAF Custom Rules

Tool to retrieve custom WAF rules for a specific Shield Zone.

Get Shield WAF Engine Config

Tool to retrieve Shield WAF engine configuration settings.

Get Shield WAF Enums

Tool to retrieve available enums for Shield WAF configuration.

Get Shield WAF Profiles

Tool to retrieve available WAF profiles for Shield zones.

Get Shield WAF Rules Plan Segmentation

Tool to retrieve WAF rules organized by subscription plan tiers.

Get Shield WAF Rules Review Triggered

Tool to retrieve triggered WAF rules for review in a specific Shield Zone.

Get Shield WAF Rules by Shield Zone ID

Tool to retrieve Shield WAF Rules for a specific Shield Zone.

Get Shield Zone

Tool to retrieve detailed configuration of a specific Shield Zone.

Get Shield Zone Access List

Tool to retrieve a specific custom access list from a Shield Zone.

Get Shield Zone Access List Enums

Tool to retrieve available enums for Shield Zone Access List configuration.

Get Shield Zone Access Lists

Tool to retrieve all access lists for a Shield Zone, including both managed threat lists and custom lists.

Get Shield Zone by Pull Zone ID

Tool to retrieve Shield Zone details by Pull Zone ID.

Get Shield Zones Pull Zone Mapping

Tool to retrieve the mapping between Shield Zones and Pull Zones.

Get Statistics

Tool to retrieve CDN statistics data for bandwidth, requests, cache performance, and geographic distribution.

Get Storage Zone Details

Tool to retrieve the full details of a storage zone, including configuration, usage metrics, and credentials.

Get Storage Zone List

Tool to list all storage zones in your Bunny CDN account.

Get User Audit Log

Tool to retrieve user audit log entries for a specific date with optional filtering.

Get User Details

Tool to retrieve complete details of the currently authorized user account.

Get User Limits

Tool to retrieve user limits and quotas for Magic Containers.

Get What's New Items

Tool to retrieve What's New items for the current user.

Invalidate Database Auth Tokens

Tool to invalidate all authentication tokens for a BunnyCDN database.

Invalidate Group Auth Tokens

Tool to invalidate authentication tokens for a specific database group.

List API Keys

Tool to retrieve a paginated list of all API keys in your BunnyCDN account.

List Applications

Tool to list all Magic Container applications in your Bunny CDN account.

List Container Image Tags

Tool to list all available tags for a container image in a registry.

List Container Registries

Tool to list all container registries in your BunnyCDN Magic Containers account.

List Country List

Tool to retrieve the list of countries supported by BunnyCDN with their tax rates and Points of Presence.

List Database Active Usage

Tool to retrieve active database usage statistics.

List Database Configuration

Tool to retrieve database configuration including available storage regions, primary regions, and replica regions.

List Databases V2

Tool to list databases with pagination support using the v2 API.

List Database Usage

Tool to retrieve aggregated usage metrics for a Bunny Database instance.

List Database Versions

Tool to list all versions of a specific database.

List Edge Scripts

Retrieve a paginated list of all edge scripts in your BunnyCDN account.

List Database Groups

Tool to retrieve a list of all database groups in your BunnyCDN account.

List Group Statistics

Tool to retrieve time-series statistics for a database group.

List Database Group Usage

Tool to retrieve aggregated usage statistics for a database group over a specified time period.

List Nodes

Tool to retrieve a list of Magic Container nodes in your BunnyCDN account.

List Notifications

Tool to list all notifications for the currently logged in user.

List Region List

Tool to retrieve the list of regions supported by BunnyCDN with their geographic coordinates and pricing.

List Regions

Tool to list all available regions for Magic Containers.

List Video Libraries

Retrieve a paginated list of all video libraries in your BunnyCDN account.

List Volumes

Tool to list all volumes for a Magic Container application in your BunnyCDN account.

Post Shield WAF Rules Review Triggered

Tool to review and apply actions to triggered WAF rules in a specific Shield Zone.

Purge Pull Zone

Purges the entire CDN cache for a specified pull zone.

Purge URL

Purge a specific URL from the BunnyCDN cache to force it to be refreshed from the origin.

Remove Allowed Referer

Removes a hostname from the allowed referer list for a pull zone.

Remove Blocked IP

Tool to remove an IP address from the blocked list of a pull zone.

Remove Blocked Referer

Tool to remove a blocked referer from a pull zone.

Reset Pull Zone Security Key

Tool to reset the security token key for a specific pull zone.

Reset What's New

Tool to reset the What's New notification list for the current user.

Restore Database

Tool to restore a BunnyCDN database to a specific generation/version.

Search Global Search

Perform a global search across all BunnyCDN resources (pull zones, storage zones, DNS zones, scripts, streams).

Search Public Container Images

Tool to search for public container images by prefix in a registry.

Set Edge Rule Enabled

Tool to enable or disable an edge rule in a BunnyCDN pull zone.

Set Force SSL

Tool to set Force SSL on a pull zone hostname.

Set Notifications Opened

Tool to mark all user notifications as opened.

Update Database

Tool to update an existing Bunny Database.

Update Database Group

Tool to update a database group by its ID.

Update Pull Zone

Tool to update settings for a specific pull zone.

Update Shield Bot Detection Configuration

Tool to update bot detection configuration for a specific Shield Zone.

Update Shield Rate Limit by ID

Tool to update a specific rate limit configuration by its ID.

Update Shield Zone

Tool to update configuration settings for a Shield Zone.

Update Shield Zone Access List

Tool to update a custom access list in a Shield Zone.

Update Shield Zone Access List Configuration

Tool to update an access list configuration in a Shield Zone.

Update Shield Zone Upload Scanning

Tool to update upload scanning settings for a shield zone.

Update Storage Zone

Tool to update settings for a specific storage zone.

Update User Details

Tool to update the currently authorized user's account details.

Validate Origin URL Pull Zone

Tool to validate an origin URL before creating or configuring a pull zone.

FAQ

Frequently asked questions

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

Yes, you can. LangChain 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 Bunnycdn tools.

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

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 Bunnycdn data and credentials are handled as safely as possible.

Start with Bunnycdn.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Bunnycdn tool your agent needs.Free to start.

Start building