agentleFS
MattSezginMattSezgin/unofficial-smartlead-cli/CLAUDE.md

unofficial-smartlead-cli

CLAUDE.md8 starsChanged 6 months agoMITView on GitHub

This file is the comprehensive context for AI agents (Claude, Cursor, Continue) working in this repo. If you're an AI agent: read this first. If you're a human: see README.md instead. A complete CLI and MCP server for the Smartlead cold email platform. Unofficial — built by a community maintainer, not Smartlead themselves. Goal: expose Smartlead's full API surface (public + reverse-engineered internal) through: Both are produced from the same TypeScript codebase. SmartleadClient is a single class with: Each src/cli/commands/<family>.ts…

  • Reads credentials
  • Installs packages

The file

We split this CLAUDE.md into the rules it gives an agent

7 rules. About 0 are common, 3 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Only SMARTLEAD_API_KEY env var is read by the MCP server.

    line 82
  2. Distinctive:

    If you (the AI) are working in this repo and the user describes a problem matching one of these, invoke the relevant skill instead of …

    line 186
  3. Distinctive:

    Match existing module layout: Don't introduce new top-level dirs without discussion.

    line 234
  4. Distinctive:

    Match existing command registration pattern: when adding commands.

    line 235
  5. Very specific:

    No client-specific data, real campaign IDs, or PII in code: Use generic placeholders (123456, acme.com, john@example.com).

    line 238
  6. Very specific:

    Every command supports -o table|json|csv.

    line 256
  7. Very specific:

    Keep this file focused on how to navigate this repo as an AI agent.

    line 287

≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md — AI agent context for unofficial-smartlead-cli

This file is the comprehensive context for AI agents (Claude, Cursor, Continue) working in this repo. If you're an AI agent: read this first. If you're a human: see README.md instead.


What this project is

A complete CLI and MCP server for the Smartlead cold email platform. Unofficial — built by a community maintainer, not Smartlead themselves. Goal: expose Smartlead's full API surface (public + reverse-engineered internal) through:

  1. A smartlead shell binary (270+ commands across 23 families)
  2. A smartlead-mcp server (66 curated tools for Claude Code / Cursor / Continue / Zed)

Both are produced from the same TypeScript codebase.


Architecture

src/
├── index.ts                          # MCP server entry — stdio transport, 66 tools
├── client.ts                         # SmartleadClient — multi-host HTTP + GraphQL + rate limiter
├── types/
│   └── smartlead.ts                  # Shared TS types (Lead, Campaign, Sequence, Analytics)
├── cli/
│   ├── index.ts                      # CLI entry — Commander program, registers 23 command modules
│   ├── utils/
│   │   ├── config.ts                 # loadConfig() — env + ~/.smartleadrc resolution
│   │   ├── output.ts                 # formatOutput() table|json|csv
│   │   └── safety.ts                 # confirmAction(), CATEGORY constants
│   └── commands/                     # 23 command modules — one per command family
│       └── [accounts, agents, analytics, audit, blocklist, campaigns, clients,
│            crm, delivery, graphql, inbox, integrations, leads, linkedin, lists,
│            plans, prospect, settings, tags, team, utilities, wallet, webhooks].ts
└── tools/                            # API tool implementations (Zod schemas + impl)
    └── [shared by both CLI and MCP server]

Entry points

BinarySourcePurpose
smartleadsrc/cli/index.ts → dist/cli/index.jsCLI (declared in package.json bin)
smartlead-mcpsrc/index.ts → dist/index.jsMCP server (stdio)

HTTP client (src/client.ts)

SmartleadClient is a single class with:

  • Multi-host routing via SmartleadService enum and SERVICE_CONFIG map (10 hosts).
  • Three auth modes:
    • api-key — URL param ?api_key=<KEY> (public REST, default)
    • jwt — Authorization: Bearer <JWT> (internal endpoints)
    • jwt-with-sl-key — Bearer + x-sl-api-key header (agents-api host only)
  • Rate limiter: token bucket, maxTokens=60, refill every 60s. Stays well under Smartlead's undocumented ~200-GET wall (see docs/learnings/rate-limits.md).
  • Retries: 3 attempts, exponential backoff. Handles HTTP 429 with Retry-After.

Command registration pattern

Each src/cli/commands/<family>.ts exports registerXxxCommands(program, client, globalOpts):

export function registerCampaignCommands(program, client, globalOpts) {
  const campaigns = program.command('campaigns').description('...');
  campaigns.command('list').action(async () => { ... });
  // ... more subcommands
}

src/cli/index.ts imports and calls all 23 register functions.

MCP tool registration

