Guide · Amazon Keyspaces · Apache Cassandra · MCP Server Tools

Amazon Keyspaces (Cassandra) for MCP Servers — Driver Setup, Auth, CQL CRUD

Amazon Keyspaces is a fully managed, serverless Apache Cassandra-compatible database. It handles cluster management, replication, and patching so your MCP server tools interact with a CQL-compatible endpoint that scales on demand. For MCP developers, Keyspaces is a good fit when you need wide-row storage, time-series data with natural partitioning by entity ID, or high-throughput write workloads where DynamoDB's key-value model is too rigid but a full self-managed Cassandra cluster is too operationally expensive. This guide covers the two-API model (management SDK vs CQL driver), authentication options, TLS setup, table creation, and production patterns for MCP tool handlers.

TL;DR

Amazon Keyspaces has two separate APIs: management operations (CreateKeyspace, CreateTable, GetTable) go through @aws-sdk/client-keyspaces; data operations (SELECT, INSERT, UPDATE, DELETE) go through the cassandra-driver npm package connecting to cassandra.REGION.amazonaws.com:9142 over TLS. Auth to the CQL endpoint uses service-specific credentials (IAM user) or SigV4-based temporary credentials. Always create the Client once at module load time and reuse it across tool calls — connecting per-request costs 100–500 ms. Use await client.execute(cql, params, { prepare: true }) for parameterized queries; never string-concatenate user values into CQL.

Two APIs: management vs data

Unlike DynamoDB, which uses a single SDK for everything, Keyspaces splits management and data operations into fundamentally different interfaces.

Operation typePackageProtocolAuth
Create/delete keyspace@aws-sdk/client-keyspacesHTTPS + SigV4Standard IAM
Create/alter/drop table@aws-sdk/client-keyspaces or CQL DDLHTTPS or CQL binaryIAM or service-specific credentials
SELECT / INSERT / UPDATE / DELETEcassandra-driverCQL binary (port 9142, TLS)Service-specific credentials or SigV4
List tables, describe schema@aws-sdk/client-keyspacesHTTPS + SigV4Standard IAM
PITR / backups@aws-sdk/client-keyspacesHTTPS + SigV4Standard IAM

In a typical MCP server setup, you use @aws-sdk/client-keyspaces at deploy-time (or in migration scripts) to provision the keyspace and tables, and cassandra-driver in your tool handlers for all data access.

Authentication — service-specific credentials

The CQL binary protocol used by cassandra-driver does not natively support AWS SigV4. The simplest production auth method is service-specific credentials: IAM generates a username and password scoped to cassandra.amazonaws.com. These are static credentials stored in Secrets Manager.

# Generate service-specific credentials for an IAM user
aws iam create-service-specific-credential \
  --user-name keyspaces-mcp-user \
  --service-name cassandra.amazonaws.com
# Returns: ServiceUserName, ServicePassword (save to Secrets Manager immediately)
# These credentials are separate from the IAM user's console/API credentials

Service-specific credentials have important properties:

For applications running on Lambda or ECS that need to use the execution role (not an IAM user), AWS provides a Sigv4AuthProvider approach. See the note at the end of this section.

Connecting cassandra-driver to Amazon Keyspaces

Install the driver and the Amazon root CA certificate:

npm install cassandra-driver
# Download Amazon root CA (required for TLS validation)
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem

Create the client. Instantiate it once at module initialization, not inside request handlers:

import { Client, auth, policies } from 'cassandra-driver';
import * as fs from 'fs';
import { getSecret } from './secrets.js'; // your Secrets Manager wrapper

