ch-eli-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,61 @@
1
+ name: release
2
+
3
+ # Publishes to PyPI (org secret PYPI_API_TOKEN) + the MCP Registry (GitHub OIDC).
4
+ # Trigger: push a version tag, e.g. `git tag v0.1.0 && git push origin v0.1.0`.
5
+ # Pattern matches gb-eli-mcp (classic token; OIDC trusted-publishing hit a
6
+ # persistent invalid-publisher error across the fleet).
7
+
8
+ on:
9
+ push:
10
+ tags:
11
+ - "v*"
12
+ workflow_dispatch: {} # manual re-run of the MCP Registry publish without bumping the package version
13
+
14
+ permissions:
15
+ contents: read
16
+ id-token: write # required for the MCP Registry OIDC login
17
+
18
+ jobs:
19
+ build-and-publish-pypi:
20
+ if: github.event_name == 'push' # only on a version tag; skipped on manual dispatch
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+
25
+ - name: Set up Python
26
+ uses: actions/setup-python@v5
27
+ with:
28
+ python-version: "3.12"
29
+
30
+ - name: Install build tooling
31
+ run: python -m pip install --upgrade build
32
+
33
+ - name: Build sdist + wheel
34
+ run: python -m build
35
+
36
+ - name: Publish to PyPI (org API token)
37
+ uses: pypa/gh-action-pypi-publish@release/v1
38
+ with:
39
+ password: ${{ secrets.PYPI_API_TOKEN }}
40
+
41
+ publish-mcp-registry:
42
+ needs: build-and-publish-pypi
43
+ # run after a successful PyPI publish, OR standalone on manual dispatch
44
+ if: always() && (github.event_name == 'workflow_dispatch' || needs.build-and-publish-pypi.result == 'success')
45
+ runs-on: ubuntu-latest
46
+ permissions:
47
+ contents: read
48
+ id-token: write # OIDC login to the MCP Registry
49
+ steps:
50
+ - uses: actions/checkout@v4
51
+
52
+ - name: Install mcp-publisher
53
+ run: |
54
+ curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_amd64.tar.gz" | tar xz mcp-publisher
55
+ sudo mv mcp-publisher /usr/local/bin/
56
+
57
+ - name: Login to MCP Registry (GitHub OIDC)
58
+ run: mcp-publisher login github-oidc
59
+
60
+ - name: Publish server.json to MCP Registry
61
+ run: mcp-publisher publish
@@ -0,0 +1,20 @@
1
+ # Python
2
+ .venv/
3
+ __pycache__/
4
+ *.py[cod]
5
+ *.egg-info/
6
+ dist/
7
+ build/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+
12
+ # Local runtime (never source)
13
+ .matematic/
14
+ *.log
15
+
16
+ # OS
17
+ .DS_Store
18
+ Thumbs.db
19
+
20
+ # Note: tests/fixtures/* ARE committed - public Finlex data needed for tests.
@@ -0,0 +1,53 @@
1
+ # Discovery notes - Switzerland
2
+
3
+ Date: 2026-07-06.
4
+
5
+ ## Why Switzerland, and why it stands out in this fleet
6
+
7
+ The user asked to also check Switzerland and Monaco after the Americas ROI
8
+ sweep. Live probing found Fedlex is the strongest non-EU legal API found so
9
+ far in this whole project: genuinely ELI-native (the resource URI itself is
10
+ the ELI, no adaptation needed, unlike NL/SE/FR/BR/US/CO/CA in this fleet,
11
+ which all had to explain why they do NOT have native ELI). Confirmed via
12
+ the JOLux ontology, the same one Luxembourg's Legilux uses - meaning
13
+ Switzerland and Luxembourg share a data model family despite Switzerland
14
+ being outside the EU.
15
+
16
+ ## What was tried and what worked
17
+
18
+ - `https://fedlex.data.admin.ch/sparqlendpoint` - keyless SPARQL, confirmed
19
+ live 2026-07-06.
20
+ - An existing third-party connector, `loicvuilliomenet-boop/fedlex-mcp`
21
+ (found via web search, listed on mcpservers.org), confirmed Fedlex is a
22
+ known target - but its GitHub license field reports `NOASSERTION`
23
+ (all-rights-reserved by default), it has 1 star, and its last push was
24
+ 2026-03-30 (over 3 months stale at time of writing). Not forked or
25
+ depended on; used only as a signal that the target is viable. This
26
+ connector's code is written from scratch against the official endpoint.
27
+ - Virtuoso's `bif:contains` full-text extension is disabled on this public
28
+ endpoint (`"Illegal requests in query"` error) - switched to a standard
29
+ `FILTER(CONTAINS(LCASE(?title), "..."))`, confirmed working (e.g.
30
+ searching "Datenschutz" correctly returns the Federal Data Protection Act
31
+ and related instruments).
32
+ - The official tutorial repo `swiss/fedlex-sparql` (a JupyterLite notebook)
33
+ provided the working query patterns for JOLux navigation (Work ->
34
+ Expression -> title/titleShort, `classifiedByTaxonomyEntry` -> SR
35
+ number).
36
+
37
+ ## Monaco and Cyprus - checked and skipped in the same pass
38
+
39
+ - **Monaco** (`legimonaco.mc`) - plain HTML government site, no API surface
40
+ found. Population ~39,000; even a clean API would carry limited ROI at
41
+ this market size. SKIP.
42
+ - **Cyprus** (`cylaw.org`) - a bare Apache directory index of HTML files
43
+ under `/nomoi/indexes/`, no JSON/XML API. This is the same
44
+ "legal-information-institute" pattern (like SAFLII/KenyaLaw, already
45
+ SKIP'd elsewhere in this fleet's discovery notes) - scraping-only, off
46
+ the zero-cloud principle this fleet follows. SKIP.
47
+
48
+ ## Not resolved / revisit later
49
+
50
+ - No confirmed bulk/offline mode - would need to resolve
51
+ `jolux:isExemplifiedBy` manifestation links for full text, not attempted
52
+ in this pass.
53
+ - Cantonal legislation and Federal Supreme Court case law not surveyed.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: ch-eli-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for Swiss federal legislation (Fedlex, native ELI) with verifiable citations.
5
+ Project-URL: Repository, https://github.com/matematicsolutions/ch-eli-mcp
6
+ Project-URL: Issues, https://github.com/matematicsolutions/ch-eli-mcp/issues
7
+ Project-URL: Homepage, https://matematic.co
8
+ Author-email: Matematic Solutions <kontakt@matematic.co>, Wieslaw Mazur <mazur.wieslaw2022@gmail.com>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: eli,fedlex,law,legaltech,mcp,sparql,switzerland
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Legal Industry
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Office/Business
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: anyio>=4.3
22
+ Requires-Dist: diskcache>=5.6
23
+ Requires-Dist: fastmcp>=0.2.0
24
+ Requires-Dist: httpx>=0.27
25
+ Provides-Extra: dev
26
+ Requires-Dist: mypy>=1.10; extra == 'dev'
27
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
28
+ Requires-Dist: pytest>=8.0; extra == 'dev'
29
+ Requires-Dist: ruff>=0.5; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # ch-eli-mcp
33
+
34
+ <!-- mcp-name: io.github.matematicsolutions/ch-eli-mcp -->
35
+
36
+ MCP server for Swiss federal legislation via Fedlex, the Federal
37
+ Chancellery's official publication platform. Fedlex is genuinely
38
+ ELI-native (European Legislation Identifier) even though Switzerland is
39
+ not an EU member. Multilingual: German, French, Italian, English.
40
+
41
+ ## What this is not
42
+
43
+ This connector returns metadata (title, SR number) via SPARQL - not the
44
+ operative text of the law. `source_url` points to the public Fedlex page
45
+ where the full text lives.
46
+
47
+ ## Tools
48
+
49
+ | Tool | Purpose |
50
+ |---|---|
51
+ | `ch_search_acts` | Full-text search over act titles, in one of four languages |
52
+ | `ch_get_act` | Full detail for one act by its Fedlex ELI URI |
53
+
54
+ Every response carries `lex_uri` (the native ELI URI - not invented, taken
55
+ directly from Fedlex), `source_url` (the public HTML page), and
56
+ `human_readable_citation` (e.g. `"Bundesverfassung der Schweizerischen
57
+ Eidgenossenschaft (SR 101)"` - the SR number is Switzerland's own
58
+ Systematische Sammlung / Classified Compilation citation convention).
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pip install ch-eli-mcp
64
+ ```
65
+
66
+ ## Configuration
67
+
68
+ | Env var | Default |
69
+ |---|---|
70
+ | `CH_ELI_CACHE_DIR` | `~/.matematic/cache/ch-eli` |
71
+ | `CH_ELI_AUDIT_DIR` | `~/.matematic/audit` |
72
+ | `CH_ELI_BASE_URL` | `https://fedlex.data.admin.ch/sparqlendpoint` |
73
+
74
+ ## License
75
+
76
+ Apache-2.0 (code). Fedlex content is official Swiss federal publication
77
+ material (see [SOURCES.md](SOURCES.md)).
@@ -0,0 +1,46 @@
1
+ # ch-eli-mcp
2
+
3
+ <!-- mcp-name: io.github.matematicsolutions/ch-eli-mcp -->
4
+
5
+ MCP server for Swiss federal legislation via Fedlex, the Federal
6
+ Chancellery's official publication platform. Fedlex is genuinely
7
+ ELI-native (European Legislation Identifier) even though Switzerland is
8
+ not an EU member. Multilingual: German, French, Italian, English.
9
+
10
+ ## What this is not
11
+
12
+ This connector returns metadata (title, SR number) via SPARQL - not the
13
+ operative text of the law. `source_url` points to the public Fedlex page
14
+ where the full text lives.
15
+
16
+ ## Tools
17
+
18
+ | Tool | Purpose |
19
+ |---|---|
20
+ | `ch_search_acts` | Full-text search over act titles, in one of four languages |
21
+ | `ch_get_act` | Full detail for one act by its Fedlex ELI URI |
22
+
23
+ Every response carries `lex_uri` (the native ELI URI - not invented, taken
24
+ directly from Fedlex), `source_url` (the public HTML page), and
25
+ `human_readable_citation` (e.g. `"Bundesverfassung der Schweizerischen
26
+ Eidgenossenschaft (SR 101)"` - the SR number is Switzerland's own
27
+ Systematische Sammlung / Classified Compilation citation convention).
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install ch-eli-mcp
33
+ ```
34
+
35
+ ## Configuration
36
+
37
+ | Env var | Default |
38
+ |---|---|
39
+ | `CH_ELI_CACHE_DIR` | `~/.matematic/cache/ch-eli` |
40
+ | `CH_ELI_AUDIT_DIR` | `~/.matematic/audit` |
41
+ | `CH_ELI_BASE_URL` | `https://fedlex.data.admin.ch/sparqlendpoint` |
42
+
43
+ ## License
44
+
45
+ Apache-2.0 (code). Fedlex content is official Swiss federal publication
46
+ material (see [SOURCES.md](SOURCES.md)).
@@ -0,0 +1,39 @@
1
+ # Sources
2
+
3
+ ## Fedlex SPARQL endpoint (`fedlex.data.admin.ch/sparqlendpoint`)
4
+
5
+ - **Origin**: Swiss Federal Chancellery.
6
+ - **License**: official federal publication platform; no separate reuse
7
+ license found during discovery beyond it being the public consolidation
8
+ meant for public use - same caution class as other government legal
9
+ text sources in this fleet (flagged, not blocking a keyless-fetch
10
+ connector).
11
+ - **Access**: keyless SPARQL 1.1 (Virtuoso), JSON results.
12
+ - **Ontology**: JOLux (`http://data.legilux.public.lu/resource/ontology/jolux#`)
13
+ - the same ontology namespace used by Luxembourg's Legilux, confirmed by
14
+ cross-referencing `lu-eli-mcp`'s discovery notes. Models Work
15
+ (`ConsolidationAbstract`) / Expression (`isRealizedBy`, per-language
16
+ title) / Manifestation (`isEmbodiedBy`, file format + download link).
17
+ - **Identifier**: the resource URI itself, e.g.
18
+ `https://fedlex.data.admin.ch/eli/cc/1999/404` for the Federal
19
+ Constitution - genuinely ELI, not an adapted local scheme (unlike most
20
+ non-EU connectors in this fleet).
21
+ - **Citation convention**: SR number (Systematische Sammlung des
22
+ Bundesrechts / Classified Compilation), e.g. "SR 101" - queried via
23
+ `jolux:classifiedByTaxonomyEntry` -> `skos:notation`.
24
+ - **Full-text search caveat**: Virtuoso's `bif:contains` extension returns
25
+ `"Illegal requests in query"` on this public endpoint (unlike Chile's BCN
26
+ endpoint, where it works) - this connector uses a standard SPARQL
27
+ `FILTER(CONTAINS(...))` instead, which is portable but slower on large
28
+ result sets.
29
+
30
+ ## Not covered (out of scope for this connector)
31
+
32
+ - **Full operative text** - the SPARQL endpoint exposes metadata and
33
+ manifestation links (e.g. PDF download URLs via `jolux:isExemplifiedBy`),
34
+ not inline article text. A future version could resolve those links.
35
+ - **Cantonal legislation** - each canton publishes separately; not
36
+ surveyed in this pass.
37
+ - **Case law** (Federal Supreme Court decisions) - not surveyed in this
38
+ pass; a natural v0.2 feature if Fedlex or a sibling platform exposes it
39
+ via the same SPARQL endpoint.
@@ -0,0 +1,4 @@
1
+ {
2
+ "$schema": "https://glama.ai/mcp/schemas/server.json",
3
+ "maintainers": ["mazurwieslaw2022-cmd"]
4
+ }
@@ -0,0 +1,65 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ch-eli-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for Swiss federal legislation (Fedlex, native ELI) with verifiable citations."
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ requires-python = ">=3.11"
12
+ authors = [
13
+ { name = "Matematic Solutions", email = "kontakt@matematic.co" },
14
+ { name = "Wieslaw Mazur", email = "mazur.wieslaw2022@gmail.com" },
15
+ ]
16
+ keywords = ["mcp", "legaltech", "switzerland", "fedlex", "eli", "sparql", "law"]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Intended Audience :: Legal Industry",
20
+ "License :: OSI Approved :: Apache Software License",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Topic :: Office/Business",
26
+ ]
27
+ dependencies = [
28
+ "fastmcp>=0.2.0",
29
+ "httpx>=0.27",
30
+ "diskcache>=5.6",
31
+ "anyio>=4.3",
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pytest>=8.0",
37
+ "pytest-asyncio>=0.23",
38
+ "mypy>=1.10",
39
+ "ruff>=0.5",
40
+ ]
41
+
42
+ [project.urls]
43
+ Repository = "https://github.com/matematicsolutions/ch-eli-mcp"
44
+ Issues = "https://github.com/matematicsolutions/ch-eli-mcp/issues"
45
+ Homepage = "https://matematic.co"
46
+
47
+ [project.scripts]
48
+ ch-eli-mcp = "ch_eli_mcp.server:main"
49
+
50
+ [tool.hatch.build.targets.wheel]
51
+ packages = ["src/ch_eli_mcp"]
52
+
53
+ [tool.ruff]
54
+ line-length = 100
55
+ target-version = "py311"
56
+
57
+ [tool.ruff.lint]
58
+ select = ["E", "F", "I", "B", "UP", "N", "SIM", "RUF"]
59
+
60
+ [tool.ruff.lint.per-file-ignores]
61
+ "src/ch_eli_mcp/server.py" = ["E501"]
62
+
63
+ [tool.pytest.ini_options]
64
+ asyncio_mode = "auto"
65
+ testpaths = ["tests"]
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "io.github.matematicsolutions/ch-eli-mcp",
4
+ "description": "MCP server for Swiss federal legislation via Fedlex (native ELI), verifiable citations.",
5
+ "version": "0.1.0",
6
+ "repository": {
7
+ "url": "https://github.com/matematicsolutions/ch-eli-mcp",
8
+ "source": "github"
9
+ },
10
+ "packages": [
11
+ {
12
+ "registryType": "pypi",
13
+ "registryBaseUrl": "https://pypi.org",
14
+ "identifier": "ch-eli-mcp",
15
+ "version": "0.1.0",
16
+ "runtimeHint": "uvx",
17
+ "transport": {
18
+ "type": "stdio"
19
+ }
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1,3 @@
1
+ """ch-eli-mcp - MCP connector for Swiss federal legislation (Fedlex)."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,94 @@
1
+ """JSONL audit logger for AI Act art. 12.
2
+
3
+ Every call to every MCP tool writes one JSON line to:
4
+
5
+ ~/.matematic/audit/ch-eli-mcp.jsonl
6
+
7
+ (or to the directory given by ``CH_ELI_AUDIT_DIR``).
8
+
9
+ If the write fails, the tool returns an error instead of silently continuing
10
+ (Art. 2 CONSTITUTION.md). Inherited verbatim from the other eu-legal-mcp connectors.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import time
19
+ from datetime import UTC, datetime
20
+ from pathlib import Path
21
+ from typing import Any, Literal
22
+
23
+ Status = Literal["ok", "error"]
24
+
25
+ _AUDIT_FILENAME = "ch-eli-mcp.jsonl"
26
+
27
+
28
+ def _resolve_audit_dir() -> Path:
29
+ env = os.environ.get("CH_ELI_AUDIT_DIR")
30
+ if env:
31
+ return Path(env).expanduser()
32
+ return Path.home() / ".matematic" / "audit"
33
+
34
+
35
+ def hash_input(payload: Any) -> str:
36
+ """SHA-256 of a stable JSON serialization of the input."""
37
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
38
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
39
+
40
+
41
+ class AuditLogger:
42
+ """Append-only JSONL logger."""
43
+
44
+ def __init__(self, audit_dir: Path | None = None) -> None:
45
+ self._dir = (audit_dir or _resolve_audit_dir()).expanduser()
46
+ self._dir.mkdir(parents=True, exist_ok=True)
47
+ self._path = self._dir / _AUDIT_FILENAME
48
+
49
+ @property
50
+ def path(self) -> Path:
51
+ return self._path
52
+
53
+ def log(
54
+ self,
55
+ *,
56
+ tool: str,
57
+ input_hash: str,
58
+ output_count_or_size: int,
59
+ duration_ms: int,
60
+ status: Status,
61
+ error: str | None = None,
62
+ ) -> None:
63
+ record: dict[str, Any] = {
64
+ "ts": datetime.now(UTC).isoformat(timespec="milliseconds"),
65
+ "tool": tool,
66
+ "input_hash": input_hash,
67
+ "output_count_or_size": output_count_or_size,
68
+ "duration_ms": duration_ms,
69
+ "status": status,
70
+ }
71
+ if error is not None:
72
+ record["error"] = error[:500]
73
+ line = json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
74
+ with self._path.open("a", encoding="utf-8") as fh:
75
+ fh.write(line)
76
+
77
+
78
+ class _Timer:
79
+ """Context-managed timer in milliseconds."""
80
+
81
+ def __init__(self) -> None:
82
+ self._t0 = 0.0
83
+ self.duration_ms = 0
84
+
85
+ def __enter__(self) -> _Timer:
86
+ self._t0 = time.perf_counter()
87
+ return self
88
+
89
+ def __exit__(self, *_exc: object) -> None:
90
+ self.duration_ms = int((time.perf_counter() - self._t0) * 1000)
91
+
92
+
93
+ def timer() -> _Timer:
94
+ return _Timer()
@@ -0,0 +1,56 @@
1
+ """Thin wrapper over diskcache - key is URL, TTL per category.
2
+
3
+ Inherited verbatim from the other eu-legal-mcp connectors (only env var and dir differ).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from diskcache import Cache
13
+
14
+ DEFAULT_TTL_ACT = 24 * 60 * 60
15
+ DEFAULT_TTL_LIST = 60 * 60
16
+ DEFAULT_TTL_DICT = 7 * 24 * 60 * 60
17
+ DEFAULT_TTL_CHANGES = 5 * 60
18
+
19
+
20
+ def _resolve_cache_dir() -> Path:
21
+ env = os.environ.get("CH_ELI_CACHE_DIR")
22
+ if env:
23
+ return Path(env).expanduser()
24
+ return Path.home() / ".matematic" / "cache" / "ch-eli"
25
+
26
+
27
+ class HttpCache:
28
+ """Caches HTTP responses (already deserialized to dict / str)."""
29
+
30
+ def __init__(self, cache_dir: Path | None = None) -> None:
31
+ self._dir = (cache_dir or _resolve_cache_dir()).expanduser()
32
+ self._dir.mkdir(parents=True, exist_ok=True)
33
+ self._cache: Cache = Cache(str(self._dir))
34
+
35
+ def get(self, key: str) -> Any:
36
+ return self._cache.get(key, default=None)
37
+
38
+ def set(self, key: str, value: Any, ttl: int) -> None:
39
+ self._cache.set(key, value, expire=ttl)
40
+
41
+ def close(self) -> None:
42
+ self._cache.close()
43
+
44
+ @staticmethod
45
+ def ttl_for(category: str) -> int:
46
+ match category:
47
+ case "act":
48
+ return DEFAULT_TTL_ACT
49
+ case "list" | "search":
50
+ return DEFAULT_TTL_LIST
51
+ case "dict":
52
+ return DEFAULT_TTL_DICT
53
+ case "changes":
54
+ return DEFAULT_TTL_CHANGES
55
+ case _:
56
+ return DEFAULT_TTL_LIST
@@ -0,0 +1,56 @@
1
+ """Citation contract for ch-eli-mcp.
2
+
3
+ Fedlex is genuinely ELI-native: every act has a URI of the form
4
+ ``https://fedlex.data.admin.ch/eli/cc/{year}/{number}``. The Swiss citation
5
+ convention layered on top is the SR number (Systematische Sammmlung /
6
+ Classified Compilation number, e.g. "101" for the Federal Constitution) -
7
+ we surface both.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ from .models import Act, Citation
15
+
16
+ _LANG_URIS = {
17
+ "DEU": "de",
18
+ "FRA": "fr",
19
+ "ITA": "it",
20
+ "ENG": "en",
21
+ }
22
+
23
+ _PUBLIC_BASE = "https://www.fedlex.admin.ch"
24
+ _DATA_BASE = "https://fedlex.data.admin.ch"
25
+
26
+
27
+ def lang_uri(lang: str) -> str:
28
+ """Map a short language code (de/fr/it/en) to the EU authority-table URI Fedlex expects."""
29
+ code = lang.upper()
30
+ if code in ("DE", "FR", "IT", "EN"):
31
+ code = {"DE": "DEU", "FR": "FRA", "IT": "ITA", "EN": "ENG"}[code]
32
+ if code not in _LANG_URIS:
33
+ raise ValueError(f"unsupported lang={lang!r}")
34
+ return f"http://publications.europa.eu/resource/authority/language/{code}"
35
+
36
+
37
+ def parse_act(uri: str, lang: str, row: dict[str, Any]) -> Act:
38
+ def _val(key: str) -> str | None:
39
+ return row.get(key, {}).get("value")
40
+
41
+ return Act(
42
+ uri=uri,
43
+ lang=lang,
44
+ sr_number=_val("sr_number"),
45
+ title=_val("title"),
46
+ title_short=_val("title_short"),
47
+ )
48
+
49
+
50
+ def build_citation(a: Act) -> Citation:
51
+ short_lang = {"DEU": "de", "FRA": "fr", "ITA": "it", "ENG": "en"}.get(a.lang, "en")
52
+ path = a.uri.replace(_DATA_BASE, "").lstrip("/")
53
+ source_url = f"{_PUBLIC_BASE}/{path}/{short_lang}"
54
+ label = a.title_short or a.title or a.uri
55
+ human = f"{label} (SR {a.sr_number})" if a.sr_number else label
56
+ return Citation(lex_uri=a.uri, human_readable_citation=human, source_url=source_url)
@@ -0,0 +1,111 @@
1
+ """Async httpx client for the Fedlex SPARQL endpoint (fedlex.data.admin.ch).
2
+
3
+ Keyless, live Virtuoso SPARQL endpoint over Swiss federal legislation,
4
+ modelled with the JOLux ontology (same family used by Luxembourg's Legilux).
5
+ Fedlex is genuinely ELI-native - the resource URI itself is the ELI.
6
+
7
+ Note: Virtuoso's ``bif:contains`` full-text extension is disabled on this
8
+ public endpoint ("Illegal requests in query"), unlike the Chilean BCN
9
+ endpoint - full-text search here uses a standard SPARQL ``CONTAINS`` filter,
10
+ which is slower but portable.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import anyio
16
+ import httpx
17
+
18
+ from .cache import HttpCache
19
+ from .citations import lang_uri
20
+
21
+ DEFAULT_BASE_URL = "https://fedlex.data.admin.ch/sparqlendpoint"
22
+ DEFAULT_TIMEOUT = httpx.Timeout(40.0, connect=10.0)
23
+ USER_AGENT = "ch-eli-mcp/0.1.0 (+https://github.com/matematicsolutions/ch-eli-mcp)"
24
+
25
+ _RETRY_STATUS = frozenset({429, 500, 502, 503, 504})
26
+ _MAX_ATTEMPTS = 3
27
+
28
+ _PREFIXES = """\
29
+ PREFIX jolux: <http://data.legilux.public.lu/resource/ontology/jolux#>
30
+ PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
31
+ """
32
+
33
+ _SEARCH_QUERY = _PREFIXES + """\
34
+ SELECT DISTINCT ?s ?title ?title_short ?sr_number WHERE {
35
+ ?s a jolux:ConsolidationAbstract ; jolux:isRealizedBy ?expr .
36
+ ?expr jolux:language <%s> ; jolux:title ?title .
37
+ OPTIONAL { ?expr jolux:titleShort ?title_short }
38
+ OPTIONAL { ?s jolux:classifiedByTaxonomyEntry ?tax . ?tax skos:notation ?sr_number }
39
+ FILTER(CONTAINS(LCASE(?title), "%s"))
40
+ } LIMIT %d
41
+ """
42
+
43
+ _GET_QUERY = _PREFIXES + """\
44
+ SELECT ?title ?title_short ?sr_number WHERE {
45
+ <%s> jolux:isRealizedBy ?expr .
46
+ ?expr jolux:language <%s> ; jolux:title ?title .
47
+ OPTIONAL { ?expr jolux:titleShort ?title_short }
48
+ OPTIONAL { <%s> jolux:classifiedByTaxonomyEntry ?tax . ?tax skos:notation ?sr_number }
49
+ }
50
+ """
51
+
52
+
53
+ class FedlexClient:
54
+ """Async client. Use as ``async with FedlexClient() as c: ...``."""
55
+
56
+ def __init__(
57
+ self,
58
+ base_url: str = DEFAULT_BASE_URL,
59
+ cache: HttpCache | None = None,
60
+ timeout: httpx.Timeout = DEFAULT_TIMEOUT,
61
+ ) -> None:
62
+ self.base_url = base_url
63
+ self._cache = cache or HttpCache()
64
+ self._http = httpx.AsyncClient(
65
+ timeout=timeout,
66
+ headers={"User-Agent": USER_AGENT, "Accept": "application/sparql-results+json"},
67
+ )
68
+
69
+ async def __aenter__(self) -> FedlexClient:
70
+ return self
71
+
72
+ async def __aexit__(self, *_exc: object) -> None:
73
+ await self.aclose()
74
+
75
+ async def aclose(self) -> None:
76
+ await self._http.aclose()
77
+ self._cache.close()
78
+
79
+ async def _query(self, sparql: str, *, category: str) -> list[dict]:
80
+ cache_key = self.base_url + "?q=" + sparql
81
+ cached = self._cache.get(cache_key)
82
+ if cached is not None and isinstance(cached, list):
83
+ return cached
84
+ last_exc: Exception | None = None
85
+ for attempt in range(_MAX_ATTEMPTS):
86
+ try:
87
+ resp = await self._http.get(self.base_url, params={"query": sparql})
88
+ resp.raise_for_status()
89
+ bindings = resp.json()["results"]["bindings"]
90
+ self._cache.set(cache_key, bindings, ttl=HttpCache.ttl_for(category))
91
+ return bindings
92
+ except httpx.HTTPStatusError as exc:
93
+ last_exc = exc
94
+ if exc.response.status_code not in _RETRY_STATUS or attempt == _MAX_ATTEMPTS - 1:
95
+ raise
96
+ except (httpx.TransportError, httpx.TimeoutException) as exc:
97
+ last_exc = exc
98
+ if attempt == _MAX_ATTEMPTS - 1:
99
+ raise
100
+ await anyio.sleep(0.5 * (2**attempt))
101
+ assert last_exc is not None
102
+ raise last_exc
103
+
104
+ async def search(self, query: str, lang: str = "DEU", limit: int = 20) -> list[dict]:
105
+ needle = query.lower().replace('"', '\\"')
106
+ sparql = _SEARCH_QUERY % (lang_uri(lang), needle, limit)
107
+ return await self._query(sparql, category="search")
108
+
109
+ async def get_act(self, uri: str, lang: str = "DEU") -> list[dict]:
110
+ sparql = _GET_QUERY % (uri, lang_uri(lang), uri)
111
+ return await self._query(sparql, category="act")
@@ -0,0 +1,21 @@
1
+ """Plain dataclasses mirroring the Fedlex jolux ontology (SPARQL query results)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Act:
10
+ uri: str
11
+ lang: str
12
+ sr_number: str | None
13
+ title: str | None
14
+ title_short: str | None
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Citation:
19
+ lex_uri: str
20
+ human_readable_citation: str
21
+ source_url: str
@@ -0,0 +1,194 @@
1
+ """FastMCP entry point - Swiss federal legislation (Fedlex) tools.
2
+
3
+ Run:
4
+
5
+ python -m ch_eli_mcp.server
6
+
7
+ Configuration via env:
8
+
9
+ - ``CH_ELI_CACHE_DIR`` (default ``~/.matematic/cache/ch-eli``)
10
+ - ``CH_ELI_AUDIT_DIR`` (default ``~/.matematic/audit``)
11
+ - ``CH_ELI_BASE_URL`` (default ``https://fedlex.data.admin.ch/sparqlendpoint``)
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import dataclasses
17
+ import os
18
+
19
+ import httpx
20
+ from fastmcp import FastMCP
21
+ from mcp.types import ToolAnnotations
22
+
23
+ from .audit import AuditLogger, hash_input, timer
24
+ from .citations import build_citation, parse_act
25
+ from .client import DEFAULT_BASE_URL, FedlexClient
26
+
27
+ INSTRUCTIONS = """\
28
+ This MCP server exposes Fedlex, the Swiss Federal Chancellery's official publication platform for federal legislation. Fedlex is genuinely ELI-native - the resource URI itself is the ELI (European Legislation Identifier), even though Switzerland is not an EU member. Multilingual: German, French, Italian, English.
29
+
30
+ ## Call order
31
+
32
+ 1. `ch_search_acts` - full-text search over act titles in a given `lang` (`"DEU"`, `"FRA"`, `"ITA"`, or `"ENG"`).
33
+ 2. `ch_get_act` - full detail for one act by its `uri` (from the search results), including its SR number (Systematische Sammlung / Classified Compilation number - the citation convention used in Swiss legal practice).
34
+
35
+ ## Hard constraints
36
+
37
+ - **The ELI is the URI itself** - `lex_uri` is never invented, it comes directly from the SPARQL query result.
38
+ - **Every response has `human_readable_citation` + `source_url`** - cite both to the user (e.g. "Bundesverfassung der Schweizerischen Eidgenossenschaft (SR 101)").
39
+ - **No full-text law content** - this connector returns metadata (title, SR number), not the operative articles. Follow `source_url` for that.
40
+ - **Audit log JSONL** - every tool call appends to `~/.matematic/audit/ch-eli-mcp.jsonl`.
41
+
42
+ ## Error iteration
43
+
44
+ Tools return a structured error with a `[code]` prefix:
45
+ - `invalid_arg` - a parameter is missing, out of range, or an unsupported `lang`.
46
+ - `not_found` - no act exists at that URI.
47
+ - `upstream_error` - a Fedlex SPARQL endpoint error (HTTP, timeout, malformed query). Retry once before surfacing.
48
+
49
+ ## Response style
50
+
51
+ - Cite acts as `human_readable_citation`: "Bundesverfassung der Schweizerischen Eidgenossenschaft (SR 101)".
52
+ - NEVER invent a URI, SR number, or title - take each from the tool output.
53
+ """
54
+
55
+
56
+ class ToolError(Exception):
57
+ """Structured error for ch-eli MCP tools - visible to the LLM with a [code] prefix."""
58
+
59
+ VALID_CODES = frozenset({"invalid_arg", "not_found", "upstream_error"})
60
+
61
+ def __init__(self, code: str, message: str):
62
+ if code not in self.VALID_CODES:
63
+ raise ValueError(f"Unknown ToolError code: {code}. Valid: {sorted(self.VALID_CODES)}")
64
+ self.code = code
65
+ super().__init__(f"[{code}] {message}")
66
+
67
+
68
+ READ_ONLY = ToolAnnotations(
69
+ readOnlyHint=True,
70
+ idempotentHint=True,
71
+ destructiveHint=False,
72
+ openWorldHint=True,
73
+ )
74
+
75
+ mcp: FastMCP = FastMCP(name="ch-eli-mcp", instructions=INSTRUCTIONS)
76
+
77
+ _VALID_LANGS = frozenset({"DEU", "FRA", "ITA", "ENG"})
78
+
79
+
80
+ def _base_url() -> str:
81
+ return os.environ.get("CH_ELI_BASE_URL", DEFAULT_BASE_URL)
82
+
83
+
84
+ def _audit() -> AuditLogger:
85
+ return AuditLogger()
86
+
87
+
88
+ def _check_lang(lang: str) -> str:
89
+ code = lang.upper()
90
+ if code not in _VALID_LANGS:
91
+ raise ToolError("invalid_arg", f"lang={lang!r} must be one of {sorted(_VALID_LANGS)}.")
92
+ return code
93
+
94
+
95
+ def _map_upstream(exc: Exception) -> Exception:
96
+ if isinstance(exc, (httpx.HTTPStatusError, httpx.TransportError, httpx.TimeoutException)):
97
+ return ToolError("upstream_error", f"Fedlex SPARQL endpoint error: {type(exc).__name__}: {exc}")
98
+ return exc
99
+
100
+
101
+ def _to_dict(a) -> dict:
102
+ citation = build_citation(a)
103
+ return {**dataclasses.asdict(a), **dataclasses.asdict(citation)}
104
+
105
+
106
+ # ---------------------------------------------------------------------------
107
+ # ch_search_acts
108
+ # ---------------------------------------------------------------------------
109
+
110
+
111
+ @mcp.tool(annotations=READ_ONLY)
112
+ async def ch_search_acts(query: str, lang: str = "DEU", limit: int = 20) -> dict:
113
+ """Full-text search over Swiss federal act titles.
114
+
115
+ Args:
116
+ query: free text, e.g. ``"Datenschutz"``.
117
+ lang: one of ``"DEU"``, ``"FRA"``, ``"ITA"``, ``"ENG"`` (default ``"DEU"``).
118
+ limit: max results (default 20).
119
+
120
+ Returns:
121
+ ``{"total": int, "items": [...]}`` - each item carries the citation contract.
122
+ """
123
+ audit = _audit()
124
+ if not query or not query.strip():
125
+ raise ToolError("invalid_arg", "query must be a non-empty string.")
126
+ lang = _check_lang(lang)
127
+ input_hash = hash_input({"query": query, "lang": lang, "limit": limit})
128
+
129
+ with timer() as t:
130
+ try:
131
+ async with FedlexClient(base_url=_base_url()) as client:
132
+ rows = await client.search(query, lang, limit)
133
+ except Exception as exc:
134
+ audit.log(tool="ch_search_acts", input_hash=input_hash, output_count_or_size=0,
135
+ duration_ms=t.duration_ms if t.duration_ms else 0, status="error",
136
+ error=f"{type(exc).__name__}: {exc}")
137
+ raise _map_upstream(exc) from exc
138
+
139
+ items = [
140
+ _to_dict(parse_act(r["s"]["value"], lang, r)) for r in rows
141
+ ]
142
+ audit.log(tool="ch_search_acts", input_hash=input_hash, output_count_or_size=len(items),
143
+ duration_ms=t.duration_ms, status="ok")
144
+ return {"total": len(items), "items": items}
145
+
146
+
147
+ # ---------------------------------------------------------------------------
148
+ # ch_get_act
149
+ # ---------------------------------------------------------------------------
150
+
151
+
152
+ @mcp.tool(annotations=READ_ONLY)
153
+ async def ch_get_act(uri: str, lang: str = "DEU") -> dict:
154
+ """Fetch full detail for one Swiss federal act by its Fedlex ELI URI.
155
+
156
+ Args:
157
+ uri: e.g. ``"https://fedlex.data.admin.ch/eli/cc/1999/404"``.
158
+ lang: one of ``"DEU"``, ``"FRA"``, ``"ITA"``, ``"ENG"`` (default ``"DEU"``).
159
+
160
+ Returns:
161
+ A dict with ``sr_number``, ``title``, ``title_short``, ``lex_uri``,
162
+ ``human_readable_citation``, ``source_url``.
163
+ """
164
+ audit = _audit()
165
+ if not uri or not uri.startswith("https://fedlex.data.admin.ch/eli/"):
166
+ raise ToolError("invalid_arg", "uri must be a https://fedlex.data.admin.ch/eli/... URI.")
167
+ lang = _check_lang(lang)
168
+ input_hash = hash_input({"uri": uri, "lang": lang})
169
+
170
+ with timer() as t:
171
+ try:
172
+ async with FedlexClient(base_url=_base_url()) as client:
173
+ rows = await client.get_act(uri, lang)
174
+ except Exception as exc:
175
+ audit.log(tool="ch_get_act", input_hash=input_hash, output_count_or_size=0,
176
+ duration_ms=t.duration_ms if t.duration_ms else 0, status="error",
177
+ error=f"{type(exc).__name__}: {exc}")
178
+ raise _map_upstream(exc) from exc
179
+
180
+ if not rows:
181
+ raise ToolError("not_found", f"No act found at uri={uri!r} for lang={lang!r}.")
182
+ result = _to_dict(parse_act(uri, lang, rows[0]))
183
+ audit.log(tool="ch_get_act", input_hash=input_hash, output_count_or_size=1,
184
+ duration_ms=t.duration_ms, status="ok")
185
+ return result
186
+
187
+
188
+ def main() -> None:
189
+ """Run the MCP server over stdio (default for Claude Code)."""
190
+ mcp.run()
191
+
192
+
193
+ if __name__ == "__main__":
194
+ main()
@@ -0,0 +1,28 @@
1
+ """Live smoke test against the real Fedlex SPARQL endpoint. Network required."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ from ch_eli_mcp.citations import build_citation, parse_act
8
+ from ch_eli_mcp.client import FedlexClient
9
+
10
+
11
+ @pytest.mark.asyncio
12
+ async def test_search_and_get_act() -> None:
13
+ async with FedlexClient() as client:
14
+ rows = await client.search("Datenschutz", "DEU", limit=3)
15
+ assert len(rows) == 3
16
+
17
+ first = parse_act(rows[0]["s"]["value"], "DEU", rows[0])
18
+ citation = build_citation(first)
19
+ assert citation.lex_uri.startswith("https://fedlex.data.admin.ch/eli/")
20
+ assert citation.source_url.startswith("https://www.fedlex.admin.ch/eli/")
21
+
22
+ constitution_uri = "https://fedlex.data.admin.ch/eli/cc/1999/404"
23
+ detail_rows = await client.get_act(constitution_uri, "DEU")
24
+ assert detail_rows
25
+ detail = parse_act(constitution_uri, "DEU", detail_rows[0])
26
+ detail_citation = build_citation(detail)
27
+ assert detail.sr_number == "101"
28
+ assert detail_citation.human_readable_citation == "BV (SR 101)"