Skip to main content
Glama
Porygon MCP Server

Porygon MCP Server

by CodeyLawyer
README.md
# Porygon: MCP server for Swiss energy and telecom documents

An MCP server (Streamable HTTP, API-key protected) that gives an AI agent (e.g. Microsoft Copilot
Studio, Claude) search and read access to public documents of Swiss regulators and authorities:
ElCom (directives, communications, decisions, reports, FAQs, press releases), ESTI, BFE, Swissgrid,
Pronovo, EDÖB, BACS, BAKOM, EnDK, EnergieSchweiz and commentaries on cantonal building law
(ZG, LU, NW, SG, TG, AG, GR, OW). Law texts and court decisions are deliberately not included.
A weekly crawler builds a SQLite full-text index (with local OCR for scanned PDFs). The full list
of sources, with access and usage notes, is in [`SOURCES.md`](SOURCES.md).

> **Disclaimer: use and copying at your own risk.** The software is provided "as is", without
> warranty of any kind and without any liability of the author, to the extent permitted by law
> (see sections 7 and 8 of the [Apache License 2.0](LICENSE)). In particular:
> - Independent project, not affiliated with any of the authorities or organisations named.
> - Results are extracts of documents, not legal advice and not legally binding. They may be
>   incomplete, outdated or wrong (including OCR errors); always check the original.
> - You are responsible for operating it lawfully: check the terms of use of every source before
>   you run it, in particular for public or commercial reuse, and comply with data protection and
>   your organisation's rules. No document content is part of this repository.
> - You are responsible for securing your own deployment (keys, network, updates).

> **VSE member documents (optional): access only in agreement with the VSE.** The code contains an
> optional crawler for the member area of strom.ch. It is inactive without credentials. Using it
> without the explicit permission of the VSE for automated access and for the intended use (e.g.
> processing by AI systems) is not allowed. The content is copyrighted: never publish or pass it on.
> See section 7.

| Tool | What it does |
|---|---|
| `list_weisungen(year?, query?)` | Lists directives (number, date, title) from `/de/weisungen` |
| `get_weisung(number, offset?, max_chars?)` | Extracted text of one directive PDF, e.g. `"5/2025"`, with paging |
| `list_mitteilungen(year?, query?)` | Lists communications from `/de/mitteilungen` (id, date, title) |
| `get_mitteilung(id, offset?, max_chars?)` | Extracted text of one communication PDF |
| `list_berichte(year?, query?, category?)` | Lists reports and studies from `/de/berichte-und-studien` (5 sub-pages plus "Weitere FAQ"); the 300+ weekly *Marktberichte* only appear with `category="Marktberichte"` |
| `get_bericht(id, offset?, max_chars?)` | Extracted text of one report PDF |
| `list_dokumente(kind, year?, query?)` | `kind` = ElCom `stellungnahmen`, `newsletter`, `veranstaltungen`, `verfuegungen`, `medienmitteilungen`; ESTI `esti-weisungen`, `esti-mitteilungen`; BFE `bfe`; Swissgrid `swissgrid` |
| `get_dokument(id, offset?, max_chars?)` | Extracted text of any document PDF by id (works for all `list_*` ids except directives) |
| `list_baukommentare(authority?, query?)` | Commentaries on cantonal building law: Zug, Luzern, Nidwalden, St. Gallen, Thurgau, Aargau, Graubünden, Obwalden (see `SOURCES.md`); id, category, title, url; title search only |
| `get_baukommentar(id, offset?, max_chars?)` | Text of one commentary entry (web page or PDF), with source link |
| `search_documents(query, source?, category?, limit?)` | **Full-text** search (with snippets) over the weekly index: sources `elcom`, `baurecht`, `esti`, `bfe`, `swissgrid`, `pronovo`, `edoeb`, `bacs`, `bakom`, `endk`, `energieschweiz`, `vse` (VSE only if `EXPOSE_VSE=true`); VSE content only if `EXPOSE_VSE=true` |
| `get_indexed_document(id, offset?, max_chars?)` | Indexed full text of a hit (ids from `search_documents`), paged |
| `list_neuigkeiten(since?, days?, source?, category?, limit?)` | New or changed documents in the weekly index (newest first); a source's first crawl is baseline, not news |
| `quellen_uebersicht()` | Sources with content, document counts, index state and matching tools |
| `search_faq(query?, category?, max_chars?)` | Searches the HTML FAQ pages (ElCom: Grundversorgung, Smart Meter, Stromtarife, Sunshine-Regulierung; BFE: Herkunftsnachweis); without `query` it lists the questions |

