MCP Integration
MCP Integration Guide
Sección titulada «MCP Integration Guide»Companion del AI-First Engineering Framework v6.5
Version: 2.0.0 | Fecha: Marzo 2026 Fuentes: Anthropic MCP Spec (2024-2026), CIO “MCP on Executive Agenda” (Feb 2026), MCP Roadmap Blog (Mar 2026), The New Stack “MCP Growing Pains” (Mar 2026), CData “Enterprise MCP Adoption” (Mar 2026)
1. Qué es MCP
Sección titulada «1. Qué es MCP»Model Context Protocol (MCP) es un estándar abierto que permite a aplicaciones AI conectarse a fuentes de datos, herramientas y workflows de forma uniforme. Creado por Anthropic (Nov 2024), adoptado por OpenAI, Google, Microsoft y la industria en 2025-2026.
“MCP is suddenly on every executive agenda” — CIO.com, Feb 2026
Arquitectura
Sección titulada «Arquitectura»┌──────────────┐ MCP Protocol ┌──────────────┐│ AI Agent │◄─────────────────────►│ MCP Server ││ (Claude Code,│ JSON-RPC over │ (tu servicio)││ Cursor, │ Streamable HTTP │ ││ Copilot) │ or stdio │ - Tools │└──────────────┘ │ - Resources │ │ - Prompts │ └──────┬───────┘ │ ┌──────▼───────┐ │ Tu Sistema │ │ (DB, API, │ │ Files...) │ └──────────────┘Primitivas MCP
Sección titulada «Primitivas MCP»| Primitiva | Descripción | Ejemplo |
|---|---|---|
| Tools | Funciones invocables por el agente | search_users, deploy_service |
| Resources | Datos expuestos al agente (read-only) | Archivos, esquemas DB, configs |
| Prompts | Templates de interacción predefinidos | ”Analizar este log de errores” |
2. MCP Roadmap 2026
Sección titulada «2. MCP Roadmap 2026»El roadmap oficial prioriza 4 areas:
| Area Prioritaria | Descripcion | Status (Mar 2026) |
|---|---|---|
| Transport Evolution | Stateless horizontal scaling, session handling, Server Cards | 🔄 Activo |
| Agent Communication | Tasks primitive (SEP-1686), retry semantics, result expiry | 🔄 Activo |
| Governance Maturation | Contributor ladder, WG delegation model, charter template | 🔄 Activo |
| Enterprise Readiness | Audit trails, SSO, gateway patterns, config portability | 📋 Enterprise WG formandose |
Features individuales
Sección titulada «Features individuales»| Feature | Status (Mar 2026) | Impacto |
|---|---|---|
| Streamable HTTP transport | ✅ Estable | Reemplaza SSE, mejor para prod |
| OAuth 2.1 authentication | ✅ Estable | Auth estandar para servers remotos |
| Server Cards (.well-known) | 🔄 En progreso | Metadata descubrible para registries |
| Tasks primitive (SEP-1686) | 🔄 En progreso | Call-now / fetch-later entre agentes |
| Elicitation (human-in-loop) | ✅ Estable | Agente pide input al humano |
| Tool annotations | ✅ Estable | Metadata: readOnly, destructive, etc. |
| DPoP (SEP-1932) | 🔄 En progreso | Proof of possession para tokens |
| Workload Identity Federation (SEP-1933) | 🔄 En progreso | Identity sin secrets estaticos |
2.1 MCP Server Cards
Sección titulada «2.1 MCP Server Cards»Que son: Un estandar para exponer metadata estructurada de un MCP server via .well-known URL, permitiendo que browsers, crawlers y registries descubran las capacidades del server sin conectarse.
# Ejemplo: https://mi-mcp-server.com/.well-known/mcp-server-card.json{ "name": "project-tools", "version": "1.0.0", "description": "Herramientas del proyecto", "tools": ["get_project_config", "search_contracts", "validate_spec"], "auth": "oauth2.1", "transport": "streamable-http"}Impacto: Facilita discovery automatico de MCP servers, fundamental para marketplaces y enterprise registries.
2.2 MCP vs A2A (Agent-to-Agent Protocol)
Sección titulada «2.2 MCP vs A2A (Agent-to-Agent Protocol)»Google introdujo A2A como complemento a MCP. Son protocolos complementarios, no competidores:
| Aspecto | MCP | A2A (Google) |
|---|---|---|
| Proposito | Agent ↔ Tools/Data | Agent ↔ Agent (peer-to-peer) |
| Modelo | Cliente-servidor | Peer-to-peer con Agent Cards |
| Ejemplo | Claude Code → PostgreSQL MCP | Agent Planner → Agent Builder |
| Cuando usar | Acceso a herramientas y datos externos | Coordinacion entre agentes autonomos |
| Autor | Anthropic + comunidad (Linux Foundation) | |
| Status | Produccion (v2026-03) | Early adoption |
Recomendacion del framework:
- MCP para toda integracion agent → tools/data (nuestro caso principal).
- A2A cuando se necesite coordinacion peer-to-peer entre agentes de diferentes proveedores.
- Para orquestacion interna (mismo proyecto), los patrones de Multi-Agent Guide (Hub&Spoke, Pipeline, etc.) son suficientes sin necesidad de A2A.
2.2.1 A2A Implementation Patterns (v6.4 — GAP-11)
Sección titulada «2.2.1 A2A Implementation Patterns (v6.4 — GAP-11)»Fuentes: Google ADK A2A Protocol (Dic 2025), GuruSup “MCP vs A2A” (Mar 2026), A2A Spec v0.2 (Feb 2026), Anthropic “Building Effective Agents” (Mar 2026)
A2A esta madurando como estandar para comunicacion inter-agente cross-framework. Esta seccion documenta los patrones de implementacion para equipos que necesiten integrar agentes de diferentes proveedores o plataformas.
Conceptos Fundamentales A2A
Sección titulada «Conceptos Fundamentales A2A»┌─────────────────────────────────────────────────────────────┐│ A2A Protocol Stack │├─────────────────────────────────────────────────────────────┤│ Agent Card (discovery) → /.well-known/agent.json ││ Task Primitives → create, get, cancel, subscribe ││ Message Exchange → request/response + streaming ││ Transport → HTTPS + SSE (Server-Sent Events)││ Auth → OAuth 2.0 / API Keys │└─────────────────────────────────────────────────────────────┘Agent Card: Documento JSON que describe las capacidades de un agente. Es el equivalente A2A al tool_annotations de MCP, pero a nivel de agente completo.
# Ejemplo: Agent Card para un agente de QA# Publicar en: https://mi-servicio.com/.well-known/agent.json{ "name": "qa-evaluator-agent", "description": "Evalua calidad de codigo generado por AI contra evals definidos", "url": "https://qa-agent.mi-empresa.com/a2a", "version": "1.0.0", "capabilities": { "streaming": true, "pushNotifications": false, "stateTransitionHistory": true }, "skills": [ { "id": "code-review", "name": "AI Code Review", "description": "Revisa codigo contra standards del framework", "inputModes": ["text/plain", "application/json"], "outputModes": ["application/json"] }, { "id": "eval-execution", "name": "Eval Suite Runner", "description": "Ejecuta suite de evaluacion y reporta resultados", "inputModes": ["application/json"], "outputModes": ["application/json"] } ], "authentication": { "schemes": ["oauth2"], "credentials": "See /auth/token endpoint" }}Patron 1: Discovery + Delegation
Sección titulada «Patron 1: Discovery + Delegation»El patron mas simple: un agente orquestador descubre agentes especializados via Agent Cards y les delega tareas.
Orchestrator Agent │ ├─→ GET /.well-known/agent.json (discovery) │ ← { name: "qa-agent", skills: [...] } │ ├─→ POST /a2a/tasks (create task) │ { "skill": "code-review", "input": { "code": "..." } } │ ← { "taskId": "task-123", "status": "working" } │ ├─→ GET /a2a/tasks/task-123 (poll status) │ ← { "status": "completed", "output": { "issues": [...] } } │ └─→ Process resultsCuando usar: Integracion con agentes externos (otros equipos, vendors, open-source agents).
Cuando NO usar: Agentes internos del mismo proyecto — usar patrones Multi-Agent Guide (Hub&Spoke, Pipeline).
Patron 2: Streaming Task con SSE
Sección titulada «Patron 2: Streaming Task con SSE»Para tareas de larga duracion donde el agente remoto reporta progreso incrementalmente.
Orchestrator Remote Agent │ │ ├──POST /a2a/tasks ──────────────→│ │ (skill: "full-eval") │ │ │ │←── SSE: status="working" ───────┤ │←── SSE: progress=25% ──────────┤ │←── SSE: artifact="partial.json"─┤ │←── SSE: progress=75% ──────────┤ │←── SSE: status="completed" ────┤ │←── SSE: output={...} ──────────┤ │ │ └── Close connection │Timeout: Configurar max_task_duration en project-config.yaml (default: 300s para A2A tasks).
Patron 3: Multi-Agent Federation (A2A + MCP Hibrido)
Sección titulada «Patron 3: Multi-Agent Federation (A2A + MCP Hibrido)»Patron avanzado: combinar MCP (para tools/data) con A2A (para agentes peer).
┌─── Mi Proyecto ────────────────────────────┐│ ││ Orchestrator Agent ││ ├── MCP → PostgreSQL Server (tools) ││ ├── MCP → GitHub Server (tools) ││ ├── MCP → Framework Compliance (tools) ││ │ ││ ├── A2A → External QA Agent (peer) ││ ├── A2A → External Security Agent (peer) ││ └── A2A → Partner API Agent (peer) ││ │└─────────────────────────────────────────────┘Regla del framework: Preferir MCP para tools/data, A2A solo para agentes externos autonomos.
Security Considerations para A2A
Sección titulada «Security Considerations para A2A»| Riesgo | Mitigacion | Ref OWASP |
|---|---|---|
| Agent impersonation | Validar Agent Card con TLS + firma digital | ASI03 |
| Task injection | Input validation en cada skill, schemas estrictos | ASI01 |
| Data exfiltration via A2A | Classification-aware routing: no enviar restricted data | ASI07 |
| Runaway tasks | max_task_duration, circuit breaker, cancel endpoint | ASI09 |
| Supply chain (agentes maliciosos) | Agent Card audit, allowlist de agentes confiables | ASI04 |
Configuracion en project-config.yaml
Sección titulada «Configuracion en project-config.yaml»# Agregar en project-config.yaml si se usa A2Aintegrations: a2a: enabled: false # true si se usan agentes A2A agents: - name: "external-qa" url: "https://qa.partner.com/a2a" agent_card: "https://qa.partner.com/.well-known/agent.json" auth: "oauth2" max_task_duration: 300 # segundos allowed_skills: ["code-review", "eval-execution"] data_classification_max: "internal" # no enviar > internal security: require_tls: true verify_agent_cards: true audit_all_tasks: true rate_limit_per_agent: 100 # tasks/horaChecklist A2A por Track
Sección titulada «Checklist A2A por Track»| Actividad | Solo | Lean | Full |
|---|---|---|---|
| Evaluar necesidad de A2A | ⬜ Opcional | ⬜ Si integracion externa | ✅ Obligatorio |
| Publicar Agent Card propio | ❌ No aplica | ⬜ Si expone agentes | ✅ Si expone agentes |
| Auditar Agent Cards externos | ❌ No aplica | ✅ Antes de integrar | ✅ Antes de integrar |
| Configurar auth A2A | ❌ No aplica | ✅ OAuth 2.0 | ✅ OAuth 2.0 + mTLS |
| Monitorear tasks A2A | ❌ No aplica | ⬜ Basico | ✅ Observabilidad completa |
| Data classification routing | ❌ No aplica | ✅ Solo internal/public | ✅ Por campo/entidad |
2.2.2 AG-UI Protocol — Agent-Frontend Communication (v6.5)
Sección titulada «2.2.2 AG-UI Protocol — Agent-Frontend Communication (v6.5)»Status: On-the-Horizon — el protocolo esta en desarrollo activo. Documentado aqui para awareness y planificacion. Fuente: AG-UI Protocol specification (2025-2026), CopilotKit AG-UI Reference Implementation
AG-UI (Agent-User Interface) es un protocolo emergente para la comunicacion estandarizada entre agentes AI y frontends/UIs. Mientras MCP conecta agentes a tools/data, y A2A conecta agentes entre si, AG-UI define como un agente se comunica con el usuario a traves de la interfaz.
Relacion MCP + A2A + AG-UI
Sección titulada «Relacion MCP + A2A + AG-UI»┌─────────────────────────────────────────────────────────────────┐│ Agent Protocol Stack Completo (2026) ││ ││ ┌──────────┐ AG-UI ┌──────────┐ MCP ┌──────────┐ ││ │ Frontend │◄──────────►│ Agent │◄────────►│ Tools/ │ ││ │ (React, │ streaming │ (Claude, │ JSON-RPC│ Data │ ││ │ mobile) │ events │ GPT, │ │ (DB,API)│ ││ └──────────┘ │ custom) │ └──────────┘ ││ │ │ ││ │ │ A2A ┌──────────┐ ││ │ │◄────────►│ Other │ ││ └──────────┘ tasks │ Agents │ ││ └──────────┘ ││ ││ Frontend ← AG-UI → Agent ← MCP → Tools ││ ← A2A → Agents │└─────────────────────────────────────────────────────────────────┘Conceptos Fundamentales AG-UI
Sección titulada «Conceptos Fundamentales AG-UI»| Concepto | Descripcion | Equivalente en otros protocolos |
|---|---|---|
| Events | Streaming de eventos del agente al frontend | SSE / WebSocket messages |
| Lifecycle Events | run_started, run_finished, run_error | Agent session management |
| Text Message Events | Streaming de tokens para respuesta en tiempo real | LLM streaming output |
| Tool Call Events | Notificacion al frontend de tool calls en progreso | MCP progress notifications |
| State Events | Shared state entre agente y frontend | Context synchronization |
| Custom Events | Eventos especificos del dominio | Application-specific hooks |
AG-UI Event Flow (Ejemplo)
Sección titulada «AG-UI Event Flow (Ejemplo)»Frontend Agent MCP Server │ │ │ │── User message ────────►│ │ │ │── run_started ───────────►│(frontend) │◄── text_message_start ──│ │ │◄── text_message_content │ │ │◄── text_message_content │ │ │ │ │ │◄── tool_call_start ─────│── MCP tool call ─────────►│ │ (show "Searching...") │ │ │ │◄── MCP tool result ───────│ │◄── tool_call_end ───────│ │ │ (show results) │ │ │ │ │ │◄── text_message_content │ │ │◄── text_message_end ────│ │ │◄── run_finished ────────│ │Cuando Usar AG-UI (Decision Tree)
Sección titulada «Cuando Usar AG-UI (Decision Tree)»¿Tu agente tiene un frontend dedicado?├── NO (solo CLI/API) → No necesitas AG-UI└── SI → ¿Necesitas UX rica durante agent processing? ├── NO (show spinner, wait for result) → No necesitas AG-UI └── SI → ¿Que necesitas? ├── Streaming text → SSE basico es suficiente ├── Progress de tool calls + streaming → **AG-UI recomendado** ├── Shared state agent-frontend → **AG-UI recomendado** └── Human-in-the-loop via UI → **AG-UI recomendado**Configuracion en project-config.yaml
Sección titulada «Configuracion en project-config.yaml»# Agregar en project-config.yaml si se usa AG-UIintegrations: ag_ui: enabled: false # true si se usa AG-UI transport: "sse" # sse | websocket events: lifecycle: true # run_started, run_finished text_streaming: true # Token-by-token streaming tool_progress: true # Show tool calls in UI state_sync: false # Shared state (advanced) custom_events: [] # Domain-specific events security: cors_origins: ["https://mi-app.com"] rate_limit: 100 # events/second auth: "bearer_token" # Same as API authChecklist AG-UI por Track
Sección titulada «Checklist AG-UI por Track»| Actividad | Solo | Lean | Full |
|---|---|---|---|
| Evaluar necesidad de AG-UI | ⬜ Opcional | ⬜ Si hay frontend | ✅ Si hay frontend |
| Implementar event streaming | SSE basico | AG-UI lifecycle + text | AG-UI completo |
| Tool progress en UI | No | Basico | Con UX patterns |
| Human-in-the-loop via UI | No | Botones aprobacion | Flujo completo |
| State synchronization | No | No | Si se necesita |
Nota: AG-UI esta evolucionando rapidamente. Monitorear la especificacion oficial y evaluar adopcion cuando la version 1.0 sea publicada. Para la mayoria de los proyectos hoy, SSE con lifecycle events basicos es suficiente.
2.3 Enterprise MCP Architecture
Sección titulada «2.3 Enterprise MCP Architecture»Fuentes: CIO “MCP on Every Executive Agenda” (Feb 2026), The New Stack “MCP’s Growing Pains” (Mar 2026), CData “Enterprise MCP Adoption” (Mar 2026), MCP Roadmap 2026 — Enterprise Readiness pillar
MCP esta pasando de herramienta de desarrollo a infraestructura enterprise. Las organizaciones que adoptan MCP a escala enfrentan retos que no existen en uso individual.
2.3.1 MCP Gateway Pattern
Sección titulada «2.3.1 MCP Gateway Pattern»Patron central para enterprise: un proxy que centraliza auth, rate limiting, audit y routing de MCP requests.
┌─────────────────────────────────────────────────────────────┐│ MCP GATEWAY PATTERN ││ ││ ┌─────────┐ ┌─────────┐ ┌─────────┐ ││ │ Agent 1 │ │ Agent 2 │ │ Agent N │ ← MCP Clients ││ └────┬────┘ └────┬────┘ └────┬────┘ ││ │ │ │ ││ └────────────┼────────────┘ ││ │ ││ ┌──────▼──────┐ ││ │ MCP Gateway │ ← Central proxy ││ │ │ ││ │ ┌─────────┐ │ ││ │ │ Auth │ │ OAuth 2.1 / SSO / DPoP ││ │ ├─────────┤ │ ││ │ │ Rate │ │ Per-tenant / per-user limits ││ │ │ Limit │ │ ││ │ ├─────────┤ │ ││ │ │ Audit │ │ Full request/response logging ││ │ │ Trail │ │ ││ │ ├─────────┤ │ ││ │ │ Router │ │ Route to correct MCP server ││ │ └─────────┘ │ ││ └──┬───┬───┬──┘ ││ │ │ │ ││ ▼ ▼ ▼ ││ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ││ │ DB │ │ CRM │ │ Git │ │ ERP │ ← MCP Servers ││ │Server│ │Server│ │Server│ │Server│ ││ └──────┘ └──────┘ └──────┘ └──────┘ │└─────────────────────────────────────────────────────────────┘# MCP Gateway configuration examplemcp_gateway: listen: "0.0.0.0:8443" tls: true
authentication: method: "oauth2.1" issuer: "https://auth.company.com" required_scopes: ["mcp:read", "mcp:write"] dpop_enabled: true # Proof of possession (SEP-1932)
authorization: rbac: roles: developer: allowed_servers: ["context7", "github", "db-readonly"] max_requests_per_min: 100 lead: allowed_servers: ["*"] max_requests_per_min: 500 agent: allowed_servers: ["project-tools", "db-readonly"] max_requests_per_min: 200 require_tool_annotation_check: true
rate_limiting: global: 10000 # requests/min across all tenants per_tenant: 1000 per_user: 100 per_tool: destructive: 10 # max 10 destructive calls/min read_only: 500
audit: enabled: true format: "structured_json" destination: "elasticsearch" # or splunk, datadog, cloudwatch fields: - timestamp - user_id - agent_id - server_name - tool_name - tool_annotation # readOnly, destructive, etc. - request_hash # For deduplication - response_status - latency_ms retention: "90d" # EU AI Act compliance
routing: discovery: "server_cards" # Use .well-known/mcp-server-card.json health_check_interval: "30s" failover: "round_robin" timeout: "30s"2.3.2 Multi-Tenant MCP
Sección titulada «2.3.2 Multi-Tenant MCP»Para organizaciones SaaS o con multiples equipos compartiendo infraestructura MCP:
# Multi-tenant MCP configurationmulti_tenant: isolation_model: "namespace" # namespace | dedicated | shared
tenants: - id: "team-alpha" namespace: "alpha" servers: - name: "alpha-db" type: "postgresql" connection: "postgres://alpha_user@db/alpha_schema" max_connections: 5 - name: "alpha-github" type: "github" repo: "org/alpha-project" quotas: max_requests_per_hour: 5000 max_concurrent_connections: 10 max_data_egress_mb: 100
- id: "team-beta" namespace: "beta" servers: - name: "beta-db" type: "postgresql" connection: "postgres://beta_user@db/beta_schema" max_connections: 5 quotas: max_requests_per_hour: 3000 max_concurrent_connections: 5 max_data_egress_mb: 50
cross_tenant: allowed: false # Tenants cannot access each other's servers shared_servers: ["context7", "sequential-thinking"] # Read-only shared2.3.3 SSO/SAML Integration
Sección titulada «2.3.3 SSO/SAML Integration»# SSO integration for MCPsso_integration: provider: "okta" # okta | azure_ad | google_workspace protocol: "saml2.0"
flow: 1_agent_requests: "Agent calls MCP Gateway with bearer token" 2_gateway_validates: "Gateway validates token against IdP" 3_extract_claims: "Extract user_id, roles, tenant from SAML assertion" 4_authorize: "Apply RBAC based on extracted claims" 5_proxy: "Forward to appropriate MCP server with scoped credentials"
# Cross-App Access pattern (xaa.dev) cross_app_access: enabled: true description: "Allow MCP servers to access enterprise apps via SSO" supported_apps: ["salesforce", "jira", "confluence", "github"] token_lifetime: "5m" # Short-lived JIT tokens2.3.4 Centralized Audit Trail (EU AI Act Compliance)
Sección titulada «2.3.4 Centralized Audit Trail (EU AI Act Compliance)»# Patron: MCP Audit Logger para EU AI Actimport jsonfrom datetime import datetime
class MCPAuditLogger: """Logger de audit para MCP calls — cumple EU AI Act Art. 12 (Record-keeping)."""
REQUIRED_FIELDS = [ "timestamp", "agent_id", "user_id", "tenant_id", "server_name", "tool_name", "tool_annotation", "input_hash", "output_hash", "status", "latency_ms", "ai_system_id", # EU AI Act identifier ]
def log(self, event: dict): """Log MCP call event with all required fields.""" record = { "timestamp": datetime.utcnow().isoformat(), "version": "1.0", **{k: event.get(k, "unknown") for k in self.REQUIRED_FIELDS}, "metadata": { "framework_version": "6.2", "eu_ai_act_article": "Art.12", "retention_days": 90, } } # Send to audit destination self._send_to_elasticsearch(record)
# Alert on destructive operations if event.get("tool_annotation") == "destructive": self._alert_security_team(record)2.3.5 Connection Pooling y Performance
Sección titulada «2.3.5 Connection Pooling y Performance»# MCP connection pool configurationconnection_pooling: enabled: true
per_server: min_connections: 2 max_connections: 20 idle_timeout: "5m" max_lifetime: "1h"
health_check: interval: "30s" timeout: "5s" unhealthy_threshold: 3 healthy_threshold: 1
circuit_breaker: enabled: true failure_threshold: 5 recovery_time: "60s" half_open_requests: 32.3.6 Enterprise MCP por Track
Sección titulada «2.3.6 Enterprise MCP por Track»| Componente | Solo | Lean | Full |
|---|---|---|---|
| Gateway | N/A (directo) | Gateway simple (nginx/envoy) | Gateway dedicado + monitoring |
| Auth | API key local | OAuth 2.1 | SSO + DPoP + RBAC |
| Rate Limiting | N/A | Per-user basic | Per-tenant + per-tool |
| Audit | Logs locales | Structured logs | Elasticsearch + dashboards |
| Multi-tenant | N/A | Namespace isolation | Dedicated isolation |
| Discovery | Manual config | Server Cards | Registry + auto-discovery |
| Monitoring | Manual checks | Health endpoint | Full observability stack |
2.4 MCP Server Lifecycle Management
Sección titulada «2.4 MCP Server Lifecycle Management»Fuente: The New Stack “MCP’s Biggest Growing Pains” (Mar 2026), MCP Roadmap 2026 — Enterprise Readiness
2.4.1 Lifecycle Stages
Sección titulada «2.4.1 Lifecycle Stages»┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐│ Develop │─►│ Test │─►│ Deploy │─►│ Monitor │─►│ Retire ││ │ │ │ │ │ │ │ │ ││ - Code │ │ - Unit │ │ - Canary │ │ - Health │ │ - Drain ││ - Spec │ │ - Integ │ │ - Blue/ │ │ - Usage │ │ - Notify ││ - Card │ │ - Sec │ │ Green │ │ - Perf │ │ - Remove │└──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘2.4.2 Deploy Pipeline
Sección titulada «2.4.2 Deploy Pipeline»name: MCP Server Deploy Pipelineon: push: paths: ['mcp_servers/**']
jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Unit tests run: pytest tests/mcp/ -v --cov=mcp_servers --cov-fail-under=80 - name: Security scan run: | pip install safety bandit safety check bandit -r mcp_servers/ - name: MCP compliance check run: | # Verify server card exists and is valid python -c " import json card = json.load(open('mcp_servers/server-card.json')) assert 'name' in card assert 'version' in card assert 'tools' in card print('Server card valid') "
canary: needs: test runs-on: ubuntu-latest steps: - name: Deploy canary (10% traffic) run: | # Deploy new version alongside current kubectl apply -f k8s/mcp-server-canary.yaml # Route 10% of MCP requests to canary kubectl patch virtualservice mcp-gateway \ --patch '{"spec":{"http":[{"route":[{"destination":{"host":"mcp-server","subset":"stable"},"weight":90},{"destination":{"host":"mcp-server","subset":"canary"},"weight":10}]}]}}'
- name: Monitor canary (5 min) run: | sleep 300 # Check error rate ERROR_RATE=$(curl -s "http://prometheus:9090/api/v1/query?query=mcp_error_rate{version='canary'}" | jq '.data.result[0].value[1]') if (( $(echo "$ERROR_RATE > 0.05" | bc -l) )); then echo "Canary failed — rolling back" kubectl rollout undo deployment/mcp-server-canary exit 1 fi echo "Canary passed — promoting"
promote: needs: canary runs-on: ubuntu-latest steps: - name: Promote to production run: | kubectl set image deployment/mcp-server mcp-server=registry/mcp-server:${{ github.sha }} kubectl rollout status deployment/mcp-server --timeout=120s
#### 2.4.3 Health Check Endpoints
```python# MCP Server con health endpoints integradosfrom fastmcp import FastMCPfrom datetime import datetime
mcp = FastMCP(name="project-tools", version="2.0.0")
# Health state_start_time = datetime.utcnow()_request_count = 0_error_count = 0
@mcp.tool()def health_check() -> dict: """Health check endpoint for monitoring.""" uptime = (datetime.utcnow() - _start_time).total_seconds() error_rate = _error_count / max(_request_count, 1)
return { "status": "healthy" if error_rate < 0.05 else "degraded", "uptime_seconds": uptime, "version": "2.0.0", "requests_total": _request_count, "error_rate": round(error_rate, 4), "checks": { "database": _check_db(), "memory_mb": _get_memory_usage(), "dependencies": _check_deps(), } }
@mcp.tool()def readiness_check() -> dict: """Readiness probe — is the server ready to accept requests?""" return { "ready": True, "version": "2.0.0", "tools_loaded": len(mcp.tools), }2.4.4 Version Pinning & Registry
Sección titulada «2.4.4 Version Pinning & Registry»# MCP Server Registry (interno)mcp_registry: servers: - name: "project-tools" current_version: "2.0.0" min_supported_version: "1.5.0" deprecation_date: null server_card_url: "https://mcp.internal/project-tools/.well-known/mcp-server-card.json" health_url: "https://mcp.internal/project-tools/health" owner: "team-alpha"
- name: "db-readonly" current_version: "1.3.0" min_supported_version: "1.0.0" deprecation_date: "2026-06-01" replacement: "db-readonly-v2" server_card_url: "https://mcp.internal/db-readonly/.well-known/mcp-server-card.json"
# Version policy version_policy: pin_strategy: "minor" # Accept patch updates, pin minor auto_update: false # Require explicit upgrade rollback_window: "7d" # Keep previous version for 7 days
# Deprecation workflow deprecation: notice_period: "30d" steps: 1: "Announce deprecation in registry + Slack" 2: "Log warnings on deprecated server calls" 3: "Block new connections after notice period" 4: "Drain existing connections over 7 days" 5: "Decommission server"2.4.5 Rollback Strategy
Sección titulada «2.4.5 Rollback Strategy»# Rollback rapido de MCP server#!/bin/bashMCP_SERVER=$1PREVIOUS_VERSION=$(kubectl get deployment $MCP_SERVER -o jsonpath='{.metadata.annotations.previous-version}')
echo "Rolling back $MCP_SERVER to version $PREVIOUS_VERSION"
# 1. Rollback deploymentkubectl rollout undo deployment/$MCP_SERVER
# 2. Update registrycurl -X PATCH "https://mcp-registry.internal/servers/$MCP_SERVER" \ -H "Content-Type: application/json" \ -d "{\"current_version\": \"$PREVIOUS_VERSION\", \"rollback_reason\": \"automated\"}"
# 3. Notifycurl -X POST "$SLACK_WEBHOOK" \ -d "{\"text\": \"⚠️ MCP Server '$MCP_SERVER' rolled back to $PREVIOUS_VERSION\"}"
# 4. Verify healthsleep 10HEALTH=$(curl -s "https://mcp.internal/$MCP_SERVER/health" | jq -r '.status')echo "Health after rollback: $HEALTH"3. MCP Servers Esenciales para Desarrollo
Sección titulada «3. MCP Servers Esenciales para Desarrollo»3.1 Desarrollo AI-First
Sección titulada «3.1 Desarrollo AI-First»| Server | Qué hace | Cuándo usarlo |
|---|---|---|
| Context7 | Docs actualizadas de cualquier librería | Siempre — evita hallucinations con APIs |
| Sequential Thinking | Razonamiento paso a paso estructurado | Problemas complejos, arquitectura |
| Stitch | Diseño UI generativo | Fase F04/F06 con Vibe Design |
| Chrome DevTools | Inspección live del browser | Debug frontend, testing visual |
| PostgreSQL/MySQL | Queries directas a DB | F02 Domain Discovery, F06 Build |
| GitHub | PRs, issues, repo operations | CI/CD, automation |
| Filesystem | Acceso a archivos del proyecto | Siempre (built-in en Claude Code) |
3.2 Especializados por Dominio
Sección titulada «3.2 Especializados por Dominio»| Server | Dominio | Función |
|---|---|---|
| Stripe MCP | Fintech | Test accounts, payment flows |
| Nuxt MCP | Frontend (Vue) | Docs v4, best practices |
| Supabase MCP | Backend-as-Service | Schema, functions, auth |
| Sentry MCP | Observability | Error tracking, performance |
| Firecrawl | Web scraping | Extracción de datos web |
4. Crear tu Propio MCP Server
Sección titulada «4. Crear tu Propio MCP Server»4.1 Template: Python (FastMCP)
Sección titulada «4.1 Template: Python (FastMCP)»"""MCP Server para tu proyecto.Expone herramientas específicas del dominio al agente AI."""from fastmcp import FastMCPimport yaml
mcp = FastMCP( name="project-tools", version="1.0.0", description="Herramientas del proyecto [CODENAME]")
# ── TOOLS ──────────────────────────────────────────
@mcp.tool()def get_project_config() -> dict: """Retorna la configuración actual del proyecto.""" with open("project/project-config.yaml") as f: return yaml.safe_load(f)
@mcp.tool()def search_contracts(query: str) -> list[dict]: """Busca en los contratos OpenAPI del proyecto.
Args: query: Término de búsqueda (endpoint, schema, etc.) """ import glob results = [] for spec_file in glob.glob("project/F05_contracts/.openspec/*.yaml"): with open(spec_file) as f: content = f.read() if query.lower() in content.lower(): results.append({ "file": spec_file, "preview": content[:500] }) return results
@mcp.tool()def validate_against_spec( code: str, spec_path: str) -> dict: """Valida que el código implementa correctamente un spec.
Args: code: Código fuente a validar spec_path: Ruta al archivo de spec OpenAPI """ # Implementación de validación import subprocess result = subprocess.run( ["npx", "spectral", "lint", spec_path], capture_output=True, text=True ) return { "valid": result.returncode == 0, "issues": result.stdout, "errors": result.stderr }
@mcp.tool()def get_adr(adr_id: str) -> str: """Obtiene un Architecture Decision Record.
Args: adr_id: ID del ADR (e.g., "001", "002") """ import os path = f"project/F04_architecture/adr_{adr_id}_*.md" import glob files = glob.glob(path) if files: with open(files[0]) as f: return f.read() return f"ADR {adr_id} not found"
# ── RESOURCES ──────────────────────────────────────
@mcp.resource("project://config")def project_config_resource() -> str: """Configuración del proyecto como resource.""" with open("project/project-config.yaml") as f: return f.read()
@mcp.resource("project://architecture/{adr_id}")def adr_resource(adr_id: str) -> str: """ADRs como resources navegables.""" return get_adr(adr_id)
# ── PROMPTS ────────────────────────────────────────
@mcp.prompt()def review_implementation(spec_path: str, code_path: str) -> str: """Prompt para revisar implementación vs spec.""" return f"""Review this implementation against the specification.
Spec: {spec_path}Code: {code_path}
Check for:1. All endpoints implemented2. Request/response schemas match3. Error handling covers all spec-defined errors4. Authentication/authorization as specified"""
if __name__ == "__main__": mcp.run(transport="stdio")4.2 Template: Node.js (TypeScript SDK)
Sección titulada «4.2 Template: Node.js (TypeScript SDK)»import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";import { z } from "zod";import fs from "fs";import yaml from "js-yaml";
const server = new McpServer({ name: "project-tools", version: "1.0.0",});
// ── TOOLS ──────────────────────────────────────────
server.tool( "get_project_config", "Returns the current project configuration", {}, async () => { const config = yaml.load( fs.readFileSync("project/project-config.yaml", "utf8") ); return { content: [{ type: "text", text: JSON.stringify(config, null, 2) }] }; });
server.tool( "search_adrs", "Search Architecture Decision Records", { query: z.string().describe("Search term for ADRs") }, async ({ query }) => { const adrs = fs.readdirSync("project/F04_architecture") .filter(f => f.startsWith("adr_") && f.endsWith(".md"));
const matches = adrs.filter(f => { const content = fs.readFileSync(`project/F04_architecture/${f}`, "utf8"); return content.toLowerCase().includes(query.toLowerCase()); });
return { content: [{ type: "text", text: JSON.stringify(matches) }] }; });
// ── Run ────────────────────────────────────────────const transport = new StdioServerTransport();await server.connect(transport);4.3 Configuración en Claude Code
Sección titulada «4.3 Configuración en Claude Code»// .claude/settings.json (añadir a mcpServers){ "mcpServers": { "project-tools": { "command": "python", "args": ["mcp_servers/project_server.py"], "env": { "PROJECT_ROOT": "." } }, "context7": { "command": "npx", "args": ["-y", "@context7/mcp-server"] }, "sequential-thinking": { "command": "npx", "args": ["-y", "@anthropic/mcp-sequential-thinking"] } }}5. Patrones de Uso por Fase
Sección titulada «5. Patrones de Uso por Fase»| Fase | MCP Server recomendado | Uso |
|---|---|---|
| F01 Strategy | Sequential Thinking | Análisis de problemas complejos |
| F02 Domain | PostgreSQL/MySQL, project-tools | Explorar datos y esquemas existentes |
| F03 Context | Context7 | Docs actualizadas de stack elegido |
| F04 Architecture | project-tools, Sequential Thinking | Consultar ADRs, razonar sobre trade-offs |
| F05 Contracts | project-tools | Validar specs, buscar contratos |
| F06 Build | Context7, Stitch, Chrome DevTools | Docs, diseño UI, debug visual |
| F07 TEVV | project-tools, Chrome DevTools | Validar contra specs, testing visual |
| F08 Security | GitHub, project-tools | Security review, vulnerability scan |
| F09 Operations | GitHub, Sentry | Deploy, monitoring, error tracking |
| F10 Evolution | project-tools | Análisis de métricas, retrospectiva |
6. Seguridad MCP
Sección titulada «6. Seguridad MCP»6.1 Principios
Sección titulada «6.1 Principios»- Least Privilege: Cada server expone solo lo necesario.
- Tool Annotations: Marcar herramientas destructivas.
- Auth obligatorio: OAuth 2.1 para servers remotos.
- Audit logging: Registrar todas las invocaciones.
- Sandbox: MCP servers no deben tener acceso al sistema completo.
6.2 Checklist de Seguridad
Sección titulada «6.2 Checklist de Seguridad»# Auditar antes de instalar cualquier MCP server:security_review: - source_code_reviewed: true # ¿Revisaste el código? - permissions_minimal: true # ¿Solo accede a lo necesario? - no_data_exfiltration: true # ¿No envía datos a terceros? - auth_configured: true # ¿Auth habilitado si es remoto? - tool_annotations_present: true # ¿Tools marcados correctamente? - destructive_tools_guarded: true # ¿Acciones destructivas requieren confirmación?7. Testing de MCP Servers
Sección titulada «7. Testing de MCP Servers»"""Tests para tu MCP server."""import pytestfrom mcp_servers.project_server import mcp
@pytest.mark.asyncioasync def test_get_project_config(): result = await mcp.call_tool("get_project_config", {}) assert "codename" in str(result)
@pytest.mark.asyncioasync def test_search_contracts(): result = await mcp.call_tool("search_contracts", {"query": "users"}) assert isinstance(result, list)
@pytest.mark.asyncioasync def test_get_adr_not_found(): result = await mcp.call_tool("get_adr", {"adr_id": "999"}) assert "not found" in result.lower()8. Anti-Patrones
Sección titulada «8. Anti-Patrones»| Anti-patrón | Problema | Solución |
|---|---|---|
| Server monolítico | Context bloat, lento | Un server por dominio |
| Tools sin descripción | Agente elige mal | Descriptions detalladas + annotations |
| Sin auth remoto | Riesgo de seguridad | OAuth 2.1 obligatorio |
| Exponer DB sin filtro | Data leaks | Views/queries predefinidas |
| Instalar sin auditar | Supply chain risk | Security review checklist |
| Duplicar tools | Agente confundido | Sin overlap funcional |
9. Auditoria de Seguridad MCP
Sección titulada «9. Auditoria de Seguridad MCP»El script mcp-security-audit.py (v7.7) permite auditar la postura de seguridad de los MCP servers configurados en el proyecto. Complementa la checklist manual de §6.2 con verificacion automatizada.
9.1 Comandos Principales
Sección titulada «9.1 Comandos Principales»# Actualizar base de datos de CVEs conocidos para MCP serverspython3 scripts/mcp-security-audit.py --update-cves
# Verificar Server Cards (metadata, versiones, permisos declarados)python3 scripts/mcp-security-audit.py --check-server-cards
# Validar attestation (cadena de confianza del servidor)python3 scripts/mcp-security-audit.py --check-attestation
# Auditoria completa (los 3 checks combinados)python3 scripts/mcp-security-audit.py --update-cves --check-server-cards --check-attestation9.2 Que Verifica Cada Check
Sección titulada «9.2 Que Verifica Cada Check»| Check | Que valida | Cuando usar |
|---|---|---|
--update-cves | Vulnerabilidades conocidas en servers instalados | Diario en CI, antes de agregar servers |
--check-server-cards | Metadata del server, versiones, tool annotations | Al configurar nuevo server |
--check-attestation | Firma y cadena de confianza del servidor MCP | Antes de conectar a servers remotos |
9.3 Integracion con CI
Sección titulada «9.3 Integracion con CI»# .github/workflows/security-scan.yml (fragmento)- name: MCP Security Audit run: | python3 scripts/mcp-security-audit.py \ --update-cves \ --check-server-cards \ --check-attestation \ --format json > mcp-audit-report.json10. Checklist de Implementación
Sección titulada «10. Checklist de Implementación»- Identificar 3-5 MCP servers esenciales para el proyecto
- Auditar seguridad de cada server (checklist §6.2)
- Configurar en
.claude/settings.json - Crear MCP server propio del proyecto (template §4)
- Escribir tests para MCP server propio
- Documentar servers en
project-config.yaml - Verificar tool annotations (readOnly, destructive)
- Configurar auth para servers remotos
Documento generado como companion operativo de AI Software Factory OS v7.7. Enterprise MCP patterns basados en: CIO “MCP on Executive Agenda” (Feb 2026), The New Stack “MCP Growing Pains” (Mar 2026), CData “Enterprise MCP Adoption” (Mar 2026), MCP Roadmap 2026 Blog (Mar 2026). A2A Implementation Patterns agregados en v6.4 (GAP-11). Auditoria de seguridad MCP extendida agregada en v7.7.