# How to integrate Serpapi MCP with Vercel AI SDK v6

```json
{
  "title": "How to integrate Serpapi MCP with Vercel AI SDK v6",
  "toolkit": "Serpapi",
  "toolkit_slug": "serpapi",
  "framework": "Vercel AI SDK",
  "framework_slug": "ai-sdk",
  "url": "https://composio.dev/toolkits/serpapi/framework/ai-sdk",
  "markdown_url": "https://composio.dev/toolkits/serpapi/framework/ai-sdk.md",
  "updated_at": "2026-05-12T10:25:34.617Z"
}
```

## Introduction

This guide walks you through connecting Serpapi to Vercel AI SDK v6 using the Composio tool router. By the end, you'll have a working Serpapi agent that can find latest job postings for python developers, show recent stock news for apple inc, list concerts happening in new york this week through natural language commands.
This guide will help you understand how to give your Vercel AI SDK agent real control over a Serpapi account through Composio's Serpapi MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Serpapi with

- [ChatGPT](https://composio.dev/toolkits/serpapi/framework/chatgpt)
- [OpenAI Agents SDK](https://composio.dev/toolkits/serpapi/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/serpapi/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/serpapi/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/serpapi/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/serpapi/framework/codex)
- [Cursor](https://composio.dev/toolkits/serpapi/framework/cursor)
- [VS Code](https://composio.dev/toolkits/serpapi/framework/vscode)
- [OpenCode](https://composio.dev/toolkits/serpapi/framework/opencode)
- [OpenClaw](https://composio.dev/toolkits/serpapi/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/serpapi/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/serpapi/framework/cli)
- [Google ADK](https://composio.dev/toolkits/serpapi/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/serpapi/framework/langchain)
- [Mastra AI](https://composio.dev/toolkits/serpapi/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/serpapi/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/serpapi/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- How to set up and configure a Vercel AI SDK agent with Serpapi integration
- Using Composio's Tool Router to dynamically load and access Serpapi 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 Serpapi MCP server, and what's possible with it?

The Serpapi MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your SerpApi account. It provides structured and secure access to real-time search engine results, so your agent can perform actions like scraping search data, analyzing trends, retrieving product listings, and exploring local business information on your behalf.
- Real-time web search across engines: Instantly fetch structured search results from Google, Bing, Baidu, and DuckDuckGo for any query, including organic results, ads, and rich snippets.
- Product and marketplace data extraction: Automatically search eBay for products and retrieve detailed, structured product data to power research or price comparison workflows.
- Event and job listings discovery: Let your agent search Google Events and Google Jobs to uncover upcoming events, conferences, or relevant job postings with granular location and keyword filters.
- Financial and stock information retrieval: Seamlessly pull the latest company details, stock prices, market news, and trends from Google Finance using a simple query.
- Location and map-based search: Enable your agent to perform Google Maps searches to find local businesses, attractions, or venues—complete with structured location data and optional GPS-based results.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `SERPAPI_BAIDU_SEARCH` | Search Baidu with Query | Search Baidu (Chinese search engine) and retrieve search results. Requires a search query string in the 'q' parameter. Returns organic search results, answer boxes, and pagination info in JSON format. |
| `SERPAPI_BING_MAPS` | Bing Maps Search | Tool to scrape Bing Maps results using SerpApi. Use when you need to find local businesses, places, or get detailed location information including addresses, phone numbers, ratings, reviews, and more. Supports searching by query or specific place ID. |
| `SERPAPI_BING_SEARCH` | Bing Search | Retrieve Bing Search Engine Results via SerpAPI (requires active SerpAPI connection; if unavailable, use COMPOSIO_SEARCH_WEB or COMPOSIO_SEARCH_NEWS). Consumes SerpAPI credits per call; throttle to ~1–2 calls/second and apply exponential backoff on HTTP 429. Supports query, location, language, and device parameters. Set `location`, `mkt`, or `cc` explicitly when local relevance matters — result ranking is highly sensitive to localization. |
| `SERPAPI_DUCK_DUCK_GO_LIGHT_SEARCH` | DuckDuckGo Light Search | Tool to access the world's fastest DuckDuckGo Search API via SerpApi. Scrapes DuckDuckGo search results in JSON format with critical data for faster response times, without extra-rich results. Use when you need quick DuckDuckGo search results with essential information. Supports location-based searches, date filtering, and pagination (15 results per page). |
| `SERPAPI_DUCK_DUCK_GO_MAPS` | DuckDuckGo Maps search | Scrapes DuckDuckGo Maps results via SerpApi. Use when searching for location-based information like businesses, restaurants, or services in a specific geographic area. Returns structured data including ratings, reviews, addresses, operating hours, and contact information. |
| `SERPAPI_DUCK_DUCK_GO_SEARCH` | DuckDuckGo search | Performs a DuckDuckGo search via SerpApi to retrieve SERP data, including organic results, ads, and structured information. Requires a valid SerpApi connection configured in Composio. Results may be localized by region by default. |
| `SERPAPI_EBAY_SEARCH` | eBay Search | Retrieve eBay Search Results via SerpApi (requires active SerpApi connected account). Supports parameters like nkw (query), location, etc. Returns product SERP data in JSON format. Listing prices and fees may be incomplete or inconsistent; verify total cost on the source page before comparing results. |
| `SERPAPI_EVENT_SEARCH` | Search Google Events | Searches for events (e.g., concerts, festivals, conferences) by query, retrieving structured data from Google's event search results via the SerpApi Google Events engine. |
| `SERPAPI_FINANCE_SEARCH` | Search finance | Retrieves structured financial information (e.g., company data, stock details, market trends, news) from Google Finance via SERP API based on a query. Requires active SerpApi credentials. Empty results for delisted, illiquid, or newly listed assets are valid 'no data' responses. High query volumes may trigger HTTP 429 rate limits; apply backoff on retries. |
| `SERPAPI_GET_AVAILABLE_LOCATION_OPTIONS_FOR_GOOGLE_SEARCHES` | Get Location Options | Tool to get available location options for Google searches. Returns location names, codes, and identifiers that can be used in the location parameter. Use when you need to find valid location values for search queries. |
| `SERPAPI_GET_FACEBOOK_PROFILE` | Get Facebook profile information | Tool to retrieve public information from a Facebook profile or page using SerpAPI. Use when you need to fetch profile details, bio, photos, followers, ratings, or contact information. |
| `SERPAPI_GET_GOOGLE_ABOUT_THIS_RESULT` | Get Google About This Result | Tool to get Google 'About this result' information for a website. Use when you need detailed information about a specific URL including company details, social profiles, web citations, and reviews. |
| `SERPAPI_GET_GOOGLE_HOTELS_AUTOCOMPLETE_SUGGESTIONS` | Get Google Hotels Autocomplete | Tool to get autocomplete suggestions for Google Hotels destination searches. Use when users need to search for hotel destinations, properties, or locations before performing a full hotel search. |
| `SERPAPI_GET_GOOGLE_IMAGES_RELATED_CONTENT` | Get Google Images Related Content | Get related content for a specific Google Images result. Requires a related_content_id obtained from a Google Images search. Use when you need to find similar images or related visual content for a particular image. |
| `SERPAPI_GET_GOOGLE_PATENT_DETAILS` | Get Google Patent Details | Tool to retrieve detailed information about a specific patent or scholar document from Google Patents via SerpApi. Use when you need patent details, claims, citations, inventors, assignees, legal events, or scholar publication information. |
| `SERPAPI_GET_SEARCH_ARCHIVE` | Get Search Archive | Tool to retrieve results from a previous async search using its search ID. Use when you need to fetch results from searches submitted with async=true. Searches can be retrieved up to 31 days after completion. |
| `SERPAPI_GOOGLE_DOMAINS_LIST` | Google Domains List | Retrieve the list of supported Google domains for search queries. |
| `SERPAPI_GOOGLE_FORUMS_SEARCH` | Google Forums Search | Tool to scrape forum results from Google's Forums Platform using SerpApi. Use when you need to search forum discussions, get forum titles, dates, links, answers with voting data, and related searches. |
| `SERPAPI_GOOGLE_JOBS_SEARCH` | Google Jobs Search | Retrieve Google Jobs Search Results via SerpApi. Returns job SERP data in JSON; key attributes like `work_from_home`, `posted_at`, `salary`, and `schedule_type` are nested under `detected_extensions` per job object and are often absent — treat as optional. Results may include stale postings; verify recency via `detected_extensions.posted_at`. Supports pagination, location filtering, and remote-job filtering. |
| `SERPAPI_GOOGLE_LENS_SEARCH` | Google Lens search | Performs reverse image search using Google Lens to find visually similar images, products, and related content. Use when you need to identify objects, find similar products, or get information about images. Requires a publicly accessible image URL. |
| `SERPAPI_GOOGLE_LIGHT_SEARCH` | Google Light Search | Retrieve Google Light Search Results via SerpApi. Requires an active SerpApi connection. Supports q, location, gl, hl, and other SERP parameters. Returns lightweight JSON SERP data; results are in organic_results (handle missing/empty gracefully). Snippets are shallow — follow citation URLs with BROWSER_TOOL_FETCH_WEBPAGE for full content. Rate limit: HTTP 429 under heavy use; keep to ~1–2 requests/sec with exponential backoff on retry. |
| `SERPAPI_GOOGLE_MAPS_POSTS` | Google Maps Posts | Scrapes Google Maps Posts for a business location via SerpApi. Extracts local posts published by business owners including titles, descriptions, links, images, and publication dates. Returns 10 posts per page with pagination support. |
| `SERPAPI_GOOGLE_MAPS_SEARCH` | Google maps search | Performs a Google Maps search via SERP API. Takes a query, optionally using specific GPS coordinates and pagination, returning structured location data. |
| `SERPAPI_GOOGLE_PLAY_PRODUCT` | Google Play Product Search | Tool to retrieve detailed Google Play product information using SerpApi. Supports apps, movies, TV shows, audiobooks, and books. Use when you need product details, ratings, reviews, or media for Google Play Store items. |
| `SERPAPI_GOOGLE_SCHOLAR_AUTHOR` | Google Scholar Author Profile | Scrapes full Google Scholar Author page including articles, citations, metrics, and co-authors. Use when you need detailed information about a specific researcher's publications and academic profile. |
| `SERPAPI_GOOGLE_SCHOLAR_CITE` | Google Scholar Cite | Scrapes full Google Scholar Citations with multiple citation formats. Retrieves MLA, APA, Chicago, Harvard, and Vancouver style citations along with download links for BibTeX, EndNote, RefMan, and RefWorks. Use when you need formatted citations for a specific research paper identified by its Google Scholar ID. |
| `SERPAPI_GOOGLE_VIDEOS_LIGHT` | Google Videos Light Search | Tool to scrape Google Videos results using SerpApi's ultra-fast Google Videos Light API. Use when you need video titles, links, thumbnails, snippets, upload dates, and durations from Google Videos search. This lighter version excludes rich results for faster response times. |
| `SERPAPI_HOTEL_SEARCH` | Hotel Search | Retrieve Google Hotel Search Results. Supports parameters like q (query), location, etc. Returns hotel SERP data in JSON format. |
| `SERPAPI_IMAGE_SEARCH` | Image search | Searches Google Images via SERP API for a given query, returning structured image results. Requires a valid SerpAPI authenticated connection. The number of results can be controlled using the 'num' parameter (1-100). If not specified, it defaults to 20 results. |
| `SERPAPI_NAVER_SEARCH` | Naver Search | Tool to search Naver (South Korea's leading search engine) for Korean web results and content. Use when searching for Korean-language content, news, videos, images, or shopping results. Supports various search categories and filtering options including time periods and sorting. |
| `SERPAPI_NEWS_SEARCH` | Search for news articles | Searches Google News (via SerpApi, `tbm=nws`) for articles matching a query; precise key-phrase queries yield best results. Auth is handled via SerpApi connection — do not pass api_key as a parameter. Results returned under `news_results` field (~10 items/page). Rate-limited: throttle to ~1 req/s; HTTP 429 on bursts — apply exponential backoff (1s, 2s, 4s). Covers news content only; pair with SERPAPI_SEARCH for broader web sources. Headlines/snippets only — use EXA_GET_CONTENTS_ACTION for full article text. |
| `SERPAPI_OPEN_TABLE_REVIEWS` | OpenTable Reviews Search | Tool to scrape OpenTable restaurant reviews using SerpApi. Retrieves user reviews, ratings, restaurant responses, images, and AI-generated summaries. Use when you need detailed review data for OpenTable restaurants. |
| `SERPAPI_PLAY_SEARCH` | Google Play Search | Retrieve Google Play Store Search Results. Supports parameters like q (query), gl, hl, etc. Returns app SERP data in JSON format. |
| `SERPAPI_SCHOLAR_SEARCH` | Search Google Scholar | Searches Google Scholar via SerpApi for academic literature, papers, articles, and citations based on a query. Response results may include `inline_links.cited_by` and `resources` (PDF links), but these fields are not guaranteed; check for their existence and type before accessing. |
| `SERPAPI_SEARCH` | Serp API search | Performs a real-time Google search via the SerpAPI connection (must be active; if unavailable, use COMPOSIO_SEARCH_WEB or other COMPOSIO_SEARCH_* tools). Returns ~10 organic results per page nested under results.organic_results — not a flat list; handle missing/empty arrays. Paginate via start offset or serpapi_pagination.next; max num=100; stop when domains plateau to avoid quota exhaustion. Rate-limited: throttle to 1–2 req/s; HTTP 429 on bursts — apply exponential backoff (1s, 2s, 4s). Derive result rank from array index (absolute rank = start + index; no explicit rank field). Lacks date-bound controls — embed recency terms in query or use SERPAPI_NEWS_SEARCH for time-sensitive queries. Results may include ads and sponsored content; prefer authoritative domains. Use vertical tools (SERPAPI_IMAGE_SEARCH, SERPAPI_NEWS_SEARCH, SERPAPI_YOU_TUBE_SEARCH, SERPAPI_GOOGLE_JOBS_SEARCH) for specialized query types. |
| `SERPAPI_SEARCH_APPLE_APP_STORE` | Search Apple App Store | Tool to search Apple App Store for iOS and Mac apps. Returns app details including ratings, reviews, descriptions, and developer information. Use when you need to find apps on the Apple App Store or get information about specific apps. |
| `SERPAPI_SEARCH_GOOGLE_IMAGES_LIGHT` | Google Images Light Search | Tool to scrape Google Images results using SerpApi's Google Images Light API. Use when you need fast image search with thumbnails, titles, sources, and original image URLs from Google Images. This lightweight version provides faster response times compared to the full Google Images API. |
| `SERPAPI_SEARCH_GOOGLE_LOCAL_SERVICES` | Search Google Local Services | Search Google Local Services for service providers like electricians, plumbers, HVAC technicians, and more. Use when you need to find local service professionals with Google's guaranteed badge and verified business information. |
| `SERPAPI_SEARCH_YELP` | Search Yelp businesses | Tool to search Yelp for businesses and places using SerpApi. Returns business listings with ratings, reviews, hours, contact information, and location details. Use when you need to find local businesses, restaurants, services, or read customer reviews. |
| `SERPAPI_SHOPPING_SEARCH` | Shopping search | Searches Google Shopping via SerpAPI for a specific product, returning structured listings in results.shopping_results. Requires an active SerpAPI connection. Response fields such as rating, review_count, extracted_price, and extracted_old_price may be absent; null-check before ranking or computing discounts. Discount percentages in listings may reflect aggregate promotional claims, not per-item pricing. |
| `SERPAPI_TRENDS_SEARCH` | Google Trends search | Fetches Google Trends data; returns relative 0–100 interest indices (not absolute volumes) meaningful only when comparing queries within the same request. The `query`'s format (single/multiple terms) must comply with the selected `data_type`. |
| `SERPAPI_WALMART_PRODUCT_REVIEWS` | Walmart Product Reviews | Tool to scrape full Walmart product reviews using SerpApi's Walmart Product Reviews API. Retrieves ratings, review text, user information, and helpful votes for a specific product. Use when you need detailed customer feedback and sentiment analysis for Walmart products. |
| `SERPAPI_WALMART_SEARCH` | Walmart Search | Retrieve Walmart Search Results. Supports parameters like query, location, store ID, etc. Returns product SERP data in JSON format. |
| `SERPAPI_YAHOO_SEARCH` | Yahoo Search | Retrieve Yahoo! Search Engine Results. Supports query, location, language, and device parameters. |
| `SERPAPI_YAHOO_VIDEOS` | Yahoo Videos Search | Scrape Yahoo! Videos results with position, title, thumbnail, link, preview, source, duration, date and more. Use when you need to search for video content on Yahoo! Videos. |
| `SERPAPI_YANDEX_IMAGES_SEARCH` | Yandex Images Search | Tool to search Yandex Images for image results with advanced filters. Use when searching for images on Yandex with filters like size, color, type, or performing reverse image search. |
| `SERPAPI_YANDEX_SEARCH` | Yandex Search | Retrieve Yandex Search Results. Supports parameters like text (query), location, etc. Returns SERP data in JSON format. |
| `SERPAPI_YOU_TUBE_SEARCH` | YouTube Search | Retrieve YouTube Search Results. Supports parameters like search_query, location, etc. Returns video SERP data in JSON format. |

## Supported Triggers

None listed.

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

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

## Step-by-step Guide

### 1. Prerequisites

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

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) 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](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install required dependencies

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
```bash
npm install @ai-sdk/openai @ai-sdk/mcp @composio/core ai dotenv
```

### 3. Set up environment variables

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
```bash
OPENAI_API_KEY=your_openai_api_key_here
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
```

### 4. Import required modules and validate environment

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
```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,
});
```

### 5. Create Tool Router session and initialize MCP client

What's happening:
- We're creating a Tool Router session that gives your agent access to Serpapi 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 Serpapi-related tools through the MCP protocol
```typescript
async function main() {
  // Create a tool router session for the user
  const session = await composio.create(composioUserID!, {
    toolkits: ["serpapi"],
  });

  const mcpUrl = session.mcp.url;
```

### 6. Connect to MCP server and retrieve 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 Serpapi tools that the agent can use
```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();
```

### 7. Initialize conversation and CLI interface

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
```typescript
let messages: ModelMessage[] = [];

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

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

rl.prompt();
```

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

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 Serpapi 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
```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);
});
```

## Complete Code

```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: ["serpapi"],
  });

  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 serpapi, 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 Serpapi 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 Serpapi MCP Agent with another framework

- [ChatGPT](https://composio.dev/toolkits/serpapi/framework/chatgpt)
- [OpenAI Agents SDK](https://composio.dev/toolkits/serpapi/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/serpapi/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/serpapi/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/serpapi/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/serpapi/framework/codex)
- [Cursor](https://composio.dev/toolkits/serpapi/framework/cursor)
- [VS Code](https://composio.dev/toolkits/serpapi/framework/vscode)
- [OpenCode](https://composio.dev/toolkits/serpapi/framework/opencode)
- [OpenClaw](https://composio.dev/toolkits/serpapi/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/serpapi/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/serpapi/framework/cli)
- [Google ADK](https://composio.dev/toolkits/serpapi/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/serpapi/framework/langchain)
- [Mastra AI](https://composio.dev/toolkits/serpapi/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/serpapi/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/serpapi/framework/crew-ai)

## Related Toolkits

- [Firecrawl](https://composio.dev/toolkits/firecrawl) - Firecrawl automates large-scale web crawling and data extraction. It helps organizations efficiently gather, index, and analyze content from online sources.
- [Tavily](https://composio.dev/toolkits/tavily) - Tavily offers powerful search and data retrieval from documents, databases, and the web. It helps teams locate and filter information instantly, saving hours on research.
- [Exa](https://composio.dev/toolkits/exa) - Exa is a data extraction and search platform for gathering and analyzing information from websites, APIs, or databases. It helps teams quickly surface insights and automate data-driven workflows.
- [Peopledatalabs](https://composio.dev/toolkits/peopledatalabs) - Peopledatalabs delivers B2B data enrichment and identity resolution APIs. Supercharge your apps with accurate, up-to-date business and contact data.
- [Snowflake](https://composio.dev/toolkits/snowflake) - Snowflake is a cloud data warehouse built for elastic scaling, secure data sharing, and fast SQL analytics across major clouds.
- [Posthog](https://composio.dev/toolkits/posthog) - PostHog is an open-source analytics platform for tracking user interactions and product metrics. It helps teams refine features, analyze funnels, and reduce churn with actionable insights.
- [Amplitude](https://composio.dev/toolkits/amplitude) - Amplitude is a digital analytics platform for product and behavioral data insights. It helps teams analyze user journeys and make data-driven decisions quickly.
- [Bright Data MCP](https://composio.dev/toolkits/brightdata_mcp) - Bright Data MCP is an AI-powered web scraping and data collection platform. Instantly access public web data in real time with advanced scraping tools.
- [Browseai](https://composio.dev/toolkits/browseai) - Browseai is a web automation and data extraction platform that turns any website into an API. It's perfect for monitoring websites and retrieving structured data without manual scraping.
- [ClickHouse](https://composio.dev/toolkits/clickhouse) - ClickHouse is an open-source, column-oriented database for real-time analytics and big data processing using SQL. Its lightning-fast query performance makes it ideal for handling large datasets and delivering instant insights.
- [Coinmarketcal](https://composio.dev/toolkits/coinmarketcal) - CoinMarketCal is a community-powered crypto calendar for upcoming events, announcements, and releases. It helps traders track market-moving developments and stay ahead in the crypto space.
- [Control d](https://composio.dev/toolkits/control_d) - Control d is a customizable DNS filtering and traffic redirection platform. It helps you manage internet access, enforce policies, and monitor usage across devices and networks.
- [Databox](https://composio.dev/toolkits/databox) - Databox is a business analytics platform that connects your data from any tool and device. It helps you track KPIs, build dashboards, and discover actionable insights.
- [Databricks](https://composio.dev/toolkits/databricks) - Databricks is a unified analytics platform for big data and AI on the lakehouse architecture. It empowers data teams to collaborate, analyze, and build scalable solutions efficiently.
- [Datagma](https://composio.dev/toolkits/datagma) - Datagma delivers data intelligence and analytics for business growth and market discovery. Get actionable market insights and track competitors to inform your strategy.
- [Delighted](https://composio.dev/toolkits/delighted) - Delighted is a customer feedback platform based on the Net Promoter System®. It helps you quickly gather, track, and act on customer sentiment.
- [Dovetail](https://composio.dev/toolkits/dovetail) - Dovetail is a research analysis platform for transcript review and insight generation. It helps teams code interviews, analyze feedback, and create actionable research summaries.
- [Dub](https://composio.dev/toolkits/dub) - Dub is a short link management platform with analytics and API access. Use it to easily create, manage, and track branded short links for your business.
- [Fireflies](https://composio.dev/toolkits/fireflies) - Fireflies.ai is an AI-powered meeting assistant that records, transcribes, and analyzes voice conversations. It helps teams capture call notes automatically and search or summarize meetings effortlessly.
- [Google Analytics](https://composio.dev/toolkits/google_analytics) - Google Analytics tracks and reports website traffic, user behavior, and conversions. It helps marketers optimize performance and understand customer journeys.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Serpapi MCP?

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

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

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

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