# How to integrate Lemon squeezy MCP with LlamaIndex

```json
{
  "title": "How to integrate Lemon squeezy MCP with LlamaIndex",
  "toolkit": "Lemon squeezy",
  "toolkit_slug": "lemon_squeezy",
  "framework": "LlamaIndex",
  "framework_slug": "llama-index",
  "url": "https://composio.dev/toolkits/lemon_squeezy/framework/llama-index",
  "markdown_url": "https://composio.dev/toolkits/lemon_squeezy/framework/llama-index.md",
  "updated_at": "2026-05-12T10:17:24.755Z"
}
```

## Introduction

This guide walks you through connecting Lemon squeezy to LlamaIndex using the Composio tool router. By the end, you'll have a working Lemon squeezy agent that can list all recent orders for your store, create a new customer with email address, show all active discounts available now through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Lemon squeezy account through Composio's Lemon squeezy MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Lemon squeezy with

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

## TL;DR

Here's what you'll learn:
- Set your OpenAI and Composio API keys
- Install LlamaIndex and Composio packages
- Create a Composio Tool Router session for Lemon squeezy
- Connect LlamaIndex to the Lemon squeezy MCP server
- Build a Lemon squeezy-powered agent using LlamaIndex
- Interact with Lemon squeezy through natural language

## What is LlamaIndex?

LlamaIndex is a data framework for building LLM applications. It provides tools for connecting LLMs to external data sources and services through agents and tools.
Key features include:
- ReAct Agent: Reasoning and acting pattern for tool-using agents
- MCP Tools: Native support for Model Context Protocol
- Context Management: Maintain conversation context across interactions
- Async Support: Built for async/await patterns

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

