Guide · Amazon Bedrock · Model Customization

Amazon Bedrock Custom Model Import for MCP Servers — GGUF, Safetensors, and the ImportedModel API

Bedrock Custom Model Import lets you bring your own model weights — GGUF quantizations from llama.cpp or HuggingFace Safetensors — into Bedrock without provisioning EC2 instances or managing inference infrastructure. You stage the artifacts in an S3 bucket, call CreateModelImportJobCommand, poll until the job reaches Completed status, then invoke the model by its importedModelArn using the standard InvokeModelCommand. The workflow complements Bedrock's built-in fine-tuning: if you fine-tune a base model externally (using a framework like Axolotl or LLaMA-Factory), you can import the resulting weights directly into Bedrock and call them from your MCP server alongside first-party Bedrock models. This guide covers the full import lifecycle, the ListImportedModelsCommand and GetImportedModelCommand APIs, and an MCP server wrapper that handles the native prompt format and ModelNotReadyException retry logic. For Bedrock's managed fine-tuning workflow, see Bedrock Fine-Tuning. For allocating dedicated throughput to an imported model, see Provisioned Throughput.

TL;DR

Upload GGUF or Safetensors weights to S3 in the same region as your import job. Call CreateModelImportJobCommand with an S3 URI pointing to the model directory. Poll GetModelImportJobCommand until status === "Completed". Retrieve the importedModelArn from GetImportedModelCommand. Invoke with InvokeModelCommand using the model's native chat template — imported models do not support ConverseCommand.

What Custom Model Import is — and what it is not

Bedrock Custom Model Import is a hosting service. You supply the weights; Bedrock manages the hardware, scaling, and API endpoint. Once a model is imported, you call it exactly like any other Bedrock model — same SDK, same IAM authorization model, same CloudWatch metrics — but with InvokeModelCommand rather than ConverseCommand. The key distinction from Bedrock's native fine-tuning (CreateModelCustomizationJob) is that the training happens outside AWS. You fine-tune using whatever tooling you prefer, produce a weights artifact, and import the result. The two workflows are complementary: externally fine-tune a Llama 3 8B on domain data, convert the output to GGUF or Safetensors, upload to S3, import into Bedrock, and invoke via your MCP server — without running a single EC2 GPU instance after import.

Bedrock handles capacity differently for imported models than for first-party models. Imported models run on on-demand capacity by default; throughput is not guaranteed. For production MCP servers that require predictable latency, pair the imported model with a Provisioned Throughput allocation.

Supported formats and architectures

Bedrock Custom Model Import supports two weight formats:

FormatSourceNotes
GGUF llama.cpp, HuggingFace GGUF repos Quantized weights. Single .gguf file per model. Quantization level affects quality and memory use — see gotchas below.
Safetensors HuggingFace Hub, Axolotl, LLaMA-Factory output Full-precision or half-precision shards. Upload all .safetensors shard files plus config.json and tokenizer.json to the same S3 prefix.

Supported model architectures include Llama 2, Llama 3, Mistral, and Falcon. Not all architectures are supported — consult the AWS documentation for the current supported architecture list, as it expands with service updates. Attempting to import an unsupported architecture causes the job to fail with a ValidationException describing the incompatibility.

Model weights must reside in an S3 bucket in the same AWS region as the import job. Cross-region S3 URIs are rejected at job creation time. For Safetensors, the S3 prefix (the "directory") must contain all shards — Bedrock reads the prefix recursively, so organize shards under a single common prefix with no unrelated files mixed in.

Package installation and IAM setup

The import job APIs live in @aws-sdk/client-bedrock. Invocation uses @aws-sdk/client-bedrock-runtime. Install both:

npm install @aws-sdk/client-bedrock @aws-sdk/client-bedrock-runtime

The IAM principal running the import job and the MCP server both need a set of permissions. A minimal policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "BedrockImportManagement",
      "Effect": "Allow",
      "Action": [
        "bedrock:CreateModelImportJob",
        "bedrock:GetModelImportJob",
        "bedrock:ListModelImportJobs",
        "bedrock:ListImportedModels",
        "bedrock:GetImportedModel",
        "bedrock:DeleteImportedModel"
      ],
      "Resource": "*"
    },
    {
      "Sid": "BedrockImportedModelInvoke",
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModel",
        "bedrock:InvokeModelWithResponseStream"
      ],
      "Resource": "arn:aws:bedrock:us-east-1:123456789012:imported-model/*"
    },
    {
      "Sid": "S3ModelArtifactsRead",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::my-model-artifacts-bucket",
        "arn:aws:s3:::my-model-artifacts-bucket/*"
      ]
    }
  ]
}

