How to integrate New relic MCP with Mastra AI

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

New relic logo
Mastra AI logo
divider

Introduction

This guide walks you through connecting New relic to Mastra AI using the Composio tool router. By the end, you'll have a working New relic agent that can list all alert policies for your account, create a new webhook alert channel, get all applications monitored in new relic through natural language commands.

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

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

Also integrate New relic with

TL;DR

Here's what you'll learn:
  • Set up your environment so Mastra, OpenAI, and Composio work together
  • Create a Tool Router session in Composio that exposes New relic tools
  • Connect Mastra's MCP client to the Composio generated MCP URL
  • Fetch New relic tool definitions and attach them as a toolset
  • Build a Mastra agent that can reason, call tools, and return structured results
  • Run an interactive CLI where you can chat with your New relic agent

What is Mastra AI?

Mastra AI is a TypeScript framework for building AI agents with tool support. It provides a clean API for creating agents that can use external services through MCP.

Key features include:

  • MCP Client: Built-in support for Model Context Protocol servers
  • Toolsets: Organize tools into logical groups
  • Step Callbacks: Monitor and debug agent execution
  • OpenAI Integration: Works with OpenAI models via @ai-sdk/openai

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

The New Relic MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your New Relic account. It provides structured and secure access to your observability data and alerting infrastructure, so your agent can perform actions like retrieving application metrics, managing alert policies, updating notification channels, and monitoring browser applications on your behalf.

  • Comprehensive alert policy management: Effortlessly create, update, or delete New Relic alert policies to keep your monitoring rules current and effective.
  • Alert notification channel control: Register new alert endpoints, update existing channels, or list all notification channels to optimize how your team receives important alerts.
  • Real-time application monitoring: Instantly retrieve a list of all monitored applications, filter them by name or host, and stay on top of your software stack’s health.
  • Browser application insights: List and filter browser applications to monitor user experience and catch frontend issues before they escalate.
  • Alert condition visibility: Fetch detailed alert conditions for specific policies, so you can audit or fine-tune how your system responds to incidents.

Supported Tools & Triggers

