Logo vun Production-Grade MCP Server + Agentic System

Production-Grade MCP Server + Agentic System

Communautéit
FareedKhan-dev

Building a Production-Grade MCP Server Architecture with a Multi-Agent System

EditeurFareedKhan-dev
Repositoryproduction-grade-mcp-agentic-system
SproochPython
Forks
19
Stären
65
Disponibel Tools
0
Transporttypstdio, streamable-http
Kategorien
LizenzMIT
Linken
  • Tools mat KI-Workflows verbannen

    Production-Grade MCP Server + Agentic System stellt MCP-Funktioune bereit, déi vu kompatibele KI-Clienten a KI-Agente kënne benotzt ginn.

  • 0 disponibel Tools

    Kuckt Iech déi opruffbar Aktiounen hei drënner un, mat Nimm a Beschreiwungen, wa se vum Server geliwwert ginn.

  • Konfiguratioun fir ze kopéieren

    Benotzt d'Installatiounsbeispiller, fir dëse Server an Ärem bevorzugte MCP-Client ze konfiguréieren.

  • Indicateure fir Open Source

    65 Stären an 19 Forks aus dem verlinkte Repository.

🏛️ Production-Grade MCP Server + Agentic System

A reference implementation of an MCP server designed to actually ship

Multi-tenant · Authenticated · Observable · Rate-limited · Cached · Circuit-broken · Governed

Python 3.11+ MCP 2026 License: MIT Docker


📖 Full Step-by-Step Blog Walkthrough

This repository is the companion codebase for a long-form blog post that walks through every single component end to end, with every line of code explained in context. Start there if you want to understand the "why" behind the architecture before reading the code.

🔗 Building a Production-Grade MCP Server Architecture with Agentic System →


🎯 What This Is

Most MCP tutorials end with a @tool decorator that returns "hello world". That is fine for a demo. It is not what ships.

This repository is a reference implementation of an MCP server designed to run in production: multi-tenant, authenticated, observable, rate-limited, cached, circuit-broken, and governed. It exposes a company's heterogeneous data layer (Postgres, Elasticsearch, S3, vector DB) to AI agents as a single, secure tool surface, and ships with a four-agent support copilot (Planner → Retriever → Synthesizer → Critic) that uses it end to end.

The codebase is deliberately organised around twelve components that keep showing up on the 3 AM pager when teams skip them. Each one lives in its own module and can be read, replaced, or extended independently.


🏗️ Architecture Overview

The complete production-grade system: MCP server dispatch pipeline on the right, four-agent orchestrator on the left, data plane on top, observability on the bottom, identity and governance as crosscutting concerns.


🧩 The 12 Components

#ComponentLives inWhat it gives you
1🚪 Transport & Session Layerserver.pystdio for local, Streamable HTTP for remote, horizontal-scale-friendly sessions
2🔐 Authentication Serverauth/oauth.pyOAuth 2.1 + PKCE, short-lived JWTs, JWKS validation
3⚖️ Authorization & Policy Engineauth/policy.pyTool-level RBAC, tenant-scoped ABAC, deny-by-default
4📚 Tool Registry & Discoverytools/registry.pyDynamic toolsets, .well-known capability metadata
5✅ Input Validation Layervalidation/schemas.pyPydantic schemas, enum constraints, agent-adversarial input as default threat model
6🔧 Tool Execution Enginetools/base.pyThree-level hierarchy (atomic / composed / workflow)
7🔄 Circuit Breaker & Retryreliability/Closed → open → half-open, Adaptive Timeout Budget Allocation
8🚦 Rate Limiting & Quotasratelimit/limiter.pyRedis token-bucket (Lua-atomic), per-tenant and per-tool
9⚡ Caching Layercache/manager.pyTwo-tier (L1 in-process, L2 Redis), stampede prevention
10🧱 Structured Error Frameworkerrors/framework.pyMachine-readable errors with retryable and hint fields
11🔭 Observability Stackobservability/OpenTelemetry traces, Prometheus metrics, audit logs
12🛡️ Governance & Multi-Tenancygovernance/Tenant isolation, approval gates, outbound HTTP allowlisting