The server reads the ElCom pages live (listings cached for 1 hour, PDF text cached in memory,
max. 50 documents), so new documents appear automatically without a deployment.

Only public websites are accessed (VSE: see the warning above). No customer or personal data is
processed; do not pass such data in questions. An instruction page for users is served at `/`
(set `PUBLIC_URL`). The server's `instructions` and tool descriptions tell agents which tool to use.

## 1. Prerequisites

- Python 3.10 or newer
- VS Code (with the *Python* extension) or PyCharm
- Optional: Node.js (for the MCP Inspector), Docker (for deployment)

## 2. Set up in your IDE

Open the project folder in VS Code (`File > Open Folder`) and use the integrated terminal.

**macOS / Linux**
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
```

**Windows (PowerShell)**
```powershell
py -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
copy .env.example .env
```

Select the interpreter: `Ctrl+Shift+P` > *Python: Select Interpreter* > choose `.venv`.

Generate an API key and paste it into `.env` as `MCP_API_KEY=...`:
```bash
python -c "import secrets; print(secrets.token_urlsafe(32))"
```
The server refuses to start without a key. Never put the key into code or commit `.env`.

## 3. Run it

**VS Code:** *Run and Debug* panel, choose **ElCom MCP server**, press F5 (loads `.env`).

**Terminal (macOS/Linux):**
```bash
set -a; source .env; set +a
python server.py
```
**Terminal (PowerShell):** `$env:MCP_API_KEY="your-key"; python server.py`

The server listens on `http://127.0.0.1:8000`; the MCP endpoint is `/mcp`.

## 4. Test it

Health check (no key needed): `curl http://localhost:8000/health`

Smoke test of all sources (also usable as a monitor, see section 8):
```bash
python smoke_test.py          # needs MCP_API_KEY (and optionally MCP_URL) in the environment
```

Manual calls:
```bash
curl -s http://localhost:8000/mcp \
  -H "x-api-key: YOUR_KEY" -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
Interactive: `npx @modelcontextprotocol/inspector`, transport **Streamable HTTP**,
URL `http://localhost:8000/mcp`, header `x-api-key: YOUR_KEY`.

The minimum counts in `smoke_test.py` (`CHECKS`) show the expected sizes per source (about 44
directives, 500+ decisions, 500 building-law commentary entries, ... at the time of writing).

## 5. Connect it to Copilot Studio

Copilot Studio calls your server from Microsoft's cloud, so it needs a public HTTPS URL.

**Quick test with a tunnel** (keep the server running):
```bash
cloudflared tunnel --url http://localhost:8000      # or: devtunnel host -p 8000 --allow-anonymous
```
Add the printed hostname to `ALLOWED_HOSTS` in `.env`
(e.g. `ALLOWED_HOSTS=localhost:*,127.0.0.1:*,abc123.trycloudflare.com`) and restart.
Without this, requests fail with HTTP 421.

**In Copilot Studio:** agent > *Tools* > *Add a tool* > *Model Context Protocol* and enter

- Server URL: `https://<your-public-host>/mcp`
- Authentication: API key, header name `x-api-key`, value = your `MCP_API_KEY`

After adding tools later, refresh the MCP connection in Copilot Studio.

## 6. Hosting (production)

The server is stateless (in-memory caches only), so it runs well as one small container.
Requirements: HTTPS, a stable hostname, outbound access to `www.elcom.admin.ch:443`.

```bash
docker build -t porygon .
docker run -d --name porygon --restart unless-stopped \
  -p 127.0.0.1:8000:8000 --env-file .env porygon
```

Options (clarify with your IT / information security first):

