Skip to content

Architecture

Harbor connects one team to a WooCommerce store through a shared Model Context Protocol (MCP) gateway. People use dashboard chat or an external MCP client. The gateway applies the same identity, tool permissions and audit rules to both paths.

Technology stack

Layer Technology and responsibility
Console React 19, TypeScript and Vite; browser sessions, connection management, chat and Activity
Application Python 3.12 and FastAPI; identity, registry, chat orchestration and management API
MCP Official Python SDK; Streamable HTTP gateway and three separate upstream services
Chat Google Gen AI SDK and Gemini; tool selection and response generation
Application data PostgreSQL, SQLAlchemy and Alembic migrations
Store WordPress, WooCommerce, PHP and MariaDB
Deployment Docker images, Helm and K3s; k3d runs the local cluster
Documentation MkDocs with Material; built as a static site

Dependency lockfiles and container definitions record exact versions. See development for the source map and deployment for runtime configuration.

Design decisions

Decision Alternatives considered Reason
One FastAPI service for identity, registry, gateway, chat and audit Separate management API and gateway services One team and one replica do not need independent scaling. A single process shares the session check, permission check and audit code across the console API, /mcp and chat. A split would add an internal API with its own authentication. The modules (backend/gateway.py, backend/chat.py) are separable if that changes.
WooCommerce REST API for the commerce upstream WP-CLI; SQL against MariaDB REST applies WooCommerce's own validation, hooks and stock rules, and works between pods with a scoped key. WP-CLI would need a shell in the WordPress pod for every call, through pods/exec rights or a sidecar. SQL would bypass WooCommerce's rules, and its schema is not a stable interface. WP-CLI is still used once, by the bootstrap Job.
Public tool names slug__name_hash Server prefix only; opaque IDs A prefix alone can still collide after names are sanitized and shortened. An eight-character hash of the original name keeps aliases unique and stable, and the readable part helps people and models. Aliases stay within 60 characters.
SHA-256 for API keys, Argon2 for passwords Argon2 for both Keys are 256-bit random values, so a fast hash is not guessable, and every MCP request must look one up. Argon2 costs 64 MiB per check and would sit on that path. Passwords are low-entropy, so they need a slow hash.
Registered upstream credentials in one Kubernetes Secret, referenced by key from PostgreSQL Encrypted column in PostgreSQL Values stay out of database dumps and registry rows, K3s encrypts the Secret at rest, and RBAC limits the gateway to get and patch on that one Secret. The gateway can read every registered credential; for one team that is the intended boundary.
Build images on the node and import them into k3s Push to a container registry A single node needs no registry to run or pay for, and images never leave the host. Builds use the node's CPU and memory, and a multi-node cluster would need a registry; the chart already accepts registry image references.
K3s everywhere: k3d locally, k3s on the server kind; Minikube Traefik, local-path storage and the NetworkPolicy controller behave the same in both places, so Helm values are the only difference.
Gemini for chat, kept optional Other hosted providers; a local model The free tier is enough for a demonstration, and the provider is confined to backend/chat.py. The gateway, keys and external clients work without any model key.

Components

An upstream is a connected MCP service. The gateway is the shared entry point that authenticates clients, applies permissions and routes their calls.

---
config:
  flowchart:
    useMaxWidth: false
  theme: base
  themeVariables:
    primaryColor: "#e8ece4"
    primaryBorderColor: "#136b69"
    primaryTextColor: "#121517"
    lineColor: "#545d56"
---
flowchart TB
    accTitle: Harbor service architecture
    accDescr: The console and external clients reach the FastAPI application and MCP gateway. The gateway stores identity and activity in PostgreSQL and routes tools to three upstream MCP services. The commerce service calls WooCommerce, which stores its data in MariaDB and persistent WordPress files.
    UI[React console] -->|Session cookie| API[FastAPI and MCP gateway]
    CLI[External MCP client] -->|Bearer key| API
    API --> PG[(PostgreSQL)]
    API -->|Service credentials| MCP[Commerce, policies and shipping MCP]
    MCP -->|Commerce REST calls| WP[WordPress + WooCommerce]
    WP --> DATA[(MariaDB and WordPress files)]

