# How to integrate Synthflow ai MCP with LlamaIndex

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

## Introduction

This guide walks you through connecting Synthflow ai to LlamaIndex using the Composio tool router. By the end, you'll have a working Synthflow ai agent that can create a new ai assistant for customer support, list all current voice assistants in your account, fetch details for team 'sales outreach' through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Synthflow ai account through Composio's Synthflow ai MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Synthflow ai with

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

## TL;DR

Here's what you'll learn:
- Set your OpenAI and Composio API keys
- Install LlamaIndex and Composio packages
- Create a Composio Tool Router session for Synthflow ai
- Connect LlamaIndex to the Synthflow ai MCP server
- Build a Synthflow ai-powered agent using LlamaIndex
- Interact with Synthflow ai 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 Synthflow ai MCP server, and what's possible with it?

The Synthflow ai MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Synthflow ai account. It provides structured and secure access to your voice automation tools, so your agent can perform actions like managing voice assistants, handling teams, retrieving phone numbers, and automating call center operations on your behalf.
- AI assistant management: Create, list, update, or delete AI-powered voice assistants to tailor customer interactions and automate call flows as needed.
- Team creation and configuration: Set up new teams, modify existing ones, or remove teams to optimize your call center's routing and operational structure.
- Knowledge base integration: Retrieve and manage knowledge base details to ensure your assistants have accurate, up-to-date information for conversations.
- Phone number administration: Fetch and organize phone numbers linked to your workspace, making it easy to assign or reassign numbers for inbound and outbound campaigns.
- Comprehensive assistant and team insights: Access detailed metadata and configuration for both assistants and teams, streamlining oversight and decision-making for your AI-powered operations.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `SYNTHFLOW_AI_ADD_KB_SOURCE_DOCUMENT` | Add document to knowledge base source | Tool to add a document to a knowledge base source. Use when you need to attach PDF files, web pages, or text content to an existing knowledge base. |
| `SYNTHFLOW_AI_ATTACH_ACTIONS_TO_AGENT` | Attach Actions to Agent | Tool to attach one or more actions to an agent. Use when you need to configure an agent with specific actions by providing the agent's model_id and an array of action IDs. |
| `SYNTHFLOW_AI_ATTACH_CONTACT_TO_MEMORY_STORE` | Attach contact to memory store | Tool to attach a contact to a memory store. Use when you need to associate a specific contact with a memory store for persistent data storage. |
| `SYNTHFLOW_AI_ATTACH_KNOWLEDGE_BASE_TO_AGENT` | Attach knowledge base to agent | Tool to attach a knowledge base to an agent. Use when you need to connect a knowledge base to a specific AI assistant by providing both IDs. |
| `SYNTHFLOW_AI_ATTACH_MEMORY_STORE_TO_AGENT` | Attach memory store to agent | Tool to attach a memory store to an agent. Use when you need to connect a memory store resource to a specific assistant for knowledge retrieval. |
| `SYNTHFLOW_AI_CREATE_ACTION` | Create Action | Tool to create a new action in Synthflow AI. Use when you need to configure an action such as real-time booking, information extraction, live transfer, SMS sending, custom HTTP calls, or custom evaluations. Exactly one action type must be specified in the request. |
| `SYNTHFLOW_AI_CREATE_ASSISTANT` | Create Assistant | Tool to create a new assistant. Use when you need to initialize a Synthflow AI assistant by specifying its name, type, and agent configuration. |
| `SYNTHFLOW_AI_CREATE_CONTACT` | Create a contact | Tool to create a new contact in Synthflow AI. Use when you need to add a contact with name and phone number. |
| `SYNTHFLOW_AI_CREATE_KNOWLEDGE_BASE` | Create knowledge base | Tool to create a new knowledge base and return its ID. Use when you need to set up a knowledge repository for retrieval-augmented generation (RAG) in assistants. |
| `SYNTHFLOW_AI_CREATE_MEMORY_STORE` | Create memory store | Tool to create a new memory store. Use when you need to initialize a knowledge repository for storing conversation history, customer data, or other contextual information. |
| `SYNTHFLOW_AI_CREATE_PHONE_BOOK` | Create Phone Book | Tool to create a new phone book. Use when you need to create a contact list for organizing phone numbers in Synthflow AI. |
| `SYNTHFLOW_AI_CREATE_PHONE_BOOK_ENTRY` | Create phone book entry | Tool to create a phone book entry. Use when you need to add a new phone number with a transfer condition to an existing phone book. |
| `SYNTHFLOW_AI_CREATE_SIMULATION_CASE` | Create Simulation Case | Tool to create a new simulation case. Use when you need to set up test scenarios for evaluating assistant behavior against defined success criteria. |
| `SYNTHFLOW_AI_CREATE_SIMULATION_SCENARIO` | Create a simulation scenario | Tool to create a new simulation scenario. Use when you need to define a template for generating test cases to ensure coverage of specific situations. |
| `SYNTHFLOW_AI_CREATE_SIMULATION_SUITE` | Create a new simulation suite | Tool to create a new simulation suite attached to a specific agent. Use when you need to set up test scenarios for an agent. The suite can only execute on the agent specified by model_id. |
| `SYNTHFLOW_AI_CREATE_TEAM` | Create a new team | Tool to create a new team. Use when you need to programmatically set up a Synthflow AI assistant group with routing rules. |
| `SYNTHFLOW_AI_DELETE_ACTION` | Delete an action | Tool to delete an existing action. Use after confirming the action ID to permanently remove it. |
| `SYNTHFLOW_AI_DELETE_ASSISTANT` | Delete an assistant | Tool to delete an existing AI assistant. Use after confirming the assistant ID. Example: Delete assistant with ID 'assistant_123'. |
| `SYNTHFLOW_AI_DELETE_CHAT` | Delete a chat session | Tool to delete a chat session. Use when you need to remove an existing chat by its ID. Confirm the chat ID before calling. |
| `SYNTHFLOW_AI_DELETE_CONTACT` | Delete a contact | Tool to delete an existing contact. Use after confirming the contact ID. |
| `SYNTHFLOW_AI_DELETE_KNOWLEDGE_BASE` | Delete knowledge base | Tool to delete an existing knowledge base. Use after confirming the knowledge base ID to permanently remove it. |
| `SYNTHFLOW_AI_DELETE_KNOWLEDGE_BASE_SOURCE` | Delete a knowledge base source | Tool to delete a source from a knowledge base. Use when you need to remove a specific source from a knowledge base after confirming both IDs. |
| `SYNTHFLOW_AI_DELETE_MEMORY_STORE` | Delete a memory store | Tool to delete a memory store. Use when you need to remove a memory store after confirming its ID. |
| `SYNTHFLOW_AI_DELETE_PHONE_BOOK` | Delete a phone book | Tool to delete an existing phone book. Use when you need to remove a Synthflow AI phone book after it's no longer needed. Confirm the phone book ID before calling. |
| `SYNTHFLOW_AI_DELETE_PHONE_BOOK_ENTRY` | Delete a phone book entry | Tool to delete a phone book entry. Use when you need to remove a specific entry from a phone book. Confirm both phone_book_id and entry_id before calling. |
| `SYNTHFLOW_AI_DELETE_SIMULATION_CASE` | Delete a simulation case | Tool to delete a simulation case by ID. Use after confirming the simulation case ID to remove it permanently. |
| `SYNTHFLOW_AI_DELETE_SIMULATION_SCENARIO` | Delete a simulation scenario | Tool to delete an existing simulation scenario. Use after confirming the scenario ID. Example: Delete simulation scenario with ID '41fc8c4a-b372-4309-813a-545505b2d0e5'. |
| `SYNTHFLOW_AI_DELETE_SIMULATION_SUITE` | Delete a simulation suite | Tool to delete a simulation suite by ID. Use when you need to remove a simulation suite that is no longer needed. Confirm the suite ID before calling. |
| `SYNTHFLOW_AI_DELETE_SUBACCOUNT` | Delete a subaccount | Tool to delete an existing subaccount. Use after confirming the subaccount ID. Example: Delete subaccount with ID 'test_subaccount_id_12345'. |
| `SYNTHFLOW_AI_DELETE_TEAM` | Delete a team | Tool to delete an existing team. Use when you need to remove a Synthflow AI team after it's no longer needed. Confirm the team ID before calling. |
| `SYNTHFLOW_AI_DETACH_ACTION` | Detach actions from assistant | Tool to detach one or more actions from an AI assistant. Use when you need to remove specific actions from an agent's configuration. |
| `SYNTHFLOW_AI_DETACH_KNOWLEDGE_BASE` | Detach knowledge base | Tool to detach a knowledge base from an AI assistant. Use when you need to remove a knowledge base association from an agent. |
| `SYNTHFLOW_AI_DETACH_MEMORY_STORE_CONTACT` | Detach contact from memory store | Tool to detach a contact from a memory store. Use when you need to remove a contact from a specific memory store. |
| `SYNTHFLOW_AI_DETACH_MEMORY_STORE_FROM_AGENT` | Detach memory store from agent | Tool to detach a memory store from an agent. Use when you need to remove a memory store from a specific agent/assistant. |
| `SYNTHFLOW_AI_EXECUTE_SIMULATION_SUITE` | Execute simulation suite | Tool to execute all test cases in a simulation suite. The suite runs on the target agent (must match the suite's model_id). Use when you need to validate an agent's performance against pre-configured test scenarios. |
| `SYNTHFLOW_AI_EXPORT_ANALYTICS` | Export analytics data | Tool to export analytics data for calls within a specified date range. Use when you need to retrieve call analytics, filter by assistant/agent, call type, or time period. Defaults to past 7 days if no dates specified; maximum date range is 120 days. |
| `SYNTHFLOW_AI_GET_ACTION` | Get action metadata | Tool to retrieve metadata about a specific action by its ID. Use when you need to inspect an action's configuration and parameters. |
| `SYNTHFLOW_AI_GET_ASSISTANT` | Get AI assistant details | Tool to retrieve details of a specific AI assistant. Use after confirming the assistant's ID to fetch its configuration and metadata. |
| `SYNTHFLOW_AI_GET_CALL` | Get phone call details | Tool to retrieve the transcript and detailed metadata for a specific phone call. Use when you need to access call recordings, transcripts, duration, or telephony details for a completed call. |
| `SYNTHFLOW_AI_GET_CONTACT` | Get contact details | Tool to retrieve details of a specific contact by its ID. Use when you need to fetch contact information. |
| `SYNTHFLOW_AI_GET_KNOWLEDGE_BASE` | Get knowledge base | Tool to retrieve details of a specific knowledge base by its ID. Use after confirming the knowledge base ID to fetch its metadata. |
| `SYNTHFLOW_AI_GET_MEMORY_STORE` | Get memory store | Tool to retrieve details of a specific memory store by its ID. Use when you need to fetch metadata and configuration of an existing memory store. |
| `SYNTHFLOW_AI_GET_MEMORY_STORE_CONTACT_DATA` | Get memory store contact data | Tool to retrieve memory data for a specific contact in a memory store. Use when you need to fetch stored memory information associated with a particular contact. |
| `SYNTHFLOW_AI_GET_NUMBERS` | Get phone numbers | Tool to retrieve a list of phone numbers associated with a workspace. Use when you need to fetch numbers assigned to your account for a given workspace. |
| `SYNTHFLOW_AI_GET_SIMULATION` | Get simulation details | Tool to retrieve details of a specific simulation by ID. Use to fetch simulation results including timeline, recording, and success criteria evaluation after a simulation has been executed. |
| `SYNTHFLOW_AI_GET_SIMULATION_CASE` | Get Simulation Case | Tool to retrieve a simulation case by ID. Use when you need to fetch details of a specific simulation case including its prompt, success criteria, and metadata. |
| `SYNTHFLOW_AI_GET_SIMULATION_SCENARIO` | Get simulation scenario | Tool to retrieve a simulation scenario by ID. Use when you need to fetch details of a specific simulation scenario template. |
| `SYNTHFLOW_AI_GET_SIMULATION_SUITE` | Get simulation suite by ID | Tool to retrieve a simulation suite by ID. Use when you need to fetch details about a specific simulation suite including its test cases and associated agent information. |
| `SYNTHFLOW_AI_GET_SUBACCOUNT` | Get subaccount details | Tool to retrieve detailed metadata about a specific subaccount by ID. Use when you need to fetch subaccount information including permissions, subscription details, and members. |
| `SYNTHFLOW_AI_GET_TEAM` | Get team details | Tool to retrieve details of a specific team by its ID. Use after confirming the team exists to inspect its configuration. |
| `SYNTHFLOW_AI_INITIALIZE_ACTION` | Initialize Action | Tool to initialize a custom action with specified variables. Use when you have an action ID and need to initialize it with configuration variables. |
| `SYNTHFLOW_AI_LIST_ACTIONS` | List actions | Tool to list all actions in the workspace. Use when you need to retrieve a paginated list of available actions and their configurations. |
| `SYNTHFLOW_AI_LIST_ASSISTANTS` | List AI assistants | Tool to list all AI assistants associated with the account. Use when you need to retrieve a paginated list of assistants. |
| `SYNTHFLOW_AI_LIST_CALLS` | List call history | Tool to retrieve call history (call logs) with filtering to check outcomes/statuses after placing calls. Use after making voice calls to list recent calls for a model, filter by phone number/time window, and confirm outcomes like completed/no-answer/busy/failed. |
| `SYNTHFLOW_AI_LIST_CHATS` | List chats | Tool to retrieve a list of chats, optionally filtered by agent ID. Use when you need to view chat history or check recent conversations. |
| `SYNTHFLOW_AI_LIST_CONTACTS` | List contacts | Tool to retrieve a list of contacts with optional search filtering. Use when you need to list all contacts or search for specific contacts by phone number. |
| `SYNTHFLOW_AI_LIST_MEMORY_STORES` | List memory stores | Tool to list memory stores with optional filtering by title. Use when you need to retrieve all memory stores in a workspace, optionally filtered by search term. |
| `SYNTHFLOW_AI_LIST_PHONE_BOOKS` | List Phone Books | Tool to list all phone books in your workspace. Use when you need to retrieve all phone books for organizing contacts in Synthflow AI. |
| `SYNTHFLOW_AI_LIST_SIMULATION_CASES` | List Simulation Cases | Tool to list simulation cases with pagination and optional filtering by name or type. Use when you need to retrieve simulation cases for testing agent behavior. |
| `SYNTHFLOW_AI_LIST_SIMULATION_CASES_BY_AGENT` | List simulation cases by agent | Tool to list all simulation cases created for a specific agent. Use when you need to retrieve test scenarios associated with a particular agent ID. |
| `SYNTHFLOW_AI_LIST_SIMULATIONS` | List simulations | Tool to list simulations with pagination and optional filters. Use when you need to retrieve simulation records, optionally filtered by session ID, status, date range, or target agent. |
| `SYNTHFLOW_AI_LIST_SIMULATION_SCENARIOS` | List simulation scenarios | Tool to list simulation scenarios with pagination and optional filtering. Use when you need to retrieve simulation scenario templates with support for search by name and date range filtering. |
| `SYNTHFLOW_AI_LIST_SIMULATION_SESSIONS` | List simulation sessions | Tool to list simulation sessions with pagination and optional filters. Use when you need to retrieve simulation sessions, optionally filtered by target agent, date range, or paginated results. |
| `SYNTHFLOW_AI_LIST_SIMULATION_SUITES` | List simulation suites | Tool to list simulation suites with pagination and optional filtering. Use when you need to retrieve simulation suites, optionally filtered by model IDs, date range, or search term. |
| `SYNTHFLOW_AI_LIST_SUBACCOUNTS` | List subaccounts | Tool to list all subaccounts associated with the authenticated account. Use when you need to retrieve all subaccounts and their configurations. |
| `SYNTHFLOW_AI_LIST_TEAMS` | List teams | Tool to list assistant teams. Use when you need to retrieve all teams in a workspace. |
| `SYNTHFLOW_AI_LIST_VOICES` | List voices | Tool to list all text-to-speech voices in a workspace. Use when you need to retrieve voices available for TTS in a given workspace. |
| `SYNTHFLOW_AI_LIST_WEBHOOK_LOGS` | List webhook logs | Tool to retrieve paginated webhook logs with filtering and search capability. Use when you need to audit webhook delivery, check webhook statuses, troubleshoot failed webhooks, or search for specific webhook events by date range, status, type, or associated call/assistant. |
| `SYNTHFLOW_AI_MAKE_VOICE_CALL` | Make a voice call | Tool to initiate a real-time voice call via the AI agent. Use when you have the agent ID, customer name, and phone number ready. |
| `SYNTHFLOW_AI_START_SIMULATION` | Start Simulation | Tool to start a new simulation using a simulation case. Use when you need to execute a test scenario against an agent to validate its behavior and performance. |
| `SYNTHFLOW_AI_UPDATE_ACTION` | Update Action | Tool to update an existing action in Synthflow AI. Use when you need to modify an action's configuration such as real-time booking, information extraction, live transfer, SMS sending, custom HTTP calls, or custom evaluations. Exactly one action type must be specified in the request along with the action_id. |
| `SYNTHFLOW_AI_UPDATE_ASSISTANT` | Update Assistant | Tool to update an existing assistant’s settings. Use after confirming the assistant exists. Modify settings like name, phone, recording, webhook, or agent configuration. |
| `SYNTHFLOW_AI_UPDATE_CONTACT` | Update a contact | Tool to update an existing contact in Synthflow AI. Use when you need to modify contact details like name, phone, email, or metadata. |
| `SYNTHFLOW_AI_UPDATE_KNOWLEDGE_BASE` | Update knowledge base | Tool to update an existing knowledge base's name or usage conditions. Use after confirming the knowledge base exists. |
| `SYNTHFLOW_AI_UPDATE_MEMORY_STORE` | Update memory store | Tool to update an existing memory store's title and description. Use when you need to modify metadata of a memory store. |
| `SYNTHFLOW_AI_UPDATE_SIMULATION_CASE` | Update Simulation Case | Tool to update an existing simulation case. Use when you need to modify the name, prompt, success criteria, or evaluation method of a simulation case. |
| `SYNTHFLOW_AI_UPDATE_SIMULATION_SCENARIO` | Update a simulation scenario | Tool to update an existing simulation scenario. Use when you need to modify the name or description of a scenario template. |
| `SYNTHFLOW_AI_UPDATE_SIMULATION_SUITE` | Update an existing simulation suite | Tool to update an existing simulation suite. Use when you need to modify the name or agent model of a simulation suite. At least one of name or model_id must be provided. |
| `SYNTHFLOW_AI_UPDATE_TEAM` | Update an existing team | Tool to update an existing team. Use after confirming the team exists and you have new configuration values. |

## Supported Triggers

None listed.

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

The Synthflow ai MCP server is an implementation of the Model Context Protocol that connects your AI agent to Synthflow ai. It provides structured and secure access so your agent can perform Synthflow ai operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before you begin, make sure you have:
- Python 3.8/Node 16 or higher installed
- A Composio account with the API key
- An OpenAI API key
- A Synthflow ai account and project
- Basic familiarity with async Python/Typescript

### 1. Getting API Keys for OpenAI, Composio, and Synthflow ai

No description provided.

### 2. Installing dependencies

No description provided.
```python
pip install composio-llamaindex llama-index llama-index-llms-openai llama-index-tools-mcp python-dotenv
```

```typescript
npm install @composio/llamaindex @llamaindex/openai @llamaindex/tools @llamaindex/workflow dotenv
```

### 3. Set environment variables

Create a .env file in your project root:
These credentials will be used to:
- Authenticate with OpenAI's GPT-5 model
- Connect to Composio's Tool Router
- Identify your Composio user session for Synthflow ai access
```bash
OPENAI_API_KEY=your-openai-api-key
COMPOSIO_API_KEY=your-composio-api-key
COMPOSIO_USER_ID=your-user-id
```

### 4. Import modules

No description provided.
```python
import asyncio
import os
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();
```

### 5. Load environment variables and initialize Composio

No description provided.
```python
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set in the environment")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set in the environment")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set in the environment")
```

```typescript
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!COMPOSIO_API_KEY) throw new Error("COMPOSIO_API_KEY is not set");
if (!COMPOSIO_USER_ID) throw new Error("COMPOSIO_USER_ID is not set");
```

### 6. Create a Tool Router session and build the agent function

What's happening here:
- We create a Composio client using your API key and configure it with the LlamaIndex provider
- We then create a tool router MCP session for your user, specifying the toolkits we want to use (in this case, synthflow ai)
- 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 Synthflow ai tools.
- The MCP tools are mapped to LlamaIndex-compatible tools and plug them into the Agent.
```python
async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["synthflow_ai"],
    )

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

```typescript
async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["synthflow_ai"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
        description : "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Synthflow ai actions." ,
    llm,
    tools,
  });

  return agent;
}
```

### 7. Create an interactive chat loop

No description provided.
```python
async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")
```

```typescript
async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}
```

### 8. Define the main entry point

What's happening here:
- We're orchestrating the entire application flow
- The agent gets built with proper error handling
- Then we kick off the interactive chat loop so you can start talking to Synthflow ai
```python
async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")
```

```typescript
async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err) {
    console.error("Failed to start agent:", err);
    process.exit(1);
  }
}