Tools
Add Notification Channels to PolicyTool to add notification channels to an alert policy using the NerdGraph GraphQL API.
Add Tags to EntityTool to add tags with values to a specific New Relic entity via NerdGraph GraphQL API.
Add Widgets to Dashboard PageTool to add widgets to an existing New Relic dashboard page via NerdGraph GraphQL API.
Configure Cloud IntegrationTool to enable and configure cloud integrations for monitoring in New Relic.
Create AI Notifications ChannelTool to create a New Relic AI Notifications channel via NerdGraph GraphQL API.
Create AI Notifications DestinationTool to create an AI notifications destination in New Relic for services like Jira or ServiceNow.
Create AI WorkflowTool to create an AI workflow for automated incident response in New Relic.
Create Alert Notification ChannelTool to create an alert notification channel.
Create Alert PolicyCreates a new alert policy in New Relic.
Create Static NRQL Alert ConditionTool to create a static NRQL alert condition using New Relic's NerdGraph GraphQL API.
Create Alert Policy (GraphQL)Tool to create a new alert policy using New Relic's NerdGraph GraphQL API.
Create API Access KeysTool to create New Relic API access keys using NerdGraph.
Create Broken Links MonitorTool to create a broken links monitor that scans a webpage for broken links.
Create DashboardTool to create a New Relic dashboard using NerdGraph GraphQL API.
Create Dashboard Snapshot URLTool to create a snapshot URL for sharing a New Relic dashboard at a specific point in time.
Create Deployment MarkerTool to record a deployment marker in New Relic to track changes and their effects on your systems.
Create Entity RelationshipTool to create or replace a user-defined relationship between two New Relic entities via NerdGraph GraphQL API.
Create Example Browser ApplicationTool to create a new browser application in New Relic via NerdGraph GraphQL API.
Create Example Mobile ApplicationTool to create a new example mobile application in New Relic via NerdGraph GraphQL API.
Create External Service Alert ConditionTool to create an external service alert condition in New Relic.
Create Infrastructure Alert ConditionTool to create an infrastructure alert condition in New Relic.
Create Location Failure Alert ConditionTool to create a location failure alert condition in New Relic.
Create Log Data Partition RuleTool to create a log data partition rule using New Relic's NerdGraph GraphQL API.
Create Lookup TableTool to upload a new lookup table to your New Relic account.
Create Metric Normalization RuleTool to create a metric normalization rule using New Relic's NerdGraph GraphQL API.
Create Synthetic MonitorTool to create a new synthetic monitor in New Relic for monitoring website or API availability.
Create NRQL Baseline Alert ConditionTool to create a NRQL baseline alert condition in New Relic via NerdGraph GraphQL API.
Create NRQL ConditionCreates a new NRQL alert condition for a specified policy.
Create Scripted MonitorTool to create a scripted monitor in New Relic Synthetics using NerdGraph GraphQL API.
Create Secure CredentialTool to add a secure credential to New Relic for use in synthetic monitors.
Create Service LevelTool to create a service level indicator (SLI) and optional objectives (SLO) using New Relic's NerdGraph GraphQL API.
Create Synthetics Alert ConditionTool to create a synthetics alert condition for monitoring synthetic checks.
Create Synthetics Private LocationTool to create a Synthetics private location via New Relic's NerdGraph GraphQL API.
Create Synthetics Secure CredentialTool to create a secure credential in New Relic Synthetics using NerdGraph GraphQL API.
Create Synthetics Simple MonitorTool to create a New Relic Synthetics simple (ping) monitor to check URL/endpoint accessibility.
Create UserTool to create a new user in New Relic account via NerdGraph GraphQL API.
Delete Agent ApplicationTool to delete an APM application entity via NerdGraph GraphQL API.
Delete AI notifications channelTool to delete an AI notifications channel via NerdGraph GraphQL API.
Delete AI Notifications DestinationTool to delete an AI notifications destination via NerdGraph GraphQL API.
Delete Alert ChannelTool to delete an alert notification channel via REST API.
Delete alert policyTool to delete an existing alert policy via REST API.
Delete alerts conditionTool to delete an alert condition via NerdGraph GraphQL API.
Delete Alert Policy via GraphQLTool to delete an alert policy using New Relic's NerdGraph GraphQL API.
Delete API Access KeysTool to delete API access keys (ingest/license keys or user keys) via New Relic's NerdGraph GraphQL API.
Delete DashboardTool to delete a New Relic dashboard using its entity GUID via NerdGraph GraphQL API.
Delete Data Partition RuleTool to delete a data partition rule via New Relic's NerdGraph GraphQL API.
Delete EntityTool to delete entities via New Relic's NerdGraph GraphQL API.
Delete Entity Relationship (User-Defined)Tool to delete user-defined relationships between entities via New Relic's NerdGraph GraphQL API.
Delete External Service ConditionTool to delete an external service alert condition in New Relic.
Delete Infrastructure Alert ConditionTool to delete an infrastructure alert condition.
Delete Location Failure Alert ConditionTool to delete a location failure alert condition via REST API.
Delete Lookup TableTool to delete a lookup table from New Relic.
Delete synthetic monitorTool to delete an existing synthetic monitor.
Delete NRQL ConditionTool to delete a NRQL alert condition via REST API.
Remove channel from policyTool to remove a notification channel from an alert policy.
Delete Secure CredentialTool to delete an existing secure credential from New Relic Synthetics.
Delete Synthetics Alert ConditionTool to delete a synthetics alert condition.
Delete Synthetics Monitor (GraphQL)Tool to delete a synthetic monitor using its GUID via New Relic's NerdGraph GraphQL API.
Delete Synthetics Private LocationTool to delete a synthetics private location via New Relic's NerdGraph GraphQL API.
Delete Synthetics Secure CredentialTool to delete a secure credential used in synthetic monitors via NerdGraph GraphQL API.
Delete Tag Values From EntityTool to delete specific tag values from a New Relic entity via NerdGraph GraphQL API.
Delete User Management UserTool to delete a user via New Relic's NerdGraph User Management API.
Delete WorkloadTool to delete a workload from New Relic by its GUID using NerdGraph GraphQL API.
Disable Cloud IntegrationTool to disable (remove) a cloud integration in New Relic.
Disable Metric Normalization RuleTool to disable a metric normalization rule using New Relic's NerdGraph GraphQL API.
Duplicate WorkloadTool to duplicate an existing workload using New Relic's NerdGraph GraphQL API.
Edit Metric Normalization RuleTool to edit an existing metric normalization rule using New Relic's NerdGraph GraphQL API.
Enable Metric Normalization RuleTool to enable a previously disabled metric normalization rule using New Relic's NerdGraph GraphQL API.
Execute NRQL QueryTool to execute NRQL queries to retrieve data from New Relic via NerdGraph GraphQL API.
Fetch Browser ConfigurationTool to fetch browser application configuration via New Relic's NerdGraph GraphQL API.
Fetch Browser JavaScript SnippetTool to fetch the JavaScript loader script snippet for a New Relic browser application.
Fetch Mobile Application TokenTool to fetch mobile application token for a given mobile app entity GUID via New Relic's NerdGraph GraphQL API.
Fetch Rules CollectionTool to fetch rules from a New Relic collection (Scorecard) via NerdGraph GraphQL API.
Fetch Your Organization IDTool to fetch your organization ID and name via New Relic's NerdGraph GraphQL API.
Get Alert ChannelsRetrieves a paginated list of alert notification channels configured in your New Relic account.
Get Alert ConditionsTool to retrieve alert conditions for a specified policy.
Get Alert PoliciesTool to retrieve a list of alert policies.
Get Alerts ViolationsTool to retrieve a list of alert violations from New Relic.
Get ApplicationsTool to retrieve a list of New Relic applications.
Get App Metric DataTool to retrieve metric timeslice data for a New Relic application.
Get Application Metrics NamesTool to retrieve a list of available metric names for a New Relic application.
Get Browser ApplicationsTool to list New Relic browser applications.
Get Dashboard Entity QueryTool to query detailed information about a New Relic dashboard entity using its GUID via NerdGraph GraphQL API.
Get Infrastructure Alert ConditionTool to retrieve details for a specific infrastructure alert condition.
Get Lookup TableTool to download a lookup table that was previously uploaded to New Relic.
Get Mobile ApplicationTool to retrieve details for a specific New Relic mobile application including crash count and crash rate.
Get Mobile Application MetricsTool to retrieve metric names for a New Relic mobile application.
Get Mobile Metric DataTool to retrieve metric data for a mobile application including crash count and crash rate.
Get Secure CredentialTool to retrieve a specific secure credential by key from New Relic Synthetics.
Get Synthetic MonitorTool to retrieve details for a specific synthetic monitor by its ID.
Link Cloud AccountTool to link cloud provider accounts (AWS, Azure, GCP) to your New Relic account for monitoring.
List DeploymentsTool to retrieve a list of all past deployments for a New Relic application.
List External Service Alert ConditionsTool to retrieve a list of external service alert conditions for a specified policy.
List Infrastructure Alert ConditionsTool to list infrastructure alert conditions for a specific policy.
List Key TransactionsTool to retrieve a list of New Relic key transactions.
List Location Failure Alert ConditionsTool to retrieve a list of location failure alert conditions for a specific policy.
List Synthetic Monitor LocationsTool to retrieve the list of valid locations for synthetic monitors.
List Lookup TablesTool to list all lookup tables previously uploaded for an account.
List Mobile ApplicationsTool to list all mobile applications in your New Relic account.
List Synthetic MonitorsTool to retrieve a list of all synthetic monitors in your New Relic account.
List NRQL Alert ConditionsTool to retrieve NRQL alert conditions for a specified policy.
List Secure CredentialsTool to retrieve a list of all secure credentials in your New Relic account.
List Synthetics Alert ConditionsTool to retrieve a list of synthetics alert conditions for a policy.
Override Entity Golden MetricsTool to override golden metrics or golden tags for a specific entity type in a New Relic account or workload.
Override Entity Golden TagsTool to override golden tags for entity types via New Relic's NerdGraph GraphQL API.
Patch Synthetic MonitorTool to partially update individual attributes of an existing synthetic monitor in New Relic.
Query Cloud ProvidersTool to query available cloud providers for a New Relic account.
Query ErrorTool to query error data from New Relic using NRQL (New Relic Query Language) via the NerdGraph GraphQL API.
Query Example Read QueryTool to execute GraphQL read queries against New Relic's NerdGraph API.
Remove Entity from Alert ConditionTool to remove an entity from an alert condition in New Relic.
Remove Notification Channels From PolicyTool to remove notification channels from an alert policy via NerdGraph GraphQL API.
Rename Cloud AccountTool to rename linked cloud provider accounts in New Relic via the NerdGraph GraphQL API.
Replace Tags On EntityTool to replace the entire set of tags on a New Relic entity with a new tag set via NerdGraph GraphQL API.
Reset Entity Golden MetricsTool to reset custom golden metrics and golden tags to New Relic defaults for an entity.
Reset Entity Golden TagsTool to reset golden tags for entities to their default values using New Relic's NerdGraph GraphQL API.
Revoke Authorization AccessTool to revoke access grants with a data access policy in New Relic.
Search EntitiesTool to search for New Relic entities by attributes including name, type, domain, and other values using NerdGraph GraphQL API.
Send EventsTool to send custom event data to New Relic's Event API.
Send TracesTool to send distributed tracing data to New Relic in New Relic format.
Test AI Notification Destination By IDTool to test an AI notification destination configuration by ID using New Relic NerdGraph API.
Test AI Notifications ChannelTool to test an AI notifications channel via NerdGraph GraphQL API.
Test AI Notifications DestinationTool to test AI notifications destinations via NerdGraph GraphQL API.
Test Notification ChannelTool to test a New Relic AI notification channel by sending a test notification.
Undelete DashboardTool to undelete a previously deleted dashboard via NerdGraph GraphQL API.
Update AccountTool to update a New Relic account name via the NerdGraph GraphQL API.
Update Agent Application SettingsTool to update APM agent application settings using New Relic's NerdGraph GraphQL API.
Update AI Notification ChannelTool to update an AI notification channel via NerdGraph GraphQL API.
Update AI Notifications DestinationTool to update an AI notifications destination via NerdGraph GraphQL API.
Update Alert Notification ChannelTool to update an existing New Relic alert notification channel.
Update Alert PolicyTool to update an existing alert policy via New Relic's NerdGraph GraphQL API.
Update Alert Policy (REST)Tool to update an existing alert policy via New Relic's REST API v2.
Update API Access KeysTool to update API access keys (ingest/license keys or user keys) via New Relic's NerdGraph GraphQL API.
Update Browser SettingsTool to update browser monitoring settings for a New Relic browser application via NerdGraph GraphQL mutation.
Update Cross-Account ElectionsTool to update cross-account alerting elections via New Relic's NerdGraph GraphQL API.
Update DashboardTool to update an existing New Relic dashboard using its entity GUID via NerdGraph GraphQL API.
Update Dashboard Live URL Creation PoliciesTool to update dashboard live URL creation policies using New Relic's NerdGraph GraphQL API.
Update Dashboard PageTool to update a dashboard page in New Relic via NerdGraph GraphQL API.
Update Dashboard Widgets In PageTool to update widgets in a New Relic dashboard page via NerdGraph GraphQL API.
Update Data Partition RuleTool to update an existing log data partition rule in New Relic via NerdGraph GraphQL API.
Update External Service ConditionTool to update an external service alert condition in New Relic.
Update Infrastructure Alert ConditionTool to update an infrastructure alert condition in New Relic.
Update Location Failure Alert ConditionTool to update a location failure alert condition in New Relic.
Update Lookup TableTool to replace an existing lookup table in your New Relic account.
Update Mobile Settings ExampleTool to update mobile application settings using New Relic's NerdGraph GraphQL API.
Update Monitor ScriptTool to update the script for a SCRIPT_BROWSER or SCRIPT_API synthetic monitor in New Relic.
Update NRQL Baseline Alert ConditionTool to update a NRQL baseline alert condition in New Relic via the NerdGraph GraphQL API.
Update NRQL ConditionTool to update an existing NRQL alert condition in New Relic.
Update NRQL Static Alert ConditionTool to update a NRQL static alert condition via New Relic's NerdGraph GraphQL API.
Update Policy ChannelsTool to associate notification channels with an alert policy using the REST API v2.
Update Scripted MonitorTool to update a scripted synthetic monitor (browser or API) in New Relic using the NerdGraph GraphQL API.
Update Secure CredentialTool to update an existing secure credential in New Relic Synthetics.
Update Service Level IndicatorTool to update a Service Level Indicator (SLI) and its objectives via New Relic's NerdGraph GraphQL API.
Update Synthetics Alert ConditionTool to update an existing synthetics alert condition.
Update Synthetics Simple MonitorTool to update an existing ping monitor configuration in New Relic Synthetics using NerdGraph GraphQL API.
Update Synthetic MonitorTool to fully update an existing synthetic monitor in New Relic using PUT method.
Update UserTool to update user information in New Relic account via NerdGraph GraphQL API.
Update AI WorkflowTool to update an existing New Relic AI workflow via NerdGraph GraphQL API.
Update WorkloadTool to update an existing workload configuration via New Relic's NerdGraph GraphQL API.

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 starting, make sure you have:
  • Node.js 18 or higher
  • A Composio account with an active API key
  • An OpenAI API key
  • Basic familiarity with TypeScript

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key.
  • You need credits or a connected billing setup to use the models.
  • Store the key somewhere safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Go to Settings and copy your API key.
  • This key lets your Mastra agent talk to Composio and reach New relic through MCP.

