Guide · Amazon Personalize · Runtime Recommendations

Amazon Personalize Recommendations for MCP Servers — GetRecommendations, Ranking, and Batch Inference

Once a Personalize campaign or domain recommender is live, your MCP server tools call the runtime plane to fetch personalized results. The @aws-sdk/client-personalize-runtime package provides three operations: GetRecommendationsCommand for top-N items for a user or items similar to a given item, GetPersonalizedRankingCommand to re-rank an existing list, and CreateBatchInferenceJobCommand for offline scoring of your full user base. This guide covers all three operations, dynamic filter expressions with parameter substitution, context-aware recommendations, promotions, and how to handle cold-start users who have no interaction history.

TL;DR

Use GetRecommendationsCommand with userId for user-specific recommendations or itemId for related items. Apply a filterArn to exclude already-seen or ineligible items — dynamic filters take filterValues as a Record<string, string> where values are JSON-encoded string arrays. For search result re-ranking, use GetPersonalizedRankingCommand instead — it preserves your existing retrieval set and applies personalized ordering on top. All runtime calls go through @aws-sdk/client-personalize-runtime, not @aws-sdk/client-personalize.

Basic recommendation call

The runtime client targets a different endpoint than the management client:

import {
  PersonalizeRuntimeClient,
  GetRecommendationsCommand,
} from "@aws-sdk/client-personalize-runtime";

const runtime = new PersonalizeRuntimeClient({ region: "us-east-1" });

// User-based recommendations (requires aws-user-personalization or domain recommender)
const result = await runtime.send(new GetRecommendationsCommand({
  campaignArn: "arn:aws:personalize:us-east-1:123456789012:campaign/mcp-recommendations-prod",
  userId:      "user-42",
  numResults:  10,     // 1–500; default 25
}));

for (const item of result.itemList ?? []) {
  console.log(item.itemId, item.score);
  // item.score is a float between 0 and 1; higher = more relevant
  // scores are relative to this response — do not compare across separate calls
}

The itemList array is sorted by score descending — the most relevant item is always at index 0. Scores are normalized within each response and are not meaningful as absolute values or for cross-user comparisons. Use rank position, not score value, when deciding how many items to surface in your MCP tool response.

Related item recommendations

To find items similar to a given item (requires a campaign trained on aws-similar-items), pass itemId instead of userId:

const related = await runtime.send(new GetRecommendationsCommand({
  campaignArn: "arn:aws:personalize:us-east-1:123456789012:campaign/mcp-similar-items",
  itemId:      "tool-database-query-mcp",
  numResults:  5,
}));

// Returns items that co-occur with tool-database-query-mcp in user sessions
for (const item of related.itemList ?? []) {
  console.log("Related tool:", item.itemId);
}

The aws-similar-items recipe combines collaborative filtering (what users who interacted with item X also interacted with) and content-based signals (item attributes from your Items dataset). Pass both a userId and an itemId to blend user preferences with item similarity — this is called hybrid inference and can improve relevance when the user has limited history with the specific item type.

Using domain recommenders

For domain dataset groups (ECOMMERCE or VIDEO_ON_DEMAND), use recommenderArn instead of campaignArn:

const domainResult = await runtime.send(new GetRecommendationsCommand({
  recommenderArn: "arn:aws:personalize:us-east-1:123456789012:recommender/ecommerce-recommended-for-you",
  userId:         "user-42",
  numResults:     10,
}));

Domain recommenders auto-update on a schedule managed by AWS — you do not need to call CreateSolutionVersionCommand or UpdateCampaignCommand. The trade-off is less control over training configuration and a fixed recipe. Use custom campaigns when you need non-standard hyperparameters or recipes; use domain recommenders for standard e-commerce or media use cases.

Filtering recommendations

Filters allow you to exclude or include items based on metadata or interaction history. Create a filter first:

import { CreateFilterCommand } from "@aws-sdk/client-personalize";

// Static filter: exclude items the user has already interacted with
const { filterArn: excludeViewedFilter } = await personalize.send(new CreateFilterCommand({
  name:           "exclude-already-invoked",
  datasetGroupArn,
  filterExpression: 'EXCLUDE itemId WHERE Interactions.EVENT_TYPE IN ("invoke")',
}));

Apply the filter at inference time:

const filtered = await runtime.send(new GetRecommendationsCommand({
  campaignArn: "arn:aws:personalize:us-east-1:123456789012:campaign/mcp-recommendations-prod",
  userId:      "user-42",
  numResults:  10,
  filterArn:   "arn:aws:personalize:us-east-1:123456789012:filter/exclude-already-invoked",
}));

