Back to Browse

Senado Br Mcp Cloudflare MCP Server

Cloud & DevOpsModerate5.2MCP RegistryLocalRemote
Free

Server data from the Official MCP Registry

MCP server for Brazilian Federal Senate open data (legislative, administrative, e-Cidadania).

About

MCP server for Brazilian Federal Senate open data (legislative, administrative, e-Cidadania).

Remote endpoints: streamable-http: https://senado.sidneybissoli.com/mcp

Security Report

5.2
Moderate5.2Moderate Risk

The server is a public, hosted, no-auth MCP server that queries official Brazilian Senate open-data APIs, and its declared network_http and D1/cache use match its purpose. The visible code shows no exfiltration, shell execution, or hardcoded secrets; the truncated sources limit full verification, so the score is a conditional assessment based on the excerpts provided. Supply chain analysis found 12 known vulnerabilities in dependencies (0 critical, 6 high severity). Package verification found 1 issue.

5 files analyzed · 17 issues found

Security scores are indicators to help you make informed decisions, not guarantees. Always review permissions before connecting any MCP server.

Permissions Required

This plugin requests these system permissions. Most are normal for its category.

HTTP Network Access

Connects to external APIs or services over the internet.

env_vars

Check that this permission is expected for this type of plugin.

database

Check that this permission is expected for this type of plugin.

File System Read

Reads files on your machine. Normal for tools that analyze or process local data.

How to Install & Connect

Available as Local & Remote

This plugin can run on your machine or connect to a hosted endpoint. during install.

Documentation

View on GitHub

From the project's GitHub README.

Senado Brasil MCP Server

Cloudflare Workers MCP Tools CI MCP Registry LobeHub LightNow capabilities senado-br-mcp-cloudflare MCP server smithery badge GitHub stars GitHub Sponsors License: MIT Status

🇧🇷 Leia em Português

A public, hosted MCP server that gives AI assistants live, structured access to Brazilian Senate open data — no installation, no account, no API key. Point your MCP client at the hosted endpoint and start asking about senators, bills, votes, expenses, and more. It runs on Cloudflare Workers over Streamable HTTP.

It exposes 69 tools, 4 prompts, and 5 resources across two domains:

  • Legislative — senators; bills and their tramitation; votes; committees; plenary sessions, results and presidential vetoes; party-bloc voting orientation; speeches and stenographic transcripts; blocs and leadership; federal legislation; and citizen participation via the e-Cidadania portal.
  • Administrative — CEAPS parliamentary-quota expenses; housing allowance; civil servants and payroll; overtime; interns; procurement contracts and biddings; outsourced staff; petty-cash funds; and budget execution.

Data comes from three official sources — the legislative open-data API, the administrative open-data API, and the e-Cidadania portal. All tool responses are in Portuguese (pt-BR). See CHANGELOG.md for release history.

See it in action

Point a client at the endpoint and ask in plain language — English or Portuguese:

  • "How did São Paulo's senators vote in the most recent floor votes?" → senado_search_votacoes
  • "Show the legislative progress of PEC 45/2019 (a constitutional amendment proposal)." → senado_buscar_materias + senado_obter_materia
  • "How much was spent on the CEAPS parliamentary allowance in 2024, broken down by expense type?" → senado_ceaps

The answers come live from the Senate's official open-data APIs — exact figures with provenance, not numbers guessed from training data.

Compared with the alternatives

Other Brazilian MCP servers also touch the Senate — mcp-brasil and mcp-dados-br are multi-source aggregators in which the Senate is one source among many. The difference is coverage and how you run it. Measured in each one's source code on 2026-10-11:

Senate toolsCoversWhere it runs
senado-br-mcp (this)69legislative, administrative (CEAPS, staff, contracts, budget) and e-Cidadania, with provenance on every answerhosted, no install or key; or npx
mcp-brasil 0.14.026legislative (senators, bills, floor votes, committees, agenda) — plus dozens of other government sourceslocal or self-hosted (Python)
mcp-dados-br 0.6.03sitting senators, bill list, vote tally — plus IBGE, BCB, INMET, Chamber of Deputieslocal (Python)

