# How to integrate Imgix MCP with LlamaIndex

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

## Introduction

This guide walks you through connecting Imgix to LlamaIndex using the Composio tool router. By the end, you'll have a working Imgix agent that can auto-optimize all images in this folder, overlay company logo on product photos, extract main color palette from image through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Imgix account through Composio's Imgix MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Imgix with

- [OpenAI Agents SDK](https://composio.dev/toolkits/imgix/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/imgix/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/imgix/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/imgix/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/imgix/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/imgix/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/imgix/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/imgix/framework/cli)
- [Google ADK](https://composio.dev/toolkits/imgix/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/imgix/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/imgix/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/imgix/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/imgix/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 Imgix
- Connect LlamaIndex to the Imgix MCP server
- Build a Imgix-powered agent using LlamaIndex
- Interact with Imgix 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 Imgix MCP server, and what's possible with it?

The Imgix MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Imgix account. It provides structured and secure access to your image library, so your agent can perform actions like optimizing images, applying overlays, adjusting visual properties, and extracting color palettes on your behalf.
- Real-time image optimization: Ask your agent to automatically compress, enhance, or format images for faster delivery and better quality using Imgix's auto optimization tools.
- Dynamic overlays and blending: Direct the agent to blend images, text, or solid colors over your base images—perfect for watermarks, banners, or creative composites.
- Precision image adjustments: Have your agent modify image brightness, contrast, and border settings to meet your design and branding needs instantly.
- Extract and analyze color palettes: Let your agent pull color palettes from any image, making it easy to generate theme colors or analyze brand consistency.
- Fine-tune overlay positioning: Control exactly where overlays appear on your images by specifying alignment and pixel-level positioning through your agent.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `IMGIX_ADD_ASSET_FROM_ORIGIN` | IMGIX_ADD_ASSET_FROM_ORIGIN | Tool to queue a path from your origin to be added to the Asset Manager. Imports the asset metadata without uploading the asset itself. Use when you need to register an existing origin-hosted file with imgix. |
| `IMGIX_AUTO` | Imgix Auto Optimization | Apply automatic image optimizations using imgix's auto parameter. Use this tool to automatically optimize images for web delivery. Common use cases: - Reduce file sizes with 'compress' for faster page loads - Auto-select modern formats (AVIF/WebP) with 'format' based on browser support - Enhance image quality with 'enhance' (adjusts brightness, contrast, saturation) - Remove red-eye from portrait photos with 'redeye' Multiple options can be combined (e.g., ['compress', 'format']) for cumulative optimizations. The 'true' option is a convenient shorthand that applies 'enhance' automatically. Note: This tool works with the imgix Rendering API and requires a valid imgix source domain. For testing, use 'assets.imgix.net' with paths like 'examples/kingfisher.jpg'. |
| `IMGIX_BLEND` | Blend Overlay | Tool to overlay an image, text, or color onto a base image using imgix blending parameters. Use after specifying the base image URL and blend parameters to composite layers. |
| `IMGIX_BLEND_ALIGN` | Imgix Blend Align | Tool to align the overlay relative to the base image when blending. Use after constructing a base Imgix URL to specify horizontal and vertical alignment (e.g., 'left,top'). |
| `IMGIX_BLEND_COLOR` | Blend Color Over Image | Tool to blend a solid color over an image using CSS keyword or hex. Use when you need to apply color overlay transformations to an existing image URL. |
| `IMGIX_BLEND_X` | Imgix Blend X Position | Position an overlay image horizontally on a base image using imgix's blend-x parameter. Use this tool when you need to place an overlay (image or color) at a specific horizontal offset from the left edge of the base image. This is useful for creating watermarks, badges, or composite images where precise positioning is required. Note: The blend-x parameter only affects image overlays. Color overlays always cover the entire image regardless of this setting. |
| `IMGIX_BORDER` | Draw Image Border | Tool to draw a border around an image. Use when you need to overlay a border without resizing. |
| `IMGIX_BRI` | Adjust Image Brightness | Tool to adjust image brightness. Use when you need to modify an image's brightness level (−100 to 100) by supplying your source domain and asset path. |
| `IMGIX_CANCEL_UPLOAD_SESSION` | IMGIX_CANCEL_UPLOAD_SESSION | Tool to cancel an Imgix Asset Manager upload session. Use when you need to abort an in-progress or abandoned upload flow and clean up the session. |
| `IMGIX_CH` | IMGIX_CH | Tool to opt in to Client Hints. Use when you want Imgix URLs to adapt based on browser headers (Width, DPR, Save-Data). |
| `IMGIX_CLOSE_UPLOAD_SESSION` | IMGIX_CLOSE_UPLOAD_SESSION | Tool to close an Imgix Asset Manager upload session after the client uploads to the presigned URL. Use after uploading a file to expedite asset processing. Closing is strongly recommended by imgix. |
| `IMGIX_CON` | Adjust Image Contrast | Tool to adjust image contrast. Use when you need to modify an image's contrast level (−100 to 100). |
| `IMGIX_CREATE_IMGIX_SOURCE` | IMGIX_CREATE_IMGIX_SOURCE | Tool to create and deploy a new imgix Source. Use when you need to add a new image source with deployment configuration for S3, Web Folder, Web Proxy, GCS, Azure, or S3-compatible storage. Requires source name and deployment details with type-specific credentials and settings. |
| `IMGIX_CREATE_UPLOAD_SESSION` | IMGIX_CREATE_UPLOAD_SESSION | Tool to create an Imgix Asset Manager upload session and return a presigned URL for client-side upload. Use when you need to upload a new image to a storage-backed imgix Source without requiring external hosting. Client performs HTTP PUT of file bytes to the presigned URL, then calls IMGIX_CLOSE_UPLOAD_SESSION to finalize. |
| `IMGIX_CS` | IMGIX_CS | Tool to set or strip output color space/profile on an Imgix image. Use when optimizing compatibility and file size (e.g., cs=strip for smaller metadata). |
| `IMGIX_DL` | IMGIX_DL | Download an asset from an Imgix source with optional custom filename. Use this tool when you need to: - Download images or assets from an Imgix CDN source - Force a specific download filename (via 'dl' parameter) - Download assets with special character filenames (via 'dl64' parameter) The asset is fetched from the Imgix CDN and returned as a downloadable file reference. If neither 'dl' nor 'dl64' is specified, the original filename from the path is used. |
| `IMGIX_DPI` | Adjust Image DPI | Tool to embed DPI (dots-per-inch) metadata for print output on an Imgix-rendered image. Use when preparing images for print to set accurate DPI. Supports JPEG and PNG only. |
| `IMGIX_DPR` | Set Device Pixel Ratio | Tool to set device pixel ratio for an Imgix image. Use when rendering at specific display densities to ensure correct sharpness. Example: 'dpr=2&w=500&h=300' doubles resolution relative to dimensions. |
| `IMGIX_EXPIRES` | Imgix URL Expiration | Tool to append an expiration parameter to an Imgix URL so it returns 404 after a given time. Use when you want the image URL to stop serving beyond a specific UNIX timestamp. |
| `IMGIX_FIT` | IMGIX_FIT | Tool to control how an image fits target dimensions after resizing. Use when specifying width, height, and fit behavior. |
| `IMGIX_FM` | IMGIX_FM | Tool to choose output file format for the rendered asset. Use after specifying the asset path when you need to convert its format. |
| `IMGIX_FORCE_ASPECT_RATIO` | Force Aspect Ratio | Tool to force a target aspect ratio on an Imgix image. Use when a specific W:H frame is needed after choosing fit=crop or fit=fill. Example: 'ar=16:9&fit=crop&w=800' yields a 16:9, 800px-wide URL. |
| `IMGIX_GET_SOURCE` | IMGIX_GET_SOURCE | Tool to retrieve details for a single imgix Source by its ID. Returns the source configuration including deployment status, type, and settings. |
| `IMGIX_GET_UPLOAD_SESSION_STATUS` | IMGIX_GET_UPLOAD_SESSION_STATUS | Tool to retrieve the status of an Imgix Asset Manager upload session. Use when you need to check the current state (PENDING/CLOSED/COMPLETE/CANCELED) of an upload session for polling or verification after client PUT and/or after closing. |
| `IMGIX_H` | IMGIX_H | Tool to set output image height in pixels or as a ratio of the source height. Use after constructing an Imgix URL to adjust only height. |
| `IMGIX_HIGH` | Adjust Image Highlights | Tool to adjust highlight tonal mapping (−100 to 0). Use when preserving detail in bright areas of an image. |
| `IMGIX_LIST_ASSETS` | IMGIX_LIST_ASSETS | Tool to retrieve a paginated list of assets in an imgix Source. Use when you need to list, filter, or search assets with cursor-based pagination and sorting. |
| `IMGIX_LIST_REPORTS` | IMGIX_LIST_REPORTS | Tool to retrieve a list of all available reports for your imgix account. Use when you need to access analytics and usage information. Reports are generated daily and retained for 90 days. |
| `IMGIX_LIST_SOURCES` | IMGIX_LIST_SOURCES | Tool to list all Sources for an account. Use when you need to retrieve and paginate through sources with optional sorting and filtering. |
| `IMGIX_MARK_BASE` | Set Watermark Base URL | Tool to set the base URL prepended to the watermark image path. Use when you need to host watermark assets on a custom domain or CDN. |
| `IMGIX_MARK_FIT` | Watermark Fit Mode | Tool to set how a watermark fits its target dimensions. Use when applying a watermark and you need control over fitting behavior (e.g., selecting 'scale'). For 'crop', ensure 'mark-w' and 'mark-h' are also provided. |
| `IMGIX_MARK_H` | Imgix Mark Height | Tool to set watermark height on an Imgix URL in pixels or as a ratio of the watermark source. Use when adjusting overlay height while preserving aspect ratio. |
| `IMGIX_MARK_PAD` | IMGIX_MARK_PAD | Tool to set pixel padding between a watermark and the image edge or between tiled watermarks. Use after configuring watermark URL and alignment to adjust spacing precisely. |
| `IMGIX_MARK_W` | Watermark Width | Tool to set watermark width. Use when you need to enforce a watermark's width in pixels or as a proportion. Use after specifying watermark source. |
| `IMGIX_MASK` | IMGIX_MASK | Tool to apply a mask to an image. Use when needing rounded corners, ellipse shapes, or image-based masks. |
| `IMGIX_MAX_H` | IMGIX_MAX_H | Constrain the maximum height of an imgix image. This tool applies fit=crop along with the max-h parameter to ensure images do not exceed the specified height. Ideal for vertically-scrolling feeds or galleries where user-uploaded images may have unpredictable heights. Returns a downloadable image URL. |
| `IMGIX_MAX_W` | IMGIX_MAX_W | Tool to set the maximum output width on an Imgix URL. Use when you need to cap width (works only with fit=crop). Call after specifying fit=crop on the URL. |
| `IMGIX_PALETTE` | IMGIX_PALETTE | Tool to extract a color palette from an image in CSS or JSON form. Use when you need to analyze an image's dominant colors after any transformations. |
| `IMGIX_PREFIX` | Set CSS Palette Prefix | Tool to set class-name prefix for CSS palette output. Use when customizing CSS selectors for color-palette styling. |
| `IMGIX_PURGE_IMGIX_ASSET` | IMGIX_PURGE_ASSET | Tool to purge an asset from the imgix cache. Use when you need to invalidate cached versions of an image and force imgix to fetch a fresh version from origin on the next request. |
| `IMGIX_Q` | Set Output Quality | Tool to set output quality for lossy formats. Use when adjusting image compression quality for lossy image delivery. |
| `IMGIX_RECT` | IMGIX_RECT | Tool to select a source-image rectangle region in Imgix before other resizing. Use when you need to crop a specific region (x,y,w,h) of the source image. |
| `IMGIX_ROT` | Imgix Rotate | Tool to rotate an image on Imgix. Use when you need to apply a counter-clockwise rotation (0–359°) with optional mode control. |
| `IMGIX_ROT_TYPE` | IMGIX_ROT_TYPE | Tool to control rotation behavior when `rot` is applied. Use after applying a `rot` parameter to choose between pivot (show entire image) or straighten (zoom and crop) behavior. |
| `IMGIX_TXT` | Text Overlay | Tool to render a single-line UTF-8 text overlay on an image. Use when you need simple text captions. |
| `IMGIX_TXT_ALIGN` | IMGIX_TXT_ALIGN | Tool to align a text overlay on an Imgix image. Use when you need to position text by specifying vertical (top/middle/bottom) and horizontal (left/center/right) alignment. |
| `IMGIX_TXT_COLOR` | Set Text Color | Tool to set text overlay color on an Imgix image. Use when customizing text overlays with CSS color keywords or hex codes. |
| `IMGIX_TXT_FONT` | Set Text Font | Tool to choose font family/style for overlay text. Use when customizing text appearance after specifying content. Supports CSS font categories and optional bold/italic flags. |
| `IMGIX_TXT_LINE` | Set Text Outline Width | Tool to set outline width around overlay text. Use when styling text overlays on images. |
| `IMGIX_TXT_LINE_COLOR` | Text Outline Color | Apply an outline color to text overlays on Imgix images. The text outline must first be enabled using the txt-line parameter (outline width > 0). This action fetches and returns the rendered image with the specified outline color applied. |
| `IMGIX_TXT_SHAD` | IMGIX_TXT_SHAD | Set text shadow strength for imgix text overlays. The txt-shad parameter controls the drop shadow intensity (0-10) applied to text rendered on images. Note: This parameter only has a visible effect when combined with text overlay parameters (e.g., txt parameter). Use this action to add depth and visibility to text overlays on images. |
| `IMGIX_TXT_SIZE` | IMGIX_TXT_SIZE | Tool to set text font size in pixels. Use when overlaying text and needing precise control over font size. Specify after defining the text content; default is 12px. |
| `IMGIX_UPDATE_SOURCE` | IMGIX_UPDATE_SOURCE | Tool to update an existing imgix Source. Use when you need to modify source name, deployment configuration, bucket settings, or other source attributes. Deployment changes trigger automatic redeployment. |

## Supported Triggers

None listed.

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

The Imgix MCP server is an implementation of the Model Context Protocol that connects your AI agent to Imgix. It provides structured and secure access so your agent can perform Imgix 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 Imgix account and project
- Basic familiarity with async Python/Typescript

### 1. Getting API Keys for OpenAI, Composio, and Imgix

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 Imgix 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, imgix)
- 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 Imgix 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=["imgix"],
    )

    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 Imgix actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Imgix 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: ["imgix"],
    },
  );

  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 Imgix 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 Imgix
