Skip to main content
Glama

Get Download Statistics

get_download_stats

Retrieve npm package download statistics for specific time periods to analyze usage trends and popularity.

Instructions

Get download statistics from npm

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
packageNameYes
periodNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
endYes
startYes
periodYes
packageYes
downloadsYes

Implementation Reference

  • The handler function for the 'get_download_stats' tool. It fetches download statistics from the npm API for a given package and period, validates the response using DownloadStatsSchema, formats the output, and returns structured content with text summary.
    async ({ packageName, period = "last-month" }) => {
      try {
        const encodedPackageName = encodeURIComponent(packageName);
        const response = await fetch(
          `https://api.npmjs.org/downloads/point/${period}/${encodedPackageName}`
        );
    
        if (!response.ok) {
          throw new Error(
            `Failed to fetch download stats: ${response.statusText}`
          );
        }
    
        const rawData = await response.json();
        const parseResult = DownloadStatsSchema.safeParse(rawData);
    
        if (!parseResult.success) {
          throw new Error(
            `Invalid download stats structure: ${parseResult.error.message}`
          );
        }
    
        const data = parseResult.data;
        const output = {
          package: data.package,
          downloads: data.downloads,
          period,
          start: data.start,
          end: data.end,
        };
    
        return {
          content: [
            {
              type: "text",
              text: `Package: ${
                data.package
              }\nDownloads (${period}): ${data.downloads.toLocaleString()}\nPeriod: ${
                data.start
              } to ${data.end}`,
            },
          ],
          structuredContent: output,
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error fetching download stats: ${
                error instanceof Error ? error.message : "Unknown error"
              }`,
            },
          ],
          isError: true,
        };
      }
    }
  • Zod schema used within the handler to validate the raw JSON response from the npm downloads API.
    const DownloadStatsSchema = z.object({
      downloads: z.number(),
      start: z.string(),
      end: z.string(),
      package: z.string(),
    });
  • Input and output schemas defined in the tool registration, using Zod for validation of tool arguments and expected output.
    {
      title: "Get Download Statistics",
      description: "Get download statistics from npm",
      inputSchema: {
        packageName: z.string(),
        period: z.enum(["last-day", "last-week", "last-month"]).optional(),
      },
      outputSchema: {
        package: z.string(),
        downloads: z.number(),
        period: z.string(),
        start: z.string(),
        end: z.string(),
      },
    },
  • src/index.ts:520-595 (registration)
    The server.registerTool call that registers the 'get_download_stats' tool with its schema and handler function.
    server.registerTool(
      "get_download_stats",
      {
        title: "Get Download Statistics",
        description: "Get download statistics from npm",
        inputSchema: {
          packageName: z.string(),
          period: z.enum(["last-day", "last-week", "last-month"]).optional(),
        },
        outputSchema: {
          package: z.string(),
          downloads: z.number(),
          period: z.string(),
          start: z.string(),
          end: z.string(),
        },
      },
      async ({ packageName, period = "last-month" }) => {
        try {
          const encodedPackageName = encodeURIComponent(packageName);
          const response = await fetch(
            `https://api.npmjs.org/downloads/point/${period}/${encodedPackageName}`
          );
    
          if (!response.ok) {
            throw new Error(
              `Failed to fetch download stats: ${response.statusText}`
            );
          }
    
          const rawData = await response.json();
          const parseResult = DownloadStatsSchema.safeParse(rawData);
    
          if (!parseResult.success) {
            throw new Error(
              `Invalid download stats structure: ${parseResult.error.message}`
            );
          }
    
          const data = parseResult.data;
          const output = {
            package: data.package,
            downloads: data.downloads,
            period,
            start: data.start,
            end: data.end,
          };
    
          return {
            content: [
              {
                type: "text",
                text: `Package: ${
                  data.package
                }\nDownloads (${period}): ${data.downloads.toLocaleString()}\nPeriod: ${
                  data.start
                } to ${data.end}`,
              },
            ],
            structuredContent: output,
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error fetching download stats: ${
                  error instanceof Error ? error.message : "Unknown error"
                }`,
              },
            ],
            isError: true,
          };
        }
      }
    );
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 it 'gets' data, implying a read-only operation, but doesn't specify if it requires authentication, rate limits, or the format of returned statistics. This leaves significant gaps for a tool that likely interacts with an external API.

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 with zero waste, front-loading the core functionality. It's appropriately sized for a simple tool, making it easy to parse quickly.

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 has an output schema (which handles return values), no annotations, and a simple input schema, the description is minimally adequate. However, it lacks details on behavioral aspects like API constraints or error handling, which are important for completeness in a real-world usage scenario.

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 0%, so the description must compensate, but it adds no information about parameters beyond what the schema implies. The schema clearly defines 'packageName' and 'period' with an enum, so the baseline is 3, as the description doesn't enhance understanding of what these parameters mean in context.

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 ('Get download statistics') and resource ('from npm'), making the purpose immediately understandable. It doesn't differentiate from sibling tools like 'get_package_info' or 'get_package_quality', which might also provide statistical data, so it doesn't reach the highest score.

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 'get_package_info' or 'compare_packages', nor does it mention prerequisites or exclusions. It's a basic statement of function without context.

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/JuanSebastianGB/npm-context-agent-mcp'

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