How to integrate Google Super MCP with LlamaIndex

Framework Integration Gradient
Google Super Logo
LlamaIndex Logo
divider

Introduction

This guide walks you through connecting Google Super to LlamaIndex using the Composio tool router. By the end, you'll have a working Google Super agent that can share this google drive file with my team, summarize unread gmail messages from today, add a new sheet to my budget spreadsheet, upload these photos to my family album through natural language commands.

This guide will help you understand how to give your LlamaIndex agent real control over a Google Super account through Composio's Google Super MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

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 Google Super
  • Connect LlamaIndex to the Google Super MCP server
  • Build a Google Super-powered agent using LlamaIndex
  • Interact with Google Super 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 Google Super MCP server, and what's possible with it?

The Google Super MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Google Super account. It provides structured and secure access to all your core Google services—Drive, Calendar, Gmail, Sheets, Analytics, Ads, Photos, and more—so your agent can perform actions like managing files, organizing emails, updating spreadsheets, and handling media on your behalf.

  • Unified email and label management: Enable your agent to organize Gmail by adding or removing labels, and streamline inbox workflows for faster, smarter communication.
  • Spreadsheet creation and data operations: Direct your agent to create new sheets, aggregate and analyze column data, or append rows and columns to Google Sheets for seamless data management.
  • Collaborative file sharing and permissions: Have your agent update Google Drive file sharing settings, granting roles or access to users, groups, or domains effortlessly.
  • Media upload and organization in Google Photos: Let your agent batch upload media files, add them to albums, or enrich your photo library by automating media management tasks.
  • Customer and ads list management: Empower your agent to add or remove contacts from Google Ads customer lists, making marketing and outreach a breeze without manual effort.

Supported Tools & Triggers

