Guide · AWS SageMaker · Processing Jobs · Feature Engineering · MCP Tools
SageMaker Processing Jobs from MCP Server Tools
SageMaker Processing Jobs run arbitrary Python scripts on managed compute — they are the standard pattern for data preprocessing, feature engineering, and model evaluation tasks that need more resources than a Lambda function but don't require the full training job lifecycle. Every processing job mounts S3 input paths into the container, runs your script, and uploads the container's output directories back to S3 when the script exits. The low-level API (CreateProcessingJob) is flexible but verbose; the SageMaker Python SDK provides higher-level classes — SKLearnProcessor, ScriptProcessor, and FrameworkProcessor — that handle container image selection and argument formatting. For MCP servers, processing jobs are most useful for three tasks: preprocessing raw data before a training job (tokenization, normalization, train/test splitting); batch model evaluation (computing metrics on a held-out test set after training); and on-demand feature computation (generating embeddings or derived features triggered by an MCP tool call). For model training see SageMaker Training Jobs; for large-scale batch inference see SageMaker Batch Transform; for ML workflow orchestration see SageMaker Pipelines.
TL;DR
Call sagemaker.create_processing_job(**params) with an AppSpecification (container + entrypoint), ProcessingInputs (S3 → container path), ProcessingOutputConfig (container path → S3), and ProcessingResources. Poll sagemaker.describe_processing_job(ProcessingJobName=name)["ProcessingJobStatus"] — terminal states are Completed, Failed, Stopped. For scikit-learn scripts, use SKLearnProcessor from the sagemaker SDK to avoid hardcoding the ECR URI.
- SageMaker Training Jobs — train models on processed feature data
- SageMaker Batch Transform — batch inference without an endpoint
- SageMaker Model Registry — version and approve models after evaluation
- SageMaker Pipelines — ProcessingStep in ML workflow DAGs
- SageMaker Feature Store — write processed features to online/offline stores
CreateProcessingJob — low-level API anatomy
The low-level boto3 call gives full control. This example runs a custom Python script from S3 to preprocess a CSV dataset:
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"
# Scikit-learn container image (region-specific, check AWS docs for your region)
SKLEARN_IMAGE = "683313688378.dkr.ecr.us-east-1.amazonaws.com/sagemaker-scikit-learn:1.2-1-cpu-py3"
def launch_preprocessing_job(
job_name: str,
raw_data_s3_uri: str,
output_s3_prefix: str,
) -> dict:
"""MCP tool handler: preprocess CSV data before a training job."""
response = sagemaker.create_processing_job(
ProcessingJobName=job_name,
# Container and script to run
AppSpecification={
"ImageUri": SKLEARN_IMAGE,
"ContainerEntrypoint": ["python3"],
"ContainerArguments": [
"/opt/ml/processing/code/preprocess.py",
"--input-path", "/opt/ml/processing/input/raw/",
"--output-path", "/opt/ml/processing/output/",
"--test-fraction", "0.2",
],
},
# S3 → container path mappings (inputs are downloaded before script runs)
ProcessingInputs=[
{
"InputName": "raw-data",
"S3Input": {
"S3Uri": raw_data_s3_uri,
"LocalPath": "/opt/ml/processing/input/raw/",
"S3DataType": "S3Prefix",
"S3InputMode": "File",
"S3DataDistributionType": "FullyReplicated",
"S3CompressionType": "None",
},
},
{
"InputName": "code",
"S3Input": {
"S3Uri": f"s3://{BUCKET}/scripts/preprocess.py",
"LocalPath": "/opt/ml/processing/code/",
"S3DataType": "S3Prefix",
"S3InputMode": "File",
},
},
],
# Container paths → S3 (uploaded after script exits successfully)
ProcessingOutputConfig={
"Outputs": [
{
"OutputName": "train",
"S3Output": {
"S3Uri": f"{output_s3_prefix}/train/",
"LocalPath": "/opt/ml/processing/output/train/",
"S3UploadMode": "EndOfJob",
},
},
{
"OutputName": "test",
"S3Output": {
"S3Uri": f"{output_s3_prefix}/test/",
"LocalPath": "/opt/ml/processing/output/test/",
"S3UploadMode": "EndOfJob",
},
},
],
},
# Compute resources
ProcessingResources={
"ClusterConfig": {
"InstanceType": "ml.m5.large",
"InstanceCount": 1,
"VolumeSizeInGB": 20,
}
},
# Wall-clock timeout
StoppingCondition={"MaxRuntimeInSeconds": 3600},
RoleArn=ROLE_ARN,
Environment={
"PYTHONPATH": "/opt/ml/processing/code",
"LOG_LEVEL": "INFO",
},
)
return {
"processing_job_arn": response["ProcessingJobArn"],
"job_name": job_name,
"output_prefix": output_s3_prefix,
}
The AppSpecification.ContainerEntrypoint overrides the container's default entrypoint. For custom scripts you typically set it to ["python3"] and pass the script path as the first element of ContainerArguments. The script must already be in the container (built into the image) or downloaded to the container at runtime via a code input channel.
S3UploadMode: "EndOfJob" (default) uploads outputs after the script exits with status 0. S3UploadMode: "Continuous" uploads files as they appear in the output directory — useful for long-running jobs where you want partial results available in S3 before the job finishes. Continuous mode generates many small S3 PUT operations; use it only when intermediate access is genuinely needed.
SKLearnProcessor — high-level pattern for scikit-learn scripts
The SKLearnProcessor from the SageMaker Python SDK selects the correct ECR image for your chosen scikit-learn version and simplifies input/output specification:
from sagemaker.sklearn.processing import SKLearnProcessor
from sagemaker.processing import ProcessingInput, ProcessingOutput
import sagemaker
# Create a SageMaker session (uses boto3 session under the hood)
session = sagemaker.Session()
def run_sklearn_preprocessing(
job_name: str,
raw_s3_uri: str,
output_prefix: str,
instance_type: str = "ml.m5.large",
) -> dict:
"""
Run a scikit-learn preprocessing script using SKLearnProcessor.
Simpler than the low-level API: no ECR URI hardcoding needed.
"""
processor = SKLearnProcessor(
framework_version="1.2-1",
role=ROLE_ARN,
instance_type=instance_type,
instance_count=1,
volume_size_in_gb=20,
max_runtime_in_seconds=3600,
sagemaker_session=session,
env={"LOG_LEVEL": "DEBUG"},
)
# run() is SYNCHRONOUS by default — it blocks until the job completes
# To run async from an MCP tool, use wait=False
processor.run(
code="preprocess.py", # local file or S3 URI of the script
job_name=job_name,
arguments=[
"--test-fraction", "0.2",
"--label-column", "target",
],
inputs=[
ProcessingInput(
source=raw_s3_uri,
destination="/opt/ml/processing/input/",
input_name="raw-data",
)
],
outputs=[
ProcessingOutput(
source="/opt/ml/processing/output/train/",
destination=f"{output_prefix}/train/",
output_name="train",
),
ProcessingOutput(
source="/opt/ml/processing/output/test/",
destination=f"{output_prefix}/test/",
output_name="test",
),
],
wait=False, # return immediately; poll status separately
logs=False, # don't stream logs to stdout in the MCP server process
)
return {
"job_name": processor.latest_job.job_name,
"output_prefix": output_prefix,
}
def get_sklearn_job_status(job_name: str) -> str:
"""Poll the processing job status."""
desc = sagemaker.Session().sagemaker_client.describe_processing_job(
ProcessingJobName=job_name
)
return desc["ProcessingJobStatus"]
processor.run(wait=False) returns immediately after submitting the job. The processor.latest_job attribute holds a ProcessingJob object with the job name. For MCP servers, always use wait=False — blocking an MCP tool handler thread for the duration of a processing job (minutes to hours) is never correct.
When code="preprocess.py" is a local file path (not an S3 URI), the SDK uploads it to S3 automatically before submitting the job. The upload destination is s3://<default-bucket>/<base-job-name>/input/code/preprocess.py. The script is injected as a processing input with InputName="code".
ScriptProcessor — custom containers for any runtime
ScriptProcessor works like SKLearnProcessor but lets you specify any container image — useful for Node.js, R, or custom Python environments with non-standard dependencies:
from sagemaker.processing import ScriptProcessor, ProcessingInput, ProcessingOutput
def run_custom_processing_job(
job_name: str,
input_s3_uri: str,
output_s3_prefix: str,
custom_image_uri: str,
) -> dict:
"""
Run a processing script in a custom container image.
Use when the script needs libraries not available in built-in images.
"""
processor = ScriptProcessor(
image_uri=custom_image_uri, # your ECR image with custom dependencies
command=["python3"],
role=ROLE_ARN,
instance_type="ml.m5.xlarge",
instance_count=1,
volume_size_in_gb=30,
max_runtime_in_seconds=7200,
env={
"MODEL_ENDPOINT": "https://api.example.com",
"API_KEY": "fetch-from-ssm-at-runtime", # fetch from SSM Parameter Store inside the script
},
)
processor.run(
code="s3://my-ml-bucket/scripts/extract_features.py", # S3 URI of script
job_name=job_name,
arguments=["--batch-size", "1000"],
inputs=[
ProcessingInput(
source=input_s3_uri,
destination="/opt/ml/processing/input/",
)
],
outputs=[
ProcessingOutput(
source="/opt/ml/processing/output/",
destination=output_s3_prefix,
)
],
wait=False,
logs=False,
)
return {"job_name": processor.latest_job.job_name}
# Low-level status polling (works for all processor types)
TERMINAL_PROCESSING_STATES = {"Completed", "Failed", "Stopped"}
def wait_for_processing_job(job_name: str, poll_interval: int = 30) -> dict:
while True:
desc = sagemaker.describe_processing_job(ProcessingJobName=job_name)
status = desc["ProcessingJobStatus"]
if status in TERMINAL_PROCESSING_STATES:
if status == "Failed":
raise RuntimeError(
f"Processing job {job_name} failed: {desc.get('FailureReason', 'unknown')}"
)
return desc
time.sleep(poll_interval)
ScriptProcessor passes your script to the container by uploading it to S3 and injecting it as a processing input — the same mechanism as SKLearnProcessor. The key difference is that command=["python3"] must be a valid executable inside your container. If your image uses Node.js, set command=["node"].
Model evaluation — computing test metrics after training
A common MCP workflow pattern: after a training job completes, launch a processing job to evaluate the model on the test set and write a metrics JSON file to S3 that feeds the Model Registry:
from sagemaker.processing import ScriptProcessor, ProcessingInput, ProcessingOutput
EVAL_SCRIPT = """
import json
import os
import tarfile
import joblib
import pandas as pd
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
# SageMaker mounts inputs to these paths
MODEL_DIR = "/opt/ml/processing/model/"
TEST_DATA_DIR = "/opt/ml/processing/test/"
OUTPUT_DIR = "/opt/ml/processing/evaluation/"
# Extract model from training job artifact
with tarfile.open(os.path.join(MODEL_DIR, "model.tar.gz")) as tar:
tar.extractall(path=MODEL_DIR)
model = joblib.load(os.path.join(MODEL_DIR, "model.joblib"))
# Load test data
test_df = pd.read_csv(os.path.join(TEST_DATA_DIR, "test.csv"))
X_test = test_df.drop("label", axis=1)
y_test = test_df["label"]
# Compute metrics
y_pred = model.predict(X_test)
y_prob = model.predict_proba(X_test)[:, 1]
metrics = {
"classification_metrics": {
"accuracy": {"value": float(accuracy_score(y_test, y_pred))},
"f1": {"value": float(f1_score(y_test, y_pred, average="weighted"))},
"roc_auc": {"value": float(roc_auc_score(y_test, y_prob))},
}
}
os.makedirs(OUTPUT_DIR, exist_ok=True)
with open(os.path.join(OUTPUT_DIR, "evaluation.json"), "w") as f:
json.dump(metrics, f, indent=2)
print(f"Evaluation complete: {metrics}")
"""
def launch_model_evaluation_job(
job_name: str,
model_artifact_s3_uri: str, # S3 URI of model.tar.gz from training job
test_data_s3_uri: str,
output_prefix: str,
) -> dict:
"""Launch a processing job to evaluate model quality."""
# Upload evaluation script to S3 first
import boto3
s3 = boto3.client("s3")
s3.put_object(
Bucket=BUCKET,
Key="scripts/evaluate.py",
Body=EVAL_SCRIPT.encode("utf-8"),
)
processor = SKLearnProcessor(
framework_version="1.2-1",
role=ROLE_ARN,
instance_type="ml.m5.large",
instance_count=1,
volume_size_in_gb=20,
max_runtime_in_seconds=1800,
sagemaker_session=sagemaker.Session(),
)
processor.run(
code=f"s3://{BUCKET}/scripts/evaluate.py",
job_name=job_name,
inputs=[
ProcessingInput(
source=model_artifact_s3_uri,
destination="/opt/ml/processing/model/",
input_name="model",
),
ProcessingInput(
source=test_data_s3_uri,
destination="/opt/ml/processing/test/",
input_name="test-data",
),
],
outputs=[
ProcessingOutput(
source="/opt/ml/processing/evaluation/",
destination=f"{output_prefix}/evaluation/",
output_name="evaluation",
)
],
wait=False,
logs=False,
)
return {
"job_name": processor.latest_job.job_name,
"evaluation_output": f"{output_prefix}/evaluation/evaluation.json",
}
The evaluation.json format above matches the structure expected by SageMaker Model Registry's ModelMetrics.ModelQuality field — if you later register the model with CreateModelPackage, you can pass this S3 URI directly as the model quality metrics source. See SageMaker Model Registry for how the evaluation output feeds into model approval workflows.
Processing inputs — S3 data types and distribution modes
The S3DataType and S3DataDistributionType fields in S3Input control what SageMaker downloads and how it distributes data across instances:
# S3DataType options:
# "S3Prefix" — download everything under the given S3 prefix (most common)
# "ManifestFile" — S3 URI of a JSON manifest file listing individual S3 objects
# "AugmentedManifestFile" — manifest with inline attribute values (for Ground Truth)
# S3DataDistributionType options (only relevant when InstanceCount > 1):
# "FullyReplicated" — download full dataset to every instance (default)
# "ShardedByS3Key" — distribute files across instances, each gets a subset
# For single-instance jobs (InstanceCount=1), distribution type doesn't matter.
# For multi-instance processing (e.g., distributing 1TB across 10 instances):
sagemaker.create_processing_job(
ProcessingJobName=job_name,
AppSpecification={
"ImageUri": SKLEARN_IMAGE,
"ContainerEntrypoint": ["python3", "/opt/ml/processing/code/process.py"],
},
ProcessingInputs=[
{
"InputName": "data",
"S3Input": {
"S3Uri": f"s3://{BUCKET}/raw-data/",
"LocalPath": "/opt/ml/processing/input/",
"S3DataType": "S3Prefix",
"S3InputMode": "File",
# Each of the 10 instances gets ~1/10 of the files:
"S3DataDistributionType": "ShardedByS3Key",
},
},
],
ProcessingOutputConfig={
"Outputs": [
{
"OutputName": "processed",
"S3Output": {
"S3Uri": f"s3://{BUCKET}/processed/",
"LocalPath": "/opt/ml/processing/output/",
"S3UploadMode": "EndOfJob",
},
}
]
},
ProcessingResources={
"ClusterConfig": {
"InstanceType": "ml.m5.4xlarge",
"InstanceCount": 10,
"VolumeSizeInGB": 50,
}
},
StoppingCondition={"MaxRuntimeInSeconds": 7200},
RoleArn=ROLE_ARN,
)
ManifestFile mode is useful when you need to process a specific subset of files from a large S3 bucket rather than an entire prefix. The manifest is a JSON file (or JSON Lines file) where each line contains the S3 URI of one input file. SageMaker downloads only the listed files rather than the full prefix.
The S3InputMode: "Pipe" option streams data as a FIFO instead of downloading it first. It is only supported for specific container configurations and is rarely used in processing jobs (it's more common in training jobs). Stick with "File" mode unless you have specific streaming requirements.
Environment variables and secrets injection
Processing jobs support arbitrary environment variables. For secrets (API keys, database passwords), use AWS Secrets Manager or SSM Parameter Store rather than hardcoding values:
import boto3
secrets_manager = boto3.client("secretsmanager", region_name="us-east-1")
def get_secret(secret_name: str) -> str:
"""Fetch a secret value at MCP tool handler time, not inside the container."""
response = secrets_manager.get_secret_value(SecretId=secret_name)
return response["SecretString"]
def launch_processing_with_secrets(job_name: str, input_uri: str) -> dict:
"""
Inject secrets as environment variables at job creation time.
The secret value is fetched once and embedded in the job definition —
it's visible in DescribeProcessingJob response. For higher security,
grant the execution role access to Secrets Manager and fetch inside the script.
"""
db_password = get_secret("prod/db/password")
sagemaker.create_processing_job(
ProcessingJobName=job_name,
AppSpecification={
"ImageUri": SKLEARN_IMAGE,
"ContainerEntrypoint": [
"python3", "/opt/ml/processing/code/ingest.py"
],
},
ProcessingInputs=[
{
"InputName": "code",
"S3Input": {
"S3Uri": f"s3://{BUCKET}/scripts/ingest.py",
"LocalPath": "/opt/ml/processing/code/",
"S3DataType": "S3Prefix",
"S3InputMode": "File",
},
}
],
ProcessingOutputConfig={
"Outputs": [
{
"OutputName": "data",
"S3Output": {
"S3Uri": f"s3://{BUCKET}/ingested/",
"LocalPath": "/opt/ml/processing/output/",
"S3UploadMode": "EndOfJob",
},
}
]
},
ProcessingResources={
"ClusterConfig": {
"InstanceType": "ml.m5.large",
"InstanceCount": 1,
"VolumeSizeInGB": 20,
}
},
StoppingCondition={"MaxRuntimeInSeconds": 1800},
RoleArn=ROLE_ARN,
# Environment variables available inside the container
Environment={
"DB_HOST": "prod-db.cluster-xxxxx.us-east-1.rds.amazonaws.com",
"DB_PORT": "5432",
"DB_PASSWORD": db_password, # fetched before job creation
},
)
return {"job_name": job_name}
Environment variables injected at job creation time are stored in the SageMaker control plane and are visible in the DescribeProcessingJob response. For highly sensitive values, fetch secrets directly inside the container script using the execution role's permissions to call Secrets Manager — the secret value then never appears in job metadata.
Key gotchas
- ProcessingJobName must be unique. Like training jobs, processing job names cannot be reused per account+region. Always append a timestamp or UUID to prevent
ResourceInUseerrors on subsequent runs. - Script exit code 0 triggers output upload; non-zero skips it. If your script raises an uncaught exception and exits with a non-zero code, SageMaker marks the job
Failedand does not upload any output directories to S3. Wrap critical processing logic in try/except and exit cleanly if partial results should still be saved. - All outputs are uploaded from the declared LocalPath regardless of what files exist there. If your script writes output to
/opt/ml/processing/output/results/but theS3Output.LocalPathis/opt/ml/processing/output/, the results subdirectory is included. If the declaredLocalPathis empty, an empty upload succeeds silently — you won't see an error but S3 will have no output files. - SKLearnProcessor.run(wait=False) returns before the job is in a pollable state. There's a brief period after submission where
DescribeProcessingJobreturnsResourceNotFoundException. Sleep 3–5 seconds before the first polling call or catch and retry the first describe call. - VolumeSizeInGB is for the EBS volume on the instance, not RAM. If your script loads the full dataset into memory and your instance has only 8 GB of RAM, it will OOM even with 100 GB of EBS. Size the instance type for in-memory data, not disk storage.
- code= in processor.run() must be a local path or S3 URI, not an S3 file object.
code="s3://bucket/key/script.py"works directly;code=open("script.py")does not. The SDK uploads local files automatically, but the upload destination is under the default SageMaker bucket — ensure your execution role can write to that bucket. - S3DataDistributionType ShardedByS3Key distributes files, not bytes. If you have 10 files of unequal size distributed across 10 instances, one instance may get the 100 GB file while others get 1 MB files. For even distribution, pre-split large files into equal-sized chunks before the processing job or use a manifest file to control the distribution explicitly.
- Processing jobs do not support spot instances. Unlike training jobs, there is no
EnableManagedSpotTrainingequivalent for processing jobs. Use on-demand instances. For cost optimization, use smaller instance types (ml.m5.large is often sufficient for preprocessing) or run preprocessing as a Glue job instead.