Guide · Amazon S3 · Compliance and Immutability
S3 Object Lock for MCP Servers — WORM Compliance for Audit Logs and Immutable Artifacts
MCP servers that handle sensitive operations — financial transactions, healthcare queries, legal document lookups, PII-touching tools — must often satisfy compliance requirements around data immutability: audit logs that cannot be altered or deleted, model outputs that must be preserved for regulatory review, tool invocation records with tamper-evident retention. S3 Object Lock implements WORM (Write Once Read Many) protection directly at the storage layer, making it impossible to delete or overwrite an object before its retention period expires — even for the account root user in COMPLIANCE mode. This guide covers the two retention modes (GOVERNANCE vs COMPLIANCE), legal holds, bucket default retention configuration, the Node.js SDK integration for locking objects at write time, how to handle locked-object errors in tool handlers, and the interplay between versioning (required for Object Lock) and retention policies.
TL;DR
Object Lock must be enabled at bucket creation time — it cannot be enabled on an existing bucket. Enabling Object Lock automatically enables versioning. Use GOVERNANCE mode during development (overridable with s3:BypassGovernanceRetention permission) and COMPLIANCE mode in production (no override possible, even by root). Set a bucket-level default retention to lock every object automatically. Write audit logs with ObjectLockMode and ObjectLockRetainUntilDate in the PutObject call. Attempting to delete a locked object returns HTTP 403 — catch AccessDenied in your tool handlers and handle it as an immutability violation, not a permission error.
Retention modes: GOVERNANCE vs COMPLIANCE
| Attribute | GOVERNANCE | COMPLIANCE |
|---|---|---|
| Can shorten retention period | Yes, with s3:BypassGovernanceRetention IAM permission | No. Cannot be shortened by anyone, including account root |
| Can delete before expiry | Yes, with s3:BypassGovernanceRetention + x-amz-bypass-governance-retention: true header | No. DeleteObject returns 403 until retention expires |
| Can extend retention period | Yes | Yes (can only extend, never shorten) |
| Appropriate for | Development, internal audit logs, pre-production testing | Regulatory compliance (SEC 17a-4, HIPAA, FINRA, GDPR data preservation orders) |
| Recovery from misconfiguration | Possible — revoke and bypass | Impossible until expiry — test retention periods carefully before switching to COMPLIANCE |
Warning: Setting a 7-year retention period in COMPLIANCE mode on a bucket filled with the wrong data means you pay 7 years of S3 storage costs with no option to delete. Test all Object Lock configurations in GOVERNANCE mode first with short retention periods (e.g., 1 day) before promoting to COMPLIANCE with production retention durations.
Creating an Object Lock-enabled bucket
Object Lock must be specified at bucket creation — there is no API to enable it on an existing bucket:
import {
S3Client,
CreateBucketCommand,
PutObjectLockConfigurationCommand,
ObjectLockEnabled,
ObjectLockRetentionMode,
} from "@aws-sdk/client-s3";
const s3 = new S3Client({ region: "us-east-1" });
// 1. Create bucket with Object Lock enabled
// (automatically enables versioning)
await s3.send(new CreateBucketCommand({
Bucket: "mcp-audit-logs",
ObjectLockEnabledForBucket: true,
// For us-east-1, do not include CreateBucketConfiguration
// For other regions, include the LocationConstraint here
}));
// 2. Set bucket-level default retention
// Every object written to this bucket gets COMPLIANCE retention for 2 years
// unless overridden at the object level
await s3.send(new PutObjectLockConfigurationCommand({
Bucket: "mcp-audit-logs",
ObjectLockConfiguration: {
ObjectLockEnabled: ObjectLockEnabled.Enabled,
Rule: {
DefaultRetention: {
Mode: ObjectLockRetentionMode.COMPLIANCE,
// Use Days OR Years, not both
Days: 730, // 2 years
},
},
},
}));
With a default retention set, every new object version written to mcp-audit-logs gets a retention expiry date of now + 730 days applied automatically — even if the PutObject call does not include any Object Lock parameters.
Writing audit logs with explicit retention
For fine-grained control, set retention at the object level in the PutObject call. This overrides the bucket default for that specific object:
import { PutObjectCommand, ObjectLockMode } from "@aws-sdk/client-s3";
interface AuditRecord {
timestamp: string;
toolName: string;
userId: string;
inputParams: unknown;
outputSummary: string;
sessionId: string;
}
export async function writeAuditLog(record: AuditRecord): Promise<void> {
const retainUntil = new Date();
retainUntil.setFullYear(retainUntil.getFullYear() + 7); // 7-year regulatory retention
const key = `audit/${record.timestamp.substring(0, 10)}/${record.sessionId}/${Date.now()}.json`;
await s3.send(new PutObjectCommand({
Bucket: "mcp-audit-logs",
Key: key,
Body: JSON.stringify(record),
ContentType: "application/json",
// Explicit retention overrides bucket default for this object
ObjectLockMode: ObjectLockMode.COMPLIANCE,
ObjectLockRetainUntilDate: retainUntil,
// Server-side encryption for sensitive audit data
ServerSideEncryption: "aws:kms",
SSEKMSKeyId: process.env.AUDIT_KMS_KEY_ARN!,
// Checksum for tamper detection
ChecksumAlgorithm: "SHA256",
}));
}
// MCP tool wrapper that records every tool invocation
export function withAuditLog<P, R>(
toolName: string,
handler: (params: P, userId: string) => Promise<R>,
) {
return async (params: P, userId: string): Promise<R> => {
const start = Date.now();
let outputSummary = "";
let error: Error | null = null;
try {
const result = await handler(params, userId);
outputSummary = `success (${Date.now() - start}ms)`;
return result;
} catch (err: any) {
error = err;
outputSummary = `error: ${err.message}`;
throw err;
} finally {
await writeAuditLog({
timestamp: new Date().toISOString(),
toolName,
userId,
inputParams: params,
outputSummary,
sessionId: (params as any)?.sessionId ?? "unknown",
}).catch(auditErr => {
// Audit write failure should NOT silently drop — alert but don't throw
console.error("AUDIT WRITE FAILED:", auditErr);
// In production: also send to CloudWatch Logs as backup
});
}
};
}
Reading and inspecting locked objects
Locked objects are read normally with GetObjectCommand. To inspect the retention configuration on an existing object:
import {
GetObjectRetentionCommand,
GetObjectLegalHoldCommand,
HeadObjectCommand,
} from "@aws-sdk/client-s3";
export async function inspectObjectLock(bucket: string, key: string, versionId?: string) {
// Get retention period
const retention = await s3.send(new GetObjectRetentionCommand({
Bucket: bucket,
Key: key,
VersionId: versionId,
}));
// Get legal hold status
const legalHold = await s3.send(new GetObjectLegalHoldCommand({
Bucket: bucket,
Key: key,
VersionId: versionId,
}));
// Also available via HeadObject response headers
const head = await s3.send(new HeadObjectCommand({
Bucket: bucket,
Key: key,
VersionId: versionId,
}));
return {
retentionMode: retention.Retention?.Mode,
retainUntil: retention.Retention?.RetainUntilDate,
legalHold: legalHold.LegalHold?.Status,
checksum: head.ChecksumSHA256,
versionId: head.VersionId,
};
}
Legal holds — indefinite protection independent of retention period
A legal hold freezes an object indefinitely, independent of its retention period. Even if retention expires, an object with an active legal hold cannot be deleted. Use legal holds for objects involved in litigation or regulatory investigations:
import {
PutObjectLegalHoldCommand,
ObjectLockLegalHoldStatus,
} from "@aws-sdk/client-s3";
// Place legal hold on a session's audit logs
export async function placeLegalHold(bucket: string, key: string, versionId: string): Promise<void> {
await s3.send(new PutObjectLegalHoldCommand({
Bucket: bucket,
Key: key,
VersionId: versionId,
LegalHold: { Status: ObjectLockLegalHoldStatus.ON },
}));
}
// Release legal hold when litigation concludes
export async function releaseLegalHold(bucket: string, key: string, versionId: string): Promise<void> {
await s3.send(new PutObjectLegalHoldCommand({
Bucket: bucket,
Key: key,
VersionId: versionId,
LegalHold: { Status: ObjectLockLegalHoldStatus.OFF },
}));
}
Legal hold on/off requires the s3:PutObjectLegalHold IAM action. This should be restricted to a privileged role (compliance officer, legal team tooling), not the standard MCP server runtime role.
Handling locked-object errors in MCP tool handlers
When an MCP tool handler attempts to delete or overwrite a locked object, S3 returns AccessDenied (HTTP 403). This is different from an IAM permission error — both use the same error code. Distinguish them by checking the error message:
import { DeleteObjectCommand } from "@aws-sdk/client-s3";
export async function deleteArtifact(bucket: string, key: string, versionId: string): Promise<void> {
try {
await s3.send(new DeleteObjectCommand({
Bucket: bucket,
Key: key,
VersionId: versionId,
}));
} catch (err: any) {
if (err.name === "AccessDenied") {
// Could be: (1) IAM missing DeleteObject permission, or
// (2) Object is locked (COMPLIANCE mode or legal hold)
// Distinguish by checking the error message
if (
err.message?.includes("Object Lock") ||
err.message?.includes("retention")
) {
throw new Error(
`Object ${key}@${versionId} is WORM-locked until its retention period expires. ` +
`Check compliance requirements before attempting deletion.`
);
}
throw new Error(`IAM permission denied for s3:DeleteObject on ${bucket}/${key}`);
}
throw err;
}
}
For GOVERNANCE mode objects, an operator with s3:BypassGovernanceRetention permission can override the lock by passing BypassGovernanceRetention: true in DeleteObjectCommand:
// GOVERNANCE bypass — only for privileged roles, never in MCP server runtime code
await s3.send(new DeleteObjectCommand({
Bucket: "mcp-audit-logs-dev",
Key: key,
VersionId: versionId,
BypassGovernanceRetention: true,
}));
Versioning and Object Lock interaction
Object Lock requires versioning. Important implications for MCP server audit log buckets:
- Every PUT creates a new version. Writing to the same key (e.g., appending to an audit log file) creates a new version; the old version remains locked separately. Use unique keys per log entry (e.g., include
Date.now()or a UUID in the key) rather than re-using keys. - Delete markers are not locked. A
DeleteObjectCommandwithout a VersionId creates a delete marker — the locked version still exists beneath it. The object is not deleted and storage is still billed. The locked version must expire naturally. - Lifecycle rules cannot expire locked objects. S3 lifecycle rules that transition or expire objects are blocked by Object Lock during the retention period. Plan your storage costs accordingly — locked objects in COMPLIANCE mode will remain and be billed until expiry.
- MFA Delete is compatible with Object Lock for an extra layer of protection on GOVERNANCE mode objects.
import { ListObjectVersionsCommand } from "@aws-sdk/client-s3";
// List all versions of an audit log key (including delete markers)
async function listAuditVersions(bucket: string, keyPrefix: string) {
const response = await s3.send(new ListObjectVersionsCommand({
Bucket: bucket,
Prefix: keyPrefix,
MaxKeys: 1000,
}));
return {
versions: response.Versions ?? [], // Live versions (each with VersionId)
deleteMarkers: response.DeleteMarkers ?? [], // Delete markers (soft deletes)
isTruncated: response.IsTruncated,
};
}
IAM permissions
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "MCPRuntimeAuditWrite",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:HeadObject"
],
"Resource": "arn:aws:s3:::mcp-audit-logs/*"
},
{
"Sid": "MCPRuntimeAuditList",
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:ListBucketVersions"
],
"Resource": "arn:aws:s3:::mcp-audit-logs"
},
{
"Sid": "MCPRuntimeRetentionRead",
"Effect": "Allow",
"Action": [
"s3:GetObjectRetention",
"s3:GetObjectLegalHold"
],
"Resource": "arn:aws:s3:::mcp-audit-logs/*"
}
// Note: s3:PutObjectRetention, s3:PutObjectLegalHold, s3:BypassGovernanceRetention
// should NOT be in the MCP server runtime role — these are privileged ops
// for compliance officers / DevOps roles only.
]
}
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
InvalidBucketState on PutObjectLockConfiguration | Trying to enable Object Lock on an existing bucket (bucket already created without it) | Object Lock must be enabled at bucket creation — create a new bucket with ObjectLockEnabledForBucket: true |
AccessDenied on DeleteObject | Object is in COMPLIANCE retention or has active legal hold | Wait for retention expiry (COMPLIANCE) or release legal hold (privileged role required); COMPLIANCE objects cannot be deleted early by anyone |
MalformedXML on PutObjectLockConfiguration | Specifying both Days and Years in DefaultRetention | Use either Days OR Years, never both |
| Object exists but GetObjectRetention returns no retention | Object was written before the bucket default retention was set, or written without Object Lock headers | Explicitly set retention on individual objects via PutObjectRetention; bucket default only applies to objects written after the default was set |
| High storage costs from versioning | Non-current object versions from overwrites accumulating in locked bucket | Use unique keys per audit record (never overwrite); lifecycle rules cannot expire locked versions before retention, but can expire non-locked versions and delete markers once their retention has cleared |
Related guides
- S3 Intelligent-Tiering for MCP servers: automatic cost optimization for stored artifacts
- S3 Express One Zone for MCP servers: ultra-low latency hot cache with directory buckets
- S3 Multi-Region Access Points for MCP servers: global artifact distribution and routing
- CloudTrail Lake for MCP server audit queries
- MCP server uptime monitoring