Tools
Triggers
Add EnrichmentAdds an enrichment at a specified position in a defined album.
Add file sharing preferenceModifies sharing permissions for an existing google drive file, granting a specified role to a user, group, domain, or 'anyone'.
Modify email labelsAdds and/or removes specified gmail labels for a message; ensure `message id` and all `label ids` are valid (use 'listlabels' for custom label ids).
Add or remove to customer listAddorremovetocustomerlist tool will add a contact to a customer list in google ads.
Add Sheet to SpreadsheetAdds a new sheet (worksheet) to a spreadsheet.
Aggregate Column DataSearches for rows where a specific column matches a value and performs mathematical operations on data from another column.
Append DimensionTool to append new rows or columns to a sheet, increasing its size.
Batch Add Media ItemsAdds one or more media items to an album in google photos.
Batch Create Media ItemsUnified action to upload media files and create them as items in google photos.
Batch get spreadsheetRetrieves data from specified cell ranges in a google spreadsheet; ensure the spreadsheet has at least one worksheet and any explicitly referenced sheet names in ranges exist.
Batch Get Media ItemsReturns the list of media items for the specified media item identifiers.
Batch update spreadsheetUpdates a specified range in a google sheet with given values, or appends them as new rows if `first cell location` is omitted; ensure the target sheet exists and the spreadsheet contains at least one worksheet.
Batch Update Values by Data FilterTool to update values in ranges matching data filters.
Insert Calendar into ListInserts an existing calendar into the user's calendar list.
Update Calendar List EntryUpdates an existing entry on the user\'s calendar list.
Delete CalendarDeletes a secondary calendar.
Update CalendarUpdates metadata for a calendar.
Clear Basic FilterTool to clear the basic filter from a sheet.
Clear CalendarClears a primary calendar.
Clear tasksPermanently clears all completed tasks from a specified google tasks list; this action is destructive and idempotent.
Clear spreadsheet valuesClears cell content (preserving formatting and notes) from a specified a1 notation range in a google spreadsheet; the range must correspond to an existing sheet and cells.
Copy Google DocumentTool to create a copy of an existing google document.
Copy fileDuplicates an existing file in google drive, identified by its `file id`.
Create AlbumCreates a new album in google photos.
Create Chart in Google SheetsCreate a chart in a google sheets spreadsheet using the specified data range and chart type.
Create CommentTool to create a comment on a file.
Create customer listCreatecustomerlist tool will create a customer list in google ads.
Create a documentCreates a new google docs document using the provided title as filename and inserts the initial text at the beginning if non-empty, returning the document's id and metadata (excluding body content).
Create Document MarkdownCreates a new google docs document, optionally initializing it with a title and content provided as markdown text.
Create Shared DriveTool to create a new shared drive.
Create email draftCreates a gmail email draft, supporting to/cc/bcc, subject, plain/html body (ensure `is html=true` for html), attachments, and threading.
Create EventCreates an event on a google calendar, needing rfc3339 utc start/end times (end after start) and write access to the calendar.
Create Expanded Data SetTool to create an expanded data set for a property.
Create File or FolderCreates a new file or folder with metadata.
Create a File from TextCreates a new file in google drive from provided text content (up to 10mb), supporting various formats including automatic conversion to google workspace types.
Create a folderCreates a new folder in google drive, optionally within a parent folder specified by its id or name; if a parent name is provided but not found, the action will fail.
Create FooterTool to create a new footer in a google document.
Create FootnoteTool to create a new footnote in a google document.
Create a Google SheetCreates a new google spreadsheet in google drive using the provided title.
Create HeaderTool to create a new header in a google document.
Create labelCreates a new label with a unique name in the specified user's gmail account.
Create a MeetCreates a new google meet space, optionally configuring its access type and entry point access controls.
Create Named RangeTool to create a new named range in a google document.
Create Paragraph BulletsTool to add bullets to paragraphs within a specified range in a google document.
Create ReplyTool to create a reply to a comment in google drive.
Create Shortcut to File/FolderTool to create a shortcut to a file or folder in google drive.
Create spreadsheet columnCreates a new column in a google spreadsheet, requiring a valid `spreadsheet id` and an existing `sheet id`; an out-of-bounds `insert index` may append/prepend the column.
Create spreadsheet rowInserts a new, empty row into a specified sheet of a google spreadsheet at a given index, optionally inheriting formatting from the row above.
Create a task listCreates a new task list with the specified title.
Delete CommentDeletes a comment from a file.
Delete Content Range in DocumentTool to delete a range of content from a google document.
Delete Dimension (Rows/Columns)Tool to delete specified rows or columns from a sheet in a google spreadsheet.
Delete DraftPermanently deletes a specific gmail draft using its id; ensure the draft exists and the user has necessary permissions for the given `user id`.
Delete Shared DriveTool to permanently delete a shared drive.
Delete eventDeletes a specified event by `event id` from a google calendar (`calendar id`); this action is idempotent and raises a 404 error if the event is not found.
Delete FooterTool to delete a footer from a google document.
Delete HeaderDeletes the header from the specified section or the default header if no section is specified.
Delete messagePermanently deletes a specific email message by its id from a gmail mailbox; for `user id`, use 'me' for the authenticated user or an email address to which the authenticated user has delegated access.
Delete Named RangeTool to delete a named range from a google document.
Delete Paragraph BulletsTool to remove bullets from paragraphs within a specified range in a google document.
Delete PermissionDeletes a permission from a file by permission id.
Delete ReplyTool to delete a specific reply by reply id.
Delete SheetTool to delete a sheet (worksheet) from a spreadsheet.
Delete TableTool to delete an entire table from a google document.
Delete Table ColumnTool to delete a column from a table in a google document.
Delete Table RowTool to delete a row from a table in a google document.
Delete taskDeletes a specified task from a given task list in google tasks.
Delete task listPermanently deletes an existing google task list, identified by `tasklist id`, along with all its tasks; this operation is irreversible.
Distance MatrixCalculates travel distance and time for a matrix of origins and destinations.
Download a file from Google DriveDownloads a file from google drive by its id.
Create a calendarCreates a new, empty google calendar with the specified title (summary).
Edit FileUpdates an existing google drive file by overwriting its entire content with new text (max 10mb).
Empty TrashTool to permanently delete all of the user's trashed files.
Get Event InstancesReturns instances of the specified recurring event.
List EventsReturns events on the specified calendar.
Move EventMoves an event to another calendar, i.
Watch EventsWatch for changes to events resources.
Execute SQL on SpreadsheetExecute sql queries against google sheets tables.
Fetch emailsFetches a list of email messages from a gmail account, supporting filtering, pagination, and optional full content retrieval.
Fetch message by message IDFetches a specific email message by its id, provided the `message id` exists and is accessible to the authenticated `user id`.
Fetch Message by Thread IDRetrieves messages from a gmail thread using its `thread id`, where the thread must be accessible by the specified `user id`.
Modify File LabelsModifies the set of labels applied to a file.
Find eventFinds events in a specified google calendar using text query, time ranges (event start/end, last modification), and event types; ensure `timemin` is not chronologically after `timemax` if both are provided.
Find fileTool to list or search for files and folders in google drive.
Find folderTool to find a folder in google drive by its name and optionally a parent folder.
Find free slotsFinds both free and busy time slots in google calendars for specified calendars within a defined time range (defaults to the current day utc if `time min`/`time max` are omitted).
Find worksheet by titleFinds a worksheet by its exact, case-sensitive title within a google spreadsheet; returns a boolean indicating if found and the complete metadata of the entire spreadsheet, regardless of whether the target worksheet is found.
Format cellApplies text and background cell formatting to a specified range in a google sheets worksheet.
Forward email messageForward an existing gmail message to specified recipients, preserving original body and attachments.
Query Free/Busy InformationReturns free/busy information for a set of calendars.
Generate File IDsGenerates a set of file ids which can be provided in create or copy requests.
Get aboutTool to retrieve information about the user, the user's drive, and system capabilities.
Get AccountTool to retrieve a single account by its resource name.
Get AlbumReturns the album based on the specified albumid.
Get Gmail attachmentRetrieves a specific attachment by id from a message in a user's gmail mailbox, requiring valid message and attachment ids.
Get Google CalendarRetrieves a specific google calendar, identified by `calendar id`, to which the authenticated user has access.
Get Campaign By IdGetcampaignbyid tool will return details of a campaign in google ads.
Get campaign by nameGetcampaignbyname tool will run a sql getcampaignbyname in google ads.
Get Changes Start Page TokenTool to get the starting pagetoken for listing future changes in google drive.
Get Charts from SpreadsheetTool to retrieve a list of all charts from a specified google sheets spreadsheet.
Get CommentTool to get a comment by id.
Get conference recordGet conference record
Get contactsFetches contacts (connections) for the authenticated google account, allowing selection of specific data fields and pagination.
Get current date and timeGets the current date and time, allowing for a specific timezone offset.
Get customer listsGetcustomerlists tool will list all customer lists in google ads.
Get directionsFetches detailed directions between an origin and a destination, supporting intermediate waypoints and various travel modes.
Get document by idRetrieves an existing google document by its id; will error if the document is not found.
Get Shared DriveTool to get a shared drive by id.
Get File MetadataTool to get a file's metadata by id.
Download Photos Media ItemDownloads a media item from google photos and returns it as a file.
Get Meet detailsRetrieve details of a google meet space using its unique identifier.
Get Participant SessionTool to get a specific participant session from a conference record.
Get PeopleRetrieves either a specific person's details (using `resource name`) or lists 'other contacts' (if `other contacts` is true), with `person fields` specifying the data to return.
Get PermissionGets a permission by id.
Get ProfileRetrieves key gmail profile information (email address, message/thread totals, history id) for a user.
Get recordings by conference record IDRetrieves recordings from google meet for a given conference record id.
Get ReplyTool to get a specific reply to a comment on a file.
Get RevisionTool to get a specific revision's metadata by revision id.
Get RouteCalculates one or more routes between two specified locations using various travel modes and preferences; addresses must be resolvable by google maps.
Get sheet namesLists all worksheet names from a specified google spreadsheet (which must exist), useful for discovering sheets before further operations.
Get Spreadsheet by Data FilterReturns the spreadsheet at the given id, filtered by the specified data filters.
Get spreadsheet infoRetrieves comprehensive metadata for a google spreadsheet using its id, excluding cell data.
Get Table SchemaThis action is used to get the schema of a table in a google spreadsheet, call this action to get the schema of a table in a spreadsheet before you query the table.
Get TaskUse to retrieve a specific google task if its `task id` and parent `tasklist id` are known.
Get task listRetrieves a specific task list from the user's google tasks if the `tasklist id` exists for the authenticated user.
Get transcripts by conference record IDRetrieves all transcripts for a specific google meet conference using its conferencerecord id.
Delete folder or fileTool to delete a file or folder in google drive.
Hide Shared DriveTool to hide a shared drive from the default view.
Insert Dimension in Google SheetTool to insert new rows or columns into a sheet at a specified location.
Insert Inline ImageTool to insert an image from a given uri at a specified location in a google document as an inline image.
Insert Page BreakTool to insert a page break into a google document.
Insert Table in Google DocTool to insert a table into a google document.
Insert Table ColumnTool to insert a new column into a table in a google document.
Insert TaskCreates a new task in a given `tasklist id`, optionally as a subtask of an existing `task parent` or positioned after an existing `task previous` sibling, where both `task parent` and `task previous` must belong to the same `tasklist id` if specified.
Insert Text into DocumentTool to insert a string of text at a specified location within a google document.
List AccountsTool to list all accounts accessible by the caller.
List ACL RulesRetrieves the list of access control rules (acls) for a specified calendar, providing the necessary 'rule id' values required for updating specific acl rules.
List AlbumsLists all albums shown to a user in the albums tab of google photos.
List AudiencesTool to list all audiences on a property.
List Google CalendarsRetrieves calendars from the user's google calendar list, with options for pagination and filtering.
List ChangesTool to list the changes for a user or shared drive.
List CommentsTool to list all comments for a file in google drive.
List Conference RecordsTool to list conference records.
List draftsRetrieves a paginated list of email drafts from a user's gmail account.
List File LabelsTool to list the labels on a file.
List Files and FoldersTool to list a user's files and folders in google drive.
List Gmail labelsRetrieves a list of all system and user-created labels for the specified gmail account.
List Media ItemsLists all media items from a user's google photos library.
List Participant SessionsTool to list all participant sessions for a specific conference record in google meet.
List PermissionsTool to list a file's permissions.
List Replies to CommentTool to list replies to a comment in google drive.
List File RevisionsTool to list a file's revisions.
List Shared DrivesTool to list the user's shared drives.
List Charts from SpreadsheetTool to retrieve a list of charts with their ids and metadata from a google sheets spreadsheet.
List Tables in SpreadsheetThis action is used to list all tables in a google spreadsheet, call this action to get the list of tables in a spreadsheet.
List task listsFetches the authenticated user's task lists from google tasks; results may be paginated.
List TasksRetrieves tasks from a google tasks list; all date/time strings must be rfc3339 utc, and `showcompleted` must be true if `completedmin` or `completedmax` are specified.
List threadsRetrieves a list of email threads from a gmail account, identified by `user id` (email address or 'me'), supporting filtering and pagination.
Look up spreadsheet rowFinds the first row in a google spreadsheet where a cell's entire content exactly matches the query string, searching within a specified a1 notation range or the first sheet by default.
Embed Google MapTool to generate an embeddable google map url and html iframe code.
Modify thread labelsAdds or removes specified existing label ids from a gmail thread, affecting all its messages; ensure the thread id is valid.
Move FileTool to move a file from one folder to another in google drive.
Move TaskMoves the specified task to another position in the destination task list.
Move to TrashMoves an existing, non-deleted email message to the trash for the specified user.
Nearby searchSearches for places (e.
Patch CalendarPartially updates (patches) an existing google calendar, modifying only the fields provided; `summary` is mandatory and cannot be an empty string, and an empty string for `description` or `location` clears them.
Patch EventUpdates specified fields of an existing event in a google calendar using patch semantics (array fields like `attendees` are fully replaced if provided); ensure the `calendar id` and `event id` are valid and the user has write access to the calendar.
Patch LabelPatches the specified label.
Patch TaskPartially updates an existing task (identified by `task id`) within a specific google task list (identified by `tasklist id`), modifying only the provided attributes from `taskinput` (e.
Patch task listUpdates the title of an existing google tasks task list.
Query Spreadsheet TableThis action is used to query a table in a google spreadsheet, call this action to query a table in a spreadsheet.
Quick Add EventParses natural language text to quickly create a basic google calendar event with its title, date, and time, suitable for simple scheduling; does not support direct attendee addition or recurring events, and `calendar id` must be valid if not 'primary'.
Remove attendee from eventRemoves an attendee from a specified event in a google calendar; the calendar and event must exist.
Remove labelPermanently deletes a specific, existing user-created gmail label by its id for a user; cannot delete system labels.
Replace All Text in DocumentTool to replace all occurrences of a specified text string with another text string throughout a google document.
Replace Image in DocumentTool to replace a specific image in a document with a new image from a uri.
Reply to email threadSends a reply within a specific gmail thread using the original thread's subject, requiring a valid `thread id` and correctly formatted email addresses.
Search Developer MetadataTool to search for developer metadata in a spreadsheet.
Search DocumentsSearch for google documents using various filters including name, content, date ranges, and more.
Search Media ItemsSearches for media items in a user's google photos library.
Search PeopleSearches contacts by matching the query against names, nicknames, emails, phone numbers, and organizations, optionally including 'other contacts'.
Search SpreadsheetsSearch for google spreadsheets using various filters including name, content, date ranges, and more.
Send DraftSends the specified, existing draft to the recipients in the to, cc, and bcc headers.
Send EmailSends an email via gmail api using the authenticated user's google profile display name, requiring `is html=true` if the body contains html and valid `s3key`, `mimetype`, `name` for any attachment.
Set Basic FilterTool to set a basic filter on a sheet in a google spreadsheet.
List SettingsReturns all user settings for the authenticated user.
Watch SettingsWatch for changes to settings resources.
Create sheet from JSONCreates a new google spreadsheet and populates its first worksheet from `sheet json`, which must be non-empty as its first item's keys establish the headers.
Copy Sheet to Another SpreadsheetTool to copy a single sheet from a spreadsheet to another spreadsheet.
Append Values to SpreadsheetTool to append values to a spreadsheet.
Batch Clear Spreadsheet ValuesTool to clear one or more ranges of values from a spreadsheet.
Batch Clear Values By Data FilterClears one or more ranges of values from a spreadsheet using data filters.
Batch Get Spreadsheet Values by Data FilterTool to return one or more ranges of values from a spreadsheet that match the specified data filters.
Stop Watch ChannelTool to stop watching resources through a specified channel.
Sync EventsSynchronizes google calendar events, performing a full sync if no `sync token` is provided or if a 410 gone error (due to an expired token) necessitates it, otherwise performs an incremental sync for events changed since the `sync token` was issued.
Text SearchSearches for places on google maps using a textual query (e.
Unhide Shared DriveTool to unhide a shared drive.
Unmerge Table CellsTool to unmerge previously merged cells in a table.
Untrash FileTool to restore a file from the trash.
Update ACL RuleUpdates an access control rule for the specified calendar.
Update AlbumUpdates an album's title or cover photo in google photos.
Update CommentTool to update an existing comment on a google drive file.
Update Document MarkdownReplaces the entire content of an existing google docs document with new markdown text; requires edit permissions for the document.
Update Document StyleTool to update the overall document style, such as page size, margins, and default text direction.
Update Shared DriveTool to update the metadata for a shared drive.
Update Google eventUpdates an existing event by `event id` in a google calendar; this is a full put replacement, so provide all desired fields as unspecified ones may be cleared or reset.
Update existing documentApplies programmatic edits, such as text insertion, deletion, or formatting, to a specified google doc using the `batchupdate` api method.
Update File (Metadata)Updates file metadata.
Update File Revision MetadataUpdates metadata of a file revision (e.
Update Media ItemUpdates a media item's description in google photos.
Update PermissionTool to update a permission with patch semantics.
Update ReplyTool to update a reply to a comment on a google drive file.
Update Sheet PropertiesTool to update properties of a sheet (worksheet) within a google spreadsheet, such as its title, index, visibility, tab color, or grid properties.
Update Google Meet SpaceUpdates a meeting space.
Update Spreadsheet PropertiesTool to update properties of a spreadsheet, such as its title, locale, or auto-recalculation settings.
Update Table Row StyleTool to update the style of a table row in a google document.
Update TaskUpdates the specified task.
Update Task ListUpdates the authenticated user's specified task list.
Upload FileUploads a file (max 5mb) to google drive, moving it to a specified folder if a valid folder id is provided, otherwise uploads to root.
Upload MediaUpload a media file to google photos.
Watch Drive ChangesTool to subscribe to changes for a user or shared drive in google drive.

What is the Composio tool router, and how does it fit here?

What is Tool Router?

Composio's Tool Router helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Tool Router

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Tool Router works

The Tool Router follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

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 Google Super account and project
  • Basic familiarity with async Python/Typescript

Getting API Keys for OpenAI, Composio, and Google Super

OpenAI API key (OPENAI_API_KEY)
  • Go to the OpenAI dashboard
  • Create an API key if you don't have one
  • Assign it to OPENAI_API_KEY in .env
Composio API key and user ID
  • Log into the Composio dashboard
  • Copy your API key from Settings
    • Use this as COMPOSIO_API_KEY
  • Pick a stable user identifier (email or ID)
    • Use this as COMPOSIO_USER_ID

Installing dependencies

pip install composio-llamaindex llama-index llama-index-llms-openai llama-index-tools-mcp python-dotenv

Create a new Python project and install the necessary dependencies:

  • composio-llamaindex: Composio's LlamaIndex integration
  • llama-index: Core LlamaIndex framework
  • llama-index-llms-openai: OpenAI LLM integration
  • llama-index-tools-mcp: MCP client for LlamaIndex
  • python-dotenv: Environment variable management

Set environment variables

bash
OPENAI_API_KEY=your-openai-api-key
COMPOSIO_API_KEY=your-composio-api-key
COMPOSIO_USER_ID=your-user-id

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 Google Super access

Import modules

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()

Create a new file called google super_llamaindex_agent.py and import the required modules:

Key imports:

  • asyncio: For async/await support
  • Composio: Main client for Composio services
  • LlamaIndexProvider: Adapts Composio tools for LlamaIndex
  • ReActAgent: LlamaIndex's reasoning and action agent
  • BasicMCPClient: Connects to MCP endpoints
  • McpToolSpec: Converts MCP tools to LlamaIndex format

Load environment variables and initialize Composio

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")

What's happening:

This ensures missing credentials cause early, clear errors before the agent attempts to initialise.

Create a Tool Router session and build the agent function

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

    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 Google Super actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Google Super actions.
    """
    return ReActAgent(tools=tools, llm=llm, description=description, system_prompt=system_prompt, verbose=True)

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, google super)
  • 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 Google Super tools.
  • The MCP tools are mapped to LlamaIndex-compatible tools and plug them into the Agent.

Create an interactive chat loop

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}")

What's happening here:

  • We're creating a direct terminal interface to chat with your Google Super database
  • The LLM's responses are streamed to the CLI for faster interaction.
  • The agent uses context to maintain conversation history
  • You can type 'quit' or 'exit' to stop the chat loop gracefully
  • Agent responses and any errors are displayed in a clear, readable format

Define the main entry point

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!")

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 Google Super

Run the agent

npx ts-node llamaindex-agent.ts

When prompted, authenticate and authorise your agent with Google Super, then start asking questions.

Complete Code

Here's the complete code to get you started with Google Super and LlamaIndex:

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

    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 Google Super actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Google Super 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!")

Conclusion

You've successfully connected Google Super to LlamaIndex through Composio's Tool Router MCP layer. Key takeaways:
  • Tool Router dynamically exposes Google Super 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 Google Super MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Google Super MCP?

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

Can I manage the permissions and scopes for Google Super while using Tool Router?

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

Used by agents from

Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
ASU
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.