The diagram groups the three MCP upstreams for readability; each runs independently. Chat calls Gemini from FastAPI and executes tools through the gateway. Storefront browsers connect directly to WordPress through ingress.

The React dashboard is served as a static application. FastAPI contains the identity, registry, gateway, chat and audit modules in one deployment. PostgreSQL stores users, hashed keys, sessions, invitations, server metadata, tool catalogues, permissions, pending confirmations and audit records. The store runs WordPress with WooCommerce and its own MariaDB database. WordPress content, MariaDB and PostgreSQL each have persistent volumes.

Three independent Python processes expose Streamable HTTP MCP: WooCommerce, store policies and shipping estimates. The last two use versioned sample business rules. They return sample rules and estimates; neither connects to a live carrier or policy provider. WooCommerce owns products, checkout, prices and orders. Its adapter uses the WooCommerce REST API instead of bypassing application rules with SQL.

The public ingress hosts are the dashboard and storefront. /api and /mcp on the console host route to FastAPI. Upstreams and databases have only ClusterIP services. Kubernetes NetworkPolicies and a separate gateway-to-upstream bearer credential prevent ordinary cluster workloads from using the MCP services.

Cluster topology

Everything runs in the harbor namespace except the Traefik ingress controller. A default-deny NetworkPolicy blocks all pod traffic; each arrow below is an explicit allow rule. Pods without an arrow to them cannot be reached from anywhere.

flowchart LR
    accTitle: Harbor cluster topology
    accDescr: Traefik routes the console host to the dashboard and gateway and the store host to WordPress. Only the gateway reaches the three MCP upstreams and PostgreSQL. Only the WooCommerce upstream reaches WordPress, and only WordPress reaches MariaDB. The gateway may call the Kubernetes API and public HTTPS addresses.
    NET((Internet)) -->|80, 443| T[Traefik<br>kube-system]
    subgraph H[namespace harbor]
        D[dashboard]
        G[gateway]
        WOO[woo-mcp]
        POL[policies-mcp]
        SHIP[shipping-mcp]
        PG[(postgres)]
        WP[wordpress]
        DB[(mariadb)]
    end
    T -->|console host /| D
    T -->|console host /api, /mcp| G
    T -->|store host /| WP
    G -->|8001, bearer| WOO
    G -->|8001, bearer| POL
    G -->|8001, bearer| SHIP
    G -->|5432| PG
    WOO -->|8080, signed REST| WP
    WP -->|3306| DB
    G -->|443| API[Kubernetes API]
    G -->|443, public addresses only| EXT[Gemini and public MCP servers]
Resource Used by Contents
Secret harbor-app-secrets Every workload except the dashboard, as environment variables Database passwords, session secret, bootstrap administrator password, WooCommerce keys, bundled upstream tokens, Gemini key
Secret harbor-upstream-credentials Gateway, through the Kubernetes API (get, patch on this Secret only) Credentials of registered upstreams
Secret harbor-ingress-tls Traefik (production only) Certificate issued by cert-manager
Volume postgres-data PostgreSQL Users, keys, sessions, registry, Activity
Volume mariadb-data MariaDB WooCommerce products, orders and settings
Volume wordpress-data WordPress Plugins, theme and uploads

One tool execution path

An external client sends its personal API key to /mcp. Middleware authenticates every request against the database, including requests on an existing MCP transport. The handler resolves the public tool alias, checks the server is enabled, applies the user's role, validates the JSON arguments and calls the original tool through the official Python SDK.