📖 Diving Deeper, Section by Section

Each diagram below links back to the corresponding section in the blog, where every line of code is walked through in detail.

📦 Data Persistence Layer

Postgres + Row-Level Security · Tenant isolation at the DB layer

🚪 Transport & Session Layer

Dual transport · Stateless session · Middleware chain

🔐 Authentication, Policy & Governance

OAuth 2.1 · YAML policies · Human-in-the-loop approvals

🔧 Tool Execution Engine

Three-level hierarchy · Atomic · Composed · Workflow

🔄 Reliability Layer

Circuit breakers · Retry with jitter · ATBA budget allocator

⚡ Rate Limiting & Caching

Redis token bucket · Two-tier cache · Stampede lock

🔭 Observability Stack

OpenTelemetry · Prometheus · Audit logs · One trace ID

🤖 Multi-Agentic Architecture

Four-agent design · Planner · Retriever · Synthesizer · Critic

🎼 The Orchestrator Flow

End-to-end agent orchestration with one bounded revise loop


🚀 Quick Start

Prerequisites

  • Docker & Docker Compose
  • Python 3.11+ (only for running the CLI locally)
  • An Anthropic API key (for the agent layer)

1. Clone and Configure

bash
git clone https://github.com/FareedKhan-dev/production-grade-mcp-agentic-system.git
cd production-grade-mcp-agentic-system
cp .env.example .env

Edit .env and set at minimum:

  • ANTHROPIC_API_KEY — for the agent layer
  • ATLAS_AUTH_JWKS_URL — your OAuth 2.1 provider's JWKS endpoint (or leave default for dev)

2. Bring Up the Stack

bash
docker compose up -d

That brings up the full local environment:

ServiceURLWhat it is
🏛️ MCP Serverhttp://localhost:8080/mcpStreamable HTTP endpoint
🔍 Discoveryhttp://localhost:8080/.well-known/mcp-serverUnauthenticated capability metadata
📊 Metricshttp://localhost:8080/metricsPrometheus scrape target
❤️ Healthhttp://localhost:8080/healthzLiveness probe
🔭 Jaegerhttp://localhost:16686Distributed tracing UI
📈 Grafanahttp://localhost:3000Metrics dashboards (admin / admin)
🗄️ MinIO Consolehttp://localhost:9001S3-compatible storage UI

3. Run the Support Copilot CLI

bash
pip install -e .

export ATLAS_MCP_URL=http://localhost:8080
export ATLAS_MCP_TOKEN=dev-token
export ATLAS_TENANT=acme
export ANTHROPIC_API_KEY=sk-ant-...

atlas-copilot "Why was the refund on order o_9002 for CUST-1001 delayed?"

You will see the four agents run end-to-end, the final draft printed with [S1][S2] citations, and a full trace summary including token counts, tool calls, and the run_id that ties back to Jaeger.

4. Connect from Claude Desktop / Cursor

Add this to your MCP host config:

json
{
  "mcpServers": {
    "production-mcp": {
      "type": "http",
      "url": "http://localhost:8080/mcp",
      "headers": {
        "Authorization": "Bearer ${ATLAS_MCP_TOKEN}",
        "X-Tenant-Id": "acme"
      }
    }
  }
}

📂 Repository Structure