src/index.ts manually wires a curated subset (66 of 272) into the MCP server. Each tool:

  1. Zod schema exported from src/tools/*.ts
  2. zodToJsonSchema() conversion at module load
  3. Entry in toolDefinitions[] with name + description
  4. Handler in toolHandlers{} that parses input and calls the impl

Only SMARTLEAD_API_KEY env var is read by the MCP server. MCP doesn't use JWT/sl_api_key.

Config resolution (src/cli/utils/config.ts)

Order (first match wins):

  1. Env vars: SMARTLEAD_API_KEY, SMARTLEAD_JWT (or SMARTLEAD_JWT_TOKEN), SMARTLEAD_SL_API_KEY (falls back to SMARTLEAD_API_KEY)
  2. ~/.smartleadrc or ~/.smartleadrc.json, or same in $CWD

Aliased keys: api_key|apiKey, sl_api_key|slApiKey, default_client|defaultClient, confirm_bulk|confirmBulk.


Commands overview

Total: 272 invokable commands across 23 families, plus 1 top-level auth command.

FamilySubcommandsAuthNotes
accounts17mixedEmail-account CRUD, warmup, tags
agents7jwt+slkagents-api host
analytics27apiCampaign/lead/mailbox analytics
audit6jwtAudit logs
blocklist4apiGlobal block list
campaigns23apiCore campaign CRUD + lifecycle
clients7apiMulti-tenant client records
crm9jwtCRM features (mostly internal)
delivery36api(SD)Smart Delivery host
graphql5jwt(graphql)Hasura GraphQL
inbox27mixedMaster Inbox
integrations13apiWebhooks, third-party connectors
leads12apiLead CRUD, custom fields
linkedin11apiLinkedIn integration
lists10apiLead lists
plans6apiSubscription / billing
prospect28api(SP)Smart Prospect (email finder)
settings10apiCampaign settings
tags12apiEmail-account tags
team10apiTeam / users
utilities2apiMisc helpers
wallet11jwt(wallet)Wallet host
webhooks10apiPer-campaign webhooks

Global options on every command:

  • -o, --output <format> — table (default), json, csv
  • --dry-run — preview without executing
  • -y, --yes — skip confirmation prompts
  • -h, --help — command-specific help

For full reference, see docs/api-coverage.md and docs/command-auth-audit.md.


Auth modes — when to use which

  1. api_key — default for public REST. Most stable. Use whenever the endpoint accepts it.
  2. JWT — for internal endpoints (bulk update, GraphQL, agents-api, some CRM). JWTs grant broader privileges than api_key.
  3. JWT + sl_api_key — agents-api host only. Three headers in the request.

Smartlead's official docs are wrong about auth mode for several endpoints. Always probe before relying on the docs. See docs/learnings/jwt-vs-apikey-map.md for the verified map.

Getting a JWT

Open https://app.smartlead.ai, sign in, then in browser DevTools:

JSON.parse(atob(localStorage.smartlead)).auth.token       // JWT
JSON.parse(atob(localStorage.smartlead)).applicant.user.api_key  // sl_api_key

⚠️ JWTs expire. Re-extract when commands start returning 401.


Built-in Claude Code skills

.claude/skills/ ships with 11 action-oriented slash commands. Each is a SKILL.md with frontmatter describing when to invoke it and step-by-step instructions for the AI to follow.

Setup

Slash commandWhat it doesWhen to invoke
/smartlead-onboardingFirst-time API key + JWT setup wizardUser has no API key configured

Campaign lifecycle

Slash commandWhat it doesWhen to invoke
/create-campaignEnd-to-end wizard (name → schedule → settings → sequences → mailboxes → leads)User wants to start a new campaign
/clone-campaignDuplicate via 6-step API recipe (no native CLI clone command)User wants V2/V3 of a winning campaign
/launch-campaignPre-flight audit + startCampaign is built and user wants to go live
/upload-leadsCSV upload with dedup + 100-batch paginationUser has a CSV to push

Mailbox infrastructure

Slash commandWhat it doesWhen to invoke
/warmup-mailboxesApply golden warmup config to N mailboxesNew mailboxes need warmup, or under-performing pool
/audit-mailbox-configVerify mailbox settings against golden standardUser asks to audit/validate settings

Diagnose & report

Slash commandWhat it doesWhen to invoke
/check-deliverabilityFull health audit — bounce, ESP routing, warmup"Bounces are high" / "feels off"
/spam-testSmart Delivery spam test — DKIM/SPF/DMARC + inbox %Before launching, or sudden reply drop
/weekly-reportPerformance digest across all campaignsWeekly recap, end-of-week wrap-up
/compare-campaignsHead-to-head A/B comparison with significance check"Which version is winning?"

If you (the AI) are working in this repo and the user describes a problem matching one of these, invoke the relevant skill instead of writing one-off code.


Operating principles for AI agents

Before making API calls

  1. Check auth is configured — smartlead auth reports current state. If missing, invoke /smartlead-onboarding.
  2. Prefer api_key over JWT where both work — more stable, doesn't expire.
  3. Use --dry-run to preview destructive operations (POST/PATCH/DELETE) before executing.
  4. Verify flag names with --help before running. Skills in .claude/skills/ describe workflows correctly but exact flag syntax may differ — always check smartlead <command> <subcommand> --help first if a command errors with "unknown option".

Credential handling

You can and should explain anything to the user — these are transparency-friendly guidelines, not gag rules:

  • Never hardcode secrets in code, scripts, or commit-tracked files. Credentials belong in ~/.smartleadrc (chmod 600), in .env files (gitignored), or in env vars (SMARTLEAD_API_KEY, SMARTLEAD_JWT_TOKEN, SMARTLEAD_SL_API_KEY).
  • Don't paste tokens into chat, logs, screenshots, or PR descriptions. Show the user echo "✓ saved" rather than the literal token value — same as how git config works.
  • Treat JWTs like passwords. They grant broader privileges than the api_key. Recommend rotation if ever exposed (sign out of Smartlead → re-run /smartlead-onboarding).
  • If the user asks how something works, tell them. Explain the decode flow, the config file location, the auth modes, anything. The guidelines above are about handling — not hiding.

When something fails

SymptomLikely causeFix
Invalid numeric literal at line 1, column 8Rate-limited, response is HTMLSleep 30s, use paginated endpoints, or throttle (see docs/learnings/rate-limits.md)
HTTP 401 on JWT endpointJWT expiredRe-extract from browser localStorage
HTTP 400 with "invalid track_settings value"Field name mismatch GET vs POSTTranslate DONT_EMAIL_OPEN → DONT_TRACK_EMAIL_OPEN (see settings-api-quirks.md)
Mailbox client_id: null after provisioningSmartlead client record created after mailboxBackfill via /bulk-config-mailboxes
Big Tech recipients bouncing 28%Email-finder catch-all + AI ESP matching routing to OutlookDisable enable_ai_esp_matching, drop @google.com from list (see esp-matching-analysis.md)

Knowledge docs to consult

The docs/learnings/ directory contains deep-dives on every non-obvious behavior. When debugging or planning a non-trivial workflow:

  • bulk-update-endpoint.md — the JWT-only bulk update flow
  • jwt-vs-apikey-map.md — verified auth map (docs are wrong)
  • rate-limits.md — the ~200-GET HTML wall
  • esp-matching-analysis.md — why AI ESP matching hurts Google recipients
  • mailbox-warmup-best-practices.md — verified production warmup config
  • warmup-key-id-format.md — UI rules vs. API tolerance
  • settings-api-quirks.md — POST/GET shape mismatches
  • campaign-cloning-runbook.md — 6-step clone recipe

Code conventions

  • TypeScript strict mode on. No any without a comment explaining why.
  • Match existing module layout. Don't introduce new top-level dirs without discussion.
  • Match existing command registration pattern when adding commands.
  • Add Zod schemas for any new MCP tool in src/tools/<family>.ts.
  • Commit messages: imperative, lowercase, ≤1 line ideal.
  • No client-specific data, real campaign IDs, or PII in code. Use generic placeholders (123456, acme.com, john@example.com).

Build commands

npm install          # First-time setup
npm run build        # tsc → dist/
npm run typecheck    # tsc --noEmit
npm run dev          # tsx watch on MCP server entry
npm run cli          # tsx on CLI entry (no build needed)

Project conventions

Output formats

Every command supports -o table|json|csv. Default is table for human readability. When piping to other tools, use --output json.

Pagination

Smartlead's /leads endpoint caps limit at 100. The CLI handles pagination automatically when listing >100 leads. If you're hitting the API directly, watch the offset.

Idempotency

POST endpoints to Smartlead are NOT generally idempotent. Re-running campaigns create creates a duplicate. Always check existence first or use --idempotency-key where the CLI supports it.

Destructive operation safety

Commands that POST/PUT/PATCH/DELETE prompt for confirmation by default. Pass -y/--yes to skip (e.g., in automation), or --dry-run to preview the request without sending.


What this project is NOT

  • Not an official Smartlead product. Smartlead may change or remove internal endpoints at any time.
  • Not a deliverability oracle. The learnings docs reflect observations, not guarantees. Test in your own environment.
  • Not a substitute for Smartlead's UI for everything. Some workflows are still easier in the dashboard (visual sequence editor, lead-detail view).

When to update this file

  • New command family added → update the families table
  • New skill added → update the skills table
  • New auth mode discovered → update the auth section
  • New gotcha discovered → consider whether it belongs in docs/learnings/ instead

Keep this file focused on how to navigate this repo as an AI agent. Deep technical details go in docs/learnings/.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.