Inspiration

In the Yucatán peninsula of Mexico, when an energy company arrives at a Mayan ejido (communal land) with a proposal for a megaproject, communities sometimes have days to respond. Days to evaluate 30-year contracts, environmental impact, and their rights under ILO Convention

  1. Their legal advisors — lawyers at NGOs, academics, journalists — are overwhelmed.

Between 2012 and 2019, the Mexican Energy Regulatory Commission granted 42 permits for large-scale renewable energy projects in the peninsula, mostly over Mayan ejidal lands. Some have been denied by SEMARNAT, some suspended by courts, others operating today with complaints before the Inter-American Court of Human Rights.

Tierra Clara was built to give legal advisors a tool that does the heavy lifting — retrieving applicable Mexican federal law, finding analogous historical projects, and producing a structured comparative analysis — so they can focus on advising the community.

What it does

Tierra Clara is an AI agent that helps NGO legal advisors evaluate energy project proposals in real time:

  1. The advisor records or types a description of the case (audio in Spanish supported via Gemini multimodal transcription).
  2. The agent extracts structured data and asks for missing critical fields rather than inventing them.
  3. It searches 955 chunks of Mexican federal regulation (Convenio 169 OIT, Ley Agraria, Ley de la Industria Eléctrica, LGEEPA) using MongoDB Atlas Vector Search.
  4. It retrieves analogous projects from a corpus of 38 megaprojects documented by GeoComunes and Articulación Yucatán (2012-2019).
  5. It produces a complete legal brief in under 90 seconds: red flags, applicable articles cited verbatim, historical precedents with regulatory outcomes, comparative analysis, and actionable recommendations.

Additionally, advisors can query the corpus directly in natural language. The agent decides what queries to execute against MongoDB via the official MongoDB MCP Server (Model Context Protocol), with transparent display of every tool call it makes.

How I built it

Architecture:

  • Agent orchestration: Google ADK 2.1.0 (part of Google Cloud Agent Builder) for multi-step agent workflows
  • Language model: Gemini 2.5 Flash via Vertex AI for reasoning, transcription, and structured output
  • Embeddings: Vertex AI text-embedding-004 (768 dimensions)
  • Storage: MongoDB Atlas with Vector Search indexes on regulatory corpus and analogous projects
  • MCP integration: Official mongodb-mcp-server@1.12.0 connected via Model Context Protocol, enabling the agent to query the database in natural language with full transparency
  • API: FastAPI with three endpoints: /api/transcribe, /api/analyze, /api/explore
  • Frontend: Vanilla HTML/JS and GSAP for animations
  • Hosting: Google Cloud Run

Design principles:

  • No hallucination by design: every legal citation is retrieved verbatim from MongoDB; the agent cannot cite articles that don't exist
  • Honesty over completion: when critical fields are missing (e.g., state), the agent asks the user instead of inventing
  • Structured outputs validated by Pydantic: every LLM response passes schema validation; malformed outputs trigger corrective retries
  • Data sovereignty: the system does NOT accept raw PDF contracts with personal data of ejidatarios, respecting LFPDPPP and the spirit of Convenio 169. The advisor describes the case in their own words.

Challenges I ran into

Gemini output formatting flakiness. The site_analyzer agent occasionally omitted the output tags in its structured outputs, causing parsing failures roughly 40% of the time. Investigation showed the comparator was vulnerable in both step 1 and step 2. Fix: temperature=0 + JSON fallback extraction + corrective retries. Result: 16/16 consecutive successful runs.

Vector Search bias toward emblematic projects. Initial seeding produced 4 detailed "emblematic" projects and 34 basic ones. Vector Search consistently returned only the emblematic ones, ignoring the basic corpus. Fix: enriched all 34 basic projects with structured key_factors, making them semantically discoverable.

MongoDB MCP Server cold start timeout. The MCP server needed more than 5 seconds to bootstrap (npx + Node.js + Atlas TLS handshake), but ADK's default timeout was 5s. Caused TaskGroup errors in production. Fix: explicit timeout=30s in StdioConnectionParams.