Dynamic filters with parameter substitution

Static filter expressions embed literal values. Dynamic filters use $VARIABLE_NAME placeholders that you substitute at call time via filterValues:

// Define a dynamic filter at creation time — $CATEGORY is a placeholder
const { filterArn: categoryFilter } = await personalize.send(new CreateFilterCommand({
  name:           "filter-by-category",
  datasetGroupArn,
  filterExpression: 'INCLUDE itemId WHERE Items.CATEGORY IN ($CATEGORY)',
}));

// At inference time, provide the substitution value as a JSON-encoded string array
const categoryResult = await runtime.send(new GetRecommendationsCommand({
  campaignArn: "arn:aws:personalize:us-east-1:123456789012:campaign/mcp-recommendations-prod",
  userId:      "user-42",
  numResults:  10,
  filterArn:   "arn:aws:personalize:us-east-1:123456789012:filter/filter-by-category",
  filterValues: {
    CATEGORY: JSON.stringify(["database", "monitoring"]),
    // Note: filterValues values must be JSON-encoded arrays of strings
    // Do NOT pass: CATEGORY: "database" — this will fail or give wrong results
    // Do pass:     CATEGORY: '["database","monitoring"]'
  },
}));

The filterValues map keys must match the placeholder names in the filter expression (without the $ prefix). Values must be JSON-encoded string arrays even for single values: JSON.stringify(["database"]), not "database". This is the most common mistake with dynamic filters and produces a ResourceNotFoundException or silently returns fewer results than expected.

Contextual recommendations

The context parameter passes signals about the current request that the model uses to adjust rankings. It requires that the Items or Users dataset includes corresponding columns:

// context keys must match metadata field names in your Items or Users dataset
const contextResult = await runtime.send(new GetRecommendationsCommand({
  campaignArn: "arn:aws:personalize:us-east-1:123456789012:campaign/mcp-recommendations-prod",
  userId:      "user-42",
  numResults:  10,
  context: {
    DEVICE_TYPE:   "api-client",   // current interface type — values must match training data
    PLAN_TIER:     "author",       // user's current plan tier
    TIME_OF_DAY:   "morning",      // coarse time bucket for time-sensitive recommendations
  },
}));

Context is only used if the training data included these fields with matching values. If the model was not trained with contextual features, the context parameter is silently ignored. Contextual features require the Items or Users dataset to have columns with metadata: { categorical: true } that were populated with the same value vocabulary used in the context map.

Personalized ranking (re-ranking existing results)

Use GetPersonalizedRankingCommand when you have a fixed set of candidates from a retrieval step (keyword search, semantic search, or rule-based filtering) and want to re-order them by user preference:

import { GetPersonalizedRankingCommand } from "@aws-sdk/client-personalize-runtime";

// candidateItems could come from a keyword search, semantic retrieval, or allowlist
const candidateItems = [
  "tool-database-query-mcp",
  "tool-search-mcp",
  "tool-read-file-mcp",
  "tool-write-file-mcp",
  "tool-execute-code-mcp",
];

const ranked = await runtime.send(new GetPersonalizedRankingCommand({
  campaignArn: "arn:aws:personalize:us-east-1:123456789012:campaign/mcp-personalized-ranking",
  userId:      "user-42",
  inputList:   candidateItems,     // up to 500 items; returned in personalized order
  filterArn:   excludeViewedFilter,
  filterValues: {},
  context: {
    DEVICE_TYPE: "api-client",
  },
}));

console.log("Re-ranked results:");
for (const item of ranked.personalizedRanking ?? []) {
  console.log(item.itemId, item.score);
}

The campaign must be trained on the aws-personalized-ranking recipe (not aws-user-personalization) for GetPersonalizedRankingCommand to work. The personalizedRanking output preserves the input item IDs but orders them by predicted relevance for the user. Items that the filter excludes are removed from the output — the response may have fewer items than the input list.

Key use case for MCP servers: after a semantic similarity search returns 50 candidate documents, re-rank them by user reading history before returning the top 5 to the agent. This two-stage retrieval + reranking pattern produces significantly better results than either approach alone.

Handling cold-start users

Users with zero interaction history return recommendations based on item popularity (the model falls back to popularity for unknown users). To handle this gracefully in MCP tool responses:

async function getRecommendations(userId: string, numResults = 10) {
  const result = await runtime.send(new GetRecommendationsCommand({
    campaignArn: CAMPAIGN_ARN,
    userId,
    numResults,
  }));

  const items = result.itemList ?? [];

  // If user is cold-start, scores will be uniformly low or items will be only popular items
  // Check item count — cold-start users still get results, just popularity-based
  return {
    items:          items.map(i => i.itemId),
    isPersonalized: items.some(i => (i.score ?? 0) > 0.01),
  };
}

