How to integrate Api ninjas MCP with Vercel AI SDK v6

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Api ninjas logo
Vercel AI SDK logo
divider

Introduction

This guide walks you through connecting Api ninjas to Vercel AI SDK v6 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 Vercel AI SDK 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:
  • How to set up and configure a Vercel AI SDK agent with Api ninjas integration
  • Using Composio's Tool Router to dynamically load and access Api ninjas tools
  • Creating an MCP client connection using HTTP transport
  • Building an interactive CLI chat interface with conversation history management
  • Handling tool calls and results within the Vercel AI SDK framework

What is Vercel AI SDK?

The Vercel AI SDK is a TypeScript library for building AI-powered applications. It provides tools for creating agents that can use external services and maintain conversation state.

Key features include:

  • streamText: Core function for streaming responses with real-time tool support
  • MCP Client: Built-in support for Model Context Protocol via @ai-sdk/mcp
  • Step Counting: Control multi-step tool execution with stopWhen: stepCountIs()
  • OpenAI Provider: Native integration with OpenAI models

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.

Supported Tools & Triggers

Tools
Analyze Text SentimentTool to analyze the sentiment of text.
Generate Barcode ImageTool to generate a barcode image for specified text.
BIN LookupTool to look up bank information from a Bank Identification Number.
Get Bitcoin Price and Market DataTool to retrieve the latest Bitcoin price and 24-hour market data.
Calculate Calories BurnedTool to calculate calories burned for an activity based on duration and body weight.
Calculate MortgageTool to calculate mortgage payments and breakdowns.
Calculate Sales TaxTool to calculate sales tax for a purchase amount at a US location.
Check Domain AvailabilityTool to check domain availability and retrieve registration information.
Check If Date Is Public HolidayTool to check if a specific date is a public holiday in a given country.
Check If Date Is Working DayTool to check if a date is a working day in a specific country.
Check SpellingTool to check spelling and get corrections for text.
Commodity PriceGet real-time commodity prices from major exchanges (CME, NYMEX, COMEX).
Compute Text SimilarityTool to compute semantic similarity between two texts.
Convert CurrencyConvert between currencies using current exchange rates.
Convert UnitConvert between measurement units across different categories.
Crypto PriceGet the current real-time price for a cryptocurrency trading pair.
Detect Text LanguageTool to detect the language of input text.
Check Disposable EmailTool to check whether an email address is from a disposable email provider.
DNS LookupTool to retrieve DNS records for a specified domain.
Earnings CalendarFetches historical earnings data (EPS and revenue - actual vs.
Earnings Call TranscriptRetrieve the full earnings call transcript for a publicly traded company.
ETF InfoRetrieve detailed information about an Exchange-Traded Fund (ETF) by its ticker symbol.
Extract Webpage ContentTool to extract main content and metadata from a webpage.
Filter Profanity from TextTool to detect and censor profanity in text.
Find EV Charging StationsTool to find electric vehicle charging stations near a specified location.
Generate Lorem Ipsum TextTool to generate Lorem Ipsum placeholder text.
Generate Secure PasswordTool to generate secure random passwords with configurable length and character types.
Generate QR CodeTool to generate QR code images for encoding data.
Generate Random User ProfilesTool to generate fake random user profiles with realistic data.
Generate Sudoku PuzzleTool to generate a new Sudoku puzzle with a specified difficulty level.
Generate Text EmbeddingsTool to encode text into vector embeddings using NLP models.
Generate User Agent StringTool to generate realistic random user agent strings with optional filters for brand, model, OS, and browser.
Get Random Life AdviceTool to get a random piece of life advice from the API Ninjas Advice endpoint.
Get Aircraft InformationTool to retrieve aircraft information by manufacturer and model including specifications and performance data.
Get Airline InformationTool to retrieve airline information by name, IATA code, or ICAO code.
Get Airport InformationTool to search for airport information by IATA code, ICAO code, name, city, country, or region.
Get Air Quality DataTool to retrieve air quality index and pollutant data for a location.
Get Animal InformationTool to retrieve detailed scientific information about animal species including taxonomy, habitat, diet, and physical characteristics.
Get Baby NamesTool to get baby name suggestions by gender.
Get Random Bucket List IdeaTool to retrieve a random bucket list idea or activity.
Get Cat Breed InformationTool to retrieve information on cat breeds matching specified parameters.
Get Celebrity InformationTool to search for celebrity information by name or other criteria.
Get Chuck Norris JokeTool to retrieve a random Chuck Norris joke from the API Ninjas database.
Get City InformationTool to retrieve city information by name, country, coordinates, or population filters.
Get Cocktail RecipesTool to search for cocktail recipes by name or ingredients.
Get Company LogoTool to retrieve company logo images by company name or ticker symbol.
Get and Increment CounterTool to get and optionally increment a persistent counter.
Get Country Flag SVGTool to retrieve country flag images in SVG format.
Get Country InformationTool to retrieve detailed country information by name, ISO code, or filtering by economic and demographic criteria.
Get County InformationTool to retrieve US county information by name, ZIP code, or state.
Get Random Dad JokesTool to retrieve random dad jokes from API Ninjas.
Get Day in History EventsTool to get historical events for a specific date.
Get Dictionary DefinitionTool to retrieve dictionary definition for an English word.
Get Dog Breed InformationTool to get information on dog breeds matching specified parameters.
Get EarningsTool to retrieve comprehensive earnings report data for publicly traded companies.
Get Electric Vehicle InfoGet electric vehicle information by make, model, year range, or electric range.
Get Emoji InformationTool to retrieve emoji information and images from the API Ninjas Emoji database.
Get Exchange RateGet the current exchange rate for a currency pair.
Get ExercisesTool to get exercise information by muscle group, type, or difficulty level.
Get Fact of the DayTool to retrieve the fact of the day from API Ninjas.
Get Random FactsTool to retrieve random interesting facts from API Ninjas.
Get GDP DataTool to get GDP data for a country.
Convert City to CoordinatesTool to convert city names to geographic coordinates (forward geocoding).
Get Helicopter InformationTool to get helicopter information by manufacturer, model, and specifications.
Get Historical EventsTool to retrieve historical events by date or keywords.
Get Historical FiguresTool to search for historical figures by name.
Get Random Hobby SuggestionsTool to get random hobby suggestions from API Ninjas.
Get HolidaysTool to retrieve holidays for a specific country and year.
Get Daily HoroscopeTool to get daily horoscope for a zodiac sign.
Get Hospital InformationTool to retrieve hospital information by name, location, or geographic coordinates.
Income TaxGet current and historical income tax bracket rates for a country by year.
Get Insider TransactionsTool to get insider trading transactions for publicly traded companies.
Get IP GeolocationTool to retrieve geolocation information for an IP address.
Get Joke of the DayTool to retrieve the joke of the day from API Ninjas.
Get Random JokesTool to retrieve random jokes from API Ninjas.
Get Motorcycle SpecificationsTool to get detailed motorcycle specifications by make, model, and year.
Get Mutual Fund InfoTool to get mutual fund information by ticker.
Get MX RecordsTool to retrieve MX (Mail Exchange) records for a specified domain.
Get Planet InformationTool to retrieve detailed information about planets and exoplanets including mass, radius, orbital period, temperature, and host star data.
Get Population DataTool to get population data for a country.
Get Postal Code Location InfoTool to retrieve location information for Canadian postal codes.
Get Property Tax RatesTool to get property tax rates by city, county, or ZIP code.
Get Public HolidaysTool to retrieve official public holidays for a specific country and year.
Get Quote of the DayTool to retrieve the quote of the day from API Ninjas.
Get Random QuotesTool to get random quotes from famous people, filtered by category or author.
Get Random ImageTool to get a random image by category from API Ninjas.
Get Random QuotesTool to retrieve random quotes from API Ninjas.
Get Random WordTool to get a random English word from the API Ninjas Random Word endpoint.
Get RecipeTool to search for recipes by title or ingredients from a database of over 200,000 recipes.
Convert Coordinates to LocationTool to convert geographic coordinates to location information (reverse geocoding).
Get Rhyming WordsTool to get words that rhyme with a given word.
Get Random RiddlesTool to retrieve random riddles with answers from API Ninjas.
Get Sales Tax RatesTool to get sales tax rates by ZIP code or city and state.
Get SEC FilingTool to retrieve SEC filing information for publicly traded companies.
Get S&P 500 ConstituentsTool to retrieve current S&P 500 index constituents with filtering by ticker, name, sector, or date added.
Get Star InformationTool to retrieve detailed information about stars including name, constellation, coordinates, magnitude, distance, and spectral classification.
Get Stock Exchange InformationTool to retrieve stock exchange information by Market Identifier Code (MIC), name, city, or country.
Get Stock PriceTool to get current stock price data for any publicly traded company or index.
Get SWIFT CodeTool to get bank information from SWIFT code or search by bank name, city, or country.
Get ThesaurusTool to get synonyms and antonyms for an English word.
Get TickerTool to retrieve comprehensive company profile information for publicly traded companies by stock ticker symbol.
Get Timezone InformationTool to get timezone information for a location including UTC offset, local time, and timezone name.
Get Trivia QuestionsTool to retrieve trivia questions by category from API Ninjas.
Get Trivia of the DayTool to retrieve the trivia question of the day from API Ninjas.
Get Unemployment RateTool to get unemployment rate data for countries.
Get University InformationTool to retrieve university information by name or country.
Get URL Location InfoTool to get location information for a URL domain.
Get Current WeatherTool to retrieve current weather data for a location.
Get Weather ForecastTool to retrieve 5-day weather forecast in 3-hour intervals for a location.
Get WHOIS InformationTool to get WHOIS domain registration information including registrar, creation date, and expiration date.
Get Working DaysTool to get working days for a specific country and time period.
Get World TimeTool to get current date and time for a location with detailed date/time components.
Get US Zipcode Location InfoTool to retrieve location information for US zip codes.
IBAN LookupTool to look up and validate an International Bank Account Number (IBAN).
Income Tax CalculatorTool to calculate income taxes for US and Canada.
Get Inflation DataTool to get current inflation data for a country.
Interest RateTool to get current interest rates for central banks and benchmarks.
List Stock TickersTool to retrieve a paginated list of all available stock ticker symbols and company names.
VIN LookupTool to decode Vehicle Identification Number (VIN) and retrieve vehicle information.
Market CapTool to get real-time market cap data for a company.
Mortgage RateTool to get current and historical mortgage rates.
Extract Nutrition InformationTool to extract nutrition information from text query.
Scrape Website ContentTool to scrape HTML content from a URL using the API Ninjas Webscraper endpoint.
Solve Sudoku PuzzleTool to solve a Sudoku puzzle using the API Ninjas Sudoku Solver.
Validate EmailTool to validate email address format and check deliverability.
Validate EU VATTool to retrieve and validate EU VAT (Value Added Tax) rates by country code.
Validate Phone NumberTool to validate and format phone numbers.
Validate Routing NumberTool to validate and retrieve bank information from a routing number.

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

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

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

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Prerequisites

Before you begin, make sure you have:
  • Node.js and npm installed
  • A Composio account with API key
  • An OpenAI API key

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 required dependencies

bash
npm install @ai-sdk/openai @ai-sdk/mcp @composio/core ai dotenv

First, install the necessary packages for your project.

What you're installing:

  • @ai-sdk/openai: Vercel AI SDK's OpenAI provider
  • @ai-sdk/mcp: MCP client for Vercel AI SDK
  • @composio/core: Composio SDK for tool integration
  • ai: Core Vercel AI SDK
  • dotenv: Environment variable management

Set up environment variables

bash
OPENAI_API_KEY=your_openai_api_key_here
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here

Create a .env file in your project root.

What's needed:

  • OPENAI_API_KEY: Your OpenAI API key for GPT model access
  • COMPOSIO_API_KEY: Your Composio API key for tool access
  • COMPOSIO_USER_ID: A unique identifier for the user session

Import required modules and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});
What's happening:
  • We're importing all necessary libraries including Vercel AI SDK's OpenAI provider and Composio
  • The dotenv/config import automatically loads environment variables
  • The MCP client import enables connection to Composio's tool server

