How to integrate Sentry MCP with Vercel AI SDK

Framework Integration Gradient
Sentry Logo
Vercel AI SDK Logo
divider

Introduction

This guide walks you through connecting Sentry to Vercel AI SDK using the Composio tool router. By the end, you'll have a working Sentry agent that can create dashboard tracking errors for my project, add new member to sentry organization, set up alert for critical exceptions, grant my team access to a project through natural language commands.

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

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

TL;DR

Here's what you'll learn:
  • How to set up and configure a Vercel AI SDK agent with Sentry integration
  • Using Composio's Tool Router to dynamically load and access Sentry 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
  • Step Counting: Control multi-step tool execution
  • OpenAI Provider: Native integration with OpenAI models

What is the Sentry MCP server, and what's possible with it?

The Sentry MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Sentry account. It provides structured and secure access to your projects, teams, and monitoring data, so your agent can perform actions like managing alerts, configuring dashboards, inviting team members, and tracking error monitors on your behalf.

  • Project and team management: Your agent can access project details, add teams to projects, and manage organization teams, helping you stay on top of collaboration and permissions.
  • Organization member onboarding: Effortlessly invite new members to your Sentry organization or add existing members to teams via email, streamlining team setup and access control.
  • Automated alert and monitor creation: Set up metric alert rules and create scheduled monitors (like cron jobs) to track incidents and automate error tracking for projects.
  • Dashboard and widget configuration: Instruct your agent to create custom dashboards with widgets tailored to your organization's needs, enabling focused error monitoring and visualization.
  • User identity and email management: Link users to external identity providers or manage user emails, keeping your organization’s authentication and contact information up to date.

Supported Tools & Triggers