sequenceDiagram
    accTitle: One external tool call
    accDescr: The gateway authenticates the key, resolves the alias, records a pending audit row, checks permissions, validates arguments, loads the upstream credential and calls the upstream. It validates the result, finishes the audit row and replies.
    autonumber
    participant C as MCP client
    participant G as Gateway /mcp
    participant P as PostgreSQL
    participant S as Credential Secret
    participant U as woo-mcp
    participant W as WooCommerce
    C->>G: tools/call with alias and arguments, Bearer user key
    G->>P: Look up key hash, load user and role
    G->>G: Resolve alias to server and original tool name
    G->>P: Insert audit row as pending
    G->>G: Check server enabled and role permits the tool
    Note over G: Per-upstream slot and tool deadline start
    G->>G: Validate arguments in the schema worker
    G->>S: Read this upstream's credential
    G->>U: tools/call with original name and server credential
    U->>W: Signed REST request
    W-->>U: JSON response
    U-->>G: Tool result
    G->>G: Validate result, redact credential
    G->>P: Finish audit row with outcome and duration
    G-->>C: Result, or a clear error

The user's key never leaves the gateway. Steps 6 to 12 run under the tool deadline, so a slow or dead upstream ends as a timeout for that call only. Policies and shipping follow the same path but answer from their own rules instead of calling WooCommerce.

Dashboard chat uses a short-lived, signed delegation token bound to the verified dashboard session. The gateway checks that session and the user's current role for each delegated call. Browser-supplied user IDs never establish identity. The chat module uses an HTTP MCP client for execution, so the same gateway authorization and audit code applies. The LLM and browser never receive upstream credentials.

The chat loop disables automatic SDK function execution. It presents permitted tools, receives function calls, executes read operations through MCP and supplies results back to the model. Mutations pause for a one-use confirmation bound to the user and session. Calls bind the intended tool to its upstream revision, destination, schema and permissions. The gateway checks that binding and current authority again after waiting for capacity and completing the upstream handshake. Automatic chat calls also require the tool to remain read-only. A changed connection or permission requires a fresh proposal. A bounded number of rounds, calls, output bytes and concurrent requests limits resource use.

sequenceDiagram
    accTitle: Dashboard chat acting as the signed-in user
    accDescr: The chat module lists tools permitted for the user, sends them to Gemini, and executes each function call through the gateway with a signed delegation token. Read tools run immediately; write tools wait for the user's approval.
    participant B as Browser
    participant A as Chat module
    participant M as Gemini
    participant G as Gateway /mcp
    B->>A: POST /api/chat with session cookie and CSRF token
    A->>A: List tools permitted for this user
    A->>M: Conversation and permitted tool declarations
    M-->>A: Function call
    alt Read tool
        A->>G: tools/call with a 5-minute delegation token for this session
        G-->>A: Result, audited under the user
        A->>M: Function result
        M-->>A: Answer
        A-->>B: Answer and the tool calls made
    else Write tool
        A-->>B: Confirmation card with the exact tool and arguments
        B->>A: POST /api/chat/confirm
        A->>G: tools/call bound to the reviewed target
        G-->>A: Result, audited under the user
        A-->>B: Result
    end

The confirmation flow is part of dashboard chat. External administrator clients may invoke write tools directly. Member keys remain limited to tools the administrator has classified as read operations.

Large tool catalogs in chat

Small catalogs go directly to Gemini. If the permitted catalog exceeds 40 tools or 48 KiB of serialized function declarations, chat starts with one internal harbor_search_tools function. These are Harbor's application budgets, not Gemini's advertised limits.

Search ranks the permitted tool names, server names and descriptions locally. It returns at most five matches and enables their complete schemas for the next model round. A new search replaces the selection; pagination and query refinement let the model reach later tools without accumulating the whole catalog. A schema that cannot fit is reported explicitly and remains unavailable in chat. It is never truncated to make execution possible.

Every selected schema is bound to its upstream revision, destination and permissions. Chat refreshes the identity before discovery and execution, rejects changed targets, and keeps the same write-confirmation flow. Search requests share the existing 12-function-call and eight-round limits. Discovery inspects a catalog; only actual gateway calls create tool-execution audit records.

External MCP clients still receive the ordinary tool list, paginated at 100 entries, and invoke the original public aliases. They control their own model context. The standalone reference agent follows all pages but reports an explicit error above its smaller 40-tool/48-KiB model budget.

Discovery, routing and failures

