Guide · Amazon Personalize · Event Tracking
Amazon Personalize Event Tracking for MCP Servers — PutEvents, PutUsers, PutItems, and Coldstart
Amazon Personalize improves its recommendations in near-real-time when you stream interaction events back to it. The @aws-sdk/client-personalize-events SDK provides three write operations: PutEventsCommand to record user interactions (clicks, invocations, completions), PutUsersCommand to update user metadata without a full S3 import job, and PutItemsCommand to add or update catalog items incrementally. This guide covers all three, impression-based training for rejected items, closing the recommendation feedback loop via RECOMMENDATION_ID, coldstart session handling for anonymous MCP sessions, and the per-event property schema requirements.
TL;DR
Create an event tracker with CreateEventTrackerCommand — it returns a trackingId that you embed in every PutEventsCommand call. Each event in the eventList needs at minimum: eventType (string), sentAt (Date), and properties (a JSON string with {"itemId": "..."}). Impressions and recommendationId are optional but strongly improve model quality. Use the events SDK package (@aws-sdk/client-personalize-events), not the management or runtime packages.
Why real-time events matter
Batch imports via S3 are a snapshot in time. A user who invokes five new MCP tools after the last import has no interaction signal for those tools until the next import runs. Without real-time event tracking, Personalize models are always stale — the feedback loop from recommendation to signal is broken.
With PutEventsCommand, new interactions are incorporated into the model's inference engine within minutes (not at the next training job). The model uses these recent interactions for user representation updates even without retraining the full solution version. This is called online learning at the inference layer.
Creating an event tracker
An event tracker is the bridge between your application and the Interactions dataset. It returns a trackingId that authenticates your event submissions:
import { PersonalizeClient, CreateEventTrackerCommand,
DescribeEventTrackerCommand } from "@aws-sdk/client-personalize";
const personalize = new PersonalizeClient({ region: "us-east-1" });
const { eventTrackerId, trackingId } = await personalize.send(new CreateEventTrackerCommand({
name: "mcp-event-tracker",
datasetGroupArn: "arn:aws:personalize:us-east-1:123456789012:dataset-group/mcp-tools-recommendations",
}));
// Store trackingId — you need it in every PutEventsCommand call
// eventTrackerId is the management ID; trackingId is the runtime credential
console.log("Tracking ID:", trackingId);
// "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" (UUID format)
One event tracker per dataset group is the standard pattern. trackingId is a UUID that you should store in environment configuration — treat it like an API key (it authenticates writes to your dataset). An event tracker does not require IAM credentials in the PutEventsCommand call itself when called from within your AWS account with appropriate IAM permissions on the events endpoint; the trackingId routes the event to the correct dataset group.
Sending events with PutEventsCommand
Install the events package separately — it ships as its own SDK client:
npm install @aws-sdk/client-personalize-events
import {
PersonalizeEventsClient,
PutEventsCommand,
} from "@aws-sdk/client-personalize-events";
const eventsClient = new PersonalizeEventsClient({ region: "us-east-1" });
await eventsClient.send(new PutEventsCommand({
trackingId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // from CreateEventTrackerCommand
userId: "user-42",
sessionId: "sess-20261116-abc123", // group events in one browsing/agent session
eventList: [
{
eventId: "evt-" + Date.now(), // optional deduplication ID; Personalize ignores re-sent eventIds
eventType: "invoke", // must match EVENT_TYPE values in your schema
sentAt: new Date(), // timestamp of the interaction
itemId: "tool-database-query-mcp", // the item the user interacted with
properties: JSON.stringify({ // must be a JSON string
itemId: "tool-database-query-mcp", // REQUIRED: itemId in properties
// Additional metadata keys that match your Interactions schema fields
// EVENT_VALUE maps to a numeric strength signal (optional)
}),
},
],
}));
The properties field is a JSON-encoded string (not an object). It must contain at minimum {"itemId": "..."}. This is a common source of errors: passing a JavaScript object directly instead of JSON.stringify({...}) causes a silent failure where the event is accepted (HTTP 200) but the itemId is not extracted, so the interaction is recorded with no item association.
Impression data — training on rejected items
Impression data records which items were visible to the user when they made their choice. This is the most valuable signal for improving recommendation quality because it tells the model what the user did not choose from the available options:
// Your MCP tool returned these 10 recommendations to the user
const recommendedItems = [
"tool-search-mcp",
"tool-database-query-mcp",
"tool-read-file-mcp",
"tool-write-file-mcp",
"tool-execute-code-mcp",
"tool-send-email-mcp",
"tool-create-ticket-mcp",
"tool-schedule-meeting-mcp",
"tool-get-weather-mcp",
"tool-translate-text-mcp",
];
// The user invoked only tool-database-query-mcp
await eventsClient.send(new PutEventsCommand({
trackingId: TRACKING_ID,
userId: "user-42",
sessionId: "sess-20261116-abc123",
eventList: [
{
eventType: "invoke",
sentAt: new Date(),
itemId: "tool-database-query-mcp", // what the user chose
impression: recommendedItems, // ALL items that were shown (array of itemIds)
properties: JSON.stringify({ itemId: "tool-database-query-mcp" }),
},
],
}));
The impression array trains the model that the user was exposed to 9 other items and chose not to invoke them. Without impression data, the model sees only positive interactions (what was clicked/invoked) and has no signal about what was rejected. Impression-trained models typically show 10–30% improvement in recommendation precision for the same dataset.
Include the chosen item in the impression array — it represents the full context the user saw. If you do not have impression tracking in your MCP server today (i.e., you do not log what was shown), add it before instrumenting PutEvents — capturing the impression list at the same time as the click is far easier than retrofitting it later.
Closing the feedback loop with RECOMMENDATION_ID
When a recommendation leads to an interaction, pass the recommendationId back via the event to close the feedback loop. This enables Personalize's online metrics to attribute the interaction to the specific recommendation that triggered it:
// 1. Get recommendations and capture the recommendationId
const result = await runtime.send(new GetRecommendationsCommand({
campaignArn: CAMPAIGN_ARN,
userId: "user-42",
numResults: 10,
}));
const { recommendationId, itemList } = result;
// 2. Present items to user, capture what they interacted with
// (In an MCP server: return item list, then capture the tool the agent invoked next)
// 3. When the user interacts with an item, send the event with recommendationId
await eventsClient.send(new PutEventsCommand({
trackingId: TRACKING_ID,
userId: "user-42",
sessionId: "sess-20261116-abc123",
eventList: [
{
eventType: "invoke",
sentAt: new Date(),
itemId: "tool-database-query-mcp",
recommendationId: recommendationId!, // links this event to the recommendation
impression: itemList!.map(i => i.itemId!),
properties: JSON.stringify({ itemId: "tool-database-query-mcp" }),
},
],
}));
recommendationId is returned by both GetRecommendationsCommand and GetPersonalizedRankingCommand. It is a UUID that Personalize uses internally for A/B testing attribution and recommendation quality metrics. It is optional in PutEventsCommand but enables the DescribeDataset online metrics dashboard in the Personalize console to show click-through rates per campaign.
Coldstart: anonymous sessions before user authentication
MCP servers often handle requests before a user identity is established — during an OAuth flow, before first login, or in multi-turn agent sessions where the user is identified mid-conversation. Personalize handles this via session-scoped event tracking:
// Before user logs in: use sessionId only (userId is omitted or empty string)
// Personalize records these as anonymous interactions associated with the session
await eventsClient.send(new PutEventsCommand({
trackingId: TRACKING_ID,
userId: "", // empty string = anonymous / pre-auth
sessionId: "sess-anonymous-20261116-xyz", // stable session ID from cookie or agent context
eventList: [
{
eventType: "view",
sentAt: new Date(),
itemId: "tool-search-mcp",
properties: JSON.stringify({ itemId: "tool-search-mcp" }),
},
],
}));
// When the user authenticates — send the SAME sessionId with the now-known userId
// Personalize links the anonymous session interactions to this user
await eventsClient.send(new PutEventsCommand({
trackingId: TRACKING_ID,
userId: "user-42", // now known
sessionId: "sess-anonymous-20261116-xyz", // SAME sessionId as before login
eventList: [
{
eventType: "invoke",
sentAt: new Date(),
itemId: "tool-database-query-mcp",
properties: JSON.stringify({ itemId: "tool-database-query-mcp" }),
},
],
}));
The session linkage is Personalize's mechanism for coldstart identity resolution: anonymous interactions from the session are retrospectively attributed to the user when the first authenticated event arrives with the same sessionId. Use a stable session identifier (not a per-request UUID) — if the session ID changes between the anonymous phase and the authenticated phase, the linkage is lost.
Incremental user metadata updates with PutUsersCommand
When a user upgrades their plan, changes their role, or any user attribute changes, use PutUsersCommand to update their metadata without re-uploading the full Users dataset from S3:
import { PutUsersCommand } from "@aws-sdk/client-personalize-events";
await eventsClient.send(new PutUsersCommand({
datasetArn: "arn:aws:personalize:us-east-1:123456789012:dataset/mcp-tools-recommendations/USERS",
users: [
{
userId: "user-42",
properties: JSON.stringify({
PLAN_TIER: "team", // was "author", now upgraded to "team"
}),
},
{
userId: "user-99",
properties: JSON.stringify({
PLAN_TIER: "enterprise",
}),
},
],
// Max 10 users per call
}));
The properties value must be a JSON string (not an object). Property keys must match your Users schema field names exactly (the reserved-name case: PLAN_TIER, not planTier). Updates are incremental — only the specified keys are updated, existing keys that are not mentioned are preserved. To delete a property, explicitly set it to null in the properties JSON: {"PLAN_TIER": null}.
PutUsersCommand accepts up to 10 users per request. For bulk updates (e.g., syncing plan tier changes from a billing webhook), batch them in groups of 10:
async function batchPutUsers(users: Array<{userId: string, planTier: string}>) {
const BATCH_SIZE = 10;
for (let i = 0; i < users.length; i += BATCH_SIZE) {
const batch = users.slice(i, i + BATCH_SIZE);
await eventsClient.send(new PutUsersCommand({
datasetArn: USERS_DATASET_ARN,
users: batch.map(u => ({
userId: u.userId,
properties: JSON.stringify({ PLAN_TIER: u.planTier }),
})),
}));
// Small delay to avoid ThrottlingException (Personalize limits: 10 req/sec for PutUsers)
if (i + BATCH_SIZE < users.length) await new Promise(r => setTimeout(r, 110));
}
}
Incremental item catalog updates with PutItemsCommand
Use PutItemsCommand when new tools, documents, or catalog items are added and you do not want to wait for the next scheduled S3 batch import:
import { PutItemsCommand } from "@aws-sdk/client-personalize-events";
await eventsClient.send(new PutItemsCommand({
datasetArn: "arn:aws:personalize:us-east-1:123456789012:dataset/mcp-tools-recommendations/ITEMS",
items: [
{
itemId: "tool-new-mcp-integration",
properties: JSON.stringify({
CATEGORY: "integration",
CONTENT_TYPE: "mcp-tool",
CREATION_TIMESTAMP: Math.floor(Date.now() / 1000), // Unix seconds
}),
},
],
// Max 10 items per call
}));
New items added via PutItemsCommand become visible to the recommendation model within a few minutes but are in cold-start (no interaction history). They will appear in recommendations only when:
- The campaign has
explorationWeight > 0(the default is 0.3) — exploration slots can surface new items - Or real-time interaction events (
PutEventsCommand) accumulate enough signal to rank the item above the exploration floor - Or the next full solution version training run completes
The CREATION_TIMESTAMP reserved field (Unix seconds) is used by the exploration algorithm to prioritize newer items. Items without CREATION_TIMESTAMP are treated as old for exploration purposes, reducing the chance they surface in the exploration slots even when explorationItemAgeCutOff is set.
Event type conventions for MCP servers
Establish consistent event type names before you start recording — changing them later requires a schema migration and re-import:
| eventType | MCP server meaning | Signal strength |
|---|---|---|
invoke | User or agent called the tool | High positive |
complete | Tool invocation completed successfully | High positive |
error | Tool invocation failed or was rejected | Weak negative |
view | Tool was shown in a listing or search result | Low positive (use with impressions) |
skip | Tool was shown but explicitly deselected | Moderate negative |
bookmark | User saved tool to a shortlist or favorites | Strong positive |
Personalize treats all event types as positive interactions by default unless you use EVENT_VALUE to signal strength (0.0 = strong negative, 1.0 = strong positive). If you want error or skip events to suppress an item in recommendations, weight them with a low EVENT_VALUE in the event properties and ensure your Interactions schema includes EVENT_VALUE as a nullable float field.
IAM for event tracking
The MCP server runtime role needs three permissions for the events plane:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"personalize:PutEvents",
"personalize:PutUsers",
"personalize:PutItems"
],
"Resource": "arn:aws:personalize:us-east-1:123456789012:event-tracker/mcp-event-tracker"
}
]
}
Note: PutUsers and PutItems target the event tracker ARN, not the dataset ARN, for IAM purposes. The dataset ARN appears in the SDK request body but is not the IAM resource for these actions. PutEvents does not require dataset ARN in the request at all — only the trackingId is used for routing.