🧩 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 ​
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 SearchDomain Components (Components/) ​
Domain components encapsulate vertical business features, HTTP/JSON-RPC controller routes, Minimal API route endpoints, and domain validation services:
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).
Clients:ClientEndpoints.cs&ClientsController.cs: Client registration and OAuth client management.CredentialService.cs: Automated client configuration generation (claude_desktop_config.json, Cursor config, environment templates).
AppKeys:AppKey.cs&AppKeyModels.cs: High-entropy machine keys (mcp-*-*-*), key prefixes (KeyPrefix), AES-256-GCM encrypted keys, scopes (ScopesJson), and attribution (OwnerSid).AppKeyEndpoints.cs&AppKeysController.cs: Endpoints for key minting, revocation, prefix lookups, and validation.
Providers:ProviderEndpoints.cs&ProvidersController.cs: Management of Identity and Secret Provider configurations.ProviderConfigSecurityHelper.cs: Transparent encryption/decryption of provider JSON configuration payloads.
Authorization:PolicyEndpoints.cs&PermissionsController.cs: Endpoints for RBAC policies and group mappings.SecurityValidationHelper.cs: CIDR subnet evaluation, private IP blocking, SSRF prevention, and Administrator SID verification (S-1-5-32-544).
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:
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.
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.
Identity:CompositeIdentityProvider.cs: Aggregates Active Directory, OIDC, and AppKey authenticators.ActiveDirectoryIdentityProvider.cs&LdapActiveDirectoryService.cs: Resolves Windows Kerberos/NTLM caller SIDs via LDAP.OidcIdentityProvider.cs: Extracts authenticated user contexts from reverse-proxy headers (Remote-User,Remote-Groups,Remote-User-Sid).
Secrets:CompositeSecretRetriever.cs: Dispatches to Vault, Windows Registry, or Environment retrievers with a 5-minute sliding in-memory cache.VaultSecretRetriever.cs: Fetches secrets from HashiCorp Vault KV v2 using AppRole or Token authentication.WindowsRegistrySecretRetriever.cs: Fetches Windows DPAPI-protected registry keys (HKLM/HKCU).EnvironmentSecretRetriever.cs: Reads container environment variables.SymmetricEncryptionHelper.cs: AES-256-GCM envelope encryption for database fields and config payloads.
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:
ClientSession(Partial Class Architecture):ClientSession.cs: Main session lifecycle coordinator.ClientSession.Authorization.cs: Multi-stage RBAC authorization, caller identity resolution, and audit logging.ClientSession.BackendInitializer.cs: Asynchronous concurrent warming of downstream backend connections and tool schemas.ClientSession.ProxyForwarder.cs: Dispatches requests to downstream servers, tracks upstream GUIDs, and demultiplexes responses.ClientSession.JsonRpcRewriter.cs: UsesSystem.Text.Json.Nodes.JsonNodeto un-namespace tool names and rewrite message bodies safely without fragile string manipulation.ClientSession.NotificationBroadcaster.cs: Fan-out broadcasting of notifications across active client channels.
Routing Coordinators:SessionManager.cs: Thread-safe tracking and cleanup of active client connections.BackendConnection.cs: Manages a single upstream server connection channel, health state, and cached capabilities.SemanticSearchService.cs: Hybrid BM25 keyword matching combined with cosine similarity vector scoring.DynamicEmbeddingService.cs,OnnxEmbeddingService.cs, andApiEmbeddingService.cs: Vector embedding calculation via local CPU ONNX runtime (all-MiniLM-L6-v2) or remote OpenAI-compatible APIs.ToolRoutingManager.cs,ResourceRoutingManager.cs,PromptRoutingManager.cs: Namespacing, un-namespacing, and routing of individual MCP capabilities.
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.tsTyped 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: