Files

15 KiB

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

SquareMCP — System Architecture

Full architecture reference for AI agents and engineers picking up this project.


System Overview

SquareMCP is a multi-tenant MCP (Model Context Protocol) gateway that lets AI assistants (claude.ai, Codex CLI, opencode, Claude Desktop) control social media, email, and messaging platforms on behalf of authenticated users.

Three public services:

Subdomain Purpose Port
hermes.squaremcp.com MCP API + OAuth server 3456
app.squaremcp.com Customer dashboard SPA 8080
docs.squaremcp.com Developer documentation 80

Infrastructure Diagram

                           Internet
                               │
                     ┌─────────▼─────────┐
                     │   nginx ingress    │
                     │  (MicroK8s addon)  │
                     └─────────┬─────────┘
                               │  TLS termination
                   ┌───────────┼───────────┐
                   │           │           │
         ┌─────────▼──┐  ┌─────▼──────┐  ┌▼────────────┐
         │ hermes-mcp  │  │squaremcp-  │  │squaremcp-   │
         │    pod      │  │  app pod   │  │  docs pod   │
         │  port 3456  │  │  port 8080 │  │  port 80    │
         └──────┬──────┘  └────────────┘  └─────────────┘
                │ hostNetwork: true
     ┌──────────┼──────────┐
     │          │          │
┌────▼───┐ ┌───▼────┐ ┌───▼──────────────────┐
│ MySQL 8│ │Redis 7 │ │ /home/garfield/       │
│  3306  │ │  6379  │ │ obsidian/vaults       │
│(Docker)│ │(Docker)│ │ (mounted at /vaults)  │
└────────┘ └────────┘ └──────────────────────┘

Key infrastructure facts:

  • MicroK8s single-node cluster, fetcherpay namespace
  • hermes-mcp pod uses hostNetwork: true — binds directly to host network on port 3456
  • MySQL and Redis run as standalone Docker containers on the same host (not in K8s)
  • Image registry: localhost:32000 (MicroK8s built-in registry)
  • TLS: cert-manager + Let's Encrypt (letsencrypt-prod ClusterIssuer)
  • Obsidian vault mounted as hostPath volume into the hermes pod

Deployment Pattern

Every code change follows this exact sequence:

# 1. Build
npm run build

# 2. Docker
docker build -t localhost:32000/hermes-mcp:latest .
docker push localhost:32000/hermes-mcp:latest

# 3. Get the new sha256 digest
docker inspect localhost:32000/hermes-mcp:latest \
  --format='{{index .RepoDigests 0}}'
# → localhost:32000/hermes-mcp@sha256:<new-digest>

# 4. Update hermes-k8s.yaml with new digest (NEVER use :latest tag in k8s)
# image: localhost:32000/hermes-mcp@sha256:<new-digest>

# 5. Apply
microk8s kubectl apply -f hermes-k8s.yaml

# 6. Verify
microk8s kubectl rollout status deployment/hermes-mcp -n fetcherpay

Critical: hermes-k8s.yaml is gitignored because it contains plaintext secrets. Never force-add it.


Authentication Architecture

Three auth methods (checked in priority order)

Incoming request
      │
      ├─ x-api-key header = MCP_API_KEY?  → superadmin (global access)
      │
      ├─ x-api-key header (customer key)?  → resolve Customer from MySQL
      │
      ├─ Authorization: Bearer <token>?
      │    ├─ JWT?  → decode, resolve Customer by sub
      │    └─ OAuth token?  → validate in oauth_tokens table
      │
      └─ Cookie: session=<JWT>?  → decode, resolve Customer from MySQL
  • Payload: { sub: customerId, email, plan, role }
  • httpOnly: true, secure: true, sameSite: 'lax', domain: '.squaremcp.com'
  • Valid for 7 days
  • Set by POST /api/auth/login and POST /login (OAuth flow)

OAuth 2.0 + PKCE

Full RFC 6749 + RFC 7636 implementation with Dynamic Client Registration (RFC 7591).

Endpoints:

  • GET /.well-known/oauth-authorization-server — server metadata
  • GET /.well-known/oauth-protected-resource — resource metadata
  • POST /oauth/register — DCR (clients self-register)
  • GET /oauth/authorize — consent page
  • POST /oauth/authorize — approve/deny
  • POST /oauth/token — code exchange
  • POST /oauth/revoke — token revocation

OAuth Login Flow (claude.ai)

This flow applies to any MCP client that uses browser-based OAuth (claude.ai, Cursor, etc).

