cl-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.
- cl_eli_mcp-0.1.0/.github/workflows/release.yml +61 -0
- cl_eli_mcp-0.1.0/.gitignore +20 -0
- cl_eli_mcp-0.1.0/DISCOVERY.md +36 -0
- cl_eli_mcp-0.1.0/LICENSE +202 -0
- cl_eli_mcp-0.1.0/PKG-INFO +75 -0
- cl_eli_mcp-0.1.0/README.md +44 -0
- cl_eli_mcp-0.1.0/SOURCES.md +31 -0
- cl_eli_mcp-0.1.0/glama.json +4 -0
- cl_eli_mcp-0.1.0/pyproject.toml +65 -0
- cl_eli_mcp-0.1.0/server.json +22 -0
- cl_eli_mcp-0.1.0/src/cl_eli_mcp/__init__.py +3 -0
- cl_eli_mcp-0.1.0/src/cl_eli_mcp/audit.py +94 -0
- cl_eli_mcp-0.1.0/src/cl_eli_mcp/cache.py +56 -0
- cl_eli_mcp-0.1.0/src/cl_eli_mcp/citations.py +76 -0
- cl_eli_mcp-0.1.0/src/cl_eli_mcp/client.py +103 -0
- cl_eli_mcp-0.1.0/src/cl_eli_mcp/models.py +24 -0
- cl_eli_mcp-0.1.0/src/cl_eli_mcp/server.py +181 -0
- cl_eli_mcp-0.1.0/tests/test_smoke.py +27 -0
|
@@ -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,36 @@
|
|
|
1
|
+
# Discovery notes - Chile
|
|
2
|
+
|
|
3
|
+
Date: 2026-07-06.
|
|
4
|
+
|
|
5
|
+
## Why SPARQL instead of the documented REST web service
|
|
6
|
+
|
|
7
|
+
An earlier regional sweep flagged Chile's `legislacion_abierta_web_service`
|
|
8
|
+
as the most mature-looking source in the non-Brazil, non-US Latin America
|
|
9
|
+
set (a dedicated developer portal with RDF/OWL ontologies). Live probing on
|
|
10
|
+
2026-07-06 found the documented REST endpoint
|
|
11
|
+
(`leychile.cl/Consulta/legislacion_abierta_web_service`,
|
|
12
|
+
`bcn.cl/leychile/Consulta/legislacion_abierta_web_service`) returns HTTP 401
|
|
13
|
+
on every variant tried, from this network. Rather than guess at
|
|
14
|
+
undocumented auth, the developer portal itself (`datos.bcn.cl`) turned out
|
|
15
|
+
to expose a live, keyless SPARQL 1.1 endpoint over the same underlying data
|
|
16
|
+
(Virtuoso, `https://datos.bcn.cl/sparql`) - confirmed working and used here
|
|
17
|
+
instead.
|
|
18
|
+
|
|
19
|
+
## What's genuinely strong here
|
|
20
|
+
|
|
21
|
+
The `bcn-norms` ontology models norms as FRBR Work (`RootNorm`) /
|
|
22
|
+
Expression / Manifestation, and every root norm has a persistent,
|
|
23
|
+
dereferenceable resource URI encoding jurisdiction/type/issuing-body/date/
|
|
24
|
+
number - structurally the same idea as ELI, even though BCN does not use
|
|
25
|
+
that name. This is the strongest identifier scheme found in the Latin
|
|
26
|
+
America sweep outside Brazil's LexML URN Lex.
|
|
27
|
+
|
|
28
|
+
## Revisit later
|
|
29
|
+
|
|
30
|
+
- Confirm whether the legacy `legislacion_abierta_web_service` 401 is a
|
|
31
|
+
genuine access restriction or geo/IP-based - if it turns out to be open
|
|
32
|
+
from a different network, it may expose full operative text that the
|
|
33
|
+
SPARQL endpoint does not.
|
|
34
|
+
- `NormInstance` (versioned/consolidated text) and cross-references
|
|
35
|
+
(`modifiesTo`, `agreeWith`) exist in the ontology but are not exposed as
|
|
36
|
+
tools yet - a natural v0.2.
|
cl_eli_mcp-0.1.0/LICENSE
ADDED
|
@@ -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,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cl-eli-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server for Chilean legislation (BCN Linked Open Data SPARQL endpoint) with verifiable citations.
|
|
5
|
+
Project-URL: Repository, https://github.com/matematicsolutions/cl-eli-mcp
|
|
6
|
+
Project-URL: Issues, https://github.com/matematicsolutions/cl-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: bcn,chile,law,legaltech,mcp,sparql
|
|
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
|
+
# cl-eli-mcp
|
|
33
|
+
|
|
34
|
+
<!-- mcp-name: io.github.matematicsolutions/cl-eli-mcp -->
|
|
35
|
+
|
|
36
|
+
MCP server for Chilean legislation via the BCN (Biblioteca del Congreso
|
|
37
|
+
Nacional de Chile) Linked Open Data SPARQL endpoint. Searches and fetches
|
|
38
|
+
laws, decrees, and resolutions by their persistent resource URI.
|
|
39
|
+
|
|
40
|
+
## What this is not
|
|
41
|
+
|
|
42
|
+
BCN's resource URIs are not formally called ELI, but they carry the same
|
|
43
|
+
idea: jurisdiction, type, issuing body, date, number, all in one
|
|
44
|
+
dereferenceable URI. This connector returns metadata (title, number, dates,
|
|
45
|
+
issuing body) - not the operative text of the law. Following `source_url`
|
|
46
|
+
(the same URI, content-negotiated) takes you to the human-readable page.
|
|
47
|
+
|
|
48
|
+
## Tools
|
|
49
|
+
|
|
50
|
+
| Tool | Purpose |
|
|
51
|
+
|---|---|
|
|
52
|
+
| `cl_search_norms` | Full-text search over norm titles |
|
|
53
|
+
| `cl_get_norm` | Full detail for one norm by its BCN resource URI |
|
|
54
|
+
|
|
55
|
+
Every response carries `lex_uri` and `source_url` (both the BCN resource
|
|
56
|
+
URI) and `human_readable_citation` (e.g. `"Ley 18290, de 1984-01-23"`).
|
|
57
|
+
|
|
58
|
+
## Install
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install cl-eli-mcp
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Configuration
|
|
65
|
+
|
|
66
|
+
| Env var | Default |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `CL_ELI_CACHE_DIR` | `~/.matematic/cache/cl-eli` |
|
|
69
|
+
| `CL_ELI_AUDIT_DIR` | `~/.matematic/audit` |
|
|
70
|
+
| `CL_ELI_BASE_URL` | `https://datos.bcn.cl/sparql` |
|
|
71
|
+
|
|
72
|
+
## License
|
|
73
|
+
|
|
74
|
+
Apache-2.0 (code). BCN Linked Open Data is a public government dataset (see
|
|
75
|
+
[SOURCES.md](SOURCES.md)).
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# cl-eli-mcp
|
|
2
|
+
|
|
3
|
+
<!-- mcp-name: io.github.matematicsolutions/cl-eli-mcp -->
|
|
4
|
+
|
|
5
|
+
MCP server for Chilean legislation via the BCN (Biblioteca del Congreso
|
|
6
|
+
Nacional de Chile) Linked Open Data SPARQL endpoint. Searches and fetches
|
|
7
|
+
laws, decrees, and resolutions by their persistent resource URI.
|
|
8
|
+
|
|
9
|
+
## What this is not
|
|
10
|
+
|
|
11
|
+
BCN's resource URIs are not formally called ELI, but they carry the same
|
|
12
|
+
idea: jurisdiction, type, issuing body, date, number, all in one
|
|
13
|
+
dereferenceable URI. This connector returns metadata (title, number, dates,
|
|
14
|
+
issuing body) - not the operative text of the law. Following `source_url`
|
|
15
|
+
(the same URI, content-negotiated) takes you to the human-readable page.
|
|
16
|
+
|
|
17
|
+
## Tools
|
|
18
|
+
|
|
19
|
+
| Tool | Purpose |
|
|
20
|
+
|---|---|
|
|
21
|
+
| `cl_search_norms` | Full-text search over norm titles |
|
|
22
|
+
| `cl_get_norm` | Full detail for one norm by its BCN resource URI |
|
|
23
|
+
|
|
24
|
+
Every response carries `lex_uri` and `source_url` (both the BCN resource
|
|
25
|
+
URI) and `human_readable_citation` (e.g. `"Ley 18290, de 1984-01-23"`).
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install cl-eli-mcp
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Configuration
|
|
34
|
+
|
|
35
|
+
| Env var | Default |
|
|
36
|
+
|---|---|
|
|
37
|
+
| `CL_ELI_CACHE_DIR` | `~/.matematic/cache/cl-eli` |
|
|
38
|
+
| `CL_ELI_AUDIT_DIR` | `~/.matematic/audit` |
|
|
39
|
+
| `CL_ELI_BASE_URL` | `https://datos.bcn.cl/sparql` |
|
|
40
|
+
|
|
41
|
+
## License
|
|
42
|
+
|
|
43
|
+
Apache-2.0 (code). BCN Linked Open Data is a public government dataset (see
|
|
44
|
+
[SOURCES.md](SOURCES.md)).
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Sources
|
|
2
|
+
|
|
3
|
+
## BCN Linked Open Data (`datos.bcn.cl`)
|
|
4
|
+
|
|
5
|
+
- **Origin**: Biblioteca del Congreso Nacional de Chile.
|
|
6
|
+
- **License**: public government open data.
|
|
7
|
+
- **Access**: keyless SPARQL 1.1 (Virtuoso), JSON results, `bif:contains` full-text extension.
|
|
8
|
+
- **Ontology**: `http://datos.bcn.cl/ontologies/bcn-norms#` (Norm / RootNorm /
|
|
9
|
+
NormInstance, FRBR Work/Expression/Manifestation model). Confirmed live
|
|
10
|
+
2026-07-06: 748,783 `Norm` instances, 359,720 `RootNorm` (top-level laws/
|
|
11
|
+
decrees/resolutions).
|
|
12
|
+
- **Identifier**: the resource URI itself, e.g.
|
|
13
|
+
`http://datos.bcn.cl/recurso/cl/ley/ministerio-de-justicia/1984-02-07/18290`
|
|
14
|
+
- jurisdiction/type/issuing-body/date/number, dereferenceable (redirects to
|
|
15
|
+
a human-readable page). Not formally ELI, but the same idea.
|
|
16
|
+
- **Coverage**: this connector only queries `RootNorm` title/number/
|
|
17
|
+
promulgationDate via SPARQL. It does not cover `NormInstance` (versioned
|
|
18
|
+
text), `VotoProyectoDeLey` (bill votes), `EjecucionPresupuesto` (budget
|
|
19
|
+
execution), or any of the other classes in this same triple store.
|
|
20
|
+
|
|
21
|
+
## Not covered (out of scope for this connector)
|
|
22
|
+
|
|
23
|
+
- **Legacy `legislacion_abierta_web_service`** (leychile.cl/bcn.cl) - the
|
|
24
|
+
older REST-style web service returned HTTP 401 on every probe from this
|
|
25
|
+
network on 2026-07-06 (possibly geo/IP-restricted or deprecated in favor
|
|
26
|
+
of the SPARQL endpoint). Not used here.
|
|
27
|
+
- **Full operative text of a law** - the SPARQL endpoint exposes metadata,
|
|
28
|
+
not article-level text. `leychileCode` (present on some norms) is the
|
|
29
|
+
numeric ID used by the legacy web viewer, kept here for reference only -
|
|
30
|
+
not resolved into a URL, since the legacy domain was unreachable during
|
|
31
|
+
discovery.
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cl-eli-mcp"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "MCP server for Chilean legislation (BCN Linked Open Data SPARQL endpoint) 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", "chile", "bcn", "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/cl-eli-mcp"
|
|
44
|
+
Issues = "https://github.com/matematicsolutions/cl-eli-mcp/issues"
|
|
45
|
+
Homepage = "https://matematic.co"
|
|
46
|
+
|
|
47
|
+
[project.scripts]
|
|
48
|
+
cl-eli-mcp = "cl_eli_mcp.server:main"
|
|
49
|
+
|
|
50
|
+
[tool.hatch.build.targets.wheel]
|
|
51
|
+
packages = ["src/cl_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/cl_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/cl-eli-mcp",
|
|
4
|
+
"description": "MCP server for Chilean legislation via BCN Linked Open Data, verifiable citations.",
|
|
5
|
+
"version": "0.1.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"url": "https://github.com/matematicsolutions/cl-eli-mcp",
|
|
8
|
+
"source": "github"
|
|
9
|
+
},
|
|
10
|
+
"packages": [
|
|
11
|
+
{
|
|
12
|
+
"registryType": "pypi",
|
|
13
|
+
"registryBaseUrl": "https://pypi.org",
|
|
14
|
+
"identifier": "cl-eli-mcp",
|
|
15
|
+
"version": "0.1.0",
|
|
16
|
+
"runtimeHint": "uvx",
|
|
17
|
+
"transport": {
|
|
18
|
+
"type": "stdio"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
]
|
|
22
|
+
}
|
|
@@ -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/cl-eli-mcp.jsonl
|
|
6
|
+
|
|
7
|
+
(or to the directory given by ``CL_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 = "cl-eli-mcp.jsonl"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _resolve_audit_dir() -> Path:
|
|
29
|
+
env = os.environ.get("CL_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("CL_ELI_CACHE_DIR")
|
|
22
|
+
if env:
|
|
23
|
+
return Path(env).expanduser()
|
|
24
|
+
return Path.home() / ".matematic" / "cache" / "cl-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,76 @@
|
|
|
1
|
+
"""Citation contract for cl-eli-mcp.
|
|
2
|
+
|
|
3
|
+
BCN's Linked Open Data resource URIs (e.g.
|
|
4
|
+
``http://datos.bcn.cl/recurso/cl/ley/ministerio-de-justicia/1984-02-07/18290``)
|
|
5
|
+
are already a native, dereferenceable persistent identifier - not called ELI,
|
|
6
|
+
but structurally the same idea (jurisdiction/type/issuing-body/date/number).
|
|
7
|
+
We use it directly rather than inventing anything.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from .models import Citation, Norm
|
|
15
|
+
|
|
16
|
+
_TYPE_LABELS = {
|
|
17
|
+
"ley": "Ley",
|
|
18
|
+
"dto": "Decreto",
|
|
19
|
+
"dfl": "Decreto con Fuerza de Ley",
|
|
20
|
+
"dl": "Decreto Ley",
|
|
21
|
+
"res": "Resolucion",
|
|
22
|
+
"auto": "Auto Acordado",
|
|
23
|
+
"cir": "Circular",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _extract_type(uri: str) -> str:
|
|
28
|
+
parts = uri.split("/recurso/cl/", 1)
|
|
29
|
+
if len(parts) != 2:
|
|
30
|
+
return "norma"
|
|
31
|
+
return parts[1].split("/", 1)[0]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def group_describe(bindings: list[dict[str, Any]]) -> dict[str, list[str]]:
|
|
35
|
+
"""Group SPARQL DESCRIBE-style (?p ?o) bindings by predicate local name."""
|
|
36
|
+
grouped: dict[str, list[str]] = {}
|
|
37
|
+
for row in bindings:
|
|
38
|
+
pred = row["p"]["value"]
|
|
39
|
+
local = pred.rsplit("#", 1)[-1].rsplit("/", 1)[-1]
|
|
40
|
+
grouped.setdefault(local, []).append(row["o"]["value"])
|
|
41
|
+
return grouped
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def norm_from_search_row(row: dict[str, Any]) -> Norm:
|
|
45
|
+
uri = row["s"]["value"]
|
|
46
|
+
return Norm(
|
|
47
|
+
uri=uri,
|
|
48
|
+
norm_type=_extract_type(uri),
|
|
49
|
+
number=row.get("number", {}).get("value"),
|
|
50
|
+
title=row.get("title", {}).get("value"),
|
|
51
|
+
organism=None,
|
|
52
|
+
promulgation_date=row.get("pdate", {}).get("value"),
|
|
53
|
+
publish_date=None,
|
|
54
|
+
leychile_code=None,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def norm_from_bindings(uri: str, props: dict[str, list[str]]) -> Norm:
|
|
59
|
+
return Norm(
|
|
60
|
+
uri=uri,
|
|
61
|
+
norm_type=_extract_type(uri),
|
|
62
|
+
number=(props.get("hasNumber") or [None])[0],
|
|
63
|
+
title=(props.get("title") or props.get("label") or [None])[0],
|
|
64
|
+
organism=(props.get("createdBy") or [None])[0],
|
|
65
|
+
promulgation_date=(props.get("promulgationDate") or [None])[0],
|
|
66
|
+
publish_date=(props.get("publishDate") or [None])[0],
|
|
67
|
+
leychile_code=(props.get("leychileCode") or [None])[0],
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def build_citation(n: Any) -> Citation:
|
|
72
|
+
label = _TYPE_LABELS.get(n.norm_type, n.norm_type.capitalize())
|
|
73
|
+
number = n.number or "?"
|
|
74
|
+
date = n.promulgation_date or n.publish_date or ""
|
|
75
|
+
human = f"{label} {number}" + (f", de {date}" if date else "")
|
|
76
|
+
return Citation(lex_uri=n.uri, human_readable_citation=human, source_url=n.uri)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Async httpx client for the BCN Linked Open Data SPARQL endpoint (datos.bcn.cl/sparql).
|
|
2
|
+
|
|
3
|
+
Keyless, live Virtuoso SPARQL endpoint over Chilean legislation (748,783+ norm
|
|
4
|
+
instances per a 2026-07-06 live count). Full-text search uses Virtuoso's
|
|
5
|
+
``bif:contains`` extension over titles.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import anyio
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .cache import HttpCache
|
|
14
|
+
|
|
15
|
+
DEFAULT_BASE_URL = "https://datos.bcn.cl/sparql"
|
|
16
|
+
DEFAULT_TIMEOUT = httpx.Timeout(40.0, connect=10.0)
|
|
17
|
+
USER_AGENT = "cl-eli-mcp/0.1.0 (+https://github.com/matematicsolutions/cl-eli-mcp)"
|
|
18
|
+
|
|
19
|
+
_RETRY_STATUS = frozenset({429, 500, 502, 503, 504})
|
|
20
|
+
_MAX_ATTEMPTS = 3
|
|
21
|
+
|
|
22
|
+
_PREFIXES = """\
|
|
23
|
+
PREFIX bcnorms: <http://datos.bcn.cl/ontologies/bcn-norms#>
|
|
24
|
+
PREFIX dc: <http://purl.org/dc/elements/1.1/>
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
_SEARCH_QUERY = _PREFIXES + """\
|
|
28
|
+
SELECT ?s ?title ?number ?pdate WHERE {
|
|
29
|
+
?s a bcnorms:RootNorm ; dc:title ?title .
|
|
30
|
+
?title bif:contains "%s" .
|
|
31
|
+
OPTIONAL { ?s bcnorms:hasNumber ?number }
|
|
32
|
+
OPTIONAL { ?s bcnorms:promulgationDate ?pdate }
|
|
33
|
+
} LIMIT %d
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
_DESCRIBE_QUERY = _PREFIXES + """\
|
|
37
|
+
SELECT ?p ?o WHERE { <%s> ?p ?o }
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BcnSparqlClient:
|
|
42
|
+
"""Async client. Use as ``async with BcnSparqlClient() as c: ...``."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
47
|
+
cache: HttpCache | None = None,
|
|
48
|
+
timeout: httpx.Timeout = DEFAULT_TIMEOUT,
|
|
49
|
+
) -> None:
|
|
50
|
+
self.base_url = base_url
|
|
51
|
+
self._cache = cache or HttpCache()
|
|
52
|
+
self._http = httpx.AsyncClient(
|
|
53
|
+
timeout=timeout,
|
|
54
|
+
headers={"User-Agent": USER_AGENT, "Accept": "application/sparql-results+json"},
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
async def __aenter__(self) -> BcnSparqlClient:
|
|
58
|
+
return self
|
|
59
|
+
|
|
60
|
+
async def __aexit__(self, *_exc: object) -> None:
|
|
61
|
+
await self.aclose()
|
|
62
|
+
|
|
63
|
+
async def aclose(self) -> None:
|
|
64
|
+
await self._http.aclose()
|
|
65
|
+
self._cache.close()
|
|
66
|
+
|
|
67
|
+
async def _query(self, sparql: str, *, category: str) -> list[dict]:
|
|
68
|
+
cache_key = self.base_url + "?q=" + sparql
|
|
69
|
+
cached = self._cache.get(cache_key)
|
|
70
|
+
if cached is not None and isinstance(cached, list):
|
|
71
|
+
return cached
|
|
72
|
+
last_exc: Exception | None = None
|
|
73
|
+
for attempt in range(_MAX_ATTEMPTS):
|
|
74
|
+
try:
|
|
75
|
+
params = {"query": sparql, "format": "json"}
|
|
76
|
+
resp = await self._http.get(self.base_url, params=params)
|
|
77
|
+
resp.raise_for_status()
|
|
78
|
+
bindings = resp.json()["results"]["bindings"]
|
|
79
|
+
self._cache.set(cache_key, bindings, ttl=HttpCache.ttl_for(category))
|
|
80
|
+
return bindings
|
|
81
|
+
except httpx.HTTPStatusError as exc:
|
|
82
|
+
last_exc = exc
|
|
83
|
+
if exc.response.status_code not in _RETRY_STATUS or attempt == _MAX_ATTEMPTS - 1:
|
|
84
|
+
raise
|
|
85
|
+
except (httpx.TransportError, httpx.TimeoutException) as exc:
|
|
86
|
+
last_exc = exc
|
|
87
|
+
if attempt == _MAX_ATTEMPTS - 1:
|
|
88
|
+
raise
|
|
89
|
+
await anyio.sleep(0.5 * (2**attempt))
|
|
90
|
+
assert last_exc is not None
|
|
91
|
+
raise last_exc
|
|
92
|
+
|
|
93
|
+
async def search(self, query: str, limit: int = 20) -> list[dict]:
|
|
94
|
+
# Virtuoso's bif:contains needs an explicit boolean expression for
|
|
95
|
+
# multi-word phrases - a bare "word1 word2" string is a syntax error.
|
|
96
|
+
words = [w.replace("'", "").replace('"', "") for w in query.split() if w]
|
|
97
|
+
contains_expr = " AND ".join(f"'{w}'" for w in words) or f"'{query}'"
|
|
98
|
+
sparql = _SEARCH_QUERY % (contains_expr, limit)
|
|
99
|
+
return await self._query(sparql, category="search")
|
|
100
|
+
|
|
101
|
+
async def describe(self, uri: str) -> list[dict]:
|
|
102
|
+
sparql = _DESCRIBE_QUERY % uri
|
|
103
|
+
return await self._query(sparql, category="act")
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Plain dataclasses mirroring the BCN bcn-norms ontology (SPARQL query results)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Norm:
|
|
10
|
+
uri: str
|
|
11
|
+
norm_type: str
|
|
12
|
+
number: str | None
|
|
13
|
+
title: str | None
|
|
14
|
+
organism: str | None
|
|
15
|
+
promulgation_date: str | None
|
|
16
|
+
publish_date: str | None
|
|
17
|
+
leychile_code: str | None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Citation:
|
|
22
|
+
lex_uri: str
|
|
23
|
+
human_readable_citation: str
|
|
24
|
+
source_url: str
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""FastMCP entry point - Chilean legislation (BCN Linked Open Data) tools.
|
|
2
|
+
|
|
3
|
+
Run:
|
|
4
|
+
|
|
5
|
+
python -m cl_eli_mcp.server
|
|
6
|
+
|
|
7
|
+
Configuration via env:
|
|
8
|
+
|
|
9
|
+
- ``CL_ELI_CACHE_DIR`` (default ``~/.matematic/cache/cl-eli``)
|
|
10
|
+
- ``CL_ELI_AUDIT_DIR`` (default ``~/.matematic/audit``)
|
|
11
|
+
- ``CL_ELI_BASE_URL`` (default ``https://datos.bcn.cl/sparql``)
|
|
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, group_describe, norm_from_bindings, norm_from_search_row
|
|
25
|
+
from .client import DEFAULT_BASE_URL, BcnSparqlClient
|
|
26
|
+
|
|
27
|
+
INSTRUCTIONS = """\
|
|
28
|
+
This MCP server exposes the BCN (Biblioteca del Congreso Nacional de Chile) Linked Open Data SPARQL endpoint. It searches and fetches Chilean legislation (laws, decrees, resolutions) via a persistent resource URI - not called ELI, but structurally the same idea: jurisdiction/type/issuing-body/date/number.
|
|
29
|
+
|
|
30
|
+
## Call order
|
|
31
|
+
|
|
32
|
+
1. `cl_search_norms` - full-text search over norm titles (e.g. "ley de transito").
|
|
33
|
+
2. `cl_get_norm` - full detail for one norm by its `uri` (from the search results).
|
|
34
|
+
|
|
35
|
+
## Hard constraints
|
|
36
|
+
|
|
37
|
+
- **The resource URI IS the citation contract** - `lex_uri` and `source_url` are the same BCN URI; dereferencing it (a plain GET, following redirects) resolves to a human-readable page.
|
|
38
|
+
- **No full-text law content** - this connector returns metadata (title, number, dates, issuing body), not the operative articles of the law. For that, follow `source_url`.
|
|
39
|
+
- **Every response has `human_readable_citation`** - e.g. "Ley 18290, de 1984-01-23". Cite it plus `source_url`.
|
|
40
|
+
- **Audit log JSONL** - every tool call appends to `~/.matematic/audit/cl-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 or malformed.
|
|
46
|
+
- `not_found` - no norm exists at that URI.
|
|
47
|
+
- `upstream_error` - a BCN SPARQL endpoint error (HTTP, timeout, malformed query). Retry once before surfacing.
|
|
48
|
+
|
|
49
|
+
## Response style
|
|
50
|
+
|
|
51
|
+
- Cite norms as `human_readable_citation`: "Ley 18290, de 1984-01-23".
|
|
52
|
+
- NEVER invent a URI, a number or a date - take each from the tool output.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ToolError(Exception):
|
|
57
|
+
"""Structured error for cl-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="cl-eli-mcp", instructions=INSTRUCTIONS)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _base_url() -> str:
|
|
79
|
+
return os.environ.get("CL_ELI_BASE_URL", DEFAULT_BASE_URL)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _audit() -> AuditLogger:
|
|
83
|
+
return AuditLogger()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _map_upstream(exc: Exception) -> Exception:
|
|
87
|
+
if isinstance(exc, (httpx.HTTPStatusError, httpx.TransportError, httpx.TimeoutException)):
|
|
88
|
+
return ToolError("upstream_error", f"BCN SPARQL endpoint error: {type(exc).__name__}: {exc}")
|
|
89
|
+
return exc
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _to_dict(n) -> dict:
|
|
93
|
+
citation = build_citation(n)
|
|
94
|
+
return {**dataclasses.asdict(n), **dataclasses.asdict(citation)}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ---------------------------------------------------------------------------
|
|
98
|
+
# cl_search_norms
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
103
|
+
async def cl_search_norms(query: str, limit: int = 20) -> dict:
|
|
104
|
+
"""Full-text search over Chilean legislation titles.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
query: free text, e.g. ``"ley de transito"``.
|
|
108
|
+
limit: max results (default 20).
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
``{"total": int, "items": [...]}`` - each item carries the citation contract.
|
|
112
|
+
"""
|
|
113
|
+
audit = _audit()
|
|
114
|
+
if not query or not query.strip():
|
|
115
|
+
raise ToolError("invalid_arg", "query must be a non-empty string.")
|
|
116
|
+
input_hash = hash_input({"query": query, "limit": limit})
|
|
117
|
+
|
|
118
|
+
with timer() as t:
|
|
119
|
+
try:
|
|
120
|
+
async with BcnSparqlClient(base_url=_base_url()) as client:
|
|
121
|
+
rows = await client.search(query, limit)
|
|
122
|
+
except Exception as exc:
|
|
123
|
+
audit.log(tool="cl_search_norms", input_hash=input_hash, output_count_or_size=0,
|
|
124
|
+
duration_ms=t.duration_ms if t.duration_ms else 0, status="error",
|
|
125
|
+
error=f"{type(exc).__name__}: {exc}")
|
|
126
|
+
raise _map_upstream(exc) from exc
|
|
127
|
+
|
|
128
|
+
items = [_to_dict(norm_from_search_row(r)) for r in rows]
|
|
129
|
+
audit.log(tool="cl_search_norms", input_hash=input_hash, output_count_or_size=len(items),
|
|
130
|
+
duration_ms=t.duration_ms, status="ok")
|
|
131
|
+
return {"total": len(items), "items": items}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ---------------------------------------------------------------------------
|
|
135
|
+
# cl_get_norm
|
|
136
|
+
# ---------------------------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
140
|
+
async def cl_get_norm(uri: str) -> dict:
|
|
141
|
+
"""Fetch full detail for one Chilean norm by its BCN resource URI.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
uri: e.g. ``"http://datos.bcn.cl/recurso/cl/ley/ministerio-de-justicia/1984-02-07/18290"``.
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
A dict with ``norm_type``, ``number``, ``title``, ``organism``,
|
|
148
|
+
``promulgation_date``, ``publish_date``, ``leychile_code``,
|
|
149
|
+
``lex_uri``, ``human_readable_citation``, ``source_url``.
|
|
150
|
+
"""
|
|
151
|
+
audit = _audit()
|
|
152
|
+
if not uri or not uri.startswith("http://datos.bcn.cl/recurso/"):
|
|
153
|
+
raise ToolError("invalid_arg", "uri must be a http://datos.bcn.cl/recurso/... BCN resource URI.")
|
|
154
|
+
input_hash = hash_input({"uri": uri})
|
|
155
|
+
|
|
156
|
+
with timer() as t:
|
|
157
|
+
try:
|
|
158
|
+
async with BcnSparqlClient(base_url=_base_url()) as client:
|
|
159
|
+
bindings = await client.describe(uri)
|
|
160
|
+
except Exception as exc:
|
|
161
|
+
audit.log(tool="cl_get_norm", input_hash=input_hash, output_count_or_size=0,
|
|
162
|
+
duration_ms=t.duration_ms if t.duration_ms else 0, status="error",
|
|
163
|
+
error=f"{type(exc).__name__}: {exc}")
|
|
164
|
+
raise _map_upstream(exc) from exc
|
|
165
|
+
|
|
166
|
+
if not bindings:
|
|
167
|
+
raise ToolError("not_found", f"No norm found at uri={uri!r}.")
|
|
168
|
+
props = group_describe(bindings)
|
|
169
|
+
result = _to_dict(norm_from_bindings(uri, props))
|
|
170
|
+
audit.log(tool="cl_get_norm", input_hash=input_hash, output_count_or_size=1,
|
|
171
|
+
duration_ms=t.duration_ms, status="ok")
|
|
172
|
+
return result
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def main() -> None:
|
|
176
|
+
"""Run the MCP server over stdio (default for Claude Code)."""
|
|
177
|
+
mcp.run()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
if __name__ == "__main__":
|
|
181
|
+
main()
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Live smoke test against the real BCN SPARQL endpoint. Network required."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from cl_eli_mcp.citations import build_citation, group_describe, norm_from_bindings, norm_from_search_row
|
|
8
|
+
from cl_eli_mcp.client import BcnSparqlClient
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pytest.mark.asyncio
|
|
12
|
+
async def test_search_and_describe_norm() -> None:
|
|
13
|
+
async with BcnSparqlClient() as client:
|
|
14
|
+
rows = await client.search("ley de transito", limit=2)
|
|
15
|
+
assert len(rows) == 2
|
|
16
|
+
|
|
17
|
+
norm = norm_from_search_row(rows[0])
|
|
18
|
+
citation = build_citation(norm)
|
|
19
|
+
assert citation.lex_uri.startswith("http://datos.bcn.cl/recurso/cl/")
|
|
20
|
+
assert citation.human_readable_citation.startswith("Ley ")
|
|
21
|
+
|
|
22
|
+
bindings = await client.describe(norm.uri)
|
|
23
|
+
assert bindings
|
|
24
|
+
props = group_describe(bindings)
|
|
25
|
+
detail = norm_from_bindings(norm.uri, props)
|
|
26
|
+
assert detail.title is not None
|
|
27
|
+
assert detail.organism is not None
|