```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 Imgix, 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=["imgix"],
    )

    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 Imgix actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Imgix 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: ["imgix"],
    },
  );

  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 Imgix 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 Imgix to LlamaIndex through Composio's Tool Router MCP layer.
Key takeaways:
- Tool Router dynamically exposes Imgix 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 Imgix MCP Agent with another framework

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

## Related Toolkits

- [Figma](https://composio.dev/toolkits/figma) - Figma is a collaborative interface design tool for teams and individuals. It streamlines design workflows with real-time collaboration and easy sharing.
- [Abyssale](https://composio.dev/toolkits/abyssale) - Abyssale is a creative automation platform for generating images, videos, GIFs, PDFs, and HTML5 content programmatically. It streamlines and scales visual content production for marketing, design, and operations teams.
- [Alttext ai](https://composio.dev/toolkits/alttext_ai) - AltText.ai is a service that generates alt text for images automatically. It helps boost accessibility and SEO for your visual content.
- [Bannerbear](https://composio.dev/toolkits/bannerbear) - Bannerbear is an API-driven platform for generating images and videos automatically at scale. It helps businesses create custom graphics, social visuals, and marketing assets using powerful templates.
- [Canva](https://composio.dev/toolkits/canva) - Canva is a drag-and-drop design suite for creating professional graphics, presentations, and marketing materials. It makes it easy for anyone to design with beautiful templates and a vast library of elements.
- [Claid ai](https://composio.dev/toolkits/claid_ai) - Claid.ai delivers AI-driven image editing APIs for tasks like background removal, upscaling, and color correction. It helps automate and enhance image workflows with powerful, developer-friendly tools.
- [Cloudinary](https://composio.dev/toolkits/cloudinary) - Cloudinary is a cloud-based platform for managing, uploading, and transforming images and videos. It streamlines media workflows and delivers optimized assets globally.
- [Cults](https://composio.dev/toolkits/cults) - Cults is a digital marketplace for 3D printing models, connecting designers and makers. It lets creators share, sell, and discover a huge variety of printable designs easily.
- [DeepImage](https://composio.dev/toolkits/deepimage) - DeepImage is an AI-powered image enhancer and upscaler. Get higher-quality images with just a few clicks.
- [Dreamstudio](https://composio.dev/toolkits/dreamstudio) - DreamStudio is Stability AI’s platform for generating and editing images with AI. It lets you easily turn ideas into stunning visuals, fast.
- [Dynapictures](https://composio.dev/toolkits/dynapictures) - Dynapictures is a cloud-based platform for generating personalized images at scale. Instantly create hundreds of custom visuals using your data sources, like Google Sheets.
- [Fal.ai](https://composio.dev/toolkits/fal_ai) - Fal.ai is a generative media platform offering 600+ AI models for images, video, voice, and audio. Developers use Fal.ai for fast, scalable access to cutting-edge generative AI tools.
- [Gamma](https://composio.dev/toolkits/gamma) - Gamma is an AI-powered platform for making beautiful, interactive presentations and documents. It lets anyone create and share engaging decks with minimal effort.
- [Html to image](https://composio.dev/toolkits/html_to_image) - Html to image converts HTML and CSS into images or captures web page screenshots. Instantly generate visuals from code or web content—no manual screenshots needed.
- [Imagior](https://composio.dev/toolkits/imagior) - Imagior is an AI-powered image generation platform that lets you create and customize images using dynamic templates and APIs. Perfect for businesses and creators needing fast, scalable visuals without design hassle.
- [Imejis io](https://composio.dev/toolkits/imejis_io) - Imejis io is an API-based image generation platform with powerful customization and template support. It lets you create and modify images in seconds, no manual design work required.
- [Kraken io](https://composio.dev/toolkits/kraken_io) - Kraken.io is an image optimization and compression platform. It helps you shrink image file sizes while keeping visual quality intact.
- [Logo dev](https://composio.dev/toolkits/logo_dev) - Logo.dev is an API and database for high-resolution company logos and brand metadata. Instantly fetch official logos from any domain without scraping or manual searching.
- [Miro](https://composio.dev/toolkits/miro) - Miro is a collaborative online whiteboard platform for teams to brainstorm, design, and manage projects visually. It streamlines teamwork by enabling real-time idea sharing, diagramming, and workflow planning in a single space.
- [Mural](https://composio.dev/toolkits/mural) - Mural is a digital whiteboard platform for distributed visual collaboration. It helps teams brainstorm, map ideas, and diagram together in real time.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Imgix MCP?

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

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

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

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