Skip to content

🧩 Backend & Frontend Component Architecture ​

This document details the software architecture, component boundaries, dependency inversion rules, subsystem interactions, and frontend state management in the Model Context Gateway (MCG).


📑 Table of Contents ​

  1. Backend Component & Boundary Model
  2. Frontend Component & Typed Architecture

1. Backend Component & Boundary Model ​

The C# ASP.NET Core backend codebase is partitioned into three strictly bounded contexts following Clean Architecture and Domain-Driven Design principles: Components/, Infrastructure/, and Core/.

├── Components/
│   ├── Servers/         # Upstream server registry, validation, health checks, discovery & MapServerEndpoints
│   ├── Clients/         # Registered clients, credential service, OAuth endpoints & MapClientEndpoints
│   ├── AppKeys/         # AppKey models, authorization keys, hashing, scope checks & MapAppKeyEndpoints
│   ├── Providers/       # Auth/Secret provider settings, envelope crypto & MapProviderEndpoints
│   ├── Authorization/   # Access policies, group mappings, RBAC evaluation & MapPolicyEndpoints
│   └── Capabilities/    # Native tools, virtual proxy execution, tool/prompt/resource handlers & MapCapabilityEndpoints
├── Infrastructure/
│   ├── Persistence/     # Dapper repositories, database connection factory, migrations & seeders
│   ├── Transports/      # SSE, HTTP, STDIO, state manager & target proxy
│   ├── Identity/        # Active Directory, OIDC, AppKey identity providers & LDAP service
│   ├── Secrets/         # Vault, Windows Registry, Environment secret retrievers & encryption
│   └── Logging/         # Audit logger, PII sanitization & in-memory log providers
└── Core/
    ├── Protocol/        # JSON-RPC 2.0 protocol models & polymorphic converter
    └── Routing/         # ClientSession, SessionManager, BackendConnection & Semantic Search

Domain Components (Components/) ​

Domain components encapsulate vertical business features, HTTP/JSON-RPC controller routes, Minimal API route endpoints, and domain validation services:

  1. Servers:

    • McpServer.cs: Data model representing upstream MCP servers, endpoints, transport types, categories, headers, and secret associations.
    • ServerEndpoints.cs: Minimal API mapping for CRUD operations, inspections, and health states (GET /api/servers, POST /api/servers, DELETE /api/servers/{id}).
    • ServerValidationHelper.cs: URL syntax checking, Server-Side Request Forgery (SSRF) prevention, and parameter sanitization.
    • DockerAutoDiscoveryService.cs: Dynamic label-based container discovery (mcp.enable=true, mcp.name, mcp.port).
    • BackendHealthCheckService.cs: Background periodic health prober (15s HTTP GET + 30s JSON-RPC ping).
  2. Clients:

  3. AppKeys:

  4. Providers:

  5. Authorization:

  6. Capabilities:

    • ProxyEndpoints.cs: Core HTTP/SSE entrypoints (/sse, /message, /{targetServerId}).
    • CapabilityEndpoints.cs: Tool, prompt, resource, and custom file catalog management.
    • CustomToolRegistry.cs: In-process native tools for Plex (PlexGetLibrarySectionsTool, PlexSearchLibraryTool, PlexGetSessionsTool, etc.) and Overseerr (SeerrSearchMediaTool, SeerrRequestMediaTool, SeerrGetRequestsTool, etc.).

Infrastructure Services (Infrastructure/) ​

Infrastructure provides concrete technical implementations for interfaces defined across Core and Components:

  1. Persistence:

    • DbConnectionFactory.cs: Multi-database factory supporting SQLite (WAL), MS SQL Server (Microsoft.Data.SqlClient), and MySQL (MySqlConnector).
    • Repositories.cs: High-performance Dapper repository layer.
    • DatabaseSeederService.cs: Automatic in-process migrations, schema compatibility validation, and default configuration seeding.
  2. Transports:

    • ITransport.cs: Unified abstraction for downstream transport channels.
    • SseTransport.cs: Full-duplex persistent Server-Sent Events channel with POST message forwarding.
    • HttpTransport.cs: Stateless half-duplex HTTP POST and chunked streaming transport.
    • StdioTransport.cs: Subprocess STDIO transport communicating via newline-delimited JSON-RPC (NDJSON).
    • JsonRpcStateManager.cs: Manages pending request completion sources (PendingRequestTcs), ID rewriting, cancellation tokens, and connection resets.
  3. Identity:

  4. Secrets:

  5. Logging:

    • AuditLogger.cs: Writes structured invocation and admin audit trails.
    • PiiSanitizer.cs: Regex sanitizer stripping Bearer tokens, API keys, passwords, and connection strings.
    • InMemoryLogger.cs: Thread-safe ring buffer powering the real-time Test Bench UI console.