MCP Client                hermes.squaremcp.com
    │                             │
    ├─ POST /oauth/register ──────►
    │◄─ { client_id, client_secret }
    │
    │  [browser popup opens]
    │
    ├─ GET /oauth/authorize ───────►
    │                    no session cookie?
    │◄─ 302 /login?return_to=<authorize URL>
    │
    ├─ GET /login ────────────────►
    │◄─ HTML login form ───────────
    │
    ├─ POST /login ───────────────►
    │                    verify credentials
    │                    set cookie (FIRST-PARTY on hermes.squaremcp.com)
    │◄─ 302 /oauth/authorize?... ──
    │
    ├─ GET /oauth/authorize ───────►
    │                    session cookie found ✓
    │◄─ consent HTML ──────────────
    │
    ├─ POST /oauth/authorize ──────►
    │                    action=allow
    │◄─ 302 redirect_uri?code=<auth_code>
    │
    ├─ POST /oauth/token ─────────►
    │   code + code_verifier (PKCE)
    │◄─ { access_token, token_type }
    │
    ├─ POST /mcp (Bearer access_token) ►
    │◄─ MCP tools response ────────

Why /login is on hermes.squaremcp.com (not app.squaremcp.com): Browser CHIPS (Cookie Partitioning) means a cookie set when app.squaremcp.com is the top-level site is not visible when hermes.squaremcp.com is the top-level site. The OAuth popup runs on hermes, so the login must also happen on hermes to set a first-party cookie.


Multi-Tenancy Architecture

Credential storage

Redis key: creds:{customerId}:{platform}
Value: AES-256-GCM encrypted JSON
Key: CREDENTIAL_ENCRYPTION_KEY env var

Platforms: whatsapp, email, linkedin, tiktok, facebook,
           instagram, twitter, telegram, discord, snapchat

MCP session lifecycle

POST /mcp (with Bearer token)
    │
    ├─ requireAuth resolves Customer from token
    ├─ sessionId from mcp-session-id header or generated
    ├─ sessionCustomers.set(sessionId, customer)
    ├─ httpTransports.set(sessionId, transport)
    │
    └─ createMcpServer(customer) — MCP server per session
         │
         └─ handleToolCall(name, args, customer)
              ├─ checkLimit(customerId, plan) — abort if over limit
              ├─ customer.getCredential(platform) — decrypt from Redis
              ├─ call platform API
              └─ recordUsage(customerId, platform, action)

Customer resolution

-- customers table (MySQL)
CREATE TABLE customers (
  id           VARCHAR(64) PRIMARY KEY,
  email        VARCHAR(255) UNIQUE NOT NULL,
  password_hash VARCHAR(255),
  api_key      VARCHAR(64) UNIQUE NOT NULL,
  plan         ENUM('free','starter','growth','enterprise') DEFAULT 'free',
  role         ENUM('user','admin') DEFAULT 'user',
  active       BOOLEAN DEFAULT TRUE,
  reset_token  VARCHAR(64),
  reset_expires_at DATETIME,
  created_at   DATETIME DEFAULT CURRENT_TIMESTAMP
);

Platform Clients

51 MCP tools across 11 platforms:

Platform Client file Tools
Email (IMAP/SMTP) src/imap.ts, src/smtp.ts search_messages, read_message, send_email, create_draft, list_folders, get_profile
Obsidian src/clients/obsidian.ts obsidian_search_notes, obsidian_read_note, obsidian_append_to_note, obsidian_update_note, obsidian_sync_status
WhatsApp src/clients/whatsapp.ts whatsapp_send_message, whatsapp_send_template, whatsapp_list_templates, whatsapp_get_message_status
LinkedIn src/clients/linkedin.ts linkedin_get_profile, linkedin_create_post, linkedin_search_connections, linkedin_send_message, linkedin_upload_video
TikTok src/clients/tiktok.ts tiktok_get_profile, tiktok_get_creator_info, tiktok_create_video, tiktok_get_video_status
Facebook src/clients/facebook.ts facebook_get_page, facebook_get_posts, facebook_create_post, facebook_create_photo_post, facebook_create_video_post
Instagram src/clients/instagram.ts instagram_get_profile, instagram_get_media, instagram_create_post, instagram_create_reel
Twitter/X src/clients/twitter.ts twitter_get_user_profile, twitter_get_user_tweets, twitter_search_tweets, twitter_create_tweet, twitter_upload_video
Telegram src/clients/telegram.ts telegram_get_me, telegram_send_message, telegram_send_photo, telegram_get_updates, telegram_get_chat
Discord src/clients/discord.ts discord_get_me, discord_get_guilds, discord_get_channels, discord_send_message, discord_get_messages
Snapchat src/clients/snapchat.ts snapchat_get_me, snapchat_get_ad_accounts, snapchat_create_snap

