Guide · AWS SageMaker · Model Registry · MLOps · MCP Tools
SageMaker Model Registry from MCP Server Tools
SageMaker Model Registry stores versioned model packages in a ModelPackageGroup and gates deployments behind an approval workflow — only Approved model versions can be deployed to production endpoints. Every model version (a ModelPackage) records the container image, model artifacts S3 URI, supported instance types, and optional quality metrics from evaluation jobs. This creates an auditable history: for each deployed model you can trace back to the training job, dataset, and evaluation scores that produced it. For MCP servers, the registry is most useful in three scenarios: automated training pipelines that register and auto-approve models when evaluation metrics pass a threshold; human-in-the-loop workflows where an MCP tool surfaces pending approval requests; and deployment gating where an MCP tool deploys only the latest approved version. For training the models that get registered see SageMaker Training Jobs; for evaluation that feeds quality metrics see SageMaker Processing Jobs; for deploying registered models to endpoints see SageMaker Endpoints; for orchestrating the full workflow see SageMaker Pipelines.
TL;DR
Create a ModelPackageGroup once per model family. Register versions with CreateModelPackage (requires InferenceSpecification). Versions start as PendingManualApproval — approve with UpdateModelPackage(ModelApprovalStatus="Approved"). Deploy the latest approved version by passing its ARN to create_model(ModelPackageName=arn) then creating an endpoint config and endpoint.
- SageMaker Training Jobs — produce model artifacts to register
- SageMaker Processing Jobs — generate evaluation metrics for registration
- SageMaker Batch Transform — batch score using a registered model version
- SageMaker Endpoints — deploy approved model versions to real-time endpoints
- SageMaker Pipelines — RegisterModel step in automated ML workflows
ModelPackageGroup — the container for model versions
A ModelPackageGroup is a named container that holds all versions of a model family. Create it once and reuse it across training runs:
import boto3
sagemaker = boto3.client("sagemaker", region_name="us-east-1")
def create_model_package_group(
group_name: str,
description: str,
) -> str:
"""
Create a ModelPackageGroup (do this once per model family).
Returns the ModelPackageGroupArn.
"""
response = sagemaker.create_model_package_group(
ModelPackageGroupName=group_name,
ModelPackageGroupDescription=description,
Tags=[
{"Key": "team", "Value": "ml-platform"},
{"Key": "use-case", "Value": "churn-prediction"},
],
)
return response["ModelPackageGroupArn"]
def get_or_create_model_package_group(group_name: str) -> str:
"""Get the group ARN if it exists, create it if not."""
try:
response = sagemaker.describe_model_package_group(
ModelPackageGroupName=group_name
)
return response["ModelPackageGroupArn"]
except sagemaker.exceptions.from_code("ValidationException"):
# Group doesn't exist — create it
return create_model_package_group(group_name, f"{group_name} model versions")
except Exception:
# describe_model_package_group raises ClientError with code 'ValidationException'
# for non-existent groups in some SDK versions
return create_model_package_group(group_name, f"{group_name} model versions")
ModelPackageGroupName must be unique per AWS account and region. It persists indefinitely until you explicitly delete it with DeleteModelPackageGroup. Use a naming convention that reflects the model's purpose and production lineage: "churn-prediction-prod", "recommender-v2-eu". Group names appear in deployment audit logs, so clarity matters.
CreateModelPackage — registering a model version
Each model version is a ModelPackage within a group. The InferenceSpecification is required — it describes the container image and supported content types for serving the model:
ROLE_ARN = "arn:aws:iam::123456789012:role/SageMakerExecutionRole"
IMAGE_URI = "683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-xgboost:1.7-1"
BUCKET = "my-ml-bucket"
def register_model_version(
group_name: str,
model_artifact_s3_uri: str,
training_job_name: str,
evaluation_metrics_s3_uri: str | None = None,
auto_approve: bool = False,
) -> dict:
"""
Register a trained model as a new version in the Model Registry.
Returns the ModelPackageArn and version number.
"""
model_package_kwargs = {
"ModelPackageGroupName": group_name,
"ModelPackageDescription": f"Trained from {training_job_name}",
# Required: describes how to serve this model
"InferenceSpecification": {
"Containers": [
{
"Image": IMAGE_URI,
"ModelDataUrl": model_artifact_s3_uri,
# Optional: environment variables for the inference container
"Environment": {
"SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
},
# Optional: framework version for SageMaker Studio display
"Framework": "XGBOOST",
"FrameworkVersion": "1.7",
}
],
# Supported request content types for real-time and batch inference
"SupportedContentTypes": ["text/csv", "application/json"],
"SupportedResponseMIMETypes": ["text/csv", "application/json"],
# Supported instance types for endpoints and transform jobs
"SupportedRealtimeInferenceInstanceTypes": [
"ml.m5.large", "ml.m5.xlarge", "ml.m5.2xlarge",
],
"SupportedTransformInstanceTypes": [
"ml.m5.large", "ml.m5.xlarge", "ml.m5.2xlarge",
],
},
# Approval status: PendingManualApproval (default) or Approved
"ModelApprovalStatus": "Approved" if auto_approve else "PendingManualApproval",
# Tag with training job metadata for traceability
"CustomerMetadataProperties": {
"training-job-name": training_job_name,
"registered-by": "mcp-tool",
},
"Tags": [
{"Key": "source-training-job", "Value": training_job_name},
],
}
# Attach evaluation metrics if provided (from a processing job evaluation run)
if evaluation_metrics_s3_uri:
model_package_kwargs["ModelMetrics"] = {
"ModelQuality": {
"Statistics": {
"ContentType": "application/json",
"S3Uri": evaluation_metrics_s3_uri,
}
}
}
response = sagemaker.create_model_package(**model_package_kwargs)
arn = response["ModelPackageArn"]
# Extract version number from ARN — it's the last segment
version = int(arn.split("/")[-1])
return {
"model_package_arn": arn,
"version": version,
"approval_status": "Approved" if auto_approve else "PendingManualApproval",
}
InferenceSpecification.Containers describes how the model is served. For models packaged as a single container, provide one entry. For inference pipelines (preprocessing container → model container), provide multiple containers in order — SageMaker chains requests through them in sequence during inference.
ModelDataUrl must be an S3 URI ending in model.tar.gz — the same artifact produced by a training job's OutputDataConfig. SageMaker extracts the archive to /opt/ml/model/ before serving predictions. The execution role must have s3:GetObject permission on the model artifact S3 URI.
Approval status — the deployment gate
Model packages have three approval states. Only Approved versions can be deployed to production endpoints when approval-gated deployment pipelines are used:
def approve_model_version(model_package_arn: str, reason: str = "") -> None:
"""Approve a model version for deployment."""
sagemaker.update_model_package(
ModelPackageName=model_package_arn,
ModelApprovalStatus="Approved",
ApprovalDescription=reason, # optional comment visible in Studio
)
def reject_model_version(model_package_arn: str, reason: str) -> None:
"""Reject a model version (e.g., evaluation metrics below threshold)."""
sagemaker.update_model_package(
ModelPackageName=model_package_arn,
ModelApprovalStatus="Rejected",
ApprovalDescription=reason,
)
def auto_approve_if_metrics_pass(
model_package_arn: str,
evaluation_s3_uri: str,
min_accuracy: float = 0.90,
) -> dict:
"""
Read evaluation metrics from S3 and approve the model if they exceed the threshold.
"""
import json
import boto3
s3 = boto3.client("s3")
bucket, key = evaluation_s3_uri.replace("s3://", "").split("/", 1)
response = s3.get_object(Bucket=bucket, Key=key)
metrics = json.loads(response["Body"].read())
accuracy = metrics["classification_metrics"]["accuracy"]["value"]
if accuracy >= min_accuracy:
approve_model_version(
model_package_arn,
reason=f"Auto-approved: accuracy={accuracy:.4f} >= threshold={min_accuracy}",
)
return {"approved": True, "accuracy": accuracy}
else:
reject_model_version(
model_package_arn,
reason=f"Auto-rejected: accuracy={accuracy:.4f} < threshold={min_accuracy}",
)
return {"approved": False, "accuracy": accuracy}
# Approval status values:
# "PendingManualApproval" — default; cannot be deployed via approval-gated pipelines
# "Approved" — can be deployed
# "Rejected" — cannot be deployed; excluded from "latest approved" queries
ApprovalDescription is a free-text field (max 1024 characters) that records who approved or rejected the model and why. In a team environment, include the reviewer's name, the evaluation run date, and the key metrics: "Approved by alice@company.com on 2026-11-28. accuracy=0.924, AUC=0.971. Test set: 2026-Q4-holdout." This creates an audit trail without requiring a separate database.
Approval transitions are one-directional in practice but technically bidirectional — you can move a model from Rejected back to PendingManualApproval or directly to Approved if a decision was made in error. All transitions are logged in AWS CloudTrail with the caller's IAM identity.
Listing and querying model versions
def list_model_versions(
group_name: str,
approval_status: str | None = None, # None = all, or "Approved", "Rejected", "PendingManualApproval"
max_results: int = 20,
) -> list[dict]:
"""
List model versions in a group, optionally filtered by approval status.
Returns versions in descending order (newest first).
"""
kwargs = {
"ModelPackageGroupName": group_name,
"SortBy": "CreationTime",
"SortOrder": "Descending",
"MaxResults": max_results,
}
if approval_status:
kwargs["ModelApprovalStatus"] = approval_status
response = sagemaker.list_model_packages(**kwargs)
return [
{
"version": int(pkg["ModelPackageArn"].split("/")[-1]),
"arn": pkg["ModelPackageArn"],
"status": pkg["ModelApprovalStatus"],
"created_at": pkg["CreationTime"].isoformat(),
"description": pkg.get("ModelPackageDescription", ""),
}
for pkg in response["ModelPackageSummaryList"]
]
def get_latest_approved_version(group_name: str) -> dict | None:
"""Return the most recently approved model version, or None if none exist."""
versions = list_model_versions(group_name, approval_status="Approved", max_results=1)
return versions[0] if versions else None
def describe_model_version(model_package_arn: str) -> dict:
"""Get full details of a model package including metrics and inference spec."""
desc = sagemaker.describe_model_package(ModelPackageName=model_package_arn)
return {
"arn": desc["ModelPackageArn"],
"version": int(desc["ModelPackageArn"].split("/")[-1]),
"group": desc["ModelPackageGroupName"],
"status": desc["ModelApprovalStatus"],
"approval_description": desc.get("ApprovalDescription", ""),
"created_at": desc["CreationTime"].isoformat(),
"description": desc.get("ModelPackageDescription", ""),
"metadata": desc.get("CustomerMetadataProperties", {}),
"containers": [
{
"image": c["Image"],
"model_data_url": c.get("ModelDataUrl", ""),
}
for c in desc["InferenceSpecification"]["Containers"]
],
}
list_model_packages supports pagination via a NextToken in the response. For groups with many versions (hundreds or thousands over time), always paginate rather than relying on MaxResults alone. The API returns a maximum of 100 versions per call.
CustomerMetadataProperties (the string-to-string metadata dict attached at registration time) is searchable via list_model_packages with the NameContains filter — but only on the ModelPackageName, not on custom properties. For rich metadata querying (find all models trained on a specific dataset), store metadata in a separate DynamoDB table keyed by model package ARN.
Deploying an approved model version to an endpoint
def deploy_approved_model_version(
group_name: str,
endpoint_name: str,
instance_type: str = "ml.m5.large",
instance_count: int = 1,
) -> dict:
"""
Find the latest approved version in the group and deploy it to an endpoint.
Creates a new SageMaker Model from the ModelPackage, then an endpoint config,
then the endpoint itself.
"""
# Step 1: find latest approved version
latest = get_latest_approved_version(group_name)
if not latest:
raise ValueError(f"No approved model versions found in group {group_name}")
model_package_arn = latest["arn"]
version = latest["version"]
model_name = f"{group_name}-v{version}-{int(__import__('time').time())}"
# Step 2: create a SageMaker Model from the ModelPackage
sagemaker.create_model(
ModelName=model_name,
# Reference the ModelPackage instead of specifying container+artifacts directly
Containers=[{"ModelPackageName": model_package_arn}],
ExecutionRoleArn=ROLE_ARN,
)
# Step 3: create endpoint config
config_name = f"{model_name}-config"
sagemaker.create_endpoint_config(
EndpointConfigName=config_name,
ProductionVariants=[
{
"VariantName": "AllTraffic",
"ModelName": model_name,
"InstanceType": instance_type,
"InitialInstanceCount": instance_count,
"InitialVariantWeight": 1.0,
}
],
)
# Step 4: create or update endpoint
try:
sagemaker.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=config_name,
Tags=[
{"Key": "model-package-arn", "Value": model_package_arn},
{"Key": "model-version", "Value": str(version)},
],
)
action = "created"
except sagemaker.exceptions.from_code("ValidationException") as e:
if "Cannot create already existing endpoint" in str(e):
# Endpoint exists — update to new config (rolling update)
sagemaker.update_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=config_name,
)
action = "updated"
else:
raise
return {
"endpoint_name": endpoint_name,
"model_name": model_name,
"model_package_arn": model_package_arn,
"version": version,
"action": action,
}
def get_pending_approval_requests(group_name: str) -> list[dict]:
"""
List all model versions awaiting manual approval.
Useful for an MCP tool that surfaces approval queues.
"""
return list_model_versions(
group_name,
approval_status="PendingManualApproval",
max_results=50,
)
When creating a SageMaker Model from a ModelPackage, you use Containers=[{"ModelPackageName": model_package_arn}] instead of specifying the image URI and model data URL directly. SageMaker resolves the container specification from the ModelPackage's InferenceSpecification at model creation time. This means changing the container version for a model family only requires registering a new ModelPackage version, not updating every downstream deployment script.
update_endpoint performs a rolling update — SageMaker provisions new instances with the new config before terminating old ones, so the endpoint stays in service. The endpoint status transitions to Updating during the rollout and returns to InService when complete. Use describe_endpoint to poll EndpointStatus if you need to wait for the rollout to finish.
Attaching model metrics at registration
def register_with_full_metrics(
group_name: str,
model_artifact_s3_uri: str,
training_job_name: str,
evaluation_output_prefix: str,
) -> dict:
"""
Register a model version with model quality, bias, and explainability metrics.
evaluation_output_prefix should contain outputs from a processing/clarify job.
"""
response = sagemaker.create_model_package(
ModelPackageGroupName=group_name,
InferenceSpecification={
"Containers": [
{
"Image": IMAGE_URI,
"ModelDataUrl": model_artifact_s3_uri,
}
],
"SupportedContentTypes": ["text/csv"],
"SupportedResponseMIMETypes": ["text/csv"],
"SupportedRealtimeInferenceInstanceTypes": ["ml.m5.large"],
"SupportedTransformInstanceTypes": ["ml.m5.large"],
},
# Model quality metrics (from evaluation job evaluation.json)
ModelMetrics={
"ModelQuality": {
"Statistics": {
"ContentType": "application/json",
"S3Uri": f"{evaluation_output_prefix}/evaluation/evaluation.json",
},
# Optional: constraint file for model monitor baseline
# "Constraints": {
# "ContentType": "application/json",
# "S3Uri": f"{evaluation_output_prefix}/constraints.json",
# },
},
# Bias analysis (from SageMaker Clarify bias job)
# "Bias": {
# "Report": {
# "ContentType": "application/json",
# "S3Uri": f"{evaluation_output_prefix}/bias/analysis.json",
# }
# },
# Explainability (from SageMaker Clarify explainability job)
# "Explainability": {
# "Report": {
# "ContentType": "application/json",
# "S3Uri": f"{evaluation_output_prefix}/explainability/analysis.json",
# }
# },
},
ModelApprovalStatus="PendingManualApproval",
ModelPackageDescription=f"Trained by {training_job_name}",
# Drift check baseline for Model Monitor (optional)
DriftCheckBaselines={
"ModelQuality": {
"Statistics": {
"ContentType": "application/json",
"S3Uri": f"{evaluation_output_prefix}/evaluation/evaluation.json",
}
}
},
CustomerMetadataProperties={
"training-job": training_job_name,
"eval-prefix": evaluation_output_prefix,
},
)
return {
"model_package_arn": response["ModelPackageArn"],
"version": int(response["ModelPackageArn"].split("/")[-1]),
}
The ModelMetrics.ModelQuality.Statistics.S3Uri field should point to a JSON file with the structure {"classification_metrics": {"accuracy": {"value": 0.92}, ...}} — the same format produced by the evaluation processing job pattern in SageMaker Processing Jobs. SageMaker Studio displays this file's values as the model version's quality metrics in the Model Registry UI.
DriftCheckBaselines establishes the reference distribution for Model Monitor. When you later enable continuous quality monitoring on an endpoint, SageMaker compares live predictions against this baseline to detect data or quality drift. Setting this at registration time saves you from having to run a separate baseline job after deployment.
Key gotchas
- InferenceSpecification is required for versioned model packages.
CreateModelPackagewithoutInferenceSpecificationis only valid for non-versioned (standalone) model packages. Within aModelPackageGroup,InferenceSpecificationis mandatory — omitting it raisesValidationException: InferenceSpecification is required for versioned model packages. - Model version numbers are auto-assigned and cannot be set. SageMaker assigns version numbers starting from 1, incrementing with each registration. You cannot specify a version number, skip versions, or register
v5beforev4. Version numbers appear as the last path segment of the ModelPackage ARN:arn:aws:sagemaker:...:model-package/my-group/5. - Approval status changes are audited in CloudTrail but not in DescribeModelPackage history.
DescribeModelPackageshows only the currentModelApprovalStatusandApprovalDescription, not the full status history. For audit trails of who approved what and when, query CloudTrail forUpdateModelPackageevents filtered by the model package ARN. - CustomerMetadataProperties values are strings only, max 256 characters each, max 50 properties. You cannot store nested JSON or large blobs in these properties. For rich metadata, use Tags (max 50 key-value pairs) in addition to CustomerMetadataProperties, or store metadata in a separate DynamoDB table keyed by model package ARN.
- DeleteModelPackageGroup fails if the group contains any model packages. You must delete all model packages in the group first with
DeleteModelPackagebefore deleting the group. There is noforce=Trueoption — this protects against accidentally deleting production model history. - Deploying a model from a ModelPackage ARN uses Containers not PrimaryContainer. When calling
create_modelwith a ModelPackage reference, useContainers=[{"ModelPackageName": arn}], notPrimaryContainer={"ModelPackageName": arn}. UsingPrimaryContainerraises aValidationExceptionfor model package references even though it works for container+artifacts specifications. - list_model_packages returns max 100 per call regardless of MaxResults. Pass
MaxResults=100and paginate usingNextTokenfor groups with many versions. Groups accumulate a new version every training run — a weekly training cadence produces 52 versions per year, so after two years you will need pagination. - ModelMetrics S3 URIs must be accessible by SageMaker's service principal, not just your execution role. If the evaluation output bucket has a restrictive bucket policy, add
sagemaker.amazonaws.comas a principal withs3:GetObjectaccess, or ensure the execution role's trust relationship allows the SageMaker service to assume it and access the files.