Core Protocol & Routing Engine (Core/) ​

The Core assembly contains high-performance routing coordinators and protocol engines that remain free of concrete external dependencies:

  1. ClientSession (Partial Class Architecture):

  2. Routing Coordinators:


Architectural Boundary Constraints ​

To preserve modularity, testability, and maintainability across releases, the codebase enforces five strict architectural boundary constraints:


Component Subsystem Diagram ​

The following class diagram illustrates the dependency inversion contracts connecting domain endpoints, session management, abstract transports, database factories, and secret retrievers:


2. Frontend Component & Typed Architecture ​

React 19 & Vite SPA Architecture ​

The web dashboard is built using React 19, TypeScript, Vite, and Zustand. It features a dark-mode interface styled with centralized CSS variables (variables.css, layout.css, dashboard.css, tester.css), eliminating UI layout shifts via align-items: flex-start and scrollbar-gutter: stable.


Domain Component Decomposition ​

The frontend source structure clearly separates typed API communication, modular views, reactive Zustand stores, and TypeScript domain models:

frontend/src/
├── api/                    # Typed API Client Layer (Axios / Fetch Wrappers)
│   ├── api.ts              # Base API instance, headers & error handling
│   ├── serverApi.ts        # Server CRUD & discovery endpoints
│   ├── clientApi.ts        # Registered OAuth clients
│   ├── appKeyApi.ts        # AppKey minting, revocation & verification
│   ├── securityApi.ts      # Policies & group mappings
│   ├── settingsApi.ts      # Provider configs & system settings
│   ├── userApi.ts          # Authenticated user identity & version info
│   └── testbenchApi.ts     # Tool execution, search simulation & log streaming
├── components/             # Domain UI Component Trees
│   ├── servers/            # DashboardView, ServerModal, ServerInspectModal, ServerCard
│   ├── clients/            # RegisteredClientsCard, ClientSetupGuide, AppKeysCard, ClientModal
│   ├── security/           # SecurityView, PolicyModal, MappingModal
│   ├── settings/           # SettingsView, GeneralTab, IdentityAuthTab, SecretProvidersTab,
│   │                       # AccessControlTab, CustomFilesTab, BackupsTab
│   ├── testbench/          # TestBenchView (Interactive JSON Schema Form Builder, Console, & Log Stream)
│   └── shared/             # Header, Footer, Toasts, Modal, StatusBadge, PaginationToolbar
├── stores/                 # Centralized Zustand Reactive Stores
│   ├── useServerStore.ts   # Servers list, health states, filter queries
│   ├── useClientStore.ts   # Registered clients & setup guides
│   ├── useAppKeyStore.ts   # Active keys, key creation modal, copy buffer
│   ├── useSettingsStore.ts # Provider configs, dynamic encryption flags
│   ├── useUserStore.ts     # Current user, roles, SIDs, version cache
│   ├── useLogStore.ts      # Real-time logs ring buffer & level filters
│   └── useToastStore.ts    # Notification toast queue with auto-dismiss
└── types/                  # Canonical TypeScript Domain Interfaces
    ├── server.ts, client.ts, appKey.ts, security.ts, settings.ts, user.ts, testbench.ts

Typed API Layer & Zustand State Stores ​

The frontend strictly separates UI rendering from state synchronization and network communication:

  • useServerStore: Manages the server inventory, category tags, search filters, modal inspection state, and health check polling intervals.
  • useClientStore: Coordinates registered OAuth clients, client setup guide generation, and configuration downloads.
  • useAppKeyStore: Handles key creation workflows, reveals raw secret tokens once upon generation, and manages granular scope boundaries.
  • useSettingsStore: Coordinates identity and secret provider configuration forms, toggles password masking, and encrypts configuration payloads.
  • useUserStore: Tracks the authenticated user session, resolved roles, SIDs, permissions, and fallback gateway version information.
  • useLogStore: Streams logs via a thread-safe ring buffer with severity filters (Debug, Info, Warn, Error) for the Test Bench.
  • useToastStore: Centralized ephemeral toast notification queue with auto-dismissal.

Frontend Architecture & State Flow Diagram ​


Related Specifications:

Released under the Apache 2.0 License.