# How to integrate Ramp MCP with LlamaIndex

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

## Introduction

This guide walks you through connecting Ramp to LlamaIndex using the Composio tool router. By the end, you'll have a working Ramp agent that can download last month's statement as pdf, list all transactions over $500 this week, get details of your virtual cards through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Ramp account through Composio's Ramp MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Ramp with

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

The Ramp MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Ramp account. It provides structured and secure access to your company's financial data, so your agent can fetch transactions, analyze card activity, generate statements, manage departments, and retrieve detailed expense information on your behalf.
- Comprehensive transaction tracking: Instantly pull lists of all your business transactions or your own card activity, making it easy to monitor expenses and spot anomalies.
- Card management and insights: Retrieve details about specific Ramp cards or see all cards assigned to you, including limits, status, and cardholder info for better financial oversight.
- Automated statement generation: Ask your agent to generate and download account statements in multiple formats (PDF, CSV, JSON) for reporting or bookkeeping.
- Department and organizational management: Create new departments or fetch detailed department profiles to help structure your expense tracking and categorize spending.
- Detailed transaction analysis: Dive into specific transactions to get merchant information, receipts, dispute details, and accounting codes for audit and compliance purposes.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `RAMP_CREATE_DEPARTMENT` | Create Department | Tool for creating a new department in your Ramp organization. Perfect for setting up organizational structure and expense categorization. |
| `RAMP_CREATE_INVENTORY_ITEM_ACCOUNTING_FIELD` | Create Inventory Item Accounting Field | Tool to create a new inventory item accounting field for tracking inventory categories. Use when setting up inventory tracking for an accounting connection. Note: There can only be one active inventory item accounting field per accounting connection. |
| `RAMP_CREATE_MEMO` | Create Transaction Memo | Tool for uploading a new memo for a transaction in Ramp. Use when you need to add notes or context to existing transactions. |
| `RAMP_CREATE_MILEAGE_REIMBURSEMENT` | Create Mileage Reimbursement | Tool to create a mileage reimbursement in Ramp. Use when a user needs to submit a reimbursement for business-related travel distance. Requires distance, reimbursee_id, and trip_date as mandatory fields. |
| `RAMP_CREATE_NEW_CUSTOM_ACCOUNTING_FIELD` | Create New Custom Accounting Field | Tool for creating a new custom accounting field. Note: This operation requires elevated permissions not available in the demo API. |
| `RAMP_CREATE_TAX_CODE_ACCOUNTING_FIELD` | Create Tax Code Accounting Field | Tool to create a new tax code accounting field in Ramp. There can only be one active tax code accounting field per accounting connection. Use when you need to set up tax code tracking for an accounting integration. |
| `RAMP_CREATE_USER_INVITE` | Create User Invite | Tool to create a user invite for onboarding new employees to Ramp. Triggers an async task to send an invite email. Users must accept the invite to be onboarded. Assign users to specific entities using location_id. |
| `RAMP_CREATE_WEBHOOK_SUBSCRIPTION` | Create Webhook Subscription | Tool to create a new webhook subscription for receiving event notifications from Ramp. Use when you need to set up real-time notifications for events like transactions, bills, or reimbursements. The newly registered subscription will be in pending verification state and requires endpoint verification with the provided challenge. |
| `RAMP_DEACTIVATE_USER` | Deactivate User | Tool to deactivate a user in your Ramp organization. Use when you need to prevent a user from logging in, spending on cards, or receiving notifications. Once deactivated, users cannot access their Ramp account or perform any actions. |
| `RAMP_DELETE_ACCOUNTING_ACCOUNT` | Delete Accounting GL Account | Tool to delete a general ledger account from Ramp. Use when you need to remove a GL account from the accounting system. |
| `RAMP_DELETE_ACCOUNTING_CONNECTION` | Delete Accounting Connection | Tool to disconnect the current active API-based accounting connection. Use when you need to disable the accounting integration. This action will clear associated accounting settings including Custom Fields, GL Accounts, and Vendors. Only API-based connections can be disconnected via this endpoint. |
| `RAMP_DELETE_ACCOUNTING_FIELDS` | Delete Custom Accounting Field | Tool to delete a custom accounting field from Ramp. Use when you need to remove a custom accounting field from the system. Note: Fields are read-only and cannot be deleted when a direct accounting connection is enabled. |
| `RAMP_DELETE_ACCOUNTING_INVENTORY_ITEM_OPTIONS` | Delete Accounting Inventory Item Option | Tool to delete an accounting inventory item option from Ramp. Use when you need to remove an inventory item option from the accounting system. |
| `RAMP_DELETE_ACCOUNTING_TAX_CODE` | Delete Tax Code Accounting Field | Tool to delete the tax code accounting field from Ramp. Use when you need to remove the tax code field configuration. Note: The tax code field must exist before deletion. |
| `RAMP_DELETE_ACCOUNTING_TAX_CODE_OPTIONS` | Delete Accounting Tax Code Option | Tool to delete a tax code option from Ramp. Use when you need to remove a tax code option from the accounting system. |
| `RAMP_DELETE_ACCOUNTING_TAX_RATES` | Delete Accounting Tax Rate | Tool to delete an accounting tax rate from Ramp. Use when you need to remove a tax rate from the accounting system. |
| `RAMP_DELETE_ACCOUNTING_VENDORS` | Delete Accounting Vendor | Tool to delete an accounting vendor from Ramp. Use when you need to remove a vendor from the accounting system. |
| `RAMP_DELETE_CUSTOM_FIELD_OPTION` | Delete Custom Field Option | Tool to delete a custom accounting field option from Ramp. Use when you need to remove a specific option from a custom accounting field. |
| `RAMP_DELETE_INVENTORY_ITEM_FIELD` | Delete Inventory Item Field | Tool to delete the inventory item accounting field from Ramp. Use when you need to remove the inventory item field from the accounting connection. This uses the authenticated connection's context to identify which inventory item field to delete. |
| `RAMP_DELETE_SPEND_ALLOCATION_DELETE_USERS` | Remove Users from Shared Limit | Tool to remove users from a shared spend limit in Ramp. Use when you need to revoke a user's access to a shared spending allocation. |
| `RAMP_DELETE_WEBHOOK` | Delete Webhook Subscription | Tool to delete a webhook subscription by ID. Use when you need to remove a webhook subscription from Ramp. The operation is irreversible and returns no content on success. |
| `RAMP_FETCH_ACCOUNTING_ACCOUNT` | Fetch General Ledger Account | Tool to fetch a specific general ledger account by ID from Ramp. Use when you need to retrieve detailed information about a single GL account. |
| `RAMP_FETCH_ACCOUNTING_VENDOR` | Fetch Accounting Vendor | Tool to fetch a specific accounting vendor by ID from Ramp. Use when you need to retrieve detailed information about a single accounting vendor for coding transactions, reimbursements, bills, or purchase orders. |
| `RAMP_FETCH_CUSTOM_ACCOUNTING_FIELD` | Fetch Custom Accounting Field | Tool for fetching a custom accounting field. |
| `RAMP_GET_ACCOUNTING_ACCOUNTS` | List General Ledger Accounts | Tool to list general ledger accounts from Ramp. Use when you need to retrieve GL accounts for accounting integration or transaction categorization. |
| `RAMP_GET_ACCOUNTING_ALL_CONNECTIONS` | Fetch All Accounting Connections | Tool to fetch all accounting connections for the current Ramp business. Use when you need to view all accounting integrations, including both active and inactive connections. |
| `RAMP_GET_ACCOUNTING_CONNECTION` | Get Accounting Connection | Tool to fetch the current active accounting connection for a Ramp account. Use when you need to check the status, type, or configuration of the active accounting integration with providers like QuickBooks or NetSuite. |
| `RAMP_GET_ACCOUNTING_CONNECTION_BY_ID` | Fetch Accounting Connection By ID | Tool to fetch a specific accounting connection by ID from Ramp. Use when you need to retrieve detailed information about a particular accounting integration. |
| `RAMP_GET_ACCOUNTING_FIELDS` | List Custom Accounting Fields | Tool to list custom accounting fields for coding transactions. Use when you need to retrieve custom accounting fields that can be leveraged to code transactions, reimbursements, and bills. |
| `RAMP_GET_ACCOUNTING_VENDORS` | List Accounting Vendors | Tool to list accounting vendors from Ramp. Use when you need to retrieve vendor data for transaction coding, reimbursements, bills, or purchase orders in the accounting system. |
| `RAMP_GET_ALL_TRANSACTIONS` | Get All Transactions | Get all the transactions. |
| `RAMP_GET_CARD` | Get Card | Tool for retrieving detailed information about a specific card. Returns comprehensive card details including spending limits, cardholder info, and fulfillment status. Use this to get complete card profile for analysis or troubleshooting. |
| `RAMP_GET_CARD_VAULT_RESOURCE` | Get Card Vault Resource | Tool to fetch a card's sensitive details from the vault. Requires vault API access. Use when you need to retrieve PAN or CVV for a specific card. This endpoint uses a separate vault base URL. |
| `RAMP_GET_CUSTOM_FIELD_OPTION` | Get Custom Field Option | Tool to fetch a custom accounting field option by its ID. Use when you need to retrieve details about a specific custom accounting field option from Ramp's accounting integration. |
| `RAMP_GET_DEPARTMENT` | Get Department | Tool for retrieving detailed information about a specific department. Returns comprehensive department details including hierarchy information. Use this to get complete department profile for organizational analysis. |
| `RAMP_GET_INVENTORY_ITEM_FIELD` | Get Inventory Item Field | Tool to fetch inventory item accounting field for the current accounting connection. Use when you need to retrieve the inventory item field configuration from the connected ERP system. |
| `RAMP_GET_MEMO` | Get Memo | Tool to fetch a transaction memo. Use when you need to retrieve the memo text associated with a specific transaction. |
| `RAMP_GET_REIMBURSEMENT` | Get Reimbursement Details | Tool for retrieving complete details of a specific reimbursement. Includes amount, status, user information, accounting details, receipts, and sync status. Use this to get comprehensive reimbursement information for approval workflows or detailed analysis. |
| `RAMP_GET_SPEND_LIMIT` | Get Spend Limit | Tool to fetch detailed information about a specific spend limit. Use when you need to retrieve comprehensive limit details including balance, restrictions, linked cards, and users. |
| `RAMP_GET_STATEMENT` | Get Statement | Tool for retrieving statement details or downloading statements. Supports JSON, PDF, and CSV formats for financial reporting. |
| `RAMP_GET_TRANSACTION` | Get Transaction Details | Tool for retrieving complete details of a specific transaction. Includes merchant details, receipts, accounting codes, and dispute information. |
| `RAMP_GET_USER` | Get User | Tool to retrieve detailed information about a specific Ramp user by their ID. Use when you need complete user profile information including role, status, department, and custom fields. |
| `RAMP_GET_USERS_DEFERRED_STATUS` | Get Users Deferred Status | Tool for fetching the status of a deferred user task. Use when you need to check the progress or outcome of asynchronous user operations like user creation. |
| `RAMP_GET_VENDOR` | Get Vendor Details | Tool for retrieving detailed information about a specific vendor. Returns comprehensive vendor details including spending totals, category, and contact information. Use this to get complete vendor profile for analysis or updates. |
| `RAMP_GET_WEBHOOK` | Get Webhook | Tool to retrieve detailed information about a specific webhook subscription by ID. Use when you need to check webhook configuration, status, or event types. |
| `RAMP_ISSUE_VIRTUAL_CARD` | Issue Virtual Card | Tool for issuing virtual cards to users instantly. Creates cards with customizable spending limits and restrictions. Returns full card details including card number and CVV. |
| `RAMP_LIST_ACCOUNTING_INVENTORY_ITEM_OPTIONS` | List Accounting Inventory Item Options | Tool to list accounting inventory item options from Ramp. Use when you need to retrieve inventory items for accounting integration or transaction categorization. |
| `RAMP_LIST_ACCOUNTING_TAX_RATES` | List Accounting Tax Rates | Tool to list tax rates from Ramp's accounting integration. Use when you need to retrieve tax rate information for transaction categorization or tax compliance. |
| `RAMP_LIST_CARDS` | List All Cards | Tool for listing all cards across the organization with optional filters. Returns card details including spending limits, cardholder info, and state. Use this to analyze card distribution, monitor card states, or find specific cards. |
| `RAMP_LIST_DEPARTMENTS` | List Departments | Tool for listing all departments in the organization. Returns department details including names, codes, and hierarchy information. Use this to analyze organizational structure and department relationships. |
| `RAMP_LIST_MEMOS` | List Memos | Tool for listing memos associated with transactions in your Ramp organization. Returns memo details with support for filtering by card, user, department, location, manager, merchant, and date range. |
| `RAMP_LIST_REIMBURSEMENTS` | List Reimbursements | Tool for listing reimbursements with comprehensive filtering options. Returns reimbursement details including amounts, status, sync information, and associated entities. Use this to analyze reimbursement patterns, track approval workflows, and manage expense reimbursements. |
| `RAMP_LIST_STATEMENTS` | List Statements | Tool for listing all statements with filtering options. Perfect for financial reporting and reconciliation workflows. |
| `RAMP_LIST_USERS` | List Users | Tool for listing users in your Ramp organization with flexible filtering. Perfect for user audits, access management, and organizational analysis. Helps identify inactive users, role distribution, and departmental structures. |
| `RAMP_LIST_VENDORS` | List Vendors | Tool for listing vendors with their spending information. Returns vendor details including spending totals, categories, and activity status. Use this to analyze vendor relationships and procurement patterns. |
| `RAMP_LIST_VENDORS_ACCOUNTS` | List Vendor Bank Accounts | Tool for listing bank accounts associated with a specific vendor. Returns account details including currency, payment method, and default status. Use this to retrieve payment account information for vendor transactions. |
| `RAMP_LIST_VENDORS_CONTACTS` | List Vendor Contacts | Tool for listing contacts associated with a specific vendor. Returns contact information including names, emails, and phone numbers. Use this to find vendor contact details for communication or relationship management. |
| `RAMP_LIST_VENDORS_CREDITS` | List Vendor Credits | Tool to list all vendor credits for all vendors of a business. Use when you need to track vendor credits, analyze credit usage across vendors, or reconcile vendor accounts. |
| `RAMP_LIST_WEBHOOKS` | List Webhooks | Tool for listing all webhook subscriptions for the organization. Returns webhook details including endpoint URLs, event types, and status. Use this to audit webhook configurations and monitor active subscriptions. |
| `RAMP_OPTIONS_FOR_CUSTOM_ACCOUNTING_FIELD` | Options for Custom Accounting Field | Tool for listing options for a given accounting field. |
| `RAMP_PATCH_ACCOUNTING_CONNECTION` | Update Accounting Connection | Tool to update an accounting connection's settings. Use when you need to modify configuration for API-based accounting connections. This endpoint is restricted to Accounting API based connections only. |
| `RAMP_PATCH_CARD_RESOURCE` | Update Card | Tool to update a card's properties including owner, display name, and spending restrictions. Use when you need to modify card settings or reassign card ownership. |
| `RAMP_PATCH_CUSTOM_FIELD_OPTION` | Update Custom Field Option | Tool to update a custom accounting field option. Use when you need to modify display name, code, value, or visibility of an existing field option. |
| `RAMP_PATCH_GL_ACCOUNT_RESOURCE` | Update General Ledger Account | Tool to update a general ledger account in Ramp. Use when you need to modify the name, code, or reactivate a deleted GL account. |
| `RAMP_PATCH_INVENTORY_ITEM_FIELD` | Update Inventory Item Field | Tool to update the inventory item accounting field for a Ramp connection. Use when you need to modify the name or display name of the inventory item field. |
| `RAMP_POST_ACCOUNTING_ACCOUNTS` | Upload Accounting GL Accounts | Tool to batch upload general ledger accounts to Ramp. Supports up to 500 accounts per call with all-or-nothing validation. Use when you need to create GL accounts in Ramp's accounting system. |
| `RAMP_POST_ACCOUNTING_CONNECTION` | Create Accounting Connection | Tool to register a new API-based accounting connection between Ramp and an accounting provider. Use when establishing a new connection to accounting systems like QuickBooks, NetSuite, or Xero. If a Universal CSV connection exists, it will be upgraded to an API-based connection. |
| `RAMP_POST_ACCOUNTING_VENDORS` | Upload Accounting Vendors | Tool to batch upload vendors to Ramp for coding transactions, bills, and purchase orders. Supports up to 500 vendors per call with all-or-nothing validation. Use when you need to create vendors in Ramp's accounting system. |
| `RAMP_POST_INVENTORY_ITEM_OPTIONS` | Upload Inventory Item Options | Tool to upload inventory item options for an active inventory item accounting field. Use when you need to create inventory items in Ramp's accounting system. |
| `RAMP_POST_PHYSICAL_CARD` | Create Physical Card | Tool to create a physical card asynchronously. Returns a task ID which can be used to track the card creation status. Physical cards require fulfillment details with a shipping address. Use when a user needs a physical card for in-person transactions. |
| `RAMP_REACTIVATE_ACCOUNTING_CONNECTION` | Reactivate Accounting Connection | Tool to reactivate a previously unlinked accounting connection by changing its status back to linked. This preserves all previous accounting field configurations and settings. Use when you need to restore a disconnected accounting integration. The business must not have any other active accounting connections. |
| `RAMP_REACTIVATE_USER` | Reactivate User | Tool to reactivate a suspended user in your Ramp organization. Use when you need to restore a user's access. Upon reactivation, users can log in to Ramp again, spend on their previously issued cards, and resume receiving Ramp notifications. |
| `RAMP_SUBMIT_REIMBURSEMENT_RECEIPT` | Submit Reimbursement Receipt | Tool to upload a receipt for a reimbursement. Use when submitting receipts for out-of-pocket expenses. If reimbursement_id is provided, attaches the receipt to an existing reimbursement; otherwise creates a new draft reimbursement via OCR. |
| `RAMP_SUSPEND_CARD` | Suspend Card | Tool to suspend a card by creating an async task that locks the card from use. Use when you need to temporarily disable a card. The suspension is revertable. |
| `RAMP_TERMINATE_CARD` | Terminate Card | Tool to permanently terminate a Ramp card. This action creates an async task to terminate the card and is irreversible. Use when you need to permanently deactivate a card. The response contains a task ID that can be used to check the termination status. |
| `RAMP_UPDATE_ACCOUNTING_FIELD` | Update Custom Accounting Field | Tool to update a custom accounting field. Use when you need to modify the display name, name, or splittable setting of an existing custom accounting field. |
| `RAMP_UPDATE_ACCOUNTING_INVENTORY_ITEM_OPTIONS` | Update Accounting Inventory Item Option | Tool to update an inventory item option in Ramp's accounting system. Use when you need to modify an existing inventory item option's details. |
| `RAMP_UPDATE_ACCOUNTING_TAX_CODE` | Update Accounting Tax Code | Tool to update tax code accounting field. Use when you need to modify the name or display name of the tax code field in Ramp's accounting system. |
| `RAMP_UPDATE_ACCOUNTING_TAX_CODE_OPTIONS` | Update Accounting Tax Code Option | Tool to update a tax code option in Ramp. Use when you need to modify the name or associated tax rates of an existing tax code option. |
| `RAMP_UPDATE_ACCOUNTING_TAX_RATE` | Update Accounting Tax Rate | Tool to update an accounting tax rate in Ramp. Use when you need to modify the name, rate percentage, or associated GL account for an existing tax rate. |
| `RAMP_UPDATE_ACCOUNTING_VENDOR` | Update Accounting Vendor | Tool to update an accounting vendor in Ramp. Use when you need to modify vendor details such as name or code, or reactivate a deleted vendor. |
| `RAMP_UPDATE_CARD_LIMIT` | Update Card Spending Limit | Tool for updating spending limits on a card. Note: This returns the limits associated with the card. The actual update might require using the limit ID directly via PATCH /limits/{limit_id}. |
| `RAMP_UPDATE_DEPARTMENT` | Update Department | Tool for updating an existing department in your Ramp organization. Useful for reorganizing departmental structure or renaming departments. |
| `RAMP_UPDATE_LIMITS` | Update Spending Limit | Tool to update a spending limit in Ramp. Use when you need to modify limit settings such as display name, spending restrictions, permitted spend types, or user assignments. |
| `RAMP_UPDATE_USER` | Update User | Tool to update an existing user in your Ramp organization. Use when modifying user information such as name, department, role, or manager assignments. |
| `RAMP_UPLOAD_NEW_OPTIONS` | Upload New Options for Custom Accounting Field | Tool for uploading new options for a given accounting field. |
| `RAMP_UPLOAD_TAX_CODE_OPTIONS` | Upload Tax Code Options | Tool to upload tax code options to Ramp. Use when you need to create or update tax codes in the accounting system. Requires an active tax code accounting field for the accounting connection. |
| `RAMP_UPLOAD_TAX_RATES` | Upload Accounting Tax Rates | Tool to batch upload tax rates to Ramp. Supports up to 500 tax rates per call with all-or-nothing validation. Use when you need to create tax rates in Ramp's accounting system. Ensure data is sanitized and tax rates do not already exist before uploading. |

