# How to integrate Serpapi MCP with Claude Agent SDK

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

## Introduction

This guide walks you through connecting Serpapi to the Claude Agent SDK 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 Claude Agent 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 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)
- [Vercel AI SDK](https://composio.dev/toolkits/serpapi/framework/ai-sdk)
- [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:
- Get and set up your Claude/Anthropic and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for Serpapi
- Configure an AI agent that can use Serpapi as a tool
- Run a live chat session where you can ask the agent to perform Serpapi operations

## What is Claude Agent SDK?

The Claude Agent SDK is Anthropic's official framework for building AI agents powered by Claude. It provides a streamlined interface for creating agents with MCP tool support and conversation management.
Key features include:
- Native MCP Support: Built-in support for Model Context Protocol servers
- Permission Modes: Control tool execution permissions
- Streaming Responses: Real-time response streaming for interactive applications
- Context Manager: Clean async context management for sessions

## 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 starting, make sure you have:
- Composio API Key and Claude/Anthropic API Key
- Primary know-how of Claude Agents SDK
- A Serpapi account
- Some knowledge of Python

### 1. Getting API Keys for Claude/Anthropic and Composio

Claude/Anthropic API Key
- Go to the [Anthropic Console](https://console.anthropic.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models.
- 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 dependencies

No description provided.
```python
pip install composio-anthropic claude-agent-sdk python-dotenv
```

```typescript
npm install @anthropic-ai/claude-agent-sdk @composio/core dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates with Composio
- USER_ID identifies the user for session management
- ANTHROPIC_API_KEY authenticates with Anthropic/Claude
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here
```

### 4. Import dependencies

No description provided.
```python
import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
import os
from composio import Composio
from dotenv import load_dotenv

load_dotenv()
```

```typescript
import 'dotenv/config';
import readline from 'node:readline';
import { Composio } from '@composio/core';
import { query, type Options } from "@anthropic-ai/claude-agent-sdk";

dotenv.config();
```

### 5. Create a Composio instance and Tool Router session

No description provided.
```python
async def chat_with_remote_mcp():
    api_key = os.getenv("COMPOSIO_API_KEY")
    if not api_key:
        raise RuntimeError("COMPOSIO_API_KEY is not set")

    composio = Composio(api_key=api_key)

    # Create Tool Router session for Serpapi
    mcp_server = composio.create(
        user_id=os.getenv("USER_ID"),
        toolkits=["serpapi"]
    )

    url = mcp_server.mcp.url

    if not url:
        raise ValueError("Session URL not found")
```

```typescript
async function chat() {
  const { COMPOSIO_API_KEY, USER_ID } = process.env;
  if (!COMPOSIO_API_KEY || !USER_ID) {
    throw new Error('COMPOSIO_API_KEY and USER_ID required in .env');
  }

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

  // Create Tool Router session for Serpapi
  const session = await composio.create(USER_ID, {
    toolkits: ['serpapi'],
  });
  const mcpUrl = session?.mcp.url;
```

### 6. Configure Claude Agent with MCP

No description provided.
```python
# Configure remote MCP server for Claude
options = ClaudeAgentOptions(
    permission_mode="bypassPermissions",
    mcp_servers={
        "composio": {
            "type": "http",
            "url": url,
            "headers": {
                "x-api-key": os.getenv("COMPOSIO_API_KEY")
            }
        }
    },
    system_prompt="You are a helpful assistant with access to Serpapi tools via Composio.",
    max_turns=10
)
```

```typescript
const options: Options = {
  permissionMode: 'bypassPermissions',
  mcpServers: {
    composio: {
      type: 'http',
      url: mcpUrl,
      headers: { 'x-api-key': COMPOSIO_API_KEY }
    }
  },
  systemPrompt: 'You are a helpful assistant with access to Serpapi tools via Composio.',
  maxTurns: 10,
};
```

### 7. Create client and start chat loop

No description provided.
```python
# Create client with context manager
async with ClaudeSDKClient(options=options) as client:
    print("\nChat started. Type 'exit' or 'quit' to end.\n")

    # Main chat loop
    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit"}:
            print("Goodbye!")
            break

        # Send query
        await client.query(user_input)

        # Receive and print response
        print("Claude: ", end="", flush=True)
        async for message in client.receive_response():
            if hasattr(message, "content"):
                for block in message.content:
                    if hasattr(block, "text"):
                        print(block.text, end="", flush=True)
        print()
```

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

  console.log('\nChat started. Type "exit" to quit.\n');

  let isProcessing = false;

  async function ask(prompt: string) {
    isProcessing = true;
    rl.pause();

    process.stdout.write('Claude is thinking...');
    const stream = query({ prompt, options });

    let firstChunk = true;
    for await (const msg of stream) {
      const content = (msg as any).message?.content || (msg as any).content;
      if (Array.isArray(content)) {
        for (const block of content) {
          if (block.type === 'text' && block.text) {
            if (firstChunk) {
              process.stdout.write('\r\x1b[K');
              process.stdout.write('Claude: ');
              firstChunk = false;
            }
            process.stdout.write(block.text);
          }
        }
      }
    }
    process.stdout.write('\n\n');

    isProcessing = false;
    rl.resume();
    rl.prompt();
  }

  rl.on('line', async (line) => {
    if (isProcessing) return;

    const input = line.trim();
    if (input === 'exit') {
      rl.close();
      process.exit(0);
    }
    if (input) await ask(input);
    else rl.prompt();
  });

  await ask('What can you help me with?');
}
```

### 8. Run the application

No description provided.
```python
if __name__ == "__main__":
    asyncio.run(chat_with_remote_mcp())
```

```typescript
try {
  await chat();
} catch (error) {
  console.error(error);
  process.exit(1);
}
```

## Complete Code

```python
import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions
import os
from composio import Composio
from dotenv import load_dotenv

load_dotenv()

async def chat_with_remote_mcp():
    api_key = os.getenv("COMPOSIO_API_KEY")
    if not api_key:
        raise RuntimeError("COMPOSIO_API_KEY is not set")

    composio = Composio(api_key=api_key)

    # Create Tool Router session for Serpapi
    mcp_server = composio.create(
        user_id=os.getenv("USER_ID"),
        toolkits=["serpapi"]
    )

    url = mcp_server.mcp.url

    if not url:
        raise ValueError("Session URL not found")

    # Configure remote MCP server for Claude
    options = ClaudeAgentOptions(
        permission_mode="bypassPermissions",
        mcp_servers={
            "composio": {
                "type": "http",
                "url": url,
                "headers": {
                    "x-api-key": os.getenv("COMPOSIO_API_KEY")
                }
            }
        },
        system_prompt="You are a helpful assistant with access to Serpapi tools via Composio.",
        max_turns=10
    )

    # Create client with context manager
    async with ClaudeSDKClient(options=options) as client:
        print("\nChat started. Type 'exit' or 'quit' to end.\n")

        # Main chat loop
        while True:
            user_input = input("You: ").strip()
            if user_input.lower() in {"exit", "quit"}:
                print("Goodbye!")
                break

            # Send query
            await client.query(user_input)

            # Receive and print response
            print("Claude: ", end="", flush=True)
            async for message in client.receive_response():
                if hasattr(message, "content"):
                    for block in message.content:
                        if hasattr(block, "text"):
                            print(block.text, end="", flush=True)
            print()

if __name__ == "__main__":
    asyncio.run(chat_with_remote_mcp())
```

```typescript
import 'dotenv/config';
import readline from 'node:readline';
import { Composio } from '@composio/core';
import { query, type Options } from "@anthropic-ai/claude-agent-sdk";

async function chat() {
  const { COMPOSIO_API_KEY, USER_ID } = process.env;
  if (!COMPOSIO_API_KEY || !USER_ID) {
    throw new Error('COMPOSIO_API_KEY and USER_ID required in .env');
  }

  const composio = new Composio({ apiKey: COMPOSIO_API_KEY });
  const session = await composio.create(USER_ID, {
    toolkits: ['serpapi']
  });
  const mcp_url = session?.mcp.url;

  const options: Options = {
    permissionMode: 'bypassPermissions',
    mcpServers: {
      composio: {
        type: 'http',
        url: mcp_url,
        headers: { 'x-api-key': COMPOSIO_API_KEY }
      }
    },
    systemPrompt: 'You are a helpful assistant with access to Serpapi tools via Composio.',
    maxTurns: 10,
  };

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

  console.log('\nChat started. Type "exit" to quit.\n');

  let isProcessing = false;

  async function ask(prompt: string) {
    isProcessing = true;
    rl.pause();

    process.stdout.write('Claude is thinking...');
    const stream = query({ prompt, options });

    let firstChunk = true;
    for await (const msg of stream) {
      const content = (msg as any).message?.content || (msg as any).content;
      if (Array.isArray(content)) {
        for (const block of content) {
          if (block.type === 'text' && block.text) {
            if (firstChunk) {
              process.stdout.write('\r\x1b[K');
              process.stdout.write('Claude: ');
              firstChunk = false;
            }
            process.stdout.write(block.text);
          }
        }
      }
    }
    process.stdout.write('\n\n');

    isProcessing = false;
    rl.resume();
    rl.prompt();
  }

  rl.on('line', async (line) => {
    if (isProcessing) return;

    const input = line.trim();
    if (input === 'exit') {
      rl.close();
      process.exit(0);
    }
    if (input) await ask(input);
    else rl.prompt();
  });

  await ask('What can you help me with?');
}

try {
  await chat();
} catch (error) {
  console.error(error);
  process.exit(1);
}
```

## Conclusion

You've successfully built a Claude Agent SDK agent that can interact with Serpapi through Composio's Tool Router.
Key features:
- Native MCP support through Claude's agent framework
- Streaming responses for real-time interaction
- Permission bypass for smooth automated workflows
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## 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 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)
- [Vercel AI SDK](https://composio.dev/toolkits/serpapi/framework/ai-sdk)
- [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 Claude Agent SDK?

Yes, you can. Claude Agent SDK 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)
