co-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,26 @@
1
+ # Discovery notes - Colombia
2
+
3
+ Date: 2026-07-06.
4
+
5
+ ## Why Corte Constitucional metadata, not full text
6
+
7
+ An earlier regional sweep of Latin American sources ranked Colombia highest
8
+ by ROI outside Brazil and the US: highest lawyers-per-capita ratio in the
9
+ world (~425,000 lawyers, 801 per 100,000 people) and a confirmed
10
+ machine-readable, keyless dataset via the national open-data portal
11
+ (datos.gov.co, Socrata).
12
+
13
+ The dataset only carries metadata, not full decision text. That is enough
14
+ for a citation-verification tool - "does T-012/92 exist, who wrote it, when"
15
+ - which is a genuinely useful anti-hallucination check, in the same spirit as
16
+ `citation-grounding-pl`. Fetching full text would mean scraping
17
+ `corteconstitucional.gov.co/relatoria/...` HTML pages, a different (and more
18
+ fragile) class of connector than the rest of this fleet - not built here.
19
+
20
+ ## SUIN-Juriscol (legislation) - not covered
21
+
22
+ SUIN-Juriscol (`suin-juriscol.gov.co`) indexes Colombian legislation but is
23
+ primarily an HTML search interface. Colombia does publish some legislative
24
+ data through datos.gov.co too, but that was not probed in this pass - a
25
+ natural v0.2 feature for this repo if it turns out to be structured data
26
+ rather than another HTML-only search.
@@ -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: co-eli-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for Colombian Constitutional Court decisions (datos.gov.co) - citation verification and metadata.
5
+ Project-URL: Repository, https://github.com/matematicsolutions/co-eli-mcp
6
+ Project-URL: Issues, https://github.com/matematicsolutions/co-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: colombia,corte-constitucional,law,legaltech,mcp
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
+ # co-eli-mcp
33
+
34
+ <!-- mcp-name: io.github.matematicsolutions/co-eli-mcp -->
35
+
36
+ MCP server for the datos.gov.co open-data record of decisions (sentencias) by
37
+ the Colombian Constitutional Court (Corte Constitucional). Verifies whether a
38
+ citation exists and returns its metadata.
39
+
40
+ ## What this is not
41
+
42
+ This dataset (`v2k4-2t8s`, "Sentencias proferidas por la Corte Constitucional")
43
+ has no full-text field - only metadata: proceso, expediente, magistrado
44
+ ponente, sala, and date. `source_url` points to the public relatoria page
45
+ where the full decision text lives, but this connector does not fetch it.
46
+
47
+ ## Tools
48
+
49
+ | Tool | Purpose |
50
+ |---|---|
51
+ | `co_search_sentencias` | Free-text search (e.g. by magistrado name or proceso type) |
52
+ | `co_get_sentencia` | Exact lookup by citation, e.g. `"T-012/92"` - verifies it exists |
53
+
54
+ Every response carries `lex_uri` and `source_url` (the public
55
+ corteconstitucional.gov.co relatoria page) and `human_readable_citation`
56
+ (the citation itself, e.g. `"T-012/92"` - already the form used in practice,
57
+ so no separate identifier scheme is needed here).
58
+
59
+ ## Install
60
+
61
+ ```bash
62
+ pip install co-eli-mcp
63
+ ```
64
+
65
+ ## Configuration
66
+
67
+ | Env var | Default |
68
+ |---|---|
69
+ | `CO_ELI_CACHE_DIR` | `~/.matematic/cache/co-eli` |
70
+ | `CO_ELI_AUDIT_DIR` | `~/.matematic/audit` |
71
+ | `CO_ELI_BASE_URL` | `https://www.datos.gov.co/resource/v2k4-2t8s.json` |
72
+
73
+ ## License
74
+
75
+ Apache-2.0 (code). datos.gov.co data is open data (see [SOURCES.md](SOURCES.md)).
@@ -0,0 +1,44 @@
1
+ # co-eli-mcp
2
+
3
+ <!-- mcp-name: io.github.matematicsolutions/co-eli-mcp -->
4
+
5
+ MCP server for the datos.gov.co open-data record of decisions (sentencias) by
6
+ the Colombian Constitutional Court (Corte Constitucional). Verifies whether a
7
+ citation exists and returns its metadata.
8
+
9
+ ## What this is not
10
+
11
+ This dataset (`v2k4-2t8s`, "Sentencias proferidas por la Corte Constitucional")
12
+ has no full-text field - only metadata: proceso, expediente, magistrado
13
+ ponente, sala, and date. `source_url` points to the public relatoria page
14
+ where the full decision text lives, but this connector does not fetch it.
15
+
16
+ ## Tools
17
+
18
+ | Tool | Purpose |
19
+ |---|---|
20
+ | `co_search_sentencias` | Free-text search (e.g. by magistrado name or proceso type) |
21
+ | `co_get_sentencia` | Exact lookup by citation, e.g. `"T-012/92"` - verifies it exists |
22
+
23
+ Every response carries `lex_uri` and `source_url` (the public
24
+ corteconstitucional.gov.co relatoria page) and `human_readable_citation`
25
+ (the citation itself, e.g. `"T-012/92"` - already the form used in practice,
26
+ so no separate identifier scheme is needed here).
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install co-eli-mcp
32
+ ```
33
+
34
+ ## Configuration
35
+
36
+ | Env var | Default |
37
+ |---|---|
38
+ | `CO_ELI_CACHE_DIR` | `~/.matematic/cache/co-eli` |
39
+ | `CO_ELI_AUDIT_DIR` | `~/.matematic/audit` |
40
+ | `CO_ELI_BASE_URL` | `https://www.datos.gov.co/resource/v2k4-2t8s.json` |
41
+
42
+ ## License
43
+
44
+ Apache-2.0 (code). datos.gov.co data is open data (see [SOURCES.md](SOURCES.md)).
@@ -0,0 +1,20 @@
1
+ # Sources
2
+
3
+ ## datos.gov.co - Sentencias proferidas por la Corte Constitucional (`v2k4-2t8s`)
4
+
5
+ - **Origin**: Corte Constitucional de Colombia, published via the national
6
+ open-data portal (Socrata).
7
+ - **License**: open data.
8
+ - **Access**: keyless REST (Socrata SoQL), JSON.
9
+ - **Coverage**: all decisions from 1992 to the present, updated monthly per
10
+ the dataset description. Metadata only - proceso, expediente, magistrado
11
+ ponente, sala, sentencia citation, date. No full-text field.
12
+ - **Confirmed live** 2026-07-06: `$where=sentencia='T-012/92'` (exact lookup)
13
+ and `$q=<text>` (free-text search) both work as documented.
14
+
15
+ ## Public full-text source (not fetched by this connector)
16
+
17
+ `corteconstitucional.gov.co/relatoria/{year}/{TYPE}-{NUMBER}-{YY}.htm` serves
18
+ the full decision as HTML. Confirmed reachable (HTTP 200) for a 1992 citation.
19
+ Year in the URL path is the full 4-digit year (from `fecha_sentencia`), not
20
+ the 2-digit year suffix in the citation string itself.
@@ -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 = "co-eli-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for Colombian Constitutional Court decisions (datos.gov.co) - citation verification and metadata."
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", "colombia", "corte-constitucional", "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/co-eli-mcp"
44
+ Issues = "https://github.com/matematicsolutions/co-eli-mcp/issues"
45
+ Homepage = "https://matematic.co"
46
+
47
+ [project.scripts]
48
+ co-eli-mcp = "co_eli_mcp.server:main"
49
+
50
+ [tool.hatch.build.targets.wheel]
51
+ packages = ["src/co_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/co_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/co-eli-mcp",
4
+ "description": "MCP server for Colombian Constitutional Court case law (datos.gov.co), citation verification.",
5
+ "version": "0.1.0",
6
+ "repository": {
7
+ "url": "https://github.com/matematicsolutions/co-eli-mcp",
8
+ "source": "github"
9
+ },
10
+ "packages": [
11
+ {
12
+ "registryType": "pypi",
13
+ "registryBaseUrl": "https://pypi.org",
14
+ "identifier": "co-eli-mcp",
15
+ "version": "0.1.0",
16
+ "runtimeHint": "uvx",
17
+ "transport": {
18
+ "type": "stdio"
19
+ }
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1,3 @@
1
+ """co-eli-mcp - MCP connector for Colombian Constitutional Court decisions."""
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/co-eli-mcp.jsonl
6
+
7
+ (or to the directory given by ``CO_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 = "co-eli-mcp.jsonl"
26
+
27
+
28
+ def _resolve_audit_dir() -> Path:
29
+ env = os.environ.get("CO_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("CO_ELI_CACHE_DIR")
22
+ if env:
23
+ return Path(env).expanduser()
24
+ return Path.home() / ".matematic" / "cache" / "co-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,35 @@
1
+ """Citation contract for co-eli-mcp.
2
+
3
+ Colombia has no ELI/ECLI-style identifier for Corte Constitucional decisions.
4
+ The citation itself (e.g. "T-012/92") already IS the human-readable form used
5
+ in practice; we derive the public relatoria URL from it plus the full year
6
+ (the sentencia string only carries a 2-digit year, so we take the 4-digit
7
+ year from `fecha_sentencia` instead of guessing a century).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ from .models import Citation, Sentencia
15
+
16
+ _RELATORIA_URL = "https://www.corteconstitucional.gov.co/relatoria/{year}/{slug}.htm"
17
+
18
+
19
+ def parse_sentencia(raw: dict[str, Any]) -> Sentencia:
20
+ return Sentencia(
21
+ proceso=raw.get("proceso"),
22
+ expediente_tipo=raw.get("expediente_tipo"),
23
+ expediente_numero=raw.get("expediente_numero"),
24
+ magistrado_ponente=raw.get("magistrado_a"),
25
+ sala=raw.get("sala"),
26
+ sentencia=raw["sentencia"],
27
+ fecha_sentencia=raw.get("fecha_sentencia"),
28
+ )
29
+
30
+
31
+ def build_citation(s: Sentencia) -> Citation:
32
+ slug = s.sentencia.replace("/", "-")
33
+ year = s.fecha_sentencia[:4] if s.fecha_sentencia else "19" + s.sentencia.split("/")[-1]
34
+ source_url = _RELATORIA_URL.format(year=year, slug=slug)
35
+ return Citation(lex_uri=source_url, human_readable_citation=s.sentencia, source_url=source_url)
@@ -0,0 +1,80 @@
1
+ """Async httpx client for the Colombian open-data Socrata portal (datos.gov.co).
2
+
3
+ Keyless, JSON, dataset "Sentencias proferidas por la Corte Constitucional"
4
+ (resource id v2k4-2t8s). Metadata only - no full-text field in this dataset.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import anyio
10
+ import httpx
11
+
12
+ from .cache import HttpCache
13
+
14
+ DEFAULT_BASE_URL = "https://www.datos.gov.co/resource/v2k4-2t8s.json"
15
+ DEFAULT_TIMEOUT = httpx.Timeout(40.0, connect=10.0)
16
+ USER_AGENT = "co-eli-mcp/0.1.0 (+https://github.com/matematicsolutions/co-eli-mcp)"
17
+
18
+ _RETRY_STATUS = frozenset({429, 500, 502, 503, 504})
19
+ _MAX_ATTEMPTS = 3
20
+
21
+
22
+ class DatosGovClient:
23
+ """Async client. Use as ``async with DatosGovClient() as c: ...``."""
24
+
25
+ def __init__(
26
+ self,
27
+ base_url: str = DEFAULT_BASE_URL,
28
+ cache: HttpCache | None = None,
29
+ timeout: httpx.Timeout = DEFAULT_TIMEOUT,
30
+ ) -> None:
31
+ self.base_url = base_url
32
+ self._cache = cache or HttpCache()
33
+ self._http = httpx.AsyncClient(
34
+ timeout=timeout,
35
+ headers={"User-Agent": USER_AGENT, "Accept": "application/json"},
36
+ )
37
+
38
+ async def __aenter__(self) -> DatosGovClient:
39
+ return self
40
+
41
+ async def __aexit__(self, *_exc: object) -> None:
42
+ await self.aclose()
43
+
44
+ async def aclose(self) -> None:
45
+ await self._http.aclose()
46
+ self._cache.close()
47
+
48
+ async def _get_json(self, params: dict[str, str], *, category: str) -> list[dict]:
49
+ cache_key = self.base_url + "?" + "&".join(f"{k}={v}" for k, v in sorted(params.items()))
50
+ cached = self._cache.get(cache_key)
51
+ if cached is not None and isinstance(cached, list):
52
+ return cached
53
+ last_exc: Exception | None = None
54
+ for attempt in range(_MAX_ATTEMPTS):
55
+ try:
56
+ resp = await self._http.get(self.base_url, params=params)
57
+ resp.raise_for_status()
58
+ data = resp.json()
59
+ self._cache.set(cache_key, data, ttl=HttpCache.ttl_for(category))
60
+ return data
61
+ except httpx.HTTPStatusError as exc:
62
+ last_exc = exc
63
+ if exc.response.status_code not in _RETRY_STATUS or attempt == _MAX_ATTEMPTS - 1:
64
+ raise
65
+ except (httpx.TransportError, httpx.TimeoutException) as exc:
66
+ last_exc = exc
67
+ if attempt == _MAX_ATTEMPTS - 1:
68
+ raise
69
+ await anyio.sleep(0.5 * (2**attempt))
70
+ assert last_exc is not None
71
+ raise last_exc
72
+
73
+ async def search(self, query: str, limit: int = 20) -> list[dict]:
74
+ return await self._get_json({"$q": query, "$limit": str(limit)}, category="search")
75
+
76
+ async def get_by_sentencia(self, sentencia: str) -> list[dict]:
77
+ escaped = sentencia.replace("'", "''")
78
+ return await self._get_json(
79
+ {"$where": f"sentencia='{escaped}'"}, category="act"
80
+ )
@@ -0,0 +1,23 @@
1
+ """Plain dataclasses mirroring the datos.gov.co Socrata dataset row shape."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class Sentencia:
10
+ proceso: str | None
11
+ expediente_tipo: str | None
12
+ expediente_numero: str | None
13
+ magistrado_ponente: str | None
14
+ sala: str | None
15
+ sentencia: str
16
+ fecha_sentencia: str | None
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Citation:
21
+ lex_uri: str
22
+ human_readable_citation: str
23
+ source_url: str
@@ -0,0 +1,179 @@
1
+ """FastMCP entry point - Colombian Constitutional Court (Corte Constitucional) tools.
2
+
3
+ Run:
4
+
5
+ python -m co_eli_mcp.server
6
+
7
+ Configuration via env:
8
+
9
+ - ``CO_ELI_CACHE_DIR`` (default ``~/.matematic/cache/co-eli``)
10
+ - ``CO_ELI_AUDIT_DIR`` (default ``~/.matematic/audit``)
11
+ - ``CO_ELI_BASE_URL`` (default ``https://www.datos.gov.co/resource/v2k4-2t8s.json``)
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_sentencia
25
+ from .client import DEFAULT_BASE_URL, DatosGovClient
26
+
27
+ INSTRUCTIONS = """\
28
+ This MCP server exposes the datos.gov.co open-data record of decisions (sentencias) by the Colombian Constitutional Court (Corte Constitucional). It verifies whether a citation exists and gives its metadata - it does not fetch full decision text (this dataset has no full-text field).
29
+
30
+ ## Call order
31
+
32
+ 1. `co_search_sentencias` - free-text search (e.g. by keyword in `magistrado_a` or `proceso`).
33
+ 2. `co_get_sentencia` - exact lookup by citation, e.g. `"T-012/92"`. Use this to verify a citation actually exists before trusting it (anti-hallucination check, similar in spirit to citation-grounding-pl).
34
+
35
+ ## Hard constraints
36
+
37
+ - **No full-text retrieval** - only metadata (proceso, expediente, magistrado ponente, sala, fecha). The `source_url` points to the public Corte Constitucional relatoria page where the full text lives.
38
+ - **Every response has `human_readable_citation` + `source_url`** - cite both to the user.
39
+ - **Audit log JSONL** - every tool call appends to `~/.matematic/audit/co-eli-mcp.jsonl`.
40
+
41
+ ## Error iteration
42
+
43
+ Tools return a structured error with a `[code]` prefix:
44
+ - `invalid_arg` - a parameter is missing or malformed.
45
+ - `not_found` - no sentencia matches that exact citation.
46
+ - `upstream_error` - a datos.gov.co API error (HTTP, timeout). Retry once before surfacing.
47
+
48
+ ## Response style
49
+
50
+ - Cite decisions as `human_readable_citation`: "T-012/92".
51
+ - NEVER invent a sentencia citation, magistrado name or date - take each from the tool output. If `co_get_sentencia` returns `not_found`, say so plainly instead of guessing.
52
+ """
53
+
54
+
55
+ class ToolError(Exception):
56
+ """Structured error for co-eli MCP tools - visible to the LLM with a [code] prefix."""
57
+
58
+ VALID_CODES = frozenset({"invalid_arg", "not_found", "upstream_error"})
59
+
60
+ def __init__(self, code: str, message: str):
61
+ if code not in self.VALID_CODES:
62
+ raise ValueError(f"Unknown ToolError code: {code}. Valid: {sorted(self.VALID_CODES)}")
63
+ self.code = code
64
+ super().__init__(f"[{code}] {message}")
65
+
66
+
67
+ READ_ONLY = ToolAnnotations(
68
+ readOnlyHint=True,
69
+ idempotentHint=True,
70
+ destructiveHint=False,
71
+ openWorldHint=True,
72
+ )
73
+
74
+ mcp: FastMCP = FastMCP(name="co-eli-mcp", instructions=INSTRUCTIONS)
75
+
76
+
77
+ def _base_url() -> str:
78
+ return os.environ.get("CO_ELI_BASE_URL", DEFAULT_BASE_URL)
79
+
80
+
81
+ def _audit() -> AuditLogger:
82
+ return AuditLogger()
83
+
84
+
85
+ def _map_upstream(exc: Exception) -> Exception:
86
+ if isinstance(exc, (httpx.HTTPStatusError, httpx.TransportError, httpx.TimeoutException)):
87
+ return ToolError("upstream_error", f"datos.gov.co API error: {type(exc).__name__}: {exc}")
88
+ return exc
89
+
90
+
91
+ def _to_dict(s) -> dict:
92
+ citation = build_citation(s)
93
+ return {**dataclasses.asdict(s), **dataclasses.asdict(citation)}
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # co_search_sentencias
98
+ # ---------------------------------------------------------------------------
99
+
100
+
101
+ @mcp.tool(annotations=READ_ONLY)
102
+ async def co_search_sentencias(query: str, limit: int = 20) -> dict:
103
+ """Free-text search over Corte Constitucional decision metadata.
104
+
105
+ Args:
106
+ query: free text (e.g. part of a magistrado's name, or "tutela").
107
+ limit: max results (default 20).
108
+
109
+ Returns:
110
+ ``{"total": int, "items": [...]}`` - each item carries the citation contract.
111
+ """
112
+ audit = _audit()
113
+ if not query or not query.strip():
114
+ raise ToolError("invalid_arg", "query must be a non-empty string.")
115
+ input_hash = hash_input({"query": query, "limit": limit})
116
+
117
+ with timer() as t:
118
+ try:
119
+ async with DatosGovClient(base_url=_base_url()) as client:
120
+ raw_items = await client.search(query, limit)
121
+ except Exception as exc:
122
+ audit.log(tool="co_search_sentencias", input_hash=input_hash, output_count_or_size=0,
123
+ duration_ms=t.duration_ms if t.duration_ms else 0, status="error",
124
+ error=f"{type(exc).__name__}: {exc}")
125
+ raise _map_upstream(exc) from exc
126
+
127
+ items = [_to_dict(parse_sentencia(r)) for r in raw_items]
128
+ audit.log(tool="co_search_sentencias", input_hash=input_hash, output_count_or_size=len(items),
129
+ duration_ms=t.duration_ms, status="ok")
130
+ return {"total": len(items), "items": items}
131
+
132
+
133
+ # ---------------------------------------------------------------------------
134
+ # co_get_sentencia
135
+ # ---------------------------------------------------------------------------
136
+
137
+
138
+ @mcp.tool(annotations=READ_ONLY)
139
+ async def co_get_sentencia(sentencia: str) -> dict:
140
+ """Verify a Corte Constitucional citation and fetch its metadata.
141
+
142
+ Args:
143
+ sentencia: exact citation, e.g. ``"T-012/92"``.
144
+
145
+ Returns:
146
+ A dict with ``proceso``, ``expediente_tipo``, ``expediente_numero``,
147
+ ``magistrado_ponente``, ``sala``, ``sentencia``, ``fecha_sentencia``,
148
+ ``lex_uri``, ``human_readable_citation``, ``source_url``.
149
+ """
150
+ audit = _audit()
151
+ if not sentencia or not sentencia.strip():
152
+ raise ToolError("invalid_arg", "sentencia must be a non-empty string, e.g. 'T-012/92'.")
153
+ input_hash = hash_input({"sentencia": sentencia})
154
+
155
+ with timer() as t:
156
+ try:
157
+ async with DatosGovClient(base_url=_base_url()) as client:
158
+ raw_items = await client.get_by_sentencia(sentencia)
159
+ except Exception as exc:
160
+ audit.log(tool="co_get_sentencia", input_hash=input_hash, output_count_or_size=0,
161
+ duration_ms=t.duration_ms if t.duration_ms else 0, status="error",
162
+ error=f"{type(exc).__name__}: {exc}")
163
+ raise _map_upstream(exc) from exc
164
+
165
+ if not raw_items:
166
+ raise ToolError("not_found", f"No sentencia matching {sentencia!r} in Corte Constitucional records.")
167
+ result = _to_dict(parse_sentencia(raw_items[0]))
168
+ audit.log(tool="co_get_sentencia", input_hash=input_hash, output_count_or_size=1,
169
+ duration_ms=t.duration_ms, status="ok")
170
+ return result
171
+
172
+
173
+ def main() -> None:
174
+ """Run the MCP server over stdio (default for Claude Code)."""
175
+ mcp.run()
176
+
177
+
178
+ if __name__ == "__main__":
179
+ main()
@@ -0,0 +1,25 @@
1
+ """Live smoke test against the real datos.gov.co API. Network required."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ from co_eli_mcp.citations import build_citation, parse_sentencia
8
+ from co_eli_mcp.client import DatosGovClient
9
+
10
+
11
+ @pytest.mark.asyncio
12
+ async def test_get_and_search_sentencia() -> None:
13
+ async with DatosGovClient() as client:
14
+ items = await client.get_by_sentencia("T-012/92")
15
+ assert len(items) == 1
16
+
17
+ s = parse_sentencia(items[0])
18
+ citation = build_citation(s)
19
+ assert citation.human_readable_citation == "T-012/92"
20
+ assert citation.source_url == (
21
+ "https://www.corteconstitucional.gov.co/relatoria/1992/T-012-92.htm"
22
+ )
23
+
24
+ results = await client.search("tutela", limit=2)
25
+ assert len(results) == 2