The Lemon Squeezy MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Lemon Squeezy account. It provides structured and secure access to your e-commerce operations, so your agent can perform actions like managing customers, tracking orders, retrieving discounts, and handling subscriptions on your behalf.
- Customer creation and management: Quickly add new customers or pull up detailed customer lists, streamlining your onboarding and support flows.
- Order tracking and retrieval: Effortlessly fetch a paginated list of orders or drill down to specific order items to monitor sales activity and fulfillment status.
- Discount and affiliate insights: Retrieve all active discounts or affiliate partners, making it a breeze to analyze promotions and partner performance.
- Checkout and price listing: Access and filter all checkouts or prices across your stores and variants, helping you keep tabs on your sales funnels and product offerings.
- License key and redemption management: List all license key instances and track discount redemptions, ensuring easy oversight of software access and promotional usage.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `LEMON_SQUEEZY_CREATE_CUSTOMER` | Create Customer | Tool to create a new customer. Use after verifying the store exists and you need to add a customer to it. Example: "Create a customer John Doe with email johndoe@example.com in store 1." |
| `LEMON_SQUEEZY_CREATE_DISCOUNT` | Create Discount | Tool to create a new discount code in Lemon Squeezy. Use when you need to create promotional discounts for products or subscriptions. Example: "Create a discount code SUMMER20 with 20% off in store 123." |
| `LEMON_SQUEEZY_CREATE_WEBHOOK` | Create Webhook | Tool to create a new webhook for receiving event notifications. Use when you need to register a webhook endpoint to receive events like order_created, subscription_created, etc. Specify the webhook URL, signing secret, and event types to subscribe to. |
| `LEMON_SQUEEZY_DELETE_DISCOUNT` | Delete Discount | Tool to delete a discount by its ID. Use when you need to permanently remove a discount from a store. |
| `LEMON_SQUEEZY_DELETE_WEBHOOK` | Delete Webhook | Tool to delete a webhook. Use when you need to remove a registered webhook endpoint. |
| `LEMON_SQUEEZY_LIST_ALL_AFFILIATES` | List All Affiliates | Tool to list all affiliates. Use when you need to retrieve affiliates with optional filters and pagination. |
| `LEMON_SQUEEZY_LIST_ALL_CHECKOUTS` | List All Checkouts | Tool to list all checkouts. Use when you need a paginated list of checkouts, optionally filtering by store or variant. |
| `LEMON_SQUEEZY_LIST_ALL_CUSTOMERS` | List All Customers | Retrieves a paginated list of all customers from your Lemon Squeezy store(s). Returns customer details including email, name, location, revenue metrics (MRR, total revenue), marketing status, and relationships to orders, subscriptions, and license keys. Use this action to: - Get all customers across stores or filter by specific store_id - Find a customer by email address - List customers with pagination support (default 10 per page, max 100) - Access customer portal URLs and relationship links All parameters are optional. Without filters, returns all customers ordered by creation date (newest first). |
| `LEMON_SQUEEZY_LIST_ALL_DISCOUNT_REDEMPTIONS` | List All Discount Redemptions | Tool to list all discount redemptions. Use when you need a paginated list of discount redemptions, optionally filtering by discount or order. |
| `LEMON_SQUEEZY_LIST_ALL_DISCOUNTS` | List All Discounts | Tool to list all discounts. Use when you need a paginated list of discounts after confirming authentication. |
| `LEMON_SQUEEZY_LIST_ALL_FILES` | List All Files | Retrieves a paginated list of files from Lemon Squeezy. Use this to get digital goods that can be downloaded by customers after purchase. Each file belongs to a variant and includes download URLs (signed, expiring after 1 hour, rate-limited to 10 downloads/day/IP). Filter by variant ID or control pagination with page number and size. |
| `LEMON_SQUEEZY_LIST_ALL_LICENSE_KEY_INSTANCES` | List All License Key Instances | Tool to list all license key instances. Use when you need a paginated list of license key instances, optionally filtering by license key ID. |
| `LEMON_SQUEEZY_LIST_ALL_LICENSE_KEYS` | List All License Keys | Tool to list all license keys. Use when you need a paginated list of license keys, optionally filtering by store, order, order item, or product. |
| `LEMON_SQUEEZY_LIST_ALL_ORDER_ITEMS` | List All Order Items | Tool to list all order items. Use when you need a paginated list of order items, optionally filtered by order, product, or variant. Note: the `first_order_item` field on an order object returns only one item; use `filter_order_id` here to retrieve all line items for multi-item orders. |
| `LEMON_SQUEEZY_LIST_ALL_ORDERS` | List All Orders | Tool to list all orders. Use when you need a paginated list of orders, optionally filtering by store or user email. Monetary fields (e.g., `subtotal`, `tax`, `total`) are integers in the smallest currency unit (e.g., cents); use `*_formatted` variants for display only, not calculations. |
| `LEMON_SQUEEZY_LIST_ALL_PRICES` | List All Prices | Tool to list all prices. Use when you need a paginated list of all prices, optionally filtering by variant. |
| `LEMON_SQUEEZY_LIST_ALL_PRODUCTS` | List All Products | List all products from your Lemon Squeezy store with pagination and filtering. Returns a paginated list of products ordered by name. Each product includes pricing, status, thumbnails, checkout URLs, and metadata. Useful for browsing your product catalog, checking product details, or filtering by store. |
| `LEMON_SQUEEZY_LIST_ALL_STORES` | List All Stores | Retrieves a paginated list of all stores belonging to the authenticated Lemon Squeezy account. This action returns comprehensive store information including store details (name, slug, domain, URL), financial metrics (total sales/revenue, 30-day sales/revenue), configuration (plan, country, currency), and relationship links to associated resources (products, orders, subscriptions, discounts, license keys, webhooks, and affiliates). Returns stores ordered by name in ascending order with pagination metadata. No input parameters required. Use this as a starting point to discover available stores before working with other store-specific resources. |
| `LEMON_SQUEEZY_LIST_ALL_SUBSCRIPTION_INVOICES` | List All Subscription Invoices | Tool to list all subscription invoices. Use when you need a paginated list of subscription invoices with optional filters. |
| `LEMON_SQUEEZY_LIST_ALL_SUBSCRIPTION_ITEMS` | List All Subscription Items | Tool to list all subscription items. Use when you need a paginated list of items across subscriptions for reporting or auditing. |
| `LEMON_SQUEEZY_LIST_ALL_SUBSCRIPTIONS` | List All Subscriptions | Tool to list all subscriptions. Use when you need a paginated list of subscriptions, optionally filtered by store, order, product, or status. |
| `LEMON_SQUEEZY_LIST_ALL_USAGE_RECORDS` | List All Usage Records | Retrieves all usage records from Lemon Squeezy, with optional filtering and pagination. Usage records track consumption for usage-based billing on subscription items. Each record represents reported usage with a quantity and action type (increment or set). Records are returned in descending order by creation date (newest first). Use this when you need to: - View all usage records across subscription items - Filter usage records for a specific subscription item - Paginate through large sets of usage records Note: Returns an empty list if no usage records exist or the filter matches nothing. |
| `LEMON_SQUEEZY_LIST_ALL_VARIANTS` | List All Variants | Retrieves a paginated list of product variants from Lemon Squeezy. A variant represents a variation of a product with its own pricing options, files, and license key settings. You can filter by product ID and status (pending/draft/published), and control pagination with page number and size. |
| `LEMON_SQUEEZY_LIST_ALL_WEBHOOKS` | List All Webhooks | Tool to list all webhooks. Use when you need to retrieve registered webhooks. Supports optional filtering by store ID and pagination parameters for controlling result size and navigation. |
| `LEMON_SQUEEZY_RETRIEVE_AUTHENTICATED_USER` | Retrieve Authenticated User | Tool to retrieve the currently authenticated user from Lemon Squeezy. Use when you need to get details about the user associated with the current API key, including their name, email, avatar, and account timestamps. |
| `LEMON_SQUEEZY_RETRIEVE_CUSTOMER` | Retrieve Customer | Tool to retrieve a specific customer by their ID. Use when you need detailed information about a single customer including their email, name, location, revenue metrics, and relationships to orders and subscriptions. |
| `LEMON_SQUEEZY_RETRIEVE_DISCOUNT` | Retrieve Discount | Tool to retrieve a single discount by ID. Use when you need details about a specific discount. |
| `LEMON_SQUEEZY_RETRIEVE_STORE` | Retrieve Store | Tool to retrieve a store by its ID. Use when you need to get detailed information about a specific store. Returns comprehensive store data including financial metrics, configuration, and related resource links. |
| `LEMON_SQUEEZY_RETRIEVE_WEBHOOK` | Retrieve Webhook | Tool to retrieve a webhook by its ID. Use when you need to get details of a specific webhook configuration. |
| `LEMON_SQUEEZY_UPDATE_CUSTOMER` | Update Customer | Tool to update an existing customer with the given ID. Use when you need to modify customer details like name, email, or address information. At least one attribute field must be provided to update. |
| `LEMON_SQUEEZY_UPDATE_WEBHOOK` | Update Webhook | Tool to update an existing webhook. Use when you need to modify the URL, events, or secret for a registered webhook. |
| `LEMON_SQUEEZY_VALIDATE_LICENSE` | Validate License | Tool to validate a license key and optionally a specific license key instance. Use when you need to check if a license key is valid and active. |

