# How to integrate Tomtom MCP with LlamaIndex

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

## Introduction

This guide walks you through connecting Tomtom to LlamaIndex using the Composio tool router. By the end, you'll have a working Tomtom agent that can find nearby ev charging stations with live status, calculate fastest driving route to airport, search for italian restaurants around times square through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Tomtom account through Composio's Tomtom MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Tomtom with

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

The Tomtom MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Tomtom account. It provides structured and secure access to TomTom's advanced mapping, navigation, and location services, so your agent can perform actions like calculating routes, searching for points of interest, retrieving live traffic data, and managing map assets on your behalf.
- Dynamic route calculation and navigation: Ask your agent to generate driving, walking, or cycling routes with waypoints and real-time traffic considerations to optimize travel plans.
- Flexible location and place search: Let your agent perform fuzzy searches for addresses or points of interest, or find nearby locations by category such as restaurants, EV charging stations, or landmarks.
- Real-time traffic flow and road insights: Retrieve up-to-date traffic flow data for specific road segments, helping you monitor congestion, speed trends, and plan detours proactively.
- EV charging station availability: Check the current status and availability of EV charging stations, making it easy to plan electric vehicle journeys with confidence.
- Map styling and asset management: Manage map fonts, styles, sprites, and copyrights to customize the look and feel of maps integrated into your applications.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `TOMTOM_ASSETS_LIST_FONTS` | List Map Fonts | Tool to list available font asset versions for map rendering. Call after confirming the API key is valid. |
| `TOMTOM_ASSETS_LIST_SPRITES` | List Assets Sprites | Tool to list available sprites for a given asset version. Use after determining the assetVersion. |
| `TOMTOM_ASSETS_LIST_STYLES` | List map styles | Tool to list available map styles. Use after selecting an asset version to retrieve style options. |
| `TOMTOM_CALCULATE_LONG_DISTANCE_EV_ROUTE` | Calculate Long Distance EV Route | Tool to calculate long-distance electric vehicle routes with optimal charging stops. Use when planning EV trips that require charging along the route. |
| `TOMTOM_CALCULATE_MATRIX_ROUTING_SYNC` | Calculate Matrix Routing Sync | Tool to calculate route matrix synchronously for multiple origins and destinations (up to 200 cells). Use when you need travel times and distances between multiple location pairs with support for traffic, vehicle parameters, and routing options. |
| `TOMTOM_CALCULATE_REACHABLE_RANGE` | Calculate Reachable Range | Tool to calculate the reachable range from a starting point given time, fuel, or energy constraints. Use when you need to determine how far a vehicle can travel from an origin within specified budgets. |
| `TOMTOM_CALCULATE_ROUTE` | Calculate Route | Tool to calculate driving routes. Use when you need directions with optional waypoints and traffic consideration. |
| `TOMTOM_CALCULATE_ROUTE_WITH_BODY` | Calculate Route with Body | Tool to calculate routes with advanced options via POST request. Use when you need to specify supporting points, avoid specific geographic areas, or configure vignette preferences. |
| `TOMTOM_CATEGORY_SEARCH` | Category Search | Tool to search for Points of Interest by category. Use when you need to find POIs within a specific category around a location or area. |
| `TOMTOM_CREATE_NOTIFICATIONS_GROUPS` | Create Notifications Contact Group | Tool to create a contact group for TomTom notifications. Use when you need to set up a group of webhooks or emails to receive notification alerts. |
| `TOMTOM_CREATE_ROUTING_BATCH` | Create Routing Batch | Tool to submit asynchronous batch routing requests to TomTom API. Use when you need to calculate multiple routes efficiently in a single batch operation. The API returns a batch ID that can be used to retrieve results once processing is complete. |
| `TOMTOM_CREATE_ROUTING_BATCH_SYNC` | Create Routing Batch Sync | Tool to execute synchronous batch routing requests for multiple routes or reachable ranges. Use when you need to calculate multiple routes or reachable ranges in a single API call (max 100 items). |
| `TOMTOM_CREATE_ROUTING_MATRIX_ASYNC` | Create Routing Matrix Async | Tool to submit asynchronous matrix routing calculation between multiple origins and destinations. Use when you need to calculate travel times and distances for large matrices (returns immediately with a job ID for later retrieval). |
| `TOMTOM_CREATE_ROUTING_WAYPOINTOPTIMIZATION` | Create Waypoint Optimization | Tool to optimize the sequence of waypoints to find the fastest route. Use when you need to find the optimal order to visit multiple locations (2-12 waypoints) with optional time windows and service time constraints. |
| `TOMTOM_CREATE_SEARCH_GEOMETRYFILTER` | Geometry Filter | Tool to filter POIs by geometric boundaries (circles or polygons). Use when you need to check which POIs from a list fall within specific geographic areas. Supports up to 50 POIs per request. |
| `TOMTOM_CREATE_SNAP_TO_ROADS` | Create Snap to Roads | Tool to snap GPS track points to the road network, correcting for GPS inaccuracies. Use when you need to match raw GPS coordinates to actual roads for route reconstruction or map matching. |
| `TOMTOM_CREATE_SNAP_TO_ROADS_BATCH` | Create Snap to Roads Batch | Tool to submit asynchronous batch snap to roads requests to TomTom API. Use when you need to snap multiple GPS traces to the road network efficiently. The API returns a batch ID that can be used to retrieve results once processing is complete. |
| `TOMTOM_DELETE_NOTIFICATIONS_HISTORY` | Delete Notifications History | Tool to clear the entire notifications history for the account. Use when you need to delete all historical notification records. This is an asynchronous operation that returns a PROCESSING status immediately. |
| `TOMTOM_DOWNLOAD_BATCH_SEARCH_ASYNC` | Download Batch Search Results | Tool to download results of an asynchronous batch search job. Use when you have a batch ID from a previous batch submission and need to retrieve the search results. Returns HTTP 202 if still processing (with Location header for retry), or HTTP 200 with complete results when finished. |
| `TOMTOM_DOWNLOAD_MATRIX_ROUTING_ASYNC_RESULT` | Download Matrix Routing Async Result | Tool to download results of asynchronous matrix routing job. Use when you need to retrieve completed matrix routing results using the job ID from a previous async matrix submission. |
| `TOMTOM_DOWNLOAD_SNAP_TO_ROADS_ASYNC_RESULT` | Download Snap to Roads Async Result | Tool to download results of asynchronous snap to roads batch job. Use when you need to retrieve completed snap to roads results using the job ID from a previous async batch submission. Returns batch items with projected GPS points snapped to actual road geometry and detailed road information. |
| `TOMTOM_EV_CHARGING_STATIONS_AVAILABLE` | EV Charging Stations Availability | Tool to retrieve EV charging station availability info. Use when you have the chargingAvailability ID (from POI search dataSources) to get live availability. |
| `TOMTOM_FLOW_SEGMENT_DATA` | Flow Segment Data | Tool to retrieve traffic flow data for a specific road segment. Use when you need current and free flow speeds for given coordinates. |
| `TOMTOM_FUZZY_SEARCH` | Fuzzy Search | Tool to perform a fuzzy search for addresses and points of interest. Use when you need flexible matching on free-form location queries. |
| `TOMTOM_GEOCODE_QUERY` | Geocode Query | Tool to convert a free-form address query into geographic coordinates. Use when you need to geocode an address string without structured fields. |
| `TOMTOM_GET_AUTOCOMPLETE` | Get Autocomplete Suggestions | Tool to get search suggestions as user types a query. Use when you need autocomplete suggestions for partial search input based on recognized entities like brands, categories, or locations. |
| `TOMTOM_GET_COPYRIGHTS` | Get Map Tile Copyrights | Tool to retrieve copyright information for TomTom map tiles. Use when you need to display attribution or copyright notices for map content. |
| `TOMTOM_GET_GEOMETRY_SEARCH` | Get Geometry Search | Tool to search for POIs and locations within specified geometric areas (circles or polygons). Use when you need to find places within custom-defined boundaries. |
| `TOMTOM_GET_HILLSHADE_TILE` | Get Hillshade Tile | Tool to retrieve hillshade terrain map tiles for specified coordinates and zoom. Use when you need terrain elevation shading overlays for map visualization. |
| `TOMTOM_GET_INCIDENT_VIEWPORT` | Get Incident Viewport | Tool to retrieve incident viewport information including Traffic Model ID. Use when you need the current traffic model ID for a map viewport to make subsequent traffic API calls. |
| `TOMTOM_GET_MAP_COPYRIGHTS_BOUNDING_BOX` | Get Map Copyrights Bounding Box | Tool to retrieve copyright information for a geographic bounding box. Use when you need attribution for a specific map area defined by coordinates. |
| `TOMTOM_GET_MAP_COPYRIGHTS_CAPTION` | Get Map Copyrights Caption | Tool to retrieve the copyright caption text for TomTom maps. Use when you need to display attribution or copyright notices on map displays. |
| `TOMTOM_GET_MAP_COPYRIGHTS_FORMAT` | Get Map Copyrights (Global) | Tool to retrieve copyright information for the whole world in the Maps API Raster Tile Service. Use when you need global copyright data for map display attribution. |
| `TOMTOM_GET_MAPS_ORBIS_MAP_TILE` | Get Orbis Map Tile | Tool to retrieve Orbis map tiles at specified zoom level and coordinates. Use when you need high-quality map tiles for custom map rendering. Supports both raster (PNG) and vector (PBF) tile formats. |
| `TOMTOM_GET_MAPS_ORBIS_TRAFFIC_TILE` | Get Orbis Traffic Incident Tile | Tool to retrieve Orbis Traffic Incident Tiles containing traffic incident data in Protocol Buffer format. Use when you need detailed traffic incident information for a specific tile coordinate at a given zoom level. |
| `TOMTOM_GET_MAP_STYLE_METADATA` | Get Map Style Metadata | Tool to retrieve map style metadata. Use to get a list of available map style resources. Returns available style files like flow styles and incident styles. |
| `TOMTOM_GET_MAP_STYLES` | Get map styles metadata | Tool to retrieve map style metadata as a Mapbox Style Specification JSON. Use to get a merged style definition combining map, traffic, and POI components for vector map rendering. |
| `TOMTOM_GET_NOTIFICATIONS_GROUPS_GROUPID` | Get Contact Group | Tool to retrieve details of a specific contact group by its UUID. Use when you need to get the name, webhook URLs, and email addresses associated with a contact group. |
| `TOMTOM_GET_NOTIFICATIONS_HISTORY` | Get Notifications History | Tool to retrieve notifications history from TomTom. Use when you need to list past notifications sent within a specific time range (must be less than 24 hours). |
| `TOMTOM_GET_NOTIFICATIONS_SETTINGS` | Get Notifications Settings | Tool to retrieve current notification settings. Use when you need to check notification configuration options. |
| `TOMTOM_GET_ORBIS_GEOCODE` | Orbis Geocode | Tool to geocode addresses using TomTom's Orbis Maps API. Use when converting address queries to geographic coordinates. |
| `TOMTOM_GET_ORBIS_PLACES_AUTOCOMPLETE` | Orbis Places Autocomplete | Tool to get autocomplete suggestions for place searches using TomTom Orbis Maps. Use when you need to recognize entities (brands, categories, locations) in a query and offer them as structured search terms. |
| `TOMTOM_GET_ORBIS_STRUCTURED_GEOCODE` | Orbis Structured Geocode | Tool to convert structured address fields into geographic coordinates using TomTom Orbis Maps API. Use when you have structured address components and need precise geocoding. |
| `TOMTOM_GET_ORBIS_TRAFFIC_FLOW_TILE` | Get Orbis Traffic Flow Tile | Tool to retrieve Orbis traffic flow tile data in Protocol Buffer format. Use when you need traffic flow information for a specific map tile coordinate. |
| `TOMTOM_GET_ORBIS_TRAFFIC_INCIDENT_DETAILS` | Get Orbis Traffic Incident Details | Tool to retrieve detailed Orbis traffic incidents by bounding box or IDs. Use when you need comprehensive incident data including events, delays, and geometry. |
| `TOMTOM_GET_ROUTING_BATCH` | Get Routing Batch Results | Tool to download asynchronous batch routing results. Use when you need to retrieve the results of a previously submitted batch routing request using its batch ID. Returns HTTP 202 if processing is still ongoing (retry with Location header), or HTTP 200 with completed results. |
| `TOMTOM_GET_ROUTING_MATRIX_ASYNC_STATUS` | Get Matrix Routing Async Status | Tool to check the status of an asynchronous matrix routing job. Use when you need to poll the status of a previously submitted matrix routing request to determine if it's still processing, completed successfully, or failed. |
| `TOMTOM_GET_SATELLITE_TILE` | Get Satellite Tile | Tool to retrieve satellite imagery map tiles at specified coordinates and zoom. Use when you need high-resolution satellite imagery for mapping applications. |
| `TOMTOM_GET_SNAP_TO_ROADS_BATCH_STATUS` | Get Snap to Roads Batch Status | Tool to check the status of an asynchronous Snap to Roads batch job. Use when you need to poll the status of a previously submitted snap to roads batch request to determine if it's still processing or completed. |
| `TOMTOM_GET_TRAFFIC_FLOW_TILES_RASTER` | Get Traffic Flow Tiles Raster | Tool to retrieve raster traffic flow map tiles for visualization. Use when you need to display real-time traffic flow conditions on a map. |
| `TOMTOM_GET_TRAFFIC_INCIDENT_DETAILS` | Get Traffic Incident Details | Tool to retrieve traffic incident details within a bounding box at a specified zoom level. Use when you need detailed incident information for map rendering or traffic analysis. |
| `TOMTOM_GET_TRAFFIC_INCIDENT_TILE` | Get Traffic Incident Tile | Tool to retrieve raster traffic incident map tiles showing traffic incidents at specified coordinates and zoom. Use when you need visual overlay of traffic incidents for custom map rendering. |
| `TOMTOM_GET_TRAFFIC_INCIDENT_VIEWPORT` | Get Traffic Incident Viewport | Tool to retrieve traffic incidents within a viewport defined by bounding box and zoom level. Use when you need incident data for a specific map view with overview context. |
| `TOMTOM_LIST_GEOFENCING_ALERT_RULES` | List Geofencing Alert Rules | Tool to list geofencing alert rules with optional filtering. Use when you need to retrieve configured alert rules for projects, fences, or objects. |
| `TOMTOM_LIST_GEOFENCING_ALERTS_HISTORY` | List Geofencing Alerts History | Tool to retrieve geofencing alert history within a specified time range. Use when you need to query past alerts triggered by geofencing rules. |
| `TOMTOM_LIST_GEOFENCING_OBJECTS` | List Geofencing Objects | Tool to list all tracked objects in the TomTom Geofencing system. Use when you need to retrieve all objects currently being tracked for geofencing operations. |
| `TOMTOM_LIST_LOCATION_HISTORY_OBJECTS` | List Location History Objects | Tool to list objects with location history. Use when you need to retrieve all objects being tracked for location history. |
| `TOMTOM_LIST_NOTIFICATION_GROUPS` | List Notification Groups | Tool to list notification contact groups. Use when you need to retrieve available contact groups for notifications. Note: This service will be decommissioned on January 31, 2027. |
| `TOMTOM_LIST_POI_CATEGORIES` | List POI Categories | Tool to retrieve all POI categories supported by TomTom Search API. Use when you need the complete list of category IDs and names for searching POIs. |
| `TOMTOM_LIST_SPRITE_VERSIONS` | List Sprite Versions | Tool to list available sprite asset versions. Use when you need to know which sprite versions are available after obtaining a valid API key. |
| `TOMTOM_MAP_DISPLAY_COPYRIGHTS` | Get Map Copyrights | Tool to retrieve copyright information for a specific map tile. Use when you need to display or verify attribution for a given tile. |
| `TOMTOM_MAP_DISPLAY_RASTER_TILE` | MAP_DISPLAY_RASTER_TILE | Tool to retrieve a raster map tile for specified coordinates and zoom. Use when you need direct tile image data for custom map rendering. |
| `TOMTOM_MAP_DISPLAY_STATIC_IMAGE` | Map Display Static Image | Tool to fetch a static map snapshot given center coords and zoom. Use when you need a standalone map image for display. |
| `TOMTOM_MAP_DISPLAY_WMS_GET_MAP` | Map Display WMS GetMap | Tool to retrieve a map image via WMS GetMap. Use when you need georeferenced map layers for custom rendering. |
| `TOMTOM_MATRIX_ROUTING` | Matrix Routing | Tool to calculate travel time and distance matrix between multiple locations. Use when you require a matrix of travel times and distances between multiple origins and destinations. |
| `TOMTOM_NEARBY_SEARCH` | Nearby Search | Tool to find Points of Interest near a specified location. Use after confirming coordinates to discover nearby POIs. |
| `TOMTOM_PATCH_NOTIFICATIONS_GROUPS_GROUPID` | Edit Contact Group (Partial) | Tool to partially update a contact group in TomTom Notifications API. Use when you need to edit the name, webhook URLs, or email addresses of an existing contact group. |
| `TOMTOM_POINTS_OF_INTEREST_SEARCH` | Points of Interest Search | Tool to search for points of interest by query. Use when you need POI suggestions by name or category. |
| `TOMTOM_REVERSE_GEOCODE` | Reverse Geocode | Tool to convert geographic coordinates into a human-readable address. Use when you need to obtain address information from latitude and longitude values. |
| `TOMTOM_REVERSE_GEOCODE_CROSS_STREET` | Reverse Geocode Cross Street | Tool to find the nearest cross street or intersection for given geographic coordinates. Use when you need to identify street intersections near a specific latitude/longitude position. |
| `TOMTOM_REVERSE_GEOCODE_ORBIS` | Reverse Geocode Orbis | Tool to convert geographic coordinates into a human-readable address using TomTom's Orbis Maps API. Use when you need detailed address information from latitude and longitude values with Orbis data coverage. |
| `TOMTOM_SEARCH_ALONG_ROUTE` | Search Along Route | Tool to search for Points of Interest along a specified route with detour time constraints. Use when you need to find POIs (restaurants, gas stations, hotels) accessible from a planned route. |
| `TOMTOM_SEARCH_ALONG_ROUTE_V2` | Search Along Route (v2) | Tool to search for Points of Interest along a specified route using Search API v2. Use when you need to find POIs accessible from a planned route with detour constraints. |
| `TOMTOM_SEARCH_GEOMETRY` | Search Geometry | Tool to search for POIs within geometric areas (circles or polygons). Use when you need to find points of interest constrained to specific geographic boundaries. |
| `TOMTOM_SEARCH_ORBIS_CATEGORY` | Orbis Category Search | Tool to search for Points of Interest by category using TomTom Orbis Maps API. Use when you need to find POIs within specific categories using the Orbis mapping service. |
| `TOMTOM_SEARCH_ORBIS_PLACES` | Orbis Places Search | Tool to perform fuzzy search for addresses and points of interest using TomTom Orbis Maps API. Use when you need flexible matching on free-form location queries with the Orbis mapping service. |
| `TOMTOM_SEARCH_ORBIS_POI` | Orbis POI Search | Tool to search for points of interest using TomTom Orbis Maps API. Use when you need POI suggestions by name or category from the Orbis dataset. |
| `TOMTOM_SNAP_TO_ROADS_SYNC` | Snap to Roads (Sync) | Tool to snap GPS points to the road network synchronously. Maps raw GPS coordinates to actual road geometry, useful for map matching and route reconstruction. |
| `TOMTOM_STRUCTURED_GEOCODE` | Structured Geocode | Tool to convert structured address fields into coordinates. Use after collecting street, city, and postal code. |
| `TOMTOM_TRAFFIC_INCIDENTS` | Traffic Incidents | Tool to retrieve detailed traffic incidents within a bounding box. Use when you need incident details for a defined map area. |
| `TOMTOM_UPDATE_GEOFENCING_SECRET` | Update Geofencing Secret | Tool to change the customer secret for TomTom Geofencing API. Use when you need to update or rotate the authentication secret for geofencing operations. |
| `TOMTOM_UPDATE_NOTIFICATIONS_GROUP` | Update Notifications Group | Tool to update an existing contact group in TomTom Notifications API. Use when you need to modify the name, webhook URLs, or email addresses of a contact group. |

