How to integrate Alchemy MCP with LangChain

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Alchemy logo
LangChain logo
divider

Introduction

This guide walks you through connecting Alchemy to LangChain using the Composio tool router. By the end, you'll have a working Alchemy agent that can show all nfts owned by this wallet, get recent sales for a specific nft collection, check erc20 token balances for your address through natural language commands.

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

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

Also integrate Alchemy with

TL;DR

Here's what you'll learn:
  • Get and set up your OpenAI and Composio API keys
  • Connect your Alchemy project to Composio
  • Create a Tool Router MCP session for Alchemy
  • Initialize an MCP client and retrieve Alchemy tools
  • Build a LangChain agent that can interact with Alchemy
  • 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 Alchemy MCP server, and what's possible with it?

The Alchemy MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Alchemy account. It provides structured and secure access to your blockchain data, so your agent can perform actions like fetching NFT metadata, tracking token balances, analyzing transaction history, and managing Ethereum assets on your behalf.

  • Retrieve NFT contract and token metadata: Instantly access detailed information about any NFT collection or token, including name, symbol, supply, and contract deployer.
  • Analyze NFT sales and ownership: Let your agent fetch historical NFT sales across marketplaces and list current owners for any ERC-721 or ERC-1155 token.
  • Track token balances and portfolio: Effortlessly check ERC-20 token balances for any Ethereum address to monitor holdings or build portfolio analytics.
  • List NFTs within a collection: Pull a complete list of NFTs under a specific contract to explore, display, or analyze full collections.
  • Monitor transaction counts and activity: Quickly get the transaction count (nonce) for any Ethereum address to understand activity or prepare for new transactions.

Supported Tools & Triggers

Tools
Compute NFT RarityTool to compute the rarity of each attribute for a specific NFT based on its collection.
Get NFT Collection MetadataTool to get metadata for an NFT collection using its marketplace slug (OpenSea, LooksRare, etc).
Get Collections for OwnerTool to retrieve all NFT collections held by a specified owner address.
Get Contract Metadata Batch V3Tool to retrieve metadata for multiple NFT contracts in a single batch request.
Get Contract Metadata V3Tool to get the metadata for an NFT contract including name, symbol, total supply, and token type (ERC721/ERC1155).
Get Contracts for Owner (NFT API v3)Tool to get all NFT contracts owned by an address with contract metadata.
Get NFT Floor PriceTool to get the floor price for an NFT collection across multiple marketplaces (OpenSea, LooksRare, etc).
Get Historical Token PricesRetrieves historical price data for a token over a specified time range with configurable intervals.
Get NFT Contracts By AddressTool to retrieve NFT contracts associated with one or more wallet addresses across multiple blockchain networks.
Get NFT MetadataTool to retrieve comprehensive metadata for a specific NFT, including contract details, media URLs, attributes, ownership info, and OpenSea data.
Get NFT Metadata BatchTool to retrieve metadata for multiple NFTs in a single request (up to 100 NFTs), including contract details, media URLs, attributes, and collection data.
Get NFT Sales V3Retrieves NFT sales that have occurred through on-chain marketplaces using Alchemy's v3 API.
Get NFTs for Collection V3Retrieves all NFTs in a collection using OpenSea collection slug or contract address.
Get NFTs for ContractRetrieves all NFTs for a given NFT contract address.
Get NFTs for OwnerTool to get all NFTs currently owned by a given address.
Get Owners for CollectionTool to retrieve all owner addresses for a given NFT collection contract.
Get Owners for ContractTool to get all owners of NFTs in a contract with optional token balances.
Get NFT Owners (v3)Tool to retrieve all owners for a specific NFT using Alchemy's v3 API.
Get Portfolio NFTs By AddressTool to fetch NFTs owned by multiple wallet addresses across different blockchain networks.
Get Token Prices By SymbolTool to get current token prices by symbol (e.
Get Token BalancesThis tool retrieves ERC20 token balances for a specified Ethereum address.
Get Token Balances By AddressTool to get token balances for wallet addresses across multiple networks using Alchemy's Portfolio API.
Get Token MetadataRetrieves metadata for an ERC-20 token on Ethereum mainnet, including its name, symbol, decimals, and logo URL.
Get Token Prices By AddressRetrieves current token prices by contract address and network from decentralized exchanges (DEXes).
Get Tokens By AddressTool to fetch fungible tokens (native, ERC-20, SPL) for multiple wallet addresses across networks.
Get Transaction CountThis tool retrieves the number of transactions sent from a specific address (also known as the nonce).
Get Transactions History By AddressTool to get transaction history for wallet addresses across multiple networks using Alchemy's Data API.
Invalidate NFT Contract CacheTool to invalidate the cached metadata for an NFT contract.
Check If NFT Is AirdropTool to check if a specific NFT token is marked as an airdrop.
Check If NFT Is AirdropTool to determine whether an NFT was airdropped to the owner address.
Check Collection OwnershipTool to check if a wallet address owns any token from a specific NFT collection.
Check NFT Holder StatusTool to check if a wallet address holds any NFTs from a specific contract.
Check if Contract is SpamTool to check if an NFT contract is marked as spam by Alchemy.
Check if Contract is Spam (V3)Tool to determine if a specific NFT contract is marked as spam by Alchemy.
Search NFT Contract MetadataTool to search for keywords across metadata of all ERC-721 and ERC-1155 smart contracts.
Summarize NFT AttributesRetrieves a comprehensive summary of all attributes and traits for NFTs in a collection, including trait counts and distribution statistics.

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 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 Alchemy 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 Alchemy tools
  • Validating that COMPOSIO_USER_ID is also set before proceeding

Create a Tool Router session

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

url = session.mcp.url
What's happening:
  • We're creating a Tool Router session that gives your agent access to Alchemy 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 Alchemy tools as needed

Configure the agent with the MCP URL

client = MultiServerMCPClient({
    "alchemy-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 Alchemy MCP server via HTTP
  • The client is configured with a name and the URL from our Tool Router session
  • get_tools() retrieves all available Alchemy 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 Alchemy 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 Alchemy 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=['alchemy']
    )

    url = session.mcp.url
    
    client = MultiServerMCPClient({
        "alchemy-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 Alchemy 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 Alchemy 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 Alchemy MCP Agent with another framework

FAQ

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

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

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

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