How to integrate Kadoa MCP with Vercel AI SDK v6

This guide walks you through connecting Kadoa to Vercel AI SDK v6 using the Composio tool router. By the end, you'll have a working Kadoa agent that can fetch the latest data from your workflow, check crawl status for session abc123, list all pages crawled in last run through natural language commands. This guide will help you understand how to give your Vercel AI SDK agent real control over a Kadoa account through Composio's Kadoa MCP server. Before we dive in, let's take a quick look at the key ideas and tools involved.

Kadoa logoKadoa
Api Key

Kadoa is an API-first platform for building and managing workflows that extract data from unstructured sources. It helps automate and monitor extraction tasks at scale.

77 Tools

Introduction

This guide walks you through connecting Kadoa to Vercel AI SDK v6 using the Composio tool router. By the end, you'll have a working Kadoa agent that can fetch the latest data from your workflow, check crawl status for session abc123, list all pages crawled in last run through natural language commands.

This guide will help you understand how to give your Vercel AI SDK agent real control over a Kadoa account through Composio's Kadoa MCP server.

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

Also integrate Kadoa with

TL;DR

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

The Kadoa MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Kadoa account. It provides structured and secure access to your data extraction workflows, so your agent can launch crawls, monitor sessions, retrieve extracted data, and manage workflow configurations automatically on your behalf.

  • Automated workflow monitoring and management: Ask your agent to fetch workflow configurations, enable data validation, or get the latest results from any extraction workflow you have set up.
  • Crawling session control: Have your agent check the status of crawl sessions, list all crawled pages, and pull the raw content (HTML or Markdown) from any page processed by a workflow.
  • Notification channel setup and retrieval: Direct your agent to create notification channels, list available notification event types, and fetch specific channel configurations for streamlined alerting.
  • Location and environment awareness: Let your agent retrieve all supported locations to ensure workflows run in the right environment before launching new extraction jobs.
  • Seamless data access: Instruct your agent to quickly get the most recent data output from any workflow, keeping your automations and dashboards always up to date.

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

What is Composio SDK?

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

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

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

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

Step-by-step Guide

Step by step09 STEPS
1

Prerequisites

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

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.
3

Install 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
4

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
5

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
6

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

  const mcpUrl = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Kadoa 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 Kadoa-related tools through the MCP protocol
7

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 Kadoa tools that the agent can use
8

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 kadoa, 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
9

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

  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 kadoa, 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 Kadoa 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.
TOOLS

Supported Tools

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

Bulk Approve Validation Rules

Tool to bulk approve preview validation rules for a workflow.

Create Crawl Config

Tool to create a new crawling configuration in Kadoa.

Create Notification Channel

Tool to create a notification channel for alerts delivery.

Create Schema

Create a new data schema with specified fields and entity type.

Create Support Issue

Tool to create a support ticket in Kadoa.

Create Workflow Trigger

Tool to create a trigger that fires when a source workflow emits an event.

Delete All Validation Rules

Tool to soft-delete all validation rules for a specific workflow with optional audit trail.

Delete Crawl Configuration

Tool to delete a crawling configuration by its config ID.

Delete Notification Channel

Tool to delete a notification channel by its ID.

Delete Schema

Tool to delete a schema and all its revisions.

Delete Validation Rule

Tool to delete a validation rule from a Kadoa workflow.

Delete Validation Rules (Bulk)

Tool to bulk delete multiple validation rules for a workflow.

Delete Workflow

Delete a workflow permanently from your Kadoa account.

Delete Workflow Trigger

Tool to delete a trigger from a Kadoa workflow.

Disable Validation Rule

Tool to disable a validation rule with a mandatory reason.

Enable Data Validation

Tool to enable data validation on a specified workflow.

Execute Bulk Workflow Operations

Execute actions on multiple workflows at once.

Export Activity Events

Tool to export activity events from audit logs to CSV format for compliance and audit purposes.

Export Activity Workflows

Tool to export workflow configurations and metadata as CSV for portfolio reviews and compliance reporting.

Get Workflow by ID

Retrieve detailed configuration of a workflow by its ID.

Get all locations

Retrieves all available scraping proxy locations (countries) supported by Kadoa.

Get Crawl Bucket Data

Tool to retrieve file content from the Kadoa crawling bucket (HTML or screenshot).

Get Crawl Configuration

Tool to retrieve a crawling configuration by its ID.

Get Crawled Page Content