The bedrock:InvokeModel resource ARN uses the imported-model resource type, not foundation-model. Scoping it to imported-model/* allows invocation of any imported model in the account without enumerating individual ARNs, which is practical because importedModelArn values are only known after the import job completes.

CreateModelImportJobCommand — full TypeScript example

The import job is submitted to BedrockClient (not BedrockRuntimeClient). The only required data source field is s3DataSource.s3Uri, which must point to the S3 prefix (directory) containing the model files:

import {
  BedrockClient,
  CreateModelImportJobCommand,
  GetModelImportJobCommand,
  type ModelImportJobStatus,
} from "@aws-sdk/client-bedrock";

const client = new BedrockClient({ region: "us-east-1" });

// Submit the import job
const createResponse = await client.send(new CreateModelImportJobCommand({
  jobName: "llama3-8b-custom-v2-import-20261122",
  importedModelName: "llama3-8b-custom-v2",
  modelDataSource: {
    s3DataSource: {
      // Must be in the same region as the import job.
      // For Safetensors: S3 prefix containing all shards + config.json + tokenizer.json.
      // For GGUF: S3 prefix containing the single .gguf file.
      s3Uri: "s3://my-model-artifacts-bucket/models/llama3-8b-custom-v2/",
    },
  },
  // Optional: tag the job and the resulting imported model resource
  jobTags: [{ key: "project", value: "mcp-inference" }],
  importedModelTags: [
    { key: "project", value: "mcp-inference" },
    { key: "version", value: "v2" },
  ],
}));

const jobArn = createResponse.jobArn!;
console.log("Import job ARN:", jobArn);

// Poll until terminal status
async function waitForImportJob(
  client: BedrockClient,
  jobArn: string,
  pollIntervalMs = 30_000,
): Promise<string> {
  const terminalStatuses = new Set<ModelImportJobStatus>([
    "Completed",
    "Failed",
    "Stopped",
  ]);

  while (true) {
    const statusResponse = await client.send(new GetModelImportJobCommand({
      jobIdentifier: jobArn,
    }));

    const status = statusResponse.status as ModelImportJobStatus;
    console.log(`Job status: ${status} — ${new Date().toISOString()}`);

    if (status === "Completed") {
      // importedModelArn is set once the job succeeds
      const importedModelArn = statusResponse.importedModelArn;
      if (!importedModelArn) {
        throw new Error("Job Completed but importedModelArn is missing");
      }
      return importedModelArn;
    }

    if (terminalStatuses.has(status)) {
      const failureMessage = statusResponse.failureMessage ?? "No failure message provided";
      throw new Error(`Import job reached terminal status ${status}: ${failureMessage}`);
    }

    // Status is "InProgress" — wait before polling again.
    // For 70B models, budget 15–45 minutes of S3 transfer before seeing Completed.
    await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
  }
}

const importedModelArn = await waitForImportJob(client, jobArn);
console.log("Imported model ARN:", importedModelArn);
// e.g. arn:aws:bedrock:us-east-1:123456789012:imported-model/llama3-8b-custom-v2

Job status values are InProgress, Completed, Failed, and Stopped. The Stopped status occurs if you call StopModelImportJobCommand while the job is running. The importedModelArn field on the GetModelImportJobCommand response is only populated when the status is Completed.

Use a poll interval of at least 30 seconds. For large models (>30 GB), the S3 transfer time dominates total job duration — a 70B parameter Safetensors model at ~140 GB takes 15–45 minutes depending on S3 bandwidth and region capacity. Polling every 5 seconds wastes API calls and can trigger rate limiting.

ListImportedModelsCommand and GetImportedModelCommand

Once the import job completes, the resulting model appears in the imported models catalog. Use ListImportedModelsCommand to enumerate all imported models in the account and region, and GetImportedModelCommand to retrieve the ARN needed for invocation:

import {
  BedrockClient,
  ListImportedModelsCommand,
  GetImportedModelCommand,
} from "@aws-sdk/client-bedrock";

const client = new BedrockClient({ region: "us-east-1" });

// List all imported models
const listResponse = await client.send(new ListImportedModelsCommand({
  // Optional filters:
  // nameContains: "llama3",
  // creationTimeBefore: new Date("2027-01-01"),
  // creationTimeAfter: new Date("2026-01-01"),
  maxResults: 50,
}));

for (const model of listResponse.modelSummaries ?? []) {
  console.log(`${model.modelName} — ${model.modelArn}`);
}

// Handle pagination
let nextToken = listResponse.nextToken;
while (nextToken) {
  const page = await client.send(new ListImportedModelsCommand({
    maxResults: 50,
    nextToken,
  }));
  for (const model of page.modelSummaries ?? []) {
    console.log(`${model.modelName} — ${model.modelArn}`);
  }
  nextToken = page.nextToken;
}

// Retrieve a specific model by name or ARN to get the invocation ARN
const modelDetail = await client.send(new GetImportedModelCommand({
  modelIdentifier: "llama3-8b-custom-v2",   // name or ARN both work
}));

console.log("Model ARN:", modelDetail.modelArn);
console.log("Model architecture:", modelDetail.modelArchitecture);
console.log("Model data source:", JSON.stringify(modelDetail.modelDataSource));
console.log("Creation time:", modelDetail.creationTime?.toISOString());

// modelArn is the value you pass as modelId in InvokeModelCommand
const modelId = modelDetail.modelArn!;

The modelIdentifier parameter on GetImportedModelCommand accepts either the human-readable model name you specified at import time or the full ARN. Using the name is convenient during development; use the ARN in production to avoid ambiguity if you create multiple models with similar names. The modelArn field on the response is the value you pass as modelId to InvokeModelCommand.

Note that there is a brief propagation period after the import job reaches Completed status before the model is ready for inference. During this window, GetImportedModelCommand returns the modelArn but invocation calls may return ModelNotReadyException. The MCP server wrapper in the final section handles this with retry logic.

Invoking an imported model in an MCP server

Imported models do not support ConverseCommand. You must use InvokeModelCommand with the model's native input format. For Llama 3, that means constructing the prompt with the <|begin_of_text|>, <|start_header_id|>, and <|eot_id|> special tokens that the model was trained with. For Llama 2, the format differs — use [INST]/[/INST] delimiters. Each architecture family has its own template; there is no unified abstraction at the Bedrock level for imported models.

import {
  BedrockRuntimeClient,
  InvokeModelCommand,
  InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

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

// Llama 3 native chat template
function buildLlama3Prompt(
  system: string,
  userMessage: string,
): string {
  return (
    "<|begin_of_text|>" +
    "<|start_header_id|>system<|end_header_id|>\n\n" +
    system.trim() +
    "<|eot_id|>" +
    "<|start_header_id|>user<|end_header_id|>\n\n" +
    userMessage.trim() +
    "<|eot_id|>" +
    "<|start_header_id|>assistant<|end_header_id|>\n\n"
  );
}

// Non-streaming invocation
async function invokeImportedLlama3(
  modelArn: string,
  system: string,
  userMessage: string,
): Promise<string> {
  const prompt = buildLlama3Prompt(system, userMessage);

  const response = await runtime.send(new InvokeModelCommand({
    modelId: modelArn,
    contentType: "application/json",
    accept: "application/json",
    body: JSON.stringify({
      prompt,
      max_gen_len: 2048,
      temperature: 0.6,
      top_p: 0.9,
    }),
  }));

  const decoded = new TextDecoder().decode(response.body);
  const parsed = JSON.parse(decoded) as { generation: string };
  return parsed.generation.trim();
}

// Streaming invocation
async function* invokeImportedLlama3Stream(
  modelArn: string,
  system: string,
  userMessage: string,
): AsyncGenerator<string> {
  const prompt = buildLlama3Prompt(system, userMessage);

  const response = await runtime.send(new InvokeModelWithResponseStreamCommand({
    modelId: modelArn,
    contentType: "application/json",
    accept: "application/json",
    body: JSON.stringify({
      prompt,
      max_gen_len: 2048,
      temperature: 0.6,
      top_p: 0.9,
    }),
  }));

  const decoder = new TextDecoder();
  for await (const event of response.body ?? []) {
    if (event.chunk?.bytes) {
      const chunk = JSON.parse(decoder.decode(event.chunk.bytes)) as {
        generation?: string;
        stop_reason?: string;
      };
      if (chunk.generation) {
        yield chunk.generation;
      }
    }
  }
}

The request body structure for InvokeModelCommand is model-specific. For Llama 3, the top-level fields are prompt, max_gen_len, temperature, and top_p. The response has a generation field containing the model's output. Mistral uses a different schema (prompt + max_tokens + temperature + top_p + top_k). Always consult the upstream model card or llama.cpp documentation for the correct request/response schema for the architecture you imported.

Production gotchas

Imported models are incompatible with ConverseCommand

The Bedrock ConverseCommand provides a unified messages API that works across Claude, Llama, Mistral, and other first-party models. It does not work with imported model ARNs. If you pass an importedModelArn as the modelId in a ConverseCommand call, Bedrock returns a ValidationException with a message like "The model does not support the Converse API." You must use InvokeModelCommand and construct the native chat template manually — including the model family's special tokens. If your MCP server currently uses ConverseCommand for first-party models, you need a separate code path for imported models.

GGUF quantization level affects quality and memory

GGUF files come in multiple quantization levels. The quantization suffix in the filename (e.g., llama-3-8b-Q4_K_M.gguf) determines quality and hardware cost:

LevelQualityMemory (8B model)Recommendation
Q2_KNoticeably degraded~3 GBAvoid for production — coherence suffers
Q4_K_MNear full precision~5 GBBest production trade-off
Q5_K_MVery close to FP16~6 GBGood when quality headroom matters
Q8_0Equivalent to FP16~9 GBHighest quality, uses more capacity

For most MCP server use cases, Q4_K_M is the right default. Use Q8_0 only if output quality tests show measurable regression at Q4_K_M for your specific workload.

S3 URI must be in the same region as the import job

Bedrock reads the model artifacts from S3 during the import job. If the S3 bucket is in a different region than the BedrockClient, the job fails immediately with a ValidationException — not at transfer time. Create the S3 bucket in the same region you deploy your MCP server. If you need the same model in multiple regions, copy the artifacts to a bucket in each region and run a separate import job per region.

importedModelName must be unique per account per region

Bedrock rejects CreateModelImportJobCommand calls where importedModelName matches an existing imported model in the same account and region. Use a versioned naming convention from the start: llama3-8b-custom-v1, llama3-8b-custom-v2, and so on. This also makes it straightforward to roll back — keep the previous version's ARN in your MCP server configuration and swap back if the new version underperforms. Do not reuse names, even after deleting the old model, because deletion propagation can cause transient conflicts.

Brief propagation delay after Completed status

The import job reaching Completed status and the model being ready for inference are not simultaneous. There is a short propagation period — typically under a minute, but occasionally several minutes — during which invocation calls return ModelNotReadyException. GetImportedModelCommand returns the modelArn during this window, so the ARN being present does not guarantee readiness. Implement retry logic with exponential backoff in your MCP server for the first invocation after import.

Large model import jobs are dominated by S3 transfer time

For small models (7B–8B parameters, ~5–9 GB), import jobs typically complete in 5–15 minutes. For 70B parameter models at Safetensors precision (~140 GB), expect 15–45 minutes of transfer time before the job status transitions from InProgress to Completed. Plan import jobs as offline pre-deployment steps, not inline startup operations. Store the importedModelArn in AWS SSM Parameter Store or Secrets Manager after a successful import so the MCP server can read it at startup without triggering a new import job.

MCP server integration with retry logic

The following TypeScript class wraps imported model invocation with the Llama 3 native format, handles ModelNotReadyException with exponential backoff, and exposes an MCP tool that agents can call:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
  InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";

// Retrieve the imported model ARN from SSM at startup
async function getImportedModelArn(): Promise<string> {
  const ssm = new SSMClient({ region: process.env.AWS_REGION ?? "us-east-1" });
  const response = await ssm.send(new GetParameterCommand({
    Name: process.env.MODEL_ARN_SSM_PARAM ?? "/mcp/imported-model-arn",
  }));
  const arn = response.Parameter?.Value;
  if (!arn) throw new Error("MODEL_ARN_SSM_PARAM is not set or has no value");
  return arn;
}

function buildLlama3Prompt(system: string, user: string): string {
  return (
    "<|begin_of_text|>" +
    "<|start_header_id|>system<|end_header_id|>\n\n" +
    system.trim() + "<|eot_id|>" +
    "<|start_header_id|>user<|end_header_id|>\n\n" +
    user.trim() + "<|eot_id|>" +
    "<|start_header_id|>assistant<|end_header_id|>\n\n"
  );
}

class ImportedModelClient {
  private readonly runtime: BedrockRuntimeClient;
  private readonly modelArn: string;
  private readonly maxRetries: number;

  constructor(modelArn: string, region = "us-east-1", maxRetries = 5) {
    this.runtime = new BedrockRuntimeClient({ region });
    this.modelArn = modelArn;
    this.maxRetries = maxRetries;
  }

  async invoke(
    system: string,
    userMessage: string,
    options: { maxGenLen?: number; temperature?: number } = {},
  ): Promise<string> {
    const { maxGenLen = 2048, temperature = 0.6 } = options;
    const prompt = buildLlama3Prompt(system, userMessage);

    let lastError: unknown;
    for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
      if (attempt > 0) {
        // Exponential backoff: 2s, 4s, 8s, 16s, 32s
        const delayMs = Math.min(2_000 * Math.pow(2, attempt - 1), 32_000);
        await new Promise((resolve) => setTimeout(resolve, delayMs));
      }

      try {
        const response = await this.runtime.send(new InvokeModelCommand({
          modelId: this.modelArn,
          contentType: "application/json",
          accept: "application/json",
          body: JSON.stringify({
            prompt,
            max_gen_len: maxGenLen,
            temperature,
            top_p: 0.9,
          }),
        }));

        const decoded = new TextDecoder().decode(response.body);
        const parsed = JSON.parse(decoded) as { generation: string };
        return parsed.generation.trim();
      } catch (err) {
        const name = (err as { name?: string }).name ?? "";

        // ModelNotReadyException: model is imported but not yet serving — retry
        if (name === "ModelNotReadyException" && attempt < this.maxRetries) {
          console.warn(`ModelNotReadyException on attempt ${attempt + 1}, retrying...`);
          lastError = err;
          continue;
        }

        // ThrottlingException: back off and retry
        if (name === "ThrottlingException" && attempt < this.maxRetries) {
          console.warn(`ThrottlingException on attempt ${attempt + 1}, retrying...`);
          lastError = err;
          continue;
        }

        // All other errors are non-retryable
        throw err;
      }
    }

    throw lastError;
  }

  async *invokeStream(
    system: string,
    userMessage: string,
    options: { maxGenLen?: number; temperature?: number } = {},
  ): AsyncGenerator<string> {
    const { maxGenLen = 2048, temperature = 0.6 } = options;
    const prompt = buildLlama3Prompt(system, userMessage);

    const response = await this.runtime.send(new InvokeModelWithResponseStreamCommand({
      modelId: this.modelArn,
      contentType: "application/json",
      accept: "application/json",
      body: JSON.stringify({ prompt, max_gen_len: maxGenLen, temperature, top_p: 0.9 }),
    }));

    const decoder = new TextDecoder();
    for await (const event of response.body ?? []) {
      if (event.chunk?.bytes) {
        const chunk = JSON.parse(decoder.decode(event.chunk.bytes)) as {
          generation?: string;
        };
        if (chunk.generation) yield chunk.generation;
      }
    }
  }
}

// MCP server wiring
const modelArn = await getImportedModelArn();
const importedModel = new ImportedModelClient(modelArn, process.env.AWS_REGION ?? "us-east-1");

const server = new McpServer({ name: "imported-model-tools", version: "1.0.0" });

server.tool(
  "invoke_custom_model",
  {
    system_prompt: z.string().default("You are a helpful assistant."),
    user_message: z.string().min(1).max(100_000),
    max_tokens: z.number().int().min(1).max(4096).default(2048),
    temperature: z.number().min(0).max(1).default(0.6),
  },
  async ({ system_prompt, user_message, max_tokens, temperature }) => {
    const result = await importedModel.invoke(system_prompt, user_message, {
      maxGenLen: max_tokens,
      temperature,
    });
    return { content: [{ type: "text", text: result }] };
  },
);

await server.connect(new StdioServerTransport());

The ImportedModelClient handles both ModelNotReadyException (post-import propagation delay) and ThrottlingException (on-demand capacity pressure) with exponential backoff up to 32 seconds per attempt. For production deployments, combine this with Provisioned Throughput to eliminate throttling entirely and reduce p99 latency variance.

Monitor your imported model MCP server with AliveMCP

AliveMCP monitors uptime and latency for MCP servers running imported models on Bedrock. Get alerted when your custom endpoint goes down.

Start free monitoring