This document provides an overview of the complete SWAT-Copilot MCP server implementation.
SWAT-Copilot is a Model Context Protocol (MCP) server that enables AI assistants to interact with SWAT (Soil and Water Assessment Tool) model projects. It provides tools for:
- Finding and loading SWAT projects
- Reading and parsing model inputs/outputs
- Performing hydrological analysis
- Generating visualizations
- Answering questions about model results
SWAT-Copilot/
├── src/swat_copilot/
│ ├── __init__.py # Package initialization
│ ├── __main__.py # CLI entry point
│ │
│ ├── config/ # Configuration Layer
│ │ ├── __init__.py
│ │ └── settings.py # Environment settings with Pydantic
│ │
│ ├── core/ # Domain Layer
│ │ ├── __init__.py
│ │ └── projects.py # SWATProject, SWATFile, SWATProjectLocator
│ │
│ ├── data_access/ # Data Access Layer
│ │ ├── __init__.py
│ │ ├── readers.py # File readers (Output, Control, etc.)
│ │ └── schemas.py # Data schemas (OutputData, WaterBalance)
│ │
│ ├── services/ # Service Layer
│ │ ├── __init__.py
│ │ ├── project_manager.py # Project lifecycle management
│ │ ├── summary.py # Summary generation
│ │ └── analysis.py # Statistical analysis
│ │
│ ├── integrations/mcp/ # MCP Server
│ │ ├── __init__.py
│ │ ├── __main__.py # MCP entry point
│ │ └── server.py # MCP server implementation (9 tools)
│ │
│ ├── api/ # REST API (FastAPI)
│ │ ├── __init__.py
│ │ ├── app.py # FastAPI application
│ │ └── routers/
│ │ ├── __init__.py
│ │ ├── health.py # Health check endpoints
│ │ └── summary.py # Analysis endpoints
│ │
│ ├── cli/ # CLI (Typer)
│ │ ├── __init__.py
│ │ └── app.py # CLI commands (find, load, summary, etc.)
│ │
│ ├── visualization/ # Visualization Layer
│ │ ├── __init__.py
│ │ └── plots.py # SWATPlotter with 4 plot types
│ │
│ └── llm/ # LLM Integration
│ ├── __init__.py
│ ├── prompts.py # Prompt templates
│ └── rag.py # RAG system (skeleton)
│
├── docs/
│ ├── architecture.md # Architecture overview
│ ├── GETTING_STARTED.md # Getting started guide
│ └── DEVELOPMENT.md # Development guide
│
├── examples/
│ └── basic_usage.py # Python usage examples
│
├── tests/
│ └── unit/
│ └── test_version.py # Basic test
│
├── pyproject.toml # Project metadata and dependencies
├── README.md # Main documentation
├── README_MCP.md # MCP server documentation
├── .env.example # Environment configuration template
├── .gitignore # Git ignore rules
└── PROJECT_SUMMARY.md # This file
Classes:
SWATFileType- Enum of SWAT file types (input/output)SWATFile- Represents a single SWAT fileSWATProject- Complete project with all filesSWATProjectLocator- Find and scan SWAT projects
Key Features:
- File type categorization (input vs output)
- Project validation
- Recursive project discovery
- File metadata extraction
Readers:
SWATFileReader- Base reader classOutputReader- Parse SWAT output files (.rch, .sub, .hru)ControlFileReader- Parse control file (file.cio)SubbasinFileReader- Parse subbasin files (.sub)HRUFileReader- Parse HRU files (.hru)
Schemas:
OutputData- Base output data structureReachOutput- Reach-specific outputSubbasinOutput- Subbasin-specific outputHRUOutput- HRU-specific outputWaterBalanceData- Water balance components
ProjectManager:
- Load/validate projects
- Find projects in directory trees
- Project info and metadata
SummarizeService:
- Project summaries
- Output summaries
- File counts and statistics
AnalysisService:
- Variable statistics (mean, std, min, max, etc.)
- Time series extraction
- Water balance calculation
- Scenario comparison (skeleton)
9 MCP Tools:
find_swat_projects- Search for SWAT projectsload_swat_project- Load a projectget_project_summary- Get project metadataget_output_summary- Summarize outputsget_variable_statistics- Calculate statsget_time_series- Extract time seriescalculate_water_balance- Water budgetplot_time_series- Generate time series plotplot_comparison- Compare multiple variables
Resources:
swat://project/{name}- Project dataswat://output/{type}- Output data
SWATPlotter Methods:
plot_time_series()- Time series visualizationplot_comparison()- Multi-variable comparisonplot_distribution()- Histogramplot_scatter()- Scatter plot
All plots return base64-encoded PNG images.
Commands:
swat-copilot find- Find projectsswat-copilot load- Load a projectswat-copilot summary- Project summaryswat-copilot outputs- Output summaryswat-copilot stats- Variable statisticsswat-copilot serve-mcp- Start MCP serverswat-copilot version- Show version
Endpoints:
GET /health- Health checkPOST /api/v1/projects/load- Load projectGET /api/v1/projects/find- Find projectsGET /api/v1/projects/summary- Project summaryGET /api/v1/projects/outputs/summary- Output summaryGET /api/v1/analysis/variable/statistics- Variable statsGET /api/v1/analysis/water-balance- Water balance
pandas- Data manipulationnumpy- Numerical operationspydantic- Data validationmcp- Model Context Protocol
fastapi- REST API frameworkuvicorn- ASGI servertyper- CLI frameworkrich- Terminal formatting
matplotlib- Plottingseaborn- Statistical visualization
openai- OpenAI integrationanthropic- Anthropic Claude integrationgeopandas- Geospatial features (future)
# Start server
python -m swat_copilot.integrations.mcpConfigure in Claude Desktop:
{
"mcpServers": {
"swat-copilot": {
"command": "python",
"args": ["-m", "swat_copilot.integrations.mcp"]
}
}
}from pathlib import Path
from swat_copilot.services.project_manager import ProjectManager
from swat_copilot.services.analysis import AnalysisService
# Load project
manager = ProjectManager()
project = manager.load_project(Path("/path/to/project"))
# Analyze
analyzer = AnalysisService(project)
stats = analyzer.get_variable_statistics("FLOW_OUT", "reach")
print(f"Mean streamflow: {stats['mean']:.2f} m³/s")# Find projects
swat-copilot find /models
# Load and analyze
swat-copilot load /models/my_watershed
swat-copilot stats FLOW_OUT --output-type reach# Start server
uvicorn swat_copilot.api.app:app --reload
# Access at http://localhost:8000/docs- Layered Architecture: Clear separation between domain, data access, services, and interfaces
- Dependency Direction: Lower layers don't depend on higher layers
- Type Safety: Full type hints throughout
- Testability: Services are easily mockable
- Extensibility: Easy to add new file readers, tools, or endpoints
- Master Watershed (
.Master.Watershed.dat) - Control File (
file.cio) - Subbasin files (
.sub) - HRU files (
.hru) - Routing files (
.rte) - Weather files (
.pcp,.tmp,.slr,.hmd,.wnd) - Soil files (
.sol) - Management files (
.mgt) - Groundwater files (
.gw) - Reservoir files (
.res) - Pond files (
.pnd)
- Reach outputs (
output.rch) - Subbasin outputs (
output.sub) - HRU outputs (
output.hru) - Reservoir outputs (
output.rsv) - Standard output (
output.std)
FLOW_OUT- Streamflow (m³/s)SED_OUT- Sediment (metric tons)ORGN_OUT- Organic nitrogen (kg N)ORGP_OUT- Organic phosphorus (kg P)NO3_OUT- Nitrate (kg N)SOLP_OUT- Soluble phosphorus (kg P)
PRECIP- Precipitation (mm)SURQ- Surface runoff (mm)LATQ- Lateral flow (mm)GW_Q- Groundwater flow (mm)ET- Evapotranspiration (mm)PET- Potential ET (mm)
The skeleton is complete and ready for:
- Adding actual SWAT projects for testing
- Implementing real file parsers (currently simplified)
- Adding more analysis functions
- Creating comprehensive tests
- Adding calibration tools
- Implementing RAG with SWAT documentation
- SWAT+ support
- Geospatial visualization
- Parameter sensitivity analysis
- Multi-scenario comparison
- Automated calibration
- Database persistence
- Web dashboard
- Documentation generation
- Install:
pip install -e ".[dev]" - Format:
black src/ tests/ - Lint:
ruff check src/ - Type Check:
mypy src/ - Test:
pytest --cov - Run MCP:
swat-copilot serve-mcp
- README.md - Main documentation
- README_MCP.md - MCP server guide
- docs/GETTING_STARTED.md - Installation and basics
- docs/DEVELOPMENT.md - Development guide
- docs/architecture.md - Architecture overview
- SWAT Model: https://swat.tamu.edu/
- MCP Protocol: https://modelcontextprotocol.io/
- FastAPI: https://fastapi.tiangolo.com/
- Typer: https://typer.tiangolo.com/
This repository now includes:
✅ Complete layered architecture ✅ MCP server with 9 tools ✅ REST API with FastAPI ✅ CLI with Typer ✅ Visualization system ✅ Configuration management ✅ File readers (skeleton) ✅ Analysis services ✅ LLM integration helpers ✅ Comprehensive documentation ✅ Example code ✅ Development guides ✅ Type hints throughout ✅ Proper package structure
The framework is complete and ready for:
- Testing with real SWAT projects
- Adding specific parsers for your SWAT version
- Extending with custom analysis functions
- Integration with AI assistants via MCP
- Building custom tools on top of the API
Just add your SWAT project data and start using!