Tool to retrieve content of a crawled page.

Get Crawled Pages

Tool to list pages crawled during a session.

Get Crawl Status

Tool to fetch current status of a crawling session.

Get Event Type Details

Tool to retrieve details for a specific notification event type.

Get Notification Event Types

Tool to retrieve supported notification event types.

Get Latest Workflow Data

Retrieves the extracted data from a Kadoa workflow's most recent run (or a specific run if runId is provided).

Get Latest Workflow Validation

Retrieves the latest validation results for the most recent job of a workflow.

Get Notification Channel

Tool to retrieve details of a specific notification channel.

Get Notification Logs

Tool to retrieve notification event logs with optional filtering by workflow, event type, and date range.

Get Notification Setting

Retrieves a specific notification setting by its unique identifier.

Get Schema by ID

Retrieve a specific schema by its unique identifier.

Get Validation Anomalies

Tool to retrieve all anomalies for a specific validation.

Get Validation Anomalies By Rule

Tool to retrieve anomalies for a specific validation rule.

Get Validation Configuration

Tool to retrieve the data validation configuration for a specific workflow.

Get Validation Rule

Tool to retrieve a specific validation rule by its ID.

Get Workflow Audit Log

Retrieve audit log entries for a workflow.

Get Workflow Job

Tool to retrieve the current status and telemetry information for a specific workflow job.

Get Workflow Run History

Tool to fetch workflow run history.

Get Workflows

Retrieve a paginated list of workflows with optional filtering.

Get Workflow Trigger

Tool to retrieve a specific trigger for a workflow.

Get Workflow Validation Results

Retrieves the latest validation results for a specific workflow job.

Get Workspace Details

Tool to retrieve detailed information about a workspace (user, team, or organization).

List Activity Events

Tool to retrieve activity events from audit logs with basic filtering and pagination.

List Changes

Tool to retrieve all data changes detected across workflows in your Kadoa account.

List Crawl Sessions

Tool to retrieve a paginated list of crawling sessions with optional filtering.

List Job Validations

Tool to list all validation runs for a specific job with pagination support.

List Notification Channels

Tool to retrieve all notification channels configured for the account.

List Notification Settings

Tool to retrieve all notification settings, with optional filtering by workflow ID or event type.

List Schemas

Tool to retrieve all schemas accessible by the authenticated user.

List Support States

Tool to retrieve available support issue states.

List Validation Rules

Tool to list all data validation rules with optional pagination and filtering.

List Workflow Triggers

Tool to get all triggers where the specified workflow is the source.

Pause Crawl Session

Tool to pause an active crawling session.

Pause Workflow

Tool to pause a running or scheduled workflow.

Create Advanced Workflow

Tool to create an advanced workflow.

Start Crawl Session

Starts a new web crawling session to crawl and index pages from a website.

Create Notification Setting

Tool to create a notification setting linking channels to events.

Send Test Notification

Sends a test notification event to verify notification channel configurations are working correctly.

Subscribe to Webhook Events

Tool to subscribe to specified webhook events.

Create Workflow

Create a new Kadoa web scraping workflow.

Configure Workflow Monitoring

Configure monitoring and scheduling for a Kadoa workflow to detect data changes.

Generate Workflow Validation Rule

Generate an AI-powered data validation rule for a Kadoa workflow.

Update Notification Channel

Tool to update an existing notification channel.

Resume Crawl Session

Tool to resume a paused crawling session.

Resume Workflow

Resumes a paused, preview, or error workflow.

Run Ad-hoc Extraction

Tool to synchronously extract data from a URL using a given template.

Run Workflow

Tool to trigger a workflow to run immediately.

Schedule Validation Job

Tool to schedule a data validation job for a specific workflow job.

Unsubscribe from Webhook Events

Unsubscribe from webhook event notifications by deleting a notification setting.

Update Notification Settings

Tool to update existing notification settings for events.

Update Schema

Tool to update an existing Kadoa schema.

Update Validation Configuration

Tool to update the complete data validation configuration including alerting settings for a specific workflow.

Update Workflow Metadata

Tool to update workflow metadata such as name, description, tags, and configuration settings.

Update Workflow Trigger

Tool to update trigger properties including event type and enabled status.

FAQ

Frequently asked questions

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

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 Kadoa tools.

Yes, absolutely. You can configure which Kadoa scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Kadoa data and credentials are handled as safely as possible.

Start with Kadoa.It takes 30 seconds.

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

Start building