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 directly from your MCP client.

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

  • The execute method of NrqlTool implements the core handler logic for the 'run_nrql_query' tool, validating inputs and delegating to the NewRelicClient.
    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;
    }
  • Defines the input schema for the 'run_nrql_query' tool, provided via getToolDefinition() for MCP tool listing.
    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:165-169 (registration)
    In the server's executeTool switch statement, registers the handler by instantiating NrqlTool and calling execute for 'run_nrql_query'.
    case 'run_nrql_query':
      return await new NrqlTool(this.client).execute({
        ...args,
        target_account_id: accountId,
      });
  • src/server.ts:58-105 (registration)
    Instantiates NrqlTool and registers its tool definition (name, description, schema) in the server's tools map for listTools requests.
    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);
    });
  • NewRelicClient.runNrqlQuery executes the GraphQL NerdGraph query against New Relic API to run the NRQL and returns the result.
    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?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool executes queries but doesn't describe what happens during execution (e.g., rate limits, authentication needs, query timeouts, or what constitutes a valid NRQL query). The phrase 'analyze metrics and events' hints at read-only behavior, but it's not explicit about whether this is a safe read operation or has side effects. More behavioral context is needed for a mutation-capable tool.

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, efficient sentence that front-loads the core action ('Execute NRQL queries') and purpose ('to analyze metrics and events'). There is zero waste or redundancy, making it appropriately sized for a tool with two parameters and no output schema. Every word earns its place.

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?

Given the tool's complexity (query execution with two parameters), lack of annotations, and no output schema, the description is minimally adequate. It covers the basic purpose but lacks details on behavioral traits, usage guidelines, and return values. For a tool that could involve data retrieval and potential side effects, more completeness is needed to fully inform an AI agent, though the concise structure is a positive aspect.

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 description coverage is 100%, so the schema already documents both parameters ('nrql' and 'target_account_id'). The description adds no additional parameter semantics beyond what's in the schema, such as NRQL syntax examples or account ID formatting. However, with high schema coverage, the baseline score of 3 is appropriate as the description doesn't need to compensate for gaps.

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

Purpose4/5

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

The description clearly states the action ('Execute NRQL queries') and target ('against New Relic data'), with the purpose 'to analyze metrics and events' adding useful context. It distinguishes from sibling tools like 'run_nerdgraph_query' by specifying NRQL queries rather than NerdGraph queries, though it doesn't explicitly name alternatives. The verb+resource combination is specific but could be more precise about what NRQL queries do.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives like 'run_nerdgraph_query' or other data retrieval tools in the sibling list. It mentions analyzing metrics and events, which implies usage for querying New Relic's data store, but offers no explicit when/when-not instructions, prerequisites, or comparison to other query methods.

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