Install dependencies

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

Install the required packages.

What's happening:

  • @composio/core is the Composio SDK for creating MCP sessions
  • @mastra/core provides the Agent class
  • @mastra/mcp is Mastra's MCP client
  • @ai-sdk/openai is the model wrapper for OpenAI
  • dotenv loads environment variables from .env

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your requests to Composio
  • COMPOSIO_USER_ID tells Composio which user this session belongs to
  • OPENAI_API_KEY lets the Mastra agent call OpenAI models

Import libraries and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

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

if (!openaiAPIKey) 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 as string,
});
What's happening:
  • dotenv/config auto loads your .env so process.env.* is available
  • openai gives you a Mastra compatible model wrapper
  • Agent is the Mastra agent that will call tools and produce answers
  • MCPClient connects Mastra to your Composio MCP server
  • Composio is used to create a Tool Router session

Create a Tool Router session for New relic

typescript
async function main() {
  const session = await composio.create(
    composioUserID as string,
    {
      toolkits: ["new_relic"],
    },
  );

  const composioMCPUrl = session.mcp.url;
  console.log("New relic MCP URL:", composioMCPUrl);
What's happening:
  • create spins up a short-lived MCP HTTP endpoint for this user
  • The toolkits array contains "new_relic" for New relic access
  • session.mcp.url is the MCP URL that Mastra's MCPClient will connect to

Configure Mastra MCP client and fetch tools

typescript
const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      nasdaq: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

console.log("Fetching MCP tools from Composio...");
const composioTools = await mcpClient.getTools();
console.log("Number of tools:", Object.keys(composioTools).length);
What's happening:
  • MCPClient takes an id for this client and a list of MCP servers
  • The headers property includes the x-api-key for authentication
  • getTools fetches the tool definitions exposed by the New relic toolkit

Create the Mastra agent

typescript
const agent = new Agent({
    name: "new_relic-mastra-agent",
    instructions: "You are an AI agent with New relic tools via Composio.",
    model: "openai/gpt-5",
  });
What's happening:
  • Agent is the core Mastra agent
  • name is just an identifier for logging and debugging
  • instructions guide the agent to use tools instead of only answering in natural language
  • model uses openai("gpt-5") to configure the underlying LLM

Set up interactive chat interface

typescript
let messages: AiMessageType[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end.\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({
    id: crypto.randomUUID(),
    role: "user",
    content: trimmedInput,
  });

  console.log("\nAgent is thinking...\n");

  try {
    const response = await agent.generate(messages, {
      toolsets: {
        new_relic: composioTools,
      },
      maxSteps: 8,
    });

    const { text } = response;

    if (text && text.trim().length > 0) {
      console.log(`Agent: ${text}\n`);
        messages.push({
          id: crypto.randomUUID(),
          role: "assistant",
          content: text,
        });
      }
    } catch (error) {
      console.error("\nError:", error);
    }

    rl.prompt();
  });

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

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • messages keeps the full conversation history in Mastra's expected format
  • agent.generate runs the agent with conversation history and New relic toolsets
  • maxSteps limits how many tool calls the agent can take in a single run
  • onStepFinish is a hook that prints intermediate steps for debugging