Public tool names combine an immutable server slug, a readable original tool name and a short hash of the original name. Discovery rejects a catalogue if two original names still produce the same alias. The mapping is resolved explicitly; the gateway does not trust a client-supplied destination URL. Aliases fit within 60 characters. The policies and shipping services both expose search, so aliases must distinguish tools with identical original names. JSON Schema validation has no remote or filesystem reference resolver; only in-document references are permitted.

Each upstream's tool catalogue is refreshed independently under a timeout. Tool listing reads the stored catalogues and applies live enabled and permission settings, so it does not wait for a dead upstream. A failed refresh retains the last known catalogue and marks the server Unreachable. Calls return clear failures and other services continue working. Disabled servers disappear from discovery immediately. Clients that cache their tool list need a refresh; direct calls using stale names are still rejected. The SDK advertises zero cache TTL. Clients must refresh discovery after a connection or permission change rather than relying on push notifications.

Execution has per-upstream concurrency limits and an overall deadline. Untrusted schema work runs in one reusable subprocess. Starting the process and importing its validator have a separate five-second readiness limit; each untrusted validation operation retains a two-second execution deadline. Timeout or cancellation kills and reaps the worker. Input is capped at 512 KiB, 64 nesting levels and 20,000 JSON nodes. Linux deployments also restrict the worker's address space. Startup, queueing and execution remain subject to the surrounding tool or discovery deadline, and ordinary API requests do not wait on the worker.

Writes are not automatically retried. Any failure after write dispatch can mean the store committed a mutation before the response was usable, so the response and audit record advise reconciling state before retrying. A unique SKU helps reconcile product creation; exactly-once delivery is not guaranteed.

Upstream calls bypass the MCP client's automatic output-schema validation and retry behavior. The gateway validates successful structured results against the reviewed output schema in the same bounded worker used for input validation. A malformed or expensive output schema cannot occupy the API event loop. Tools must return a completed result; interactive continuations are reported as unsupported. The WooCommerce adapter also enforces a ten-second total request deadline, a two-megabyte response limit and strict JSON number parsing. It requests uncompressed responses and rejects compressed replies before decoding. It closes timed-out streams and reports an uncertain outcome for writes.

Chat shares a provider-rate-limit cooldown across users in one gateway process. It honors structured retry hints and rejects excess concurrent requests immediately. The only automatic model retry is one explicit provider 503; it retries that generation request without repeating completed tool calls. A quota error never triggers account switching or a write retry. See provider rate limits for user-facing recovery steps.

Password hashing and verification share two non-queueing slots. Each Argon2 operation retains its 64 MiB memory cost; excess requests receive 503 with Retry-After instead of allocating another hash. Rate-limit bucket updates are synchronized across authentication threads. The limits keep concurrent hashing within the gateway's 512 MiB memory budget.

PostgreSQL connections and pool acquisition have five-second limits. Queries have a 15-second statement limit and a five-second lock-wait limit; TCP failure detection is configured on connections. MCP authentication and rejected-call auditing use bounded worker threads. The liveness route uses no database or worker-thread capacity, while readiness requires PostgreSQL. Database failures return a sanitized 503 response. Some request paths still use synchronous database queries, so the service does not promise uninterrupted responsiveness during every database failure.

Every authenticated tool attempt creates an audit row before dispatch and finishes it with duration and outcome. Denied calls and recognizable revoked-key attempts retain user attribution. Audit records contain server/tool snapshots, not customer addresses or raw order payloads. A process crash can leave a pending record; it must not be reported as success.

Credentials and Kubernetes access

Random user API keys are shown once and stored as SHA-256 hashes. Their entropy makes a fast hash appropriate; human passwords use Argon2. Dashboard sessions are opaque random tokens with hashed storage, HttpOnly cookies and CSRF protection.

Accepting an invitation signs in as the account and role recorded on that invitation. Acceptance and password login revoke the browser session they replace before issuing a fresh cookie. Other browser profiles retain their independent sessions. Tabs within one profile refresh their identity and discard the previous account's workspace state when an account changes.

