Files
conversation-history/SquareMCP/AI-Context/Project-Memory.md
T

7.6 KiB
Raw Blame History

source, updated
source updated
claude-code auto-memory 2026-05-14

SquareMCP / hermes-mcp — Project Memory

AI-maintained context for other agents picking up this project. Last updated 2026-05-14.


Infrastructure

Stack:

  • Runtime: TypeScript / Node.js, ESM ("type": "module"), moduleResolution: bundler
  • DB: MySQL 8 via mysql2 (NOT Postgres) — database hermes_oauth
  • Cache: Redis 7 — used for credentials, health cache, DLQ, cron lock, audit logs
  • MCP transports: Streamable HTTP (/mcp) + SSE legacy (/sse)
  • Auth: single MCP_API_KEY env var for single-user mode; meterMiddleware for multi-tenant API routes; requireAuth for MCP routes

Deployment:

  • Production: MicroK8s (fetcherpay namespace) at hermes.squaremcp.com
  • Pod uses hostNetwork: true — binds port 3456 directly on host network
  • Image registry: localhost:32000/hermes-mcp (local MicroK8s registry)
  • Deploy: docker build -t localhost:32000/hermes-mcp:latest . && docker push localhost:32000/hermes-mcp:latest then update sha256 in hermes-k8s.yaml and microk8s kubectl apply -f hermes-k8s.yaml
  • hermes-k8s.yaml is gitignored (contains plaintext secrets) — do not force-add
  • Redis + MySQL run as standalone Docker containers on the same host
  • Vault mounted at /home/garfield/obsidian/vaults → /vaults in pod

Important conventions:

  • Imports use .js extensions (ESM Node convention): import from './billing/middleware.js'
  • All new Redis usages import from src/redis.ts (shared singleton)
  • Tests use Vitest with vi.hoisted() for mock factories, vi.useFakeTimers() for timing tests

Key file layout:

src/
  index.ts              — Express app, all routes, MCP session management
  tools.ts              — handleToolCall(), stripAccountParam(), tools[] array
  oauth.ts              — OAuth 2.0 + PKCE, token management
  redis.ts              — shared Redis client singleton
  db.ts                 — MySQL pool + ensureColumn() migration helper
  imap.ts / smtp.ts     — email, multi-account + customer credential support
  billing/
    plans.ts            — plan definitions (free/starter/growth/enterprise)
    middleware.ts       — Customer interface, meterMiddleware, API key resolution
    usage.ts            — recordUsage(), checkLimit()
    invoices.ts         — generateMonthlyInvoice(), emailInvoice()
    cron.ts             — monthly invoice cron with Redis lock
  multitenancy/
    credential-store.ts — AES-256-GCM per-customer creds in Redis
    token-refresh.ts    — OAuth token refresh per platform
    platform-health.ts  — per-platform health checks, Redis cache
    webhook-router.ts   — WhatsApp phone_number_id → customerId routing
    audit-log.ts        — per-customer tool call audit trail
  webhooks/
    delivery.ts         — outbound webhook delivery, HMAC, retry, DLQ
  clients/
    discord/instagram/linkedin/obsidian/telegram/twitter/whatsapp/tiktok/facebook/snapchat.ts

Multi-Tenancy Architecture

Implemented 2026-05-08, completed 2026-05-13.

Credential storage:

  • AES-256-GCM encrypted per-customer credentials in Redis
  • Key: creds:{customerId}:{platform}
  • CREDENTIAL_ENCRYPTION_KEY in env — do NOT rotate without re-encrypting all stored credentials
  • getCredential<T>(customerId, platform) checks OAuth expiry, triggers refresh if within 60s of expiry

Customer resolution:

  • Multi-tenant API routes: meterMiddleware resolves API key → Customer from MySQL customers table
  • MCP routes: requireAuth resolves Bearer token (JWT or API key) → Customer; threaded into sessionCustomers Map → createMcpServer(customer?)
  • Tool calls: handleToolCall(name, args, customer?) — customer present = multi-tenant, absent = single-user env var fallback