Tools
Access project informationRetrieves detailed information for a sentry project, given its existing organization and project id or slug.
Add organization member via emailInvites a new member (or re-invites an existing non-accepted member) to a sentry organization via email, allowing specification of organization and team roles.
Add or remove user email by idAdds or removes a secondary email for an existing sentry user, determined by whether the email already exists for that user.
Add team member in organizationAdds an existing member of an organization to one of its teams; the member must already belong to the organization, and the team must also belong to that organization.
Add team to projectGrants a sentry team access to a sentry project within the specified sentry organization.
Create dashboard with widgetsCreates a sentry dashboard with widgets for an organization; `organization id or slug` and specified `project` ids must be valid, and `start`/`end` datetimes (if absolute range) must form a logical iso 8601 range.
Create external user for organizationLinks a sentry user to an external identity provider's user within a sentry organization; the sentry user must be an organization member, an active integration for the provider must be configured, and `external id` is typically required for the external user.
Create organization alert ruleCreates a sentry metric alert rule for an organization, mandating a 'critical' trigger, typically for a single project, where actions may require sentry integrations.
Create organization monitorCreates a new monitor (type 'cron job') within a sentry organization to track scheduled tasks, allowing configuration of its name, slug (which must be unique if provided), status, owner, and muting preferences for incidents.
Create organization teamCreates a new team in a sentry organization, requiring either a 'slug' (preferred, as 'name' is deprecated) or 'name' to define the team.
Create project key with optional rate limitingCreates a new client key (dsn) for an existing sentry project, with optional custom rate limit configuration.
Create project rule for alertsCreates a sentry project alert rule by defining conditions, actions, and optional filters using specific json structures (detailed in parameter descriptions) to automate responses to event patterns for an existing organization and project.
Create project webhook subscriptionRegisters a new webhook subscription for a sentry project to send http post notifications to a specified url for given events, provided the project has the 'servicehooks' feature enabled.
Create release deploy for orgCreates a new deploy record in sentry to track the introduction of a release version into a specific environment.
Create release for organizationCreates a new sentry release for an existing organization, associating it with specified projects that must belong to that organization.
Create scim group for organizationCreates a new sentry team (scim group) within an organization where scim is enabled; a url-friendly slug is auto-generated from the `displayname` (e.
Create sentry external issue linkLinks an existing sentry issue to an issue in an external service, or updates an existing link, requiring a configured sentry app installation `uuid`.
Create team project for organizationCreates a new sentry project for an existing organization and team, allowing configuration of its name, slug, platform, and default alert rules.
Create user for SAML integrationCreates a new sentry organization member via a scim request for saml integration; this action does not support setting secondary emails.
Delete dsyms for projectPermanently removes a specific debug information file (dif), used for symbolicating crash reports, from the specified sentry project and organization.
Delete external issue by uuidUnlinks an external issue (e.
Delete an external team by idUnlinks a previously established external team from a sentry team; this action does not delete either the sentry team or the external team.
Delete external user from organizationDeletes the link between an external user (e.
Delete member from teamRemoves an organization member from a sentry team, revoking their team-specific permissions, provided the member is currently part of that team.
Delete organization alert ruleDeletes a specific metric alert rule within a sentry organization.
Delete organization dashboardDeletes a custom dashboard or tombstones (marks as deleted) a pre-built dashboard within a sentry organization.
Delete organization discover queryPermanently removes a specific saved discover query (a configuration for exploring event data) from a sentry organization.
Delete organization integrationPermanently deletes a specific integration previously installed for the sentry organization.
Delete organization issuePermanently deletes a specific sentry issue, identified by its id, from an organization; this operation is irreversible and idempotent.
Delete organization memberPermanently removes a member from a sentry organization, revoking their access to that organization and all its associated projects.
Delete organization monitorDeletes a sentry cron monitor or, if `environment` is specified, only specific environments within that monitor.
Delete organization releasePermanently and irreversibly removes a sentry release, including all its associated files, identified by its version from the specified organization.
Delete org notification actionDeletes a specific spike protection notification action for a sentry organization, where `action id` must be a valid action associated with the `organization id or slug`.
Delete project by idSchedules a sentry project for asynchronous deletion within a specified organization, hiding it from most public views once the process begins.
Delete project hookDeletes a specific service hook from a sentry project using its organization, project, and hook identifiers.
Delete project issuesPermanently removes specified issues from a sentry project; if no issue ids are provided, it removes the oldest 1000 issues.
Delete project keyPermanently deletes a specific client key (dsn) for a project, preventing it from being used to send events to sentry.
Delete project monitorDeletes a sentry monitor, or optionally only its specified environments, for a given project.
Delete project replayPermanently deletes a specific sentry session replay (a video-like reproduction of user interactions, including console logs and network activity) from the specified project and organization.
Delete project rulePermanently deletes a specific issue alert rule from an existing project within an existing sentry organization.
Delete a project symbol sourceDeletes a specific custom symbol source from a project.
Delete project team associationRevokes a team's access to a sentry project; this operation is idempotent.
Delete release filePermanently deletes a specific file from an existing release, project, and organization; this action is idempotent.
Delete release file by idPermanently deletes a specific build artifact (e.
Delete team by organization and team slugSchedules a sentry team for asynchronous deletion, which releases the team's slug for reuse upon successful scheduling.
Delete a team from an organization (SCIM v2)Permanently and irreversibly deletes a specific team from a sentry organization via a scim v2 request, provided scim integration is enabled for the organization.
Delete user emails by idPermanently removes a sentry user's email address; if multiple emails exist, sentry's api logic (e.
Delete user from orgRemoves a scim-managed member from a sentry organization that has scim enabled, permanently revoking their access.
Fetch issue event by idRetrieves the 'latest', 'oldest', or 'recommended' event for a sentry issue, optionally filtered by environment(s).
Fetch organization alert rulesRetrieves a list of active metric alert rules for an existing sentry organization, identified by its id or slug.
Fetch organization release threshold statusesRetrieves derived health statuses for release thresholds in a sentry organization for a given time range, optionally filtered by environment, project, or release; `start` and `end` times must be provided together.
Fetch organization replay countRetrieves the total count of session replays for a specified sentry organization, filterable by time range, environment, project, and query.
Fetch organization replay detailsRetrieves detailed information for a specific replay session by id within a sentry organization, optionally filtering time-series data using `statsperiod` or `start`/`end`, and further refining by projects, environments, or specific fields.
Fetch organization replay selectorsFetches replay selectors (css selectors for session replays) for a sentry organization, filterable by various criteria; use either `statsperiod` or `start`/`end` for time range, not both.
Fetch project environment detailsRetrieves detailed information for a specific environment within a sentry project.
Fetch project ownership detailsRetrieves the ownership configuration, like codeowners rules or issue owner settings, for a specified sentry project.
Fetch project release filesRetrieves artifact files (e.
Fetch project replay clicksFetches a list of user click interactions for a specific sentry session replay, including the clicked dom element id and timestamp.
Fetch replay recording segmentRetrieves a specific recording segment for a sentry replay, requiring valid organization, project, replay, and segment identifiers.
Get activation of alert rule for organizationRetrieves all activations (triggered instances) for a specific metric alert rule within a sentry organization.
Get integration details by orgRetrieves details for a specific integration, identified by `integration id`, installed within an existing sentry organization, identified by `organization id or slug`.
Get organization by id or slugRetrieves a sentry organization by its id or slug; use the `detailed` parameter to optionally exclude project and team details for a more concise response.
Get organization detailsRetrieves sentry organizations accessible via the current authentication, with scope varying between user (all in region) and api key (linked org only) credentials.
Get organization environmentsRetrieves a list of deployment environments (e.
Get organization issue detailsRetrieves detailed information for a specific issue within a sentry organization.
Get organization monitor by id or slugRetrieves detailed information for a specific monitor (e.
Get organization release versionRetrieves detailed information, including optional health data and statistics, for a specific release version within a sentry organization.
Get organization sessionsRetrieves time series data for an organization's sentry project release health sessions; note session duration data (e.
Get organization stats summaryRetrieves summarized event statistics for a sentry organization, aggregated by project, allowing queries for event counts or unique occurrences over a specified time period and resolution, with filtering by project, category, and outcome.
Get project eventsRetrieves a list of error events for a specified project within a sentry organization, with options for pagination and detail level.
Get project event statsRetrieves event statistics for a specified sentry project, returning data as [timestamp, count] pairs; ensure `since` precedes `until` if both are provided.
Get project hookRetrieves detailed information for an existing service hook, identified by `hook id`, within a specific sentry project and organization.
Get project listRetrieves a list of sentry projects (representing monitored applications or services), useful for discovery or selecting a project for subsequent operations.
Get project monitor by idRetrieves detailed information for a specific sentry cron monitor, provided the organization, project, and monitor exist.
Get project rule detailsRetrieves detailed information for a specific issue alert rule within a sentry project.
Get scim group by team idRetrieves scim group information for a sentry team, if scim is enabled for the organization; the 'members' list in the response is limited to 10,000 entries.
Get sentry app installations for organizationRetrieves a list of sentry app installations for a given organization, which must exist.
Get team members by id or slugRetrieves a list of all active members for a sentry team, excluding users with pending invitations.
Get who viewed replay by projectRetrieves users who viewed a specific, existing session replay within a sentry project and organization.
List organization dashboardsRetrieves a list of custom dashboards for a sentry organization, with pagination support.
List organization membersLists all members, including those with pending invitations, for a sentry organization.
List organization releasesRetrieves a list of releases for an existing sentry organization, optionally filtering by a query string that matches the start of the release version.
List organization repositoriesRetrieves a list of version control repositories for a specific sentry organization, which must exist and is identified by its id or slug.
List organization user teamsRetrieves a list of all teams that the authenticated user has access to within the specified sentry organization.
List project usersRetrieves users who have interacted with or are recognized within a specific sentry project, optionally filtered by a query.
List SCIM v2 organization usersRetrieves a paginated list of scim (system for cross-domain identity management) users for a sentry organization, allowing for filtering, pagination, and attribute exclusion.
List teams in organizationLists teams for an existing sentry organization, optionally including project details and supporting pagination via a cursor.
Create an external teamLinks an external team or channel (e.
Modify organization monitor dataUpdates an existing sentry monitor's properties, requiring `name` and `type` (must be 'cron job'), and optionally `slug`, `status`, `owner`, or `is muted` state for a monitor within the specified organization.
Modify organization notification actionModifies an organization's notification action, specifically for `spike-protection` triggers.
Modify organization settingsUpdates settings for a sentry organization, such as name, slug, member roles, privacy, and integrations; if `avatartype` is 'upload', `avatar` (base64 image) is required.
Modify release file attributesUpdates attributes (e.
Patch SCIM group operationsPerforms scim patch operations (rfc 7644) to update attributes of a scim-enabled sentry team, provided scim integration is active for the organization.
Deactivate an organization memberDeactivates and permanently deletes a sentry organization member by using a scim patch operation to set their 'active' attribute to 'false'.
Add a symbol source to a projectAdds a new custom symbol source (http, gcs, or s3) to a project for fetching debug symbols; if an `id` is provided, it must be unique for the project and not start with 'sentry:'.
Enable spike protection for an organizationEnables or updates spike protection for specified projects (or all projects using `['$all']`) within an existing sentry organization, to which the projects must belong.
Retrieve alert rule detailsRetrieves detailed information for a specific metric alert rule within a sentry organization.
Retrieve commit files for releaseRetrieves files changed in commits for a specified sentry release; the release must exist and have linked commits.
Retrieve an organization's repository commitsRetrieves a list of commits for a given repository within a sentry organization.
Retrieve dsym files for projectRetrieve a list of debug information files (dsym files) for a specified sentry project, used for symbolication to display human-readable stack traces.
Retrieve event id for organizationResolves a sentry event id to its project and issue details within an accessible sentry organization.
Retrieve files for releaseRetrieves artifact files for a specific release version in a sentry organization; the organization and release must exist, and the response `data` field will contain the file information as a dictionary.
Retrieve issue events by idRetrieves events for a specified sentry `issue id`, which must be an existing issue.
Retrieve issue hashes for organizationRetrieves a list of grouping checksums (hashes) generated by sentry for a specific issue within an organization, used for understanding event aggregation.
Retrieve issue tag detailsRetrieves detailed information (e.
Retrieve monitor checkinsRetrieves the history of check-ins for a sentry monitor, providing insights into the health and performance of associated scheduled tasks.
Retrieve monitor checkins by orgRetrieves check-ins (pings/heartbeats of a monitored cron job or task) for a specific monitor within a sentry organization.
Retrieve notification action by org idRetrieves details for a specific spike protection notification action, which defines alerts for triggered spike protection rules, within a sentry organization.
Retrieve organization dashboardFetches detailed information about a specific custom dashboard within a sentry organization.
Retrieve organization eventsRetrieves discover event data for a sentry organization; the `sort` field must be in the `field` list (not an equation), and `field` has a 20-item limit.
Retrieve organization integrations listRetrieves a list of available integrations for an existing sentry organization.
Retrieve organization memberRetrieves details for a sentry organization member or pending invitee, including role, teams, and status, using their member id and the organization's id or slug.
Retrieve organization monitorsRetrieves cron monitors for a sentry organization, including details of nested monitor environments.
Retrieve organization projectsRetrieves a list of sentry projects for a specified organization (which must be accessible), supporting pagination via cursor.
Retrieve organization relay usageRetrieves relay usage information, primarily a list of trusted relays, for a specified sentry organization, which must have relay usage enabled.
Retrieve organization release commitsRetrieves a list of commits for a given release version in an existing sentry organization, if the release exists.
Retrieve organization replaysFetches session replays for a sentry organization; use `statsperiod` for relative time, or `start` and `end` (used together) for absolute time ranges.
Retrieve organization SCIM groupsRetrieves a paginated list of scim groups (teams) for a sentry organization; the `members` field in the response for each group will contain at most 10,000 members.
Retrieve organization stats v2Retrieves sentry organization event statistics; specify time range with `statsperiod` or both `start`/`end`; note that grouping by `project` returns a sum not a time-series, and `interval` (if used) must be 1h-1d and cleanly divide 24 hours.
Retrieve org integration configRetrieves configuration for all integrations, or a specific integration if `providerkey` is given, for an existing sentry organization.
Retrieve project environmentsRetrieves a list of environments for an existing project within a sentry organization.
Retrieve project event by idRetrieves detailed information for a specific sentry event using its id, organization identifier, and project identifier.
Retrieve project filter dataRetrieves a sentry project's current data filtering settings, used to ignore events from sources like localhost, web crawlers, or legacy browsers.
Retrieve project hooksReturn a list of service hooks (webhooks) bound to a sentry project, used to send notifications to external services upon event occurrences.
Retrieve project issues listRetrieves a list of issues for a sentry project, defaulting to unresolved issues unless an empty `query` string is provided or specific `hashes` are used.
Retrieve project key detailsRetrieves details of a specific client key (dsn) for a sentry project, which is used by sentry sdks to send event data.
List a project's client keysRetrieves a list of client keys (dsns), used by sentry sdks to send events, for a specified project within an organization.
Retrieve project members listRetrieves active organization members belonging to any team assigned to the specified sentry project.
Retrieve project release file detailsRetrieves metadata (default) or raw content (if `download` is true) for a specific file within a sentry project's release version.
Retrieve project rules by org and project idRetrieves a list of active issue alert rules associated with a specific project within an organization.
Retrieve project symbol sourcesRetrieves custom symbol sources for a sentry project, either listing all or fetching a specific one if its id is provided.
Retrieve project tag valuesRetrieves up to 1000 unique values for a specified tag key that has been recorded for events within a sentry project.
Retrieve project teamsRetrieves a list of teams with explicit access to a specific project within a sentry organization.
Retrieve release commitsRetrieves a list of commits associated with a specific release version within a sentry project.
Retrieve release deploymentsRetrieves a list of all deployment records for a specific release version in an organization, detailing each deployment's environment and timestamps.
Retrieve release file by idRetrieves a specific file's content or its metadata from a sentry release, using the `download` parameter to choose between raw content or json metadata.
Retrieve replay recording segmentsRetrieves a paginated list of recording segments for a specific sentry replay, used for reconstructing or analyzing the replay.
Retrieve saved discover queriesRetrieves a list of saved discover queries for a sentry organization, optionally filtered and sorted.
Retrieve saved discover query for organizationRetrieves a specific saved discover query (a predefined set of filters and conditions for exploring event data) for a sentry organization.
Retrieve short id for organizationResolves an existing sentry short id to its issue details within a valid sentry organization.
Retrieve source map debug eventRetrieves detailed debug information for diagnosing source map processing issues for a specific sentry event, stack trace frame, and exception index.
Retrieve team infoRetrieves detailed information for an existing sentry team within its organization, optionally expanding related data (e.
Retrieve team projectsRetrieves a list of sentry projects for a specific team within an organization, supporting pagination via a cursor.
Retrieve user email informationRetrieves a list of email addresses for an existing sentry user, identified by their `user id`.
Retrieve user feedback for projectRetrieves user feedback for a project from sentry's older 'user reports' system, excluding feedback from the modern 'user feedback widget'.
Retrieve user via SCIM APIRetrieves an individual sentry organization member's details accessible via scim v2 using their member id, noting that `firstname` and `lastname` in the response will be 'n/a'.
Save organization discover querySaves a new discover query with a unique name for a sentry organization, allowing reuse of search criteria for analyzing event data (errors, transactions) across specified projects and environments.
Fetch Tag Values for IssueRetrieves a list of distinct values for a specified tag key associated with an existing sentry issue, useful for understanding tag manifestations like browser versions or affected users.
Submit notification action API dataCreates a sentry notification action for 'spike-protection' triggers, requiring `integration id` if `service type` is 'slack', 'pagerduty', or 'opsgenie', and `target identifier`/`target display` if `service type` is 'slack' or 'opsgenie'.
Submit project user feedbackDeprecated: submits user feedback for a sentry project event (use if newer sentry feedback tools are unavailable); submit within 30 mins of event, overwritable within 5 mins.
Switch team role for memberChanges a member's role within a sentry team, ensuring the member is already part of the team and that any organization-level role restrictions are respected.
Toggle project filter statusUpdates the status or configuration of a specific inbound data filter for a sentry project; use `active` for most filters, or `subfilters` if `filter id` is `legacy-browser`.
Update environment visibilityUpdates the visibility of a specific environment within a sentry project.
Update external team integrationUpdates an existing external team integration's display name, provider, sentry integration id, or external id; the `integration id` must match a valid, configured sentry integration for the organization and the specified `provider`.
Update external user for organizationUpdates attributes of an existing external user linkage (identified by `external user id`) within a sentry organization (specified by `organization id or slug`).
Update issue attributes in organizationUpdates specified attributes of an existing sentry issue within a sentry organization, leaving other attributes unchanged.
Update organization alert rulesReplaces an existing sentry metric alert rule's configuration; fields not provided in the request are removed or reset.
Update organization dashboardUpdates an existing custom dashboard, allowing modifications to its title, widgets, and data filters; providing `widgets`, `projects`, `environment`, `period`, `start`, `end`, or `filters` will overwrite existing settings for those fields.
Update organization member roleUpdates a sentry organization member's organization-level role (`orgrole`) and/or their team roles (`teamroles`), ensuring the initiator has permissions equivalent to both the member's current and intended new `orgrole` if `orgrole` is being modified.
Update project detailsUpdates a sentry project's settings (e.
Update project issue status and detailsBulk update attributes of issues in a sentry project, targeting issues by a list of ids or by a query status (which implies updating all matching issues if ids are omitted).
Update project key configurationUpdates configuration settings (e.
Update project monitorUpdates an existing sentry monitor (used for tracking recurring tasks/cron jobs) within a specific organization and project, allowing modification of its properties such as name, slug, type, status, owner, and muting status.
Update project ownership settingsUpdates the ownership configuration settings (raw rules, fallthrough, auto-assignment, codeowners sync) for a sentry project; omitted attributes retain their current values.
Update project release file detailsUpdates the name (path) or distribution identifier of a specific file within an existing project release in sentry.
Update Project Rule By IdUpdates an existing sentry project issue alert rule by `rule id`, completely overwriting it; all rule fields must be provided in the request, as omitted fields may be cleared or reset to defaults.
Update release details for organizationUpdates an existing sentry release's details for an organization, including its reference, url, release date, associated commits, or repository references.
Update a saved query for an organizationUpdates an existing discover saved query for a sentry organization.
Update symbol source settingsUpdates an existing custom symbol source's settings in a sentry project, such as its type, name, layout preferences, and connection parameters.
Update team information by organization idUpdates the slug for an existing team within a sentry organization.
Update user emailUpdates the primary email for a sentry user; the new email must be valid and not already in use as a primary email by another sentry account.
Update webhook configurationUpdates an existing sentry service hook's target url and subscribed event types for a given project and organization.
Upload dsyms file to projectUploads a dsym (debug symbols) zip archive, containing an apple .
Upload file to project releaseUploads a file to a sentry project release, for an existing organization, project, and version; uses `multipart/form-data` and the region-specific sentry domain.
Upload release file to organizationUploads a new file, such as a source map or debug information, to an existing release version in a sentry organization.
View organization notification actionsRetrieves spike protection notification actions for a sentry organization, filterable by project ids or slugs (slugs take precedence); if `triggertype` is used, it must be 'spike-protection'.

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

What is Tool Router?

Composio's Tool Router 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 Tool Router

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

How the Tool Router works

The Tool Router 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 { experimental_createMCPClient as 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: ["sentry"],
  });

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

  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 sentry, 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 Sentry 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 Sentry MCP Agent with another framework

FAQ

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

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

Yes, you can. Vercel AI 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 Sentry tools.

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

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