# Arquitetura do Uazapi MCP Server
## Visão Geral
```
┌─────────────────────────────────────────────────────────┐
│ Claude Desktop │
│ (MCP Client) │
└────────────────────┬────────────────────────────────────┘
│ MCP Protocol (stdio)
│
┌────────────────────▼────────────────────────────────────┐
│ Uazapi MCP Server │
│ (uazapi_mcp.py) │
│ │
│ ┌────────────────────────────────────────────────┐ │
│ │ FastMCP Framework │ │
│ │ - Tool Registration │ │
│ │ - Input Validation (Pydantic) │ │
│ │ - Error Handling │ │
│ └────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────┐ │
│ │ Shared Utilities │ │
│ │ • _make_api_request() │ │
│ │ • _handle_api_error() │ │
│ │ • _format_phone_number() │ │
│ │ • _truncate_response() │ │
│ └────────────────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────────────────┐ │
│ │ MCP Tools │ │
│ │ ├─ uazapi_send_text_message │ │
│ │ ├─ uazapi_send_media_message │ │
│ │ ├─ uazapi_get_contacts │ │
│ │ └─ uazapi_get_chats │ │
│ └────────────────────────────────────────────────┘ │
│ │
└────────────────────┬────────────────────────────────────┘
│ HTTPS (httpx)
│
┌────────────────────▼────────────────────────────────────┐
│ Uazapi API (v2.0) │
│ api.uazapi.com │
│ │
│ • Authentication (Bearer Token) │
│ • Rate Limiting │
│ • WhatsApp Business API │
└──────────────────────────────────────────────────────────┘
```
## Fluxo de Dados
### 1. Envio de Mensagem de Texto
```
User Prompt: "Envie 'Olá' para +55 11 99999-9999"
│
▼
Claude Desktop (MCP Client)
│
├─ Identifica ferramenta: uazapi_send_text_message
├─ Extrai parâmetros: {phone: "5511999999999", message: "Olá"}
│
▼
MCP Server - Input Validation (Pydantic)
│
├─ Valida phone (min_length, max_length)
├─ Formata número: _format_phone_number()
├─ Valida message (min_length, max_length)
│
▼
MCP Server - Tool Execution
│
├─ Autentica: _get_auth_headers()
├─ Monta payload: {phone, message}
├─ Chama: _make_api_request("messages/send/text", "POST")
│
▼
HTTP Client (httpx)
│
├─ POST https://api.uazapi.com/instances/{id}/messages/send/text
├─ Headers: {Authorization: "Bearer {key}"}
├─ Body: {phone, message}
│
▼
Uazapi API
│
├─ Valida credenciais
├─ Processa requisição
├─ Envia para WhatsApp
├─ Retorna: {id, status}
│
▼
MCP Server - Response Formatting
│
├─ Extrai dados relevantes
├─ Formata mensagem de sucesso
├─ OU trata erro: _handle_api_error()
│
▼
Claude Desktop
│
├─ Exibe resultado ao usuário
└─ "Message sent successfully! - Recipient: +5511999999999..."
```
## Componentes Principais
### 1. FastMCP Framework
```python
mcp = FastMCP("uazapi_mcp")
@mcp.tool(
name="tool_name",
annotations={...}
)
async def tool_function(params: InputModel) -> str:
...
```
**Responsabilidades:**
- Registrar ferramentas
- Gerenciar protocolo MCP
- Validar entrada via Pydantic
- Serializar saída
### 2. Pydantic Models
```python
class SendTextMessageInput(BaseModel):
model_config = ConfigDict(...)
phone: str = Field(...)
message: str = Field(...)
@field_validator('phone')
def validate_phone(cls, v: str):
...
```
**Responsabilidades:**
- Validar tipos de dados
- Aplicar constraints (min/max, regex)
- Transformar dados (strip, format)
- Fornecer mensagens de erro claras
### 3. Shared Utilities
```python
# Requisições HTTP
async def _make_api_request(endpoint, method, **kwargs):
# Centraliza lógica de comunicação com API
...
# Tratamento de erros
def _handle_api_error(e: Exception):
# Mensagens de erro consistentes e acionáveis
...
# Formatação de dados
def _format_phone_number(phone: str):
# Normaliza números de telefone
...
# Controle de tamanho
def _truncate_response(content: str):
# Previne respostas muito grandes
...
```
**Responsabilidades:**
- Reutilização de código
- Consistência entre ferramentas
- Manutenibilidade
- DRY (Don't Repeat Yourself)
### 4. MCP Tools
Cada ferramenta segue o padrão:
```python
@mcp.tool(name="...", annotations={...})
async def tool_name(params: InputModel) -> str:
try:
# 1. Preparar dados
payload = {...}
# 2. Chamar API
response = await _make_api_request(...)
# 3. Formatar resposta
if params.format == MARKDOWN:
return format_markdown(response)
else:
return format_json(response)
except Exception as e:
return _handle_api_error(e)
```
## Padrões de Design
### 1. Separation of Concerns
```
┌─────────────────────┐
│ Input Validation │ → Pydantic Models
├─────────────────────┤
│ Business Logic │ → Tool Functions
├─────────────────────┤
│ API Communication │ → Shared Utilities
├─────────────────────┤
│ Error Handling │ → _handle_api_error()
├─────────────────────┤
│ Response Format │ → Markdown/JSON helpers
└─────────────────────┘
```
### 2. DRY (Don't Repeat Yourself)
- ✅ Uma função para todas as requisições HTTP
- ✅ Um handler centralizado de erros
- ✅ Formatadores compartilhados
- ✅ Validadores reutilizáveis
### 3. Fail-Safe Defaults
```python
# Valores padrão seguros
limit: Optional[int] = Field(default=20, ge=1, le=100)
response_format: ResponseFormat = Field(default=ResponseFormat.MARKDOWN)
# Tratamento gracioso de erros
try:
...
except Exception as e:
return _handle_api_error(e) # Nunca quebra, sempre retorna string
# Truncamento automático
if len(content) > CHARACTER_LIMIT:
content = _truncate_response(content)
```
### 4. Progressive Enhancement
**Base (Implementado):**
- Envio de mensagens (texto e mídia)
- Listagem de contatos
- Listagem de conversas
**Futuro (Expansível):**
- Grupos e comunidades
- Webhooks e eventos
- Status e presença
- Mensagens avançadas
## Segurança
### Camadas de Segurança
```
1. Input Validation
├─ Pydantic models com constraints
├─ Field validators customizados
└─ Type checking
2. Authentication
├─ Env variables (não hardcoded)
├─ Bearer token em headers
└─ Validação no startup
3. API Security
├─ HTTPS obrigatório
├─ Timeouts configurados
└─ Rate limiting respeitado
4. Error Handling
├─ Não expõe detalhes internos
├─ Mensagens sanitizadas
└─ Logs apropriados
```
### Validação em Múltiplas Camadas
```
User Input: "+55 (11) 99999-9999"
│
▼ Pydantic Validation
├─ min_length check
├─ max_length check
├─ field_validator execution
│
▼ _format_phone_number()
├─ Remove special chars
├─ Validate digits only
├─ Check minimum length
│
▼ API Request
└─ Formatted: "5511999999999"
```
## Performance
### Otimizações
1. **Async/Await**
```python
# Todas as operações I/O são assíncronas
async def _make_api_request(...):
async with httpx.AsyncClient() as client:
response = await client.request(...)
```
2. **Connection Pooling**
```python
# httpx.AsyncClient gerencia pool de conexões
# Reutiliza conexões HTTP
```
3. **Paginação**
```python
# Evita carregar todos os dados
limit: int = Field(default=20, le=100)
offset: int = Field(default=0)
```
4. **Truncamento**
```python
# Previne respostas gigantes
CHARACTER_LIMIT = 25000
if len(content) > CHARACTER_LIMIT:
content = _truncate_response(content)
```
## Extensibilidade
### Adicionar Nova Ferramenta
```
1. Modelo Pydantic
↓
2. @mcp.tool decorator
↓
3. Usar shared utilities
↓
4. Documentar
↓
5. Testar
```
### Adicionar Nova Categoria
```python
# 1. Criar enum se necessário
class GroupRole(str, Enum):
ADMIN = "admin"
MEMBER = "member"
# 2. Modelo de entrada
class CreateGroupInput(BaseModel):
...
# 3. Implementar ferramenta
@mcp.tool(...)
async def uazapi_create_group(...):
...
```
## Monitoramento e Debug
### Logs
```python
# Startup validation
if not _validate_auth():
print("WARNING: Credentials not configured")
# Runtime errors (stderr)
import sys
sys.stderr.write(f"Error: {error_details}\n")
```
### Testing
```bash
# Sintaxe
python3 -m py_compile uazapi_mcp.py
# Imports
python3 -c "import uazapi_mcp"
# MCP Inspector
uv run mcp dev uazapi_mcp.py
# Integration test
# Use Claude Desktop with test credentials
```
## Dependências
```
mcp[cli] >= 1.0.0
├─ FastMCP framework
├─ Protocol implementation
└─ CLI utilities
pydantic >= 2.0.0
├─ Input validation
├─ Type checking
└─ Model configuration
httpx >= 0.27.0
├─ Async HTTP client
├─ Connection pooling
└─ Timeout management
```
## Roadmap
### Fase 1 (Atual) ✅
- [x] Estrutura base MCP
- [x] Envio de mensagens
- [x] Listagem de contatos/chats
- [x] Validação robusta
- [x] Documentação completa
### Fase 2 (Próxima)
- [ ] Grupos e comunidades
- [ ] Webhooks
- [ ] Status e presença
- [ ] Mensagens avançadas
### Fase 3 (Futuro)
- [ ] Cache de respostas
- [ ] Rate limiting inteligente
- [ ] Retry automático
- [ ] Métricas e analytics
---
**Desenvolvido seguindo as melhores práticas do MCP Protocol**