How to integrate Agencyzoom MCP with LangChain

Framework Integration Gradient
Agencyzoom Logo
LangChain Logo
divider

Introduction

This guide walks you through connecting Agencyzoom to LangChain using the Composio tool router. By the end, you'll have a working Agencyzoom agent that can add a note to a specific customer profile, batch create five new insurance leads, change the status of a lead to won, mark today's follow-up tasks as completed through natural language commands.

This guide will help you understand how to give your LangChain agent real control over a Agencyzoom account through Composio's Agencyzoom 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:
  • Get and set up your OpenAI and Composio API keys
  • Connect your Agencyzoom project to Composio
  • Create a Tool Router MCP session for Agencyzoom
  • Initialize an MCP client and retrieve Agencyzoom tools
  • Build a LangChain agent that can interact with Agencyzoom
  • Set up an interactive chat interface for testing

What is LangChain?

LangChain is a framework for developing applications powered by language models. It provides tools and abstractions for building agents that can reason, use tools, and maintain conversation context.

Key features include:

  • Agent Framework: Build agents that can use tools and make decisions
  • MCP Integration: Connect to external services through Model Context Protocol adapters
  • Memory Management: Maintain conversation history across interactions
  • Multi-Provider Support: Works with OpenAI, Anthropic, and other LLM providers

What is the Agencyzoom MCP server, and what's possible with it?

The Agencyzoom MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Agencyzoom account. It provides structured and secure access to your agency's sales and client management data, so your agent can create leads, manage tasks, update opportunities, take notes, and analyze performance automatically on your behalf.

  • Batch contact and lead creation: Quickly add multiple new contacts or leads to your Agencyzoom CRM in a single step to keep your pipeline growing efficiently.
  • Automated task management: Let your agent mark tasks as completed or delete batches of tasks, helping your team stay organized and focused on priorities.
  • Lead status and opportunity updates: Easily update a lead's lifecycle status or add new sales opportunities, enabling your sales process to move forward without manual intervention.
  • Intelligent note-taking: Add detailed notes to customer profiles or leads automatically, ensuring important context is always captured and accessible.
  • Opportunity driver management: Create and associate driver records with opportunities to maintain complete and compliant records for insurance sales workflows.

Supported Tools & Triggers

