Skip to main content
Glama
cloudbring

New Relic MCP Server

by cloudbring

run_nrql_query

Execute NRQL queries to analyze New Relic metrics and events.

Instructions

Execute NRQL queries against New Relic data to analyze metrics and events

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
nrqlYesThe NRQL query to execute
target_account_idNoOptional New Relic account ID to query

Implementation Reference

  • Main execution handler for run_nrql_query. Validates input (non-empty NRQL, valid account ID), then calls this.client.runNrqlQuery() and returns the result.
      async execute(input: { nrql?: string; target_account_id?: string }): Promise<NrqlQueryResult> {
        // Validate input
        if (!input.nrql || typeof input.nrql !== 'string' || input.nrql.trim() === '') {
          throw new Error('Invalid or empty NRQL query provided');
        }
    
        if (!input.target_account_id) {
          throw new Error('Account ID must be provided');
        }
    
        if (input.target_account_id && !/^\d+$/.test(input.target_account_id)) {
          throw new Error('Invalid account ID format');
        }
    
        const result = await this.client.runNrqlQuery({
          nrql: input.nrql,
          accountId: input.target_account_id,
        });
    
        return result;
      }
    }
  • Zod input validation schema for run_nrql_query: nrql (required, min 1 char) and target_account_id (optional string).
    const _NrqlInputSchema = z.object({
      nrql: z.string().min(1),
      target_account_id: z.string().optional(),
    });
  • JSON Schema input schema for the tool definition: nrql (required string) and target_account_id (optional string) properties.
    getInputSchema() {
      return {
        type: 'object' as const,
        properties: {
          nrql: {
            type: 'string',
            description: 'The NRQL query to execute',
          },
          target_account_id: {
            type: 'string',
            description: 'Optional New Relic account ID to query',
          },
        },
        required: ['nrql'],
      };
    }
  • src/server.ts:57-106 (registration)
    Tool registration: NrqlTool instantiated with client, getToolDefinition() called to build tool metadata, stored in the tools Map for MCP discovery.
    private registerTools(): void {
      const nrqlTool = new NrqlTool(this.client);
      const apmTool = new ApmTool(this.client);
      const entityTool = new EntityTool(this.client);
      const alertTool = new AlertTool(this.client);
      const syntheticsTool = new SyntheticsTool(this.client);
      const nerdGraphTool = new NerdGraphTool(this.client);
      const restDeployments = new RestDeploymentsTool();
      const restApm = new RestApmTool();
      const restMetrics = new RestMetricsTool();
    
      // Register all tools
      const tools = [
        nrqlTool.getToolDefinition(),
        apmTool.getListApplicationsTool(),
        entityTool.getSearchTool(),
        entityTool.getDetailsTool(),
        alertTool.getPoliciesTool(),
        alertTool.getIncidentsTool(),
        alertTool.getAcknowledgeTool(),
        syntheticsTool.getListMonitorsTool(),
        syntheticsTool.getCreateMonitorTool(),
        nerdGraphTool.getQueryTool(),
        // REST v2 tools
        restDeployments.getCreateTool(),
        restDeployments.getListTool(),
        restDeployments.getDeleteTool(),
        restApm.getListApplicationsTool(),
        restMetrics.getListMetricNamesTool(),
        restMetrics.getMetricDataTool(),
        restMetrics.getListApplicationHostsTool(),
        {
          name: 'get_account_details',
          description: 'Get New Relic account details',
          inputSchema: {
            type: 'object' as const,
            properties: {
              target_account_id: {
                type: 'string' as const,
                description: 'Optional account ID to get details for',
              },
            },
          },
        },
      ];
    
      tools.forEach((tool) => {
        this.tools.set(tool.name, tool);
      });
    }
  • Client helper that executes the actual NRQL query via New Relic's NerdGraph API. Builds a GraphQL query, calls executeNerdGraphQuery, parses results, and detects time series queries.
    async runNrqlQuery(params: { nrql: string; accountId: string }): Promise<NrqlQueryResult> {
      if (!params.nrql || typeof params.nrql !== 'string') {
        throw new Error('Invalid or empty NRQL query provided');
      }
    
      if (!params.accountId || !/^\d+$/.test(params.accountId)) {
        throw new Error('Invalid account ID format');
      }
    
      const query = `{
        actor {
          account(id: ${params.accountId}) {
            nrql(query: "${params.nrql.replace(/"/g, '\\"')}") {
              results
              metadata {
                eventTypes
                timeWindow {
                  begin
                  end
                }
                facets
              }
            }
          }
        }
      }`;
    
      try {
        type NrqlResponse = {
          actor?: {
            account?: {
              nrql?: {
                results?: Array<Record<string, unknown>>;
                metadata?: {
                  eventTypes?: string[];
                  timeWindow?: { begin: number; end: number };
                  facets?: string[];
                };
              };
            };
          };
        };
        const response = (await this.executeNerdGraphQuery<NrqlResponse>(
          query
        )) as GraphQLResponse<NrqlResponse>;
    
        if (response.errors) {
          const errorMessage = response.errors[0]?.message || 'NRQL query failed';
          throw new Error(errorMessage);
        }
    
        const nrqlResult = response.data?.actor?.account?.nrql;
    
        if (!nrqlResult) {
          throw new Error('No results returned from NRQL query');
        }
    
        // Detect if it's a time series query
        const isTimeSeries = params.nrql.toLowerCase().includes('timeseries');
    
        return {
          results: nrqlResult.results || [],
          metadata: {
            ...nrqlResult.metadata,
            timeSeries: isTimeSeries,
          },
        };
      } catch (error: unknown) {
        if (error instanceof Error && error.message.includes('Syntax error')) {
          throw new Error(`NRQL Syntax error: ${error.message}`);
        }
        throw error instanceof Error ? error : new Error(String(error));
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description must convey behavioral traits. It only states the action without disclosing whether it is read-only, destructive, has rate limits, or the nature of the results. This lack of detail makes it insufficient for safe agent decision-making.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence of 12 words, highly concise and front-loaded with the action 'Execute NRQL queries'. No wasted words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has a simple schema with two parameters fully described. However, the description omits details about result format, pagination, query limits, or error handling, which are important for a query tool. The lack of output schema and annotations further reduces completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% with descriptions for both parameters (nrql and target_account_id). The description adds minimal value beyond the schema, only contextualizing the target data. The baseline score of 3 applies as the schema already provides parameter semantics.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool executes NRQL queries against New Relic data for analyzing metrics and events. This distinguishes it from siblings like run_nerdgraph_query (GraphQL) and others for specific operations like alerts, monitors, and deployments.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies use for querying New Relic data with NRQL but does not provide explicit guidance on when to use this tool versus alternatives, such as run_nerdgraph_query. No 'when not to use' or alternative references are given.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/cloudbring/newrelic-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server