## Supported Triggers

None listed.

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

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

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

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 Ramp 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, ramp)
- 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 Ramp 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=["ramp"],
    )

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

  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 Ramp 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 Ramp
```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 Ramp, 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=["ramp"],
    )

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

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

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

## Related Toolkits

- [Stripe](https://composio.dev/toolkits/stripe) - Stripe is a global online payments platform offering APIs for managing payments, customers, and subscriptions. Trusted by businesses for secure, efficient, and scalable payment processing worldwide.
- [Alpha vantage](https://composio.dev/toolkits/alpha_vantage) - Alpha Vantage is a financial data platform offering real-time and historical stock market APIs. Get instant, reliable access to equities, forex, and technical analysis data for smarter trading decisions.
- [Altoviz](https://composio.dev/toolkits/altoviz) - Altoviz is a cloud-based billing and invoicing platform for businesses. It streamlines online payments, expense tracking, and customizable invoice management.
- [Benzinga](https://composio.dev/toolkits/benzinga) - Benzinga provides real-time financial news and data APIs for market coverage. It helps you track breaking news and actionable market insights instantly.
- [Brex](https://composio.dev/toolkits/brex) - Brex provides corporate credit cards and spend management tailored for startups and tech businesses. It helps optimize company cash flow, streamline accounting, and accelerate business growth.
- [Chaser](https://composio.dev/toolkits/chaser) - Chaser is accounts receivable automation software that sends invoice reminders and helps businesses get paid faster. It streamlines the collections process to save time and improve cash flow.
- [Clientary](https://composio.dev/toolkits/clientary) - Clientary is a platform for managing clients, invoices, projects, proposals, and more. It streamlines client work and saves you serious admin time.
- [Coinbase](https://composio.dev/toolkits/coinbase) - Coinbase is a platform for buying, selling, and storing cryptocurrency. It makes exchanging and managing crypto simple and secure for everyone.
- [Coinranking](https://composio.dev/toolkits/coinranking) - Coinranking is a comprehensive cryptocurrency market data platform offering access to real-time coin prices, market caps, and historical data. Get accurate, up-to-date stats for thousands of digital assets in one place.
- [Coupa](https://composio.dev/toolkits/coupa) - Coupa is a business spend management platform for procurement, invoicing, and expenses. It helps organizations streamline purchasing, control costs, and gain complete visibility over financial operations.
- [CurrencyScoop](https://composio.dev/toolkits/currencyscoop) - CurrencyScoop is a developer-friendly API for real-time and historical currency exchange rates. Easily access fiat and crypto data for smart, up-to-date financial applications.
- [Daffy](https://composio.dev/toolkits/daffy) - Daffy is a modern charitable giving platform with a donor-advised fund. Easily set aside funds, grow them tax-free, and donate to over 1.7 million U.S. charities.
- [Eagle doc](https://composio.dev/toolkits/eagle_doc) - Eagle doc is an AI-powered OCR API for invoices and receipts. It delivers fast, reliable, and accurate document data extraction for seamless automation.
- [Elorus](https://composio.dev/toolkits/elorus) - Elorus is an online invoicing and time-tracking software for freelancers and small businesses. Easily manage finances, bill clients, and track work in one place.
- [Eodhd apis](https://composio.dev/toolkits/eodhd_apis) - Eodhd apis delivers comprehensive financial data, including live and historical stock prices, via robust APIs. Easily access reliable, up-to-date market insights to power your apps, dashboards, and analytics.
- [Fidel api](https://composio.dev/toolkits/fidel_api) - Fidel api is a secure platform for linking payment cards to web and mobile apps. It enables real-time card transaction monitoring and event-based automation for businesses.
- [Finage](https://composio.dev/toolkits/finage) - Finage is a secure API platform delivering real-time and historical financial data for stocks, forex, crypto, indices, and commodities. It empowers developers and businesses to access, analyze, and act on market data instantly.
- [Finmei](https://composio.dev/toolkits/finmei) - Finmei is an invoicing tool that simplifies billing, invoice management, and expense tracking. Ideal for automating and organizing your business finances in one place.
- [Fixer](https://composio.dev/toolkits/fixer) - Fixer is a currency data API offering real-time and historical exchange rates for 170 currencies. Instantly access accurate, up-to-date forex data for your applications and workflows.
- [Fixer io](https://composio.dev/toolkits/fixer_io) - Fixer.io is a lightweight API for real-time and historical foreign exchange rates. It makes global currency conversion fast, accurate, and hassle-free.

## Frequently Asked Questions

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

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

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

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

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