Guide · Amazon Bedrock · Prompt Management
Bedrock Prompt Variables for MCP Servers — {{Syntax}}, Rendering, and Validation
Bedrock Prompt Management variables use {{variable_name}} syntax — double curly braces, no spaces — and can appear anywhere in a TEXT template string or in any text field inside a CHAT template's messages or system content. Variable substitution is not performed server-side: GetPromptCommand returns the raw template with the {{variable_name}} placeholders intact. Your MCP server is responsible for fetching the template, substituting the values, and passing the rendered content to ConverseCommand. This means variable validation, escaping, and error handling are entirely on the client side. The inputVariables array on each variant is metadata — it tells tooling which variables the template expects, but Bedrock does not validate at fetch time whether you have supplied values for all of them. This guide covers the complete rendering pipeline for both TEXT and CHAT template types. For the prompt creation and fetch APIs, see Prompt Management Overview. For versioning, see Prompt Versions. For CHAT template structure, see CHAT vs TEXT Templates.
TL;DR
Variables use {{name}} syntax. Bedrock does not render them server-side — you do it in TypeScript after GetPromptCommand. Missing variable: placeholder stays as literal text in the rendered string (no error). Unknown variable: ignored. Variable names are case-sensitive. Render TEXT templates with a simple regex replace; render CHAT templates by walking every content[].text field in every message plus the system block.
Variable syntax rules
Bedrock uses {{variable_name}} as the placeholder delimiter. The rules:
- Double curly braces, no spaces inside.
{{name}}is valid.{{ name }}(with spaces) is not substituted — it stays as a literal string. - Alphanumeric and underscores only.
{{max_sentences}}is valid.{{max-sentences}}(hyphen) will not match the standard rendering pattern. - Case-sensitive.
{{Content}}and{{content}}are different variables. TheinputVariablesarray defines the canonical names; use them exactly. - Can appear multiple times. A variable can be used more than once in a template. All occurrences are replaced when rendering.
- Can appear in CHAT system text, user messages, and assistant messages. Every text node in a CHAT template is independently rendered.
The inputVariables array on the variant is an array of {"name": "variable_name"} objects. It is advisory — your rendering code should validate against it, but Bedrock itself does not enforce it on fetch.
Building a type-safe renderer
The core rendering function replaces all occurrences of {{name}} with the corresponding value. It throws for missing variables rather than silently leaving placeholders:
/**
* Replace {{variable}} placeholders in a template string.
* Throws if a placeholder has no matching value in `variables`.
*/
export function renderTemplate(
template: string,
variables: Record<string, string>,
): string {
return template.replace(/\{\{(\w+)\}\}/g, (match, name: string) => {
if (name in variables) return variables[name];
throw new Error(
`Prompt variable "{{${name}}}" has no value. ` +
`Provided keys: ${Object.keys(variables).join(", ")}`,
);
});
}
/**
* Validate that all declared inputVariables have a value before rendering.
* Call this before renderTemplate to get a descriptive error early.
*/
export function validateVariables(
inputVariables: Array<{ name: string }>,
provided: Record<string, string>,
): void {
const missing = inputVariables
.map(v => v.name)
.filter(name => !(name in provided));
if (missing.length > 0) {
throw new Error(
`Missing prompt variables: ${missing.join(", ")}`,
);
}
}
The regex /\{\{(\w+)\}\}/g matches zero or more word characters (\w = letters, digits, underscores) between double braces. If your template uses a variable name with hyphens, the regex will not match it — which is consistent with Bedrock's own naming rules (hyphens are not documented as valid variable name characters).
Rendering a TEXT template and invoking the model
For templateType: "TEXT", the entire prompt is in templateConfiguration.text.text. Render it and pass as a single user message to ConverseCommand:
import { BedrockClient, GetPromptCommand } from "@aws-sdk/client-bedrock";
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
const bedrockMgmt = new BedrockClient({ region: "us-east-1" });
const bedrockRuntime = new BedrockRuntimeClient({ region: "us-east-1" });
export async function invokeTextPrompt(
promptId: string,
promptVersion: string,
variables: Record<string, string>,
variantName?: string,
): Promise<string> {
// 1. Fetch the versioned template
const response = await bedrockMgmt.send(new GetPromptCommand({
promptIdentifier: promptId,
promptVersion,
}));
const variant = variantName
? response.variants?.find(v => v.name === variantName)
: response.variants?.find(v => v.name === response.defaultVariant)
?? response.variants?.[0];
if (!variant) throw new Error(`Variant not found: ${variantName ?? "default"}`);
if (variant.templateType !== "TEXT") {
throw new Error(`Expected TEXT template, got ${variant.templateType}`);
}
const textConfig = variant.templateConfiguration!.text!;
// 2. Validate variables before rendering
validateVariables(textConfig.inputVariables ?? [], variables);
// 3. Render the template
const renderedText = renderTemplate(textConfig.text, variables);
// 4. Invoke the model via Converse
const modelId = variant.modelId ?? "anthropic.claude-3-5-haiku-20241022-v1:0";
const infConfig = variant.inferenceConfiguration?.text;
const result = await bedrockRuntime.send(new ConverseCommand({
modelId,
messages: [{ role: "user", content: [{ text: renderedText }] }],
inferenceConfig: {
temperature: infConfig?.temperature ?? 0.5,
maxTokens: infConfig?.maxTokens ?? 1024,
topP: infConfig?.topP,
stopSequences: infConfig?.stopSequences,
},
}));
return result.output?.message?.content?.[0]?.text ?? "";
}
Notice that inferenceConfig in ConverseCommand uses camelCase (temperature, maxTokens), while inferenceConfiguration.text in the prompt also uses camelCase. The names align — just be careful that the runtime's inferenceConfig wrapper is a direct object (not nested in a text sub-object as it is in the prompt resource).
Rendering CHAT template variables
CHAT templates have variables distributed across multiple text nodes: in the system block and in each message's content[].text. You must walk the entire structure:
import type { Message, SystemContentBlock } from "@aws-sdk/client-bedrock-runtime";
import type { ChatPromptTemplateConfiguration } from "@aws-sdk/client-bedrock";
/**
* Render all variables in a CHAT template configuration.
* Returns objects ready to pass to ConverseCommand.
*/
export function renderChatTemplate(
chatConfig: ChatPromptTemplateConfiguration,
variables: Record<string, string>,
): {
system: SystemContentBlock[];
messages: Message[];
} {
// Render system prompt (optional field)
const system: SystemContentBlock[] = (chatConfig.system ?? []).map(s => ({
text: renderTemplate(s.text ?? "", variables),
}));
// Render every message's content blocks
const messages: Message[] = (chatConfig.messages ?? []).map(msg => ({
role: msg.role as "user" | "assistant",
content: (msg.content ?? []).map(block => {
if ("text" in block && typeof block.text === "string") {
return { text: renderTemplate(block.text, variables) };
}
return block; // non-text blocks (images, documents) pass through unchanged
}),
}));
return { system, messages };
}
// Full CHAT invoke
export async function invokeChatPrompt(
promptId: string,
promptVersion: string,
variables: Record<string, string>,
variantName?: string,
): Promise<string> {
const response = await bedrockMgmt.send(new GetPromptCommand({
promptIdentifier: promptId,
promptVersion,
}));
const variant = variantName
? response.variants?.find(v => v.name === variantName)
: response.variants?.find(v => v.name === response.defaultVariant)
?? response.variants?.[0];
if (!variant) throw new Error("Variant not found");
if (variant.templateType !== "CHAT") {
throw new Error(`Expected CHAT template, got ${variant.templateType}`);
}
const chatConfig = variant.templateConfiguration!.chat!;
validateVariables(chatConfig.inputVariables ?? [], variables);
const { system, messages } = renderChatTemplate(chatConfig, variables);
const modelId = variant.modelId ?? "anthropic.claude-3-5-sonnet-20241022-v2:0";
const infConfig = variant.inferenceConfiguration?.text;
const result = await bedrockRuntime.send(new ConverseCommand({
modelId,
system: system.length > 0 ? system : undefined,
messages,
inferenceConfig: {
temperature: infConfig?.temperature ?? 0.5,
maxTokens: infConfig?.maxTokens ?? 1024,
},
}));
return result.output?.message?.content?.[0]?.text ?? "";
}
The system field in ConverseCommand takes an array of SystemContentBlock (not a plain string). Passing an empty array where the model does not expect a system prompt is harmless — most Bedrock models ignore an empty system block. Passing undefined rather than [] is cleaner when there is no system message.
Variable gotchas
Missing variable: silent placeholder leak
If you do not throw on missing variables (and instead let the regex leave the {{var}} literal in place), the model receives the unrendered placeholder. This often does not cause an error — the model may interpret {{content}} as an instruction to do something with a variable called "content", producing strange or nonsensical output. The failure mode is silent: the model returns a response, just the wrong one. Always throw on missing variables rather than silently injecting placeholders into model context.
Extra variables: silently ignored
If you pass a variable that does not appear in the template (e.g. you renamed the variable in the template but not in your TypeScript code), no error is thrown — the value is simply never inserted. The mismatch goes undetected unless you explicitly check that every provided variable key appears in the inputVariables array:
export function validateNoExtraVariables(
inputVariables: Array<{ name: string }>,
provided: Record<string, string>,
): void {
const declared = new Set(inputVariables.map(v => v.name));
const extra = Object.keys(provided).filter(k => !declared.has(k));
if (extra.length > 0) {
// Warn rather than throw — extra variables are likely a code/template mismatch
console.warn(`Unused prompt variables: ${extra.join(", ")}`);
}
}
Whitespace and newlines are injected verbatim
Variable values are inserted exactly as provided — no trimming, no escaping. If a tool handler passes content = fetchResult.trim(), the prompt renders correctly. If it passes raw API output with leading/trailing newlines, those newlines appear in the rendered prompt. For tool outputs injected into prompts, always trim and potentially truncate before substitution.
Template hot-reload
If you cache the prompt template at startup (recommended), and the template's variable names change in a new version, the cache will serve the old inputVariables metadata. For safety, tie the cache key to the version number. When you deploy a new version (by updating PROMPT_VERSION env var), the server starts fresh with the new template, so the old variable names are never used with the new template.
MCP tool handler with prompt injection
A complete MCP tool that fetches a versioned prompt, validates inputs, and returns the model's response:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({ name: "content-tools", version: "1.0.0" });
const PROMPT_ID = process.env.SUMMARIZE_PROMPT_ID!;
const PROMPT_VERSION = process.env.SUMMARIZE_PROMPT_VERSION!;
server.tool(
"summarize",
{
content: z.string().min(1).max(100_000).describe("Text to summarize"),
max_sentences: z.number().int().min(1).max(10).default(3)
.describe("Maximum sentences in the summary"),
},
async ({ content, max_sentences }) => {
// Trim content to avoid injecting excessive whitespace
const trimmedContent = content.trim().slice(0, 50_000);
const summary = await invokeTextPrompt(
PROMPT_ID,
PROMPT_VERSION,
{
content: trimmedContent,
max_sentences: String(max_sentences),
},
);
return {
content: [{ type: "text", text: summary }],
};
},
);
const transport = new StdioServerTransport();
await server.connect(transport);
Note that all variable values must be strings. max_sentences is a number in the Zod schema, but the prompt template uses it as a string interpolation. Convert numeric inputs with String() before passing to the renderer. The model receives the rendered string and interprets the number naturally from context.
Related pages in this arc
- Prompt Management Overview — CreatePrompt, GetPrompt, prompt anatomy, IAM, startup caching pattern
- Prompt Versions — CreatePromptVersionCommand, immutability, CI/CD workflow, rollback
- CHAT vs TEXT Templates — CHAT template structure, system role, few-shot examples, multi-variant selection
For calling the model after rendering, see Bedrock Converse API. For guardrails that run before or after model invocation, see Bedrock Guardrails.