## Supported Triggers

None listed.

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

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

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

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 Tomtom 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, tomtom)
- 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 Tomtom 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=["tomtom"],
    )

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

  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 Tomtom 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 Tomtom
```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 Tomtom, 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=["tomtom"],
    )

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

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

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

## Related Toolkits

- [Excel](https://composio.dev/toolkits/excel) - Microsoft Excel is a robust spreadsheet application for organizing, analyzing, and visualizing data. It's the go-to tool for calculations, reporting, and flexible data management.
- [21risk](https://composio.dev/toolkits/_21risk) - 21RISK is a web app built for easy checklist, audit, and compliance management. It streamlines risk processes so teams can focus on what matters.
- [Abstract](https://composio.dev/toolkits/abstract) - Abstract provides a suite of APIs for automating data validation and enrichment tasks. It helps developers streamline workflows and ensure data quality with minimal effort.
- [Addressfinder](https://composio.dev/toolkits/addressfinder) - Addressfinder is a data quality platform for verifying addresses, emails, and phone numbers. It helps you ensure accurate customer and contact data every time.
- [Agenty](https://composio.dev/toolkits/agenty) - Agenty is a web scraping and automation platform for extracting data and automating browser tasks—no coding needed. It streamlines data collection, monitoring, and repetitive online actions.
- [Ambee](https://composio.dev/toolkits/ambee) - Ambee is an environmental data platform providing real-time, hyperlocal APIs for air quality, weather, and pollen. Get precise environmental insights to power smarter decisions in your apps and workflows.
- [Ambient weather](https://composio.dev/toolkits/ambient_weather) - Ambient Weather is a platform for personal weather stations with a robust API for accessing local, real-time, and historical weather data. Get detailed environmental insights directly from your own sensors for smarter apps and automations.
- [Anonyflow](https://composio.dev/toolkits/anonyflow) - Anonyflow is a service for encryption-based data anonymization and secure data sharing. It helps organizations meet GDPR, CCPA, and HIPAA data privacy compliance requirements.
- [Api ninjas](https://composio.dev/toolkits/api_ninjas) - Api ninjas offers 120+ public APIs spanning categories like weather, finance, sports, and more. Developers use it to supercharge apps with real-time data and actionable endpoints.
- [Api sports](https://composio.dev/toolkits/api_sports) - Api sports is a comprehensive sports data platform covering 2,000+ competitions with live scores and 15+ years of stats. Instantly access up-to-date sports information for analysis, apps, or chatbots.
- [Apify](https://composio.dev/toolkits/apify) - Apify is a cloud platform for building, deploying, and managing web scraping and automation tools called Actors. It lets you automate data extraction and workflow tasks at scale—no infrastructure headaches.
- [Autom](https://composio.dev/toolkits/autom) - Autom is a lightning-fast search engine results data platform for Google, Bing, and Brave. Developers use it to access fresh, low-latency SERP data on demand.
- [Beaconchain](https://composio.dev/toolkits/beaconchain) - Beaconchain is a real-time analytics platform for Ethereum 2.0's Beacon Chain. It provides detailed insights into validators, blocks, and overall network performance.
- [Big data cloud](https://composio.dev/toolkits/big_data_cloud) - BigDataCloud provides APIs for geolocation, reverse geocoding, and address validation. Instantly access reliable location intelligence to enhance your applications and workflows.
- [Bigpicture io](https://composio.dev/toolkits/bigpicture_io) - BigPicture.io offers APIs for accessing detailed company and profile data. Instantly enrich your applications with up-to-date insights on 20M+ businesses.
- [Bitquery](https://composio.dev/toolkits/bitquery) - Bitquery is a blockchain data platform offering indexed, real-time, and historical data from 40+ blockchains via GraphQL APIs. Get unified, reliable access to complex on-chain data for analytics, trading, and research.
- [Brightdata](https://composio.dev/toolkits/brightdata) - Brightdata is a leading web data platform offering advanced scraping, SERP APIs, and anti-bot tools. It lets you collect public web data at scale, bypassing blocks and friction.
- [Builtwith](https://composio.dev/toolkits/builtwith) - BuiltWith is a web technology profiler that uncovers the technologies powering any website. Gain actionable insights into analytics, hosting, and content management stacks for smarter research and lead generation.
- [Byteforms](https://composio.dev/toolkits/byteforms) - Byteforms is an all-in-one platform for creating forms, managing submissions, and integrating data. It streamlines workflows by centralizing form data collection and automation.
- [Cabinpanda](https://composio.dev/toolkits/cabinpanda) - Cabinpanda is a data collection platform for building and managing online forms. It helps streamline how you gather, organize, and analyze responses.

## Frequently Asked Questions

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

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

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

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

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