| Option | Notes |
|---|---|
| **Azure Container Apps** (or App Service for Containers) | Fits Copilot Studio; HTTPS and a hostname included; store `MCP_API_KEY` as a secret / Key Vault reference; 1 replica, small size (0.25 vCPU / 0.5 GB is enough) |
| **Own Docker host + reverse proxy** (Caddy/nginx) | Proxy terminates TLS and forwards to the container. `docker-compose.yml` and `deploy/porygon.caddy` are a ready example (no published ports; the proxy reaches the service on the `edge` Docker network) |

Settings for any option:
- `ALLOWED_HOSTS` = public hostname (e.g. `mcp.example.org`); `HOST=0.0.0.0` inside the container (already set in the Dockerfile).
- `PUBLIC_URL` = `https://<hostname>/mcp`, shown on the instruction page.
- **Rate limit** (built in, per client address): `RATE_LIMIT_PER_MIN` (default 300) and, after
  `AUTH_FAIL_LIMIT` wrong keys (default 10) within `AUTH_FAIL_WINDOW` seconds (default 600), a block
  with HTTP 429 until the window has passed. The client address is the last `X-Forwarded-For` entry
  set by your proxy; set `TRUST_PROXY=false` if the server is reachable directly. Counters live in
  memory (one process), so a restart resets them. Keep the proxy-level limits too.
- Use a long random `MCP_API_KEY`, rotate it regularly and whenever it leaks (update Copilot Studio too).
- Run a single replica or several; they share nothing, caches just warm up per instance.

## 7. Weekly crawler and full-text index

`crawler.py` builds a SQLite full-text index (`PORYGON_DB`, table `docs` with FTS5) that powers
`search_documents`. It indexes ElCom documents (not the weekly Marktberichte), the building-law
commentaries and, if credentials are set, the VSE documents (PDFs only).

- **Schedule:** the crawler container runs `python crawler.py --loop`. A source is crawled again
  when its last successful run is older than 7 days, starting in the hour `CRAWL_HOUR` (default 3,
  container time = UTC), optionally only on `CRAWL_WEEKDAY` (0 = Monday ... 6 = Sunday; the minimum
  interval is then 5 days). The very first run starts immediately.
- **Low load:** one request at a time, 3 s pause plus jitter, conditional requests (ETag /
  Last-Modified) and content hashes (unchanged files are not processed again), robots.txt honoured,
  abort on HTTP 429 or after 5 consecutive failures. Container limit: 0.5 CPU, 768 MB.
- **OCR for scanned PDFs:** the crawler image contains Tesseract (languages
  deu, fra, eng) and recognises PDFs without a text layer locally, page by page (200 dpi, max. 120
  pages and ~25 min per document, about 25-30 s per page at 0.5 CPU). The text starts with a notice
  that it was recognised automatically. Nothing leaves the server. Documents are OCR'd once;
  `OCR_LANGS`, `OCR_DPI`, `OCR_MAX_PAGES` can be set in `.env.crawler`. The server image has no OCR.
- **Removed documents** disappear from the index after a complete run.
- **Manual run:** `python crawler.py --once --sources baurecht` (add `--limit 5` for a test).
- **Local test without Docker:** `PORYGON_DB=data/porygon.db python crawler.py --once --limit 5`.

### VSE (strom.ch) credentials

> **Warning: only in agreement with the VSE.** Do not enable this part unless the VSE has
> explicitly permitted automated access to its member area and the intended use (including
> processing by AI systems and making the content available to an AI agent). The content is
> copyrighted and may be member-only: do not publish it or hand it to third parties. Without
> credentials the crawler skips VSE.

1. Copy `.env.crawler.example` to `.env.crawler` and enter `VSE_USER` / `VSE_PASSWORD` **yourself in
   your editor** (never in a chat, never in code). Only the crawler container reads this file.
   Use a dedicated account if the VSE allows it.
2. Test once: `docker compose run --rm crawler python crawler.py --once --sources vse --limit 5`.
   Check the log: "N documents listed, M PDFs". A login failure (form changed, 2-factor, captcha)
   is reported as `VSE login failed`.
3. VSE content stays **hidden from the MCP tools** until you set `EXPOSE_VSE=true` in `.env`
   (do this only after the VSE terms for AI use are clarified in writing, and keep the endpoint
   private to authorised users).
