How to integrate Api ninjas MCP with LangChain

This guide walks you through connecting Api ninjas to LangChain using the Composio tool router. By the end, you'll have a working Api ninjas agent that can get real-time bitcoin price and market data, check if this email is disposable, look up bank info for this bin through natural language commands. This guide will help you understand how to give your LangChain agent real control over a Api ninjas account through Composio's Api ninjas MCP server. Before we dive in, let's take a quick look at the key ideas and tools involved.

Api ninjas logoApi ninjas
Api Key

Api ninjas offers 120+ public APIs spanning categories like weather, finance, sports, and more. Developers use it to supercharge apps with real-time data and actionable endpoints.

128 Tools

Introduction

This guide walks you through connecting Api ninjas to LangChain using the Composio tool router. By the end, you'll have a working Api ninjas agent that can get real-time bitcoin price and market data, check if this email is disposable, look up bank info for this bin through natural language commands.

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

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

Also integrate Api ninjas with

TL;DR

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

The Api ninjas MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Api ninjas account. It provides structured and secure access to a wide array of real-time data APIs, so your agent can perform actions like fetching financial data, generating barcodes, validating emails, and looking up domains on your behalf.

  • Fetch live financial and crypto data: Instantly retrieve up-to-date prices for stocks, commodities, ETFs, and cryptocurrencies, or access earnings calendars and transcripts for informed decision-making.
  • Barcode generation on demand: Have your agent create barcode images for custom data or text, perfect for inventory, tickets, or quick sharing of encoded information.
  • Email validation and security checks: Automatically check if an email address is disposable or risky before engaging users or sending communications.
  • Bank and payment info lookup: Look up bank details using BIN numbers, helping with payment processing, fraud detection, or financial analysis.
  • Domain and DNS diagnostics: Let your agent perform DNS lookups to fetch domain records, aiding in troubleshooting or technical audits quickly and efficiently.

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

Step by step10 STEPS
1

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
2

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.
3

Install dependencies

npm install @composio/langchain @langchain/core @langchain/openai @langchain/mcp-adapters 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/core is the core agent framework
  • dotenv/config loads environment variables
4

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
5

Import dependencies

import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

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

Initialize Composio client

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });
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 Api ninjas tools
  • Validating that COMPOSIO_USER_ID is also set before proceeding
7

Create a Tool Router session

const session = await composio.create(
    userId as string,
    {
        toolkits: ['api_ninjas']
    }
);

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

Configure the agent with the MCP URL

const client = new MultiServerMCPClient({
    "api_ninjas-agent": {
        transport: "http",
        url: url,
        headers: {
            "x-api-key": process.env.COMPOSIO_API_KEY
        }
    }
});

const tools = await client.getTools();

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

Set up interactive chat interface

let conversationHistory: any[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log("Ask any Api ninjas related question or task to the agent.\n");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: '
});

rl.prompt();

rl.on('line', async (userInput: string) => {
    const trimmedInput = userInput.trim();

    if (['exit', 'quit', 'bye'].includes(trimmedInput.toLowerCase())) {
        console.log("\nGoodbye!");
        rl.close();
        process.exit(0);
    }

    if (!trimmedInput) {
        rl.prompt();
        return;
    }

    conversationHistory.push({ role: "user", content: trimmedInput });
    console.log("\nAgent is thinking...\n");

    const response = await agent.invoke({ messages: conversationHistory });
    conversationHistory = response.messages;

    const finalResponse = response.messages[response.messages.length - 1]?.content;
    console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

    rl.on('close', () => {
        console.log('\n👋 Session ended.');
        process.exit(0);
    });
What's happening:
  • We initialize an empty conversationHistory list to maintain context across interactions
  • A readline interface is used to continuously accept 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 invoke() method with the full conversation history
  • Users can type 'exit', 'quit', or 'bye' to end the chat session gracefully
10

Run the application

main().catch((err) => {
    console.error('Fatal error:', err);
    process.exit(1);
});
What's happening:
  • We call the main() function to start the application

Complete Code

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

import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
import { MultiServerMCPClient } from "@langchain/mcp-adapters";  
import { createAgent } from "langchain";
import * as readline from 'readline';
import 'dotenv/config';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.COMPOSIO_USER_ID;

if (!composioApiKey) throw new Error('COMPOSIO_API_KEY is not set');
if (!userId) throw new Error('COMPOSIO_USER_ID is not set');

async function main() {
    const composio = new Composio({
        apiKey: composioApiKey as string,
        provider: new LangchainProvider()
    });

    const session = await composio.create(
        userId as string,
        {
            toolkits: ['api_ninjas']
        }
    );

    const url = session.mcp.url;
    
    const client = new MultiServerMCPClient({
        "api_ninjas-agent": {
            transport: "http",
            url: url,
            headers: {
                "x-api-key": process.env.COMPOSIO_API_KEY
            }
        }
    });
    
    const tools = await client.getTools();
  
    const agent = createAgent({ model: "gpt-5", tools });
    
    let conversationHistory: any[] = [];
    
    console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
    console.log("Ask any Api ninjas related question or task to the agent.\n");
    
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        prompt: 'You: '
    });

    rl.prompt();

    rl.on('line', async (userInput: string) => {
        const trimmedInput = userInput.trim();
        
        if (['exit', 'quit', 'bye'].includes(trimmedInput.toLowerCase())) {
            console.log("\nGoodbye!");
            rl.close();
            process.exit(0);
        }
        
        if (!trimmedInput) {
            rl.prompt();
            return;
        }
        
        conversationHistory.push({ role: "user", content: trimmedInput });
        console.log("\nAgent is thinking...\n");
        
        const response = await agent.invoke({ messages: conversationHistory });
        conversationHistory = response.messages;
        
        const finalResponse = response.messages[response.messages.length - 1]?.content;
        console.log(`Agent: ${finalResponse}\n`);
        
        rl.prompt();
    });

    rl.on('close', () => {
        console.log('\nSession ended.');
        process.exit(0);
    });
}

main().catch((err) => {
    console.error('Fatal error:', err);
    process.exit(1);
});

Conclusion

You've successfully built a LangChain agent that can interact with Api ninjas 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.
TOOLS

Supported Tools

Every Api ninjas action and event your agent gets out of the box.

Analyze Text Sentiment

Tool to analyze the sentiment of text.

Generate Barcode Image

Tool to generate a barcode image for specified text.

BIN Lookup

Tool to look up bank information from a Bank Identification Number.

Get Bitcoin Price and Market Data

Tool to retrieve the latest Bitcoin price and 24-hour market data.

Calculate Calories Burned

Tool to calculate calories burned for an activity based on duration and body weight.

Calculate Mortgage

Tool to calculate mortgage payments and breakdowns.

Calculate Sales Tax

Tool to calculate sales tax for a purchase amount at a US location.

Check Domain Availability

Tool to check domain availability and retrieve registration information.

Check If Date Is Public Holiday

Tool to check if a specific date is a public holiday in a given country.

Check If Date Is Working Day

Tool to check if a date is a working day in a specific country.

Check Spelling

Tool to check spelling and get corrections for text.

Commodity Price

Get real-time commodity prices from major exchanges (CME, NYMEX, COMEX).

Compute Text Similarity

Tool to compute semantic similarity between two texts.

Convert Currency

Convert between currencies using current exchange rates.

Convert Unit

Convert between measurement units across different categories.

Crypto Price

Get the current real-time price for a cryptocurrency trading pair.

Detect Text Language

Tool to detect the language of input text.

Check Disposable Email

Tool to check whether an email address is from a disposable email provider.

DNS Lookup

Tool to retrieve DNS records for a specified domain.

Earnings Calendar

