Guide · Amazon Forecast · Generating & Querying Forecasts

Amazon Forecast Query for MCP Servers — CreateForecastCommand, QueryForecastCommand, and Percentile Bands

Once a predictor is trained, generating and querying forecasts is a two-step process. First, CreateForecastCommand materializes predictions into a named forecast artifact — a process that takes 10–30 minutes for large datasets. Then, QueryForecastCommand from the @aws-sdk/client-forecastquery package retrieves per-item predictions in under 100 ms at runtime. This guide covers both steps, explains how to interpret p10/p50/p90 percentile bands, shows how to export bulk forecasts to S3, and describes the deletion order required to tear down resources without hitting dependency errors.

TL;DR

Step 1 — CreateForecastCommand

A forecast artifact materializes predictions from a trained predictor into a queryable object. Creating a forecast involves specifying which quantiles to generate:

import { CreateForecastCommand } from "@aws-sdk/client-forecast";

const { ForecastArn } = await forecast.send(new CreateForecastCommand({
  ForecastName: "mcp-endpoint-forecast-2026-11-16",
  PredictorArn,
  // ForecastTypes: quantile strings — decimal probabilities, NOT integers or "p10" labels
  // "0.1" = p10 (optimistic lower bound), "0.5" = p50 (median), "0.9" = p90 (pessimistic upper bound)
  ForecastTypes: ["0.1", "0.5", "0.9"],
  // TimeSeriesSelector: optional — generate forecasts for a subset of items
  // TimeSeriesSelector: {
  //   TimeSeriesIdentifiers: {
  //     DataSource: { S3Config: { Path, RoleArn } },
  //     Format: "CSV",
  //     Schema: { Attributes: [{ AttributeName: "item_id", AttributeType: "string" }] },
  //   },
  // },
  Tags: [{ Key: "project", Value: "alivemcp" }],
}));

console.log("Forecast ARN:", ForecastArn);

Polling until ACTIVE

import { DescribeForecastCommand } from "@aws-sdk/client-forecast";

async function waitForForecast(ForecastArn) {
  while (true) {
    const { Status, Message } = await forecast.send(
      new DescribeForecastCommand({ ForecastArn })
    );
    if (Status === "ACTIVE") return;
    if (Status === "CREATE_FAILED") throw new Error(`Forecast failed: ${Message}`);
    console.log("Forecast status:", Status);
    await new Promise(r => setTimeout(r, 60_000)); // poll every 60s — takes 10–30 min
  }
}

await waitForForecast(ForecastArn);

Step 2 — QueryForecastCommand at runtime

Once the forecast is ACTIVE, MCP server tools can query it on demand. The query client uses a different SDK package and endpoint:

import { ForecastQueryClient, QueryForecastCommand } from "@aws-sdk/client-forecastquery";

// DIFFERENT client from management operations
const forecastQuery = new ForecastQueryClient({ region: "us-east-1" });

const response = await forecastQuery.send(new QueryForecastCommand({
  ForecastArn,
  Filters: {
    item_id: "weather-mcp-prod",   // filter to a specific item
    // For RETAIL domain with location dimension: add "location": "us-west-2"
  },
  // Optional: narrow to a time window within the forecast horizon
  // StartDate: "2026-11-17T00:00:00",   // ISO 8601 UTC
  // EndDate:   "2026-11-18T00:00:00",
}));

const predictions = response.Forecast.Predictions;
console.log("p10 (optimistic):", predictions.p10);
// [{ Timestamp: "2026-11-17T00:00:00", Value: 72 },
//  { Timestamp: "2026-11-17T01:00:00", Value: 65 }, ...]

console.log("p50 (median):", predictions.p50);
// [{ Timestamp: "2026-11-17T00:00:00", Value: 142 }, ...]

console.log("p90 (pessimistic):", predictions.p90);
// [{ Timestamp: "2026-11-17T00:00:00", Value: 218 }, ...]

Understanding percentile bands

Amazon Forecast returns probabilistic predictions rather than a single point estimate. The three quantiles represent:

QuantileInterpretationUse in MCP server tools
p10 (0.1)Optimistic lower bound: actual value will exceed this 90% of the timeMinimum capacity floor for resource pre-allocation
p50 (0.5)Median: actual value will be above and below this roughly equallyBest single-number estimate for dashboards and reporting
p90 (0.9)Pessimistic upper bound: actual value will be below this 90% of the timeCapacity ceiling for autoscaling triggers and incident budgeting