Create Tool Router session and initialize MCP client

typescript
async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["api_ninjas"],
  });

  const mcpUrl = 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 mcp object contains the URL and authentication headers needed to connect to the MCP server
  • This session provides access to all Api ninjas-related tools through the MCP protocol

Connect to MCP server and retrieve tools

typescript
const mcpClient = await createMCPClient({
  transport: {
    type: "http",
    url: mcpUrl,
    headers: session.mcp.headers, // Authentication headers for the Composio MCP server
  },
});

const tools = await mcpClient.tools();
What's happening:
  • We're creating an MCP client that connects to our Composio Tool Router session via HTTP
  • The mcp.url provides the endpoint, and mcp.headers contains authentication credentials
  • The type: "http" is important - Composio requires HTTP transport
  • tools() retrieves all available Api ninjas tools that the agent can use

Initialize conversation and CLI interface

typescript
let messages: ModelMessage[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
console.log(
  "Ask any questions related to api_ninjas, like summarize my last 5 emails, send an email, etc... :)))\n",
);

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

rl.prompt();
What's happening:
  • We initialize an empty messages array to maintain conversation history
  • A readline interface is created to accept user input from the command line
  • Instructions are displayed to guide the user on how to interact with the agent

Handle user input and stream responses with real-time tool feedback

typescript
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;
  }

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

  try {
    const stream = streamText({
      model: openai("gpt-5"),
      messages,
      tools,
      toolChoice: "auto",
      stopWhen: stepCountIs(10),
      onStepFinish: (step) => {
        for (const toolCall of step.toolCalls) {
          console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • We use streamText instead of generateText to stream responses in real-time
  • toolChoice: "auto" allows the model to decide when to use Api ninjas tools
  • stopWhen: stepCountIs(10) allows up to 10 steps for complex multi-tool operations
  • onStepFinish callback displays which tools are being used in real-time
  • We iterate through the text stream to create a typewriter effect as the agent responds
  • The complete response is added to conversation history to maintain context
  • Errors are caught and displayed with helpful retry suggestions

Complete Code

Here's the complete code to get you started with Api ninjas and Vercel AI SDK:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Composio } from "@composio/core";
import * as readline from "readline";
import { streamText, type ModelMessage, stepCountIs } from "ai";
import { createMCPClient } from "@ai-sdk/mcp";

const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey,
});

async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["api_ninjas"],
  });

  const mcpUrl = session.mcp.url;

  const mcpClient = await createMCPClient({
    transport: {
      type: "http",
      url: mcpUrl,
      headers: session.mcp.headers, // Authentication headers for the Composio MCP server
    },
  });

  const tools = await mcpClient.tools();

  let messages: ModelMessage[] = [];

  console.log("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
  console.log(
    "Ask any questions related to api_ninjas, like summarize my last 5 emails, send an email, etc... :)))\n",
  );

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

  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;
    }

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

    try {
      const stream = streamText({
        model: openai("gpt-5"),
        messages,
        tools,
        toolChoice: "auto",
        stopWhen: stepCountIs(10),
        onStepFinish: (step) => {
          for (const toolCall of step.toolCalls) {
            console.log(`[Using tool: ${toolCall.toolName}]`);
          }
          if (step.toolCalls.length > 0) {
            console.log(""); // Add space after tool calls
          }
        },
      });

      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk);
      }

      console.log("\n\n---\n");

      // Get final result for message history
      const response = await stream.response;
      if (response?.messages?.length) {
        messages.push(...response.messages);
      }
    } catch (error) {
      console.error("\nAn error occurred while talking to the agent:");
      console.error(error);
      console.log(
        "\nYou can try again or restart the app if it keeps happening.\n",
      );
    } finally {
      rl.prompt();
    }
  });

  rl.on("close", async () => {
    await mcpClient.close();
    console.log("\n👋 Session ended.");
    process.exit(0);
  });
}

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

Conclusion

You've successfully built a Api ninjas agent using the Vercel AI SDK with streaming capabilities! This implementation provides a powerful foundation for building AI applications with natural language interfaces and real-time feedback.

Key features of this implementation:

  • Real-time streaming responses for a better user experience with typewriter effect
  • Live tool execution feedback showing which tools are being used as the agent works
  • Dynamic tool loading through Composio's Tool Router with secure authentication
  • Multi-step tool execution with configurable step limits (up to 10 steps)
  • Comprehensive error handling for robust agent execution
  • Conversation history maintenance for context-aware responses

You can extend this further by adding custom error handling, implementing specific business logic, or integrating additional Composio toolkits to create multi-app workflows.

How to build Api ninjas MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Api ninjas MCP?

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.

Can I use Tool Router MCP with Vercel AI SDK v6?

Yes, you can. Vercel AI SDK v6 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.

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

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.

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