mcp-cnes
This MCP server provides tools to load, search, and analyze data from Brazil's National Register of Health Establishments (CNES).
cnes_load_data: Import a CSV file exported from the official CNES dashboard into a local database, consolidating records with counts of loaded, read, rejected, and ignored rows.
cnes_search_municipio: Search for health establishments by partial or full municipality name, with optional bed count range filtering (min_leitos/max_leitos) and a configurable result limit (1–500).
cnes_search_cnes: Look up a specific establishment by its unique 7-digit CNES code.
cnes_search_uf: Retrieve establishments by Brazilian state (2-letter UF code), with optional bed count range and result limit (1–500).
cnes_statistics: Get aggregate statistics of the loaded data, including total establishments, total existing beds, total SUS beds, breakdown by state, last update timestamp, and source file name.
cnes_download_instructions: Receive step-by-step guidance on manually downloading a CSV from the official CNES dashboard, including the URL, steps, available columns, and post-download actions.
Provides tools to load CNES (Brazilian health establishments) CSV data and search for establishments by municipality, CNES code, or state, and retrieve statistics from the loaded data.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-cnesBusque estabelecimentos de saúde em Manaus"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP CNES
Servidor MCP local para consultar dados públicos do Cadastro Nacional de Estabelecimentos de Saúde (CNES) e transformar registros hospitalares em recortes úteis para pesquisa, qualificação de leads e exportação para CRM.
O MCP CNES usa fontes oficiais do Ministério da Saúde/DATASUS, funciona por
stdio, não exige chave de API e expõe 23 ferramentas MCP.
O que você pode fazer
localizar hospitais por município, UF, tipo, gestão, natureza jurídica e porte;
consultar razão social, CNPJ, mantenedora, endereço e contatos institucionais;
diferenciar leitos de UTI, cirúrgicos, clínicos, obstétricos e complementares;
identificar redes hospitalares pelo CNPJ da mantenedora;
detectar expansão, retração, entrada e saída entre competências;
calcular scores comerciais com pesos informados em cada chamada;
exportar seleções auditáveis em CSV, JSON, JSONL ou XLSX;
manter lotes históricos para comparação sem misturar competências.
O CNES descreve capacidade instalada. O projeto não calcula nem estima taxa de ocupação. CPF e nomes de pessoas físicas não fazem parte dos schemas, retornos ou arquivos exportados.
Related MCP server: cid10-br-mcp
Início rápido
O primeiro objetivo é fazer o cliente MCP listar as ferramentas e executar uma consulta real. O fluxo completo é:
instalar Git e uv
→ clonar o repositório
→ sincronizar o ambiente
→ configurar o cliente MCP
→ carregar uma competência
→ consultar hospitaisA versão 0.1.2 é distribuída pelo GitHub. PyPI, npm e instalação própria por
curl ainda não são canais oficiais; por enquanto, use o checkout conforme as
instruções abaixo.
Requisitos do sistema
Windows 10/11, macOS ou Linux;
Git;
uv 0.12 ou superior;
acesso HTTPS ao Portal SUS e acesso FTP ao DATASUS para a base completa;
espaço em disco compatível com os arquivos consultados.
O runtime suporta Python 3.11 ou superior. O arquivo .python-version seleciona
Python 3.14 para desenvolvimento, e o uv pode provisionar essa versão sem alterar
o Python global do sistema.
Arquivos da base completa podem ser grandes. O limite de download padrão dessa fonte é 2 GiB; escolha um diretório com espaço livre suficiente antes da primeira carga.
Setup no sistema
Instalar o uv
No Windows, instale o Git pelo site oficial ou pelo gerenciador de pacotes da sua organização. Depois, em PowerShell:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"No macOS ou Linux, instale o Git pelo gerenciador do sistema e execute:
curl -LsSf https://astral.sh/uv/install.sh | shAbra um novo terminal caso uv ainda não esteja no PATH.
Instalar a versão estável
Os mesmos comandos funcionam em PowerShell, macOS e Linux:
git --version
uv --version
git clone --branch v0.1.2 --depth 1 https://github.com/kevyn-castelo/mcp-cnes.git
cd mcp-cnes
uv sync --locked
uv run python --versionPara contribuir ou testar alterações ainda não lançadas, clone main sem
--branch e sem --depth 1.
O comando uv sync --locked recria o ambiente a partir de pyproject.toml e
uv.lock. Não reutilize a .venv copiada de outra máquina.
Verificar o servidor
No diretório do projeto, execute:
uv run mcp-cnesO processo utiliza stdio e fica aguardando um cliente MCP. Um terminal sem
prompt ou mensagens após a inicialização é esperado. Pressione Ctrl+C para
encerrar o teste manual.
Configurar no cliente MCP
Adicione um servidor chamado cnes na configuração do seu cliente. Substitua
CAMINHO_ABSOLUTO pelo diretório do checkout.
{
"mcpServers": {
"cnes": {
"command": "uv",
"args": [
"--directory",
"CAMINHO_ABSOLUTO",
"run",
"mcp-cnes"
]
}
}
}Sistema | Exemplo de caminho absoluto | Localizar |
Windows |
|
|
macOS |
|
|
Linux |
|
|
Se o cliente não encontrar uv, substitua "command": "uv" pelo caminho
absoluto retornado na última coluna.
Salve a configuração e reinicie completamente o cliente MCP. O nome e a localização
do arquivo de configuração variam entre Claude Desktop, Cursor, VS Code, Codex e
outros clientes; consulte a documentação do cliente para localizar a seção
mcpServers.
Configuração de dados e armazenamento
Sem configuração adicional, bancos, caches e arquivos remotos ficam sob
downloads/ dentro do checkout. Para separar código e dados, adicione um bloco
env ao servidor já configurado:
{
"env": {
"MCP_CNES_COLUMNAR_DATABASE_PATH": "C:/dados/mcp-cnes/cnes.duckdb",
"MCP_CNES_COLUMNAR_DIR": "C:/dados/mcp-cnes/parquet",
"MCP_CNES_OUTPUT_DIR": "C:/dados/mcp-cnes/exports"
}
}Use caminhos absolutos equivalentes em macOS ou Linux. Configure também os diretórios de importação, download e cache da tabela abaixo quando quiser manter todos os dados fora do checkout.
O arquivo .env.example serve como referência, mas o entrypoint não o carrega automaticamente: defina as variáveis no cliente MCP ou no ambiente do processo.
Variáveis mais úteis
Variável | Padrão | Finalidade |
|
| Diretório autorizado para importações CSV manuais |
|
| Banco de consultas colunares |
|
| Lotes imutáveis em Parquet |
|
| Destino permitido para exports |
|
| Artefatos baixados das fontes oficiais |
|
| Índices e metadados de cache |
|
| Quantidade de lotes concluídos retidos |
|
| TTL do cache de fontes ainda mutáveis |
|
| Limite do artefato anual do Portal SUS |
|
| Limite do ZIP mensal da base completa |
|
| Timeout HTTP em segundos |
|
| Máximo de tentativas para falhas transitórias |
Para importação manual, MCP_CNES_ALLOWED_CSV_FILES pode restringir os nomes
aceitos, separados por vírgula. Arquivos fora de MCP_CNES_DATA_DIR, links que
escapem desse diretório e CSVs acima do limite são rejeitados antes da leitura.
Configurações inválidas interrompem a inicialização com erro explícito, antes de qualquer download ou processamento.
Fazer a primeira consulta
Depois de reiniciar o cliente, experimente esta sequência em linguagem natural.
1. Verificar as fontes
Liste as fontes disponíveis no MCP CNES e informe o status de cada uma.
O cliente deve chamar cnes_list_sources e mostrar:
portal_sus_hospitais_leitos, para o contratov1;datasus_base_completa, para o contratov2.
Uma fonte externa indisponível aparece como indisponivel, com o motivo. O
servidor não transforma falhas de rede em respostas vazias.
2. Descobrir uma competência
Liste as competências do Portal SUS para 2025.
O cliente deve usar cnes_list_competencias com ano=2025 e devolver competências
mensais no formato YYYYMM.
3. Carregar os dados
Carregue a competência 202512 do Portal SUS para o Amazonas e deixe o lote ativo.
O cliente deve chamar cnes_fetch com algo equivalente a:
{
"competencia": "202512",
"uf": "AM",
"fonte": "portal_sus_hospitais_leitos",
"auto_load": true
}A resposta informa lote_id, quantidade de registros, filtros locais, ETag e se o
download usou cache. A primeira chamada pode demorar porque o Portal SUS publica
um arquivo anual completo; trocar apenas o município no mesmo ano deve reutilizar
o artefato.
4. Pesquisar hospitais
Liste os 10 maiores hospitais de Manaus por número de leitos existentes.
O cliente pode usar cnes_search_municipio com tipo_estabelecimento="HOSPITAL",
order_by="leitos_existentes" e limit=10.
Nesse ponto, a instalação está funcional: o servidor foi iniciado, uma competência foi carregada e uma consulta retornou estabelecimentos reais.
Usar o contrato v2
Para razão social, CNPJ, mantenedora, endereço, contato institucional, geolocalização qualificada, habilitações e leitos por tipo, carregue a base mensal completa:
Carregue a competência 202512 usando a fonte datasus_base_completa.
Uma consulta v2 simples já pode usar esse lote. Gatilhos e score, porém, precisam de um lote v2 retido para cada competência comparada. Antes dos exemplos de tendência, solicite também:
Carregue a competência 202012 usando a fonte datasus_base_completa.
Se houver mais de um lote v2 para a mesma competência, informe explicitamente
lote_a e lote_b. Depois, use prompts como:
“Mostre hospitais com UTI em São Paulo usando o contrato v2.”
“Agrupe as unidades por CNPJ da mantenedora e ordene pelo total de leitos.”
“Compare 202012 e 202512 e mostre expansões de pelo menos 20 leitos.”
“Calcule o score dos leads usando pesos iguais para porte, complexidade, mix pagador e tendência.”
O ZIP mensal completo pode conter centenas de milhares de estabelecimentos e leva mais tempo e espaço que a fonte anual de hospitais e leitos.
Fontes e contratos
Fonte | Cobertura | Contrato | Características |
| Hospitais, classificação e totais de leitos |
| Arquivo anual; filtros aplicados localmente |
| Dados institucionais, habilitações e leitos por tipo |
| ZIP mensal; persistência em DuckDB/Parquet |
CSV manual | Arquivo previamente aprovado pelo operador |
| Importação confinada ao diretório configurado |
O contrato v1 mantém os 11 campos canônicos originais. O contrato aditivo v2
preserva v1 e acrescenta dados institucionais, geolocalização qualificada,
habilitações e leitos desagregados.
Leia docs/fontes.md para conhecer layouts, regras de derivação, cache, limites e fontes investigadas.
Ferramentas disponíveis
As 23 ferramentas são agrupadas por objetivo:
Grupo | Ferramentas |
Ingestão e qualidade |
|
Lotes |
|
Buscas v1 |
|
Análises v1 |
|
Inteligência comercial v2 |
|
Exportação |
|
As 19 ferramentas existentes permanecem compatíveis com o contrato v1. As quatro
ferramentas comerciais usam v2; cnes_export mantém v1 por padrão e também
suporta o perfil CRM baseado em v2.
Inputs e outputs possuem JSON Schema. Parâmetros extras são rejeitados, CNES exige
sete dígitos, UF exige duas letras e limit aceita valores de 1 a 500. Falhas
recuperáveis são retornadas ao cliente como erro MCP, não como sucesso vazio.
Referências de arquivos em respostas são relativas aos diretórios configurados;
o servidor não divulga caminhos absolutos do host.
Exportar para CRM
cnes_export aceita CSV, JSON, JSONL e XLSX. Para exportar exatamente uma seleção,
informe cnes_list; para repetir uma consulta paginada, use os mesmos filtros,
limit, offset e order_by.
Exemplo de solicitação:
Exporte estes 10 códigos CNES em JSONL com perfil crm_generico.
O perfil crm_generico usa cnes:cnpj como chave de deduplicação. CSV, JSON e
JSONL recebem proveniência por registro; XLSX recebe a aba _metadados. Os
metadados incluem competência, lote, filtros, versão da fonte, timestamp e versão
do contrato.
Dados locais, cache e retenção
Um lote fica ativo por vez, mas lotes anteriores podem ser consultados pelo identificador.
A fonte anual reutiliza o download entre filtros do mesmo ano e revalida períodos ainda abertos.
A base completa mantém Parquets imutáveis por lote e consulta os dados com DuckDB.
cnes_purgefica desabilitado por padrão. O operador precisa iniciar o servidor comMCP_CNES_ALLOW_PURGE=truee cada chamada deve informarconfirmacaocomoEXCLUIR_LOTE:<lote_id>ouLIMPAR_CACHE.Não apague manualmente um banco ou Parquet enquanto o servidor estiver em uso.
Consulte docs/data-retention.md para a política mínima de dados e retenção.
Privacidade e limites de interpretação
O pipeline padrão aceita somente estabelecimentos classificados como pessoa jurídica na base completa.
CPF e nomes de responsáveis, profissionais ou diretores não são coletados, persistidos ou exportados.
Telefone, e-mail, CNPJ e endereço são tratados como dados institucionais.
No contrato
v2, campos numéricos marcados como ausentes permanecem nulos e aparecem emcampos_ausentes; o contratov1preserva sua semântica histórica.leitos_sus / leitos_existentesrepresenta mix cadastral de leitos, não taxa de ocupação.Resultados dependem da atualização e disponibilidade das fontes oficiais.
Desenvolvimento e verificação
Suíte local
# Testes determinísticos; não acessam serviços externos
uv run pytest -m "not live"
# Qualidade estática
uv run ruff check src tests benchmarks
uv run pyright
# Cobertura
uv run pytest tests/unit tests/integration -m "not live" `
--cov=mcp_cnes.domain --cov=mcp_cnes.application `
--cov-report=term-missing
# Contratos do SDK MCP
uv run pytest tests/unit/test_mcp_sdk_contract.py -m "not live"
# Artefatos de distribuição
uv buildEm macOS ou Linux, substitua o acento grave de continuação do PowerShell por \
ou execute o comando de cobertura em uma única linha.
MCP Inspector
uv run mcp dev src/mcp_cnes/mcp_app.pyTestes externos
Os testes live só acessam a internet quando explicitamente autorizados:
$env:CNES_RUN_LIVE_TESTS = "1"
uv run pytest -m live
Remove-Item Env:CNES_RUN_LIVE_TESTSO workflow Live smoke pode ser iniciado manualmente no GitHub Actions. O CI de
pull requests executa auditoria de dependências, Ruff, Pyright, testes de unidade,
integração, contratos e cobertura.
Solução de problemas
uv não é reconhecido
Abra um novo terminal após a instalação. Use where.exe uv no Windows ou
command -v uv em macOS/Linux. Se necessário, coloque o caminho absoluto no campo
command da configuração MCP.
O cliente não mostra as ferramentas
Execute
uv run mcp-cnesno diretório do projeto.Confirme que o processo permanece aguardando em
stdio.Valide o JSON do cliente e o caminho absoluto em
--directory.Reinicie completamente o cliente MCP.
Confira os logs do cliente, não apenas a janela de conversa.
uv sync --locked falha
Confirme uv --version e acesso ao índice de pacotes. A .venv é descartável,
mas remova somente a .venv deste checkout e apenas quando nenhum processo do
MCP estiver usando seus executáveis.
Uma fonte está indisponível
Use cnes_list_sources para obter o status e o motivo. Portal SUS e DATASUS são
serviços externos; tente novamente apenas quando a falha for marcada como
transitória. O servidor não substitui indisponibilidade por lista vazia.
A importação manual foi rejeitada
Confirme que o arquivo é CSV, está dentro de MCP_CNES_DATA_DIR, respeita
MCP_CNES_MAX_CSV_SIZE_BYTES e, quando configurada, consta em
MCP_CNES_ALLOWED_CSV_FILES.
O banco parece bloqueado ou inconsistente
Não apague o catálogo em uso. Encerre os clientes que executam o MCP e preserve os arquivos para diagnóstico. Use um diretório separado para smokes e validações de cutover.
Documentação adicional
Documento | Conteúdo |
Origens oficiais, campos, cache e limitações | |
Persistência, privacidade e retenção | |
Validação operacional e recuperação | |
Histórico das versões | |
Versão recomendada e endurecida | |
Histórico; substituída por inconsistência de versão | |
Histórico da release inicial | |
Reporte responsável de vulnerabilidades |
Estrutura do projeto
mcp-cnes/
├── pyproject.toml
├── uv.lock
├── src/mcp_cnes/
│ ├── domain/ # modelos e regras puras
│ ├── application/ # casos de uso e portas
│ ├── infrastructure/ # fontes, importação, persistência e exports
│ ├── interfaces/mcp/ # servidor, tools e schemas MCP
│ ├── mcp_app.py # objeto usado pelo MCP CLI e Inspector
│ └── __main__.py # entrypoint stdio
├── tests/ # testes unitários, integração e contratos
├── docs/ # fontes, retenção, cutover e releases
└── downloads/ # dados locais; ignorados pelo GitLicença e origem dos dados
O código é distribuído sob a licença MIT.
Os dados do CNES são públicos e disponibilizados pelo Ministério da Saúde/DATASUS. A licença do código não altera os termos, a disponibilidade nem a responsabilidade sobre os dados de origem.
Available Tools
6 toolscnes_download_instructionsA
Explica como obter um CSV no dashboard oficial do CNES.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| url | Yes | |
| passos | Yes | |
| titulo | Yes | |
| apos_download | Yes | |
| colunas_disponiveis | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Sem anotações, a descrição tem o ônus total de revelar o comportamento. Ela informa que é uma explicação, mas não esclarece se a saída é um texto passo a passo, um link ou outra forma, nem menciona efeitos colaterais ou requisitos. Isso é insuficiente.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A descrição é uma única frase em português, direta e sem redundância. É concisa, transmitindo a finalidade de forma imediata e sem desperdício de palavras.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Considerando a simplicidade (sem parâmetros, com output schema), a descrição é razoavelmente completa para comunicar o propósito. A existência de output schema reduz a necessidade de detalhar retornos, mas a falta de contexto sobre o formato da saída e o momento de uso impede uma nota máxima.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
A ferramenta possui zero parâmetros e o schema de entrada é vazio, com cobertura de descrição em 100%. Conforme a regra, com 0 parâmetros a linha de base é 4, e a descrição não precisa compensar detalhes de parâmetros.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
A descrição declara especificamente que a ferramenta explica como obter um CSV no dashboard oficial do CNES. O verbo 'explica' e o recurso 'CSV no dashboard' são claros, distinguindo-se das ferramentas irmãs que executam funções de busca ou carga de dados.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Não há orientação sobre quando usar esta ferramenta versus as alternativas. Não menciona que deve ser utilizada para obter instruções manuais de download, nem indica quaisquer exceções. Apenas descreve a função, sem contexto de uso.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
cnes_load_dataA
Carrega e consolida atomicamente um CSV exportado do CNES.
| Name | Required | Description | Default |
|---|---|---|---|
| filepath | Yes | Caminho para um arquivo CSV do CNES |
Output Schema
| Name | Required | Description |
|---|---|---|
| success | Yes | |
| mensagem | Yes | |
| linhas_lidas | Yes | |
| linhas_ignoradas | Yes | |
| linhas_rejeitadas | Yes | |
| registros_carregados | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must carry the transparency burden. It discloses the atomicity of the operation ('atomicamente') and the consolidation aspect, which are meaningful behavioral traits. However, it does not describe potential side effects, such as whether data is overwritten or appended, or any permission requirements.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, concise sentence that clearly states the tool's action and target resource with no unnecessary words. It earns its place and is easy to parse.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
This is a simple tool with one parameter and an output schema, so the description does not need to explain return values. It covers the core action and highlights atomicity, which is essential for a data-loading operation. However, a brief note on whether the operation replaces or appends existing data would make it more complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% because the only parameter, 'filepath', has a description. The tool description does not add further parameter semantics beyond what is already in the schema, aligning with the baseline for high schema coverage.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb 'Carrega e consolida atomicamente' (loads and atomically consolidates) with a clear resource 'CSV exportado do CNES'. This distinguishes it from sibling tools like cnes_search_municipio and cnes_statistics, which are search/analysis tools rather than load/ingest tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies the tool is used for loading CNES CSV data but does not explicitly state when to use it versus alternatives, nor does it mention any exclusions or prerequisites. The purpose is clear from context, but no direct guidance is provided.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
cnes_search_cnesA
Busca um estabelecimento pelo código CNES de sete dígitos.
| Name | Required | Description | Default |
|---|---|---|---|
| cnes | Yes | Código CNES com exatamente sete dígitos |
Output Schema
| Name | Required | Description |
|---|---|---|
| mensagem | No | |
| encontrado | Yes | |
| estabelecimento | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the burden. It indicates a read-only search operation via 'busca', but doesn't disclose return format, error handling, or whether multiple results are possible. This is a minimal behavioral disclosure for a simple read tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
One sentence, front-loaded with the verb and resource. No waste.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple with a single required parameter, and an output schema exists, so the description needn't explain return values. It adequately covers the purpose, but lacks comparative context with sibling search tools, which is a minor gap given its simplicity.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The parameter is fully described in the schema with pattern and explanation, giving 100% coverage. The description adds little beyond restating the seven-digit code, but since schema is complete, the baseline of 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses the specific verb 'Busca' (searches) and identifies the resource as an establishment, clearly stating the search key is the seven-digit CNES code. This distinguishes it from sibling tools like cnes_search_municipio and cnes_search_uf, which search by other criteria.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies the tool is used when searching by CNES code, which is clear from the phrase 'pelo código CNES'. However, it doesn't explicitly compare against alternatives or state when to prefer this over the municipality or UF searches, so it lacks explicit when-not guidance.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
cnes_search_municipioA
Busca estabelecimentos por município e faixa opcional de leitos.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Quantidade máxima de resultados | |
| municipio | Yes | Nome parcial ou completo do município | |
| max_leitos | No | Máximo inclusivo de leitos | |
| min_leitos | No | Mínimo inclusivo de leitos |
Output Schema
| Name | Required | Description |
|---|---|---|
| municipio | Yes | |
| filtros_leitos | Yes | |
| estabelecimentos | Yes | |
| total_retornados | Yes | |
| total_encontrados | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the burden of disclosing behavior. It correctly uses the verb 'Busca', implying a read-only search operation, but it does not disclose additional behavioral traits such as result limits, default pagination, or whether the search is case-sensitive. The output schema covers return values, but the description itself adds minimal behavioral context beyond the core action.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single sentence that conveys the essential purpose and scope without any filler. Every word earns its place, and it is appropriately short for a tool whose details are largely in the schema.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the output schema and 100% parameter coverage, the description is complete enough for an agent to understand the tool's function. It correctly highlights the main filters (municipality and bed range) and the tool's focus, while the output schema covers return values. The only minor gap is the lack of explicit mention of the 'limit' parameter, but the schema already documents it.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the baseline is 3. The description refers to the key parameters (municipio, min_leitos, max_leitos) through 'município' and 'faixa opcional de leitos', but it does not add any syntax, format, or interaction details beyond what the schema already provides. Therefore, it neither enhances nor detracts from the schema semantics.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states it searches establishments ('estabelecimentos') by municipality ('munícipio') and optional bed range ('faixa opcional de leitos'), using a specific verb 'Busca'. The municipality scope distinguishes it from sibling tools like cnes_search_uf, making the purpose unambiguous.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The phrase 'por município' clearly implies the intended use case for municipality-based searches, providing clear context. However, it does not explicitly exclude other use cases or mention alternatives like cnes_search_uf, so it lacks explicit exclusions but is still clear enough for an agent to infer when to use it.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
cnes_search_ufB
Busca estabelecimentos por UF e faixa opcional de leitos.
| Name | Required | Description | Default |
|---|---|---|---|
| uf | Yes | Sigla da UF com duas letras | |
| limit | No | Quantidade máxima de resultados | |
| max_leitos | No | Máximo inclusivo de leitos | |
| min_leitos | No | Mínimo inclusivo de leitos |
Output Schema
| Name | Required | Description |
|---|---|---|
| uf | Yes | |
| filtros_leitos | Yes | |
| estabelecimentos | Yes | |
| total_retornados | Yes | |
| total_encontrados | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The description gives minimal behavioral information: it implies a read-only search operation and the filtering by UF and bed range. However, it does not disclose any additional behavior such as pagination, result limits, or the nature of the response, which would be important given no annotations are provided.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, concise sentence that directly states the tool's purpose. It has no redundancy, but it is also quite sparse; it could benefit from a bit more detail without becoming verbose.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool has a comprehensive schema (100% param coverage) and an output schema, the description only needs to convey the core purpose, which it does. However, it lacks any mention of the intended use case relative to sibling tools, making it somewhat incomplete for an AI agent.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema descriptions cover all four parameters (100% coverage), so the description adds little semantic value. It does mention the 'faixa opcional de leitos' concept, but the schema already defines min_leitos and max_leitos inclusiveness, so the description adds no new dimension.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses the specific verb 'busca' (searches) and the resource 'estabelecimentos' (establishments), clearly stating the search by UF and optional bed range. This distinguishes it from sibling tools like cnes_search_municipio (different filter) and cnes_search_cnes (search by CNES).
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus the sibling tools. It only states what it does, without mentioning conditions, alternatives, or exclusions.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
cnes_statisticsA
Retorna estatísticas dos dados atualmente carregados.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| arquivo_fonte | Yes | |
| total_leitos_sus | Yes | |
| ultima_atualizacao | Yes | |
| total_estabelecimentos | Yes | |
| estabelecimentos_por_uf | Yes | |
| total_leitos_existentes | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must carry the full burden of disclosing behavior. It does not state whether the tool is read-only, what happens if no data is loaded, or any potential side effects. The only behavioral hint is the dependency on previously loaded data, which is insufficient for full transparency.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, focused sentence in Portuguese that conveys the essential purpose without unnecessary words. Every word earns its place, and it is immediately understandable.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool has no parameters and an output schema exists, the description adequately covers the prerequisites by referencing loaded data. It could be more specific about what statistics are returned, but the output schema likely captures that. The description is sufficiently complete for a simple tool.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has zero parameters, so there is nothing to document in the schema or description. Per the baseline for 0 parameters, a score of 4 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly identifies the tool's function as returning statistics for currently loaded data. The verb 'Retorna' (returns) and object 'estatísticas' specify the action and resource, and it is distinct from sibling search/load tools. However, the exact nature of the statistics is not elaborated, preventing a perfect score.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The phrase 'dados atualmente carregados' implies the tool should be used after data is loaded, providing a clear precondition for use. It does not explicitly mention alternatives or exclusions, but none are needed for a statistics tool. This gives a clear context, though not fully explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
6 tool updates
v0.1.0- First observed
cnes_download_instructions - First observed
cnes_load_data - First observed
cnes_search_cnes - First observed
cnes_search_municipio - First observed
cnes_search_uf - First observed
cnes_statistics
TDQS
Scored across 6 tools
Each tool has a clearly distinct purpose: loading data, retrieving instructions, performing three different types of searches (by municipality, CNES code, or UF), and computing statistics. There is no overlap or ambiguity between these operations.
All tools share the 'cnes_' prefix and use lowercase with underscores. Most follow a verb_target pattern (load_data, search_municipio, etc.), though 'cnes_statistics' is a noun rather than a verb, deviating slightly from the pattern.
Six tools is well-suited for a CNES data server covering ingest, guidance, multiple query methods, and statistics. The count feels neither sparse nor bloated, and each tool contributes a necessary function.
The server covers the full workflow: loading data, searching by key identifiers (CNES code, municipality, UF), and generating statistics. Minor gaps exist, such as no explicit way to clear or update loaded data, but the atomic load operation and search coverage handle core needs well.
Maintenance
Related MCP Connectors
MCP server for Brazilian Federal Senate open data (legislative, administrative, e-Cidadania).
MCP server for US nursing facility search and ownership lookup (NursingHomeDatabase).
Hosted MCP server exposing US hospital procedure cost data to AI assistants
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceMCP Server for accessing 36 Brazilian public data sources and 1 agent, enabling AI agents to query government data on economy, legislation, transparency, judiciary, elections, environment, health, and more.MIT
- AlicenseAqualityFmaintenanceMCP server for Brazilian ICD-10 (CID-10) that enables search, lookup, hierarchy navigation, statistics, and validation of disease codes from official DATASUS data.61,777 npm1MIT
- FlicenseNot gradedqualityCmaintenanceRead-only MCP server for querying Brazilian CNES health establishment data in PostgreSQL, enabling AI-assisted database exploration and analysis.-
- AlicenseNot gradedqualityCmaintenanceMCP server for querying Brazilian Federal Council of Medicine (CFM) registration data from official sources. It provides a read-only tool to consult medical registrations via natural language.MIT