For MCP server monitoring, the p90 band is the most actionable: if the current observed request rate is approaching the p90 forecast value, you're in an unusual high-traffic condition that warrants investigation. If p10 drops sharply for the next 2 hours, that's a predicted quiet period — a good maintenance window candidate.

The width of the prediction interval (p90 − p10) is a measure of the model's confidence. A narrow band means the pattern is regular and predictable; a wide band means the model has high uncertainty, often due to noisy historical data or insufficient training history.

Requesting additional quantiles

Beyond the standard three, you can request any quantiles from 0.01 to 0.99:

const { ForecastArn } = await forecast.send(new CreateForecastCommand({
  ForecastName: "mcp-endpoint-forecast-detailed",
  PredictorArn,
  ForecastTypes: ["0.1", "0.25", "0.5", "0.75", "0.9"],
  // Response will include: predictions.p10, p25, p50, p75, p90
}));

More quantiles means more forecast generation time and higher generation costs (billed per time step). For capacity planning, p10/p50/p90 is usually sufficient; for SLA tracking where you need "what's the value we'll stay below 99% of the time," add "0.99".

Filtering forecast output with TimeSeriesSelector

By default, CreateForecastCommand generates predictions for every item in the dataset — which can be expensive for large item catalogs. TimeSeriesSelector limits generation to a subset:

// First, upload a CSV with the item_ids you want to include:
// weather-mcp-prod
// maps-mcp-prod
// calendar-mcp-prod
// (one item_id per row, no header)

await s3.send(new PutObjectCommand({
  Bucket: "my-forecast-data",
  Key: "mcp-endpoints/priority-items.csv",
  Body: "weather-mcp-prod\nmaps-mcp-prod\ncalendar-mcp-prod",
}));

const { ForecastArn } = await forecast.send(new CreateForecastCommand({
  ForecastName: "mcp-priority-forecast",
  PredictorArn,
  ForecastTypes: ["0.1", "0.5", "0.9"],
  TimeSeriesSelector: {
    TimeSeriesIdentifiers: {
      DataSource: {
        S3Config: {
          Path: "s3://my-forecast-data/mcp-endpoints/priority-items.csv",
          RoleArn,
        },
      },
      Format: "CSV",
      Schema: {
        Attributes: [{ AttributeName: "item_id", AttributeType: "string" }],
      },
    },
  },
}));

Batch export with CreateForecastExportJobCommand

For workflows where you pre-compute all forecasts and cache them (e.g., nightly batch run feeding a Redis cache), CreateForecastExportJobCommand writes all predictions to S3 as CSV or Parquet:

import { CreateForecastExportJobCommand, DescribeForecastExportJobCommand } from "@aws-sdk/client-forecast";

const { ForecastExportJobArn } = await forecast.send(new CreateForecastExportJobCommand({
  ForecastExportJobName: "mcp-forecast-export-2026-11-16",
  ForecastArn,
  Destination: {
    S3Config: {
      Path: "s3://my-forecast-data/mcp-forecasts/2026-11-16/",
      RoleArn,   // role needs s3:PutObject
    },
  },
  Format: "CSV",    // "CSV" | "PARQUET"
  Tags: [{ Key: "project", Value: "alivemcp" }],
}));

// Poll until complete
while (true) {
  const { Status, Message } = await forecast.send(
    new DescribeForecastExportJobCommand({ ForecastExportJobArn })
  );
  if (Status === "ACTIVE") break;
  if (Status === "CREATE_FAILED") throw new Error(`Export failed: ${Message}`);
  await new Promise(r => setTimeout(r, 30_000));
}

The exported CSV contains one row per item per time step per quantile:

item_id,date,p10,p50,p90
weather-mcp-prod,2026-11-17T00:00:00Z,72,142,218
weather-mcp-prod,2026-11-17T01:00:00Z,65,131,197
maps-mcp-prod,2026-11-17T00:00:00Z,201,312,423

Parquet format is more efficient for large exports (typically 5–10× smaller than CSV) and faster to read in bulk analytics workflows using Athena or EMR.

What-If analysis

Forecast supports scenario modeling — "what would the forecast look like if I changed a covariate?" — via what-if analysis. This is useful for MCP server capacity planning ("what if we add a new high-traffic client?"):

