gap-agriculture-mcp

eagleisbatman/gap-agriculture-mcp

3.2

If you are the rightful owner of gap-agriculture-mcp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

The GAP Agriculture MCP Server is a Model Context Protocol server designed to provide agriculture weather intelligence using Tomorrow Now's Global Access Platform (GAP) API.

Tools
4
Resources
0
Prompts
0

🌾 GAP Agriculture MCP Server

License: MIT Node.js TypeScript

Model Context Protocol (MCP) server providing agriculture weather intelligence.

Transforms weather data from TomorrowNow's Global Access Platform (GAP) into actionable agricultural advice: weather forecasts, planting decisions, irrigation schedules, and farming guidance.

✨ Features

4 Agricultural Tools

ToolPurpose
get_weather_forecast1-14 day forecasts (temperature, rain, humidity, wind)
get_planting_recommendationYES/NO planting decisions for specific crops
get_irrigation_advisory7-day irrigation schedules with water balance calculations
get_farming_advisoryComprehensive crop management and risk alerts

Supported Crops (22)

Cereals: maize, wheat, rice, sorghum, millet Legumes: beans, cowpea, pigeon_pea, groundnut Roots: cassava, sweet_potato, potato Vegetables: tomato, cabbage, kale, onion, vegetables Cash Crops: tea, coffee, sugarcane, banana, sunflower, cotton

Note: Crop list currently optimized for East Africa. You can customize the crop list for your region in src/index.ts, but remember that weather data availability depends on GAP coverage in your area.

Technical Features

  • āœ… Processes 50-member ensemble forecasts into single values
  • āœ… Crop-specific logic (temperature ranges, water requirements)
  • āœ… Farmer-friendly responses (no technical jargon)
  • āœ… TypeScript for production reliability
  • āœ… StreamableHTTP MCP transport

šŸŒ Geographic Coverage

IMPORTANT: This MCP server relies on TomorrowNow's Global Access Platform (GAP) for weather data. GAP coverage is limited to specific regions where TomorrowNow operates.

Check GAP availability for your region before deployment.

Current GAP coverage includes parts of:

  • East Africa (Kenya, Tanzania, Uganda, Ethiopia, Somalia)
  • Other regions may be available - verify at tomorrownow.org

Note: The 22 supported crops can be customized for any region, but the server will only work where GAP provides weather data coverage.

šŸƒ Quick Start

Prerequisites

  • Node.js >= 18.0.0
  • GAP API Token from Tomorrow Now
  • Verify GAP covers your target region

Local Setup

# Clone and install
git clone https://github.com/eagleisbatman/gap-agriculture-mcp.git
cd gap-agriculture-mcp
npm install

# Configure environment
cp .env.example .env
# Edit .env: Add your GAP_API_TOKEN

# Start development server
npm run dev

# Test
curl http://localhost:3000/health

Expected Response:

{
  "status": "healthy",
  "service": "gap-agriculture-mcp-server",
  "gapApiConfigured": true
}

āš™ļø Configuration

Environment Variables

# Required
GAP_API_TOKEN=your_gap_api_token_here

# Optional (defaults shown)
PORT=3000
NODE_ENV=production
GAP_API_BASE_URL=https://gap.tomorrownow.org/api/v1
ALLOWED_ORIGINS=*

Get GAP API Token

  1. Visit TomorrowNow
  2. Sign up / Log in
  3. Generate API token
  4. Add to .env

šŸš€ Deployment

This server can be deployed to any Node.js hosting platform:

  • PaaS: Railway, Heroku, Render, Fly.io
  • Cloud: AWS (EC2/Lambda), Google Cloud Run, Azure App Service
  • Containerized: Docker, Kubernetes
  • VPS: DigitalOcean, Linode, your own server

Generic Deployment Steps

  1. Push code to version control (GitHub, GitLab, etc.)
  2. Choose hosting platform based on your needs
  3. Configure environment variables:
    • Set GAP_API_TOKEN
    • Optionally set PORT, NODE_ENV, ALLOWED_ORIGINS
  4. Deploy using platform-specific method
  5. Test: curl https://your-deployment-url/health

Platform-Specific Notes

Railway/Heroku/Render: Auto-detect Node.js, use npm start AWS Lambda: May need serverless framework adapter Docker: Use provided Dockerfile (if available) or create one VPS: Use PM2 or systemd for process management

šŸ”Œ Integration

OpenAI Agent Builder

1. Deploy MCP Server (any platform)

2. Create Agent Workflow:

3. Add MCP Server:

  • Add Tool → Custom MCP Server
  • Name: gap-agriculture-mcp
  • Transport: StreamableHTTP
  • URL: https://your-deployment-url/mcp

4. Configure System Prompt:

See the FarmerChat Widget repository for a complete example system prompt (SYSTEM_PROMPT.md) that:

  • Instructs the LLM to use MCP tools exclusively for weather data
  • Hides technical details from end users
  • Keeps responses concise and actionable
  • Lists all supported crops
  • Provides user-friendly error messages

5. Test the agent:

The MCP server accepts coordinates in two ways:

Option A - Default coordinates (Recommended for production): Configure default coordinates via HTTP headers when creating ChatKit sessions. Users can then ask simple questions:

