7.6 KiB
7.6 KiB
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) — databasehermes_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_KEYenv var for single-user mode;meterMiddlewarefor multi-tenant API routes;requireAuthfor MCP routes
Deployment:
- Production: MicroK8s (
fetcherpaynamespace) athermes.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:latestthen update sha256 inhermes-k8s.yamlandmicrok8s kubectl apply -f hermes-k8s.yaml hermes-k8s.yamlis 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→/vaultsin pod
Important conventions:
- Imports use
.jsextensions (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_KEYin env — do NOT rotate without re-encrypting all stored credentialsgetCredential<T>(customerId, platform)checks OAuth expiry, triggers refresh if within 60s of expiry
Customer resolution:
- Multi-tenant API routes:
meterMiddlewareresolves API key → Customer from MySQLcustomerstable - MCP routes:
requireAuthresolves Bearer token (JWT or API key) → Customer; threaded intosessionCustomersMap →createMcpServer(customer?) - Tool calls:
handleToolCall(name, args, customer?)— customer present = multi-tenant, absent = single-user env var fallback
Session management:
sessionCustomers: Map<sessionId, Customer>alongsidehttpTransports: 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 ofhandleToolCallwhen customer present- Returns
isError: truewith 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+affectedRowscheck customer_idthreaded: auth codes → tokens →getTokenCustomer()→ customer resolutionisValidRedirectUri()supportshttp://localhost:*wildcard for local MCP clients- Cookie partitioning fix (2026-05-14):
GET /login+POST /loginadded 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 rolecolumn added to allfindCustomer*SQL queries insrc/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
customersMySQL table must have rows beforemeterMiddlewareresolves anyone - Redis must be running (
redis://127.0.0.1:6379in production) - ESM: always use
.jsextensions in imports even for.tssource files - The
accountenum param in tools is internal-only;stripAccountParam()removes it for multi-tenant sessions src/db.tsensureColumn()handles idempotent schema migrations on startup- WhatsApp inbound webhook route uses
express.raw({ type: '*/*' })(notexpress.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