How to integrate Safetyculture MCP with LlamaIndex

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Safetyculture logo
LlamaIndex logo
divider

Introduction

This guide walks you through connecting Safetyculture to LlamaIndex using the Composio tool router. By the end, you'll have a working Safetyculture agent that can show inspections updated in the last week, list all available audit templates now, create a new group for safety managers through natural language commands.

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

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

Also integrate Safetyculture with

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

The Safetyculture MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your SafetyCulture account. It provides structured and secure access to your organization's safety, inspection, and audit data, so your agent can perform actions like managing user groups, listing audit templates, retrieving inspection updates, and handling webhook secrets on your behalf.

  • Automated group management: Easily create new groups or list all existing groups to organize users by roles, teams, or functions within your organization.
  • Template discovery for audits: Quickly list available templates so your agent can recommend or select the right audit or inspection forms for your team’s needs.
  • Inspection update retrieval: Seamlessly search for inspections that have been modified since your last sync, making it simple to track recent activity or follow up on specific audits.
  • Webhook security management: Retrieve or regenerate webhook signature secrets, ensuring secure and reliable integration with external systems or automation workflows.

Supported Tools & Triggers

Tools
Bulk Add File OwnersTool to bulk add file owners to multiple files in Documents.
Add Incident CollaboratorsTool to add collaborators (assignees) to an incident in SafetyCulture.
Archive AssetArchives an asset in your SafetyCulture organization.
Archive Document ItemTool to archive a document item (file or folder) in SafetyCulture.
Assign Permission SetTool to assign users to a permission set.
Cancel Create or Update Users JobTool to cancel a create-or-update users job.
Clone Incidents CategoryTool to clone an existing incident category in SafetyCulture.
Create ActionTool to create a new action in SafetyCulture.
Create Action ScheduleTool to create a recurring action schedule in SafetyCulture.
Create AssetCreates a new asset in your SafetyCulture organization with the specified asset type, field values, and optional site assignment.
Create Asset FieldCreates a custom field for assets in your SafetyCulture organization.
Bulk Create AssetsCreates multiple assets in a single request.
Create Asset TypeCreates a new asset type for your SafetyCulture organization.
Create Credential TypeCreates a new credential type in SafetyCulture.
Create Directory FolderCreates a new folder in the SafetyCulture directory hierarchy.
Create Directory Users Folders MembershipTool to associate users to folders in the SafetyCulture directory.
Create DocumentsTool to create a new file in SafetyCulture Documents and get an upload URL.
Create GroupCreates a new group in the SafetyCulture organization.
Create Heads Up AnnouncementCreates a new Heads Up announcement in SafetyCulture.
Create Incidents CategoryTool to create a new incident category in SafetyCulture.
Create Incidents Detail FieldTool to create a new incident detail field in SafetyCulture.
Create Incidents InvestigationTool to create a new investigation in SafetyCulture.
Create OSHA CaseTool to create an OSHA case record in SafetyCulture.
Create OSHA EstablishmentTool to create a new OSHA establishment record in SafetyCulture.
Create Integration ConfigurationCreates a configuration for an existing application installation in your organization.
Create Integration App InstallationCreates an installation of an existing application in your organization.
Create Schedule ItemTool to create a schedule item in SafetyCulture.
Create Action Shared LinkTool to create a shared link for an action in SafetyCulture.
Create Tasks Custom FieldTool to create a custom field and map it to a specific action type in SafetyCulture.
Create Incident (Legacy)Tool to create an incident (legacy issue) in SafetyCulture.
Create Issue Web Report LinkTool to create a shared link for an issue's web report in SafetyCulture.
Create Tasks Task TypeTool to create a new task type in SafetyCulture.
Create Task Timeline CommentTool to add a comment to a task timeline in SafetyCulture.
Create User FieldTool to create a custom user field in SafetyCulture.
Create WebhookTool to create a webhook in SafetyCulture.
Delete ActionsTool to bulk delete multiple actions from SafetyCulture.
Delete AssetPermanently deletes an asset from your SafetyCulture organization.
Delete Asset FieldPermanently deletes a custom asset field from your SafetyCulture organization.
Delete Asset TypePermanently deletes a custom asset type from your SafetyCulture organization.
Delete Credential TypePermanently deletes a credential type from your SafetyCulture organization.
Delete Action LabelsTool to delete action labels from your SafetyCulture organization.
Delete Directory FoldersTool to bulk delete directory folders.
Delete Directory Folder UsersRemove association for multiple users from a specific folder.
Delete Directory User FoldersRemove association for a specific user to multiple folders.
Bulk Delete GroupsTool to bulk delete multiple groups from the SafetyCulture organization.
Delete IncidentsTool to bulk delete multiple incidents (issues) from your SafetyCulture organization.
Delete Incident CategoryPermanently deletes an incident category from your SafetyCulture organization.
Delete Incident Detail FieldPermanently deletes an incident detail field from your SafetyCulture organization.
Delete InvestigationPermanently deletes an investigation from your SafetyCulture organization.
Delete Incidents OSHA CaseTool to permanently delete an OSHA case from SafetyCulture.
Delete OSHA EstablishmentPermanently deletes an OSHA establishment from your SafetyCulture organization.
Delete Integration ConfigurationDeletes a configuration for an existing application installation in SafetyCulture.
Delete Integration App InstallationDeletes an existing application installation from SafetyCulture.
Delete Action Shared LinkTool to delete (revoke) an action shared link in SafetyCulture.
Delete Tasks Custom FieldPermanently deletes a custom field from your SafetyCulture tasks configuration.
Delete Action TypeTool to delete an action type in SafetyCulture.
Delete User FieldTool to permanently delete a user field from your SafetyCulture organization.
Delete WebhookPermanently deletes a webhook from your SafetyCulture organization.
Deprovision SensorDe-provisions a sensor from SafetyCulture.
Disable User FieldTool to archive a user field in SafetyCulture.
Get Action Assignees FeedTool to retrieve the data feed for action assignees.
Get ActionsTool to list actions from SafetyCulture tasks API.
Get AssetTool to retrieve full details of an asset from SafetyCulture.
Get Asset By CodeTool to retrieve an asset's full details using its code.
Get Assets FeedTool to retrieve a data feed of all assets in your SafetyCulture organization.
Get Asset TypeRetrieves details of a specific asset type by ID.
Get Credential SettingsTool to retrieve credential settings for your SafetyCulture organization.
Get Credential TypeTool to retrieve details of a specific credential type by ID.
Get Directory FolderRetrieves details of a specific directory folder by ID.
Get Directory Folder UsersRetrieves users associated with a directory folder, including both directly and indirectly (inherited) associated users.
Get Directory Folder Users AssociatedTool to retrieve users directly associated to a folder.
Get Directory Folder Users InheritedRetrieves users indirectly associated (inherited) to a folder.
Get Directory Organization LabelsTool to retrieve custom labels mapping for your SafetyCulture organization.
Get Folders By ParentRetrieves child folders for a specific parent folder by ID.
Get DocumentsTool to retrieve a paginated list of credentials from SafetyCulture.
Get Incident Questions And AnswersTool to retrieve questions and answers for a specific incident (issue) in SafetyCulture.
Get Category Detail FieldsTool to retrieve detail fields for a specific incident category.
Get Incidents CountTool to get the total count of incidents (issues) in SafetyCulture.
Get Incidents InvestigationTool to retrieve a specific investigation from SafetyCulture.
Get Incidents OSHA Establishment EmployeesTool to retrieve establishment employee records from SafetyCulture OSHA.
Get OSHA EstablishmentTool to retrieve an OSHA establishment record from SafetyCulture.
Get Establishment HoursTool to retrieve establishment hours from SafetyCulture OSHA service.
Get Integrations Apps InstallationTool to retrieve details of a specific app installation by its app ID and installation ID.
Get Investigation AccessTool to retrieve access information for a specific investigation.
Get Investigation Actions CountTool to retrieve the count of actions linked to a specific investigation in SafetyCulture.
Get Investigation Inspection CountTool to retrieve the count of inspections linked to a specific investigation.
Get Investigation Issue CountTool to get the count of issues linked to an investigation.
Get Investigation Media CountTool to retrieve the count of media linked to an investigation in SafetyCulture.
Get Investigation PDF ReportTool to retrieve the PDF report for a specific investigation.
Get Lesson AttemptsTool to retrieve all lesson attempts for users in your organization.
Get Lesson Progress EventsTool to retrieve all lesson progress events for users in your organization.
Get Lesson StatisticsTool to retrieve lesson statistics for all lessons in your organization.
Get Loneworker JobsTool to retrieve all loneworker jobs in your organization.
Get Permission SetTool to retrieve a permission set from SafetyCulture.
Get Rapid Refresh AnswersTool to retrieve rapid refresh answers from your organization's training analytics.
Get Sensor IDTool to retrieve a sensor ID from SafetyCulture.
Get Signature SecretRetrieves the current webhook signature secret token from SafetyCulture.
Get Survey AnswersTool to retrieve survey answers from training analytics.
Get Survey Question DefinitionsTool to retrieve survey question definitions from training courses in your organization.
Get Tasks Action LabelsTool to retrieve all action labels configured in your SafetyCulture organization.
Get Tasks ActionsTool to retrieve a specific action from SafetyCulture.
Get Action Shared LinkTool to retrieve an existing action shared link.
Get Tasks Custom Fields UnmappedTool to retrieve custom fields not mapped to a specific action type.
Get Tasks IncidentTool to retrieve a specific incident (issue) from SafetyCulture.
Get Tasks Incidents PDF ReportTool to export an incident (issue) to PDF from SafetyCulture.
Get TimelineTool to retrieve timeline events for a SafetyCulture task.
Get Training CollectionsTool to retrieve all training collections in your organization.
Get Training CoursesTool to retrieve all training courses in your organization.
Get Training Course LessonsTool to retrieve all lessons for a given training course.
Get Training Courses StatisticsTool to retrieve course statistics for all courses in your organization.
Get Training Individual LeaderboardsTool to retrieve all individual leaderboards in your organization.
Get Training PathsTool to retrieve learning paths from your SafetyCulture organization.
Get Training Rapid RefreshTool to retrieve all rapid refreshes in your organization.
Get Training Slides StatisticsTool to retrieve all slide statistics for training slides in your organization.
Get Training User Lesson ProgressTool to retrieve lesson progress for a specific user in SafetyCulture Training.
Get Slide User StatisticsTool to retrieve all slide statistics for a specific user in your organization.
Get User GroupsRetrieves the list of groups that a specific user belongs to.
Get User Lesson Progress EventsTool to retrieve lesson progress events for a specific user.
Get Users Upsert JobTool to retrieve details of a create-or-update users job.
Get User AttributesTool to retrieve user attributes from SafetyCulture.
Get WebhookTool to retrieve details of a specific webhook from SafetyCulture.
Ingest Sensor ReadingsTool to ingest sensor readings into SafetyCulture.
Initialize Create or Update Users JobTool to initialize a create-or-update users job in SafetyCulture.
Link Documents to EntitiesTool to link files/documents to other areas of the SafetyCulture platform such as assets.
List Action FieldsTool to retrieve action fields data feed from SafetyCulture.
List ActionsTool to retrieve actions from the SafetyCulture data feed.
List Activity Log EventsTool to retrieve activity log events from SafetyCulture.
List AssetsTool to retrieve assets from your SafetyCulture organization with optional filtering and sorting.
List Asset Type FieldsRetrieves all fields and their association status for a specific asset type.
List Companies FeedTool to retrieve the data feed for contractor companies.
List Company Documents FeedTool to retrieve the data feed for contractor company documents.
List Company Members FeedTool to retrieve the data feed for contractor company user memberships.
List Company Document TypesTool to retrieve a paginated list of company document types from SafetyCulture.
List Company TypesTool to list company types in your SafetyCulture organization.
List Company Types with MetricsTool to list company types with associated metrics and statistics.
List Contractor CompaniesTool to list contractor companies based on applied filters.
List Create-or-Update Users JobsTool to retrieve a list of create-or-update users jobs.
List Credential VersionsTool to list all versions of a credential document.
List Directory FoldersTool to retrieve all folders from your SafetyCulture organization directory.
List Directory User Folder IDsTool to list folders the requesting user is associated with.
List Credential TypesTool to list credential types (licenses and credentials) in your SafetyCulture organization.
List FieldsTool to retrieve all asset fields in your SafetyCulture organization.
List GroupsRetrieves all groups in the organization.
List Groups (Feed)Tool to retrieve groups via the feed endpoint.
List Group UsersTool to retrieve the data feed for group users.
List Heads Ups (Management)Tool to retrieve a list of heads ups (announcements) in management view.
List Incidents CategoriesTool to retrieve all incident categories from SafetyCulture.
List Incidents Field LibraryTool to retrieve the detail field library from SafetyCulture.
List Incidents FieldsTool to list all fields for a specific incident category in SafetyCulture.
List Incidents Investigation Detail FieldsTool to retrieve investigation detail fields from SafetyCulture incidents data feed.
List Incidents Investigation FieldsTool to retrieve investigation fields from the SafetyCulture data feed.
List Investigation RelationshipsTool to retrieve investigation relationships from the SafetyCulture data feed.
List Incidents InvestigationsTool to retrieve investigations from the SafetyCulture incidents feed.
List Investigations (Advanced)Tool to list investigations from SafetyCulture with advanced filtering and sorting capabilities.
List Incidents Settings LogTool to retrieve settings log events for incidents from SafetyCulture.
List Incidents OSHA CasesTool to retrieve OSHA cases from SafetyCulture.
List OSHA EstablishmentsTool to retrieve OSHA establishments from SafetyCulture.
List Incidents StatusesTool to retrieve all incident statuses from SafetyCulture.
List Integration ApplicationsTool to retrieve all integration applications available for installation in your SafetyCulture organization.
List Integrations Apps InstallationsTool to list all existing app installations in the organization.
List Investigation ActionsTool to list actions linked to a SafetyCulture investigation.
List Investigation InspectionsTool to retrieve inspections linked to a specific investigation.
List Investigation IssuesTool to list issues linked to a SafetyCulture investigation.
List Investigation Activity LogTool to retrieve activity log entries for a specific investigation in SafetyCulture.
List Investigation MediaTool to retrieve media (images and videos) associated with a SafetyCulture investigation.
List Issue AssigneesTool to retrieve issue assignees data feed from SafetyCulture.
List Issue RelationsTool to retrieve a feed of issue relations items.
List IssuesTool to retrieve issues from the SafetyCulture data feed.
List Issue Timeline ItemsTool to retrieve issue timeline items from the SafetyCulture data feed.
List Permission SetsTool to list permission sets in your SafetyCulture organization.
List Schedule AssigneesTool to retrieve schedule assignees data feed (v2).
List Schedule ItemsTool to list schedule items from SafetyCulture.
List Schedule ItemsTool to list schedule items from SafetyCulture.
List Scheduling Schedule OccurrencesTool to retrieve the data feed for schedule occurrences (v2).
List Scheduling SchedulesTool to retrieve the data feed for schedules (v2).
List SensorsTool to retrieve all hardware sensors in your SafetyCulture organization.
List Site MembersTool to retrieve the data feed for site members.
List SitesTool to retrieve sites data feed from your SafetyCulture organization.
List Tasks Action FieldsTool to retrieve tasks action fields data feed from SafetyCulture.
List Tasks CategoriesTool to list task categories in SafetyCulture.
List Tasks IncidentsTool to list issues (incidents) from SafetyCulture.
List Template PermissionsTool to retrieve the data feed for template permissions.
List TemplatesRetrieves all templates (also known as inspection forms or checklists) available in your SafetyCulture organization.
List Training Course ProgressTool to retrieve the data feed for training course progress.
List Asset TypesTool to list asset types in your SafetyCulture organization with pagination and filtering.
List User FieldsTool to retrieve user fields in your SafetyCulture organization.
List UsersTool to retrieve a data feed of all users in your SafetyCulture organization.
List WebhooksTool to retrieve all webhooks configured in your SafetyCulture organization.
Lookup Assets By FieldTool to search for assets by matching a specific field name and value.
Map Field to Task TypeMaps a custom field to a task type in SafetyCulture.
Move Documents ItemTool to move a file or folder to a different location in Documents.
Move FoldersTool to move one or more folders to a new parent folder or to the root level.
Provision SensorTool to provision a new sensor in SafetyCulture.
Regenerate Signature SecretRegenerates the webhook signature secret for your SafetyCulture organization.
Register Integration AppRegisters a new custom application in SafetyCulture for integration purposes.
Bulk Remove File OwnersTool to bulk remove owners (users or groups) from files in SafetyCulture Documents.
Remove Incident CollaboratorsTool to remove collaborators (assignees) from an incident (issue) in SafetyCulture.
Restore Archived AssetRestores an archived asset in your SafetyCulture organization.
Restore FieldTool to restore an archived field in SafetyCulture.
Search Directory FoldersTool to search for folders in the directory hierarchy.
Search Documents ItemsTool to search files and folders in SafetyCulture documents.
Search Modified InspectionsTool to retrieve inspections modified since a given timestamp.
Set Category Detail FieldsTool to set detail fields for an incident category in SafetyCulture.
Set Incidents Detail Field OptionsTool to set the options for a select-type detail field in SafetyCulture incidents.
Set User AttributesTool to set or update user attributes for a specific user in SafetyCulture.
Set User Field SettingsTool to update field settings for a user field in SafetyCulture.
Start Users Upsert JobTool to start an initialized create-or-update users job.
Unmap Field From Task TypeTool to unmap a custom field from a task type in SafetyCulture.
Update Action AssetUpdates the asset associated with an action in SafetyCulture.
Update Action AssigneesUpdates the assignees of an action in SafetyCulture.
Update Action Due DateTool to update the due date of an action in SafetyCulture.
Update Action LabelsTool to update the labels associated with an action in SafetyCulture.
Update Action PriorityTool to update the priority of an action in SafetyCulture.
Update Action StatusTool to update the status of an action in SafetyCulture.
Update AssetUpdates an existing asset in SafetyCulture.
Update Asset LocationTool to update an asset's geographic location in your SafetyCulture organization.
Bulk Update AssetsTool to update multiple assets in a single operation.
Update Asset Type FieldsTool to update asset type field associations.
Update Credential TypeTool to update a credential type in SafetyCulture.
Update Credentials SettingsUpdates the credential settings for your organization.
Update DocumentsTool to update a file in SafetyCulture Documents by modifying its metadata such as name or description.
Update OSHA EstablishmentTool to update an OSHA establishment in SafetyCulture.
Update FieldTool to update an existing asset field in SafetyCulture.
Bulk Update File OwnersTool to bulk replace file owners (users or groups) in SafetyCulture Documents.
Update Folder PropertiesTool to update a folder's properties in SafetyCulture.
Update Incident Due DateTool to update the due date of an incident in SafetyCulture.
Update Incident CategoryUpdates an existing incident category in SafetyCulture.
Rename Incident Detail FieldTool to rename a detail field in SafetyCulture incidents.
Update Incidents FieldsTool to update fields for a specific incident category in SafetyCulture.
Update InvestigationUpdates an investigation in SafetyCulture by performing operations such as changing the title, description, status, or managing related entities.
Update OSHA CaseTool to update an existing OSHA case in SafetyCulture.
Update OSHA Establishment EmployeesTool to update the average employee count for an OSHA establishment.
Update OSHA Establishment HoursTool to update the hours worked for an OSHA establishment.
Update Incident PriorityTool to update the priority of an incident in SafetyCulture.
Update Incident StatusesTool to update the complete set of incident statuses for your SafetyCulture organization.
Update Incident StatusTool to update the status of an incident/issue in SafetyCulture.
Update Integration App Installation ConfigurationTool to update a configuration for an existing application installation in SafetyCulture.
Update Integrations AppsTool to update an existing custom application in SafetyCulture.
Update InvestigationsTool to update investigations in bulk.
Update Permission SetUpdates a custom permission set in SafetyCulture.
Update Task Action DescriptionTool to update the description of a task action in SafetyCulture.
Update Action SiteTool to update the site (folder) of an action in SafetyCulture.
Update Action TitleUpdates the title of an action in SafetyCulture.
Update Tasks Custom FieldTool to rename a custom field in SafetyCulture tasks configuration.
Update Task Incident CategoryTool to update the category of an incident/task in SafetyCulture.
Update Tasks Incidents DescriptionTool to update the description of a task incident in SafetyCulture.
Update Incident Occurred AtTool to update the occurred_at timestamp for an incident (issue) in SafetyCulture.
Update Incident SiteTool to update the site (folder) associated with an incident in SafetyCulture.
Update Incident TitleTool to update the title of an incident (legacy issue) in SafetyCulture.
Update Tasks Task TypeTool to rename a task type (action type) in SafetyCulture.
Update TypeTool to update an asset type in SafetyCulture.
Update User FieldTool to update a user field in SafetyCulture.
Update WebhookTool to update an existing webhook configuration in SafetyCulture.
Upsert Action LabelCreate or update an action label for categorizing actions in your SafetyCulture organization.
Create or Update UsersTool to create or update users synchronously in bulk.

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

What is Composio SDK?

Composio's Composio SDK 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 Composio SDK

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

How the Composio SDK works

The Composio SDK 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 Safetyculture account and project
  • Basic familiarity with async Python/Typescript

Getting API Keys for OpenAI, Composio, and Safetyculture

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 Safetyculture 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 safetyculture_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=["safetyculture"],
    )

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

Run the agent

npx ts-node llamaindex-agent.ts

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

Complete Code

Here's the complete code to get you started with Safetyculture 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=["safetyculture"],
    )

    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 Safetyculture actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Safetyculture 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 Safetyculture to LlamaIndex through Composio's Tool Router MCP layer. Key takeaways:
  • Tool Router dynamically exposes Safetyculture 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 Safetyculture MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Safetyculture MCP?

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

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

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

Used by agents from

Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
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.