// Called once at module load; client is reused across all MCP tool calls
export async function createKeyspacesClient(region: string): Promise<Client> {
  const { ServiceUserName, ServicePassword } = JSON.parse(
    await getSecret('keyspaces/service-credentials')
  );

  const client = new Client({
    contactPoints: [`cassandra.${region}.amazonaws.com`],
    localDataCenter: region,
    authProvider: new auth.PlainTextAuthProvider(ServiceUserName, ServicePassword),
    sslOptions: {
      ca: [fs.readFileSync('./AmazonRootCA1.pem')],
      host: `cassandra.${region}.amazonaws.com`,
      rejectUnauthorized: true,
    },
    keyspace: 'mcp_server',
    protocolOptions: { port: 9142 },
    pooling: {
      local: { coreConnectionsPerHost: 2, maxRequestsPerConnection: 1024 },
    },
    socketOptions: {
      connectTimeout: 5000,
      readTimeout: 12000,
    },
    // Keyspaces does not support LOCAL_QUORUM for read repairs on write path
    // — use LOCAL_QUORUM for reads and LOCAL_QUORUM for writes (default for Keyspaces)
    policies: {
      retry: new policies.retry.RetryPolicy(),
      reconnection: new policies.reconnection.ExponentialReconnectionPolicy(1000, 60000),
    },
  });

  await client.connect();
  return client;
}

Key configuration notes:

Using IAM roles (SigV4 temporary credentials)

If your MCP server runs on Lambda or ECS and you cannot use an IAM user, generate service-specific credentials dynamically from the execution role using the IAM API at startup, or implement a PlainTextAuthProvider wrapper that calls STS. AWS has an open-source reference implementation in the amazon-keyspaces-with-sigv4-example-javascript GitHub repository. The pattern:

import { IAMClient, CreateServiceSpecificCredentialCommand } from '@aws-sdk/client-iam';

// Use the execution role to call IAM — this requires iam:CreateServiceSpecificCredential
// on the role (which requires the IAM user ARN to be in the resource, or use an allow-all
// scoped specifically to cassandra.amazonaws.com)
//
// Alternative: use a pre-generated service-specific credential stored in Secrets Manager
// and rotate it via a Secrets Manager rotation Lambda. This is the simpler production path.
//
// The IAM-role-based SigV4 approach requires the Amazon Keyspaces SigV4 auth plugin,
// which wraps cassandra-driver and handles token refresh automatically.
// npm install amazon-keyspaces-sigv4-auth (community package — verify before use in prod)

For most MCP server deployments, the simpler path is: generate service-specific credentials once, store in Secrets Manager, and use the rotation Lambda pattern. Reserve the SigV4 plugin for environments where IAM user creation is policy-restricted.

Creating keyspaces and tables via the management SDK

Use @aws-sdk/client-keyspaces for schema provisioning. These are AWS API calls, not CQL — they go through HTTPS with standard IAM credentials:

import {
  KeyspacesClient,
  CreateKeyspaceCommand,
  CreateTableCommand,
  GetTableCommand,
  TableStatus,
  EncryptionType,
} from '@aws-sdk/client-keyspaces';

const ksClient = new KeyspacesClient({ region: 'us-east-1' });

// Create a keyspace
await ksClient.send(new CreateKeyspaceCommand({
  keyspaceName: 'mcp_server',
  replicationSpecification: {
    replicationStrategy: 'SINGLE_REGION',
    // For multi-region tables (preview feature): replicationStrategy: 'MULTI_REGION'
    // with regionList specifying additional regions
  },
  tags: [{ key: 'billing:project', value: 'mcp-server-prod' }],
}));

// Create a table — column definitions and primary key structure
await ksClient.send(new CreateTableCommand({
  keyspaceName: 'mcp_server',
  tableName: 'tool_sessions',
  schemaDefinition: {
    allColumns: [
      { name: 'session_id',  type: 'uuid' },
      { name: 'created_at', type: 'timestamp' },
      { name: 'tool_name',  type: 'text' },
      { name: 'payload',    type: 'text' },
      { name: 'status',     type: 'text' },
    ],
    partitionKeys: [{ name: 'session_id' }],
    clusteringKeys: [{ name: 'created_at', orderBy: 'ASC' }],
  },
  capacitySpecification: {
    throughputMode: 'PAY_PER_REQUEST',  // on-demand; no capacity planning needed
  },
  encryptionSpecification: {
    type: EncryptionType.AWS_OWNED_KMS_KEY,  // or CUSTOMER_MANAGED_KMS_KEY with kmsKeyIdentifier
  },
  pointInTimeRecovery: { status: 'ENABLED' },
  defaultTimeToLive: 86400,  // 24-hour TTL on all rows; override per-row with USING TTL
  tags: [{ key: 'billing:project', value: 'mcp-server-prod' }],
}));

