ZeroCarbon Documentation
Infrastructure-Grade Carbon Accounting API
Not just a calculator—a complete carbon activity ingestion, normalization, verification, and reporting engine that transforms raw operational data into audit-ready emissions intelligence.
Highlights
What Makes ZeroCarbon API Different?
Canonical Activity Model
Single unbreakable data contract for all emissions. 35+ standardized fields with full type safety and Zod validation.
Confidence Scoring
5-factor weighted algorithm (0–100%) assessing data quality: Source quality, Completeness, Factor quality, Temporal accuracy, Methodological rigor.
Git-like Audit Trail
SHA-256 hash chains for every carbon activity. Complete version history with tamper-proof integrity verification.
Carbon Ledger
Double-entry bookkeeping for emissions. Tracks balance_before, transaction_amount, balance_after for complete transparency.
Core Architecture
ZeroCarbon API v3 is built on four foundational pillars that ensure data integrity, compliance, and scalability.
1. Canonical Activity Model
Every emission flows through a single, unbreakable data contract with 35+ standardized fields. This ensures consistency across all data sources—whether from manual entry, CSV uploads, ERP integrations, or IoT sensors.
2. Confidence Scoring System
Data quality is quantified using a 5-factor weighted algorithm (0–100% scale).
3. Audit Trail & Version Control
Git-like version control for every carbon activity using SHA-256 hash chains.
Provides tamper-proof integrity verification meeting SEC, CSRD, and BRSR audit requirements.
4. Carbon Ledger (Double-Entry Bookkeeping)
Accounting-grade emission tracking with separate ledgers for Scope 1, 2, and 3.
emission_addemission_reduceoffset_purchaseoffset_retirebalance_beforetransaction_amountbalance_afterFrozen period-end balances for regulatory reporting
Quick Example (Node.js SDK)
import { ZeroCarbon } from 'zerocarbon-nodejs-sdk'; import * as dotenv from 'dotenv'; dotenv.config(); // Initialize client const client = new ZeroCarbon({ apiKey: process.env.ZEROCARBON_API_KEY!, baseUrl: 'https://api.zerocarbon.org.in/v1' }); // Submit electricity activity const result = await client.emissions.calculate({ activity_type: 'electricity', quantity: 1500, unit: 'kWh', location: { country: 'IN', state: 'MH' }, period: { start: '2026-02-01', end: '2026-02-28' } }); console.log(`Emissions: ${result.emissions_kg_co2e} kg CO2e`); console.log(`Confidence: ${result.confidence_score}`);
Base URL
https://api.zerocarbon.org.in/v1
Next Steps
Quick Start Guide
Install SDKs and submit your first activity in 5 minutes.
Authentication
Learn how to generate and manage API keys.
API Reference
Explore all available endpoints and parameters.
Quick Start Guide
Get up and running with the ZeroCarbon API in under 5 minutes.
Get API Key
Sign up and generate your API key.
Install SDK
Install the ZeroCarbon SDK using npm, pnpm, yarn, or pip.
Make Request
Submit your first carbon activity and receive emissions data.
Step 1: Get Your API Key
Prerequisites
API access requires one of the following:
- Professional Plan (₹14,999/month) + API Add-on Pack (₹999–₹2,999/month)
- Enterprise Plan (₹39,999/month) (includes unlimited API keys)
Note: Trial and Starter plans do not include API access.
Generate Your API Key
- Log in to your ZeroCarbon dashboard.
- Navigate to: Settings → Billing → API Keys
- Click Create New API Key.
- Select either:Test (zc_test_)Live (zc_live_)
- Copy your API key (it is shown only once).
Security Best Practice
- Never commit API keys to Git.
- Never expose API keys publicly.
- Store keys using environment variables or a secrets manager.
Step 2: Install the SDK
Node.js / TypeScript
npm install zerocarbon-nodejs-sdk dotenv # or pnpm add zerocarbon-nodejs-sdk dotenv # or yarn add zerocarbon-nodejs-sdk dotenv
Python
pip install zerocarbon-python-sdk python-dotenvStep 3: Submit Your First Activity
Node.js / TypeScript Example
import { ZeroCarbon } from "zerocarbon-nodejs-sdk"; import * as dotenv from "dotenv"; dotenv.config(); const client = new ZeroCarbon({ apiKey: process.env.ZEROCARBON_API_KEY!, baseUrl: "https://api.zerocarbon.org.in/v1", }); async function submitActivity() { try { const result = await client.emissions.calculate({ activity_type: "electricity", quantity: 1500, unit: "kWh", period: { start: "2026-02-01", end: "2026-02-28", }, location: { country: "IN", state: "MH", city: "Mumbai", }, source: { type: "manual", confidence: 0.95, }, }); console.log("✅ Activity submitted successfully!"); console.log(`📊 Emissions: ${result.emissions_kg_co2e} kg CO2e`); console.log(`🎯 Confidence: ${result.confidence_score}`); console.log(`🔗 Activity ID: ${result.activity_id}`); } catch (error) { console.error("❌ Error:", error); } } submitActivity();
Python Example
from zerocarbon import ZeroCarbon
import os
from dotenv import load_dotenv
load_dotenv()
client = ZeroCarbon(
api_key=os.getenv("ZEROCARBON_API_KEY"),
base_url="https://api.zerocarbon.org.in/v1"
)
result = client.emissions.calculate({
"activity_type": "electricity",
"quantity": 1500,
"unit": "kWh",
"period": {
"start": "2026-02-01",
"end": "2026-02-28"
},
"location": {
"country": "IN",
"state": "MH",
"city": "Mumbai"
},
"source": {
"type": "manual",
"confidence": 0.95
}
})
print("✅ Activity submitted successfully!")
print(f"📊 Emissions: {result['emissions_kg_co2e']} kg CO2e")
print(f"🎯 Confidence: {result['confidence_score']}")
print(f"🔗 Activity ID: {result['activity_id']}")What's Next?
📋Carbon Activity Model
Understand the complete data model, available activity types, and supported fields.
📚API Reference
Explore every endpoint, request schema, response format, and error code.
📊Generate Reports
Create BRSR, GHG Protocol, and custom compliance reports.
💡Complete Examples
View full end-to-end integration examples for common workflows.
Helpful Tips
Connect AI Agent (MCP)
Connect the ZeroCarbon MCP (Model Context Protocol) server to your AI agent in 30 seconds for autonomous carbon accounting.
Add Server to Config
Add the ZeroCarbon MCP endpoint to your MCP client config (Claude Desktop / Cline / Cursor / Windsurf / Any MCP-compatible agent).
Paste API Key
Drop in a zc_live_ or zc_test_ key. The agent will use it for all authenticated ledger operations automatically.
Ask Anything
Start with: "What was our Scope 2 electricity footprint last month?" Your agent will call the MCP server and reason over the ledger.
MCP Server Endpoint
{
"name": "zerocarbon-mcp",
"url": "https://api.zerocarbon.org.in/api/v1/mcp",
"transport": "sse",
"headers": {
"Authorization": "Bearer undefined"
}
}Client Config Examples
{
"mcpServers": {
"zerocarbon": {
"url": "https://api.zerocarbon.org.in/api/v1/mcp",
"transport": "sse",
"headers": {
"Authorization": "Bearer ${ZEROCARBON_API_KEY}"
}
}
}
}Settings → MCP Servers → Add Server → paste:
{
"type": "sse",
"name": "ZeroCarbon",
"url": "https://api.zerocarbon.org.in/api/v1/mcp",
"headers": {
"Authorization": "Bearer ${ZEROCARBON_API_KEY}"
}
}Exposed MCP Tools
Every tool is callable by your AI agent with full schema validation and audit logging.
| Tool Name | Scope | Description |
|---|---|---|
carbon.activities.submit | Write | Ingest one or more carbon activities with idempotency protection. |
carbon.emissions.get | Read | Retrieve aggregated emissions with scope & category breakdowns. |
carbon.ledger.balance | Read | Fetch the Scope 1 / 2 / 3 double-entry ledger balance for a period. |
carbon.reports.generate | Write | Generate BRSR / GHG Protocol compliance reports (PDF/CSV/Excel). |
carbon.marketplace.checkout | Write | Create a Dodo Payments checkout session for offset credits. |
rag.documents.search | Read | Semantic search (pgvector) over your uploaded invoice & bill corpus. |
mcp.audit.trail | Read | Retrieve SHA-256 hash chain audit history for an activity. |
check_circleTest the Connection
Once connected, send this prompt to confirm the handshakes:
AI Developer Guide
Deep-dive guide for building autonomous carbon accounting agents on top of the ZeroCarbon MCP. Covers ReAct patterns, prompt chaining, RAG over invoices, and self-healing retries.
Autonomous Reasoning Loop
The ZeroCarbon MCP runs a ReAct-style while loop (capped at 10 iterations) so the agent can dynamically chain tools instead of firing a single-shot answer.
Recommended Prompt Patterns
Copy paste these system prompt blocks into your favourite agent for best performance.
Audit-Style Grounded Answers
You are ZeroCarbon Auditor, a senior carbon accounting assistant. RULES — Non-negotiable output contract: 1. Every emissions number MUST come from a call to the carbon.* MCP tools. 2. Never estimate, never guess — if the data is missing, CALL THE TOOL. 3. Every claim MUST be followed by: - [activity_id: act_xxx] or - [ledger_hash: sha256:xxx] 4. If a Prisma / validation error is returned, read the message, adjust the arguments, and RETRY the same MCP call (self-heal) — do not show errors to the user. 5. Always break totals into Scope 1 / Scope 2 / Scope 3 percentages.
RAG + Invoice Audit
When asked about a bill, invoice, or utility statement: FLOW: 1. ALWAYS call rag.documents.search first — search using the supplier name, the month, and the amount. 2. If documents match → extract quantity (kWh, liters, kg) from the OCR text. 3. Call carbon.activities.submit with the parsed data + idempotency key = SHA256(date + supplier + amount). 4. Return: the original invoice snippet + the calculated kg CO2e + confidence score breakdown. NEVER submit an activity without first searching the corpus when the user references a physical bill. This is the #1 cause of duplicate writes.
Offset Purchase Flow
When the user wants to "offset" or "neutralize" emissions: 1. Call carbon.ledger.balance to get the current NET balance (Scope1/2/3). 2. Confirm the tonnes CO2e with the user explicitly. 3. Call carbon.marketplace.checkout (NEVER create offsets without calling this endpoint — taxes + VAT are computed by Dodo Payments MoR). 4. Return: checkout_url + the OffsetCertificate record that will be issued after payment confirmation. IMPORTANT: Do NOT skip step 2. Offset purchases are billable and the user MUST confirm tonnage before you emit a checkout link.
RAG Pipeline (Invoices → Embeddings → Ledger)
bug_reportAgent Self-Healing — Intercepted Errors
These error classes are never shown to the user — the MCP server catches them and sends them privately back into the LLM context with a RETRY instruction.
| Error Class | Root Cause | Auto-Heal Strategy |
|---|---|---|
Prisma P2002 | Duplicate unique constraint on idempotency_key | Return {duplicate: true} + existing record; agent skips write. |
ZodValidationError | Activity payload failed schema validation | Inject field path + reason; agent rebuilds payload. |
PgVectorIndexError | RAG embedding was not yet indexed | Exponential backoff 500ms → 2s → retry same search. |
DodoRateLimit (429) | Marketplace checkout throttled | Exponential backoff up to 3 retries with jitter. |
ScopeMismatch | Activity category does not match declared scope | Agent corrects the scope field based on GHG Protocol matrix. |
Authentication
Learn how to securely authenticate your API requests using API keys.
Overview
The ZeroCarbon API uses API Keys for authentication. Every API request must include your API key in the Authorization header using the Bearer authentication scheme.
Getting an API Key
Prerequisites
API access requires one of the following:
- Professional Plan (₹14,999/month) + API Add-on Pack (₹999–₹2,999/month)
- Enterprise Plan (₹39,999/month) (includes unlimited API keys)
Note: Trial and Starter plans do not include API access. Upgrade your plan to get started.
Generate an API Key
- Log in to your ZeroCarbon dashboard.
- Navigate to: Settings → Billing → API Keys
- Click Create New API Key.
- Choose either:Test (zc_test_)Live (zc_live_)
- Give the key a descriptive name (e.g., Production API or Development).
- Copy the generated key immediately—it will only be shown once.
Important Security Notice
Your API key is displayed only once during creation. Store it securely using environment variables or a password manager. If you lose the key, you must generate a new one.
Making Authenticated Requests
Include your API key in the Authorization header using the Bearer scheme.
cURL Example
curl https://api.zerocarbon.org.in/v1/company/dashboard \ -H "Authorization: Bearer zc_live_abc123xyz789..." \ -H "Content-Type: application/json"
Node.js / TypeScript
import { ZeroCarbon } from "zerocarbon-nodejs-sdk"; import * as dotenv from "dotenv"; dotenv.config(); const client = new ZeroCarbon({ apiKey: process.env.ZEROCARBON_API_KEY!, baseUrl: "https://api.zerocarbon.org.in/v1", }); // SDK automatically includes the Authorization header const dashboard = await client.dashboard.get();
Python
import os
from dotenv import load_dotenv
from zerocarbon import ZeroCarbon
load_dotenv()
client = ZeroCarbon(
api_key=os.getenv("ZEROCARBON_API_KEY"),
base_url="https://api.zerocarbon.org.in/v1"
)
# SDK automatically includes the Authorization header
dashboard = client.dashboard.get()Raw HTTP Request
const response = await fetch( "https://api.zerocarbon.org.in/v1/company/dashboard", { method: "GET", headers: { Authorization: `Bearer ${process.env.ZEROCARBON_API_KEY}`, "Content-Type": "application/json", }, } ); const data = await response.json();
API Key Types
ZeroCarbon provides two types of API keys for different environments.
Live Keys
Prefix: zc_live_
Use Live keys in production.
- Real data
- Persistent records
- Billing applies
- Production rate limits
Test Keys
Prefix: zc_test_
Use Test keys during development and testing.
- Sandbox environment
- Isolated data
- Resettable database
- No billing
API Add-on Packs (Professional Plan)
Professional Plan users must purchase one of the following API access packs.
| Pack | Access Level | Endpoints | Price |
|---|---|---|---|
Pack 1 | Read-only | GET endpoints only | ₹999/month |
Pack 2POPULAR | Read + Write | GET + POST + PUT | ₹1,999/month |
Pack 3 | Full Access | All endpoints (GET/POST/PUT/DELETE) | ₹2,999/month |
Enterprise Plan includes unlimited API keys with full API access—no additional API packs are required.
Security Best Practices
Store Keys in Environment Variables
Never hardcode API keys in your source code.
# Add this file to .gitignore
ZEROCARBON_API_KEY=zc_live_abc123xyz789...Rotate Keys Regularly
Periodically rotate API keys to improve security.
- Generate a new key.
- Update your application.
- Verify everything works.
- Delete the old key.
This prevents downtime during key rotation.
Use Separate Keys per Environment
Create separate keys for:
This reduces risk and simplifies key rotation.
Restrict Key Permissions
When supported, restrict API keys by:
to reduce exposure in case a key is compromised.
Authentication Errors
If authentication fails, the API returns 401 Unauthorized.
Example Response
{
"success": false,
"error": {
"code": "INVALID_API_KEY",
"message": "The provided API key is invalid or has been revoked",
"status": 401
}
}Common Authentication Errors
| Error Code | Description |
|---|---|
INVALID_API_KEY | API key is malformed or does not exist |
API_KEY_REVOKED | API key has been deleted or revoked |
API_KEY_EXPIRED | API key has expired (if expiration is enabled) |
RATE_LIMIT_EXCEEDED | Too many requests. Wait or upgrade your rate limits. |
API Reference
Complete reference for all ZeroCarbon API endpoints and request formats.
Base URL
https://api.zerocarbon.org.in/v1Endpoints Overview
| Endpoint | Method | Description |
|---|---|---|
/activities | POST | Submit carbon emission activities |
/emissions | GET | Retrieve aggregated emissions |
/reports | POST | Generate compliance reports |
Additional endpoints | Various | Bulk upload, activity management, emission factors |
Submit Activities
Submit one or multiple carbon emission activities.
POST /activitiesRequest Body
interface ActivitySubmission { activity_type: string; // "electricity", "fuel", "travel", etc. scope: "1" | "2" | "3"; quantity: number; unit: string; period: { start: string; // ISO 8601 end: string; }; location: { country: string; state?: string; city?: string; grid_region?: string; }; source?: { type: string; // "manual", "api", "csv" confidence: number; // 0.0 - 1.0 name?: string; reference?: string; }; metadata?: Record<string, any>; }
Example Request
const response = await fetch( "https://api.zerocarbon.org.in/v1/activities", { method: "POST", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ activity_type: "electricity", scope: "2", quantity: 1500, unit: "kWh", period: { start: "2026-02-01", end: "2026-02-28", }, location: { country: "IN", state: "Maharashtra", city: "Mumbai", }, source: { type: "manual", confidence: 1.0, name: "Monthly Utility Bill", }, }), } ); const data = await response.json();
Response
{
"success": true,
"data": {
"activity_id": "act_abc123xyz789",
"emissions_kg_co2e": 1125.50,
"confidence_score": 0.95,
"emission_factor": {
"value": 0.751,
"unit": "kg CO2e/kWh",
"source": "India Central Electricity Authority 2025",
"region": "Western Grid"
},
"created_at": "2026-02-15T10:30:00Z"
},
"meta": {
"timestamp": "2026-02-15T10:30:00Z",
"request_id": "req_xyz789abc123"
}
}Get Emissions
Retrieve aggregated emissions for a specified period.
GET /emissionsQuery Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
start_date | string | ✅ | ISO 8601 start date |
end_date | string | ✅ | ISO 8601 end date |
scope | string | No | Filter by Scope (1, 2, or 3) |
group_by | string | No | day, week, month, year |
activity_type | string | No | Filter by activity type |
Example Request
curl "https://api.zerocarbon.org.in/v1/emissions?start_date=2026-02-01&end_date=2026-02-28&group_by=month" \ -H "Authorization: Bearer YOUR_API_KEY"
Response
{
"success": true,
"data": {
"total_kg_co2e": 45678.90,
"period": {
"start": "2026-02-01",
"end": "2026-02-28"
},
"breakdown": [
{
"scope": "1",
"emissions_kg_co2e": 12345.67,
"percentage": 27.0
},
{
"scope": "2",
"emissions_kg_co2e": 23456.78,
"percentage": 51.3
},
{
"scope": "3",
"emissions_kg_co2e": 9876.45,
"percentage": 21.7
}
],
"by_activity_type": [
{
"activity_type": "electricity",
"emissions_kg_co2e": 20000.00,
"count": 12
},
{
"activity_type": "fuel",
"emissions_kg_co2e": 15000.00,
"count": 8
}
]
}
}Generate Reports
Generate compliance reports in PDF, CSV, Excel, or JSON format.
POST /reportsRequest Body
interface ReportRequest { report_type: "brsr" | "ghg_protocol" | "custom"; period: { start: string; end: string; }; format: "pdf" | "csv" | "excel" | "json"; include: { scope_1?: boolean; scope_2?: boolean; scope_3?: boolean; verification?: boolean; audit_trail?: boolean; }; }
Example Request
const response = await fetch( "https://api.zerocarbon.org.in/v1/reports", { method: "POST", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ report_type: "brsr", period: { start: "2025-04-01", end: "2026-03-31", }, format: "pdf", include: { scope_1: true, scope_2: true, scope_3: true, verification: true, }, }), } ); const data = await response.json();
Additional Endpoints
Additional endpoints available in the API include:
Error Response Format
All API errors follow a consistent structure.
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid request parameters",
"status": 400,
"details": {
"field": "quantity",
"reason": "Must be a positive number"
}
},
"meta": {
"timestamp": "2026-02-15T10:30:00Z",
"request_id": "req_xyz789"
}
}Common Error Codes
| Status | Code | Description |
|---|---|---|
| 400 | BAD_REQUEST | Invalid request parameters |
| 401 | UNAUTHORIZED | Authentication failed |
| 403 | FORBIDDEN | Insufficient permissions |
| 404 | NOT_FOUND | Requested resource not found |
| 429 | RATE_LIMIT_EXCEEDED | Too many requests |
| 500 | INTERNAL_ERROR | Internal server error |
Canonical Activity Model
Single, unbreakable data contract for all carbon activities. Every emission flowing through the ledger conforms to this exact schema — regardless of whether it arrives via CSV, API, ERP integration, IoT telemetry, or drag-and-drop OCR.
Standardized Fields
activity_type · scope · quantity · unit · period · location · source · metadata — 35+ total typed fields.
Full Type Safety
TypeScript interfaces + Python dataclasses are generated from the same Zod source of truth.
Zod Validation
Every field has precise min/max, enum, regex, and temporal checks with detailed developer error messages.
Idempotency Guarantees
SHA-256 hash of (date + supplier + amount) is enforced at write time — duplicates are skipped atomically.
Scope Segregation
Schema-level enums ensure Scope 1/2/3 records never bleed across ledgers at ingestion time.
Temporal Rigor
period.start and period.end are always ISO 8601; overlaps are detected during ledger append.
Source Provenance
Every record carries source.type (meter / api / csv / manual) and source.confidence [0–1].
Extensible Metadata
Record<string, any> metadata bag for custom attributes (fuel_type, vehicle_count, etc.).
The TypeScript Contract
export interface CanonicalActivity { // Generated by the ledger activity_id?: `act_${string}`; idempotency_key?: string; // SHA-256 (unique, enforced) // Tenant linkage (auto-injected by API key) organization_id: `org_${string}`; // Emission identity activity_type: ActivityType; // 8 standard types: electricity | fuel | travel | ... scope: "1" | "2" | "3"; category?: string; // GHG Protocol category label // Consumption quantity: number; // Strictly positive finite unit: Unit; // "kWh" | "liters" | "kg" | "km" | ... // Reporting period (ISO 8601) period: { start: string; end: string }; // Spatial location: { country: string; // ISO 3166-1 alpha-2 state?: string; city?: string; grid_region?: string; facility_id?: `fac_${string}`; }; // Provenance + confidence inputs source: { type: "meter" | "api" | "supplier" | "csv" | "manual" | "estimate"; confidence: number; // 0.0 – 1.0 name?: string; reference?: string; }; // Customer extensibility metadata?: Record<string, JsonValue>; }
Non-Negotiable Idempotency Rule
The server always computes its own idempotency_key and will never trust one sent by the client.
This closes a massive audit trail footgun: two clients submitting the same physical bill from different devices or SDK versions will always collapse to one canonical ledger write and return the same activity_id, never double-counting tonnes CO2e.
Confidence Scoring
5-factor weighted algorithm (0–100%) that quantifies data quality, not quantity. Every activity record returns a confidence score that downstream reports and audit trails reference explicitly.
| Factor | Weight | Grading Ladder (best → worst) |
|---|---|---|
| Source Quality | 25% | Meter95%API90%Supplier80%Manual70%Estimate50% |
| Data Completeness | 25% | Required fields populatedMetadata richness |
| Emission Factor Quality | 20% | Region-specific95%National80%Global defaults60% |
| Temporal Accuracy | 15% | Real-time98%Daily90%Monthly75%Annual55% |
| Methodological Rigor | 15% | Tier 498%Tier 388%Tier 272%Tier 155% |
Overall Confidence Ratings
Response Shape
{
"confidence": {
"overall": 89.7,
"rating": "Good",
"breakdown": {
"source_quality": { "score": 90, "weight": 25 },
"data_completeness": { "score": 95, "weight": 25 },
"emission_factor_qual": { "score": 80, "weight": 20 },
"temporal_accuracy": { "score": 85, "weight": 15 },
"methodological_rigor": { "score": 88, "weight": 15 }
},
"recommendations": [
"Provide sub-monthly meter reads to raise Temporal Accuracy → 95%",
"Switch from national to state-level grid factor for +12% overall"
]
}
}Carbon Ledger (Double-Entry)
Accounting-grade double-entry bookkeeping for emissions. Three independent scope ledgers (Scope 1 / Scope 2 / Scope 3) — every write records the exact before → delta → after balance, append-only, with SHA-256 chain integrity.
Transaction Types
emission_addIncrease gross tonnes on the scope ledger.emission_reduceReduction / avoidance credit on the scope.offset_purchasePost-purchase, pre-retirement offset accrual.offset_retireFinalized retirement → reduces NET balance.Balance Invariant
Every append is atomic, serialisable, and audit-timestamped. Two concurrent ingests on the same scope cannot produce a torn read — Postgres SERIALIZABLE isolation is mandatory on the ledger writer.
Example: Ledger Append (1,500 kWh Office Electricity)
{
"ledger_entry_id": "led_2xJ9FkXq7vmc",
"scope": "2",
"transaction_type": "emission_add",
"activity_id": "act_abc123xyz789",
"period": { "start": "2026-02-01", "end": "2026-02-28" },
"balance_before": 12450.75,
"transaction_amount": 1125.50,
"balance_after": 13576.25,
"unit": "kg CO2e",
"recorded_at": "2026-03-05T09:12:44.231Z",
"integrity": {
"prev_hash": "sha256:0f9a…c31d",
"this_hash": "sha256:b27e…14aa",
"chain_index": 1482
}
}Ingest Telemetry
Observable ingestion pipeline: every write is tracked from raw payload through OCR / validation / emission calc to ledger append. Debug misaligned numbers in seconds instead of hours.
5-Stage Ingestion Pipeline
Per-Activity Telemetry Record
interface IngestTelemetry { ingest_id: `ing_${string}`; activity_id: `act_${string}` | null; // null on failure status: "received" | "validated" | "deduped" | "calculated" | "appended" | "failed"; failure_reason: string | null; // Timings (ms) per stage — feed to your APM durations_ms: { validation: number; dedup: number; calc: number; ledger_append: number; total: number; }; // Input fingerprint for audit reproduction input: { content_hash: string; // SHA-256 of canonical JSON size_bytes: number; origin: "api" | "csv" | "ocr" | "iot" | "mcp-agent"; caller: string; // user_id / api_key_id / "ai-agent:{agent_id}" }; // Chosen factor at calc time (provenance of the number) factor: { factor_id: string; factor_value: number; // e.g. 0.751 kg CO2e / kWh factor_region: string; factor_source: string; // "India CEA 2025" tier: 1 | 2 | 3 | 4; }; }
Ingest Rate Limits
| Plan | Burst (per min) | Sustained (per hour) | Max batch size |
|---|---|---|---|
| Professional + Pack 2 | 250 / min | 10,000 / hr | 100 |
| Professional + Pack 3 | 1,000 / min | 50,000 / hr | 500 |
| Enterprise | Unlimited | Unlimited | 5,000 |
Emission Factors
The ZeroCarbon factor library ships with 18,000+ region-specific factors (2024–2025 data years) and follows a strict, auditable selection precedence. Factors are version-pinned per tenant — new factor releases never silently regrade old reports.
filter_altFactor Selection Precedence (highest → lowest)
Featured Factor Samples (India, 2025)
| Activity / Fuel | Unit | Factor (kg CO₂e) | Region | Source | Tier |
|---|---|---|---|---|---|
| Grid electricity (India) | per kWh | 0.7510 | National | CEA 2024 – MoP | T3 |
| Grid electricity (Western Grid, MH) | per kWh | 0.7284 | State/Disc | India CEA – WRPC 2025 | T2 |
| Diesel (stationary combustion) | per liter | 2.6810 | National | MoEF&CC 2024 EIs | T3 |
| Petrol (mobile, passenger) | per liter | 2.3300 | National | AISI / GM India | T3 |
| Natural Gas (PNG – household) | per Nm³ | 2.1580 | National | PNGRB 2024 | T3 |
| Air travel, economy domestic (India) | per pax-km | 0.1780 | National | DGCA / DEFRA mirror | T3 |
| Municipal solid waste – landfill | per tonne | 435.0 | National | CPCB 2024 guidelines | T3 |
push_pinVersion Pinning & Backfilling
Carbon Activity Model
Understanding the canonical data structure used for submitting carbon emission activities.
Overview
The Carbon Activity Model is the foundational data contract for every emission record submitted to the ZeroCarbon platform.
Regardless of whether emissions originate from electricity, fuel, travel, waste, water, agriculture, or any other source, every activity follows this unified schema.
Supported Activity Types
| Activity Type | Description |
|---|---|
electricity | Grid electricity consumption |
fuel | Fuel combustion (diesel, petrol, natural gas, etc.) |
travel | Transportation and mobility |
water | Water consumption and treatment |
waste | Waste generation and disposal |
spend | Spend-based emission calculations |
refrigerants | Fugitive refrigerant emissions |
agriculture | Agricultural activities |
Carbon Activity Schema
interface CarbonActivity { // Generated by the platform activity_id?: string; // Organization organization_id: string; // Activity activity_type: string; scope: "1" | "2" | "3"; category?: string; // Consumption quantity: number; unit: string; // Reporting Period period: { start: string; // ISO 8601 end: string; }; // Location location: { country: string; state?: string; city?: string; grid_region?: string; facility_id?: string; }; // Data Source source: { type: string; // manual, api, csv, meter confidence: number; // 0.0 - 1.0 name?: string; reference?: string; }; // Optional Metadata metadata?: Record<string, any>; // Managed by the platform created_at?: string; updated_at?: string; }
Example Activities
Electricity
{
"activity_type": "electricity",
"scope": "2",
"quantity": 5000,
"unit": "kWh",
"period": {
"start": "2026-02-01",
"end": "2026-02-28"
},
"location": {
"country": "IN",
"state": "Maharashtra",
"grid_region": "Western"
},
"source": {
"type": "manual",
"confidence": 1.0,
"name": "MSEDCL Bill"
}
}Fuel Combustion
{
"activity_type": "fuel",
"scope": "1",
"category": "stationary_combustion",
"quantity": 500,
"unit": "liters",
"period": {
"start": "2026-02-01",
"end": "2026-02-28"
},
"location": {
"country": "IN",
"state": "Karnataka",
"city": "Bangalore"
},
"source": {
"type": "manual",
"confidence": 0.95,
"name": "Fuel Purchase Records"
},
"metadata": {
"fuel_type": "diesel",
"vehicle_type": "generator"
}
}Scopes & Categories
Understand how the GHG Protocol Corporate Standard classifies greenhouse gas emissions into Scope 1, Scope 2, and Scope 3.
Overview
The GHG Protocol Corporate Standardcategorizes emissions into three scopes based on where they occur across an organization's operations and value chain.
| Scope | Description |
|---|---|
| Scope 1 | Direct emissions from owned or controlled sources |
| Scope 2 | Indirect emissions from purchased electricity, heat, steam, or cooling |
| Scope 3 | All other indirect emissions across the value chain |
Direct Emissions
Emissions generated directly from assets that your organization owns or controls.
Common Categories
Examples
{
"activity_type": "fuel",
"scope": "1",
"category": "mobile_combustion",
"quantity": 1000,
"unit": "liters",
"metadata": {
"fuel_type": "diesel",
"vehicle_count": 10,
"fleet_type": "delivery_vans"
}
}Indirect Energy Emissions
Emissions resulting from the generation of purchased energy consumed by your organization.
Common Categories
Examples
{
"activity_type": "electricity",
"scope": "2",
"quantity": 5000,
"unit": "kWh",
"location": {
"country": "IN",
"state": "Maharashtra"
}
}Value Chain Emissions
All other indirect emissions occurring throughout your upstream and downstream value chain.
| Category | Description |
|---|---|
| 1 | Purchased Goods & Services |
| 2 | Capital Goods |
| 3 | Fuel & Energy Related Activities |
| 4 | Upstream Transportation & Distribution |
| 5 | Waste Generated in Operations |
| 6 | Business Travel |
| 7 | Employee Commuting |
| 8 | Upstream Leased Assets |
| Category | Description |
|---|---|
| 9 | Downstream Transportation & Distribution |
| 10 | Processing of Sold Products |
| 11 | Use of Sold Products |
| 12 | End-of-Life Treatment of Sold Products |
| 13 | Downstream Leased Assets |
| 14 | Franchises |
| 15 | Investments |
{
"activity_type": "travel",
"scope": "3",
"category": "business_travel",
"quantity": 2500,
"unit": "km",
"metadata": {
"mode": "flight",
"class": "economy",
"route": "domestic"
}
}Choosing the Correct Scope
Use the following decision flow when classifying an activity:
Do you own or control the emission source?
✅ Yes → Scope 1
Is it purchased electricity, heat, steam, or cooling?
✅ Yes → Scope 2
Is it any other indirect emission within your value chain?
✅ Yes → Scope 3
Node.js SDK
The official ZeroCarbon Node.js SDK provides a TypeScript-first interface for integrating the ZeroCarbon API into Node.js applications with full type safety and modern async/await support.
Installation
Using npm:
npm install zerocarbon-nodejs-sdk
Using Yarn:
yarn add zerocarbon-nodejs-sdk
Quick Start
Initialize the Client
Create a client using your API key.
import { ZeroCarbon } from "zerocarbon-nodejs-sdk"; const client = new ZeroCarbon({ apiKey: process.env.ZEROCARBON_API_KEY!, });
Submit an Activity
Submit an emission activity for automatic CO₂e calculation.
const result = await client.activities.create({ activity_type: "electricity", scope: "2", quantity: 1500, unit: "kWh", period: { start: "2026-02-01", end: "2026-02-28", }, location: { country: "IN", state: "Maharashtra", }, }); console.log(`Emissions: ${result.emissions_kg_co2e} kg CO₂e`);
Retrieve Emissions
Fetch aggregated emissions for a given time period.
const emissions = await client.emissions.get({ start_date: "2026-02-01", end_date: "2026-02-28", scope: "2", group_by: "month", }); console.log(`Total: ${emissions.total_kg_co2e} kg CO₂e`);
API Methods
client.activities.create(data)Creates a single carbon activity and returns the calculated emissions.
| Parameter | Type | Required |
|---|---|---|
data | ActivitySubmission | ✅ |
ActivityResponseclient.emissions.get(params)Retrieves aggregated emissions data.
start_dateBeginning of reporting periodend_dateEnd of reporting periodscopeOptional scope filtergroup_byday • week • month • yearEmissionsResponseclient.reports.generate(config)Generate compliance or sustainability reports.
ReportResponseTypeScript Support
The SDK ships with complete TypeScript definitions, providing autocomplete, type safety, and request/response interfaces.
import type { ActivitySubmission, EmissionsResponse, ReportConfig, } from "zerocarbon-nodejs-sdk"; const activity: ActivitySubmission = { activity_type: "electricity", scope: "2", quantity: 1500, unit: "kWh", // Full autocomplete and type checking };
Features
Carbon Marketplace (Dodo)
Native Carbon Offset Marketplace built for global compliance. ZeroCarbon acts as the Broker — Dodo Payments is the Merchant of Record (MoR). Taxes, VAT, KYC, invoicing, and localized remittances are handled entirely by Dodo so your ledger stays clean.
Supplies credit inventory, publishes credit vintages and methodologies, emits OffsetCertificate + CarbonCreditRetirement records on the ledger.
Handles every payment, runs global KYC, issues customer invoices, files tax / VAT returns across 190+ jurisdictions, returns webhooks.
Check out via Dodo hosted page. Receive: email receipt + Dodo invoice + ZeroCarbon retirement certificate in your dashboard + Scope 3 ledger credit.
Sample Credit Inventory
| Listing | Methodology | Vintage | Region | Price (₹ / tCO₂e) | Available |
|---|---|---|---|---|---|
| Afforestation – Western Ghats | Verra VCS 4 + CCB | 2024 | IN-MH | ₹ 1,495 | 28,410 t |
| Wind – Gujarat Kutch | Gold Standard VER | 2023 | IN-GJ | ₹ 890 | 51,000 t |
| Solar PV – Rajasthan Bhadla | Verra VCS 4 | 2024 | IN-RJ | ₹ 760 | 1,12,850 t |
| Cookstoves – Odisha LPG swap | Gold Standard 3.0 | 2022 | IN-OR | ₹ 540 | 37,000 t |
| Mangrove Restoration – Sundarbans | Verra VCS 4 + CCB | 2024 | IN-WB | ₹ 2,280 | 9,450 t |
shopping_cart_checkoutThe Checkout Flow
POST /api/v1/marketplace/checkout — Example
const session = await fetch(`https://api.zerocarbon.org.in/api/v1/marketplace/checkout`, { method: "POST", headers: { "Authorization": "Bearer zc_live_…", "Content-Type": "application/json" }, body: JSON.stringify({ items: [ { listing_id: "list_9xAp3QjR6t", // Wind – Gujarat Kutch tonnes: 50, } ], // Either (authenticated user) or (guest checkout) company_id: "org_2x3FkQq…", // return URL after Dodo hosted page completes success_url: "https://app.zerocarbon.org.in/offsets/thanks?order=ord_123", cancel_url: "https://app.zerocarbon.org.in/offsets", // MoR (Dodo) will compute GST/IGST/import VAT from buyer_country + billing_address buyer: { legal_name: "Acme Logistics Pvt. Ltd.", country: "IN", state: "MH", gstin: "27AAACA1234B1Z5", email: "billing@acme.in", } }) }).then(r => r.json()); // Redirect the buyer to: console.log(session.dodo_checkout_url); // → https://pay.dodo.money/session/cs_test_Ab1…Cd9
POST /api/webhooks/dodo-payments — Automated Fulfillment
This endpoint is called by Dodo, signed with your webhook shared secret. On successful payment.succeeded the following ledger side-effects run inside a single transaction:
receipt_longFee Breakdown (per order)
verified_userReporting Artefacts Issued
ZeroCarbon MCP — Platform Overview
Production-Ready
Enterprise carbon accounting, tracking, and compliance platform with advanced analytics, regulatory automation, and a new AI-powered reasoning engine.
publicOverview
ZeroCarbon is a comprehensive carbon management platform designed for enterprises to track, analyze, and reduce their carbon footprint while ensuring compliance with global standards (BRSR, SEC, EU ETS, UK regulations). Built with cutting-edge technology and AI-powered insights.
Key Highlights
Multi-Standard Compliance
BRSR, GHG Protocol, SEC Climate Disclosure, EU ETS
Supply Chain Engagement
Track Scope 3 emissions across your entire value chain
Science-Based Targets
Integrate with SBTi for validated climate commitments
AI MCP Reasoning Engine
Autonomous AI OS with ReAct loops and RAG injection
Enterprise Security
SSO, encryption, and guaranteed idempotency for data protection
Real-time Dashboard
Live carbon tracking with beautiful data visualizations
Carbon Marketplace
Compliant offsets powered by Dodo Payments (MoR)
API-First Design
Comprehensive REST API with SDKs for Python & Node.js
flash_onInfrastructure-Grade API v3
Transform your carbon accounting from a calculator to a full-scale emissions intelligence platform.
verifiedCanonical Activity Model
Single, unbreakable data contract for all carbon activities across your organization:
analyticsConfidence Scoring System
Data quality quantified with a 5-factor weighted algorithm (0-100% scale):
| Factor | Weight | Description |
|---|---|---|
| Source Quality | 25% | Meter (95%) > API (90%) > Supplier (80%) > Manual (70%) > Estimate (50%) |
| Data Completeness | 25% | Required fields populated, metadata richness |
| Emission Factor Quality | 20% | Region-specific > national > global defaults |
| Temporal Accuracy | 15% | Real-time > daily > monthly > annual |
| Methodological Rigor | 15% | GHG Protocol Tier 1-4 classification |
fact_checkAudit Trail & Version Control
Git-like version control for every carbon activity:
pgvector inside Neon Postgres to semantically retrieve uploaded invoices during audits.account_balanceCarbon Ledger (Double-Entry Bookkeeping)
Accounting-grade emission tracking:
- •
emission_add - •
emission_reduce - •
offset_purchase - •
offset_retire
- arrow_backbalance_before
- swap_horiztransaction_amount
- arrow_forwardbalance_after
- Separate ledgers for Scope 1
- Separate ledgers for Scope 2
- Separate ledgers for Scope 3
smart_toyThe ZeroCarbon MCP (AI Operating System)
ZeroCarbon is powered by a Model Context Protocol (MCP) server (POST /api/v1/mcp) that operates as the brain of the platform.
MCP Features
Autonomous ReAct Loop
The AI dynamically chains internal tools together. It can query a database, analyze the response, and call a subsequent tool before returning a final answer (capped at 10 iterations to prevent infinite loops).
High-Performance Parallelization
Complex multi-tool requests are intercepted and executed concurrently using Promise.all(), drastically reducing query latency.
Self-Healing Mechanics
If the AI attempts an invalid database operation (e.g., a Prisma constraint violation), the backend securely intercepts the crash, feeds the raw error log back to the AI, and allows it to autonomously correct its parameters and retry.
Retrieval-Augmented Generation (RAG)
Uses Neon's pgvector to semantically search uploaded invoices and bills.
storefrontCarbon Offset Marketplace (Dodo MoR)
ZeroCarbon features a native Carbon Offset Marketplace built for global compliance.
We utilize Dodo Payments as our MoR to automatically handle localized taxes and VAT across the globe.
POST /api/v1/marketplace/checkout calculates the base credit price + a 3% platform fee, redirecting the user to a compliant checkout session.
Upon successful payment, the POST /api/webhooks/dodo-payments webhook decrements inventory and generates strict OffsetCertificate and CarbonCreditRetirement records. It even supports dynamic guest checkout routing.
rocket_launchAdvanced SDK Features
from zerocarbon import ZeroCarbon, ActivityBuilder
client = ZeroCarbon(api_key="zc_live_...", environment="production")
builder = ActivityBuilder(org_id="your_org")
# Typed activity creation
activity = builder.electricity(
kwh=1500,
period="2026-02",
location={"country": "IN", "state": "MH"},
source={"type": "meter", "confidence": 0.95}
)
# Batch ingestion with automatic retry and idempotency protection
result = client.activities.ingest([activity])
print(f"Confidence: {result['data']['activities'][0]['confidence']['overall']}%")import { ZeroCarbon } from 'zerocarbon-nodejs-sdk'; const client = new ZeroCarbon({ apiKey: 'zc_live_...', retryConfig: { maxRetries: 3, retryDelay: 1000 } }); // Typed builders with offline queue const activity = client.activities.electricity({ kwh: 1500, period: '2026-02', location: { country: 'IN', state: 'MH' } }); const result = await client.activities.ingest({ activities: [activity] });
routeCore API Endpoints
/api/v1/mcpAI Reasoning Gateway (Accepts Base64 fileContent for RAG)/api/v1/marketplace/checkoutCreate Dodo Payments session/api/webhooks/dodo-paymentsWebhook fulfillment endpoint/api/v1/company/authCompany login/v1/activitiesSubmit carbon emission activities/v1/emissionsRetrieve aggregated emissions data/v1/reportsGenerate compliance reportsBuilt for a sustainable future
ZeroCarbon Architecture Context (AI Guide)
Ultra-condensed guide for future AI agents
Serves as a rapid reference map to quickly understand the structure, data models, and logic of the ZeroCarbon project without needing to blindly grep the entire codebase, saving thousands of tokens.
Core Stack
| Layer | Technology | Reference |
|---|---|---|
| Framework | Next.js 15.5.12 (App Router) | — |
| Database | PostgreSQL (via NEON) with Prisma ORM | prisma/schema.prisma |
| Styling | Tailwind CSS | src/app/globals.css |
| Payments/Billing | Dodo Payments SDK | src/app/api/webhooks/dodo-payments |
| AI/LLM | Google Gemini 2.5 | src/lib/ai/gemini.ts |
| Vector DB | pgvector inside Postgres | src/lib/ai/rag.ts |
Key Directories
src/app/Next.js frontend pages and API routes.
src/app/api/v1/mcp/The brain of the application. Contains the AI Operating System (MCP Server).
src/lib/Core backend logic.
src/lib/ai/RAG, MCP Reasoning Loop, Prompts.
src/lib/db/Prisma Client instance.
src/lib/document/OCR and data extraction pipelines (Cloudinary).
src/lib/core/emissions/Emission calculation engines and math formulas.
Database Schema Overview
The database uses prisma/schema.prisma and relies heavily on relational UUID strings (cuid).
CompanyCore TenantThe core tenant. Everything cascades from here. (No email field—emails belong to User).
UserAuthThe authentication model. Linked to a Company.
EmissionRecordLedger HeartThe heart of the ledger. Stores all Scope 1, 2, and 3 calculations. Uses idempotency_key to prevent duplicate writes during automated AI ingests.
DocumentUploadAudit TrailTracks uploaded bills/invoices. Fields like uploaded_by_ai_agent are used for audit trails.
CarbonCreditListingMarketplaceInventory for the Carbon Marketplace.
OffsetCertificate & CarbonCreditRetirementLedgersLedgers generated when a user purchases offsets. Must contain strict attributes like valid_from and total_cost.
The MCP Server (AI Operating System)
src/app/api/v1/mcp/route.tssrc/lib/ai/mcp-reasoning.tsIdempotency & Concurrency
Automated AI actions (like parsing 50 invoices in bulk) rely on Idempotency Keys.
When the AI generates a draft emission record, it computes an idempotency key (usually a hash of date + supplier + amount).
If the exact key exists, the backend skips creation and returns duplicate: true. Do NOT bypass this protection.