You’re running Claude Code at scale across your engineering team. Great. But here’s the question keeping your security team up at night: Where’s the audit trail? What exactly is everyone doing, when, and with what data?
If you work in financial services, healthcare, or any industry where compliance isn’t optional, you know the pain. Generic activity logs don’t cut it. You need something purpose-built to surface the events that actually matter—API calls, file access, data handling, dependency modifications—in a format that your SIEM can ingest and your auditors can trust.
That’s where the Claude Code Compliance API comes in. It’s not a nice-to-have. It’s the backbone of enterprise-grade usage tracking, automated compliance reporting, and the evidence you need when regulators ask what your developers were doing with that AI-powered coding assistant.
The Compliance Problem: Why Generic Logs Aren’t Enough
Let’s be honest: traditional application logging doesn’t work for Claude Code. Here’s why.
Claude Code operates at the intersection of three risk domains:
Data Risk: Your engineers are potentially executing code, reading sensitive files, and querying APIs. You need to know which files they accessed, which external systems they touched, and whether any PII leaked.
Operational Risk: When someone runs a bash command or makes a network request through Claude Code, is it authorized? Does it violate your environment policies? Did someone accidentally drop a database table?
Compliance Risk: For SOC 2, HIPAA, PCI-DSS, or GDPR, you need to prove you knew what was happening, you monitored it, and you responded appropriately when things looked wrong.
Standard syslog or application logs give you process-level events. They don’t tell you why the engineer asked Claude to do something, what they were thinking, or what the user interaction pattern was. They’re fragments without context.
The Compliance API fills that gap. It’s built specifically to expose Claude Code sessions as discrete audit events, complete with:
- User identity and team affiliation
- Session lifecycle (start, pause, commands executed, end)
- File and network access patterns
- API calls and external system interactions
- Risk indicators (privilege escalation, policy violations)
- Environmental context (project, workspace, time of day)
Think of it as the difference between knowing “someone accessed a file” versus knowing “Engineer Alice at 2 PM accessed the production database credentials file, for 47 seconds, after Claude suggested connecting to the live database.”
Understanding the API Architecture
The Compliance API isn’t monolithic. It’s composed of several logical layers:
Events Layer
Raw events are the foundation. Every meaningful action in Claude Code generates one: session creation, command execution, file access, external API calls, errors, policy violations.
Events have a standard schema:
{
"event_id": "evt_1a2b3c4d5e6f",
"timestamp": "2026-03-16T14:23:47Z",
"session_id": "sess_user_project_20260316_142300",
"user_id": "user_alice_acme",
"event_type": "command.execute",
"event_action": "bash_command",
"severity": "medium",
"resource": {
"type": "file",
"path": "/app/src/database.js",
"access_mode": "read"
},
"context": {
"project": "inventory-api",
"workspace": "production-support",
"command": "grep -r 'password' src/",
"exit_code": 0
},
"risk_signals": ["credential_search"],
"metadata": {
"ip_address": "10.0.1.45",
"user_agent": "Claude Code v2.1.0",
"duration_ms": 3421
}
}
Every event captures the what (event type), who (user), when (timestamp), where (resource), and crucially, the risk (severity, risk_signals). This is the grain of salt your compliance team needs—not the entire ocean of logs, but the meaningful particles.
Query Layer
You don’t want to stream all events into your SIEM. You’d drown. Instead, the Query API lets you pull events intelligently:
Time-windowed queries: Get events from the last 24 hours, or audit a specific date range.
Filtered queries: Pull only file access events, or only network calls, or only policy violations.
Aggregation queries: Get usage statistics—how many engineers used Claude Code this week, how many file system operations occurred, what percentage touched sensitive resources.
Session-level queries: Get the complete timeline of a user’s Claude Code session, including every action, every pause, every decision point.
This is where you stop thinking about individual log lines and start thinking about stories. You’re asking: “Show me everything Alice did during her Claude Code session on Tuesday afternoon. Did she access the right files? Did anything look suspicious?”
Compliance Reports Layer
On top of queries, we provide pre-built compliance report generators. These are parameterized report templates that do the heavy lifting:
- Usage Audit Report: Who used Claude Code, when, for how long, on what projects
- Data Access Report: Which sensitive files or systems were accessed, by whom, in which context
- Policy Violation Report: Events that triggered policy rules or risk thresholds
- Incident Investigation Report: Deep-dive timeline for a specific user or session
- Quarterly Attestation Report: Aggregate evidence for auditors (SOC 2, HIPAA, etc.)
Each report comes pre-formatted for export (CSV, JSON, PDF with digital signature), ready to hand to your audit team or regulatory body.
Integration Layer
Finally, you’ve got connectors to major SIEM and compliance platforms:
- Splunk: Real-time event streaming via HEC
- Datadog: Native integration with Log Management
- Elastic: Bulk indexing to Elasticsearch clusters
- AWS CloudWatch: Direct event export to CloudWatch Logs
- Compliance-specific tools: ServiceNow, Domo, Looker dashboards
The integration layer doesn’t dump raw events. It transforms them into platform-specific schemas, so Splunk sees Splunk-shaped data, Datadog sees Datadog-shaped data. It’s the adapter that saves you from having to write transformation pipelines yourself.
Working with the Core Endpoints
Let’s get practical. Here are the endpoints you’ll use most:
GET /compliance/v1/sessions
List Claude Code sessions matching your filters.
curl -X GET "https://api.claudecode.ai/compliance/v1/sessions" \
-H "Authorization: Bearer $COMPLIANCE_API_KEY" \
-H "X-Org-ID: org_acme" \
--data-urlencode "start_time=2026-03-10T00:00:00Z" \
--data-urlencode "end_time=2026-03-16T23:59:59Z" \
--data-urlencode "user_id=user_alice_acme" \
--data-urlencode "project=inventory-api" \
--data-urlencode "limit=100"
Response:
{
"sessions": [
{
"session_id": "sess_alice_inventory_20260316_100000",
"user_id": "user_alice_acme",
"user_email": "[email protected]",
"project": "inventory-api",
"workspace": "main",
"start_time": "2026-03-16T10:00:00Z",
"end_time": "2026-03-16T11:45:30Z",
"duration_minutes": 105,
"event_count": 247,
"risk_level": "low",
"status": "completed"
}
],
"total": 1,
"pagination": {
"cursor": "next_page_token_xyz"
}
}
You’re not getting raw events yet—just the session summaries. This is good for your dashboard: “Here’s a timeline of who used Claude Code and for how long.” It’s lightweight, aggregated, and easy to visualize.
GET /compliance/v1/events
Get granular events within a session or time window.
curl -X GET "https://api.claudecode.ai/compliance/v1/events" \
-H "Authorization: Bearer $COMPLIANCE_API_KEY" \
-H "X-Org-ID: org_acme" \
--data-urlencode "session_id=sess_alice_inventory_20260316_100000" \
--data-urlencode "event_type=file.read,api.call" \
--data-urlencode "severity=medium,high" \
--data-urlencode "limit=500"
Response:
{
"events": [
{
"event_id": "evt_1a2b3c4d",
"timestamp": "2026-03-16T10:15:22Z",
"session_id": "sess_alice_inventory_20260316_100000",
"event_type": "file.read",
"resource": {
"type": "file",
"path": "/app/config/database.env"
},
"severity": "high",
"risk_signals": ["credential_file"],
"context": {
"reason": "Looking for database connection string",
"file_size_bytes": 256
}
},
{
"event_id": "evt_2b3c4d5e",
"timestamp": "2026-03-16T10:16:45Z",
"session_id": "sess_alice_inventory_20260316_100000",
"event_type": "api.call",
"resource": {
"type": "api",
"endpoint": "https://database-server.internal/v1/query"
},
"severity": "high",
"risk_signals": ["external_network_call", "database_access"],
"context": {
"method": "POST",
"response_code": 200,
"request_size_bytes": 1024,
"response_size_bytes": 5120
}
}
],
"total": 247,
"pagination": {
"cursor": "next_page_token_abc"
}
}
Now you’re seeing the granular picture. Alice accessed a credential file and then made a network call to your database server. The API flagged both as high-severity because they’re sensitive. Your SIEM or compliance tool can ingest this and correlate it: “Is this normal? Should Alice be accessing the database from Claude Code?”
POST /compliance/v1/reports/generate
Kick off a compliance report generation job.
curl -X POST "https://api.claudecode.ai/compliance/v1/reports/generate" \
-H "Authorization: Bearer $COMPLIANCE_API_KEY" \
-H "X-Org-ID: org_acme" \
-H "Content-Type: application/json" \
-d '{
"report_type": "data_access",
"start_time": "2026-03-01T00:00:00Z",
"end_time": "2026-03-31T23:59:59Z",
"filters": {
"severity": ["high", "critical"],
"user_ids": ["user_alice_acme", "user_bob_acme"],
"event_types": ["file.read", "api.call"]
},
"format": "pdf",
"include_recommendations": true
}'
Response:
{
"job_id": "job_report_2026031600001",
"status": "pending",
"created_at": "2026-03-16T14:30:00Z",
"estimated_completion": "2026-03-16T14:35:00Z",
"report_type": "data_access",
"format": "pdf"
}
The job runs asynchronously. In a few minutes, you’ll have a PDF report with charts, tables, and narrative findings. This is what you hand to your auditors. It’s not a dump of raw data—it’s structured, it’s focused, it’s professional.
The Hidden Layer: Why This Matters for Enterprise
Here’s what makes the Compliance API actually useful, beyond the obvious.
First: Risk signals are baked in. Every event doesn’t get flagged as high-risk. The API engine evaluates context. Accessing a credential file when you’re implementing database integration is higher-risk than accessing a public config file. Making a network call to your internal database is normal; making a network call to some random external IP is flagged. The API doesn’t just log—it thinks.
This saves your security team from alert fatigue. You’re not wading through 10,000 events to find the 5 that matter. The API surfaces the signal.
Second: The API respects your data retention policy. By default, events expire after 90 days. But here’s the catch—compliance events (policy violations, high-severity actions, incidents) are retained longer. Some organizations need 7 years of retention for regulatory reasons. You configure a retention_policy, and the API automatically:
- Deletes routine events after their TTL
- Archives compliance events to cold storage
- Provides time-travel queries over the retained data
- Generates “data destroyed” attestations for auditors
This is critical. You can’t store 100% of events forever—it’s too expensive. But you must keep the events that matter. The API automates that decision.
Third: The API provides cryptographic proof. Every event includes a signature:
{
"event_id": "evt_1a2b3c4d",
"timestamp": "2026-03-16T10:15:22Z",
// ... event data ...
"signature": {
"algorithm": "sha256",
"value": "abc123def456...",
"signed_by": "compliance-service-key-2026-q1"
},
"hash_chain": {
"previous_event_hash": "xyz789...",
"current_event_hash": "abc123def456..."
}
}
This creates an audit trail that can’t be forged. Your auditors can verify that events haven’t been deleted or modified after the fact. It’s blockchain-y in spirit, but practical: you’re building immutability without the performance cost.
Building a Real Compliance Workflow
Let me walk through a realistic scenario. Your company processes payment card data (PCI-DSS regulated). You want to know if anyone’s accessing credential stores through Claude Code.
Step 1: Define your policy
{
"policy_name": "credential_access_audit",
"rules": [
{
"rule_id": "rule_cred_file_read",
"description": "Alert on reads of credential files",
"conditions": {
"event_type": "file.read",
"resource_path_patterns": [
"**/*.env",
"**/*.pem",
"**/credentials/*",
"**/.ssh/*"
]
},
"action": "flag_high_severity",
"notify": ["[email protected]"]
},
{
"rule_id": "rule_cred_file_modify",
"description": "Alert on modifications to credential files",
"conditions": {
"event_type": ["file.write", "file.delete"],
"resource_path_patterns": ["**/*.env", "**/*.pem", "**/credentials/*"]
},
"action": "flag_critical_severity",
"notify": ["[email protected]", "[email protected]"]
}
]
}
You POST this to /compliance/v1/policies/create. The API validates it and starts enforcing it immediately.
Step 2: Stream events to your SIEM
You configure the SIEM integration endpoint:
{
"integration_type": "splunk_hec",
"endpoint": "https://splunk.acme.com:8088/services/collector",
"token": "${SPLUNK_HEC_TOKEN}",
"batch_size": 100,
"flush_interval_seconds": 5,
"event_filters": {
"severity": ["medium", "high", "critical"],
"include_policy_violations": true
}
}
Now every event that matches your filters gets pushed to Splunk in real time. Your SIEM is seeing what’s happening, and you can set up alerting rules in Splunk to notify security ops immediately.
Step 3: Query for incidents
Two weeks later, your security team gets a report that one of your developers may have leaked credentials. You query the API:
curl -X GET "https://api.claudecode.ai/compliance/v1/events" \
-H "Authorization: Bearer $COMPLIANCE_API_KEY" \
--data-urlencode "user_id=user_charlie_acme" \
--data-urlencode "event_type=file.read,file.write" \
--data-urlencode "severity=high,critical" \
--data-urlencode "start_time=2026-03-01T00:00:00Z" \
--data-urlencode "end_time=2026-03-16T23:59:59Z" | jq .
You get a timeline of all of Charlie’s high-severity file access events. You can see exactly when he accessed which files, whether he copied them elsewhere, whether network calls followed.
Step 4: Generate an incident report
curl -X POST "https://api.claudecode.ai/compliance/v1/reports/generate" \
-H "Authorization: Bearer $COMPLIANCE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"report_type": "incident_investigation",
"user_id": "user_charlie_acme",
"start_time": "2026-03-01T00:00:00Z",
"end_time": "2026-03-16T23:59:59Z",
"include_context": true,
"include_recommendations": true,
"format": "pdf"
}'
Within minutes, you have a professional incident report with a timeline, risk assessment, and recommendations. You hand this to your legal team and your auditors. You’ve proved that you were monitoring, you detected it, and you’re taking action.
Common Pitfalls and How to Avoid Them
Pitfall 1: Over-retention
New compliance officers often say, “Keep everything forever, just in case.” This is expensive and counterproductive. You end up with so much data that signal gets buried in noise. The storage costs also climb astronomically—by year two, you’re paying thousands per month for data you’ll never query.
Fix: Set intelligent retention policies. Keep routine events for 90 days. Archive high-severity and policy-violation events for the full compliance period (often 7 years, but stored in cheaper cold storage, not hot queries). This gives you audit-ready data without the storage bill. Many organizations use tiered storage: hot for 90 days, warm for 1 year, cold for 7 years.
Pitfall 2: No context in your alerts
You set up Splunk to alert on “file.read of *.env file.” Great. But when the alert fires at 3 AM, your on-call engineer sees a raw event ID and no context. Is it an emergency? Is it Bob doing normal maintenance or a security incident?
Fix: Include context in your SIEM integration. Push not just the event, but also the session summary, the user profile, and the policy rule that triggered. Your alert becomes: “Alice ([email protected]) from IP 10.0.1.45 read /app/.env (27 KB) at 10:15 AM on Mar 16. This triggered policy ‘credential_access_audit’.” Now your engineer can decide in seconds whether to page the security team or let it ride.
Pitfall 3: Forgetting about data retention API calls
Here’s a subtle one: your compliance tool makes API calls to the Compliance API to fetch events for reports. Those API calls are themselves audit events. If you’re not careful, you end up logging your own logging, exponentially. This creates bloat and makes queries slower.
Fix: The Compliance API has an internal: true flag for self-generated events. Use it when you’re making API calls from your compliance or SIEM system. This keeps your logs clean and prevents infinite recursion. Your compliance automation won’t pollute the audit trail.
Pitfall 4: Not exporting evidence in tamper-proof format
You generate a compliance report and email it to your auditors as a PDF. But how does the auditor know it wasn’t modified after generation? In a regulatory dispute, a unsigned PDF is worthless.
Fix: Use the signed export format. When you generate a report, request export_format: pdf_signed. The API creates a PDF with an embedded digital signature (signed by Anthropic’s compliance service). Your auditor can verify the signature in Adobe Reader or any PDF tool. This provides legal proof that the report was generated at a specific time and hasn’t been altered.
Pitfall 5: Weak API key management
You create a single API key, share it across your team, and stick it in a Slack channel for “safekeeping.” Now anyone who was ever in that channel has permanent access to 7 years of compliance data.
Fix: Implement proper API key lifecycle management. Create per-system keys (one for your SIEM, one for your dashboard, one for incident response). Set expiration dates. Rotate quarterly. Use IP whitelisting to restrict where the key can be used. If a key is compromised, you revoke that single key, not your entire compliance infrastructure.
Integration Patterns in the Real World
Let me sketch three real patterns that enterprises use:
Pattern 1: Daily Compliance Dashboard
You ingest Compliance API events into your data warehouse (BigQuery, Snowflake, Redshift). Every night, you run aggregation queries:
- Events per user, per project, per severity level
- Top accessed files and APIs
- Policy violations, counts by rule
- Comparison to previous week
You visualize this in a Looker or Tableau dashboard that your security team checks every morning. It’s a heartbeat for your organization’s Claude Code usage. Anomalies jump out: “Why are there 10x more high-severity events today?” Your team has context for the day ahead.
Pattern 2: Automated Incident Response
You write a Lambda (or Cloud Function) that subscribes to Compliance API events. When an event matches a critical policy rule, the Lambda:
- Fetches the full session context
- Runs automated analysis (is this common for this user? is the time of day normal?)
- If it’s genuinely anomalous, creates a Jira ticket and notifies [email protected]
- If it’s probably benign, logs it but doesn’t alert (reducing noise)
This is “playbook automation”—you’ve encoded your team’s incident response knowledge into code. It means your security team spends less time on false positives and more time on real threats.
Pattern 3: Quarterly Attestation Reporting
You run a scheduled job that hits /compliance/v1/reports/generate with report_type: quarterly_attestation. The API:
- Pulls all events from the quarter
- Applies your organization’s compliance framework (SOC 2, HIPAA, etc.)
- Generates charts and metrics
- Creates a narrative summary for auditors
- Outputs a signed PDF
You hand this to your auditors as proof of compliance. The report is machine-generated, so it’s consistent, complete, and defensible. No “oops, we forgot to log this” moments.
Data Retention and Export Formats
Let’s talk about the boring-but-critical stuff.
By default, events expire after 90 days. But you can configure retention tiers:
{
"retention_policies": [
{
"event_type": ["file.read", "command.execute"],
"retention_days": 90,
"storage_class": "hot"
},
{
"event_type": ["policy.violation", "security.incident"],
"retention_days": 2555,
"storage_class": "cold"
},
{
"risk_signals": ["credential_access", "privilege_escalation"],
"retention_days": 2555,
"storage_class": "cold"
}
]
}
“Hot” storage is queryable in real time. “Cold” storage is cheaper but has higher latency (maybe 5-10 seconds to retrieve an event from archive). You pay for speed or cost; pick your tradeoff.
For exports, you get multiple formats:
- CSV: Simple, importable into Excel, databases, SIEMs
- JSON Lines: One JSON object per line, perfect for streaming processing
- Parquet: Columnar format, compressed, great for data warehouses
- PDF: Human-readable reports with charts and signatures
- SIEM-native: Splunk SPL, Datadog JSON, Elastic ndjson
When you request an export, you specify the format. The API handles the transformation.
The Authentication and Authorization Model
The Compliance API uses API key authentication, but it’s stricter than typical APIs.
Every request requires:
Authorization: Bearer $COMPLIANCE_API_KEY
X-Org-ID: org_acme
X-Request-ID: req_unique_id_for_audit_trail
The X-Org-ID header is critical—it scopes all queries to your organization. You can never accidentally query another organization’s compliance data.
API keys have fine-grained permissions:
{
"api_key": "key_compliance_acme_20260316",
"permissions": [
"compliance:sessions:read",
"compliance:events:read",
"compliance:reports:generate",
"compliance:policies:read"
],
"scopes": {
"org_ids": ["org_acme"],
"projects": ["*"],
"severity_levels": ["medium", "high", "critical"]
},
"ip_whitelist": ["10.0.0.0/8", "203.0.113.0/24"],
"expires_at": "2027-03-16T00:00:00Z"
}
You can grant your SIEM integration read-only access to sessions and events, but not the ability to delete or modify policies. Your security team gets full access. Your compliance officer gets read-only access. Least privilege, enforced at the API key level.
Advanced Use Cases: Going Deeper
Let’s explore some scenarios that push the Compliance API further.
Scenario 1: Regulatory Investigation
HIPAA investigator wants to know if any Claude Code user accessed patient records last month. You have 200 engineers and 10,000+ events daily. Traditional searching would take hours.
With the Compliance API:
curl -X POST "https://api.claudecode.ai/compliance/v1/events/search" \
-H "Authorization: Bearer $COMPLIANCE_API_KEY" \
-H "X-Org-ID: org_healthcare" \
-H "Content-Type: application/json" \
-d '{
"query": {
"time_range": {
"start": "2026-02-01T00:00:00Z",
"end": "2026-02-28T23:59:59Z"
},
"resource_classifications": ["healthcare_data", "patient_records"],
"event_types": ["file.read", "api.call", "database.query"],
"severity_min": "medium"
},
"include_session_metadata": true,
"include_user_profile": true,
"output_format": "investigation_report"
}'
The API returns not just the events, but context: who the user is, what team they’re on, what their usual access patterns look like, whether this access was anomalous. If someone normally never touches patient records and suddenly accessed them through Claude Code, that’s flagged as anomalous. The report includes all of this in a format your legal team and auditors can review.
Scenario 2: Insider Threat Detection
You want to catch suspicious patterns: someone accessing files they don’t normally touch, escalating privileges, copying large amounts of data, making network calls to external IPs.
The Compliance API supports behavioral anomaly detection:
{
"detection_rule": "insider_threat_pattern",
"rules": [
{
"rule_id": "unusual_file_access_volume",
"description": "User accessing 10x more files than baseline in 1 hour",
"anomaly_detector": "time_series",
"baseline_window_days": 30,
"threshold_multiplier": 10,
"action": "flag_high_severity"
},
{
"rule_id": "privilege_escalation",
"description": "User attempting to run commands with escalated privileges",
"conditions": {
"command_patterns": ["sudo", "su -", "RunAs"]
},
"action": "flag_critical_severity"
},
{
"rule_id": "data_exfiltration_pattern",
"description": "Reading sensitive files followed by external network call",
"correlation": {
"event_sequence": [
{ "event_type": "file.read", "resource_classification": "sensitive" },
{ "event_type": "api.call", "destination_type": "external" }
],
"within_seconds": 300
},
"action": "flag_critical_severity"
}
]
}
You POST this anomaly detection ruleset to the API. Now, every event gets evaluated against these rules. If Alice’s usage suddenly spikes 10x above her baseline, the system flags it automatically. No human has to spot the pattern manually.
Scenario 3: Multi-Tenant Compliance (MSP/SaaS)
You’re a managed services provider (MSP) and you manage Claude Code deployments for 50 different customers. Each customer has different compliance requirements. Customer A (a bank) requires SOC 2. Customer B (a healthcare provider) requires HIPAA.
The Compliance API supports multi-tenant separation:
{
"org_id": "org_customer_a_bank",
"compliance_framework": "soc2",
"policies": [
{
"policy_id": "soc2_access_control",
"description": "All file access must be logged and reviewed",
"enforcement": "strict"
}
]
}
And separately:
{
"org_id": "org_customer_b_healthcare",
"compliance_framework": "hipaa",
"policies": [
{
"policy_id": "hipaa_phi_protection",
"description": "No access to PHI without audit logging and encryption",
"enforcement": "strict"
}
]
}
Each customer gets their own API key, scoped to their org. Your compliance engine generates framework-specific reports for each. You can generate a SOC 2 report for Customer A and a HIPAA report for Customer B—both from the same underlying API, but shaped by their requirements. This scales to 50 customers, or 500. Each sees only their own data. Each gets compliance reports in their required format.
Performance and Scalability Considerations
If you’re deploying at large scale, you need to understand the API’s performance characteristics.
Query Performance: Sessions endpoint is optimized for aggregation queries. Filtering 10,000 sessions by time range and user is sub-second. Event queries on large time ranges (30+ days) might take 2-5 seconds—acceptable for async report generation, not for real-time dashboards.
Ingestion Rate: The API handles up to 100,000 events per second per organization. If you’re smaller, you’re fine. If you have 10,000+ engineers all using Claude Code simultaneously, you’re pushing toward limits. Contact Anthropic’s enterprise support team for high-throughput plans.
Storage Costs: Events in hot storage cost roughly $0.05 per GB per month. With an average event size of 2 KB, that’s roughly 500 events per MB. If you store 1 million events per day, that’s ~2 GB/day, or ~60 GB/month, or ~$3/month in hot storage. Cold storage is 10x cheaper. Reasonable for most enterprises. Budget accordingly as you scale.
API Rate Limits: Standard tier allows 1,000 requests per minute per API key. Enterprise tier allows 10,000 requests per minute. If you’re making requests faster than that, you’re probably doing something inefficient. Batch your queries when possible. Use aggregation endpoints instead of pulling individual events.
Building a Compliance Dashboard (Practical Example)
Let me sketch a real Python implementation for a compliance dashboard that queries the API hourly and updates a Grafana instance:
from datetime import datetime, timedelta
class ComplianceMonitor:
def __init__(self, api_key, org_id):
self.api_key = api_key
self.org_id = org_id
self.base_url = "https://api.claudecode.ai/compliance/v1"
self.headers = {
"Authorization": f"Bearer {api_key}",
"X-Org-ID": org_id,
"Content-Type": "application/json"
}
def get_sessions_summary(self, hours=24):
"""Get session count and risk breakdown for last N hours"""
start_time = (datetime.utcnow() - timedelta(hours=hours)).isoformat() + "Z"
end_time = datetime.utcnow().isoformat() + "Z"
params = {
"start_time": start_time,
"end_time": end_time,
"aggregate": True,
"group_by": "risk_level"
}
response = requests.get(
f"{self.base_url}/sessions",
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
def get_policy_violations(self, hours=1):
"""Get recent policy violations for alerting"""
start_time = (datetime.utcnow() - timedelta(hours=hours)).isoformat() + "Z"
end_time = datetime.utcnow().isoformat() + "Z"
params = {
"start_time": start_time,
"end_time": end_time,
"severity": "critical,high",
"has_policy_violation": True
}
response = requests.get(
f"{self.base_url}/events",
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
def send_to_grafana(self, metric_name, value, labels=None):
"""Send metric to Grafana via Prometheus remote write"""
# Simplified example—in production, use proper Prometheus client library
grafana_url = os.getenv("GRAFANA_PROMETHEUS_URL")
if not grafana_url:
return
timestamp = int(datetime.utcnow().timestamp()) * 1000
metric = {
"metric": {
"__name__": f"claude_code_compliance_{metric_name}",
**(labels or {})
},
"value": [timestamp, value]
}
requests.post(
f"{grafana_url}/api/v1/write",
json={"timeseries": [metric]}
)
def run_hourly_check(self):
"""Hourly monitoring task"""
# Get session summary
sessions = self.get_sessions_summary(hours=1)
# Send metrics to Grafana
self.send_to_grafana("sessions_total", sessions.get("total", 0))
for risk_level in ["low", "medium", "high", "critical"]:
count = sessions.get("by_risk_level", {}).get(risk_level, 0)
self.send_to_grafana("sessions_by_risk", count, {"risk_level": risk_level})
# Check for policy violations
violations = self.get_policy_violations(hours=1)
if violations.get("events"):
for event in violations["events"]:
# Log to your incident response system
print(f"CRITICAL: Policy violation detected: {event}")
if __name__ == "__main__":
api_key = os.getenv("COMPLIANCE_API_KEY")
org_id = os.getenv("ORG_ID")
monitor = ComplianceMonitor(api_key, org_id)
monitor.run_hourly_check()
You run this script every hour via cron or Kubernetes CronJob. It queries the Compliance API, extracts metrics, and sends them to Grafana. Your dashboard updates automatically. Your team sees real-time compliance posture. Anomalies surface before they become incidents.
Troubleshooting Common Issues
Issue: API quota exhausted
You’re seeing 429 errors (“too many requests”). This usually means your integration is making redundant API calls.
Solution: Implement caching on your end. If you’re querying for “events from last hour” every minute, cache the result for 5 minutes. You’re not losing visibility; you’re just batching queries. Use aggregation endpoints instead of pulling individual events when possible.
Issue: Cold storage queries timing out
You’re querying 6-month-old compliance events and hitting timeouts.
Solution: Cold storage has higher latency. Increase your query timeout to 30 seconds. Better yet, if you regularly query historical data, request that Anthropic moves the data to a warm tier temporarily. For one-off audits, accept the latency.
Issue: Report generation failing without clear errors
You’re posting to /reports/generate but getting generic 500 errors.
Solution: Check that your filter criteria actually match events. If you’re filtering for severity: "informational" but only high-severity events are stored, the report will be empty and may fail. Validate your filters by running a preliminary events query first.
Wrapping Up: Building Compliance Into Your Culture
The Compliance API is powerful, but it’s not a magic wand. It gives you visibility, but you have to decide what’s acceptable and what’s not.
Start by defining your policies clearly. What counts as high-risk? What files and systems are sensitive? What’s your acceptable use case for Claude Code? Write that down. Then encode it into the Compliance API.
Integrate with your SIEM and dashboard tools. Don’t let compliance reports happen once a quarter in a vacuum. Make it a continuous, visible process. Your team will naturally start thinking about compliance when they know they’re being monitored fairly and consistently.
Educate your developers. The Compliance API isn’t meant to be punitive. It’s meant to keep everyone safe—both the company and the engineer. If an engineer knows that accessing credential files gets flagged and reviewed, they’ll be more careful. That’s good for everyone.
And remember: compliance is about risk management, not about creating security theater. The Compliance API helps you manage real risks—unauthorized data access, privilege escalation, policy violations—in a way that’s proportionate and evidence-based.
Use it well, and your organization will have Claude Code that’s both powerful and trustworthy. That’s enterprise-grade AI, the way it should be.
Real-World Implementation Timeline
Most enterprises take 4-8 weeks to fully integrate the Compliance API into their infrastructure. Here’s a realistic timeline:
Week 1-2: Planning and Scoping
During this phase, you work with stakeholders across security, engineering, and compliance to define requirements. Key questions to answer: What’s your current logging infrastructure? Who needs access to compliance data? What regulations apply? Which systems are sensitive? This discovery phase prevents false starts and ensures you’re building the right thing.
Week 2-3: API Key Management and Authentication
Set up your API keys, define fine-grained permissions, and integrate with your identity management system (Okta, Azure AD, Ping). This is security-critical and shouldn’t be rushed. Configure IP whitelisting, set key expiration dates, and establish a rotation schedule. Document the process clearly so new team members can understand how to request access correctly.
Week 3-5: SIEM Integration
Connect your SIEM platform (Splunk, Datadog, Elastic) to the Compliance API. Build the transformation pipelines so events arrive in the right format. Create your first dashboard showing session activity and risk levels. Test with synthetic events before going live. This usually takes 2-3 weeks because SIEM integrations require careful attention to schema mapping and filtering rules.
Week 5-6: Policy Definition and Testing
Define your organization-specific policies. What counts as credential access? Which resources are sensitive? What network calls are suspicious? Create policies incrementally—don’t try to define everything at once. Test each policy with real data (or synthetic data that matches your patterns) to make sure it triggers appropriately without excessive false positives.
Week 6-8: Incident Response Integration
Build automated incident response playbooks. Create Jira/ServiceNow tickets automatically for high-severity policy violations. Set up Slack or email notifications to your security team. Test the end-to-end flow: event occurs → policy triggers → ticket created → team notified. This closing-the-loop phase is where the system becomes genuinely valuable.
During this timeline, run regular check-ins with stakeholders. Show them the dashboard. Let them see what’s being logged. Gather feedback early and adjust before going production. By week 8, you should have a working system that your team trusts.
Cost Analysis and ROI
Enterprises often ask: “How much does this cost, and is it worth it?” The answer depends on your organization, but here’s a framework for thinking about it.
Direct Costs
- API licensing: typically $5,000-$25,000/month depending on event volume and retention requirements
- Integration work: 2-3 engineers for 4-8 weeks (roughly $50,000-$100,000 in labor)
- SIEM expansion: you might need additional SIEM licenses or storage (varies widely, $10,000-$50,000+)
- Ongoing operations: 1 engineer part-time maintaining dashboards and policies
Indirect Benefits
- Reduced audit costs: Professional audits cost $50,000-$150,000 per engagement. If the Compliance API cuts that in half through better documentation and evidence, the ROI is immediate.
- Faster incident response: When you can query seven years of events and reconstruct what happened in minutes instead of days, you reduce incident response costs by an order of magnitude.
- Risk avoidance: One prevented data breach (whether through detection or compliance evidence) saves hundreds of thousands of dollars. Even a small percentage improvement in preventing incidents pays for the system many times over.
- Team productivity: Engineers spend less time dealing with security reviews and audits. Your security team spends less time on manual investigation. That’s worth money.
For most enterprises spending $1M+ on engineering, the Compliance API pays for itself through audit savings and incident cost reduction within the first year. For smaller organizations, you’re building compliance infrastructure that scales with your team.
Governance and Change Management
The Compliance API creates visibility, which creates governance opportunities. Use this thoughtfully.
Create a compliance review board—a monthly meeting where security, engineering, and compliance review the previous month’s logs, violations, and patterns. This creates transparency and allows your team to surface context that automated systems miss. An engineer might say: “That high-severity event looks scary, but it was actually part of a planned security audit. We should tag those differently.” These conversations improve your system over time.
Establish a clear policy for how violations are handled. Is it an automated alert and investigation? Does it require manager approval? Is discipline involved, or is it more educational? Whatever you decide, document it and apply it consistently. Your engineers deserve to know how they’re being monitored and what the consequences are.
Version-control your policies like you version-control your code. Store policy definitions in Git. Require pull request reviews for policy changes. Document why you’re changing a rule. This creates an audit trail and prevents drift.
Compliance API Roadmap
The Compliance API is evolving. Here are features that Anthropic is adding:
In 2026: Machine learning–based anomaly detection (automatically learns your team’s normal patterns and flags deviations), end-to-end encryption option (events encrypted in transit and at rest), native SOC 2 report generation (fully automated attestation document generation).
2026-2027: Federated query API (query compliance data across multiple organizations in one request), blockchain-backed event signing (immutable proof of event integrity), policy-as-code frameworks (define policies in Python or Go instead of JSON).
2027+: GraphQL API for compliance querying, deep learning incident prediction (predictive alerts before incidents happen), generative compliance report writing (AI-generated narrative analyses).
These features are coming, but the core capabilities you have today are production-ready and powerful. Don’t wait for perfect features. Deploy with what exists now and upgrade as new capabilities arrive.
Troubleshooting Integration Issues
Issue: Events arriving slowly in SIEM
If there’s latency between the Compliance API and your SIEM, check your batch size and flush interval settings. Increase batch size to 500+ and flush interval to 10-30 seconds. This increases latency by a few seconds but reduces SIEM load. For near-real-time requirements, use smaller batches and flush immediately, but understand the tradeoff: faster delivery = higher API overhead.
Issue: Policy not triggering as expected
Always validate your policy logic by running test events first. Use /compliance/v1/test-policy endpoint to send synthetic events and verify your policy rules respond correctly. Policies use AND logic by default for multiple conditions—if you want OR logic, structure your policy differently or create multiple rules.
Issue: API key rotation causing downtime
Plan key rotations carefully. Generate a new key, configure both old and new keys in your integrations, verify both work, then retire the old key after 24 hours. Don’t rotate immediately—give your systems time to start using the new key. For critical integrations (SIEM), do this during a maintenance window.
At -iNet, we believe that enterprise tools should be both powerful and transparent. The Compliance API for Claude Code is that rare combination: it gives you the oversight you need without hindering your team’s ability to innovate. If you’re deploying Claude Code at scale, it’s worth the investment.