# ContextForge Architecture

An open-source registry and proxy that federates MCP, A2A, and REST/gRPC APIs with centralized governance, discovery, and observability.

56
Services
19
Routers
15
Middleware
6
Transports
55
DB Models
50
ADRs
FastAPI ASGI Framework SQLAlchemy ORM Pydantic Validation PostgreSQL / SQLite Redis Cache & Pub/Sub orjson Serialization OpenTelemetry Tracing Prometheus Metrics Helm / K8s / OCI
🌐 Client Layer
External
Browsers, CLI tools, AI agents, and federated gateways connect through multiple protocols.
Web Browsers Claude Code MCP Clients A2A Agents Federated Peers REST Clients gRPC Clients
▼
⚡ Transport Layer
6 Protocols
Multi-protocol ingress supporting all major MCP transports with protocol negotiation and translation.
HTTP/JSON-RPC 2.0 Server-Sent Events WebSocket Streamable HTTP STDIO gRPC Rust MCP Runtime
▼
🛡 Middleware Pipeline
15 Components
Ordered pipeline of cross-cutting concerns: authentication, authorization, logging, validation, and security headers.
Auth Extraction HTTP Auth Token Scoping RBAC Enforcement Request Logging Observability Security Headers Correlation ID Compression Protocol Version Validation Token Usage DB Query Logging Request Context Path Filter
▼
🔀 Router Layer
19 Routers
HTTP endpoint definitions, each focused on a specific API domain: auth, MCP entities, admin, LLM, observability.
Auth Email Auth OAuth SSO Tokens RBAC Teams LLM Chat LLM Admin LLM Config LLM Proxy Observability Log Search Metrics Cancellation Well-Known Server Well-Known Reverse Proxy ToolOps
▼
⚙ Service Layer
56 Services
Business logic organized into single-responsibility services: MCP entities, auth, AI/agents, observability, and infrastructure.
Tool Service Resource Service Prompt Service Server Service Gateway Service A2A Service Session Pool OAuth Manager SSO Service Team Management Encryption Observability Metrics Buffer Import/Export Plugin Service +42 more
▼
💾 Data Layer
3 Backends
Persistent storage with SQLAlchemy ORM, pluggable cache backends, and session management.
PostgreSQL SQLite Redis In-Memory Cache Alembic Migrations Connection Pooling 55 ORM Models Session Registry
⇅
🧩 Plugin Framework
Cross-Cutting
Extensible plugin system with hooks into every layer: MCP operations, HTTP auth, policy enforcement, and agent integration. Supports in-process Python, remote MCP, gRPC, and STDIO transports.
Tool Hooks Resource Hooks Prompt Hooks Agent Hooks HTTP Hooks Policy Hooks Plugin Registry Plugin Manager External: MCP External: gRPC External: Unix/STDIO

## Architecture Diagrams

Visual representations of the ContextForge system from different perspectives.

## Component Explorer

Browse all architecture components. Click any card for details.

Request Lifecycle
Trace how a request flows through the ContextForge architecture

## Service Dependency Graph

Interactive force-directed graph of service relationships. Drag nodes to explore. Scroll to zoom.

MCP Core Auth Observability AI/Agents Data Infrastructure

## Security Architecture

Two-layer security model: Token Scoping (visibility) + RBAC (permissions)

### 🔑 Authentication

Multiple authentication strategies with secure defaults.

- JWT tokens (HS256, RS256) with audience verification
- Email/password with Argon2id hashing
- OAuth 2.0 authorization code flow with PKCE
- SSO/OIDC (Keycloak, Entra ID, Google, GitHub)
- API tokens with granular scoping
- Session-based persistence with DB authority

### 🛡 Token Scoping (Layer 1)

Controls what resources a caller can see.

- API tokens: JWT teams claim is sole authority
- Session tokens: DB is authority, JWT only narrows
- Missing teams key = public-only (secure default)
- Admin bypass requires both teams: null + is_admin: true
- Fail-closed on any ambiguity