What's the weather?
Should I plant maize?
Do I need to irrigate?

Option B - Explicit coordinates (For testing or multi-location support): Users can specify different locations:

What's the weather for latitude XX.XXXX, longitude YY.YYYY?
Should I plant maize at latitude XX.XXXX, longitude YY.YYYY?

See the FarmerChat Widget for a complete example of how to configure default coordinates via session headers.

šŸ”§ Configuring Default Coordinates

The MCP server accepts default coordinates via HTTP headers, allowing farmers to ask questions without specifying location every time.

How It Works

When your AI agent calls the MCP server, include these custom headers:

X-Farm-Latitude: XX.XXXX
X-Farm-Longitude: YY.YYYY

The server uses these as defaults when users don't provide coordinates in their query.

Example: OpenAI ChatKit Integration

// In your session creation endpoint
const response = await fetch('https://api.openai.com/v1/chatkit/sessions', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${OPENAI_API_KEY}`,
    'Content-Type': 'application/json',
    'X-Farm-Latitude': '-1.2864',      // Your region's default latitude
    'X-Farm-Longitude': '36.8172'      // Your region's default longitude
  },
  body: JSON.stringify({
    workflow_id: WORKFLOW_ID
  })
});

Example: Direct MCP Call

curl -X POST https://your-mcp-server.com/mcp \
  -H "Content-Type: application/json" \
  -H "X-Farm-Latitude: XX.XXXX" \
  -H "X-Farm-Longitude: YY.YYYY" \
  -d '{"tool": "get_weather_forecast", "args": {}}'

User Experience

With default coordinates configured:

  • User: "What's the weather?"
  • Agent: Uses default coordinates, provides weather

Without default coordinates:

  • User: "What's the weather?"
  • Agent: "I need to know your farm location to provide weather information. Please let me know where your farm is located."

For a complete implementation example, see the FarmerChat Widget repository.

šŸ—ļø Architecture

AI Agent (OpenAI/Claude/Custom)
    ↓ MCP Protocol (StreamableHTTP) + Custom Headers
Express.js MCP Server (This Repo)
    ↓ Reads X-Farm-Latitude, X-Farm-Longitude from headers
    ↓ Uses as defaults if user doesn't provide coordinates
    ↓ HTTP REST
GAP API (TomorrowNow)
    - Provides: Weather data only
    - Returns: 50-member ensemble forecasts

Server analyzes weather data and generates:
    - Planting recommendations
    - Irrigation schedules
    - Farming advice

Critical: GAP provides ONLY weather data. All agricultural analysis happens in this server's code (src/index.ts).

šŸ“ Project Structure

gap-mcp-server/
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ index.ts          # Main: 4 MCP tools + agricultural logic
│   └── gap-client.ts     # GAP API client wrapper
ā”œā”€ā”€ dist/                 # Compiled output (generated)
ā”œā”€ā”€ .env                  # Environment variables (gitignored)
ā”œā”€ā”€ .env.example          # Environment template
ā”œā”€ā”€ package.json          # Dependencies and scripts
ā”œā”€ā”€ tsconfig.json         # TypeScript config
ā”œā”€ā”€ CLAUDE.md             # Development guidance
└── README.md             # This file

šŸ› ļø Development

Commands

npm install     # Install dependencies
npm run build   # Compile TypeScript
npm run dev     # Development mode (hot reload)
npm start       # Production mode

Adding Crops

  1. Edit src/index.ts
  2. Add to enum in all 4 tools (search for z.enum)
  3. Add case in switch statements:
    • get_farming_advisory (~line 275)
    • get_planting_recommendation (~line 450)
  4. Define: optimal temperature, water needs, special conditions
  5. Test, commit, deploy

Customizing for Your Region

  1. Update crop list: Add/remove crops relevant to your region
  2. Adjust thresholds: Modify temperature/rainfall ranges in crop logic
  3. Change units: Adapt temperature (°C/°F) and rainfall (mm/inches) if needed
  4. Language: Translate response strings for local language support

šŸ› Troubleshooting

Server Won't Start

Error: GAP_API_TOKEN is not set

# Check .env exists
ls -la .env

# Verify token is set
grep GAP_API_TOKEN .env

# If missing, copy template
cp .env.example .env
# Then edit .env

GAP API Errors

401 Unauthorized: Invalid or expired API token 404 Not Found: Coordinates outside GAP coverage area or invalid dates

Important: If you consistently get 404 errors with valid coordinates, your region may not be covered by TomorrowNow GAP Platform. Verify coverage at tomorrownow.org

MCP Connection Failed

  1. Test health endpoint: curl https://your-url/health
  2. Check server logs for errors
  3. Verify CORS allows your AI agent's domain
  4. Ensure URL uses https://

Deployment Issues

  • Verify GAP_API_TOKEN is set in platform's environment variables
  • Check build logs for compilation errors
  • Server must bind to 0.0.0.0 (not localhost)
  • Don't hardcode PORT - use process.env.PORT

šŸ“š Resources

šŸ“„ License

MIT License - see file


Open source agricultural intelligence for farmers worldwide 🌾

⭐ Star this repo