agri-space / server.py
gchipeta's picture
Upload 2 files
ea3c945 verified
Raw History Blame Contribute Delete
6.33 kB
"""CosmosAI Agriculture MCP server (prototype).
Data lives in the data/ folder as CSV files that can be edited without touching code:
data/prices.csv crop, market, price_mwk_per_kg, date, status
data/input_rates.csv crop, seed_kg_per_acre, fertiliser_kg_per_acre, typical_yield_kg_per_acre, status
data/advice.csv id, crop, source, date, text, status
Set status to "verified" only once a row has been checked against a real source.
Rows with any other status are reported to the model as unverified.
Files are re-read automatically when they change, so no restart is needed.
Run locally: python server.py
Run over HTTP: MCP_API_KEY=secret python server.py --http (port 7860, endpoint /mcp)
"""
import csv
import hmac
import os
import re
import sys
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("cosmosai-agriculture", host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))
DATA_DIR = os.environ.get("DATA_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "data"))
UNVERIFIED_NOTE = "Some or all of this data is NOT verified. Do not present it to farmers as confirmed advice."
_cache = {}
def load(name):
"""Read a CSV from DATA_DIR, re-reading only when the file has changed."""
path = os.path.join(DATA_DIR, name)
mtime = os.path.getmtime(path)
cached = _cache.get(name)
if cached and cached[0] == mtime:
return cached[1]
with open(path, newline="", encoding="utf-8") as f:
rows = [{k.strip(): (v or "").strip() for k, v in r.items()} for r in csv.DictReader(f)]
_cache[name] = (mtime, rows)
return rows
def note_for(rows):
"""Return a warning if any returned row is not marked verified."""
if any(r.get("status", "").lower() != "verified" for r in rows):
return {"note": UNVERIFIED_NOTE}
return {}
def tokens(s):
return set(re.findall(r"[a-z]+", s.lower()))
@mcp.tool()
def list_crops() -> dict:
"""List the crops this server has any data for. Call this if unsure which crop names are supported."""
crops = set()
for name in ("prices.csv", "input_rates.csv", "advice.csv"):
crops |= {r["crop"].lower() for r in load(name) if r.get("crop")}
return {"crops": sorted(crops)}
@mcp.tool()
def calc_profit(total_cost: float, quantity: float, price_per_unit: float) -> dict:
"""Calculate revenue, profit and profit margin for a sale. All money in Malawi Kwacha (MWK).
Use this for any profit or loss arithmetic instead of calculating mentally."""
revenue = quantity * price_per_unit
profit = revenue - total_cost
return {
"revenue_mwk": revenue,
"profit_mwk": profit,
"margin_percent_of_sales": round(100 * profit / revenue, 1) if revenue else None,
"profit_percent_of_cost": round(100 * profit / total_cost, 1) if total_cost else None,
}
@mcp.tool()
def calc_inputs(crop: str, area_acres: float) -> dict:
"""Estimate seed and fertiliser needed, and expected yield, for a crop on a given area in acres."""
rows = [r for r in load("input_rates.csv") if r["crop"].lower() == crop.lower()]
if not rows:
return {"error": f"No data for crop '{crop}'. Use list_crops to see supported crops."}
r = rows[0]
return {
"crop": crop.lower(),
"area_acres": area_acres,
"seed_kg": float(r["seed_kg_per_acre"]) * area_acres,
"fertiliser_kg": float(r["fertiliser_kg_per_acre"]) * area_acres,
"expected_yield_kg": float(r["typical_yield_kg_per_acre"]) * area_acres,
**note_for(rows),
}
@mcp.tool()
def get_prices(crop: str, market: str = "") -> dict:
"""Get the latest recorded price per kg for a crop, optionally for one market.
Returns the most recent entry for each market, with its date."""
rows = [r for r in load("prices.csv") if r["crop"].lower() == crop.lower()
and (not market or r["market"].lower() == market.lower())]
if not rows:
return {"results": [], "message": "No price found for that crop/market."}
latest = {}
for r in rows:
key = r["market"].lower()
if key not in latest or r["date"] > latest[key]["date"]:
latest[key] = r
results = [{"crop": r["crop"], "market": r["market"],
"price_mwk_per_kg": float(r["price_mwk_per_kg"]), "date": r["date"],
"status": r.get("status", "")} for r in latest.values()]
return {"results": results, **note_for(list(latest.values()))}
@mcp.tool()
def search_advice(question_in_english: str, crop: str = "", max_results: int = 3) -> dict:
"""Search farming advice passages. Pass the question in English.
Returns passages with source and date so the answer can cite them."""
q = tokens(question_in_english)
scored = []
for a in load("advice.csv"):
if crop and a["crop"].lower() != crop.lower():
continue
score = len(q & tokens(a["text"])) + (2 if a["crop"].lower() in q else 0)
if score > 0:
scored.append((score, a))
scored.sort(key=lambda x: -x[0])
top = [a for _, a in scored[:max_results]]
return {"results": [{"source": a["source"], "date": a["date"], "text": a["text"],
"status": a.get("status", "")} for a in top], **note_for(top)}
def build_http_app():
"""Streamable-HTTP app that requires the header Authorization: Bearer <MCP_API_KEY>."""
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
api_key = os.environ.get("MCP_API_KEY", "")
if not api_key:
raise SystemExit("Set the MCP_API_KEY environment variable (a long random secret) before starting.")
class ApiKeyAuth(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
sent = request.headers.get("authorization", "")
if not hmac.compare_digest(sent, f"Bearer {api_key}"):
return JSONResponse({"error": "unauthorized"}, status_code=401)
return await call_next(request)
app = mcp.streamable_http_app()
app.add_middleware(ApiKeyAuth)
return app
if __name__ == "__main__":
if "--http" in sys.argv:
import uvicorn
uvicorn.run(build_http_app(), host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))
else:
mcp.run()