Complete Code

Here's the complete code to get you started with New relic and Mastra AI:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

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

if (!openaiAPIKey) 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 as string });

async function main() {
  const session = await composio.create(composioUserID as string, {
    toolkits: ["new_relic"],
  });

  const composioMCPUrl = session.mcp.url;

  const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      new_relic: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "new_relic-mastra-agent",
    instructions: "You are an AI agent with New relic tools via Composio.",
    model: "openai/gpt-5",
  });

  let messages: AiMessageType[] = [];

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

  rl.prompt();

  rl.on("line", async (input: string) => {
    const trimmed = input.trim();
    if (["exit", "quit"].includes(trimmed.toLowerCase())) {
      rl.close();
      return;
    }

    messages.push({ id: crypto.randomUUID(), role: "user", content: trimmed });

    const { text } = await agent.generate(messages, {
      toolsets: { new_relic: composioTools },
      maxSteps: 8,
    });

    if (text) {
      console.log(`Agent: ${text}\n`);
      messages.push({ id: crypto.randomUUID(), role: "assistant", content: text });
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main();

Conclusion

You've built a Mastra AI agent that can interact with New relic through Composio's Tool Router. You can extend this further by:
  • Adding other toolkits like Gmail, Slack, or GitHub
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows

How to build New relic MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and New relic MCP?

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

Can I use Tool Router MCP with Mastra AI?

Yes, you can. Mastra AI 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 New relic tools.

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

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