dictcc-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ permissions:
11
+ id-token: write # required for PyPI trusted publishing (OIDC)
12
+ contents: read
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+ - run: pip install build
19
+ - run: python -m build
20
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,61 @@
1
+ name: Publish to MCP Registry
2
+
3
+ # Official MCP Registry (registry.modelcontextprotocol.io) via GitHub OIDC.
4
+ # No secret, no interactive login: the runner's OIDC token proves ownership
5
+ # of the io.github.mohammad-abbasi-sh/* namespace.
6
+ # Refs: https://github.com/modelcontextprotocol/registry
7
+
8
+ on:
9
+ push:
10
+ tags: ["v*"]
11
+ workflow_dispatch:
12
+
13
+ jobs:
14
+ publish:
15
+ runs-on: ubuntu-latest
16
+ permissions:
17
+ id-token: write # required for OIDC -> MCP Registry
18
+ contents: read
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+
22
+ - name: Sync server.json version to tag
23
+ # Only sync when running on a version tag (v*). On workflow_dispatch
24
+ # (ref = refs/heads/main) keep the version committed in server.json.
25
+ run: |
26
+ VER=""
27
+ if [[ "$GITHUB_REF" == refs/tags/* ]]; then
28
+ TAG="${GITHUB_REF#refs/tags/}"
29
+ VER="${TAG#v}"
30
+ fi
31
+ if [ -n "$VER" ]; then
32
+ python3 - "$VER" << 'EOF'
33
+ import json, sys
34
+ ver = sys.argv[1]
35
+ d = json.load(open('server.json'))
36
+ d['version'] = ver
37
+ for pkg in d.get('packages', []):
38
+ pkg['version'] = ver
39
+ json.dump(d, open('server.json', 'w'), indent=2, ensure_ascii=False)
40
+ print('server.json version ->', ver)
41
+ EOF
42
+ else
43
+ echo "No version tag ($GITHUB_REF); keeping server.json version as-is"
44
+ fi
45
+
46
+ - name: Install mcp-publisher
47
+ run: |
48
+ curl -sL "https://github.com/modelcontextprotocol/registry/releases/download/v1.8.7/mcp-publisher_linux_amd64.tar.gz" -o /tmp/mcp-publisher.tar.gz
49
+ tar -xzf /tmp/mcp-publisher.tar.gz -C /tmp
50
+ sudo mv /tmp/mcp-publisher /usr/local/bin/mcp-publisher
51
+ mcp-publisher --version
52
+
53
+ - name: Validate server.json
54
+ run: mcp-publisher validate server.json
55
+
56
+ - name: Publish to MCP Registry (OIDC)
57
+ run: |
58
+ mcp-publisher login github-oidc
59
+ mcp-publisher publish server.json
60
+ # A registry outage must never break the release; re-run from Actions if needed.
61
+ continue-on-error: true
@@ -0,0 +1,21 @@
1
+ name: Daily live smoke
2
+
3
+ # One fixed probe per day: catches fingerprint rot / bot-wall changes
4
+ # before users hit them. Fails visibly on 403/timeout.
5
+ on:
6
+ schedule:
7
+ - cron: "0 6 * * *"
8
+ workflow_dispatch:
9
+
10
+ jobs:
11
+ smoke:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+ - name: Install
19
+ run: pip install -e .
20
+ - name: Smoke probe
21
+ run: python tests/smoke_live.py
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohammad Abbasi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.5
2
+ Name: dictcc-mcp
3
+ Version: 0.1.0
4
+ Summary: Unofficial read-only MCP server for dict.cc — translations across 23 language pairs
5
+ Author: Mohammad Abbasi
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: httpx>=0.27
10
+ Requires-Dist: mcp<2
11
+ Description-Content-Type: text/markdown
12
+
13
+ # dictcc-mcp 🌐
14
+
15
+ mcp-name: io.github.mohammad-abbasi-sh/dictcc-mcp
16
+
17
+ Unofficial **read-only** MCP server for **[dict.cc](https://www.dict.cc)** — dict.cc translations from dict.cc (free, no key, no login): German-English plus 22 more pairs, with word class, gender, usage notes and community votes. No key, no login.
18
+
19
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with dict.cc.
20
+
21
+ ## For AI agents
22
+
23
+ Add to your MCP client config (stdio):
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "dictcc": {
29
+ "command": "uvx",
30
+ "args": ["dictcc-mcp==0.1.0"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Or run locally: `python -m dictcc_mcp.server` (needs `mcp<2`, `httpx`).
37
+
38
+ ## Tools
39
+
40
+ | Tool | Description |
41
+ |------|-------------|
42
+ | `dictcc_translate` | Translate a word or phrase with dict.cc: translations with word class, gender, usage notes & community votes — `query`, `pair` (de-en default; de-el, de-eo, de-es, de-fi, de-fr, de-hr, de-hu, de-is, de-it, de-la, de-nl, de-no, de-pl, de-pt, de-ro, de-ru, de-sk, de-sq, de-sr, de-sv, de-tr, de-uk), `limit` 1..50 |
43
+ | `dictcc_search` | Find dict.cc headwords matching a query (prefix/containment) — `query`, `pair` (de-en default), `limit` 1..50 |
44
+ | `dictcc_health` | Reachability probe (ok / blocked / error) — one polite request |
45
+
46
+ ## Notes
47
+
48
+ - All data comes from **dict.cc's public search pages** (free, no key, no login).
49
+ - Translation rows carry the word, `<var>` word-class markers (`{adj}`, `{n}`, `{f}` …), `<kbd>` bracket notes and the community vote count; rows are returned in dict.cc's own vote ranking.
50
+ - 23 language pairs share the same page structure (DE-EN on `www.dict.cc`, the rest on `<deXX>.dict.cc`); the query direction is auto-detected from which side matches first in dict.cc's ranking.
51
+ - dict.cc has NO example sentences and NO verb conjugation on these pages (verified 2026-11-10) — only translations and headword search are exposed. For verb conjugation use `duden-mcp`.
52
+ - A query with no matches returns 200 with zero rows (not an error).
53
+
54
+ Tests: 23/23 green (18 offline + 5 live, 2026-11-10).
55
+
56
+ ## Development
57
+
58
+ ```bash
59
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
60
+ .venv/bin/pip install -e .
61
+ .venv/bin/python -m pytest tests/ -q
62
+ ```
63
+
64
+ ## License
65
+
66
+ MIT
67
+
68
+ ---
69
+
70
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,48 @@
1
+ # dictcc-mcp 🌐
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/dictcc-mcp
4
+
5
+ Inoffizieller **nur lesender** MCP-Server für **[dict.cc](https://www.dict.cc)** — dict.cc-Übersetzungen von dict.cc (kostenlos, kein Schlüssel, kein Login): Deutsch-Englisch plus 22 weitere Sprachenpaare, mit Wortart, Genus, Gebrauchshinweisen und Community-Stimmen. Kein Schlüssel, keine Anmeldung.
6
+
7
+ > Gebaut von Mohammad Abbasi als Teil der "Germany MCP factory". Nicht mit dict.cc verbunden.
8
+
9
+ ## Für KI-Agenten
10
+
11
+ Zur MCP-Client-Konfiguration hinzufügen (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "dictcc": {
17
+ "command": "uvx",
18
+ "args": ["dictcc-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Oder lokal starten: `python -m dictcc_mcp.server` (benötigt `mcp<2`, `httpx`).
25
+
26
+ ## Tools
27
+
28
+ | Tool | Beschreibung |
29
+ |------|-------------|
30
+ | `dictcc_translate` | Ein Wort mit dict.cc übersetzen (23 Sprachenpaare) |
31
+ | `dictcc_search` | dict.cc-Stichwörter zu einer Suchanfrage finden |
32
+ | `dictcc_health` | Erreichbarkeitsprüfung (ok / blocked / error) — eine höfliche Anfrage |
33
+
34
+ ## Entwicklung
35
+
36
+ ```bash
37
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
38
+ .venv/bin/pip install -e .
39
+ .venv/bin/python -m pytest tests/ -q
40
+ ```
41
+
42
+ ## Lizenz
43
+
44
+ MIT
45
+
46
+ ---
47
+
48
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,48 @@
1
+ # dictcc-mcp 🌐
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/dictcc-mcp
4
+
5
+ سرور MCP غیررسمی و **فقط‌خواندنی** برای **[dict.cc](https://www.dict.cc)** — ترجمه‌های dict.cc از dict.cc (رایگان، بدون کلید): آلمانی–انگلیسی و ۲۲ زبان دیگر، با نوع کلمه، جنسیت، توضیحات کاربرد و آرای کاربران. بدون کلید، بدون ورود.
6
+
7
+ > ساختهٔ محمد عباسی، بخشی از «کارخانهٔ MCP آلمان». وابسته به dict.cc نیست.
8
+
9
+ ## برای ایجنت‌های هوش مصنوعی
10
+
11
+ به پیکربندی MCP کلاینت اضافه کنید (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "dictcc": {
17
+ "command": "uvx",
18
+ "args": ["dictcc-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ یا به‌صورت محلی اجرا کنید: `python -m dictcc_mcp.server` (نیازمند `mcp<2` و `httpx`).
25
+
26
+ ## ابزارها
27
+
28
+ | ابزار | توضیح |
29
+ |------|-------|
30
+ | `dictcc_translate` | ترجمهٔ واژه با dict.cc (۲۳ زبان) |
31
+ | `dictcc_search` | یافتن سرخط‌های dict.cc مطابق پرس‌وجو |
32
+ | `dictcc_health` | بررسی دسترس‌پذیری (ok / blocked / error) — یک درخواست مؤدبانه |
33
+
34
+ ## توسعه
35
+
36
+ ```bash
37
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
38
+ .venv/bin/pip install -e .
39
+ .venv/bin/python -m pytest tests/ -q
40
+ ```
41
+
42
+ ## لایسنس
43
+
44
+ MIT
45
+
46
+ ---
47
+
48
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,58 @@
1
+ # dictcc-mcp 🌐
2
+
3
+ mcp-name: io.github.mohammad-abbasi-sh/dictcc-mcp
4
+
5
+ Unofficial **read-only** MCP server for **[dict.cc](https://www.dict.cc)** — dict.cc translations from dict.cc (free, no key, no login): German-English plus 22 more pairs, with word class, gender, usage notes and community votes. No key, no login.
6
+
7
+ > Built by Mohammad Abbasi as part of the "Germany MCP factory". Not affiliated with dict.cc.
8
+
9
+ ## For AI agents
10
+
11
+ Add to your MCP client config (stdio):
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "dictcc": {
17
+ "command": "uvx",
18
+ "args": ["dictcc-mcp==0.1.0"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Or run locally: `python -m dictcc_mcp.server` (needs `mcp<2`, `httpx`).
25
+
26
+ ## Tools
27
+
28
+ | Tool | Description |
29
+ |------|-------------|
30
+ | `dictcc_translate` | Translate a word or phrase with dict.cc: translations with word class, gender, usage notes & community votes — `query`, `pair` (de-en default; de-el, de-eo, de-es, de-fi, de-fr, de-hr, de-hu, de-is, de-it, de-la, de-nl, de-no, de-pl, de-pt, de-ro, de-ru, de-sk, de-sq, de-sr, de-sv, de-tr, de-uk), `limit` 1..50 |
31
+ | `dictcc_search` | Find dict.cc headwords matching a query (prefix/containment) — `query`, `pair` (de-en default), `limit` 1..50 |
32
+ | `dictcc_health` | Reachability probe (ok / blocked / error) — one polite request |
33
+
34
+ ## Notes
35
+
36
+ - All data comes from **dict.cc's public search pages** (free, no key, no login).
37
+ - Translation rows carry the word, `<var>` word-class markers (`{adj}`, `{n}`, `{f}` …), `<kbd>` bracket notes and the community vote count; rows are returned in dict.cc's own vote ranking.
38
+ - 23 language pairs share the same page structure (DE-EN on `www.dict.cc`, the rest on `<deXX>.dict.cc`); the query direction is auto-detected from which side matches first in dict.cc's ranking.
39
+ - dict.cc has NO example sentences and NO verb conjugation on these pages (verified 2026-11-10) — only translations and headword search are exposed. For verb conjugation use `duden-mcp`.
40
+ - A query with no matches returns 200 with zero rows (not an error).
41
+
42
+ Tests: 23/23 green (18 offline + 5 live, 2026-11-10).
43
+
44
+ ## Development
45
+
46
+ ```bash
47
+ python3 -m venv .venv && .venv/bin/pip install "mcp<2" httpx pytest
48
+ .venv/bin/pip install -e .
49
+ .venv/bin/python -m pytest tests/ -q
50
+ ```
51
+
52
+ ## License
53
+
54
+ MIT
55
+
56
+ ---
57
+
58
+ Built by [Mohammad Abbasi](https://github.com/mohammad-abbasi-sh) — [Almanibama](https://almanibama.ir) · [mabbasi.ir](https://mabbasi.ir)
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "dictcc-mcp"
7
+ version = "0.1.0"
8
+ description = "Unofficial read-only MCP server for dict.cc — translations across 23 language pairs"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "mcp<2",
14
+ "httpx>=0.27",
15
+ ]
16
+ authors = [{ name = "Mohammad Abbasi" }]
17
+
18
+ [project.scripts]
19
+ dictcc-mcp = "dictcc_mcp.server:main"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/dictcc_mcp"]
23
+
24
+ [tool.pytest.ini_options]
25
+ markers = ["live: tests that hit the real https://www.dict.cc site"]
@@ -0,0 +1 @@
1
+ {"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "description": "Unofficial read-only MCP server for dict.cc — translations in 23 language pairs.", "name": "io.github.mohammad-abbasi-sh/dictcc-mcp", "packages": [{"identifier": "dictcc-mcp", "registryBaseUrl": "https://pypi.org", "registryType": "pypi", "transport": {"type": "stdio"}, "version": "0.1.0"}], "repository": {"source": "github", "url": "https://github.com/mohammad-abbasi-sh/dictcc-mcp"}, "title": "dict.cc — German-English & 22 more pairs: translations with word class, gender & votes", "version": "0.1.0", "websiteUrl": "https://github.com/mohammad-abbasi-sh/dictcc-mcp"}
@@ -0,0 +1,7 @@
1
+ """dictcc_mcp — unofficial read-only MCP server for dict.cc.
2
+
3
+ dict.cc translations from dict.cc (free, no key, no login): German-English plus 22 more pairs, with word class, gender, usage notes and community votes.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,186 @@
1
+ """Domain logic: shape dict.cc translation pages into compact dicts
2
+ (stdlib only).
3
+
4
+ Data source: dict.cc public search pages
5
+ (https://www.dict.cc/?s=<word> for DE-EN,
6
+ https://<pair>.dict.cc/?s=<word> for the other pairs) — free, no key,
7
+ no login.
8
+
9
+ Page structure (server-rendered HTML, verified 2026-11-10):
10
+ - translation rows are <tr id='tr1'>…<tr id='trN'> with four <td>s:
11
+ [spacer][foreign side][German side][spacer]. The foreign cell
12
+ holds the word (first <a>), <var> word-class markers ({adj}, {n},
13
+ {f} …) and <kbd> bracket notes; the German cell additionally
14
+ carries a <div> with the community vote count. A no-match query
15
+ returns 200 with zero rows.
16
+ - dict.cc has NO example sentences and NO verb conjugation on these
17
+ pages (verified: 'Beispiel' 0, no verb links, no audio URLs) — the
18
+ server exposes only what exists: translations + headword search.
19
+ - Other pairs share the same structure (verified DE-FR 39 rows,
20
+ DE-ES 15, DE-IT 31, DE-TR/DE-RU 200).
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import html as _html
25
+ import re
26
+ from urllib.parse import quote
27
+
28
+ # pair code -> (subdomain, foreign language code). de-en lives on www.
29
+ PAIRS = {
30
+ "de-en": ("www", "en"),
31
+ "de-el": ("deel", "el"),
32
+ "de-eo": ("deeo", "eo"),
33
+ "de-es": ("dees", "es"),
34
+ "de-fi": ("defi", "fi"),
35
+ "de-fr": ("defr", "fr"),
36
+ "de-hr": ("dehr", "hr"),
37
+ "de-hu": ("dehu", "hu"),
38
+ "de-is": ("deis", "is"),
39
+ "de-it": ("deit", "it"),
40
+ "de-la": ("dela", "la"),
41
+ "de-nl": ("denl", "nl"),
42
+ "de-no": ("deno", "no"),
43
+ "de-pl": ("depl", "pl"),
44
+ "de-pt": ("dept", "pt"),
45
+ "de-ro": ("dero", "ro"),
46
+ "de-ru": ("deru", "ru"),
47
+ "de-sk": ("desk", "sk"),
48
+ "de-sq": ("desq", "sq"),
49
+ "de-sr": ("desr", "sr"),
50
+ "de-sv": ("desv", "sv"),
51
+ "de-tr": ("detr", "tr"),
52
+ "de-uk": ("deuk", "uk"),
53
+ }
54
+
55
+ LANG_NAMES = {
56
+ "en": "English", "el": "Greek", "eo": "Esperanto", "es": "Spanish",
57
+ "fi": "Finnish", "fr": "French", "hr": "Croatian", "hu": "Hungarian",
58
+ "is": "Icelandic", "it": "Italian", "la": "Latin", "nl": "Dutch",
59
+ "no": "Norwegian", "pl": "Polish", "pt": "Portuguese",
60
+ "ro": "Romanian", "ru": "Russian", "sk": "Slovak", "sq": "Albanian",
61
+ "sr": "Serbian", "sv": "Swedish", "tr": "Turkish",
62
+ "uk": "Ukrainian",
63
+ }
64
+
65
+ _TAG_RE = re.compile(r"<[^>]+>")
66
+ _WS_RE = re.compile(r"\s+")
67
+ _ROW_RE = re.compile(r"<tr id='tr\d+'>(.*?)</tr>", re.S)
68
+ _TD_RE = re.compile(r"<td[^>]*>(.*?)</td>", re.S)
69
+
70
+
71
+ def validate_pair(pair: str) -> str:
72
+ p = (pair or "de-en").strip().lower()
73
+ if p not in PAIRS:
74
+ raise ValueError(
75
+ f"unsupported pair: {pair!r} "
76
+ f"(use one of: {', '.join(sorted(PAIRS))})")
77
+ return p
78
+
79
+
80
+ def validate_query(query: str) -> str:
81
+ q = (query or "").strip()
82
+ if not q:
83
+ raise ValueError("query must not be empty")
84
+ if len(q) > 100:
85
+ raise ValueError("query too long (max 100 characters)")
86
+ return q
87
+
88
+
89
+ def validate_limit(limit: int) -> int:
90
+ if not 1 <= limit <= 50:
91
+ raise ValueError(f"limit out of range: {limit} (expected 1..50)")
92
+ return limit
93
+
94
+
95
+ def pair_url(pair: str, query: str) -> str:
96
+ sub, _lang = PAIRS[pair]
97
+ return f"https://{sub}.dict.cc/?s={quote(query)}"
98
+
99
+
100
+ def _clean(text: str) -> str:
101
+ return _WS_RE.sub(" ", _html.unescape(_TAG_RE.sub(" ", text or ""))).strip()
102
+
103
+
104
+ def _parse_cell(cell: str) -> dict:
105
+ """{word, info, votes} — word = first link text; info = <var>
106
+ markers + <kbd> bracket notes; votes = community vote count."""
107
+ m = re.search(r"<a[^>]*>(.*?)</a>", cell, re.S)
108
+ word = _clean(m.group(1)) if m else ""
109
+ # compound marker: <b>Haus</b>- / Akzept-<b>Haus</b> render with a
110
+ # space around the hyphen after tag stripping; rejoin it
111
+ word = re.sub(r"\s*-\s*", "-", word)
112
+ markers = [_clean(v) for v in re.findall(
113
+ r"<var[^>]*>([^<]*)</var>", cell)]
114
+ notes = [_clean(k) for k in re.findall(
115
+ r"<kbd[^>]*>([^<]*)</kbd>", cell)]
116
+ notes = [n for n in notes if n]
117
+ info_parts = [x for x in markers if x]
118
+ if notes:
119
+ info_parts.append(" ".join(notes))
120
+ vm = re.search(r"<div[^>]*>(\d+)</div>", cell)
121
+ return {"word": word,
122
+ "info": " ".join(info_parts),
123
+ "votes": int(vm.group(1)) if vm else 0}
124
+
125
+
126
+ def parse_table(html: str, other_lang: str) -> list[dict]:
127
+ """[{german, german_info, <other_lang>, <other_lang>_info, votes}]
128
+ — row order (dict.cc's own ranking by votes)."""
129
+ out = []
130
+ for row in _ROW_RE.findall(html):
131
+ tds = _TD_RE.findall(row)
132
+ if len(tds) < 3:
133
+ continue
134
+ foreign = _parse_cell(tds[1])
135
+ german = _parse_cell(tds[2])
136
+ if not foreign["word"] and not german["word"]:
137
+ continue
138
+ out.append({
139
+ "german": german["word"],
140
+ "german_info": german["info"],
141
+ other_lang: foreign["word"],
142
+ f"{other_lang}_info": foreign["info"],
143
+ "votes": german["votes"] or foreign["votes"],
144
+ })
145
+ return out
146
+
147
+
148
+ def detect_direction(items: list[dict], query: str, other_lang: str) -> str:
149
+ """Which side the query matched: 'de', the foreign code, or
150
+ 'unknown'. Rows are dict.cc's own relevance ranking, so the
151
+ first row that matches decides; within a row, exact beats prefix
152
+ beats substring. (A plain all-German-first scan mislabels an
153
+ English query like 'house' because a German loanword 'House'
154
+ sits further down the list.)"""
155
+ q = query.casefold()
156
+ for it in items:
157
+ de, other = it["german"].casefold(), it[other_lang].casefold()
158
+ if de == q:
159
+ return "de"
160
+ if other == q:
161
+ return other_lang
162
+ if de.startswith(q):
163
+ return "de"
164
+ if other.startswith(q):
165
+ return other_lang
166
+ if q in de:
167
+ return "de"
168
+ if q in other:
169
+ return other_lang
170
+ return "unknown"
171
+
172
+
173
+ def parse_search(html: str, other_lang: str, query: str) -> list[dict]:
174
+ """Distinct headwords containing the query, from both sides of
175
+ the result table, in row order: [{word, lang}]."""
176
+ q = query.casefold()
177
+ out: list[dict] = []
178
+ seen = set()
179
+ for it in parse_table(html, other_lang):
180
+ for word, lang in ((it["german"], "de"),
181
+ (it[other_lang], other_lang)):
182
+ key = (word.casefold(), lang)
183
+ if word and q in word.casefold() and key not in seen:
184
+ seen.add(key)
185
+ out.append({"word": word, "lang": lang})
186
+ return out
@@ -0,0 +1,99 @@
1
+ """HTTP layer for dictcc_mcp — plain httpx GETs against dict.cc.
2
+
3
+ No key, no login. One retry on 429/5xx; error taxonomy (403/429/other).
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import ssl
9
+ import time
10
+
11
+ import httpx
12
+
13
+ UA = (
14
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
15
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
16
+ )
17
+ TIMEOUT = 25.0
18
+ PROBE_URL = "https://www.dict.cc/?s=Haus"
19
+ SOURCE = "dict.cc"
20
+
21
+
22
+ class DictccMcpError(RuntimeError):
23
+ pass
24
+
25
+
26
+ def _verify():
27
+ """TLS trust store: the OS bundle when present, else httpx/certifi."""
28
+ for path in (
29
+ "/etc/ssl/certs/ca-certificates.crt",
30
+ ssl.get_default_verify_paths().openssl_cafile,
31
+ ):
32
+ if path and os.path.exists(path):
33
+ return ssl.create_default_context(cafile=path)
34
+ return True
35
+
36
+
37
+ def _client() -> httpx.Client:
38
+ # NOTE: we read the proxy URL from the environment but never log it.
39
+ proxy = os.environ.get("https_proxy") or os.environ.get("HTTPS_PROXY")
40
+ return httpx.Client(
41
+ headers={"User-Agent": UA, "Accept": "application/json, application/xml, text/html, */*"},
42
+ timeout=TIMEOUT,
43
+ proxy=proxy or None,
44
+ trust_env=False,
45
+ verify=_verify(),
46
+ )
47
+
48
+
49
+ def fetch_text(url: str) -> str:
50
+ """GET one URL and return its text. One retry on 429/5xx."""
51
+ last_exc: Exception | None = None
52
+ r: httpx.Response | None = None
53
+ for attempt in range(2):
54
+ try:
55
+ with _client() as c:
56
+ r = c.get(url)
57
+ except httpx.HTTPError as e:
58
+ last_exc = e
59
+ if attempt == 0:
60
+ time.sleep(1.0)
61
+ continue
62
+ raise DictccMcpError(f"network error fetching {url}: {e}") from e
63
+ if r.status_code in (429, 500, 502, 503):
64
+ if attempt == 0:
65
+ time.sleep(1.0)
66
+ continue
67
+ break
68
+ assert r is not None # loop always assigns r or raises
69
+ if r.status_code == 403:
70
+ raise DictccMcpError(
71
+ f"{SOURCE} returned HTTP 403 for {url} (bot wall) — try again later"
72
+ )
73
+ if r.status_code == 429:
74
+ raise DictccMcpError(
75
+ f"{SOURCE} rate-limited the request (HTTP 429) — try again later"
76
+ )
77
+ if r.status_code != 200:
78
+ raise DictccMcpError(f"{SOURCE} returned HTTP {r.status_code} for {url}")
79
+ return r.text
80
+
81
+
82
+ def health_check() -> dict:
83
+ """One polite probe of the source site.
84
+
85
+ Returns {"status": "ok"|"blocked"|"error", "http_status": int|None,
86
+ "url": ..., "detail": ...}. Used by the `<prefix>_health` tool
87
+ and the daily smoke CI.
88
+ """
89
+ url = PROBE_URL
90
+ try:
91
+ fetch_text(url)
92
+ except DictccMcpError as e:
93
+ msg = str(e)
94
+ if "403" in msg:
95
+ return {"status": "blocked", "http_status": 403, "url": url, "detail": msg}
96
+ if "429" in msg:
97
+ return {"status": "blocked", "http_status": 429, "url": url, "detail": msg}
98
+ return {"status": "error", "http_status": None, "url": url, "detail": msg}
99
+ return {"status": "ok", "http_status": 200, "url": url}