How to integrate Dnsfilter MCP with Vercel AI SDK v6

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Dnsfilter logo
Vercel AI SDK logo
divider

Introduction

This guide walks you through connecting Dnsfilter to Vercel AI SDK v6 using the Composio tool router. By the end, you'll have a working Dnsfilter agent that can list all ip addresses in your network, retrieve billing information for your organization, get details for a specific filtering category through natural language commands.

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

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

Also integrate Dnsfilter with

TL;DR

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

The Dnsfilter MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Dnsfilter account. It provides structured and secure access to your DNSFilter environment, so your agent can perform actions like listing IPs, retrieving categories, managing network devices, and accessing billing information on your behalf.

  • Comprehensive IP address management: Direct your agent to list, fetch, or create IP address entries for your networks, streamlining network administration.
  • Efficient category and content filtering: Have your agent retrieve details for specific filtering categories or list all available content categories to fine-tune organizational policies.
  • Network device inventory automation: Ask your agent to list all MAC addresses and applications in your environment, making it easy to keep track of connected devices and services.
  • Application category insight: Instantly access information about application categories or retrieve all application categories to stay updated on your filtering options.
  • Billing information access: Let your agent pull detailed billing information for your organization, supporting audits and automated reporting workflows.

Supported Tools & Triggers

Tools
Add Allowed ApplicationAdds a single application to the allow list of a policy in DNSFilter.
Add Allowlist Domains to PoliciesTool to bulk add one or more domains to one or more policies' allow lists.
Add Blacklist Category To PolicyTool to add a single category to a policy's blocklist.
Add Blacklist Domain To PolicyTool to add a single domain to a policy's blocklist.
Add Blocked ApplicationAdds a single application to the block list of a policy in DNSFilter.
Add Blocklist Domains To PoliciesTool to add one or more domains to the blocklist of multiple policies at once.
Add Whitelist DomainTool to add a single domain to a policy's allowlist.
Cancel OrganizationSets an organization as 'Canceled' in DNSFilter by its unique ID.
Check User Agent Bulk Updates Has MixedCheck if user agent attributes are mixed in a bulk selection.
Create API KeysCreates a new API key in DNSFilter for authentication and API access.
Create CyberSight CSV ExportCreates a CyberSight CSV export record to track export of CyberSight report information.
Create IP AddressCreates a new IP address entry in DNSFilter for network filtering and policy enforcement.
Create MAC AddressCreates a new MAC address entry in DNSFilter with the specified data.
Create NetworksCreates a new network with the specified configuration in DNSFilter.
Bulk Create NetworksBulk create multiple networks in DNSFilter with a single API call.
Create Organization UserAdds a new or existing user with the specified email to an organization in DNSFilter.
Create PoliciesCreates a new DNS filtering policy with the specified configuration in DNSFilter.
Create Scheduled PolicyCreates a new scheduled (time-based) policy in DNSFilter.
Create Scheduled Report PreviewsCreates a scheduled report preview for an organization, triggering background generation of the report.
Create Scheduled ReportCreates a scheduled report in DNSFilter to automate regular delivery of network activity and security summaries.
Create User Agent Bulk DeletesCreate a user agent bulk delete operation in DNSFilter.
Create User Agent CleanupCreates a user agent cleanup to track bulk deletion of inactive user agents in DNSFilter.
Delete API KeyTool to remove an API key by its ID.
Delete IP AddressRemoves an IP address from DNSFilter by its unique ID.
Delete MAC AddressDeletes a MAC address entry from DNSFilter by its ID.
Delete Networks (Bulk)Bulk destroy multiple networks in DNSFilter.
Delete PoliciesDeletes a DNS filtering policy from DNSFilter by its unique ID.
Delete Scheduled PoliciesRemoves a scheduled policy from the DNSFilter database by its unique ID.
Delete Scheduled ReportTool to delete a scheduled report by its ID.
Get API KeyTool to retrieve detailed information about a specific API key by its ID.
Get Application CategoryRetrieves detailed information about a specific DNSFilter application category by its ID.
Get Billing AddressRetrieves the billing address for a specific DNSFilter organization.
Get Billing InformationRetrieves billing records for a specific DNSFilter organization.
Get CategoryTool to get basic information of a specific category.
Get IP AddressRetrieves detailed information for a specific IP address record by its ID.
Get MAC AddressRetrieves detailed information for a specific MAC address record by its ID.
Get Organization Usage MetricsRetrieves usage metrics for a DNSFilter organization over a specified date range.
Get Organization Usage Detailed MetricsRetrieves detailed usage metrics for a specific DNSFilter organization.
Get My IP AddressTool to retrieve the requester's IP address as reported by DNSFilter API.
Get Networks Bulk Create StatusTool to check the status of a bulk network creation job.
Get Networks Bulk Destroy StatusCheck the status of a bulk network destroy operation.
Get Networks Bulk Update StatusCheck the status of a bulk network update job.
Get Networks CSV ExportRetrieves a networks CSV export by its ID.
Get NotesTool to retrieve notes associated with a specific resource (policy, MSP, or organization) and domain.
Get OrganizationTool to get basic information of a specific organization by ID.
Get Organization UserTool to retrieve user details and permissions for a specific organization.
Get PolicyTool to get basic information of the specified policy.
Get Policy Permissive ModeTool to retrieve the permissive mode setting for a specific policy.
Get Policy IPRetrieves basic information for a specific Policy IP by its ID.
Get Scheduled Report PreviewTool to retrieve a specific scheduled report preview by its ID.
Get UserTool to get basic information of a specified user by ID.
Get User Agent CleanupTool to get the specific user agent cleanup by ID.
Get User Agent CSV ExportTool to retrieve a specific user agent CSV export by its ID.
Get User Agents Uninstall PINTool to get the uninstall PIN for an organization's user agents.
List All Agent Local UsersGet all agent local users associated with a user organization.
List All Block PagesRetrieves all block pages associated with the current user.
List All IP AddressesRetrieves one page of IP addresses across all networks in your organization.
List API KeysRetrieves the list of API keys associated with the authenticated user.
List Application CategoriesRetrieves all available application categories from DNSFilter.
List All ApplicationsTool to list all applications basic information including deleted ones.
List BillingRetrieve payment method information from Stripe for a DNSFilter organization.
List All Categories (Including Internal)Tool to list all categories including internal categories from DNSFilter.
List Current UserTool to fetch information about the currently authenticated user.
List CyberSight Activity TypesTool to retrieve all available CyberSight activity types.
List Domains Bulk LookupRetrieves domain information and category classifications for multiple FQDNs in a single request.
List Domains User LookupTool to look up all domains associated with a particular FQDN.
List Enterprise ConnectionsList all enterprise connections for a DNSFilter organization.
List InvoicesRetrieves billing invoices for a DNSFilter organization with pagination and sorting support.
List All IP Addresses (All Endpoint)Tool to retrieve all user-associated IP addresses with basic information.
List MAC AddressesTool to list MAC addresses associated with an organization.
List All NetworksTool to retrieve ALL networks associated with the user with basic information.
List Networks GeoTool to retrieve networks with geographical information only.
List All MSP NetworksTool to retrieve ALL networks associated with the MSP user with basic information.
List Network SubnetsTool to retrieve subnets associated with a specific network.
List All OrganizationsTool to get all organizations with optional filtering by type, MSP relationships, or name.
List Organizations SettingsTool to get basic information and settings of the specified organization.
List Organization UsersTool to get the users for a specified organization.
List PoliciesTool to retrieve basic information about user-associated policies.
List All PoliciesTool to retrieve ALL user-associated policies with basic information.
List Policies for ApplicationTool to retrieve policies information for a specific application.
List Policy IPsList policy IPs in your DNSFilter organization.
List QP MethodsTool to list all QP (Query Protection) methods available in DNSFilter.
List All Scheduled PoliciesTool to retrieve ALL scheduled policies associated with the current user.
List Traffic Reports QPSGet queries per second (QPS) metrics for DNS traffic over a specified time period.
List Traffic Reports QPS Active AgentsGet queries per second (QPS) statistics for roaming clients over a time period.
List Traffic Reports QPS Active CollectionsTool to retrieve queries per second (QPS) metrics for active collections over a specified time period.
List Traffic Reports QPS Active OrganizationsRetrieves the total number of queries per second (QPS) over a time period for active organizations.
List Traffic Reports QPS Active UsersGet the total number of queries per second (QPS) in a time period (maximum 20 minutes) for active users.
List Traffic Reports Query LogsGet query raw logs from DNSFilter traffic reports in a specified period of time.
List Traffic Reports Top AgentsGet the top user agents by DNS traffic volume in a specified time period.
List Traffic Reports Top Application CategoriesGet the top application categories domains in a period of time.
List Traffic Reports Top CategoriesGet the top domain categories accessed during a specified time period.
List Traffic Reports Top CollectionsTool to retrieve the top collections by traffic volume over a specified time period.
List Traffic Reports Top DomainsGet the top requested domains over a specified time period.
List Traffic Reports Top NetworksGet the top networks ranked by DNS traffic volume over a specified time period.
List Traffic Reports Top OrganizationsGets the top organizations by DNS traffic volume over a specified time period.
List Top Organizations by RequestsGet the top organizations ranked by total number of DNS requests over a specified time period.
List Traffic Reports Top UsersGet the top users by DNS query volume over a specified time period.
List Traffic Reports Total Applications StatsGet statistics of number of requests by application in a time period.
List Traffic Reports Total Applications Agents StatsGet statistics of number of requests for roaming clients by application in a period of time.
List Traffic Reports Total Applications Collections StatsGet statistics of number of requests for collections by application over a specified time period.
List Traffic Reports Total Applications Networks StatsGet statistics showing the number of requests for sites by application across networks over a specified time period.
List Traffic Reports Total Applications OrganizationsTool to get statistics of number of requests for organizations by application in a period of time.
List Traffic Reports Total Applications Users StatsGet statistics of the number of requests for users by application within a specified time period.
List Traffic Reports Total CategoriesGet the total number of requests by category for sites in a period of time.
List Traffic Reports Total Categories for AgentsGet the total number of requests by category for roaming clients (user agents) during a specified time period.
List Traffic Reports Total Categories CollectionsGet the total number of DNS requests by category for collections over a specified time period.
List Total Categories by OrganizationsGet the total number of DNS requests by category for organizations over a specified time period.
List Traffic Reports by Category for UsersGets the total number of DNS requests by category for users in a specified time period.
List Traffic Reports Total Category StatsTool to get the total number of stats for a category in a period of time.
List Traffic Reports Total Client StatsGets the organization network, users and client stats from traffic reports.
List Traffic Reports Total CollectionsGet the total number of DNS requests by collection for sites over a specified time period.
List Traffic Reports Total Collections AgentsGet the total number of requests by collection for roaming clients over a specified time period.
List Traffic Reports Total Collections OrganizationsGet the total number of DNS requests by collection for organizations over a specified time period.
List Traffic Reports Total Collections UsersGet the total number of DNS requests by collection for users over a specified time period.
List Traffic Reports Total DeploymentsGets the organization deployments information including collections, relays, sync tools, user agents, and users.
List Traffic Reports Total Domain RequestsGet the total number of requests for a domain over a specified time period.
List Traffic Reports Total DomainsGet the total number of requests by domain for sites in a period of time.
List Traffic Reports Total Domains CollectionsTool to retrieve the total number of DNS requests by domain for collections within a specified time period.
List Total Domains by OrganizationsGet the total number of DNS requests by domain for organizations over a specified time period.
List Traffic Reports Total Domain StatsTool to get the total number of stats for a domain in a period of time.
List Traffic Reports Total Domains UsersGets the total number of DNS requests by domain for users in a period of time.
List Total Organizations RequestsGet the total number of DNS requests for organizations in a specified time period.
List Traffic Reports Total Organizations StatsRetrieves aggregated DNS traffic statistics across organizations for a specified time period.
List Traffic Reports Total RequestsGet the total number of DNS requests over a specified time period.
List Traffic Reports Total Requests for AgentsGet the total number of requests for roaming clients (user agents) during a specified time period.
List Traffic Reports Total Requests CollectionsGet the total number of requests for collections over a specified time period.
List Traffic Reports Total Requests GeoGets the total number of DNS requests by geographic location for organizations in a specified time period.
List Total Requests OrganizationsGet the total number of DNS requests for organizations in a specified time period.
List Traffic Reports Total Requests UsersGets the total number of requests for users in a period of time.
List Traffic Reports Total Roaming ClientsGets the roaming clients information for the specified organization.
List Traffic Reports Total ThreatsGet the total number of threats detected over a specified time period.
List Traffic Reports Total Threats AgentsGet the total number of threats for roaming clients in a period of time.
List Total Threats by CollectionsTool to retrieve the total number of threats for collections over a specified time period.
List Total Threats by OrganizationsGet the total number of threats detected for organizations over a specified time period.
List Traffic Reports Total Threats UsersGet the total number of threats for users in a period of time.
List User Agent Bulk Deletes CountsTool to get user agent bulk delete counts by filtering criteria.
List User Agent Bulk Updates CountsTool to get user agent bulk delete counts by filters.
List User Agent ReleasesGets a list of latest user agent releases for each unique combination of agent_type, architecture, release_channels, and white label.
List User Agent Releases RelayTool to get a list of latest relay releases for each unique combination of architecture, release channels, and white label.
List All User AgentsTool to retrieve ALL user agents with basic information.
List User Agents CountsTool to get counts of user agents for each status.
List User Agents CSVTool to export user agents as CSV data for a specific organization.
List User Agent TagsRetrieves all tags used by user agents on a network or organization.
List All UsersTool to get all users basic information with optional pagination.
Lookup Network By IPTool to get basic network information based on an IP address lookup.
Remove Allowed ApplicationRemoves a single application from the allow list of a policy in DNSFilter.
Remove Allowlist Domains from PoliciesTool to remove one or more domains from one or more policies' allow lists.
Remove Blacklist CategoryTool to remove a single category from a policy's blocklist.
Remove Blacklist Domain From PolicyTool to remove a single domain from a policy's blocklist.
Remove Blocked ApplicationRemoves a single application from the block list of a policy in DNSFilter.
Remove Blocklist DomainsTool to remove one or more domains from one or more policy block lists in bulk.
Remove Whitelist Domain from PolicyTool to remove a single domain from a policy's whitelist/allowlist.
Resend User InviteTool to resend an invitation email to a user in a DNSFilter organization.
Suggest Domain ThreatSubmit a domain threat report to DNSFilter for review and potential threat categorization.
Update Billing AddressUpdates the billing address for a DNSFilter organization.
Update Current UserUpdates profile attributes for the currently authenticated DNSFilter user.
Update Enterprise ConnectionUpdates an existing enterprise connection for SSO authentication in DNSFilter.
Update IP AddressUpdates an existing IP address record in DNSFilter with new data.
Update MAC AddressUpdates an existing MAC address entry in DNSFilter with new configuration.
Bulk Update NetworksTool to bulk update multiple networks with specified configuration changes.
Update OrganizationsUpdates an existing organization with the specified data in DNSFilter.
Update Organization UserUpdates a user or permissions within an organization in DNSFilter.
Update PoliciesUpdates an existing DNS filtering policy with the specified configuration in DNSFilter.
Update Policies ApplicationUpdates a policy with the specified application data, configuring which policies allow or block access to an application.
Update Policy Permissive ModeTool to update the permissive mode setting for a specific policy.
Update Scheduled PoliciesUpdates an existing scheduled policy in DNSFilter with the specified data.
Update Scheduled ReportsUpdates an existing scheduled report configuration in DNSFilter.
Update User Agent CleanupsUpdates a user agent cleanup operation in DNSFilter.
Validate Auth0 JWTTool to validate a JWT with Auth0.

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

What is Composio SDK?

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

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

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

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

Step-by-step Guide

Prerequisites

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

Getting API Keys for OpenAI and Composio

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

Install required dependencies

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

First, install the necessary packages for your project.

What you're installing:

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

Set up environment variables

bash
OPENAI_API_KEY=your_openai_api_key_here
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here

Create a .env file in your project root.

What's needed:

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

Import required modules and validate environment

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

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

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

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

Create Tool Router session and initialize MCP client

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

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

Connect to MCP server and retrieve tools

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

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

Initialize conversation and CLI interface

typescript
let messages: ModelMessage[] = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • We use streamText instead of generateText to stream responses in real-time
  • toolChoice: "auto" allows the model to decide when to use Dnsfilter 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 Dnsfilter 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: ["dnsfilter"],
  });

  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 dnsfilter, 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 Dnsfilter 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 Dnsfilter MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Dnsfilter MCP?

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

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

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

Used by agents from

Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.