Skip to main content
Glama
UFSC Email MCP Server

UFSC Email MCP Server

UFSC Email MCP Server 📬

Servidor Model Context Protocol (MCP) para integração com o e-mail institucional da Universidade Federal de Santa Catarina (UFSC) (imap.ufsc.br) e outros servidores IMAP modernos.

Permite que assistentes de Inteligência Artificial (ChatGPT, Claude Desktop, Cursor, Orca, agentes n8n e outros) leiam, pesquisem, organizem, movam e marquem e-mails institucionais como lidos com segurança e rastreabilidade.


✨ Funcionalidades

  • Busca e Leitura de Mensagens:

    • list_messages: Lista mensagens de qualquer pasta (INBOX, SPAM, subpastas personalizadas) com suporte a filtros e paginação.

    • get_message: Recupera o conteúdo completo do e-mail (texto puro, formatação e metadados).

    • download_attachment: Baixa e extrai texto de anexos (incluindo processamento seguro de PDFs e documentos DOCX).

  • Organização e Marcação de Mensagens:

    • mark_messages_read: Marca mensagens como lidas (seen: true) ou não lidas (seen: false) via comandos IMAP \Seen de forma idempotente e segura por UID.

    • move_messages: Move mensagens individualmente ou em lote entre pastas, com o parâmetro opcional mark_as_read: true para marcar como lida e arquivar na mesma operação.

    • save_draft: Cria rascunhos de e-mails diretamente no servidor.

  • Dois Modos de Transporte MCP:

    • Stdio (Local): Para clientes desktop (Claude Desktop, Cursor, VS Code, Orca local).

    • Streamable HTTP / SSE (Remoto): Servidor HTTP protegido por Bearer Token (MCP_AUTH_TOKEN) para conexão direta com ChatGPT, n8n, Traefik, Docker e integrações em nuvem.

  • Segurança e Conformidade:

    • Utiliza estritamente UIDs IMAP para evitar inconsistências de sequência.

    • Suporte a carregamento de credenciais por variáveis de ambiente ou arquivos de segredo (/config/password).

    • Modo somente-leitura opcional (IMAP_READ_ONLY=true).


Related MCP server: Email MCP Server

⚙️ Parâmetros do E-mail da UFSC

Parâmetro

Valor Recomendado

Observações

Servidor IMAP

imap.ufsc.br

Servidor oficial da SETIC/UFSC

Porta

993

Porta segura padrão IMAP

Segurança

SSL/TLS (IMAP_TLS=true)

Obrigatório para comunicação criptografada

Usuário

seu.usuario@ufsc.br

Seu e-mail institucional ou identificador IdUFSC

Senha

sua-senha-idufsc

Senha de acesso ao IdUFSC


🚀 Instalação e Preparação

1. Clonar o Repositório

git clone https://github.com/jeanmartina/ufsc-email-mcp.git
cd ufsc-email-mcp

2. Configurar Variáveis de Ambiente

Copie o arquivo de exemplo e preencha suas credenciais:

cp .env.example .env

Edite o .env:

# Conexão IMAP da UFSC
IMAP_HOST=imap.ufsc.br
IMAP_PORT=993
IMAP_TLS=true
IMAP_USER=seu.idufsc@ufsc.br
IMAP_PASSWORD=sua_senha_idufsc
IMAP_READ_ONLY=false

# Configuração HTTP (para ChatGPT / Claude Remoto)
PORT=8087
HOST=0.0.0.0
MCP_AUTH_TOKEN=gere_um_token_seguro_aqui

3. Instalar Dependências e Compilar

Requer Node.js >= 22.

npm install
npm run build

🖥️ Como Executar

Opção 1: Via Docker Compose (Recomendado para Servidor / ChatGPT)

A maneira mais simples de rodar como serviço contínuo:

docker compose up -d --build

O serviço iniciará na porta 8087 (ou na definida em .env) com suporte a Streamable HTTP e proteção por token.

Opção 2: Como Servidor HTTP Local / Manual

npm run serve
# ou: node http-server.mjs

O endpoint HTTP estará disponível em:

  • http://localhost:8087/ (ou /mcp)

  • Cabeçalho de autorização: Authorization: Bearer <SEU_MCP_AUTH_TOKEN>

Opção 3: Modo Stdio no Claude Desktop

No seu arquivo claude_desktop_config.json (geralmente em ~/.config/Claude/claude_desktop_config.json no Linux ou %APPDATA%\Claude no Windows):