### 🔒 RBAC (Layer 2)

Controls what actions a caller can do.

- platform_admin — global wildcard access
- team_admin — team management + read/execute
- developer — tools read/execute, resources read
- viewer — read-only access to team resources
- Permission audit logging on all changes

### 🔐 Encryption & Secrets

Defense in depth for data at rest and in transit.

- AES encryption for stored tokens and secrets
- mTLS support for plugin-to-gateway communication
- SSL/TLS context caching for performance
- Argon2id password hashing (time=3, mem=64MB)
- Secure cookie flags (httponly, secure, samesite)

### ✅ Input Validation

Defense at system boundaries with layered validation.

- Pydantic schema validation on all inputs
- JSON-RPC 2.0 structure validation
- Content type and size checking
- Dangerous pattern detection (injection, XSS)
- Jinja2 sandboxed template rendering

### 🌐 HTTP Security

Comprehensive response hardening and transport security.

- HSTS with long max-age
- Content Security Policy (CSP)
- X-Frame-Options, X-Content-Type-Options
- CORS with domain whitelisting
- Referrer-Policy and XSS-Protection

## Data Layer

55 SQLAlchemy ORM models across authentication, MCP entities, observability, and configuration.

## Plugin Architecture

Extensible hook-based system with support for in-process Python, remote MCP, gRPC, and STDIO transports.

### Plugin Manager & Registry

Central lifecycle management: discovery, loading, validation, configuration, and health monitoring.

framework/manager.py framework/registry.py framework/loader/ framework/settings.py framework/validators.py
▼

### Hook System

Event-driven hooks into every MCP operation, HTTP request lifecycle, and policy evaluation.

tool_pre_invoke
tool_post_invoke
resource_pre_fetch
resource_post_fetch
prompt_pre_fetch
prompt_post_fetch
agent_pre_invoke
agent_post_invoke
http_pre_request
http_auth_resolve
http_auth_check
http_post_request
▼

### Plugin Transports

Plugins can run in-process or communicate over network protocols for language-agnostic extensibility.

In-Process (Python) Remote MCP Server gRPC (Protobuf) Unix Socket / STDIO Streamable HTTP
▼

### Execution Modes

Fine-grained control over plugin behavior per-hook with four enforcement levels.

enforce — block on violations enforce_ignore_error — block violations, skip errors permissive — log only disabled — skip execution
▼

### Policy Engine

Declarative policy evaluation with structured payloads, audit trails, and violation reporting.

plugins/policy.py Structured Payloads Violation Reports Audit Integration

## Protocol Architecture

ContextForge supports 6 transport protocols, the MCP JSON-RPC specification, A2A agent protocol, and OAuth 2.0.

### Transport Protocols

### MCP JSON-RPC Methods (22 methods)

All methods follow the JSON-RPC 2.0 specification over any supported transport. Dispatched in mcpgateway/main.py.

### Higher-Level Protocols

## Architecture Decision Records

50 ADRs documenting key architectural choices, technology selections, and design trade-offs.

## API Surface

REST endpoints organized by router, plus MCP JSON-RPC protocol methods.

### REST API Endpoints by Router

Router | File | GET | POST | PUT | DELETE | PATCH | Total
--- | --- | --- | --- | --- | --- | --- | ---

### Core Application Routes (main.py)

Method | Path | Description
--- | --- | ---

### MCP Protocol Endpoints

Transport | Path | Description
--- | --- | ---

## Technology Stack

Core dependencies powering ContextForge, organized by domain.

## Configuration Reference

Key environment variables organized by domain. Click a category to expand. Sources: .env.example | mcpgateway/config.py

## Development & CI/CD

Development workflow, 18 GitHub Actions workflows, code quality gates, and the 16-phase release process.

### CI/CD Pipeline

### GitHub Actions Workflows (18)

### Code Quality Gates

### Release Process (16 Phases)

Semantic versioning with RC support. Version bumped via bump2version across 4 canonical files.

### Testing Matrix