## Supported Triggers

None listed.

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

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

## Step-by-step Guide

### 1. Prerequisites

Before you begin, make sure you have:
- Python 3.8/Node 16 or higher installed
- A Composio account with the API key
- An OpenAI API key
- A Lemon squeezy account and project
- Basic familiarity with async Python/Typescript

### 1. Getting API Keys for OpenAI, Composio, and Lemon squeezy

No description provided.

### 2. Installing dependencies

No description provided.
```python
pip install composio-llamaindex llama-index llama-index-llms-openai llama-index-tools-mcp python-dotenv
```

```typescript
npm install @composio/llamaindex @llamaindex/openai @llamaindex/tools @llamaindex/workflow dotenv
```

### 3. Set environment variables

Create a .env file in your project root:
These credentials will be used to:
- Authenticate with OpenAI's GPT-5 model
- Connect to Composio's Tool Router
- Identify your Composio user session for Lemon squeezy access
```bash
OPENAI_API_KEY=your-openai-api-key
COMPOSIO_API_KEY=your-composio-api-key
COMPOSIO_USER_ID=your-user-id
```

### 4. Import modules

No description provided.
```python
import asyncio
import os
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();
```

### 5. Load environment variables and initialize Composio

No description provided.
```python
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set in the environment")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set in the environment")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set in the environment")
```

```typescript
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!COMPOSIO_API_KEY) throw new Error("COMPOSIO_API_KEY is not set");
if (!COMPOSIO_USER_ID) throw new Error("COMPOSIO_USER_ID is not set");
```