{
  "mcpServers": {
    "ufsc-email": {
      "command": "node",
      "args": ["/caminho/absoluto/ufsc-email-mcp/dist/index.js"],
      "env": {
        "IMAP_HOST": "imap.ufsc.br",
        "IMAP_PORT": "993",
        "IMAP_TLS": "true",
        "IMAP_USER": "seu.idufsc@ufsc.br",
        "IMAP_PASSWORD": "sua_senha_idufsc",
        "IMAP_READ_ONLY": "false"
      }
    }
  }
}

Opção 4: Configuração no Cursor (.cursor/mcp.json)

{
  "mcpServers": {
    "ufsc-email": {
      "command": "node",
      "args": ["/caminho/absoluto/ufsc-email-mcp/dist/index.js"],
      "env": {
        "IMAP_HOST": "imap.ufsc.br",
        "IMAP_PORT": "993",
        "IMAP_TLS": "true",
        "IMAP_USER": "seu.idufsc@ufsc.br",
        "IMAP_PASSWORD": "sua_senha_idufsc"
      }
    }
  }
}

🤖 Conectando com o ChatGPT

Para conectar este MCP ao ChatGPT (via Custom GPT ou interface com suporte a MCP Streamable HTTP):

  1. URL do Servidor: https://seu-dominio-ou-ip/mcp

  2. Tipo de Autenticação: Bearer Token

  3. Token: O mesmo valor configurado em MCP_AUTH_TOKEN.


🛠️ Ferramentas MCP Disponíveis (Tools Reference)

1. mark_messages_read

Marca uma ou mais mensagens como lidas ou não lidas na pasta informada.

{
  "mailbox": "INBOX",
  "uids": [1024, 1025],
  "seen": true
}

2. move_messages

Move mensagens para uma pasta de destino (individualmente ou em lote), opcionalmente marcando-as como lidas. Por segurança contra movimentações acidentais, a ferramenta utiliza confirmação explícita em duas etapas:

  1. Etapa 1 (Prévia e Emissão de Token): Chame a ferramenta com os argumentos desejados sem confirm_token. O servidor retornará o resumo da operação (operation_summary), o tempo de validade (expires_in_seconds) e um token exclusivo (confirm_token).

  2. Etapa 2 (Confirmação e Execução): Chame a ferramenta novamente repetindo os mesmos parâmetros e incluindo confirm_token: "<token>". O servidor validará o token atômico de uso único e executará a movimentação.

// Chamada com confirmação
{
  "mailbox": "INBOX",
  "destination": "Arquivo",
  "uids": [1024],
  "mark_as_read": true,
  "confirm_token": "token_recebido_na_etapa_1"
}

Também suporta movimentação em lote para múltiplos destinos na mesma requisição:

{
  "mailbox": "INBOX",
  "mode": "move",
  "mark_as_read": true,
  "moves": [
    { "uids": [1024, 1025], "destination": "Arquivo.2026" },
    { "uids": [1026], "destination": "LATAM" }
  ]
}

3. list_messages

Lista os e-mails com metadados e status de leitura.

{
  "mailbox": "INBOX",
  "limit": 10
}

4. get_message

Lê o conteúdo completo de um e-mail através do seu UID.

{
  "mailbox": "INBOX",
  "uid": 1024
}

5. save_draft

Cria um novo rascunho de e-mail na pasta de rascunhos.

{
  "to": ["colegiado@ufsc.br"],
  "subject": "Parecer de Processo",
  "body": "Prezados,\n\nSegue parecer..."
}

6. list_archive_entries e read_archive_entry

Inspeciona com segurança arquivos .zip anexados (até IMAP_MAX_ARCHIVE_BYTES, padrão 32 MiB) e extrai texto paginado de PDFs (com rastreabilidade == Page N ==), DOCX, XLSX, PPTX, ODT, ODS, TXT, CSV, HTML, JSON, XML e RTF, ou materializa o arquivo original em diretório temporário isolado (mode: "download").

Choosing which tools load

Use IMAP_ALLOW_TOOLS and IMAP_DENY_TOOLS (see Choosing which tools load) to restrict exposed MCP tools in production deployments.


🧪 Testes Automatizados

O projeto inclui suíte completa de testes unitários e de integração utilizando Vitest:

npm test

Para rodar os testes específicos de marcação e movimentação:

npx vitest run test/mark-messages-read.test.ts

📄 Licença

Distribuído sob a licença MIT. Veja o arquivo LICENSE para mais detalhes.

Available Tools

6 tools
get_attachmentsList, read or download attachmentsA
Read-onlyIdempotent

