mx-postal-codes
Allows LangChain agents to interact with the Mexican postal code database, including consulting postal codes, validating addresses, and searching settlements.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mx-postal-codesshow me the details for postal code 06600"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Mexico Postal Codes API ๐ฒ๐ฝ
Ultra-fast RESTful API built with Python 3.12, FastAPI, SQLite in WAL mode, and Docker, designed to respond in < 1 ms with the official catalog of Postal Codes, Settlements, Municipalities, and States of Mexico.
๐ Legal Attribution Clause (Mandatory under CC BY 4.0)
This API uses and processes geographic and postal code information from the official catalog published by the Mexican Postal Service (SEPOMEX) through datos.gob.mx under the Creative Commons Attribution 4.0 International license.
๐ Main Features
API Contract and Specification: docs/api_contract.md
Speed and Performance: Sub-millisecond response times with SQLite in Write-Ahead Logging (WAL) mode and
orjsonserialization.Cybersecurity: OWASP hardening, security headers, Rate Limiting, strict Pydantic v2 regex validation, and Docker non-root user.
Enterprise Error Handling: RFC 7807 (Problem Details) format with a unique
X-Correlation-IDper request.Audit & Logging: Structured JSON logs via
loguruwith daily rotation at midnight (00:00),.zipcompression, and 30-day retention.Deadlock Prevention: HTTP connections in read-only mode (
mode=ro) withPRAGMA busy_timeout=5000;.Automatic Ingestion Script: Downloads, cleans (ISO-8859-1 to UTF-8), and populates the database atomically.
๐ฆ Installation and Local Execution
1. Prerequisites
Python 3.10+
Virtualenv or Docker
2. Set up environment and install dependencies
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt3. Run Data Ingestion (SEPOMEX / datos.gob.mx)
python scripts/ingest_sepomex.pyThis command will download the official CPdescarga.txt file and generate sepomex.db with more than 148,000 settlements and optimized indexes.
4. Start Development Server
uvicorn app.main:app --reload --port 8000Visit the interactive documentation at: http://localhost:8000/docs
๐ณ Running with Docker
Option A: Docker Build & Run
docker build -t codigos-postales-api .
docker run -p 8000:8000 codigos-postales-apiOption B: Docker Compose
docker-compose up -d๐ Authentication & Rate Limiting (API Key & JWT)
The API features a hybrid authentication scheme configurable from .env:
1. Operation Modes (REQUIRE_AUTH)
REQUIRE_AUTH=False(Public API Mode, default): The endpoints are freely accessible. Request control is performed via IP Rate Limiting (120 req/min by default).REQUIRE_AUTH=True(Enterprise Protected API Mode): Requires every request to send valid credentials in the headers.
2. Supported Authentication Options
Header
X-API-Key:curl -H "X-API-Key: key-dev-12345" http://localhost:8000/api/v1/codigo-postal/01000JWT Bearer Token (
Authorization: Bearer <token>):JWT token exchange (valid for 24 hours):
curl -X POST http://localhost:8000/api/v1/auth/token -H "X-API-Key: key-dev-12345"Request with the returned token:
curl -H "Authorization: Bearer <tu_jwt_token>" http://localhost:8000/api/v1/codigo-postal/01000
๐ ๏ธ Available Endpoints
Method | Endpoint | Description |
|
| Interactive web dashboard for observability, statistics, and GeoJSON map |
|
| Query details of a postal code (includes |
|
| Mass batch validation and normalization of up to 100 addresses in a single HTTP request |
|
| Export coordinates and settlements in standard GeoJSON format ( |
|
| Real-time autocomplete by prefix of 2 to 5 digits |
|
| Geographic proximity search (Haversine + Bounding Box) |
|
| Accent-insensitive FTS5 search, combined filters, pagination, and direct export ( |
|
| Fast accent-insensitive settlement search |
|
| List of the 32 federal entities (with |
|
| Municipalities by state code |
|
| Full municipality detail with all its postal codes and settlements |
|
| Export complete geographic layers of the state in GeoJSON format ( |
|
| Generate and download executive PDF report (optional parameters |
|
| JavaScript widget for automatic autocompletion of client-side HTML forms |
|
| Metric statistics and breakdown of the SEPOMEX catalog |
|
| Live audit logs and server events in JSON format |
|
| CC BY 4.0 Legal Attribution Clause |
|
| Monitoring metrics in Prometheus standard |
|
| Healthcheck for Docker/K8s monitoring |
๐ฆ Official SDK Clients (mx-postal-client)
The project includes two lightweight SDK client packages to easily consume the API without writing manual HTTP requests:
Python SDK (
sdk/python):pip install ./sdk/pythonfrom mx_postal_client import MXPostalClient client = MXPostalClient(base_url="http://localhost:8080") cp_data = client.get_codigo_postal("01000", colonia="San รngel")TypeScript / Node.js SDK (
sdk/typescript):npm install ./sdk/typescriptimport { MXPostalClient } from 'mx-postal-client'; const client = new MXPostalClient({ baseUrl: 'http://localhost:8080' }); const detail = await client.getCodigoPostal('01000');
๐ค Integration with AI Agents (Model Context Protocol - MCP)
The API includes an official MCP Server (scripts/mcp_server.py) that allows AI Agents (Claude Desktop, ChatGPT, Antigravity IDE, LangChain, AutoGPT) to query and interact with the official geographic database of Mexico in natural language.
Tools Exposed for AI:
consultar_codigo_postal(cp): Returns the complete geographic record and list of settlements.validar_direccion_postal(codigo_postal, colonia, estado, municipio): Validates in real time the data match with SEPOMEX.buscar_asentamientos_por_nombre(nombre_colonia, limite): Natural language search by keywords.
Configuration in Claude Desktop / Antigravity IDE (mcp.json):
{
"mcpServers": {
"mx-postal-codes": {
"command": "python3",
"args": ["/ruta/absoluta/a/codigos-postales-api/scripts/mcp_server.py"]
}
}
}๐ Automatic Verification of the SEPOMEX Catalog
The container runs an asynchronous monthly scheduler in the background that checks for updates in datos.gob.mx without affecting HTTP latency (< 1 ms).
To manually run the verification or force the catalog update inside the Docker container:
docker exec codigos_postales_api python3 scripts/check_updates.py --force๐ Comparison with the State of the Art (2026)
Technical comparison of our solution against open-source alternatives and commercial SaaS services currently on the market:
Technical Dimension / Functionality | ๐ This Project | ๐ข Tlaloc.sh | ๐ Sepomex-MCP | โก go-mexpost | ๐ณ Copomex |
Architecture | Self-Hosted (Docker/WAL) | Cloud SaaS | Self-Hosted / Python | Self-Hosted / Go | Cloud SaaS |
p99 Latency | < 0.5 ms (L1 RAM Cache) | ~120 ms | ~15 ms | ~2 ms | ~200 ms |
SAT CFDI 4.0 Standard | โ
Native ( | โ Native | โ Not available | โ Not available | โ ๏ธ Partial |
Batch Mass Validation ( | โ Up to 100 req/request | โ Not available | โ Not available | โ Not available | โ Not available |
GeoJSON Vector (Postal Code and State) | โ Complete (Point & Bounds) | โ Not available | โ Not available | โ Not available | โ Not available |
Executive PDF Report | โ Native (ReportLab) | โ Not available | โ Not available | โ Not available | โ Not available |
JavaScript Frontend Widget | โ
| โ Not available | โ Not available | โ Not available | โ ๏ธ Custom JS |
MCP Server for AI Agents | โ
| โ Not available | โ Included | โ Not available | โ Not available |
Official SDKs (Python/TS) | โ
| โ HTTP requests | โ HTTP requests | โ HTTP requests | โ HTTP requests |
Payload Size Protection (1 MB) | โ
| โ ๏ธ Unknown | โ Not available | โ ๏ธ Proxy level | โ ๏ธ Proxy level |
Operational Cost | $0 USD (Unlimited) | Pay-per-lookup | $0 USD | $0 USD | $15-$150 USD/m |
๐ฌ Experiments
The project includes a complete suite of load tests, GPS geofencing, tax normalization, and interoperability with Artificial Intelligence Agents (MCP).
Phase 1 (Latency and Batch): 58.91x acceleration in batch validation (
POST /batch-validate).Phase 2 (SAT Normalization): Algorithmic $F_1$-Score of 90.45% with 100% precision on a dataset of 1,000 noisy samples.
Phase 3 (AI Agents / MCP): 99.43% token savings when interoperating via the MCP Server.
๐งช Running Tests
pytestThis server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
Official Mexican data for AI agents: CURP, RFC, CFDI, postal codes, phone, SPEI/CEP, DOF, geocoding.
Address validation & geocoding for AI agents: 240+ countries, UK PAF, free US/CA enrichment
Validate LatAm IDs: Mexican CLABE, Brazilian CNPJ/CPF checksums + BrasilAPI company/CEP/bank lookups
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/alonsomaciasm/codigos-postales-api'
If you have feedback or need assistance with the MCP directory API, please join our Discord server