Logotipo de Production-Grade MCP Server + Agentic System

Production-Grade MCP Server + Agentic System

Comunidad
FareedKhan-dev

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

EditorFareedKhan-dev
Repositorioproduction-grade-mcp-agentic-system
IdiomaPython
Forks
19
Estrellas
65
Herramientas disponibles
0
Tipo de transportestdio, streamable-http
Categorías
LicenciaMIT
Enlaces
  • Conecta herramientas a flujos de trabajo con IA

    Production-Grade MCP Server + Agentic System ofrece funciones MCP que pueden usar los clientes y agentes de IA compatibles.

  • 0 herramientas disponibles

    Explora a continuación las acciones que se pueden invocar, con sus nombres y descripciones cuando el servidor los proporcione.

  • Configuración lista para copiar

    Usa los ejemplos de instalación para configurar este servidor en tu cliente MCP preferido.

  • Indicadores de interés en el código abierto

    65 estrellas y 19 forks en el repositorio enlazado.

🏛️ 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

Instalación

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

Usa el MCP de Production-Grade MCP Server + Agentic System con varios modelos de IA

TypingMind conecta las herramientas MCP a nivel del espacio de trabajo, por lo que, una vez conectado Production-Grade MCP Server + Agentic System, puedes usarlo con distintos modelos de IA en TypingMind sin tener que configurarlo por separado para cada modelo. Puedes ejecutar MCP localmente en tu dispositivo o conectarte a la URL de un servidor MCP remoto.

Opción 1: Usa el conector local

Usa esta opción si el servidor MCP necesita acceder a archivos locales, aplicaciones o recursos privados de tu ordenador.

1

Abre los ajustes de MCP

En TypingMind, ve a Ajustes, luego a Ajustes avanzados y a Model Context Protocol, y elige Configurar conector.

  1. Abre TypingMind en tu navegador.
  2. Haz clic en el icono de Ajustes.
  3. Ve a Ajustes avanzados.
  4. Abre la sección Model Context Protocol.
  5. Haz clic en Configurar conector y elige Este dispositivo.
Pantalla de configuración del conector MCP de TypingMind con «Este dispositivo» seleccionado
2

Ejecuta el comando del conector

Elige Este dispositivo, copia el comando de TypingMind y ejecútalo en Terminal. Mantén el proceso en ejecución mientras uses MCP.

  1. Copia el comando de configuración que muestra TypingMind.
  2. Abre Terminal en macOS o Windows Terminal en Windows.
  3. Pega y ejecuta el comando.
  4. Acepta la instalación del paquete si Terminal te pide confirmación para continuar.
  5. Mantén el proceso en ejecución en la ventana de Terminal mientras uses las herramientas MCP.
3

Añade Production-Grade MCP Server + Agentic System como servidor

Cuando el estado del conector sea «Listo», haz clic en «Edita servidores» y pega la configuración del servidor MCP.

  1. Espera hasta que el estado del conector indique «Listo».
  2. Haz clic en Edita servidores.
  3. Pega la configuración del servidor MCP de Production-Grade MCP Server + Agentic System.
  4. Guarda la lista de servidores.
  5. Actualiza para comprobar que el conector sigue listo.
