TerraGuard

Backend API

Python/FastAPI core API powering TerraGuard with 40+ endpoints, 6 AI agents, 5 MCP servers, and Inngest-driven async workflows for disaster event management.

Overview

The tg-backend-api is the central service of the TerraGuard platform. Built with Python and FastAPI, it provides the core REST API that the frontend and other services consume. It handles event management, AI-powered enrichment, reporting, knowledge base operations, notifications, and team/organization management.

The service runs on port 5601 and exposes all routes under the /api/v1 prefix.

Architecture

Loading diagram...

Key Features

40+ REST Endpoints

The API aggregates routers from over 30 modules covering events, reports, knowledge, notifications, organizations, teams, dashboards, and more. All routers are registered in app/apis/routes.py.

6 AI Agents

Built with the pydantic-ai framework, each agent handles a specific task in the enrichment pipeline:

AgentPurpose
gdacs_response_agentAnalyzes and structures GDACS event data
news_filter_agentLLM-based validation of news article relevance
news_briefing_agentGenerates concise news briefings from discovered articles
notify_agentCrafts notification content for email and Telegram
gdacs_rag_agentRetrieval-augmented generation for event Q&A
report_generation_agentMulti-section report generation using MCP tools (ReAct pattern)

5 MCP Servers

Model Context Protocol servers provide tool access for the report generation agent:

ServerPortPurpose
Brave Search8001Web search tool
Doclink8002Document URL retrieval
GeoPop8003Geocoding and population data
DB Search8004Database query tool
Vector Search8005Semantic search over knowledge base

Inngest Async Workflows

The service uses Inngest (backed by Redis) for event-driven background processing. Key workflow functions include:

  • execute_event_pipeline — Orchestrates the full enrichment pipeline for new events
  • process_event_from_go — Handles webhook events from the Event Processor
  • centralized_scheduler — Manages scheduled tasks (news crawling, report generation)
  • send_email — Async email delivery
  • sqs_poller — Legacy SQS message processing

Database

PostgreSQL with two critical extensions:

  • PostGIS — Geospatial queries (proximity searches, region containment)
  • pgVector — Vector embeddings for semantic search over crawled knowledge

All models are defined in app/models.py (~2000+ lines of SQLModel definitions).

Configuration

Key environment variables from .env:

VariableDescriptionDefault
DATABASE_HOSTPostgreSQL hostlocalhost
DATABASE_PORTPostgreSQL port5432
DATABASE_NAMEDatabase nametg_db
OPENAI_API_KEYOpenAI API key for AI agentsrequired
GEMINI_API_KEYGoogle Gemini API keyrequired
SERPER_API_KEYSerper.dev key — primary web/news searchrequired
BRAVE_API_KEYBrave Search key — search fallbackoptional
GEO_POP_APIURL of the GeoPop API servicehttp://localhost:8077/api/v1
INNGEST_BASE_URLInngest server URLhttp://localhost:8288
INNGEST_EVENT_KEYInngest event signing keyrequired
INNGEST_SIGNING_KEYInngest webhook signing keyrequired
TELEGRAM_BOT_TOKENTelegram bot token for notificationsrequired
SMTP_HOSTSMTP server for email notificationslocalhost
SMTP_PORTSMTP port1025
FRONTEND_URLFrontend URL for links in notificationshttp://localhost:3000

API Endpoints

The API is organized into the following route groups (all prefixed with /api/v1):

PrefixTagDescription
/authauthAuthentication and user management
/eventseventsDisaster event CRUD and queries
/event-newsevent-newsNews articles linked to events
/event-notesevent-notesManual notes on events
/event-pipelineevent-pipelineEvent processing pipeline triggers
/evaluateevaluateAI evaluation endpoints
/dashboarddashboardDashboard aggregations and stats
/knowledgeknowledgeKnowledge base management
/documentsdocumentsDocument upload and processing
/reportsreportsReport generation and management
/report-templatesreport-templatesReport template CRUD
/report-schedulersreport-schedulersScheduled report configuration
/notificationsnotificationsNotification history and triggers
/message-templatesmessage-templatesEmail/Telegram templates
/organizationsorganizationsOrganization management
/matrixmatrixOrganization alert matrices
/matrix-regionsmatrix-regionsRegion-specific matrix config
/teamsteamsTeam management
/rolesrolesRole management
/contactscontactsContact directory
/country-configscountry-configsPer-country settings
/geo-locationgeo-locationGeocoding utilities
/ingestingestManual event ingestion
/internalinternalInternal webhooks (event processor)
/update-schedulerupdate-schedulerScheduled update configuration
/news-crawler-schedulernews-crawler-schedulerNews crawl scheduling

Directory Structure

tg-backend-api/
├── app/
│   ├── main.py                 # FastAPI application entry point
│   ├── config.py               # Pydantic Settings configuration
│   ├── models.py               # SQLModel definitions (2000+ lines)
│   ├── apis/
│   │   ├── routes.py           # Router aggregation (30+ routers)
│   │   ├── auth/               # Authentication endpoints
│   │   ├── event/              # Event CRUD
│   │   ├── event_news/         # Event news management
│   │   ├── knowledge/          # Knowledge base
│   │   ├── reports/            # Report generation
│   │   ├── notification/       # Notifications
│   │   ├── organization/       # Org, matrix, country config
│   │   ├── dashboard/          # Dashboard stats
│   │   └── internal/           # Internal webhooks
│   ├── agents/
│   │   ├── gdacs_response_agent.py
│   │   ├── news_filter_agent.py
│   │   ├── news_briefing_agent.py
│   │   ├── notify_agent.py
│   │   ├── gdacs_rag_agent.py
│   │   └── report_generation_agent/
│   ├── inngest/
│   │   ├── worker.py           # Inngest worker process
│   │   ├── client.py           # Inngest client configuration
│   │   ├── registry.py         # Function registration
│   │   └── functions/
│   │       ├── execute_event_pipeline.py
│   │       ├── process_event_from_go.py
│   │       ├── centralized_scheduler.py
│   │       └── send_email.py
│   ├── mcp/
│   │   ├── runner.py           # MCP server runner
│   │   ├── db_search/          # Database search MCP
│   │   ├── vector_search/      # Vector search MCP
│   │   ├── doclink/            # Document link MCP
│   │   └── geopop/             # GeoPop proxy MCP
│   └── common/
│       ├── search_providers.py  # Serper (primary) + Brave (fallback) search
│       ├── firecrawl_client.py # Web Crawler client
│       └── document_processor_client.py
├── alembic/                    # Database migrations
├── Makefile
└── pyproject.toml

Running

# Start the API server
make server

# Start the Inngest worker (separate terminal)
make inngest

# Start all MCP servers (separate terminal)
make mcp-all

# Run integration tests
make e2e-test

On this page