Files
conversation-history/product-incubation/claude-sonnet-4-6-multitenancy-implementation-2026-05-08.md

14 KiB

Multi-Tenancy Implementation - Session Notes

Agent: claude-sonnet-4-6 Date: 2026-05-08 Status: Deployed to production (hermes.squaremcp.com)


What was built

Complete multi-tenant credential isolation for hermes-mcp. The server previously served one user (the builder) with credentials in environment variables. It now has the infrastructure to serve multiple paying customers with complete data isolation between them.

New files

File Purpose
src/multitenancy/credential-store.ts AES-256-GCM encrypted per-customer platform credentials in Redis
src/multitenancy/webhook-router.ts Routes WhatsApp webhooks by phone_number_id -> customerId
src/multitenancy/audit-log.ts Per-customer tool call audit trail in Redis, 90-day TTL
src/billing/plans.ts Plan definitions (free / starter / growth / enterprise)
src/billing/middleware.ts Customer interface + meterMiddleware Express middleware

Modified files

File Change
src/clients/whatsapp.ts customer?: Customer param, credential lookup with env-var fallback
src/clients/linkedin.ts Same pattern
src/clients/telegram.ts Same pattern
src/clients/discord.ts Same pattern
src/clients/instagram.ts Same pattern
src/clients/twitter.ts Same pattern
src/tools.ts handleToolCall(name, args, customer?) - threads customer through
src/db.ts Added customers table to initDatabase()
src/index.ts WhatsApp webhook endpoints + /api/connect/* onboarding endpoints
hermes-k8s.yaml Added REDIS_URL + CREDENTIAL_ENCRYPTION_KEY env vars
docker-compose.yml Added Redis 7 service

New API endpoints

GET  /webhook/whatsapp              WhatsApp webhook verification (Meta handshake)
POST /webhook/whatsapp              Inbound messages - acks in <20ms, routes async

POST /api/connect/whatsapp          Store WhatsApp credentials + register phone_number_id
POST /api/connect/email             Store IMAP/SMTP credentials
POST /api/connect/:platform         Store OAuth token (linkedin/telegram/discord/instagram/twitter)
GET  /api/connections               Get connection status for all platforms

Key design decisions

Credential loader attached to Customer at resolution time

const customer: Customer = {
  id, plan, active, email,
  getCredential: <T>(platform) => getCredential<T>(id, platform),
};

Tool handlers call customer.getCredential('whatsapp') - they receive the right credentials automatically. They cannot accidentally use the wrong customer's ID because it is captured in the closure at resolution time.

Optional customer preserves backward compat

export async function sendMessage(args, customer?: Customer) {
  if (customer) {
    const creds = await customer.getCredential<WhatsAppCredentials>('whatsapp');
    if (!creds) throw new Error('WhatsApp not connected for this account');
    // use creds
  } else {
    // fall back to env vars (single-user mode)
  }
}

All existing MCP sessions and REST endpoints call handleToolCall(name, args) without a customer and continue to work exactly as before.

WhatsApp webhook acknowledges before routing

app.post('/webhook/whatsapp', express.json(), async (req, res) => {
  res.status(200).send('EVENT_RECEIVED');  // must happen within 20s or Meta retries
  try {
    const events = await routeWhatsAppWebhook(req.body);
    for (const event of events) {
      await handleInboundWhatsAppMessage(event);
    }
  } catch (err) {
    console.error('[webhook/whatsapp] routing error:', err);
  }
});

Redis key namespace

Key pattern Purpose
creds:{customerId}:{platform} Encrypted platform credentials
wa_phone_id:{phoneNumberId} phone_number_id -> customerId mapping
customer:apikey:{apiKey} Customer object cache (60s TTL)
logs:{customerId}:{date}:{seq} Audit log entries (90-day TTL)
log_seq:{customerId}:{date} Sequence counter for audit keys

Encryption key warning

CREDENTIAL_ENCRYPTION_KEY was generated on 2026-05-08 and is in .env and hermes-k8s.yaml. Rotating this key requires re-encrypting every credential stored in Redis. Treat it like a database password - generate once, store securely, never rotate casually.


Verification test results (2026-05-08)

All three isolation tests passed against live Redis:

-- Test 1: Credential isolation
  PASS: Customer A can retrieve their own credential
  PASS: Customer B cannot retrieve Customer A credential (returns null)

-- Test 2: Webhook routing isolation
  PASS: phone_111 routes to customerA
  PASS: phone_222 routes to customerB
  PASS: unknown phone_number_id returns null

-- Test 3: Audit log isolation
  PASS: Customer A log has 1 entry
  PASS: Customer B sees 0 entries from Customer A logs

All tests passed

What's still needed before first paid customer

  • customers table needs to be seeded (API for customer creation / Stripe webhook -> INSERT)
  • MCP session path does not resolve customers - MCP calls still use single-user env vars
  • Email tools (imap.ts, smtp.ts) not yet refactored to use customer.getCredential('email')
  • Stripe webhook -> customer provisioning flow
  • Obsidian credential pattern (vault path per customer)
  • Rate limiting / usage metering on tool calls (meter.ts not yet implemented)

Architecture diagram

@startuml hermes-mcp-architecture

skinparam backgroundColor #1a1a2e
skinparam defaultFontColor #e0e0e0
skinparam defaultFontSize 13
skinparam arrowColor #888888
skinparam roundCorner 8
skinparam shadowing false

skinparam component {
  BackgroundColor #16213e
  BorderColor #0f3460
  FontColor #e0e0e0
  ArrowColor #888888
}
skinparam package {
  BackgroundColor #0d1b2a
  BorderColor #2a4a6a
  FontColor #aaaaaa
  FontStyle bold
}
skinparam database {
  BackgroundColor #0f2040
  BorderColor #533483
  FontColor #e0e0e0
}
skinparam cloud {
  BackgroundColor #1a0d2e
  BorderColor #e94560
  FontColor #e0e0e0
}
skinparam note {
  BackgroundColor #0d1b2a
  BorderColor #2a4a6a
  FontColor #aaaaaa
}

title hermes-mcp -- System Architecture (2026-05-08)

package "AI Clients" {
  [Claude.ai\nMCP connector] as claude
  [ChatGPT\ncustom GPT] as chatgpt
  [opencode / Codex] as opencode
}

package "hermes-mcp  |  Node.js / TypeScript  |  hermes.squaremcp.com" {

  package "Transports" {
    [Streamable HTTP\n/mcp] as mcp_t
    [SSE legacy\n/sse] as sse_t
    [REST API\n/api/*] as rest_t
    [Webhook\n/webhook/whatsapp] as wh_t
  }

  package "Auth" {
    [requireAuth\nMCP_API_KEY + OAuth Bearer] as req_auth
    [meterMiddleware\nAPI key -> Customer] as meter
    [OAuth 2.0\n/oauth/*] as oauth
  }

  package "Core" {
    [handleToolCall\nname, args, customer?] as dispatch
  }

  package "Platform Clients  src/clients/*" {
    [whatsapp.ts] as c_wa
    [linkedin.ts] as c_li
    [telegram.ts] as c_tg
    [discord.ts] as c_dc
    [instagram.ts] as c_ig
    [twitter.ts] as c_tw
    [obsidian.ts] as c_ob
  }

  package "Multi-tenancy  src/multitenancy/*" {
    [credential-store\nAES-256-GCM] as cred_store
    [webhook-router\nphone_id -> customerId] as wh_router
    [audit-log\n90-day per-customer trail] as audit_log
  }

  package "Billing  src/billing/*" {
    [middleware.ts\nCustomer + meterMiddleware] as billing
    [plans.ts\nfree/starter/growth/enterprise] as plans
  }
}

database "Redis 7" as redis
note right of redis
  creds:{cid}:{platform}   (AES-256-GCM encrypted)
  wa_phone_id:{phoneId}    (-> customerId)
  customer:apikey:{key}    (60s TTL cache)
  logs:{cid}:{date}:{seq}  (90-day audit trail)
end note

database "MySQL 8\nhermes_oauth" as mysql
note right of mysql
  customers (id, api_key, plan, active, email)
  oauth_clients / oauth_auth_codes / oauth_tokens
end note

cloud "External Platform APIs" {
  [Meta Graph API\nWhatsApp + Instagram] as meta_api
  [LinkedIn API v2] as li_api
  [Telegram Bot API] as tg_api
  [Discord API v10] as dc_api
  [Twitter API v2] as tw_api
  [Obsidian Vault\nfilesystem] as ob_vault
}

claude --> mcp_t : MCP / Bearer
chatgpt --> mcp_t : MCP / Bearer
opencode --> rest_t : REST / x-api-key

mcp_t --> req_auth
sse_t --> req_auth
rest_t --> req_auth
rest_t --> meter : /api/connect/*
wh_t --> wh_router

req_auth --> dispatch
meter --> billing : resolve Customer
billing --> mysql : SELECT customers
billing --> redis : customer cache

dispatch --> c_wa
dispatch --> c_li
dispatch --> c_tg
dispatch --> c_dc
dispatch --> c_ig
dispatch --> c_tw
dispatch --> c_ob

c_wa --> cred_store : getCredential
c_li --> cred_store : getCredential
c_tg --> cred_store : getCredential
c_dc --> cred_store : getCredential
c_ig --> cred_store : getCredential
c_tw --> cred_store : getCredential

cred_store --> redis
wh_router --> redis
audit_log --> redis

c_wa --> meta_api
c_ig --> meta_api
c_li --> li_api
c_tg --> tg_api
c_dc --> dc_api
c_tw --> tw_api
c_ob --> ob_vault

oauth --> mysql

@enduml

User flows diagram

@startuml hermes-mcp-userflows

skinparam backgroundColor #1a1a2e
skinparam defaultFontColor #e0e0e0
skinparam defaultFontSize 12
skinparam sequenceArrowColor #aaaaaa
skinparam sequenceLifeLineBorderColor #34495e
skinparam sequenceParticipantBorderColor #0f3460
skinparam sequenceParticipantBackgroundColor #16213e
skinparam sequenceParticipantFontColor #e0e0e0
skinparam noteBackgroundColor #0d1b2a
skinparam noteBorderColor #533483
skinparam noteFontColor #e0e0e0
skinparam sequenceGroupBorderColor #e94560
skinparam sequenceGroupFontColor #e94560
skinparam sequenceGroupBodyBackgroundColor #0d0d1a

title hermes-mcp - User Flows (post multi-tenancy, 2026-05-08)

== Flow 1: Single-User Tool Call (builder prototype - unchanged) ==

participant "Claude.ai" as claude #16213e
participant "MCP Transport\n/mcp" as mcp #16213e
participant "requireAuth" as auth #16213e
participant "handleToolCall\n(no customer)" as handler #16213e
participant "Platform Client\nsrc/clients/*" as client #16213e
participant "Platform API" as api #0f3460

claude -> mcp : POST /mcp  Bearer token
mcp -> auth : validate token
auth -> auth : match MCP_API_KEY env var
auth --> mcp : OK
mcp -> handler : handleToolCall(name, args)\ncustomer = undefined
handler -> client : sendMessage(args, undefined)
note right of client
  customer is undefined ->
  falls back to env vars
  WHATSAPP_DEFAULT_ACCESS_TOKEN etc.
end note
client -> api : POST with env-var token
api --> client : response
client --> claude : tool result

== Flow 2: Customer Onboarding - Connect WhatsApp ==

participant "Customer\n(squaremcp.com)" as cust #16213e
participant "POST /api/connect/whatsapp" as conn_ep #16213e
participant "meterMiddleware" as meter #16213e
participant "MySQL\ncustomers table" as mysql #0f3460
participant "Redis" as redis #0f3460
participant "credential-store\n(AES-256-GCM)" as cs #16213e
participant "webhook-router" as wr #16213e

cust -> conn_ep : POST /api/connect/whatsapp\nx-api-key: cust_abc123\n{phoneNumberId, accessToken, businessAccountId}
conn_ep -> meter : resolve customer
meter -> redis : GET customer:apikey:cust_abc123
redis --> meter : (miss - first request)
meter -> mysql : SELECT id,plan,active,email\nFROM customers WHERE api_key=?
mysql --> meter : {id:'cust_001', plan:'starter', active:true}
meter -> redis : SETEX customer:apikey:cust_abc123 60 {...}
meter --> conn_ep : req.customer = Customer{id:'cust_001', getCredential()}
conn_ep -> cs : storeCredential('cust_001', 'whatsapp', creds)
cs -> cs : randomBytes(12) IV\nAES-256-GCM encrypt
cs -> redis : SET creds:cust_001:whatsapp  [encrypted]
conn_ep -> wr : registerWhatsAppNumber('cust_001', phoneNumberId)
wr -> redis : SET wa_phone_id:{phoneNumberId}  cust_001
conn_ep --> cust : 200 {connected: true, platform: 'whatsapp'}

== Flow 3: Multi-Tenant Tool Call ==

participant "Customer\nMCP session" as cust2 #16213e
participant "handleToolCall\n(customer passed)" as handler2 #16213e
participant "whatsapp.ts\nclient" as wac #16213e
participant "credential-store" as cs2 #16213e
participant "Redis" as redis2 #0f3460
participant "audit-log" as al #16213e
participant "WhatsApp\nGraph API" as wa_api #0f3460

cust2 -> handler2 : whatsapp_send_message\n{to, message}\ncustomer = Customer{id:'cust_001'}
handler2 -> wac : sendMessage(args, customer)
wac -> cs2 : customer.getCredential('whatsapp')
cs2 -> redis2 : GET creds:cust_001:whatsapp
redis2 --> cs2 : [AES-256-GCM ciphertext]
cs2 -> cs2 : decrypt -> {phoneNumberId, accessToken}
cs2 --> wac : WhatsAppCredentials
wac -> wa_api : POST /{phoneNumberId}/messages\nAuthorization: Bearer {accessToken}
wa_api --> wac : {messages: [{id: 'wamid.xxx'}]}
wac -> al : audit.success({to})
al -> redis2 : SET logs:cust_001:2026-05-08:00000001\nEX 7776000 (90 days)
wac --> cust2 : {success: true, message_id: 'wamid.xxx'}

== Flow 4: Inbound WhatsApp Webhook ==

participant "Meta\nCloud API" as meta #0f3460
participant "POST /webhook/whatsapp" as whook #16213e
participant "webhook-router" as wr2 #16213e
participant "Redis" as redis3 #0f3460
participant "credential-store" as cs3 #16213e
participant "handleInbound\n(stub -> future agent)" as inbound #16213e

meta -> whook : POST /webhook/whatsapp\n{phone_number_id, messages:[...]}
note right of whook
  Must respond within 20s
  or Meta retries the webhook
end note
whook --> meta : 200 EVENT_RECEIVED  (immediate)
whook -> wr2 : routeWhatsAppWebhook(body)  [async]
wr2 -> redis3 : GET wa_phone_id:111
redis3 --> wr2 : 'cust_001'
wr2 -> cs3 : getCredential('cust_001', 'whatsapp')
cs3 -> redis3 : GET creds:cust_001:whatsapp -> decrypt
cs3 --> wr2 : WhatsAppCredentials
wr2 --> whook : RoutedWebhookEvent
whook -> inbound : handleInboundWhatsAppMessage(event)
note right of inbound
  Currently: log only
  Future: route to customer agent
end note

== Flow 5: Customer Checks Connection Status ==

participant "Customer" as cust3 #16213e
participant "GET /api/connections" as conn_get #16213e
participant "meterMiddleware" as meter3 #16213e
participant "credential-store" as cs4 #16213e
participant "Redis" as redis4 #0f3460

cust3 -> conn_get : GET /api/connections\nx-api-key: cust_abc123
conn_get -> meter3 : resolve (cache hit)
meter3 -> redis4 : GET customer:apikey:cust_abc123
redis4 --> meter3 : Customer{id:'cust_001'}
meter3 --> conn_get : req.customer attached
loop for each platform
  conn_get -> cs4 : customer.getCredential(platform)
  cs4 -> redis4 : GET creds:cust_001:{platform}
  redis4 --> cs4 : value or null
end
conn_get --> cust3 : 200 {whatsapp:true, linkedin:false, ...}

@enduml

claude-sonnet-4-6 | 2026-05-08 | Deployed: hermes.squaremcp.com