.
├── 📄 README.md
├── 🐳 docker-compose.yml          # Full local stack: app + data + observability
├── 🐳 Dockerfile                  # Two-stage build, non-root runtime
├── 📜 LICENSE
├── 📦 pyproject.toml              # Dependencies, dev tools, CLI entry points
├── ⚙️  .env.example                # Every setting documented by component
│
├── 🔧 config/                     # Runtime configuration (hot-reloadable)
│   ├── http_allowlist.yaml       # Per-tenant outbound HTTP allowlist
│   └── policy.yaml               # YAML-driven authorization policies
│
├── 🚢 deploy/                     # Deployment sidecar configs
│   ├── otel/config.yaml          # OpenTelemetry Collector pipeline
│   ├── prometheus/prometheus.yml # Prometheus scrape targets
│   └── sql/init.sql              # Schema + RLS policies + seed data
│
├── 📚 docs/                       # Deep-dive documentation
│   ├── AGENT_SYSTEM.md           # Multi-agent orchestrator internals
│   ├── ARCHITECTURE.md           # The 12 components in detail
│   └── DEPLOYMENT.md             # K8s, Cloudflare Workers, bare-metal
│
├── 🧠 src/atlas_mcp/              # Main application source
│   ├── config.py                 # Centralized typed settings
│   ├── server.py                 # ⚡ Component 1: Transport & dispatch
│   │
│   ├── 🤖 agents/                 # Four-agent support copilot
│   │   ├── planner.py            # Emits retrieval plan JSON
│   │   ├── retriever.py          # Bounded tool-calling loop
│   │   ├── synthesizer.py        # Drafts reply with citations
│   │   ├── critic.py             # Approves or sends one revise
│   │   ├── orchestrator.py       # Wires the four agents together
│   │   ├── mcp_client.py         # Thin JSON-RPC MCP client
│   │   ├── memory.py             # STM (Redis) + LTM (vector)
│   │   └── cli.py                # atlas-copilot CLI entry point
│   │
│   ├── 🔐 auth/                   # Components 2 + 3
│   │   ├── oauth.py              # JWT + JWKS validation
│   │   ├── middleware.py         # Bearer token extraction
│   │   └── policy.py             # YAML-driven policy engine
│   │
│   ├── 🛡️  governance/             # Component 12
│   │   ├── tenant.py             # Tenant pinning middleware
│   │   └── approval.py           # Human-in-the-loop gate
│   │
│   ├── 🔧 tools/                  # Components 4 + 6
│   │   ├── registry.py           # In-memory tool index + discovery
│   │   ├── base.py               # Tool abstract base + metadata
│   │   ├── atomic/               # Level 1: one backend each
│   │   ├── composed/             # Level 2: deterministic chains
│   │   └── workflow/             # Level 3: multi-step procedures
│   │
│   ├── 🔄 reliability/            # Component 7
│   │   ├── circuit_breaker.py    # 3-state machine per tool
│   │   ├── retry.py              # Exponential backoff + jitter
│   │   └── atba.py               # Adaptive Timeout Budget Allocation
│   │
│   ├── 🚦 ratelimit/              # Component 8
│   │   └── limiter.py            # Redis token bucket (Lua-atomic)
│   │
│   ├── ⚡ cache/                   # Component 9
│   │   └── manager.py            # L1 + L2 cache with stampede lock
│   │
│   ├── 🧱 errors/                 # Component 10
│   │   └── framework.py          # Structured Error Recovery (SERF)
│   │
│   ├── 🔭 observability/          # Component 11
│   │   ├── tracing.py            # OpenTelemetry spans
│   │   ├── metrics.py            # Prometheus instruments
│   │   └── audit.py              # Structured JSONL audit log
│   │
│   └── ✅ validation/             # Component 5
│       └── schemas.py            # Tool call envelope
│
└── 🧪 tests/                      # Narrow tests, load-bearing properties
    ├── test_circuit_breaker.py   # State machine transitions
    ├── test_errors.py            # SERF wire format + retry semantics
    └── test_policy.py            # Deny-beats-allow + default-deny

🎨 Tech Stack

LayerTechnology
LanguagePython 3.11+
Web frameworkStarlette + Uvicorn
MCP SDKmcp>=1.2.0
AuthPyJWT + Authlib (OAuth 2.1 resource server)
ValidationPydantic v2 + Pydantic Settings
Databaseasyncpg (PostgreSQL 16 with RLS)
SearchElasticsearch 8 (async client)
Vector DBQdrant
Object storageaioboto3 (MinIO / S3)
Cache + queuesRedis 7 (redis[hiredis])
Reliabilitytenacity (retries) + custom breaker + custom ATBA
TracingOpenTelemetry SDK + OTLP exporter
Metricsprometheus_client
Loggingstructlog (JSON)
LLMAnthropic Messages API (Claude)

