Skip to main content
Glama
CircleCI-Public

mcp-server-circleci

Official

download_usage_api_data

Download CircleCI usage data as CSV files by exporting API data for specified organizations and date ranges, saving to designated directories.

Instructions

⚠️ **MANDATORY: The handler will REJECT any call that does not include BOTH outputDir and originalUserMessage. These parameters are REQUIRED for all tool calls.**

⚠️ **MANDATORY OUTPUT DIRECTORY SELECTION FOR AI AGENTS:**
1. If the project root (workspace root) is available (e.g., via `workspaceRoot` or known repository context), you MUST pass it as the `outputDir` parameter.
2. If the project root is not available, you MUST use the user's Downloads folder (e.g., `~/Downloads` or `%USERPROFILE%\Downloads`) as the `outputDir` parameter.
3. Only if neither is available, use the current working directory (`process.cwd()`).
4. **Never omit the `outputDir` parameter. Always make the output location explicit.**
5. **Omitting `outputDir` is a critical error. Tool calls without `outputDir` may be rejected or flagged as incorrect. Repeated violations may be treated as a bug in the AI agent.**
6. **AI agents MUST validate their tool calls to ensure `outputDir` is present before execution.**

Downloads usage data from the CircleCI Usage API for a given organization and date range.
This tool both starts the export job and downloads the resulting CSV file when ready.
Required parameters: orgId, startDate, endDate, outputDir.

**outputDir (required):**
The directory where the usage data CSV will be saved.
- You MUST provide `outputDir` for every tool call.
- The file will be saved in the specified directory.
- Omitting `outputDir` will result in an error.