Bootstrap configuration lives in Kubernetes Secrets created by a setup script. Dynamically registered upstream credentials live in a dedicated mutable Secret; PostgreSQL stores references. Each bundled upstream reads its own service token from the application Secret. Editing or deleting the gateway's credential copy cannot change that service's authentication or prevent its pod from starting. The backend service account has get and patch rights on the mutable credential Secret only. It cannot enumerate other Secrets or create workloads. Kubernetes does not offer per-field authorization inside one Secret, so the gateway can read all registered upstream credentials. This is the intended trust boundary for one team.

Helm references existing Secrets instead of including credential values in release manifests. The setup script does not replace existing runtime credentials on a normal redeployment. K3s secret encryption is enabled at cluster creation. This protects datastore files at rest, not against a cluster administrator or a compromised gateway process.

The first application start seeds the administrator and three bundled connections, then stores a bootstrap marker in PostgreSQL. Subsequent starts preserve registry deletions as well as edits and disabled states.

Store correctness

The adapter uses OAuth 1.0 HMAC-SHA256 for internal HTTP requests, with credentials in the Authorization header. WooCommerce signs against its public home URL, so transport and signing origins are configured separately. The consumer secret is not sent in a URL. In production, external ingress uses TLS. The internal network remains a cluster trust boundary; request signing is not payload encryption.

Prices remain decimal strings and Python Decimal values. The sample store uses INR and Asia/Kolkata. Today's order bounds use the configured store timezone. Lists expose page counts so callers can request further pages. Order tools project only the fields needed for operations and shipping regions.

Local and production

Local k3d runs K3s with Traefik, local-path storage and an embedded NetworkPolicy controller. The same Helm chart accepts production hosts, TLS Secret references, storage class, sizes, image tags and resource settings. Production images can come from an accessible private registry or be built and imported directly on a single k3s node. The VPS deployment procedure uses the latter approach.

Both environments install the same chart; only values change. Local values come from deploy/values-local.yaml plus .runtime/values-runtime.yaml, written by scripts/deploy.ps1. Production values come from deploy/values-prod.yaml plus .runtime/values-vps.json, written by scripts/deploy-vps.sh. Settings not listed use the chart defaults in both.

Setting Local Production
Console and store hosts harbor.localhost, store.localhost DNS names passed to deploy-vps.sh
Public URLs http://…:8080 https://…
Ingress TLS None harbor-ingress-tls, issued by cert-manager through the HTTP-01 issuer in deploy/vps/tls.yaml
ACME solver NetworkPolicy Off On (networkPolicy.allowAcmeHttp01)
Ingress controller k3d's Traefik, published on 127.0.0.1:8080/8443 Traefik with externalTrafficPolicy: Local and an HTTP-to-HTTPS redirect (deploy/vps/traefik.yaml)
Session cookies gateway.secureCookies: false true
Images :dev tags, rebuilt by bootstrap.ps1 An immutable release tag, built on the node and imported into k3s
Volumes (WordPress, MariaDB, PostgreSQL) local-path, 2/2/1 GiB local-path, 10/10/5 GiB
Proxy trust The node's pod CIDRs, discovered at deploy time The node's pod CIDRs, discovered at deploy time
API-server egress The chart's default Service IP (10.43.0.1/32) and the node's internal IP, discovered at deploy time The Kubernetes Service IP and the node's internal IP, both discovered at deploy time
Credentials .secrets/development.json, created by bootstrap.ps1 .secrets/development.json on the host, created by prepare-secrets.py
Administrator email From the local credential file The ADMIN_EMAIL argument

Secret names, probes, resource limits and the remaining NetworkPolicies are the same in both environments.

Each component runs one replica. PostgreSQL and MariaDB have no high-availability configuration, local-path volumes stay on one node, rate limits are process-local, and the gateway is not horizontally scaled. Moving to multiple nodes requires changes to storage, session handling and rate limiting before increasing replicas.

Upgrades use versioned images and Helm. Application rollback is distinct from database rollback. Back up the databases and WordPress content before an incompatible migration. Do not assume helm rollback restores persistent data.

References