Directory Structure

hermes-mcp/
├── src/
│   ├── index.ts              — Express app, all routes, MCP session mgmt
│   ├── tools.ts              — handleToolCall(), tools[] registry
│   ├── oauth.ts              — OAuth 2.0 + PKCE implementation
│   ├── auth.ts               — bcrypt, JWT, customer lookups
│   ├── db.ts                 — MySQL pool, ensureColumn() migration
│   ├── redis.ts              — shared Redis singleton
│   ├── imap.ts               — IMAP multi-account reader
│   ├── smtp.ts               — SMTP multi-account sender
│   ├── manifest.ts           — OpenAPI schema generation
│   ├── billing/
│   │   ├── plans.ts          — plan definitions + limits
│   │   ├── middleware.ts     — Customer interface, meterMiddleware
│   │   ├── usage.ts          — recordUsage(), checkLimit()
│   │   ├── invoices.ts       — invoice generation
│   │   └── cron.ts           — monthly invoice cron (Redis lock)
│   ├── multitenancy/
│   │   ├── credential-store.ts  — AES-256-GCM Redis creds
│   │   ├── token-refresh.ts     — OAuth token refresh
│   │   ├── platform-health.ts   — health checks + Redis cache
│   │   ├── webhook-router.ts    — WhatsApp inbound routing
│   │   └── audit-log.ts         — per-customer tool call audit
│   ├── webhooks/
│   │   └── delivery.ts          — outbound HMAC webhook + retry + DLQ
│   └── clients/
│       ├── discord.ts
│       ├── facebook.ts
│       ├── instagram.ts
│       ├── linkedin.ts
│       ├── obsidian.ts
│       ├── snapchat.ts
│       ├── telegram.ts
│       ├── tiktok.ts
│       ├── twitter.ts
│       └── whatsapp.ts
├── product/
│   └── app/                  — SaaS dashboard SPA
│       ├── index.html
│       ├── app.js
│       ├── styles.css
│       ├── Dockerfile
│       └── app-k8s.yaml
├── docs/                     — Developer docs site
│   ├── index.html
│   ├── getting-started.html
│   ├── platforms.html
│   ├── agent-tutorial.html
│   ├── styles.css
│   ├── Dockerfile
│   └── docs-k8s.yaml
├── hermes-k8s.yaml           — gitignored (contains plaintext secrets)
├── ARCHITECTURE.md           — this document (repo copy)
└── DEPLOY.md                 — deployment runbook

Data Flow: Tool Call

AI assistant
    │
    ├─ POST https://hermes.squaremcp.com/mcp
    │   Authorization: Bearer <access_token>
    │   { method: "tools/call", params: { name: "linkedin_create_post", arguments: {...} } }
    │
    └─► requireAuth
          │  validates token → resolves customerId
          │
          └─► createMcpServer(customer)
                │
                └─► handleToolCall("linkedin_create_post", args, customer)
                      │
                      ├─ checkLimit(customerId, "starter") → OK
                      │
                      ├─ customer.getCredential("linkedin")
                      │    └─ Redis GET creds:{customerId}:linkedin
                      │         → AES-256-GCM decrypt → { accessToken, ... }
                      │
                      ├─ linkedin.createPost(accessToken, content)
                      │    └─ POST https://api.linkedin.com/v2/ugcPosts
                      │
                      ├─ recordUsage(customerId, "linkedin", "linkedin_create_post")
                      │    └─ INSERT INTO usage_logs
                      │
                      └─ return { content: [{ type: "text", text: "Posted! ID: ..." }] }

Plan Limits

Plan Monthly tool calls Price
free 100 $0
starter 1,000 TBD
growth 10,000 TBD
enterprise unlimited (-1) TBD

First signup is auto-promoted to admin + enterprise.


Key Invariants

  1. ESM imports use .js extensions even for .ts source files — TypeScript moduleResolution: bundler
  2. CREDENTIAL_ENCRYPTION_KEY must not be rotated without re-encrypting all Redis credentials
  3. hermes-k8s.yaml is gitignored — never force-add; never paste its contents in chat
  4. account param in tools is internal — stripAccountParam() removes it before tool args are shown to MCP clients in multi-tenant sessions
  5. WhatsApp inbound webhook uses express.raw({ type: '*/*' }) for raw body HMAC verification — do not switch to express.json() on that route
  6. Cookie partitioning (CHIPS) — always set cookies in the first-party context of the domain where they'll be read; the /login route on hermes.squaremcp.com exists specifically for this reason