# How to integrate Tomtom MCP with LangChain

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

## Introduction

This guide walks you through connecting Tomtom to LangChain 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 LangChain 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)
- [Vercel AI SDK](https://composio.dev/toolkits/tomtom/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/tomtom/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/tomtom/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/tomtom/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- Get and set up your OpenAI and Composio API keys
- Connect your Tomtom project to Composio
- Create a Tool Router MCP session for Tomtom
- Initialize an MCP client and retrieve Tomtom tools
- Build a LangChain agent that can interact with Tomtom
- Set up an interactive chat interface for testing

## What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides tools and abstractions for building agents that can reason, use tools, and maintain conversation context.
Key features include:
- Agent Framework: Build agents that can use tools and make decisions
- MCP Integration: Connect to external services through Model Context Protocol adapters
- Memory Management: Maintain conversation history across interactions
- Multi-Provider Support: Works with OpenAI, Anthropic, and other LLM providers

## 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

No description provided.

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

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install dependencies

No description provided.
```python
pip install composio-langchain langchain-mcp-adapters langchain python-dotenv
```

```typescript
npm install @composio/langchain @langchain/core @langchain/openai @langchain/mcp-adapters dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates your requests to Composio's API
- COMPOSIO_USER_ID identifies the user for session management
- OPENAI_API_KEY enables access to OpenAI's language models
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_composio_user_id_here
OPENAI_API_KEY=your_openai_api_key_here
```

### 4. Import dependencies

No description provided.
```python
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
from dotenv import load_dotenv
from composio import Composio
import asyncio
import os

load_dotenv()
```

```typescript
import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

dotenv.config();
```

### 5. Initialize Composio client

What's happening:
- We're loading the COMPOSIO_API_KEY from environment variables and validating it exists
- Creating a Composio instance that will manage our connection to Tomtom tools
- Validating that COMPOSIO_USER_ID is also set before proceeding
```python
async def main():
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))

    if not os.getenv("COMPOSIO_API_KEY"):
        raise ValueError("COMPOSIO_API_KEY is not set")
    if not os.getenv("COMPOSIO_USER_ID"):
        raise ValueError("COMPOSIO_USER_ID is not set")
```

```typescript
const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });
```

### 6. Create a Tool Router session

What's happening:
- We're creating a Tool Router session that gives your agent access to Tomtom tools
- The create method takes the user ID and specifies which toolkits should be available
- The returned session.mcp.url is the MCP server URL that your agent will use
- This approach allows the agent to dynamically load and use Tomtom tools as needed
```python
# Create Tool Router session for Tomtom
session = composio.create(
    user_id=os.getenv("COMPOSIO_USER_ID"),
    toolkits=['tomtom']
)

url = session.mcp.url
```

```typescript
const session = await composio.create(
    userId as string,
    {
        toolkits: ['tomtom']
    }
);

const url = session.mcp.url;
```

### 7. Configure the agent with the MCP URL

No description provided.
```python
client = MultiServerMCPClient({
    "tomtom-agent": {
        "transport": "streamable_http",
        "url": session.mcp.url,
        "headers": {
            "x-api-key": os.getenv("COMPOSIO_API_KEY")
        }
    }
})

tools = await client.get_tools()

agent = create_agent("gpt-5", tools)
```

```typescript
const client = new MultiServerMCPClient({
    "tomtom-agent": {
        transport: "http",
        url: url,
        headers: {
            "x-api-key": process.env.COMPOSIO_API_KEY
        }
    }
});

const tools = await client.getTools();

const agent = createAgent({ model: "gpt-5", tools });
```

### 8. Set up interactive chat interface

No description provided.
```python
conversation_history = []

print("Chat started! Type 'exit' or 'quit' to end the conversation.\n")
print("Ask any Tomtom related question or task to the agent.\n")

while True:
    user_input = input("You: ").strip()

    if user_input.lower() in ['exit', 'quit', 'bye']:
        print("\nGoodbye!")
        break

    if not user_input:
        continue

    conversation_history.append({"role": "user", "content": user_input})
    print("\nAgent is thinking...\n")

    response = await agent.ainvoke({"messages": conversation_history})
    conversation_history = response['messages']
    final_response = response['messages'][-1].content
    print(f"Agent: {final_response}\n")
```

```typescript
let conversationHistory: any[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log("Ask any Tomtom related question or task to the agent.\n");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: '
});

rl.prompt();

rl.on('line', async (userInput: string) => {
    const trimmedInput = userInput.trim();

    if (['exit', 'quit', 'bye'].includes(trimmedInput.toLowerCase())) {
        console.log("\nGoodbye!");
        rl.close();
        process.exit(0);
    }

    if (!trimmedInput) {
        rl.prompt();
        return;
    }

    conversationHistory.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    const response = await agent.invoke({ messages: conversationHistory });
    conversationHistory = response.messages;

    const finalResponse = response.messages[response.messages.length - 1]?.content;
    console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

    rl.on('close', () => {
        console.log('\n👋 Session ended.');
        process.exit(0);
    });
```

### 9. Run the application

No description provided.
```python
if __name__ == "__main__":
    asyncio.run(main())
```

```typescript
main().catch((err) => {
    console.error('Fatal error:', err);
    process.exit(1);
});
```

## Complete Code

```python
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
from dotenv import load_dotenv
from composio import Composio
import asyncio
import os

load_dotenv()

async def main():
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))
    
    if not os.getenv("COMPOSIO_API_KEY"):
        raise ValueError("COMPOSIO_API_KEY is not set")
    if not os.getenv("COMPOSIO_USER_ID"):
        raise ValueError("COMPOSIO_USER_ID is not set")
    
    session = composio.create(
        user_id=os.getenv("COMPOSIO_USER_ID"),
        toolkits=['tomtom']
    )

    url = session.mcp.url
    
    client = MultiServerMCPClient({
        "tomtom-agent": {
            "transport": "streamable_http",
            "url": url,
            "headers": {
                "x-api-key": os.getenv("COMPOSIO_API_KEY")
            }
        }
    })
    
    tools = await client.get_tools()
  
    agent = create_agent("gpt-5", tools)
    
    conversation_history = []
    
    print("Chat started! Type 'exit' or 'quit' to end the conversation.\n")
    print("Ask any Tomtom related question or task to the agent.\n")
    
    while True:
        user_input = input("You: ").strip()
        
        if user_input.lower() in ['exit', 'quit', 'bye']:
            print("\nGoodbye!")
            break
        
        if not user_input:
            continue
        
        conversation_history.append({"role": "user", "content": user_input})
        print("\nAgent is thinking...\n")
        
        response = await agent.ainvoke({"messages": conversation_history})
        conversation_history = response['messages']
        final_response = response['messages'][-1].content
        print(f"Agent: {final_response}\n")

if __name__ == "__main__":
    asyncio.run(main())
```

```typescript
import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";  
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });

    const session = await composio.create(
        userId as string,
        {
            toolkits: ['tomtom']
        }
    );

    const url = session.mcp.url;
    
    const client = new MultiServerMCPClient({
        "tomtom-agent": {
            transport: "http",
            url: url,
            headers: {
                "x-api-key": process.env.COMPOSIO_API_KEY
            }
        }
    });
    
    const tools = await client.getTools();
  
    const agent = createAgent({ model: "gpt-5", tools });
    
    let conversationHistory: any[] = [];
    
    console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
    console.log("Ask any Tomtom related question or task to the agent.\n");
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        prompt: 'You: '
    });

    rl.prompt();

    rl.on('line', async (userInput: string) => {
        const trimmedInput = userInput.trim();
        
        if (['exit', 'quit', 'bye'].includes(trimmedInput.toLowerCase())) {
            console.log("\nGoodbye!");
            rl.close();
            process.exit(0);
        }
        
        if (!trimmedInput) {
            rl.prompt();
            return;
        }
        
        conversationHistory.push({ role: "user", content: trimmedInput });
        console.log("\nAgent is thinking...\n");
        
        const response = await agent.invoke({ messages: conversationHistory });
        conversationHistory = response.messages;
        
        const finalResponse = response.messages[response.messages.length - 1]?.content;
        console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

    rl.on('close', () => {
        console.log('\nSession ended.');
        process.exit(0);
    });
}

main().catch((err) => {
    console.error('Fatal error:', err);
    process.exit(1);
});
```

## Conclusion

You've successfully built a LangChain agent that can interact with Tomtom through Composio's Tool Router.
Key features of this implementation:
- Dynamic tool loading through Composio's Tool Router
- Conversation history maintenance for context-aware responses
- Async Python provides clean, efficient execution of agent workflows
You can extend this further by adding error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

## 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)
- [Vercel AI SDK](https://composio.dev/toolkits/tomtom/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/tomtom/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/tomtom/framework/llama-index)
- [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 LangChain?

Yes, you can. LangChain 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)