### 6. Create a Tool Router session and build the agent function

What's happening here:
- We create a Composio client using your API key and configure it with the LlamaIndex provider
- We then create a tool router MCP session for your user, specifying the toolkits we want to use (in this case, lemon squeezy)
- The session returns an MCP HTTP endpoint URL that acts as a gateway to all your configured tools
- LlamaIndex will connect to this endpoint to dynamically discover and use the available Lemon squeezy tools.
- The MCP tools are mapped to LlamaIndex-compatible tools and plug them into the Agent.
```python
async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["lemon_squeezy"],
    )

    mcp_url = session.mcp.url
    print(f"Composio MCP URL: {mcp_url}")

    mcp_client = BasicMCPClient(mcp_url, headers={"x-api-key": COMPOSIO_API_KEY})
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    llm = OpenAI(model="gpt-5")

    description = "An agent that uses Composio Tool Router MCP tools to perform Lemon squeezy actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Lemon squeezy actions.
    """
    return ReActAgent(tools=tools, llm=llm, description=description, system_prompt=system_prompt, verbose=True)
```

```typescript
async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["lemon_squeezy"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
        description : "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Lemon squeezy actions." ,
    llm,
    tools,
  });

  return agent;
}
```

### 7. Create an interactive chat loop

No description provided.
```python
async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")
```

```typescript
async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}
```

### 8. Define the main entry point

What's happening here:
- We're orchestrating the entire application flow
- The agent gets built with proper error handling
- Then we kick off the interactive chat loop so you can start talking to Lemon squeezy
```python
async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")
```

```typescript
async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err) {
    console.error("Failed to start agent:", err);
    process.exit(1);
  }
}

main();
```

### 9. Run the agent

When prompted, authenticate and authorise your agent with Lemon squeezy, then start asking questions.
```bash
python llamaindex_agent.py
```

```typescript
npx ts-node llamaindex-agent.ts
```

## Complete Code

```python
import asyncio
import os
import signal
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set")

async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["lemon_squeezy"],
    )

    mcp_url = session.mcp.url
    print(f"Composio MCP URL: {mcp_url}")

    mcp_client = BasicMCPClient(mcp_url, headers={"x-api-key": COMPOSIO_API_KEY})
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    llm = OpenAI(model="gpt-5")
    description = "An agent that uses Composio Tool Router MCP tools to perform Lemon squeezy actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Lemon squeezy actions.
    """
    return ReActAgent(
        tools=tools,
        llm=llm,
        description=description,
        system_prompt=system_prompt,
        verbose=True,
    );

async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")

async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";
import { LlamaindexProvider } from "@composio/llamaindex";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();

const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) {
    throw new Error("OPENAI_API_KEY is not set in the environment");
  }
if (!COMPOSIO_API_KEY) {
    throw new Error("COMPOSIO_API_KEY is not set in the environment");
  }
if (!COMPOSIO_USER_ID) {
    throw new Error("COMPOSIO_USER_ID is not set in the environment");
  }

async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["lemon_squeezy"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
    description:
      "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Lemon squeezy actions." ,
    llm,
    tools,
  });

  return agent;
}

async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}

async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err: any) {
    console.error("Failed to start agent:", err?.message ?? err);
    process.exit(1);
  }
}

main();
```

## Conclusion

You've successfully connected Lemon squeezy to LlamaIndex through Composio's Tool Router MCP layer.
Key takeaways:
- Tool Router dynamically exposes Lemon squeezy tools through an MCP endpoint
- LlamaIndex's ReActAgent handles reasoning and orchestration; Composio handles integrations
- The agent becomes more capable without increasing prompt size
- Async Python provides clean, efficient execution of agent workflows
You can easily extend this to other toolkits like Gmail, Notion, Stripe, GitHub, and more by adding them to the toolkits parameter.

## How to build Lemon squeezy MCP Agent with another framework

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

## Related Toolkits

