Guide · AWS SageMaker · Training Jobs · MCP Tools
SageMaker Training Jobs from MCP Server Tools
MCP tool handlers that launch SageMaker training jobs call CreateTrainingJob and then poll DescribeTrainingJob — there is no synchronous training API, and the job may run for seconds or days depending on dataset size and resource configuration. The minimum viable call requires five things: an algorithm specification (built-in or custom container), input channel definitions pointing to S3, an output configuration for model artifacts, a resource configuration specifying instance type and count, and an IAM role ARN with permissions to read inputs and write outputs. Beyond the minimum, three patterns dominate MCP server integrations: managed spot training saves 60–90% on compute cost by running on spare capacity with automatic checkpointing; training metric definitions let SageMaker parse CloudWatch logs in real-time so an MCP tool can surface loss curves during training; and secondary status polling distinguishes transient states like Downloading or Training from terminal states like Completed or Failed. For batch inference after training see SageMaker Batch Transform; for versioning trained models see SageMaker Model Registry; for preprocessing pipelines before training see SageMaker Processing Jobs.
TL;DR
Call sagemaker.create_training_job(**params). Poll sagemaker.describe_training_job(TrainingJobName=name)["TrainingJobStatus"] — terminal states are Completed, Failed, Stopped. Add EnableManagedSpotTraining=True + CheckpointConfig + StoppingCondition.MaxWaitTimeInSeconds for spot savings. Set MetricDefinitions in AlgorithmSpecification to surface training metrics via sagemaker.list_training_jobs_for_hyperparameter_tuning_job or CloudWatch.
- SageMaker Processing Jobs — data preprocessing and feature engineering before training
- SageMaker Batch Transform — batch inference on training outputs
- SageMaker Model Registry — version and approve trained models
- SageMaker Pipelines — orchestrate training + evaluation as a DAG
- SageMaker Endpoints — deploy trained models for real-time inference
CreateTrainingJob — full parameter anatomy
A complete training job call that launches XGBoost on a CSV dataset from S3 — this covers all required fields and the most commonly used optional ones:
import boto3
import time
sagemaker = boto3.client("sagemaker", region_name="us-east-1")
ROLE_ARN = "arn:aws:iam::123456789012:role/SageMakerExecutionRole"
BUCKET = "my-ml-bucket"
IMAGE_URI = "683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-xgboost:1.7-1"
def launch_training_job(job_name: str, train_s3_uri: str, val_s3_uri: str) -> dict:
"""MCP tool handler: launch a SageMaker XGBoost training job."""
response = sagemaker.create_training_job(
TrainingJobName=job_name,
# Algorithm — built-in image or custom container URI
AlgorithmSpecification={
"TrainingImage": IMAGE_URI,
"TrainingInputMode": "File", # or "Pipe" for large streaming datasets
"EnableSageMakerMetricsTimeSeries": True, # enables metric extraction
"MetricDefinitions": [
{"Name": "train:rmse", "Regex": r"train-rmse:(\S+)"},
{"Name": "validation:rmse", "Regex": r"validation-rmse:(\S+)"},
],
},
# Input channels — each channel maps a name to an S3 path
InputDataConfig=[
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": train_s3_uri,
"S3DataDistributionType": "FullyReplicated",
}
},
"ContentType": "text/csv",
"CompressionType": "None", # or "Gzip"
},
{
"ChannelName": "validation",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": val_s3_uri,
"S3DataDistributionType": "FullyReplicated",
}
},
"ContentType": "text/csv",
"CompressionType": "None",
},
],
# Where to write model artifacts (model.tar.gz)
OutputDataConfig={
"S3OutputPath": f"s3://{BUCKET}/training-output/{job_name}/",
# Optional: "KmsKeyId": "arn:aws:kms:..." for encryption
},
# Compute resources
ResourceConfig={
"InstanceType": "ml.m5.xlarge",
"InstanceCount": 1,
"VolumeSizeInGB": 20,
},
# Maximum wall-clock time the job is allowed to run
StoppingCondition={
"MaxRuntimeInSeconds": 3600, # 1 hour hard limit
},
# Hyperparameters passed to the training script as CLI args
HyperParameters={
"max_depth": "5",
"eta": "0.2",
"num_round": "100",
"objective": "reg:squarederror",
# Note: ALL values must be strings, even numbers
},
RoleArn=ROLE_ARN,
Tags=[
{"Key": "mcp-tool", "Value": "train-model"},
{"Key": "environment", "Value": "production"},
],
)
return {
"training_job_arn": response["TrainingJobArn"],
"job_name": job_name,
}
The TrainingJobName must be unique per AWS account and region — no two jobs can share the same name, even after one completes. A common pattern is to include a timestamp or run ID: f"xgboost-{dataset_version}-{int(time.time())}".
TrainingInputMode controls how data is delivered to the container. File mode (most common) downloads the full dataset from S3 to the instance's EBS volume before training begins — download time counts against MaxRuntimeInSeconds. Pipe mode streams data directly from S3 as the container reads it, reducing startup time for large datasets but requiring streaming-aware training code. FastFile mode (available on select algorithms) uses FUSE mounting for near-instant start with random access.
Polling training job status
Training jobs are asynchronous. After CreateTrainingJob returns successfully (immediately), the job progresses through several states before reaching a terminal state:
TERMINAL_STATES = {"Completed", "Failed", "Stopped"}
POLL_INTERVAL_SECONDS = 30
def wait_for_training_job(job_name: str, timeout_seconds: int = 7200) -> dict:
"""
Poll DescribeTrainingJob until a terminal state is reached.
Returns the final job description dict.
"""
start = time.time()
last_secondary_status = None
while True:
if time.time() - start > timeout_seconds:
raise TimeoutError(
f"Training job {job_name} did not complete within "
f"{timeout_seconds}s"
)
desc = sagemaker.describe_training_job(TrainingJobName=job_name)
status = desc["TrainingJobStatus"]
secondary = desc.get("SecondaryStatus", "")
if secondary != last_secondary_status:
print(f"[{job_name}] {status} / {secondary}")
last_secondary_status = secondary
if status in TERMINAL_STATES:
return desc
time.sleep(POLL_INTERVAL_SECONDS)
def get_model_artifacts_uri(job_name: str) -> str:
"""Return S3 URI of model.tar.gz after a completed training job."""
desc = sagemaker.describe_training_job(TrainingJobName=job_name)
if desc["TrainingJobStatus"] != "Completed":
raise ValueError(
f"Training job {job_name} is {desc['TrainingJobStatus']}, "
"not Completed — no model artifacts available"
)
return desc["ModelArtifacts"]["S3ModelArtifacts"]
TrainingJobStatus (the high-level status) and SecondaryStatus (the fine-grained status) are both useful. TrainingJobStatus has six values: InProgress, Completed, Failed, Stopping, Stopped, and the brief initial Starting. SecondaryStatus provides human-readable operational details: Starting, Downloading, Training, Uploading, Stopping, Stopped, MaxRuntimeExceeded, Interrupted (spot interruption), Failed.
The Interrupted secondary status is specific to managed spot training — it means the spot instance was reclaimed by AWS. In that case, the job automatically resumes on a new spot instance from the latest checkpoint if CheckpointConfig is set. An Interrupted job that cannot be resumed within MaxWaitTimeInSeconds transitions to Stopped.
When TrainingJobStatus is Failed, check desc["FailureReason"] — it contains the error message that caused the failure. Common values: "ClientError: Please ensure that the S3 object exists and is accessible" (data channel misconfigured), "ClientError: Container exited with a non-zero exit code" (training script error), "ResourceLimitExceeded" (account limit hit on instance type).
Managed spot training for 60–90% cost reduction
Spot training runs the job on unused EC2 capacity at a fraction of on-demand price. SageMaker handles interruptions transparently — when a spot instance is reclaimed, the job pauses and resumes on a new instance from the last checkpoint. For MCP servers that trigger periodic retraining, spot training can cut compute costs dramatically:
def launch_spot_training_job(
job_name: str,
train_s3_uri: str,
val_s3_uri: str,
) -> dict:
"""Launch training on spot instances with automatic checkpointing."""
checkpoint_s3_uri = f"s3://{BUCKET}/checkpoints/{job_name}/"
response = sagemaker.create_training_job(
TrainingJobName=job_name,
AlgorithmSpecification={
"TrainingImage": IMAGE_URI,
"TrainingInputMode": "File",
"EnableSageMakerMetricsTimeSeries": True,
"MetricDefinitions": [
{"Name": "train:loss", "Regex": r"train_loss=(\S+)"},
{"Name": "validation:loss", "Regex": r"val_loss=(\S+)"},
],
},
InputDataConfig=[
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": train_s3_uri,
"S3DataDistributionType": "FullyReplicated",
}
},
"ContentType": "application/x-recordio-protobuf",
},
],
OutputDataConfig={
"S3OutputPath": f"s3://{BUCKET}/training-output/{job_name}/",
},
ResourceConfig={
"InstanceType": "ml.p3.2xlarge",
"InstanceCount": 1,
"VolumeSizeInGB": 50,
},
# Spot training requires BOTH of these:
EnableManagedSpotTraining=True,
StoppingCondition={
"MaxRuntimeInSeconds": 3600, # max training time (not counting wait)
"MaxWaitTimeInSeconds": 7200, # max total wall-clock time incl. spot waits
# MaxWaitTimeInSeconds must be >= MaxRuntimeInSeconds
},
# Required for spot training: where to save and restore checkpoints
CheckpointConfig={
"S3Uri": checkpoint_s3_uri,
"LocalPath": "/opt/ml/checkpoints", # must match training script's checkpoint dir
},
HyperParameters={
"epochs": "50",
"learning_rate": "0.001",
"batch_size": "256",
},
RoleArn=ROLE_ARN,
)
return {
"training_job_arn": response["TrainingJobArn"],
"checkpoint_uri": checkpoint_s3_uri,
}
The MaxWaitTimeInSeconds in StoppingCondition is the total time budget including waiting for spot capacity. MaxRuntimeInSeconds is the actual training time limit — waiting for spot instances does not count against it. Setting MaxWaitTimeInSeconds too low (e.g., equal to MaxRuntimeInSeconds) means that a single spot interruption can cause the job to time out without completing even if training would only take a few minutes.
Your training script must save checkpoints to the LocalPath directory periodically (not just at the end). SageMaker copies that directory to S3Uri after each epoch-level save. On resume, the same directory is populated from S3 before training restarts. For TensorFlow use tf.keras.callbacks.ModelCheckpoint; for PyTorch use torch.save(model.state_dict(), "/opt/ml/checkpoints/checkpoint.pt"); for XGBoost use model.save_model("/opt/ml/checkpoints/xgb.model") and pass checkpoint_path hyperparameter.
Spot savings are largest on GPU instance types (p3, p3dn, p4d) where on-demand prices are highest. For CPU-only training (m5, c5), the spot discount is typically 50–70%. Check desc["BillableTimeInSeconds"] vs desc["TrainingTimeInSeconds"] after the job — billable time is the actual compute seconds charged, excluding spot wait time.
Training metrics — extracting loss curves during training
SageMaker parses training container stdout/stderr logs via the regex patterns in MetricDefinitions and publishes matching values to CloudWatch in real-time. An MCP tool can retrieve current training metrics without waiting for the job to complete:
import boto3
import datetime
cloudwatch = boto3.client("cloudwatch", region_name="us-east-1")
def get_training_metrics(job_name: str, metric_name: str = "train:rmse") -> list[dict]:
"""
Retrieve training metric time series from CloudWatch.
Available immediately once the Training secondary status begins.
"""
response = cloudwatch.get_metric_statistics(
Namespace="/aws/sagemaker/TrainingJobs",
MetricName=metric_name,
Dimensions=[
{"Name": "TrainingJobName", "Value": job_name},
],
StartTime=datetime.datetime.utcnow() - datetime.timedelta(hours=24),
EndTime=datetime.datetime.utcnow(),
Period=60, # 1-minute granularity
Statistics=["Average"],
)
return sorted(
[
{
"timestamp": point["Timestamp"].isoformat(),
"value": point["Average"],
}
for point in response["Datapoints"]
],
key=lambda x: x["timestamp"],
)
def describe_training_job_metrics(job_name: str) -> dict:
"""
Get final metrics from DescribeTrainingJob FinalMetricDataList.
Only available after the job reaches Completed status.
"""
desc = sagemaker.describe_training_job(TrainingJobName=job_name)
final_metrics = desc.get("FinalMetricDataList", [])
return {
m["MetricName"]: {
"value": m["Value"],
"timestamp": m["Timestamp"].isoformat(),
}
for m in final_metrics
}
The MetricDefinitions regex must exactly match what your training script prints to stdout or stderr. SageMaker does not capture metrics that don't match a defined pattern — if the job logs "Epoch 10/50 — loss: 0.42, val_loss: 0.51", the regex must be r"loss: (\S+)" not r"loss=(\S+)". Each definition has a Name (the metric key) and a Regex with exactly one capture group whose value is the numeric metric value.
EnableSageMakerMetricsTimeSeries must be True in AlgorithmSpecification for CloudWatch metrics to be published — it defaults to False. Without it, metrics are still collected in FinalMetricDataList after job completion, but the real-time CloudWatch time series are not available.
Built-in algorithms (XGBoost, Linear Learner, BlazingText, etc.) have predefined metric definitions — you don't need to specify MetricDefinitions for them. The metrics are documented per algorithm in the SageMaker Developer Guide. For custom containers, all metrics must be defined explicitly.
Stopping a training job early
An MCP tool can stop a running training job before it completes. The job transitions to Stopping then Stopped; model artifacts are uploaded from whatever checkpoints exist:
def stop_training_job(job_name: str) -> bool:
"""
Request graceful stop of a running training job.
Returns True if the stop request was accepted.
"""
desc = sagemaker.describe_training_job(TrainingJobName=job_name)
if desc["TrainingJobStatus"] not in {"InProgress", "Starting"}:
return False # already in a terminal state or stopping
sagemaker.stop_training_job(TrainingJobName=job_name)
return True
def list_active_training_jobs(name_prefix: str | None = None) -> list[dict]:
"""List currently running or starting training jobs."""
kwargs = {"StatusEquals": "InProgress"}
if name_prefix:
kwargs["NameContains"] = name_prefix
response = sagemaker.list_training_jobs(**kwargs)
return [
{
"job_name": j["TrainingJobName"],
"status": j["TrainingJobStatus"],
"created_at": j["CreationTime"].isoformat(),
}
for j in response["TrainingJobSummaries"]
]
StopTrainingJob sends a SIGTERM to the training container. The container has approximately 120 seconds to save a final checkpoint before SageMaker forcibly terminates it. Well-written training scripts catch SIGTERM and flush the current checkpoint — this is especially important for spot training where interruptions also arrive as SIGTERM.
Stopping a spot training job saves the checkpoint in S3 so the job can be restarted later by launching a new training job with the same CheckpointConfig.S3Uri and including a hyperparameter pointing to the checkpoint path. The original stopped job cannot be restarted; a new job must be created.
Distributed training for large datasets
Setting InstanceCount > 1 in ResourceConfig enables distributed training. SageMaker handles cluster provisioning, but your training script must be written for distributed execution:
def launch_distributed_training_job(
job_name: str,
train_s3_uri: str,
) -> dict:
"""Launch a distributed training job on 4 instances."""
response = sagemaker.create_training_job(
TrainingJobName=job_name,
AlgorithmSpecification={
"TrainingImage": "763104351884.dkr.ecr.us-east-1.amazonaws.com/pytorch-training:2.1.0-gpu-py310-cu121-ubuntu20.04-sagemaker",
"TrainingInputMode": "FastFile",
},
InputDataConfig=[
{
"ChannelName": "train",
"DataSource": {
"S3DataSource": {
"S3DataType": "S3Prefix",
"S3Uri": train_s3_uri,
# ShardedByS3Key distributes data partitions across instances
"S3DataDistributionType": "ShardedByS3Key",
}
},
},
],
OutputDataConfig={
"S3OutputPath": f"s3://{BUCKET}/distributed-output/{job_name}/",
},
ResourceConfig={
"InstanceType": "ml.p3.16xlarge",
"InstanceCount": 4, # 4 instances, 8 GPUs each = 32 GPUs total
"VolumeSizeInGB": 100,
},
# SageMaker distributed training library (data parallel)
HyperParameters={
"sagemaker_program": "train.py",
"sagemaker_submit_directory": f"s3://{BUCKET}/code/train.tar.gz",
"sagemaker_distributed_dataparallel_enabled": "true",
"sagemaker_instance_count": "4",
"sagemaker_num_gpus": "8",
},
StoppingCondition={"MaxRuntimeInSeconds": 86400},
RoleArn=ROLE_ARN,
)
return response
For distributed training, use S3DataDistributionType: "ShardedByS3Key" so each instance receives a different subset of the training data rather than the full dataset. FullyReplicated copies the entire dataset to every instance, which is correct for some algorithms (e.g., gradient boosting) but wastes network time for large datasets with data-parallel neural networks.
SageMaker provides two distributed training libraries for PyTorch and TensorFlow: the data parallel library (all instances process different data shards, gradients are averaged) and the model parallel library (the model itself is split across GPUs for models too large for a single GPU). The model parallel library is configured via ModelParallelism in a separate DebugHookConfig extension. For most fine-tuning scenarios, the data parallel library is simpler and sufficient.
IAM permissions required
The execution role ARN passed to CreateTrainingJob must have permissions to read training data, write artifacts, pull the container image, and publish metrics. The minimum policy:
# Minimum IAM policy for SageMaker training job execution role
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::my-ml-bucket",
"arn:aws:s3:::my-ml-bucket/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": "arn:aws:s3:::my-ml-bucket/training-output/*"
},
{
"Effect": "Allow",
"Action": [
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"ecr:GetAuthorizationToken"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:log-group:/aws/sagemaker/TrainingJobs/*"
},
{
"Effect": "Allow",
"Action": "cloudwatch:PutMetricData",
"Resource": "*"
}
]
}
# The role must also have this trust policy:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "sagemaker.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}
The calling IAM identity (your MCP server's Lambda role, ECS task role, or EC2 instance profile) also needs sagemaker:CreateTrainingJob, sagemaker:DescribeTrainingJob, sagemaker:StopTrainingJob, and iam:PassRole (to pass the execution role to SageMaker). Missing iam:PassRole produces an AccessDeniedException with the message "not authorized to perform iam:PassRole" — it's a separate permission from the training job permissions.
Key gotchas
- TrainingJobName must be globally unique per account+region, forever. Completed and failed jobs still occupy their name — you cannot reuse it. Always append a timestamp or UUID. Using a fixed name causes
ResourceInUseon the second run. - All HyperParameters values must be strings.
HyperParametersis adict[str, str]. Passing"max_depth": 5(integer) raises aParamValidationErrorbefore the API call even leaves the client. Usestr()on all numeric values. - MaxWaitTimeInSeconds must be >= MaxRuntimeInSeconds for spot training. If
MaxWaitTimeInSecondsis less thanMaxRuntimeInSeconds, SageMaker raises aValidationException. A common default: setMaxRuntimeInSecondsto the expected training duration × 1.5, andMaxWaitTimeInSecondstoMaxRuntimeInSeconds× 2. - Checkpoint LocalPath must match the path used in your training script. If the training script saves to
/opt/ml/checkpointsbutCheckpointConfig.LocalPathsays/checkpoints, no checkpoints are synced to S3. The mismatch produces no error — the job runs but spot resumption starts from scratch. - File mode download time counts against MaxRuntimeInSeconds. A 100 GB dataset on
ml.m5.xlarge(1 Gbps network) takes ~15 minutes to download before training begins. IfMaxRuntimeInSecondsis too tight, the job times out during download. UseFastFilemode or add a buffer of at least 20% over expected download time. - DescribeTrainingJob before job appears in control plane raises ResourceNotFound. There's a brief delay (usually under 5 seconds) between
CreateTrainingJobreturning and the job appearing inDescribeTrainingJob. If you poll immediately in a tight loop, add a 5-second sleep before the first describe call or catchResourceNotFoundException. - Built-in algorithm images are region-specific. The ECR image URI for XGBoost in
us-east-1is different fromeu-west-1. Use thesagemakerPython SDK'simage_uris.retrieve()helper to get the correct URI for your region rather than hardcoding. - FinalMetricDataList is only populated for jobs with EnableSageMakerMetricsTimeSeries=True. Without it, the field is an empty list even if MetricDefinitions were specified. The metrics exist in CloudWatch logs but not in the structured
FinalMetricDataListfield.