4. The login form `/de/user/login` is disallowed in the VSE robots.txt; the automated login is only
   acceptable with the VSE's permission (see `SOURCES.md`).

## 8. Keeping it up to date

**Content is always current.** Listings are re-read from elcom.admin.ch at most once per hour
and PDFs are fetched on demand. A restart clears the caches, which is harmless.

What needs care is the *parser*: if ElCom changes its page layout, the listings become empty
or the tool returns `No documents found`. Plan for this:

1. **Monitor.** Run `smoke_test.py` on a schedule (e.g. daily; Azure Monitor availability test,
   GitHub Actions cron, Windows Task Scheduler or cron) with `MCP_URL` and `MCP_API_KEY` set.
   Exit code 1 means a source no longer parses (the minimum counts are in `CHECKS`).
   Also watch `/health` for liveness.
2. **Fix.** The page parser is `parse_listing` (documents) and `parse_faq` (FAQs) in `server.py`.
3. **Rebuild the image regularly** (e.g. monthly) to pick up security updates of Python and
   the dependencies in `requirements.txt`; pin and test upgrades of the `mcp` package, its API
   changes between versions.
4. **Redeploy** with the usual CI/CD or `docker build` + `docker run`.

## 9. Adding more data later

- **New website for the full-text index only:** add a `Site` to `sites.py` (sitemap + include/exclude patterns on the URL path, or lists of PDFs), add its host to `sites.EXTRA_HOSTS`, the source name to `CRAWL_SOURCES`, and to `SOURCE_LABEL` / `_search_sources` in `server.py`.
- **New document page** with the same ElCom download list: add it to `COLLECTIONS` (or
  `BERICHTE_PAGES`) in `server.py`. It is then available via `list_dokumente(kind)`, `get_dokument`.
- **New FAQ page** with accordions: add it to `FAQ_PAGES`.
- **New tool:** add a function decorated with `@mcp.tool()`. Give it a clear docstring; the
  agent chooses tools based on it.
- **Other domains / authorities:** add the host to `ALLOWED_FETCH_HOSTS`, write a small parser and record the source in `SOURCES.md` (only after approval). Keep an explicit allowlist.

## Security notes

- Tools accept no URLs; documents are looked up by number or id, and every outgoing request,
  including redirects, must target an https host in `ALLOWED_FETCH_HOSTS` (ElCom and the approved authorities).
- All endpoints except `/health` and the instruction page `/` need the API key (`x-api-key` or
  `Authorization: Bearer`, compared in constant time). Per-client rate limit and a block after
  repeated wrong keys (section 6).
- The instruction page has no scripts and a strict Content-Security-Policy; it contains no secrets.
- Never commit `.env` or `.env.crawler`. Rotate the key if it leaks.
- Container hardening in `docker-compose.yml`: read-only root file system, no capabilities,
  `no-new-privileges`, memory and CPU limits, non-root user.
- Report vulnerabilities privately to the repository owner (GitHub security advisory), not in a public issue.
- PDF size is capped at 25 MB. Results from this server are extracts of public documents;
  verify them against the original PDF before relying on them (legal and regulatory topics
  should be checked by the responsible department).

## Troubleshooting

| Symptom | Likely cause |
|---|---|
| `MCP_API_KEY is not set` on start | `.env` not loaded. Use the VS Code launch config or export the variables |
| 401 Unauthorized | Missing or wrong key header |
| 421 Misdirected Request | Hostname not in `ALLOWED_HOSTS` |
| `No documents found` / smoke test fails | ElCom page layout changed or the page was unreachable; check logs, adjust parser |
| `no extractable text` | The PDF is a scan and has not been OCR'd yet (the crawler does that on its next run) or the OCR found too little text; open the original |

## Licence

The source code is licensed under the [Apache License 2.0](LICENSE). Copyright 2026 CodeyLawyer.
If you redistribute or build on it, keep the licence text and the [NOTICE](NOTICE) file, retain the
copyright notices and mark changed files as changed (Apache-2.0, sections 4a to 4d).

The licence covers the code only, **not** the documents of authorities or associations that the
software reads: their own terms of use apply (see `SOURCES.md`). The VSE crawler additionally
requires the VSE's agreement (see the warning at the top).