- [Addresszen](https://composio.dev/toolkits/addresszen) - Addresszen is a real-time address autocomplete and verification service. It helps capture accurate, deliverable addresses with instant suggestions and validation.
- [Asin data api](https://composio.dev/toolkits/asin_data_api) - Asin data api gives you detailed, real-time product data from Amazon, including price, rank, and reviews. Perfect for e-commerce pros and data-driven marketers who need instant marketplace insights.
- [Baselinker](https://composio.dev/toolkits/baselinker) - BaseLinker is an all-in-one e-commerce management platform connecting stores, marketplaces, carriers, and more. It streamlines order processing, inventory control, and automates your sales operations.
- [Bestbuy](https://composio.dev/toolkits/bestbuy) - Best Buy is a leading retailer offering APIs for product, store, and recommendation data. Instantly access up-to-date retail insights for smarter shopping and decision-making.
- [Btcpay server](https://composio.dev/toolkits/btcpay_server) - BTCPay Server is a free, open-source, self-hosted Bitcoin payment processor. It lets merchants accept Bitcoin payments directly, cutting out middlemen and boosting privacy.
- [Cdr platform](https://composio.dev/toolkits/cdr_platform) - Cdr platform is an API for purchasing carbon dioxide removal services. It enables businesses to offset emissions by accessing verified carbon removal projects.
- [Cloudcart](https://composio.dev/toolkits/cloudcart) - CloudCart is an e-commerce platform for building and managing online stores. It helps businesses streamline product listings, orders, and customer engagement.
- [Countdown api](https://composio.dev/toolkits/countdown_api) - Countdown API gives you real-time, structured eBay product data, reviews, and seller feedback. Perfect for powering price monitoring, product research, or marketplace analytics workflows.
- [Dpd2](https://composio.dev/toolkits/dpd2) - Dpd2 is a robust email management platform for handling, sorting, and automating email workflows. Streamline your communications and boost productivity with advanced sorting, labeling, and response tools.
- [Finerworks](https://composio.dev/toolkits/finerworks) - FinerWorks is an online platform for fine art and photo printing services. Artists and photographers use it to order custom prints and manage print inventory efficiently.
- [Fingertip](https://composio.dev/toolkits/fingertip) - Fingertip is a business management platform for selling, booking, and customer engagement—all from a single link. It helps businesses streamline operations and connect with customers across social channels.
- [Fraudlabs pro](https://composio.dev/toolkits/fraudlabs_pro) - FraudLabs Pro is an online payment fraud detection service for e-commerce and merchants. It helps minimize chargebacks and revenue loss by detecting and preventing fraudulent transactions.
- [Gift up](https://composio.dev/toolkits/gift_up) - Gift Up! is a digital platform for selling, managing, and redeeming gift cards online. It streamlines promotions and gift card transactions for businesses and their customers.
- [Goody](https://composio.dev/toolkits/goody) - Goody is a gifting platform that lets users send gifts and physical products without handling logistics. It streamlines gifting by managing delivery, fulfillment, and recipient experience.
- [Gumroad](https://composio.dev/toolkits/gumroad) - Gumroad is a platform for selling digital products, physical goods, and memberships with a simple checkout and marketing tools. It streamlines creator payouts and helps you grow your audience effortlessly.
- [Instacart](https://composio.dev/toolkits/instacart) - Instacart is an online grocery delivery and pickup service platform. It lets you discover local retailers and create shoppable lists and recipes with ease.
- [Junglescout](https://composio.dev/toolkits/junglescout) - Junglescout is an Amazon product research and analytics platform for sellers. It delivers sales estimates, competitive insights, and optimization tools to boost your Amazon business.
- [Ko fi](https://composio.dev/toolkits/ko_fi) - Ko-fi is a platform that lets creators receive donations, memberships, and sales from fans. It helps creators monetize their work and grow their audience with minimal friction.
- [Loyverse](https://composio.dev/toolkits/loyverse) - Loyverse is a point-of-sale (POS) platform for small businesses, offering tools for sales, inventory, and customer loyalty. It helps streamline retail operations and boost customer engagement.
- [Memberstack](https://composio.dev/toolkits/memberstack) - Memberstack lets you add user authentication, payments, and member management to your website—no backend code required. Easily manage your site's members and subscriptions from a single platform.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Lemon squeezy MCP?

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

### Can I use Tool Router MCP with LlamaIndex?

Yes, you can. LlamaIndex 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 Lemon squeezy tools.

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

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

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