Without part_id: lists the attachments of a message with their type, size, whether the policy allows fetching them and whether their text can be read. With part_id: returns that one attachment. Small text and images come back inline so you can read them; a PDF, Word, Excel, PowerPoint or OpenDocument file can be read as text with mode="text", which is the only way to read a document without access to this server's filesystem; anything else is written to the download directory, if one is configured, and you get the path. part_id must come from a listing call of this same tool. Executables are refused even when they claim to be something else — including when writing to disk.

Inputs: uid (required), mode, offset, mailbox, +2 more. Returns: uid, body, data, note, +23 more

get_messageGet one messageA
Read-onlyIdempotent

Fetches one message by UID and returns its headers and text body, fenced as untrusted content, together with a server-side security assessment (SPF/DKIM/DMARC verdicts, prompt-injection and homoglyph signals) and the list of its attachments. Does not change the read state. Set include_thread to also list the surrounding conversation.

Inputs: uid (required), mailbox, include_thread. Returns: uid, body, date, source, +8 more

get_server_infoServer and account informationA
Read-onlyIdempotent

Reports what this account and server can do: the configured mailbox, IMAP capabilities, which flags the mailbox stores permanently, whether the new-mail keyword can be used, and which tool groups are enabled. Start here when a call fails for reasons that sound like configuration.

Inputs: no named parameters. Returns: tls, host, port, limits, +8 more

list_mailboxesList mailboxesA
Read-onlyIdempotent

Lists every folder in the account with its message and unseen counts, its special-use role (drafts, sent, trash, junk) and whether it can hold messages. Use the returned "path" verbatim wherever a tool takes a mailbox.

Inputs: no named parameters. Returns: note, source, mailboxes, truncated, +4 more

list_messagesList and search messagesA
Read-onlyIdempotent

Lists messages newest first, optionally narrowed by sender, recipient, subject, body text, date range or flags. With no criteria it simply pages through the mailbox. Every filter is applied by the mail server, so searching a large folder is cheap. Returns summaries only — use get_message for the body.

Inputs: to, body, from, seen, +8 more. Returns: offset, source, mailbox, messages, +5 more

list_new_messagesList messages not seen beforeA

Returns messages this server has not handed over yet, newest first, and then marks them with the "AiSeen" keyword so the next call returns only what arrived since. This is separate from the human read/unread state, which is never touched. Use dry_run to preview without marking.

Inputs: limit, dry_run. Returns: marked, source, dry_run, mailbox, +6 more

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 6 tools

    Disambiguation4/5

    Most tools are clearly distinct: server diagnostics, mailbox listing, message retrieval, and attachment handling. The only potential overlap is between list_messages and list_new_messages, but their descriptions make the distinction between general search/paging and server-tracked new mail explicit.

    Naming Consistency5/5

    All tools use consistent snake_case verb_noun naming: get_server_info, list_mailboxes, list_messages, list_new_messages, get_message, get_attachments. The pattern is predictable and readable throughout.

    Tool Count5/5

    Six tools is well within the appropriate range and each has a clear role in a read-focused email workflow. No tool appears redundant or trivial.

    Completeness3/5

    The surface covers reading, searching, new-message tracking, message bodies, and attachments well. However, for an email server it lacks obvious write/lifecycle operations such as send, reply, delete, move, and flag/read-state management, which will cause failures for common email tasks.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables AI assistants to read, search, send, reply, forward, organize, schedule, and analyze email across multiple IMAP/SMTP accounts, with drafts, provider-aware labels, calendar extraction, verification-code catching, and a real-time inbox watcher. It runs over stdio or Streamable HTTP, with TLS, OAuth2, provider auto-detection, and a guided setup wizard.
      31 npm
      ISC
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables AI assistants to read, search, send, reply, forward, schedule, and organize email across multiple IMAP/SMTP accounts, including drafts, labels, bulk operations, real-time mailbox watching, verification-code capture, calendar extraction, and analytics. It runs locally over stdio or as a networked Streamable HTTP service with OAuth2 sign-in and provider auto-detection.
      31 npm
      ISC
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to search and read email, inspect attachments, and optionally send messages and organize folders through existing IMAP and SMTP mailboxes. Supports Docker, stdio, and HTTPS OAuth deployment with read-only or full-access modes.
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables AI assistants to read, search, send, reply, forward, schedule, and analyze email across multiple IMAP/SMTP accounts, with drafts, templates, provider-aware labels, bulk operations, attachment handling, calendar extraction, and real-time IMAP IDLE watching. Connections are secured with TLS/STARTTLS, OAuth2 support, and rate limiting, and it can run over stdio locally or Streamable HTTP for networked access.
      31 npm
      ISC