Sync vault notes: April-November 2026 sessions, projects, and architecture
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fe4fe656be
commit
994c7ae577
379 files changed
+55216
-107
No files matched your search
@@ -0,0 +1,73 @@
|
||||
# Kimi Handoff — Communications docs + ChatGPT picker (needs deploy)
|
||||
|
||||
**Date:** 2026-06-16
|
||||
**Session author:** Claude (Sonnet 4.6)
|
||||
**Status:** Committed + pushed to `main`. **NOT deployed** — static sites need rebuild + redeploy.
|
||||
|
||||
---
|
||||
|
||||
## What was done
|
||||
|
||||
1. **Diagnosed and fixed `invalid_client` error on the "hermes-all-in" ChatGPT GPT.**
|
||||
- Root cause: the `oauth_clients` MySQL table was wiped during today's earlier deploy session (MySQL container restart). The dynamically-registered (DCR) client_id that GPT was using no longer existed server-side.
|
||||
- Verified `/oauth/register` (DCR) and `/oauth/authorize` still work correctly end-to-end (registered a throwaway test client, confirmed it returned `302` to `/login` rather than `invalid_client`, then deleted the test row).
|
||||
- **Fix applied by user:** disconnect/reconnect the "hermes-all-in" connector in ChatGPT so it re-runs DCR and gets a fresh client_id. **Not independently re-verified after reconnect — worth a quick check that it's working now.**
|
||||
|
||||
2. **Found and fixed a documentation gap for the newly-published Communications GPT** (`https://chatgpt.com/g/g-6a0f35429e8c81918e8caedbb8b2e4c5-communications-manager`):
|
||||
- `docs/` (squaremcp-docs site) had a full dedicated page for Living Brief but nothing for Communications.
|
||||
- `product/app/app.js` (squaremcp-app dashboard) — the "Connect AI Client → ChatGPT" picker only ever offered the old unscoped `/openapi.json`, never the scoped specs that now exist (`/openapi-communications.json`, `/openapi-living-brief.json`, etc.) and never linked the two already-published GPTs directly.
|
||||
- `product/site/privacy.html` / `terms.html` — still don't have language specific to Communications data handling (profile data, draft content, connected social accounts). **Not fixed in this session — still open**, was flagged on the original Communications OAuth handoff checklist too.
|
||||
|
||||
3. **Changes made (committed, not deployed):**
|
||||
- New file `docs/communications.html` — guide page mirroring `living-brief.html` (get-started steps, capabilities, example prompts, privacy/control notes), linking to the live Communications GPT URL above.
|
||||
- `docs/index.html`, `getting-started.html`, `platforms.html`, `agent-tutorial.html`, `living-brief.html` — added "Communications" nav link across all docs pages; added a card on the index page.
|
||||
- `product/app/app.js` — ChatGPT picker now leads with direct "Open" links for both published GPTs (Living Brief, Communications), and offers correctly-scoped spec URLs (Communications-only / Living Brief-only / Mail / Social / Everything) for anyone building their own custom GPT Action.
|
||||
|
||||
Commits:
|
||||
- `984c77d` — `deploy(k8s): add Communications OAuth client and bump image to 61ce4c7` (hermes-k8s.yaml secret/image commit from earlier in the day, already deployed)
|
||||
- `453831a` — `docs(communications): add docs page and fix ChatGPT connect picker` (today's docs/app work — **this is the one that needs deploying**)
|
||||
|
||||
---
|
||||
|
||||
## What's still needed
|
||||
|
||||
### Deploy the docs + app sites (high priority — currently live sites don't reflect any of this)
|
||||
|
||||
Both are separate Deployments from `hermes-mcp`, built from their own Dockerfiles, same registry-NodePort workaround applies:
|
||||
|
||||
```bash
|
||||
# docs site
|
||||
cd ~/hermes-mcp/docs
|
||||
docker build -t localhost:32000/squaremcp-docs:$(git rev-parse --short HEAD) .
|
||||
docker save localhost:32000/squaremcp-docs:$(git rev-parse --short HEAD) -o /tmp/squaremcp-docs.tar
|
||||
microk8s ctr image import /tmp/squaremcp-docs.tar
|
||||
# update docs-k8s.yaml image ref to the tag above (or digest if you push it through properly), imagePullPolicy: IfNotPresent
|
||||
microk8s kubectl apply -f docs-k8s.yaml
|
||||
microk8s kubectl rollout status deployment/squaremcp-docs -n fetcherpay
|
||||
|
||||
# app site
|
||||
cd ~/hermes-mcp/product/app
|
||||
docker build -t localhost:32000/squaremcp-app:$(git rev-parse --short HEAD) .
|
||||
docker save localhost:32000/squaremcp-app:$(git rev-parse --short HEAD) -o /tmp/squaremcp-app.tar
|
||||
microk8s ctr image import /tmp/squaremcp-app.tar
|
||||
# update app-k8s.yaml image ref similarly
|
||||
microk8s kubectl apply -f app-k8s.yaml
|
||||
microk8s kubectl rollout status deployment/squaremcp-app -n fetcherpay
|
||||
```
|
||||
|
||||
After deploy, verify:
|
||||
- `https://docs.squaremcp.com/communications.html` loads and nav shows "Communications" on every page
|
||||
- `https://app.squaremcp.com` → Connect AI Client → ChatGPT picker shows the two "Open" links + scoped spec buttons (not just the old single openapi.json link)
|
||||
|
||||
### Other open items (carried over, still not done)
|
||||
|
||||
1. Re-verify the "hermes-all-in" GPT actually connects cleanly now after the disconnect/reconnect (DCR re-registration) — wasn't independently re-tested this session.
|
||||
2. Update `product/site/privacy.html` and `terms.html` to specifically cover Communications data handling.
|
||||
3. Everything else from the prior handoff (`2026-06-16-kimi-handoff-current-state-and-next-tasks.md`) that wasn't already closed out: nginx-ingress chronic restarts, registry NodePort inaccessibility, `fetcherpay-leads-api`/`worker` ImagePullBackOff, `hermes.fetcherpay.com`/`ollama.fetcherpay.com` ingress.
|
||||
|
||||
---
|
||||
|
||||
## Related vault docs
|
||||
|
||||
- Original handoff: `SquareMCP/AI-Context/2026-06-16-kimi-handoff-current-state-and-next-tasks.md`
|
||||
- Communications OAuth deploy result: `SquareMCP/deployments/2026-06-16-communications-chatgpt-oauth-deploy-result.md`
|
||||
@@ -0,0 +1,190 @@
|
||||
# Kimi Handoff — Current State and Next Tasks
|
||||
|
||||
**Date:** 2026-06-16
|
||||
**Session author:** Kimi Code
|
||||
**Environment:** `art0` (104.190.60.129) — MicroK8s single-node cluster
|
||||
**Sudo password:** `onelove`
|
||||
|
||||
---
|
||||
|
||||
## What was completed in this session
|
||||
|
||||
### 1. Observability stack finalized
|
||||
|
||||
- OpenTelemetry Collector deployed in `observability` namespace (traces → Tempo, logs → Loki, metrics → FetcherPay Prometheus via remote write)
|
||||
- FetcherPay Prometheus remote-write receiver enabled
|
||||
- Redis exporter added and scraping
|
||||
- Grafana dashboards imported: Loki Operational, Tempo Operational, comprehensive Health Overview
|
||||
- Runbooks written in `SquareMCP/runbooks/observability/`
|
||||
|
||||
**Dashboard URL:** https://dashboard.fetcherpay.com
|
||||
**Grafana login:** `admin` / `admin_secure_2024`
|
||||
|
||||
### 2. Communications Manager — Week 3 chat UI deployed
|
||||
|
||||
- Commit `565b115` deployed
|
||||
- Image `localhost:32000/hermes-mcp@sha256:6fc290aea78e063b79814eab5325e3816ebb6120c5c268b677a889d52e0f1dc7`
|
||||
- Browser QA completed: profile creation, chat draft generation, Instagram image URL attach, edit, approve/publish, autonomous toggle hidden below 10 approvals
|
||||
|
||||
**Result doc:** `SquareMCP/deployments/2026-06-16-phase1-week3-chat-ui-deploy-result.md`
|
||||
|
||||
### 3. Communications ChatGPT OAuth scoping deployed
|
||||
|
||||
- Commit `61ce4c7` deployed
|
||||
- Image `localhost:32000/hermes-mcp:61ce4c7` (loaded via `microk8s ctr image import` due to registry NodePort issue)
|
||||
- New OAuth client registered for Communications GPT:
|
||||
- Client ID: `d5b4125c62c6f7ae61740116f8661dbb`
|
||||
- Client secret: set in `hermes-k8s.yaml` (not committed)
|
||||
- `/openapi-communications.json` live and scoped to Communications endpoints
|
||||
|
||||
**Result doc:** `SquareMCP/deployments/2026-06-16-communications-chatgpt-oauth-deploy-result.md`
|
||||
|
||||
---
|
||||
|
||||
## Current state of key services
|
||||
|
||||
| Service | Namespace | Status | Notes |
|
||||
|---------|-----------|--------|-------|
|
||||
| hermes-mcp | fetcherpay | Running | hostNetwork on :3456, latest image `61ce4c7` |
|
||||
| prometheus | fetcherpay | Running | remote-write receiver enabled |
|
||||
| grafana | observability | Running | 3/3 Ready |
|
||||
| otel-collector | observability | Running | traces/logs/metrics flowing |
|
||||
| loki | observability | Running | |
|
||||
| tempo | observability | Running | |
|
||||
| alertmanager | observability | Running | email + Slack routing |
|
||||
| mysql | Docker host | Running | `:3306`, volume `fetcherpay_mysql_data` |
|
||||
| redis | fetcherpay | Running | `:6379`, password in `redis-secret` |
|
||||
| nginx-ingress-microk8s | ingress | Running | **317 restarts** — chronic issue |
|
||||
| registry | container-registry | Running | NodePort `32000` not accessible from host |
|
||||
|
||||
---
|
||||
|
||||
## Known pre-existing issues
|
||||
|
||||
1. **`fetcherpay-leads-api` / `fetcherpay-leads-worker` — `ImagePullBackOff`**
|
||||
- Pointing to dead registry `23.120.207.35:32000`
|
||||
- Current registry is `localhost:32000`; `fetcherpay/leads-api:latest` exists but `v16-import-fix` does not
|
||||
- Fix: repoint image refs or delete if abandoned
|
||||
|
||||
2. **`nginx-ingress-microk8s-controller` — chronic restarts**
|
||||
- ~1 restart/day over 9 months
|
||||
- Likely OOM / sandbox churn on single-node MicroK8s
|
||||
- Fix: add memory limits, check `dmesg` OOM logs
|
||||
|
||||
3. **Registry NodePort `localhost:32000` not accessible from host**
|
||||
- Docker push fails
|
||||
- Workaround: `docker save` + `microk8s ctr image import`
|
||||
- Fix: investigate why NodePort isn't bound on host
|
||||
|
||||
4. **`hermes.squaremcp.com` root path returns 404**
|
||||
- API works; static dashboard is at `/app/index.html`
|
||||
- Expected behavior per active issues list
|
||||
|
||||
5. **`hermes.fetcherpay.com` and `ollama.fetcherpay.com` not in ingress**
|
||||
- Not configured yet
|
||||
|
||||
6. **Docker containers `mt5` and `obsidian` were stopped during deploy**
|
||||
- Need to be restarted if user wants them running
|
||||
|
||||
---
|
||||
|
||||
## Next tasks for the next agent
|
||||
|
||||
### High priority (user-facing / blocking)
|
||||
|
||||
1. **Complete the Communications ChatGPT GPT creation**
|
||||
- Original handoff: `SquareMCP/deployments/2026-06-16-communications-chatgpt-oauth-deploy-handoff.md`
|
||||
- Steps:
|
||||
1. In ChatGPT Builder, import Actions from `https://hermes.squaremcp.com/openapi-communications.json`
|
||||
2. Configure OAuth:
|
||||
- Client ID: `d5b4125c62c6f7ae61740116f8661dbb`
|
||||
- Client Secret: read from `hermes-k8s.yaml` env var `COMMUNICATIONS_OAUTH_CLIENT_SECRET`
|
||||
- Authorization URL: `https://hermes.squaremcp.com/oauth/authorize`
|
||||
- Token URL: `https://hermes.squaremcp.com/oauth/token`
|
||||
3. Test end-to-end OAuth flow in the GPT (profile → chat → draft → approve/publish)
|
||||
4. Add GPT name/description/icon
|
||||
5. Verify privacy/terms pages cover Communications data handling
|
||||
6. Set visibility to Public
|
||||
|
||||
2. **Fix `fetcherpay-leads-api` / `fetcherpay-leads-worker`**
|
||||
- Either repoint to `localhost:32000/fetcherpay/leads-api:latest` or delete if abandoned
|
||||
|
||||
3. **Restart user containers if requested**
|
||||
- `mt5`: `cd ~/mt5-docker && ./start-mt5.sh`
|
||||
- `obsidian`: rerun original docker run command
|
||||
|
||||
### Medium priority (infrastructure stability)
|
||||
|
||||
4. **Stabilize nginx-ingress controller**
|
||||
- Add memory request/limit to ingress DaemonSet
|
||||
- Monitor restart rate after change
|
||||
|
||||
5. **Fix registry NodePort accessibility**
|
||||
- Investigate why `localhost:32000` is not listening on host despite NodePort service
|
||||
- This blocks normal `docker push` workflow
|
||||
|
||||
6. **Add `hermes.fetcherpay.com` and `ollama.fetcherpay.com` ingress**
|
||||
- Requires deciding what backend services to route to
|
||||
|
||||
### Low priority / cleanup
|
||||
|
||||
7. **Commit or revert `hermes-k8s.yaml` changes**
|
||||
- Currently has uncommitted local changes (OAuth credentials + image tag)
|
||||
- Secret must not be committed
|
||||
- Consider moving secrets to a Kubernetes Secret resource
|
||||
|
||||
8. **Delete QA test accounts if no longer needed**
|
||||
- `qa-clickthrough-20260616@squaremcp.com` may have been lost during MySQL restart, but verify
|
||||
|
||||
---
|
||||
|
||||
## Access and credentials
|
||||
|
||||
| System | URL / Command | Credentials |
|
||||
|--------|---------------|-------------|
|
||||
| Grafana | https://dashboard.fetcherpay.com | `admin` / `admin_secure_2024` |
|
||||
| Hermes API | https://hermes.squaremcp.com | Smoke-test API key: `672e1f42f94b48fb94f866a4dd9b793d` |
|
||||
| Dashboard UI | https://hermes.squaremcp.com/app/index.html | Smoke-test: `smoke-test@squaremcp.com` (password unknown — use API key or create new user) |
|
||||
| MySQL | `127.0.0.1:3306` | `root` / `fetcherpay` |
|
||||
| K8s | `microk8s kubectl` | sudo password `onelove` |
|
||||
|
||||
---
|
||||
|
||||
## Important gotchas
|
||||
|
||||
- `hermes-k8s.yaml` is tracked in git but contains secrets. Do **not** commit new OAuth secret values.
|
||||
- Direct `kubectl exec`/`logs`/`port-forward` often fails due to kubelet TLS cert not including `104.190.60.129`. Use `--insecure-skip-tls-verify-backend=true` for logs, or `kubectl proxy` for HTTP checks.
|
||||
- The cluster is a single-node MicroK8s setup. Restarting nodes or heavy resource use can trigger sandbox churn.
|
||||
- Docker containers binding ports 80/443/3000/8080 must be stopped before `kubectl apply` to avoid port conflicts.
|
||||
|
||||
---
|
||||
|
||||
## Useful one-liners
|
||||
|
||||
```bash
|
||||
# Cluster health
|
||||
microk8s kubectl get pods -n fetcherpay
|
||||
microk8s kubectl get pods -n observability
|
||||
|
||||
# Hermes logs
|
||||
microk8s kubectl logs -n fetcherpay -l app=hermes-mcp --tail=50 --insecure-skip-tls-verify-backend=true
|
||||
|
||||
# MySQL query
|
||||
mysql -h127.0.0.1 -uroot -pfetcherpay hermes_oauth -e "SELECT ..."
|
||||
|
||||
# Registry workaround build/push
|
||||
SHA=$(git rev-parse --short HEAD)
|
||||
docker build -t localhost:32000/hermes-mcp:$SHA .
|
||||
docker save localhost:32000/hermes-mcp:$SHA -o /tmp/hermes-mcp-$SHA.tar
|
||||
microk8s ctr image import /tmp/hermes-mcp-$SHA.tar
|
||||
# Then update hermes-k8s.yaml image to localhost:32000/hermes-mcp:$SHA with imagePullPolicy: IfNotPresent
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Related vault docs
|
||||
|
||||
- Week 3 deploy result: `SquareMCP/deployments/2026-06-16-phase1-week3-chat-ui-deploy-result.md`
|
||||
- OAuth deploy result: `SquareMCP/deployments/2026-06-16-communications-chatgpt-oauth-deploy-result.md`
|
||||
- Observability runbooks: `SquareMCP/runbooks/observability/`
|
||||
- Monitoring deploy session: `SquareMCP/deployments/2026-06-16-otel-collector-remote-write-loki-tempo-dashboards.md`
|
||||
@@ -0,0 +1,56 @@
|
||||
# Handoff: API Keys Feature — 2026-06-17
|
||||
|
||||
## What was built
|
||||
|
||||
Added a working API Keys tab to the SquareMCP dashboard so customers can retrieve and copy their bearer token.
|
||||
|
||||
## Commit
|
||||
|
||||
`bf1e690` — feat(app): add API Keys tab so customers can retrieve their bearer token
|
||||
|
||||
## Changes
|
||||
|
||||
### Backend (src/billing/middleware.ts)
|
||||
- Added `api_key: string` to Customer interface and CustomerRow interface
|
||||
- Updated both resolveCustomerByApiKey and resolveCustomerById SELECT queries to include api_key and role
|
||||
- Updated buildCustomer to pass api_key through
|
||||
|
||||
### Backend (src/index.ts)
|
||||
- GET /api/auth/me now returns `api_key` alongside {id, email, plan, role} using req.customer.api_key
|
||||
|
||||
### Frontend (product/app/index.html)
|
||||
- Added API Keys nav button (data-view="apikeys")
|
||||
- Added #api-keys-section with code display and Copy button, styled using existing .webhook-card classes
|
||||
|
||||
### Frontend (product/app/app.js)
|
||||
- Added api-keys-section to the view toggle in the nav click handler
|
||||
- Added loadApiKeys() function: calls GET /api/auth/me, populates #api-key-display, wires Copy button with "Copied!" flash
|
||||
- Updated ChatGPT picker copy from "Settings -> API Keys" to "the API Keys tab"
|
||||
|
||||
### Tests (src/tools.test.ts)
|
||||
- Added api_key to mockCustomer fixture
|
||||
|
||||
## Deploy instructions for kimi-cli
|
||||
|
||||
Two deploys needed from branch main at commit bf1e690:
|
||||
|
||||
### 1. hermes-mcp (backend)
|
||||
- Build: docker build -t localhost:32000/hermes-mcp:<sha> .
|
||||
- Import: docker save localhost:32000/hermes-mcp:<sha> | microk8s ctr image import -
|
||||
- Edit hermes-k8s.yaml image tag (do NOT commit)
|
||||
- Apply: microk8s kubectl apply -f hermes-k8s.yaml
|
||||
- Verify: microk8s kubectl rollout status deployment/hermes-mcp -n fetcherpay
|
||||
|
||||
### 2. squaremcp-app (frontend)
|
||||
- Build: docker build -f product/app/Dockerfile -t localhost:32000/squaremcp-app:<sha> .
|
||||
- Import: docker save localhost:32000/squaremcp-app:<sha> | microk8s ctr image import -
|
||||
- Edit product/app/app-k8s.yaml image tag (do NOT commit)
|
||||
- Apply: microk8s kubectl apply -f product/app/app-k8s.yaml
|
||||
- Verify: microk8s kubectl rollout status deployment/squaremcp-app -n fetcherpay
|
||||
|
||||
## Verification after deploy
|
||||
|
||||
1. Log in at https://app.squaremcp.com
|
||||
2. Click API Keys in the top nav
|
||||
3. Your key appears in a code block with a Copy button
|
||||
4. Test: curl -H "Authorization: Bearer <key>" https://hermes.squaremcp.com/api/auth/me
|
||||
@@ -0,0 +1,81 @@
|
||||
# Handoff: Bearer Auth Fix — 2026-06-17
|
||||
|
||||
## Problem
|
||||
|
||||
ChatGPT GPT Actions (Communications Manager, Living Brief) send
|
||||
`Authorization: Bearer <api_key>` per the OpenAPI `bearerAuth` spec.
|
||||
The Express auth middleware only accepted keys via `x-api-key` header
|
||||
or `?key=` query param — Bearer was not checked, so every GPT Action
|
||||
call returned 401.
|
||||
|
||||
## Commit
|
||||
|
||||
`6ca0ca6` — fix(auth): accept customer API key via Authorization: Bearer header
|
||||
|
||||
## Changes
|
||||
|
||||
### src/index.ts — requireAuth middleware
|
||||
|
||||
Added `bearerValue = extractBearerToken(req)` (function already existed)
|
||||
and included it as a third fallback in the `apiKeyProvided` expression:
|
||||
|
||||
```ts
|
||||
// Before
|
||||
const apiKeyProvided = req.headers['x-api-key'] || req.query.key;
|
||||
|
||||
// After
|
||||
const bearerValue = extractBearerToken(req);
|
||||
const apiKeyProvided = req.headers['x-api-key'] || req.query.key || bearerValue;
|
||||
```
|
||||
|
||||
All communications, obsidian, email, and MCP routes use requireAuth.
|
||||
|
||||
### src/billing/middleware.ts — meterMiddleware
|
||||
|
||||
Same pattern, inlined since extractBearerToken lives in index.ts:
|
||||
|
||||
```ts
|
||||
// Before
|
||||
const apiKey = req.headers['x-api-key'] || req.query.key;
|
||||
|
||||
// After
|
||||
const authHeader = req.headers.authorization;
|
||||
const bearerValue = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : undefined;
|
||||
const apiKey = req.headers['x-api-key'] || req.query.key || bearerValue;
|
||||
```
|
||||
|
||||
Connection, webhook, and health routes use meterMiddleware.
|
||||
|
||||
## Auth flow after the fix
|
||||
|
||||
1. Extract bearer value from `Authorization: Bearer <token>`
|
||||
2. Try as API key: `resolveCustomerByApiKey(bearerValue)` — succeeds if it
|
||||
matches a customer row in the DB
|
||||
3. If no match (OAuth token, not API key): falls through to the existing
|
||||
OAuth access token validation — no regression
|
||||
|
||||
## Deploy instructions for kimi-cli
|
||||
|
||||
Only hermes-mcp needs rebuilding (no frontend changes).
|
||||
|
||||
```
|
||||
cd /path/to/hermes-mcp
|
||||
SHA=6ca0ca6
|
||||
docker build -t localhost:32000/hermes-mcp:$SHA .
|
||||
docker save localhost:32000/hermes-mcp:$SHA | microk8s ctr image import -
|
||||
# OR: docker push localhost:32000/hermes-mcp:$SHA
|
||||
# Edit hermes-k8s.yaml image tag to $SHA — do NOT commit
|
||||
microk8s kubectl apply -f hermes-k8s.yaml
|
||||
microk8s kubectl rollout status deployment/hermes-mcp -n fetcherpay
|
||||
```
|
||||
|
||||
## Verification after deploy
|
||||
|
||||
Get the API key from the API Keys tab at https://app.squaremcp.com, then:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer <api_key>" https://hermes.squaremcp.com/api/auth/me
|
||||
# Should return: {"id":"...","email":"...","plan":"...","api_key":"..."}
|
||||
```
|
||||
|
||||
If that returns 200, the Communications Manager GPT will authenticate.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Kimi Handoff — Session/Form Bug Fix + Pending Deploys
|
||||
|
||||
**Date:** 2026-06-17
|
||||
**Session author:** Claude (Sonnet 4.6)
|
||||
**Status:** Committed + pushed to `main` at `c6ab014`. Three deploys needed.
|
||||
|
||||
---
|
||||
|
||||
## What was fixed (commit `c6ab014`)
|
||||
|
||||
### Bug: "Save Connection" form leaking credentials to the URL and invalidating sessions
|
||||
|
||||
**Symptom:** After submitting the platform connect form (e.g. Facebook), the browser navigated to `https://app.squaremcp.com/?accessToken=<TOKEN>&pageId=<ID>`, then the user was redirected to the login page showing "Invalid session".
|
||||
|
||||
Three root causes, all fixed:
|
||||
|
||||
#### Fix 1 — `product/app/app.js:678` — form defaulted to GET
|
||||
The `<form class="connect-form">` had no `method` attribute (default GET) and no `action` attribute (default = current URL). Any failure to call `e.preventDefault()` would append the form fields as query params in the address bar, exposing credentials to browser history and server logs.
|
||||
|
||||
**Change:** Added `method="post" action="javascript:void(0)"` to the form template. Native fallback submit is now a no-op instead of a GET navigation.
|
||||
|
||||
#### Fix 2 — `product/app/app.js:698` — stale `errorEl` reference
|
||||
`errorEl` was obtained via `document.getElementById('connect-error')` — a document-wide lookup. If `openModal()` was called again while a fetch was in flight (replacing `modalBody.innerHTML`), this returned the wrong element or `null`, causing a TypeError that left the form without a working submit listener — meaning the *next* submit fell through to the native GET.
|
||||
|
||||
**Change:** Changed to `form.querySelector('#connect-error')` so the reference is always scoped to the live form.
|
||||
|
||||
#### Fix 3 — `src/index.ts:1561` — login cookie missing `domain` + wrong `sameSite`
|
||||
`POST /api/auth/login` set the session cookie with `sameSite: 'strict'` and no `domain` attribute (scoped to `hermes.squaremcp.com` only). The signup endpoint and native login page both use `sameSite: 'lax'` + `domain: '.squaremcp.com'`. Inconsistency caused cross-subdomain session requests to behave differently depending on auth path.
|
||||
|
||||
**Change:** Aligned to `sameSite: 'lax'` + `domain: '.squaremcp.com'`.
|
||||
|
||||
---
|
||||
|
||||
## Three deploys needed
|
||||
|
||||
### Deploy A — `squaremcp-app` (urgent — fixes credential leak for live users)
|
||||
|
||||
Commit `c6ab014` changed `product/app/app.js`.
|
||||
|
||||
```bash
|
||||
cd ~/hermes-mcp/product/app
|
||||
git pull # gets c6ab014
|
||||
docker build -t localhost:32000/squaremcp-app:c6ab014 .
|
||||
docker save localhost:32000/squaremcp-app:c6ab014 -o /tmp/squaremcp-app-c6ab014.tar
|
||||
microk8s ctr image import /tmp/squaremcp-app-c6ab014.tar
|
||||
# update product/app/app-k8s.yaml: image → localhost:32000/squaremcp-app:c6ab014, imagePullPolicy: IfNotPresent
|
||||
microk8s kubectl apply -f product/app/app-k8s.yaml
|
||||
microk8s kubectl rollout status deployment/squaremcp-app -n fetcherpay
|
||||
```
|
||||
|
||||
Verify: go to `https://app.squaremcp.com`, log in, click Connect on Facebook, fill in dummy credentials, submit — URL must NOT change to `?accessToken=...`. Error should appear inline in the modal.
|
||||
|
||||
### Deploy B — `hermes-mcp` (fixes login cookie for new sessions)
|
||||
|
||||
Commit `c6ab014` also changed `src/index.ts` (login cookie fix). Hermes needs a rebuild.
|
||||
|
||||
```bash
|
||||
cd ~/hermes-mcp
|
||||
git pull # gets c6ab014
|
||||
docker build -t localhost:32000/hermes-mcp:c6ab014 .
|
||||
docker save localhost:32000/hermes-mcp:c6ab014 -o /tmp/hermes-mcp-c6ab014.tar
|
||||
microk8s ctr image import /tmp/hermes-mcp-c6ab014.tar
|
||||
# update hermes-k8s.yaml: image → localhost:32000/hermes-mcp:c6ab014, imagePullPolicy: IfNotPresent
|
||||
# DO NOT commit hermes-k8s.yaml — it contains the Communications OAuth secret
|
||||
microk8s kubectl apply -f hermes-k8s.yaml
|
||||
microk8s kubectl rollout status deployment/hermes-mcp -n fetcherpay
|
||||
```
|
||||
|
||||
Verify: log out of `https://app.squaremcp.com`, log back in, DevTools → Application → Cookies for `hermes.squaremcp.com` — the `session` cookie should show `Domain: .squaremcp.com` and `SameSite: Lax`.
|
||||
|
||||
### Deploy C — `squaremcp-docs` (Communications docs page, still pending from 2026-06-16)
|
||||
|
||||
Commit `453831a` added `docs/communications.html` and updated nav across all docs pages. No new changes in this session — just the build that was deferred.
|
||||
|
||||
```bash
|
||||
cd ~/hermes-mcp/docs
|
||||
docker build -t localhost:32000/squaremcp-docs:453831a .
|
||||
docker save localhost:32000/squaremcp-docs:453831a -o /tmp/squaremcp-docs.tar
|
||||
microk8s ctr image import /tmp/squaremcp-docs.tar
|
||||
# update docs/docs-k8s.yaml image similarly
|
||||
microk8s kubectl apply -f docs/docs-k8s.yaml
|
||||
microk8s kubectl rollout status deployment/squaremcp-docs -n fetcherpay
|
||||
```
|
||||
|
||||
Verify: `https://docs.squaremcp.com/communications.html` loads; "Communications" shows in nav on every page.
|
||||
|
||||
---
|
||||
|
||||
## Side issue fixed this session — Redis pod sandbox churn
|
||||
|
||||
The hermes-mcp pod was stuck in `ContainerCreating` / readiness-probe failing because the Redis pod was stuck on a `SandboxChanged` event (classic single-node MicroK8s churn). Force-deleted the Redis pod; it came back healthy and hermes-mcp recovered automatically. No code change needed. Monitor: if Redis churns again, `microk8s kubectl delete pod -n fetcherpay -l app=redis --force --grace-period=0` is the fix. Adding memory limits to the ingress controller (from the previous open items list) would reduce overall sandbox pressure.
|
||||
|
||||
---
|
||||
|
||||
## Note on "Invalid session" for existing users
|
||||
|
||||
Users whose accounts were created before the MySQL container restart on 2026-06-16 will continue to get "Invalid session" errors from `meterMiddleware` — their customer rows were wiped and can't be recovered. Those users need to re-register. Fix 3 (login cookie alignment) prevents new users from hitting the cookie inconsistency going forward.
|
||||
|
||||
---
|
||||
|
||||
## Related vault docs
|
||||
|
||||
- Previous handoff (docs/picker deploy, Deploy C above): `SquareMCP/AI-Context/2026-06-16-claude-handoff-communications-docs-and-picker.md`
|
||||
- Communications OAuth deploy result: `SquareMCP/deployments/2026-06-16-communications-chatgpt-oauth-deploy-result.md`
|
||||
@@ -0,0 +1,359 @@
|
||||
---
|
||||
source: claude-code auto-generated
|
||||
updated: 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:
|
||||
|
||||
```bash
|
||||
# 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
|
||||
```
|
||||
|
||||
### JWT session cookie
|
||||
- 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
|
||||
```sql
|
||||
-- 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
|
||||
@@ -0,0 +1,119 @@
|
||||
---
|
||||
status: IMPLEMENTED
|
||||
source: gstack /plan-ceo-review
|
||||
generated: 2026-05-13
|
||||
implemented: 2026-05-13
|
||||
---
|
||||
# CEO Plan: SquareMCP v2 — Complete Foundation + MCP-Native Platform
|
||||
|
||||
Generated by /plan-ceo-review on 2026-05-13
|
||||
Branch: main | Mode: SELECTIVE EXPANSION
|
||||
Repo: garfield/hermes-mcp
|
||||
|
||||
## Context
|
||||
|
||||
hermes-mcp is the backend for SquareMCP — a unified MCP gateway for 9 social/messaging platforms (WhatsApp, LinkedIn, Telegram, Discord, Instagram, Twitter, TikTok, Facebook, Obsidian). Multi-tenancy was added 2026-05-08. SaaS web app was shipped 2026-05-13. YC application is being prepared.
|
||||
|
||||
**All 10 scope items were implemented and deployed 2026-05-13. Commit: 61dab40.**
|
||||
|
||||
## What Was Built (v2)
|
||||
|
||||
### Step 1 — MCP session threading + plan limit enforcement
|
||||
- `createMcpServer(customer?)` pattern: customer resolved from `requireAuth` middleware, threaded through `sessionCustomers` Map into MCP tool calls
|
||||
- `handleToolCall` gates on `checkLimit(customer.id, customer.plan)` at entry — returns `isError: true` when over limit
|
||||
- Usage platform attribution fixed: known-prefix matching replaces broken `name.split('_')[0]`
|
||||
- `stripAccountParam(tool)` deep-clones Tool objects, removes `account` enum for multi-tenant sessions
|
||||
|
||||
### Step 2 — Invoice fixes + cron
|
||||
- `generateMonthlyInvoice`: billing period uses previous month (not current month bug fixed)
|
||||
- Idempotency: UNIQUE constraint on `(customer_id, period_start)` + duplicate cleanup migration
|
||||
- Invoice number: `crypto.randomBytes(4).toString('hex')` (not `Math.random()`)
|
||||
- `emailInvoice()` sends HTML invoice via system SMTP
|
||||
- Cron `0 9 1 * *` with compare-delete Redis lock (`SET NX` + Lua DEL)
|
||||
|
||||
### Step 3 — Email multi-tenancy + platform coverage
|
||||
- `src/imap.ts` / `src/smtp.ts` accept `customer?` param, use `EmailCredentials.smtpHost/smtpPort`
|
||||
- TikTok, Facebook, Snapchat added to growth/enterprise plan tiers
|
||||
|
||||
### Step 4 — Analytics dashboard
|
||||
- `GET /api/usage/daily` → `{ date, count }[]` for Chart.js
|
||||
- Platform breakdown bars + daily sparkline in SaaS app
|
||||
|
||||
### Step 5 — Platform health checks
|
||||
- `src/multitenancy/platform-health.ts`: all 11 platforms checked in parallel
|
||||
- Redis cache key `health:{customerId}:{platform}`, 10-min TTL
|
||||
- Status values: `healthy | expired | disconnected | unknown`
|
||||
- Token refresh on near-expiry (60s buffer) via dynamic import to avoid circular dep
|
||||
|
||||
### Step 6 — Dynamic tool schema filtering
|
||||
- `stripAccountParam` exported from `src/tools.ts`
|
||||
- Multi-tenant sessions get tools array without internal `account` param
|
||||
|
||||
### Steps 7–8 — OAuth hardening + DCR browser flow
|
||||
- Atomic auth code consumption: `UPDATE SET used=TRUE WHERE used=FALSE` + `affectedRows` check
|
||||
- `customer_id` threaded through auth codes → tokens
|
||||
- `getTokenCustomer()` in `src/oauth.ts`
|
||||
- `isValidRedirectUri()` with `http://localhost:*` wildcard support
|
||||
- `ensureOAuthAppRegistered()` on startup (ON DUPLICATE KEY UPDATE)
|
||||
- `GET /oauth/connect-mcp` → server-side redirect keeps client_id off frontend
|
||||
- Callback page renders MCP client config snippets
|
||||
|
||||
### Step 9 — Inbound webhooks
|
||||
- `src/webhooks/delivery.ts`: HMAC-SHA256 (`X-SquareMCP-Signature: sha256=...`)
|
||||
- 3× exponential retry: 1s → 4s → 16s
|
||||
- Redis DLQ `webhook:dlq:{customerId}` with 7-day TTL
|
||||
- SSRF protection: blocks private IPs, localhost, .local, non-http schemes
|
||||
- `GET/POST/DELETE /api/webhooks/config`, `GET /api/admin/webhooks/dlq/:customerId`
|
||||
|
||||
### Step 10 — Developer docs
|
||||
- Static HTML + GitHub Pages in `/docs`
|
||||
- Pages: index, getting-started, platforms, agent-tutorial
|
||||
- Full Node.js MCP agent code example with Anthropic SDK
|
||||
|
||||
## Vision
|
||||
|
||||
**10x version:** An AI agent is set up once, automatically discovers all the user's social platforms via MCP tool listing, and can publish to all 9 platforms without writing a single API client. Setup is a browser OAuth flow. Monthly invoices arrive automatically. Revenue scales to 100+ customers with zero marginal billing work.
|
||||
|
||||
**Delight opportunities shipped:**
|
||||
1. Green/yellow/amber health indicators per platform in dashboard
|
||||
2. Platform-by-platform usage chart
|
||||
3. Browser OAuth for MCP clients — no API key config files
|
||||
4. Invoice in email inbox
|
||||
5. Inbound message routing — reactive AI agents
|
||||
|
||||
## Landscape
|
||||
|
||||
All competitors (Ayrshare, Socialync, Zernio, Bundle.social) are REST-first adding MCP as afterthought. Cloudflare, Zuplo, Apigee are doing enterprise MCP governance but not social. **SquareMCP is uniquely positioned as MCP-native from day one — this is the real moat.**
|
||||
|
||||
## NOT in Scope (deferred)
|
||||
- Stripe/payment processing (invoicing-first until revenue validates)
|
||||
- Team workspaces / multi-user accounts
|
||||
- Connector marketplace / SDK for third-party connectors
|
||||
- Mobile app
|
||||
- Token refresh flows for all platforms (LinkedIn, Twitter, TikTok, Instagram done; others deferred to v1.2)
|
||||
- Customer-facing webhook DLQ drain (deferred to v2.1)
|
||||
- Session hijack protection (store `{ transport, customerId }`, return 403 on mismatch — v2.1)
|
||||
|
||||
## Dream State Delta
|
||||
```
|
||||
BEFORE v2 (2026-05-13) AFTER v2 12-MONTH IDEAL
|
||||
MCP server: single-tenant → MCP server: multi-tenant → 50+ paying customers
|
||||
SaaS app: no metering + metering enforced Stripe or equivalent
|
||||
Invoices: manual + auto monthly invoices Team workspaces
|
||||
No analytics + analytics dashboard Analytics product
|
||||
No platform health + health checks + refresh Connector marketplace
|
||||
API key setup only + OAuth MCP connections SDK for devs
|
||||
Publish-only + inbound webhooks Reactive agent platform
|
||||
No docs + developer docs site Category-defining docs
|
||||
```
|
||||
|
||||
## Review Verdicts
|
||||
|
||||
| Review | Status |
|
||||
|--------|--------|
|
||||
| CEO Review (/plan-ceo-review) | CLEARED |
|
||||
| Outside Voice — Codex (CEO) | 18 findings → all resolved |
|
||||
| Eng Review (/plan-eng-review) | CLEARED |
|
||||
| Outside Voice — Codex (Eng) | 20 findings → all resolved |
|
||||
|
||||
**0 unresolved issues. Implemented and deployed 2026-05-13.**
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
source: gstack /plan-eng-review
|
||||
generated: 2026-05-13
|
||||
branch: main
|
||||
---
|
||||
# Eng Review: Test Plan
|
||||
Generated by /plan-eng-review on 2026-05-13
|
||||
Branch: main | Repo: garfield/hermes-mcp
|
||||
|
||||
## Framework
|
||||
Vitest (ESM-compatible). `npm install -D vitest @types/vitest`
|
||||
Scripts: `"test": "vitest run"`, `"test:watch": "vitest"`
|
||||
|
||||
Mock strategy:
|
||||
- `vi.mock('../db.js')` → mock `getPool()` to return a fake pool
|
||||
- `vi.mock('../redis.js')` → mock Redis client methods
|
||||
- `vi.mock('nodemailer')` → mock createTransport for emailInvoice tests
|
||||
- `vi.hoisted(() => ({ mockFn: vi.fn() }))` pattern for mocks referenced before module init
|
||||
|
||||
## Test Files (all implemented)
|
||||
- `src/tools.test.ts` — plan limit gate, platform attribution, error handling, stripAccountParam
|
||||
- `src/oauth.test.ts` — isValidRedirectUri, createAuthCode, exchangeCodeForToken, getTokenCustomer, validateAccessToken
|
||||
- `src/oauth-dcr.test.ts` — ensureOAuthAppRegistered SQL shape, all DCR redirect URI cases
|
||||
- `src/webhooks/delivery.test.ts` — SSRF URL validation (9 tests), delivery behavior (8 tests)
|
||||
- `src/multitenancy/credential-store.test.ts` — round-trip encryption, expiry check, token refresh
|
||||
- `src/multitenancy/platform-health.test.ts` — cache hit/miss, healthy/expired/disconnected/unknown states
|
||||
|
||||
## Key Interactions Verified
|
||||
|
||||
### Billing
|
||||
- `generateMonthlyInvoice()`: SQL WHERE uses previous month start/end, NOT current month
|
||||
- `generateMonthlyInvoice()`: returns existing invoice on `(customer_id, period_start)` unique constraint (MySQL 1062)
|
||||
- `generateInvoiceNumber()`: uses `crypto.randomBytes(4).toString('hex')` — never `Math.random()`
|
||||
- `emailInvoice()`: calls nodemailer.sendMail with correct subject, HTML body, invoice_number
|
||||
|
||||
### Usage Platform Attribution
|
||||
- `send_email` → `email`
|
||||
- `linkedin_create_post` → `linkedin`
|
||||
- `obsidian_search_notes` → `obsidian`
|
||||
- `tiktok_create_video` → `tiktok`
|
||||
- `create_draft` → `email`
|
||||
- `whatsapp_send_message` → `whatsapp`
|
||||
- Known-prefix matching (not `name.split('_')[0]` which was broken)
|
||||
|
||||
### OAuth Customer Binding
|
||||
- `getTokenCustomer(validToken)` → returns `{ customerId }` when token exists in DB
|
||||
- `getTokenCustomer(expiredToken)` → returns null
|
||||
- `exchangeCodeForToken()` stores `customer_id` in `oauth_tokens` table
|
||||
- Atomic consume: `UPDATE SET used=TRUE WHERE used=FALSE` + `affectedRows === 0` → null (replay protection)
|
||||
|
||||
### OAuth Security
|
||||
- `GET /oauth/authorize` with `redirect_uri` not in `client.redirect_uris` → 400
|
||||
- `POST /oauth/authorize` with invalid `redirect_uri` → 400, no code issued
|
||||
- `http://localhost:*` wildcard: allows `http://localhost:\d+` specifically
|
||||
- `GET /oauth/authorize` unauthenticated → redirect to `/login?return_to=...`
|
||||
|
||||
### MCP Session Threading
|
||||
- `createSession(customer)` stores customer in `sessionCustomers` map keyed by sessionId
|
||||
- Reused session → same customer from creation time
|
||||
- Session close → deletes from both `httpTransports` AND `sessionCustomers`
|
||||
|
||||
### Cron Invoice Lock
|
||||
- First process acquires `invoice:cron:lock` via SET NX → runs loop
|
||||
- Second process finds lock → logs and returns immediately
|
||||
- Lock released via Lua compare-delete (prevents A deleting B's lock on TTL expiry)
|
||||
|
||||
### Webhook Delivery
|
||||
- `signPayload(secret, rawBody)` → `sha256=<HMAC-SHA256-hex>`
|
||||
- Success on first attempt → no retry, no DLQ
|
||||
- Fails twice, succeeds third → 3 total attempts, no DLQ
|
||||
- Fails all 4 attempts → appended to Redis `webhook:dlq:{customerId}` EXPIRE 604800
|
||||
|
||||
### SSRF Protection
|
||||
- Accepts `https://my-server.example.com/hook`
|
||||
- Rejects: `ftp://`, `127.x`, `10.x`, `192.168.x`, `172.16-31.x`, `localhost`, `.local`
|
||||
|
||||
## Edge Cases
|
||||
- `generateMonthlyInvoice()` for customer with zero usage → returns null
|
||||
- `checkLimit()` for enterprise plan (limit === -1) → always `{ allowed: true }`
|
||||
- `handleToolCall()` with customer over limit → returns MCP error object with `isError: true`
|
||||
- `getTokenCustomer()` when DB is down → returns null (error caught, not propagated)
|
||||
- Webhook delivery with non-2xx response → failure (retry)
|
||||
- Webhook delivery with network timeout → failure (retry)
|
||||
|
||||
## Critical Paths (must not regress)
|
||||
- **Invoice period**: On June 1st at 09:00 UTC, cron bills May (NOT June)
|
||||
- **Invoice idempotency**: admin endpoint + cron both calling generateMonthlyInvoice for same customer/month returns same invoice
|
||||
- **Bearer token auth**: MCP session created with valid customer API key gets req.customer set correctly
|
||||
- **Webhook HMAC**: Recipient verifies `X-SquareMCP-Signature` against raw body — not parsed body
|
||||
- **Token refresh**: 60-second buffer before expiry triggers refresh; dynamic import avoids circular dep
|
||||
|
||||
## Architecture Decisions Captured
|
||||
|
||||
### Dynamic import for token refresh
|
||||
`src/multitenancy/credential-store.ts` uses `await import('./token-refresh.js')` inside the function body (not at module level) to break the circular dependency between credential-store and token-refresh.
|
||||
|
||||
### vi.hoisted() pattern
|
||||
Used in `oauth.test.ts`, `credential-store.test.ts` for mock factories that reference variables before module initialization. Pattern:
|
||||
```typescript
|
||||
const { mockExecute } = vi.hoisted(() => ({ mockExecute: vi.fn() }));
|
||||
vi.mock('../db.js', () => ({ getPool: vi.fn(() => ({ execute: mockExecute })) }));
|
||||
```
|
||||
|
||||
### Fake timers for retry testing
|
||||
`delivery.test.ts` uses `vi.useFakeTimers()` + `vi.advanceTimersByTimeAsync(1000/4000/16000)` to test retry delay logic without real waits.
|
||||
|
||||
### stripAccountParam deep-clone
|
||||
Tools array is module-level global. `stripAccountParam` must use spread/Object.fromEntries to avoid mutating shared state across sessions.
|
||||
@@ -0,0 +1,149 @@
|
||||
---
|
||||
source: claude-code auto-memory
|
||||
updated: 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
|
||||
Reference in new issue
Block a user