Ajustes de MCP de TypingMind con un servidor activo y el botón «Edita servidores»
{
  "mcpServers": {
    "production-grade-mcp-agentic-system": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Úsala con distintos modelos

Guarda la lista de servidores, abre Plugins, activa las herramientas MCP de Production-Grade MCP Server + Agentic System y selecciona cualquier modelo de IA compatible en TypingMind para usar las herramientas en el chat o asignárselas a un agente de IA.

  1. Abre la página Plugins en TypingMind.
  2. Activa las herramientas MCP de Production-Grade MCP Server + Agentic System.
  3. Inicia un chat y elige el modelo de IA que quieras usar.
  4. Usa las herramientas MCP en el chat o asígnalas a un agente de IA.
  5. Cambia a otro modelo de IA cuando lo necesites sin volver a conectar MCP.
Chat de TypingMind que usa herramientas MCP activadas con un modelo de IA seleccionado
¿Puedes usar Production-Grade MCP Server + Agentic System para ayudarme con esta tarea?
Production-Grade MCP Server + Agentic System
Claro. Lo he leído.
Esto he encontrado usando Production-Grade MCP Server + Agentic System.

Opción 2: Añade la URL de un servidor MCP

Usa esta opción si Production-Grade MCP Server + Agentic System ya está alojado en un servidor remoto o si tu equipo quiere un conector compartido al que puedan acceder varios usuarios.

1

Abre Conectores MCP

En TypingMind, ve a Plugins, abre Conectores MCP y elige Añadir URL.

  1. Abre TypingMind en tu navegador.
  2. Ve a Plugins.
  3. Abre Conectores MCP.
  4. Haz clic en Añadir URL.
Formulario de TypingMind para añadir la URL de un servidor MCP personalizado
2

Pega la URL del servidor

Introduce la URL del servidor MCP facilitada por el proveedor en el campo URL del servidor. Añade un nombre de conexión, una descripción, un icono, cabeceras HTTP personalizadas o la configuración del cliente OAuth si el servidor los requiere.

  1. Pega la URL del servidor MCP facilitada por el proveedor en el campo URL del servidor.
  2. Introduce un nombre para la conexión de Production-Grade MCP Server + Agentic System.
  3. Añade una descripción y un icono si quieres que sea más fácil de identificar.
  4. Añade cabeceras HTTP personalizadas o los datos del cliente OAuth si el servidor requiere autenticación.
3

Crea la conexión

Haz clic en Crear conexión, vuelve a la lista de plugins y comprueba que la nueva conexión MCP esté activa.

  1. Haz clic en Crear conexión.
  2. Vuelve a la lista de conectores MCP.
  3. Comprueba que la conexión de Production-Grade MCP Server + Agentic System aparezca como activa.
  4. Actualiza la lista de plugins si la conexión no aparece de inmediato.
4

Cambia de modelo sin volver a conectar

Inicia un chat con tu modelo preferido, activa las herramientas de Production-Grade MCP Server + Agentic System desde Plugins y cambia de modelo cuando lo necesites. La conexión MCP seguirá disponible en el espacio de trabajo de TypingMind.

  1. Inicia un nuevo chat en TypingMind.
  2. Selecciona el modelo de IA que quieras usar.
  3. Activa las herramientas de Production-Grade MCP Server + Agentic System desde Plugins.
  4. Pide al modelo que use la herramienta cuando sea necesario.
  5. Cambia a otro modelo de IA y reutiliza la misma conexión MCP.
Chat de TypingMind que usa herramientas MCP activadas con un modelo de IA seleccionado
¿Puedes usar Production-Grade MCP Server + Agentic System para ayudarme con esta tarea?
Production-Grade MCP Server + Agentic System
Claro. Lo he leído.
Esto he encontrado usando Production-Grade MCP Server + Agentic System.

Preguntas frecuentes

¿Para qué sirve el servidor MCP Production-Grade MCP Server + Agentic System?

Production-Grade MCP Server + Agentic System es un servidor MCP que permite a los clientes de IA compatibles conectarse a herramientas y contexto externos. En TypingMind, basta con añadir este servidor MCP una vez para que sus herramientas estén disponibles en tu espacio de trabajo de IA.

¿Puedo usar el servidor MCP Production-Grade MCP Server + Agentic System con varios modelos de IA en TypingMind?

Sí. TypingMind conecta las herramientas MCP a nivel del espacio de trabajo, por lo que puedes usar Production-Grade MCP Server + Agentic System con distintos modelos de IA, como Claude, ChatGPT, Gemini u otros que hayas configurado en TypingMind, sin configurar el servidor MCP por separado para cada modelo.

¿Por qué usar el conector MCP de Production-Grade MCP Server + Agentic System con TypingMind?

TypingMind es una de las mejores interfaces de chat con LLM porque reúne varios modelos de IA, prompts, plugins, agentes de IA, claves de API y herramientas MCP en un solo espacio de trabajo. Con Production-Grade MCP Server + Agentic System conectado, puedes usar sus herramientas MCP con tus modelos preferidos y mantener organizado tu flujo de trabajo de chat en TypingMind.

¿Cómo conecto el servidor MCP Production-Grade MCP Server + Agentic System a TypingMind?

Puedes conectar Production-Grade MCP Server + Agentic System en TypingMind con el conector MCP local o añadiendo la URL de un servidor MCP remoto. Usa el conector local cuando el servidor necesite acceder a archivos, aplicaciones o recursos privados de tu dispositivo, y una URL de servidor cuando el servidor MCP esté alojado de forma remota.

¿Qué herramientas ofrece el servidor MCP Production-Grade MCP Server + Agentic System en TypingMind?

Production-Grade MCP Server + Agentic System ofrece funciones MCP que puedes activar desde la página Plugins de TypingMind y usar en el chat o asignar a agentes de IA.

¿Tengo que compartir mis claves de API con TypingMind para usar el servidor MCP Production-Grade MCP Server + Agentic System?

No. TypingMind prioriza el funcionamiento local y te permite mantener el control de tus proveedores de modelos, claves de API, prompts y configuración MCP. Si Production-Grade MCP Server + Agentic System requiere autenticación, añade las cabeceras, los ajustes de OAuth o la configuración local necesarios para ese servidor MCP al crear la conexión.

Servidores MCP relacionados

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