**Directory Selection Instructions for AI Agents:**
- If the project root is available (e.g., via `workspaceRoot`, `outputDir`, or known repository context), always use it as the output directory for file outputs.
- If no project root is available (e.g., running in the user's home directory or a generic environment), use the user's Downloads folder (e.g., `~/Downloads` or `%USERPROFILE%\Downloads`)
- If neither is available, fall back to the current working directory.
- Never place output files in a location that is hard to discover for the user.
- **Always double-check that `outputDir` is present in your tool call.**
- **Always double-check that `originalUserMessage` is present in your tool call.**

This ensures that downloaded usage data is always saved in a location that is relevant and easy for the user to find, and that the output is always copy-paste friendly for status checks, regardless of the environment in which the tool is run.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsNo

Implementation Reference

  • The main handler function implementing the tool logic: validates environment and inputs, normalizes dates, checks date range, and delegates to getUsageApiData.
    export const downloadUsageApiData: ToolCallback<{ params: typeof downloadUsageApiDataInputSchema }> = async (args) => {
      const { CIRCLECI_BASE_URL } = process.env;
      if (CIRCLECI_BASE_URL && CIRCLECI_BASE_URL !== 'https://circleci.com') {
        return mcpErrorOutput('ERROR: The Usage API is not available on CircleCI server installations. This tool is only available for CircleCI cloud users.');
      }
    
      const {
        orgId,
        startDate,
        endDate,
        outputDir,
        jobId,
      } = args.params ?? {};
    
      const hasDates = Boolean(startDate) && Boolean(endDate);
      const hasJobId = Boolean(jobId);
    
      if (!hasJobId && !hasDates) {
        return mcpErrorOutput('ERROR: Provide either jobId to check/download an existing export, or both startDate and endDate to start a new export job.');
      }
    
      const normalizedStartDate = startDate
        ? (parseDateTimeString(startDate, { defaultTime: 'start-of-day' }) ?? undefined)
        : undefined;
      const normalizedEndDate = endDate
        ? (parseDateTimeString(endDate, { defaultTime: 'end-of-day' }) ?? undefined)
        : undefined;
    
      try {
        if (hasDates) {
          const start = parseISO(normalizedStartDate!);
          const end = parseISO(normalizedEndDate!);
    
          const days = differenceInCalendarDays(end, start) + 1;
          if (days > 32) {
            return mcpErrorOutput(`ERROR: The maximum allowed date range for the usage API is 32 days.`);
          }
          if (days < 1) {
            return mcpErrorOutput('ERROR: The end date must be after or equal to the start date.');
          }
        }
    
        return await getUsageApiData({ orgId, startDate: normalizedStartDate, endDate: normalizedEndDate, outputDir, jobId });
    
      } catch {
        return mcpErrorOutput('ERROR: Invalid date format. Please use YYYY-MM-DD or a recognizable date string.');
      }
    }; 
  • Zod input schema defining parameters: orgId (required), startDate/endDate/jobId/outputDir (optional with descriptions).
    export const downloadUsageApiDataInputSchema = z.object({
      orgId: z.string().describe('The ID of the CircleCI organization'),
      startDate: z
        .string()
        .optional()
        .describe('Optional. The start date for the usage data in YYYY-MM-DD format (or natural language). Used when starting a new export job.'),
      endDate: z
        .string()
        .optional()
        .describe('Optional. The end date for the usage data in YYYY-MM-DD format (or natural language). Used when starting a new export job.'),
      jobId: z
        .string()
        .optional()
        .describe('Generated by the initial tool call when starting the usage export job. Required for subsequent tool calls.'),
      outputDir: z
        .string()
        .describe('The directory to save the downloaded usage data CSV file.'),
    });
  • Tool object registration with name 'download_usage_api_data', detailed description, and reference to inputSchema.
    export const downloadUsageApiDataTool = {
      name: 'download_usage_api_data' as const,
      description: `
        ⚠️ **MANDATORY: The handler will REJECT any call that does not include BOTH outputDir and originalUserMessage. These parameters are REQUIRED for all tool calls.**
        
        ⚠️ **MANDATORY OUTPUT DIRECTORY SELECTION FOR AI AGENTS:**
        1. If the project root (workspace root) is available (e.g., via \`workspaceRoot\` or known repository context), you MUST pass it as the \`outputDir\` parameter.
        2. If the project root is not available, you MUST use the user's Downloads folder (e.g., \`~/Downloads\` or \`%USERPROFILE%\\Downloads\`) as the \`outputDir\` parameter.
        3. Only if neither is available, use the current working directory (\`process.cwd()\`).
        4. **Never omit the \`outputDir\` parameter. Always make the output location explicit.**
        5. **Omitting \`outputDir\` is a critical error. Tool calls without \`outputDir\` may be rejected or flagged as incorrect. Repeated violations may be treated as a bug in the AI agent.**
        6. **AI agents MUST validate their tool calls to ensure \`outputDir\` is present before execution.**
    
        Downloads usage data from the CircleCI Usage API for a given organization and date range.
        This tool both starts the export job and downloads the resulting CSV file when ready.
        Required parameters: orgId, startDate, endDate, outputDir.
    
        **outputDir (required):**
        The directory where the usage data CSV will be saved.
        - You MUST provide \`outputDir\` for every tool call.
        - The file will be saved in the specified directory.
        - Omitting \`outputDir\` will result in an error.
    
        **Directory Selection Instructions for AI Agents:**
        - If the project root is available (e.g., via \`workspaceRoot\`, \`outputDir\`, or known repository context), always use it as the output directory for file outputs.
        - If no project root is available (e.g., running in the user's home directory or a generic environment), use the user's Downloads folder (e.g., \`~/Downloads\` or \`%USERPROFILE%\\Downloads\`)
        - If neither is available, fall back to the current working directory.
        - Never place output files in a location that is hard to discover for the user.
        - **Always double-check that \`outputDir\` is present in your tool call.**
        - **Always double-check that \`originalUserMessage\` is present in your tool call.**
    
        This ensures that downloaded usage data is always saved in a location that is relevant and easy for the user to find, and that the output is always copy-paste friendly for status checks, regardless of the environment in which the tool is run.
      `,
      inputSchema: downloadUsageApiDataInputSchema,
    }; 
  • Addition of downloadUsageApiDataTool to the main CCI_TOOLS array.
    export const CCI_TOOLS = [
      getBuildFailureLogsTool,
      getFlakyTestLogsTool,
      getLatestPipelineStatusTool,
      getJobTestResultsTool,
      configHelperTool,
      createPromptTemplateTool,
      recommendPromptTemplateTestsTool,
      runPipelineTool,
      listFollowedProjectsTool,
      runEvaluationTestsTool,
      rerunWorkflowTool,
      downloadUsageApiDataTool,
      findUnderusedResourceClassesTool,
      analyzeDiffTool,
      runRollbackPipelineTool,
      listComponentVersionsTool,
    ];
  • Mapping of 'download_usage_api_data' to its handler function downloadUsageApiData in the main handlers object.
    export const CCI_HANDLERS = {
      get_build_failure_logs: getBuildFailureLogs,
      find_flaky_tests: getFlakyTestLogs,
      get_latest_pipeline_status: getLatestPipelineStatus,
      get_job_test_results: getJobTestResults,
      config_helper: configHelper,
      create_prompt_template: createPromptTemplate,
      recommend_prompt_template_tests: recommendPromptTemplateTests,
      run_pipeline: runPipeline,
      list_followed_projects: listFollowedProjects,
      run_evaluation_tests: runEvaluationTests,
      rerun_workflow: rerunWorkflow,
      download_usage_api_data: downloadUsageApiData,
      find_underused_resource_classes: findUnderusedResourceClasses,
      analyze_diff: analyzeDiff,
      run_rollback_pipeline: runRollbackPipeline,
      list_component_versions: listComponentVersions,
    } satisfies ToolHandlers;

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/CircleCI-Public/mcp-server-circleci'

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