There is no explicit cold-start flag in the API response. The model silently falls back to popularity-based recommendations for new users. The practical threshold: users with fewer than 2–5 interactions receive effectively popularity-based results. Use real-time event tracking (PutEventsCommand) to accumulate interactions as quickly as possible to exit cold-start.

Promotions

Promotions force a minimum number of slots in the results to come from a specified filter — useful for surfacing sponsored content, featured items, or new releases:

const promoted = await runtime.send(new GetRecommendationsCommand({
  campaignArn: CAMPAIGN_ARN,
  userId:      "user-42",
  numResults:  10,
  promotions: [
    {
      name:            "new-tools-promo",
      percentPromotedItems: 20,   // 20% of results = 2 out of 10 slots
      filterArn:       "arn:aws:personalize:us-east-1:123456789012:filter/new-items-only",
      filterValues:    {},
    },
  ],
}));

// At least 20% of results (rounded up) will satisfy the promotion filter
// Remaining 80% are the standard personalized recommendation

The promotion slots are drawn from the filtered item set that scores highest for the user. If fewer items match the promotion filter than required by percentPromotedItems, Personalize fills as many promotion slots as possible without padding. Up to 1 promotion per request is supported.

Batch inference for offline scoring

Use batch inference to generate recommendations for all users at once and store them in S3 for later serving, analytics, or pre-warming a cache:

import { CreateBatchInferenceJobCommand, DescribeBatchInferenceJobCommand }
  from "@aws-sdk/client-personalize";

// Input format in S3: one JSON object per line (JSONL)
// {"userId": "user-1"}
// {"userId": "user-2"}
// ...

const { batchInferenceJobArn } = await personalize.send(new CreateBatchInferenceJobCommand({
  jobName:       "mcp-recommendations-batch-20261116",
  solutionVersionArn,
  numResults:    25,     // recommendations per user
  roleArn:       "arn:aws:iam::123456789012:role/PersonalizeS3Role",
  jobInput: {
    s3DataSource: { path: "s3://my-bucket/personalize/batch-input/" },
  },
  jobOutput: {
    s3DataDestination: { path: "s3://my-bucket/personalize/batch-output/" },
  },
  batchInferenceJobConfig: {
    itemExplorationConfig: {
      explorationWeight:        "0.3",
      explorationItemAgeCutOff: "30",
    },
  },
  filterArn: excludeViewedFilter,   // apply same filter as real-time calls
}));

// Poll until ACTIVE (minutes to hours depending on user count)
let batchStatus = "";
while (!["ACTIVE", "CREATE FAILED"].includes(batchStatus)) {
  const resp = await personalize.send(new DescribeBatchInferenceJobCommand({
    batchInferenceJobArn,
  }));
  batchStatus = resp.batchInferenceJob!.status!;
  if (batchStatus !== "ACTIVE") await new Promise(r => setTimeout(r, 60_000));
}

// Output format in S3: one JSON object per line
// {"input":{"userId":"user-1"},"output":{"recommendedItems":[{"itemId":"i1","score":0.42},...]}}
// {"input":{"userId":"user-2"},"output":{"recommendedItems":[{"itemId":"i3","score":0.38},...]}}
// Error rows:
// {"input":{"userId":"user-99"},"error":"No item data"}

Batch inference costs $0.067 per user processed. For 10,000 users, a batch job costs approximately $6.70. Use it to pre-compute a "top 25" recommendation cache in a DynamoDB or Redis table — your MCP tool then reads from cache at sub-millisecond latency rather than calling the Personalize runtime at ~50–100ms per request.

Output files are written to the S3 destination with the same key prefix as the input, plus a suffix like .out. For large user bases, the output is split into multiple files. Use an S3 listing or Athena to aggregate.

IAM for runtime calls

The MCP server's runtime execution role needs only three permissions:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "personalize:GetRecommendations",
        "personalize:GetPersonalizedRanking"
      ],
      "Resource": [
        "arn:aws:personalize:us-east-1:123456789012:campaign/mcp-recommendations-prod",
        "arn:aws:personalize:us-east-1:123456789012:campaign/mcp-personalized-ranking"
      ]
    }
  ]
}

Runtime actions use the personalize: IAM prefix but target the personalize-runtime endpoint. Lock down the resource to specific campaign ARNs — do not use "Resource": "*" which would allow calling any campaign in the account. The batch inference job permissions (personalize:CreateBatchInferenceJob) belong in the provisioning role, not the runtime execution role.