How to integrate Moco MCP with Vercel AI SDK v6

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Moco logo
Vercel AI SDK logo
divider

Introduction

This guide walks you through connecting Moco to Vercel AI SDK v6 using the Composio tool router. By the end, you'll have a working Moco agent that can list activities tracked for this week, create a new company called greentech, get details for deal with id 456 through natural language commands.

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

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

Also integrate Moco with

TL;DR

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

The Moco MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Moco account. It provides structured and secure access to your business and project management data, so your agent can manage time tracking, handle deals, organize contacts, and update project activities on your behalf.

  • Automated time tracking and activity management: Let your agent list, retrieve, and update time entries, so tracking billable hours and project work is effortless.
  • Deal and pipeline automation: Ask your agent to fetch deal details, delete obsolete deals, or reference available deal categories to keep your sales pipeline up to date.
  • Comprehensive contact and company organization: Have your agent list contacts, add new companies, or delete companies as your business relationships evolve.
  • Comment retrieval for collaboration: Retrieve and review comments on various resources, helping your team stay in sync and informed.
  • Flexible project and resource control: Use your agent to access and manage project-related information, so you can stay organized without manual data entry.

Supported Tools & Triggers

Tools
Activate Offer Customer ApprovalTool to activate customer approval on an offer to generate the offer_document_url.
List ActivitiesRetrieves a list of activities (time entries) from MOCO.
Get ActivityTool to retrieve a single activity by ID.
Update ActivityTool to update an existing activity.
Assign OfferTool to assign an offer to a project, company, or deal.
Assign Purchase to ProjectTool to assign a purchase item to a project by creating or linking to an expense.
List commentsTool to retrieve a list of comments.
Create CompanyCreates a new company in MOCO (customer, supplier, or organization).
Delete a companyTool to delete a company.
List ContactsTool to retrieve a list of contacts.
Create Account Catalog ServiceTool to create a catalog service including its items.
Create Catalog Service ItemTool to create a new item within a catalog service in MOCO.
Create Account Custom PropertyTool to create a new custom property in MOCO.
Create Activities BulkTool to bulk create multiple activities (time entries) at once in MOCO.
Create ActivityTool to create a new activity (time tracking entry) in MOCO.
Create CommentTool to create a new comment on a MOCO resource.
Create Comments BulkTool to create multiple comments in bulk for MOCO objects.
Create ContactTool to create a new contact person in MOCO.
Create DealTool to create a new deal in MOCO.
Create Deal CategoryCreates a new deal category in MOCO with a name and probability percentage.
Create EmploymentCreate a new employment (weekly work model) for a user in MOCO.
Create Expense TemplateTool to create a new expense template in MOCO.
Create HolidayCreate a new holiday entry for a user in MOCO.
Add Invoice AttachmentTool to add a PDF attachment to an existing invoice.
Create Invoice Bookkeeping ExportTool to create a new invoice bookkeeping export.
Create Invoice PaymentTool to create a new invoice payment.
Create Invoice ReminderTool to create a new invoice reminder for an existing invoice.
Create Invoice Payments BulkTool to create multiple invoice payments in bulk.
Create OfferTool to create a new offer/proposal.
Create Offer AttachmentTool to upload an attachment to an offer.
Create Project ContractTool to create a new contract (assign staff) for a project in MOCO.
Create Project ExpenseTool to create an additional service entry (expense) on a project.
Create Project Expenses BulkTool to create multiple project expense entries in bulk.
Create Project Payment ScheduleTool to create a payment schedule entry for a project.
Create Recurring Expense on ProjectTool to create a recurring additional services entry on a project in MOCO.
Trigger Recurring ExpenseTool to manually trigger the creation of an expense entry for an active recurring expense ahead of its automatic schedule.
Create Project TaskTool to create a new task (service) for a project in MOCO.
Create Purchase Bookkeeping ExportTool to create a new purchase bookkeeping export.
Create Purchase PaymentTool to create a new purchase payment.
Create Purchase Payments BulkTool to create multiple purchase payments in bulk.
Create ReceiptTool to create a new receipt.
Create ScheduleTool to create a planning entry (absence/schedule).
Create TagTool to create a new tag in MOCO.
Create Task TemplateTool to create a new task template in MOCO.
Create UnitTool to create a new unit/team in MOCO.
Create UserTool to create a new staff member/user in MOCO.
Create Users PresencesTool to create a presence entry (work time tracking) in MOCO.
Toggle User PresenceTool to toggle user presence (clock in/out) in MOCO.
Create Work Time AdjustmentTool to create a new work time adjustment in MOCO.
Deactivate Offer Customer ApprovalTool to deactivate a customer approval on an offer to prevent access and signing.
List Deal CategoriesRetrieves all deal categories configured in MOCO with their IDs, names, probabilities, and timestamps.
Delete DealTool to delete a deal.
Get DealRetrieves detailed information for a specific deal/lead by its ID from MOCO.
List DealsTool to retrieve a list of all deals (leads).
Update DealTool to update an existing deal.
Delete Catalog ServiceTool to delete a catalog service.
Delete Account Custom PropertyTool to delete a custom property in MOCO.
Delete Expense TemplateTool to delete an expense template.
Delete Catalog Service ItemTool to delete an item from a catalog service.
Delete CommentTool to delete a manually created comment.
Delete Contact PersonTool to delete a contact person in MOCO.
Delete Deal CategoryTool to delete a deal category.
Delete InvoiceTool to delete a single invoice.
Delete Invoice PaymentTool to delete an invoice payment.
Delete Offers AttachmentsTool to remove an attachment from an offer.
Delete PresenceTool to delete a presence entry.
Delete ProjectTool to delete a project.
Delete Project Staff AssignmentTool to delete a staff assignment (contract) from a project.
Delete Project ExpenseTool to delete an additional services entry on a project.
Delete Project Payment ScheduleTool to delete a payment schedule from a project.
Delete Project Recurring ExpenseTool to delete a recurring expense from a project.
Delete Project TaskTool to delete a specific task from a project.
Delete All Project TasksTool to bulk delete all deletable tasks on a project.
Delete PurchaseTool to delete a purchase.
Delete Purchase PaymentTool to delete a purchase payment.
Delete ScheduleTool to delete a schedule entry (absence).
Delete TagTool to delete a tag in MOCO.
Delete TaggingsTool to selectively remove tags from an entity.
Delete UserTool to delete a user from MOCO.
Delete EmploymentTool to delete an employment (weekly work model) for a user.
Disable Project ShareTool to deactivate project report sharing.
Mark Project Expenses as BilledTool to mark project expense entries as already billed.
Get Catalog Service ItemTool to retrieve a specific item within a catalog service in MOCO.
Get Account Fixed CostsTool to retrieve all fixed costs from the account.
Get Cashflow ReportTool to retrieve the cashflow report from MOCO.
Get CommentTool to retrieve a single comment by ID.
Get CompanyTool to retrieve a single company by ID from MOCO.
Get ContactTool to retrieve detailed information for a specific contact person by ID from MOCO.
Get Custom PropertyTool to retrieve a single custom property by ID from MOCO.
Get Deal CategoryTool to retrieve a single deal category by ID.
Get EmploymentTool to retrieve a single employment (weekly work model) by ID.
Get HolidayTool to retrieve a single holiday entry by ID.
Get Internal Hourly RatesTool to retrieve all internal hourly rates from the account.
Get InvoiceTool to retrieve a single invoice by ID with full details including items, payments, and reminders.
Get Invoice Bookkeeping ExportTool to retrieve a single invoice bookkeeping export by ID.
Get Invoice PaymentTool to retrieve a single invoice payment by ID.
Get Invoice ReminderTool to retrieve a single invoice reminder by ID.
Get Invoice RemindersTool to retrieve all invoice reminders.
Get Invoice Bookkeeping ExportsTool to retrieve all invoice bookkeeping exports.
Get Invoice ExpensesTool to retrieve all expenses that were invoiced in a particular invoice.
Get Locked InvoicesTool to retrieve all locked invoices.
Get Invoice PaymentsTool to retrieve all invoice payments.
Get Invoice TimesheetTool to retrieve a time sheet for a particular invoice, i.
Get Offer Customer ApprovalTool to retrieve customer approval status and URL for an offer.
Get Offer PDFTool to retrieve a single offer document as PDF.
Get PresenceTool to retrieve a single presence entry by ID.
Get ProfileTool to retrieve the current authenticated user's profile.
Get Project ContractTool to retrieve a single staff assignment (contract) on a project.
Get Single Project ExpenseTool to retrieve a single additional service (expense) for a project.
Get Project Payment Schedules By IDTool to retrieve all payment schedules for a specific project by its ID.
Get Project ReportTool to retrieve a project report with budget, hours, costs, and business indicators.
Get Project ExpensesTool to retrieve all additional services (expenses) for a project.
Get Projects Payment SchedulesTool to retrieve all payment schedules for fixed price projects.
Get Project Payment ScheduleTool to retrieve a single payment schedule entry for a project by its ID.
Get Project Recurring ExpensesTool to retrieve all recurring expenses for a specific project.
Get Project TaskTool to retrieve a single task on a project by project ID and task ID.
Get PurchaseTool to retrieve a single purchase by ID.
Get Purchase Bookkeeping ExportTool to retrieve a single purchase bookkeeping export by ID.
Get Purchase PaymentTool to retrieve a single purchase payment by ID.
Get Purchase Bookkeeping ExportsTool to retrieve all purchase bookkeeping exports.
Get Purchase BudgetsTool to retrieve purchase budgets for a given fiscal year.
Get Purchase PaymentsTool to retrieve all purchase payments.
Get ReceiptTool to retrieve a single receipt by ID from MOCO.
Get ReceiptsRetrieves a list of receipts (expense receipts) from MOCO.
Get All Recurring ExpensesTool to retrieve all recurring additional services entries across all projects in MOCO.
Get Report AbsencesTool to retrieve absence report showing employee absences by type and date range.
Get Finance ReportTool to retrieve the finance report from MOCO.
Get Utilization ReportTool to retrieve the utilization report from MOCO.
Get ScheduleTool to retrieve a single planning entry (schedule) by ID.
Get TagTool to retrieve a single tag by ID.
Get TaggingsTool to retrieve the list of tags associated with an entity.
Get TagsTool to retrieve the list of tags from MOCO.
Get Task TemplateTool to retrieve a single task template by ID.
Get UnitTool to retrieve a single unit/team by ID from MOCO.
Get UserTool to retrieve detailed information for a specific user/staff member by ID.
Get User Performance ReportTool to retrieve a user's performance report comparing tracked hours vs target hours.
Get VAT Code PurchaseTool to retrieve a single VAT code for purchases by ID from MOCO.
Get VAT Code PurchasesTool to retrieve the list of purchase VAT codes.
Get VAT Code SaleTool to retrieve a single VAT code for sales by ID from MOCO.
Get VAT Code SalesTool to retrieve the list of sale VAT codes from MOCO.
Get Work Time AdjustmentTool to retrieve a single work time adjustment by ID.
Create InvoiceTool to create a new invoice.
List InvoicesTool to retrieve a list of all invoices.
List All Project ExpensesTool to retrieve all project expenses across all projects.
List Assigned ProjectsTool to retrieve all projects assigned to the authenticated user.
List Catalog ServicesList all catalog services (Leistungskatalog) from the account.
List CompaniesTool to retrieve all companies (customers and suppliers).
List Custom PropertiesTool to retrieve all custom properties from MOCO.
List EmploymentsRetrieve all user employments from MOCO.
List Expense TemplatesTool to retrieve all expense templates from MOCO.
List HolidaysTool to retrieve all user holidays/vacation entries from MOCO.
List Hourly RatesTool to retrieve all hourly rates from MOCO.
List Invoice AttachmentsTool to retrieve all attachments for an invoice.
List Offer AttachmentsTool to retrieve all attachments for a specific offer.
List PresencesTool to retrieve all user presences (attendance entries) from MOCO.
List Project ContractsTool to retrieve all contracts (assigned staff) for a project.
List Project GroupsRetrieve all project groups from MOCO.
List Project TasksTool to retrieve all tasks (services) for a project by project ID.
List Purchase CategoriesRetrieves all purchase categories configured in MOCO with their IDs, names, account codes, and status.
List Purchase DraftsTool to retrieve all purchase drafts (German: Ausgaben – Entwürfe).
List PurchasesTool to retrieve all purchases (supplier invoices).
List SchedulesTool to retrieve all absences (schedules) from MOCO.
List Task TemplatesTool to retrieve all task templates from MOCO.
List UnitsTool to retrieve all units/teams in MOCO.
List User RolesTool to retrieve all user permission roles in MOCO.
List Work Time AdjustmentsTool to retrieve all user work time adjustments from MOCO.
Get OfferTool to retrieve a single offer by ID.
List OffersTool to retrieve a list of all offers.
Patch TaggingsTool to partially update taggings by adding new tags to an entity without removing existing tags.
List Planning EntriesTool to retrieve a list of all planning entries.
Create Planning EntryTool to create a new planning entry.
Get Planning EntryTool to retrieve a single planning entry by ID.
Create ProjectTool to create a new project in MOCO.
Get ProjectRetrieves comprehensive details for a specific project by its ID.
List ProjectsTool to retrieve a list of all projects.
Update ProjectTool to update an existing project.
Create PurchaseTool to create a new purchase.
Send Invoice by EmailTool to send an invoice by email.
Send Invoice Reminder EmailTool to send an invoice reminder by email.
Send Offer EmailTool to send an offer by email to specified recipients.
Share ProjectTool to activate project report sharing and get a shareable URL.
Start Activity TimerTool to start or continue a timer on an activity.
Stop Activity TimerTool to stop a timer running on an activity.
Unassign Project from Project GroupTool to unassign a project from its project group.
Update Account Catalog ServiceTool to update a catalog service.
Update Catalog Service ItemTool to update an existing item within a catalog service in MOCO.
Update Account Custom PropertiesTool to update a custom property in MOCO.
Update Expense TemplateTool to update an existing expense template in MOCO.
Update Account Internal Hourly RatesTool to update internal hourly rates for one or more users for a specific year.
Update CommentTool to update an existing comment on a MOCO resource.
Update CompanyTool to update an existing company.
Update Contact PersonTool to update an existing contact person in MOCO.
Update Deal CategoryTool to update an existing deal category in MOCO.
Update HolidayTool to update an existing holiday entry in MOCO.
Update Invoice StatusTool to update an invoice status.
Update Offer StatusTool to update the status of an offer.
Update Planning EntryTool to update an existing planning entry.
Update PresenceTool to update a presence entry (work time tracking) in MOCO.
Archive ProjectTool to archive a project in MOCO.
Update Project ContractTool to update a staff assignment to a project.
Update Project ExpenseTool to update an additional services entry (expense) on a project.
Update Project Payment ScheduleTool to update a payment schedule entry for a project.
Update Project Recurring ExpenseTool to update a recurring additional services entry on a project.
Update Project TaskTool to update an existing task on a project in MOCO.
Unarchive ProjectTool to reactivate an archived project.
Update PurchaseTool to update an existing purchase.
Update Purchase DocumentTool to update or store a purchase document.
Update Purchase StatusTool to update the status of a purchase.
Update ReceiptTool to update an existing receipt.
Update ScheduleTool to update a planning entry (absence/schedule).
Update TagTool to update an existing tag in MOCO.
Update TaggingsTool to replace all tags associated with an entity.
Update Task TemplateTool to update an existing task template in MOCO.
Update UnitTool to update an existing unit/team.
Update UserTool to update an existing staff member/user in MOCO.
Update User EmploymentTool to update a user employment record.
Update Work Time AdjustmentTool to update an existing work time adjustment in MOCO.
List UsersList all users in MOCO with optional filters.

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

  const mcpUrl = session.mcp.url;
What's happening:
  • We're creating a Tool Router session that gives your agent access to Moco 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 Moco-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 Moco 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 moco, 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 Moco 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 Moco 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: ["moco"],
  });

  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 moco, 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 Moco 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 Moco MCP Agent with another framework

FAQ

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

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

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

Yes, absolutely. You can configure which Moco 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 Moco 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.