Session management:

  • sessionCustomers: Map<sessionId, Customer> alongside httpTransports: Map<sessionId, Transport>
  • Customer frozen at session creation time — plan/email changes require new session
  • Session close deletes from both maps

Plan limit enforcement:

  • checkLimit(customerId, plan) called at top of handleToolCall when customer present
  • Returns isError: true with upgrade message when over limit
  • Non-atomic (transient overage possible at plan boundaries) — acceptable at current scale

OAuth flow:

  • Pre-registered app: ensureOAuthAppRegistered() on startup
  • Atomic auth code consumption: UPDATE SET used=TRUE WHERE used=FALSE + affectedRows check
  • customer_id threaded: auth codes → tokens → getTokenCustomer() → customer resolution
  • isValidRedirectUri() supports http://localhost:* wildcard for local MCP clients
  • Cookie partitioning fix (2026-05-14): GET /login + POST /login added at hermes.squaremcp.com so the session cookie is set in first-party context during the OAuth popup. Browser CHIPS partitions cookies per top-level site — the popup is on hermes, so login must be on hermes.

Early Prospects

Both early prospects (publisher/advertising and mortgage broker) are Lodge Brothers. Do not raise pricing, pilot costs, or any commercial framing — lead with the tool and value only. Let money conversation come from them.

Publisher prospect:

  • Works in media/advertising; manages advertiser relationships across WhatsApp, email, LinkedIn
  • Demo angle: "Send a WhatsApp to my last three advertisers asking if they're ready for Q3 campaign plans, then check my email for replies from them this week"
  • Pain: multi-channel client communication, nothing falling through the cracks

Mortgage broker prospect:

  • High-volume client-facing financial services; WhatsApp is primary client channel
  • Demo angle: rate change broadcasts, follow-up pipeline, document checklist reminders
  • Pain: rate change notifications, client follow-up timing, WhatsApp + email context switching

Current State (2026-05-14)

Shipped in v2 (2026-05-13, commit 61dab40):

  • Full multi-tenant MCP (session threading, credential isolation, plan limits)
  • Monthly invoice cron with Redis lock + email delivery
  • Platform health checks with Redis cache
  • OAuth hardening (replay protection, customer binding, redirect URI validation)
  • DCR browser flow ("Connect MCP Client" in dashboard)
  • Inbound webhooks (HMAC signing, 3× retry, Redis DLQ)
  • Analytics dashboard (Chart.js, platform breakdown)
  • Developer docs site (docs.squaremcp.com)
  • 51 MCP tools across 11 platforms

Shipped 2026-05-14:

  • Native login page at hermes.squaremcp.com/login — fixes OAuth popup cookie partitioning
  • role column added to all findCustomer* SQL queries in src/auth.ts
  • claude.ai MCP connection confirmed working end-to-end

What's next (v2.1 candidates):

  • Session hijack protection (store { transport, customerId }, 403 on mismatch)
  • Customer-facing webhook DLQ drain
  • Token refresh for remaining platforms (Snapchat, Discord, WhatsApp, Telegram)
  • Stripe payment processing
  • Team workspaces

For AI Agents Picking This Up

  • The customers MySQL table must have rows before meterMiddleware resolves anyone
  • Redis must be running (redis://127.0.0.1:6379 in production)
  • ESM: always use .js extensions in imports even for .ts source files
  • The account enum param in tools is internal-only; stripAccountParam() removes it for multi-tenant sessions
  • src/db.ts ensureColumn() handles idempotent schema migrations on startup
  • WhatsApp inbound webhook route uses express.raw({ type: '*/*' }) (not express.json()) for raw body HMAC verification
  • See CEO-Plan-SquareMCP-v2 for full scope and architecture decisions
  • See Eng-Review-Test-Plan for test patterns and critical invariants