Tools
Authenticate for JWT via V4 SSOAuthenticates a user via v4 single sign-on (sso) using the provided callback `code` (typically required for success) to retrieve a jwt and initial user session information.
Batch create contactsCreates 1 to 5 new contacts in agencyzoom in a single batch api call.
Batch create leadsCreates up to 5 new leads in agencyzoom; all referenced entity ids (e.
Batch delete tasksDeletes multiple agencyzoom tasks in a batch; task deletion is permanent and the response indicates overall batch success, not individual task status.
Change lead statusUpdates a lead's lifecycle status (e.
Mark task as completedMarks an existing and accessible task in agencyzoom as 'completed'; this action does not return the full updated task object.
Create a customer noteAdds a new note to an existing customer's profile using their id; cannot be used to edit or retrieve existing notes.
Create a driver for an opportunityCreates a new driver record associated with an existing agencyzoom opportunity using its id; full driver details are handled by the api endpoint directly, not specified in this action's request.
Create a lead noteAdds a new note to an existing lead in agencyzoom, identified by `leadid`.
Create a lead opportunityAdds a new sales opportunity to an existing lead in agencyzoom, requiring a valid `leadid`, `carrierid`, `productlineid`, and that custom field names match existing definitions in agencyzoom.
Create a lead quoteCreates a new insurance quote for an existing lead in agencyzoom, using valid carrier and product line ids, to track a proposal; this action does not bind policies or process payments.
Create an opportunityCreates a new lead opportunity in agencyzoom; this action cannot update existing opportunities.
Create a vehicle for an opportunityAdds a new vehicle record to a specified opportunity; `opportunityid` must refer to a valid, existing opportunity.
Create business leadCreates or updates a business lead in agencyzoom using detailed personal and company information, for b2b sales and marketing lead management.
Create leadCreates a new lead or updates an existing one in agencyzoom; ensure `pipelineid`, `stageid`, `leadsourceid`, and `assignto` reference valid, existing entities.
Create task post endpointCreates a new task in agencyzoom; ensure `assigneeid`, `customerid`, or `leadid` are valid existing entities if provided, and use `contactemail`, `customerid`, or `leadid` to link the task to a contact.
Delete a customerIrreversibly deletes a customer and all associated data in agencyzoom using their `customerid`; useful for offboarding or data privacy compliance.
Delete customer filePermanently deletes a specific file, identified by `fileid`, associated with a customer, identified by `customerid`.
Delete a customer policyPermanently deletes a specific policy associated with a customer, for instance, if it's cancelled or inactive; this action is irreversible and requires caution.
Delete an opportunity driver by IDPermanently deletes an existing agencyzoom driver (e.
Delete file from leadDeletes a specific file (identified by `fileid`) associated with an existing lead (identified by `leadid`); this operation is irreversible.
Delete a lead opportunityPermanently deletes an existing opportunity (by `opportunityid`) associated with an existing lead (by `leadid`) when it's irrelevant, closed, or erroneous; the lead itself remains.
Delete a lead quoteDeletes a specific quote from a lead, requiring that the lead and quote exist and are associated.
Delete an opportunityPermanently deletes a specific opportunity by its unique id; this action is irreversible and requires a valid, existing `opportunityid`.
Delete a taskPermanently and irreversibly deletes an existing task, identified by its `taskid`.
Delete a vehiclePermanently deletes a vehicle record by its `vehicleid`, which must correspond to an existing vehicle in the agencyzoom system.
Delete thread messageDeletes a specific message from an email thread within agencyzoom, where the message id is implicitly handled (e.
Delete email threadPermanently deletes a specific email thread from the agencyzoom system, identified by its `threadid` (expected by the endpoint), provided the thread exists.
Get a list of assign groupsRetrieves all assign groups configured in agencyzoom, used for categorizing or assigning items to specific teams or units.
Get a list of carriersRetrieves all insurance carriers from agencyzoom, typically used for populating selection lists or synchronizing carrier data; does not return detailed policy or coverage information.
Get a list of CSRsFetches all customer service representatives (csrs), including their id and name, returning an empty list if none are configured.
Get a list of custom fieldsRetrieves metadata for all configured custom field definitions, not the specific values entered for individual records.
Get a list of drivers for an opportunityRetrieves a list of drivers (individuals), including their personal details, licensing information, and relationship status, associated with a specific, existing `opportunityid` in agencyzoom.
Get a list of employeesRetrieves a complete list of all employees for the authenticated agency; returns an empty list if no employees are configured.
Get lead source categoriesRetrieves a comprehensive list of all predefined lead source categories from agencyzoom, used to classify lead origins.
Get lead sourcesFetches a list of all lead sources configured in agencyzoom, including their id, name, sales exclusion status, and category id.
Get a list of life professionalsRetrieves a list of life insurance professionals, including only their contact and status information (excluding sales or customer data), from the agencyzoom platform.
Get a list of locationsRetrieves all agency locations or branches from agencyzoom; filtering options are not available.
Get loss reasonsRetrieves a list of all predefined loss reasons from agencyzoom, used for populating ui elements or analysis, returning all reasons without filtering or statistical data.
Get a list of pipelinesRetrieves all pipelines and their stages from agencyzoom to understand workflow structures; this is a read-only operation and does not return individual items (like leads or tasks) within these pipelines.
Get a list of producersRetrieves a list of all producers from agencyzoom, typically related to text thread functionalities.
Get product lines and policy typesFetches all product lines and policy types from agencyzoom, each detailed with its id, name, and product category id.
Get a list of recycle eventsRetrieves the history of recycling activities (e.
Retrieve vehicles for opportunityRetrieves all vehicles associated with an existing opportunity, using its unique opportunityid.
Get AMS policies for a customerRetrieves a customer's synchronized agency management system (ams) policy data (typically a single policy); requires an active ams integration, may return empty/default values if data is missing.
Get auth URL for V4 SSORetrieves a fresh authentication url for agencyzoom's v4 single sign-on (sso) process; call before each sso attempt as the url may change and should not be cached.
Get departments groupsFetches department and group information for an agency, optionally filtered by a specific `agencynumber`, to analyze its organizational structure.
Get lead filesRetrieves metadata for files linked to leads; sends an empty post request, which typically fetches a default set of files (not full lead details) for existing leads with documents.
Retrieve notes for specific leadFetches the complete history of notes for a specific lead by `leadid` (which must exist), useful for reviewing context for communications or follow-ups; this is a read-only operation.
Get lead quotesRetrieves all insurance quotes (active and inactive) for a specific lead id, useful for reviewing or tracking quote history.
Get lead tasksRetrieves all tasks for a specific lead, identified by its `leadid`, to review its activity history or manage follow-ups.
Get list of end stagesFetches a list of all defined end stages, representing final steps in processes like lead conversion or policy closure.
Get policies for a customerRetrieves from agencyzoom details for an insurance policy of an existing customer (identified by `customerid`), excluding premium payment history or claims information.
Get the customer detailsFetches comprehensive details for a specific customer, including personal information, policies, notes, tasks, files, and custom fields, using their unique customer id.
Get the customer tasksFetches all tasks (read-only task data) for a customer by `customerid` to review their activities, follow-ups, and action items; the `customerid` must be valid.
Get the driver detailsRetrieves detailed information for a specific, existing driver (by `driverid`) associated with an agencyzoom opportunity.
Get the lead detailsRetrieves comprehensive details for a specific lead in agencyzoom by its unique `leadid` (which must correspond to an existing lead), including contact information, status, associated opportunities, quotes/policies, custom fields, and interaction history.
Get the opportunities for a leadRetrieves all sales opportunities and their details for a specified, existing `leadid` in agencyzoom.
Get the opportunity detailsFetches comprehensive details for an existing opportunity using its unique `opportunityid`.
Get the task detailsRetrieves comprehensive details for a specific task using its unique `taskid`, which must correspond to an existing task in agencyzoom.
Get the vehicle detailsRetrieves detailed information for a specific vehicle, often associated with an agencyzoom opportunity, using its unique vehicleid.
Get thread detailsSearches and retrieves detailed information for email threads in agencyzoom; no explicit search criteria are passed in this request.
Link a driver to opportunityAssigns or reassigns an existing driver to an existing opportunity.
Link vehicle to opportunityLinks an existing vehicle to an existing sales opportunity in agencyzoom using their respective ids, typically for managing auto insurance policies or related services.
List Product CategoriesRetrieves a complete, unfiltered list of all product categories (id and name) from agencyzoom, useful for understanding product organization or populating ui elements.
Log the user inAuthenticates an existing agencyzoom user using their email (as username) and password to obtain a jwt for api access; this action does not support new user creation.
Log the user outUse this action to log the current user out of agencyzoom by invalidating their active session token.
Mark thread as unreadMarks a text thread in agencyzoom as read or unread using its `threadid`; this action does not modify message content and the specified `threadid` must refer to an existing thread.
Move lead to soldMarks an existing lead as sold by its `leadid` and records product details; `productlineid`, `premium`, `effectivedate`, and `solddate` are operationally required for each sold product, despite schema flexibility.
Remove text threadCall this action to permanently delete a text thread in agencyzoom; the target thread is identified by the api via implicit context as this action accepts no parameters.
Reopen a taskReopens an existing agencyzoom task that is currently 'completed' or 'closed', allowing it to be reactivated with optional comments.
Search business classificationsRetrieves a comprehensive list of all available business classifications from agencyzoom, each including an id, code, and description.
Search customersSearches for customers in agencyzoom using criteria like contact information, policy details, or custom fields, with options for filtering, sorting, and pagination.
Search email threadsRetrieves a list of email thread metadata from agencyzoom, suitable for an overview when no specific filtering, sorting, or pagination is needed, as results are subject to default server-side limits and ordering.
Search leadsRetrieves agencyzoom leads, using filters, pagination, and sorting options sent in the post body, as the request schema itself is empty.
Search leads countRetrieves a summary of lead counts categorized by workflow stage from agencyzoom; this action does not support filtering and returns aggregate counts rather than individual lead details.
Search life and health leadsSearches for life and health insurance leads by providing filter criteria (matching alrlead fields) in the request body; an empty request may retrieve all leads or a default set.
Search SMS threadsSearches and retrieves sms threads from agencyzoom, with search parameters, filters, sorting, and pagination typically provided in the request body of this post operation.
Search and list tasksSearches and lists tasks, supporting pagination and accepting filter criteria in the post request body despite an empty request schema.
List service ticketsRetrieves a list of service tickets from agencyzoom, optionally filtered by criteria such as status, priority, or date ranges.
Get text thread detailsRetrieves detailed messages for an implicitly specified text thread.
Unlink driver from opportunityUnlinks a currently associated driver from an agencyzoom opportunity, used when the driver is no longer relevant, for policy or data updates, potentially impacting the opportunity's status or associated policy details.
Unlink vehicle from opportunityUnlinks a specific, existing vehicle from a specific, existing opportunity using their respective ids, removing only the association and not the records themselves.
Unread email threadUpdates the read or unread status of a specific email thread within agencyzoom.
Update a driver's detailsUpdates an existing driver's details in agencyzoom, requiring `driverid` in the path and `firstname` and `lastname` in the request.
Rename lead fileUpdates a lead's file name to `newfilename`; requires `fileid` of the target file, which must be associated with both the `leadid` (path parameter) and the provided `customerreferralid`.
Update a lead opportunityUpdates an existing opportunity's details (carrier, product line, premium, items, custom fields) for a specific lead; `leadid`, opportunity `id`, `carrierid`, and `productlineid` must refer to existing entities.
Update lead quote dataUpdates an existing quote for a specified lead in agencyzoom when its details require revision, ensuring the provided `leadid` (path parameter), quote `id` (body parameter), `carrierid`, and `productlineid` are valid and correspond to existing entities.
Update an opportunityUpdates an existing opportunity with the provided details; ensure any custom field names are predefined in agencyzoom configuration.
Update policy by idUpdates an existing insurance policy for the given `policyid`; monetary values must be in cents and dates in yyyy-mm-dd format.
Update a vehicle's detailsUpdates details for an existing vehicle within an opportunity; this action cannot be used to create new vehicle records.
Update business leadUpdates an existing business lead, identified by `leadid` (which must be valid and existing), using data provided in the request body not defined in this schema.
Update customer info using idUpdates an existing customer's information in agencyzoom using their unique customerid.
Update leadUpdates an existing lead's information in agencyzoom using the `leadid`; ensure the `leadid` corresponds to an existing lead in agencyzoom.
Update lead status by idUpdates a lead's status (0=active, 2=won, 3=lost, 5=xdated) by `leadid`, optionally setting workflow, stage, date, loss reason, x-date type, source, recycle stage/pipeline, or tags; requires `date` and `xdatetype` for status 5 (xdated), and `lossreasonid` for status 3 (lost).
Update my profileUpdates the profile information (first name, last name, email, and optional phone) for the currently authenticated user in agencyzoom; the provided email address must be unique within the system.
Add tags to a policyAdds new comma-separated `tagnames` to a policy, requiring `tagnames` and identification by either `policyid` or `amspolicyid`; if `amspolicyid` is provided, `policyid` is ignored, and existing tags are not affected.
Update taskModifies an existing agencyzoom task (which must be valid and identified by `taskid` in the path) with new attributes from the request body, which must also contain `taskid`.
Log user in via SSOLogs a user into the agencyzoom platform via single sign-on (sso).

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 starting this tutorial, make sure you have:
  • Python 3.10 or higher installed on your system
  • A Composio account with an API key
  • An OpenAI API key
  • Basic familiarity with Python and async programming

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.

Install dependencies

pip install composio-langchain langchain-mcp-adapters langchain python-dotenv

Install the required packages for LangChain with MCP support.

What's happening:

  • composio-langchain provides Composio integration for LangChain
  • langchain-mcp-adapters enables MCP client connections
  • langchain is the core agent framework
  • python-dotenv loads environment variables

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_composio_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your requests to Composio's API
  • COMPOSIO_USER_ID identifies the user for session management
  • OPENAI_API_KEY enables access to OpenAI's language models

Import dependencies

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

load_dotenv()
What's happening:
  • We're importing LangChain's MCP adapter and Composio SDK
  • The dotenv import loads environment variables from your .env file
  • This setup prepares the foundation for connecting LangChain with Agencyzoom functionality through MCP

Initialize Composio client

async def main():
    composio = Composio(api_key=os.getenv("COMPOSIO_API_KEY"))

    if not os.getenv("COMPOSIO_API_KEY"):
        raise ValueError("COMPOSIO_API_KEY is not set")
    if not os.getenv("COMPOSIO_USER_ID"):
        raise ValueError("COMPOSIO_USER_ID is not set")
What's happening:
  • We're loading the COMPOSIO_API_KEY from environment variables and validating it exists
  • Creating a Composio instance that will manage our connection to Agencyzoom tools
  • Validating that COMPOSIO_USER_ID is also set before proceeding

Create a Tool Router session

# Create Tool Router session for Agencyzoom
session = composio.create(
    user_id=os.getenv("COMPOSIO_USER_ID"),
    toolkits=['agencyzoom']
)

url = session.mcp.url
What's happening:
  • We're creating a Tool Router session that gives your agent access to Agencyzoom tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use
  • This approach allows the agent to dynamically load and use Agencyzoom tools as needed

Configure the agent with the MCP URL

client = MultiServerMCPClient({
    "agencyzoom-agent": {
        "transport": "streamable_http",
        "url": session.mcp.url,
        "headers": {
            "x-api-key": os.getenv("COMPOSIO_API_KEY")
        }
    }
})

tools = await client.get_tools()

agent = create_agent("gpt-5", tools)
What's happening:
  • We're creating a MultiServerMCPClient that connects to our Agencyzoom MCP server via HTTP
  • The client is configured with a name and the URL from our Tool Router session
  • get_tools() retrieves all available Agencyzoom tools that the agent can use
  • We're creating a LangChain agent using the GPT-5 model

Set up interactive chat interface

conversation_history = []

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

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

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

    if not user_input:
        continue

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

    response = await agent.ainvoke({"messages": conversation_history})
    conversation_history = response['messages']
    final_response = response['messages'][-1].content
    print(f"Agent: {final_response}\n")
What's happening:
  • We initialize an empty conversation_history list to maintain context across interactions
  • A while loop continuously accepts user input from the command line
  • When a user types a message, it's added to the conversation history and sent to the agent
  • The agent processes the request using the ainvoke() method with the full conversation history
  • Users can type 'exit', 'quit', or 'bye' to end the chat session gracefully

Run the application

if __name__ == "__main__":
    asyncio.run(main())
What's happening:
  • We call the main() function using asyncio.run() to start the application

Complete Code

Here's the complete code to get you started with Agencyzoom and LangChain:

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

load_dotenv()

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

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

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

Conclusion

You've successfully built a LangChain agent that can interact with Agencyzoom through Composio's Tool Router.

Key features of this implementation:

  • Dynamic tool loading through Composio's Tool Router
  • Conversation history maintenance for context-aware responses
  • Async Python provides clean, efficient execution of agent workflows
You can extend this further by adding error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

How to build Agencyzoom MCP Agent with another framework

FAQ

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

With a standalone Agencyzoom MCP server, the agents and LLMs can only access a fixed set of Agencyzoom tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Agencyzoom and many other apps based on the task at hand, all through a single MCP endpoint.

Can I use Tool Router MCP with LangChain?

Yes, you can. LangChain fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Agencyzoom tools.

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

Yes, absolutely. You can configure which Agencyzoom 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 Agencyzoom 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.