Fetches historical earnings data (EPS and revenue - actual vs.

Earnings Call Transcript

Retrieve the full earnings call transcript for a publicly traded company.

ETF Info

Retrieve detailed information about an Exchange-Traded Fund (ETF) by its ticker symbol.

Extract Webpage Content

Tool to extract main content and metadata from a webpage.

Filter Profanity from Text

Tool to detect and censor profanity in text.

Find EV Charging Stations

Tool to find electric vehicle charging stations near a specified location.

Generate Lorem Ipsum Text

Tool to generate Lorem Ipsum placeholder text.

Generate Secure Password

Tool to generate secure random passwords with configurable length and character types.

Generate QR Code

Tool to generate QR code images for encoding data.

Generate Random User Profiles

Tool to generate fake random user profiles with realistic data.

Generate Sudoku Puzzle

Tool to generate a new Sudoku puzzle with a specified difficulty level.

Generate Text Embeddings

Tool to encode text into vector embeddings using NLP models.

Generate User Agent String

Tool to generate realistic random user agent strings with optional filters for brand, model, OS, and browser.

Get Random Life Advice

Tool to get a random piece of life advice from the API Ninjas Advice endpoint.

Get Aircraft Information

Tool to retrieve aircraft information by manufacturer and model including specifications and performance data.

Get Airline Information

Tool to retrieve airline information by name, IATA code, or ICAO code.

Get Airport Information

Tool to search for airport information by IATA code, ICAO code, name, city, country, or region.

Get Air Quality Data

Tool to retrieve air quality index and pollutant data for a location.

Get Animal Information

Tool to retrieve detailed scientific information about animal species including taxonomy, habitat, diet, and physical characteristics.

Get Baby Names

Tool to get baby name suggestions by gender.

Get Random Bucket List Idea

Tool to retrieve a random bucket list idea or activity.

Get Cat Breed Information

Tool to retrieve information on cat breeds matching specified parameters.

Get Celebrity Information

Tool to search for celebrity information by name or other criteria.

Get Chuck Norris Joke

Tool to retrieve a random Chuck Norris joke from the API Ninjas database.

Get City Information

Tool to retrieve city information by name, country, coordinates, or population filters.

Get Cocktail Recipes

Tool to search for cocktail recipes by name or ingredients.

Get Company Logo

Tool to retrieve company logo images by company name or ticker symbol.

Get and Increment Counter

Tool to get and optionally increment a persistent counter.

Get Country Flag SVG

Tool to retrieve country flag images in SVG format.

Get Country Information

Tool to retrieve detailed country information by name, ISO code, or filtering by economic and demographic criteria.

Get County Information

Tool to retrieve US county information by name, ZIP code, or state.

Get Random Dad Jokes

Tool to retrieve random dad jokes from API Ninjas.

Get Day in History Events

Tool to get historical events for a specific date.

Get Dictionary Definition

Tool to retrieve dictionary definition for an English word.

Get Dog Breed Information

Tool to get information on dog breeds matching specified parameters.

Get Earnings

Tool to retrieve comprehensive earnings report data for publicly traded companies.

Get Electric Vehicle Info

Get electric vehicle information by make, model, year range, or electric range.

Get Emoji Information

Tool to retrieve emoji information and images from the API Ninjas Emoji database.

Get Exchange Rate

Get the current exchange rate for a currency pair.

Get Exercises

Tool to get exercise information by muscle group, type, or difficulty level.

Get Fact of the Day

Tool to retrieve the fact of the day from API Ninjas.

Get Random Facts

Tool to retrieve random interesting facts from API Ninjas.

Get GDP Data

Tool to get GDP data for a country.

Convert City to Coordinates

Tool to convert city names to geographic coordinates (forward geocoding).

Get Helicopter Information

Tool to get helicopter information by manufacturer, model, and specifications.

Get Historical Events

Tool to retrieve historical events by date or keywords.

Get Historical Figures

Tool to search for historical figures by name.

Get Random Hobby Suggestions

Tool to get random hobby suggestions from API Ninjas.

Get Holidays

Tool to retrieve holidays for a specific country and year.

Get Daily Horoscope

Tool to get daily horoscope for a zodiac sign.

Get Hospital Information

Tool to retrieve hospital information by name, location, or geographic coordinates.

Income Tax

Get current and historical income tax bracket rates for a country by year.

Get Insider Transactions

Tool to get insider trading transactions for publicly traded companies.

Get IP Geolocation

Tool to retrieve geolocation information for an IP address.

Get Joke of the Day

Tool to retrieve the joke of the day from API Ninjas.

Get Random Jokes

Tool to retrieve random jokes from API Ninjas.

Get Motorcycle Specifications

Tool to get detailed motorcycle specifications by make, model, and year.

Get Mutual Fund Info

Tool to get mutual fund information by ticker.

Get MX Records

Tool to retrieve MX (Mail Exchange) records for a specified domain.

Get Planet Information

Tool to retrieve detailed information about planets and exoplanets including mass, radius, orbital period, temperature, and host star data.

Get Population Data

Tool to get population data for a country.

Get Postal Code Location Info

Tool to retrieve location information for Canadian postal codes.

Get Property Tax Rates

Tool to get property tax rates by city, county, or ZIP code.

Get Public Holidays

Tool to retrieve official public holidays for a specific country and year.

Get Quote of the Day

Tool to retrieve the quote of the day from API Ninjas.

Get Random Quotes

Tool to get random quotes from famous people, filtered by category or author.

Get Random Image

Tool to get a random image by category from API Ninjas.

Get Random Quotes

Tool to retrieve random quotes from API Ninjas.

Get Random Word

Tool to get a random English word from the API Ninjas Random Word endpoint.

Get Recipe

Tool to search for recipes by title or ingredients from a database of over 200,000 recipes.

Convert Coordinates to Location

Tool to convert geographic coordinates to location information (reverse geocoding).

Get Rhyming Words

Tool to get words that rhyme with a given word.

Get Random Riddles

Tool to retrieve random riddles with answers from API Ninjas.

Get Sales Tax Rates

Tool to get sales tax rates by ZIP code or city and state.

Get SEC Filing

Tool to retrieve SEC filing information for publicly traded companies.

Get S&P 500 Constituents

Tool to retrieve current S&P 500 index constituents with filtering by ticker, name, sector, or date added.

Get Star Information

Tool to retrieve detailed information about stars including name, constellation, coordinates, magnitude, distance, and spectral classification.

Get Stock Exchange Information

Tool to retrieve stock exchange information by Market Identifier Code (MIC), name, city, or country.

Get Stock Price

Tool to get current stock price data for any publicly traded company or index.

Get SWIFT Code

Tool to get bank information from SWIFT code or search by bank name, city, or country.

Get Thesaurus

Tool to get synonyms and antonyms for an English word.

Get Ticker

Tool to retrieve comprehensive company profile information for publicly traded companies by stock ticker symbol.

Get Timezone Information

Tool to get timezone information for a location including UTC offset, local time, and timezone name.

Get Trivia Questions

Tool to retrieve trivia questions by category from API Ninjas.

Get Trivia of the Day

Tool to retrieve the trivia question of the day from API Ninjas.

Get Unemployment Rate

Tool to get unemployment rate data for countries.

Get University Information

Tool to retrieve university information by name or country.

Get URL Location Info

Tool to get location information for a URL domain.

Get Current Weather

Tool to retrieve current weather data for a location.

Get Weather Forecast

Tool to retrieve 5-day weather forecast in 3-hour intervals for a location.

Get WHOIS Information

Tool to get WHOIS domain registration information including registrar, creation date, and expiration date.

Get Working Days

Tool to get working days for a specific country and time period.

Get World Time

Tool to get current date and time for a location with detailed date/time components.

Get US Zipcode Location Info

Tool to retrieve location information for US zip codes.

IBAN Lookup

Tool to look up and validate an International Bank Account Number (IBAN).

Income Tax Calculator

Tool to calculate income taxes for US and Canada.

Get Inflation Data

Tool to get current inflation data for a country.

Interest Rate

Tool to get current interest rates for central banks and benchmarks.

List Stock Tickers

Tool to retrieve a paginated list of all available stock ticker symbols and company names.

VIN Lookup

Tool to decode Vehicle Identification Number (VIN) and retrieve vehicle information.

Market Cap

Tool to get real-time market cap data for a company.

Mortgage Rate

Tool to get current and historical mortgage rates.

Extract Nutrition Information

Tool to extract nutrition information from text query.

Scrape Website Content

Tool to scrape HTML content from a URL using the API Ninjas Webscraper endpoint.

Solve Sudoku Puzzle

Tool to solve a Sudoku puzzle using the API Ninjas Sudoku Solver.

Validate Email

Tool to validate email address format and check deliverability.

Validate EU VAT

Tool to retrieve and validate EU VAT (Value Added Tax) rates by country code.

Validate Phone Number

Tool to validate and format phone numbers.

Validate Routing Number

Tool to validate and retrieve bank information from a routing number.

FAQ

Frequently asked questions

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

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 Api ninjas tools.

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

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 Api ninjas data and credentials are handled as safely as possible.

Start with Api ninjas.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Api ninjas tool your agent needs.Free to start.

Start building