Pick an aggregator when the question crosses the Senate with the Chamber of Deputies, the electoral court (TSE) or the Transparency Portal. Pick this server for expenses (CEAPS), staff, contracts, budget, speeches, committee votes, vetoes or e-Cidadania — areas the others don't cover. Full per-area table, side-by-side examples and how to re-measure (in Portuguese): docs/comparativo-alternativas.md.

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

OpenAI / ChatGPT app surface

For OpenAI Apps SDK submission and review, the Worker also exposes a curated MCP surface:

https://senado.sidneybissoli.com/mcp/openai-app-v2

This endpoint intentionally keeps the full public MCP server intact at /mcp, but limits tool discovery to 27 high-signal, intent-oriented tools for ChatGPT app use. /mcp/openai-app remains available as a legacy alias, but new ChatGPT app configurations should use /mcp/openai-app-v2 so clients fetch the current tool schema. The tools still call the same handlers and return the same provenance envelope; only the advertised surface is narrower. Any ChatGPT app listing should present this as an independent open-data research app, not as an official Senate, OpenAI or ChatGPT connector.

For ChatGPT Apps, those 27 tools also advertise a shared MCP Apps UI template at ui://senado-br-mcp/openai-app-dashboard-v2.html. The self-contained widget renders the returned structuredContent as a compact dashboard with metrics, main records, and source/provenance, without adding another model-visible data tool.

Public legal URLs for app review:

  • Privacy policy: https://senado.sidneybissoli.com/privacy
  • Terms of use: https://senado.sidneybissoli.com/terms

ChatGPT (Deep Research)

ChatGPT deep research (and company knowledge, and research workflows over the Responses API) only uses an MCP server that exposes exactly search and fetch — this server does, on top of the senado_* tools, on the full /mcp surface (not on the curated app profile). Point the connector at the hosted endpoint, no key required:

https://senado.sidneybissoli.com/mcp

search ranks the query against the senators in office and the active committees of the Senate and the National Congress and returns { id, title, url } (sen:<código> / com:<código>); fetch returns the document as readable Markdown — the senator's biography and mandates, or the committee's summary and board — with the canonical public page (the senator's profile on www25.senado.leg.br or the committee page on legis.senado.leg.br), which is what ChatGPT cites. Both carry the same provenance block as every other tool, in structuredContent and _meta (the text channel is the contract's JSON). In ChatGPT's developer mode (Settings → Security and login → Developer mode) any tool is callable — the senado_* tools remain the ones to use for data.

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.

Run locally (npx · stdio)

Prefer not to route queries through a third-party host (e.g. a newsroom policy)? The same server also runs as a local stdio process that talks directly to the official government APIs — same 69 tools, same provenance envelope, no Cloudflare in the loop. This is the npm/stdio channel, published as senado-br-mcp.

Point a command-based client (Claude Desktop/Code, etc.) at the package — npm fetches and runs it, no clone or build:

{
  "mcpServers": {
    "senado-br": {
      "command": "npx",
      "args": ["-y", "senado-br-mcp"]
    }
  }
}

To run it directly or hack on it, use the source checkout instead:

git clone https://github.com/SidneyBissoli/senado-br-mcp-cloudflare
cd senado-br-mcp-cloudflare
npm install
npm run build
node dist/cli.js   # serves MCP over stdio (Ctrl+C to stop)

Parity with the hosted server: the legislative and administrative tools are identical (same upstream APIs, same throttle/cache/provenance) — locally the L1 Cloudflare cache is a no-op, but the L0 in-memory cache still works, so results are the same. The only difference is the e-Cidadania list/corpus tools: without D1 they fall back to a live scrape of the ~5 REST highlights, flagged via meta.fonte / possivelDesatualizacao; the detail tools (obter_*) are identical. Logs go to stderr — stdout carries only the JSON-RPC protocol stream.

Agent Skill (optional)