🧪 Testing

The test suite is deliberately narrow, covering the three load-bearing safety properties:

bash
pip install -e ".[dev]"
pytest -v
  • test_circuit_breaker.py — state machine transitions, retryable vs deterministic error classification
  • test_errors.py — SERF wire format, retry semantics, MCP-level error data
  • test_policy.py — default-deny, deny-beats-allow, glob matching, PII condition blocking

🛣️ Production Deployment

For running this in an actual production environment (managed Postgres, real OAuth provider, SIEM integration, Kubernetes), see docs/DEPLOYMENT.md.

Key swaps between local dev and production:

Local (docker-compose)Production
Dev JWT issuerWorkOS AuthKit / Auth0 / Keycloak
MinIOAWS S3 / GCS / Azure Blob
Local PostgresAWS RDS / Cloud SQL / Supabase
Redis containerUpstash / ElastiCache / MemoryDB
Local OTel collectorDatadog / Honeycomb / Grafana Cloud
File-based audit logSplunk / Chronicle / SIEM of choice

📚 Documentation


📜 License

MIT. See LICENSE.


⭐ If this helped you, please consider starring the repo

Built with ☕ and a lot of 3 AM debugging

📖 Read the full blog walkthrough · 🐛 Report an issue · 💬 Start a discussion

Installatioun

TypingMind
{
  "mcpServers": {
    "production-grade-mcp-agentic-system": {
      "command": "atlas-copilot",
      "args": [
        "{{config.QUERY}}"
      ],
      "env": {
        "QUERY": "<QUERY>"
      }
    }
  }
}

Production-Grade MCP Server + Agentic System MCP mat verschiddene KI-Modeller benotzen

TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Soubal Production-Grade MCP Server + Agentic System verbonnen ass, kënnt Dir et mat verschiddene KI-Modeller an TypingMind benotzen, amplaz et fir all Modell separat anzeriichten. Dir kënnt MCP lokal op Ärem Apparat ausféieren oder Iech mat enger Remote-MCP-Server-URL verbannen.

Optioun 1: De lokale Connector benotzen

Benotzt dës Optioun, wann den MCP-Server Zougrëff op lokal Fichieren, Appen oder privat Ressourcen op Ärem Computer brauch.

1

D'MCP-Astellungen opmaachen

Gitt an TypingMind op „Astellungen“, „Erweidert Astellungen“, dann op „Model Context Protocol“ a wielt „Connector ariichten“.

  1. Maacht TypingMind an Ärem Browser op.
  2. Klickt op d'Astellungssymbol.
  3. Gitt op „Erweidert Astellungen“.
  4. Maacht d'Sektioun „Model Context Protocol“ op.
  5. Klickt op „Connector ariichten“ a wielt „Dësen Apparat“.
Ariichtungsbildschierm vum TypingMind-MCP-Connector mat „Dësen Apparat“ ausgewielt
2

De Connector-Befeel ausféieren

Wielt „Dësen Apparat“, kopéiert de Befeel aus TypingMind a féiert en am Terminal aus. Loosst de Prozess lafen, wärend Dir MCP benotzt.

  1. Kopéiert den Ariichtungsbefeel, deen TypingMind uweist.
  2. Maacht Terminal op macOS oder Windows Terminal op Windows op.
  3. Pescht de Befeel an a féiert en aus.
  4. Bestätegt d'Installatioun vum Package, wann den Terminal Iech freet, ob Dir weiderfuere wëllt.
  5. Loosst den Terminal an de Prozess doranner lafen, wärend Dir MCP-Tools benotzt.
3

Production-Grade MCP Server + Agentic System als Server derbäisetzen

Wann de Connector-Status „Prett“ ass, klickt op „Serveren änneren“ a pescht d'MCP-Serverkonfiguratioun an.

  1. Waart, bis de Connector-Status „Prett“ weist.
  2. Klickt op „Serveren änneren“.
  3. Pescht d'MCP-Serverkonfiguratioun vu Production-Grade MCP Server + Agentic System an.
  4. Späichert d'Serverlëscht.
  5. Aktualiséiert, wann Dir kontrolléiere wëllt, ob de Connector nach ëmmer prett ass.
MCP-Astellunge vun TypingMind mat aktivem Server an dem Knäppchen „Serveren änneren“
{
  "mcpServers": {
    "production-grade-mcp-agentic-system": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

D'Verbindung mat verschiddene Modeller benotzen

Späichert d'Serverlëscht, maacht „Plugins“ op an aktivéiert d'MCP-Tools vu Production-Grade MCP Server + Agentic System. Wielt dann e belibegen ënnerstëtzte KI-Modell an TypingMind a benotzt d'Tools am Chat oder weist se engem KI-Agent zou.

  1. Maacht d'Säit „Plugins“ an TypingMind op.
  2. Aktivéiert d'MCP-Tools vu Production-Grade MCP Server + Agentic System.
  3. Start e Chat a wielt de KI-Modell, deen Dir benotze wëllt.
  4. Benotzt d'MCP-Tools am Chat oder weist se engem KI-Agent zou.
  5. Wiesselt bei Bedarf op en anere KI-Modell, ouni MCP nei ze verbannen.
TypingMind-Chat mat aktivéierte MCP-Tools an engem ausgewielte KI-Modell
Hëlleft Dir mir bei dëser Aufgab mat Production-Grade MCP Server + Agentic System?
Production-Grade MCP Server + Agentic System
Jo. Ech hunn et gelies.
Dat hunn ech mat Production-Grade MCP Server + Agentic System fonnt.

Optioun 2: Eng MCP-Server-URL derbäisetzen

Benotzt dës Optioun, wann Production-Grade MCP Server + Agentic System scho remote gehost gëtt oder Är Ekipp ee gemeinsame Connector wëllt, op dee méi Benotzer kënnen zougräifen.

1

MCP-Connectoren opmaachen

Gitt an TypingMind op „Plugins“, maacht „MCP-Connectoren“ op a wielt dann „URL derbäisetzen“.

  1. Maacht TypingMind an Ärem Browser op.
  2. Gitt op „Plugins“.
  3. Maacht „MCP-Connectoren“ op.
  4. Klickt op „URL derbäisetzen“.
TypingMind-Formulaire fir eng benotzerdefinéiert MCP-Server-URL derbäizesetzen
2

D'Server-URL apeschen

Gitt d'MCP-Server-URL vum Ubidder am Feld „Server-URL“ an. Setzt e Verbindungsnumm, eng Beschreiwung, e Symbol, benotzerdefinéiert HTTP-Headeren oder OAuth-Clientastellungen derbäi, wann de Server se erfuerdert.

  1. Pescht d'MCP-Server-URL vum Ubidder an d'Feld „Server-URL“.
  2. Gitt en Numm fir d'Verbindung mat Production-Grade MCP Server + Agentic System an.
  3. Setzt eng Beschreiwung an e Symbol derbäi, fir d'Verbindung méi einfach erëmzeerkennen.
  4. Setzt benotzerdefinéiert HTTP-Headeren oder OAuth-Clientdetailer derbäi, wann de Server eng Authentifizéierung erfuerdert.
3

D'Verbindung erstellen

Klickt op „Verbindung erstellen“, gitt dann zeréck op d'Plugin-Lëscht a kontrolléiert, ob déi nei MCP-Verbindung aktiv ass.

  1. Klickt op „Verbindung erstellen“.
  2. Gitt zeréck op d'Lëscht vun de MCP-Connectoren.
  3. Kontrolléiert, ob d'Verbindung mat Production-Grade MCP Server + Agentic System als aktiv ugewise gëtt.
  4. Aktualiséiert d'Plugin-Lëscht, wann d'Verbindung net direkt ugewise gëtt.
4

Modeller wiesselen ouni nei ze verbannen

Start e Chat mat Ärem bevorzugte Modell, aktivéiert d'Tools vu Production-Grade MCP Server + Agentic System ënner „Plugins“ a wiesselt bei Bedarf op en anere Modell. D'MCP-Verbindung bleift am TypingMind-Aarbechtsberäich disponibel.

  1. Start en neie Chat an TypingMind.
  2. Wielt de KI-Modell, deen Dir benotze wëllt.
  3. Aktivéiert d'Tools vu Production-Grade MCP Server + Agentic System ënner „Plugins“.
  4. Biet de Modell, den Tool ze benotzen, wann néideg.
  5. Wiesselt op en anere KI-Modell a benotzt déiselwecht MCP-Verbindung weider.
TypingMind-Chat mat aktivéierte MCP-Tools an engem ausgewielte KI-Modell
Hëlleft Dir mir bei dëser Aufgab mat Production-Grade MCP Server + Agentic System?
Production-Grade MCP Server + Agentic System
Jo. Ech hunn et gelies.
Dat hunn ech mat Production-Grade MCP Server + Agentic System fonnt.

Heefeg gestallte Froen

Fir wat gëtt de MCP-Server Production-Grade MCP Server + Agentic System benotzt?

Production-Grade MCP Server + Agentic System ass e MCP-Server, deen et kompatibele KI-Clienten erlaabt, sech mat externen Tools a Kontext ze verbannen. An TypingMind kënnt Dir dëse MCP-Server eemol derbäisetzen a seng Tools an Ärem KI-Aarbechtsberäich zur Verfügung stellen.

Kann ech Production-Grade MCP Server + Agentic System MCP mat méi KI-Modeller an TypingMind benotzen?

Jo. TypingMind verbënnt MCP-Tools um Niveau vum Aarbechtsberäich. Sou kënnt Dir Production-Grade MCP Server + Agentic System mat verschiddene KI-Modeller wéi Claude, ChatGPT, Gemini oder anere Modeller benotzen, déi Dir an TypingMind konfiguréiert hutt, ouni de MCP-Server fir all Modell separat anzeriichten.

Firwat Production-Grade MCP Server + Agentic System MCP mat TypingMind benotzen?

TypingMind ass eng vun de beschte Benotzeruewerfläche fir LLM-Chat, well et méi KI-Modeller, Prompts, Plugins, KI-Agenten, API-Schlësselen a MCP-Tools an engem Aarbechtsberäich zesummebréngt. Wann Production-Grade MCP Server + Agentic System verbonnen ass, kënnt Dir seng MCP-Tools mat Äre bevorzugte Modeller benotzen a gläichzäiteg Är Chataarbecht an TypingMind organiséieren.

Wéi verbannen ech Production-Grade MCP Server + Agentic System MCP mat TypingMind?

Dir kënnt Production-Grade MCP Server + Agentic System iwwer de lokale MCP-Connector oder iwwer d'URL vun engem Remote-MCP-Server mat TypingMind verbannen. Benotzt de lokale Connector, wann de Server Zougrëff op Fichieren, Apps oder privat Ressourcen op Ärem Apparat brauch, an eng Server-URL, wann de MCP-Server op Distanz gehost gëtt.

Wéi eng Tools stellt Production-Grade MCP Server + Agentic System MCP an TypingMind zur Verfügung?

Production-Grade MCP Server + Agentic System stellt MCP-Funktiounen zur Verfügung, déi Dir op der Plugins-Säit vun TypingMind aktivéiere kënnt, fir se am Chat ze benotzen oder KI-Agenten zouzeweisen.

Muss ech meng API-Schlëssele mat TypingMind deelen, fir Production-Grade MCP Server + Agentic System MCP ze benotzen?

Nee. TypingMind setzt op lokal Veraarbechtung a léisst Iech d'Kontroll iwwer Är Modellubidder, API-Schlësselen, Prompts a MCP-Konfiguratioun. Wann Production-Grade MCP Server + Agentic System eng Authentifizéierung verlaangt, setzt déi néideg Headeren, OAuth-Astellungen oder lokal Konfiguratioun fir dee MCP-Server derbäi, wann Dir d'Verbindung erstallt.

Änlech MCP-Serveren

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