Cascading non-determinism in the analogous project ranking. With the same input, the agent occasionally returned different top-1 precedents between runs. Root cause: extract_site_input ran without temperature=0, causing variance in extracted fields, which cascaded into the embedding query, which cascaded into Vector Search ordering. Fix: temperature=0 across all LLM calls + analogous query built only from stable structured fields. Result: 2/2 consistent top-1 in validation.

Architecture decision: pymongo vs MCP for retrieval. Could have refactored all database access through MCP, but that would have broken validated retrieval pipelines. Chose additive integration: pymongo for structured retrieval (Vector Search with metadata filters), MongoDB MCP Server for natural language exploration. Both work in parallel.

Accomplishments I'm proud of

This is the first solo project I've built that I'm showing to the world. Before Tierra Clara, I had never touched Google Cloud Platform, never used MongoDB, never worked with Vertex AI. The stack was completely new to me. Learning it while shipping something real was the hardest and most rewarding part of this build.

I designed the architecture to be extensible. The agent's core capabilities — retrieval, structured extraction, comparative reasoning — are decoupled from the specific corpus and the specific use case. The same architecture could serve communities in Oaxaca, Tehuantepec, or any region with documented territorial conflicts.

I built this thinking about a real user, not a global market. María José — a legal advisor in an NGO supporting Mayan ejidos — was the persona I designed every interaction for. Her time is limited. Her trust matters. The agent had to be honest with her: when it doesn't know something, it asks. It doesn't invent.

The agent doesn't hallucinate. Every legal citation in the output is retrieved verbatim from the regulatory corpus in MongoDB. The agent cannot cite an article that doesn't exist. When critical information is missing from the user's input, the agent stops and asks — it never assumes.

End-to-end analysis in under 90 seconds. From an audio recording in Spanish to a complete legal brief with red flags, applicable articles, and historical precedents.

Real MongoDB MCP integration. Not just connecting to MongoDB — proper Model Context Protocol integration where the agent decides what query to make against the database in natural language, with full transparency about which tool it invoked and with what arguments.

What I learned

You can ship something serious with a stack you've never used before — if you're willing to be wrong a loooot. Three weeks ago I had never created a Vertex AI project. Now I have an agent in production on Cloud Run, talking to MongoDB Atlas with Vector Search, integrated with Google ADK and the official MongoDB MCP Server. I broke things many times. Each break taught me something about the layer underneath.

Designing for non-hallucination is harder than it looks. It's not just "tell the model not to make things up." It requires careful prompt engineering, structured output validation with Pydantic, retrieval-first architecture, and explicit handling of "I don't know" states. The agent has to be okay with returning incomplete results when the input is incomplete.

Production hardening reveals brittleness. A smoke test passing once doesn't mean a system is reliable. My comparator went from 57% success rate to 100% only after hunting bugs I couldn't see in early development — Gemini occasionally omitting output tags, Vector Search returning unstable orderings, cascading variance from a single un-pinned temperature parameter.

The Model Context Protocol is a paradigm shift. Giving an agent the ability to formulate its own database queries — rather than relying on hardcoded retrievers — opens up exploration patterns that wouldn't fit in a predefined API. María José can ask the corpus questions I never anticipated.

What's next for Tierra Clara

  • PDF ingestion with PII redaction: allow advisors to upload contracts after automatic redaction of personal data of ejidatarios
  • Expansion beyond the Yucatán peninsula: integrate corpora for Oaxaca, Tehuantepec, and other regions with documented territorial conflicts
  • Conversational database exploration: turn the current single-turn /api/explore into a continuous chat for deeper research workflows
  • Production API management with Apigee: rate limiting, API key authentication, threat protection
  • Gemini 2.5 Flash vs Pro evaluation: quantitative comparison on long-tail legal cases
  • Translation of legal articles to Mayan and other indigenous languages, respecting the principle that consultation must be in the community's language

Built With

Share this project:

Updates