main();
```

### 9. Run the agent

When prompted, authenticate and authorise your agent with Synthflow ai, then start asking questions.
```bash
python llamaindex_agent.py
```

```typescript
npx ts-node llamaindex-agent.ts
```

## Complete Code

```python
import asyncio
import os
import signal
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set")

async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["synthflow_ai"],
    )

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

async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")

async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";
import { LlamaindexProvider } from "@composio/llamaindex";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();

const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) {
    throw new Error("OPENAI_API_KEY is not set in the environment");
  }
if (!COMPOSIO_API_KEY) {
    throw new Error("COMPOSIO_API_KEY is not set in the environment");
  }
if (!COMPOSIO_USER_ID) {
    throw new Error("COMPOSIO_USER_ID is not set in the environment");
  }

async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["synthflow_ai"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
    description:
      "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Synthflow ai actions." ,
    llm,
    tools,
  });

  return agent;
}

async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}

async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err: any) {
    console.error("Failed to start agent:", err?.message ?? err);
    process.exit(1);
  }
}

main();
```

## Conclusion

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

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

## Related Toolkits

- [Aeroleads](https://composio.dev/toolkits/aeroleads) - Aeroleads is a B2B lead generation platform for finding business emails and phone numbers. Grow your sales pipeline faster with powerful prospecting tools.
- [Autobound](https://composio.dev/toolkits/autobound) - Autobound is an AI-powered sales engagement platform that crafts hyper-personalized outreach and insights. It helps sales teams boost response rates and close more deals through tailored content and recommendations.
- [Better proposals](https://composio.dev/toolkits/better_proposals) - Better Proposals is a web-based tool for crafting and sending professional proposals. It helps teams impress clients and close deals faster with slick, easy-to-use templates.
- [Bidsketch](https://composio.dev/toolkits/bidsketch) - Bidsketch is a proposal software that helps businesses create professional proposals quickly and efficiently. It streamlines the proposal process, saving time while boosting client win rates.
- [Bolna](https://composio.dev/toolkits/bolna) - Bolna is an AI platform for building conversational voice agents. It helps businesses automate support and streamline interactions through natural, voice-powered conversations.
- [Botsonic](https://composio.dev/toolkits/botsonic) - Botsonic is a no-code AI chatbot builder for easily creating and deploying chatbots to your website. It empowers businesses to offer conversational experiences without writing code.
- [Botstar](https://composio.dev/toolkits/botstar) - BotStar is a comprehensive chatbot platform for designing, developing, and training chatbots visually on Messenger and websites. It helps businesses automate conversations and customer interactions without coding.
- [Callerapi](https://composio.dev/toolkits/callerapi) - CallerAPI is a white-label caller identification platform for branded caller ID and fraud prevention. It helps businesses boost customer trust while stopping spam, fraud, and robocalls.
- [Callingly](https://composio.dev/toolkits/callingly) - Callingly is a lead response management platform that automates immediate call and text follow-ups with new leads. It helps sales teams boost response speed and close more deals by connecting seamlessly with CRMs and lead sources.
- [Callpage](https://composio.dev/toolkits/callpage) - Callpage is a lead capture platform that lets businesses instantly connect with website visitors via callback. It boosts lead generation and increases your sales conversion rates.
- [Clearout](https://composio.dev/toolkits/clearout) - Clearout is an AI-powered service for verifying, finding, and enriching email addresses. It boosts deliverability and helps you discover high-quality leads effortlessly.
- [Clientary](https://composio.dev/toolkits/clientary) - Clientary is a platform for managing clients, invoices, projects, proposals, and more. It streamlines client work and saves you serious admin time.
- [Convolo ai](https://composio.dev/toolkits/convolo_ai) - Convolo ai is an AI-powered communications platform for sales teams. It accelerates lead response and improves conversion rates by automating calls and integrating workflows.
- [Delighted](https://composio.dev/toolkits/delighted) - Delighted is a customer feedback platform based on the Net Promoter System®. It helps you quickly gather, track, and act on customer sentiment.
- [Emelia](https://composio.dev/toolkits/emelia) - Emelia is an all-in-one B2B prospecting platform for cold-email, LinkedIn outreach, and prospect research. It streamlines outbound campaigns so you can find, engage, and warm up leads faster.
- [Findymail](https://composio.dev/toolkits/findymail) - Findymail is a B2B data provider offering verified email and phone contacts for sales prospecting. Enhance outreach with automated exports, email verification, and CRM enrichment.
- [Freshdesk](https://composio.dev/toolkits/freshdesk) - Freshdesk is customer support software with ticketing and automation tools. It helps teams streamline helpdesk operations for faster, better customer support.
- [Fullenrich](https://composio.dev/toolkits/fullenrich) - FullEnrich is a B2B contact enrichment platform that aggregates emails and phone numbers from 15+ data vendors. Instantly find and verify lead contact data to boost your outreach.
- [Gatherup](https://composio.dev/toolkits/gatherup) - GatherUp is a customer feedback and online review management platform. It helps businesses boost their reputation by streamlining how they collect and manage customer feedback.
- [Getprospect](https://composio.dev/toolkits/getprospect) - Getprospect is a business email discovery tool with LinkedIn integration. Use it to quickly find and verify professional email addresses.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Synthflow ai MCP?

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

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

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

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