mcp-secure-server-giulia-ai

mcp-secure-server-giulia-ai

Secure MCP server with API-key authentication, bcrypt-hashed keys, and SQLite storage. It protects tools like user listing and secure greetings, requiring a valid environment-set key.

Category
Visit Server

README

PRJ-05 — Servidor MCP Seguro (autenticação por API Key)

Servidor MCP (FastMCP, transporte stdio) cujas tools só executam mediante uma API Key válida. As chaves são geradas com secrets.token_urlsafe, hasheadas com bcrypt e guardadas em SQLite; a validação usa bcrypt.checkpw. Senhas de usuário também são hasheadas com bcrypt. Corresponde ao Capítulo 6 do livro Model Context Protocol (Sandeco).

Arquitetura

database.py    → SQLite (tabelas users, api_keys) — grava em data/database.db
repository.py  → UserRepository / APIKeyRepository (SQL parametrizado)
generate_api_key.py → par (segredo, hash bcrypt)
api_key_controller.py → orquestra geração/validação/máscara de chaves
server_seguro.py → tools MCP protegidas (tool_segura, listar_usuarios)
main.py        → CLI de bootstrap (create-user / gen-key / list-users)

Formato da chave pública: sk-{user_id}-{secret} (só o hash do segredo é persistido).

Uso

uv sync

# 1) cria um usuário (senha hasheada com bcrypt)
uv run python src/main.py create-user --name "Giulia" --email giulia@ex.com --password ***

# 2) gera a API Key (exibida UMA vez)
uv run python src/main.py gen-key --user-id 1 --name "chave-dev"

# 3) configure a chave no ambiente
cp .env.example .env   # e cole a full key em GIULIA_AI_API_KEY

# 4) sobe o servidor MCP
uv run python src/server_seguro.py

Com a chave configurada, a tool tool_segura retorna uma saudação com os dados do usuário autenticado; sem chave (ou inválida), toda tool lança API Key inválida.

Segurança

  • Segredos hasheados (bcrypt + salt), nunca em texto puro no banco.
  • SQL sempre parametrizado (sem injeção).
  • Chave exibida uma única vez; no banco fica só a versão mascarada + hash.
  • .env e data/*.db fora do controle de versão (ver .gitignore).

Custo da validação

Cada chave guarda dois derivados: o hash bcrypt (o verificador) e um lookup_hash (SHA-256, apenas um índice). A validação localiza a linha exata pelo índice e roda bcrypt.checkpw uma vez. Antes o bcrypt rodava contra todas as chaves do usuário até casar — O(n) numa função que é lenta de propósito.

SHA-256 puro seria fraco para senha, mas o segredo aqui tem 32 bytes de secrets.token_urlsafe: não há dicionário que ataque isso. É o mesmo desenho usado por provedores de API em produção — índice rápido para achar, verificador lento para confirmar. Bancos criados antes da coluna existir são migrados automaticamente, e as chaves antigas continuam válidas.

Limitação: isto não autentica o chamador

A tool lê a chave de os.getenv("GIULIA_AI_API_KEY") — do ambiente do próprio servidor, não de um parâmetro enviado pelo cliente.

Em stdio o servidor MCP é um processo filho do cliente: um processo, um cliente. Não existe "outro chamador" para distinguir — a fronteira de confiança é o sistema operacional, não o protocolo. O que este projeto entrega é credencial bem guardada + um gate de configuração.

Autenticação de chamador só passa a fazer sentido com transporte HTTP, com a chave viajando na requisição. Essa camada não está implementada aqui.

Testes

uv run pytest        # 33 testes, contra SQLite temporário

Cobrem o formato da chave, o não-vazamento do segredo no arquivo do banco, o mascaramento, a validação (incluindo chave de outro usuário), a contagem de chamadas ao bcrypt, a migração do lookup_hash e a revogação.

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured