Senado BR MCP Server
Brazilian Federal Senate open data over MCP — 90 tools across the legislative process, Senate administration (CEAPS expenses, payroll, contracts) and the e-Cidadania portal. Cloudflare Workers, Streamable HTTP, no auth. Responses in pt-BR.
Documentation
senado-br-mcp (Cloudflare Workers)
A public, hosted MCP server for Brazilian Senate open data, running on Cloudflare Workers (Streamable HTTP). It is already deployed and open access — just point your MCP client at the hosted endpoint; no installation, no account, no API key required.
Provides 65 tools (plus 4 prompts and 5 resources) organized into 19 groups covering the legislative domain (senators, bills, votes, committees, plenary sessions and results, presidential vetoes, party-bloc voting orientation, legislative processes, reference data, citizen participation via e-Cidadania, speeches and stenographic transcripts, blocs and leadership, federal legislation, committee voting) and the administrative domain (CEAPS parliamentary quota expenses, housing allowance, civil servants and payroll, overtime, interns, procurement contracts, biddings, outsourced staff, petty-cash funds, budget execution and own revenues). Connects to three sources: the legislative open data API, the administrative open data API and the e-Cidadania portal.
v2.1.0: all tools that consumed endpoints marked deprecated upstream (the legacy
/materia/*family and/senador/{codigo}/votacoes) were migrated to the v3/processoand/votacaoAPIs, keeping tool names and output keys stable.v2.2.0: adds the administrative domain (groups O, P, Q, R — 16 tools) consuming
adm.senado.gov.br. Large datasets (CEAPS ≈ 10 MB/year, payroll ≈ 5.5 MB/month) are fetched once, cached, and filtered/aggregated inside the Worker — tools never return raw dumps.v2.3.0: every tool now declares MCP annotations (
readOnlyHint,openWorldHint) and a structured-output schema; canonical endpoint moved to the custom domainhttps://senado.sidneybissoli.com/mcp(the*.workers.devURL still works as a fallback).v3.0.0: consolidated 90 → 65 tools by merging near-duplicate tools into enum/secao/tipo parameters (e.g. reference tables →
senado_tabelas_referencia; per-process sub-resources →senado_processo_detalhe;senado_mesawith acasaparam;senado_search_votacoesabsorbing the recent-votes/list tools). Breaking change: several tool names were removed or renamed.v3.1.0: adds the MCP prompts capability (4 reusable pt-BR workflow templates — CEAPS expenses, bill tracking, senator votes, e-Cidadania overview) and the resources capability (5 static context docs: usage guide, tool catalog, glossary, and the tipos-matéria / UFs reference tables). Ships a
LICENSEfile (MIT).
Use it (hosted — no setup)
This is a remote, hosted, open-access server. To use it, point any MCP client at the Streamable HTTP endpoint — no install, no account, no API key, no configuration:
https://senado.sidneybissoli.com/mcp
Install (any client)
For clients that launch MCP servers as a command — and for one-command setup — use the
mcp-remote bridge. No build, no config, no key:
npx -y mcp-remote https://senado.sidneybissoli.com/mcp
- One-click (LobeHub): open the server page and click Install.
- Native remote URL (Claude Desktop/Code and other Streamable-HTTP clients): see Connecting MCP Clients.
Everything below Architecture (Prerequisites, Setup, Deploy) is only for optionally self-hosting your own instance — it is not required to use this public server.
Architecture
- Runtime: Cloudflare Workers (ESM)
- Transport: Streamable HTTP (MCP spec 2025-03-26) via
createMcpHandlerfromagents/mcp - Protocol: MCP over JSON-RPC — single
/mcpendpoint handles POST, GET, DELETE - SDK:
@modelcontextprotocol/sdk1.26.0+ (per-request McpServer instances) - Validation: Zod schemas for all tool inputs
- Caching: 2-layer (L0 memory + L1 Cache API) with SHA-256 keying
- e-Cidadania store: D1 database refreshed by a Cron Trigger (every 2h) — list tools read from D1 with a live-scrape fallback and a staleness flag; detail tools stay live with write-through (see e-Cidadania)
- Rate limiting: Token bucket — global (8 req/s) + per-client (2 req/s)
- Upstream throttle: Max 6 concurrent requests, 10s timeout, retry with exponential backoff
- Auth: Optional Bearer token (set the
API_KEYsecret; open access when unset). Constant-time comparison. - Observability: Structured JSON logging + in-memory counters exposed at
/metrics - Tests: Vitest unit tests for parsers, helpers, cache, throttle, and auth
Self-hosting (optional)
Not needed to use the server — it is already hosted at
https://senado.sidneybissoli.com/mcp(open access). Follow this section only if you want to run your own private instance.
Prerequisites
- Node.js 18+
- Wrangler CLI v4+
- Cloudflare account
Setup
1. Install dependencies
npm install
2. Create KV namespace
# Create the KV namespace
wrangler kv namespace create CACHE_KV
# Note the ID from the output, e.g.:
# { binding = "CACHE_KV", id = "abc123..." }
3. Configure wrangler.toml
Replace the placeholder KV namespace ID:
[[kv_namespaces]]
binding = "CACHE_KV"
id = "YOUR_KV_NAMESPACE_ID_HERE"
Optionally set ALLOWED_ORIGIN to restrict CORS:
[vars]
ALLOWED_ORIGIN = "https://your-app.example.com"
The e-Cidadania pipeline needs a D1 database and a Cron Trigger (both already declared in wrangler.toml — replace the database ID):
[[d1_databases]]
binding = "ECIDADANIA_DB"
database_name = "senado-ecidadania"
database_id = "YOUR_D1_DATABASE_ID_HERE"
[triggers]
crons = ["0 */2 * * *"]
Create the database (paste the returned ID above) and apply the schema:
npx wrangler d1 create senado-ecidadania
npx wrangler d1 migrations apply senado-ecidadania --remote
The list tools fall back to live scraping when D1 is empty, so the server works before the first Cron run.
4. (Optional) Enable authentication
wrangler secret put API_KEY
# Clients must then send: Authorization: Bearer <key>
# When API_KEY is not set, the server is open access.
5. Local development
npm run dev
# Dev server runs locally on port 8787 (local only).
# The public MCP endpoint is https://senado.sidneybissoli.com/mcp
6. Tests and typecheck
npm test # run all tests once
npm run test:watch # watch mode
npm run typecheck # tsc --noEmit
7. Deploy
npm run deploy
# Serves at https://senado.sidneybissoli.com (custom domain) and
# https://senado-br-mcp.sidneybissoli.workers.dev (workers.dev fallback)
Endpoints
| Path | Methods | Description |
|---|---|---|
/mcp | POST, GET, DELETE, OPTIONS | MCP Streamable HTTP endpoint (managed by createMcpHandler) |
/health | GET | Health check — returns ok (always public) |
/metrics | GET | JSON counters: requests, tool calls, cache hits/misses, upstream calls/retries/errors, auth failures (always public) |
MCP Request Examples
All requests go to POST /mcp with JSON-RPC 2.0 format.
List available tools
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}
Call a tool — List senators from SP
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "senado_listar_senadores",
"arguments": {
"uf": "SP",
"emExercicio": true
}
}
}
Call a tool — Search bills by keyword
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "senado_buscar_materias",
"arguments": {
"palavraChave": "inteligência artificial",
"tramitando": true
}
}
}
Call a tool — Get recent plenary votes
{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "senado_search_votacoes",
"arguments": {
"dias": 7
}
}
}
Call a tool — Most popular citizen ideas
{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "senado_ecidadania_listar_ideias",
"arguments": {
"ordenarPor": "apoios",
"ordem": "desc",
"status": "aberta"
}
}
}
Upstream API Endpoints
The server consumes two classes of upstream endpoints from the Senado API:
Legacy endpoints (.json suffix, PascalCase responses)
Used by Groups A, E, F, H, I, J, K, L, M, N. The .json suffix is appended automatically by upstream.ts. None of these is marked deprecated upstream.
| Upstream path | Used by |
|---|---|
/senador/lista/atual | senado_listar_senadores |
/senador/lista/legislatura/{legislatura} | senado_listar_senadores (param legislatura) |
/senador/{codigo} | senado_obter_senador |
/senador/{codigo}/licencas, /comissoes, /cargos, /historicoAcademico, /filiacoes, /profissao | senado_senador_historico (tipo enum) |
/senador/afastados | senado_senadores_afastados |
/senador/{codigo}/apartes | senado_discursos_senador (tipo=apartes) |
/comissao/lista/colegiados | senado_listar_comissoes (+ sigla-to-code resolution) |
/comissao/{codigo} | senado_obter_comissao (secao=resumo; numeric code, not sigla) |
/composicao/comissao/{codigo} | senado_obter_comissao (secao=membros) |
/comissao/agenda/{data} | senado_agenda_comissoes |
/comissao/agenda/{dataInicio}/{dataFim} | senado_reunioes_comissao |
/comissao/reuniao/{codigoReuniao} | senado_reuniao_comissao |
/comissao/cpi/{sigla}/requerimentos | senado_requerimentos_cpi (empty body = no requests) |
/materia/distribuicao/autoria, /distribuicao/relatoria/{sigla} | senado_distribuicao_materias |
/plenario/agenda/dia/{data}, /agenda/mes/{data}, /agenda/cn/... | senado_agenda_plenario |
/plenario/resultado/{data}, /resultado/cn/{data}, /resultado/mes/{data} | senado_resultado_plenario |
/plenario/resultado/veto/{codigo} (+ /materia/, /dispositivo/) | senado_resultado_veto |
/plenario/votacao/orientacaoBancada/{data} (+ período) | senado_orientacao_bancada |
/plenario/encontro/{codigo} (+ /pauta, /resultado, /resumo) | senado_encontro_plenario |
/plenario/tiposSessao, /lista/tiposComparecimento, /lista/legislaturas | senado_tabelas_plenario |
/materia/vetos/{ano}, /vetos/aposrcn, /vetos/antesrcn, /vetos/encerrados | senado_vetos |
/taquigrafia/notas/{sessao|reuniao}/{id} | senado_notas_taquigraficas |
/taquigrafia/videos/{sessao|reuniao}/{id} | senado_videos_taquigrafia |
/senador/{codigo}/discursos | senado_discursos_senador |
/plenario/lista/discursos/{dataInicio}/{dataFim} | senado_discursos_plenario |
/discurso/texto-integral/{codigo} | senado_discurso_texto (plain text, fetched directly) |
/senador/lista/tiposUsoPalavra | senado_tabelas_referencia (tabela=tipos-uso-palavra) |
/composicao/lista/blocos | senado_listar_blocos |
/composicao/bloco/{codigo} | senado_obter_bloco |
/composicao/lideranca | senado_liderancas |
/composicao/mesaSF | senado_mesa (casa=senado) |
/composicao/mesaCN | senado_mesa (casa=congresso) |
/orcamento/lista | senado_orcamento_parlamentar (tipo=emendas) |
/orcamento/oficios | senado_orcamento_parlamentar (tipo=oficios) |
/legislacao/lista | senado_buscar_legislacao |
/legislacao/{codigo} | senado_obter_legislacao |
/legislacao/tiposNorma | senado_tabelas_referencia (tabela=tipos-norma) |
/votacaoComissao/comissao/{sigla} | senado_votacao_comissao (por=comissao) |
/votacaoComissao/parlamentar/{codigo} | senado_votacao_comissao (por=senador) |
/votacaoComissao/materia/{sigla}/{numero}/{ano} | senado_votacao_comissao (por=materia) |
/autor/lista/atual | senado_autores_atuais |
v3 endpoints (flat JSON arrays/objects, camelCase)
Used by Groups B, C, D. Dates must be in ISO format (YYYY-MM-DD) — tools accept YYYYMMDD and convert. The codigoMateria query param bridges legacy matéria codes to v3 processes.
| Upstream path | Used by |
|---|---|
/votacao | senado_obter_votacao, senado_search_votacoes, senado_votos_materia, senado_votacoes_senador |
/processo | senado_search_processos, senado_buscar_materias |
/processo/{id} | senado_obter_processo, senado_obter_materia (secao=detalhe/tramitacao) |
/processo/documento | senado_obter_materia (secao=textos) |
/processo/emenda | senado_processo_detalhe (secao=emendas) |
/processo/relatoria | senado_processo_detalhe (secao=relatorias), senado_obter_materia (rapporteur) |
/processo/prazo | senado_processo_detalhe (secao=prazos) |
/processo/{siglas,assuntos,classes,destinos,entes,tipos-*} | senado_tabelas_processo (12 reference tables) |
Administrative API (adm.senado.gov.br/adm-dadosabertos, flat snake_case JSON)
Used by Groups O, P, Q, R via admFetch (no .json suffix; HTTP 404 treated as empty collection). Base URL configurable via SENADO_ADM_BASE_URL.
| Upstream path | Used by |
|---|---|
/api/v1/senadores/despesas_ceaps/{ano} | senado_ceaps (~10 MB/year, cached + aggregated in-Worker) |
/api/v1/senadores/{auxilio-moradia,escritorios,aposentados} | senado_senadores_admin (tipo enum) |
/api/v1/servidores/servidores/{ativos,efetivos,comissionados,inativos} | senado_servidores |
/api/v1/servidores/remuneracoes/{ano}/{mes} | senado_remuneracoes_servidores (~5.5 MB/month) |
/api/v1/servidores/horas-extras/{ano}/{mes} | senado_horas_extras |
/api/v1/servidores/quantitativos/*, /previsao-aposentadoria, /api/v1/senadores/quantitativos/senadores | senado_pessoal_tabelas (quantitativos) |
/api/v1/servidores/{estagiarios,pensionistas,lotacoes,cargos} | senado_pessoal_tabelas (listas nominais) |
/api/v1/contratacoes/contratos (+ /{id}/aditivos) | senado_contratos, senado_contratacao_detalhe |
/api/v1/contratacoes/{tipo}/{id}/{itens,pagamentos,garantias} | senado_contratacao_detalhe |
/api/v1/contratacoes/licitacoes | senado_licitacoes |
/api/v1/contratacoes/terceirizados | senado_terceirizados |
/api/v1/contratacoes/empresas | senado_empresas_contratadas (~13 MB, requires filter) |
/api/v1/contratacoes/{atas_registro_preco,notas_empenho,menores_aprendizes} | senado_contratacoes_lista |
/api/v1/supridos/{ano} (+ atosConcessao, empenhos, movimentacoes, transacoes) | senado_suprimento_fundos |
senado.gov.br/bi-arqs/Arquimedes/Financeiro/{Despesa,Receitas}SenadoDadosAbertos.json | senado_execucao_orcamentaria (daily JSON feeds, Brazilian decimal strings normalized) |
e-Cidadania (D1-backed, Cron-refreshed)
The e-Cidadania list data (consultas, ideias, eventos) is persisted in a D1 database and refreshed by a Cron Trigger (0 */2 * * *) instead of being scraped on every call. The scheduled job (src/scraper/pipeline.ts) scrapes the internal REST highlight endpoints (restcolecaomaismateria, restcolecaomaisideia, restcolecaomaisaudiencia — the top ~5 per entity, not the full corpus; these endpoints have no pagination), then:
- upserts
ecidadania_current(one row per item — what the tools read), - appends
ecidadania_historyonly when an item'scontent_hashchanges (time-series-ready), - records each run in
ecidadania_scrape_runs.
An anomaly guard (src/scraper/anomaly.ts) ensures a failed or anomalous run (zero rows, or fewer than ECIDADANIA_ANOMALY_MIN_PCT% of the last good run) never overwrites the last good state.
The list / analysis tools (listar_*, consultas_analise, sugerir_tema_enquete) read from D1 via resolveList (src/scraper/store.ts): D1-first, with a graceful live-scrape fallback when D1 is empty or stale (older than ECIDADANIA_STALE_MAX_MIN minutes). Every list response carries an additive meta (fonte, lastScrapedAt, possivelDesatualizacao) so callers always see the data's real age and never get stale data silently.
The detail tools (obter_*) stay live (HTML scraped with CSS-class-targeted regex) for freshness, and write their richer payload through to ecidadania_detalhe fire-and-forget (deduped by content_hash), so detail history accrues without adding latency to the response.
The list endpoints track the portal's highlighted collections (a few items per entity) plus their time series — not the complete e-Cidadania corpus. Full-corpus ingestion via the paginated
/pesquisa*HTML pages is a separate, deferred effort.
Caching
Layer architecture
| Layer | Storage | Scope | TTL range | Purpose |
|---|---|---|---|---|
| L0 | In-memory Map | Per-isolate | 30-300s | Ultra-fast, eliminates redundant requests within a Worker isolate |
| L1 | Cloudflare Cache API (caches.default) | Per-colo (PoP) | 60-600s | Shared across requests at the same edge location |
| L2 | KV (optional) | Global | Variable | Reserved for rare, low-write data |
Cache categories
| Category | L0 TTL | L1 TTL | Used for |
|---|---|---|---|
| STATIC | 300s | 600s | Legislation types, static reference |
| SEMI_STATIC | 120s | 300s | Party list, UF list, committee details |
| DYNAMIC | 30s | 60s | Agendas, recent votes, meeting lists |
| ON_DEMAND | 30s | 120s | Specific bill/senator/vote lookups |
POST caching approach
MCP uses POST for all tools/call requests. Caching POST responses is not natively supported by the Cache API, which requires GET requests. The solution:
- Hash parameters — Tool name + sorted parameters are hashed with SHA-256
- Synthetic GET key — A synthetic URL
https://senado-br-mcp.internal/__cache/{tool}/{hash}is constructed - Cache API match/put — The synthetic GET URL is used with
caches.default.match()andcaches.default.put(), allowing standard Cache API operations on POST-originated data
This caching happens at the tool level (inside each tool's callback), not at the MCP transport level.
Tool Inventory
Group H — Reference/Metadata (1 tool)
| Tool | Description |
|---|---|
senado_tabelas_referencia | Tabelas de referência via tabela enum: tipos-materia, partidos, ufs, legislatura-atual, tipos-norma, tipos-uso-palavra |
Group A — Senators (5 tools)
| Tool | Description |
|---|---|
senado_listar_senadores | Lista senadores em exercício/por legislatura, com filtros nome (busca parcial sem acento), uf e partido |
senado_obter_senador | Detalhe biográfico de um senador: bio, mandatos, partido, contato |
senado_votacoes_senador | Como um senador votou em cada matéria (via v3 /votacao) |
senado_senador_historico | Histórico funcional via tipo enum: licencas, comissoes, cargos, historico-academico, filiacoes, profissoes |
senado_senadores_afastados | Senadores atualmente afastados (fora de exercício) |
Group B — Bills/Matters (2 tools, v3 backend)
| Tool | Description |
|---|---|
senado_buscar_materias | Busca matérias por tipo, número, ano, palavra-chave, autor ou tramitação (via v3 /processo) |
senado_obter_materia | Dados de uma matéria via secao enum: detalhe (situação/relator), tramitacao (histórico) ou textos (documentos) |
Group C — Processes (5 tools)
| Tool | Description |
|---|---|
senado_search_processos | Busca processos legislativos (complementar à busca de matérias) |
senado_obter_processo | Detalhes completos de um processo legislativo específico |
senado_processo_detalhe | Aspecto de um processo via secao enum: emendas, relatorias ou prazos |
senado_autores_atuais | Parlamentares autores de processos em tramitação, ordenados por produção |
senado_tabelas_processo | 12 tabelas de referência (siglas, assuntos, classes, tipos-*) via tabela enum |
Group D — Votes (3 tools)
| Tool | Description |
|---|---|
senado_obter_votacao | Detalhes de uma votação com votos nominais. Aceita codigoVotacao (codigoSessao da sessão plenária). |
senado_votos_materia | Votações de uma matéria (via v3 /votacao?codigoMateria), com votos nominais opcionais |
senado_search_votacoes | Busca/listagem flexível de votações do plenário por dias, período, processo, matéria ou senador |
Group E — Committees (7 tools)
| Tool | Description |
|---|---|
senado_listar_comissoes | Lista comissões (colegiados) ativas, filtráveis por tipo |
senado_obter_comissao | Dados de uma comissão via secao enum: resumo (mesa/totais) ou membros (composição). Resolve sigla para código internamente. |
senado_reunioes_comissao | Reuniões de uma comissão num período (lida com intervalos entre anos) |
senado_agenda_comissoes | Agenda de reuniões de todas as comissões numa data |
senado_reuniao_comissao | Detalhe completo de uma reunião: partes, itens, convidados, resultados, links pauta/ata |
senado_requerimentos_cpi | Requerimentos protocolados numa CPI em atividade, paginados |
senado_distribuicao_materias | Estatísticas de carga por senador numa comissão: autoria ou relatoria |
Group F — Plenary (7 tools)
| Tool | Description |
|---|---|
senado_agenda_plenario | Plenary schedule — by day, month or Congress (escopo dia/mes/cn) |
senado_resultado_plenario | Session results: items deliberated, opinions, outcomes (SF/CN/month) |
senado_orientacao_bancada | Party leadership voting instructions per vote, with tallies |
senado_vetos | Presidential vetoes by year or tramitation status |
senado_resultado_veto | Nominal veto vote results (by veto, vetoed bill or device) |
senado_encontro_plenario | Legislative session detail, agenda items, results or summary |
senado_tabelas_plenario | Session types, attendance types, legislatures list |
Group G — e-Cidadania (8 tools)
| Tool | Description |
|---|---|
senado_ecidadania_listar_consultas | Consultas públicas com votação sim/não dos cidadãos |
senado_ecidadania_obter_consulta | Detalhe de uma consulta: votos, autor, relator, comentários |
senado_ecidadania_consultas_analise | Analisa consultas via modo enum: consenso (alta concordância) ou polarizada (~50/50) |
senado_ecidadania_listar_ideias | Ideias legislativas de cidadãos; ranking das mais apoiadas via ordenarPor: apoios |
senado_ecidadania_obter_ideia | Detalhe de uma ideia: texto, apoios, status de conversão em projeto |
senado_ecidadania_listar_eventos | Eventos interativos (audiências, sabatinas, lives); ranking dos mais comentados via ordenarPor |
senado_ecidadania_obter_evento | Detalhe de um evento: pauta, convidados, link de vídeo |
senado_ecidadania_sugerir_tema_enquete | Sugere temas para enquete mensal a partir de critérios configuráveis |
Group I — Speeches (3 tools)
| Tool | Description |
|---|---|
senado_discursos_senador | Pronunciamentos de um senador via tipo enum: discursos (próprios) ou apartes (intervenções) |
senado_discursos_plenario | Todos os discursos em plenário num intervalo de datas |
senado_discurso_texto | Texto integral de um pronunciamento/discurso específico |
Group J — Blocs & Leadership (4 tools)
| Tool | Description |
|---|---|
senado_listar_blocos | Blocos parlamentares do Senado e seus partidos membros |
senado_obter_bloco | Detalhes de um bloco parlamentar específico |
senado_liderancas | Lideranças do Senado/Congresso (líderes, vice-líderes), filtráveis |
senado_mesa | Membros da Mesa Diretora via casa enum: senado (Mesa do SF) ou congresso (Mesa do CN) |
Group K — Budget (1 tool)
| Tool | Description |
|---|---|
senado_orcamento_parlamentar | Dados de emendas orçamentárias via tipo enum: emendas (lotes) ou oficios (ofícios de apoio) |
Group L — Federal Law (2 tools)
| Tool | Description |
|---|---|
senado_buscar_legislacao | Busca normas jurídicas federais por tipo, número, ano ou data (ao menos um obrigatório) |
senado_obter_legislacao | Detalhes de uma norma jurídica federal específica |
Group M — Committee Voting (1 tool)
| Tool | Description |
|---|---|
senado_votacao_comissao | Votações em comissões via por enum: comissao, senador ou materia; período opcional |
Group N — Taquigrafia (2 tools)
| Tool | Description |
|---|---|
senado_notas_taquigraficas | Official transcripts of plenary sessions or committee meetings — summary mode with excerpts, full-text mode paginated in blocks, speaker filter |
senado_videos_taquigrafia | Video/audio units per session or meeting, with speaker and media links |
Group O — Senadores/Administrativo (2 tools)
| Tool | Description |
|---|---|
senado_ceaps | CEAPS parliamentary quota expenses by year — aggregated by senator, expense type, month or supplier, or itemized detail; filters by senator/month/type/supplier |
senado_senadores_admin | Dados administrativos dos senadores via tipo enum: auxilio-moradia, escritorios-apoio ou aposentados |
Group P — Servidores / Gestão de Pessoas (4 tools)
| Tool | Description |
|---|---|
senado_servidores | Civil servants by status (active/effective/commissioned/inactive), filterable by name, unit, position |
senado_remuneracoes_servidores | Monthly payroll — summary by payroll type or per-person composition with computed gross |
senado_horas_extras | Overtime payments by month with totals |
senado_pessoal_tabelas | Tabelas de pessoal via tabela enum: quantitativos (pessoal, cargos-funcoes, previsao-aposentadoria, senadores) e listas (estagiarios, pensionistas, lotacoes, cargos) |
Group Q — Contratações (6 tools)
| Tool | Description |
|---|---|
senado_contratos | Contracts with server-side filters: supplier, CNPJ, year, number, object, labor |
senado_contratacao_detalhe | Items, payments, guarantees, amendments or activations of a contract/ata/empenho |
senado_licitacoes | Biddings by number or object text |
senado_terceirizados | Outsourced collaborators by name, company or unit |
senado_empresas_contratadas | Companies contracting with the Senate (requires name/CNPJ filter) |
senado_contratacoes_lista | Price-registration atas, commitment notes, young apprentices |
Group R — Suprimento de Fundos (1 tool)
| Tool | Description |
|---|---|
senado_suprimento_fundos | Petty-cash advances by year: recipients, concession acts, commitments, movements, card transactions |
Group S — Orçamento do Senado (1 tool)
| Tool | Description |
|---|---|
senado_execucao_orcamentaria | Budget execution since 2013 (allocation, committed/settled/paid) and own revenues since 2012 (forecast vs collected) — aggregated by year, action, expense group, source or revenue origin |
Total: 65 tools
Prompts (4)
Reusable pt-BR workflow templates (MCP prompts capability), defined in src/prompts.ts:
| Prompt | Args | What it guides |
|---|---|---|
senado_gastos_senador | senador, ano | Resolve o senador e agrega/detalha despesas CEAPS. |
senado_tramitacao_materia | sigla, numero, ano | Obtém situação atual + histórico de tramitação da matéria. |
senado_votos_senador | senador, periodo? | Lista os votos nominais do senador no período. |
senado_panorama_ecidadania | — | Consolida consultas (consenso/polarização), ideias e eventos populares. |
Resources (5)
Static context documents/tables (MCP resources capability), defined in src/resources.ts:
| URI | Type | Content |
|---|---|---|
senado://guia | markdown | Visão geral e qual ferramenta usar por objetivo. |
senado://catalogo | markdown | As 65 ferramentas agrupadas por domínio. |
senado://glossario | markdown | Siglas e termos do Senado (PEC, CEAPS, CCJ, RCN…). |
senado://tabelas/tipos-materia | json | Tipos de proposição (sigla/nome/descrição). |
senado://tabelas/ufs | json | As 27 unidades federativas. |
Project Structure
src/
├── index.ts # Worker entrypoint (fetch handler + scheduled/Cron handler)
├── server.ts # McpServer factory (creates per-request instance)
├── auth.ts # Optional Bearer token auth (constant-time compare)
├── metrics.ts # In-memory counters served at /metrics
├── types.ts # Env, cache categories, safeguard constants
├── cache/
│ ├── l0-memory.ts # In-memory Map cache with TTL + LRU eviction
│ ├── l1-cache-api.ts # Cloudflare Cache API wrapper (synthetic GET keys)
│ └── manager.ts # Cache orchestrator (L0 → L1 → upstream)
├── throttle/
│ ├── token-bucket.ts # Token bucket rate limiter (global + per-client)
│ └── upstream.ts # Upstream fetch with concurrency limit, retry, timeout
├── scraper/
│ ├── ecidadania.ts # Isolated e-Cidadania scraper (REST lists + regex HTML detail)
│ ├── pipeline.ts # Cron sync: scrape → upsert current + append-on-change history
│ ├── anomaly.ts # Run classification (anomalous run never overwrites current)
│ └── store.ts # D1 reads (resolveList + staleness) + detail write-through
├── instrument.ts # Per-tool call telemetry (in-memory + Analytics Engine)
├── utils/
│ ├── logger.ts # Structured JSON logging
│ └── validation.ts # toolResult, toolError, errorFrom, buildParams, ensureArray helpers
└── tools/
├── referencia.ts # Group H — 1 reference/metadata tool
├── senadores.ts # Group A — 5 senator tools
├── materias.ts # Group B — 2 bill/matter tools (v3 backend)
├── processos.ts # Group C — 5 process tools
├── votacoes.ts # Group D — 3 vote tools
├── comissoes.ts # Group E — 7 committee tools
├── plenario.ts # Group F — 7 plenary tools
├── ecidadania.ts # Group G — 8 e-Cidadania tools (read from D1; see scraper/)
├── discursos.ts # Group I — 3 speech tools
├── composicao.ts # Group J — 4 bloc/leadership tools
├── orcamento.ts # Group K — 1 budget tool
├── legislacao.ts # Group L — 2 federal law tools
├── votacao-comissao.ts # Group M — 1 committee voting tool
├── taquigrafia.ts # Group N — 2 stenographic record tools
├── senadores-admin.ts # Group O — 2 admin senator tools (CEAPS, housing)
├── servidores.ts # Group P — 4 personnel tools
├── contratacoes.ts # Group Q — 6 procurement tools
├── supridos.ts # Group R — 1 petty-cash tool
└── orcamento-senado.ts # Group S — 1 budget execution tool
migrations/ # D1 schema (0001 tables, 0002 indexes) for the e-Cidadania pipeline
tests/ # Vitest unit tests mirroring src/ (parsers, cache, throttle, auth, scraper,
# pipeline/anomaly/store, plus e-Cidadania contract tests over real fixtures)
Environment Variables
| Variable | Required | Default | Description |
|---|---|---|---|
SENADO_BASE_URL | No | https://legis.senado.leg.br/dadosabertos | Legislative API base URL |
SENADO_ADM_BASE_URL | No | https://adm.senado.gov.br/adm-dadosabertos | Administrative API base URL |
ALLOWED_ORIGIN | No | * | CORS allowed origin |
API_KEY | No (secret) | — | When set, requires Authorization: Bearer <key> on all requests except /health, /metrics, and CORS preflight |
CACHE_KV | Yes (binding) | — | KV namespace for L2 cache |
ECIDADANIA_DB | Yes (binding) | — | D1 database for the e-Cidadania pipeline (list persistence + history) |
ECIDADANIA_STALE_MAX_MIN | No | 360 | Minutes before D1-backed e-Cidadania reads flag possible staleness and fall back to live |
ECIDADANIA_ANOMALY_MIN_PCT | No | 50 | A Cron run returning fewer than this % of the last good run's rows is anomalous and won't overwrite current |
SENADO_ANALYTICS | No (binding) | — | Analytics Engine dataset for per-tool call telemetry |
Connecting MCP Clients
This is a remote server (Streamable HTTP, no install, open access) — point any MCP client at
https://senado.sidneybissoli.com/mcp. Besides 65 tools, it exposes prompts (ready-made pt-BR
workflows: senado_gastos_senador, senado_tramitacao_materia, senado_votos_senador,
senado_panorama_ecidadania) and resources (senado://guia, senado://catalogo,
senado://glossario, senado://tabelas/tipos-materia, senado://tabelas/ufs).
One-click (LobeHub)
Install from the LobeHub marketplace — open the server page and click Install (it pre-fills the remote endpoint, no config needed).
Claude Desktop / Claude Code
Add to your MCP configuration:
{
"mcpServers": {
"senado-br": {
"url": "https://senado.sidneybissoli.com/mcp"
}
}
}
For command-based clients (or any client without native remote support), use the mcp-remote bridge:
{
"mcpServers": {
"senado-br": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://senado.sidneybissoli.com/mcp"]
}
}
}
MCP Inspector
npx @modelcontextprotocol/inspector https://senado.sidneybissoli.com/mcp
License
MIT
Credits
Icon: "Amanhecer no Congresso Nacional" — photograph of the Brazilian National Congress, used under a Creative Commons license. (If you are the author, open an issue so we can add full attribution / the license link.)