Table creation is asynchronous — poll GetTableCommand until tableStatus === "ACTIVE" before attempting CQL data operations:

async function waitForTable(keyspace: string, table: string): Promise<void> {
  for (let attempt = 0; attempt < 30; attempt++) {
    const { table: t } = await ksClient.send(new GetTableCommand({
      keyspaceName: keyspace,
      tableName: table,
    }));
    if (t?.status === TableStatus.ACTIVE) return;
    await new Promise(r => setTimeout(r, 5000));
  }
  throw new Error(`Table ${keyspace}.${table} did not become ACTIVE`);
}

CRUD patterns in MCP tool handlers

All data operations use the cassandra-driver Client. Always use prepared statements — Keyspaces compiles the query plan on the first execution and caches it, reducing per-request latency on subsequent calls. Never interpolate user-supplied values into CQL strings.

INSERT

import { types } from 'cassandra-driver';

// INSERT with explicit TTL — the row expires after 1 hour regardless of table default
await client.execute(
  `INSERT INTO mcp_server.tool_sessions
     (session_id, created_at, tool_name, payload, status)
   VALUES (?, ?, ?, ?, ?)
   USING TTL 3600`,
  [
    types.Uuid.random(),       // session_id
    new Date(),                // created_at — cassandra-driver maps JS Date to Cassandra timestamp
    'search_codebase',         // tool_name
    JSON.stringify(toolInput), // payload — serialize complex objects to text
    'pending',                 // status
  ],
  { prepare: true }
);

SELECT with pagination

// Fetch all events for a session in chronological order
const result = await client.execute(
  `SELECT session_id, created_at, tool_name, status
   FROM mcp_server.tool_sessions
   WHERE session_id = ?
   ORDER BY created_at ASC
   LIMIT 100`,
  [sessionId],
  {
    prepare: true,
    fetchSize: 100,
    // For multi-page result sets, pass the previous result.pageState
    // pageState: previousResult.pageState,
  }
);

const rows = result.rows.map(row => ({
  toolName: row.tool_name,
  createdAt: row.created_at,   // JS Date object
  status: row.status,
}));

UPDATE

// UPDATE with IF condition (lightweight transaction — costs 4x a regular write)
// Use sparingly; for most MCP state updates a blind write is sufficient
const result = await client.execute(
  `UPDATE mcp_server.tool_sessions
   SET status = ?
   WHERE session_id = ? AND created_at = ?
   IF status = 'pending'`,
  ['running', sessionId, createdAt],
  { prepare: true }
);

// result.rows[0]['[applied]'] is true if the condition was met
const applied = result.rows[0]?.['[applied]'] ?? false;

DELETE

// DELETE a specific clustering row
await client.execute(
  `DELETE FROM mcp_server.tool_sessions
   WHERE session_id = ? AND created_at = ?`,
  [sessionId, createdAt],
  { prepare: true }
);

// DELETE an entire partition (all clustering rows for a session_id)
await client.execute(
  `DELETE FROM mcp_server.tool_sessions WHERE session_id = ?`,
  [sessionId],
  { prepare: true }
);

Consistency levels

Amazon Keyspaces supports only LOCAL_-prefixed consistency levels. Attempting to use QUORUM or ONE (without the LOCAL prefix) returns an error. The effective choices for MCP server tools:

LevelWritesReadsUse when
LOCAL_QUORUMDefault; acknowledged by majority of replicas in the regionDefault; reads from majority — avoids stale readsAll production MCP tool writes and reads
LOCAL_ONEAcknowledged by one replicaServed by closest replica — may return stale data for up to a few secondsHigh-throughput read-only analytics tools where eventual consistency is acceptable
LOCAL_SERIALNot applicableUsed with lightweight transactions (IF conditions)Read-your-writes consistency for LWT operations
import { types } from 'cassandra-driver';

// Set consistency per query
const result = await client.execute(cql, params, {
  prepare: true,
  consistency: types.consistencies.localQuorum,  // explicitly set; default is already LOCAL_QUORUM
});

// For LWT reads
const lwtResult = await client.execute(conditionalCql, params, {
  prepare: true,
  serialConsistency: types.consistencies.localSerial,
});

IAM policy for Keyspaces access

The IAM user whose service-specific credentials you use must have an IAM policy granting Keyspaces data access. The management API calls (CreateTable, GetTable) also require IAM permissions on the management plane:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "KeyspacesDataAccess",
      "Effect": "Allow",
      "Action": [
        "cassandra:Select",
        "cassandra:Modify"
      ],
      "Resource": [
        "arn:aws:cassandra:us-east-1:123456789012:/keyspace/mcp_server/table/tool_sessions",
        "arn:aws:cassandra:us-east-1:123456789012:/keyspace/system*"
      ]
    },
    {
      "Sid": "KeyspacesManagement",
      "Effect": "Allow",
      "Action": [
        "cassandra:Create",
        "cassandra:Drop",
        "cassandra:Alter"
      ],
      "Resource": "arn:aws:cassandra:us-east-1:123456789012:/keyspace/mcp_server/*"
    }
  ]
}

The cassandra:Select action covers all CQL read operations; cassandra:Modify covers INSERT, UPDATE, DELETE. The system* keyspace resource is required because cassandra-driver queries system tables (system_schema, system_schema_mcs) for metadata and prepared statement caching at connection time.

Client lifecycle in Lambda and long-running servers

How you manage the Client object depends on your MCP server runtime:

RuntimePatternNotes
LambdaInitialize client outside the handler (module scope); reuse across warm invocationsCold start adds ~200–500 ms for TLS handshake + driver connect. Keep Lambda warm or accept cold-start cost.
ECS / Fargate long-runningInitialize once at startup; handle NoHostAvailableException with reconnect logicThe ExponentialReconnectionPolicy handles transient Keyspaces maintenance events automatically.
Short-lived containersInitialize at startup; call await client.shutdown() in process SIGTERM handlerAvoids connection leak warnings in CloudWatch logs during container shutdown.
// Lambda-safe pattern: module-scope singleton
let _client: Client | null = null;

async function getClient(): Promise<Client> {
  if (!_client) {
    _client = await createKeyspacesClient(process.env.AWS_REGION!);
  }
  return _client;
}

export const handler = async (event: MCPEvent) => {
  const client = await getClient();
  // ... use client for tool calls
};

Common errors and fixes

ErrorCauseFix
NoHostAvailableExceptionWrong localDataCenter (must match region string exactly) or missing TLS CA certSet localDataCenter to the exact region string (e.g., us-east-1); ensure AmazonRootCA1.pem is bundled
Unauthorized on CQL connectWrong service-specific credentials or credentials deactivatedRegenerate via aws iam create-service-specific-credential; update Secrets Manager
InvalidQueryError: Consistency level LOCAL_QUORUM is not supportedAttempting non-LOCAL consistency levelUse only localQuorum, localOne, or localSerial
WriteTimeoutExceptionHigh write throughput hitting on-demand burst limits or provisioned WCU capAdd exponential backoff and retry; switch to PAY_PER_REQUEST if on provisioned
InvalidQueryError: system keyspace access deniedIAM policy missing cassandra:Select on system* keyspace resourceAdd arn:aws:cassandra:REGION:ACCOUNT:/keyspace/system* to the Select Allow statement
Table stays in CREATING stateTable creation is async; writes attempted before ACTIVEPoll GetTableCommand until tableStatus === "ACTIVE"

Related guides