# How to integrate Uploadcare MCP with LlamaIndex

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

## Introduction

This guide walks you through connecting Uploadcare to LlamaIndex using the Composio tool router. By the end, you'll have a working Uploadcare agent that can list all uploaded files from last week, rotate image file by 90 degrees clockwise, get direct download link for specific file through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Uploadcare account through Composio's Uploadcare MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Uploadcare with

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

The Uploadcare MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Uploadcare account. It provides structured and secure access to your file storage, processing, and delivery pipeline, so your agent can perform actions like listing files, retrieving file info, managing webhooks, rotating images, and handling file metadata on your behalf.
- Comprehensive file listing and retrieval: Ask your agent to list all files stored in your Uploadcare project, filter by criteria, or fetch detailed metadata for any file.
- Direct file download and sharing: Effortlessly generate secure, temporary download links for your files so you can share them or integrate with other services.
- Automated image processing: Let your agent rotate images by 90, 180, or 270 degrees, making quick edits or transformations without manual intervention.
- Webhook management for event automation: Easily create, list, or delete webhooks so your agent can subscribe to file events and enable real-time notifications or integrations.
- Metadata and group management: Enable your agent to update or delete file metadata and organize files into groups for streamlined file handling and workflows.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `UPLOADCARE_CHECK_AWS_REKOGNITION_MODERATION_STATUS` | Check AWS Rekognition Moderation Status | Tool to check the execution status of AWS Rekognition Moderation labels detection. Use after initiating a moderation check to monitor progress and determine when results are ready. |
| `UPLOADCARE_CHECK_REMOVE_BG_STATUS` | Check Remove.bg Status | Tool to check Remove.bg execution status and get the UUID of the file with removed background. Use after requesting background removal to poll for completion and retrieve the processed file UUID. |
| `UPLOADCARE_COPY_FILE_LOCAL` | Copy Uploadcare File to Local Storage | Tool to copy a file to local storage within the same Uploadcare project. Use when you need to create a duplicate of an existing file. |
| `UPLOADCARE_CREATE_FILE_GROUP_UPLOAD` | Create File Group (Upload API) | Tool to create a file group from already uploaded files using Uploadcare's Upload API. Use after files have been uploaded to group them together. |
| `UPLOADCARE_CREATE_WEBHOOK` | Create Uploadcare webhook | Create a new webhook subscription to receive notifications when file events occur. Use this to get real-time callbacks at your URL when files are uploaded, stored, deleted, or flagged. The project is automatically determined by your API credentials. Note: Each target_url must be unique per event type within your project. |
| `UPLOADCARE_DELETE_FILE_METADATA_KEY` | Delete File Metadata Key | Tool to delete a specific metadata key from an Uploadcare file. Use when you need to remove obsolete metadata after file processing. |
| `UPLOADCARE_DELETE_FILES` | Batch Delete Uploadcare Files | Tool to delete multiple files from Uploadcare storage in a single request. Use when you need to remove up to 100 files at once. Invalid UUIDs or missing files will be reported in the problems field. |
| `UPLOADCARE_DELETE_GROUP` | Delete Uploadcare Group | Tool to delete a file group. Use when you need to remove a group from the project. Note that files within the group are not deleted, only the group itself. |
| `UPLOADCARE_DELETE_SINGLE_FILE` | Delete Uploadcare File | Tool to delete a single file from Uploadcare storage by UUID. Use when you need to permanently remove a file from storage (note: file may remain in CDN cache). |
| `UPLOADCARE_DELETE_WEBHOOK` | Delete Uploadcare Webhook | Permanently deletes a webhook subscription from your Uploadcare project. Use the List Webhooks action first to obtain the webhook ID. This action is irreversible. |
| `UPLOADCARE_DELETE_WEBHOOK_BY_URL` | Delete Uploadcare Webhook by URL | Tool to delete a webhook subscription by its target URL. Use when you know the webhook's target URL but not its ID. |
| `UPLOADCARE_EXECUTE_CLAMAV_SCAN` | Execute ClamAV virus scan | Tool to execute ClamAV virus scan on an uploaded file. Use this when you need to check if a file contains viruses or malware. The scan runs asynchronously - you receive a request_id to track the scan status. Results can be retrieved from file info or via webhooks. |
| `UPLOADCARE_GET_AWS_REKOGNITION_EXECUTION_STATUS` | Get AWS Rekognition Execution Status | Tool to check AWS Rekognition execution status for label detection. Use after initiating an AWS Rekognition add-on execution to monitor job progress. |
| `UPLOADCARE_GET_CLAMAV_SCAN_STATUS` | Get ClamAV Scan Status | Tool to check the execution status of a ClamAV virus scan. Use after initiating a ClamAV scan to monitor its progress and determine when results are available. |
| `UPLOADCARE_GET_FILE_GROUP_INFO_UPLOAD` | Get File Group Info (Upload API) | Tool to get information about a file group from the Upload API. Use when you need to retrieve group details including file metadata from the upload endpoint. |
| `UPLOADCARE_GET_FILE_INFO` | Get Uploadcare File Info | Tool to get information about a specific file. Use after uploading a file to retrieve detailed metadata and usage information. |
| `UPLOADCARE_GET_FILE_METADATA` | Get File Metadata | Tool to retrieve all metadata key-value pairs associated with an Uploadcare file. Use when you need to inspect custom metadata attached to a file. |
| `UPLOADCARE_GET_FILE_METADATA_KEY` | Get File Metadata Key Value | Tool to get the value of a specific metadata key for an Uploadcare file. Use when you need to retrieve custom metadata associated with a file. |
| `UPLOADCARE_GET_GROUP_INFO` | Get Uploadcare Group Info | Tool to get information about a specific file group. Use when you need to retrieve detailed metadata about a group and its contained files. |
| `UPLOADCARE_GET_PROJECT_INFO` | Get Uploadcare Project Info | Tool to get information about the current Uploadcare project. Use when you need to retrieve project configuration details. |
| `UPLOADCARE_GET_UPLOADED_FILE_INFO` | Get Uploaded File Info | Tool to get information about an uploaded file using Uploadcare's Upload API. Use this to retrieve file metadata including size, MIME type, and content information immediately after upload. |
| `UPLOADCARE_GET_URL_UPLOAD_STATUS` | Get URL Upload Status | Tool to check the status of a URL upload task. Use after initiating a file upload from a URL to monitor progress or verify completion. |
| `UPLOADCARE_IMAGE_MIRROR` | Mirror Uploadcare Image | Tool to mirror an image horizontally via Uploadcare CDN. Use when you need the URL of a horizontally flipped image. |
| `UPLOADCARE_LIST_FILES` | List Uploadcare Files | List files in an Uploadcare project with pagination and optional filtering. Use this tool to retrieve uploaded files. Supports filtering by storage status, removal status, and date range. Results are paginated with optional ordering. |
| `UPLOADCARE_LIST_GROUPS` | List Uploadcare Groups | Tool to list groups in the project. Use when you need to retrieve paginated groups of files. |
| `UPLOADCARE_LIST_WEBHOOKS` | List Uploadcare Webhooks | Retrieves all webhook subscriptions for the authenticated Uploadcare project. Use this tool to view configured webhooks that receive notifications for file events (uploads, deletions, storage, etc.). Returns an array of webhook objects with their IDs, target URLs, event types, and active status. |
| `UPLOADCARE_ROTATE_IMAGE` | Rotate Image | Tool to rotate an image by specified degrees counterclockwise. Use when you need to rotate an uploaded image by 90, 180, or 270 degrees. Use after confirming the file UUID. |
| `UPLOADCARE_START_MULTIPART_UPLOAD` | Start Multipart Upload | Tool to start a multipart upload session for files larger than 100MB. Use when you need to upload large files that exceed the direct upload size limit. Returns presigned URLs for uploading file parts. |
| `UPLOADCARE_STORE_BATCH_FILES` | Batch Store Files | Tool to store multiple files in one request. Use when you need to mark up to 100 files as permanently stored in bulk. |
| `UPLOADCARE_STORE_FILE` | Store Uploadcare File | Tool to mark an Uploadcare file as permanently stored. Use after uploading a file when you need to store it permanently. |
| `UPLOADCARE_STORE_SINGLE_FILE` | Store Single Uploadcare File | Tool to store a single file by UUID permanently. Use when you need to make an uploaded file available permanently (stored files are retained indefinitely). |
| `UPLOADCARE_UPDATE_FILE_METADATA_KEY` | Update File Metadata Key | Tool to update or set the value of a specific metadata key for a file. Use when you need to add or modify file metadata. |
| `UPLOADCARE_UPDATE_WEBHOOK` | Update Uploadcare webhook | Update an existing webhook subscription by its ID. Use this to modify the target URL, event type, active status, or signing secret of a webhook. Only provide the fields you want to update - all fields are optional except the webhook ID. |
| `UPLOADCARE_UPLOAD_FROM_URL` | Upload File from URL | Tool to upload a file from a publicly available URL to Uploadcare. Use when you need to import files from external URLs into your Uploadcare project. |