import {
  CreateWhatIfAnalysisCommand,
  CreateWhatIfForecastCommand,
  QueryWhatIfForecastCommand,
} from "@aws-sdk/client-forecast";
import { ForecastQueryClient } from "@aws-sdk/client-forecastquery";

// Create the analysis container
const { WhatIfAnalysisArn } = await forecast.send(new CreateWhatIfAnalysisCommand({
  WhatIfAnalysisName: "mcp-new-client-scenario",
  ForecastArn,
  // TimeSeriesSelector: optionally limit to specific items
}));

// Define a scenario: scale up traffic by 50% for a specific item
const { WhatIfForecastArn } = await forecast.send(new CreateWhatIfForecastCommand({
  WhatIfForecastName: "plus-50pct-traffic",
  WhatIfAnalysisArn,
  TimeSeriesTransformations: [{
    Action: {
      AttributeName: "target_value",
      Operation: "MULTIPLY",
      Value: 1.5,
    },
    TimeSeriesConditions: [{
      AttributeName: "item_id",
      AttributeValue: "weather-mcp-prod",
      Condition: "EQUALS",
    }],
  }],
}));

// Query what-if forecast (use forecastquery client, same package)
const whatIfResponse = await forecastQuery.send(new QueryWhatIfForecastCommand({
  WhatIfForecastArn,
  Filters: { item_id: "weather-mcp-prod" },
}));
console.log("Scenario p90:", whatIfResponse.Forecast.Predictions.p90);

Forecast lifecycle and cost management

Forecast artifacts incur storage costs while they exist. Query costs are low ($0.01/1K queries) but forecast objects themselves are charged for generation. Use a nightly regeneration pattern and delete stale forecasts:

import { DeleteForecastCommand, ListForecastsCommand } from "@aws-sdk/client-forecast";

// List all forecasts (paginated via NextToken)
const { Forecasts } = await forecast.send(new ListForecastsCommand({
  Filters: [{ Condition: "IS", Key: "PredictorArn", Value: PredictorArn }],
}));

// Sort by creation time, keep the most recent, delete the rest
const sorted = Forecasts.sort((a, b) =>
  new Date(b.CreationTime) - new Date(a.CreationTime)
);

for (const old of sorted.slice(1)) {  // keep index 0 (newest)
  console.log("Deleting old forecast:", old.ForecastArn);
  await forecast.send(new DeleteForecastCommand({ ForecastArn: old.ForecastArn }));
  // Deletion is async — wait a few seconds before deleting predictor
}

Deletion order reference

All resources must be deleted in dependency order. Attempting to delete a parent while children exist returns ResourceInUseException:

  1. Delete forecast export jobs (DeleteForecastExportJobCommand) — if any are attached to the forecast
  2. Delete what-if forecasts (DeleteWhatIfForecastCommand), then what-if analyses (DeleteWhatIfAnalysisCommand)
  3. Delete forecasts (DeleteForecastCommand)
  4. Delete explainability resources (DeleteExplainabilityCommand)
  5. Delete predictors (DeletePredictorCommand)
  6. Delete predictor backtest export jobs if created
  7. Delete dataset import jobs (DeleteDatasetImportJobCommand)
  8. Delete datasets (DeleteDatasetCommand)
  9. Delete dataset group (DeleteDatasetGroupCommand)

All delete operations are asynchronous. After calling DeleteForecastCommand, poll DescribeForecastCommand until it throws ResourceNotFoundException before proceeding to delete the predictor.

IAM permissions for query calls

The runtime inference role (used by your MCP server) needs only the query permission — it should not have management permissions:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": [
      "forecast:QueryForecast",
      "forecast:QueryWhatIfForecast"   // only if using what-if scenarios
    ],
    "Resource": "arn:aws:forecast:us-east-1:123456789012:forecast/*"
    // Narrow to specific forecast ARN in production:
    // "Resource": "arn:aws:forecast:us-east-1:123456789012:forecast/mcp-endpoint-forecast-*"
  }]
}

The management role (used by deployment pipelines or admin tools) needs the broader forecast:Create*, forecast:Delete*, and forecast:Describe* permissions. Keeping these roles separate prevents an MCP server compromise from being able to modify or delete forecast resources.

Complete Amazon Forecast series

Related guides: SageMaker endpoints with MCP servers · CloudWatch metrics · Kinesis Firehose for MCP event streaming