This repo bundles a Claude Agent Skill at .claude/skills/senado-br/ that teaches Claude when to reach for this server and how to use its 69 tools well — a themed tool map, common question→tool playbooks, the provenance contract, and gotchas (dates, the codigoMateria bridge, e-Cidadania's open-set listing, pagination). It points back to the server's own senado://catalogo / senado://guia resources rather than duplicating them.

Claude Code auto-discovers it when you work in this repo. To use it elsewhere, copy .claude/skills/senado-br/ into your ~/.claude/skills/, or zip the folder and upload it in claude.ai (Settings → Features). The skill assumes the senado-br MCP server is connected (hosted or via npx).

Architecture

  • Runtime: Cloudflare Workers (ESM)
  • Transport: Streamable HTTP (MCP spec 2025-03-26) via createMcpHandler from agents/mcp
  • Protocol: MCP over JSON-RPC — /mcp handles the full public server; /mcp/openai-app-v2 exposes a curated 27-tool profile plus a shared MCP Apps widget for OpenAI app review/submission (/mcp/openai-app remains as a legacy alias)
  • SDK: @modelcontextprotocol/server 2.x (per-request McpServer instances; the v1 @modelcontextprotocol/sdk is not installed — agents still lists it as a peer, satisfied via legacy-peer-deps)
  • Validation: Zod schemas for all tool inputs
  • Caching: 2-layer (L0 memory + L1 Cache API) with SHA-256 keying
  • e-Cidadania store: D1 database — since 3.26.0 every e-Cidadania tool reads the daily copy of the dataset (layer 3, c3_* tables) with per-block origin and collection instant; the corpus (refreshed daily + 2h Cron) answers only for items not yet in the copy, and the live scrape only when neither has them (see e-Cidadania)
  • Rate limiting: Token bucket — global (8 req/s) + per-client (2 req/s)
  • Upstream throttle: Max 6 concurrent requests, 10s budget per trip, retry on 429/5xx/network with exponential backoff and Retry-After (portfolio shared fetch @sbissoli/mcp-upstream); every response's provenance carries the measured retrieval diagnostics (trips, attempts, anomalies)
  • Auth: Optional Bearer token (set the API_KEY secret; open access when unset). Constant-time comparison.
  • Observability: Structured JSON logging + in-memory counters at /metrics; per-tool call telemetry (selection, error rate, cache-vs-live) in Cloudflare Analytics Engine, PII-free
  • Liveness: Runs on Cloudflare's own global network behind a custom domain — no third-party host that can go dark. Public /health and /status (version + last-deploy id/timestamp) make uptime and the current build verifiable; the status badge above pings the live endpoint
  • 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 22+ (engines.node)
  • 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

PathMethodsDescription
/GETLanding page (pt-BR) — identifies the client behind the outgoing User-Agent: what the service is, load posture, contact (always public)
/mcpPOST, GET, DELETE, OPTIONSMCP Streamable HTTP endpoint (managed by createMcpHandler)
/healthGETHealth check — returns ok (always public)
/statusGETJSON: status, version, and last-deploy metadata (deploy.id/tag/timestamp) — liveness + current build, no MCP handshake needed (always public)
/metricsGETJSON counters: requests, tool calls, cache hits/misses, upstream calls/retries/errors, auth failures (always public)
/.well-known/mcp/server-card.jsonGETMCP server card for directory scanners (Smithery): serverInfo, authentication, tools/resources/prompts — generated from the live full profile by @sbissoli/mcp-surface/card (always public)

Surface fingerprint, checkable from the registry

Every release publishes, in its MCP Registry entry, the sha256 of the surface /mcp serves (initialize, tools, resources, prompts of the full profile) and which methods answer there without a credential. A surface change without a version bump fails the build; the fingerprint in the registry lets a client check the same thing on its own side. Canonical form and procedure: SPEC.md of @sbissoli/mcp-surface. To check it yourself (Node 18+, no dependencies):

curl -sO https://raw.githubusercontent.com/SidneyBissoli/mcp-br-commons/main/packages/mcp-surface/exemplos/verify.mjs
node verify.mjs io.github.SidneyBissoli/senado-br-mcp-cloudflare

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 pathUsed by
/senador/lista/atualsenado_listar_senadores
/senador/lista/legislatura/{legislatura}senado_listar_senadores (param legislatura; emExercicio crossed with /senador/lista/atual)
/senador/{codigo} (+ /mandatos)senado_obter_senador (biografia + mandatos via chamada extra)
/senador/{codigo}/licencas, /comissoes, /cargos, /historicoAcademico, /filiacoes, /profissaosenado_senador_historico (tipo enum)
/senador/afastadossenado_senadores_afastados, senado_listar_senadores (emExercicio: false)
/senador/{codigo}/apartessenado_discursos_senador (tipo=apartes)
/comissao/lista/colegiadossenado_listar_comissoes (+ sigla-to-code resolution)
/comissao/{codigo}senado_obter_comissao (secao=resumo; numeric code, not sigla)
/composicao/comissao/{codigo} (+ ?ativas=S)senado_obter_comissao (secao=membros)
/comissao/agenda/{data}senado_agenda_comissoes, senado_reunioes_comissao (one read per day)
/comissao/agenda/{dataInicio}/{dataFim}senado_reuniao_comissao (by sigla, last 14 days)
/comissao/reuniao/{codigoReuniao}senado_reuniao_comissao
/comissao/cpi/{sigla}/requerimentossenado_requerimentos_cpi (upstream often empty even for active CPIs — empty result carries an aviso)
/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/legislaturassenado_tabelas_plenario
/materia/vetos/{ano}, /vetos/aposrcn, /vetos/antesrcn, /vetos/encerradossenado_vetos
/taquigrafia/notas/{sessao|reuniao}/{id}senado_notas_taquigraficas
/taquigrafia/videos/{sessao|reuniao}/{id}senado_videos_taquigrafia
/senador/{codigo}/discursossenado_discursos_senador
/plenario/lista/discursos/{dataInicio}/{dataFim}senado_discursos_plenario
/discurso/texto-integral/{codigo}senado_discurso_texto (plain text, fetched directly)
/senador/lista/tiposUsoPalavrasenado_tabelas_referencia (tabela=tipos-uso-palavra)
/composicao/lista/blocossenado_listar_blocos
/composicao/bloco/{codigo}senado_obter_bloco
/composicao/liderancasenado_liderancas
/composicao/mesaSFsenado_mesa (casa=senado)
/composicao/mesaCNsenado_mesa (casa=congresso)
/orcamento/listasenado_orcamento_parlamentar (tipo=emendas)
/orcamento/oficiossenado_orcamento_parlamentar (tipo=oficios)
/legislacao/listasenado_buscar_legislacao
/legislacao/{codigo}senado_obter_legislacao
/legislacao/tiposNormasenado_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/atualsenado_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 pathUsed by
/votacaosenado_obter_votacao, senado_search_votacoes, senado_votos_materia, senado_votacoes_senador
/processosenado_search_processos, senado_buscar_materias
/processo/{id}senado_obter_processo, senado_obter_materia (secao=detalhe/tramitacao)
/processo/documentosenado_obter_materia (secao=textos)
/processo/emendasenado_processo_detalhe (secao=emendas)
/processo/relatoriasenado_processo_detalhe (secao=relatorias), senado_obter_materia (rapporteur)
/processo/prazosenado_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 pathUsed by
/api/v1/senadores/despesas_ceaps/{ano}senado_ceaps (~10 MB/year, cached + aggregated in-Worker)
/api/v1/senadores/{auxilio-moradia-imoveis-funcionais,escritorios-apoio,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/senadoressenado_pessoal_tabelas (quantitativos)
/api/v1/servidores/{pensionistas,lotacoes,cargos}, /api/v1/colaboradores/estagiariossenado_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/licitacoessenado_licitacoes
/api/v1/contratacoes/terceirizadossenado_terceirizados
/api/v1/contratacoes/empresassenado_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.jsonsenado_execucao_orcamentaria (daily JSON feeds, Brazilian decimal strings normalized)

e-Cidadania (D1-backed, Cron-refreshed)

The e-Cidadania list data is persisted in a D1 database (ecidadania_current/_history/_scrape_runs, discriminated by entidade; plus ecidadania_comentarios for the audiência comment level and ecidadania_detalhe_cursor for the resumable detail backfill — added in schema v2) and read from there instead of being scraped on every call. Three cadences write into it:

  • a daily off-Worker GitHub Action owns the full corpus of the three live entities (consultas, eventos, ideias; see below) — the source of truth. Daily (not weekly) because the first-seen series MIN(scraped_at) is the only measurable entry-rhythm signal and every skipped day permanently shortens it (ROADMAP Etapa 2, decisão D3);
  • a weekly ingest Action (.github/workflows/verify-consultas-votos.yml — historical filename) for the consultas_votos acervo: the Senado republishes the Arquimedes CSV periodically (confirmed 2026-07-20), so the weekly run re-ingests the current vintage under the same anomaly guards as the other corpora (see below);
  • an in-Worker Cron Trigger (0 */2 * * *, src/scraper/pipeline.ts → refreshEcidadania) does only a targeted metric splice of the ~5 REST highlights per live entity (restcolecaomaismateria/ideia/audiencia — votos/comentários/apoios), recorded as ok-metrica so it never re-breaks the corpus baseline and never touches the long tail. In v2 the eventos splice preserves the corpus's canonical comment count (the daily crawl is the source of truth for comentarios, so the splice can't ping-pong it against the degraded REST count).

Both writers build payloads through the canonical buildXResumo builders + shared contentHash, so their rows are byte-identical. Each write:

  • upserts ecidadania_current (one row per item — what the tools read),
  • appends ecidadania_history only when an item's content_hash changes (time-series-ready),
  • records each run in ecidadania_scrape_runs.

An anomaly guard (src/scraper/anomaly.ts, classifyRun) ensures a failed or anomalous corpus run (zero rows, or fewer than ECIDADANIA_CORPUS_MIN_PCT% of the last good run) never overwrites the last good state.

The list / analysis tools (listar_*, consultas_analise, sugerir_tema_enquete, consultas_votos) read from D1 via resolveList (src/scraper/store.ts): D1-first. Because every entity is now a full corpus, a stale corpus is served from D1 flagged (possivelDesatualizacao: true) rather than collapsing to the ~5-item live highlights (the original coverage bug); the live scrape is reserved for an empty D1 (cold start, before the first weekly run). Staleness uses ECIDADANIA_CORPUS_STALE_MAX_MIN (~10 days). 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.

Since 3.26.0 (ROADMAP D3) the tools read layer 3 first. The daily observations job (observacoes-ecidadania.yml) projects the published dataset tables it builds (scripts/publicacao/) into D1 as c3_* tables (scripts/publicacao/projetar-d1.ts; names in src/scraper/camada3-tabelas.ts; DDL generated from the 3.0.0 dictionary), writing only the rows that changed since the last applied projection (a key × hash snapshot kept in the private bucket). src/scraper/camada3.ts reads them: lists filter/sort/page in SQL, obter_ideia adds serieApoios and situacaoNoTempo, obter_consulta adds serieVotos (change points only, capped at 60 with a cut notice), and every item says where and when each page block came from (origem…/coletadoEm…, the dictionary names). Items not yet in layer 3 come from the corpus (marked corpus); obter_* of an item in neither falls back to the live path above. Without the c3_* tables (stdio channel, cold D1) every tool behaves as described above.

Since 3.27.0 (ROADMAP E1) obter_consulta and obter_ideia also return materiasOficiais: the official bill each item is tied to (Senate codigoMateria or Chamber proposition id — the consultation id already is the bill code; an idea's proposition is read from the link the portal publishes, never by name), its identification, the reading status at the official source, and the authors with their role (iniciativa = who introduced it, texto = author of the text under consideration, camara = Chamber), codigoParlamentar (follow with senado_obter_senador) or idDeputado. Read from c3_vinculos_materias / c3_vinculos_autores (dataset tables vinculos/materias and vinculos/autores, built from the official API responses the autoria job archives daily); D1 keeps only what the tools show (no links of the per-UF vote archive). Without those tables the field is absent.

Full-corpus ingestion (off-Worker)

The three live e-Cidadania corpora are owned by the daily Action (.github/workflows/ingest-ecidadania.yml), each with its own scripts/ingest-ecidadania/index-*.ts orchestrator emitting batched out-*.sql the apply step bulk-loads:

  • consultas — open consultations (detailed below). In v2 each crawled matter is also enriched from its detail page (visualizacaomateria) for autoria/relator; those are immutable, so only rows not yet enriched are fetched.
  • eventos — audiências/eventos from the principalaudiencia?p=N HTML listing; status comes straight from the listing block (no /processo bridge). In v2 every event is enriched from its detail page (canonical data/hora + comissaoNomeCompleto/local/descricao/pauta/convidados/videoUrl) and its AJAX comment fragment (canonical count + one ecidadania_comentarios row per comment, diffed against the stored hashes and emitted as out-eventos-comentarios-*.sql).
  • ideias — ideias legislativas (~113.7k) from pesquisaideia?situacao=N&p=M, crawled per situacao bucket (the listing has no inline status) and emitted in ~10k-statement batches. In v2 the listing crawl preserves the immutable detail fields, and a separate resumable backfill (index-ideias-detalhe.ts, run via ingest:ecidadania:ideias-detalhe) fills them a chunk per run — because ~113.7k detail fetches don't fit one Action, it persists a cursor in ecidadania_detalhe_cursor and wraps around at the end.

The fourth entity, consultas_votos, is a separate historical acervo of votes-by-UF parsed from the ~33 MB Arquimedes CSV (Proposições-com-votos.csv), aggregated to one record per matéria with a votosPorUf breakdown. The CSV's "dados atualizados até" stamp becomes the provenance data_vintage; it is excluded from the row hash (consultaVotoCore) so a re-ingest with unchanged votes doesn't churn _history. STATUS ATUAL is uniformly "Descontinuado", hence archival, not a migration of the open consultations. Served by senado_ecidadania_consultas_votos with provenance pointing at the CSV (ECIDADANIA_ARQUIMEDES). It is excluded from the daily job and owned by its own weekly ingest Action (.github/workflows/verify-consultas-votos.yml — the filename keeps the historical verify- prefix): the acervo was originally treated as a frozen single vintage (ROADMAP Etapa 2, decisão D1) and the weekly run only verified it, but on 2026-07-20 the Senado republished the CSV as a fresh vintage (+43 matérias, 648 updated), so the scheduled run now re-ingests the current vintage under the standard anomaly guards (empty/truncated CSV and the catastrophic floor still fail without writing; force dispatch overrides the floor). The script's verify mode (INGEST_CONSULTAS_VOTOS_VERIFY=1 / --verify) remains available as an on-demand integrity check.

The consultas job is the reference implementation:

consultas covers the full set of OPEN consultations — every matter currently in tramitação (~7.7k), not just the ~5 highlights. Confirmed on the first run: the pesquisamateria listing is in-tramitação-only, so closed/historical consultations are not captured by this source (a pre-ingestion historical backfill is out of scope). Three settled design decisions:

  1. Decoupled ingestion. The open set is acquired by an off-Worker TypeScript job (scripts/ingest-ecidadania/, run by a daily GitHub Action — .github/workflows/ingest-ecidadania.yml) that paginates the HTML listing (pesquisamateria?p=1..N, the only full-coverage source for open consultations) for ids + vote counts and bulk-loads D1; the Worker only reads. The brittle, long crawl is kept out of the request/Cron path.
  2. Status from /processo, not HTML. A consultation runs from presentation until the end of tramitação, so status is a function of the matter: aberta ⟺ the codigoMateria is in the /processo tramitando=S set, derived from robust JSON (never scraped). Every consultation enters as aberta (the listing only yields in-tramitação matters); on each complete run the job re-derives status for all stored rows by /processo membership (not by listing-absence, which can be transient), so a consultation whose matter leaves tramitação flips to encerrada. The encerrada/todas sets therefore grow over time; consultations that closed before the first ingestion aren't captured (out of scope). The list/analysis tools default to status: aberta.
  3. Two reconciled cadences (one shared writer contract). The job reuses contentHash + the ConsultaResumo builder + classifyRun from src/scraper/, so its rows are byte-identical to the Cron's. The daily job owns the long tail; the 2h Cron keeps the ~5 hot/open highlights fresh via a targeted metric splice (recorded as ok-metrica, bypassing the corpus classifyRun baseline). Corpus freshness (possivelDesatualizacao) is computed from the last status='ok' run and uses a larger window (ECIDADANIA_CORPUS_STALE_MAX_MIN), and a stale consultas corpus is served from D1 flagged rather than collapsing back to the live highlights.

Write guards on the load: an incomplete crawl (any page failed) or an incomplete /processo status universe writes only an erro run row; even a complete crawl is rejected by a catastrophic floor (ECIDADANIA_CORPUS_MIN_PCT, default 80% of the last good corpus) to guard against a degraded page — overridable with --force / INGEST_FORCE=1 for a legitimate large shrink. Run daily via the Action, or manually:

CLOUDFLARE_API_TOKEN=… npm run ingest:ecidadania                 # writes scripts/ingest-ecidadania/out.sql
npx wrangler d1 execute senado-ecidadania --remote --file=scripts/ingest-ecidadania/out.sql

Caching

Layer architecture

LayerStorageScopeTTL rangePurpose
L0In-memory MapPer-isolate30-300sUltra-fast, eliminates redundant requests within a Worker isolate
L1Cloudflare Cache API (caches.default)Per-colo (PoP)60-600sShared across requests at the same edge location
L2KV (optional)GlobalVariableReserved for rare, low-write data

Cache categories

CategoryL0 TTLL1 TTLUsed for
STATIC300s600sLegislation types, static reference
SEMI_STATIC120s300sParty list, UF list, committee details
DYNAMIC30s60sAgendas, recent votes, meeting lists
ON_DEMAND30s120sSpecific 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:

  1. Hash parameters — Tool name + sorted parameters are hashed with SHA-256
  2. Synthetic GET key — A synthetic URL https://senado-br-mcp.internal/__cache/{tool}/{hash} is constructed
  3. Cache API match/put — The synthetic GET URL is used with caches.default.match() and caches.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.

Provenance

Every tool attaches a provenance envelope so a result is traceable back to its official source — provenance is treated as a first-class part of the answer, not an optional extra (the audience is journalists and political-science researchers, for whom an un-sourced figure is unusable). The envelope implements the portfolio-wide provenance contract (@sbissoli/mcp-provenance): the server builds and validates a full canonical model per response, and emits its concise projection — a fixed-order block with explicit null for unknown fields; responses that merge several upstream reads also list each part with its own extraction instant (field_sources), and the block's retrieved_at is then the oldest of them. The block lives in structuredContent.provenance (parseable by clients; note the advertised per-tool output schema is permissive, so contract validation happens server-side at build time, in the package) and is mirrored as a compact source footer in the text content for clients that only render text — the data JSON itself is not duplicated with the envelope, to keep the per-response token cost low.

Coverage spans all four upstream sources, each with its own source/citation/license (in src/utils/provenance.ts):

  • Senado Federal — Dados Abertos (Legislativo) — legis.senado.leg.br/dadosabertos
  • Senado Federal — Dados Abertos (Administrativo) — adm.senado.gov.br/adm-dadosabertos
  • Senado Federal — Execução Orçamentária e Financeira — Arquimedes/Financeiro feed at senado.gov.br
  • Senado Federal — Portal e-Cidadania — www12.senado.leg.br/ecidadania

Fields of the concise block (contract v1.3 since 3.18.5; per response — one tool, one source; keys in this fixed order; the first seven are always present, with null when the source does not expose the value; the optional ones are absent, never empty, when they do not apply):

Documentation truncated — see the full README on GitHub.

Reviews

No reviews yet

Be the first to review this server!