Ir al contenido

MCP Integration

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)

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

┌──────────────┐ 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...) │
└──────────────┘
PrimitivaDescripciónEjemplo
ToolsFunciones invocables por el agentesearch_users, deploy_service
ResourcesDatos expuestos al agente (read-only)Archivos, esquemas DB, configs
PromptsTemplates de interacción predefinidos”Analizar este log de errores”

El roadmap oficial prioriza 4 areas:

Area PrioritariaDescripcionStatus (Mar 2026)
Transport EvolutionStateless horizontal scaling, session handling, Server Cards🔄 Activo
Agent CommunicationTasks primitive (SEP-1686), retry semantics, result expiry🔄 Activo
Governance MaturationContributor ladder, WG delegation model, charter template🔄 Activo
Enterprise ReadinessAudit trails, SSO, gateway patterns, config portability📋 Enterprise WG formandose
FeatureStatus (Mar 2026)Impacto
Streamable HTTP transport✅ EstableReemplaza SSE, mejor para prod
OAuth 2.1 authentication✅ EstableAuth estandar para servers remotos
Server Cards (.well-known)🔄 En progresoMetadata descubrible para registries
Tasks primitive (SEP-1686)🔄 En progresoCall-now / fetch-later entre agentes
Elicitation (human-in-loop)✅ EstableAgente pide input al humano
Tool annotations✅ EstableMetadata: readOnly, destructive, etc.
DPoP (SEP-1932)🔄 En progresoProof of possession para tokens
Workload Identity Federation (SEP-1933)🔄 En progresoIdentity sin secrets estaticos

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.

Google introdujo A2A como complemento a MCP. Son protocolos complementarios, no competidores:

AspectoMCPA2A (Google)
PropositoAgent ↔ Tools/DataAgent ↔ Agent (peer-to-peer)
ModeloCliente-servidorPeer-to-peer con Agent Cards
EjemploClaude Code → PostgreSQL MCPAgent Planner → Agent Builder
Cuando usarAcceso a herramientas y datos externosCoordinacion entre agentes autonomos
AutorAnthropic + comunidad (Linux Foundation)Google
StatusProduccion (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.

┌─────────────────────────────────────────────────────────────┐
│ 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"
}
}

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 results

Cuando 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).

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.

RiesgoMitigacionRef OWASP
Agent impersonationValidar Agent Card con TLS + firma digitalASI03
Task injectionInput validation en cada skill, schemas estrictosASI01
Data exfiltration via A2AClassification-aware routing: no enviar restricted dataASI07
Runaway tasksmax_task_duration, circuit breaker, cancel endpointASI09
Supply chain (agentes maliciosos)Agent Card audit, allowlist de agentes confiablesASI04
# Agregar en project-config.yaml si se usa A2A
integrations:
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/hora
ActividadSoloLeanFull
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.

┌─────────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────────┘
ConceptoDescripcionEquivalente en otros protocolos
EventsStreaming de eventos del agente al frontendSSE / WebSocket messages
Lifecycle Eventsrun_started, run_finished, run_errorAgent session management
Text Message EventsStreaming de tokens para respuesta en tiempo realLLM streaming output
Tool Call EventsNotificacion al frontend de tool calls en progresoMCP progress notifications
State EventsShared state entre agente y frontendContext synchronization
Custom EventsEventos especificos del dominioApplication-specific hooks
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 ────────│ │
¿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**
# Agregar en project-config.yaml si se usa AG-UI
integrations:
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 auth
ActividadSoloLeanFull
Evaluar necesidad de AG-UI⬜ Opcional⬜ Si hay frontend✅ Si hay frontend
Implementar event streamingSSE basicoAG-UI lifecycle + textAG-UI completo
Tool progress en UINoBasicoCon UX patterns
Human-in-the-loop via UINoBotones aprobacionFlujo completo
State synchronizationNoNoSi 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.

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.

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 example
mcp_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"

Para organizaciones SaaS o con multiples equipos compartiendo infraestructura MCP:

# Multi-tenant MCP configuration
multi_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 shared
# SSO integration for MCP
sso_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 tokens

2.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 Act
import json
from 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)
# MCP connection pool configuration
connection_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: 3
ComponenteSoloLeanFull
GatewayN/A (directo)Gateway simple (nginx/envoy)Gateway dedicado + monitoring
AuthAPI key localOAuth 2.1SSO + DPoP + RBAC
Rate LimitingN/APer-user basicPer-tenant + per-tool
AuditLogs localesStructured logsElasticsearch + dashboards
Multi-tenantN/ANamespace isolationDedicated isolation
DiscoveryManual configServer CardsRegistry + auto-discovery
MonitoringManual checksHealth endpointFull observability stack

Fuente: The New Stack “MCP’s Biggest Growing Pains” (Mar 2026), MCP Roadmap 2026 — Enterprise Readiness

┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Develop │─►│ Test │─►│ Deploy │─►│ Monitor │─►│ Retire │
│ │ │ │ │ │ │ │ │ │
│ - Code │ │ - Unit │ │ - Canary │ │ - Health │ │ - Drain │
│ - Spec │ │ - Integ │ │ - Blue/ │ │ - Usage │ │ - Notify │
│ - Card │ │ - Sec │ │ Green │ │ - Perf │ │ - Remove │
└──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘
.github/workflows/mcp-server-deploy.yaml
name: MCP Server Deploy Pipeline
on:
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 integrados
from fastmcp import FastMCP
from 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),
}
# 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"
scripts/mcp-rollback.sh
# Rollback rapido de MCP server
#!/bin/bash
MCP_SERVER=$1
PREVIOUS_VERSION=$(kubectl get deployment $MCP_SERVER -o jsonpath='{.metadata.annotations.previous-version}')
echo "Rolling back $MCP_SERVER to version $PREVIOUS_VERSION"
# 1. Rollback deployment
kubectl rollout undo deployment/$MCP_SERVER
# 2. Update registry
curl -X PATCH "https://mcp-registry.internal/servers/$MCP_SERVER" \
-H "Content-Type: application/json" \
-d "{\"current_version\": \"$PREVIOUS_VERSION\", \"rollback_reason\": \"automated\"}"
# 3. Notify
curl -X POST "$SLACK_WEBHOOK" \
-d "{\"text\": \"⚠️ MCP Server '$MCP_SERVER' rolled back to $PREVIOUS_VERSION\"}"
# 4. Verify health
sleep 10
HEALTH=$(curl -s "https://mcp.internal/$MCP_SERVER/health" | jq -r '.status')
echo "Health after rollback: $HEALTH"
ServerQué haceCuándo usarlo
Context7Docs actualizadas de cualquier libreríaSiempre — evita hallucinations con APIs
Sequential ThinkingRazonamiento paso a paso estructuradoProblemas complejos, arquitectura
StitchDiseño UI generativoFase F04/F06 con Vibe Design
Chrome DevToolsInspección live del browserDebug frontend, testing visual
PostgreSQL/MySQLQueries directas a DBF02 Domain Discovery, F06 Build
GitHubPRs, issues, repo operationsCI/CD, automation
FilesystemAcceso a archivos del proyectoSiempre (built-in en Claude Code)
ServerDominioFunción
Stripe MCPFintechTest accounts, payment flows
Nuxt MCPFrontend (Vue)Docs v4, best practices
Supabase MCPBackend-as-ServiceSchema, functions, auth
Sentry MCPObservabilityError tracking, performance
FirecrawlWeb scrapingExtracción de datos web
mcp_servers/project_server.py
"""
MCP Server para tu proyecto.
Expone herramientas específicas del dominio al agente AI.
"""
from fastmcp import FastMCP
import 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 implemented
2. Request/response schemas match
3. Error handling covers all spec-defined errors
4. Authentication/authorization as specified
"""
if __name__ == "__main__":
mcp.run(transport="stdio")
mcp_servers/project_server.ts
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);
// .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"]
}
}
}
FaseMCP Server recomendadoUso
F01 StrategySequential ThinkingAnálisis de problemas complejos
F02 DomainPostgreSQL/MySQL, project-toolsExplorar datos y esquemas existentes
F03 ContextContext7Docs actualizadas de stack elegido
F04 Architectureproject-tools, Sequential ThinkingConsultar ADRs, razonar sobre trade-offs
F05 Contractsproject-toolsValidar specs, buscar contratos
F06 BuildContext7, Stitch, Chrome DevToolsDocs, diseño UI, debug visual
F07 TEVVproject-tools, Chrome DevToolsValidar contra specs, testing visual
F08 SecurityGitHub, project-toolsSecurity review, vulnerability scan
F09 OperationsGitHub, SentryDeploy, monitoring, error tracking
F10 Evolutionproject-toolsAnálisis de métricas, retrospectiva
  1. Least Privilege: Cada server expone solo lo necesario.
  2. Tool Annotations: Marcar herramientas destructivas.
  3. Auth obligatorio: OAuth 2.1 para servers remotos.
  4. Audit logging: Registrar todas las invocaciones.
  5. Sandbox: MCP servers no deben tener acceso al sistema completo.
# 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?
tests/test_mcp_server.py
"""Tests para tu MCP server."""
import pytest
from mcp_servers.project_server import mcp
@pytest.mark.asyncio
async def test_get_project_config():
result = await mcp.call_tool("get_project_config", {})
assert "codename" in str(result)
@pytest.mark.asyncio
async def test_search_contracts():
result = await mcp.call_tool("search_contracts", {"query": "users"})
assert isinstance(result, list)
@pytest.mark.asyncio
async def test_get_adr_not_found():
result = await mcp.call_tool("get_adr", {"adr_id": "999"})
assert "not found" in result.lower()
Anti-patrónProblemaSolución
Server monolíticoContext bloat, lentoUn server por dominio
Tools sin descripciónAgente elige malDescriptions detalladas + annotations
Sin auth remotoRiesgo de seguridadOAuth 2.1 obligatorio
Exponer DB sin filtroData leaksViews/queries predefinidas
Instalar sin auditarSupply chain riskSecurity review checklist
Duplicar toolsAgente confundidoSin overlap funcional

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.

Ventana de terminal
# Actualizar base de datos de CVEs conocidos para MCP servers
python3 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-attestation
CheckQue validaCuando usar
--update-cvesVulnerabilidades conocidas en servers instaladosDiario en CI, antes de agregar servers
--check-server-cardsMetadata del server, versiones, tool annotationsAl configurar nuevo server
--check-attestationFirma y cadena de confianza del servidor MCPAntes de conectar a servers remotos
# .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.json
  • 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.