## Supported Triggers

None listed.

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

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

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

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 Uploadcare 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, uploadcare)
- 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 Uploadcare 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=["uploadcare"],
    )

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

  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 Uploadcare 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 Uploadcare
```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 Uploadcare, 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=["uploadcare"],
    )

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

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

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

## Related Toolkits

- [Google Drive](https://composio.dev/toolkits/googledrive) - Google Drive is a cloud storage platform for uploading, sharing, and collaborating on files. It's perfect for keeping your documents accessible and organized across devices.
- [Google Docs](https://composio.dev/toolkits/googledocs) - Google Docs is a cloud-based word processor that enables document creation and real-time collaboration. Its seamless sharing and version history make team editing and content management a breeze.
- [Google Super](https://composio.dev/toolkits/googlesuper) - Google Super is an all-in-one suite combining Gmail, Drive, Calendar, Sheets, Analytics, and more. It gives you a unified platform to manage your digital life, boosting productivity and organization.
- [Affinda](https://composio.dev/toolkits/affinda) - Affinda is an AI-powered document processing platform that automates data extraction from resumes, invoices, and more. It streamlines document-heavy workflows by turning files into structured, actionable data.
- [Agility cms](https://composio.dev/toolkits/agility_cms) - Agility CMS is a headless content management system for building and managing digital experiences across platforms. It lets teams update content quickly and deliver omnichannel experiences with ease.
- [Algodocs](https://composio.dev/toolkits/algodocs) - Algodocs is an AI-powered platform that automates data extraction from business documents. It delivers fast, secure, and accurate processing without templates or manual training.
- [Api2pdf](https://composio.dev/toolkits/api2pdf) - Api2Pdf is a REST API for generating PDFs from HTML, URLs, and documents using powerful engines like wkhtmltopdf and Headless Chrome. It streamlines document conversion and automation for developers and businesses.
- [Aryn](https://composio.dev/toolkits/aryn) - Aryn is an AI-powered platform for parsing, extracting, and analyzing data from unstructured documents. Use it to automate document processing and unlock actionable insights from your files.
- [Boldsign](https://composio.dev/toolkits/boldsign) - Boldsign is a digital eSignature platform for sending, signing, and tracking documents online. Organizations use it to automate agreements and manage legally binding workflows efficiently.
- [Boloforms](https://composio.dev/toolkits/boloforms) - BoloForms is an eSignature platform built for small businesses, offering unlimited signatures, templates, and forms. It simplifies digital document signing and team collaboration at a predictable, fixed price.
- [Box](https://composio.dev/toolkits/box) - Box is a cloud content management and file sharing platform for businesses. It helps teams securely store, organize, and collaborate on files from anywhere.
- [Carbone](https://composio.dev/toolkits/carbone) - Carbone is a blazing-fast report generator that turns JSON data into PDFs, Word docs, spreadsheets, and more using flexible templates. It lets you automate document creation at scale with minimal code.
- [Castingwords](https://composio.dev/toolkits/castingwords) - CastingWords is a transcription service specializing in human-powered, accurate transcripts via a simple API. Get seamless audio-to-text conversion for interviews, meetings, podcasts, and more.
- [Cloudconvert](https://composio.dev/toolkits/cloudconvert) - CloudConvert is a powerful file conversion service supporting over 200 file formats. It streamlines converting, compressing, and managing documents, media, and more, all in one place.
- [Cloudlayer](https://composio.dev/toolkits/cloudlayer) - Cloudlayer is a document and asset generation service for creating PDFs and images via API or SDKs. It lets you automate high-quality doc creation, saving dev time and reducing manual work.
- [Cloudpress](https://composio.dev/toolkits/cloudpress) - Cloudpress is a content export tool for Google Docs and Notion. It automates publishing to your favorite Content Management Systems.
- [Contentful graphql](https://composio.dev/toolkits/contentful_graphql) - Contentful graphql is a content delivery API that lets you access Contentful data using GraphQL queries. It gives you efficient, flexible ways to fetch and manage structured content for any digital project.
- [Conversion tools](https://composio.dev/toolkits/conversion_tools) - Conversion Tools is an online service for converting documents between formats such as PDF, Word, Excel, XML, and CSV. It lets you automate complex document workflows with just a few clicks.
- [Convertapi](https://composio.dev/toolkits/convertapi) - ConvertAPI is a robust file conversion service for documents, images, and spreadsheets. It streamlines programmatic format changes and lets developers automate complex workflows with a single API.
- [Craftmypdf](https://composio.dev/toolkits/craftmypdf) - CraftMyPDF is a web-based service for designing and generating PDFs with templates and live data. It streamlines document creation by automating personalized PDFs at scale.

## Frequently Asked Questions

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

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

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

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

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