Guide · Amazon Redshift · Data API · Pagination · MCP Server Tools
Redshift Data API Pagination for MCP Servers — NextToken, Column Metadata, Type Conversion
The Redshift Data API returns query results in pages of up to 100 rows per GetStatementResultCommand call. For analytical queries that return thousands of rows, your MCP tool must loop on NextToken to collect all pages, then convert the wire-format field values — which arrive as a discriminated union of { stringValue }, { longValue }, { doubleValue }, { booleanValue }, or { isNull: true } — into JavaScript-native types using the column metadata from the first page. Getting this wrong produces tools that silently truncate results at 100 rows, mistype numeric columns as strings, or crash on NULL values. This guide covers the complete pagination loop, column metadata extraction, type conversion for every Redshift data type, result size limits, streaming patterns for very large result sets, and practical result shaping for LLM-friendly MCP tool responses.
TL;DR
Call GetStatementResultCommand with the statement ID; if the response has a NextToken, call again with { Id, NextToken } until NextToken is absent. Column metadata (name, type, nullable) is in response.columnMetadata[] — present on every page but identical across pages, so extract it once from the first page. Each row is Field[] where each Field is a discriminated union; the populated key tells you the type. Redshift INTEGER/BIGINT arrive as longValue (JavaScript number — safe up to 2^53); NUMERIC/DECIMAL arrive as stringValue to preserve precision. Add a hard LIMIT clause to every MCP tool query — the Data API has a 100 MB result size limit and returns an error (not a truncated result) when exceeded.
The pagination loop — complete implementation
The Redshift Data API stores query results in a temporary result cache for 24 hours after the statement completes. GetStatementResultCommand reads from this cache in pages. Each page delivers up to 100 rows by default; the maximum is 100,000 rows per page (set via the undocumented SDK parameter, but the API enforces 100 rows in practice for most result sizes).
import {
RedshiftDataClient,
GetStatementResultCommand,
type ColumnMetadata,
type Field,
} from "@aws-sdk/client-redshift-data";
const rsData = new RedshiftDataClient({ region: "us-east-1" });
interface QueryResult {
columns: ColumnMetadata[];
rows: Record<string, unknown>[];
totalRows: number;
}
async function fetchAllPages(statementId: string): Promise<QueryResult> {
let nextToken: string | undefined;
let columns: ColumnMetadata[] = [];
const allRows: Record<string, unknown>[] = [];
do {
const response = await rsData.send(new GetStatementResultCommand({
Id: statementId,
NextToken: nextToken,
}));
// Column metadata is present on every page — extract on first page only
if (columns.length === 0 && response.columnMetadata) {
columns = response.columnMetadata;
}
// Convert rows from Field[] discriminated union to plain objects
for (const row of response.records ?? []) {
allRows.push(rowToObject(row, columns));
}
nextToken = response.NextToken;
} while (nextToken);
return {
columns,
rows: allRows,
totalRows: allRows.length,
};
}
function rowToObject(
row: Field[],
columns: ColumnMetadata[]
): Record<string, unknown> {
const obj: Record<string, unknown> = {};
for (let i = 0; i < columns.length; i++) {
const col = columns[i];
const field = row[i];
obj[col.name!] = fieldToValue(field, col);
}
return obj;
}
The do...while loop ensures we always make at least one call (necessary to handle zero-row result sets). The first call always returns column metadata; subsequent pages repeat it but we skip re-assignment after the first page.
Field type conversion — every Redshift type
Each Field in a Redshift Data API response is a discriminated union of exactly one populated key. The key name tells you the JavaScript-native type to use. Here is the complete mapping:
| Field key | Redshift types | JavaScript value | Notes |
|---|---|---|---|
stringValue | VARCHAR, CHAR, TEXT, BPCHAR, TIMEZONEOID, DATE, TIMESTAMP, TIMESTAMPTZ, NUMERIC, DECIMAL, GEOMETRY, SUPER | string | NUMERIC/DECIMAL always arrive as strings to preserve precision beyond IEEE 754 |
longValue | SMALLINT, INTEGER, INT, INT2, INT4, INT8, BIGINT, OID | number | Safe for values up to 2^53 − 1; use BigInt for BIGINT columns that might exceed that |
doubleValue | FLOAT, FLOAT4, FLOAT8, REAL, DOUBLE PRECISION | number | IEEE 754 double; precision matches Redshift's storage |
booleanValue | BOOLEAN, BOOL | boolean | Direct JS boolean; no string coercion needed |
isNull: true | Any nullable column with NULL value | null | The isNull key is set to true; all other keys are absent |
blobValue | VARBYTE, BINARY | Uint8Array | Binary columns; rare in analytics workloads |
function fieldToValue(field: Field, col: ColumnMetadata): unknown {
// NULL check first — isNull is the discriminator for NULL values
if (field.isNull === true) return null;
// String types — covers VARCHAR, CHAR, DATE, TIMESTAMP, NUMERIC, DECIMAL
if (field.stringValue !== undefined) {
// Preserve NUMERIC/DECIMAL as strings; convert DATE/TIMESTAMP if needed
const typeName = col.typeName?.toUpperCase() ?? "";
if (typeName === "DATE") return new Date(field.stringValue);
if (typeName === "TIMESTAMP" || typeName === "TIMESTAMPTZ") {
return new Date(field.stringValue);
}
return field.stringValue;
}
// Integer types — SMALLINT, INTEGER, BIGINT
if (field.longValue !== undefined) {
// Guard against precision loss on BIGINT > 2^53
const typeName = col.typeName?.toUpperCase() ?? "";
if ((typeName === "INT8" || typeName === "BIGINT") && Math.abs(field.longValue) > Number.MAX_SAFE_INTEGER) {
return BigInt(field.longValue);
}
return field.longValue;
}
// Float types
if (field.doubleValue !== undefined) return field.doubleValue;
// Boolean
if (field.booleanValue !== undefined) return field.booleanValue;
// Binary
if (field.blobValue !== undefined) return field.blobValue;
return null; // shouldn't reach here with well-formed responses
}
The most common conversion mistake is treating NUMERIC/DECIMAL columns as numbers. These types arrive as stringValue specifically because Redshift preserves arbitrary precision (up to 38 significant digits) and IEEE 754 double cannot represent the full range. For monetary values or high-precision calculations, keep them as strings and use a decimal library like decimal.js for arithmetic.
Column metadata fields
ColumnMetadata provides the information needed to correctly interpret and label each column in the response. Key fields:
interface ColumnMetadata {
name?: string; // Column name from the SELECT list or alias
typeName?: string; // Redshift type name: "varchar", "int8", "numeric", "bool", etc.
typeCode?: number; // JDBC type code (mostly useful for interop with JDBC clients)
nullable?: number; // 0=NOT NULL, 1=nullable, 2=unknown
length?: number; // Max length for VARCHAR/CHAR columns (characters)
precision?: number; // Total digits for NUMERIC/DECIMAL
scale?: number; // Digits after decimal for NUMERIC/DECIMAL
schemaName?: string; // Schema the column's table belongs to
tableName?: string; // Table the column came from (empty for computed columns)
label?: string; // Column label — same as name unless you used AS alias
}
For computed columns like COUNT(*) or SUM(revenue), tableName is empty and name is the generated alias or the expression text. Always use the SQL AS alias for computed columns to get predictable name values in the metadata:
-- Use explicit aliases for all computed columns
SELECT
DATE_TRUNC('month', event_at) AS month,
COUNT(*) AS event_count,
SUM(revenue_usd) AS total_revenue,
AVG(response_ms) AS avg_response_ms
FROM events
GROUP BY 1
ORDER BY 1 DESC
LIMIT 100;
Result size limits and query design for MCP tools
The Redshift Data API enforces a 100 MB limit on the total result set stored in cache. When a query produces more than 100 MB of result data, the Data API returns an error — it does not silently truncate. The statement enters FAILED status with an error message indicating the result size limit was exceeded.
Always add an explicit LIMIT clause to MCP tool queries. Even queries that "should be small" can produce large result sets on growing datasets. A practical limit for LLM-facing tools is 500–1000 rows — an AI agent cannot meaningfully process more than that anyway, and returning thousands of rows wastes tokens and increases response latency.
// MCP tool: "get recent sales by region"
const sql = `
SELECT
region,
SUM(sale_amount) AS total_sales,
COUNT(*) AS order_count,
AVG(sale_amount) AS avg_order_value
FROM sales
WHERE sale_date >= DATEADD(month, -3, GETDATE())
GROUP BY region
ORDER BY total_sales DESC
LIMIT 100 -- always explicit LIMIT in MCP tool queries
`;
// For tools that must fetch all rows (e.g., export tools),
// add a size guard before pagination:
const { TotalNumRows } = await rsData.send(new DescribeStatementCommand({
Id: statementId,
}));
if ((TotalNumRows ?? 0) > 10_000) {
throw new McpError(
ErrorCode.InvalidRequest,
`Query returned ${TotalNumRows} rows — too many to return via this tool. ` +
"Use a more specific filter or the export tool for bulk operations."
);
}
Fetching only the first page for preview tools
Some MCP tools legitimately want only a preview — the first N rows to understand the data shape. Skip the pagination loop and fetch exactly one page:
// Preview tool: show first 20 rows of a table
async function previewTable(tableName: string, limit = 20) {
const statementId = await executeAndWait(
`SELECT * FROM ${sanitizeIdentifier(tableName)} LIMIT ${limit}`
);
// Single GetStatementResult call — don't loop on NextToken
const { records, columnMetadata } = await rsData.send(
new GetStatementResultCommand({ Id: statementId })
);
return {
columns: columnMetadata?.map(c => ({ name: c.name, type: c.typeName })) ?? [],
rows: (records ?? []).map(row => rowToObject(row, columnMetadata ?? [])),
hasMore: !!response.NextToken, // tell caller if truncated
};
}
function sanitizeIdentifier(name: string): string {
// Prevent SQL injection in table names — only allow schema.table or table pattern
if (!/^[a-zA-Z_][a-zA-Z0-9_.]*$/.test(name)) {
throw new Error(`Invalid table name: ${name}`);
}
return name;
}
Streaming large results with ListStatements and chunked fetching
For export-class MCP tools that legitimately need all rows from a large result set, paginate in batches and stream rows to the caller using an async generator. This avoids holding all rows in memory simultaneously:
async function* streamQueryResults(statementId: string): AsyncGenerator<Record<string, unknown>[]> {
let nextToken: string | undefined;
let columns: ColumnMetadata[] = [];
let pageNum = 0;
do {
const response = await rsData.send(new GetStatementResultCommand({
Id: statementId,
NextToken: nextToken,
}));
if (pageNum === 0 && response.columnMetadata) {
columns = response.columnMetadata;
}
const page = (response.records ?? []).map(row => rowToObject(row, columns));
if (page.length > 0) yield page;
nextToken = response.NextToken;
pageNum++;
// Respect Data API rate limits: 10 GetStatementResult calls per second
if (nextToken) await new Promise(r => setTimeout(r, 100));
} while (nextToken);
}
// Usage in an MCP tool that exports data as NDJSON
async function exportQueryToNdjson(statementId: string): Promise<string> {
const lines: string[] = [];
for await (const page of streamQueryResults(statementId)) {
for (const row of page) {
lines.push(JSON.stringify(row));
}
}
return lines.join("\n");
}
The 100ms sleep between pages guards against hitting the Data API rate limit of 10 calls per second for GetStatementResult. At 100 rows per page, this gives you roughly 1,000 rows per second of throughput — fast enough for most export use cases while staying within API limits.
Formatting results for LLM consumption
AI agents reading Redshift query results through an MCP tool benefit from structured output with column types visible. Rather than returning raw JavaScript objects, return a schema-annotated format:
function formatResultForLlm(result: QueryResult): string {
const { columns, rows, totalRows } = result;
// Build column header with type hints
const header = columns.map(c => `${c.name} (${c.typeName})`).join(" | ");
const separator = columns.map(() => "---").join(" | ");
// Format rows as a markdown table
const dataRows = rows.slice(0, 50).map(row => // cap at 50 rows in LLM response
columns.map(c => {
const val = row[c.name!];
if (val === null) return "NULL";
if (val instanceof Date) return val.toISOString().slice(0, 10);
return String(val);
}).join(" | ")
);
const truncationNote = totalRows > 50
? `\n\n*Showing first 50 of ${totalRows} rows.*`
: "";
return `| ${header} |\n| ${separator} |\n${dataRows.map(r => `| ${r} |`).join("\n")}${truncationNote}`;
}
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
| Results truncated at 100 rows | Not looping on NextToken | Use the pagination loop; check for response.NextToken after every page |
| NUMERIC columns arrive as strings | Intentional — Redshift Data API encodes NUMERIC as stringValue for precision | Use a decimal library for arithmetic; do not parseFloat() without awareness of precision loss |
ValidationException: query result exceeded 100 MB | Query returned more data than the cache limit | Add LIMIT clause; use UNLOAD TO S3 for bulk exports instead of Data API |
ResourceNotFoundException on GetStatementResult | Statement result cache expired (24-hour TTL) or wrong ID | Re-run the query; don't cache statement IDs for more than 24 hours |
| ThrottlingException on pagination loop | Exceeding 10 GetStatementResult calls/sec | Add 100ms delay between pagination calls |
| NULL values causing type errors | field.isNull === true check missing | Always check isNull before accessing stringValue/longValue/etc. |
Related guides
- Amazon Redshift for MCP servers: Data API basics, IAM auth, async execution
- Redshift Serverless: namespaces, workgroups, RPU configuration, cold starts
- Redshift Spectrum: query S3 data lakes with external tables from MCP tools
- Redshift COPY command: bulk-load S3 data into Redshift from MCP tools
- MCP server uptime monitoring